Ejemplo n.º 1
0
void generatePlots(Files *inputs, const string &path)
{
    Files::const_iterator first_source = inputs->begin();
    TDirectory *folder = dynamic_cast<TDirectory *>(first_source->second->Get(path.c_str()));
    if (!folder)
    {
        cerr << "Failed to extract folder: " << path << endl;

        return;
    }
    //
    //gain time, do not add the objects in the list in memory
    //
    Bool_t status = TH1::AddDirectoryStatus();
    TH1::AddDirectory(kFALSE);

    // loop over all keys in this directory
    TIter nextkey(folder->GetListOfKeys() );

    for(TKey *key, *oldkey=0; key = (TKey*) nextkey(); )
    {
        //keep only the highest cycle number for each key
        if (oldkey
            && !strcmp(oldkey->GetName(), key->GetName()))

            continue;

        // read object from first source file
        //
        TObject *obj = key->ReadObj();

        if ( obj->IsA()->InheritsFrom(TH1::Class()))
        {
            cout << obj->GetName() << endl;

            TCanvas *canvas = new TCanvas();

            canvas->SetWindowSize(640, 480);

            THStack *stack = new THStack();
            TLegend  *legend = new TLegend(.6, .98, .98, .58);
            legend->SetBorderSize(1);
            legend->SetLineStyle(1);
            legend->SetTextFont(43);
            legend->SetTextSizePixels(12);
            legend->SetFillColor(0);

            TH1 *h1 = dynamic_cast<TH1*>(obj);
            legend->AddEntry(h1, style(h1, first_source->first).c_str(), "pl");
            h1->Scale(1.0 / h1->Integral());

            stack->Add(h1);

            // loop over all source files and add the content of the
            // correspondant histogram to the one pointed to by "h1"
            for(Files::const_iterator input = ++inputs->begin();
                    inputs->end() != input;
                    ++input)
            {
                TH1 *h2 = dynamic_cast<TH1*>(input->second->Get((path + "/" + obj->GetName()).c_str()));
                if (!h2)
                {
                    cerr << "Failed to extract plot from input: " << endl;

                    continue;
                }

                h2->Scale(1. / h2->Integral());
                legend->AddEntry(h2, style(h2, input->first).c_str(), "pl");
                stack->Add(h2);
            }

            stack->Draw("h nostack");
            legend->Draw();
            stack->GetXaxis()->SetTitle(h1->GetXaxis()->GetTitle());

            canvas->Update();
        } else {
            // object is of no type that we know or can handle
            //
            cout << "Unknown object type, name: "
                << obj->GetName() << " title: " << obj->GetTitle() << endl;
        }
    }

    // save modifications to target file
    TH1::AddDirectory(status);
}
Ejemplo n.º 2
0
TList* readHistos(vector<string> inputRootFiles, bool fillNameStrings){
  TList* thelistHistos = new TList();
  for (int j=0; j< inputRootFiles.size(); j++) 
    {
      int numMax = 0;
      //cout <<"inputProcess: "<<inputProcess.at(j)<<endl;
      // Access input ROOT file (can access over secure shell)
      cout <<"inputRootFiles.at(j) "<<inputRootFiles.at(j)<<endl; 
      TFile *rootTFile = new TFile((inputRootFiles.at(j)).c_str()); // open root file
      TDirectory *current_sourcedir = gDirectory;
      TIter nextkey( current_sourcedir->GetListOfKeys() );
      TKey *key;
      
      // loop over keys(ROOT objects) within the root file
      while ((key = (TKey*)nextkey())) 
        {
	  TObject *obj = key->ReadObj();
	  
	  TH1 *histoObj = (TH1*)obj;
	  TH1* h1 = 0; //points to the new copied hist we will make
          int totalbins = 0;
	  // rename histogram
          if ( obj->IsA()->InheritsFrom( "TH1" ) ) 
            {
              string histname = obj->GetName();
	      size_t found = histname.find("lumi");
              string theProcess = "lumi";

              string new_theProcess = "_" + theProcess;
              histname.erase(found-1, new_theProcess.size());
              string histName = histname;
              cout << histName << endl;
              for (int o = 0; o < inputHistoName.size(); o++)
                {   
                  if ( histName == inputHistoName.at(o) )
		    {
                      int numBins = histoObj->GetXaxis()->GetNbins();
		      double lowerEdge = histoObj->GetXaxis()->GetXmin();
		      double upperEdge = histoObj->GetXaxis()->GetXmax();
		      
		      h1 = new TH1F (histName.c_str(), histName.c_str(),
			             numBins, lowerEdge, upperEdge);
                      
                      TH1F* tmp2 = static_cast<TH1F*>(h1);
                      totalbins = tmp2->GetSize();

                      for (int k=0; k <= totalbins; k++)
                        {
                          h1->SetBinContent(k,(histoObj->GetBinContent(k)));
                          h1->SetBinError(k,(histoObj->GetBinError(k)));
                        }

                      h1 = Rebinh(h1);
                      //cout<<"h1 "<<h1->GetName()<<"   Integral  "<<h1->Integral()<<endl; 
		      thelistHistos->Add(h1);
		      if(fillNameStrings) nHistList++;
		      if(fillNameStrings) theHistNameStrings.push_back(histName);
		      numMax++;
		    } // close if loop on selected histograms
		} // close for loop on selected histograms
	    } // close if loop InheritsFrom("TH1")
	} // close while loop
      // If first input ROOT file (Data), store total number of histograms
      if (j == 0)
          numHistos = numMax;
      // Else exit the code if a ROOT file has a different number of histograms
      else
        {
          if (numMax != numHistos)
            {
              cerr << "ERROR: Input Root Files DO NOT have the same number"
                   << " of histograms." << endl;
              exit (1);
            }
        }
    } // close for loop over root files

    return thelistHistos;
}
Ejemplo n.º 3
0
void MergeHistos(TDirectory *target, TList *sourcelist) {
  

  cout << "Target path: " << target->GetPath() << endl;
  TString path( (char*)strstr( target->GetPath(), ":" ) );
  path.Remove( 0, 2 );
  TFile *first_source = (TFile*)sourcelist->First();
  
  first_source->cd(path);
  
  TDirectory *current_sourcedir = gDirectory;
  //gain time, do not add the objects in the list in memory
  Bool_t status = TH1::AddDirectoryStatus();
  TH1::AddDirectory(kFALSE);

  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key, *oldkey=0;
  cout << "Merging histograms ..." << endl;
  while ( (key = (TKey*)nextkey())) {

    //keep only the highest cycle number for each key
    if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;

    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();

    if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) {
      // descendant of TH1 -> merge it

      cout << "               ..." << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;

      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      while ( nextsource ) {
	//cout << "     File: " << nextsource->GetName() << endl;
	// make sure we are at the correct directory level by cd'ing to path
	nextsource->cd( path );
	TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
	if (key2) {
	  TH1 *h2 = (TH1*)key2->ReadObj();
	  h1->Add( h2 );
	  delete h2;
	}
	else {
	  // damaged file
	}

	nextsource = (TFile*)sourcelist->After( nextsource );
      }
    }
    else if ( obj->IsA()->InheritsFrom( TTree::Class() ) ) {
      /*
      // loop over all source files create a chain of Trees "globChain"
      const char* obj_name= obj->GetName();

      globChain = new TChain(obj_name);
      globChain->Add(first_source->GetName());
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      //      const char* file_name = nextsource->GetName();
      // cout << "file name  " << file_name << endl;
      while ( nextsource ) {

      globChain->Add(nextsource->GetName());
      nextsource = (TFile*)sourcelist->After( nextsource );
      }
      */
    } else if ( obj->IsA()->InheritsFrom( TDirectory::Class() ) ) {
      // it's a subdirectory

      cout << "Found subdirectory " << obj->GetName() << endl;

      // create a new subdir of same name and title in the target file
      target->cd();
      TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );

      // newdir is now the starting point of another round of merging
      // newdir still knows its depth within the target file via
      // GetPath(), so we can still figure out where we are in the recursion
      MergeHistos( newdir, sourcelist );

    } else {

      // object is of no type that we know or can handle
      cout << "Unknown object type, name: "
	   << obj->GetName() << " title: " << obj->GetTitle() << endl;
    }

    // now write the merged histogram (which is "in" obj) to the target file
    // note that this will just store obj in the current directory level,
    // which is not persistent until the complete directory itself is stored
    // by "target->Write()" below
    if ( obj ) {
      target->cd();

      //!!if the object is a tree, it is stored in globChain...
      if(obj->IsA()->InheritsFrom( TTree::Class() ))
	//globChain->Merge(target->GetFile(),0,"keep");
	cout << " skiped TTree " << endl;
      else
	obj->Write( key->GetName() );
    }

  } // while ( ( TKey *key = (TKey*)nextkey() ) )
  

    // save modifications to target file
  target->SaveSelf(kTRUE);
  TH1::AddDirectory(status);
  
}
Ejemplo n.º 4
0
//-----------------------------------------------------------------------------
StatusCode
RootHistCnv::RDirectoryCnv::fillObjRefs(IOpaqueAddress* pAddr,DataObject* pObj)  {
  MsgStream log(msgSvc(), "RDirectoryCnv");
  IRegistry* pReg = pObj->registry();
  std::string full  = pReg->identifier();
  const std::string& fname = pAddr->par()[0];

  TFile *tf;
  findTFile(full,tf).ignore();

  // cd to TFile:
  setDirectory(full);
  TIter nextkey(gDirectory->GetListOfKeys());
  while (TKey *key = (TKey*)nextkey()) {
    IOpaqueAddress* pA = 0;
    TObject *obj = key->ReadObj();
    std::string title = obj->GetTitle();
    std::string sid = obj->GetName();
    std::string f2 = full + "/" + sid;
    int idh = ::strtol(sid.c_str(),NULL,10);
    // introduced by Grigori Rybkine
    std::string clname = key->GetClassName();
    std::string clnm = clname.substr(0,3);
    TClass* isa = obj->IsA();
    if (isa->InheritsFrom("TTree")) {
      createAddress(full, CLID_ColumnWiseTuple, idh, obj, pA).ignore();
      TTree* tree = (TTree*) obj;
      tree->Print();
      log << MSG::DEBUG << "Reg CWNT \"" << obj->GetTitle()
       	  << "\" as " << f2 << endmsg;
      title = "/" + sid;
    } else if (isa->InheritsFrom("TDirectory")) {
      createAddress(full,CLID_NTupleDirectory, title, obj, pA).ignore();
    } else if ( isa == TProfile::Class() ) {
      createAddress(full,CLID_ProfileH,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TProfile2D::Class() ) {
      createAddress(full,CLID_ProfileH2,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1C::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1S::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1I::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1F::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1D::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2C::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2S::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2I::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2F::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2D::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3C::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3S::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3I::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3F::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3D::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else {
      log << MSG::ERROR << "Encountered an unknown object with key: "
      	  << obj->GetName() << " in ROOT file " << fname << endmsg;
      return StatusCode::FAILURE;
    }
    if ( 0 != pA )    {
      StatusCode sc = dataManager()->registerAddress(pReg, title, pA);
      if ( !sc.isSuccess() )  {
        log << MSG::ERROR << "Failed to register address for " << full  << endmsg;
        return sc;
      }
      log << MSG::VERBOSE << "Created address for " << clnm
          << "'" << title << "' in " << full << endmsg;
    }
  }
  return StatusCode::SUCCESS;
}
Ejemplo n.º 5
0
Bool_t fitsHere(TLegend *l,Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
    Bool_t fits = true;
    TList *list = l->GetListOfPrimitives();
    for (Int_t k = 0; list->At(k) != 0 && fits; k++)
    {
        TObject *obj = ((TLegendEntry*)(list->At(k)))->GetObject();
        if (obj == 0) continue;
        TClass *cl = obj->IsA();

        //Histogram, drawn as a histogram
        if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
         && cl != TProfile::Class() && ((TH1*)obj)->GetMarkerColor() == kWhite)
        {
            Int_t where = 0;
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i) < x1) continue;   //to the left of the legend
                if (h->GetBinLowEdge(i)                     > x2) continue;   //to the right of the legend
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;   //inside the legend
                if (h->GetBinContent(i) < y1)
                {
                    if (where == 0) where = -1;             //below the legend
                    if (where == 1) fits = false;           //a previous bin was above it so there's a vertical line through it
                }
                if (h->GetBinContent(i) > y2)
                {
                    if (where == 0) where = 1;              //above the legend
                    if (where == -1) fits = false;          //a previous bin was below it so there's a vertical line through it
                }
            }
            continue;
        }
        //Histogram, drawn with Draw("P")
        else if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
              && cl != TProfile::Class())
        //Probably TProfile would be the same but I haven't tested it
        {
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i)/2 < x1) continue;
                if (h->GetBinLowEdge(i)                       > x2) continue;
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y2 && h->GetBinContent(i) - h->GetBinError(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y1 && h->GetBinContent(i) - h->GetBinError(i) < y1) fits = false;
            }
        }
        else if (cl->InheritsFrom("TF1") && !cl->InheritsFrom("TF2"))
        {
            //TF1 *f = (TF1*)obj;
            //Double_t max = f->GetMaximum(x1,x2);
            //Double_t min = f->GetMinimum(x1,x2);
            //if (min < y2 && max > y1) fits = false;
        }
        // else if (cl->InheritsFrom(...... add more objects here
        else
        {
            cout << "Don't know how to place the legend around objects of type " << obj->ClassName() << "." << endl
                 << "Add this class into placeLegend.C if you want it to work properly." << endl
                 << "The legend will still be placed around any other objects." << endl;
        }
    }
    return fits;
}
Ejemplo n.º 6
0
void combinePreFullTests( string rootFullName, string rootPreTest, string rootOutputName)
{

  // open output file 
  TFile *_fileSave = TFile::Open( rootOutputName.c_str(), "new" );
  // open existing files
  TFile * fileFullTest = TFile::Open( rootFullName.c_str(),"read" );  
  TFile * filePreTest = TFile::Open( rootPreTest.c_str(),"read" );

  fileFullTest->cd();
  if( ! fileFullTest ) continue;
  
  TIter nextkey( gDirectory->GetListOfKeys() );
  TKey * key;

  cout << "Copy Subdirectory/histograms from " << fileFullTest->GetName() << endl;
  cout << "into the file: " << _fileSave->GetName() << endl;

  while( ( key = (TKey*)nextkey() ) ) {
    
    TObject * obj = key->ReadObj();
    if (obj->IsA()->InheritsFrom( "TDirectory" )){
      cout << "----- Subdir " << obj->GetName() <<  "  " << obj->GetUniqueID() << endl;
      // create same structure
      _fileSave->mkdir(obj->GetName());
      
      // loop over all histograms in subdirectory
      fileFullTest->cd(obj->GetName());
      TIter nextkey2( gDirectory->GetListOfKeys() );
      TKey * key2;
       
      string objName = obj->GetName(); 
      if (objName.substr(0,3) == "BB2"){
	cout << "for Subdirectory BB2 in file " << fileFullTest->GetName() << " do nothing"  << endl;
      }
      else{
	while( ( key2 = (TKey*)nextkey2() ) ) {
	  _fileSave->cd();	
	  TObject * obj2 = key2->ReadObj();
	  
	  if( obj2->IsA()->InheritsFrom( "TH2D" )) {
	    //cout << "2d histograms " << obj2->GetName() << endl;
	    TH2D * h2 = (TH2D*)obj2;	  
	    _fileSave->cd(obj->GetName());
	    h2->Write();	  
	  }
	  else if ( obj2->IsA()->InheritsFrom( "TH1D" )) {	  
	    //cout << "1d histograms " << obj2->GetName() << endl;
	    TH1D * h1 = (TH1D*)obj2;
	    _fileSave->cd(obj->GetName());
	    h1->Write();	  
	  }	
	}
      } // do not save BB2 from Fulltest but from next file
      // here please save BB2 to final file

    }
    else{
      // store Histograms which are not in a subdirectory HA and HD
      _fileSave->cd();
      if ( obj->IsA()->InheritsFrom( "TH1D" )) {	  
	//cout << "1d histograms " << obj->GetName() << endl;
	TH1D * h1 = (TH1D*)obj;
	_fileSave->cd();
	h1->Write();	  
      }	
      //cout << obj->GetName() <<  " this is a histogram " << endl;
    }

  }

  // Now use BB2 from Pretest and store it in the outputfile _fileSave

  if( ! filePreTest ) continue;

  filePreTest->cd();
  filePreTest->cd("BB2");
  cout << "copy BB2 histograms from file " << filePreTest->GetName() << " into " << _fileSave->GetName() << endl;
 
  TIter nextkey3( gDirectory->GetListOfKeys() );
  TKey * key3;
  while( ( key3 = (TKey*)nextkey3() ) ) {    
    TObject * obj3 = key3->ReadObj();
    if( obj3->IsA()->InheritsFrom( "TH2D" )) {
      //cout << "2d histograms " << obj3->GetName() << endl;
      TH2D * h2 = (TH2D*)obj3;	  
      _fileSave->cd("BB2");
      h2->Write();	  
    }
    else if ( obj3->IsA()->InheritsFrom( "TH1D" )) {	  
      //cout << "1d histograms " << obj3->GetName() << endl;
      TH1D * h1 = (TH1D*)obj3;
      _fileSave->cd("BB2");
      h1->Write();	  
    }
    //cout << "----- " << obj3->GetName() << endl;
  }


  fileFullTest->Close();
  filePreTest->Close();
  _fileSave->Close();

}