Beispiel #1
0
void parseStructure(TDirectory* td1, TDirectory* td2) {
  string dir_name = td1->GetTitle();
  string dir_path = td1->GetPath();
  //  cout << "ParseStructure: dir_name=" << dir_name << ", dir_path=" << dir_path << endl;
  dir_path = dir_path.substr(dir_path.find("DQMData")+8);
  setPath(dir_path, td2);
  TIter next(td1->GetListOfKeys());
  TKey *key;
  while  ( (key = dynamic_cast<TKey*>(next())) ) 
    {
      string clName(key->GetClassName());
      if (clName == "TDirectoryFile") {
        string name(key->GetName());
        if (name.find("forward_") == string::npos  && 
            name.find("backward_") == string::npos &&
            name.find("ring_") == string::npos) {
	  td1->cd(name.c_str());
	  TDirectory *curr_dir = gDirectory; // dynamic_cast<TDirectory*>(obj);
	  parseStructure(curr_dir, td2);
        } else return;
      } else if (clName == "TObjString") {
	//	cout << clName << "  " << key->GetName() << endl;
        TObject* obj = key->ReadObj();
        obj->Write();
      } else {
	key->ReadObj();
      }
    }
}
Beispiel #2
0
void rdphi::Terminate()
{
//cout << "total event: " << NevtAll << "rejected: " << rejected_events << endl; 

  TFile *f = new TFile("output.root","RECREATE");

  //Write output Histograms
  TList *tl = GetOutputList();
  int l = tl->GetEntries();
  for ( int i = 0 ; i < l ; i++ )
  {
    TObject *o = tl->At(i);

    if ( o->InheritsFrom("TH1") )
    {
      cout << "TresChorros: Saving Histogram: "
          << "  Class: " << o->ClassName()  
          << "  Name: "<< o->GetName() 
          << "  Title: " << o->GetTitle()
          << " " 
          << endl << flush;
      o->Write();
    }
    }
  f->Flush();
  f->Close();  

}
Beispiel #3
0
/**
 * @brief Write all TObjects from a given TCollection into a certain directory structure in the file
 *
 * @param col pointer to a TCollection-based container
 * @param dirname name of a directory inside the output file to which the objects should be written
 * @param subdirname optional name of a subdirectory inside dirname to which the objects should be written
 *
 * This method whites all TObject-based objects contained in the TCollection-based container (see ROOT documentation)
 * into a directory whose name is given by dirname inside the output file. If dirname does not exist
 * in the output file, it will be created. Otherwise, contents of the col collection will be appended to an existing
 * directory.
 *
 * If the optional subdirectory name is specified (subdirname parameter, defaults to empty string) then the
 * contents of the collection will be written to "dirname/subdirname". If the "subdirname" directory does not
 * exist inside the "dirname" directory, it will be created.
 *
 */
void JPetWriter::writeCollection(const TCollection* col, const char* dirname, const char* subdirname)
{

  TDirectory* current =  fFile->GetDirectory(dirname);

  if (!current) {
    current = fFile->mkdir(dirname);
  }

  assert(current);

  // use a subdirectory if requested by user
  if (!std::string(subdirname).empty()) {

    if (current->GetDirectory(subdirname)) {
      current = current->GetDirectory(subdirname);
    } else {
      current = current->mkdir(subdirname);
    }
  }

  assert(current);

  current->cd();

  TIterator* it = col->MakeIterator();

  TObject* obj;
  while ((obj = it->Next())) {
    obj->Write();
  }

  fFile->cd();
}
Beispiel #4
0
void CopyDir(TDirectory *source) {
   //copy all objects and subdirs of directory source as a subdir of the current directory   
   source->ls();
   TDirectory *savdir = gDirectory;
   TDirectory *adir = savdir->mkdir(source->GetName());
   adir->cd();
   //loop on all entries of this directory
   TKey *key;
   TIter nextkey(source->GetListOfKeys());
   while ((key = (TKey*)nextkey())) {
      const char *classname = key->GetClassName();
      TClass *cl = gROOT->GetClass(classname);
      if (!cl) continue;
      if (cl->InheritsFrom(TDirectory::Class())) {
         source->cd(key->GetName());
         TDirectory *subdir = gDirectory;
         adir->cd();
         CopyDir(subdir);
         adir->cd();
      } else if (cl->InheritsFrom(TTree::Class())) {
         TTree *T = (TTree*)source->Get(key->GetName());
         adir->cd();
         TTree *newT = T->CloneTree(-1,"fast");
         newT->Write();
      } else {
         source->cd();
         TObject *obj = key->ReadObj();
         adir->cd();
         obj->Write();
         delete obj;
     }
  }
  adir->SaveSelf(kTRUE);
  savdir->cd();
}
void CopyElement(char *fTempStr) {
	printf("Copy: %s\n", fTempStr);
	RootFileP->cd();
	TObject *o = gROOT->FindObject(fTempStr);
	if (o) {
		RootFile2->cd();
		o->Write();
	} else {
		printf("Object %s not found.\n", fTempStr);
	}
}
Beispiel #6
0
void CopyElement(char *fTempStr) {
	printf("Copy: %s.\n", fTempStr);
	RootFileHHistograms->cd();
	TObject *o = gROOT->FindObject(fTempStr);
	if (o) {
		RootFileHHistograms_Rescaled->cd();
		o->Write();
	} else {
		printf("Object %s not found.\n", fTempStr);
	}
}
Beispiel #7
0
// helper function to add and weight all plots in the subsamples
void addDir(const std::string& path, const std::vector< std::pair< TFile*, double > >& files, TFile *target, int verbose) 
{
  // loop all objects in the file
  std::vector< std::pair< TFile*, double > >::const_iterator first=files.begin();
  first->first->cd(path.c_str());
  TIter nextkey(gDirectory->GetListOfKeys());
  TKey *key=0;
  while ( (key = (TKey*)nextkey())) {
    // read object from first source file
    first->first->cd(path.c_str());
    TObject *obj = key->ReadObj();
    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // if descendant of TH1 -> mergeit
      TH1 *h1 = (TH1*)obj;
      h1->Sumw2();
      h1->Scale(first->second);
      // loop over all source files and add the content of the
      // corresponding histogram to the one pointed to by "h1"
      for(std::vector< std::pair< TFile*, double > >::const_iterator file=first+1; file!=files.end(); ++file) {
	// make sure we are at the correct directory level by cd'ing to path
	file->first->cd(path.c_str());
	TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );
	if ( h2 ) {
	  h2->Sumw2();
	  h1->Add(h2,file->second);
	  delete h2; // don't know if this is necessary, i.e. if
	  // h2 is created by the call to gDirectory above.
	}
      }
    }
    else if (obj->IsA()->InheritsFrom( "TDirectory"  ) ) {
      // for a subdirectory
      if(verbose>1) std::cout << "Found subdirectory " << obj->GetName() << std::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
      addDir(newdir->GetName(),files,target, verbose);
    }
    if ( obj ) {
      target->cd(path.c_str());
      obj->Write( key->GetName() );
    }
    delete obj;
  }
  target->Write();
  delete key;
}
Beispiel #8
0
void WriteMergeObjects( TFile *target ) {
  cout << "Writing the merged data." << endl;

  TIterator *nextobj = MergeObjects.MakeIterator();
  TObjString *pathname_obj;
  while( (pathname_obj = (TObjString *)nextobj->Next()) ) {
    TString path,name;
    SplitPathName(pathname_obj->String(),&path,&name);

    TObject *obj = MergeObjects.GetValue(pathname_obj);
    target->cd(path);

    obj->Write( name );

    delete obj;
  }
  MergeObjects.Clear();

  target->Write();

  // Temporarily let multiple root files remain if > 2GB
  // Prevent Target_1.root Target_2.root, ... from happening.
  //  long long max_tree_size = 200000000000LL; // 200 GB
  //  if(TTree::GetMaxTreeSize() < max_tree_size ) {
  //    TTree::SetMaxTreeSize(max_tree_size);
  //  }

  nextobj = MergeChains.MakeIterator();
  TObjString *pathname_obj;
  while( (pathname_obj = (TObjString *)nextobj->Next()) ) {
    TString path,name;
    SplitPathName(pathname_obj->String(),&path,&name);

    TChain *ch = (TChain *)MergeChains.GetValue(pathname_obj);
    target->cd(path);
    ch->Merge(target,0,"KEEP");

    delete ch;

	// in case of multiple objects with same pathname, must remove
	// this one from the list so we don't get the same (deleted)
	// one next time we look up the same name
	MergeChains.Remove(pathname_obj);
  }
  MergeChains.Clear();

  InitializedMergeObjects = false;
}
Beispiel #9
0
//================================================
void mode1()
{
  TString filename = "Rootfiles/Run14_AuAu200.StudyLumiDep.root";
  TFile *fin = TFile::Open(filename.Data());
  TFile *fout = TFile::Open(Form("%s_filter.root",filename.Data()),"recreate");
  TKey *key;
  TIter nextkey(fin->GetListOfKeys());
  while ((key = (TKey*)nextkey())) 
    {
      TObject *obj = key->ReadObj();   
      if ( obj->IsA()->InheritsFrom( "TH2" ) ) continue;
      obj->Write();
    }
  fout->Close();
  fin->Close();
}
Beispiel #10
0
void saveHist(const char* filename, const char* pat)
{
  TList* list = gDirectory->GetList() ;
  TIterator* iter = list->MakeIterator();

  TRegexp re(pat,kTRUE) ;

  TFile outf(filename,"RECREATE") ;
  TObject* obj ;
  while((obj=iter->Next())) {    
    if (TString(obj->GetName()).Index(re)>=0) {
      obj->Write() ;
      std::cout << "." ;
    //  cout << setw(9) << counter++ << " : " << obj->GetName() << std::endl ;
    }
  }
  std::cout << std::endl ;
  outf.Close() ;

  delete iter ;
}
Beispiel #11
0
//-----------------------------------------------------------------------------
/// Convert the transient object to the requested representation.
StatusCode RootHistCnv::RConverter::createRep(DataObject* pObject,
                                              IOpaqueAddress*& pAddr)
//-----------------------------------------------------------------------------
{
  GlobalDirectoryRestore restore;
  pAddr = 0;
  try   {
    TDirectory* pParentDir = changeDirectory(pObject);
    if ( pParentDir )   {
      TObject* pTObj = createPersistent(pObject);
      if ( pTObj )   {
        pTObj->Write();
        delete pTObj;
        return createAddress(pObject, pParentDir, 0, pAddr);
      }
    }
  }
  catch (...)   {
  }
  MsgStream log (msgSvc(), "RConverter");
  log << MSG::ERROR << "Failed to create persistent Object!" << endmsg;
  return StatusCode::FAILURE;
}
Beispiel #12
0
void saveHist(const char* filename, const char* pat)
{

  cout << "\n\n Saving histograms matching " << pat << " in file " << filename << "\n\n" << flush ;

  TList* list = gDirectory->GetList() ;
  TIterator* iter = list->MakeIterator();

  TRegexp re(pat,kTRUE) ;

  TFile outf(filename,"RECREATE") ;
  TObject* obj ;
  while((obj=iter->Next())) {
    if (TString(obj->GetName()).Index(re)>=0) {
      obj->Write() ;
      std::cout << "." ;
    }
  }
  std::cout << std::endl ;
  outf.Close() ;

  delete iter ;
}
//Clone the file excluding the histogram (code stolen from Rene Brun)
void copyDir(TDirectory *source,std::string iSkipHist,bool iFirst=true) { 
  //copy all objects and subdirs of directory source as a subdir of the current directory   
  TDirectory *savdir = gDirectory;
  TDirectory *adir   = savdir;
  if(!iFirst) adir   = savdir->mkdir(source->GetName());
  if(!iFirst) adir->cd();
  //loop on all entries of this directory
  TKey *key;
  TIter nextkey(source->GetListOfKeys());
  while ((key = (TKey*)nextkey())) {
    const char *classname = key->GetClassName();
    TClass *cl = gROOT->GetClass(classname);
    if (!cl) continue;
    if (cl->InheritsFrom(TDirectory::Class())) {
      source->cd(key->GetName());
      TDirectory *subdir = gDirectory;
      adir->cd();
      copyDir(subdir,iSkipHist,false);
      adir->cd();
    } else {
      source->cd();
      TObject *obj = key->ReadObj();
      std::string pFullName = std::string(adir->GetName())+"/"+std::string(obj->GetName());
      std::string iSkipHist2 = iSkipHist;
      std::string fine_binning = "_fine_binning";
      iSkipHist2.replace(iSkipHist2.find(fine_binning), fine_binning.length(),"");
      if(pFullName.find(iSkipHist) != std::string::npos || pFullName.find(iSkipHist2) != std::string::npos) {
	continue;
      }
      adir->cd();
      obj->Write();
      delete obj;
    }
  }
  adir->SaveSelf(kTRUE);
  savdir->cd();
}
Beispiel #14
0
void SavePerfInfo(const Char_t *filename)
{
   // Save PROOF timing information from TPerfStats to file 'filename' 

   if (!gProof) {
      cout << "PROOF must be run to save output performance information" << endl;
      return;
   }
   
   TFile f(filename, "UPDATE");
   if (f.IsZombie()) {
      cout << "Could not open file " << filename << " for writing" << endl;
   } else {
      f.cd();
      
      TIter NextObject(gProof->GetOutputList());
      TObject* obj = 0;
      while (obj = NextObject()) {
         TString objname = obj->GetName();
         if (objname.Contains(TRegexp("^PROOF_"))) {
            // must list the objects since other PROOF_ objects exist
            // besides timing objects
            if (objname == "PROOF_PerfStats" ||
                objname == "PROOF_PacketsHist" ||
                objname == "PROOF_EventsHist" ||
                objname == "PROOF_NodeHist" ||
                objname == "PROOF_LatencyHist" ||
                objname == "PROOF_ProcTimeHist" ||
                objname == "PROOF_CpuTimeHist")
               obj->Write();
         }
      }

      f.Close();
   }

}
Beispiel #15
0
/**
 * Dumps the AliHLTGlobalTriggerDecision objects found in HLT output data.
 *
 * \param dataSource  This is the path to the raw data or the ROOT/DATE file
 *     contining the raw data. (default is the current directory).
 * \param firstEvent  The event number of the first event to process. (default = 0)
 * \param lastEvent  The event number of the last event to process. If this is
 *     less than firstEvent then it is set to maximum events available
 *     automatically. (default = -1)
 * \param output  Specifies the name of a ROOT output file. This file will be
 *     generated and the objects written to it. If the value is NULL then
 *     no output is written to file. (default = NULL)
 * \param debug  Specifies if full debug messages should be printed.
 */
void DumpGlobalTrigger(
		const char* dataSource = "./",
		Int_t firstEvent = 0,
		Int_t lastEvent = -1,
		const char* output = NULL,
		bool debug = false
	)
{
	if (debug)
	{
		AliLog::SetModuleDebugLevel("HLT", AliLog::kMaxType);
		AliHLTSystem* sys = AliHLTPluginBase::GetInstance();
		sys->SetGlobalLoggingLevel(kHLTLogAll);
	}
	
	gSystem->Load("libHLTrec");
	TFile* file = NULL;
	if (output != NULL)
	{
		file = new TFile(output, "RECREATE");
		if (file == NULL)
		{
			cerr << "ERROR: Could not create file '" << output << "'." << endl;
			return;
		}
	}
	
	// Setup the raw reader and HLTOUT handler.
	AliRawReader* rawReader = AliRawReader::Create(dataSource);
	if (rawReader == NULL)
	{
		cerr << "ERROR: Could not create raw reader for '" << dataSource << "'." << endl;
		if (file != NULL) delete file;
		return;
	}
	if (! rawReader->IsRawReaderValid())
	{
		cerr << "ERROR: Raw reader is not valid for '" << dataSource << "'." << endl;
		delete rawReader;
		if (file != NULL) delete file;
		return;
	}
	AliHLTOUT* hltout = AliHLTOUT::New(rawReader);
	if (hltout == NULL)
	{
		cerr << "ERROR: Could not create an AliHLTOUT object for '" << dataSource << "'." << endl;
		delete rawReader;
		if (file != NULL) delete file;
		return;
	}
	
	// Make sure that the lastEvent is greater than firstEvent.
	if (lastEvent < firstEvent) lastEvent = rawReader->GetNumberOfEvents();
	if (lastEvent < firstEvent) lastEvent = firstEvent;
	
	// Need to call NextEvent once here or we will start at the wrong event.
	if (! rawReader->NextEvent())
	{
		cout << "No events found in '" << dataSource << "'." << endl;
		AliHLTOUT::Delete(hltout);
		delete rawReader;
		if (file != NULL) delete file;
		return;
	}
	
	// Now step through the events.
	for (int i = 0; i < firstEvent; i++) rawReader->NextEvent();
	for (int i = firstEvent; i <= lastEvent; i++)
	{
		int result = hltout->Init();
		if (result != 0)
		{
			cerr << "ERROR: could not initialise HLTOUT." << endl;
			hltout->Reset();
			continue;
		}
		cout << "#################### Event " << i << " in " << dataSource
			<< " has event ID = " << hltout->EventId()
			<< " (0x" << hex << hltout->EventId() << dec << ")"
			<< " ####################" << endl;
		
		for (result = hltout->SelectFirstDataBlock();
		     result >= 0;
		     result = hltout->SelectNextDataBlock()
		    )
		{
			AliHLTComponentDataType dt;
			AliHLTUInt32_t spec = 0;
			hltout->GetDataBlockDescription(dt, spec);
			TObject* obj = hltout->GetDataObject();
			if (obj == NULL) continue;
			if (obj->IsA()->GetBaseClass("AliHLTGlobalTriggerDecision") != NULL)
			{
				if (dt != kAliHLTDataTypeGlobalTrigger)
				{
					cerr << "WARNING: Found an AliHLTGlobalTriggerDecision object in a data block of type '"
						<< AliHLTComponent::DataType2Text(dt).c_str()
						<< "' but expected '"
						<< AliHLTComponent::DataType2Text(kAliHLTDataTypeGlobalTrigger).c_str()
						<< "'." << endl;
				}
				if (file != NULL)
				{
					obj->Write(
						Form("HLTGlobalDecision_event_0x%llX", hltout->EventId()),
						TObject::kOverwrite
					);
				}
				obj->Print();
			}
			hltout->ReleaseDataObject(obj);
		}
		
		result = hltout->Reset();
		if (result != 0)
		{
			cerr << "ERROR: could not reset HLTOUT." << endl;
			hltout->Reset();
			continue;
		}
		rawReader->NextEvent();
	}
	
	AliHLTOUT::Delete(hltout);
	delete rawReader;
	if (file != NULL) delete file;
}
Beispiel #16
0
void EWKcorr_Ele() {
  
//  Int_t iso=00; Int_t pt=3;  

  Target = TFile::Open( "Total_FRcorr60_60.root", "RECREATE" );
  char faa[100]; 
  FileList = new TList();
  strcpy(faa,"");
  sprintf(faa,"SingleElectron_FR60_60.root");
  FileList->Add( TFile::Open(faa) ); 
  strcpy(faa,"");
  sprintf(faa,"Wjets_FR60_60.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"DY_10-50_FR60_60.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"DY_50_FR60_60.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"ttbar_FR60_60.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Wgamma_FR60_60.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
/*
  sprintf(faa,"Zjet_20-30_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_30-50_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_50-80_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_80-120_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_120-170_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_170-230_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_230-300_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
  strcpy(faa,"");
  sprintf(faa,"Zjet_300_FR60_28.root");
  FileList->Add( TFile::Open(faa) );
*/
  FileList->Print();

  TString path( (char*)strstr( Target->GetPath(), ":" ) );
  path.Remove( 0, 2 );

  TFile *first_source = (TFile*)FileList->First();
  first_source->cd( path );
  TDirectory *current_sourcedir = gDirectory;

  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key;
  while ( (key = (TKey*)nextkey())) {

    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();
    if ( obj->IsA()->InheritsFrom( "TH1F" ) || obj->IsA()->InheritsFrom( "TH2F" ) ) {
      // descendant of TH1F -> merge it

      //      cout << "Merging histogram " << obj->GetName() << endl;
      TH1F *h1 = (TH1F*)obj;

      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)FileList->After( first_source );
      Int_t scal=0;
      while ( nextsource ) {
        
        // make sure we are at the correct directory level by cd'ing to path
        nextsource->cd( path );
        TH1F *h2 = (TH1F*)gDirectory->Get( h1->GetName() );
        h1->SetDefaultSumw2(true);
        if ( h2 ) {
          h2->SetDefaultSumw2(true);
          h1->Add( h2 , scaling[scal] );  //scale factor not need if is need the same as to be applied to h1
          cout<<"file "<<nextsource->GetName()<<endl;
	  cout<<"scaling "<<scaling[scal]<<" scal "<<scal<<endl;
          delete h2; // don't know if this is necessary, i.e. if 
                     // h2 is created by the call to gDirectory above.
        }
	
        nextsource = (TFile*)FileList->After( nextsource );
	scal++;
      }
    }
    // 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();
      obj->Write( key->GetName() );
    }
    
  } // while ( ( TKey *key = (TKey*)nextkey() ) )
  
  Target->Write();
  
  Target->cd();
  getFakerate2(h_nEvents, h_nEventsFO, h_FOrate);
  getFakerate1(h_nVertex1, h_nVertex0, h_nVertex2);
  h_FOrate->Write("h_FOrate3");
  h_nEvents->Write("h_Events2");
  h_nEventsFO->Write("h_EventsFO2");
  h_nVertex1->Write("h_nVertex1_2");
  h_nVertex0->Write("h_nVertex0_2");
  h_nVertex2->Write("h_nVertex3");
  delete h_nVertex2;
  delete h_FOrate;
  Target->Close();

}   
Beispiel #17
0
void MergeRootfile( 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;
  std::vector<double>::iterator wItr;

  while ( (key = (TKey*)nextkey())) {
    wItr=WeightList->begin();

    //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" ) ) {
      // descendant of TH1 -> merge it

      //      cout << "Merging histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;
      h1->Sumw2();

      // weight is eff * sigma, because the histos are produced on the ~same initial
      // events, and eff is already included (in reconstruction), weight is just sigma
      h1->Scale(double(*wItr));
  
      // 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 );
      wItr++;
      while ( nextsource ) {
        
        // 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();
	   h2->Sumw2();
	   h2->Scale( double(*wItr) );
           h1->Add( h2 );
           delete h2;
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
	wItr++;
      }
    }
    else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
      
      // 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" ) ) {
      // 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
      MergeRootfile( 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" ))
          globChain->Merge(target->GetFile(),0,"keep");
	else
	obj->Write( key->GetName() );
    }

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

  // save modifications to target file
  target->SaveSelf(kTRUE);
  TH1::AddDirectory(status);
}
Beispiel #18
0
void MergeRootfile( char *core, TDirectory *target, TList *sourcelist ) {
  printf("merging only histos with core=%s=\n",core);

  //  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;

  int nh=0;
  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key;
  while ( (key = (TKey*)nextkey())) {
    const char *name=key->GetName();
    char * c1=strstr(name,core);
    if(c1==0) continue;
    if(c1-name>2) continue;
    nh++;
    if(nh%100==0) printf("nh=%d addingX %s\n",nh,name);
    
    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();
    
    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> merge it
      
      //      cout << "Merging histogram " << 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 ) {
        
        // make sure we are at the correct directory level by cd'ing to path
        nextsource->cd( path );
        TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );
        if ( h2 ) {
          h1->Add( h2 );
          delete h2; // don't know if this is necessary, i.e. if 
                     // h2 is created by the call to gDirectory above.
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
      }
    }
    else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
      
      // 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" ) ) {
      // 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
      MergeRootfile( core,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" ))
	globChain->Write( key->GetName() );
      else
	obj->Write( key->GetName() );
    }
    
  } // while ( ( TKey *key = (TKey*)nextkey() ) )
  
  // save modifications to target file
  target->Write();
  
}
Beispiel #19
0
void ScaleAll1file( TDirectory *target, FileInfo_t& source ) {

  cout << "Target path: " << target->GetPath() << endl;
  TString path( (char*)strstr( target->GetPath(), ":" ) );
  path.Remove( 0, 2 );

  source.fp->cd( path );
  TDirectory *current_sourcedir = gDirectory;

  // loop over all keys in this directory

  bool newdir = true;

  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key;
  while ( (key = (TKey*)nextkey())) {

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

    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> scale it

      if (newdir) {
	newdir=false;
	cout << "Scaling histograms: " << endl;
      }

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

      h1->Scale(source.weight);

    } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
      // it's a subdirectory

      newdir = true;

      cout << "\n=====> Found subdirectory " << obj->GetName();
      cout << "<=====\n" << 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
      ScaleAll1file( newdir, source );

    } else {

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

    // now write the scaledd 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();

      obj->Write( key->GetName() );
    }

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

  cout << endl;

  // save modifications to target file
  target->Write();

}
Beispiel #20
0
void hmerge_( TDirectory *target, TList *sourcelist, double crossArray[] ) {

  //cout << "Target path: " << target->GetPath() << endl;
  TString rpath( (char*)strstr( target->GetPath(), ":" ) );
  rpath.Remove( 0, 2 );

  TFile *first_source = (TFile*)sourcelist->First();

  first_source->cd( rpath );
  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;
  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( rpath );
    TObject *obj = key->ReadObj();

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

      //cout << "Merging histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;
      h1->Sumw2();

      // Scale by the cross-section factor
      h1->Scale(crossArray[0]);

      // 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 );

      int q = 1; // This keeps track of which
                 // cross section factor to use
      while ( nextsource ) {
        // make sure we are at the correct directory level by cd'ing to rpath
        nextsource->cd( rpath );
        TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
        if (key2) {
           TH1 *h2 = (TH1*)key2->ReadObj();
           h2->Sumw2();

           // Scale by the cross-section factor before adding.
           h2->Scale(crossArray[q]);
           h1->Add( h2 );
           q++;
           delete h2;
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
      }

    } else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {

      // 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 );
      while ( nextsource ) {
        globChain->Add(nextsource->GetName());
        nextsource = (TFile*)sourcelist->After( nextsource );
      }

    } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {

      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
      hmerge_( newdir, sourcelist,crossArray );

    } 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" ))
          globChain->Merge(target->GetFile(),0,"keep");
        else
        obj->Write( key->GetName() );
    }

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

  // save modifications to target file
  target->SaveSelf(kTRUE);
  TH1::AddDirectory(status);

}
Beispiel #21
0
void getSubSetRoot(TString dirname){
	using namespace ztop;
	using namespace std;

	std::vector<TString> plots;
	plots << "lepton_pt" << "lepton_eta" << "dilepton_mll" << "lepton_multi"
			<< "alllepton_multi" << "lepton_etafine" << "lepton_iso";




	TFile *f =new TFile(dirname+"/raw.root");
	TFile *fout = new TFile(dirname+"/plotHistos.root","RECREATE");

	//get num and den

	std::vector<TString> adds;
	adds << "_num" << "_den" << "_num_mc" << "_den_mc";


	for(size_t i=0;i<plots.size();i++){
		TString plotname=plots.at(i);
		for(size_t j=0;j<adds.size();j++){
			TString name=plotname+adds.at(j);
			TObject * obj = f->Get(name);
			fout->cd();
			obj->Write();
		}
	}

	TFile *f3 =new TFile(dirname+"/scalefactors.root");
	std::vector<TString> addssf;
	addssf << "_eff" << "_eff_mc";


	for(size_t i=0;i<plots.size();i++){
		TString plotname=plots.at(i);
		for(size_t j=0;j<addssf.size();j++){
			TString name=plotname+addssf.at(j);
			TObject * obj = f3->Get(name);
			fout->cd();
			obj->Write();
		}
	}

	TString channel="";
	if(dirname.Contains("ee")) channel="ee";
	else if(dirname.Contains("emu")) channel="emu";
	else if(dirname.Contains("mumu")) channel="mumu";
	else std::cout << "naming of triggerSummary  nor done automatically - if not intended, check dirnames (should contain channel name" << std::endl;

	TFile *fout2 = new TFile("triggerSummary_"+channel+".root","RECREATE");
	fout2->cd();
	std::vector<TString> addsdssf;
	addsdssf << "lepton_eta2d_sf";
	TCanvas * c1=new TCanvas();
	setGStyle();
	double epsilon=0.0000001;
	for(size_t i=0;i<addsdssf.size();i++){
		TString plotname=addsdssf.at(i);
		TObject * obj = f3->Get(plotname);
		fout2->cd();

		if((TString)obj->ClassName() == "TH2D"){
			TH2D * h=(TH2D*)f3->Get(plotname);
			h->SetName("scalefactor_eta2d_with_syst");
			std::cout << "Writing: "<< h->GetName() << std::endl;
			h->Write();
			//make plot with deleted "empty" bins
			for(int x=0;x<=h->GetNbinsX();x++){
				for(int j=0;j<=h->GetNbinsY();j++){
					if(fabs(h->GetBinContent(x,j) - 1) < epsilon && (fabs(h->GetBinError(x,j) - 0.01)< epsilon || h->GetBinError(x,j) < epsilon)){
						h->SetBinContent(x,j,0);
						h->SetBinError(x,j,0);
					}
				}
			}
			c1->Clear();
			c1->SetBatch(true);
			h->Draw("colz,e,text");
			c1->Print(channel+"_eta2d_sf.pdf");

		}



	}
	delete c1;

}
void
RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
                                          int calculatorType,
                                          int testStatType,
                                          bool useCLs,
                                          int npoints,
                                          const char * fileNameBase ){

   // analyze result produced by the inverter, optionally save it in a file


   double lowerLimit = 0;
   double llError = 0;
#if defined ROOT_SVN_VERSION &&  ROOT_SVN_VERSION >= 44126
   if (r->IsTwoSided()) {
      lowerLimit = r->LowerLimit();
      llError = r->LowerLimitEstimatedError();
   }
#else
   lowerLimit = r->LowerLimit();
   llError = r->LowerLimitEstimatedError();
#endif

   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();

   //std::cout << "DEBUG : [ " << lowerLimit << " , " << upperLimit << "  ] " << std::endl;

   if (lowerLimit < upperLimit*(1.- 1.E-4) && lowerLimit != 0)
      std::cout << "The computed lower limit is: " << lowerLimit << " +/- " << llError << std::endl;
   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;


   // compute expected limit
   std::cout << "Expected upper limits, using the B (alternate) model : " << std::endl;
   std::cout << " expected limit (median) " << r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;
   std::cout << " expected limit (-2 sig) " << r->GetExpectedUpperLimit(-2) << std::endl;
   std::cout << " expected limit (+2 sig) " << r->GetExpectedUpperLimit(2) << std::endl;


   // detailed output
   if (mEnableDetOutput) {
      mWriteResult=true;
      Info("StandardHypoTestInvDemo","detailed output will be written in output result file");
   }


   // write result in a file
   if (r != NULL && mWriteResult) {

      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : (calculatorType == 1) ? "Hybr" : "Asym";
      const char *  limitType = (useCLs) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      if (mResultFileName.IsNull()) {
         mResultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);
         //strip the / from the filename
         if (mMassValue.size()>0) {
            mResultFileName += mMassValue.c_str();
            mResultFileName += "_";
         }

         TString name = fileNameBase;
         name.Replace(0, name.Last('/')+1, "");
         mResultFileName += name;
      }

      // get (if existing) rebuilt UL distribution
      TString uldistFile = "RULDist.root";
      TObject * ulDist = 0;
      bool existULDist = !gSystem->AccessPathName(uldistFile);
      if (existULDist) {
         TFile * fileULDist = TFile::Open(uldistFile);
         if (fileULDist) ulDist= fileULDist->Get("RULDist");
      }


      TFile * fileOut = new TFile(mResultFileName,"RECREATE");
      r->Write();
      if (ulDist) ulDist->Write();
      Info("StandardHypoTestInvDemo","HypoTestInverterResult has been written in the file %s",mResultFileName.Data());

      fileOut->Close();
   }


   // plot the result ( p values vs scan points)
   std::string typeName = "";
   if (calculatorType == 0 )
      typeName = "Frequentist";
   if (calculatorType == 1 )
      typeName = "Hybrid";
   else if (calculatorType == 2 || calculatorType == 3) {
      typeName = "Asymptotic";
      mPlotHypoTestResult = false;
   }

   const char * resultName = r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName.c_str(),resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);

   // plot in a new canvas with style
   TString c1Name = TString::Format("%s_Scan",typeName.c_str());
   TCanvas * c1 = new TCanvas(c1Name);
   c1->SetLogy(false);

   plot->Draw("CLb 2CL");  // plot all and Clb

   // if (useCLs)
   //    plot->Draw("CLb 2CL");  // plot all and Clb
   // else
   //    plot->Draw("");  // plot all and Clb

   const int nEntries = r->ArraySize();

   // plot test statistics distributions for the two hypothesis
   if (mPlotHypoTestResult) {
      TCanvas * c2 = new TCanvas();
      if (nEntries > 1) {
         int ny = TMath::CeilNint(TMath::Sqrt(nEntries));
         int nx = TMath::CeilNint(double(nEntries)/ny);
         c2->Divide( nx,ny);
      }
      for (int i=0; i<nEntries; i++) {
         if (nEntries > 1) c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
   }


}
void recupThePlots(){
//	TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots");
	//theDr->ls();
	cout << "coucou" << theOutFileName << endl;
	
	TFile *myOutFile = new TFile(theOutFileName,"RECREATE");
	
	TSystemDirectory dir(thePath, thePath);
	TSystemFile *file;
	TString fname;
	TIter next(dir.GetListOfFiles());
	while (((file=(TSystemFile*)next()))) {
		fname = file->GetName();
		if ((fname.BeginsWith("TnP"))&&fname.Contains("data")) {
                        cout <<  "--------------------"<< "\n";
                        cout << fname << "\n";
			TFile *myFile = new TFile(fname);
			TIter nextkey(myFile->GetListOfKeys());                   
			TKey *key;
			while ((key = (TKey*)nextkey())) {
                                // cout << key << "\n";
				TString theTypeClasse = key->GetClassName();
				TString theNomClasse = key->GetTitle();
                                   cout << "theTypeClasse:  "<< theTypeClasse << " ,  " << theNomClasse << "\n";
				if ( theTypeClasse == "TDirectoryFile" ){
                                        //    cout << "we are here 1" << "\n";
					TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse);
					TIter nextkey2(theDr->GetListOfKeys());
					TKey *key2;
					while ((key2 = (TKey*)nextkey2())) {
						TString theTypeClasse2 = key2->GetClassName();
						TString theNomClasse2 = key2->GetTitle();	
						if ( theTypeClasse == "TDirectoryFile" || theTypeClasse == "TGraphAsymmErrors" ){
							TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/fit_eff_plots");
							TIter nextkey3(theDr2->GetListOfKeys());
							TKey *key3;
							while ((key3 = (TKey*)nextkey3())) {
								TString theTypeClasse3 = key3->GetClassName();
								TString theNomClasse3 = key3->GetName();	
				 				cout << "type = " << theTypeClasse3 << " nom = " << theNomClasse3 << endl;
						
								TCanvas *theCanvas = (TCanvas*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/fit_eff_plots/"+theNomClasse3);
								TIter nextObject(theCanvas->GetListOfPrimitives());
								TObject *obj;
								while ((obj = (TObject*)nextObject())) {
									if (obj->InheritsFrom("TGraphAsymmErrors")) {
					        				cout << "histo: " << obj->GetName() << endl;
										myOutFile->cd();
										obj->Write(theNomClasse2+"_"+theNomClasse3);
										myFile->cd();
									}
									if (obj->InheritsFrom("TH2F")) {
										cout << "the TH2F = " << obj->GetName() << endl;
										myOutFile->cd();
										obj->Write(theNomClasse2+"_"+theNomClasse3);
										myFile->cd();
									}
								}
							}
						}

					}
			
				}
			}
			delete myFile;
		}
	
	}
	myOutFile->Close();

}
Beispiel #24
0
void MergeRootfile( TDirectory *target, const vector<pair<TFile*, float> >& vFileList) {

   //  cout << "Target path: " << target->GetPath() << endl;
   TString path( (char*)strstr( target->GetPath(), ":" ) );
   path.Remove( 0, 2 );
	
	vec_pair_it it = vFileList.begin();
   TFile *first_source = (*it).first;
   const float first_weight = (*it).second;
   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;
   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 << "Merging histogram " << obj->GetName() << endl;
         TH1 *h1 = (TH1*)obj;
			if (first_weight>0) {
				h1->Scale(first_weight);
			}

         // loop over all source files and add the content of the
         // correspondant histogram to the one pointed to by "h1"
			for (vec_pair_it nextsrc = vFileList.begin()+1; nextsrc != vFileList.end(); ++nextsrc ) {

            // make sure we are at the correct directory level by cd'ing to path
            (*nextsrc).first->cd( path );
				const float next_weight = (*nextsrc).second;
            TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
            if (key2) {
               TH1 *h2 = (TH1*)key2->ReadObj();
					if (next_weight>0) h2->Scale(next_weight);
               h1->Add( h2 );
               delete h2;
            }
         }

      } 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());
			for (vec_pair_it nextsrc = vFileList.begin()+1; nextsrc != vFileList.end(); ++nextsrc ) {

            globChain->Add(nextsrc->first->GetName());
         }

      } 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
         MergeRootfile( newdir, vFileList);

      } 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");
         else
            obj->Write( key->GetName() );
      }

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

   // save modifications to target file
   target->SaveSelf(kTRUE);
   TH1::AddDirectory(status);
}
Beispiel #25
0
void MergeRootfile(TDirectory *target, TList *sourcelist )
{
    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
    TIter nextkey( current_sourcedir->GetListOfKeys() );
    TKey *key, *oldkey=0;
    while ( (key = (TKey*)nextkey()))
    {
        //keep only the highest cycle number for each key
        if (oldkey &&
            !strcmp(oldkey->GetName(),key->GetName()))

            continue;

        cout << "process key: " << key->GetName() << endl;

        // 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
            //
            TH1 *h1 = (TH1*) obj;
            scale(first_source, h1);

            // loop over all source files and add the content of the
            // correspondant histogram to the one pointed to by "h1"
            for(TFile *nextsource = (TFile*)sourcelist->After(first_source);
                nextsource;
                nextsource = (TFile*)sourcelist->After(nextsource))
            {
                // 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();
                    scale(nextsource, h2);

                    h1->Add(h2);

                    delete h2;
                }
            }
        }
        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
            MergeRootfile( 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;

            continue;
        }

        // 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...
            obj->Write( key->GetName() );
        }

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

    // save modifications to target file
    target->SaveSelf(kTRUE);
    TH1::AddDirectory(status);
}