コード例 #1
0
//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname, Bool_t loadFromDir = kTRUE)
{
  bool verbose = false;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);

  TTree* t = 0;
  if (loadFromDir) {
    TDirectory *dir = (TDirectory*)inf->FindObjectAny("ElectronValidationMod");
    assert(dir);
    

    t = (TTree*)dir->Get("ElectronIDOptimizationTree");
    assert(t);
  } else {
    t = (TTree*)inf->Get("ElectronIDOptimizationTree");  
  }

  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
コード例 #2
0
//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname, int nsel)
{
  bool verbose = false;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);

  //TDirectory *dir = (TDirectory*)inf->FindObjectAny("HwwMakeNtupleMod");
  //assert(dir);

  TTree* t;
  
  if     (nsel==0) t = (TTree*) gROOT->FindObject("HwwTree0");
  else if(nsel==1) t = (TTree*) gROOT->FindObject("HwwTree1");
  else if(nsel==2) t = (TTree*) gROOT->FindObject("HwwTree2");
  else if(nsel==3) t = (TTree*) gROOT->FindObject("HwwTree3");
  else if(nsel==4) t = (TTree*) gROOT->FindObject("HwwTree4");
  else             assert(1);
  t->SetName("tree");
  assert(t);

  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
コード例 #3
0
//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname, const char* tname)
{
  bool verbose = false;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);

  TTree* t = (TTree*)inf->Get(tname);
  
  if (!t) {
    TDirectory *dir = (TDirectory*)inf->FindObjectAny("eleIDdir");
    if (!dir) {
      cout << "Cannot get Directory HwwNtuplerMod from file " << infname << endl;
      assert(dir);
    }
    t = (TTree*)dir->Get(tname);
  }

  if (!t) {
    cout << "Cannot get Tree with name " << tname << " from file " << infname << endl;
  }
  assert(t);


  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
コード例 #4
0
//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname)
{
  bool verbose = true;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);

  //TDirectory *dir = (TDirectory*)inf->FindObjectAny("HwwMakeNtupleMod");
  //assert(dir);

  TTree* t;
  t = (TTree*) inf->Get("HwwTree0");
  if(!t) t = (TTree*) inf->Get("HwwTree1");
  if(!t) t = (TTree*) inf->Get("HwwTree2");
  if(!t) t = (TTree*) inf->Get("tree");
  assert(t);
  t->SetName("tree");

  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
コード例 #5
0
TTree *skim(std::string var, TTree *fullTree, std::string newname, std::string cutstr, bool isWeighted , bool reweighted){

  std::cout << newname.c_str() << " " << cutstr.c_str() << std::endl;
  fullTree->Draw(">>cutlist",cutstr.c_str());
  TEventList *keep_points = (TEventList*)gDirectory->Get("cutlist");
  int nEntries = fullTree->GetEntries();

  float x;
  float weight, weight_in, weight_in_pu; 
  float catvar1,catvar2,catvar3,catvar4;
  float tau1,tau2;

  float genpt;

  TLorentzVector *jet;

  TTree *newTree = new TTree(newname.c_str(),newname.c_str());
  newTree->Branch(var.c_str(),&x,Form("%s/Float_t",var.c_str()));
  newTree->Branch("weight",&weight,"weight/Float_t");
  newTree->Branch("jet1mprune",&catvar1,"jet1mprume/Float_t");
  newTree->Branch("jet1mtrim",&catvar2,"jet1mtrim/Float_t");
  newTree->Branch("jet1tau2o1",&catvar3,"jet1tau12o1/Float_t");
  newTree->Branch("jet1pt",&catvar4,"jet1pt/Float_t");
  
  fullTree->SetBranchAddress(var.c_str(),&x);
  fullTree->SetBranchAddress("scale1fb",&weight_in);
  fullTree->SetBranchAddress("puweight",&weight_in_pu);
  fullTree->SetBranchAddress("jet1mprune",&catvar1);
  fullTree->SetBranchAddress("jet1mtrim" ,&catvar2);
  fullTree->SetBranchAddress("jet1tau2" ,&tau2);
  fullTree->SetBranchAddress("jet1tau1" ,&tau1);
  fullTree->SetBranchAddress("jet1"     ,&jet);

  if ( reweighted){
    	std::cout << "Reweighting For generated PT " << std::endl;
  	fullTree->SetBranchAddress("genvpt"     ,&genpt);
  }

  std::cout << " Filling Skim tree " << newTree->GetName() << std::endl;

  for (int evt=0;evt<nEntries;evt++){
    fullTree->GetEntry(evt);
    if ( !(keep_points->Contains(evt)) ) continue;
    if (isWeighted) weight = weight_in*weight_in_pu*luminosity;
    else weight = 1.;
    if (reweighted) { 
    	if (genpt<reweightgenpt->GetXaxis()->GetXmax() && genpt>reweightgenpt->GetXaxis()->GetXmin()) {
	  weight*=reweightgenpt->GetBinContent(reweightgenpt->FindBin(genpt));
	}
	//std::cout << "genpt = " << genpt << ", weight = " << reweightgenpt->GetBinContent(reweightgenpt->FindBin(genpt)) <<std::endl;
    }
    catvar3 = tau2/tau1;  // make the sub-structure variable
    catvar4 = jet->Pt();
    //std::cout << jet->Pt() << std::endl; 
    newTree->Fill();
  }

  return newTree;
}
コード例 #6
0
//------------------------------------------------------------------------------
// getTreeFromFile
//------------------------------------------------------------------------------
TTree* getTreeFromFile(const char* infname, const char* tname)
{
  bool verbose = false;

  if (verbose) {
    cout << "--- Open file " << infname << endl;
  }
  
  TFile* inf = new TFile(infname,"read");
  assert(inf);
  TTree* t = (TTree*)inf->Get(tname);
  assert(t);

  if (verbose) {
    cout << "---\tRecovered tree " << t->GetName()
	 << " with "<< t->GetEntries() << " entries" << endl;
  }
  
  return t;
}
コード例 #7
0
ファイル: rewritetrees.C プロジェクト: hbakhshi/Analysis13TeV
void rewritetrees(){
  TString trees[] = {"iso2j1t" , "noniso2j1t" , "iso2j0t" , "noniso2j0t" , "iso3j2t" , "noniso3j2t" , "iso3j1t" , "noniso3j1t" };

  struct{
    float weight;
    float mtw;
    float met;
    bool data;
    bool qcd;
  } info;

  TFile* fout = TFile::Open("out.root" , "RECREATE");

  for( int i=0 ; i < 8 ; i++){
    cout << trees[i] << endl;
    TTree* tree = (TTree*)( _file0->Get("Trees/" + trees[i] ) );
    tree->SetBranchAddress( "info" , &info );

    tree->Print();

    TTree* tout = new TTree( tree->GetName() , tree->GetTitle() );
    tout->SetAutoSave( 10000 );
    tout->Branch( "weight" , &info.weight );
    tout->Branch( "mtw" , &info.mtw);
    tout->Branch( "met" , &info.met );
    tout->Branch( "data" , &info.data );
    tout->Branch( "qcd" , &info.qcd );

    for(int j = 0 ; j < tree->GetEntries() ; j++){
      tree->GetEntry(j);
      tout->Fill();
      //cout << i ;
    }
    
    
  }

  fout->Write();
  fout->Close();
}
コード例 #8
0
ファイル: fit1d.C プロジェクト: quittnat/light_diphoton
//get the RooDataSet, multiply each roorealvar by the event_weight
void get_roodset_from_ttree(TDirectoryFile *f, TString treename, RooDataSet* &roodset){
  cout << "Creating roodset from file: " << f->GetName() << " with tree: " << treename.Data() << endl;

  TTree *t = NULL;
  assert(roodset==NULL);
  f->GetObject(treename.Data(),t);
  if (!t) {cout << "Impossible to find TTree " << treename.Data() << endl; return;}
  TObjArray *objs = t->GetListOfBranches();
  //disables all branches
  t->SetBranchStatus("*",0);


  float v_rooisopv1;
  float v_rooisopv2;
  float v_rooisowv1;
  float v_rooisowv2;
  float v_roovar1;
  float v_roovar2;
  float v_roopt1;
  float v_roosieie1;
  float v_rooeta1;
  float v_roopt2;
  float v_roosieie2;
  float v_rooeta2;
  float v_roodiphopt;
  float v_roodiphomass;
  float v_roorho;
  float v_roosigma;
  float v_roonvtx;
  float v_rooweight;

  TBranch *b_roovar1;
  TBranch *b_roovar2;
  TBranch *b_rooisopv1;
  TBranch *b_rooisopv2;
  TBranch *b_rooisowv1;
  TBranch *b_rooisowv2;
  TBranch *b_roopt1;
  TBranch *b_roosieie1;
  TBranch *b_rooeta1;
  TBranch *b_roopt2;
  TBranch *b_roosieie2;
  TBranch *b_rooeta2;
  TBranch *b_roodiphopt;
  TBranch *b_roodiphomass;
  TBranch *b_roorho;
  TBranch *b_roosigma;
  TBranch *b_roonvtx;
  TBranch *b_rooweight;

  const int nvars = 18;
  float* ptrs[nvars]={&v_roovar1,&v_roovar2,&v_rooisopv1,&v_rooisopv2,&v_rooisowv1,&v_rooisowv2,&v_roopt1,&v_roosieie1,&v_rooeta1,&v_roopt2,&v_roosieie2,&v_rooeta2,&v_roodiphopt,&v_roodiphomass,&v_roorho,&v_roosigma,&v_roonvtx,&v_rooweight};
  TBranch** branches[nvars]={&b_roovar1,&b_roovar2,&b_rooisopv1,&b_rooisopv2,&b_rooisowv1,&b_rooisowv2,&b_roopt1,&b_roosieie1,&b_rooeta1,&b_roopt2,&b_roosieie2,&b_rooeta2,&b_roodiphopt,&b_roodiphomass,&b_roorho,&b_roosigma,&b_roonvtx,&b_rooweight};
  RooRealVar* rooptrs[nvars]={roovar1,roovar2,rooisopv1,rooisopv2,rooisowv1,rooisowv2,roopt1,roosieie1,rooeta1,roopt2,roosieie2,rooeta2,roodiphopt,roodiphomass,roorho,roosigma,roonvtx,rooweight};
  bool status[nvars];
  RooArgSet args;
  for (int i=0; i<nvars; i++){ 
    status[i]=0;
    TString name = rooptrs[i]->GetName();
    TObject *obj = objs->FindObject(name.Data());
    if (!obj) continue;
    t->SetBranchStatus(name.Data(),1);
    status[i]=1;
    t->SetBranchAddress(name.Data(),ptrs[i],branches[i]);
 
   args.add(*(rooptrs[i]));
  }

  TString newname = Form("roo_%s",t->GetName());
  roodset = new RooDataSet(newname.Data(),newname.Data(),args,WeightVar(*rooweight) );
  for (int j=0; j<t->GetEntries(); j++){
    t->GetEntry(j);
    for (int i=0; i<nvars; i++){
      if (!status[i]) continue;
      rooptrs[i]->setVal(*(ptrs[i]));
    }
    roodset->add(args,v_rooweight);
  }

  cout << "Imported roodset " << newname.Data() << " from TTree " << t->GetName() << endl;
  roodset->Print();

}
コード例 #9
0
ファイル: CheckESD.C プロジェクト: JanFSchulte/monalisa
void CheckESD(const char* fileNameE="AliESDsTmp.root",const char* fileNameR="alien:///alice/data/2010/LHC10h/000137549/ESDs/pass1_4plus/10000137549001.100/AliESDs.root") {
	
	Int_t nev = 10;
	Int_t nskip = 0;
	const char* fileNameM = "AliESDs.root";
	const char *trgname;
	
	if (gSystem->Getenv("DC_ESDFILE")) {
    fileNameR = gSystem->Getenv("DC_ESDFILE");
  }
  if (gSystem->Getenv("DC_NEVENTS")) {
    nev = atoi(gSystem->Getenv("DC_NEVENTS"));
  }
	if (gSystem->Getenv("DC_TRGNAME")) {
    trgname = gSystem->Getenv("DC_TRGNAME");
  }
	if (gSystem->Getenv("DC_EEVENT")) {
		nskip = atoi(gSystem->Getenv("DC_EEVENT"));
	}
	
	if (!gGrid) TGrid::Connect("alien://");
  TFile *_fileE = TFile::Open(fileNameE);
  TFile *_fileR = TFile::Open(fileNameR);
  AliESDEvent* esdE = new AliESDEvent();
  AliESDEvent* esdR = new AliESDEvent();
	
	AliESDRun* runM = 0x0;
	AliESDHeader* headM = 0x0;
	AliESDZDC* zdcM = 0x0;
	AliESDVZERO* vzeroM = 0x0;
	AliMultiplicity *multM = 0x0;
	
	TTree* treeESDE;
  TTree* treeESDR;
  _fileE->GetObject("esdTree", treeESDE);
  _fileR->GetObject("esdTree", treeESDR);
  esdE->ReadFromTree(treeESDE);
  esdR->ReadFromTree(treeESDR);
	
	// Output ESDs
	TFile *_fileM = TFile::Open(fileNameM, "RECREATE");
	TTree *treeESDM = new TTree("esdTree", "Tree with ESD objects");
  AliESDEvent *esdM = new AliESDEvent();
  esdM->CreateStdContent();
	esdM->WriteToTree(treeESDM);
	
  Int_t nEventsE = treeESDE->GetEntries();
  Int_t nEventsR = treeESDR->GetEntries();
  Int_t nEvents = TMath::Min(nEventsE,nEventsR);
	nEvents = TMath::Min(nEvents,nev);
	Int_t lastSelectedEvent = -1;
	if (nskip>0) {
		printf("We will skip %d events\n",nskip);
		lastSelectedEvent = nskip-1;
	}
  for (Int_t iEv=0; iEv<nEvents; iEv++) {
    printf("Event %i\n",iEv);
		
    treeESDE->GetEvent(iEv);
		if (trgname) {
			for (Int_t jEv=lastSelectedEvent+1; jEv<nEventsR; jEv++) {
				treeESDR->GetEvent(jEv);
				
				TString firedTrigClasses = esdR->GetFiredTriggerClasses();
				if (firedTrigClasses.Contains(trgname)) {
					lastSelectedEvent = jEv;
					break;
				}
			}
		}	else {
			treeESDR->GetEvent(iEv);
			lastSelectedEvent = iEv;
		}
		printf("and Event %i\n",lastSelectedEvent);
		
    // Copy the esd event from the Merged (Signal) reconstrcution
		*esdM = *esdE;
		
		// Replace some branches with those from original esd event
		runM = dynamic_cast<AliESDRun *>(esdM->FindListObject("AliESDRun"));
		*runM = *(dynamic_cast<AliESDRun *>(esdR->FindListObject("AliESDRun")));
		headM = dynamic_cast<AliESDHeader *>(esdM->FindListObject("AliESDHeader"));
		*headM = *(dynamic_cast<AliESDHeader *>(esdR->FindListObject("AliESDHeader")));
		zdcM = dynamic_cast<AliESDZDC *>(esdM->FindListObject("AliESDZDC"));
		*zdcM = *(dynamic_cast<AliESDZDC *>(esdR->FindListObject("AliESDZDC")));
		vzeroM = dynamic_cast<AliESDVZERO *>(esdM->FindListObject("AliESDVZERO"));
		*vzeroM = *(dynamic_cast<AliESDVZERO *>(esdR->FindListObject("AliESDVZERO")));
		multM = dynamic_cast<AliMultiplicity *>(esdM->FindListObject("AliMultiplicity"));
		*multM = *(dynamic_cast<AliMultiplicity *>(esdR->FindListObject("AliMultiplicity")));
		
		treeESDM->Fill();
  }
	_fileM->cd();
	treeESDM->Write(treeESDM->GetName(),TObject::kOverwrite);
	_fileM->Close();
	
}
コード例 #10
0
ファイル: striptree.C プロジェクト: zatserkl/root-macros
void striptree(TString fileName="", Int_t nAPVs=4)
{
  //===========================================================================
  // Change the inputs
  //===========================================================================

  //TString fileName = "Raw_Data_July1_Ped_300V";
  //TString fileName = "Raw_Data_July1_Source_300V";
  //TString fileName = "Raw_Data_July1_Ped_200V";
  //TString fileName = "Raw_Data_Pedestal_300V";
  // TString fileName = "Raw_Data_Source_300V";

  // TString fileName = "Raw_Data_Sept_3_1";
  // TString fileName = "Raw_Data_test_3_7";
  // TString fileName = "Raw_Data_Albox_2011_03_31_1";
  //-- TString fileName = "Raw_Data_04_01_AL_center_1";
  // TString fileName = "Raw_Data_04_01_AL_7820_1";
  //-- TString fileName = "Raw_Data_7817_04_01_1";
  // TString fileName = "Raw_Data_7817_04_01_bkg_1";

  //int nAPVs = 4;

  //TString fileName = "Raw_Data_July1_Source_200V";
  //int nAPVs = 1;

  int nEvents = -1; // -1 means all

  TString dat = fileName;
  TString eps = fileName + "-events.eps";
  TString root = fileName + "-events.root";

  TFile* file = new TFile(root, "RECREATE");

  //===========================================================================
  // Read the data and make a 2D scatter plot
  //===========================================================================

  ifstream in(dat);
  if (!in) {
     cout<< "File " << dat << " not found" <<endl;
     return;
  }

  TString comments = "vertical --> APV0, APV1, ... of event 1, ...";
  TString s;
  while (1) {
    s.ReadLine(in);
    if (s.BeginsWith(comments))
      break;
  }
  gStyle->SetOptStat(10);
  TString title = fileName+"   ADC Counts vs Channel";
  TString title32 = fileName+"   ADC Counts vs Channel for 32 ch";
  TH2D *h2d = new TH2D("h2d", title.Data(), nAPVs*128, 0, nAPVs*128, 200, 0, 200);
  TH2D *h2d32 = new TH2D("h2d32", title.Data(), 16, 0, 16, 200, 0, 200);
  TProfile *profile = new TProfile("profile", title32.Data(), nAPVs*128, 0, nAPVs*128);

  int event, apv, channel, adc;
  // TTree* tree = new TTree("tree", "tree");
  // tree->Branch("event",   &event,   "event/I");
  // tree->Branch("apv",     &apv,     "apv/I");
  // tree->Branch("channel", &channel, "channel/I");
  // tree->Branch("adc",     &adc,     "adc/I");

  Int_t raw[512];
  TTree* etree = new TTree("etree", "etree");
  etree->Branch("raw",   &raw,   "raw[512]/I");    // etree->Draw("raw:Iteration$","Entry$==0")
  etree->SetMarkerStyle(6);
  etree->SetMarkerColor(2);

  int n = 0;
  while (1) {
    in >> s;
    if (!in.good())
      break;
    if (s.BeginsWith("]DATA]")) // last line
      break;
    n++;
    if ((nEvents != -1) && (n > nEvents))
      break;
    event = atoi(s.Data());
    if (event%100 == 0)
      cout << "Processing event " << event << endl;
    for (int i=0; i<2; i++)
      in >> s; // time

    Int_t ichannel = 0;
    for (apv=1; apv<=nAPVs; apv++) {
      in >> s; // header + analog APV data + one tick mark
      int sequenceNumber = 0;
      TString subString = "";
      int length = s.Length();
      for (int j=0; j<length; j++) {
        char c = s[j];
        if (c != ',') {
          subString += c;
        } else {
          if (sequenceNumber >= 12) {
            channel = sequenceNumber - 12;
            adc = atoi(subString.Data());
            h2d->Fill((apv - 1) * 128 + channel + 0.5, adc);
            h2d32->Fill(((apv - 1) * 128 + channel)/32 + 0.5, adc);
            profile->Fill((apv - 1) * 128 + channel + 0.5, adc);
            //tree->Fill();
            raw[ichannel] = adc;
            ++ichannel;
          }
          subString = "";
          sequenceNumber++;
        }
      }
    }
    etree->Fill();
  }
  in.close();

  TCanvas *canvas = new TCanvas;
  canvas->Divide(1,2);
  canvas->cd();
  canvas->cd(1); h2d->Draw();
  canvas->cd(2); profile->Draw();
  canvas->SaveAs(eps);
  // //-- TFile file(root, "RECREATE");
  // h2d->Write();
  // profile->Write();
  // tree->Write();
  // //file.Close();
  cout<< "\nWrite " << etree->GetEntries() << " of tree " << etree->GetName() << " into file " << file->GetName() <<endl;
  cout<< "To plot strip content use e.g. etree->Draw(\"raw:Iteration$\",\"Entry$==0\")" <<endl;
  file->Write();
}
コード例 #11
0
int main(int argc, char **argv)
{
	TString analysis = "Lb2Lmumu";
	bool MC = false;
	TString base = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/";

	if(argc > 1)
	{
		string arg = argv[1];
		if(arg == "MC") MC = true;
	}

	vector< string > novar;
	novar.push_back("Lb_MassCons");
	novar.push_back("Lb_MassConsLambda");
	novar.push_back("Lb_MassConsJpsiLambda");
	novar.push_back("cosTheta");
	novar.push_back("cosThetaL");
	novar.push_back("cosThetaB");
	novar.push_back("phiL");
	novar.push_back("phiB");
	novar.push_back("dphi");
	novar.push_back("cosTheta_TRUE");
	novar.push_back("cosThetaL_TRUE");
	novar.push_back("cosThetaB_TRUE");
	novar.push_back("phiL_TRUE");
	novar.push_back("phiB_TRUE");
	novar.push_back("dphi_TRUE");

	TCut cutJpsi = CutsDef::cutJpsi;
	TCut cutMuMu = CutsDef::cutMuMu_veto;

	TreeReader* treeReader = new TreeReader("tree");

	TString namefile = base + "candLb";
	if(MC) namefile += "_MC";
	namefile += ".root";

	TFile * candFile = new TFile(namefile,"recreate");

	if(!MC) treeReader->AddFile(base+analysis+"_CL_NBweighted.root");
	else treeReader->AddFile(base+analysis+"_MC_Pythia8_NBweighted.root");
	treeReader->Initialize(novar,"except");

	Analysis * anaLbMuMu = new Analysis("Lb2Lmumu","Lb",treeReader,&cutMuMu);

	candFile->cd();
	TTree * candLbMuMu = anaLbMuMu->applyCuts(&addVariables);
	candLbMuMu->Write();
	string tnameMuMu = candLbMuMu->GetName();

	candFile->Close();
	candFile = TFile::Open(namefile,"update");
	TTree * singleCand_LbMuMu = anaLbMuMu->checkMultiple("weight",namefile,tnameMuMu,&randomKill);
	singleCand_LbMuMu->Write();



	if(MC)
	{
		treeReader = new TreeReader("tree");
		treeReader->AddFile(base+"Lb2JpsiL_MC_Pythia8_NBweighted.root");
		treeReader->Initialize(novar,"except");
	}
	Analysis * anaLbJpsi = new Analysis("Lb2JpsiL","Lb",treeReader,&cutJpsi);

	candFile->cd();
	TTree * candLbJpsi = anaLbJpsi->applyCuts(&addVariables);
	candLbJpsi->Write();
	string tnameJpsi = candLbJpsi->GetName();

	candFile->Close();
	candFile = TFile::Open(namefile,"update");	
	TTree * singleCand_LbJpsi = anaLbJpsi->checkMultiple("weight",namefile,tnameJpsi,&randomKill);
	singleCand_LbJpsi->Write();

	candFile->cd();
	TTree * candLbJpsi_reduced = anaLbJpsi->applyCuts(&addVariables,300);
	candLbJpsi_reduced->SetName("candLb2JpsiL_reduced");
	candLbJpsi_reduced->Write();



	if(MC)
	{
		candFile->cd();
		TCut jpsiSwap = cutJpsi + CutsDef::jpsiSwapID;
		TCut mumuSwap = cutMuMu + CutsDef::mumuSwapID;
		TTree * mumuSwapTree = anaLbMuMu->applyCuts(&mumuSwap, false,&addVariables);
		mumuSwapTree->SetName("candLmumuSwap");
		mumuSwapTree->Write();
		TTree * jpsiSwapTree = anaLbJpsi->applyCuts(&jpsiSwap, false, &addVariables);
		jpsiSwapTree->SetName("candJpsiLSwap");
		jpsiSwapTree->Write();

		TreeReader * KSReader = new TreeReader("tree");
		KSReader->AddFile(base+"Bd2JpsiKS_MC12_NBweighted.root");
		KSReader->Initialize(novar,"except");
		TCut cutBdLL = cutJpsi + CutsDef::LLcut;
		TCut cutBdDD = cutJpsi + CutsDef::DDcut;
		Analysis * KSAnalysis_LL = new Analysis("BdJpsiKS_LL","B0",KSReader,&cutBdLL);
		TTree *KSTree_LL = KSAnalysis_LL->applyCuts(&addVariables);		
		KSTree_LL->Write();
		Analysis * KSAnalysis_DD = new Analysis("BdJpsiKS_DD","B0",KSReader,&cutBdDD);
		TTree *KSTree_DD = KSAnalysis_DD->applyCuts(&addVariables);		
		KSTree_DD->Write();
		Analysis * KSAnalysis_all = new Analysis("BdJpsiKS","B0",KSReader,&cutJpsi);
		TTree *KSTree = KSAnalysis_all->applyCuts(&addVariables);		
		KSTree->Write();

		candFile->cd();
		TreeReader * KstmumuReader = new TreeReader("tree");
		KstmumuReader->AddFile(base+"Bu2Kstmumu_MC12_NBweighted.root");
		KstmumuReader->Initialize(novar,"except");
		Analysis * KstmumuAnalysis = new Analysis("BuKstmumu","B0",KstmumuReader,&cutMuMu);
		TTree *KstmumuTree = KstmumuAnalysis->applyCuts(&addVariables);
		KstmumuTree->Write();

		candFile->cd();
		TreeReader * KSmumuReader = new TreeReader("tree");
		KSmumuReader->AddFile(base+"Bd2KSmumu_MC12_NBweighted.root");
		KSmumuReader->Initialize(novar,"except");
		Analysis * KSmumuAnalysis = new Analysis("BdKSmumu","B0",KSmumuReader,&cutMuMu);
		TTree *KSmumuTree = KSmumuAnalysis->applyCuts(&addVariables);
		KSmumuTree->Write();

		candFile->cd();
		TreeReader * JpsiGenReader = new TreeReader("tree");
		JpsiGenReader->AddFile("/afs/cern.ch/work/k/kreps/public/LbLMuMuAna/generatorLevel/LbJpsiLGenOnlyDaughInAccForRadiativeTail.root");
		JpsiGenReader->Initialize();
		TCut JpsiTailCut = "TMath::Power(J_psi_1S_MASS/1000,2) < 8 && Lb_MASS > 5300 && Lambda0_MASS > 1105 && Lambda0_MASS < 1125";
		Analysis * JpsiTailAnalysis = new Analysis("JpsiTail","Lb",JpsiGenReader,&JpsiTailCut);
		TTree *JpsiTailTree = JpsiTailAnalysis->applyCuts(&RenameMass, 0.1);
		JpsiTailTree->Write();
	}

	candFile->Close();
	delete candFile;

	return 0;
}
コード例 #12
0
ファイル: FlagClones.cpp プロジェクト: abmorris/BsphiKK
void FlagClones(string fileName = "BsphiKK_data_duplicates.root")
{
  // get the input
  TTree* tree = GetTree(fileName.c_str());
  // clone the tree..
  int num_entries = tree->GetEntries();
  vector<int> flag_clones; flag_clones.resize(num_entries);
  for (int i = 0; i < num_entries; ++i)
  {
    flag_clones[i] = 1;
  }
  double sort_var;
  //tree->SetBranchAddress("B_s0_ENDVERTEX_CHI2",&sort_var);
  UInt_t run;tree->SetBranchAddress("runNumber",&run);
  ULong64_t event; tree->SetBranchAddress("eventNumber",&event);
  int key1; tree->SetBranchAddress("Kminus_TRACK_Key",&key1);
  int key2; tree->SetBranchAddress("Kminus0_TRACK_Key",&key2);
  int key3; tree->SetBranchAddress("Kplus_TRACK_Key",&key3);
  int key4; tree->SetBranchAddress("Kplus0_TRACK_Key",&key4);
  int i = 0;
  TRandom generator(9875);
  cout << "Finding duplicate candidates in a sample containing " << num_entries << " events" << endl;
  while(i < num_entries)
  {
    tree->GetEntry(i);
    sort_var = generator.Rndm();
    int run_i = run;
    int event_i = event;
    vector<CloneInfo> clones;
    CloneTagger tagger(clones);
    tagger.addToClones({key1,key2,key3,key4},i,sort_var);
    int j = i+1;
    for (j=i+1;j<num_entries; j++)
    {
      tree->GetEntry(j);
      sort_var = generator.Rndm();
      int run_j = run;
      int event_j = event;
      if(run_j!=run_i || event_j!=event_i)
      {
        break;
      }
      else
      {
        tagger.addToClones({key1,key2,key3,key4},j,sort_var);
      }
    }
    tagger.sortClones();
    tagger.tagClones();
    if(clones.size() > 1)
    {
      for(auto clone : clones)
      {
        flag_clones[clone.i()] = clone.isAlive();
      }
    }
    i=j;
  }
  // make the output
  string outputName = fileName.substr(0,fileName.size() - 5);
  outputName += "_Clone.root";
  TFile* outFile = TFile::Open(outputName.c_str(),"RECREATE");
  cout << "Reading: " << tree->GetName() << " from " << fileName  << " to " << outputName << endl;
  TTree*  newtree = tree->CloneTree(-1);
  int isAlive;
  TBranch *branch_bestVtxChi2 = newtree->Branch("isDup",&isAlive, "isDup/I");
  num_entries = newtree->GetEntries();
  // loop again and write the branch
  for (i=0;i<num_entries; i++)
  {
    newtree->GetEntry(i);
    isAlive = flag_clones[i];
    branch_bestVtxChi2->Fill();
  }
  newtree->Write();
  outFile->Close();
  return;
}
コード例 #13
0
ファイル: HelperProcess.C プロジェクト: istaslis/pPbmacro
//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();
}
コード例 #14
0
ファイル: H4Reco.cpp プロジェクト: H4VFE/H4Analysis
//**********MAIN**************************************************************************
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        cout << argv[0] << " cfg file " << "[run]" << endl; 
        return -1;
    }

    //---memory consumption tracking---
    float cpu[2]{0}, mem[2]={0}, vsz[2]={0}, rss[2]={0};

    //---load options---    
    CfgManager opts;
    opts.ParseConfigFile(argv[1]);

    //-----input setup-----    
    if(argc > 2)
    {
        vector<string> run(1, argv[2]);
        opts.SetOpt("h4reco.run", run);
    }
    string outSuffix = opts.GetOpt<string>("h4reco.outNameSuffix");
    string run = opts.GetOpt<string>("h4reco.run");
    TChain* inTree = new TChain("H4tree");
    ReadInputFiles(opts, inTree);
    H4Tree h4Tree(inTree);

    //-----output setup-----
    uint64 index=stoul(run)*1e9;
    TFile* outROOT = new TFile("ntuples/"+outSuffix+TString(run)+".root", "RECREATE");
    outROOT->cd();
    RecoTree mainTree(&index);

    //---Get plugin sequence---
    PluginLoader<PluginBase>* loader;
    vector<PluginLoader<PluginBase>* > pluginLoaders;    
    map<string, PluginBase*> pluginMap;
    vector<PluginBase*> pluginSequence;
    vector<string> pluginList = opts.GetOpt<vector<string> >("h4reco.pluginList");    
    //---plugin creation
    pluginLoaders.reserve(pluginList.size());
    for(auto& plugin : pluginList)
    {
        cout << ">>> Loading plugin <" << plugin << ">" << endl;
        //---create loader 
        loader = new PluginLoader<PluginBase>(opts.GetOpt<string>(plugin+".pluginType"));
        pluginLoaders.push_back(loader);
        pluginLoaders.back()->Create();
        //---get instance and put it in the plugin sequence   
        PluginBase* newPlugin = pluginLoaders.back()->CreateInstance();
        if(newPlugin)
        {
            pluginSequence.push_back(newPlugin);
            pluginSequence.back()->SetInstanceName(plugin);
            pluginMap[plugin] = pluginSequence.back();
        }
        else
        {
            cout << ">>> ERROR: plugin type " << opts.GetOpt<string>(plugin+".pluginType") << " is not defined." << endl;
            return 0;
        }
    }

    //---begin
    for(auto& plugin : pluginSequence)
    {
        plugin->Begin(opts, &index);
        for(auto& shared : plugin->GetSharedData("", "TTree", true))
        {
            TTree* tree = (TTree*)shared.obj;
            tree->SetMaxVirtualSize(10000);
            tree->SetDirectory(outROOT);
        }
    }
            
    //---events loop
    int maxEvents=opts.GetOpt<int>("h4reco.maxEvents");
    cout << ">>> Processing H4DAQ run #" << run << " <<<" << endl;
    while(h4Tree.NextEntry() && (index-stoul(run)*1e9<maxEvents || maxEvents==-1))
    {
        if(index % 1000 == 0)
        {
            cout << ">>>Processed events: " << index-stoul(run)*1e9 << "/"
                 << (maxEvents<0 ? h4Tree.GetEntries() : min((int)h4Tree.GetEntries(), maxEvents))
                 << endl;
            TrackProcess(cpu, mem, vsz, rss);
        }

        //---call ProcessEvent for each plugin
        for(auto& plugin : pluginSequence)
            plugin->ProcessEvent(h4Tree, pluginMap, opts);

        //---fill the main tree with info variables and increase event counter
        mainTree.time_stamp = h4Tree.evtTimeStart;
        mainTree.run = h4Tree.runNumber;
        mainTree.spill = h4Tree.spillNumber;
        mainTree.event = h4Tree.evtNumber;
        mainTree.Fill();
        ++index;
    }

    //---end
    for(auto& plugin : pluginSequence)
    {
        //---call endjob for each plugin
        plugin->End(opts);
        //---get permanent data from each plugin and store them in the out file
        for(auto& shared : plugin->GetSharedData())
        {
            if(shared.obj->IsA()->GetName() == string("TTree"))
            {
                TTree* currentTree = (TTree*)shared.obj;
                outROOT->cd();
                currentTree->BuildIndex("index");
                currentTree->Write(currentTree->GetName(), TObject::kOverwrite);
                mainTree.AddFriend(currentTree->GetName());
            }
            else
            {
                outROOT->cd();
                shared.obj->Write(shared.tag.c_str(), TObject::kOverwrite);
            }
        }
    }
    
    //---close
    mainTree.Write();
    opts.Write("cfg");
    outROOT->Close();
    for(auto& loader : pluginLoaders)
        loader->Destroy();

    //---info
    TrackProcess(cpu, mem, vsz, rss);

    exit(0);
}    
コード例 #15
0
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, 
                                    Int_t Option = 0, Int_t NToys = 1) {


  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================    
  TRandom3 *randomnumber = new TRandom3(seed);
//   RooRealVar m("m","mass",60,130);

  RooCategory sample("sample","");
  sample.defineType("Pass",1);
  sample.defineType("Fail",2);

  //--------------------------------------------------------------------------------------------------------------
  //Load Workspace
  //==============================================================================================================    
  TFile *f = new TFile (workspaceFile.c_str(), "READ");
  RooWorkspace *w = (RooWorkspace*)f->Get("MassFitWorkspace");

  //--------------------------------------------------------------------------------------------------------------
  //Setup output tree
  //==============================================================================================================    
  TFile *outputfile = new TFile (Form("EffToyResults_Option%d_Seed%d.root",Option, seed), "RECREATE");
  float varEff = 0;
  float varEffErrL = 0;
  float varEffErrH = 0;
  TTree *outTree = new TTree("eff","eff");
  outTree->Branch("eff",&varEff, "eff/F");
  outTree->Branch("efferrl",&varEffErrL, "efferrl/F");
  outTree->Branch("efferrh",&varEffErrH, "efferrh/F");
  
  //--------------------------------------------------------------------------------------------------------------
  //Load Model
  //==============================================================================================================    
  RooSimultaneous *totalPdf = (RooSimultaneous*)w->pdf("totalPdf");
  RooRealVar *m_default = (RooRealVar*)w->var("m");
  m_default->setRange("signalRange",85, 95);
  
  //get default models
  RooAddPdf *modelPass_default = (RooAddPdf*)w->pdf("modelPass");
  RooAddPdf *modelFail_default = (RooAddPdf*)w->pdf("modelFail");

  //get variables
  RooRealVar *Nsig = (RooRealVar*)w->var("Nsig");
  RooRealVar *eff = (RooRealVar*)w->var("eff");
  RooRealVar *NbkgFail = (RooRealVar*)w->var("NbkgFail");

  RooFormulaVar NsigPass("NsigPass","eff*Nsig",RooArgList(*eff,*Nsig));	 
  RooFormulaVar NsigFail("NsigFail","(1.0-eff)*Nsig",RooArgList(*eff,*Nsig));

  //get number of expected events
  Double_t npass = 100;
  Double_t nfail = 169;

  //*************************************************************************************
  //make alternative model
  //*************************************************************************************
  RooRealVar *tFail_default = (RooRealVar*)w->var("tFail");
  RooRealVar *fracFail_default = (RooRealVar*)w->var("fracFail");
 

  RooRealVar *meanFail_default = (RooRealVar*)w->var("meanFail");
  RooRealVar *sigmaFail_default = (RooRealVar*)w->var("sigmaFail");
  RooHistPdf *bkgFailTemplate_default = (RooHistPdf*)w->pdf("bkgHistPdfFail");
  RooFFTConvPdf *sigFail_default = (RooFFTConvPdf*)w->pdf("signalFail");
  RooFFTConvPdf *bkgFail_default = (RooFFTConvPdf*)w->pdf("bkgConvPdfFail");
  RooExtendPdf *esignalFail_default = (RooExtendPdf *)w->pdf("esignalFail");
  RooExtendPdf *ebackgroundFail_default = (RooExtendPdf *)w->pdf("ebackgroundFail");
  RooExponential *bkgexpFail_default = (RooExponential*)w->pdf("bkgexpFail");
  RooAddPdf *backgroundFail_default = (RooAddPdf*)w->pdf("backgroundFail");
  RooGaussian *bkggausFail_default = (RooGaussian*)w->pdf("bkggausFail");

  //shifted mean
  RooRealVar *meanFail_shifted = new RooRealVar("meanFail_shifted","meanFail_shifted", 0, -5, 5);
  meanFail_shifted->setVal(meanFail_default->getVal());
  if (Option == 1) meanFail_shifted->setVal(meanFail_default->getVal()-1.0);
  else if (Option == 2) meanFail_shifted->setVal(meanFail_default->getVal()+1.0);  
  else if (Option == 11) meanFail_shifted->setVal(meanFail_default->getVal()-2.0);
  else if (Option == 12) meanFail_shifted->setVal(meanFail_default->getVal()+2.0);  

  RooRealVar *sigmaFail_shifted = new RooRealVar("sigmaFail_shifted","sigmaFail_shifted", 0, -5, 5);
  sigmaFail_shifted->setVal(sigmaFail_default->getVal());
  if (Option == 3) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*1.2);
  else if (Option == 4) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*0.8);

  CMCBkgTemplateConvGaussianPlusExp *bkgFailModel = new CMCBkgTemplateConvGaussianPlusExp(*m_default,bkgFailTemplate_default,false,meanFail_shifted,sigmaFail_shifted, "shifted");
  bkgFailModel->t->setVal(tFail_default->getVal());
  bkgFailModel->frac->setVal(fracFail_default->getVal());

  cout << "mean : " << meanFail_default->getVal() << " - " << meanFail_shifted->getVal() << endl;
  cout << "sigma : " << sigmaFail_default->getVal() << " - " << sigmaFail_shifted->getVal() << endl;
  cout << "t: " << tFail_default->getVal() << " - " << bkgFailModel->t->getVal() << endl;
  cout << "frac: " << fracFail_default->getVal() << " - " << bkgFailModel->frac->getVal() << endl;
  
  cout << "eff: " << eff->getVal() << " : " << NsigPass.getVal() << " / " << (NsigPass.getVal() + NsigFail.getVal()) << endl;
  cout << "NbkgFail: " << NbkgFail->getVal() << endl;


  //make alternative fail model
  RooAddPdf *modelFail=0;
  RooExtendPdf *esignalFail=0, *ebackgroundFail=0;
  ebackgroundFail = new RooExtendPdf("ebackgroundFail_shifted","ebackgroundFail_shifted",*(bkgFailModel->model),*NbkgFail,"signalRange");
  modelFail       = new RooAddPdf("modelFail","Model for FAIL sample", RooArgList(*esignalFail_default,*ebackgroundFail));



  cout << "*************************************\n";
  ebackgroundFail->Print();
  cout << "*************************************\n";
  ebackgroundFail_default->Print();
  cout << "*************************************\n";
  modelFail->Print();
  cout << "*************************************\n";
  modelFail_default->Print();
  cout << "*************************************\n";

  TCanvas *cv = new TCanvas("cv","cv",800,600);

  RooPlot *mframeFail_default = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail_default->plotOn(mframeFail_default);
  modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
  modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail_default->GetYaxis()->SetTitle("");
  mframeFail_default->GetYaxis()->SetTitleOffset(1.2);
  mframeFail_default->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail_default->GetXaxis()->SetTitleOffset(1.05);
  mframeFail_default->SetTitle("");
  mframeFail_default->Draw();

  cv->SaveAs("DefaultModel.gif");

  RooPlot *mframeFail = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail->plotOn(mframeFail);
  modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
  modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail->GetYaxis()->SetTitle("");
  mframeFail->GetYaxis()->SetTitleOffset(1.2);
  mframeFail->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail->GetXaxis()->SetTitleOffset(1.05);
  mframeFail->SetTitle("");
  mframeFail->Draw();
  cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


  //*************************************************************************************
  //Do Toys
  //*************************************************************************************
  for(uint t=0; t < NToys; ++t) {

    RooDataSet *pseudoData_pass    = modelPass_default->generate(*m_default, randomnumber->Poisson(npass));
    RooDataSet *pseudoData_fail  = 0;
    pseudoData_fail    = modelFail->generate(*m_default, randomnumber->Poisson(nfail));
    RooDataSet *pseudoDataCombined = new RooDataSet("pseudoDataCombined","pseudoDataCombined",RooArgList(*m_default),
                                                    RooFit::Index(sample),
                                                    RooFit::Import("Pass",*pseudoData_pass),
                                                    RooFit::Import("Fail",*pseudoData_fail));

    pseudoDataCombined->write(Form("toy%d.txt",t));

    RooFitResult *fitResult=0;
    fitResult = totalPdf->fitTo(*pseudoDataCombined,
                                RooFit::Extended(),
                                RooFit::Strategy(2),
                                //RooFit::Minos(RooArgSet(eff)),
                                RooFit::Save());

    cout << "\n\n";
    cout << "Eff Fit: " << eff->getVal() << " -" << fabs(eff->getErrorLo()) << " +" << eff->getErrorHi() << endl;

    //Fill Tree
    varEff = eff->getVal();
    varEffErrL = fabs(eff->getErrorLo());
    varEffErrH = eff->getErrorHi();
    outTree->Fill();


//   //*************************************************************************************
//   //Plot Toys
//   //*************************************************************************************
//   TCanvas *cv = new TCanvas("cv","cv",800,600);
//   char pname[50];
//   char binlabelx[100];
//   char binlabely[100];
//   char yield[50];
//   char effstr[100];
//   char nsigstr[100];
//   char nbkgstr[100];
//   char chi2str[100];

//   //
//   // Plot passing probes
//   //

//   RooPlot *mframeFail_default = m.frame(Bins(Int_t(130-60)/2));
//   modelFail_default->plotOn(mframeFail_default);
//   modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
//   modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
//   mframeFail_default->Draw();
//   cv->SaveAs("DefaultModel.gif");





//   RooPlot *mframeFail = m.frame(Bins(Int_t(130-60)/2));
//   modelFail->plotOn(mframeFail);
//   modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
//   modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));

//   sprintf(yield,"%u Events",(Int_t)passTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigPass.getVal(),NsigPass.getPropagatedError(*fitResult));
//     plotPass.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   plotPass.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);
//     plotPass.AddTextBox(0.70,0.73,0.94,0.83,0,kBlack,-1,1,nsigstr);//,chi2str);

//   mframeFail->Draw();
//   cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


 
//   //
//   // Plot failing probes
//   //
//   sprintf(pname,"fail%s_%i",name.Data(),ibin);
//   sprintf(yield,"%u Events",(Int_t)failTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigFail.getVal(),NsigFail.getPropagatedError(*fitResult));
//   sprintf(nbkgstr,"N_{bkg} = %.1f #pm %.1f",NbkgFail.getVal(),NbkgFail.getPropagatedError(*fitResult));
//   sprintf(chi2str,"#chi^{2}/DOF = %.3f",mframePass->chiSquare(nflfail));
//   CPlot plotFail(pname,mframeFail,"Failing probes","tag-probe mass [GeV/c^{2}]","Events / 2.0 GeV/c^{2}");
//   plotFail.AddTextBox(binlabelx,0.21,0.85,0.51,0.90,0,kBlack,-1);
//   if((name.CompareTo("etapt")==0) || (name.CompareTo("etaphi")==0)) {
//     plotFail.AddTextBox(binlabely,0.21,0.80,0.51,0.85,0,kBlack,-1);    
//     plotFail.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   } else {
//     plotFail.AddTextBox(yield,0.21,0.81,0.51,0.85,0,kBlack,-1);
//   }
//   plotFail.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);  
//   plotFail.AddTextBox(0.70,0.68,0.94,0.83,0,kBlack,-1,2,nsigstr,nbkgstr);//,chi2str);
//   plotFail.Draw(cfail,kTRUE,format);  




  } //for loop over all toys
  



  //*************************************************************************************
  //Save To File
  //*************************************************************************************
  outputfile->WriteTObject(outTree, outTree->GetName(), "WriteDelete");

}
コード例 #16
0
void SkimClassification(TString process="ZnnH125")
{
    gROOT->LoadMacro("HelperFunctions.h" );  // make functions visible to TTreeFormula
    gROOT->SetBatch(1);

    //TChain * chain  = new TChain("tree");
    //TString fname   = "";
    //TString dijet   = "DiJetPt_";
    //TString dirMC   = "dcache:/pnfs/cms/WAX/resilient/jiafu/ZnunuHbb/" + tagMC + "/";
    //TString dirData = "dcache:/pnfs/cms/WAX/resilient/jiafu/ZnunuHbb/" + tagData + "/";
    TString indir   = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Spring15_PU20bx25/skimV12_v2/step3/";
    TString outdir  = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Spring15_PU20bx25/skimV12_v2/step3/skim_ZnnH_classification/";
    TString prefix  = "Step3_";
    TString suffix  = ".root";

    TFile *input = TFile::Open(indir + prefix + process + suffix);
    if (!input) {
        std::cout << "ERROR: Could not open input file." << std::endl;
        exit(1);
    }
    TTree *tree   = (TTree *) input->Get("tree");
    Long64_t entries = tree->GetEntriesFast();
    
    // Make output directory if it doesn't exist
    if (gSystem->AccessPathName(outdir))
        gSystem->mkdir(outdir);
    TString outname = outdir + prefix + Form("%s.root", process.Data());

    TFile* output = TFile::Open(outname, "RECREATE");

    // Get selections
    const std::vector < std::string > & selExpressions = GetSelExpressions("ZnunuHighPt") ;
    //    const UInt_t nsels = 3;  // ZnunuHighPt, ZnunuLowPt, ZnunuLowCSV
    const UInt_t nsels = 1;  // just one now...  ZnunuHighPt, ZnunuLowPt, ZnunuLowCSV

    //    assert(nsels == selExpressions.size()); <-- fixME
    // even-number events for training, odd-number events for testing
    TCut evenselection = "evt  %2 == 0";
    TCut oddselection  = "evt %2 == 1";

    TTreeFormula *ttf = 0;
    std::vector < TTreeFormula * >::const_iterator formIt, formItEnd;

    // Loop over selections
    std::vector<Long64_t> ventries;
    for (unsigned int i = 0; i < nsels; i++) {
        TString selname = "ZnunuHighPt";
        if (i == 1) {
            selname = "ZnunuMedPt";
	    //	    selExpressions = GetSelExpressions("ZnunuMedPt") ;
        } else if (i == 2) {
            selname = "ZnunuLowPt";
	    // selExpressions = GetSelExpressions("ZnunuLowPt") ;
        }

        TTree *t1 = (TTree*) tree->CloneTree(0);
        TTree *t2 = (TTree*) tree->CloneTree(0);
        
        t1->SetName(TString::Format("%s_%s_train", tree->GetName(), selname.Data()));
        t2->SetName(TString::Format("%s_%s", tree->GetName(), selname.Data()));
        
        // The clones should not delete any shared i/o buffers.
        ResetDeleteBranches(t1);
        ResetDeleteBranches(t2);
        
        ttf = new TTreeFormula(Form("ttfsel%i", i), selExpressions.at(i).c_str(), tree);
        ttf->SetQuickLoad(1);
        TTreeFormula *ttf1 = new TTreeFormula(Form("ttfeven%i", i), evenselection, tree);
        ttf1->SetQuickLoad(1);
        TTreeFormula *ttf2 = new TTreeFormula(Form("ttfodd%i", i), oddselection, tree);
        ttf2->SetQuickLoad(1);
        if (!ttf || !ttf->GetNdim()) {
            std::cerr << "ERROR: Failed to find any TTree variable from the selection: " << selExpressions.at(i) << std::endl;
            return;
        }

        
        /// Loop over events
        Int_t curTree = tree->GetTreeNumber();
        const Long64_t nentries = tree->GetEntries();
        for (Long64_t ievt = 0; ievt < nentries; ievt++) {
            Long64_t entryNumber = tree->GetEntryNumber(ievt);
            if (entryNumber < 0)  break;
            Long64_t localEntry = tree->LoadTree(entryNumber);
            if (localEntry < 0)  break;
            if (tree->GetTreeNumber() != curTree) {
                curTree = tree->GetTreeNumber();
                ttf ->UpdateFormulaLeaves();  // if using TChain
                ttf1->UpdateFormulaLeaves();  // if using TChain
                ttf2->UpdateFormulaLeaves();  // if using TChain
            }
            
            const Int_t ndata = ttf->GetNdata();
            Bool_t keep = kFALSE;
            for(Int_t current = 0; current<ndata && !keep; current++) {
                keep |= (bool(ttf->EvalInstance(current)) != 0);
            }
            if (!keep)  continue;


            bool even  = (bool) ttf1->EvalInstance();
            bool odd   = (bool) ttf2->EvalInstance();
            if (even && odd) {
                std::cerr << "ERROR: An event cannot be even and odd at the same time." << std::cout;
                return;
            }

            tree->GetEntry(entryNumber, 1);  // get all branches
            if (even) {
                t1->Fill();
            } else {
                t2->Fill();
            }
        }  // end loop over events

        t1->Write();
        t2->Write();
        
        ventries.push_back(t1->GetEntriesFast() + t2->GetEntriesFast());
        
        delete ttf;
        delete ttf1;
        delete ttf2;
    }
    
    std::clog << process << ": skimmed from " << entries << " to " << ventries[0] << " (ZnunuHighPt), " << ventries[1] << " (ZnunuLowPt), " << ventries[2] << " (ZnunuLowCSV) " << " entries." << std::endl;

    output->Close();
    input->Close();

    delete output;
    delete input;

    return;
}
コード例 #17
0
void fullPedestalAnalysis(string inputDIR, string outputDIR, string inputCablingMap, string outputFileName){

  gROOT->ProcessLine("gErrorIgnoreLevel = 1");
  
  // open the file and prepare the cluster tree, adding the other trees as frined --> memory consuming                                                                                                
  std::cout<<"##################################"<<std::endl;
  std::cout<<"###### fullPedestalAnalysis ######"<<std::endl;
  std::cout<<"##################################"<<std::endl;

  clock_t tStart = clock();

  // prepare style and load macros                                                                                                                                                                    
  setTDRStyle();
  gROOT->SetBatch(kTRUE);

  system(("mkdir -p "+outputDIR).c_str());
  ifstream file;

  std::cout<<"### Make input file list"<<std::endl;
  system(("find "+inputDIR+" -name \"*.root\" > file.temp").c_str());
  std::ifstream infile;
  string line;
  vector<string> fileList;
  infile.open("file.temp",ifstream::in);
  if(infile.is_open()){
    while(!infile.eof()){
      getline(infile,line);
      if(line != "" and TString(line).Contains(".root") and line !="\n"){
        fileList.push_back(line);
      }
    }
  }
  system("rm file.temp");
  std::sort(fileList.begin(),fileList.end());

  TFile* cablingFile = TFile::Open(inputCablingMap.c_str(),"READ");
  cablingFile->cd();
  TTree* readoutMap = (TTree*) cablingFile->FindObjectAny("readoutMap");
  TTreeReader reader(readoutMap);
  TTreeReaderValue<uint32_t> detid    (reader,"detid");
  TTreeReaderValue<uint16_t> fecCrate (reader,"fecCrate");
  TTreeReaderValue<uint16_t> fecSlot  (reader,"fecSlot");
  TTreeReaderValue<uint16_t> fecRing  (reader,"fecRing");
  TTreeReaderValue<uint16_t> ccuAdd   (reader,"ccuAdd");
  TTreeReaderValue<uint16_t> ccuChan  (reader,"ccuChan");
  TTreeReaderValue<uint16_t> lldChannel  (reader,"lldChannel");
  TTreeReaderValue<uint16_t> fedId  (reader,"fedId");
  TTreeReaderValue<uint16_t> fedCh  (reader,"fedCh");

  // output tree
  TFile* ouputTreeFile = new TFile((outputDIR+"/"+outputFileName).c_str(),"RECREATE");
  ouputTreeFile->cd();
  ouputTreeFile->SetCompressionLevel(0);
  TTree* outputTree = new TTree("pedestalFullNoise","pedestalFullNoise");
  
  // branches
  uint32_t detid_,fedKey_;
  uint16_t fecCrate_,fecSlot_, fecRing_, ccuAdd_, ccuChan_, lldChannel_, fedId_, fedCh_, apvId_, stripId_;
  float    noiseMean_,noiseRMS_, noiseSkewness_, noiseKurtosis_;
  float    fitChi2_, fitChi2Probab_, fitStatus_;
  float    fitGausMean_, fitGausSigma_, fitGausNormalization_;
  float    fitGausMeanError_, fitGausSigmaError_, fitGausNormalizationError_;
  float    noiseIntegral3Sigma_, noiseIntegral3SigmaFromFit_;
  float    noiseIntegral4Sigma_, noiseIntegral4SigmaFromFit_;
  float    noiseIntegral5Sigma_, noiseIntegral5SigmaFromFit_;
  float    kSValue_, kSProbab_, jBValue_, jBProbab_, aDValue_, aDProbab_;
  vector<float> noiseDistribution_, noiseDistributionError_;
  float xMin_, xMax_, nBin_ ;

  outputTree->Branch("detid",&detid_,"detid/i");
  outputTree->Branch("fedKey",&fedKey_,"fedKey/i");
  outputTree->Branch("fecCrate",&fecCrate_,"fecCrate/s");
  outputTree->Branch("fecSlot",&fecSlot_,"fecSlot/s");
  outputTree->Branch("fecRing",&fecRing_,"fecRing/s");
  outputTree->Branch("ccuAdd",&ccuAdd_,"ccuAdd/s");
  outputTree->Branch("ccuChan",&ccuChan_,"ccuChan/s");
  outputTree->Branch("lldChannel",&lldChannel_,"lldChannel/s");
  outputTree->Branch("fedId",&fedId_,"fedId/s");
  outputTree->Branch("fedCh",&fedCh_,"fedCh/s");
  outputTree->Branch("apvId",&apvId_,"apvId/s");
  outputTree->Branch("stripId",&stripId_,"stripId/s");

  outputTree->Branch("noiseMean",&noiseMean_,"noiseMean/F");
  outputTree->Branch("noiseRMS",&noiseRMS_,"noiseRMS/F");
  outputTree->Branch("noiseSkewness",&noiseSkewness_,"noiseSkewness/F");
  outputTree->Branch("noiseKurtosis",&noiseKurtosis_,"noiseKurtosis/F");
  outputTree->Branch("fitGausNormalization",&fitGausNormalization_,"fitGausNormalization/F");
  outputTree->Branch("fitGausMean",&fitGausMean_,"fitGausMean/F");
  outputTree->Branch("fitGausSigma",&fitGausSigma_,"fitGausSigma/F");
  outputTree->Branch("fitGausNormalizationError",&fitGausNormalizationError_,"fitGausNormalizationError/F");
  outputTree->Branch("fitGausMeanError",&fitGausMeanError_,"fitGausMeanError/F");
  outputTree->Branch("fitGausSigmaError",&fitGausSigmaError_,"fitGausSigmaError/F");
  outputTree->Branch("fitChi2",&fitChi2_,"fitChi2/F");
  outputTree->Branch("fitChi2Probab",&fitChi2Probab_,"fitChi2Probab/F");
  outputTree->Branch("fitStatus",&fitStatus_,"fitStatus_F");
  outputTree->Branch("noiseIntegral3Sigma",&noiseIntegral3Sigma_,"noiseIntegral3Sigma/F");
  outputTree->Branch("noiseIntegral3SigmaFromFit",&noiseIntegral3SigmaFromFit_,"noiseIntegral3SigmaFromFit/F");
  outputTree->Branch("noiseIntegral4Sigma",&noiseIntegral4Sigma_,"noiseIntegral4Sigma/F");
  outputTree->Branch("noiseIntegral4SigmaFromFit",&noiseIntegral4SigmaFromFit_,"noiseIntegral4SigmaFromFit/F");
  outputTree->Branch("noiseIntegral5Sigma",&noiseIntegral4Sigma_,"noiseIntegral5Sigma/F");
  outputTree->Branch("noiseIntegral5SigmaFromFit",&noiseIntegral4SigmaFromFit_,"noiseIntegral5SigmaFromFit/F");
  outputTree->Branch("kSValue",&kSValue_,"kSValue/F");
  outputTree->Branch("jBValue",&jBValue_,"jBValue/F");
  outputTree->Branch("aDValue",&aDValue_,"aDValue/F");
  outputTree->Branch("kSProbab",&kSProbab_,"kSProbab/F");
  outputTree->Branch("jBProbab",&jBProbab_,"jBProbab/F");
  outputTree->Branch("aDProbab",&aDProbab_,"aDProbab/F");
  outputTree->Branch("xMin",&xMin_,"xMin/F");
  outputTree->Branch("xMax",&xMax_,"xMax/F");
  outputTree->Branch("nBin",&nBin_,"nBin/F");

  bool histoBranches = false;

  // Loop on the file list to extract each histogram 2D DQM histo with full noise distribution  
  TH1F* histoNoiseStrip = NULL;
  TF1*  fitFunc = NULL;
  TH1F* randomHisto = NULL;
  TFitResultPtr result;
  for(auto file : fileList){
    cout<<"input file: "<<file<<endl;
    TFile* inputFile = TFile::Open(file.c_str(),"READ");
    inputFile->cd();
    // take into account that the DQM file structure for strips is always the same --> use cabling map to browse the histograms
    reader.SetEntry(0);
    TH2* histoNoise = NULL;
    long int iChannel = 0;
    int noFitResult = 0;
    while(reader.Next()){
      cout.flush();
      if(iChannel %10 == 0) cout<<"\r"<<"iChannel "<<100*double(iChannel)/(readoutMap->GetEntries()/reductionFactor)<<" % ";
      if(iChannel > double(readoutMap->GetEntries())/reductionFactor) break;
      iChannel++;
      TString objName;
      uint32_t fedKey =  SiStripFedKey(*fedId,SiStripFedKey::feUnit(*fedCh),SiStripFedKey::feChan(*fedCh)).key();
      std::stringstream stream;
      stream << std::hex << fedKey;
      string fedKeyStr = stream.str();
      if(fedKeyStr.size() == 4)
	objName = Form("DQMData/SiStrip/ControlView/FecCrate%d/FecSlot%d/FecRing%d/CcuAddr%d/CcuChan%d/ExpertHisto_PedsFullNoise_FedKey0x0000%s_LldChannel%d_Noise2D",*fecCrate,*fecSlot,*fecRing,*ccuAdd,*ccuChan,fedKeyStr.c_str(),*lldChannel);      
      else if(fedKeyStr.size() == 5)
	objName = Form("DQMData/SiStrip/ControlView/FecCrate%d/FecSlot%d/FecRing%d/CcuAddr%d/CcuChan%d/ExpertHisto_PedsFullNoise_FedKey0x000%s_LldChannel%d_Noise2D",*fecCrate,*fecSlot,*fecRing,*ccuAdd,*ccuChan,fedKeyStr.c_str(),*lldChannel);      
      else
	cerr<<"hex number to short "<<fedKeyStr<<" --> please check "<<endl;

      inputFile->GetObject(objName.Data(),histoNoise);
      // extract single strip noise histogram --> loop on the y-axis
      uint16_t apvID = 0;
      uint16_t stripID = 0;       
      if(histoNoiseStrip == 0 or histoNoiseStrip == NULL){
	histoNoiseStrip = new TH1F ("histoNoiseStrip","",histoNoise->GetNbinsX(),histoNoise->GetXaxis()->GetXmin(),histoNoise->GetXaxis()->GetXmax());
	histoNoiseStrip->Sumw2();
      }
      for(int iBinY = 0; iBinY < histoNoise->GetNbinsY(); iBinY++){
	histoNoiseStrip->Reset();
	histoNoiseStrip->SetDirectory(0);
	// two multiplexed APV per line
	if(iBinY < histoNoise->GetNbinsY()/2) apvID = 1;
	else apvID = 2;
	// strip id
	stripID++;
	if(stripID > 128) stripID = 1;
	// loop on x-axis bin
	for(int iBinX = 0; iBinX < histoNoise->GetNbinsX(); iBinX++){
	  histoNoiseStrip->SetBinContent(iBinX+1,histoNoise->GetBinContent(iBinX+1,iBinY+1));
	  histoNoiseStrip->SetBinError(iBinX+1,histoNoise->GetBinError(iBinX+1,iBinY+1));	    
	}
     	
	// to initialize branches
	detid_ = 0; fedKey_ = 0; fecCrate_ = 0; fecSlot_ = 0; fecRing_ = 0; ccuAdd_ = 0; ccuChan_ = 0; lldChannel_ = 0; fedId_ = 0; fedCh_ = 0; apvId_ = 0; stripId_ = 0; 
	noiseMean_ = 0.; noiseRMS_ =  0.; noiseSkewness_ = 0.; noiseKurtosis_ = 0.; 
	fitGausMean_ = 0.; fitGausSigma_ = 0.;fitGausNormalization_ = 0.;
	fitGausMeanError_ = 0.; fitGausSigmaError_ = 0.;fitGausNormalizationError_ = 0.;	  	  
	fitChi2_ = 0.; fitChi2Probab_ = 0.; fitStatus_ = -1.; 
	noiseIntegral3Sigma_ = 0.; noiseIntegral3SigmaFromFit_ = 0.; 
	noiseIntegral4Sigma_ = 0.; noiseIntegral4SigmaFromFit_ = 0.; 
	noiseIntegral5Sigma_ = 0.; noiseIntegral5SigmaFromFit_ = 0.; 
	kSProbab_ = 0.; jBProbab_ = 0.;
	kSValue_ = 0.; jBValue_ = 0.; 
	aDValue_= 0.; aDProbab_ = 0.;
	nBin_ = 0.; xMin_ = 0.; xMax_ = 0.;
	
	// basic info
	detid_ = *detid;
	fedKey_ = fedKey;
	fecCrate_ = *fecCrate;
	fecSlot_ = *fecSlot;
	fecRing_ = *fecRing;
	ccuAdd_  = *ccuAdd;
	ccuChan_ = *ccuChan;
	lldChannel_ = *lldChannel;
	fedId_   = *fedId;
	fedCh_   = *fedCh;
	apvId_   = apvID;
	stripId_ = stripID;
	
	// basic info of nioise distribution
	noiseMean_ = histoNoiseStrip->GetMean();
	noiseRMS_  = histoNoiseStrip->GetRMS();
	noiseSkewness_ = histoNoiseStrip->GetSkewness();
	noiseKurtosis_ = histoNoiseStrip->GetKurtosis();
	float integral = histoNoiseStrip->Integral();	
	noiseIntegral3Sigma_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+noiseRMS_*3),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-noiseRMS_*3)))/integral;
	noiseIntegral4Sigma_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+noiseRMS_*4),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-noiseRMS_*4)))/integral;
	noiseIntegral5Sigma_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+noiseRMS_*5),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-noiseRMS_*5)))/integral;
	
	// make a gaussian fit	  	
	if(fitFunc == NULL or fitFunc == 0){
	  fitFunc = new TF1 ("fitFunc","gaus(0)",histoNoise->GetXaxis()->GetXmin(),histoNoise->GetXaxis()->GetXmax());
	}
	fitFunc->SetRange(histoNoise->GetXaxis()->GetXmin(),histoNoise->GetXaxis()->GetXmax());
	fitFunc->SetParameters(histoNoiseStrip->Integral(),noiseMean_,noiseRMS_);
	result = histoNoiseStrip->Fit(fitFunc,"QSR");

	if(result.Get()){
	    fitStatus_     = result->Status();
	    fitGausNormalization_  = fitFunc->GetParameter(0);
	    fitGausMean_   = fitFunc->GetParameter(1);
	    fitGausSigma_  = fitFunc->GetParameter(2);
	    fitGausNormalizationError_  = fitFunc->GetParError(0);
	    fitGausMeanError_  = fitFunc->GetParError(1);
	    fitGausSigmaError_ = fitFunc->GetParError(2);
	    fitChi2_           = result->Chi2();
	    fitChi2Probab_     = result->Prob();

	    noiseIntegral3SigmaFromFit_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+fitGausSigma_*3),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-fitGausSigma_*3)))/histoNoiseStrip->Integral();
	    noiseIntegral4SigmaFromFit_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+fitGausSigma_*4),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-fitGausSigma_*4)))/histoNoiseStrip->Integral();
	    noiseIntegral5SigmaFromFit_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+fitGausSigma_*5),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-fitGausSigma_*5)))/histoNoiseStrip->Integral();
	    
	    jBValue_   = (histoNoiseStrip->Integral()/6)*(noiseSkewness_*noiseSkewness_+(noiseKurtosis_*noiseKurtosis_)/4);	  
	    jBProbab_  = ROOT::Math::chisquared_cdf_c(jBValue_,2);

	    if(randomHisto == 0 or randomHisto == NULL)
	      randomHisto = (TH1F*) histoNoiseStrip->Clone("randomHisto");	    	    
	    randomHisto->Reset();
	    randomHisto->SetDirectory(0);     
	
      
	    if(integral != 0){	      
	      if(generateRandomDistribution){
		randomHisto->FillRandom("fitFunc",histoNoiseStrip->Integral());	    
		kSValue_  = histoNoiseStrip->KolmogorovTest(randomHisto,"MN");
		kSProbab_ = histoNoiseStrip->KolmogorovTest(randomHisto,"N");	    
		aDValue_  = histoNoiseStrip->AndersonDarlingTest(randomHisto,"T");
		aDProbab_ = histoNoiseStrip->AndersonDarlingTest(randomHisto);
	      }
	      else{
		
		randomHisto->Add(fitFunc);		
		kSValue_  = histoNoiseStrip->KolmogorovTest(randomHisto,"MN"); 
		kSProbab_ = histoNoiseStrip->KolmogorovTest(randomHisto,"N");
		// AD test
		ROOT::Fit::BinData data1;
		ROOT::Fit::BinData data2;
		ROOT::Fit::FillData(data1,histoNoiseStrip,0);
		data2.Initialize(randomHisto->GetNbinsX()+1,1);
		for(int ibin = 0; ibin < randomHisto->GetNbinsX(); ibin++){ 
		  if(histoNoiseStrip->GetBinContent(ibin+1) != 0 or randomHisto->GetBinContent(ibin+1) >= 1)
		    data2.Add(randomHisto->GetBinCenter(ibin+1),randomHisto->GetBinContent(ibin+1),randomHisto->GetBinError(ibin+1));
		}
	  
		double probab;
		double value;
		ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2,probab,value);
		aDValue_ = value;
		aDProbab_ = probab;
	      }
	    }
	}
	else
	  noFitResult++;
	
	if(not histoBranches){
	  noiseDistribution_.clear();
	  noiseDistributionError_.clear();
	  outputTree->Branch("noiseDistribution","vector<float>",&noiseDistribution_);
	  outputTree->Branch("noiseDistributionError","vector<float>",&noiseDistributionError_);
	  histoBranches = true;
	}
    
	// set histogram
	noiseDistribution_.clear();
	noiseDistributionError_.clear();
	for(int iBin = 0; iBin < histoNoiseStrip->GetNbinsX(); iBin++){
	  noiseDistribution_.push_back(histoNoiseStrip->GetBinContent(iBin+1));
	  noiseDistributionError_.push_back(histoNoiseStrip->GetBinError(iBin+1));	      
	}
    
	nBin_ = histoNoiseStrip->GetNbinsX();
	xMin_ = histoNoise->GetXaxis()->GetBinLowEdge(1);
	xMax_ = histoNoise->GetXaxis()->GetBinLowEdge(histoNoise->GetNbinsX()+1);

	// fill all branches for each strip
	ouputTreeFile->cd();
	outputTree->Fill();
      }
    }
    inputFile->Close();
    std::cout<<std::endl;
    cout<<"No fit results found for "<<100*double(noFitResult)/iChannel<<endl;
  }
  outputTree->BuildIndex("detid");
  outputTree->Write(outputTree->GetName(),TObject::kOverwrite);
  ouputTreeFile->Close();
  cablingFile->Close();

  /* Do your stuff here */
  cout<<"Time taken: "<<(double)(clock() - tStart)/CLOCKS_PER_SEC<<endl;  
}
コード例 #18
0
//________________________________________________________________________________
void MergeComplexHistogramFile( const Char_t *TargetName=0, const Char_t *inputFilesPattern=0) 
{
  if (TargetName && TargetName[0] && inputFilesPattern && inputFilesPattern[0] ) {
    printf(" An experimental version of macro.\n");
    TStopwatch time;
    Int_t fileCounter = 0;
    Int_t dirCounter = 0;
    Int_t treeCounter = 0;
    Int_t histogramCounter = 0;
     // Create the output file
     TFile *outFile = TFile::Open(TargetName,"RECREATE");
     TDirectory *outDir = outFile;
     TDirIter listOfFiles(inputFilesPattern);
     const char *fileName = 0;
     while ( (fileName =  listOfFiles.NextFile() ) ) {
        Int_t currentDirDepth = 0;
        printf(".");
        fileCounter++;
        StFileIter file(fileName);
        TObject *obj = 0;
        while ( (obj = *file) ) {
           Int_t depth = file.GetDepth();
           while (depth < currentDirDepth) {
                outDir = outDir->GetMotherDir();
                currentDirDepth--;
           }
           if ( obj->IsA()->InheritsFrom(TH1::Class()) ) {
              // descendant of TH1 -> merge it
              // printf("Merging histogram: %s\n",obj->GetName() ); 
//              std::cout << "Merging histogram " << obj->GetName() << std::endl;
              TH1 *h1 = (TH1*)obj;
              TH1 *dstHistogram = 0;
              // Check whether we found the new histogram
              if ( (dstHistogram = (TH1 *)outDir->FindObject(h1->GetName()))) {
                 // Accumulate  the  histogram
                  dstHistogram->Add(h1);
                  delete h1;  // Optional, to reduce the memory consumption
                  printf("h");
              } else {
                // First time - move the histogram
                h1->SetDirectory(outDir);
                printf(" The new Histogram found: %s \n", h1->GetName() );
                histogramCounter++;
              }
           } else  if ( obj->IsA()->InheritsFrom(TTree::Class()) ) {
              // descendant of TTree  -> merge it
              // printf("Merging Tree %p:%s\n",obj, obj->GetName() ); 
              TTree *tree = (TTree*)obj;
              TTree *dstTree = 0;
              // Check whether we found the new histogram
              if ( (dstTree = (TTree *)outDir->FindObject(tree->GetName()))) {
                   // printf("Merging %p:%s with the existing Tree %p:%s\n"
                   //       ,tree,tree->GetName(),dstTree, dstTree->GetName() ); 
                  // Merge  the  tree
                  TList *nextTree = new TList(); nextTree->Add(tree); 
                  dstTree->Merge(nextTree);
                  delete tree;  // Optional, to reduce the memory consumption
                  delete nextTree;
                  printf("t");
              } else {
                // First time - move the TTree
                TDirectory *saveDir = 0;
                if (outDir != gDirectory) {
                   saveDir = gDirectory;
                   outDir->cd();
                }
                TList *nextTree = new TList(); nextTree->Add(tree);               
                dstTree = TTree::MergeTrees(nextTree);
                if (saveDir) saveDir->cd();
                // printf(" The new TTree found: %p:%s \n",tree, tree->GetName() );
                // printf(" Create the destination Tree %p:%s\n\n",dstTree, dstTree->GetName() );
                delete tree;  // Optional, to reduce the memory consumption
                delete nextTree;
                treeCounter++;
              }
           } else if ( obj->IsA()->InheritsFrom(TDirectory::Class()) ) {
               printf("The input sub-TDirectory object: %s depth=%d\n",obj->GetName(), depth); 
               TDirectory *d =  (TDirectory *)outDir->FindObject(obj->GetName());
               if (!d) {
                  d = outDir->mkdir(obj->GetName());
                  dirCounter++;
                  printf("The new TDirectory object: %s depth=%d\n",d->GetPathStatic(), depth); 
               }
               if (d) {
                  outDir = d;                  
                  printf("The output sub-TDirectory object: %s depth=%d\n",outDir->GetPathStatic(), depth); 

               }
           } else {
              printf("I have no idea how to merge the %s objects of the %s class. Skipping .... \n",obj->GetName(), obj->ClassName() ); 
           }
           ++file;
        }
              
     }
     printf("\n Finishing  . . . \n");
     outFile->Write();  // this creates a second copy of the TTree ???
     outFile->Close();     
     delete outFile;
     if (fileCounter)      printf(" Total files merged: %d \n", fileCounter);
     if (dirCounter)       printf(" Total TDirectory objects merged: %d \n", dirCounter);
     if (histogramCounter) printf(" Total histograms merged: %d \n", histogramCounter);
     if (treeCounter)      printf(" Total TTree\'s merged: %d \n",treeCounter);
     if (dirCounter || treeCounter) printf(" You have used the experimental version of the program. Please check the output file\n");
        
     time.Print("Merge");
  } else {
     printf("\nUsage: root MergeHistogramFile.C(\"DestinationFileName\",\"InputFilesPattern\")\n");     
     printf("------        where InputFilesPattern  ::= <regexp_pattern_for_the_input_files>|@indirect_file_list\n");
     printf("                    indirect_file_list ::= a text file with the list of the files\n");
     printf("                    indirect_file_list can be create by the shell command:\n");
     printf("                         ls -1 *.root>indirect_file_list \n\n");
  }
}
コード例 #19
0
ファイル: KVSimDir.cpp プロジェクト: GiuseppePast/kaliveda
void KVSimDir::AnalyseFile(const Char_t* filename)
{
   // Analyse ROOT file given as argument.
   // If there is a TTree in the file, then we look at all of its branches until we find one
   // containing objects which derive from KVEvent:
   //
   //   -- if they inherit from KVSimEvent, we add the file to the list of simulated data:
   //            * a KVSimFile is created. The title of the TTree where data were found will
   //               be used as 'Information' on the nature of the simulation.
   //   -- if they inherit from KVReconstructedEvent, we add the file to the list of filtered data.
   //            * a KVSimFile is created. Informations on the filtered data are extracted from
   //              TNamed objects in the file with names 'Dataset', 'System', 'Run', 'Geometry'
   //              (type of geometry used, 'ROOT' or 'KV'), 'Origin' (i.e. the name of the simulation
   //              file which was filtered), 'Filter' (type of filter: Geo, GeoThresh or Full).
   //              These objects are automatically created when data is filtered using KVEventFiltering.
   //
   // Analysis of the file stops after the first TTree with a branch satisfying one of the
   // two criteria is found (it is assumed that in each file there is only one TTree containing
   // either simulated or filtered data).

   Info("AnalyseFile", "Analysing file %s...", filename);
   TString fullpath;
   AssignAndDelete(fullpath, gSystem->ConcatFileName(GetDirectory(), filename));
   TFile* file = TFile::Open(fullpath);
   if (!file || file->IsZombie()) return;
   // look for TTrees in file
   TIter next(file->GetListOfKeys());
   TKey* key;
   while ((key = (TKey*)next())) {
      TString cn = key->GetClassName();
      if (cn == "TTree") {
         // look for branch with KVEvent objects
         TTree* tree = (TTree*)file->Get(key->GetName());
         TSeqCollection* branches = tree->GetListOfBranches();
         TIter nextB(branches);
         TBranchElement* branch;
         while ((branch = (TBranchElement*)nextB())) {
            TString branch_classname = branch->GetClassName();
            TClass* branch_class = TClass::GetClass(branch_classname, kFALSE, kTRUE);
            if (branch_class && branch_class->InheritsFrom("KVEvent")) {
               if (branch_class->InheritsFrom("KVSimEvent")) {
                  fSimData.Add(new KVSimFile(this, filename, tree->GetTitle(), tree->GetEntries(), tree->GetName(), branch->GetName()));
                  delete file;
                  return;
               } else if (branch_class->InheritsFrom("KVReconstructedEvent")) {
                  // filtered data. there must be TNamed called 'Dataset', 'System', & 'Run' in the file.
                  TNamed* ds = (TNamed*)file->Get("Dataset");
                  TNamed* orig = (TNamed*)file->Get("Origin");
                  TNamed* sys = (TNamed*)file->Get("System");
                  TNamed* r = (TNamed*)file->Get("Run");
                  TNamed* g = (TNamed*)file->Get("Geometry");
                  TNamed* f = (TNamed*)file->Get("Filter");
                  TString dataset;
                  if (ds) dataset = ds->GetTitle();
                  TString system;
                  if (sys) system = sys->GetTitle();
                  TString run;
                  if (r) run = r->GetTitle();
                  TString origin;
                  if (orig) origin = orig->GetTitle();
                  TString geometry;
                  if (g) geometry = g->GetTitle();
                  TString filter;
                  if (f) filter = f->GetTitle();
                  Int_t run_number = run.Atoi();
                  fFiltData.Add(new KVSimFile(this, filename, tree->GetTitle(), tree->GetEntries(), tree->GetName(), branch->GetName(),
                                              dataset, system, run_number, geometry, origin, filter));
                  delete file;
                  delete ds;
                  delete sys;
                  delete r;
                  delete f;
                  return;
               }
            }
         }
      }
   }
}
コード例 #20
0
ファイル: main.C プロジェクト: chnzhangrui/WtAna
void calculateEff(int nArguments) {
	string configSysName = Form("share/file.txt");
	ifstream configSystematic(configSysName.c_str());
	vector<string> fileNames;
	vector<string> treeNames;
	string fileName, treeName;
	while (!configSystematic.eof()) {
		configSystematic >> fileName >> treeName;
		if ((fileName.compare(0, 1, "#") == 0))
			continue;

		if (!configSystematic.good())
			break;

		fileNames.push_back(fileName);
		treeNames.push_back(treeName);
	}
	ofstream fout;
	fout.open("share/table.txt");
	fout << left << setw(60) << "#Systematics" << "\t\t" << setw(25) << "purity(corr,rec)(B/A+B)" << "\t\t" << setw(25) << "accept(corr,fid)(B/B'+C)" << "\t\t" << setw(25) << "eff_{fid}=a/p"
			<< setw(25) << "N_{fid}" << setw(25) << "N_{gen}" << endl;
	for (int iSys = 0; iSys < fileNames.size(); ++iSys) {
		bool c_debug(false);

		if (nArguments > 2) {
			cerr << "\n\t[INFO]\t" << "* * * main applyFiducialCut starts * * *" << endl;
			applyFiducialCut(fileNames.at(iSys).c_str());
			cerr << "\n\t[INFO]\t" << "* * * main applyFiducialCut finishes * * *" << endl;
		} else {
			cerr << "\n\t[INFO]\t" << "* * * main SKIP applyFiducialCut * * *" << endl;
		}

		/* nominal Trees */
		TFile* nominalFile = new TFile("../data/2016-04-05/reprocess/reprocess_1j1b_v11_20160405.root");
		TTree *nominalTree = (TTree*) nominalFile->Get(treeNames.at(iSys).c_str());
		cerr << "\t[INFO]\t" << "Reco  Tree " << nominalTree->GetName() << " " << nominalTree->GetEntries() << endl;
		TFile* particleFile = new TFile(Form("root/fiducialRegion_%s.root", fileNames.at(iSys).c_str()));
		TTree* particleTree = (TTree*) particleFile->Get("particleLevel");
		cerr << "\t[INFO]\t" << "Truth Tree " << particleTree->GetName() << " " << particleTree->GetEntries() << endl;

		Int_t runRecNominal;
		Int_t eventRecNominal;
		Float_t EventWeight, EventWeight_noPU, weight_leptonSF, weight_bTagSF_77, mc_weight;

		nominalTree->SetBranchAddress("mcChannelNumber", &runRecNominal);
		nominalTree->SetBranchAddress("EventNumber", &eventRecNominal);
		nominalTree->SetBranchAddress("EventWeight_noPU", &EventWeight_noPU);
		nominalTree->SetBranchAddress("EventWeight", &EventWeight);
		nominalTree->SetBranchAddress("weight_leptonSF", &weight_leptonSF);
		nominalTree->SetBranchAddress("weight_bTagSF_77", &weight_bTagSF_77);
		nominalTree->SetBranchAddress("weight_mc", &mc_weight);

		UInt_t runParticle;
		ULong64_t eventParticle;
		Float_t weight_mc;
		particleTree->SetBranchAddress("mcChannelNumber", &runParticle);
		particleTree->SetBranchAddress("eventNumber", &eventParticle);
		particleTree->SetBranchAddress("weight_mc", &weight_mc);

		/************/
		/* counting */
		/************/

		/* build particleTree index */
		particleTree->BuildIndex("mcChannelNumber", "eventNumber");
		nominalTree->BuildIndex("mcChannelNumber", "EventNumber");

		double totalEventWeight(0.), totalOverlapEventWeight(0.), totalOverlapweight_mc(0.), totalweight_mc(0.), totalOverlapmc_weight(0.);
		double ExperimentalWeight(0.);
		ofstream bugstr;
		if (c_debug)
			bugstr.open("share/bug.log");
		bool useWeight(true);
		for (Long64_t ievt = 0; ievt < (c_debug ? 10 : nominalTree->GetEntries()); ievt++) {
			nominalTree->GetEntry(ievt);
			ExperimentalWeight = (EventWeight_noPU == 0) ? 0 : (EventWeight / EventWeight_noPU) * weight_leptonSF * weight_bTagSF_77 * mc_weight;
			totalEventWeight += useWeight ? ExperimentalWeight : 1; // A+B
			if (particleTree->GetEntryWithIndex(runRecNominal, eventRecNominal) > 0) {
				totalOverlapEventWeight += useWeight ? ExperimentalWeight : 1; // B
				totalOverlapmc_weight += useWeight ? mc_weight : 1;
				if (c_debug)
					bugstr << "recon matched " << runRecNominal << " " << eventRecNominal << " totalOverlapmc_weight=" << totalOverlapmc_weight << endl;
			} else {
				if (c_debug)
					bugstr << "recon notmatc " << runRecNominal << " " << eventRecNominal << " totalOverlapmc_weight=" << totalOverlapmc_weight << endl;
			}
		}
		int dupl(0);
		vector<int> duplevts;
		ifstream ifile(Form("share/%s.overlap.dupEvt", fileNames.at(iSys).c_str()));
		if (ifile) {
			int evt;
			while (!ifile.eof()) {
				ifile >> evt;
				if (!ifile.good())
					break;
				duplevts.push_back(evt);
			}
		}
		for (Long64_t ievt = 0; ievt < (c_debug ? 10 : particleTree->GetEntries()); ievt++) {
			particleTree->GetEntry(ievt);
			totalweight_mc += useWeight ? weight_mc : 1; // B'+C
			if (nominalTree->GetEntryWithIndex(runParticle, eventParticle) > 0) {
				for (int id = 0; id < duplevts.size(); ++id) {
					if (eventParticle == duplevts.at(id)) {
						dupl++;
						cerr << "\t[WARNING]\t" << "duplicated evt No. " << eventParticle << ". But still counted." << endl;
						duplevts.erase(duplevts.begin() + id);
					}
				}

				totalOverlapweight_mc += useWeight ? weight_mc : 1; // B'
				if (c_debug)
					bugstr << "truth matched " << runParticle << " " << eventParticle << " totalOverlapweight_mc=" << totalOverlapweight_mc << endl;
			} else {
				if (c_debug)
					bugstr << "truth notmatc " << runParticle << " " << eventParticle << " totalOverlapweight_mc=" << totalOverlapweight_mc << endl;
			}
		}

		/* Make sure overlap events are the same */
		assert(fabs(totalOverlapmc_weight - totalOverlapweight_mc) < dupl + 0.001);

		double purity = totalOverlapEventWeight / totalEventWeight;
		double accept = totalOverlapEventWeight / totalweight_mc;
		cerr << "\n\t[INFO]\t" << "* * * * * * * * * * * * * * * * * * * * * * * * ";
		cerr << "\n\t[INFO]\t" << "* * * prime(') stands for weight_mc * * * * * * ";
		cerr << "\n\t[INFO]\t" << "* * * reconstructed events (A + B)  " << totalEventWeight << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * fiducial      events (B'+ C)  " << totalweight_mc << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * overlapped    events (B)    " << totalOverlapEventWeight << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * overlapped    events (B')   " << totalOverlapweight_mc << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * purity (corr, rec)  (B / A+B ) " << purity << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * accept (corr, fid)  (B / B'+C) " << accept << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * eff_{fid}             " << accept / purity << " * * *";
		cerr << "\n\t[INFO]\t" << "* * * * * * * * * * * * * * * * * * * * * * * * \n";
		cerr << "\033[1;31m\n\t[INFO]\t" << iSys << "/" << treeNames.size() << ")\t" << treeNames.at(iSys) << "\t\t" << purity << "\t\t" << accept << "\t\t" << purity / accept << "\t\t"
				<< totalweight_mc << "\033[0m" << endl;
		fout << left << setw(60) << treeNames.at(iSys) << "\t\t" << setw(25) << purity << "\t\t" << setw(25) << accept << "\t\t" << setw(25) << accept / purity << setw(25) << totalweight_mc << endl;
	}
	return;
}