コード例 #1
0
ファイル: fakeDAQ.C プロジェクト: brettviren/WbLS
void fakeDAQ(const char* outFile = "/Users/chaozhang/Projects/LBNE/WbLS/software/WbLSDAQ/data/test/fakedata.root")
{
    // WblsDaq::Spinner spinner("/Users/chaozhang/Projects/LBNE/WbLS/software/WbLSDAQ/data/test/example2.root");
    // TTree* header = spinner.header_tree();
    // TTree* footer = spinner.footer_tree();
    // TTree* events = spinner.event_tree();
    
    TFile* fp = TFile::Open("/Users/chaozhang/Projects/LBNE/WbLS/software/WbLSDAQ/data/test/example2.root"); // intentional leak
    TTree* header = (TTree*)fp->Get("Header");
    TTree* footer = (TTree*)fp->Get("Footer");
    TTree* events = (TTree*)fp->Get("FADCData");
    
    const int N = 120; // fake 400 events
    int nentries = events->GetEntries();
    gRandom->SetSeed(0);
    int startN = int(gRandom->Uniform(nentries));
    TString sel = Form("Entry$>=%d && Entry$<%d", startN, startN + N);
    TFile f(outFile, "recreate");    
    TTree *th = header->CopyTree("Entry$<8");
    TTree *tf = footer->CopyTree("Entry$<8");
    TTree *te = events->CopyTree(sel.Data());
    // TTree *te = events->CopyTree("Entry$>1850 && Entry$<1970");
    // cout << sel << endl;
    th->Write();
    tf->Write();
    te->Write();
    f.Close();
    // cout << outFile << endl;
}
コード例 #2
0
ファイル: Skimmer.C プロジェクト: cbeiraod/Stop4Body
void Skimmer(TString cname)
{
  TFile* file=TFile::Open(cname + "/treeProducerStop4Body/tree.root", "read");
  TString cutString = "nLepGood >= 1"; // Place custom cut string for the skim here

  if(!file)
  {
    std::cout << "Corrupted file! : " << cname << std::endl;
    return;
  }

  TTree* tree = static_cast<TTree*>(file->Get("tree"));
  if(!tree)
  {
    std::cout << "Corrupted file! : " << cname << std::endl;
    return;
  }

  TFile* ofile = new TFile(cname + "/treeProducerStop4Body/tree_skimmed.root", "recreate");
  TTree* otree = tree->CopyTree(cutString);

  ofile->Write();
  ofile->Close();

  gROOT->ProcessLine(".q");
}
コード例 #3
0
void skimFastNtuple(TString inputFile = "input.root",TString outputFile = "output.root", int skim = 0){

TFile *_file0 = TFile::Open(inputFile);
_file0->cd();
TTree* tree = (TTree*)_file0->Get("tree");
TTree* oldtree = tree;
cout << oldtree->GetEntries() << endl;

TFile *_file1 = TFile::Open(outputFile,"recreate");
_file1->cd();

char cutString[200];
if     (skim == 0) sprintf(cutString,"met>20||lid3!=0");
else if(skim == 1) sprintf(cutString,"(type==1||type==2)&&lid3==0&&njets<=1");
else if(skim == 2) sprintf(cutString,"min(pmet,pTrackMet)>20&&(TMath::Abs(dilep->mass()-91.1876)>15||type==1||type==2)&&lid3==0&&dilep->pt()>45&&njets<=3");
else if(skim == 3) sprintf(cutString,"((cuts & 4) == 4) && ((cuts & 512) == 512)");
else if(skim == 4) sprintf(cutString,"((cuts & 4) != 4) || ((cuts & 512) != 512)");
else if(skim == 5) sprintf(cutString,"lid3!=0");
else if(skim == 6) sprintf(cutString,"min(pmet,pTrackMet)>20&&((TMath::Abs(dilep->mass()-91.1876)>15&&dilep->pt()>45)||type==1||type==2)&&lid3==0&&dilep->pt()>30&&njets<=3");
else if(skim == 7) sprintf(cutString,"((cuts & 4) != 4) && ((cuts & 512) != 512)");
else if(skim == 8) sprintf(cutString,"lq1*lq2>0&&lid3==0");
else if(skim == 9) sprintf(cutString,"min(pmet,pTrackMet)>20&&((TMath::Abs(dilep->mass()-91.1876)>15&&((dymva>0.88&&njets==0)||(dymva>0.84&&njets==1)||(met>45&&njets>=2)))||type==1||type==2)&&lid3==0&&dilep->M()>12&&dilep->pt()>0");
else if(skim ==10) sprintf(cutString,"dilep->pt()>70&&TMath::Abs(dilep->mass()-91.1876)<30&&njets<=1");
else if(skim ==11) sprintf(cutString,"dilep->pt()>70&&njets<=1");
else {cout << "No good option" << endl; return;}
cout << "cut: " << cutString << endl;

TTree *newtree1;
newtree1 = oldtree->CopyTree(cutString);
cout << newtree1->GetEntries() << endl;

_file1->Write();
_file1->Close();
}
コード例 #4
0
ファイル: Copy.C プロジェクト: laerad84/Analysis
void Copy(){

  TFile* tfin = new TFile("/Volume0/ExpData/2012_Feb_Beam/RootFile_cosmic/CosmicResult_20120209.root");

  TFile* tfOut = new TFile("test.root","Recreate");
  TTree* tr   = (TTree*)tfin->Get("GainFitPar");
  TTree* trClone = tr->CopyTree("");
  trClone->Write();
  tfOut->Close();

}
コード例 #5
0
ファイル: hist_maker.cpp プロジェクト: Kuenni/tools3a
TTree* read_tree(char* filename, char* tree_name, char* tree_cuts)
{
    DEBUG("now reading tree " << tree_name << " with cuts: " << tree_cuts << " from file: " << filename);
    TFile* file = new TFile(filename,"READ");
    TTree* tree = (TTree*)file -> Get(tree_name);
    TFile* fileTmp = new TFile("tmpFile_.root","RECREATE");
    TTree* smallerTree= tree->CopyTree(tree_cuts);
    file -> Close();
    delete file;
    return smallerTree;
}
コード例 #6
0
ファイル: treefriend.C プロジェクト: adevress/root-1
void CreateFriendTree() {
   // Open the file created by CreateParentTree
   // Copy a subset of the TTree into a new TTree
   //   (see also tutorials copytree.C, copytree2.C and copytree3.C)
   // Create an index on the new TTree ("Run","Event")
   // Write the new TTree (including its index)
   
   TFile *f = new TFile("treeparent.root");
   TTree *T = (TTree*)f->Get("T");
   TFile *ff = new TFile("treefriend.root","recreate");
   TTree *TF = T->CopyTree("z<10");
   TF->SetName("TF");
   TF->BuildIndex("Run","Event");
   TF->Write();
   TF->Print();
   delete ff;
}
コード例 #7
0
ファイル: skimSimple2020_20m50.C プロジェクト: magania/CMS2
void skimSimple2020_20m50(char* fname){
  gSystem->Load("libFWCoreFWLite");
  AutoLibraryLoader::enable();
  
  TFile* tf = new TFile(fname);
  TTree* tr = (TTree*)tf->Get("Events");

  TFile* tfCp = new TFile(Form("%s_skimSimple2020_20m50",fname), "recreate");

  std::string selection = "Sum$(hyp_ll_p4.pt()>20&&hyp_lt_p4.pt()>20)>0&&Sum$(genps_id==23&&genps_p4.M()>20.&&genps_p4.M()<50.)>0";
  int nEvents = tr->GetEntries(); 
  int skimEvents = tr->GetEntries(selection.c_str()); 
  std::cout<<selection.c_str()<<" will select "<<skimEvents<<" out of "<<nEvents<<std::endl;   

  trCp = tr->CopyTree(selection.c_str(), "");

  trCp->Write();

  tfCp->Write();

  std::cout<<"Closing file "<<tfCp->GetName()<<" with "<<trCp->GetEntries()<<" entries in "<<trCp->GetName()<<std::endl;
  tfCp->Close();
}
コード例 #8
0
void ApplyMoreCutsBeforeFit(){
  //------------------------------------------------
    TFile * f = new TFile ("/exp/LHCb/amhis/LeptonU-/tuples/data/forfit/real-data-electrons-photon-30032016-reduced.root");
  //TFile * f = new TFile ("/exp/LHCb/amhis/LeptonU-/tuples/data/forfit/real-data-electrons-jpsi-30032016-reduced.root");
  TTree * signaltree = (TTree*)f->Get("DecayTree");
  TCut PID = "Kaon_MC12TuneV3_ProbNNk > 0.1 && Proton_MC12TuneV3_ProbNNp>0.1&&L2_PIDe>1.2&&L1_PIDe>1.2";
  
  
  // Cuts taken from  pk mumu analysis
  //  TCut HarderPID= "Proton_MC12TuneV3_ProbNNp >0.2 &&Proton_MC12TuneV3_ProbNNk<0.8 && Proton_MC12TuneV3_ProbNNpi<0.7 && Kaon_MC12TuneV3_ProbNNk>0.2 && Kaon_MC12TuneV3_ProbNNp < 0.8 &&L2_PIDe>1.2&&L1_PIDe>1.2" ;
  

  TCut HarderPID= "Proton_ProbNNp >0.2 &&Proton_ProbNNk<0.8 && Proton_ProbNNpi<0.7 && Kaon_ProbNNk>0.2 && Kaon_ProbNNp < 0.8 &&L2_PIDe>1.2&&L1_PIDe>1.2" ;
  
  TCut Kinematics = "Proton_PT >500 && Lambdab_DTF_PV_chi2<10  && Lambdab_PT>2000 ";

  TCut Lstar = "Lambdastar_M<1550 && Lambdastar_M>1450";
 
  //  TCut HopCut = "Lambdab_MM> (4000 + 344 +  100*log(Lambdab_FDCHI2_OWNPV)) ";

  TCut HopCut = "Lambdab_MM> (4000 + 344 +  75*log(Lambdab_FDCHI2_OWNPV)) ";

  TCut RemovePhi = "Lambdab_M01_Subst0_p2K>1050";
  //  TCut RemoveKst = "Lambdab_M01_Subst0_p2pi< 850 && Lambdab_M01_Subst0_p2pi>920";
  TCut RemoveKst = "Lambdab_M01_Subst0_p2pi< 850 ";
  
  //  TCut ApplyTheseCuts = HarderPID && Kinematics&& HopCut && RemovePhi && RemoveKst;
  TCut ApplyTheseCuts = HarderPID && Kinematics ;
  

  TFile * localFileForFit = new TFile("localFileForFit.root", "RECREATE"); 
  cout <<" These are the cuts that we applied : " <<  ApplyTheseCuts << endl;
  TTree * smallerTreeForFit = signaltree->CopyTree(ApplyTheseCuts);
  smallerTreeForFit->Write();
  f->Close();
  return;
}
コード例 #9
0
void plot(bool sgn_ = true, bool doROC_ = false, int steps_ = 50){


  TCanvas *c1 = new TCanvas("c1","",5,30,650,600);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);

  TLegend* leg = new TLegend(0.55,0.47,0.85,0.85,NULL,"brNDC");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetFillColor(10);
  leg->SetTextSize(0.04);

  TFile *fSgn = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDYJets-Mu-50-madgraph-PUS1_Open_MuTauStream.root","READ");
  TFile *fBkg = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleQCDmu_Open_MuTauStream.root","READ");

  if((fSgn->IsZombie()) || (fBkg->IsZombie()) ){
    cout << "No file" << endl;
    exit(1);
  }

  float vx_combRelIsoLeg1Raw[steps_];
  float vy_combRelIsoLeg1Raw[steps_];
  float vx_combRelIsoLeg1[steps_];
  float vy_combRelIsoLeg1[steps_];
  float vx_combRelIsoLeg1Beta[steps_];
  float vy_combRelIsoLeg1Beta[steps_];
  float vx_combRelIsoLeg1DBeta[steps_];
  float vy_combRelIsoLeg1DBeta[steps_];
  float vx_combRelIsoLeg1Rho[steps_];
  float vy_combRelIsoLeg1Rho[steps_];

  TH2F* hMaster = new TH2F("hMaster"," ; signal efficiency ; background efficiency", 100,0,1,100,0,1);

  TTree* treeSgn = (TTree*)fSgn->Get("outTreePtOrd");
  TTree* treeBkg = (TTree*)fBkg->Get("outTreePtOrd");

  TFile* dummy = new TFile("dummy.root","RECREATE");
  //TTree* treeSgnCut = (TTree*)treeSgn->CopyTree("isTauLegMatched && pt1>25 && pt2>20 && eta1*eta2<0");  
  //TTree* treeBkgCut = (TTree*)treeBkg->CopyTree("tightestHPSWP>-1 && pt1>25 && pt2>20 && eta1*eta2<0");  
  TTree* treeSgnCut = (TTree*)treeSgn->CopyTree("isTauLegMatched");  
  TTree* treeBkgCut = (TTree*)treeBkg->CopyTree("tightestHPSWP>0");  


  cout << treeSgnCut->GetEntries() << endl;
  cout << treeBkgCut->GetEntries() << endl;

  TH1F* SgnEffVsNvtx = new TH1F("SgnEffVsNvtx","; # reco-vtx; efficiency for CombRelIso<0.1",16,1,17);
  TH1F* BkgEffVsNvtx = new TH1F("BkgEffVsNvtx","; # reco-vtx; efficiency for CombRelIso<0.1",16,1,17);

  std::vector<string> isoDep;
  isoDep.push_back("combRelIsoLeg1");
  isoDep.push_back("combRelIsoLeg1Beta");
  isoDep.push_back("combRelIsoLeg1DBeta");
  isoDep.push_back("combRelIsoLeg1Rho");
  isoDep.push_back("combRelIsoLeg1Raw");

  std::map<std::string, TH1F*> aMapSgn;
  aMapSgn["combRelIsoLeg1Raw"] = (TH1F*)SgnEffVsNvtx->Clone("combRelIsoLeg1Raw");
  aMapSgn["combRelIsoLeg1"] = (TH1F*)SgnEffVsNvtx->Clone("combRelIsoLeg1");
  aMapSgn["combRelIsoLeg1Beta"] = (TH1F*)SgnEffVsNvtx->Clone("combRelIsoLeg1Beta");
  aMapSgn["combRelIsoLeg1DBeta"] = (TH1F*)SgnEffVsNvtx->Clone("combRelIsoLeg1DBeta");
  aMapSgn["combRelIsoLeg1Rho"] = (TH1F*)SgnEffVsNvtx->Clone("combRelIsoLeg1Rho");
  std::map<std::string, TH1F*> aMapBkg;
  aMapBkg["combRelIsoLeg1Raw"] = (TH1F*)BkgEffVsNvtx->Clone("combRelIsoLeg1Raw");
  aMapBkg["combRelIsoLeg1"] = (TH1F*)BkgEffVsNvtx->Clone("combRelIsoLeg1");
  aMapBkg["combRelIsoLeg1Beta"] = (TH1F*)BkgEffVsNvtx->Clone("combRelIsoLeg1Beta");
  aMapBkg["combRelIsoLeg1DBeta"] = (TH1F*)BkgEffVsNvtx->Clone("combRelIsoLeg1DBeta");
  aMapBkg["combRelIsoLeg1Rho"] = (TH1F*)BkgEffVsNvtx->Clone("combRelIsoLeg1Rho");

  TH1F* h1 = new TH1F("h1","",1,-10,10);

  if(doROC_){
    for(unsigned int m = 0; m < isoDep.size() ; m++){
    
      treeSgnCut->Draw( "eta1>>h1" ,"puWeight");
      float sgnDen = (float)h1->Integral();
      cout << sgnDen << endl;
      h1->Reset();
      treeBkgCut->Draw( "eta1>>h1" ,"puWeight");
      float bkgDen = (float)h1->Integral();
      cout << bkgDen << endl;
      h1->Reset();
      
      for(int i = 0; i < steps_; i++){
	
      cout << isoDep[m] << " --> " << i << endl;
      
      TCut cut(Form("puWeight*(%s<=%f)", isoDep[m].c_str(), i*(1./steps_)) );
      treeSgnCut->Draw( "eta1>>h1" ,cut );
      float sgnNum = (float)h1->Integral();
      cout << sgnNum << endl;
      h1->Reset();
      treeBkgCut->Draw( "eta1>>h1" ,cut );
      float bkgNum = (float)h1->Integral();
      cout << bkgNum << endl;
      h1->Reset();
 
      if(m==0){
	vx_combRelIsoLeg1[i] = sgnNum/sgnDen;
	vy_combRelIsoLeg1[i] = bkgNum/bkgDen;
      }
      if(m==1){
	vx_combRelIsoLeg1Beta[i] = sgnNum/sgnDen;
	vy_combRelIsoLeg1Beta[i] = bkgNum/bkgDen;
      }
      if(m==2){
	vx_combRelIsoLeg1DBeta[i] = sgnNum/sgnDen;
	vy_combRelIsoLeg1DBeta[i] = bkgNum/bkgDen;
      }
      if(m==3){
	vx_combRelIsoLeg1Rho[i] = sgnNum/sgnDen;
	vy_combRelIsoLeg1Rho[i] = bkgNum/bkgDen;
      }
      if(m==4){
	vx_combRelIsoLeg1Raw[i] = sgnNum/sgnDen;
	vy_combRelIsoLeg1Raw[i] = bkgNum/bkgDen;
      }
      }
    }
  }

  if(!doROC_){

    for(unsigned int m = 0; m < isoDep.size() ; m++){
      for(int i = 0; i<16; i++){

	float number = i+1;
	TCut cutNum(Form("%s<0.1 && numPV<(%f+0.5) && numPV>(%f-0.5)", isoDep[m].c_str(), number, number));
	TCut cutDen(Form("numPV<(%f+0.5) && numPV>(%f-0.5)", number, number));
	//TCut totCut( "" );
	
	//float tot = (float)treeSgn->GetEntries( totCut );
	float num = (float)treeSgnCut->GetEntries( cutNum );
	float den = (float)treeSgnCut->GetEntries( cutDen );
	
	aMapSgn[isoDep[m]]->SetBinContent(i+1, num/den );
	aMapSgn[isoDep[m]]->SetBinError(i+1, TMath::Sqrt(num/den*(1-num/den) /  den) );
	
	num = treeBkgCut->GetEntries( cutNum );
	den = treeBkgCut->GetEntries( cutDen );
	
	aMapBkg[isoDep[m]]->SetBinContent(i+1, num/den );
	aMapSgn[isoDep[m]]->SetBinError(i+1, TMath::Sqrt(num/den*(1-num/den) /  den) );
	
      }
      
    } 
  }

  if(sgn_ && !doROC_){

    leg->SetHeader("Z#rightarrow#tau#tau");

    for(unsigned int k = 0; k < isoDep.size() ; k++){
      if(k==0){
	aMapSgn[isoDep[k]]->SetMarkerColor(kBlack);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapSgn[isoDep[k]]->SetMarkerStyle(kFullCircle);
	aMapSgn[isoDep[k]]->GetYaxis()->SetRangeUser(0.50,1.1);
	leg->AddEntry(aMapSgn[isoDep[k]],"pfNoPileUp","P");
	aMapSgn[isoDep[k]]->Draw("P");
      }
      if(k==1){
	aMapSgn[isoDep[k]]->SetMarkerColor(kRed);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapSgn[isoDep[k]]->SetMarkerStyle(kFullSquare);
	leg->AddEntry(aMapSgn[isoDep[k]],"Beta","P");
	aMapSgn[isoDep[k]]->Draw("PSAME");
      }
      if(k==2){
	aMapSgn[isoDep[k]]->SetMarkerColor(kBlue);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapSgn[isoDep[k]]->SetMarkerStyle(kFullTriangleUp);
	leg->AddEntry(aMapSgn[isoDep[k]],"Delta Beta","P");
	aMapSgn[isoDep[k]]->Draw("PSAME");
      }
      if(k==3){
	aMapSgn[isoDep[k]]->SetMarkerColor(kGreen);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapSgn[isoDep[k]]->SetMarkerStyle(kFullTriangleDown);
	leg->AddEntry(aMapSgn[isoDep[k]],"Rho","P");
	aMapSgn[isoDep[k]]->Draw("PSAME");
      }
      if(k==4){
	aMapSgn[isoDep[k]]->SetMarkerColor(kMagenta);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapSgn[isoDep[k]]->SetMarkerStyle(kFullStar);
	leg->AddEntry(aMapSgn[isoDep[k]],"No correction","P");
	aMapSgn[isoDep[k]]->Draw("PSAME");
      }
    }
  }
  else if(!sgn_ && !doROC_){
    
    leg->SetHeader("QCD #mu-enriched");

    for(unsigned int k = 0; k < isoDep.size() ; k++){
      if(k==0){
	aMapBkg[isoDep[k]]->SetMarkerColor(kBlack);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapBkg[isoDep[k]]->SetMarkerStyle(kFullCircle);
	aMapSgn[isoDep[k]]->GetYaxis()->SetRangeUser(0.0,0.10);
	leg->AddEntry(aMapBkg[isoDep[k]],"pfNoPileUp","P");
	aMapBkg[isoDep[k]]->Draw("P");
      }
      if(k==1){
	aMapBkg[isoDep[k]]->SetMarkerColor(kRed);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapBkg[isoDep[k]]->SetMarkerStyle(kFullSquare);
	leg->AddEntry(aMapBkg[isoDep[k]],"Beta","P");
	aMapBkg[isoDep[k]]->Draw("PSAME");
      }
      if(k==2){
	aMapBkg[isoDep[k]]->SetMarkerColor(kBlue);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapBkg[isoDep[k]]->SetMarkerStyle(kFullTriangleUp);
	leg->AddEntry(aMapBkg[isoDep[k]],"Delta Beta","P");
	aMapBkg[isoDep[k]]->Draw("PSAME");
      }
      if(k==3){
	aMapBkg[isoDep[k]]->SetMarkerColor(kGreen);
	aMapSgn[isoDep[k]]->SetMarkerSize(1.4);
	aMapBkg[isoDep[k]]->SetMarkerStyle(kFullTriangleDown);
	leg->AddEntry(aMapBkg[isoDep[k]],"Rho","P");
	aMapBkg[isoDep[k]]->Draw("PSAME");
      }
      if(k==4){
	aMapBkg[isoDep[k]]->SetMarkerColor(kMagenta);
	aMapBkg[isoDep[k]]->SetMarkerSize(1.4);
	aMapBkg[isoDep[k]]->SetMarkerStyle(kFullStar);
	leg->AddEntry(aMapBkg[isoDep[k]],"No correction","P");
	aMapBkg[isoDep[k]]->Draw("PSAME");
      }
    }
  } else if(doROC_){

    leg->SetHeader("ROC");

    hMaster->Draw();

    TGraph* graph_combRelIsoLeg1Raw = new TGraph(steps_,vx_combRelIsoLeg1Raw,vy_combRelIsoLeg1Raw);
    TGraph* graph_combRelIsoLeg1 = new TGraph(steps_,vx_combRelIsoLeg1,vy_combRelIsoLeg1);
    TGraph* graph_combRelIsoLeg1Beta = new TGraph(steps_,vx_combRelIsoLeg1Beta,vy_combRelIsoLeg1Beta);
    TGraph* graph_combRelIsoLeg1DBeta = new TGraph(steps_,vx_combRelIsoLeg1DBeta,vy_combRelIsoLeg1DBeta);
    TGraph* graph_combRelIsoLeg1Rho = new TGraph(steps_,vx_combRelIsoLeg1Rho,vy_combRelIsoLeg1Rho);
    
    std::map<std::string, TGraph*> roc;
    roc["combRelIsoLeg1Raw"] = graph_combRelIsoLeg1Raw;
    roc["combRelIsoLeg1"] = graph_combRelIsoLeg1;
    roc["combRelIsoLeg1Beta"] = graph_combRelIsoLeg1Beta;
    roc["combRelIsoLeg1DBeta"] = graph_combRelIsoLeg1DBeta;
    roc["combRelIsoLeg1Rho"] = graph_combRelIsoLeg1Rho;


    for(unsigned int k = 0; k < isoDep.size() ; k++){
      if(k==0){
	roc[isoDep[k]]->SetMarkerColor(kBlack);
	roc[isoDep[k]]->SetMarkerSize(1.4);
	roc[isoDep[k]]->SetMarkerStyle(kFullCircle);
	roc[isoDep[k]]->GetYaxis()->SetRangeUser(0.50,1.1);
	leg->AddEntry(roc[isoDep[k]],"pfNoPileUp","P");
	roc[isoDep[k]]->Draw("P");
      }
      if(k==1){
	roc[isoDep[k]]->SetMarkerColor(kRed);
	roc[isoDep[k]]->SetMarkerSize(1.4);
	roc[isoDep[k]]->SetMarkerStyle(kFullSquare);
	leg->AddEntry(roc[isoDep[k]],"Beta","P");
	roc[isoDep[k]]->Draw("PSAME");
      }
      if(k==2){
	roc[isoDep[k]]->SetMarkerColor(kBlue);
	roc[isoDep[k]]->SetMarkerSize(1.4);
	roc[isoDep[k]]->SetMarkerStyle(kFullTriangleUp);
	leg->AddEntry(roc[isoDep[k]],"Delta Beta","P");
	roc[isoDep[k]]->Draw("PSAME");
      }
      if(k==3){
	roc[isoDep[k]]->SetMarkerColor(kGreen);
	roc[isoDep[k]]->SetMarkerSize(1.4);
	roc[isoDep[k]]->SetMarkerStyle(kFullTriangleDown);
	leg->AddEntry(roc[isoDep[k]],"Rho","P");
	roc[isoDep[k]]->Draw("PSAME");
      }
      if(k==4){
	roc[isoDep[k]]->SetMarkerColor(kMagenta);
	roc[isoDep[k]]->SetMarkerSize(1.4);
	roc[isoDep[k]]->SetMarkerStyle(kFullStar);
	leg->AddEntry(roc[isoDep[k]],"No correction","P");
	roc[isoDep[k]]->Draw("PSAME");
      }
    }
  }

  leg->Draw();



}
コード例 #10
0
/*****************************************************************
* root macro to skim MT2trees                                    *
* -> sample and path to shlib given as arguments                 *
*                                                                *
* Pascal Nef                             September 18th, 2011    *  
*****************************************************************/
void MT2treeSkimming(string sample, string shlib, string prefix) {
  	gSystem->Load("libPhysics");
  	gSystem->Load(shlib.c_str());

	string LABEL  = "";
	string file   = sample;
	string outfile = prefix+"/"+sample;

	// log file 
	TString log =sample+".skim.log";
	TString cuts="cuts.skim.log";
	string line="";
	ofstream f_log;
	ofstream f_cuts;
	f_log .open(log.Data(),ios::app);
	f_cuts.open(cuts.Data());
	if(!f_log.is_open()||!f_cuts.is_open()) {cout << "ERROR: cannot open file. " << endl; exit(-1);}

	// cuts --------------------------------------------
  	std::ostringstream cutStream;
	cutStream       << " " 	  
//	  << "misc.MT2 >=50"                                     << "&&" 
//	  << "misc.MET>=30"                                      << "&&"
//	  << "misc.HT > 750 "                                    << "&&"
//	  << "misc.Jet0Pass ==1"                                 << "&&"
//	  << "misc.Jet1Pass ==1"                                 << "&&"
//	  << "misc.SecondJPt  >100"                              << "&&"
//	  << "misc.PassJetID ==1"                                << "&&"
//	  << "misc.Vectorsumpt < 70"                             << "&&"
//	  << "((misc.MinMetJetDPhi >0.3&&NBJets==0)||NBJets>=1)" << "&&"
// Lepton Veto
//	  << "(NEles==0 || ele[0].lv.Pt()<10)"                   << "&&"
//	  << "(NMuons==0 || muo[0].lv.Pt()<10)"                  << "&&"
// Lepton Skim
//	  << "(ele[0].lv.Pt()>10 || muo[0].lv.Pt()>10)"          << "&&"
// LowMT2 ----------------------------
//	  << "misc.LeadingJPt >150"                              << "&&"
//	  << "NBJets >0"                                         << "&&"
//	  << "NJetsIDLoose >=4"                                  << "&&"
// -----------------------------------
//	  << "NJetsIDLoose40 >=3"                                << "&&"
// Photons
	  << "(GenDiLeptPt(0,10,0,1000,false)>=100||GenPhoton[0].Pt()>=100)"  << "&&"
//	  << "(RecoOSDiLeptPt(10,10,0,10000)>=100 ||photon[0].lv.Pt()>=100)"  << "&&"
//	  << "NPhotons >0"  
// Noise
//	  << "misc.HBHENoiseFlag == 0"                           << "&&"
//	  << "misc.CSCTightHaloID==0"                            << "&&"
	  << "misc.CrazyHCAL==0";

	
	TString basecut = cutStream.str();
	string  SEL= "("+basecut+")";
	cout << "Skimming with sel: " << SEL << endl;
	TString cuts_log = basecut.ReplaceAll("&&", "\n");
	f_cuts << "Cuts applied: " <<  cuts_log << endl;
	//  --------------------------------------------


	// files ---------------------------------------
	f_log << "Skimming file: " << file;
	TFile *_file0 = TFile::Open( (file).c_str()); 
	TTree * t = (TTree*) _file0->Get("MassTree");
	TH1F*   h_PUWeights = (TH1F*) _file0->Get("h_PUWeights");
	TH1F*   h_Events    = (TH1F*) _file0->Get("h_Events");
	t->SetMaxTreeSize(19000000000);
	TFile*out = TFile::Open( (outfile).c_str(),"RECREATE");
	TTree *tc = t->CopyTree(SEL.c_str());   
	int nentries = tc->GetEntries();
	f_log << " -> skimmed tree has " << nentries << " entries." <<endl;
	f_log.close();
	f_cuts.close();
	out->Write();
	if(h_PUWeights!=0){
		cout << "writing TH1F h_PUWeights" << endl;
		h_PUWeights->Write();
	}
	if(h_Events!=0){
		cout << "writing TH1F h_Events" << endl;
		h_Events->Write();
	}
	out->Close();
	_file0->Close();
	cout << "Result file: " << outfile << endl;
	// -------------------------------------------------

}
コード例 #11
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();
}
コード例 #12
0
ファイル: x3d.C プロジェクト: Andrej-CMS/cmssw
int x3d( TString cut, int showFlag )
{

  // Retrieve trees and apply cut
  TFile* alignedFile = new TFile("aligned.root");
  TTree* tmpTree     = (TTree*)alignedFile->Get("theTree");
  TTree* alignedTree = (TTree*)tmpTree->CopyTree(cut);

  TFile* misalignedFile = new TFile("misaligned.root");
  tmpTree        = (TTree*)misalignedFile->Get("theTree");
  TTree* misalignedTree = (TTree*)tmpTree->CopyTree(cut);

  // Set tree branches
  float x,y,z,phi,theta,length,thick,width;
  float mx,my,mz,mphi,mtheta,mlength,mthick,mwidth;
  TRotMatrix* rot;
  TRotMatrix* mrot;
  double rad2deg = 180./3.1415926;

  alignedTree->SetBranchAddress( "x",      &x      );
  alignedTree->SetBranchAddress( "y",      &y      );
  alignedTree->SetBranchAddress( "z",      &z      );
  alignedTree->SetBranchAddress( "phi",    &phi    );
  alignedTree->SetBranchAddress( "theta",  &theta  );
  alignedTree->SetBranchAddress( "length", &length );
  alignedTree->SetBranchAddress( "width",  &width  );
  alignedTree->SetBranchAddress( "thick",  &thick  );
  alignedTree->SetBranchAddress( "rot",    &rot    );

  misalignedTree->SetBranchAddress( "x",      &mx      );
  misalignedTree->SetBranchAddress( "y",      &my      );
  misalignedTree->SetBranchAddress( "z",      &mz      );
  misalignedTree->SetBranchAddress( "phi",    &mphi    );
  misalignedTree->SetBranchAddress( "theta",  &mtheta  );
  misalignedTree->SetBranchAddress( "length", &mlength );
  misalignedTree->SetBranchAddress( "width",  &mwidth  );
  misalignedTree->SetBranchAddress( "thick",  &mthick  );
  misalignedTree->SetBranchAddress( "rot",    &mrot    );

  // Create canvas
  TCanvas* c1 = new TCanvas("c1","Detector units", 200, 10, 700, 500);
  c1->cd();

  TBRIK* IP = new TBRIK("IP","IP","void",0.,0.,0.);
  TNode* rootNode = new TNode("Root","Root","IP",0.,0.,0.);
  rootNode->cd();

  int entry = 0;
  while ( alignedTree->GetEntry(entry) && misalignedTree->GetEntry(entry) )
	{
	  entry++;
	  std::ostringstream name;

	  // Aligned detector
	  name << "aBrik" << entry;
	  TBRIK* aBrik = new TBRIK(name.str().c_str(),"Aligned detector unit","void",
							   0.01,0.01,length);
	  aBrik->SetLineColor(4);

	  // Detector node (position and orientation)
	  name.str("aNode"); name << entry;
	  TNode* aNode = new TNode(name.str().c_str(),name.str().c_str(),aBrik,x,y,z);
	  // Misaligned detector
 	  name.str("mBrik");
 	  name << entry;
 	  TBRIK* mBrik = new TBRIK(name.str().c_str(),"Misaligned detector unit","void",
							   0.01,0.01,mlength);
 	  mBrik->SetLineColor(2);

	  // Detector node (position and orientation)
 	  name.str("mNode"); name << entry;
 	  TNode* mNode = new TNode(name.str().c_str(),name.str().c_str(),mBrik,mx,my,mz);

	  //if (entry>5) break;
	}

  rootNode->cd();
  rootNode->Draw();
  
  c1->GetViewer3D();

  return 0;

}
コード例 #13
0
ファイル: qaTrending.C プロジェクト: ktf/AliPhysics
TTree * InitTrees(const char * detector,  const char *referenceDet){
  //
  // Init tree for given period
  //  all  trees stored in qaMap
  //  FriendTree added to the master treeQADet
  // Currentrly in the code we assume ID="run";
  // Bug in root tree ?  - in case more than one friend tree set - indeces looks corrupted 
  //    0.) QA tree per detector Raw+MC (if exist)
  //    1.) QA trees per refernce detectors specified by string refDet e.g "TPC;TRD;TOF"
  //    2.) Logbook tree per run
  //    3.) Logbook tree per run/detector
  //    3.) RCT table
  //    4.) CPass table 
  // 
  //  tree is created with addition of friend trees which can be used in queries
  //  queries as analog to the SQL statement

  /* 
    period="LHC15o"; pass="******"
  */
  ::Info("qaTrending::InitTrees::Begin","Detector %s, RefDet=%s",detector, referenceDet);
  AliExternalInfo info;
  Int_t treeCounter=0;
  // Load trees
  TObjArray * detArray=TString(referenceDet).Tokenize(";");
  Int_t nrefDets=detArray->GetEntries();
  TVectorF runCounter(5+nrefDets*2);  // <QADet>, <Logbook>, <Logbook.Det>, <MonAlisa>, <CPass>, <QA.RefDet>xnrefDets, <Logbook.RefDet>xnrefDets
  //
  ::Info("qaTrending::InitTrees::End","Laoding trees");
  treeQADet = info.GetTreeDataQA(detector,period, pass);
  if (!treeQADet){
    ::Error("qaTrending.InitTrees", "Input QA tree %s not available", detector); 
    return 0;
  }
  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
  qaMap[TString::Format("QA.%s",detector).Data()]=treeQADet;
  //
  qaMap["Logbook"]=info.GetTree("Logbook",period,"");
  qaMap["Logbook"]->AddFriend(treeQADet,"QADet");
  treeQADet->AddFriend(qaMap["Logbook"],"Logbook");
  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
  //
  qaMap["MonALISA.RCT"]=info.GetTree("MonALISA.RCT",period,pass);
  qaMap["MonALISA.RCT"]->AddFriend(treeQADet,"QADet");
  treeQADet->AddFriend(qaMap["MonALISA.RCT"],"MonALISA.RCT");
  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
  //
  TTree *treeLogbookDetector =info.GetTree("Logbook.detector",period,"");
  if (treeLogbookDetector){
    if (detArray->GetEntries()>0){
      for (Int_t idet=0; idet<detArray->GetEntries(); idet++){
	// Load Logbook.RefDet
	const char *detName=detArray->At(idet)->GetName();	
	TTree * treeLog =treeLogbookDetector->CopyTree(TString::Format("detector==\"%s\"",detName).Data());
	if (treeLog->GetEntries()<=0){
	  ::Error("qaTrending.InitTrees","Missing Tree Logbook. %s - check the syntax",detName);
	}else{
	  treeLog->BuildIndex("run");
	  qaMap[TString::Format("Logbook.%s",detName).Data()]=treeLog;
	  treeLog->AddFriend(treeQADet, "QADet");
	  treeQADet->AddFriend(treeLog,  TString::Format("Logbook.%s",detName).Data());
	  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
	}
	// Load QA.RefDet
	TTree * treeQARefDet = info.GetTreeDataQA(detName,period, pass);
	if (treeQARefDet){
	  qaMap[TString::Format("QA.%s",detName).Data()]=treeQARefDet;
	  treeQARefDet->AddFriend(treeQADet, "QADet");
	  treeQADet->AddFriend(treeQARefDet,  TString::Format("QA.%s",detName).Data());
	  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
	}else{
	  ::Error("qaTrending.InitTrees","Missing Tree QA.%s - check the syntax",detName);
	}
      }
    }
  }
  //
  // Check consistency of data
  // 
  ::Info("qaTrending::InitTrees::End","Checking trees");
  TList *arrFriends = treeQADet->GetListOfFriends();
  for (Int_t ifriend=0; ifriend<arrFriends->GetEntries(); ifriend++){
    Int_t entries = treeQADet->Draw(TString::Format("run-%s.run", arrFriends->At(ifriend)->GetName()).Data(),"1","goff");
    Double_t mean=0;
    if (entries>0) {
      mean=TMath::Mean(entries, treeQADet->GetV1());
    }
    if (mean==0){
      ::Info("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
    }else{
      ::Error("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
    }
  }
  delete detArray;
  ::Info("qaTrending::InitTrees::End","Detector %s, RefDet=%s",detector, referenceDet);

  return treeQADet;  
}
コード例 #14
0
void fit_and_weights_norm(){

    gROOT->ProcessLine(".L ~/cern/project/lhcbStyle.C");
    lhcbStyle();
    /*gStyle->SetLabelSize(0.05,"x");
    gStyle->SetLabelSize(0.05,"y");
    gStyle->SetTitleSize(0.05,"x");
    gStyle->SetPaperSize(20,26);
    gStyle->SetPadTopMargin(0.0);
    gStyle->SetPadRightMargin(0.05); // increase for colz plots
    gStyle->SetPadBottomMargin(0.0);
    gStyle->SetPadLeftMargin(0.14);
    gStyle->SetTitleH(0.01);*/
                                                                                    //
    const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt.root");           
    const std::string treename = "withbdt";                                         
    const std::string out_file_mass("~/cern/plots/fitting/Lb2JpsipK_2011_2012_mass_fit_after_bdtg3_cut_-055.pdf");                                   
                                                                                    //

    const std::string cuts("bdtg3>=-0.55");    
    
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;

    TTree* rTree1 = tree->CopyTree( cuts.c_str() );

    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi p K^{-})", 5550., 5700., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    //RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5620., 5600., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 5.0, 1.0, 300.0);
    RooRealVar sigmaT("sigmaT", "sigmaT", 1.9, 1., 100.);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.5, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 1.5, 0.2, 10.0);
    RooRealVar nu("nu", "nu", 2., 0.7, 100.);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);
    RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0);                                    //
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
    Lambda_b0_DTF_MASS_constr1.setBins(75);
    
    
    
    
    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2);
    
    //RooStudentT * student = new RooStudentT("student", "student", Lambda_b0_DTF_MASS_constr1, mean, sigmaT, nu);
     
    RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 ));
    RooRealVar cbRatio("cbRatio","cb Ratio", 0.3, 0.1, 1.0);
    RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e1, 1e5);
    RooRealVar bgYield("bgYield","bg Yield", 1e2, 1e0, 5e5);

    //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!!
    /*
    EXT PARAMETER                                INTERNAL      INTERNAL
  NO.   NAME      VALUE            ERROR       STEP SIZE       VALUE
   1  alpha1       2.18020e+00   2.85078e-02   1.38432e-04  -2.56034e-01
   2  alpha2      -2.79102e+00   6.74385e-02   1.51818e-04  -1.49177e-02
   3  cbRatio      3.07172e-01   1.49204e-02   1.72642e-04  -5.69984e-01
   4  mean         5.61985e+03   9.58397e-03   5.56682e-05  -9.66293e-02
   5  n1           1.49358e+00   8.14447e-02   2.09300e-04  -9.70542e-01
   6  n2           1.45276e+00   1.09864e-01   2.59028e-04  -8.39538e-01
   7  sigma1       8.46303e+00   1.32851e-01   2.86985e-05  -1.01453e+00
   8  sigma2       4.93976e+00   3.42842e-02   5.03572e-06  -1.44512e+00
   
   
   
   
   4  mean         5.62097e+03   4.02152e-02   6.00497e-04   3.08772e-01
   5  sigYield     3.52933e+04   2.55400e+02   1.54032e-03  -1.69958e-02
   6  sigma1       1.22322e+01   1.10970e+00   2.87462e-03   1.63838e-01
   7  sigma2       5.54047e+00   1.41829e-01   1.08300e-03  -1.28653e-01
    */
    
   mean.setVal(5.62097e+03);
   sigma1.setVal(1.22322e+01);
   sigma2.setVal(5.54047e+00);
   
   mean.setConstant(true);
   sigma1.setConstant(true);
   sigma2.setConstant(true);
    
    
    
    //alpha1.setVal( 2.18020e+00 );
    //alpha2.setVal( -2.79102e+00 );
    //n1.setVal( 1.49358e+00 );
    //n2.setVal( 1.45276e+00 );
    //frac2.setVal( 3.81630e-01 );
    //sigma1.setVal( 7.37006e+00 );
    //sigma2.setVal( 4.90330e+00 );
    
    //double gauss
    //alpha1.setVal( 2.18020e+00 );
    //alpha2.setVal( -2.79102e+00 );
    //n1.setVal( 1.49358e+00 );
    //n2.setVal( 1.45276e+00 );
    
    
    //alpha1.setConstant( true );
    //alpha2.setConstant( true );
    //frac2.setConstant( true );
    //n1.setConstant( true );
    //n2.setConstant( true );
    //sigma1.setConstant( true );
    //sigma2.setConstant( true );

    // -- bg, mass shape
    RooRealVar a1("a1","a1", -0.1, -0.5, 0.5);
    RooExponential exp("exp", "exp", Lambda_b0_DTF_MASS_constr1, a1);
    RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1);
    RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.);
    RooRealVar sigma3("sigma3","sigma3", 5., 1., 100.);
    RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    //RooAddPdf bg("bg","bg", RooArgList(gauss3, comb), RooArgList(frac3));

    // -- add signal & bg
    RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield));  

    RooArgSet obs;
    obs.add(Lambda_b0_DTF_MASS_constr1);
    obs.add(Jpsi_M);
    //obs.add(chi_c_M);
    //obs.add(proton_ProbNNp);
    //obs.add(proton_ProbNNk);
    //obs.add(kaon_ProbNNp);
    //obs.add(kaon_ProbNNk);

    
    RooDataSet ds("ds","ds", obs, RooFit::Import(*rTree1)); 

    RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();

    RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() );
    ds.plotOn( plot );
    pdf.plotOn( plot );
    
    RooPlot* plotPullMass = Lambda_b0_DTF_MASS_constr1.frame();

    plotPullMass->addPlotable( plot->pullHist() );
    //plotPullMass->SetMinimum();
    //plotPullMass->SetMaximum();

    TCanvas* c = new TCanvas();

    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 0.95);
    //pad1->SetBottomMargin(0.1);
    //pad1->SetTopMargin(0.1);
    pad1->Draw();
    
    //TPad* pad2 = new TPad("pad2","pad2", 0, 0.05, 1, 0.4);
    TPad* pad2 = new TPad("pad2","pad2", 0, 0.05, 1, 0.3);
    pad2->Draw();
    plotPullMass->GetXaxis()->SetLabelSize(0.1);
    plotPullMass->GetYaxis()->SetLabelSize(0.1);
    plotPullMass->GetXaxis()->SetTitleSize(0.1);
    plotPullMass->GetYaxis()->SetTitleSize(0.1);

    //pdf.plotOn( plot, RooFit::Components( sig ), RooFit::LineColor( kTeal ), RooFit::LineStyle(kDashed) );
    pdf.plotOn( plot, RooFit::Components( comb ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashed) );
    //pdf.plotOn( plot, RooFit::Components( gauss3 ), RooFit::LineColor( kViolet ), RooFit::LineStyle(kDashed) );

    pad1->cd();
    plot->Draw();



    pad2->cd();
    plotPullMass->Draw("AP");

    c->SaveAs(out_file_mass.c_str());


    std::cout << rTree1->GetEntries() << " events with the following cut applied: " << cuts.c_str() << std::endl;

/*
    RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
            ds, &pdf, RooArgList(sigYield, bgYield) );


    RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ;
    
    TTree *tree_data = (TTree*)dataw_z->tree();
    TFile * newfile = TFile::Open("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/weighted_data.root","RECREATE");
    tree_data->Write();
    newfile->Close();  
    */
     
 /* 
    TCanvas* d = new TCanvas();
    RooPlot* w_chi_c_Mp = chi_c_Mp.frame();
    dataw_z->plotOn(w_chi_c_Mp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_chi_c_Mp->Draw();
    d->SaveAs("m_chicp_sweighted.png");
 
    TCanvas* e = new TCanvas();
    RooPlot* w_mass_pK = mass_pK.frame();
    dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_pK->Draw();
    e->SaveAs("m_pK_sweighted.png");
*/
/*
    TCanvas* f = new TCanvas();
    RooPlot* w_Jpsi_M = Jpsi_M.frame();
    dataw_z->plotOn(w_Jpsi_M, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_Jpsi_M->Draw();
    f->SaveAs("~/cern/plots/m_Jpsi_sweighted.png");

    TCanvas* g = new TCanvas();
    RooPlot* w_chi_c_M = chi_c_M.frame();
    dataw_z->plotOn(w_chi_c_M, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_chi_c_M->Draw();
    g->SaveAs("~/cern/plots/m_Chic_sweighted.png");
    */
}
コード例 #15
0
void TMVAClassificationApplication( TString myMethodList = "" ) 
{   
   //---------------------------------------------------------------
   // default MVA methods to be trained + tested

   // this loads the library
   TMVA::Tools::Instance();

   std::map<std::string,int> Use;

   Use["CutsGA"]          = 0; // other "Cuts" methods work identically
   // ---
   Use["Likelihood"]      = 1;
   Use["LikelihoodD"]     = 0; // the "D" extension indicates decorrelated input variables (see option strings)
   Use["LikelihoodPCA"]   = 0; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
   Use["LikelihoodKDE"]   = 0;
   Use["LikelihoodMIX"]   = 0;
   // ---
   Use["PDERS"]           = 0;
   Use["PDERSD"]          = 0;
   Use["PDERSPCA"]        = 0;
   Use["PDERSkNN"]        = 0; // depreciated until further notice
   Use["PDEFoam"]         = 0;
   // --
   Use["KNN"]             = 0;
   // ---
   Use["HMatrix"]         = 0;
   Use["Fisher"]          = 0;
   Use["FisherG"]         = 0;
   Use["BoostedFisher"]   = 0;
   Use["LD"]              = 0;
   // ---
   Use["FDA_GA"]          = 0;
   Use["FDA_SA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   Use["FDA_MCMT"]        = 0;
   // ---
   Use["MLP"]             = 0; // this is the recommended ANN
   Use["MLPBFGS"]         = 0; // recommended ANN with optional training method
   Use["MLPBNN"]          = 0;  // 
   Use["CFMlpANN"]        = 0; // *** missing
   Use["TMlpANN"]         = 0; 
   // ---
   Use["SVM"]             = 0;
   // ---
   Use["BDT"]             = 1;
   Use["BDTD"]            = 0;
   Use["BDTG"]            = 0;
   Use["BDTB"]            = 0;
   // ---
   Use["RuleFit"]         = 0;
   // ---
   Use["Category"]        = 0;
   // ---
   Use["Plugin"]          = 0;
   // ---------------------------------------------------------------

   std::cout << std::endl;
   std::cout << "==> Start TMVAClassificationApplication" << std::endl;

   if (myMethodList != "") {
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

      std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
      for (UInt_t i=0; i<mlist.size(); i++) {
         std::string regMethod(mlist[i]);

         if (Use.find(regMethod) == Use.end()) {
            std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
            for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
            std::cout << std::endl;
            return;
         }
         Use[regMethod] = 0;
      }
   }

   //
   // create the Reader object
   //
   TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    

Float_t Z_rapidity_z;
reader->AddVariable("Z_rapidity_z",&Z_rapidity_z);

Float_t THRUST_2D;
reader->AddVariable("THRUST_2D",&THRUST_2D);

Float_t L1_L2_cosangle;
reader->AddVariable("L1_L2_cosangle",&L1_L2_cosangle);

Float_t TransMass_ZH150_uncl;
reader->AddVariable("TransMass_ZH150_uncl",&TransMass_ZH150_uncl);

Float_t TransMass_ZH150;
reader->AddVariable("TransMass_ZH150",&TransMass_ZH150);

Float_t DeltaPhi_ZH;
reader->AddVariable("DeltaPhi_ZH",&DeltaPhi_ZH);

Float_t DeltaPhi_ZH_uncl;
reader->AddVariable("DeltaPhi_ZH_uncl",&DeltaPhi_ZH_uncl);

Float_t CMAngle;
reader->AddVariable("CMAngle",&CMAngle);

Float_t CS_cosangle;
reader->AddVariable("CS_cosangle",&CS_cosangle);

   // create a set of variables and declare them to the reader
   // - the variable names must corresponds in name and type to 
   // those given in the weight file(s) that you use
   Float_t var1, var2;
   Float_t var3, var4;
//   reader->AddVariable( "myvar1 := var1+var2", &var1 );
//   reader->AddVariable( "myvar2 := var1-var2", &var2 );
//   reader->AddVariable( "var3",                &var3 );
//   reader->AddVariable( "var4",                &var4 );

   //Spectator variables declared in the training have to be added to the reader, too
   Float_t spec1,spec2;
//   reader->AddSpectator( "spec1 := var1*2",   &spec1 );

 float nonsense =0;
//   reader->AddSpectator( "spec2 := var1*3",   &spec2 );

 float nonsense =0;

   Float_t Category_cat1, Category_cat2, Category_cat3;
   if (Use["Category"]){
      // add artificial spectators for distinguishing categories
//      reader->AddSpectator( "Category_cat1 := var3<=0",             &Category_cat1 );

 float nonsense =0;
//      reader->AddSpectator( "Category_cat2 := (var3>0)&&(var4<0)",  &Category_cat2 );

 float nonsense =0;
//      reader->AddSpectator( "Category_cat3 := (var3>0)&&(var4>=0)", &Category_cat3 );

 float nonsense =0;
   }
   //
   // book the MVA methods
   //
   TString dir    = "weights/";
   TString prefix = "TMVAClassification";

   // book method(s)
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
         TString methodName = it->first + " method";
         TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
         reader->BookMVA( methodName, weightfile ); 
      }
   }
   
   // example how to use your own method as plugin
   if (Use["Plugin"]) {
      // the weight file contains a line 
      // Method         : MethodName::InstanceName

      // if MethodName is not a known TMVA method, it is assumed to be
      // a user implemented method which has to be loaded via the
      // plugin mechanism
      
      // for user implemented methods the line in the weight file can be
      // Method         : PluginName::InstanceName
      // where PluginName can be anything

      // before usage the plugin has to be defined, which can happen
      // either through the following line in .rootrc:
      // # plugin handler          plugin       class            library        constructor format
      // Plugin.TMVA@@MethodBase:  PluginName   MethodClassName  UserPackage    "MethodName(DataSet&,TString)"
      //  
      // or by telling the global plugin manager directly
      gPluginMgr->AddHandler("TMVA@@MethodBase", "PluginName", "MethodClassName", "UserPackage", "MethodName(DataSet&,TString)");
      // the class is then looked for in libUserPackage.so

      // now the method can be booked like any other
      reader->BookMVA( "User method", dir + prefix + "_User.weights.txt" );
   }

   // book output histograms
   UInt_t nbin = 100;
   TH1F *histLk(0), *histLkD(0), *histLkPCA(0), *histLkKDE(0), *histLkMIX(0), *histPD(0), *histPDD(0);
   TH1F *histPDPCA(0), *histPDEFoam(0), *histPDEFoamErr(0), *histPDEFoamSig(0), *histKNN(0), *histHm(0);
   TH1F *histFi(0), *histFiG(0), *histFiB(0), *histLD(0), *histNn(0),*histNnbfgs(0),*histNnbnn(0), *histNnC(0), *histNnT(0), *histBdt(0), *histBdtG(0), *histBdtD(0);
   TH1F *histRf(0), *histSVMG(0), *histSVMP(0), *histSVML(0), *histFDAMT(0), *histFDAGA(0), *histCat(0), *histPBdt(0);

   if (Use["Likelihood"])    histLk      = new TH1F( "MVA_Likelihood",    "MVA_Likelihood",    nbin, -1, 1 );
   if (Use["LikelihoodD"])   histLkD     = new TH1F( "MVA_LikelihoodD",   "MVA_LikelihoodD",   nbin, -1, 0.9999 );
   if (Use["LikelihoodPCA"]) histLkPCA   = new TH1F( "MVA_LikelihoodPCA", "MVA_LikelihoodPCA", nbin, -1, 1 );
   if (Use["LikelihoodKDE"]) histLkKDE   = new TH1F( "MVA_LikelihoodKDE", "MVA_LikelihoodKDE", nbin,  -0.00001, 0.99999 );
   if (Use["LikelihoodMIX"]) histLkMIX   = new TH1F( "MVA_LikelihoodMIX", "MVA_LikelihoodMIX", nbin,  0, 1 );
   if (Use["PDERS"])         histPD      = new TH1F( "MVA_PDERS",         "MVA_PDERS",         nbin,  0, 1 );
   if (Use["PDERSD"])        histPDD     = new TH1F( "MVA_PDERSD",        "MVA_PDERSD",        nbin,  0, 1 );
   if (Use["PDERSPCA"])      histPDPCA   = new TH1F( "MVA_PDERSPCA",      "MVA_PDERSPCA",      nbin,  0, 1 );
   if (Use["KNN"])           histKNN     = new TH1F( "MVA_KNN",           "MVA_KNN",           nbin,  0, 1 );
   if (Use["HMatrix"])       histHm      = new TH1F( "MVA_HMatrix",       "MVA_HMatrix",       nbin, -0.95, 1.55 );
   if (Use["Fisher"])        histFi      = new TH1F( "MVA_Fisher",        "MVA_Fisher",        nbin, -4, 4 );
   if (Use["FisherG"])       histFiG     = new TH1F( "MVA_FisherG",       "MVA_FisherG",       nbin, -1, 1 );
   if (Use["BoostedFisher"]) histFiB     = new TH1F( "MVA_BoostedFisher", "MVA_BoostedFisher", nbin, -2, 2 );
   if (Use["LD"])            histLD      = new TH1F( "MVA_LD",            "MVA_LD",            nbin, -2, 2 );
   if (Use["MLP"])           histNn      = new TH1F( "MVA_MLP",           "MVA_MLP",           nbin, -1.25, 1.5 );
   if (Use["MLPBFGS"])       histNnbfgs  = new TH1F( "MVA_MLPBFGS",           "MVA_MLPBFGS",           nbin, -1.25, 1.5 );
   if (Use["MLPBNN"])        histNnbnn   = new TH1F( "MVA_MLPBNN",           "MVA_MLPBNN",           nbin, -1.25, 1.5 );
   if (Use["CFMlpANN"])      histNnC     = new TH1F( "MVA_CFMlpANN",      "MVA_CFMlpANN",      nbin,  0, 1 );
   if (Use["TMlpANN"])       histNnT     = new TH1F( "MVA_TMlpANN",       "MVA_TMlpANN",       nbin, -1.3, 1.3 );
   if (Use["BDT"])           histBdt     = new TH1F( "MVA_BDT",           "MVA_BDT",           nbin, -0.8, 0.8 );
   if (Use["BDTD"])          histBdtD    = new TH1F( "MVA_BDTD",          "MVA_BDTD",          nbin, -0.8, 0.8 );
   if (Use["BDTG"])          histBdtG    = new TH1F( "MVA_BDTG",          "MVA_BDTG",          nbin, -1.0, 1.0 );
   if (Use["RuleFit"])       histRf      = new TH1F( "MVA_RuleFit",       "MVA_RuleFit",       nbin, -2.0, 2.0 );
   if (Use["SVM_Gauss"])     histSVMG    = new TH1F( "MVA_SVM_Gauss",     "MVA_SVM_Gauss",     nbin,  0.0, 1.0 );
   if (Use["SVM_Poly"])      histSVMP    = new TH1F( "MVA_SVM_Poly",      "MVA_SVM_Poly",      nbin,  0.0, 1.0 );
   if (Use["SVM_Lin"])       histSVML    = new TH1F( "MVA_SVM_Lin",       "MVA_SVM_Lin",       nbin,  0.0, 1.0 );
   if (Use["FDA_MT"])        histFDAMT   = new TH1F( "MVA_FDA_MT",        "MVA_FDA_MT",        nbin, -2.0, 3.0 );
   if (Use["FDA_GA"])        histFDAGA   = new TH1F( "MVA_FDA_GA",        "MVA_FDA_GA",        nbin, -2.0, 3.0 );
   if (Use["Category"])      histCat     = new TH1F( "MVA_Category",      "MVA_Category",      nbin, -2., 2. );
   if (Use["Plugin"])        histPBdt    = new TH1F( "MVA_PBDT",          "MVA_BDT",           nbin, -0.8, 0.8 );

   // PDEFoam also returns per-event error, fill in histogram, and also fill significance
   if (Use["PDEFoam"]) {
      histPDEFoam    = new TH1F( "MVA_PDEFoam",       "MVA_PDEFoam",              nbin,  0, 1 );
      histPDEFoamErr = new TH1F( "MVA_PDEFoamErr",    "MVA_PDEFoam error",        nbin,  0, 1 );
      histPDEFoamSig = new TH1F( "MVA_PDEFoamSig",    "MVA_PDEFoam significance", nbin,  0, 10 );
   }

   // book example histogram for probability (the other methods are done similarly)
   TH1F *probHistFi(0), *rarityHistFi(0);
   if (Use["Fisher"]) {
      probHistFi   = new TH1F( "MVA_Fisher_Proba",  "MVA_Fisher_Proba",  nbin, 0, 1 );
      rarityHistFi = new TH1F( "MVA_Fisher_Rarity", "MVA_Fisher_Rarity", nbin, 0, 1 );
   }

   // Prepare input tree (this must be replaced by your data source)
   // in this example, there is a toy tree with signal and one with background events
   // we'll later on use only the "signal" events for the test in this example.
   //   
   TFile *input(0);
   TString fname = "/tmp/chasco/ORIGINAL//Data_MuEG2011B_1.root";   
   if (!gSystem->AccessPathName( fname )) {
      input = TFile::Open( fname ); // check if file in local directory exists
   } 
   else { 
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server
   }
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
   
   //
   // prepare the tree
   // - here the variable names have to corresponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //
   TTree* BigTree = (TTree*)input->Get("data");

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

TTree* theTree = BigTree->CopyTree("((cat == 1) + (cat == 2))*(ln==0)*(Cosmic==0)*(fabs(Mass_Z - 91.18)<10)*(Pt_Z>30)*(DeltaPhi_metjet>0.5)*(Pt_J1 < 30)*(pfMEToverPt_Z > 0.4)*(pfMEToverPt_Z < 1.8)*((Pt_Jet_btag_CSV_max > 20)*(btag_CSV_max < 0.244) + (1-(Pt_Jet_btag_CSV_max > 20)))*(sqrt(pow(dilepPROJLong + 1.25*recoilPROJLong + 0.0*uncertPROJLong,2)*(dilepPROJLong + 1.25*recoilPROJLong + 0.0*uncertPROJLong > 0) + 1.0*pow(dilepPROJPerp + 1.25*recoilPROJPerp + 0.0*uncertPROJPerp,2)*(dilepPROJPerp + 1.25*recoilPROJPerp + 0.0*uncertPROJPerp > 0)) > 45.0)");
   std::cout << "--- Select signal sample" << std::endl;
   Float_t userVar1, userVar2;
//   theTree->SetBranchAddress( "var1", &userVar1 );
//   theTree->SetBranchAddress( "var2", &userVar2 );
//   theTree->SetBranchAddress( "var3", &var3 );
//   theTree->SetBranchAddress( "var4", &var4 );

theTree->SetBranchAddress( " Z_rapidity_z", &Z_rapidity_z);

theTree->SetBranchAddress( " THRUST_2D", &THRUST_2D);

theTree->SetBranchAddress( " L1_L2_cosangle", &L1_L2_cosangle);

theTree->SetBranchAddress( " TransMass_ZH150_uncl", &TransMass_ZH150_uncl);

theTree->SetBranchAddress( " TransMass_ZH150", &TransMass_ZH150);

theTree->SetBranchAddress( " DeltaPhi_ZH", &DeltaPhi_ZH);

theTree->SetBranchAddress( " DeltaPhi_ZH_uncl", &DeltaPhi_ZH_uncl);

theTree->SetBranchAddress( " CMAngle", &CMAngle);

theTree->SetBranchAddress( " CS_cosangle", &CS_cosangle);

   // efficiency calculator for cut method
   Int_t    nSelCutsGA = 0;
   Double_t effS       = 0.7;

   std::vector<Float_t> vecVar(9); // vector for EvaluateMVA tests

   std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {

      if (ievt%1000 == 0){
         std::cout << "--- ... Processing event: " << ievt << std::endl;
      }

      theTree->GetEntry(ievt);

      var1 = userVar1 + userVar2;
      var2 = userVar1 - userVar2;

      if (ievt <20){
         // test the twodifferent Reader::EvaluateMVA functions 
         // access via registered variables compared to access via vector<float>
//         vecVar[0]=var1;
//         vecVar[1]=var2;
//         vecVar[2]=var3;
//         vecVar[3]=var4;      

vecVar[0]=Z_rapidity_z;

vecVar[1]=THRUST_2D;

vecVar[2]=L1_L2_cosangle;

vecVar[3]=TransMass_ZH150_uncl;

vecVar[4]=TransMass_ZH150;

vecVar[5]=DeltaPhi_ZH;

vecVar[6]=DeltaPhi_ZH_uncl;

vecVar[7]=CMAngle;

vecVar[8]=CS_cosangle;
         for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
            if (it->second) {
               TString mName = it->first + " method";
               Double_t mva1 = reader->EvaluateMVA( mName); 
               Double_t mva2 = reader->EvaluateMVA( vecVar, mName); 
               if (mva1 != mva2) {
                  std::cout << "++++++++++++++ ERROR in "<< mName <<", comparing different EvaluateMVA results val1=" << mva1 << " val2="<<mva2<<std::endl;
               }
            }
         }
         // now test that the inputs do matter
         TRandom3 rand(0);
//         vecVar[0]=rand.Rndm();
//         vecVar[1]=rand.Rndm();
//         vecVar[2]=rand.Rndm();
//         vecVar[3]=rand.Rndm();

vecVar[0]=rand.Rndm();

vecVar[1]=rand.Rndm();

vecVar[2]=rand.Rndm();

vecVar[3]=rand.Rndm();

vecVar[4]=rand.Rndm();

vecVar[5]=rand.Rndm();

vecVar[6]=rand.Rndm();

vecVar[7]=rand.Rndm();

vecVar[8]=rand.Rndm();
         for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
            if (it->second) {
               TString mName = it->first + " method";
               Double_t mva1 = reader->EvaluateMVA( mName); 
               Double_t mva2 = reader->EvaluateMVA( vecVar, mName); 
               if (mva1 == mva2) {
                  std::cout << "++++++++++++++ ERROR in "<< mName <<", obtaining idnetical output for different inputs" <<std::endl;
               }
            }
         }
      }
      // 
      // return the MVAs and fill to histograms
      // 
      if (Use["CutsGA"]) {
         // Cuts is a special case: give the desired signal efficienciy
         Bool_t passed = reader->EvaluateMVA( "CutsGA method", effS );
         if (passed) nSelCutsGA++;
      }

      if (Use["Likelihood"   ])   histLk     ->Fill( reader->EvaluateMVA( "Likelihood method"    ) );
      if (Use["LikelihoodD"  ])   histLkD    ->Fill( reader->EvaluateMVA( "LikelihoodD method"   ) );
      if (Use["LikelihoodPCA"])   histLkPCA  ->Fill( reader->EvaluateMVA( "LikelihoodPCA method" ) );
      if (Use["LikelihoodKDE"])   histLkKDE  ->Fill( reader->EvaluateMVA( "LikelihoodKDE method" ) );
      if (Use["LikelihoodMIX"])   histLkMIX  ->Fill( reader->EvaluateMVA( "LikelihoodMIX method" ) );
      if (Use["PDERS"        ])   histPD     ->Fill( reader->EvaluateMVA( "PDERS method"         ) );
      if (Use["PDERSD"       ])   histPDD    ->Fill( reader->EvaluateMVA( "PDERSD method"        ) );
      if (Use["PDERSPCA"     ])   histPDPCA  ->Fill( reader->EvaluateMVA( "PDERSPCA method"      ) );
      if (Use["KNN"          ])   histKNN    ->Fill( reader->EvaluateMVA( "KNN method"           ) );
      if (Use["HMatrix"      ])   histHm     ->Fill( reader->EvaluateMVA( "HMatrix method"       ) );
      if (Use["Fisher"       ])   histFi     ->Fill( reader->EvaluateMVA( "Fisher method"        ) );
      if (Use["FisherG"      ])   histFiG    ->Fill( reader->EvaluateMVA( "FisherG method"       ) );
      if (Use["BoostedFisher"])   histFiB    ->Fill( reader->EvaluateMVA( "BoostedFisher method" ) );
      if (Use["LD"           ])   histLD     ->Fill( reader->EvaluateMVA( "LD method"            ) );
      if (Use["MLP"          ])   histNn     ->Fill( reader->EvaluateMVA( "MLP method"           ) );
      if (Use["MLPBFGS"          ])   histNnbfgs ->Fill( reader->EvaluateMVA( "MLPBFGS method"           ) );
      if (Use["MLPBNN"          ])   histNnbnn ->Fill( reader->EvaluateMVA( "MLPBNN method"           ) );
      if (Use["CFMlpANN"     ])   histNnC    ->Fill( reader->EvaluateMVA( "CFMlpANN method"      ) );
      if (Use["TMlpANN"      ])   histNnT    ->Fill( reader->EvaluateMVA( "TMlpANN method"       ) );
      if (Use["BDT"          ])   histBdt    ->Fill( reader->EvaluateMVA( "BDT method"           ) );
      if (Use["BDTD"         ])   histBdtD   ->Fill( reader->EvaluateMVA( "BDTD method"          ) );
      if (Use["BDTG"         ])   histBdtG   ->Fill( reader->EvaluateMVA( "BDTG method"          ) );
      if (Use["RuleFit"      ])   histRf     ->Fill( reader->EvaluateMVA( "RuleFit method"       ) );
      if (Use["SVM_Gauss"    ])   histSVMG   ->Fill( reader->EvaluateMVA( "SVM_Gauss method"     ) );
      if (Use["SVM_Poly"     ])   histSVMP   ->Fill( reader->EvaluateMVA( "SVM_Poly method"      ) );
      if (Use["SVM_Lin"      ])   histSVML   ->Fill( reader->EvaluateMVA( "SVM_Lin method"       ) );
      if (Use["FDA_MT"       ])   histFDAMT  ->Fill( reader->EvaluateMVA( "FDA_MT method"        ) );
      if (Use["FDA_GA"       ])   histFDAGA  ->Fill( reader->EvaluateMVA( "FDA_GA method"        ) );
      if (Use["Category"     ])   histCat    ->Fill( reader->EvaluateMVA( "Category method"      ) );
      if (Use["Plugin"       ])   histPBdt   ->Fill( reader->EvaluateMVA( "P_BDT method"         ) );

      // retrieve also per-event error
      if (Use["PDEFoam"]) {
         Double_t val = reader->EvaluateMVA( "PDEFoam method" );
         Double_t err = reader->GetMVAError();
         histPDEFoam   ->Fill( val );
         histPDEFoamErr->Fill( err );         
         histPDEFoamSig->Fill( val/err );
      }         

      // retrieve probability instead of MVA output
      if (Use["Fisher"])   {
         probHistFi  ->Fill( reader->GetProba ( "Fisher method" ) );
         rarityHistFi->Fill( reader->GetRarity( "Fisher method" ) );
      }
   }
   // get elapsed time
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

   // get efficiency for cuts classifier
   if (Use["CutsGA"]) std::cout << "--- Efficiency for CutsGA method: " << double(nSelCutsGA)/theTree->GetEntries()
                                << " (for a required signal efficiency of " << effS << ")" << std::endl;

   if (Use["CutsGA"]) {

      // test: retrieve cuts for particular signal efficiency
      // CINT ignores dynamic_casts so we have to use a cuts-secific Reader function to acces the pointer  
      TMVA::MethodCuts* mcuts = reader->FindCutsMVA( "CutsGA method" ) ;

      if (mcuts) {      
         std::vector<Double_t> cutsMin;
         std::vector<Double_t> cutsMax;
         mcuts->GetCuts( 0.7, cutsMin, cutsMax );
         std::cout << "--- -------------------------------------------------------------" << std::endl;
         std::cout << "--- Retrieve cut values for signal efficiency of 0.7 from Reader" << std::endl;
         for (UInt_t ivar=0; ivar<cutsMin.size(); ivar++) {
            std::cout << "... Cut: " 
                      << cutsMin[ivar] 
                      << " < \"" 
                      << mcuts->GetInputVar(ivar)
                      << "\" <= " 
                      << cutsMax[ivar] << std::endl;
         }
         std::cout << "--- -------------------------------------------------------------" << std::endl;
      }
   }

   //
   // write histograms
   //
   TFile *target  = new TFile( "TMVApp.root","RECREATE" );
   if (Use["Likelihood"   ])   histLk     ->Write();
   if (Use["LikelihoodD"  ])   histLkD    ->Write();
   if (Use["LikelihoodPCA"])   histLkPCA  ->Write();
   if (Use["LikelihoodKDE"])   histLkKDE  ->Write();
   if (Use["LikelihoodMIX"])   histLkMIX  ->Write();
   if (Use["PDERS"        ])   histPD     ->Write();
   if (Use["PDERSD"       ])   histPDD    ->Write();
   if (Use["PDERSPCA"     ])   histPDPCA  ->Write();
   if (Use["KNN"          ])   histKNN    ->Write();
   if (Use["HMatrix"      ])   histHm     ->Write();
   if (Use["Fisher"       ])   histFi     ->Write();
   if (Use["FisherG"      ])   histFiG    ->Write();
   if (Use["BoostedFisher"])   histFiB    ->Write();
   if (Use["LD"           ])   histLD     ->Write();
   if (Use["MLP"          ])   histNn     ->Write();
   if (Use["MLPBFGS"      ])   histNnbfgs ->Write();
   if (Use["MLPBNN"       ])   histNnbnn  ->Write();
   if (Use["CFMlpANN"     ])   histNnC    ->Write();
   if (Use["TMlpANN"      ])   histNnT    ->Write();
   if (Use["BDT"          ])   histBdt    ->Write();
   if (Use["BDTD"         ])   histBdtD   ->Write();
   if (Use["BDTG"         ])   histBdtG   ->Write(); 
   if (Use["RuleFit"      ])   histRf     ->Write();
   if (Use["SVM_Gauss"    ])   histSVMG   ->Write();
   if (Use["SVM_Poly"     ])   histSVMP   ->Write();
   if (Use["SVM_Lin"      ])   histSVML   ->Write();
   if (Use["FDA_MT"       ])   histFDAMT  ->Write();
   if (Use["FDA_GA"       ])   histFDAGA  ->Write();
   if (Use["Category"     ])   histCat    ->Write();
   if (Use["Plugin"       ])   histPBdt   ->Write();

   // write also error and significance histos
   if (Use["PDEFoam"]) { histPDEFoam->Write(); histPDEFoamErr->Write(); histPDEFoamSig->Write(); }

   // write also probability hists
   if (Use["Fisher"]) { if (probHistFi != 0) probHistFi->Write(); if (rarityHistFi != 0) rarityHistFi->Write(); }
   target->Close();

   std::cout << "--- Created root file: \"TMVApp.root\" containing the MVA output histograms" << std::endl;
  
   delete reader;
    
   std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
} 
コード例 #16
0
ファイル: makeplots3_RootOut.C プロジェクト: goi42/LbJpsipPi
void makeplots3_RootOut(TString runmode="d", TString drawopt=""){
  if(runmode.Contains("tree")&&runmode.Contains("hist")){
    cout<<"Cannot do both tree and histogram output."<<endl;
    exit(EXIT_FAILURE);
  }
  if(!(runmode.Contains("tree")||runmode.Contains("hist"))){
    cout<<"This program doesn't do anything unless you specify \"tree\" or \"hist\"."<<endl;
    exit(EXIT_FAILURE);
  }
  if(runmode.Contains("hist")&&runmode.Contains("bron")){
    cout<<"Warning: \"bron\" option doesn't do anything in \"hist\" mode."<<endl;
  }
  gROOT->SetBatch(kTRUE);
  TString placeholder;//this is to avoid adding strings in functions; assign right before use
  TString placeholder2;
  TString placeholder3;
  //create necessary counters, canvases, legends, etc.
  cout<<endl;
  cout<<"Running in mode "<<runmode<<"..."<<endl<<endl;
  vector<TCanvas*> c;//each canvas holds one stack of histograms
  int ci = 0;//how many canvases have been plotted?
  vector<TLegend*> leg;//one legend per canvas
  vector<THStack*> hs;//one stack per canvas
  vector< vector<TH1F*> > h;
  TCanvas *cf = new TCanvas("cf","combined");//canvas to hold everything

  //assign things to actually be plotted
  map<TString,TString> f1quality {{"filetype","data"},{"decaymode","both"}};
  map<TString,TString> f2quality {{"filetype","MC"},{"decaymode","#Lambda^{0}"}};
  map<TString,TString> f3quality {{"filetype","MC"},{"decaymode","#Sigma^{0}"}};
  map<TString,TString> f4quality {{"filetype","MC"},{"decaymode","#Lambda*(1405)"}};
  map<TString,TString> f5quality {{"filetype","MC"},{"decaymode","#Lambda only"}};
  map<TString,TString> f8quality {{"filetype","MC"},{"decaymode","B_{0}"}};
  file f[]={// {"/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/subLimDVNtuples.root","data",f1quality}};
    // {"/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/withKScut/LMC_tuples_with_gd_info.root","LMCfile",f2quality}};
    // {"/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/withKScut/SMC_tuples_with_gd_info.root","SMCfile",f3quality},
    // {"/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/Lst/1405_fullMC/Lb_JpsiLambda_mmSpi_1405_200000.root","Lst1405MC",f4quality}
    {"/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/B0/B0.root","B0MC",f8quality},
  };

  int nFiles = (sizeof(f)/sizeof(f[0]));
  if((unsigned int)nFiles != (sizeof(Lbname)/sizeof(Lbname[0]))){
    cout<<"number of Lbnames must = nFiles"<<endl;
    cout<<"nFiles = "<<nFiles<<" while (sizeof(Lbname)/sizeof(Lbname[0])) = "<<(sizeof(Lbname)/sizeof(Lbname[0]))<<endl;
    exit(EXIT_FAILURE);
  }else if((unsigned int)nFiles != (sizeof(Jpsi_)/sizeof(Jpsi_[0]))){
    cout<<"number of Jpsi_ must = nFiles"<<endl;
    cout<<"nFiles = "<<nFiles<<" while (sizeof(Jpsi_)/sizeof(Jpsi_[0])) = "<<(sizeof(Jpsi_)/sizeof(Jpsi_[0]))<<endl;
    exit(EXIT_FAILURE);
  }else if((unsigned int)nFiles != (sizeof(massname)/sizeof(massname[0]))){
    cout<<"number of mass names must equal the number of files"<<endl;
    exit(EXIT_FAILURE);
  }

  cout<<"Starting file loop..."<<endl;
  for(int ifile=0;ifile<nFiles;ifile++){
    file * myfile = &(f[ifile]);
    TFile * thisfile = f[ifile].self;
    cout<<"Using "<<myfile->name<<"..."<<endl;
    myfile->b={{massname[ifile],"B_{0} mass",560,3800,6600},
	       {massname[ifile],"B_{0} mass LL",560,3800,6600},
	       {massname[ifile],"B_{0} mass DD",560,3800,6600},
    };
    // myfile->b={{massname[ifile],"#Lambda_{b} mass",400,4100,6100},
    // 	       {massname[ifile],"#Lambda_{b} mass LL",400,4100,6100},
    // 	       {massname[ifile],"#Lambda_{b} mass DD",400,4100,6100},
    // };
    // myfile->b={{"R_WM","#Lambda^{0} M with p #rightarrow #pi",80,300,700}, \
    // 		 {"R_WM","#Lambda^{0} M with p #rightarrow #pi LL",80,300,700}, \
    // 		 {"R_WM","#Lambda^{0} M with p #rightarrow #pi DD",80,300,700}};
    // myfile->b={{"R_M","#Lambda M LL",300,1086,1146},
    // 		 {"R_M","#Lambda M DD",300,1086,1146}};
    // // {"R_M","#Lambda^{0} M",300,1086,1146}, \
	 
    cout<<"branches declared"<<endl;
    if(myfile->name!="B0MC")
      myfile->add_tree("Lb2JpsiLTree/mytree");//all 3 files have the same tree
    else
      myfile->add_tree("B02JpsiKpiTree/mytree");
    cout<<"tree added"<<endl;
    
    int nBranches = myfile->b.size();
    
    cout<<endl<<"Starting branch loop..."<<endl;
    for(int ibranch=0; ibranch<nBranches; ibranch++){
      branch * mybranch = &(myfile->b[ibranch]);
      TString * thisbranch = &(mybranch->self);
      cout<<"On branch "<<mybranch->name<<" for file "<<myfile->name<<"..."<<endl;
      
      //assign cuts
      TCut cLL,cDD,ctrigger,cB02JpsiKst;
      makecuts(ifile,cLL,cDD,ctrigger,cB02JpsiKst);

      if(f[ifile].name=="SMCfile"){
	placeholder = "abs(R_MC_GD_MOTHER_ID)==5122&&abs(R_MC_MOTHER_ID)==3212&&R_BKGCAT==0";
	placeholder2="SMC";
      }else if(f[ifile].name=="Lst1405MC"){
	placeholder = "abs(R_MC_GD_GD_MOTHER_ID)==5122&&abs(R_MC_GD_MOTHER_ID)==13122&&abs(R_MC_MOTHER_ID)==3212&&R_BKGCAT==0";
	placeholder2="Lst1405MC";
      }
      // placeholder3="070116_plus"+placeholder2+"cuts";
      // mybranch->c = {{c070116&&(TCut)placeholder,placeholder3}};
      mybranch->c = {{cB02JpsiKst,"LimingB0cuts"}};
      int nCuts = mybranch->c.size();
      if(nCuts==0){
        //for branches with no cuts assigned, 
        //we must give them an empty cut with an empty name
        //so they can be plotted in the cuts loop
        mybranch->c = {{"",""}};
        nCuts = mybranch->c.size();
      }
      //create necessary canvasy things
      TString cistring = Form("%d",ci);
      placeholder = "c"+cistring;
      c.push_back( new TCanvas(placeholder,placeholder,1200,800) ); //create the canvases
      c[ci]->cd();
      gStyle->SetOptStat("");
      leg.push_back( new TLegend(0.125, 0.6, 0.625, 0.93) );//create legend
      placeholder = "hs"+cistring;
      hs.push_back( new THStack(placeholder,placeholder) ); //create the stack to hold the histograms
      TString leglabel="";
      TString stacktitle="";
      h.resize(ci+1);
      
      int icolor = 0;//color counter
      
      for(int icut =0; icut<nCuts; icut++){
        cut * mycut = &(mybranch->c[icut]);
        TCut * thiscut = &(mycut->self);
        //adjust LL and DD branches to have LL and DD cuts
        if(mybranch->name.Contains("LL")){
          *thiscut=*thiscut&&cLL;
          mycut->name+="_LL";
        }
        if(mybranch->name.Contains("DD")){
          *thiscut=*thiscut&&cDD;
          mycut->name+="_DD";
        }
        
        cout<<"On cut "<<mycut->name<<"..."<<endl;
	if(mycut->name.Contains(" ")){
	  cout<<"spaces are not allowed in cut names. Rename cut "<<mycut->name<<"!"<<endl;
	  exit(EXIT_FAILURE);
	}
	if(runmode.Contains("tree")){
	  //create cut trees
	  if(myfile->t.size()>1){
	    cout<<"tree vector has "<<myfile->t.size()<<"elements. How did this happen?"<<endl;
	    exit(EXIT_FAILURE);
	  }
	  TString fileoutputlocation="./";
	  if(myfile->quality["filetype"].Contains("data"))
	    fileoutputlocation = "/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/";
	  if(myfile->quality["filetype"].Contains("MC"))
	    fileoutputlocation = "/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/withKScut/";
	  if(myfile->name=="B0MC")
	    fileoutputlocation = "/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/B0/";
	  TString tempfilelocation=fileoutputlocation+"temp.root";
	  cout<<"creating tempfile... ";
	  TFile *tempfile = new TFile(tempfilelocation,"recreate");
	  cout<<"done"<<endl<<"copying tree with cuts... ";
	  TTree *temptree = myfile->t[0]->CopyTree(*thiscut);
	  cout<<"done"<<endl<<"writing tempfile... ";
	  tempfile->Write();
	  cout<<"done"<<endl<<"deleting "<<myfile->name<<" in memory... ";
	  delete thisfile;
	  cout<<"done"<<endl;
	  if(!runmode.Contains("bron")){
	    cout<<"setting branch statuses... ";
	    temptree->SetBranchStatus("*",0);
	    temptree->SetBranchStatus(*thisbranch,1);
	    cout<<"done"<<endl;
	  }
	  cout<<"creating newfile... ";
	  if(f[ifile].name=="SMCfile"){
	    placeholder2="SMC";
	  }else if(f[ifile].name=="Lst1405MC"){
	    placeholder2="Lst1405MC";
	  }else if(f[ifile].name=="B0MC"){
	    placeholder2="B0MC";
	  }
	  placeholder = fileoutputlocation+"cutfile_"+mycut->name+"_"+placeholder2+".root";
	  TFile *newfile = new TFile(placeholder,"recreate");
	  cout<<"done"<<endl<<"copying temptree... ";
	  TTree *newtree = temptree->CopyTree("");
	  cout<<"done"<<endl<<"writing newfile... ";
	  newfile->Write();
	  cout<<"done"<<endl;
	  if(!runmode.Contains("bron")){
	    cout<<"setting branch statuses... ";
	    temptree->SetBranchStatus("*",1);
	    cout<<"done"<<endl;
	  }
	  cout<<"deleting tempfile... ";
	  delete tempfile;
	  cout<<"done"<<endl<<"deleting newfile... ";
	  delete newfile;
	  cout<<"done"<<endl<<"removing tempfile... ";
	  placeholder= "rm "+tempfilelocation;
	  gSystem->Exec(placeholder);
	  cout<<"done"<<endl<<"reloading "<<myfile->name<<" and its tree in memory... ";
	  myfile->self = TFile::Open(myfile->location);
	  thisfile = myfile->self;
	  myfile->add_tree(myfile->tname[0]);
	  cout<<"done"<<endl<<"removing extra elements in tree vector, currently size "<<myfile->t.size()<<"... ";
	  if(myfile->t.size()>1){
	    myfile->t.erase(myfile->t.begin());
	    myfile->tname.erase(myfile->tname.begin());
	  }
	  cout<<"done"<<endl;
	}
	if(runmode.Contains("hist")){
	  //create convenient strings
	  TString icutstring = Form("%d",icut);
	  TString hname = "h"+cistring+icutstring;
	  placeholder3 = mycut->name;
	  placeholder2 = mybranch->name;
	  placeholder = placeholder2 + " " + placeholder3;
	  TString htitle = placeholder;
	  //create histogram
	  int nBins = mybranch->nBins;
	  int loBin = mybranch->loBin;
	  int hiBin = mybranch->hiBin;
	  h[ci].push_back( new TH1F(hname,htitle,nBins,loBin,hiBin) );
	  //draw histogram
	  cout<<"drawing histogram "<<icut+1<<"/"<<nCuts<<"...";
	  while(icolor==0||icolor==5||icolor==10||(icolor>=17&&icolor<=19)) 
	    icolor++;//skip bad colors 
	  h[ci][icut]->SetLineColor(icolor);
	  placeholder = *thisbranch+">>"+hname;
	  myfile->t[0]->Draw(placeholder,*thiscut,drawopt);//there's only one tree per file
	  cout<<"done"<<endl;
	}
      }
      ci++;//iterates every time we finish a branch
    }
      
    if(runmode.Contains("hist")){
      cout<<"saving histograms... ";
      TString fileoutputlocation="./";
      if(myfile->quality["filetype"].Contains("data"))
	fileoutputlocation = "/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/data/";
      if(myfile->quality["filetype"].Contains("MC"))
	fileoutputlocation = "/afs/cern.ch/work/m/mwilkins/Lb2JpsiLtr/MC/withKScut/";
      placeholder = fileoutputlocation+"histos_"+myfile->name+"_c070116.root";
      cout<<endl<<"saving "<<placeholder<<"... ";
      TFile* histfile = new TFile(placeholder,"recreate");
      cout<<"done"<<endl<<"writing histograms... ";
      for(unsigned int i=(ifile*nBranches);i<h.size();i++){//since there's a canvas per branch
	for(unsigned int j=0;j<h[i].size();j++){
	  h[i][j]->Write();
	}
      }
      histfile->Close();
      delete histfile;
      cout<<"done"<<endl;
    }
  }
  
  gROOT->SetBatch(kFALSE);
  cout<<"done"<<endl;
}
コード例 #17
0
ファイル: sidebandSelection.C プロジェクト: apmorris/scripts
void sidebandSelection() {

    // -- define tuple file name, tuple name and cuts to apply
    // -- and also the name of the output file
    const std::string filename = "~/cern/ntuples/Lb2chicpK_2011_2012_signal_fixed.root";
    const std::string treename("MyTuple");

    // SIDEBAND
    /*  const std::string cuts = "m_b_DTF_jpsi_chic1_constr > 5.66 && m_b_DTF_jpsi_chic1_constr < 5.70 && dtf_b < 7 && dtf_b > 0 && c2ip_b < 25 && dls_b > 10 && c2ip_kminus > 4 && c2ip_pplus > 4 && minCl_gamma > 0.03 && m_chic > 3.4 && m_chic < 3.7 && trig_b_l0tos_tos == 1 && trig_b_l1tos_tos == 1 && trig_b_l2tos_tos == 1 && trgh_track[0] < 0.3 && trgh_track[1] < 0.3 && trgh_track[2] < 0.3 && trgh_track[3] < 0.3 && K_ProbNNk > 0.15 && minann_mu > 0.1" ;
      const std::string outFilename("~/cern/ntuples/sideband.root");
    */
    // SIGNAL
    const std::string cuts = "m_b_DTF_jpsi_chic1_constr > 5.61 && m_b_DTF_jpsi_chic1_constr < 5.63 && dtf_b < 7 && dtf_b > 0 && c2ip_b < 25 && dls_b > 10 && c2ip_kminus > 4 && c2ip_pplus > 4 && minCl_gamma > 0.03 && m_chic > 3.4 && m_chic < 3.7 && trig_b_l0tos_tos == 1 && trig_b_l1tos_tos == 1 && trig_b_l2tos_tos == 1 && trgh_track[0] < 0.3 && trgh_track[1] < 0.3 && trgh_track[2] < 0.3 && trgh_track[3] < 0.3 && K_ProbNNk > 0.15 && minann_mu > 0.1" ;
    const std::string outFilename("~/cern/ntuples/signal.root");



    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;

    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;

    // -- activate the branches you need

    tree->SetBranchStatus("*", 0);
    tree->SetBranchStatus("m_b_DTF_jpsi_chic1_constr",1);
    tree->SetBranchStatus("dtf_b",1);
    tree->SetBranchStatus("c2ip_b",1);
    tree->SetBranchStatus("dls_b",1);
    tree->SetBranchStatus("c2ip_kminus",1);
    tree->SetBranchStatus("c2ip_pplus",1);
    tree->SetBranchStatus("minCl_gamma",1);
    tree->SetBranchStatus("m_chic",1);
    tree->SetBranchStatus("trig_b_l0tos_tos",1);
    tree->SetBranchStatus("trig_b_l1tos_tos",1);
    tree->SetBranchStatus("trig_b_l2tos_tos",1);
    tree->SetBranchStatus("trgh_track",1);
    tree->SetBranchStatus("ann_kaon",1);
    tree->SetBranchStatus("K_ProbNNk",1);
    tree->SetBranchStatus("ann_proton",1);
    tree->SetBranchStatus("P_ProbNNp",1);
    tree->SetBranchStatus("ann_mu",1);
    tree->SetBranchStatus("minann_mu",1);
    tree->SetBranchStatus("m_chicp",1);
    tree->SetBranchStatus("m_pK",1);
    tree->SetBranchStatus("m_jpsi",1);

    // -- this file is just here to make the 'CopyTree' happy
    TFile* dummyFile = new TFile("~/cern/ntuples/dummy.root","RECREATE");
    TTree* rTree1 = tree->CopyTree( cuts.c_str() );

    float mass, mass_chicp, mass_pK, mass_jpsi, mass_chic, dtf_b, c2ip_b, dls_b, c2ip_kminus, c2ip_pplus, minCl_gamma, trgh_track, ann_kaon, K_ProbNNk, ann_proton, P_ProbNNp, ann_mu, minann_mu;

    float trig_b_l0tos_tos, trig_b_l1tos_tos, trig_b_l2tos_tos;

    rTree1->SetBranchAddress("m_b_DTF_jpsi_chic1_constr", &mass);
    rTree1->SetBranchAddress("m_chicp", &mass_chicp);
    rTree1->SetBranchAddress("m_pK", &mass_pK);
    rTree1->SetBranchAddress("m_jpsi", &mass_jpsi);
    rTree1->SetBranchAddress("m_chic", &mass_chic);
    rTree1->SetBranchAddress("dtf_b", &dtf_b);
    rTree1->SetBranchAddress("c2ip_b", &c2ip_b);
    rTree1->SetBranchAddress("dls_b", &dls_b);
    rTree1->SetBranchAddress("c2ip_kminus", &c2ip_kminus);
    rTree1->SetBranchAddress("c2ip_pplus", &c2ip_pplus);
    rTree1->SetBranchAddress("minCl_gamma", &minCl_gamma);
    rTree1->SetBranchAddress("trig_b_l0tos_tos", &trig_b_l0tos_tos);
    rTree1->SetBranchAddress("trig_b_l1tos_tos", &trig_b_l1tos_tos);
    rTree1->SetBranchAddress("trig_b_l2tos_tos", &trig_b_l2tos_tos);
    rTree1->SetBranchAddress("trgh_track", &trgh_track);
    rTree1->SetBranchAddress("ann_kaon", &ann_kaon);
    rTree1->SetBranchAddress("K_ProbNNk", &K_ProbNNk);
    rTree1->SetBranchAddress("ann_proton", &ann_proton);
    rTree1->SetBranchAddress("P_ProbNNp", &P_ProbNNp);
    rTree1->SetBranchAddress("ann_mu", &ann_mu);
    rTree1->SetBranchAddress("minann_mu", &minann_mu);


    TFile* rFile = new TFile( outFilename.c_str() ,"RECREATE");
    TTree* rTree2 = new TTree();
    //rTree2->SetName("sideband");
    rTree2->SetName("signal");
    rTree2->Branch("mass", &mass, "mass");
    rTree2->Branch("mass_chicp", &mass_chicp, "mass_chicp/F");
    rTree2->Branch("mass_pK", &mass_pK, "mass_pK/F");
    rTree2->Branch("mass_jpsi", &mass_jpsi, "mass_jpsi/F");
    rTree2->Branch("mass_chic", &mass_chic, "mass_chic/F");
    rTree2->Branch("dtf_b", &dtf_b, "dtf_b/F");
    rTree2->Branch("c2ip_b", &c2ip_b, "c2ip_b/F");
    rTree2->Branch("dls_b", &dls_b, "dls_b/F");
    rTree2->Branch("c2ip_kminus", &c2ip_kminus, "c2ip_kminus/F");
    rTree2->Branch("c2ip_pplus", &c2ip_pplus, "c2ip_pplus/F");
    rTree2->Branch("minCl_gamma", &minCl_gamma, "minCl_gamma/F");
    rTree2->Branch("trig_b_l0tos_tos", &trig_b_l0tos_tos, "trig_b_l0tos_tos/F");
    rTree2->Branch("trig_b_l1tos_tos", &trig_b_l1tos_tos, "trig_b_l1tos_tos/F");
    rTree2->Branch("trig_b_l2tos_tos", &trig_b_l2tos_tos, "trig_b_l2tos_tos/F");
    rTree2->Branch("trgh_track", &trgh_track, "trgh_track/F");
    rTree2->Branch("ann_kaon", &ann_kaon, "ann_kaon/F");
    rTree2->Branch("K_ProbNNk", &K_ProbNNk, "K_ProbNNk/F");
    rTree2->Branch("ann_proton", &ann_proton, "ann_proton/F");
    rTree2->Branch("P_ProbNNp", &P_ProbNNp, "P_ProbNNp/F");
    rTree2->Branch("ann_mu", &ann_mu, "ann_mu/F");
    rTree2->Branch("minann_mu", &minann_mu, "minann_mu/F");


    int percentCounter = 1;

    for(int i = 0; i < rTree1->GetEntries(); ++i) {

        const int percent = (int)(rTree1->GetEntries()/100.0);

        if( i == percent*percentCounter ) {
            //std::cout << percentCounter << " %" << std::endl;
            percentCounter++;
        }

        rTree1->GetEntry(i);
        rTree2->Fill();
        //std::cout << mass << std::endl;
    }
    rTree2->Print();
    rTree2->Write();
    rFile->Save();

}
コード例 #18
0
ファイル: newReduceTree.C プロジェクト: apmorris/project
void newReduceTree(){ 

    // -- define tuple file name, tuple name and cuts to apply
    // -- and also the name of the output file
    
    const std::string filename  =   "/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/Lb2chicpK_MC_2011_2012_signal_cut.root";//change
    const std::string treename  =   "DecayTree";
    const std::string cuts      =   "";
    const std::string outFile   =   "/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/reduced_Lb2chicpK_MC_2011_2012_signal.root");//change
  

    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;

    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;
  
    // -- activate the branches you need
  
    tree->SetBranchStatus("*", 0);
    
    tree->SetBranchStatus("chi_c_M",1);
    tree->SetBranchStatus("chi_c_P",1);
    tree->SetBranchStatus("chi_c_PE",1);      
    tree->SetBranchStatus("chi_c_PT",1);
    tree->SetBranchStatus("chi_c_PX",1);
    tree->SetBranchStatus("chi_c_PY",1);
    tree->SetBranchStatus("chi_c_PZ",1);
    tree->SetBranchStatus("chi_c_ETA",1);
    
    tree->SetBranchStatus("kaon_M",1);
    tree->SetBranchStatus("kaon_P",1);
    tree->SetBranchStatus("kaon_PE",1);
    tree->SetBranchStatus("kaon_PT",1);
    tree->SetBranchStatus("kaon_PX",1);
    tree->SetBranchStatus("kaon_PY",1);
    tree->SetBranchStatus("kaon_PZ",1);
    tree->SetBranchStatus("kaon_ETA",1);

    tree->SetBranchStatus("kaon_IPCHI2_OWNPV",1);
    tree->SetBranchStatus("kaon_TRACK_GhostProb",1);
    tree->SetBranchStatus("kaon_ProbNNp",1);
    tree->SetBranchStatus("kaon_ProbNNk",1);
    
    tree->SetBranchStatus("proton_M",1);
    tree->SetBranchStatus("proton_P",1);
    tree->SetBranchStatus("proton_PE",1);
    tree->SetBranchStatus("proton_PT",1);
    tree->SetBranchStatus("proton_PX",1);
    tree->SetBranchStatus("proton_PY",1);
    tree->SetBranchStatus("proton_PZ",1);
    tree->SetBranchStatus("proton_ETA",1);

    tree->SetBranchStatus("proton_IPCHI2_OWNPV",1);
    tree->SetBranchStatus("proton_TRACK_GhostProb",1);
    tree->SetBranchStatus("proton_ProbNNp",1);
    tree->SetBranchStatus("proton_ProbNNk",1);
    
    tree->SetBranchStatus("Jpsi_M",1);
    tree->SetBranchStatus("Jpsi_P",1);
    tree->SetBranchStatus("Jpsi_PE",1);
    tree->SetBranchStatus("Jpsi_PT",1);
    tree->SetBranchStatus("Jpsi_PX",1);
    tree->SetBranchStatus("Jpsi_PY",1);
    tree->SetBranchStatus("Jpsi_PZ",1);
    tree->SetBranchStatus("Jpsi_ETA",1);
    
    tree->SetBranchStatus("gamma_M",1);
    tree->SetBranchStatus("gamma_P",1);
    tree->SetBranchStatus("gamma_PE",1);
    tree->SetBranchStatus("gamma_PT",1);
    tree->SetBranchStatus("gamma_PX",1);
    tree->SetBranchStatus("gamma_PY",1);
    tree->SetBranchStatus("gamma_PZ",1);
    tree->SetBranchStatus("gamma_CL",1);
    tree->SetBranchStatus("gamma_ETA",1);
    
    tree->SetBranchStatus("muminus_M",1);
    tree->SetBranchStatus("muminus_P",1);
    tree->SetBranchStatus("muminus_PE",1);
    tree->SetBranchStatus("muminus_PT",1);
    tree->SetBranchStatus("muminus_PX",1);
    tree->SetBranchStatus("muminus_PY",1);
    tree->SetBranchStatus("muminus_PZ",1);
    tree->SetBranchStatus("muminus_ETA",1);
    tree->SetBranchStatus("muminus_ProbNNmu",1);
    tree->SetBranchStatus("muminus_TRACK_GhostProb",1); 
    
    tree->SetBranchStatus("muplus_M",1);
    tree->SetBranchStatus("muplus_P",1);
    tree->SetBranchStatus("muplus_PE",1);
    tree->SetBranchStatus("muplus_PT",1);
    tree->SetBranchStatus("muplus_PX",1);
    tree->SetBranchStatus("muplus_PY",1);
    tree->SetBranchStatus("muplus_PZ",1);
    tree->SetBranchStatus("muplus_ETA",1);
    tree->SetBranchStatus("muplus_ProbNNmu",1);
    tree->SetBranchStatus("muplus_TRACK_GhostProb",1);
    
    tree->SetBranchStatus("Lambda_b0_DTF_MASS_constr1",1);
    tree->SetBranchStatus("Lambda_b0_DTF_MASS_constr2",1);
    tree->SetBranchStatus("Lambda_b0_DTF_CHI2NDOF",1);
    tree->SetBranchStatus("Lambda_b0_IPCHI2_OWNPV",1);
    tree->SetBranchStatus("Lambda_b0_FDS",1);
    tree->SetBranchStatus("Lambda_b0_L0MuonDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_L0DiMuonDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt1DiMuonHighMassDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt1DiMuonLowMassDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt1TrackMuonDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt1TrackAllL0Decision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt2DiMuonDetachedDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS",1);
    tree->SetBranchStatus("Lambda_b0_pi0veto",1);
    tree->SetBranchStatus("Lambda_b0_PT",1);
    
    
    //for MC only                                                                   //
    tree->SetBranchStatus("chi_c_BKGCAT",1);                                        //
    tree->SetBranchStatus("Jpsi_BKGCAT",1);                                         //
    tree->SetBranchStatus("Lambda_b0_BKGCAT",1);                                    //
    
   
    
    // -- this file is just here to make the 'CopyTree' happy
    TFile* dummyFile = new TFile("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/dummy.root","RECREATE");
    TTree* rTree1 = tree->CopyTree(cuts.c_str());




    double chi_c_M,     chi_c_P,    chi_c_PE,   chi_c_PT,   chi_c_PX,   chi_c_PY,   chi_c_PZ,   chi_c_ETA;
    double kaon_M,      kaon_P,     kaon_PE,    kaon_PX,    kaon_PT,    kaon_PY,    kaon_PZ,    kaon_ETA;
    double proton_M,    proton_P,   proton_PE,  proton_PT,  proton_PX,  proton_PY,  proton_PZ,  proton_ETA;
    double Jpsi_M,      Jpsi_P,     Jpsi_PE,    Jpsi_PT,    Jpsi_PX,    Jpsi_PY,    Jpsi_PZ,    Jpsi_ETA;
    double gamma_M,     gamma_P,    gamma_PE,   gamma_PT,   gamma_PX,   gamma_PY,   gamma_PZ,   gamma_ETA,      gamma_CL;
    double muminus_M,   muminus_P,  muminus_PE, muminus_PT, muminus_PX, muminus_PY, muminus_PZ, muminus_ETA,    muminus_ProbNNmu,   muminus_TRACK_GhostProb;
    double muplus_M,    muplus_P,   muplus_PE,  muplus_PT,  muplus_PX,  muplus_PY,  muplus_PZ,  muplus_ETA,     muplus_ProbNNmu,    muplus_TRACK_GhostProb;
    
    double kaon_IPCHI2_OWNPV,       kaon_TRACK_GhostProb,   kaon_ProbNNp,   kaon_ProbNNk;
    double proton_IPCHI2_OWNPV,     proton_TRACK_GhostProb, proton_ProbNNp, proton_ProbNNk;
    
    double Lambda_b0_DTF_MASS_constr1, Lambda_b0_DTF_MASS_constr2, Lambda_b0_DTF_CHI2NDOF, Lambda_b0_IPCHI2_OWNPV;
    double Lambda_b0_FDS, Lambda_b0_pi0veto, Lambda_b0_PT; 
    
    bool Lambda_b0_L0MuonDecision_TOS,                  Lambda_b0_L0DiMuonDecision_TOS;
    bool Lambda_b0_Hlt1DiMuonHighMassDecision_TOS,      Lambda_b0_Hlt1DiMuonLowMassDecision_TOS;
    bool Lambda_b0_Hlt1TrackMuonDecision_TOS,           Lambda_b0_Hlt1TrackAllL0Decision_TOS;
    bool Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS,    Lambda_b0_Hlt2DiMuonDetachedDecision_TOS; 
    bool Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS, Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS;
    
    
    rTree1->SetBranchAddress("chi_c_M",     &chi_c_M);
    rTree1->SetBranchAddress("chi_c_P",     &chi_c_P);
    rTree1->SetBranchAddress("chi_c_PE",    &chi_c_PE);
    rTree1->SetBranchAddress("chi_c_PT",    &chi_c_PT);
    rTree1->SetBranchAddress("chi_c_PX",    &chi_c_PX);
    rTree1->SetBranchAddress("chi_c_PY",    &chi_c_PY);
    rTree1->SetBranchAddress("chi_c_PZ",    &chi_c_PZ);
    rTree1->SetBranchAddress("chi_c_ETA",   &chi_c_ETA);
    
    rTree1->SetBranchAddress("kaon_M",      &kaon_M);
    rTree1->SetBranchAddress("kaon_P",      &kaon_P);
    rTree1->SetBranchAddress("kaon_PE",     &kaon_PE);
    rTree1->SetBranchAddress("kaon_PX",     &kaon_PX);
    rTree1->SetBranchAddress("kaon_PT",     &kaon_PT);
    rTree1->SetBranchAddress("kaon_PY",     &kaon_PY);
    rTree1->SetBranchAddress("kaon_PZ",     &kaon_PZ);
    rTree1->SetBranchAddress("kaon_ETA",    &kaon_ETA);

    rTree1->SetBranchAddress("kaon_IPCHI2_OWNPV",       &kaon_IPCHI2_OWNPV);
    rTree1->SetBranchAddress("kaon_TRACK_GhostProb",    &kaon_TRACK_GhostProb);
    rTree1->SetBranchAddress("kaon_ProbNNp",            &kaon_ProbNNp);
    rTree1->SetBranchAddress("kaon_ProbNNk",            &kaon_ProbNNk);
    
    rTree1->SetBranchAddress("proton_M",    &proton_M);
    rTree1->SetBranchAddress("proton_P",    &proton_P);
    rTree1->SetBranchAddress("proton_PE",   &proton_PE);
    rTree1->SetBranchAddress("proton_PT",   &proton_PT);
    rTree1->SetBranchAddress("proton_PX",   &proton_PX);
    rTree1->SetBranchAddress("proton_PY",   &proton_PY);
    rTree1->SetBranchAddress("proton_PZ",   &proton_PZ);
    rTree1->SetBranchAddress("proton_ETA",  &proton_ETA);

    rTree1->SetBranchAddress("proton_IPCHI2_OWNPV",     &proton_IPCHI2_OWNPV);
    rTree1->SetBranchAddress("proton_TRACK_GhostProb",  &proton_TRACK_GhostProb);
    rTree1->SetBranchAddress("proton_ProbNNp",          &proton_ProbNNp);
    rTree1->SetBranchAddress("proton_ProbNNk",          &proton_ProbNNk);

    rTree1->SetBranchAddress("Jpsi_M",      &Jpsi_M);
    rTree1->SetBranchAddress("Jpsi_P",      &Jpsi_P);
    rTree1->SetBranchAddress("Jpsi_PE",     &Jpsi_PE);
    rTree1->SetBranchAddress("Jpsi_PT",     &Jpsi_PT);
    rTree1->SetBranchAddress("Jpsi_PX",     &Jpsi_PX);
    rTree1->SetBranchAddress("Jpsi_PY",     &Jpsi_PY);
    rTree1->SetBranchAddress("Jpsi_PZ",     &Jpsi_PZ);
    rTree1->SetBranchAddress("Jpsi_ETA",    &Jpsi_ETA);
  
    rTree1->SetBranchAddress("gamma_M",     &gamma_M);
    rTree1->SetBranchAddress("gamma_P",     &gamma_P);
    rTree1->SetBranchAddress("gamma_PE",    &gamma_PE);
    rTree1->SetBranchAddress("gamma_PT",    &gamma_PT);
    rTree1->SetBranchAddress("gamma_PX",    &gamma_PX);
    rTree1->SetBranchAddress("gamma_PY",    &gamma_PY);
    rTree1->SetBranchAddress("gamma_PZ",    &gamma_PZ);
    rTree1->SetBranchAddress("gamma_ETA",   &gamma_ETA);
    rTree1->SetBranchAddress("gamma_CL",    &gamma_CL);  

    rTree1->SetBranchAddress("muminus_M",   &muminus_M);
    rTree1->SetBranchAddress("muminus_P",   &muminus_P);
    rTree1->SetBranchAddress("muminus_PE",  &muminus_PE); 
    rTree1->SetBranchAddress("muminus_PT",  &muminus_PT);
    rTree1->SetBranchAddress("muminus_PX",  &muminus_PX);
    rTree1->SetBranchAddress("muminus_PY",  &muminus_PY);
    rTree1->SetBranchAddress("muminus_PZ",  &muminus_PZ);
    rTree1->SetBranchAddress("muminus_ETA", &muminus_ETA);

    rTree1->SetBranchAddress("muminus_ProbNNmu",        &muminus_ProbNNmu);  
    rTree1->SetBranchAddress("muminus_TRACK_GhostProb", &muminus_TRACK_GhostProb);  

    rTree1->SetBranchAddress("muplus_M",    &muplus_M);
    rTree1->SetBranchAddress("muplus_P",    &muplus_P);
    rTree1->SetBranchAddress("muplus_PE",   &muplus_PE);
    rTree1->SetBranchAddress("muplus_PT",   &muplus_PT);
    rTree1->SetBranchAddress("muplus_PX",   &muplus_PX);
    rTree1->SetBranchAddress("muplus_PY",   &muplus_PY);
    rTree1->SetBranchAddress("muplus_PZ",   &muplus_PZ);
    rTree1->SetBranchAddress("muplus_ETA",  &muplus_ETA);

    rTree1->SetBranchAddress("muplus_ProbNNmu",         &muplus_ProbNNmu);  
    rTree1->SetBranchAddress("muplus_TRACK_GhostProb",  &muplus_TRACK_GhostProb);  

    rTree1->SetBranchAddress("Lambda_b0_DTF_MASS_constr1",                      &Lambda_b0_DTF_MASS_constr1);
    rTree1->SetBranchAddress("Lambda_b0_DTF_MASS_constr2",                      &Lambda_b0_DTF_MASS_constr2);
    rTree1->SetBranchAddress("Lambda_b0_DTF_CHI2NDOF",                          &Lambda_b0_DTF_CHI2NDOF);
    rTree1->SetBranchAddress("Lambda_b0_IPCHI2_OWNPV",                          &Lambda_b0_IPCHI2_OWNPV);
    rTree1->SetBranchAddress("Lambda_b0_L0DiMuonDecision_TOS",                  &Lambda_b0_L0DiMuonDecision_TOS);
    rTree1->SetBranchAddress("Lambda_b0_L0MuonDecision_TOS",                    &Lambda_b0_L0MuonDecision_TOS);
    rTree1->SetBranchAddress("Lambda_b0_FDS",                                   &Lambda_b0_FDS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt1DiMuonHighMassDecision_TOS",        &Lambda_b0_Hlt1DiMuonHighMassDecision_TOS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt1DiMuonLowMassDecision_TOS",         &Lambda_b0_Hlt1DiMuonLowMassDecision_TOS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt1TrackMuonDecision_TOS",             &Lambda_b0_Hlt1TrackMuonDecision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt1TrackAllL0Decision_TOS",            &Lambda_b0_Hlt1TrackAllL0Decision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS",      &Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt2DiMuonDetachedDecision_TOS",        &Lambda_b0_Hlt2DiMuonDetachedDecision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS",    &Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS",   &Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS);
    rTree1->SetBranchAddress("Lambda_b0_pi0veto",                               &Lambda_b0_pi0veto);
    rTree1->SetBranchAddress("Lambda_b0_PT",                                    &Lambda_b0_PT);

    
    //for MC only                                                                   //
    int chi_c_BKGCAT, Jpsi_BKGCAT, Lambda_b0_BKGCAT;                                //
    rTree1->SetBranchAddress("chi_c_BKGCAT",        &chi_c_BKGCAT);                 //
    rTree1->SetBranchAddress("Jpsi_BKGCAT",         &Jpsi_BKGCAT);                  //
    rTree1->SetBranchAddress("Lambda_b0_BKGCAT",    &Lambda_b0_BKGCAT);             //
    
    
    TFile* rFile = new TFile( outFile.c_str() ,"RECREATE");
    TTree* rTree2 = new TTree();
    rTree2->SetName("DecayTree");
    
    rTree2->Branch("chi_c_M",   &chi_c_M,   "chi_c_M/D");
    rTree2->Branch("chi_c_P",   &chi_c_P,   "chi_c_P/D");
    rTree2->Branch("chi_c_PE",  &chi_c_PE,  "chi_c_PE/D");
    rTree2->Branch("chi_c_PT",  &chi_c_PT,  "chi_c_PT/D");
    rTree2->Branch("chi_c_PX",  &chi_c_PX,  "chi_c_PX/D");
    rTree2->Branch("chi_c_PY",  &chi_c_PY,  "chi_c_PY/D");
    rTree2->Branch("chi_c_PZ",  &chi_c_PZ,  "chi_c_PZ/D");
    rTree2->Branch("chi_c_ETA", &chi_c_ETA, "chi_c_ETA/D");

    rTree2->Branch("kaon_M",    &kaon_M,    "kaon_M/D");
    rTree2->Branch("kaon_P",    &kaon_P,    "kaon_P/D");
    rTree2->Branch("kaon_PE",   &kaon_PE,   "kaon_PE/D");
    rTree2->Branch("kaon_PX",   &kaon_PX,   "kaon_PX/D");
    rTree2->Branch("kaon_PT",   &kaon_PT,   "kaon_PT/D");
    rTree2->Branch("kaon_PY",   &kaon_PY,   "kaon_PY/D");
    rTree2->Branch("kaon_PZ",   &kaon_PZ,   "kaon_PZ/D");
    rTree2->Branch("kaon_ETA",  &kaon_ETA,  "kaon_ETA/D");

    rTree2->Branch("kaon_IPCHI2_OWNPV",     &kaon_IPCHI2_OWNPV,     "kaon_IPCHI2_OWNPV/D");
    rTree2->Branch("kaon_TRACK_GhostProb",  &kaon_TRACK_GhostProb,  "kaon_TRACK_GhostProb/D");
    rTree2->Branch("kaon_ProbNNp",          &kaon_ProbNNp,          "kaon_ProbNNp/D");
    rTree2->Branch("kaon_ProbNNk",          &kaon_ProbNNk,          "kaon_ProbNNk/D");
    
    rTree2->Branch("proton_M",      &proton_M,      "proton_M/D");
    rTree2->Branch("proton_P",      &proton_P,      "proton_P/D");
    rTree2->Branch("proton_PE",     &proton_PE,     "proton_PE/D");
    rTree2->Branch("proton_PT",     &proton_PT,     "proton_PT/D");
    rTree2->Branch("proton_PX",     &proton_PX,     "proton_PX/D");
    rTree2->Branch("proton_PY",     &proton_PY,     "proton_PY/D");
    rTree2->Branch("proton_PZ",     &proton_PZ,     "proton_PZ/D");
    rTree2->Branch("proton_ETA",    &proton_ETA,    "proton_ETA/D");

    rTree2->Branch("proton_IPCHI2_OWNPV",       &proton_IPCHI2_OWNPV,       "proton_IPCHI2_OWNPV/D");
    rTree2->Branch("proton_TRACK_GhostProb",    &proton_TRACK_GhostProb,    "proton_TRACK_GhostProb/D");
    rTree2->Branch("proton_ProbNNp",            &proton_ProbNNp,            "proton_ProbNNp/D");
    rTree2->Branch("proton_ProbNNk",            &proton_ProbNNk,            "proton_ProbNNk/D");

    rTree2->Branch("Jpsi_M",    &Jpsi_M,    "Jpsi_M/D");
    rTree2->Branch("Jpsi_P",    &Jpsi_P,    "Jpsi_P/D");
    rTree2->Branch("Jpsi_PE",   &Jpsi_PE,   "Jpsi_PE/D");
    rTree2->Branch("Jpsi_PT",   &Jpsi_PT,   "Jpsi_PT/D");
    rTree2->Branch("Jpsi_PX",   &Jpsi_PX,   "Jpsi_PX/D");
    rTree2->Branch("Jpsi_PY",   &Jpsi_PY,   "Jpsi_PY/D");
    rTree2->Branch("Jpsi_PZ",   &Jpsi_PZ,   "Jpsi_PZ/D");
    rTree2->Branch("Jpsi_ETA",  &Jpsi_ETA,  "Jpsi_ETA/D");
  
    rTree2->Branch("gamma_M",   &gamma_M,   "gamma_M/D");
    rTree2->Branch("gamma_P",   &gamma_P,   "gamma_P/D");
    rTree2->Branch("gamma_PE",  &gamma_PE,  "gamma_PE/D");
    rTree2->Branch("gamma_PT",  &gamma_PT,  "gamma_PT/D");
    rTree2->Branch("gamma_PX",  &gamma_PX,  "gamma_PX/D");
    rTree2->Branch("gamma_PY",  &gamma_PY,  "gamma_PY/D");
    rTree2->Branch("gamma_PZ",  &gamma_PZ,  "gamma_PZ/D");
    rTree2->Branch("gamma_ETA", &gamma_ETA, "gamma_ETA/D");
    rTree2->Branch("gamma_CL",  &gamma_CL,  "gamma_CL/D");  

    rTree2->Branch("muminus_M",     &muminus_M,     "muminus_M/D");
    rTree2->Branch("muminus_P",     &muminus_P,     "muminus_P/D");
    rTree2->Branch("muminus_PE",    &muminus_PE,    "muminus_PE/D"); 
    rTree2->Branch("muminus_PT",    &muminus_PT,    "muminus_PT/D");
    rTree2->Branch("muminus_PX",    &muminus_PX,    "muminus_PX/D");
    rTree2->Branch("muminus_PY",    &muminus_PY,    "muminus_PY/D");
    rTree2->Branch("muminus_PZ",    &muminus_PZ,    "muminus_PZ/D");  
    rTree2->Branch("muminus_ETA",   &muminus_ETA,   "muminus_ETA/D");

    rTree2->Branch("muminus_ProbNNmu",          &muminus_ProbNNmu,          "muminus_ProbNNmu/D");  
    rTree2->Branch("muminus_TRACK_GhostProb",   &muminus_TRACK_GhostProb,   "muminus_TRACK_GhostProb/D");  

    rTree2->Branch("muplus_M",      &muplus_M,      "muplus_M/D");
    rTree2->Branch("muplus_P",      &muplus_P,      "muplus_P/D");
    rTree2->Branch("muplus_PE",     &muplus_PE,     "muplus_PE/D");
    rTree2->Branch("muplus_PT",     &muplus_PT,     "muplus_PT/D");
    rTree2->Branch("muplus_PX",     &muplus_PX,     "muplus_PX/D");
    rTree2->Branch("muplus_PY",     &muplus_PY,     "muplus_PY/D");
    rTree2->Branch("muplus_PZ",     &muplus_PZ,     "muplus_PZ/D");
    rTree2->Branch("muplus_ETA",    &muplus_ETA,    "muplus_ETA/D");

    rTree2->Branch("muplus_ProbNNmu",           &muplus_ProbNNmu,           "muplus_ProbNNmu/D");  
    rTree2->Branch("muplus_TRACK_GhostProb",    &muplus_TRACK_GhostProb,    "muplus_TRACK_GhostProb/D");  

    rTree2->Branch("Lambda_b0_DTF_MASS_constr1",    &Lambda_b0_DTF_MASS_constr1,    "Lambda_b0_DTF_MASS_constr1/D");
    rTree2->Branch("Lambda_b0_DTF_MASS_constr2",    &Lambda_b0_DTF_MASS_constr2,    "Lambda_b0_DTF_MASS_constr2/D");
    rTree2->Branch("Lambda_b0_DTF_CHI2NDOF",        &Lambda_b0_DTF_CHI2NDOF,        "Lambda_b0_DTF_CHI2NDOF/D");
    rTree2->Branch("Lambda_b0_IPCHI2_OWNPV",        &Lambda_b0_IPCHI2_OWNPV,        "Lambda_b0_IPCHI2_OWNPV/D");
    rTree2->Branch("Lambda_b0_L0DiMuonDecision_TOS",&Lambda_b0_L0DiMuonDecision_TOS,"Lambda_b0_L0DiMuonDecision_TOS/B");
    rTree2->Branch("Lambda_b0_L0MuonDecision_TOS",  &Lambda_b0_L0MuonDecision_TOS,  "Lambda_b0_L0MuonDecision_TOS/B");
    rTree2->Branch("Lambda_b0_FDS",                 &Lambda_b0_FDS,                 "Lambda_b0_FDS/D");  
    
    rTree2->Branch("Lambda_b0_Hlt1DiMuonHighMassDecision_TOS",      &Lambda_b0_Hlt1DiMuonHighMassDecision_TOS,      "Lambda_b0_Hlt1DiMuonHighMassDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt1DiMuonLowMassDecision_TOS",       &Lambda_b0_Hlt1DiMuonLowMassDecision_TOS,       "Lambda_b0_Hlt1DiMuonLowMassDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt1TrackMuonDecision_TOS",           &Lambda_b0_Hlt1TrackMuonDecision_TOS,           "Lambda_b0_Hlt1TrackMuonDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt1TrackAllL0Decision_TOS",          &Lambda_b0_Hlt1TrackAllL0Decision_TOS,          "Lambda_b0_Hlt1TrackAllL0Decision_TOS/B");
    rTree2->Branch("Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS",    &Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS,    "Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt2DiMuonDetachedDecision_TOS",      &Lambda_b0_Hlt2DiMuonDetachedDecision_TOS,      "Lambda_b0_Hlt2DiMuonDetachedDecision_TOS/B"); 
    rTree2->Branch("Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS",  &Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS,  "Lambda_b0_Hlt2DiMuonDetachedJPsiDecision_TOS/B");
    rTree2->Branch("Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS", &Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS, "Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS/B");
    
    rTree2->Branch("Lambda_b0_pi0veto", &Lambda_b0_pi0veto, "Lambda_b0_pi0veto/D");
    rTree2->Branch("Lambda_b0_PT",      &Lambda_b0_PT,      "Lambda_b0_PT/D");
                            
                                              
    //for MC only                                                                   //
    rTree2->Branch("chi_c_BKGCAT",      &chi_c_BKGCAT,      "chi_c_BKGCAT/I");      //
    rTree2->Branch("Jpsi_BKGCAT",       &Jpsi_BKGCAT,       "Jpsi_BKGCAT/I");       //
    rTree2->Branch("Lambda_b0_BKGCAT",  &Lambda_b0_BKGCAT,  "Lambda_b0_BKGCAT/I");  //
    
    
//-----------------------------------------------------------------------------------    
    
	const double mK(493.677);
    const double mpi(139.57);
    const double mp(938.27);
    
    double m_pK, m_chicp;
    double proton_as_kaon_M,        proton_as_pion_M,           proton_as_proton_M;
    double m_chicpK_proton_as_kaon, m_chicpK_proton_as_pion,    m_chicpK_proton_as_proton; 
    double m_JpsipK;
    
    rTree2->Branch("m_JpsipK",  &m_JpsipK,  "m_JpsipK/D");
	rTree2->Branch("m_chicp",   &m_chicp,   "m_chicp/D");
    rTree2->Branch("m_pK",      &m_pK,      "m_pK/D");
    
    rTree2->Branch("proton_as_kaon_M",      &proton_as_kaon_M,      "proton_as_kaon_M/D");
    rTree2->Branch("proton_as_pion_M",      &proton_as_pion_M,      "proton_as_pion_M/D");
    rTree2->Branch("proton_as_proton_M",    &proton_as_proton_M,    "proton_as_proton_M/D");
    
    rTree2->Branch("m_chicpK_proton_as_kaon",     &m_chicpK_proton_as_kaon,     "m_chicpK_proton_as_kaon/D");
    rTree2->Branch("m_chicpK_proton_as_pion",     &m_chicpK_proton_as_pion,     "m_chicpK_proton_as_pion/D");
    rTree2->Branch("m_chicpK_proton_as_proton",   &m_chicpK_proton_as_proton,   "m_chicpK_proton_as_proton/D");
	
    int percentCounter = 1;

    for(int i = 0; i < rTree1->GetEntries(); ++i){
  
      const int percent = (int)(rTree1->GetEntries()/100.0);
    
      if( i == percent*percentCounter ){
        std::cout << percentCounter << " %" << std::endl;
        percentCounter++;
      }
      
      rTree1->GetEntry(i);
      
      double proton_P = sqrt(proton_PX*proton_PX + proton_PY*proton_PY + proton_PZ*proton_PZ) ;
      
      TLorentzVector proton_as_kaon(    proton_PX,  proton_PY,  proton_PZ,  sqrt(proton_P*proton_P + mK*mK));
      TLorentzVector proton_as_pion(    proton_PX,  proton_PY,  proton_PZ,  sqrt(proton_P*proton_P + mpi*mpi));
      TLorentzVector proton_as_proton(  proton_PX,  proton_PY,  proton_PZ,  sqrt(proton_P*proton_P + proton_M*proton_M));
      
      TLorentzVector kaon(  kaon_PX,    kaon_PY,    kaon_PZ,    kaon_PE);
      TLorentzVector chic(  chi_c_PX,   chi_c_PY,   chi_c_PZ,   chi_c_PE);
      TLorentzVector proton(proton_PX,  proton_PY,  proton_PZ,  proton_PE);
      TLorentzVector Jpsi(  Jpsi_PX,    Jpsi_PY,    Jpsi_PZ,    Jpsi_PE);
      
      proton_as_kaon_M            = proton_as_kaon.M();
      proton_as_pion_M            = proton_as_pion.M();
      proton_as_proton_M          = proton_as_proton.M();
        
      TLorentzVector chic_PasK_K  = chic + kaon + proton_as_kaon;
      TLorentzVector chic_PasPi_K = chic + kaon + proton_as_pion;
      TLorentzVector chic_PasP_K  = chic + kaon + proton_as_proton;
        
      m_chicpK_proton_as_kaon     = chic_PasK_K.M();
      m_chicpK_proton_as_pion     = chic_PasPi_K.M();
      m_chicpK_proton_as_proton   = chic_PasP_K.M();
      
      TLorentzVector JpsipK       = Jpsi   + proton + kaon;
      TLorentzVector chicp        = chic   + proton;
      TLorentzVector pK           = proton + kaon;
      
      m_JpsipK  = JpsipK.M();  
      m_chicp   = chicp.M();
      m_pK      = pK.M();
        
      rTree2->Fill();
         
    
    }
    
    rTree2->Print();
    rTree2->Write();
    rFile->Save();

}
コード例 #19
0
vector<float*> simFit(
		      const string tnp_      = "elecTnP",
		      const string category_ = "elecID80",
		      double cutValue_       = 0.5,
		      const string bin_      = "abseta>1.5",
		      const float binCenter_ = 0.75,
		      const float binWidth_  = 0.75,
		      const float xLow_      = 40,
		      const float xHigh_     = 120,
		      const float nBins_     = 24,
		      bool doBinned_         = true,
		      float deltaAlpha_      = 0.0,
		      float deltaN_          = 0.0,
		      float scale_           = 0.0
		      )
  
{


  vector<float*> out;

  TFile fSgn("../prod/ElecTnP/treeElecTnP_DYJets-50-madgraph-PUS4-TnP.root");
  TTree *fullTreeSgn  = (TTree*)fSgn.Get((tnp_+"/fitter_tree").c_str());
  fSgn.cd("allEventsFilter");
  TH1F* totalEventsSgn = (TH1F*)gDirectory->Get("totalEvents");
  float readEventsSgn = totalEventsSgn->GetBinContent(1);

  // data
  TFile fdat("../prod/ElecTnP/treeElecTnP_DYJets-50-madgraph-PUS4-TnP.root");
  TTree *fullTreeData = (TTree*)fdat.Get((tnp_+"/fitter_tree").c_str());
  
  TH1F* hS           = new TH1F("hS","",1,0,150);
  TH1F* hSP          = new TH1F("hSP","",1,0,150);
  
  fullTreeSgn->Draw("mass>>hS",Form("tag_puMCWeight*(%s && mass>%f && mass<%f && mcTrue && tag_genDecay==23*11 && tag_pfRelIso<0.1 && pair_tnpCharge==0 && event_met_pfmet<25 && tag_pt>35)",bin_.c_str(),xLow_,xHigh_));
  float SGNtrue = hS->Integral();
  fullTreeSgn->Draw("mass>>hSP",Form("tag_puMCWeight*(%s && %s>=%f && mass>%f && mass<%f && mcTrue && tag_genDecay==23*11 && tag_pfRelIso<0.1 && pair_tnpCharge==0 && event_met_pfmet<25 && tag_pt>35)",bin_.c_str(),category_.c_str(),cutValue_,xLow_,xHigh_));
  float SGNtruePass = hSP->Integral();

  float McTruthEff    = SGNtruePass/SGNtrue;
  float BinomialError = TMath::Sqrt(SGNtruePass/SGNtrue*(1-SGNtruePass/SGNtrue)/SGNtrue);
  
  cout << bin_.c_str() << " ==> MCTRUTH: " << McTruthEff << " +/- " << BinomialError << endl;

  delete hS; delete hSP;

  // file to copy the trees
  TFile *templFile = new TFile(Form("dummyTempl_bin%.2f.root",binCenter_),"RECREATE");
  
  TTree* fullTreeSgnCutP = fullTreeSgn->CopyTree( Form("(%s>=%f && %s && pair_tnpCharge==0 && event_met_pfmet<25 && mcTrue && tag_genDecay==23*11 && tag_pfRelIso<0.1 && tag_pt>35)",category_.c_str(),cutValue_,bin_.c_str()) );
  TTree* fullTreeSgnCutF = fullTreeSgn->CopyTree( Form("(%s< %f && %s && pair_tnpCharge==0 && event_met_pfmet<25 && mcTrue && tag_genDecay==23*11 && tag_pfRelIso<0.1 && tag_pt>35)",category_.c_str(),cutValue_,bin_.c_str()) );
  
  RooRealVar mass("mass","m_{tp} (GeV/c^{2})",xLow_,xHigh_);
  mass.setBins( 10000, "fft" );
  mass.setBins( nBins_ );

  RooRealVar meanBkgP("meanBkgP","",59,30,100);
  RooRealVar sigmaBkgP("sigmaBkgP","",11,0,50);
  //RooLandau bkgPdfP("bkgPdfP","",mass,meanBkgP,sigmaBkgP);

  RooRealVar DataCP("DataCP","",0);
  RooExponential bkgPdfP("bkgPdfP","",mass,DataCP);

  RooRealVar meanBkgF("meanBkgF","",59,30,100);
  RooRealVar sigmaBkgF("sigmaBkgF","",11,0,50);
  //RooLandau bkgPdfF("bkgPdfF","",mass,meanBkgF,sigmaBkgF);

  RooRealVar DataCF("DataCF","",0,-10,10);
  RooExponential bkgPdfF("bkgPdfF","",mass,DataCF);

  TCanvas *c0 = new TCanvas("fitCanvas","canvas",10,30,650,600);
  c0->SetGrid(0,0);
  c0->SetFillStyle(4000);
  c0->SetFillColor(10);
  c0->SetTicky();
  c0->SetObjectStat(0);

  mass.setBins( 50 );

  /////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////// 
  // passing:

  RooDataSet sgnDataSetP("sgnDataSetP","dataset for signal", RooArgSet(mass), Import( *fullTreeSgnCutP ) );
  RooDataHist sgnDataHistP("sgnDataHistP","",RooArgSet(mass),sgnDataSetP, 1.0);
  //RooHistPdf  sgnTemplatePdfP("sgnTemplatePdfP","",RooArgSet(mass),sgnDataHistP);
  RooKeysPdf sgnTemplatePdfP("sgnTemplatePdfP","",mass,sgnDataSetP);

  // Breit-Wigner
  RooRealVar meanSgnP("meanSgnP","mean",91.19,85,100);
  RooRealVar widthSgnP("widthSgnP","width",2.49,0.,10);
  RooBreitWigner bwSgnP("bwSgnP","bw",mass,meanSgnP,widthSgnP);

  // Crystall Ball
  RooRealVar m1SgnP("m1SgnP","m1",0,-20,20);
  RooRealVar sigmaSgnP("sigmaSgnP","sigma",0.5,0,20);
  RooRealVar alfaSgnP("alfaSgnP","alfa", 0.5,-10,10);
  RooRealVar nSgnP("nSgnP","n", 1,1e-06,50);
  RooCBShape cbSgnP("cbSgnP","",mass,m1SgnP,sigmaSgnP,alfaSgnP,nSgnP);

  mass.setBins( 1000 , "fft");
  // BW (X) CB
  RooFFTConvPdf bvcbSgnP("bvcbSgnP","",mass,bwSgnP, cbSgnP);

  RooFitResult* ResSgnFitP = bvcbSgnP.fitTo(sgnDataSetP, Minos(1), Save(1), NumCPU(4) );
  RooArgSet FitParamSgnP(ResSgnFitP->floatParsFinal());
  RooRealVar* m1SgnFitP    = (RooRealVar*)(&FitParamSgnP["m1SgnP"]);
  RooRealVar* sigmaSgnFitP = (RooRealVar*)(&FitParamSgnP["sigmaSgnP"]);
  RooRealVar* alfaSgnFitP  = (RooRealVar*)(&FitParamSgnP["alfaSgnP"]);
  RooRealVar* nSgnFitP     = (RooRealVar*)(&FitParamSgnP["nSgnP"]);
  RooRealVar* nMeanSgnFitP = (RooRealVar*)(&FitParamSgnP["meanSgnP"]);
  RooRealVar* nWidthSgnFitP= (RooRealVar*)(&FitParamSgnP["widthSgnP"]);

  RooRealVar m1SgnP_C("m1SgnP_C","m1",m1SgnFitP->getVal(),-10,10);
  RooRealVar sigmaSgnP_C("sigmaSgnP_C","sigma",sigmaSgnFitP->getVal(),0,20);
  // choose to let it float or not
  
  RooRealVar meanSgnP_C("meanSgnP_C","mean",  nMeanSgnFitP->getVal() ,80,120);
  RooRealVar widthSgnP_C("widthSgnP_C","width",nWidthSgnFitP->getVal() /*,0.,10*/);

  RooRealVar alfaSgnP_C("alfaSgnP_C","alfa",alfaSgnFitP->getVal()*(1+deltaAlpha_)/*,0,20*/);
  RooRealVar nSgnP_C("nSgnP_C","n",nSgnFitP->getVal()*(1+deltaN_)/*,0,50*/);

  RooCBShape cbSgnP_C("cbSgnP_C","",mass,m1SgnP_C,sigmaSgnP_C,alfaSgnP_C,nSgnP_C);
  
  RooLognormal alfaSgnP_CPdf("alfaSgnP_CPdf","",alfaSgnP_C,RooConst(alfaSgnFitP->getVal()),RooConst(1.5));
  RooLognormal nSgnP_CPdf("nSgnP_CPdf","",nSgnP_C,RooConst(nSgnFitP->getVal()),            RooConst(1.5));

  RooLognormal meanSgnP_CPdf("meanSgnP_CPdf","",meanSgnP_C,RooConst(nMeanSgnFitP->getVal()),RooConst(1.5));
  RooLognormal widthSgnP_CPdf("widthSgnP_CPdf","",widthSgnP_C,RooConst(nWidthSgnFitP->getVal()),RooConst(1.5));

  // fitted BW (X) CB
  RooBreitWigner bwSgnP_C("bwSgnP_C","bw",mass,meanSgnP_C,widthSgnP_C);
  RooFFTConvPdf sgnPdfP("sgnPdfP","",mass,bwSgnP_C, cbSgnP_C);


  RooRealVar sgnMeanResP("sgnMeanResP","",0,-10,10);
  RooRealVar sgnSigmaResP("sgnSigmaResP","",0.5,0,10);
  RooGaussian resolModP("sgnResolModP","",mass,sgnMeanResP,sgnSigmaResP);

  mass.setBins(nBins_);
  //return;

  /////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////// 
  // failing:
  RooDataSet sgnDataSetF("sgnDataSetF","dataset for signal", RooArgSet(mass), Import( *fullTreeSgnCutF ) );
  RooDataHist sgnDataHistF("sgnDataHistF","",RooArgSet(mass),sgnDataSetF, 1.0);
  //RooHistPdf  sgnTemplatePdfF("sgnTemplatePdfF","",RooArgSet(mass),sgnDataHistF);
  RooKeysPdf sgnTemplatePdfF("sgnTemplatePdfF","",mass,sgnDataSetF);

  // Breit-Wigner
  RooRealVar meanSgnF("meanSgnF","mean",91.19,85,100);
  RooRealVar widthSgnF("widthSgnF","width",2.49,0.,10);
  RooBreitWigner bwSgnF("bwSgnF","bw",mass,meanSgnF,widthSgnF);

  // Crystall Ball
  RooRealVar m1SgnF("m1SgnF","m1",0,-20,20);
  RooRealVar sigmaSgnF("sigmaSgnF","sigma",0.5,0,20);
  RooRealVar alfaSgnF("alfaSgnF","alfa", 0.5,-10,10);
  RooRealVar nSgnF("nSgnF","n", 1,1e-06,50);
  RooCBShape cbSgnF("cbSgnF","",mass,m1SgnF,sigmaSgnF,alfaSgnF,nSgnF);

  // BW (X) CB
  RooFFTConvPdf bvcbSgnF("bvcbSgnF","",mass,bwSgnF, cbSgnF);

  RooFitResult* ResSgnFitF = bvcbSgnF.fitTo(sgnDataSetF, Minos(1), Save(1), NumCPU(4) );
  RooArgSet FitParamSgnF(ResSgnFitF->floatParsFinal());
  RooRealVar* m1SgnFitF    = (RooRealVar*)(&FitParamSgnF["m1SgnF"]);
  RooRealVar* sigmaSgnFitF = (RooRealVar*)(&FitParamSgnF["sigmaSgnF"]);
  RooRealVar* alfaSgnFitF  = (RooRealVar*)(&FitParamSgnF["alfaSgnF"]);
  RooRealVar* nSgnFitF     = (RooRealVar*)(&FitParamSgnF["nSgnF"]);
  RooRealVar* nMeanSgnFitF = (RooRealVar*)(&FitParamSgnF["meanSgnF"]);
  RooRealVar* nWidthSgnFitF= (RooRealVar*)(&FitParamSgnF["widthSgnF"]);

  RooRealVar m1SgnF_C("m1SgnF_C","m1",m1SgnFitF->getVal(),-10,10);
  RooRealVar sigmaSgnF_C("sigmaSgnF_C","sigma",sigmaSgnFitF->getVal(),0,20);
  // choose to let it float or not
  
  RooRealVar meanSgnF_C("meanSgnF_C","mean",  nMeanSgnFitF->getVal() ,80,120);
  RooRealVar widthSgnF_C("widthSgnF_C","width",nWidthSgnFitF->getVal() /*,0.,10*/);

  RooRealVar alfaSgnF_C("alfaSgnF_C","alfa",alfaSgnFitF->getVal()*(1+deltaAlpha_)/*,0,20*/);
  RooRealVar nSgnF_C("nSgnF_C","n",nSgnFitF->getVal()*(1+deltaN_)/*,0,50*/);

  RooCBShape cbSgnF_C("cbSgnF_C","",mass,m1SgnF_C,sigmaSgnF_C,alfaSgnF_C,nSgnF_C);
  
  RooLognormal alfaSgnF_CPdf("alfaSgnF_CPdf","",alfaSgnF_C,RooConst(alfaSgnFitF->getVal()),RooConst(1.5));
  RooLognormal nSgnF_CPdf("nSgnF_CPdf","",nSgnF_C,RooConst(nSgnFitF->getVal()),            RooConst(1.5));

  RooLognormal meanSgnF_CPdf("meanSgnF_CPdf","",meanSgnF_C,RooConst(nMeanSgnFitF->getVal()),RooConst(1.5));
  RooLognormal widthSgnF_CPdf("widthSgnF_CPdf","",widthSgnF_C,RooConst(nWidthSgnFitF->getVal()),RooConst(1.5));

  // fitted BW (X) CB
  RooBreitWigner bwSgnF_C("bwSgnF_C","bw",mass,meanSgnF_C,widthSgnF_C);
  RooFFTConvPdf sgnPdfF("sgnPdfF","",mass,bwSgnF_C, cbSgnF_C);


  RooRealVar sgnMeanResF("sgnMeanResF","",0,-10,10);
  RooRealVar sgnSigmaResF("sgnSigmaResF","",0.5,0,10);
  RooGaussian resolModF("sgnResolModF","",mass,sgnMeanResF,sgnSigmaResF);

  mass.setBins(nBins_);
  //return;





  // Fit
  RooCategory category("category","category") ;
  category.defineType("pass") ;
  category.defineType("fail") ;

  RooRealVar DataNumBkgF("DataNumBkgF","",0,10000000);
  RooRealVar DataNumBkgP("DataNumBkgP","",0,10000000);
  RooRealVar DataNumSgn("DataNumSgn","",  0,10000000);
  RooRealVar DataEfficiency("DataEfficiency","",0.5,0,1);
  
  RooFormulaVar DataNumSgnP("DataNumSgnP","DataEfficiency*DataNumSgn",    RooArgSet(DataEfficiency,DataNumSgn));
  RooFormulaVar DataNumSgnF("DataNumSgnF","(1-DataEfficiency)*DataNumSgn",RooArgSet(DataEfficiency,DataNumSgn));
 
  RooAddPdf DataModelP("DataModelP","",RooArgList(sgnPdfP,bkgPdfP),RooArgList(DataNumSgnP,DataNumBkgP));
  RooAddPdf DataModelF("DataModelF","",RooArgList(sgnPdfF,bkgPdfF),RooArgList(DataNumSgnF,DataNumBkgF));
  
  TFile* dummyData = new TFile("dummyData.root","RECREATE");
  TTree* fullTreeDataCutP = fullTreeData->CopyTree( Form("(%s>=%f && %s  && tag_pfRelIso<0.1 && pair_tnpCharge==0 && event_met_pfmet<25 && (tag_hlt1==1 || tag_hlt2==1) && tag_pt>35)",category_.c_str(),cutValue_,bin_.c_str()) ); 
  TTree* fullTreeDataCutF = fullTreeData->CopyTree( Form("(%s <%f && %s  && tag_pfRelIso<0.1 && pair_tnpCharge==0 && event_met_pfmet<25 && (tag_hlt1==1 || tag_hlt2==1) && tag_pt>35)",category_.c_str(),cutValue_,bin_.c_str()) );

  mass.setBins(nBins_);
  RooDataSet DataDataSetP("DataDataSetP","dataset for Data pass", RooArgSet(mass), Import( *fullTreeDataCutP ) );
  std::cout << "data dataset Pass " << DataDataSetP.numEntries() << "  " << std::endl;
  //return out;
  RooDataHist DataDataHistP("DataDataHistP","",RooArgSet(mass),DataDataSetP, 1.0);
  RooDataSet DataDataSetF("DataDataSetF","dataset for Data fail", RooArgSet(mass), Import( *fullTreeDataCutF ) );
  std::cout << "data dataset Fail " << DataDataSetF.numEntries() << "  " << std::endl;
  RooDataHist DataDataHistF("DataDataHistF","",RooArgSet(mass),DataDataSetF, 1.0);

  RooRealVar DataNumSgnP_("DataNumSgnP_","",0,10000);
  RooAddPdf DataModelP_("DataModelP_","",RooArgList(sgnPdfP,bkgPdfP),RooArgList(DataNumSgnP_,DataNumBkgP));
  DataModelP_.fitTo(DataDataSetP, Extended(1), Minos(1), Save(1), NumCPU(4),SumW2Error(1) /*,ExternalConstraints( RooArgSet(meanSgn_CPdf,widthSgn_CPdf) )*/);

  RooPlot* frame2 = mass.frame(Title("template"));
  DataDataSetP.plotOn(frame2);
  DataModelP_.plotOn(frame2, LineColor(kBlue), LineStyle(kSolid));
  DataModelP_.plotOn(frame2, Components("sgnPdfP"), LineColor(kRed), LineStyle(kSolid));
  DataModelP_.plotOn(frame2, Components("bkgPdfP"), LineColor(kGreen), LineStyle(kSolid));
  frame2->Draw();

  //return;



  // binned combined dataset
  RooDataHist DataCombData("DataCombData","combined data",mass,Index(category),Import("pass", *(DataDataSetP.createHistogram("histoDataP",mass)) ) ,Import("fail", *(DataDataSetF.createHistogram("histoDataF",mass))), Weight(0.5) ) ;
  std::cout << "data dataHist Comb " << DataCombData.sumEntries() << "  " << std::endl;
  std::cout << "+++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
  // unbinned combined dataset
  RooDataSet DataCombDataUnBinned("DataCombDataUnBinned","combined data",mass,Index(category),Import("pass", DataDataSetP ) ,Import("fail",DataDataSetF), Weight(0.5) ) ;
  std::cout << "data dataset Comb " << DataCombDataUnBinned.numEntries() << "  " << std::endl;
  std::cout << "+++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
  //return out;
  
  RooSimultaneous DataSimPdf("DataSimPdf","simultaneous pdf",category) ;
  DataSimPdf.addPdf(DataModelP,"pass") ;
  DataSimPdf.addPdf(DataModelF,"fail") ;

  //mass.setBins( 10000, "fft" );
  mass.setBins( nBins_ );
  RooFitResult* ResDataCombinedFit =  0;
  if(doBinned_)  ResDataCombinedFit = DataSimPdf.fitTo(DataCombData , Extended(1), Minos(1), Save(1), NumCPU(4), /*ExternalConstraints( RooArgSet(alfaSgn_CPdf,nSgn_CPdf) )*/  SumW2Error(1));
  else ResDataCombinedFit = DataSimPdf.fitTo(DataCombDataUnBinned , Extended(1), Minos(1), Save(1), NumCPU(4),  /*ExternalConstraints( RooArgSet(alfaSgn_CPdf,nSgn_CPdf) )*/ SumW2Error(1));


  RooArgSet DataFitParam(ResDataCombinedFit->floatParsFinal());
  RooRealVar* DataEffFit      = (RooRealVar*)(&DataFitParam["DataEfficiency"]);
  RooRealVar* DataNumSigFit   = (RooRealVar*)(&DataFitParam["DataNumSgn"]);

  RooPlot* DataFrameP = mass.frame(Bins(40),Title("CMS Preliminary 2011  #sqrt{s}=7 TeV   L=XXX pb^{-1}:  passing probe"));
  DataCombData.plotOn(DataFrameP,Cut("category==category::pass"));
  DataSimPdf.plotOn(DataFrameP,Slice(category,"pass"), ProjWData(category,DataCombData), LineColor(kBlue));
  DataSimPdf.plotOn(DataFrameP,Slice(category,"pass"), ProjWData(category,DataCombData), Components("sgnPdfP"), LineColor(kRed), LineStyle(kSolid));
  DataSimPdf.plotOn(DataFrameP,Slice(category,"pass"), ProjWData(category,DataCombData), Components("bkgPdfP"), LineColor(kMagenta), LineStyle(kDashed));
 

  RooPlot* DataFrameF = mass.frame(Bins(40),Title("CMS Preliminary 2011  #sqrt{s}=7 TeV   L=XXX pb^{-1}:  failing probe"));
  DataCombData.plotOn(DataFrameF,Cut("category==category::fail"));
  DataSimPdf.plotOn(DataFrameF,Slice(category,"fail"), ProjWData(category,DataCombData), LineColor(kBlue));
  DataSimPdf.plotOn(DataFrameF,Slice(category,"fail"), ProjWData(category,DataCombData), Components("sgnPdfF"), LineColor(kRed), LineStyle(kSolid));
  DataSimPdf.plotOn(DataFrameF,Slice(category,"fail"), ProjWData(category,DataCombData), Components("bkgPdfF"), LineColor(kMagenta), LineStyle(kDashed));


  TCanvas *cPass = new TCanvas("fitCanvasP","canvas",10,30,650,600);
  cPass->SetGrid(0,0);
  cPass->SetFillStyle(4000);
  cPass->SetFillColor(10);
  cPass->SetTicky();
  cPass->SetObjectStat(0);

  cPass->cd();
  DataFrameP->Draw();
  string fileNameP = "fitCanvasPassElecTnP_"+tnp_+"_"+category_;
  cPass->SaveAs(Form("%s_%.2f.png",fileNameP.c_str(), binCenter_));

  TCanvas *cFail = new TCanvas("fitCanvasF","canvas",10,30,650,600);
  cFail->SetGrid(0,0);
  cFail->SetFillStyle(4000);
  cFail->SetFillColor(10);
  cFail->SetTicky();
  cFail->SetObjectStat(0);

  cFail->cd();
  DataFrameF->Draw();
  string fileNameF = "fitCanvasFailElecTnP_"+tnp_+"_"+category_;
  cFail->SaveAs(Form("%s_%.2f.png",fileNameF.c_str(), binCenter_));

  ResDataCombinedFit->printArgs(std::cout);
  cout << endl;
  ResDataCombinedFit->printValue(std::cout);
  cout << endl;

  float DataErrorLo = DataEffFit->getErrorLo()<0 ? DataEffFit->getErrorLo() : (-1)*DataEffFit->getError();
  float DataErrorHi = DataEffFit->getErrorHi()>0 ? DataEffFit->getErrorHi() : DataEffFit->getError();

  cout << DataEffFit->getVal() << " +/- " << DataEffFit->getError() << "  ( " << DataErrorLo << ", " << DataErrorHi << ")" <<  endl;

  float* out1 = new float[6];
  float* out2 = new float[6];

  out1[0]=(binCenter_);
  out1[1]=(binWidth_);
  out1[2]=(binWidth_);
  out1[3]=(McTruthEff);
  out1[4]=(BinomialError);
  out1[5]=(BinomialError);

  out2[0]=(binCenter_);
  out2[1]=(binWidth_);
  out2[2]=(binWidth_);
  out2[3]=(DataEffFit->getVal());
  out2[4]=((-1)*DataErrorLo);
  out2[5]=(DataErrorHi);

  out.push_back(out1);
  out.push_back(out2);

  return out;
}
コード例 #20
0
ファイル: tnpTools5.C プロジェクト: bianchini/usercode
vector<Double_t*> simFit(bool makeSoupFit_ = false,
			 const string tnp_ = "etoTauMargLooseNoCracks70", 
			 const string category_ = "tauAntiEMVA",
			 const string bin_ = "abseta<1.5",
			 const float binCenter_ = 0.75,
			 const float binWidth_ = 0.75,
			 const float xLow_=60, 
			 const float xHigh_=120,
			 bool SumW2_ = false,
			 bool verbose_ = true){

  vector<Double_t*> out;
  //return out;

  //TFile *test = new TFile( outFile->GetName(),"UPDATE");
  // output file
  TFile *test = new TFile( Form("EtoTauPlotsFit_%s_%s_%f.root",tnp_.c_str(),category_.c_str(),binCenter_),"RECREATE");
  test->mkdir(Form("bin%f",binCenter_));

  TCanvas *c = new TCanvas("fitCanvas",Form("fitCanvas_%s_%s",tnp_.c_str(),bin_.c_str()),10,30,650,600);
  c->SetGrid(0,0);
  c->SetFillStyle(4000);
  c->SetFillColor(10);
  c->SetTicky();
  c->SetObjectStat(0);
  
  TCanvas *c2 = new TCanvas("fitCanvasTemplate",Form("fitCanvasTemplate_%s_%s",tnp_.c_str(),bin_.c_str()),10,30,650,600);
  c2->SetGrid(0,0);
  c2->SetFillStyle(4000);
  c2->SetFillColor(10);
  c2->SetTicky();
  c2->SetObjectStat(0);

  // input files
  TFile fsup("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup.root");
  TFile fbkg("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup_bkg.root");
  TFile fsgn("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup_sgn.root");
  TFile fdat("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_Data.root");
  // data from 2iter:
  //TFile fdat("/data_CMS/cms/lbianchini/35pb/testNewWriteFromPAT_Data.root");
  
  //********************** signal only tree *************************/

  TTree *fullTreeSgn = (TTree*)fsgn.Get((tnp_+"/fitter_tree").c_str());
  TH1F* hSall        = new TH1F("hSall","",1,0,150);
  TH1F* hSPall       = new TH1F("hSPall","",1,0,150);
  TH1F* hS           = new TH1F("hS","",1,0,150);
  TH1F* hSP          = new TH1F("hSP","",1,0,150);
  fullTreeSgn->Draw("mass>>hS",Form("weight*(%s && mass>%f && mass<%f && mcTrue && signalPFChargedHadrCands<1.5)",bin_.c_str(),xLow_,xHigh_));
  fullTreeSgn->Draw("mass>>hSall",Form("weight*(%s && mass>%f && mass<%f)",bin_.c_str(),xLow_,xHigh_));

  float SGNtrue = hS->Integral();
  float SGNall  = hSall->Integral();
 
  fullTreeSgn->Draw("mass>>hSP",Form("weight*(%s && %s>0 && mass>%f && mass<%f && mcTrue && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_));
  fullTreeSgn->Draw("mass>>hSPall",Form("weight*(%s && %s>0 && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_));

  float SGNtruePass = hSP->Integral();
  float SGNallPass  = hSPall->Integral();

  //********************** background only tree *************************//

  TTree *fullTreeBkg = (TTree*)fbkg.Get((tnp_+"/fitter_tree").c_str());
  TH1F* hB = new TH1F("hB","",1,0,150);
  TH1F* hBP = new TH1F("hBP","",1,0,150);
  fullTreeBkg->Draw("mass>>hB",Form("weight*(%s && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),xLow_,xHigh_));
 
  float BKG           = hB->Integral();
  float BKGUnWeighted = hB->GetEntries();
  
  fullTreeBkg->Draw("mass>>hBP",Form("weight*(%s && %s>0 && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_));
  
  float BKGPass           = hBP->Integral();
  float BKGUnWeightedPass = hBP->GetEntries();
  float BKGFail           = BKG-BKGPass;
  cout << "*********** BKGFail " << BKGFail << endl;

  //********************** soup tree *************************//

  TTree *fullTreeSoup = (TTree*)fsup.Get((tnp_+"/fitter_tree").c_str());

  //********************** data tree *************************//

  TTree *fullTreeData = (TTree*)fdat.Get((tnp_+"/fitter_tree").c_str());

  //********************** workspace ***********************//

  RooWorkspace *w = new RooWorkspace("w","w");
  // tree variables to be imported
  w->factory("mass[30,120]");
  w->factory("weight[0,10000]");
  w->factory("abseta[0,2.5]");
  w->factory("pt[0,200]");
  w->factory("mcTrue[0,1]");
  w->factory("signalPFChargedHadrCands[0,10]");
  w->factory((category_+"[0,1]").c_str());
  // background pass pdf for MC
  w->factory("RooExponential::McBackgroundPdfP(mass,McCP[0,-10,10])");
  // background fail pdf for MC
  w->factory("RooExponential::McBackgroundPdfF(mass,McCF[0,-10,10])");
  // background pass pdf for Data
  w->factory("RooExponential::DataBackgroundPdfP(mass,DataCP[0,-10,10])");
  // background fail pdf for Data
  w->factory("RooExponential::DataBackgroundPdfF(mass,DataCF[0,-10,10])");
  // fit parameters for background
  w->factory("McEfficiency[0.04,0,1]");
  w->factory("McNumSgn[0,1000000]");
  w->factory("McNumBkgP[0,100000]");
  w->factory("McNumBkgF[0,100000]"); 
  w->factory("expr::McNumSgnP('McEfficiency*McNumSgn',McEfficiency,McNumSgn)");
  w->factory("expr::McNumSgnF('(1-McEfficiency)*McNumSgn',McEfficiency,McNumSgn)");
  w->factory("McPassing[pass=1,fail=0]");
  // fit parameters for data
  w->factory("DataEfficiency[0.1,0,1]");
  w->factory("DataNumSgn[0,1000000]");
  w->factory("DataNumBkgP[0,1000000]");
  w->factory("DataNumBkgF[0,10000]");
  w->factory("expr::DataNumSgnP('DataEfficiency*DataNumSgn',DataEfficiency,DataNumSgn)");
  w->factory("expr::DataNumSgnF('(1-DataEfficiency)*DataNumSgn',DataEfficiency,DataNumSgn)");
  w->factory("DataPassing[pass=1,fail=0]");

  RooRealVar  *weight = w->var("weight");
  RooRealVar  *abseta = w->var("abseta");
  RooRealVar  *pt     = w->var("pt");
  RooRealVar  *mass   = w->var("mass");
  mass->setRange(xLow_,xHigh_);
  RooRealVar  *mcTrue = w->var("mcTrue");
  RooRealVar  *cut    = w->var( category_.c_str() );
  RooRealVar  *signalPFChargedHadrCands = w->var("signalPFChargedHadrCands");
 
  // build the template for the signal pass sample:
  RooDataSet templateP("templateP","dataset for signal-pass template", RooArgSet(*mass,*weight,*abseta,*pt,*cut,*mcTrue,*signalPFChargedHadrCands), Import( *fullTreeSgn ), /*WeightVar( *weight ),*/ Cut( Form("(mcTrue && %s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()) ) );
  // build the template for the signal fail sample:
  RooDataSet templateF("templateF","dataset for signal-fail template", RooArgSet(*mass,*weight,*abseta,*pt,*cut,*mcTrue,*signalPFChargedHadrCands), Import( *fullTreeSgn ), /*WeightVar( *weight ),*/ Cut( Form("(mcTrue && %s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()) ) );
  

  mass->setBins(24);
  RooDataHist templateHistP("templateHistP","",RooArgSet(*mass), templateP, 1.0);
  RooHistPdf TemplateSignalPdfP("TemplateSignalPdfP","",RooArgSet(*mass),templateHistP);
  w->import(TemplateSignalPdfP);

  mass->setBins(24);
  RooDataHist templateHistF("templateHistF","",RooArgSet(*mass),templateF,1.0);
  RooHistPdf TemplateSignalPdfF("TemplateSignalPdfF","",RooArgSet(*mass),templateHistF);
  w->import(TemplateSignalPdfF);

  mass->setBins(10000,"fft");

  RooPlot* TemplateFrameP = mass->frame(Bins(24),Title("Template passing"));
  templateP.plotOn(TemplateFrameP);
  w->pdf("TemplateSignalPdfP")->plotOn(TemplateFrameP);
  
  RooPlot* TemplateFrameF = mass->frame(Bins(24),Title("Template failing"));
  templateF.plotOn(TemplateFrameF);
  w->pdf("TemplateSignalPdfF")->plotOn(TemplateFrameF);

  //w->factory("RooFFTConvPdf::McSignalPdfP(mass,TemplateSignalPdfP,RooTruthModel::McResolModP(mass))");
  //w->factory("RooFFTConvPdf::McSignalPdfF(mass,TemplateSignalPdfF,RooTruthModel::McResolModF(mass))");

  // FOR GREGORY: PROBLEM WHEN TRY TO USE THE PURE TEMPLATE =>
  RooHistPdf McSignalPdfP("McSignalPdfP","McSignalPdfP",RooArgSet(*mass),templateHistP);
  RooHistPdf McSignalPdfF("McSignalPdfF","McSignalPdfF",RooArgSet(*mass),templateHistF);
  w->import(McSignalPdfP);
  w->import(McSignalPdfF);
  // FOR GREGORY: FOR DATA, CONVOLUTION IS OK =>
  w->factory("RooFFTConvPdf::DataSignalPdfP(mass,TemplateSignalPdfP,RooGaussian::DataResolModP(mass,DataMeanResP[0.0,-5.,5.],DataSigmaResP[0.5,0.,10]))");
  w->factory("RooFFTConvPdf::DataSignalPdfF(mass,TemplateSignalPdfF,RooGaussian::DataResolModF(mass,DataMeanResF[-5.,-10.,10.],DataSigmaResF[0.5,0.,10]))");
  //w->factory("RooCBShape::DataSignalPdfF(mass,DataMeanF[91.2,88,95.],DataSigmaF[3,0.5,8],DataAlfaF[1.8,0.,10],DataNF[1.0,1e-06,10])");
  //w->factory("RooFFTConvPdf::DataSignalPdfF(mass,RooVoigtian::DataVoigF(mass,DataMeanF[85,80,95],DataWidthF[2.49],DataSigmaF[3,0.5,10]),RooCBShape::DataResolModF(mass,DataMeanResF[0.5,0.,10.],DataSigmaResF[0.5,0.,10],DataAlphaResF[0.5,0.,10],DataNResF[1.0,1e-06,10]))");
  //w->factory("SUM::DataSignalPdfF(fVBP[0.5,0,1]*RooBifurGauss::bifF(mass,DataMeanResF[91.2,80,95],sigmaLF[10,0.5,40],sigmaRF[0.]), RooVoigtian::voigF(mass, DataMeanResF, widthF[2.49], sigmaVoigF[5,0.1,10]) )" );
  
  // composite model pass for MC
  w->factory("SUM::McModelP(McNumSgnP*McSignalPdfP,McNumBkgP*McBackgroundPdfP)");  
  w->factory("SUM::McModelF(McNumSgnF*McSignalPdfF,McNumBkgF*McBackgroundPdfF)");
  // composite model pass for data
  w->factory("SUM::DataModelP(DataNumSgnP*DataSignalPdfP,DataNumBkgP*DataBackgroundPdfP)");  
  w->factory("SUM::DataModelF(DataNumSgnF*DataSignalPdfF,DataNumBkgF*DataBackgroundPdfF)");  
  // simultaneous fir for MC
  w->factory("SIMUL::McModel(McPassing,pass=McModelP,fail=McModelF)");
  // simultaneous fir for data
  w->factory("SIMUL::DataModel(DataPassing,pass=DataModelP,fail=DataModelF)");
  w->Print("V");
  w->saveSnapshot("clean", w->allVars());

  w->loadSnapshot("clean");

  /****************** sim fit to soup **************************/

  ///////////////////////////////////////////////////////////////
  TFile *f = new TFile("dummySoup.root","RECREATE");
  TTree* cutTreeSoupP = fullTreeSoup->CopyTree(Form("(%s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
  TTree* cutTreeSoupF = fullTreeSoup->CopyTree(Form("(%s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
 
  RooDataSet McDataP("McDataP","dataset pass for the soup", RooArgSet(*mass), Import( *cutTreeSoupP ) );
 
  RooDataSet McDataF("McDataF","dataset fail for the soup", RooArgSet(*mass), Import( *cutTreeSoupF ) );
 
  RooDataHist McCombData("McCombData","combined data for the soup", RooArgSet(*mass), Index(*(w->cat("McPassing"))), Import("pass", *(McDataP.createHistogram("histoP",*mass)) ), Import("fail",*(McDataF.createHistogram("histoF",*mass)) ) ) ;

  RooPlot* McFrameP    = 0;
  RooPlot* McFrameF    = 0;
  RooRealVar* McEffFit = 0;

  if(makeSoupFit_){

    cout << "**************** N bins in mass " << w->var("mass")->getBins() << endl;

    RooFitResult* ResMcCombinedFit = w->pdf("McModel")->fitTo(McCombData, Extended(1), Minos(1), Save(1),  SumW2Error( SumW2_ ), Range(xLow_,xHigh_), NumCPU(4) /*, ExternalConstraints( *(w->pdf("ConstrainMcNumBkgF")) )*/ );
    test->cd(Form("bin%f",binCenter_));
    ResMcCombinedFit->Write("McFitResults_Combined");

    RooArgSet McFitParam(ResMcCombinedFit->floatParsFinal());
    McEffFit     = (RooRealVar*)(&McFitParam["McEfficiency"]);
    RooRealVar* McNumSigFit  = (RooRealVar*)(&McFitParam["McNumSgn"]);
    RooRealVar* McNumBkgPFit = (RooRealVar*)(&McFitParam["McNumBkgP"]);
    RooRealVar* McNumBkgFFit = (RooRealVar*)(&McFitParam["McNumBkgF"]);

    McFrameP = mass->frame(Bins(24),Title("MC: passing sample"));
    McCombData.plotOn(McFrameP,Cut("McPassing==McPassing::pass"));
    w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), LineColor(kBlue),Range(xLow_,xHigh_));
    w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McSignalPdfP"), LineColor(kRed),Range(xLow_,xHigh_));
    w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McBackgroundPdfP"), LineColor(kGreen),Range(xLow_,xHigh_));
    
    McFrameF = mass->frame(Bins(24),Title("MC: failing sample"));
    McCombData.plotOn(McFrameF,Cut("McPassing==McPassing::fail"));
    w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), LineColor(kBlue),Range(xLow_,xHigh_));
    w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McSignalPdfF"), LineColor(kRed),Range(xLow_,xHigh_)); 
    w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McBackgroundPdfF"), LineColor(kGreen),Range(xLow_,xHigh_)); 
  }
  
  ///////////////////////////////////////////////////////////////

  /****************** sim fit to data **************************/

  ///////////////////////////////////////////////////////////////
  TFile *f2 = new TFile("dummyData.root","RECREATE");
  TTree* cutTreeDataP = fullTreeData->CopyTree(Form("(%s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
  TTree* cutTreeDataF = fullTreeData->CopyTree(Form("(%s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
 
  RooDataSet DataDataP("DataDataP","dataset pass for the soup", RooArgSet(*mass), Import( *cutTreeDataP ) );
  RooDataSet DataDataF("DataDataF","dataset fail for the soup", RooArgSet(*mass), Import( *cutTreeDataF ) );
  RooDataHist DataCombData("DataCombData","combined data for the soup", RooArgSet(*mass), Index(*(w->cat("DataPassing"))), Import("pass",*(DataDataP.createHistogram("histoDataP",*mass))),Import("fail",*(DataDataF.createHistogram("histoDataF",*mass)))) ;

  RooFitResult* ResDataCombinedFit = w->pdf("DataModel")->fitTo(DataCombData, Extended(1), Minos(1), Save(1),  SumW2Error( SumW2_ ), Range(xLow_,xHigh_), NumCPU(4));
  test->cd(Form("bin%f",binCenter_));
  ResDataCombinedFit->Write("DataFitResults_Combined");

  RooArgSet DataFitParam(ResDataCombinedFit->floatParsFinal());
  RooRealVar* DataEffFit     = (RooRealVar*)(&DataFitParam["DataEfficiency"]);
  RooRealVar* DataNumSigFit  = (RooRealVar*)(&DataFitParam["DataNumSgn"]);
  RooRealVar* DataNumBkgPFit = (RooRealVar*)(&DataFitParam["DataNumBkgP"]);
  RooRealVar* DataNumBkgFFit = (RooRealVar*)(&DataFitParam["DataNumBkgF"]);

  RooPlot* DataFrameP = mass->frame(Bins(24),Title("Data: passing sample"));
  DataCombData.plotOn(DataFrameP,Cut("DataPassing==DataPassing::pass"));
  w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), LineColor(kBlue),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataSignalPdfP"), LineColor(kRed),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataBackgroundPdfP"), LineColor(kGreen),LineStyle(kDashed),Range(xLow_,xHigh_));
  
  RooPlot* DataFrameF = mass->frame(Bins(24),Title("Data: failing sample"));
  DataCombData.plotOn(DataFrameF,Cut("DataPassing==DataPassing::fail"));
  w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), LineColor(kBlue),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataSignalPdfF"), LineColor(kRed),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataBackgroundPdfF"), LineColor(kGreen),LineStyle(kDashed),Range(xLow_,xHigh_));
  ///////////////////////////////////////////////////////////////

 
  if(makeSoupFit_) c->Divide(2,2);
  else c->Divide(2,1);
 
  c->cd(1);
  DataFrameP->Draw();
  c->cd(2);
  DataFrameF->Draw();

  if(makeSoupFit_){
    c->cd(3);
    McFrameP->Draw();
    c->cd(4);
    McFrameF->Draw();
  }
 
  c->Draw();
 
  test->cd(Form("bin%f",binCenter_));
 
  c->Write();
 
  c2->Divide(2,1);
  c2->cd(1);
  TemplateFrameP->Draw();
  c2->cd(2);
  TemplateFrameF->Draw();
  c2->Draw();
 
  test->cd(Form("bin%f",binCenter_));
  c2->Write();


  // MINOS errors, otherwise HESSE quadratic errors
  float McErrorLo = 0;
  float McErrorHi = 0;
  if(makeSoupFit_){
    McErrorLo = McEffFit->getErrorLo()<0 ? McEffFit->getErrorLo() : (-1)*McEffFit->getError();
    McErrorHi = McEffFit->getErrorHi()>0 ? McEffFit->getErrorHi() : McEffFit->getError();
  }
  float DataErrorLo = DataEffFit->getErrorLo()<0 ? DataEffFit->getErrorLo() : (-1)*DataEffFit->getError();
  float DataErrorHi = DataEffFit->getErrorHi()>0 ? DataEffFit->getErrorHi() : DataEffFit->getError();
  float BinomialError = TMath::Sqrt(SGNtruePass/SGNtrue*(1-SGNtruePass/SGNtrue)/SGNtrue);
 
  Double_t* truthMC = new Double_t[6];
  Double_t* tnpMC   = new Double_t[6];
  Double_t* tnpData = new Double_t[6];

  truthMC[0] = binCenter_;
  truthMC[1] = binWidth_;
  truthMC[2] = binWidth_;
  truthMC[3] = SGNtruePass/SGNtrue;
  truthMC[4] = BinomialError;
  truthMC[5] = BinomialError;
  if(makeSoupFit_){
    tnpMC[0] = binCenter_;
    tnpMC[1] = binWidth_;
    tnpMC[2] = binWidth_;
    tnpMC[3] = McEffFit->getVal();
    tnpMC[4] = (-1)*McErrorLo;
    tnpMC[5] = McErrorHi;
  }
  tnpData[0] = binCenter_;
  tnpData[1] = binWidth_;
  tnpData[2] = binWidth_;
  tnpData[3] = DataEffFit->getVal();
  tnpData[4] = (-1)*DataErrorLo;
  tnpData[5] = DataErrorHi;

  out.push_back(truthMC);
  out.push_back(tnpData);
  if(makeSoupFit_) out.push_back(tnpMC);

  test->Close();

  //delete c; delete c2;

  if(verbose_) cout << "returning from bin " << bin_ << endl;
  return out;

}
コード例 #21
0
MT2LostLeptonEstimate* computeLostLepton( const MT2Sample& sample, std::vector<MT2HTRegion> HTRegions, std::vector<MT2SignalRegion> signalRegions ) {


  std::cout << std::endl << std::endl;
  std::cout << "-> Starting computation for sample: " << sample.name << std::endl;

  TFile* file = TFile::Open(sample.file.c_str());
  TTree* tree = (TTree*)file->Get("MassTree");



  std::ostringstream preselectionStream;
  preselectionStream << " " 
    << "(NTausIDLoose3Hits==0)"                   << " && "
    << "(misc.Jet0Pass ==1)"                      << " && "
    << "(misc.Jet1Pass ==1)"                      << " && "
    << "(misc.Vectorsumpt < 70)"                  << " && " 
    << "(misc.MinMetJetDPhi4Pt40 >0.3)"           << " && "
    << "(misc.MET>30.)";
  if( fFast ) preselectionStream << " && (misc.MT2>=100.) ";//lowest border in MT2

  // add "base" cuts:
  preselectionStream << " && " 
    << "(misc.PassJet40ID ==1)"                             << " && "
    << "((misc.HBHENoiseFlag == 0 || misc.ProcessID==10))"  << " && " // signal samples (fastsim) do not have this filter
    << "(misc.CSCTightHaloIDFlag == 0)"                     << " && "
    << "(misc.trackingFailureFlag==0)"                      << " && "
    << "(misc.eeBadScFlag==0)"                              << " && "
    << "(misc.EcalDeadCellTriggerPrimitiveFlag==0)"         << " && "
    << "(misc.TrackingManyStripClusFlag==0)"                << " && "
    << "(misc.TrackingTooManyStripClusFlag==0)"             << " && "
    << "(misc.TrackingLogErrorTooManyClustersFlag==0)"      << " && "
    << "(misc.CrazyHCAL==0)";
  preselectionStream << " && (misc.MET/misc.CaloMETRaw<=2.)";//HO cut

  

  std::ostringstream oneLeptonStream;
  oneLeptonStream << "((NEles==1 && NMuons==0) || (NEles==0 && NMuons==1))";
  TString oneLeptonCuts = oneLeptonStream.str().c_str();




  TString preselection = preselectionStream.str().c_str();
  TString cuts = preselection;


  bool requireRecoLepton = !(sample.sname=="Top" || sample.sname=="Wtolnu"); // only these used for efficiencies
  if( requireRecoLepton ) cuts = cuts + " && " + oneLeptonCuts;
  

  TFile* tmpFile = TFile::Open("tmp.root", "recreate");
  tmpFile->cd();
  TTree* tree_reduced = tree->CopyTree(cuts);


  std::vector<std::string> leptType;
  leptType.push_back("Ele");
  leptType.push_back("Muo");

  std::vector<MT2LeptonTypeLLEstimate*> v_llest = getLeptonTypeLLEstimate( leptType, tree_reduced, sample, HTRegions, signalRegions );

  MT2LostLeptonEstimate* llest = new MT2LostLeptonEstimate(sample.name, sample.sname);
  for( unsigned i=0; i<leptType.size(); ++i ) 
    llest->l[ leptType[i].c_str() ] = v_llest[i];

  delete tree;
  delete tree_reduced;

  tmpFile->Close();
  delete tmpFile;

  file->Close();
  delete file;
  

  return llest;

}
コード例 #22
0
void PID_misidentification() {

    // -- define tuple file name, tuple name and cuts to apply-----------------------
    // -- and also the name of the output file
    const std::string filename = "/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/background_MC_samples/Bs2JpsiX_MC_2012_signal_withbdt.root";
    const std::string treename = "withbdt";
    const std::string outFilename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/background_MC_samples/Bs2JpsiX_MC_2012_signal_withbdt_misidentification.root");
   
   
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;

    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;

    // -- activate the branches you need---------------------------------------------
  
    tree->SetBranchStatus("*", 1);  
    
    


    // -- this file is just here to make the 'CopyTree' happy
    TFile* dummyFile = new TFile("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/dummy.root","RECREATE");
    TTree* rTree1 = tree->CopyTree("bdtg>=0.85");

    double chi_c_M,  chi_c_P, chi_c_PE, chi_c_PT, chi_c_PX, chi_c_PY, chi_c_PZ, chi_c_ETA;
    double kaon_M,  kaon_P, kaon_PE, kaon_PX, kaon_PT, kaon_PY, kaon_PZ, kaon_ETA, kaon_IPCHI2_OWNPV, kaon_TRACK_GhostProb, kaon_ProbNNp, kaon_ProbNNk;
    double proton_M,  proton_P, proton_PE, proton_PT, proton_PX, proton_PY, proton_PZ, proton_ETA, proton_IPCHI2_OWNPV, proton_TRACK_GhostProb, proton_ProbNNp, proton_ProbNNk;
    double Jpsi_M, Jpsi_P, Jpsi_PE, Jpsi_PT, Jpsi_PX, Jpsi_PY, Jpsi_PZ, Jpsi_ETA;
    double gamma_M, gamma_P, gamma_PE, gamma_PT, gamma_PX, gamma_PY, gamma_PZ, gamma_ETA, gamma_CL;
    double muminus_M, muminus_P, muminus_PE, muminus_PT, muminus_PX, muminus_PY, muminus_PZ, muminus_ETA, muminus_ProbNNmu, muminus_TRACK_GhostProb;
    double muplus_M, muplus_P, muplus_PE, muplus_PT, muplus_PX, muplus_PY, muplus_PZ, muplus_ETA, muplus_ProbNNmu, muplus_TRACK_GhostProb;
    double Lambda_b0_DTF_MASS_constr1, Lambda_b0_DTF_CHI2NDOF, Lambda_b0_IPCHI2_OWNPV;
    double Lambda_b0_FDS, Lambda_b0_pi0veto, Lambda_b0_PT; 
    float bdtg; 
    
    bool Lambda_b0_L0MuonDecision_TOS, Lambda_b0_L0DiMuonDecision_TOS;
    bool Lambda_b0_Hlt1DiMuonHighMassDecision_TOS, Lambda_b0_Hlt1DiMuonLowMassDecision_TOS;
    bool Lambda_b0_Hlt1TrackMuonDecision_TOS, Lambda_b0_Hlt1TrackAllL0Decision_TOS;
    bool Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS, Lambda_b0_Hlt2DiMuonDetachedDecision_TOS;
    bool Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS;
    
    
    rTree1->SetBranchAddress("chi_c_M", &chi_c_M);
    rTree1->SetBranchAddress("chi_c_P", &chi_c_P);
    rTree1->SetBranchAddress("chi_c_PE", &chi_c_PE);
    rTree1->SetBranchAddress("chi_c_PT", &chi_c_PT);
    rTree1->SetBranchAddress("chi_c_PX", &chi_c_PX);
    rTree1->SetBranchAddress("chi_c_PY", &chi_c_PY);
    rTree1->SetBranchAddress("chi_c_PZ", &chi_c_PZ);
    //rTree1->SetBranchAddress("chi_c_ETA", &chi_c_ETA);
    
    rTree1->SetBranchAddress("kaon_M", &kaon_M);
    rTree1->SetBranchAddress("kaon_P", &kaon_P);
    rTree1->SetBranchAddress("kaon_PE", &kaon_PE);
    rTree1->SetBranchAddress("kaon_PX", &kaon_PX);
    rTree1->SetBranchAddress("kaon_PT", &kaon_PT);
    rTree1->SetBranchAddress("kaon_PY", &kaon_PY);
    rTree1->SetBranchAddress("kaon_PZ", &kaon_PZ);
    //rTree1->SetBranchAddress("kaon_ETA", &kaon_ETA);
    rTree1->SetBranchAddress("kaon_IPCHI2_OWNPV", &kaon_IPCHI2_OWNPV);
    rTree1->SetBranchAddress("kaon_TRACK_GhostProb", &kaon_TRACK_GhostProb);
    rTree1->SetBranchAddress("kaon_ProbNNp", &kaon_ProbNNp);
    rTree1->SetBranchAddress("kaon_ProbNNk", &kaon_ProbNNk);
    
    rTree1->SetBranchAddress("proton_M", &proton_M);
    rTree1->SetBranchAddress("proton_P", &proton_P);
    rTree1->SetBranchAddress("proton_PE", &proton_PE);
    rTree1->SetBranchAddress("proton_PT", &proton_PT);
    rTree1->SetBranchAddress("proton_PX", &proton_PX);
    rTree1->SetBranchAddress("proton_PY", &proton_PY);
    rTree1->SetBranchAddress("proton_PZ", &proton_PZ);
    //rTree1->SetBranchAddress("proton_ETA", &proton_ETA);
    rTree1->SetBranchAddress("proton_IPCHI2_OWNPV", &proton_IPCHI2_OWNPV);
    rTree1->SetBranchAddress("proton_TRACK_GhostProb", &proton_TRACK_GhostProb);
    rTree1->SetBranchAddress("proton_ProbNNp", &proton_ProbNNp);
    rTree1->SetBranchAddress("proton_ProbNNk", &proton_ProbNNk);

    rTree1->SetBranchAddress("Jpsi_M", &Jpsi_M);
    rTree1->SetBranchAddress("Jpsi_P", &Jpsi_P);
    rTree1->SetBranchAddress("Jpsi_PE", &Jpsi_PE);
    rTree1->SetBranchAddress("Jpsi_PT", &Jpsi_PT);
    rTree1->SetBranchAddress("Jpsi_PX", &Jpsi_PX);
    rTree1->SetBranchAddress("Jpsi_PY", &Jpsi_PY);
    rTree1->SetBranchAddress("Jpsi_PZ", &Jpsi_PZ);
    //rTree1->SetBranchAddress("Jpsi_ETA", &Jpsi_ETA);     
  
    rTree1->SetBranchAddress("gamma_M", &gamma_M);
    rTree1->SetBranchAddress("gamma_P", &gamma_P);
    rTree1->SetBranchAddress("gamma_PE", &gamma_PE);
    rTree1->SetBranchAddress("gamma_PT", &gamma_PT);
    rTree1->SetBranchAddress("gamma_PX", &gamma_PX);
    rTree1->SetBranchAddress("gamma_PY", &gamma_PY);
    rTree1->SetBranchAddress("gamma_PZ", &gamma_PZ);
    //rTree1->SetBranchAddress("gamma_ETA", &gamma_ETA);  
    rTree1->SetBranchAddress("gamma_CL", &gamma_CL);  

    rTree1->SetBranchAddress("muminus_M", &muminus_M);
    rTree1->SetBranchAddress("muminus_P", &muminus_P);
    rTree1->SetBranchAddress("muminus_PE", &muminus_PE); 
    rTree1->SetBranchAddress("muminus_PT", &muminus_PT);
    rTree1->SetBranchAddress("muminus_PX", &muminus_PX);
    rTree1->SetBranchAddress("muminus_PY", &muminus_PY);
    rTree1->SetBranchAddress("muminus_PZ", &muminus_PZ);  
    //rTree1->SetBranchAddress("muminus_ETA", &muminus_ETA);  
    rTree1->SetBranchAddress("muminus_ProbNNmu", &muminus_ProbNNmu);  
    rTree1->SetBranchAddress("muminus_TRACK_GhostProb", &muminus_TRACK_GhostProb);  

    rTree1->SetBranchAddress("muplus_M", &muplus_M);
    rTree1->SetBranchAddress("muplus_P", &muplus_P);
    rTree1->SetBranchAddress("muplus_PE", &muplus_PE);
    rTree1->SetBranchAddress("muplus_PT", &muplus_PT);
    rTree1->SetBranchAddress("muplus_PX", &muplus_PX);
    rTree1->SetBranchAddress("muplus_PY", &muplus_PY);
    rTree1->SetBranchAddress("muplus_PZ", &muplus_PZ);
    //rTree1->SetBranchAddress("muplus_ETA", &muplus_ETA);  
    rTree1->SetBranchAddress("muplus_ProbNNmu", &muplus_ProbNNmu);  
    rTree1->SetBranchAddress("muplus_TRACK_GhostProb", &muplus_TRACK_GhostProb);  

    rTree1->SetBranchAddress("Lambda_b0_DTF_MASS_constr1", &Lambda_b0_DTF_MASS_constr1);
    rTree1->SetBranchAddress("Lambda_b0_DTF_CHI2NDOF", &Lambda_b0_DTF_CHI2NDOF);
    rTree1->SetBranchAddress("Lambda_b0_IPCHI2_OWNPV", &Lambda_b0_IPCHI2_OWNPV);
    rTree1->SetBranchAddress("Lambda_b0_L0DiMuonDecision_TOS", &Lambda_b0_L0DiMuonDecision_TOS);
    rTree1->SetBranchAddress("Lambda_b0_L0MuonDecision_TOS", &Lambda_b0_L0MuonDecision_TOS);
    rTree1->SetBranchAddress("Lambda_b0_FDS", &Lambda_b0_FDS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt1DiMuonHighMassDecision_TOS", &Lambda_b0_Hlt1DiMuonHighMassDecision_TOS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt1DiMuonLowMassDecision_TOS", &Lambda_b0_Hlt1DiMuonLowMassDecision_TOS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt1TrackMuonDecision_TOS", &Lambda_b0_Hlt1TrackMuonDecision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt1TrackAllL0Decision_TOS", &Lambda_b0_Hlt1TrackAllL0Decision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS", &Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS);  
    rTree1->SetBranchAddress("Lambda_b0_Hlt2DiMuonDetachedDecision_TOS", &Lambda_b0_Hlt2DiMuonDetachedDecision_TOS); 
    rTree1->SetBranchAddress("Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS", &Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS);
    rTree1->SetBranchAddress("Lambda_b0_pi0veto", &Lambda_b0_pi0veto);
    rTree1->SetBranchAddress("Lambda_b0_PT", &Lambda_b0_PT);

    rTree1->SetBranchAddress("bdtg", &bdtg);
    //-------------------------------------------------------------------------------

    TFile* rFile = new TFile( outFilename.c_str() ,"RECREATE");
    TTree* rTree2 = new TTree();
    rTree2->SetName("withbdt");
    
    rTree2->Branch("chi_c_M", &chi_c_M, "chi_c_M/D");
    rTree2->Branch("chi_c_P", &chi_c_P, "chi_c_P/D");
    rTree2->Branch("chi_c_PE", &chi_c_PE, "chi_c_PE/D");
    rTree2->Branch("chi_c_PT", &chi_c_PT, "chi_c_PT/D");
    rTree2->Branch("chi_c_PX", &chi_c_PX, "chi_c_PX/D");
    rTree2->Branch("chi_c_PY", &chi_c_PY, "chi_c_PY/D");
    rTree2->Branch("chi_c_PZ", &chi_c_PZ, "chi_c_PZ/D");
    //rTree2->Branch("chi_c_ETA", &chi_c_ETA, "chi_c_ETA/D");
    
    rTree2->Branch("kaon_M", &kaon_M, "kaon_M/D");
    rTree2->Branch("kaon_P", &kaon_P, "kaon_P/D");
    rTree2->Branch("kaon_PE", &kaon_PE, "kaon_PE/D");
    rTree2->Branch("kaon_PX", &kaon_PX, "kaon_PX/D");
    rTree2->Branch("kaon_PT", &kaon_PT, "kaon_PT/D");
    rTree2->Branch("kaon_PY", &kaon_PY, "kaon_PY/D");
    rTree2->Branch("kaon_PZ", &kaon_PZ, "kaon_PZ/D");
    //rTree2->Branch("kaon_ETA", &kaon_ETA, "kaon_ETA/D");
    rTree2->Branch("kaon_IPCHI2_OWNPV", &kaon_IPCHI2_OWNPV, "kaon_IPCHI2_OWNPV/D");
    rTree2->Branch("kaon_TRACK_GhostProb", &kaon_TRACK_GhostProb, "kaon_TRACK_GhostProb/D");
    rTree2->Branch("kaon_ProbNNp", &kaon_ProbNNp, "kaon_ProbNNp/D");
    rTree2->Branch("kaon_ProbNNk", &kaon_ProbNNk, "kaon_ProbNNk/D");
    
    rTree2->Branch("proton_M", &proton_M, "proton_M/D");
    rTree2->Branch("proton_P", &proton_P, "proton_P/D");
    rTree2->Branch("proton_PE", &proton_PE, "proton_PE/D");
    rTree2->Branch("proton_PT", &proton_PT, "proton_PT/D");
    rTree2->Branch("proton_PX", &proton_PX, "proton_PX/D");
    rTree2->Branch("proton_PY", &proton_PY, "proton_PY/D");
    rTree2->Branch("proton_PZ", &proton_PZ, "proton_PZ/D");
    //rTree2->Branch("proton_ETA", &proton_ETA, "proton_ETA/D");
    rTree2->Branch("proton_IPCHI2_OWNPV", &proton_IPCHI2_OWNPV, "proton_IPCHI2_OWNPV/D");
    rTree2->Branch("proton_TRACK_GhostProb", &proton_TRACK_GhostProb, "proton_TRACK_GhostProb/D");
    rTree2->Branch("proton_ProbNNp", &proton_ProbNNp, "proton_ProbNNp/D");
    rTree2->Branch("proton_ProbNNk", &proton_ProbNNk, "proton_ProbNNk/D");

    rTree2->Branch("Jpsi_M", &Jpsi_M, "Jpsi_M/D");
    rTree2->Branch("Jpsi_P", &Jpsi_P, "Jpsi_P/D");
    rTree2->Branch("Jpsi_PE", &Jpsi_PE, "Jpsi_PE/D");
    rTree2->Branch("Jpsi_PT", &Jpsi_PT, "Jpsi_PT/D");
    rTree2->Branch("Jpsi_PX", &Jpsi_PX, "Jpsi_PX/D");
    rTree2->Branch("Jpsi_PY", &Jpsi_PY, "Jpsi_PY/D");
    rTree2->Branch("Jpsi_PZ", &Jpsi_PZ, "Jpsi_PZ/D");
    //rTree2->Branch("Jpsi_ETA", &Jpsi_ETA, "Jpsi_ETA/D");     
  
    rTree2->Branch("gamma_M", &gamma_M, "gamma_M/D");
    rTree2->Branch("gamma_P", &gamma_P, "gamma_P/D");
    rTree2->Branch("gamma_PE", &gamma_PE, "gamma_PE/D");
    rTree2->Branch("gamma_PT", &gamma_PT, "gamma_PT/D");
    rTree2->Branch("gamma_PX", &gamma_PX, "gamma_PX/D");
    rTree2->Branch("gamma_PY", &gamma_PY, "gamma_PY/D");
    rTree2->Branch("gamma_PZ", &gamma_PZ, "gamma_PZ/D");
    //rTree2->Branch("gamma_ETA", &gamma_ETA, "gamma_ETA/D");  
    rTree2->Branch("gamma_CL", &gamma_CL, "gamma_CL/D");  

    rTree2->Branch("muminus_M", &muminus_M, "muminus_M/D");
    rTree2->Branch("muminus_P", &muminus_P, "muminus_P/D");
    rTree2->Branch("muminus_PE", &muminus_PE, "muminus_PE/D"); 
    rTree2->Branch("muminus_PT", &muminus_PT, "muminus_PT/D");
    rTree2->Branch("muminus_PX", &muminus_PX, "muminus_PX/D");
    rTree2->Branch("muminus_PY", &muminus_PY, "muminus_PY/D");
    rTree2->Branch("muminus_PZ", &muminus_PZ, "muminus_PZ/D");  
    //rTree2->Branch("muminus_ETA", &muminus_ETA, "muminus_ETA/D");  
    rTree2->Branch("muminus_ProbNNmu", &muminus_ProbNNmu, "muminus_ProbNNmu/D");  
    rTree2->Branch("muminus_TRACK_GhostProb", &muminus_TRACK_GhostProb, "muminus_TRACK_GhostProb/D");  

    rTree2->Branch("muplus_M", &muplus_M, "muplus_M/D");
    rTree2->Branch("muplus_P", &muplus_P, "muplus_P/D");
    rTree2->Branch("muplus_PE", &muplus_PE, "muplus_PE/D");
    rTree2->Branch("muplus_PT", &muplus_PT, "muplus_PT/D");
    rTree2->Branch("muplus_PX", &muplus_PX, "muplus_PX/D");
    rTree2->Branch("muplus_PY", &muplus_PY, "muplus_PY/D");
    rTree2->Branch("muplus_PZ", &muplus_PZ, "muplus_PZ/D");
    //rTree2->Branch("muplus_ETA", &muplus_ETA, "muplus_ETA/D");  
    rTree2->Branch("muplus_ProbNNmu", &muplus_ProbNNmu, "muplus_ProbNNmu/D");  
    rTree2->Branch("muplus_TRACK_GhostProb", &muplus_TRACK_GhostProb, "muplus_TRACK_GhostProb/D");  

    rTree2->Branch("Lambda_b0_DTF_MASS_constr1", &Lambda_b0_DTF_MASS_constr1, "Lambda_b0_DTF_MASS_constr1/D");
    rTree2->Branch("Lambda_b0_DTF_CHI2NDOF", &Lambda_b0_DTF_CHI2NDOF, "Lambda_b0_DTF_CHI2NDOF/D");
    rTree2->Branch("Lambda_b0_IPCHI2_OWNPV", &Lambda_b0_IPCHI2_OWNPV, "Lambda_b0_IPCHI2_OWNPV/D");
    rTree2->Branch("Lambda_b0_L0DiMuonDecision_TOS", &Lambda_b0_L0DiMuonDecision_TOS, "Lambda_b0_L0DiMuonDecision_TOS/B");
    rTree2->Branch("Lambda_b0_L0MuonDecision_TOS", &Lambda_b0_L0MuonDecision_TOS, "Lambda_b0_L0MuonDecision_TOS/B");
    rTree2->Branch("Lambda_b0_FDS", &Lambda_b0_FDS, "Lambda_b0_FDS/D");  
    rTree2->Branch("Lambda_b0_Hlt1DiMuonHighMassDecision_TOS", &Lambda_b0_Hlt1DiMuonHighMassDecision_TOS, "Lambda_b0_Hlt1DiMuonHighMassDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt1DiMuonLowMassDecision_TOS", &Lambda_b0_Hlt1DiMuonLowMassDecision_TOS, "Lambda_b0_Hlt1DiMuonLowMassDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt1TrackMuonDecision_TOS", &Lambda_b0_Hlt1TrackMuonDecision_TOS, "Lambda_b0_Hlt1TrackMuonDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt1TrackAllL0Decision_TOS", &Lambda_b0_Hlt1TrackAllL0Decision_TOS, "Lambda_b0_Hlt1TrackAllL0Decision_TOS/B");
    rTree2->Branch("Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS", &Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS, "Lambda_b0_Hlt1SingleMuonHighPTDecision_TOS/B");  
    rTree2->Branch("Lambda_b0_Hlt2DiMuonDetachedDecision_TOS", &Lambda_b0_Hlt2DiMuonDetachedDecision_TOS, "Lambda_b0_Hlt2DiMuonDetachedDecision_TOS/B"); 
    rTree2->Branch("Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS", &Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS, "Lambda_b0_Hlt2DiMuonDetachedHeavyDecision_TOS/B");
    rTree2->Branch("Lambda_b0_pi0veto", &Lambda_b0_pi0veto, "Lambda_b0_pi0veto/D");
    rTree2->Branch("Lambda_b0_PT", &Lambda_b0_PT, "Lambda_b0_PT/D");

    rTree2->Branch("bdtg", &bdtg, "bdtg/F");
    
    
    
    //This is where the misidentification is calculated for P and K---------------------------
    

    const double mK(0.493677);
    
    double mass_proton_as_proton, mass_proton_as_kaon, mass_kaon_as_kaon;
	
    rTree2->Branch("mass_proton_as_proton", &mass_proton_as_proton, "mass_proton_as_proton/D");
    rTree2->Branch("mass_proton_as_kaon", &mass_proton_as_kaon, "mass_proton_as_kaon/D");
    rTree2->Branch("mass_kaon_as_kaon", &mass_kaon_as_kaon, "mass_kaon_as_kaon/D");
    
    double proton_P = sqrt(proton_PX*proton_PX + proton_PY*proton_PY + proton_PZ*proton_PZ) ;
    
    for(int i = 0; i < rTree1->GetEntries(); ++i){    
    //for event in tree
    
        rTree1->GetEntry(i);
        
        TLorentzVector * proton = new TLorentzVector(proton_PX, proton_PY, proton_PZ, proton_PE);
        TLorentzVector * proton_as_kaon = new TLorentzVector(proton_PX, proton_PY, proton_PZ, sqrt(proton_P*proton_P + mK*mK));
        TLorentzVector * kaon = new TLorentzVector(kaon_PX, kaon_PY, kaon_PZ, kaon_PE);  
              
        mass_proton_as_proton = proton->M();
        mass_proton_as_kaon = proton_as_kaon->M();
        mass_kaon_as_kaon = kaon->M();

        rTree2->Fill();
        
    }
   
    rTree2->Print();
    rTree2->Write();
    rFile->Save();



}
コード例 #23
0
ファイル: effCalc.C プロジェクト: apmorris/project
void effCalc(){ 

    // -- define tuple file name, tuple name and cuts to apply
    // -- and also the name of the output file
    
    const std::string filename = "/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/Lb2chicpK_MC_2011_2012_signal_withbdt.root";
    //const std::string outFilename("/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/");
        
    const std::string treename("withbdt");
    
    const std::string outfile = "~/cern/new_plots/signal_MC_gamma_PT_cut.pdf";
    const std::string xaxis   = "m(#chi_{c1}pK^{-}) (MeV/c^{2})";
    const std::string yaxis   = "Events / 2 MeV/c^{2}";
    const std::string cuts("gamma_PT > 500. ");
    
    //TStopwatch sw;
    //sw.Start();
    std::cout << "Opening file: " << filename.c_str() << endl;
    
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;

    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;
  
    // -- activate the branches you need
  
    tree->SetBranchStatus("*", 1);   
      
    //double n_pre = tree->GetEntries("bdtg>=0.85");
    //std::cout << "# of events in original tree = " << n_pre << endl;  
      
    // -- this file is just here to make the 'CopyTree' happy
    
    std::cout << "Copying tree: " << treename.c_str() << endl;
    
    TFile* newFile = new TFile("/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/dummy.root","RECREATE");
    TTree* rTree1 = tree->CopyTree( cuts.c_str() );
    
    //rTree1->Print();
    rTree1->Write();
    newFile->Save();

    
    double n_post = rTree1->GetEntries();
    
    // Including the LHCb name, formatting
    lhcbName = new TPaveText(gStyle->GetPadLeftMargin() + 0.65,
            0.87 - gStyle->GetPadTopMargin(),
            gStyle->GetPadLeftMargin() + 0.75,
            0.95 - gStyle->GetPadTopMargin(),
            "BRNDC");
    lhcbName->AddText("LHCb");
    lhcbName->SetFillColor(0);
    lhcbName->SetTextAlign(12);
    lhcbName->SetBorderSize(0);

    gStyle->SetOptStat(0);	

/*
    titleBox = new TPaveText(gStyle->GetPadLeftMargin() + 0.3,
            0.98 - gStyle->GetPadTopMargin(),
            0.98 - gStyle->GetPadLeftMargin(),
            0.83 - gStyle->GetPadTopMargin(),
            "BRNDC");
    titleBox->AddText(title.c_str());
    titleBox->SetFillColor(0);
    titleBox->SetTextAlign(12);
    titleBox->SetBorderSize(0);
*/
    
    

    // plotting ------------------------------------------------------------------- 

    // Define the histograms
    TH1D* h1 = new TH1D ("h1", "Effect of cutting #gamma pT on simulated sample post-selection", 100, 5500., 5700.);
    TH1D* h2 = new TH1D ("h2", "Effect of cutting #gamma pT on simulated sample post-selection", 100, 5500., 5700.);
    
    
    // Differentiating the two histos from each other
    //h1->Sumw2(); 	
    //h2->Sumw2();
    
    //h1->SetMarkerStyle(kFullDotLarge);
    h1->SetMarkerSize(0.7);
   
    h2->SetMarkerColor(kRed);
    //h2->SetMarkerStyle(kFullDotLarge);
    h2->SetMarkerSize(0.7);
    h2->SetLineColor(kRed);
    

    // Draw the histograms 
    rTree1->Draw("Lambda_b0_DTF_MASS_constr1>>h1", "", "goff"); 	
    tree->Draw("Lambda_b0_DTF_MASS_constr1>>h2", "", "goff");

    
    // Setting up canvas
    TCanvas* c1 = new TCanvas();
    c1->Divide(1,1);
    c1->cd(1);


    // Plotting 
    
    h2->Draw(); 
    h1->Draw("same");
    //h1->SetTitle( title.c_str() );
    h2->GetXaxis()->SetTitle( xaxis.c_str() );	
    h2->GetYaxis()->SetTitle( yaxis.c_str() );
    h2->GetXaxis()->SetLabelSize(0.04);
    h2->GetYaxis()->SetLabelSize(0.035);
    h2->GetXaxis()->SetTitleSize(0.04);
    h2->GetYaxis()->SetTitleSize(0.04);
    //lhcbName->Draw();	
    //titleBox->Draw();
    
    leg = new TLegend(0.75,0.8,0.9,0.9);
    //leg->SetHeader("The Legend Title");
    
    leg->AddEntry(h2,"before cut","l");
    leg->AddEntry(h1,"after cut","l");
    leg->Draw();	
    
    //int Nhisto1 = t1->GetEntries("");
    //c1->SaveAs( outfile.c_str() );   
    
    
    //sw.Stop();
    double n_pre = h2->Integral();
    double efficiency = n_post/n_pre;
    double error = sqrt(efficiency*(1.-efficiency)/n_pre);
    
    std::cout << "# of events in the tree before cut applied = " << n_pre << endl;
    std::cout << "Efficiency = " << efficiency << endl;
    std::cout << "Error = " << error << endl;


    //std::cout << "Total time elapsed: "; sw.Print();

}