Пример #1
0
// This piece of code is borrowed from Argo written by Nathaniel Tagg
std::vector<std::string> DataFetcher::FindLeavesOfType(std::string pattern) {
  /// Look in the tree and try to find a leaf element that matches 'pattern'.
  /// Return the full name of that leaf.
  std::vector<std::string> leaf_names;

  // Strip whitespace from pattern.
  pattern.erase(std::remove_if(pattern.begin(), pattern.end(), ::isspace),
      pattern.end());

  TObjArray * list = tree_->GetListOfLeaves();
  for (int i = 0; i < list->GetEntriesFast(); ++i) {
    TObject * o = list->At(i);
    TLeaf * leaf = (TLeaf *) o;
    std::string name = leaf->GetTypeName();
    // Strip whitespace from pattern.
    name.erase(std::remove_if(name.begin(), name.end(), ::isspace),
        name.end());
    size_t found = name.find(pattern);
    if (found != std::string::npos) {
      // Return this match.
      leaf_names.push_back(leaf->GetName());
    }
  }
  return leaf_names;
}
Пример #2
0
void dump_required_lvl2(TTree *tree, TLeaf &leaf, CodedOutputStream &o, CodedOutputStream &o2) {
    const int DL = 1; // definition level multiplier
    const int RL = 4; // repetition level multiplier

    std::cout << "Dump vector vector: " << leaf.GetName() << " " << leaf.GetTypeName() << std::endl;
    auto * branch = leaf.GetBranch();

    std::vector<std::vector<T> > * data = NULL;
    tree->SetBranchAddress(leaf.GetBranch()->GetName(), &data);
    int entries = tree->GetEntries();
    for (int i = 0; i < entries; i++) { 
        branch->GetEntry(i);
        if (data->size() == 0) {
            write_out_32(o2, DL*0 + RL*0);
        }
        for (int j = 0; j < data->size(); j++) {
            if (data->at(j).size() == 0) {
                int dl = 1;
                int rl = (j > 0 ? 1 : 0);
                write_out_32(o2, dl*DL + rl*RL);
            }
            for (int k = 0; k < data->at(j).size(); k++) {
                int dl = 2;
                int rl = (k > 0 ? 2 : (j > 0 ? 1 : 0));
                write_out_32(o2, dl*DL + rl*RL);
                write_out_type(o, data->at(j).at(k));
            }
        }
    }
}
void Output::fixLeafOffsets( TBranch * b)
{
  // recalculates the addresses for all the leaves.
  // 
  // when constructing a branch with containing a variable length array with the index
  // variable in the same branch it is not possible to specify the span of the index variable
  // This span defaults to zero. When the addresses are asigned to the various leaves in the branch
  // it calculates the size of the particular leaf (variable length array) in the buffer by looking 
  // at the span of the index variable - 0 in this case! using the method TLeaf::GetLen(). 
  // The following code shoudl be applied to the branch after the spans of the index variables have been
  // specified manually using the TLeaf::SetMaximum method. This time the GetLen method calculates the correct offset.

  TObjArray * leaves = b->GetListOfLeaves();
  char * addr = b->GetAddress();
  int offset = 0;
  int nleaves = leaves->GetEntriesFast();
  
  // loop over the leaves:
  for( int i =0; i < nleaves; ++i) {
    TLeaf * leaf = (TLeaf *)leaves->UncheckedAt(i);
    leaf->SetAddress( addr + offset );
    int oldOffset = leaf->GetOffset();
    leaf->SetOffset( offset );
    //std::cout << " offset changed from : " << oldOffset << " to " << offset << std::endl;
    TLeaf * index = leaf->GetLeafCount();
    int nelements = 1;
    if( index ) {
      nelements = index->GetMaximum(); // deal with variable length arrays
    } else {
      nelements = leaf->GetLenStatic(); // deal with single variables and fixed length arrays
    }
    offset += leaf->GetLenType() * nelements;
  }
}
Пример #4
0
void dump_required_lvl0(TTree *tree, TLeaf &leaf, CodedOutputStream &o) {
    std::cout << "Dump " << leaf.GetName() << std::endl;
    auto *branch = leaf.GetBranch();

    T data; 
    tree->SetBranchAddress(leaf.GetBranch()->GetName(), &data);
    int entries = tree->GetEntries();
    for (int i = 0; i < entries; i++) { 
        branch->GetEntry(i);
        write_out_type(o, data);
    }
}
Пример #5
0
void GAInputTreeData::SetBranchAddressToHolder(string branch_name){
    if(!fTTree->GetBranch(branch_name.c_str())){
        cout << "[GAInputTreeData-E]: branch " << branch_name << 
                " is not found";
        throw 1;
    }
    fBranchName.push_back(branch_name);
    TLeaf *leaf = fTTree->GetBranch(branch_name.c_str())
        ->GetLeaf(branch_name.c_str());
    Int_t n_data = leaf->GetNdata();
    string type_name = leaf->GetTypeName();
    fEventDataHolderManager->AddDetector(type_name,branch_name, n_data);
}
void NCIdeogram::addTree(TTree *tree, const char *mu, const char *sigma)
{
	TLeaf *leafMu = tree->FindLeaf(mu);
	TLeaf *leafSigma = tree->FindLeaf(sigma);
	TEventList *elist = tree->GetEventList();
	Long64_t j,ix,nbr;
	
	nbr = elist ? elist->GetN() : tree->GetEntries();
	for (j = 0; j < nbr; j++) {
		ix = elist ? elist->GetEntry(j) : j;
		tree->GetEntry(ix);
		addPoint(leafMu->GetValue(), leafSigma->GetValue());
	}
} // addTree()
Пример #7
0
CThreadSlm::TState
CThreadSlm::history_state_of(TState st)
{
    if (st.getLevel() >= m_N) {
        TLeaf* pl = ((TLeaf *)m_Levels[m_N]) + st.getIdx();
        return TState(pl->bol(), pl->bon());
    } else {
        TNode* pn = ((TNode *)m_Levels[st.getLevel()]) + st.getIdx();
        if (pn->ch() == (pn+1)->ch())
            return TState(pn->bol(), pn->bon());
        else
            return st;
    }
}
Пример #8
0
/// \brief Cache  MC production trees, store summary information in formated text files -> root trees
/// \param dataType  -
/// \param fileList
void CacheTestMCProductions(TString dataType, const char *fileList=NULL){
  AliExternalInfo info;
  info.fLoadMetadata=kFALSE;
  TObjArray* periodList = NULL;
  TArrayI nRuns;
  if (fileList!=NULL) {
    periodList=(gSystem->GetFromPipe(TString::Format("cat %s", fileList).Data())).Tokenize("\n");
    nRuns.Set(periodList->GetEntries());

  }else{
    TTree * tree = info.GetTree("MonALISA.ProductionMC","","");
    Int_t nProd=tree->GetEntries();
    periodList = new TObjArray(nProd);
    nRuns.Set(nProd);
    TLeaf *leaf = tree->GetLeaf("Tag");
    TLeaf *leafRuns = tree->GetLeaf("Number_of_runs");
    for (Int_t iProd=0; iProd<nProd; iProd++){
      tree->GetEntry(iProd);
      TString prodName=((char*)leaf->GetValuePointer());
      if (prodName.Contains("LHC")==0) continue;
      periodList->AddAt(new TObjString(((char*)leaf->GetValuePointer())),iProd);
      nRuns[iProd]=leafRuns->GetValue();
    }
    delete tree;
  }
  for (Int_t iPeriod=0; iPeriod<periodList->GetEntriesFast(); iPeriod++){
    TObjString * pName= (TObjString*)periodList->At(iPeriod);
    if (pName==NULL) continue;
    TTree* tree = info.GetTree(dataType.Data(),periodList->At(iPeriod)->GetName(),"passMC");
    if (tree){
      Int_t entries=tree->Draw("run","1","goff");
      TString sInfo=periodList->At(iPeriod)->GetName();
      sInfo+="\t";
      sInfo+=dataType;
      sInfo+="\t";
      sInfo+=TString::Format("%d\t",entries);
      sInfo+=TString::Format("%d\t",nRuns[iPeriod]);
      for (Int_t j=0; j<entries; j++) {
        sInfo+=TString::Format("%2.0f,",tree->GetV1()[j]);
        ::Info("CacheTestMCProductionsRun:","%s\t%s\t%d\t%d\t%d\t%2.0f",periodList->At(iPeriod)->GetName(),dataType.Data(),entries,nRuns[iPeriod],j, tree->GetV1()[j]);
      }
      sInfo+="0";
      ::Info("CacheTestMCProductionsPeriod:","%s\n",sInfo.Data());
      delete tree;
    }else{
      ::Error("CacheTestMCProductionsPeriod:","%s\t%s\t-1\t%d\t0",periodList->At(iPeriod)->GetName(), dataType.Data(),nRuns[iPeriod]);
    }
  }
}
Пример #9
0
CThreadSlm::TState&
CThreadSlm::historify(TState& st)
{
    if (st.getLevel() >= m_N) {
        TLeaf* pl = ((TLeaf *)m_Levels[m_N]) + st.getIdx();
        st.setLevel(pl->bol());
        st.setIdx(pl->bon());
    } else {
        TNode* pn = ((TNode *)m_Levels[st.getLevel()]) + st.getIdx();
        if (pn->ch() == (pn+1)->ch()) {
            st.setLevel(pn->bol());
            st.setIdx(pn->bon());
        }
    }
    return st;
}
Пример #10
0
void GAInputTreeData::SetAllBranches(){
    TObjArray* ArrayOfBranches = fTTree->GetListOfBranches();
    Int_t n_branch = ArrayOfBranches->GetEntries();
    cout << "[GAInputTreeData-M]:Loading " << n_branch << " branches from "
        << fTTree->GetName() << endl;
    for(int i_branch=0; i_branch<n_branch; i_branch++){
        TBranch* Branch = (TBranch*)ArrayOfBranches->At(i_branch);
        string branch_name = Branch->GetName();
        TLeaf *leaf = (TLeaf*)Branch->GetListOfLeaves()->At(0);//(branch_name.c_str());
        Int_t n_data = leaf->GetNdata();
        string type_name = leaf->GetTypeName();
        fBranchName.push_back(branch_name);
        fEventDataHolderManager->AddDetector(type_name, branch_name, n_data);
        cout << "[GAInputTreeData-M]:Loading branch " << branch_name
            << " (" << type_name << "[" << n_data << "])" << endl;
    }
}
Пример #11
0
void DataInterface::getDataProfile(TH2F *hProfile, TH2F *hProjection, Int_t energy) {
   if (!existsEnergyFile(energy)) {
      cout << "There are no data files with energy " << energy << endl;
      return;
   }

   TString fn = Form("Data/ExperimentalData/DataFrame_%i_MeV.root", energy);
   TFile *f = new TFile(fn);
   TTree *tree = (TTree*) f->Get("tree");

   Int_t nentries = tree->GetEntries();
   printf("Found %d frames in the DataFrame.\n", nentries);

   TLeaf *lX = tree->GetLeaf("fDataFrame.fX");
   TLeaf *lY = tree->GetLeaf("fDataFrame.fY");
   TLeaf *lLayer = tree->GetLeaf("fDataFrame.fLayer");

   Float_t x, y, layer;

   for (Int_t i=0; i<nentries; i++) {
      tree->GetEntry(i);

      for (Int_t j=0; j<lY->GetLen(); j++) {
         x = lX->GetValue(j)  + nx/2;
         y = lY->GetValue(j)  + ny/2;
         layer = lLayer->GetValue(j);

         hProfile->Fill(y, layer);
         hProjection->Fill(x, y);
      }
   }
}
Пример #12
0
void
CArpaSlm::load(const char* filename, const TLexicon& lexicon)
{
    printf("Loading ARPA slm..."); fflush(stdout);
    ifstream file(filename);
    char buf[1024];
    for (int i = 0; i <= N_GRAM; ++i) {
        unsigned lvl;
        int size;
        file.getline(buf, sizeof(buf));
        if (!file) {
            cerr << "Failed to read from" << filename << endl;
            exit(1);
        }
        sscanf(buf, "\\%d-gram\\%d%*[\n]", &lvl, &size);
        assert(lvl <= N_GRAM);
        if (lvl == 0) {
            TNode node0;
            node0.load_level0(file);
            m_levels[0].push_back(node0);
        } else if (lvl < m_N) {
            m_levels[lvl].reserve(size);
            for (int i = 0; i < size; ++i) {
                TNode node;
                node.load(file, lexicon);
                m_levels[lvl].push_back(node);
            }
        } else {
            // leaf nodes
            m_lastLevel.reserve(size);
            for (int i = 0; i < size; ++i) {
                TLeaf leaf;
                leaf.load(file, lexicon);
                m_lastLevel.push_back(leaf);
            }
        }
    }
}
Пример #13
0
int main() {
    // Get a map of the histograms of the Z Masses
    const std::string Tree_HighCut = "ZFinder/Combined Single Reco/Combined Single Reco";
    const std::string Tree_LowCut = "ZFinder/Combined Single Lowered Threshold Reco/Combined Single Lowered Threshold Reco";
    const std::string file_name = "/data/whybee0a/user/gude_2/Data/20150324_SingleElectron_2012ALL/hadded.root";
    // Open the file and load the tree
    TTree* treeH = GetTTree(file_name, Tree_HighCut);
    TBranch* event_infoH = treeH->GetBranch("event_info");
    TLeaf* EVNumbH = event_infoH->GetLeaf("event_number");
    // Pack into a hitogram
    std::set<int> eventnumber;
    std::set<int> eventnumberLow;
    for (int i = 0; i < treeH->GetEntries(); i++) {
        treeH->GetEntry(i);
        if (eventnumber.find(EVNumbH->GetValue()) == eventnumber.end()) {
            eventnumber.insert(EVNumbH->GetValue());
        } else {
            cout << "multiple events numbered :" << EVNumbH->GetValue()<<" in higher cuts" << endl;
        }

    }

    TTree* TreeLow = GetTTree(file_name, Tree_LowCut);
    TBranch* event_infoL = TreeLow->GetBranch("event_info");
    TLeaf* EVNumbLow = event_infoL->GetLeaf("event_number");
    for (int i = 0; i < TreeLow->GetEntries(); i++) {
        TreeLow->GetEntry(i);
        eventnumberLow.insert(EVNumbLow->GetValue());
        if (eventnumberLow.find(EVNumbLow->GetValue()) == eventnumber.end()) {
            eventnumberLow.insert(EVNumbLow->GetValue());
        } else {
cout << "multiple events numbered :" << EVNumbLow->GetValue()<<" in lowered cuts" << endl;
        }

    }

    return EXIT_SUCCESS;
}
Пример #14
0
map<TString, vector<TString> >GetCounterBranchListMap(TTree *t)
{
  map<TString, vector<TString> > m;
  TObjArray *l = t->GetListOfLeaves(); //sometimes leave can be named wrong - rely on branches
  int n = l->GetEntries();// cout<<t->GetName()<<" has "<<n<<" leaves"<<endl;
  for (int i=0;i<n;i++) {
    TLeaf * leaf = (TLeaf *)(*l)[i];
    TLeaf *lc = leaf->GetLeafCount();
    
    if (lc!=0) {
      m[lc->GetBranch()->GetName()].push_back(leaf->GetBranch()->GetName()); //get leaf's branch name
      if (VERBOSE) cout<<lc->GetBranch()->GetName()<<" _ "<<leaf->GetBranch()->GetName()<<endl;
    }
  }

  return m;
}
Пример #15
0
void getlist(ostream& out, TBranch* branch, int depth=0)
{
  TObjArray* array = branch->GetListOfBranches();
  if ( ! array ) return;
  if ( depth > 10 ) return;

  string name;
  int nitems = array->GetEntries();

  for (int i = 0; i < nitems; i++)
	{
	  TBranch* b = (TBranch*)((*array)[i]);
      if ( ! b ) continue;

      string branchname(b->GetName());
      out << SPACE.substr(0,4*depth) << branchname << endl;
 
      TObjArray* a = b->GetListOfLeaves();
      if ( a )
        {
          int n = a->GetEntries();
          {
              for (int j = 0; j < n; j++)
                {
                  TLeaf* leaf = (TLeaf*)((*a)[j]);
                  int count = 0;
                  int ndata = 0;
                  TLeaf* leafc = leaf->GetLeafCounter(count);
                  if ( ! leafc)
                    ndata = leaf->GetLen();
                  else
                    ndata = leafc->GetMaximum();

                  string leafname(leaf->GetName());
                  out << SPACE.substr(0,4*(depth+1)) 
                      << ndata << " " << leafname << endl;
                }
          }
//           else if ( n == 1 )
//             {
//               TBranch* bc = (TBranch*)((*a)[j]);
//               string leafname(bc->GetName());
//               if ( leafname != branchname )
//               out << SPACE.substr(0,4*(depth+1)) << leafname << endl;
//             }
        }
      getlist(out, b, depth+1);
    }
}
Пример #16
0
void DataInterface::getDataFrame(Int_t runNo, CalorimeterFrame * cf, Int_t energy) {

   if (!existsEnergyFile(energy)) {
      cout << "There are no data files with energy " << energy << endl;
      return;
   }

   Int_t eventIdFrom = runNo * kEventsPerRun;
   Int_t eventIdTo = eventIdFrom + kEventsPerRun;

   TString fn = Form("Data/ExperimentalData/DataFrame_%i_MeV.root", energy);
   TFile *f = new TFile(fn);
   TTree *tree = (TTree*) f->Get("tree");

   Int_t nentries = tree->GetEntries();
   if (eventIdTo > nentries) {
      eventIdTo = nentries;
   }
   cout << "Found " << nentries << " frames in the DataFrame.\n";

   TLeaf *lX = tree->GetLeaf("fDataFrame.fX");
   TLeaf *lY = tree->GetLeaf("fDataFrame.fY");
   TLeaf *lLayer = tree->GetLeaf("fDataFrame.fLayer");

   Int_t counter = 0;
   for (Int_t i=eventIdFrom; i<eventIdTo; i++) {
      tree->GetEntry(i);

      for (Int_t j=0; j<lX->GetLen(); j++) {
         Int_t x = lX->GetValue(j) + nx/2;
         Int_t y = lY->GetValue(j) + ny/2;
         Int_t z = lLayer->GetValue(j);

         cf->fillAt(z, x, y);
      }
      counter++;
   }
   delete f;
}
Пример #17
0
int analysis(char* filename)
{
    // char* filename = "combined.root";
    // Read in the file
    TFile* f = new TFile(filename);
    TDirectory* hists  = f->GetDirectory("hists;1");
    TDirectory* tuples = f->GetDirectory("tuples;1");

    TTree* accum = tuples->GetObjectUnchecked("AccumulatedEnergy;1");
    TLeaf* einit = accum->GetLeaf("Einit");
    TLeaf* edepo = accum->GetLeaf("Edep");

    TTree* edeps = tuples->GetObjectUnchecked("EnergyDepositions;1");

    TTree* secs  = tuples->GetObjectUnchecked("SecondarySpectrum;1");
    TLeaf* secsenergy = secs->GetLeaf("KineticEnergy");

    double ein = 0;
    double eout = 0;



    int nevents = accum->GetEntries();
    cout << "Making Summary\n";
    FILE* summary = fopen("summ.txt", "a+");

    for (int ii = 0; ii<nevents; ii++)
    {
        accum->GetEntry(ii);
        ein+=einit->GetValue();
        eout+=edepo->GetValue();
    }

    FILE* summary = fopen("summ.txt", "a+");

    time_t t = time(NULL);
    char* c_time_string = ctime(&t);
    char* mytime[20];
    strncpy(mytime, c_time_string, 19);
    mytime[ strlen(mytime) - 1 ] = '\0';

    fprintf(summary, "%s,%s,%e,%e\n", mytime, filename, ein, eout);//*c_time_string, *filename, ein, eout);
    //cout << *c_time_string << "," << *filename << "," << ein << "," << eout << "\n";
    fclose(summary);

    // Print out or save these values
    cout << "Making Histogram\n";

    nevents = secs->GetEntries();
    TH1F* secondaries = new TH1F("secondaries", "Secondary Electrons <100 keV", 92, 0.010, 0.102);

    for (int ii = 0; ii<nevents; ii++)
    {
        secs->GetEntry(ii);
        secondaries->Fill(secsenergy->GetValue());
    }

    char* suffix = ".secondaryhisto";

    cout << "Making Filenames\n";


    char* outfilename = malloc(strlen(filename) + strlen(suffix) + 1);
    strcpy(outfilename, filename);
    strcat(outfilename, suffix);

    printf("Saving Histogram: %s \n", outfilename);
    h12ascii(secondaries, outfilename);

    return 0;

}
Пример #18
0
void paracoor( TString fin = "TMVA.root", Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  
   TTree* tree = (TTree*)file->Get("TestTree");
   if(!tree) {
      cout << "--- No TestTree saved in ROOT file. Parallel coordinates will not be plotted" << endl;
      return;
   }

   // first get list of leaves in tree
   TObjArray* leafList = tree->GetListOfLeaves();
   vector<TString> vars;
   vector<TString> mvas;   
   for (Int_t iar=0; iar<leafList->GetSize(); iar++) {
      TLeaf* leaf = (TLeaf*)leafList->At(iar);
      if (leaf != 0) {
         TString leafName = leaf->GetName();
         if (leafName != "type" && leafName != "weight"  && leafName != "boostweight" &&
             leafName != "class" && leafName != "className" && leafName != "classID" && 
             !leafName.Contains("prob_")) {
            // is MVA ?
            if (TMVAGlob::ExistMethodName( leafName )) {
               mvas.push_back( leafName );
            }
            else {
               vars.push_back( leafName );
            }
         }
      }
   }

   cout << "--- Found: " << vars.size() << " variables" << endl;
   cout << "--- Found: " << mvas.size() << " MVA(s)" << endl;
   

   TString type[2] = { "Signal", "Background" };
   const Int_t nmva = mvas.size();
   TCanvas* csig[nmva];
   TCanvas* cbkg[nmva];
   for (Int_t imva=0; imva<mvas.size(); imva++) {
      cout << "--- Plotting parallel coordinates for : " << mvas[imva] << " & input variables" << endl;

      for (Int_t itype=0; itype<2; itype++) {

         // create draw option
         TString varstr = mvas[imva] + ":";
         for (Int_t ivar=0; ivar<vars.size(); ivar++) varstr += vars[ivar] + ":";
         varstr.Resize( varstr.Last( ':' ) );

         // create canvas
         TString mvashort = mvas[imva]; mvashort.ReplaceAll("MVA_","");
         TCanvas* c1 = (itype == 0) ? csig[imva] : cbkg[imva];
         c1 = new TCanvas( Form( "c1_%i",itype ), 
                           Form( "Parallel coordinate representation for %s and input variables (%s events)", 
                                 mvashort.Data(), type[itype].Data() ), 
                           50*(itype), 50*(itype), 750, 500 );      
         tree->Draw( varstr.Data(), Form("classID==%i",1-itype) , "para" );
         c1->ToggleEditor();
         gStyle->SetOptTitle(0);

         TParallelCoord*    para   = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject( "ParaCoord" );
         TParallelCoordVar* mvavar = (TParallelCoordVar*)para->GetVarList()->FindObject( mvas[imva] );
         Double_t minrange = tree->GetMinimum( mvavar->GetName() );
         Double_t maxrange = tree->GetMaximum( mvavar->GetName() );
         Double_t width    = 0.2*(maxrange - minrange);
         Double_t x1 = minrange, x2 = x1 + width;
         TParallelCoordRange* parrange = new TParallelCoordRange( mvavar, x1, x2 );
         parrange->SetLineColor(4);
         mvavar->AddRange( parrange );

         para->AddSelection("-1");

         for (Int_t ivar=1; ivar<TMath::Min(Int_t(vars.size()) + 1,3); ivar++) {
            TParallelCoordVar* var = (TParallelCoordVar*)para->GetVarList()->FindObject( vars[ivar] );
            minrange = tree->GetMinimum( var->GetName() );
            maxrange = tree->GetMaximum( var->GetName() );
            width    = 0.2*(maxrange - minrange);

            switch (ivar) {
            case 0: { x1 = minrange; x2 = x1 + width; break; }
            case 1: { x1 = 0.5*(maxrange + minrange - width)*0.02; x2 = x1 + width*0.02; break; }
            case 2: { x1 = maxrange - width; x2 = x1 + width; break; }
            }

            parrange = new TParallelCoordRange( var, x1, x2 );
            parrange->SetLineColor( ivar == 0 ? 2 : ivar == 1 ? 5 : 6 );
            var->AddRange( parrange );

            para->AddSelection( Form("%i",ivar) );
         }

         c1->Update();

         TString fname = Form( "plots/paracoor_c%i_%s", imva, itype == 0 ? "S" : "B" );
         TMVAGlob::imgconv( c1, fname );
      }
   }
}
Пример #19
0
bool execute(const std::string& skeleton, const std::string& config_file, std::string output_dir/* = ""*/) {

    std::vector<Plot> plots;
    // If an output directory is specified, use it, otherwise use the current directory
    if (output_dir == "")
      output_dir = ".";

    std::map<std::string, std::string> unique_names;

    get_plots(config_file, plots);

    std::cout << "List of requested plots: ";
    for (size_t i = 0; i < plots.size(); i++) {
        std::cout << "'" << plots[i].name << "'";
        if (i != plots.size() - 1)
            std::cout << ", ";
    }
    std::cout << std::endl;

    // Convert plots name to unique name to avoid collision between different runs
    for (Plot& plot: plots) {
        std::string uuid = get_uuid();
        unique_names[uuid] = plot.name;
        plot.name = uuid;
    }

    std::unique_ptr<TChain> t(new TChain("t"));
    t->Add(skeleton.c_str());

    std::vector<Branch> branches;
    std::function<void(TTreeFormula*)> getBranches = [&branches, &getBranches](TTreeFormula* f) {
        if (!f)
            return;

        for (size_t i = 0; i < f->GetNcodes(); i++) {
            TLeaf* leaf = f->GetLeaf(i);
            if (! leaf)
                continue;

            TBranch* p_branch = getTopBranch(leaf->GetBranch());

            Branch branch;
            branch.name = p_branch->GetName();
            if (std::find_if(branches.begin(), branches.end(), [&branch](const Branch& b) {  return b.name == branch.name;  }) == branches.end()) {
                branch.type = p_branch->GetClassName();
                if (branch.type.empty())
                    branch.type = leaf->GetTypeName();

                branches.push_back(branch);
            }

            for (size_t j = 0; j < f->fNdimensions[i]; j++) {
                if (f->fVarIndexes[i][j])
                    getBranches(f->fVarIndexes[i][j]);
            }
        }

        for (size_t i = 0; i < f->fAliases.GetEntriesFast(); i++) {
            getBranches((TTreeFormula*) f->fAliases.UncheckedAt(i));
        }
    };

    std::string hists_declaration;
    std::string text_plots;
    for (auto& p: plots) {
        // Create formulas
        std::shared_ptr<TTreeFormula> selector(new TTreeFormula("selector", p.plot_cut.c_str(), t.get()));

        getBranches(selector.get());

        std::vector<std::string> splitted_variables = split(p.variable, ":");
        for (const std::string& variable: splitted_variables) {
            std::shared_ptr<TTreeFormula> var(new TTreeFormula("var", variable.c_str(), t.get()));
            getBranches(var.get());
        }

        std::string binning = p.binning;
        binning.erase(std::remove_if(binning.begin(), binning.end(), [](char chr) { return chr == '(' || chr == ')'; }), binning.end());

        // If a variable bin size is specified, declare array that will be passed as array to histogram constructor
        if(binning.find("{") != std::string::npos){
          std::string arrayString = buildArrayForVariableBinning(binning, splitted_variables.size(), p.name);
          hists_declaration += arrayString;
        }

        std::string title = p.title + ";" + p.x_axis + ";" + p.y_axis + ";" + p.z_axis;
        std::string histogram_type = getHistogramTypeForDimension(splitted_variables.size());

        hists_declaration += "    std::unique_ptr<" + histogram_type + "> " + p.name + "(new " + histogram_type + "(\"" + p.name + "\", \"" + title + "\", " + binning + ")); " + p.name + "->SetDirectory(nullptr);\n";
 
        std::string variable_string;
        for (size_t i = 0; i < splitted_variables.size(); i++) {
            variable_string += splitted_variables[i];
            if (i != splitted_variables.size() - 1)
                variable_string += ", ";
        }

        ctemplate::TemplateDictionary plot("plot");
        plot.SetValue("CUT", p.plot_cut);
        plot.SetValue("VAR", variable_string);
        plot.SetValue("HIST", p.name);

        ctemplate::ExpandTemplate(getTemplate("Plot"), ctemplate::DO_NOT_STRIP, &plot, &text_plots);
    }

    // Sort alphabetically
    std::sort(branches.begin(), branches.end(), [](const Branch& a, const Branch& b) {
            return a.name < b.name;
            });

    std::string text_branches;
    for (const auto& branch: branches)  {
        text_branches += "const " + branch.type + "& " + branch.name + " = tree[\"" + branch.name + "\"].read<" + branch.type + ">();\n        ";
    }

    ctemplate::TemplateDictionary header("header");
    header.SetValue("BRANCHES", text_branches);

    std::string output;
    ctemplate::ExpandTemplate(getTemplate("Plotter.h"), ctemplate::DO_NOT_STRIP, &header, &output);

    std::ofstream out(output_dir + "/Plotter.h");
    out << output;
    out.close();

    output.clear();

    std::string text_save_plots;
    for (auto& p: plots) {
        ctemplate::TemplateDictionary save_plot("save_plot");
        save_plot.SetValue("UNIQUE_NAME", p.name);
        save_plot.SetValue("PLOT_NAME", unique_names[p.name]);
        ctemplate::ExpandTemplate(getTemplate("SavePlot"), ctemplate::DO_NOT_STRIP, &save_plot, &text_save_plots);
    }

    ctemplate::TemplateDictionary source("source");
    source.SetValue("HISTS_DECLARATION", hists_declaration);
    source.SetValue("PLOTS", text_plots);
    source.SetValue("SAVE_PLOTS", text_save_plots);
    ctemplate::ExpandTemplate(getTemplate("Plotter.cc"), ctemplate::DO_NOT_STRIP, &source, &output);

    out.open(output_dir + "/Plotter.cc");
    out << output;
    out.close();

    return true;
}
Пример #20
0
void Example_tags(TString topDir = "/star/rcf/GC/daq/tags")
{
//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Example_tags.C                                                       //
//                                                                      //
// shows how to use the STAR tags files                                 //
// Input: top level directory                                           //
//                                                                      //
// what it does:                                                        //
// 1. creates TChain from all tags files down from the topDir           //
// 2. loops over all events in the chain                                //
//                                                                      //
// owner: Alexandre V. Vaniachine <*****@*****.**>                //
//////////////////////////////////////////////////////////////////////////

  gSystem->Load("libTable");
  gSystem->Load("St_base");
  // start benchmarks
  gBenchmark = new TBenchmark();
  gBenchmark->Start("total");
   
  // set loop optimization level
  gROOT->ProcessLine(".O4");
  // gather all files from the same top directory into one chain
  // topDir must end with "/"
  topDir +='/';
  St_FileSet dirs(topDir);
  St_DataSetIter next(&dirs,0);
  St_DataSet *set = 0; 
  TChain chain("Tag");
  while ( (set = next()) ) {           
    if (strcmp(set->GetTitle(),"file") || 
	!(strstr(set->GetName(),".tags.root"))) continue;
    chain.Add(gSystem->ConcatFileName(topDir,set->Path()));
  }
  UInt_t nEvents = chain->GetEntries();
  cout<<"chained "<<nEvents<<" events "<<endl;

  TObjArray *files = chain.GetListOfFiles();
  UInt_t nFiles = files->GetEntriesFast();
  cout << "chained " << nFiles << " files from " << topDir << endl;

  TObjArray *leaves = chain.GetListOfLeaves();
  Int_t nleaves = leaves->GetEntriesFast();

  TString tableName = " ";
  TObjArray *tagTable = new TObjArray;

  Int_t tableCount = 0;
  Int_t *tableIndex = new Int_t[nleaves];
  Int_t tagCount = 0;

  // decode tag table names
  for (Int_t l=0;l<nleaves;l++) {
    TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
    tagCount+=leaf->GetNdata();
    TBranch *branch = leaf->GetBranch();
    // new tag table name
    if ( strstr(branch->GetName(), tableName.Data()) == 0 ) {
      tableName = branch->GetName();
      // the tableName is encoded in the branch Name before the "."
      tableName.Resize(tableName->Last('.'));
      tagTable->AddLast(new TObjString(tableName.Data()));
      tableCount++;
    }
    tableIndex[l]=tableCount-1;
  }
  cout << " tot num tables, tags = " << tableCount << "   " 
       << tagCount << endl << endl;

  //EXAMPLE 1: how to print out names of all tags and values for first event
  for (l=0;l<nleaves;l++) {
    leaf = (TLeaf*)leaves->UncheckedAt(l);
    branch = leaf->GetBranch();
    branch->GetEntry();
    // tag comment is in the title
    TString Title = leaf->GetTitle();
    Int_t dim = leaf->GetNdata();
    if (dim==1) {
      Title.ReplaceAll('['," '"); 
      Title.ReplaceAll(']',"'"); 
    }
    cout << "\n Table: ";
    cout.width(10);
    cout << ((TObjString*)tagTable->UncheckedAt(tableIndex[l]))->GetString()
	 <<" -- has tag: " << Title << endl;
    for (Int_t i=0;i<dim;i++) {
      cout <<"                               "<< leaf->GetName();
      if (dim>1) cout << '['<<i<<']';
      cout << " = " << leaf->GetValue(i) << endl; 
    }
  }

  // EXAMPLE 2: how to make a plot
  c1 = new TCanvas("c1","Beam-Gas Rejection",600,1000);
  gStyle->SetMarkerStyle(8);
  chain->Draw("n_trk_tpc[0]:n_trk_tpc[1]");

  // EXAMPLE 3: how to make a selection (write selected event numbers on the plot)
  Int_t ncoll=0;
  char aevent[10];
  TText t(0,0,"a");
  t.SetTextFont(52);
  t.SetTextSize(0.02);
  Float_t cut = 0.35;
  cout <<"\n Events with ntrk>400 and |asim|<"<<cut<<endl;
  //loop over all events: READ ONLY n_trk_tpc AND mEventNumber BRANCHES!
  gBenchmark->Start("loop");
  for (Int_t i=0;i<nFiles;i++) {
    chain.LoadTree(*(chain.GetTreeOffset()+i));
    TTree *T = chain.GetTree();
    //must renew leaf pointer for each tree
    TLeaf *ntrk = T->GetLeaf("n_trk_tpc");
    TLeaf *run = T->GetLeaf("mRunNumber");
    TLeaf *event = T->GetLeaf("mEventNumber");
    for (Int_t j=0; j<T->GetEntries(); j++){
      ntrk->GetBranch()->GetEntry(j);
      event->GetBranch()->GetEntry(j);
      run->GetBranch()->GetEntry(j);
      Int_t Nm=ntrk->GetValue(0);
      Int_t Np=ntrk->GetValue(1);
      Int_t Ntrk = Np+Nm;
      // avoid division by 0
      Float_t asim = Np-Nm;
      if (Ntrk>0) asim /= Ntrk;
      if (-cut < asim&&asim < cut && Ntrk>400) {
	cout<<"   Run "<<(UInt_t)run->GetValue()
	    <<", Event "<<event->GetValue() <<endl;
	ncoll++;
	sprintf(aevent,"%d",event->GetValue());
	t.DrawText(Np+10,Nm+10,aevent);
      }
    }
  }
  gBenchmark->Stop("loop");
  t.SetTextSize(0.05);
  t.DrawText(50,2550,"ntrk>400 and |(Np-Nm)/(Np+Nm)| < 0.35 ");
  t.DrawText(500,-300,"Ntrk with tanl<0 ");
  cout << " Selected " << ncoll << " collision candidates out of "
       << nEvents << " events" << endl;
  // stop timer and print benchmarks
  gBenchmark->Print("loop");  
  gBenchmark->Stop("total");
  gBenchmark->Print("total");  
}
Пример #21
0
/** @ingroup FMD_xsec_script
    @param scale 
    @param filename 
    @param var 
    @param medName 
    @param thick 
    @param pdgName 
*/
void
DrawXsection(Bool_t scale=kFALSE, 
	     const char* filename="xsec.root", 
	     const char* var="LOSS", 
	     const char* medName="FMD_Si$", 
	     Double_t thick=.03,
	     const char* pdgName="pi+")
{
  TFile*   file = TFile::Open(filename, "READ");
  TTree*   tree = static_cast<TTree*>(file->Get(Form("%s_%s",medName,
						     pdgName)));
  TLeaf* tb   = tree->GetLeaf("T");
  TLeaf* vb   = tree->GetLeaf(var);
  if (!vb) {
    std::cerr << "Leaf " << var << " not found" << std::endl;
    return;
  }
  Float_t tkine, value;
  tb->SetAddress(&tkine);
  vb->SetAddress(&value);
  Int_t n = tree->GetEntries();

  Float_t xscale = 1;
  Float_t yscale = 1;
  if (scale) {
    TDatabasePDG* pdgDb = TDatabasePDG::Instance();
    TParticlePDG* pdgP  = pdgDb->GetParticle(pdgName);
    if (!pdgP) {
      std::cerr << "Couldn't find particle " << pdgName << std::endl;
      return;
    }
    Double_t m = pdgP->Mass();
    Double_t q = pdgP->Charge() / 3;
    if (m == 0 || q == 0) {
      std::cerr  << "Mass is 0" << std::endl;
      return;
    }
    xscale = 1 / m;
    yscale = 1 / (q * q);
  }
  
  TGraphErrors* graph = new TGraphErrors(n);
  for (Int_t i = 0; i < n; i++) {
    tree->GetEntry(i);
    Double_t x = tkine*xscale;
    Double_t y = value*yscale;
    graph->SetPoint(i, x, y); 
    // 5 sigma
    graph->SetPointError(i, 0, 5 * .1 * y);
  }
  TCanvas* c = new TCanvas("c","c");
  c->SetLogx();
  c->SetLogy();
  graph->SetLineWidth(2);
  graph->SetFillStyle(3001);
  graph->SetFillColor(6);
  graph->Draw("L");
  graph->DrawClone("AL3");
  c->Modified();
  c->Update();
  c->cd();
  c->SaveAs("xsec.C");
  
}
Пример #22
0
// Generate dictionaries required to read `tree`.
void ensure_dictionaries(TTree *tree) {
    for (int li = 0; li < tree->GetListOfLeaves()->GetEntries(); li++) {
        TLeaf *l = (TLeaf*) tree->GetListOfLeaves()->At(li);
        ensure_dictionary(l->GetTypeName());
    }
}
Пример #23
0
//std::mutex mtx;
void ProcessFilePar(TString fileIn, TString fileOut, TString treename,  vector<TString> friends, vector<TString> branches, vector<TString> newbranches, unsigned jobid = 0, unsigned NPAR = 1)
{
  //mtx.lock(); //for threads
  TFile *fin = new TFile(fileIn);
  TTree *tjet = (TTree*)fin->Get(treename);
  //mtx.unlock();

  vector<TTree *> friendTrees;
  vector<bool> sameFileFriend;
  for (auto f:friends) {
    auto fr = tokenize(f,":");
    if (fr.size()==1) {tjet->AddFriend(fr[0]); sameFileFriend.push_back(true);}
    else if (fr.size()==2) {tjet->AddFriend(fr[1],fr[0]); sameFileFriend.push_back(false);}

    TTree *tfriend = (TTree*)fin->Get(f);
    friendTrees.push_back(tfriend);
  }

  AddBranchesByCounter(tjet, branches);
  for (unsigned i=0;i<friendTrees.size();i++) AddBranchesByCounter(friendTrees[i],branches);

  //sort branches into categories
  for (auto bName:branches) {
    TBranch *b=tjet->GetBranch(bName);
    if (b==0) cout <<"Branch "<<bName<<" doesn't exist!"<<endl;

    //parse in case there is a tree name in the branch
    auto branchtoken = tokenize(bName,".");
    auto leafname = branchtoken[branchtoken.size()-1];

    TObjArray *bl = b->GetListOfLeaves();
    if (bl->GetEntries()>1)
      cout <<" Branch "<<b->GetTitle()<<" has more than 1 leave. Taking first..."<<endl;
    if (bl->GetEntries()==0) {
      cout <<" Branch "<<b->GetTitle()<<" has no leaves! Skipping..."<<endl;
      continue;
    }

    TLeaf * l = (TLeaf *)(*bl)[0];
    //what's the type?
    TString type = l->GetTypeName();
    if (VERBOSE) cout<<l->GetTitle()<<endl;

    //array?
    bool array = l->GetLeafCount()!=0;
    TString counter;
    if (array) counter = l->GetLeafCount()->GetBranch()->GetName();

    if (type=="Float_t")
      {  if (array) {brVFloat.push_back(bName); brVFloatCounter.push_back(counter); }else brFloat.push_back(bName);}
    else if (type=="Int_t")
      {  if (array) {brVInt.push_back(bName); brVIntCounter.push_back(counter); }else brInt.push_back(bName);}
    else cout << "Unsupported branch type "<<type<<" for branch "<<bName<<". Skipping..."<<endl;
  }


  //treat counters as ints only
  AppendToListUniquely(brVIntCounter, brInt);
  AppendToListUniquely(brVFloatCounter, brInt);

  //too keep track of old branches, which cannot be read (todo: just check it...)
  int noldbrInt = brInt.size(), noldbrFloat = brFloat.size(), noldbrVInt = brVInt.size(), noldbrVIntCounter = brVIntCounter.size(), noldbrVFloat = brVFloat.size(), noldbrVFloatCounter = brVFloatCounter.size();
  //add new branches
  ParseNewBranches(newbranches, brInt, brFloat, brVInt, brVIntCounter, brVFloat, brVFloatCounter);

  //print for debugging
  if (VERBOSE) {
    cout<<"int       : "; for (auto s:brInt) cout <<s<<", "; cout<<endl;
    cout<<"float     : "; for (auto s:brFloat) cout <<s<<", "; cout<<endl;
    cout<<"Vint      : "; for (auto s:brVInt) cout <<s<<", "; cout<<endl;
    cout<<"Vfloat    : "; for (auto s:brVFloat) cout <<s<<", "; cout<<endl;
    cout<<"Vintcnt   : "; for (auto s:brVIntCounter) cout <<s<<", "; cout<<endl;
    cout<<"Vfloatcnt : "; for (auto s:brVFloatCounter) cout <<s<<", "; cout<<endl;
  }

  tjet->SetBranchStatus("*",1);
  for (auto b:brVFloat) if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,0);
  for (auto b:brFloat)  if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,0);
  for (auto b:brVInt)   if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,0);
  for (auto b:brInt)    if (tjet->GetBranch(b)!=0) {unsigned f=0; tjet->SetBranchStatus(b,0,&f); if (VERBOSE) cout<<"turning off "<<b<<", found = "<<f<<endl;}


  TFile *fout = new TFile(fileOut,"recreate");
  TTree *tjetout;


  //in case of one-to-many event - do not copy branches automatically!
  if (useOneToOne) tjetout = tjet->CloneTree(0);
  else tjetout = new TTree(tjet->GetName(),tjet->GetTitle());


  //think about memory tree
  // tjetout->SetDirectory(0);
  tjetout->SetName(tjet->GetName());
  //TTree *tjetout = new TTree("t","t");

  //to see what is copied...
  //tjetout->Print();

  for (auto b:brVFloat) if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);
  for (auto b:brFloat)  if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);
  for (auto b:brVInt)   if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);
  for (auto b:brInt)    if (tjet->GetBranch(b)!=0) tjet->SetBranchStatus(b,1);

  vector<int> valIntIn(brInt.size()), valIntOut(brInt.size());
  vector<float> valFloatIn(brFloat.size()), valFloatOut(brFloat.size());
  vector<vector<int> >valVIntIn (brVInt.size());  vector<vector<int> >valVIntOut (brVInt.size());
  vector<vector<float> >valVFloatIn (brVFloat.size());  vector<vector<float> >valVFloatOut (brVFloat.size());

  for (unsigned i=0;i<brInt.size();i++) {
    if (tjet->GetBranch(brInt[i])!=0)
      tjet->SetBranchAddress(brInt[i],&valIntIn[i]);

    if (tjetout->GetBranch(brInt[i])!=0) {//why would it?
      tjetout->SetBranchAddress(brInt[i],&valIntOut[i]); 
      cout<<"branch "<<brInt[i]<<" already exist for some reason..."<<endl; 
    }
    else //logical...
      if (NonFriendBranch(tjet, brInt[i])) 
	tjetout->Branch(brInt[i],&valIntOut[i],Form("%s/I",brInt[i].Data()));
  }

  for (unsigned i=0;i<brFloat.size();i++) {
    if (tjet->GetBranch(brFloat[i])!=0) 
      tjet->SetBranchAddress(brFloat[i],&valFloatIn[i]);
    
    if (NonFriendBranch(tjet, brFloat[i]))
      tjetout->Branch(brFloat[i],&valFloatOut[i],Form("%s/F",brFloat[i].Data()));
  }

  for (unsigned i=0;i<brVFloat.size();i++) {
    if (tjet->GetBranch(brVFloat[i])!=0) {
      valVFloatIn[i] = vector<float>(NMAX);
      tjet->SetBranchAddress(brVFloat[i],&valVFloatIn[i][0]);
    }
    

    valVFloatOut[i] = vector<float>(NMAX);
    if (NonFriendBranch(tjet, brVFloat[i]))
      tjetout->Branch(brVFloat[i],&valVFloatOut[i][0],Form("%s[%s]/F",brVFloat[i].Data(),brVFloatCounter[i].Data()));
  }

  for (unsigned i=0;i<brVInt.size();i++) {
    if (tjet->GetBranch(brVInt[i])) {
      valVIntIn[i] = vector<int>(NMAX);
      tjet->SetBranchAddress(brVInt[i],&valVIntIn[i][0]);
    }
    valVIntOut[i] = vector<int>(NMAX);
    if (NonFriendBranch(tjet, brVInt[i]))
      tjetout->Branch(brVInt[i],&valVIntOut[i][0],Form("%s[%s]/I",brVInt[i].Data(),brVIntCounter[i].Data()));
  }

  Long64_t nentries = tjet->GetEntries();
  int nentries1 = nentries/NPAR*jobid;
  int nentries2 = nentries/NPAR*(jobid+1);
  
  nentries = nentries2-nentries1; 
  int oneperc = nentries/100; if (oneperc==0) oneperc = 1;

  cout<<"Start processing..."<<endl;
  TStopwatch s;
  s.Start();
  TTimeStamp t0;
  double readTime = 0, processingTime = 0, copyToTime = 0, cloneTime=0, copyFromTime=0, fillTime = 0;
  

  for (Long64_t i=0; i<nentries;i++) {
    if (jobid==0 && i % oneperc == 0 && i>0) {
      std::cout << std::fixed;
      TTimeStamp t1; cout<<" \r"<<i/oneperc<<"%   "<<" est. time "<<setprecision(2) <<(t1-t0)*nentries/(i+.1)<<" s ";
      cout<<";Processing:"<<setprecision(2)<<processingTime/(t1-t0)*100<<" %";
      cout<<";Copy1:"<<setprecision(2) <<copyToTime/(t1-t0)*100<<" %";
      cout<<";Clone:"<<setprecision(2) <<cloneTime/(t1-t0)*100<<" %";
      cout<<";Copy2:"<<setprecision(2) <<copyFromTime/(t1-t0)*100<<" %";
      cout<<";Fill:"<<setprecision(2) <<fillTime/(t1-t0)*100<<" %";
      cout<<";Read:"<<setprecision(2) <<readTime/(t1-t0)*100<<" %";
      cout<<flush; 
    }
    
    TTimeStamp tsRead0;
    tjet->GetEntry(i+nentries1);
    TTimeStamp tsRead1;
    readTime+=tsRead1-tsRead0;

    Everything ev;
    TTimeStamp tsCpTo0;
    for (unsigned j=0;j<brInt.size();j++) ev.PutInt(brInt[j],valIntIn[j]);
    for (unsigned j=0;j<brFloat.size();j++) ev.PutFloat(brFloat[j],valFloatIn[j]);
    for (unsigned j=0;j<brVFloat.size();j++) ev.PutVFloat(brVFloat[j],brVFloatCounter[j],valVFloatIn[j]);
    for (unsigned j=0;j<brVInt.size();j++) ev.PutVInt(brVInt[j],brVIntCounter[j],valVIntIn[j]);
    TTimeStamp tsCpTo1;
    copyToTime+=tsCpTo1-tsCpTo0;
    

    TTimeStamp tsCl0;
    //think about: copy object (timing 10% ->3%) 
    //but it copies vectors, so push_back will add in the end...
    //    Everything evout = ev;
    //or even reference(in place?) (->0.2%)
    //Everything &evout = ev;
    Everything evout = ev.CloneStructure();
    TTimeStamp tsCl1;
    cloneTime+=tsCl1-tsCl0;

    bool exitEvent = false;
    int counter = 0;

    while (!exitEvent) {
    
    TTimeStamp tsPr0;
    if (useOneToOne) {
      fProcessOneToOne(ev, evout);
      evout.UpdateCounters();
      exitEvent = true;
    } else {
      exitEvent = fProcessOneToMany(ev, evout, counter); 
      //      if (!exitEvent) cout<<"event to write "<<counter<<endl;
      counter++;
    }

    TTimeStamp tsPr1;  
    processingTime+=tsPr1-tsPr0;
    
    
    //Everything evout = ev;
    TTimeStamp tsCpFrom0;
    for (unsigned j=0;j<brInt.size();j++) valIntOut[j] = evout.GetInt(brInt[j]);
    for (unsigned j=0;j<brFloat.size();j++) {valFloatOut[j] = evout.GetFloat(brFloat[j]); 
      //  cout<<brFloat[j]<<" "<<evout.GetFloat(brFloat[j])<<endl;
    }
    for (unsigned j=0;j<brVFloat.size();j++) valVFloatOut[j] = evout[brVFloat[j]];
    for (unsigned j=0;j<brVInt.size();j++) valVIntOut[j] = evout.GetVInt(brVInt[j]);
    TTimeStamp tsCpFrom1;
    copyFromTime+=tsCpFrom1-tsCpFrom0;

    TTimeStamp tsFill0;
    tjetout->Fill();
    TTimeStamp tsFill1;
    fillTime+=tsFill1-tsFill0;
  }

  }
  cout<<endl;
  s.Stop();
  cout<<"Done in ";s.Print();
  
  tjetout->FlushBaskets();
  tjetout->Write();
  
  cout<<"Copying other trees..."<<endl;

  for (unsigned i=0;i<friendTrees.size();i++) {
    TTree *t = friendTrees[i];
    if (sameFileFriend[i]) {
      //TTree *triendout = t->CloneTree(-1,"fast");
      TTree *triendout = t->CopyTree("","",nentries,nentries1);
      triendout->Write();
    }
  }
  


  fout->Close();
  friendTrees.clear();
}
Пример #24
0
int main() {
  // Get7 a map of the histograms of the Z Masses
  const std::string file_name = "/data/whybee0a/user/lesko_2/fermi/MadWithInitial/Mad2016_8_25/results/AllMHWithMothers.root";
  // Open the file and load the tree
  const std::string TreeName = "ZFinder/Combined Gen Cuts Reco/Combined Gen Cuts Reco";
  TTree* tree = GetTTree(file_name, TreeName);

  TBranch* reco = tree->GetBranch("reco");
  TLeaf* PhiStar = reco->GetLeaf("z_phistar_born");
  TLeaf* Mom1 = reco->GetLeaf("z_mom1PDG");
  TLeaf* Mom2 = reco->GetLeaf("z_mom2PDG");
  TLeaf* PenUltimateMom1 = reco->GetLeaf("z_penultimate1PDG");
  TLeaf* PenUltimateMom2 = reco->GetLeaf("z_penultimate2PDG");
  TLeaf* Z_YBorn = reco->GetLeaf("z_yBorn");

  ExploreTree(tree, Mom1, PenUltimateMom1, Mom2, PenUltimateMom2);

  TBranch* event_info = tree->GetBranch("event_info");
  //TLeaf* EVNumb = event_info->GetLeaf("event_number");
  // Pack into a hitogram

  for (int w = 0; w < 2; w++) {
    string PlotName;
    TLeaf* MomOrPenUltimateMom1 = w == 0 ? Mom1 : PenUltimateMom1;
    TLeaf* MomOrPenUltimateMom2 = w == 0 ? Mom2 : PenUltimateMom2;

    vector<string> NamesOfPlots;
    NamesOfPlots.push_back("UpQuarkPair"); //0
    NamesOfPlots.push_back("DownQuarkPair"); //1
    NamesOfPlots.push_back("StrangeQuarkPair"); //2
    NamesOfPlots.push_back("CharmQuarkPair"); //3
    NamesOfPlots.push_back("BottomQuarkPair"); //4
    NamesOfPlots.push_back("SingleQuark"); //5
    NamesOfPlots.push_back("Gluon"); //6
    NamesOfPlots.push_back("TwoQuarks"); //7
    NamesOfPlots.push_back("TwoAntiQuarks"); //8
    NamesOfPlots.push_back("QuarkAntiQuarkPair"); //9
    NamesOfPlots.push_back("QuarkAntiQuarkNotPair"); //10
    NamesOfPlots.push_back("Quark Quark And AntiQuark AntiQuark"); //11
    NamesOfPlots.push_back("Broken");

    map<string, TH1*> AllPlots;
    AllPlots[NamesOfPlots[0]] = new TH1D(NamesOfPlots[0].c_str(), NamesOfPlots[0].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[1]] = new TH1D(NamesOfPlots[1].c_str(), NamesOfPlots[1].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[2]] = new TH1D(NamesOfPlots[2].c_str(), NamesOfPlots[2].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[3]] = new TH1D(NamesOfPlots[3].c_str(), NamesOfPlots[3].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[4]] = new TH1D(NamesOfPlots[4].c_str(), NamesOfPlots[4].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[5]] = new TH1D(NamesOfPlots[5].c_str(), NamesOfPlots[5].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[6]] = new TH1D(NamesOfPlots[6].c_str(), NamesOfPlots[6].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[7]] = new TH1D(NamesOfPlots[7].c_str(), NamesOfPlots[7].c_str(), nphistar, phistarBins); //Two quarks
    AllPlots[NamesOfPlots[8]] = new TH1D(NamesOfPlots[8].c_str(), NamesOfPlots[8].c_str(), nphistar, phistarBins); //Two Anti quarks
    AllPlots[NamesOfPlots[9]] = new TH1D(NamesOfPlots[9].c_str(), NamesOfPlots[9].c_str(), nphistar, phistarBins); //
    AllPlots[NamesOfPlots[10]] = new TH1D(NamesOfPlots[10].c_str(), NamesOfPlots[10].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[11]] = new TH1D(NamesOfPlots[11].c_str(), NamesOfPlots[11].c_str(), nphistar, phistarBins);
    AllPlots[NamesOfPlots[12]] = new TH1D(NamesOfPlots[12].c_str(), NamesOfPlots[12].c_str(), nphistar, phistarBins);

    map<string, TH1*> RatioPlots; //using normalized versions of the pairs to see shape changes

    cout << "test 1" << endl;
    //Vector<TH1*> YplotsFromParents;
    //YplotsFromParents.push_back(new TH1D("YSeperatedUpQuarkPair", "UpQuarkPair", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedDownQuarkPair", "DownQuarkPair", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedStrangeQuarkPair", "StrangeQuarkPair", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedCharmQuarkPair", "CharmQuarkPair", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedBottomQuarkPair", "BottomQuarkPair", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedGluonQuarkPair", "GluonQuarkPair", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedGluon", "Gluon", nY, yBins));
    //YplotsFromParents.push_back(new TH1D("YSeperatedUnmatchingQuarks", "UnmatchingQuarks", nY, yBins));

    //TH2D* Parents = new TH2D("ParentsPDGId", "Parents PDGID", 28, -6.5, 21.5, 28, -6.5, 21.5);
    TH2D* ProductionVsY = new TH2D("ProductionVsY", "ProductionVsY", 7, 0, 7, 6, yBins);

    for (int i = 0; i < tree->GetEntries(); i++) {
      tree->GetEntry(i);
      if(PhiStar->GetValue()==-1)continue;
      if (fabs(MomOrPenUltimateMom1->GetValue()) == 1 && -MomOrPenUltimateMom1->GetValue() == MomOrPenUltimateMom2->GetValue()) {
        AllPlots["QuarkAntiQuarkPair"]->Fill(PhiStar->GetValue());
        AllPlots["UpQuarkPair"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(0.1, Z_YBorn->GetValue()
                );
      } else if (fabs(MomOrPenUltimateMom1->GetValue()) == 2 && -MomOrPenUltimateMom1->GetValue() == MomOrPenUltimateMom2->GetValue()) {
        AllPlots["QuarkAntiQuarkPair"]->Fill(PhiStar->GetValue());
        AllPlots["DownQuarkPair"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(1.1, Z_YBorn->GetValue());

      } else if (fabs(MomOrPenUltimateMom1->GetValue()) == 3 && -MomOrPenUltimateMom1->GetValue() == MomOrPenUltimateMom2->GetValue()) {
        AllPlots["QuarkAntiQuarkPair"]->Fill(PhiStar->GetValue());
        AllPlots["StrangeQuarkPair"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(2.1, Z_YBorn->GetValue());
      } else if (fabs(MomOrPenUltimateMom1->GetValue()) == 4 && -MomOrPenUltimateMom1->GetValue() == MomOrPenUltimateMom2->GetValue()) {
        AllPlots["QuarkAntiQuarkPair"]->Fill(PhiStar->GetValue());
        AllPlots["CharmQuarkPair"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(3.1, Z_YBorn->GetValue());
      } else if (fabs(MomOrPenUltimateMom1->GetValue()) == 5 && -MomOrPenUltimateMom1->GetValue() == MomOrPenUltimateMom2->GetValue()) {
        AllPlots["QuarkAntiQuarkPair"]->Fill(PhiStar->GetValue());
        AllPlots["BottomQuarkPair"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(4.1, Z_YBorn->GetValue());
      } else if ((MomOrPenUltimateMom1->GetValue() == 21 && fabs(MomOrPenUltimateMom2->GetValue()) < 7) || (MomOrPenUltimateMom2->GetValue() == 21 && fabs(MomOrPenUltimateMom1->GetValue()) < 7)) {
        AllPlots["SingleQuark"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(6.1, Z_YBorn->GetValue());
      } else if (fabs(MomOrPenUltimateMom1->GetValue()) == 21 && MomOrPenUltimateMom1->GetValue() == MomOrPenUltimateMom2->GetValue()) {
        AllPlots["Gluon"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(6.1, Z_YBorn->GetValue());
      } else if ((MomOrPenUltimateMom1->GetValue()) < 7 && (MomOrPenUltimateMom1->GetValue()) > 0 && (MomOrPenUltimateMom2->GetValue()) < 7 && (MomOrPenUltimateMom2->GetValue()) > 0) {
        AllPlots["TwoQuarks"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(7.1, Z_YBorn->GetValue());
      } else if ((MomOrPenUltimateMom1->GetValue()) > -7 && (MomOrPenUltimateMom1->GetValue()) < 0 && (MomOrPenUltimateMom2->GetValue()) > -7 && (MomOrPenUltimateMom2->GetValue()) < 0) {
        AllPlots["TwoAntiQuarks"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(7.1, Z_YBorn->GetValue());
      } else if (fabs(MomOrPenUltimateMom1->GetValue()) < 7 && fabs(MomOrPenUltimateMom1->GetValue()) < 7) {
        AllPlots["QuarkAntiQuarkNotPair"]->Fill(PhiStar->GetValue());
        ProductionVsY->Fill(7.1, Z_YBorn->GetValue());
      } else {
        cout << "SOmething broke" << endl;
        AllPlots["Broken"]->Fill(PhiStar->GetValue());
      }
    }
    
    {
        cout<<"Our first bin is "<<AllPlots["UpQuarkPair"]->GetBinContent(1)<<endl;
    }
    
  
    cout << "test 2" << endl;

    AllPlots["Quark Quark And AntiQuark AntiQuark"]->Add(AllPlots["TwoAntiQuarks"]);
    cout << "test 2.1" << endl;
    AllPlots["Quark Quark And AntiQuark AntiQuark"] ->Add(AllPlots["TwoQuarks"]);
    TH1D* AllQuarksNorm = (TH1D*) AllPlots["QuarkAntiQuarkPair"]->Clone("Devisor");
    AllQuarksNorm->Scale(1 / AllQuarksNorm->Integral());
    for (int i = 0; i < 5; i++) {
      string NewName = "Ratio" + NamesOfPlots[i];
      RatioPlots[NewName] = (TH1D*) AllPlots[NamesOfPlots[i]]->Clone(NewName.c_str());
      RatioPlots[NewName]->Scale(1 / RatioPlots[NewName]->Integral());
      RatioPlots[NewName]->Divide(AllQuarksNorm);
    }
    cout << "test 3" << endl;

    for (size_t i = 0; i < AllPlots.size(); i++) {
      for (size_t j = 1; j <= nphistar; j++) {
        AllPlots[NamesOfPlots[i]]->SetBinContent(j, AllPlots[NamesOfPlots[i]]->GetBinContent(j) / (phistarBins[j] - phistarBins[j - 1]));
      }
    }
    cout << "test 4" << endl;
    for (size_t i = 0; i < NamesOfPlots.size(); i++) {

      TCanvas canvas("canvas", "canvas", 1000, 1000);
      canvas.cd();
      canvas.SetLogx();
      canvas.SetLogy();
      gStyle->SetCanvasColor(0);
      gStyle->SetStatBorderSize(1);
      gStyle->SetOptStat("");
      gStyle->SetOptFit();
      AllPlots[NamesOfPlots[i]]->GetXaxis()->SetRangeUser(.004, 10);
      AllPlots[NamesOfPlots[i]]->Draw();
      AllPlots[NamesOfPlots[i]]->SetLineWidth(2);

      string SaveName = NamesOfPlots[i];
      SaveName = 0 == w ? "Mom_" + SaveName : "PenUltimate_" + SaveName;
      string WithType = "PhiStarPlots/Mompng/" + SaveName + ".png";
      canvas.Print(WithType.c_str());
      WithType = "PhiStarPlots/MomPDF/" + SaveName + ".pdf";
      canvas.Print(WithType.c_str());
      WithType = "PhiStarPlots/MomC/" + SaveName + ".C";
      canvas.Print(WithType.c_str());



      //if (i == 8)canvas.Print("Broken.png");
    }
    cout << "test 5" << endl;

    TCanvas canvas("c2", "c2", 1000, 1000);
    canvas.cd();
    canvas.SetLogx();
    canvas.SetLogy();
    gStyle->SetCanvasColor(0);
    gStyle->SetStatBorderSize(1);
    gStyle->SetOptStat("");

    AllPlots[NamesOfPlots[0]]->SetLineColor(kBlack);
    AllPlots[NamesOfPlots[1]]->SetLineColor(kBlue);
    AllPlots[NamesOfPlots[2]]->SetLineColor(kRed);
    AllPlots[NamesOfPlots[3]]->SetLineColor(kGreen + 1);
    AllPlots[NamesOfPlots[4]]->SetLineColor(kMagenta + 1);
    AllPlots[NamesOfPlots[5]]->SetLineColor(kOrange + 1);
    AllPlots[NamesOfPlots[6]]->SetLineColor(TColor::GetColor("#a65628"));
    AllPlots["Quark Quark And AntiQuark AntiQuark"]->SetLineColor(TColor::GetColor("#999999"));

    if (w == 0) {
      AllPlots[NamesOfPlots[0]]->SetTitle("");
      AllPlots[NamesOfPlots[0]]->SetXTitle("#phi^{*}");
      AllPlots[NamesOfPlots[0]]->GetXaxis()->CenterTitle();
      AllPlots[NamesOfPlots[0]]->Draw();
      AllPlots[NamesOfPlots[5]]->Draw("same");
    } else {
      AllPlots[NamesOfPlots[5]]->SetTitle("");
      AllPlots[NamesOfPlots[5]]->SetXTitle("#phi^{*}");
      AllPlots[NamesOfPlots[5]]->GetXaxis()->CenterTitle();
      AllPlots[NamesOfPlots[5]]->Draw();
      AllPlots[NamesOfPlots[0]]->Draw("same");
    }
    AllPlots[NamesOfPlots[1]]->Draw("same");
    AllPlots[NamesOfPlots[2]]->Draw("same");
    if (w == 0) {
      AllPlots[NamesOfPlots[3]]->Draw("same");
      AllPlots[NamesOfPlots[4]]->Draw("same");
    }
    AllPlots[NamesOfPlots[6]]->Draw("same");
    AllPlots["Quark Quark And AntiQuark AntiQuark"]->Draw("same");



    TLegend* leg = new TLegend(0.7, 0.70, 0.87, 0.89);
    leg->AddEntry(AllPlots[NamesOfPlots[0]], "u#bar{u}");
    leg->AddEntry(AllPlots[NamesOfPlots[1]], "d#bar{d}");
    leg->AddEntry(AllPlots[NamesOfPlots[2]], "s#bar{s}");
    if (w == 0) {
      leg->AddEntry(AllPlots[NamesOfPlots[3]], "c#bar{c}");
      leg->AddEntry(AllPlots[NamesOfPlots[4]], "b#bar{b}");
    }
    leg->AddEntry(AllPlots[NamesOfPlots[5]], "qg or #bar{q}g");
    leg->AddEntry(AllPlots[NamesOfPlots[6]], "gg");
    //leg->AddEntry(AllPlots[8], "Broken");NamesOfPlots[0]], "Up");
    leg->AddEntry(AllPlots[NamesOfPlots[11]], "qq or #bar{q}#bar{q}");
    leg->SetFillColor(0);
    leg->SetLineColor(0);
    leg->Draw("same");

    PlotName = w == 0 ? "Mom_AllLines.pn" : "PenUltimate_AllLines";
    string WithType = "PhiStarPlots/Mompng/" + PlotName + ".png";
    canvas.Print(WithType.c_str());
    WithType = "PhiStarPlots/MomPDF/" + PlotName + ".pdf";
    canvas.Print(WithType.c_str());
    WithType = "PhiStarPlots/MomC/" + PlotName + ".C";
    canvas.Print(WithType.c_str());
    TCanvas canvas3("c3", "c3", 1000, 1000);
    canvas3.cd();
    canvas3.SetLogz();
    gStyle->SetCanvasColor(0);
    gStyle->SetStatBorderSize(1);
    gStyle->SetOptStat("");
    cout << "test last" << endl;
    ProductionVsY->Draw("colz");
    PlotName = w == 0 ? "Mom_TwoDCompProductionToY" : "PenUltimate_TwoDCompProductionToY";
    WithType = "PhiStarPlots/Mompng/" + PlotName + ".png";
    canvas3.Print(WithType.c_str());
    WithType = "PhiStarPlots/MomPDF/" + PlotName + ".pdf";
    canvas3.Print(WithType.c_str());
    WithType = "PhiStarPlots/MomC/" + PlotName + ".C";
    canvas3.Print(WithType.c_str());
    cout << "test 7" << endl;

    TCanvas canvas4("c4", "c4", 1000, 1000); //Ratio Plots
    canvas4.Divide(1, 3 + 2 * (1 - w));
    //canvas4.SetLogx();
    //canvas4.SetLogy();
    for (int i = 0; i < 3 + 2 * (1 - w); i++) {
      string NewName = "Ratio" + NamesOfPlots[i];
      TPad * p = (TPad *) canvas4.cd(i + 1);
      p->SetLogx();
      RatioPlots[NewName]->GetXaxis()->SetRangeUser(.004, 10);
      RatioPlots[NewName]->GetXaxis()->SetTitle("#phi^{*}");
      RatioPlots[NewName]->GetXaxis()->CenterTitle();
      cout << "OUR FIRST BIN IS: " << RatioPlots[NewName]->GetBinContent(1) << endl;
      RatioPlots[NewName]->Draw();
    }
    //canvas4.cd(0);

    PlotName = w == 0 ? "Mom_RatioPlots" : "PenUltimate_RatioPlots";
    WithType = "PhiStarPlots/Mompng/" + PlotName + ".png";
    canvas4.Print(WithType.c_str());
    WithType = "PhiStarPlots/MomPDF/" + PlotName + ".pdf";
    canvas4.Print(WithType.c_str());
    WithType = "PhiStarPlots/MomC/" + PlotName + ".C";
    canvas4.Print(WithType.c_str());

    string FileName = w == 0 ? "Mom_PhiStarSeperated.root" : "PenUltimate_PhiStarSeperated.root";
    TFile SavedHistos(FileName.c_str(), "recreate");
    for (size_t i = 0; i < NamesOfPlots.size(); i++) {
      AllPlots[NamesOfPlots[i]]->Write();
    }
    SavedHistos.Write();
  }
  return EXIT_SUCCESS;
}
Пример #25
0
bool TreeReader::Initialize(vector <string> br, string opt)
{
	if(!init)
	{
	    if( !fChain )
		{
		        cout << endl;
			cout << "No tree to initialize" << endl;
			cout << endl;
			return false;
		}

		TObjArray *fileElements = fChain->GetListOfFiles();
		if( !fileElements || ( fileElements->GetEntries() == 0 ))
		{
		        cout << endl;
			cout << "No file(s) to initialize" << endl;
			cout << endl;
			return false;
		}
	}

	varList.clear();

	TObjArray* branches = fChain->GetListOfBranches();
	int nBranches = branches->GetEntries();

	for (int i = 0; i < nBranches; ++i)
	{
		TBranch* branch = (TBranch*)branches->At(i);
		string brname = branch->GetName();
		TLeaf* leaf = branch->GetLeaf(branch->GetName());

		if ( leaf == 0 )  // leaf name is different from branch name
		{
			TObjArray* leafs = branch->GetListOfLeaves();
			leaf = (TLeaf*)leafs->At(0);
		}

		string curtype = leaf->GetTypeName();
        int id = TypeDB::getType(curtype.c_str());
		int arreysize = 1;
		string title = leaf->GetTitle();
        //cout << curtype << "   " << title << endl;

		// Find out whether we have array by inspecting leaf title
		if ( title.find("[")!=std::string::npos )
		{
			TLeaf * nelem = leaf->GetLeafCounter(arreysize);
			if(arreysize == 1 && nelem != NULL) arreysize = nelem->GetMaximum() + 1; //search for maximum value of the lenght
		}


		if(id >= 0)
		{
			bool addVar = true;
			if(br.size()>0)
			{
				addVar = false;
				for(unsigned b = 0; b < br.size(); b++)
				{
					if(opt == "names" || opt == "except")
					{
						if(br[b] == brname) { addVar = true; break;}
					}
					else if(opt.find("contains")!=string::npos)
					{
						if((string(brname)).find(br[b])!=string::npos) { addVar = true; break;}
					}
					else if(opt.find("except")==string::npos) cout << "Option " << opt << " not found" << endl;
				}

				if(opt.find("except")!=string::npos) addVar = !addVar;
			}

			if(addVar)
			{
				variable * tmpVar = new variable(id,arreysize);

				tmpVar->name = leaf->GetName();
				tmpVar->bname = branch->GetName();
				tmpVar->title = title;

				varList.push_back(tmpVar);
				fChain->SetBranchAddress(tmpVar->bname,tmpVar->value.address);
			}
		}
		else
		{
			cout << curtype << ": type not found" << endl;
			exit(1);
			return false;
		}
	}

	init = true;
	continueSorting = true;
	if(pmode=="v") cout << endl << "Set up " << varList.size() << " / " << nBranches << " branches" << endl;

	return true;
}
Пример #26
0
int macroanalysis(char* filename)
{
    // char* filename = "combined.root";
    // Read in the file
    TFile* f = new TFile(filename);
    // TDirectory* hists  = f->GetDirectory("hists;1");
    // TDirectory* tuples = f->GetDirectory("tuples;1");

    TTree* accum = (TTree*) f->GetObjectUnchecked("AccumulatedEnergy;1");
    TLeaf* einit = (TLeaf*) accum->GetLeaf("Einit");
    TLeaf* edepo = (TLeaf*) accum->GetLeaf("Edep");

    TTree* edeps = (TTree*) f->GetObjectUnchecked("EnergyDepositions;1");
    TLeaf* individualdepos = (TLeaf*) edeps->GetLeaf("Edep");

    TTree* secs  = (TTree*) f->GetObjectUnchecked("SecondarySpectrum;1");
    TLeaf* secsenergy = (TLeaf*) secs->GetLeaf("KineticEnergy");

    double ein = 0;
    double eout = 0;



    int nevents = accum->GetEntries();
    for (int ii = 0; ii<nevents; ii++)
    {
        accum->GetEntry(ii);
        ein+=einit->GetValue();
        eout+=edepo->GetValue();
    }


    int ndepos = edeps->GetEntries();
    double deposum = 0;
    for (int ii = 0; ii<ndepos; ii++)
    {
        edeps->GetEntry(ii);
        deposum+=individualdepos->GetValue();
    }


    int nsecs = secs->GetEntries();
    double secsum = 0;
    for (int ii = 0; ii<nsecs; ii++)
    {
        secs->GetEntry(ii);
        secsum+=secsenergy->GetValue();
    }

    cout << "Making Summary\n";
    FILE* summary = fopen("macro_summ.txt", "a+");

    time_t t = time(NULL);
    char* c_time_string = std::ctime(&t);
    char mytime[20];
    std::strncpy(mytime, c_time_string, 19);
    mytime[ std::strlen(mytime) - 1 ] = '\0';

    std::fprintf(summary, "%s,%s,%i,%e,%e,%i,%e,%i,%e\n", mytime, filename,
            nevents, ein, eout, ndepos, deposum, nsecs, secsum);
    fclose(summary);

    cout << "Making Histogram\n";

    nevents = secs->GetEntries();
    TH1F* secondarieslow = new TH1F("secondarieslow", "Secondary Electrons <1 keV", 900, 0.000100, 0.001000);
    TH1F* secondariesmid = new TH1F("secondariesmid", "Secondary Electrons 1<E<10 keV", 900, 0.001, 0.010);
    TH1F* secondarieshigh = new TH1F("secondarieshigh", "Secondary Electrons 10<E<100 keV", 900, 0.010, 0.100);
    TH1F* secondariesveryhigh = new TH1F("secondariesveryhigh", "Secondary Electrons 100keV<E<3 MeV", 2902, 0.100, 3.002);

    for (int ii = 0; ii<nevents; ii++)
    {
        secs->GetEntry(ii);
        double en = secsenergy->GetValue();
        if (en < 0.001) secondarieslow->Fill(en, 1);
        else if (en < 0.01) secondariesmid->Fill(en, 0.1);
        else if (en < 0.1) secondarieshigh->Fill(en, 0.01);
        else secondariesveryhigh->Fill(en, 0.001);

    }

    char suffix[] = ".secondaryhisto";

    cout << "Making Filenames\n";


    char* outfilename = (char*) malloc(std::strlen(filename) + std::strlen(suffix) + 1);
    std::strcpy(outfilename, filename);
    std::strcat(outfilename, suffix);

    std::printf("Saving Histogram: %s \n", outfilename);
    h12ascii(secondarieslow, secondariesmid, secondarieshigh, secondariesveryhigh, outfilename);

    return 0;

}
Пример #27
0
/// Cache MC production information
void CacheTrendingProductions(TString dataType){
  AliExternalInfo info;
  info.fLoadMetadata=kFALSE;
  TObjArray* periodList = NULL, *idList=NULL;
  //
  TTree * tree = info.GetTree("MonALISA.ProductionCycle","","");
  Int_t nProd=tree->GetEntries();
  periodList = new TObjArray(nProd);
  idList= new TObjArray(nProd);
  TLeaf *leafTag = tree->GetLeaf("Tag");
  TLeaf *leafID   =  tree->GetLeaf("ID");
  for (Int_t iProd=0; iProd<nProd; iProd++){
    tree->GetEntry(iProd);
    TString prodName=((char*)leafTag->GetValuePointer());
    TString  idName =TString::Format("%d",TMath::Nint(leafID->GetValue()));
    if (prodName.Contains("LHC")==0) continue;
    periodList->AddAt(new TObjString(prodName),iProd);
    idList->AddAt(new TObjString(idName),iProd);
  }
  delete tree;
  //
  for (Int_t iPeriod=0; iPeriod<periodList->GetEntriesFast(); iPeriod++) {
    TObjString * pName= (TObjString*)idList->At(iPeriod);
    if (pName==NULL) continue;
    TTree* treeP = info.GetTreeProdCycleByID(idList->At(iPeriod)->GetName());
    if (treeP==NULL) continue;
    TLeaf *leafOutput = treeP->GetLeaf("outputdir");
    Int_t nRuns= treeP->GetEntries();
    treeP->GetEntry(0);
    TString path=((char*)leafOutput->GetValuePointer());
    TObjArray *pArray = path.Tokenize("/");
    if (pArray==NULL) continue;
    Int_t nElems=pArray->GetEntries();
    if (nElems<4) continue;
    TString aperiod=pArray->At(3)->GetName();
    TString apass =pArray->At(nElems-1)->GetName();
    delete pArray;
    ::Info("CacheTrendingProductions","%s\t%s\t%s\t%s\t%d",idList->At(iPeriod)->GetName(),path.Data(), aperiod.Data(),apass.Data(),nRuns);
    delete treeP;
    TTree* treeQA = info.GetTree(dataType.Data(),aperiod.Data(),apass.Data());
    if (treeQA){
      Int_t entries=treeQA->Draw("run","1","goff");
      TString sInfo=aperiod;
      sInfo+="\t";
      sInfo+=apass;
      sInfo+="\t";
      sInfo+=dataType;
      sInfo+="\t";
      sInfo+=TString::Format("%d\t",entries);
      sInfo+=TString::Format("%d\t",nRuns);
      for (Int_t j=0; j<entries; j++) {
        sInfo+=TString::Format("%2.0f,",treeQA->GetV1()[j]);
        ::Info("CacheTrendingProductionsRun:","%s\t%s\t%s\t%d\t%d\t%2.0f",aperiod.Data(),apass.Data(),dataType.Data(),entries,nRuns,treeQA->GetV1()[j]);
      }
      sInfo+="0";
      ::Info("CacheTrendingProductionsPeriod:","%s\n",sInfo.Data());
      delete treeQA;
    }else{
      ::Error("CacheTrendingProductionsPeriod:","%s\t%s\t%s\t-1\t%d\t0",aperiod.Data(),apass.Data(), dataType.Data(),nRuns);
    }
  }
}
Пример #28
0
void dump_tree(TTree *tree, const char *outdir) {
    GzipOutputStream::Options options;
    options.compression_level = 1;

    for(int li = 0; li < tree->GetListOfLeaves()->GetEntries(); li++) {
        TLeaf *l = (TLeaf*) tree->GetListOfLeaves()->At(li);

        if (lstat(outdir, NULL) == -1) {
            mkdir(outdir, 0777);
        }

        // Open data file
        std::string fn = std::string(outdir) + "/" + l->GetName() + ".dit";
        auto fd = open(fn.c_str(), O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
        assert(fd != -1);
        FileOutputStream fstream(fd);
        GzipOutputStream zstream(&fstream, options);


        // Open meta file
        std::string mfn = fn + "m";
        auto mfd = open(mfn.c_str(), O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
        assert(mfd != -1);
        FileOutputStream meta_fstream(mfd);
        GzipOutputStream meta_zstream(&meta_fstream, options);
        { // Coded stream block 
            CodedOutputStream o(&zstream);
            CodedOutputStream o2(&meta_zstream);

            // determine level and type name
            int level = 0;
            std::string tn = l->GetTypeName();
            while (tn.substr(0,6) == "vector") {
                level = level + 1;
                tn = remove_vector(tn);
            }

            if (tn == "double") {
                dump_required<double>(level, tree, *l, o, o2);
            } else if (tn == "float") {
                dump_required<float>(level, tree, *l, o, o2);
            } else if (tn == "int") {
                dump_required<int>(level, tree, *l, o, o2);
            } else if (tn == "short" || tn == "Short_t") {
                dump_required<short>(level, tree, *l, o, o2);
            } else if (tn == "unsigned int") {
                dump_required<unsigned int>(level, tree, *l, o, o2);
            } else if (tn == "unsigned short") {
                dump_required<unsigned short>(level, tree, *l, o, o2);
            } else if (tn == "Float_t") {
                dump_required<Float_t>(level, tree, *l, o, o2);
            } else if (tn == "Bool_t") {
                dump_required<Bool_t>(level, tree, *l, o, o2);
            } else if (tn == "Char_t") {
                dump_required<Char_t>(level, tree, *l, o, o2);
            } else if (tn == "Double_t") {
                dump_required<Double_t>(level, tree, *l, o, o2);
            } else if (tn == "Int_t") {
                dump_required<Int_t>(level, tree, *l, o, o2);
            } else if (tn == "UInt_t") {
                dump_required<UInt_t>(level, tree, *l, o, o2);
            } else if (tn == "string") {
                dump_required<std::string>(level, tree, *l, o, o2);
            } else {
                std::cerr << "Unknown branch type: " << tn << std::endl;
                assert(false);
            }
        }
        meta_zstream.Close();
        zstream.Close();
        meta_fstream.Close();
        fstream.Close();
    }
}
Пример #29
0
int main(int argc, char* argv[])
{
  vector<vector<double> >* voltages = new vector<vector<double> >;
  vector<vector<double> >* currents = new vector<vector<double> >;
  voltages->resize(52);
  currents->resize(52);
  TChain* chain = loadChain(argc, argv);
  int entries = chain->GetEntries();

  cout << entries/2 << " files\n";

  for(int i=0; i<entries; i++)
  {
    chain->GetEvent(i);
    for(int slot=0; slot<16; slot++)
    {
      TLeaf* vleaf = chain->GetLeaf(("VHS_"+target_card[slot]+".VM."+target_channel[slot]).c_str());
      voltages->at(slot).push_back(vleaf->GetValue(0));
      TLeaf* ileaf = chain->GetLeaf(("VHS_"+target_card[slot]+".IM."+target_channel[slot]).c_str());
      currents->at(slot).push_back(ileaf->GetValue(0));      
    }
    for(int slot=0; slot<36; slot++)
    {
      if(veto_card[slot]=="4_3")
      {
	voltages->at(slot+16).push_back(-1);
	currents->at(slot+16).push_back(-1);
      }
      else
      {
	TLeaf* vleaf = chain->GetLeaf(("VHS_"+veto_card[slot]+".VM."+veto_channel[slot]).c_str());
	voltages->at(slot+16).push_back(vleaf->GetValue(0));
	TLeaf* ileaf = chain->GetLeaf(("VHS_"+veto_card[slot]+".IM."+veto_channel[slot]).c_str());
	currents->at(slot+16).push_back(ileaf->GetValue(0));
      }
    }
  }
  
  const double allowed_dv = 100;
  const double allowed_di = 50e-06;

  vector<bool> pmt_flags_v;
  vector<bool> pmt_flags_i;
  pmt_flags_v.resize(52,0);
  pmt_flags_i.resize(52,0);


  for( auto pmt = voltages->begin();
       pmt!=voltages->end(); ++pmt )
  {
    double meanvalue = mean(*pmt);
    double deviation = std_dev(*pmt);
    //cout << "Mean: " << meanvalue << " Dev: " << deviation << endl;
    for(auto it2 = (*pmt).begin();
	it2!=(*pmt).end(); ++it2)
    {
      //cout << distance((*it).begin(), it2) << " ";
      if( abs(*it2-meanvalue) > allowed_dv )
	pmt_flags_v.at( distance(voltages->begin(), pmt) ) = true;
    }
  }

  for( auto pmt = currents->begin();
       pmt!=currents->end(); ++pmt )
  {
    double meanvalue = mean(*pmt);
    double deviation = std_dev(*pmt);
    for(auto it2 = (*pmt).begin();
	it2!=(*pmt).end(); ++it2)
      if( abs(*it2-meanvalue) > allowed_di )
	pmt_flags_i.at( distance(currents->begin(), pmt) ) = true;
  }

  bool error = false;
  // Now if we managed to pick up some flags lets say so
  for(auto it = pmt_flags_v.begin();
      it!=pmt_flags_v.end(); ++it)
    if(*it==true)
    {
      cout << "PMT: " << distance(pmt_flags_v.begin(), it) << " varied VOLTAGE more than "
	   << allowed_dv << " from its mean value" << endl;
      error = true;
    }

  for(auto it = pmt_flags_i.begin();
      it!=pmt_flags_i.end(); ++it)
    if(*it==true)
    {
      cout << "PMT: " << distance(pmt_flags_i.begin(), it) << " varied CURRENT more than "
	   << allowed_di << " from its mean value" << endl;
      error = true;
    }

  if(error == true)
  {
    cout << ">>> See error.txt for full report <<<" << endl;
    writeReport(voltages, pmt_flags_v, currents, pmt_flags_i);
  }

  delete currents;
  delete voltages;
  return 0;
}