Esempio n. 1
0
void mc2ibd_NE(TChain *tMC, TFile *fBgnd, TCanvas *cv)
{
	char str[1024];
	TLatex *txt = new TLatex();

	TH1D *hExp = (TH1D *) fBgnd->Get("hNEA-diff");
	if (!hExp) {
		printf("Histogram hNEA-diff not found in %s\n", fBgnd->GetName());
		return;
	}
	hExp->SetTitle("Delayed event energy;MeV;Events/200 keV");
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);

	gROOT->cd();
	TH1D *hMC = new TH1D("hNEMC", "Delayed event energy (MC);MeV;Events/200 keV", 45, 3, 12);
	hMC->SetLineColor(kBlue);
	tMC->Project(hMC->GetName(), "NeutronEnergy", cX && cY && cZ && cR && c20 && cGamma && cGammaMax && cPe);
	hMC->Sumw2();
	hMC->Scale(hExp->Integral(15, 45) / hMC->Integral(15,45));
	
	cv->Clear();
	hMC->Draw("hist");
	hExp->DrawCopy("same");
	TLegend *lg = new TLegend(0.65, 0.8, 0.89, 0.89);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC, "MC", "L");
	lg->Draw();
}
Esempio n. 2
0
void PrintHistogram(TH1D h) {
    gStyle->SetOptStat("eimr");
    TCanvas c("c","c",800,500);
    h.Draw();
    system("mkdir -p parms_timewalk");
    c.Print("parms_timewalk/"+TString(h.GetName())+".gif");
}
Esempio n. 3
0
void mc2ibd_R2(TChain *tMC, TFile *fBgnd, TCanvas *cv)
{
	char str[1024];
	TLatex *txt = new TLatex();

	TH1D *hExp = (TH1D *) fBgnd->Get("hR2A-diff");
	if (!hExp) {
		printf("Histogram hR2A-diff not found in %s\n", fBgnd->GetName());
		return;
	}
	hExp->SetTitle("Distance between positron and neutron, 3D case;cm;Events/4cm");
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);

	gROOT->cd();
	TH1D *hMC = new TH1D("hR2MC", "Distance between positron and neutron, 3D case (MC);cm;Events/4cm", 40, 0, 160);
	hMC->SetLineColor(kBlue);
	tMC->Project(hMC->GetName(), "Distance", cX && cY && cZ && cRXY && c20 && cGamma && cGammaMax && cPe && cN);
	hMC->Sumw2();
	hMC->Scale(hExp->Integral() / hMC->Integral());
	
	cv->Clear();
	hExp->DrawCopy();
	hMC->Draw("hist,same");
	TLegend *lg = new TLegend(0.65, 0.8, 0.89, 0.89);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC, "MC", "L");
	lg->Draw();
}
Esempio n. 4
0
void Draw_KL_Test(){

  TChain* ch = new TChain("Tree");
  TChain* ch1 = new TChain("Tree");
  
  TH1D* his  = new TH1D("Klong6g","Klong6g",20,450,550);
  TH1D* his1 = new TH1D("Klong4g","Klong4g",20,450,550);
  TH1D* his2 = new TH1D("Klong4gAll","Klong4gAll",60,250,550);

  for( int i = 0; i< 68; i++){
    ch->Add(Form("klongRootFile/kl%d.root" ,4162+i));
    ch1->Add(Form("klongRootFile/ks%d.root",4162+i));
  }
  ch->Project(his->GetName()  ,"KlongMass[0]","CutCondition==0");
  ch1->Project(his1->GetName(),"KlongMass[0]","CutCondition==0");
  ch1->Project(his2->GetName(),"KlongMass[0]","CutCondition==0");
  
  TF1* func = new TF1("func","gaus(0)+expo(3)",0,550);
  func->SetParameter(1,498);
  func->SetParameter(2,5);
  TF1* func2 = new TF1("func2","gaus(0)",0,550);
  func2->SetParameter(1,498);
  func2->SetParameter(2,5);



  TCanvas* can = new TCanvas("can","",1200,600);
  can->Divide(2,1);
  can->cd(1);
  his2->Fit(func->GetName(),"","",450,550);
  his2->Draw();
  TF1* func1 = new TF1("Test","gaus",450,550);
  func1->SetParameter(0,func->GetParameter(0));
  func1->SetParameter(1,func->GetParameter(1));
  func1->SetParameter(2,func->GetParameter(2));

  can->cd(2);
  his1->SetLineColor(2);  
  his->Draw();
  his->Fit(func2->GetName(),"","",450,550);
  func->Draw("same");
  his1->Draw("same");

  std::cout<< func2->GetParameter(0) << " " 
	   << func->GetParameter(0)  << " " 
	   << func->GetParameter(0)/func2->GetParameter(0)<< std::endl;
  std::cout<< func2->Integral(450,550) << " " 
	   << func1->Integral(450,550)  << " " 
	   << func1->Integral(450,550)/func2->Integral(450,550)
	   << std::endl;
  //ch->Draw("KlongPt[0]:KlongMass[0]>>(400,200,600,50,0,20)","(CutCondition&(1|2|4|8))==0","colz");
  gPad->SetLogz();
  TText* text = new TText(0.5,0.5,"");
  TText* text1 = new TText(0.5,0.5,"");
  text->DrawTextNDC(0.5,0.5,Form("Integral:%2.3lf",func1->Integral(450,550)));
  text1->DrawTextNDC(0.5,0.6,Form("Integral:%2.3lf",func2->Integral(450,550)));
  
}
Esempio n. 5
0
scalePair energyCorrectionDiff(TCut centCut1, float lowPt, float highPt, float lowEta, float highEta,TCut addCut) { 
   
   TString fname1 = "forest/barrelHiForestPhoton_MCphoton50_51k.root";
   if ( lowPt > 90 ) 
      fname1 = "forest/barrelHiForestPhoton_MCphoton80_28k.root";
   TFile *f1  =new TFile(fname1.Data());
   TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
   photon1->AddFriend("yEvt=yongsunHiEvt"    ,fname1.Data());
   photon1->AddFriend("ySkim=yongsunSkimTree"   ,fname1.Data());
   photon1->AddFriend("yHlt=yongsunHltTree"     ,fname1.Data());
   
   TCut collisionCut = "ySkim.pcollisionEventSelection==1";
   
   TCut hoeCut = "hadronicOverEm<0.2";
   TCut isoCut = "cc4 + cr4 + ct4j20 < 5 && sigmaIetaIeta<0.011";
   TCut ptCut  = Form("genMatchedPt>%.f && genMatchedPt <%.f",lowPt, highPt);
   TCut etaCut = Form("abs(eta)>%f && abs(eta)<%f",lowEta,highEta);
      
   TCut finalCut1 = genMatchCut1 && collisionCut && centCut1 && hoeCut && isoCut && ptCut && etaCut && addCut ; 
   TString variable1 = "pt/genMatchedPt";
   
   TH1D* hScale = new TH1D("hScale","",100,.5,1.5);
   TH1D* hdpt = new TH1D("hdpt","",100,-20,20);
   photon1->Draw(Form("%s>>%s",variable1.Data(),hScale->GetName()), finalCut1);
   photon1->Draw(Form("pt-genMatchedPt>>%s",hdpt->GetName()),       finalCut1);
   cout << "cut = " << finalCut1.GetTitle() <<endl;
   hScale->Draw();
   hdpt->Draw();
   TF1* ff =  cleverGaus(hScale);
   
   scalePair ret;
   double *ps = ff->GetParameters();
   ret.val = ps[1];
   ret.err = ff->GetParError(1);
   // resErr = ff->GetParError(2);
   ret.res  = ps[2];
   ret.resErr = ff->GetParError(2);  
   ret.absVal = hdpt->GetMean();
   cout <<"scale = " << ret.val << " +-" << ret.err << endl;
   return ret;
}
Esempio n. 6
0
void makeplot(const char *name, TTree *tree, TCut weight, const char *drawstring, const char *xlabel, int nbins, double xlow, double xhigh) {
  
  //this is for NLO with FXFX merging
//    TCut mult0 = "LHEEvent.npNLO()==0";
//    TCut mult1 = "LHEEvent.npNLO()==1";
//    TCut mult2 = "LHEEvent.npNLO()==2";
//    TCut mult3 = "LHEEvent.npNLO()==3";
  
  //this is for LO with MLM
   TCut mult0 = "GenEvent.nMEPartons()==0";
   TCut mult1 = "GenEvent.nMEPartons()==1";
   TCut mult2 = "GenEvent.nMEPartons()==2";
   TCut mult3 = "GenEvent.nMEPartons()==3";

  //this is for LO with MLM (plotting partons after excluding non-matched partons in wbb/vbf type processes)
  //   TCut mult0 = "GenEvent.nMEPartonsFiltered()==0";
  //   TCut mult1 = "GenEvent.nMEPartonsFiltered()==1";
  //   TCut mult2 = "GenEvent.nMEPartonsFiltered()==2";
  
  TH1D *hall = new TH1D(TString::Format("hall_%s",name),"",nbins,xlow,xhigh);
  TH1D *hmult0 = new TH1D(TString::Format("hmult0_%s",name),"",nbins,xlow,xhigh);
  TH1D *hmult1 = new TH1D(TString::Format("hmult1_%s",name),"",nbins,xlow,xhigh);
  TH1D *hmult2 = new TH1D(TString::Format("hmult2_%s",name),"",nbins,xlow,xhigh);
  TH1D *hmult3 = new TH1D(TString::Format("hmult3_%s",name),"",nbins,xlow,xhigh);
  
  hmult0->SetLineColor(kBlue);
  hmult1->SetLineColor(kRed);
  hmult2->SetLineColor(kMagenta);
  hmult3->SetLineColor(kGreen+1);
  
  tree->Draw(TString::Format("%s>>%s",drawstring,hall->GetName()),weight,"goff");
  tree->Draw(TString::Format("%s>>%s",drawstring,hmult0->GetName()),weight*mult0,"goff");
  tree->Draw(TString::Format("%s>>%s",drawstring,hmult1->GetName()),weight*mult1,"goff");
  tree->Draw(TString::Format("%s>>%s",drawstring,hmult2->GetName()),weight*mult2,"goff");
  tree->Draw(TString::Format("%s>>%s",drawstring,hmult3->GetName()),weight*mult3,"goff");
  
  hall->GetXaxis()->SetTitle(xlabel);
  
  TCanvas* c = new TCanvas(name,name);
  c->cd();
  hall->SetLineWidth(2);
  hall->Draw("EHIST");
  hmult0->SetLineWidth(2);
  hmult0->Draw("EHISTSAME");
  hmult1->SetLineWidth(2);
  hmult1->Draw("EHISTSAME");
  hmult2->SetLineWidth(2);
  hmult2->Draw("EHISTSAME");
  hmult3->SetLineWidth(2);
  hmult3->Draw("EHISTSAME");
  c->SetLogy();
  c->SaveAs(TString::Format("%s.pdf",name));
}
Esempio n. 7
0
void photonSpectra()
{
  TH1::SetDefaultSumw2();

  const Double_t PTBINS[] = {40, 50, 60, 80, 120, 300};
  const Int_t nPTBINS = 5;

  const TString DATA_FILE = "gammaJets_pA_Data.root";
  const TString MC_FILE = "gammaJets_pA_MC_allQCDPhoton.root";
  TFile *dataFile = TFile::Open(DATA_FILE);
  TTree *dataTree = (TTree*)dataFile->Get("photonTree");
  TFile *mcFile = TFile::Open(MC_FILE);
  TTree *mcTree = (TTree*)mcFile->Get("photonTree");

  TH1D *photonSpectra = new TH1D("photonSpectra","photonSpectra", nPTBINS, PTBINS);
  TH1D *correctedPhotonSpectra = (TH1D*)photonSpectra->Clone("correctedPhotonSpectra");

  const TCut photonEtaCut = "abs(photonTree.eta) < 1.44";
  const TCut isoCut = "ecalRecHitSumEtConeDR04 < 4.2  &&  hcalTowerSumEtConeDR04 < 2.2  &&  trkSumPtHollowConeDR04 < 2 && hadronicOverEm<0.1";
  const TCut genCut = "genCalIsoDR04<5 && abs(genMomId)<=22";
  const TCut sbCut = "(cc4+cr4+ct4PtCut20>10) && (cc4+cr4+ct4PtCut20<20) && hadronicOverEm<0.1";
  const TCut candidateCut = "sigmaIetaIeta<0.01";
  const TCut decayCut = "(sigmaIetaIeta>0.011) && (sigmaIetaIeta<0.017)";

  TCut photonPtCut = "photonTree.corrPt>40 && photonTree.corrPt<300";

  dataTree->Project(photonSpectra->GetName(),"corrPt",isoCut && photonEtaCut && photonPtCut && candidateCut);

  for(int i = 0; i<nPTBINS; ++i)
  {
    photonPtCut = Form("photonTree.corrPt>%f && photonTree.corrPt<%f", PTBINS[i], PTBINS[i+1]  );

    TCut dataCandidateCut = isoCut && photonEtaCut && photonPtCut;
    TCut sidebandCut =  sbCut && photonEtaCut && photonPtCut;
    TCut mcSignalCut = dataCandidateCut && genCut;

    fitResult fitr = getPurity(dataTree, mcTree,
  			       dataCandidateCut, sidebandCut,
  			       mcSignalCut);
    Double_t purity = fitr.purity;
    correctedPhotonSpectra->SetBinContent(i+1,photonSpectra->GetBinContent(i+1)*purity);
  }

  // TCanvas *c1 = new TCanvas();
  // photonSpectra->Draw();
  // correctedPhotonSpectra->Draw("same");

  TFile *outFile = new TFile("photonSpectra.root", "RECREATE");
  outFile->cd();
  photonSpectra->Write();
  correctedPhotonSpectra->Write();
  outFile->Close();
}
Esempio n. 8
0
void MakeHQTHiggsPtDistribution( string inputFilename ,  const string Label) {

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
  string label = "";
  if (Label != "") label = "_" + Label;
 


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  ifstream infile(inputFilename.c_str());
  vector<double> lowEdges;
  vector<double> binContent;
  double x_min;
  double x_max;
  double y;
  Int_t binNumber = 1;
  while(infile >> x_min) {
    infile >> x_max >> y;
    lowEdges.push_back(x_min);
    binContent.push_back(y);
  }

  Double_t *xLowEdges = new Double_t[lowEdges.size()];
  for (UInt_t i=0; i < lowEdges.size();i++) {
    xLowEdges[i] = lowEdges[i];
  }


  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *bosonSystemPt = new TH1D((string("HiggsPt")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", lowEdges.size()-1, xLowEdges);

  for (UInt_t i=1;i<lowEdges.size();i++) {
    bosonSystemPt->SetBinContent(i,binContent[i]);
  }

  TFile *file = new TFile("HwwAcceptanceSystematics.root", "UPDATE");
  file->WriteTObject(bosonSystemPt, bosonSystemPt->GetName(), "WriteDelete");
  file->Close();

}
Esempio n. 9
0
Spectrum roothist_to_spectrum(const TH1D & hist, const TH2D * cov, bool use_hist_uncertainties){
    const int n = hist.GetNbinsX();
    if(cov){
        if(cov->GetDimension() != 2 || cov->GetNbinsX() != n || cov->GetNbinsY() != n){
            throw runtime_error(string("covariance histogram '") + cov->GetName() + "' has wrong dimension");
        }
    }
    Spectrum s(n);
    for(int i=0; i<n; ++i){
        double c = hist.GetBinContent(i+1);
        if(!isfinite(c)){
            throw runtime_error(string("non-finite entry in histogram '") + hist.GetName() + "'");
        }
        s[i] = c;
        if(use_hist_uncertainties){
            double e = hist.GetBinError(i+1);
            if(!isfinite(e)){
                throw runtime_error(string("non-finite error in histogram '") + hist.GetName() + "'");
            }
            s.cov()(i,i) += e*e;
        }
    }
    if(cov){
        for(int i=0; i<n; ++i){
            for(int j=0; j<n; ++j){
                double c_ij = cov->GetBinContent(i+1, j+1);
                double c_ji = cov->GetBinContent(j+1, i+1);
                if(!isfinite(c_ij)){
                    throw runtime_error(string("covariance histogram '") + cov->GetName() + "' does have non-finite entry");
                }
                if(fabs(c_ij - c_ji) > 1e-8 * max(fabs(c_ij), 1.0)){
                    cerr << "covariance histogram '" << cov->GetName() <<  "' is not symmetric: C(" << i << ","<< j << ") = " << c_ij << "; transposed: " << c_ji << "; diff = " << (c_ij - c_ji) << endl;
                }
                s.cov()(i,j) += c_ij;
            }
        }
    }
    return s;
}
void CompareCFLADiffCuts()
{
  TFile newFile("~/Analysis/lambda/AliAnalysisLambda/Results/2016-01/15-NoOppChargeCut/All/CFs.root");
  TDirectory *newDir = newFile.GetDirectory("Merged");
  vector<TH1D*> newCFs;
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam010"));
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam1030"));
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam3050"));

  TFile oldFile("~/Analysis/lambda/AliAnalysisLambda/Results/2016-01/08-NewAvgSepCuts/All/CFs.root");
  TDirectory *oldDir = oldFile.GetDirectory("Merged");
  vector<TH1D*> oldCFs;
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam010"));
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam1030"));
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam3050"));

  TFile *compareFile = new TFile("Compare.root","update");
  TDirectory *dir = compareFile->GetDirectory("Delta");
  if(!dir) dir = compareFile->mkdir("Delta");
  for(UInt_t i = 0; i < newCFs.size(); i++) {
    // TH1D *ratio = (TH1D*)newCFs[i]->Clone();
    // TString name = ratio->GetName();
    // ratio->SetName(name + "Ratio");
    // ratio->SetTitle(name + "Ratio");
    // ratio->Divide(oldCFs[i]);

    // TH1D *barlowRatio = ComputeRogerBarlowRatio(newCFs[i], oldCFs[i]);
    // barlowRatio->SetName(name + "BarlowRatio");
    // barlowRatio->SetTitle(name + "BarlowRatio");

    TString name = newCFs[i]->GetName();
    TH1D *barlowDifference = ComputeRogerBarlowDifference(newCFs[i], oldCFs[i]);
    barlowDifference->SetName(name + "BarlowDifference");
    barlowDifference->SetTitle(name + "BarlowDifference");
    
    dir->cd();
    // ratio->Write();
    // barlowRatio->Write();
    barlowDifference->Write(barlowDifference->GetName(), TObject::kOverwrite);
    Chi2TestWithZero(barlowDifference);
    FitWithConstant(barlowDifference, compareFile);
    // LookAtMean(barlowDifference);
    RebinHist(barlowDifference, compareFile);
    ManuallyRebin(barlowDifference, compareFile);
  }
    
  compareFile->Close();
}
void CalcQCDNormFactor() {
  //TFile *f = TFile::Open("results/Plotter_out_2016_05_29_22h19m32.root"); // 76X Silver JSON
  TFile *f = TFile::Open("results/Plotter_out_2016_06_21_15h27m59.root"); // 76X Golden JSON
  TCanvas *c = (TCanvas*)f->Get("NJet/PlotSamples_Pass5Cuts_PassHLT");
  THStack *s = (THStack*)c->GetListOfPrimitives()->At(1);
  TH1D *data = (TH1D*)c->GetListOfPrimitives()->At(3);
  double MC_integral = 0;
  double QCD_count = 0;
  for (int i=s->GetHists()->GetEntries()-1; i>=0; --i) {
    TH1D* h = (TH1D*)s->GetHists()->At(i);
    if (i==s->GetHists()->GetEntries()-1) QCD_count = h->Integral();
    std::cout<<h->GetName()<<" "<<h->Integral()<<std::endl;
    MC_integral += h->Integral();
  }
  double data_QCD_estimate = data->Integral()- (MC_integral-QCD_count);
  double QCD_scale = data_QCD_estimate/QCD_count;
  std::cout<<"MC:                  "<<MC_integral<<std::endl;
  std::cout<<"Data:                "<<data->Integral()<<std::endl;
  std::cout<<"MC   (QCD only):     "<<QCD_count<<std::endl;
  std::cout<<"Data (QCD only est): "<<data_QCD_estimate<<std::endl;
  std::cout<<"QCD Scale: "<<QCD_scale<<std::endl;

  TH1D* qcd = (TH1D*)s->GetHists()->At(s->GetHists()->GetEntries()-1);
  qcd->Scale(QCD_scale);
  c->Draw();
  
  //TCanvas *c = (TCanvas*)f->Get("NJet/PlotSamples_Pass5Cuts_PassHLT_Ratio");
  //
  //TH1D* ratio = (TH1D*)((TVirtualPad*)c->cd(2))->GetListOfPrimitives()->At(0);
  //TF1* fit = new TF1("fit","pol1", 400, 2000);
  //ratio->Fit("fit","RBQ0");
  //fit->SetLineColor(2);
  //fit->SetLineWidth(1);
  //TF1* fit_up   = (TF1*)fit->Clone("fit_up");
  //TF1* fit_down = (TF1*)fit->Clone("fit_down");
  //fit_up  ->SetParameter(0,fit->GetParameter(0)+fit->GetParError(0)*1);
  //fit_down->SetParameter(0,fit->GetParameter(0)-fit->GetParError(0)*1);
  //fit_up  ->SetParameter(1,fit->GetParameter(1)+fit->GetParError(1)*1);
  //fit_down->SetParameter(1,fit->GetParameter(1)-fit->GetParError(1)*1);
  //fit_up  ->SetLineColor(4); fit_up  ->Draw("SAME");
  //fit_down->SetLineColor(4); fit_down->Draw("SAME");
  //fit->Draw("SAME");
  //
  //std::cout<<"Fit result:"<<std::endl;
  //std::cout<<"p0: "<<fit->GetParameter(0)<<" +- "<<fit->GetParError(0)*1<<std::endl;
  //std::cout<<"p1: "<<fit->GetParameter(1)<<" +- "<<fit->GetParError(1)*1<<std::endl;
  //f->Close();  
}
void ManuallyRebin(TH1D* h1, TFile *out)
{
  cout<<"Taking weighted average"<<endl;
  Int_t nCombine = 40; // Merge 100 bins into 1

  Int_t totalBins = h1->GetNbinsX();
  Int_t finalBins = totalBins/nCombine;
  cout<<"Final N bins:\t"<<finalBins<<endl;
  TString newName = h1->GetName();
  newName += "WgtAvg";
  TH1D *newH = new TH1D(newName, newName, finalBins,
			h1->GetXaxis()->GetXmin(),
			h1->GetXaxis()->GetXmax());
  newH->SetLineColor(kGreen);

  for(Int_t iNewBin = 0; iNewBin < finalBins; iNewBin++)
  {
    Double_t weightedSum = 0.;
    Double_t weights = 0.;
    
    for(Int_t iOldBin = 1; iOldBin < nCombine+1; iOldBin++)
    {
      Int_t binNum = iNewBin * nCombine + iOldBin;
      Double_t errorSq = pow(h1->GetBinError(binNum), 2.);
      Double_t content = h1->GetBinContent(binNum);

      weights += 1./errorSq;
      weightedSum += (1./errorSq) * content;
    }

    Double_t avg = weightedSum/weights;
    Double_t newErr = 1./sqrt(weights);

    newH->SetBinContent(iNewBin + 1, avg);
    newH->SetBinError(iNewBin + 1, newErr);
  }

  TDirectory *dir = out->GetDirectory("WeightedAvg");
  if(!dir) {
    dir = out->mkdir("WeightedAvg");
  }
  dir->cd();
  newH->SetDirectory(0);
  newH->Write(newH->GetName(), TObject::kOverwrite);
  
  // dir->Close();
  
}
void ecalSpectra()
{
  TH1::SetDefaultSumw2();

  //const Double_t PTBINS[] = {0,2.5,5,7.5,10,12.5,15,17.5, 20,25, 30,35, 40, 50, 60, 80, 120, 300};
  //const Int_t nPTBINS = 5;
  //const Int_t nPTBINS = sizeof(PTBINS)/sizeof(Double_t) -1;

  TChain *ecalTree = new TChain("ecalTree");
  ecalTree->Add("pA_promptRECO/*.root");
  //ecalTree->Add("pA_promptRECO/89.root");
  //TH1D *ecalSpectra = new TH1D("ecalSpectra","ecalSpectra", nPTBINS, PTBINS);
  TH1D *ecalSpectra = new TH1D("ecalSpectra","ecalSpectra",300,0,300);

  // const TCut ecalEtaCut = "abs(ecalTree.eta) < 1.44";
  // const TCut isoCut = "ecalRecHitSumEtConeDR04 < 4.2  &&  hcalTowerSumEtConeDR04 < 2.2  &&  trkSumPtHollowConeDR04 < 2 && hadronicOverEm<0.1";
  // const TCut genCut = "genCalIsoDR04<5 && abs(genMomId)<=22";
  // const TCut sbCut = "(cc4+cr4+ct4PtCut20>10) && (cc4+cr4+ct4PtCut20<20) && hadronicOverEm<0.1";
  // const TCut candidateCut = "sigmaIetaIeta<0.01";
  // const TCut decayCut = "(sigmaIetaIeta>0.011) && (sigmaIetaIeta<0.017)";

  //TCut ecalPtCut = "ecalTree.corrPt>40 && ecalTree.corrPt<300";

  //const TCut triggerCut = "HLT_PAPhoton10_NoCaloIdVL_v1 && HLT_PAPhoton10_NoCaloIdVL_v1_Prescl==1 && L1_SingleEG5_BptxAND_Prescl==1";
  const TCut triggerCut = "HLT_PAPhoton10_NoCaloIdVL_v1";
  const TCut showerCut = "sigmaIetaIeta > 0.011";
  const TCut etaCut = "abs(eta) < 1.44";
  //const TCut trackerIso = "trkSumPtHollowConeDR04 > 2";
  const TCut ecalIso = "ecalRecHitSumEtConeDR04 > 4.2";
  //const TCut hcalIso
  Int_t count = ecalTree->Project(ecalSpectra->GetName(),"pt", triggerCut && showerCut && etaCut && ecalIso);
  printf("Num events: %i\n", count);

  TCanvas *c1 = new TCanvas();
  ecalSpectra->Draw();
  // correctedEcalSpectra->Draw("same");
  c1->SetLogy();

  // TFile *outFile = new TFile("ecalSpectra.root", "RECREATE");
  // outFile->cd();
  // ecalSpectra->Write();
  // correctedEcalSpectra->Write();
  // outFile->Close();
}
Esempio n. 14
0
void mc2ibd_PPX(char X, TChain *tMC, TFile *fBgnd, TCanvas *cv)
{
	char str[1024];
	TH1D *hExp;
	TH1D *hMC;
	TCut cut;

	sprintf(str, "hP%cA-diff", X);
	hExp = (TH1D *) fBgnd->Get(str);
	if (!hExp) {
		printf("Histogram hP%cA-diff not found in %s\n", X, fBgnd->GetName());
		return;
	}
	gROOT->cd();
	sprintf(str, "hMCPP%c", X);
	hMC = new TH1D(str, "MC XYZ", hExp->GetNbinsX(), 0, 100);
	sprintf(str, "PositronX[%d]+%4.1f", X - 'X', (X=='Z') ? 0.5 : 2.0);
	switch (X) {
	case 'X':
		cut = cY && "PositronX[0]>=0" && cZ && cR && c20 && cGamma && cGammaMax && cPe && cN;
		break;
	case 'Y':
		cut = cX && "PositronX[1]>=0" && cZ && cR && c20 && cGamma && cGammaMax && cPe && cN;
		break;
	default:
		cut = cX && cY && cR && c20 && cGamma && cGammaMax && cPe && cN;
	}
	tMC->Project(hMC->GetName(), str, cut);
	hMC->Sumw2();
	cv->Clear();
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);
	hMC->SetLineColor(kBlue);
	hMC->SetLineWidth(1);
	hMC->Scale(hExp->Integral() / hMC->Integral());
	hExp->Draw();
	hMC->Draw("hist,same");
	TLegend *lg = new TLegend(0.5, 0.2, 0.65, 0.35);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC,  "MC",  "L");
	lg->Draw();
	cv->Update();
}
void RebinHist(TH1D* h1, TFile *out)
{
  // This rebinning method doesn't work
  // It needs to divide by the entries to make an average
  // Also, it doesn't include error weighting.
  cout<<"Rebinning histogram"<<endl;
  Int_t nBins = h1->GetNbinsX();
  TH1D *rebinHist = (TH1D*) h1->Clone();
  rebinHist->Rebin(nBins/2);

  // TFile out("Compare.root","update");
  TDirectory *dir = out->GetDirectory("Rebin");
  if(!dir) dir = out->mkdir("Rebin");
  dir->cd();

  TString histName = h1->GetName();
  histName += "Rebin";
  rebinHist->SetName(histName);
  rebinHist->SetTitle(histName);
  rebinHist->SetDirectory(0);
  rebinHist->Write(rebinHist->GetName(), TObject::kOverwrite);
  // out->Close();

}
Esempio n. 16
0
void CombineCentralitiesForDirectory(TString pairType, TDirectory *dataDir)
{
  // Gather the cfs and counts to combine centrality bins


  vector<TString> centBins010 = {"05", "510"};
  vector<TString> centBins1030 = {"1015", "1520", "2025", "2530"};
  vector<TString> centBins3050 = {"3035", "3540", "4045", "4550"};
  vector<TString> finalCentBins = {"010", "1030", "3050"};
  vector<vector<TString> > centBins;
  centBins.push_back(centBins010);
  centBins.push_back(centBins1030);
  centBins.push_back(centBins3050);

  TDirectory *mergeDir = dataDir->GetDirectory("Merged");
  if(!mergeDir) {
    cout<<"Merge directory does not exist. Cannot merge."<<endl;
    return;
  }

  //For each merge group, get the necessary CFs and counts
  for(UInt_t iMerge = 0; iMerge < centBins.size(); iMerge++) {
    vector<TH1D*> cfs;
    vector<Double_t> counts;
    Double_t totalCounts = 0;
    for(UInt_t iCF = 0; iCF < centBins[iMerge].size(); iCF++) {
      TString cfName = "CF" + pairType + centBins[iMerge][iCF];
      TH1D *cf = (TH1D*)mergeDir->Get(cfName);
      if(!cf) {
	cout<<"Could not find CF named "<<cfName<<" in "<<mergeDir->GetName()<<endl;
	return;
      }
      cfs.push_back(cf);
      TString countName = "Count" + pairType + centBins[iMerge][iCF];
      TVectorD *count = (TVectorD*) mergeDir->Get(countName);
      totalCounts += count[0](0);
      counts.push_back(count[0](0));
    }

    // Finally, combine the CFs
    TH1D *combinedCF = CombineCFs(cfs, counts);
    if (!combinedCF) {
      cout << "Combine CF returned nothing. Continuing loop."
	   <<endl;
      continue;
    }
    TVectorD finalCount(1);
    finalCount[0] = totalCounts;

    // Set names
    TString combinedCFName = "CF" + pairType + finalCentBins[iMerge];
    TString combinedCountName = "Count" + pairType + finalCentBins[iMerge];
    combinedCF->SetName(combinedCFName);
    combinedCF->SetTitle(combinedCFName);

    // Set axis ranges
    combinedCF->SetAxisRange(0.9, 1.1, "Y");
    combinedCF->SetAxisRange(0., .5, "X");
    combinedCF->SetLabelSize(0.05, "X");
    combinedCF->SetLabelSize(0.05, "Y");
    combinedCF->SetTitleSize(0.05, "X");
    combinedCF->SetNdivisions(505, "X");
    combinedCF->SetNdivisions(505, "Y");
    
    cout<<"Writing combined CF "<<combinedCF->GetName()
    	<<" to "<<mergeDir->GetName()<<endl;
    combinedCF->SetDirectory(0);
    mergeDir->cd();
    combinedCF->Write(combinedCF->GetName(), TObject::kOverwrite);
    finalCount.Write(combinedCountName, TObject::kOverwrite);
  }
}
Esempio n. 17
0
void packTemplatesMass(const int iMass) {
  // This Root macro is for the purpose of providing input for expected limit computation
  // It packs predicted background and a set of signal samples into a root file per Higgs mass
  // 
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  canvas = new TCanvas ("cg1","PadX",10,10,800,600);
  gStyle->SetPadColor(0);
  canvas->SetFillColor(0);

//   const int nbtag = 4;
  const int nbtag = 1;
  //const std::string sbtag[nbtag] = { "TCHPT", "TCHP6", "CSVT", "SSVHPT" };
  const std::string sbtag[nbtag] = { "CSVT" };

  const int nfc=3;
  const int ncateg=3;
  string sfc[nfc] = { "q", "c", "b" };

  // this is for the combination of triggers in real data
  int nTCombData = 4;
  std::string tCombData[] = {"Trig0", "Trig1", "Trig2", "Trig3"};

  std::string L1L2Mode("Weight");
  std::string signalMode("PU_WEIGHTED-NEW");
//   std::string L1L2Mode("Cut");
//   std::string signalMode("CUT_BASED");

  //std::string scenario("LowMass2011");
  //std::string scenario("MediumMass2011");

  std::string scenario;
  bool useTemplateError;
  bool useNP;
  if (  getHbbCfg(scenario,useTemplateError,useNP) != 0 ) return;

  string IgorVersion("V6");

#include "Analysis/Utilities/interface/HbbMass.h"

  if (iMass >= nSignal) {
    std::cout << "Bad iMass=" << iMass << std::endl;
    return;
  }
//   const int nSignal=7;
//   int signalMass[nSignal] = { 90, 100, 120, 140, 180, 250, 350 };
  // int signalMass[nSignal] = { 90, 100, 120, 130, 140, 160, 180, 200, 250, 350 }
  //  there are also : 450, 500, 600, 700, 800, 900, 1000
//   double efficiency[nSignal] = { 0.0022081, 0.00324694, 0.00600146, 0.00918135,
// 				0.0138382, 0.0189684, 0.0206572 };
  double efficiency[nSignal][nbtag];
  double intLumi = 0;
  string IgorScen("");
  string spacer("");
  string SashaPath("");
  string IgorPath("/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/SignalTemplates-Production");

  if (IgorVersion == "V4") {
    IgorPath.assign("/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/Systematics-test-4");
  } else if (IgorVersion == "V6") {
    IgorPath.assign("/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/SignalTemplates-Production2");
  }

  if (scenario == "LowMass2011") {
    //intLumi = 2.66794; // in fb-1
    intLumi = 2.692643;  // with new method
    IgorScen.assign("low");
    spacer.assign("");
    //SashaPath.assign("Data-Run2011AB");
    SashaPath.assign("Data-Run2011AB/TripleBtagAnalysis_CR3_SF7");
  } else if (scenario == "MediumMass2011") {
    //intLumi = 3.99983; // in fb-1
    intLumi = 4.040802;
    IgorScen.assign("medium");
    spacer.assign("/MEDIUM");
    //SashaPath.assign("Data-Run2011AB-Medium");
    SashaPath.assign("Data-Run2011AB/TripleBtagAnalysis_CR3_SF7_med");
  

  } else if (scenario == "MediumMass2012") {
    //intLumi = 3.99983; // in fb-1
    intLumi = 2.663;
    IgorScen.assign("medium");
    spacer.assign("/MEDIUM");
    //SashaPath.assign("Data-Run2011AB-Medium");
    SashaPath.assign("");
}
else {
    std::cout << "Bad scenario in packing" << std::endl;
    return;
  }
  string signalHistPattern("massEvBtag/mjjEvBTag_%s");
  if (L1L2Mode == "Weight") {
    signalHistPattern.assign("massEvBtagTW/mjjEvBTagTW_%s");
  }

  double fScal[nSignal][nbtag];
  
  // systematics
//   const int nSyst = 3;
//   std::string systName[nSyst] = { "JES", "SFbc", "SFudsg" };
//   bool realDataNuisance[nSyst] = { false, true, true }; // indicate if relevant for real data

  string bbPurity("DataDriven"); //  "MC", "DataDrivenR", "None"
  //string bbPurity("None"); //  "MC", "DataDrivenR", "None"

  bool onlineBtagCorr = true;

  int nSyst = 4;
  std::string systName[] = { "JES", "SFbc", "SFudsg", "JER" };
  bool realDataNuisance[] = { false, true, true, false }; // indicate if relevant for real data

  const int nUpDown = 2;
  std::string signalFile = "";

bool dosignal=true;


#if defined(MEDIUM2012)
dosignal=false;
nTCombData=1; ///only one trigger
//nSyst=0; /// no syst templates

#endif


  // signal templates
  if (IgorVersion != "V3") {
    std::cout << "Using signal files " << IgorVersion << std::endl;
    signalFile.assign( Form("%s/theMergeList-SUSYBBHToBB_M-%d_7TeV-pythia6-tauola%s/SF/job_1/TripleBtagAnalysisM-%d_%s.root",IgorPath.c_str(),signalMass[iMass],spacer.c_str(),signalMass[iMass],IgorScen.c_str() ) );
  } else {
    std::cout << "Using V3 signal files" << std::endl;
    signalFile.assign( Form("/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/Systematics-test-3/%s/theMergeList-SUSYBBHToBB_M-%d_7TeV-pythia6-tauola%s/SF/job_1/TripleBtagAnalysisM-%d_%s.root",signalMode.c_str(),signalMass[iMass],spacer.c_str(),signalMass[iMass],IgorScen.c_str() ) );
  }
  std::string signalSystFiles[nSyst][nUpDown];
  //bool activeNuisance[nSyst] = { true, true, true };
  std::string upDownName[nUpDown] = { "Up", "Down" };
  TH2F* hSignalSyst[nSyst][nUpDown][nbtag];

  // output file
  TFile* hout = new TFile(Form("packedTemplates-M-%d.root",signalMass[iMass]),"recreate");
  hout->cd();
  TH2::AddDirectory(true);

  TFile* fSig = new TFile( signalFile.c_str() );
  if ( fSig == NULL ) {
    std::cout << "Could not open signal central file " << signalFile.c_str() << std::endl;
    return;
  } else {
    std::cout << "Open signal file " << signalFile.c_str() << std::endl;
  }

  TH2F* hSignalCentral[nbtag];

  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    hSignalCentral[ibtag] = mergeSignal(fSig,Form(signalHistPattern.c_str(),sbtag[ibtag].c_str()),
					Form("bbH_%s",sbtag[ibtag].c_str()));
    // read the efficiency
    TH1F* histEffMerged = (TH1F*) fSig->Get(Form("TrigEff/EffMerged%s",sbtag[ibtag].c_str()));
    if ( histEffMerged == NULL) {
      std::cout << "Efficiency histo not found" << std::endl;
      return;
    }
    double newEff = histEffMerged->GetBinContent(1);
    std::cout << "Mass= " << signalMass[iMass] 
	      << " btag= " << sbtag[ibtag]
	      << " Efficiency = " << newEff << std::endl;
    efficiency[iMass][ibtag] = newEff;

    double normShould = 1000 * intLumi * efficiency[iMass][ibtag];
    double normIs = hSignalCentral[ibtag]->GetSumOfWeights();
    std::cout << hSignalCentral[ibtag]->GetName() << " TotalContents=" << hSignalCentral[ibtag]->GetSumOfWeights()
	      << std::endl;
    fScal[iMass][ibtag] = normShould / normIs;
    std::cout << "normShould = " << normShould << " normIs " << normIs
	      << " rescale by " << fScal[iMass][ibtag] << std::endl;
    hSignalCentral[ibtag]->Scale( fScal[iMass][ibtag] );
    hout->cd();
    hSignalCentral[ibtag]->Write();
    histEffMerged->Write();

    // create empty file just as marker
    ofstream markerFile;
    markerFile.open(Form("pack-%s-%s.txt",sbtag[ibtag].c_str(),scenario.c_str()),ios::app);
    markerFile << "Template for mass " << signalMass[iMass] << std::endl;
    markerFile.close();
  }

  // read the nominal cross section
  TH1F* histXSect = (TH1F*) fSig->Get("xsection/xsect");
  if ( histXSect == NULL) {
    std::cout << "xsection/xsect" << " not found" << std::endl;
    return;
  }
  histXSect->Write();

  for (int iSyst=0; iSyst<nSyst; ++iSyst) {
    for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
      if (IgorVersion != "V3") {
	signalSystFiles[iSyst][iUpDown] = Form( "%s/theMergeList-SUSYBBHToBB_M-%d_7TeV-pythia6-tauola%s/%s_Sys%s/job_1/TripleBtagAnalysisM-%d_%s.root",
						IgorPath.c_str(),signalMass[iMass],spacer.c_str(),systName[iSyst].c_str(),
						upDownName[iUpDown].c_str(),signalMass[iMass],IgorScen.c_str());
      } else {	
	signalSystFiles[iSyst][iUpDown] = Form( "/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/Systematics-test-3/%s/theMergeList-SUSYBBHToBB_M-%d_7TeV-pythia6-tauola%s/%s_Sys%s/job_1/TripleBtagAnalysisM-%d_%s.root",
						signalMode.c_str(),signalMass[iMass],spacer.c_str(),systName[iSyst].c_str(),
						upDownName[iUpDown].c_str(),signalMass[iMass],IgorScen.c_str());
      }
      std::cout << "Signal systematics file " << signalSystFiles[iSyst][iUpDown] << std::endl;
      TFile* fSigSys = new TFile( signalSystFiles[iSyst][iUpDown].c_str() );
      if ( fSigSys == NULL ) {
	std::cout << "Could not open signal syst file " << signalSystFiles[iSyst][iUpDown].c_str() << std::endl;
	return;
      }
      for (int ibtag=0; ibtag<nbtag; ++ibtag) {
	hSignalSyst[iSyst][iUpDown][ibtag] 
	  = mergeSignal(fSigSys,Form(signalHistPattern.c_str(),sbtag[ibtag].c_str()),
			Form("bbH_%s_%s_%s",systName[iSyst].c_str(),
			     upDownName[iUpDown].c_str(),sbtag[ibtag].c_str()));
	std::cout << "The merged hist has name " << hSignalSyst[iSyst][iUpDown][ibtag]->GetName() << std::endl;
	std::cout << hSignalSyst[iSyst][iUpDown][ibtag]->GetName() << " TotalContents=" << hSignalSyst[iSyst][iUpDown][ibtag]->GetSumOfWeights()
		  << std::endl;
	
	hSignalSyst[iSyst][iUpDown][ibtag]->Scale( fScal[iMass][ibtag] );
	hout->cd();
	hSignalSyst[iSyst][iUpDown][ibtag]->Write();
      }
      fSigSys->Close();
    }
  }

  // real data
  std::string backgroundFile( Form("/afs/naf.desy.de/user/r/rmankel/scratch/HbbPat/CMSSW_4_2_4_patch1/src/Analysis/HbbMSSMAnalysis/test/results/v1/%s/TripleBtagAnalysis_SF/TripleBtagAnalysis.root",SashaPath.c_str()) );

#if defined(MEDIUM2012)
//bool dosignal=true;
//backgroundFile = std::string("/data/user/marfin/CMSSW_5_3_3/src/Analysis/HbbMSSMAnalysis/test/Analysis2012/MVA-production-selection-trees/TripleBtagAnalysis.root");
backgroundFile = std::string("/data/user/marfin/CMSSW_5_3_3/src/Analysis/HbbMSSMAnalysis/test/Analysis2012/Blind-test-BG-only-Fit/MEDIUM/TripleBtagAnalysis_SF/TripleBtagAnalysis.root");
#endif


  std::cout << "Background central file : " << backgroundFile << std::endl;
  TFile* fBac = new TFile( backgroundFile.c_str() );
  if ( fBac == NULL ) {
    std::cout << "Could not open background central file " << signalFile.c_str() << std::endl;
    return;
  }

  // hist-to-be-fitted
  TH2F* mjjEbtdata[nbtag];
  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    mjjEbtdata[ibtag] = getTrigsAndMerge(fBac,Form("massEvBtag/mjjEvBTag_%s",sbtag[ibtag].c_str()),nTCombData,tCombData);

    if (mjjEbtdata[ibtag] == NULL) {
      std::cout << "Histogram not found: " << Form("massEvBtag/mjjEvBTag_%s",sbtag[ibtag].c_str()) << std::endl;
      return;
    }
    // rename
    mjjEbtdata[ibtag]->SetName( Form("Data_%s",sbtag[ibtag].c_str() ) );
    hout->cd();
    mjjEbtdata[ibtag]->Write();
  }

  TH2F* hBackgroundCentral[nbtag][ncateg][nfc];
  TH2F* hBackgroundCentralError[nbtag][ncateg][nfc];
  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    for (int icateg=0; icateg<ncateg; ++icateg) {
      int theTpat;
      if (onlineBtagCorr) {
	theTpat = 3;
      } else {
	theTpat = icateg;
      }

      for (int ifc=0; ifc<nfc; ++ifc) {
	string templateCore("massBTagTemplatesCld/MassBTagTemplateCld");
	if (bbPurity == "None") {
	   templateCore.assign("massBTagTemplatesCld/MassBTagTemplateUncld");
	}
	string hbSystName( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
				sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,theTpat) );
	hBackgroundCentral[ibtag][icateg][ifc] = getTrigsAndMerge(fBac,Form("%s_%s_%s_Cat%dTpat%d",
									   templateCore.c_str(),
									   sfc[ifc].c_str(),
									   sbtag[ibtag].c_str(),icateg,theTpat),nTCombData,tCombData);

	if ( hBackgroundCentral[ibtag][icateg][ifc] == NULL ) {
	  std::cout << "Hist not found: " << hbSystName << std::endl;
	  return;
	}
	// rename
	templateId tName(ifc,icateg);
	hBackgroundCentral[ibtag][icateg][ifc]->SetName( Form("%s_%s",tName.name().c_str(),sbtag[ibtag].c_str()) );
	// read the template errors
	templateCore.assign("errorMassBTagTemplates/ErrorMassBTagTemplate");
	string hbSystNameError( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
				sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,theTpat) );
	hBackgroundCentralError[ibtag][icateg][ifc] 
	  = getTrigsAndMerge(fBac,Form("%s_%s_%s_Cat%dTpat%d",
				       templateCore.c_str(),
				       sfc[ifc].c_str(),
				       sbtag[ibtag].c_str(),icateg,theTpat),nTCombData,tCombData);
	if ( hBackgroundCentralError[ibtag][icateg][ifc] == NULL ) {
	  std::cout << "Hist not found: " << hbSystNameError << std::endl;
	  return;
	}
	if (useTemplateError) {
	  // add the template error
	  std::cout << " ==== Adding Btag Errors ==== " << hBackgroundCentral[ibtag][icateg][ifc]->GetName() << std::endl;
	  for (int ibinx=1; ibinx<= (hBackgroundCentral[ibtag][icateg][ifc]->GetXaxis()->GetNbins()); ++ibinx) {
	    for (int ibiny=1; ibiny<= (hBackgroundCentral[ibtag][icateg][ifc]->GetYaxis()->GetNbins()); ++ibiny) {
	      float oldError = hBackgroundCentral[ibtag][icateg][ifc]->GetBinError(ibinx,ibiny);
	      float addError = hBackgroundCentralError[ibtag][icateg][ifc]->GetBinContent(ibinx,ibiny);
	      float newError = sqrt( oldError * oldError + addError * addError );
	      hBackgroundCentral[ibtag][icateg][ifc]->SetBinError(ibinx,ibiny,newError);
	    }
	  }
	}
	hout->cd();
	hBackgroundCentral[ibtag][icateg][ifc]->Write();
      }
    }
  }



  std::string backgroundSystFiles[nSyst][nUpDown];
  std::string systNameSasha[] = { "JES", "SFbc", "SFq" };
  std::string upDownNameSasha[nUpDown] = { "plus2", "minus2" };
  TH2F* hBackgroundSyst[nSyst][nUpDown][nbtag][ncateg][nfc];
  TH2F* hBackgroundSystError[nSyst][nUpDown][nbtag][ncateg][nfc];

//#if !defined(MEDIUM2012)

  // for nuisances like JEC, the up/down templates are just copies of the central templates
  for (int iSyst=0; iSyst<nSyst; ++iSyst) {
    if (! realDataNuisance[iSyst]) {
      std::cout << "Non-real data relevant nuisance: " << systName[iSyst].c_str() << std::endl;
      for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
	for (int ibtag=0; ibtag<nbtag; ++ibtag) {
	  for (int icateg=0; icateg<ncateg; ++icateg) {
	    for (int ifc=0; ifc<nfc; ++ifc) {
	      hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]
		= new TH2F( *hBackgroundCentral[ibtag][icateg][ifc] );
	      // rename
	      templateId tName(ifc,icateg);
	      hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]
		->SetName( Form("%s_%s_%s_%s",
				tName.name().c_str(),systName[iSyst].c_str(),
				upDownName[iUpDown].c_str(),sbtag[ibtag].c_str()) );
	      hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->Write();
	    }
	  }
	}
      }
    }
  }
//#endif

  fBac->Close();


  for (int iSyst=0; iSyst<nSyst; ++iSyst) {
    if (realDataNuisance[iSyst]) {
      std::cout << "Real data relevant nuisance: " << systName[iSyst].c_str() << std::endl;
      for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
//	backgroundSystFiles[iSyst][iUpDown] = Form( "/afs/naf.desy.de/user/r/rmankel/scratch/HbbPat/CMSSW_4_2_4_patch1/src/Analysis/HbbMSSMAnalysis/test/results/v1/%s/TripleBtagAnalysis_%s%s/TripleBtagAnalysis.root",SashaPath.c_str(),systNameSasha[iSyst].c_str(),upDownNameSasha[iUpDown].c_str() );
	backgroundSystFiles[iSyst][iUpDown] = Form( "/data/user/marfin/CMSSW_5_3_3/src/Analysis/HbbMSSMAnalysis/test/Analysis2012/Blind-test-BG-only-Fit/MEDIUM/TripleBtagAnalysis_%s%s/TripleBtagAnalysis.root",systNameSasha[iSyst].c_str(),upDownNameSasha[iUpDown].c_str() );
	TFile* fBacSys = new TFile( backgroundSystFiles[iSyst][iUpDown].c_str() );
	std::cout << "Background systematics file " << backgroundSystFiles[iSyst][iUpDown] << std::endl;
	if ( fBacSys == NULL ) {
	  std::cout << "Could not open background syst file " << backgroundSystFiles[iSyst][iUpDown] << std::endl;
	  return;
	}
	for (int ibtag=0; ibtag<nbtag; ++ibtag) {
	  for (int icateg=0; icateg<ncateg; ++icateg) {
	    int theTpat;
	    if (onlineBtagCorr) {
	      theTpat = 3;
	    } else {
	      theTpat = icateg;
	    }

	    for (int ifc=0; ifc<nfc; ++ifc) {
	      string templateCore("massBTagTemplatesCld/MassBTagTemplateCld");
	      if (bbPurity == "None") {
		templateCore.assign("massBTagTemplatesCld/MassBTagTemplateUncld");
	      }
	      string hbSystName( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
				      sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,theTpat) );
	      hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc] 
		= getTrigsAndMerge(fBacSys,Form("%s_%s_%s_Cat%dTpat%d",
						templateCore.c_str(),
						sfc[ifc].c_str(),
						sbtag[ibtag].c_str(),icateg,theTpat),nTCombData,tCombData);
	      if ( hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc] == NULL ) {
		std::cout << "Hist not found: " << hbSystName << std::endl;
		return;
	      }
	      // rename
	      templateId tName(ifc,icateg);
	      hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]
		->SetName( Form("%s_%s_%s_%s",
				tName.name().c_str(),systName[iSyst].c_str(),
				upDownName[iUpDown].c_str(),sbtag[ibtag].c_str()) );
	      
	      // read template errors
	      templateCore.assign("errorMassBTagTemplates/ErrorMassBTagTemplate");
	      string hbSystNameError( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
					   sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,theTpat) );
	      hBackgroundSystError[iSyst][iUpDown][ibtag][icateg][ifc] 
		= getTrigsAndMerge(fBacSys,Form("%s_%s_%s_Cat%dTpat%d",
						templateCore.c_str(),
						sfc[ifc].c_str(),
						sbtag[ibtag].c_str(),icateg,theTpat),nTCombData,tCombData);
	      if ( hBackgroundSystError[iSyst][iUpDown][ibtag][icateg][ifc] == NULL ) {
		std::cout << "Hist not found: " << hbSystNameError << std::endl;
		return;
	      }
	      if (useTemplateError) {
		// add the template error
		std::cout << " ==== ErrorAdd ==== " << hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetName() << std::endl;
		for (int ibinx=1; ibinx<= (hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetXaxis()->GetNbins()); ++ibinx) {
		  for (int ibiny=1; ibiny<= (hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetYaxis()->GetNbins()); ++ibiny) {
		    float oldError = hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetBinError(ibinx,ibiny);
		    float addError = hBackgroundSystError[iSyst][iUpDown][ibtag][icateg][ifc]->GetBinContent(ibinx,ibiny);
		    float newError = sqrt( oldError * oldError + addError * addError );
		    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->SetBinError(ibinx,ibiny,newError);
		  }
		}
	      }
	      hout->cd();
	      hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->Write();
	    }
	  }
	}
	fBacSys->Close();
      }
    }
  }

  std::cout << "Everything done " << std::endl;

#ifdef PROJECTIONS

TFile * projections_out=TFile::Open("projections.root","RECREATE");

  // loop over background templates
  //TH1D* bgProX[nbtag][ncateg][nfc];
  TH1D* bgSystProX[nSyst][nUpDown][nbtag][ncateg][nfc];
  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    for (int icateg=0; icateg<ncateg; ++icateg) {
      for (int ifc=0; ifc<nfc; ++ifc) {
	TH2F* theTemp = hBackgroundCentral[ibtag][icateg][ifc];
	TH1D* theTempProX = theTemp->ProjectionX(Form("%sProX",theTemp->GetName()),0,-1,"e");
	theTempProX->SetName( Form("%sProX",theTemp->GetName()) );
	TH1D* theTempProY = theTemp->ProjectionY(Form("%sProY",theTemp->GetName()),0,-1,"e");
	std::cout << "Made projection " << theTempProX->GetName() << std::endl;

	if ( (icateg == 0) && (ifc == 0) ) {
	  for (int ibinx=1; ibinx<= theTempProX->GetXaxis()->GetNbins(); ++ibinx) {
	    std::cout << ibinx << " content " << theTempProX->GetBinContent(ibinx)
		      << " error " << theTempProX->GetBinError(ibinx) << std::endl;
	  }
	}
	theTempProX->SetMarkerStyle(20);
	theTempProX->SetMarkerColor(1);
	theTempProX->SetLineColor(1);
	theTempProX->SetMarkerSize(1);
	std::cout << "Draw" << std::endl;
	theTempProX->Draw("EP");
	theTempProX->Write();






	//theTempProX->Draw("LP,SAME");
	// draw the SFbc systematics
	int colSyst[3] = {1, 2, 4};
	int lstyleUpDown[2] = {1, 1};
	for (int iSyst=1; iSyst<nSyst; ++iSyst) {
	  for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
	    bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc] =  hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->ProjectionX(Form("%sProXX",hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetName()),0,-1,"e");
	    bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->SetName( Form("%sProXX",hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetName()) );
	    std::cout << "Made projection " << bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->GetName() << std::endl;
	     bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->SetLineColor( colSyst[iSyst] );
	     bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->Draw("HIST,SAME");
		 bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->Write();


// 	    TH2F* theTemp = hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc];
// 	    TH1D* theTempProX = theTemp->ProjectionX(Form("%sProX",theTemp->GetName()),0,-1,"e");
// 	    theTempProX->SetLineColor( colSyst[iSyst] );
// 	    TH1D* theTempProY = theTemp->ProjectionY(Form("%sProY",theTemp->GetName()),0,-1,"e");
// 	    theTempProY->SetLineColor( colSyst[iSyst] );
// 	    //theTempProX->Draw("HIST");
	  }
	}

	canvas->Print(Form("Template_%s_%s_Cat%d_ProX.png",sbtag[ibtag].c_str(),sfc[ifc].c_str(),icateg));


	theTempProY->SetMarkerStyle(20);
	theTempProY->SetMarkerColor(1);
	theTempProY->SetLineColor(1);
	theTempProY->SetMarkerSize(1);
	std::cout << "Draw" << std::endl;
	theTempProY->Draw("EP");
	theTempProY->Write();


      }
    }
  }

projections_out->Write();
projections_out->Close();



#endif

  hout->Write();
  hout->Close();

  // close the signal central file
  fSig->Close();

  return;
}
void Channel::GetShapes(TString SelectionName, TString xtitle, const int nbins, const double *bins){ 
	MT2Shapes *tA;
	if(fWriteToFile) tA = new MT2Shapes(fOutDir, fRootFile, fLogStream);
	else             tA = new MT2Shapes(fOutDir, fRootFile);
	tA->setVerbose(fVerbose);
	tA->init(fSamples);
	tA->SetPrintSummary(true);
	tA->SetDraw(false);
	tA->SetWrite(false);
  
//                    variable,      cuts,  njet, nlep,  selection_name,      HLT,   xtitle   nbins  bins   
        tA->GetShapes(fVariable,  fCuts,    -1,  -10  , SelectionName,    fTrigger , xtitle , nbins, bins);

	// retrieve shapes
	for(int i=0; i<tA->GetNShapes(); ++i){
		TString name =tA->fh_shapes[i]->GetName();
		if      (name.Contains("QCD_"))        {hQCD         = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hQCD->SetDirectory(fDir);}
		else if (name.Contains("PhotonsJets_")){hPhotons     = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hPhotons->SetDirectory(fDir);}
		else if (name.Contains("Data_"))       {hData        = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hData->SetDirectory(fDir);}
		else if (name.Contains("WJets_"))      {hWJets       = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hWJets->SetDirectory(fDir);}
		else if (name.Contains("ZJetsToLL_"))  {hZJetsToLL   = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hZJetsToLL->SetDirectory(fDir);}
		else if (name.Contains("ZJetsToNuNu_")){hZJetsToNuNu = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hZJetsToNuNu->SetDirectory(fDir);}
		else if (name.Contains("Top_"))        {hTop         = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hTop->SetDirectory(fDir);}
		else if (name.Contains("Signal_"))     {hSignal      = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hSignal->SetDirectory(fDir);}
		else if (name.Contains("Other_"))      {hOther       = (TH1D*) tA->fh_shapes[i]->Clone(tA->fh_shapes[i]->GetName()); hOther->SetDirectory(fDir);}
	}
	delete tA;
	fGotShapes=true;

	fDir->cd();

	// fix colors
	if(hQCD!=0)        {hQCD    ->SetLineColor(kYellow+1);    hQCD    ->SetFillColor(kYellow+1);      hQCD    ->SetFillStyle(3001);}
	if(hPhotons!=0)    {hPhotons->SetLineColor(kViolet-3);    hPhotons->SetFillColor(kViolet-3);      hPhotons->SetFillStyle(3001);}
	if(hOther!=0)      {hOther  ->SetLineColor(kCyan+2);      hOther  ->SetFillColor(kCyan+2);        hOther  ->SetFillStyle(3001);}
	if(hZJetsToNuNu!=0){hZJetsToNuNu->SetLineColor(kGreen+1); hZJetsToNuNu->SetFillColor(kGreen+1);   hZJetsToNuNu  ->SetFillStyle(3001);}
	if(hSignal!=0)     {hSignal ->SetLineColor(kBlack);       hSignal  ->SetFillColor(kBlack);        hSignal  ->SetFillStyle(3001);}
	if(hZJetsToLL!=0)  {hZJetsToLL->SetLineColor(kOrange);    hZJetsToLL->SetFillColor(kOrange);      hZJetsToLL->SetFillStyle(3001);}
	if(hTop!=0)        {hTop    ->SetLineColor(600);          hTop     ->SetFillColor(600);           hTop->SetFillStyle(3001);}

	if(fSaveResults){
		if(hQCD!=0)         {hQCD->Write();}
		if(hPhotons!=0)     {hPhotons->Write();}
		if(hOther!=0)       {hOther->Write();}
		if(hData!=0)        {hData->Write();}
		if(hTop!=0)         {hTop->Write();}
		if(hZJetsToLL!=0)   {hZJetsToLL->Write();}
		if(hZJetsToNuNu!=0) {hZJetsToNuNu->Write();}
		if(hSignal!=0)      {hSignal->Write();}
	}
	if(fDraw){
		if(hQCD!=0)        DrawHisto(hQCD,           hQCD->GetName(),            "hist", this);
		if(hPhotons!=0)    DrawHisto(hPhotons,       hPhotons->GetName(),        "hist", this);
		if(hOther!=0)      DrawHisto(hOther,         hOther->GetName(),          "hist", this);
		if(hData!=0)       DrawHisto(hData,          hData->GetName(),           "EXO",  this);
		if(hTop!=0)        DrawHisto(hTop,           hTop ->GetName(),           "hist", this);
		if(hZJetsToNuNu!=0)DrawHisto(hZJetsToNuNu,   hZJetsToNuNu->GetName(),    "hist", this);
		if(hSignal!=0)     DrawHisto(hSignal,        hSignal->GetName(),         "hist", this);
		if(hZJetsToLL!=0)  DrawHisto(hZJetsToLL,     hZJetsToLL->GetName(),      "hist", this);
	}
}
void run_DataGammaJetsZllToZnunu(){

	// defs ---------------------------------------------------------
	gSystem->CompileMacro("../MT2Code/src/MT2Shapes.cc", "k");
	
	// logStream
	fLogStream = new std::ostringstream();
	
	// create dir
	if(!fOutDir.EndsWith("/")) fOutDir += "/";
	char cmd[500];
	sprintf(cmd,"mkdir -p %s", fOutDir.Data());
	system(cmd);

	DefineCutStreams(fHTmin, fHTmax, fMT2min, fMT2max);
	TString filename=fOutDir+"/"+fRootFile;
	fOutFile = new TFile(filename.Data(), "RECREATE");
	fDir     = (TDirectory*) fOutFile;

	// fix output dir
//	if(fHTmax <10000) fOutDir= TString::Format("%s_%d_HT_%d",  fOutDir.Data(), abs(fHTmin),  abs(fHTmax));
//	else              fOutDir= TString::Format("%s_%d_HT_%s",  fOutDir.Data(), abs(fHTmin),  "Inf");
//	if(fMT2max<10000) fOutDir= TString::Format("%s_%d_MT2_%d", fOutDir.Data(), abs(fMT2min), abs(fMT2max));
//	else              fOutDir= TString::Format("%s_%d_MT2_%s", fOutDir.Data(), abs(fMT2min), "Inf");
	
	// log MT2 and HT cuts
	*fLogStream << "------------------------------------------------------------------------------------------------" << endl;
	*fLogStream << "+++ new Znunu with Gamma+jets prediction                                                     +++" << endl;
	*fLogStream << "+++ outputdir: " << fOutDir <<                                                              "+++" << endl; 
	*fLogStream << "------------------------------------------------------------------------------------------------" << endl;
	
	// new prediction ------------------------------------------------------
	Prediction* prediction = new Prediction();
	prediction->fVerbose=fVerbose;
	prediction->fSave   =fSaveResults;


	// Photon Pt
	if(fDoPhotonPtShape){
  	const int gNMT2bins                   = 11;
  	double  gMT2bins[gNMT2bins+1]   = {150, 160, 170, 180, 190, 200, 225, 250, 300, 400, 550, 800}; 	
	prediction->ChPhotonPt = new Channel("PhotonPt", "photon[0].lv.Pt()", cutStream_PhotonPt.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPt);
	prediction->ChPhotonPt->fVerbose =prediction->fVerbose;
//	prediction->ChPhotonPt->GetShapes("PhotonPt", "#gamma Pt", 2, 300, 800);
	prediction->ChPhotonPt->GetShapes("PhotonPt", "#gamma Pt", 100, 150, 800);
//	prediction->ChPhotonPt->GetShapes("PhotonPt", "#gamma Pt", gNMT2bins, gMT2bins);
	}
	
	// Zll Pt
	if(fDoZllPtShape){
  	const int gNMT2bins                   = 11;
  	double  gMT2bins[gNMT2bins+1]   = {150, 160, 170, 180, 190, 200, 225, 250, 300, 400, 550, 800}; 	
	prediction->ChZllPt = new Channel("ZllPt", "RecoOSDiLeptPt(20,2.4,71,111)", cutStreamZll.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPt);
	prediction->ChZllPt->fVerbose =prediction->fVerbose;
//	prediction->ChZllPt->GetShapes("ZllPt", "Zll Pt", 2, 300, 800);
	prediction->ChZllPt->GetShapes("ZllPt", "Zll Pt", 100, 150, 800);
//	prediction->ChZllPt->GetShapes("ZllPt", "Zll Pt", gNMT2bins, gMT2bins);
	}

	// compute Zll/gamma pt ratio
	if(fDoPhotonPtShape && fDoZllPtShape){
		TH1D* hPhotonToZllPtRatio = prediction->GetRatio(fDoDataZllToPhotonRatio? prediction->ChZllPt->hData    : prediction->ChZllPt->hZJetsToLL, 
				                                 fDoDataZllToPhotonRatio? prediction->ChPhotonPt->hData : prediction->ChPhotonPt->hPhotons, 4);
		DrawHisto(hPhotonToZllPtRatio,hPhotonToZllPtRatio->GetName(),"EX0");
		TString rationame=hPhotonToZllPtRatio->GetName();
		rationame +="_fittedRatio";
		TF1 *f_lin = new TF1(rationame,"pol0(0)", fZllToGammaFitMin , fZllToGammaFitMax);   f_lin->SetLineColor(8);
		if(fDoFits){ 
			hPhotonToZllPtRatio->Fit(rationame,"0L","", fZllToGammaFitMin, fZllToGammaFitMax);    // set al weights to 1
			fZllToPhotonRatio   = f_lin->GetParameter(0);
		} else{
			fZllToPhotonRatio   = prediction->GetLimitedRatio(fDoDataZllToPhotonRatio? prediction->ChZllPt->hData: prediction->ChZllPt->hZJetsToLL,
			                                              fDoDataZllToPhotonRatio? prediction->ChPhotonPt->hData : prediction->ChPhotonPt->hPhotons,
				                                      fZllToGammaFitMin, fZllToGammaFitMax, false, fZllToPhotonRatioRelErr);
			f_lin->SetParameter(0,fZllToPhotonRatio);
		}
  		const int nBins= 3;
		const double Bins[nBins+1] = {150, fZllToGammaFitMin>150?fZllToGammaFitMin:150.0001, fZllToGammaFitMax<800? fZllToGammaFitMax:799.99, 800};
		TH1D* hErrorbar = new TH1D(rationame.Data(), "", nBins, Bins);
		hErrorbar->SetBinContent(2,fZllToPhotonRatio);
		hErrorbar->SetBinError(2,fZllToPhotonRatioRelErr*fZllToPhotonRatio);
		hErrorbar->SetBinContent(1,-10);
		hErrorbar->SetBinError( 1,0);
		hErrorbar->SetFillColor(5);
		hErrorbar->SetFillStyle(3001);
		hErrorbar->Draw("e2same");
		f_lin->Draw("same");
		hPhotonToZllPtRatio->Draw("EX0same");
	}
	
	// GenLevel Zll Pt, no acceptance cuts
	if(fDoGenZllShape){
	prediction->ChGenZllPt = new Channel("GenZllPt", "GenDiLeptPt(0,10,0,1000,true)", cutStreamGenZll.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPtMConly);
	prediction->ChGenZllPt->fVerbose =prediction->fVerbose;
	prediction->ChGenZllPt->GetShapes("GenZllPt", "GenZll Pt", 8, 0, 800);
	}
	
	// GenLevel Zll Pt, within acceptance
	if(fDoGenAccZllShape){
	prediction->ChGenZllPtAcc = new Channel("GenZllPtAcc", "GenDiLeptPt(20,2.4,71,111,true)", cutStreamGenZllAcc.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPtMConly);
	prediction->ChGenZllPtAcc->fVerbose =prediction->fVerbose;
	prediction->ChGenZllPtAcc->GetShapes("GenZllPtAcc", "GenZll Pt", 8, 0, 800);
	}
	// Get Acceptance Efficiency
	if(fDoGenZllShape && fDoGenAccZllShape){
		Bool_t binomial =true;
		TH1D* hZllAccEff = prediction->GetRatio(prediction->ChGenZllPtAcc->hZJetsToLL, prediction->ChGenZllPt->hZJetsToLL, 1, binomial);
		DrawHisto(hZllAccEff,hZllAccEff->GetName(),"EX");
//		TString rationame=hZllAccEff->GetName();
//		rationame +="_fittedRatio";
//		TF1 *f_lin = new TF1(rationame,"pol0(0)", fZllAccFitMin ,   fZllAccFitMax);   f_lin->SetLineColor(8);
//		if(fDoFits){ 
//			hZllAccEff->Fit(rationame,"0L","", fZllAccFitMin, fZllAccFitMax);    // set al weights to 1
//			fZllAccEff= f_lin->GetParameter(0);
//		} else{
//			fZllAccEff= prediction->GetLimitedRatio(prediction->ChGenZllPtAcc->hZJetsToLL,prediction->ChGenZllPt->hZJetsToLL,
//				                                fZllAccFitMin, fZllAccFitMax, true, fZllAccEffRelErr);
//			f_lin->SetParameter(0,fZllAccEff);
//		}
//  		const int nBins= 3;
//		const double Bins[nBins+1] = {150, fZllAccFitMin>150?fZllAccFitMin:150.0001, fZllAccFitMax<800? fZllAccFitMax:799.99, 800};
//		TH1D* hErrorbar = new TH1D(rationame.Data(), "", nBins,Bins);
//		hErrorbar->SetBinContent(2,fZllAccEff);
//		hErrorbar->SetBinError(2,fZllAccEffRelErr*fZllAccEff);
//		hErrorbar->SetBinContent(1,-1);
//		hErrorbar->SetBinError(1,0);
//		hErrorbar->SetFillColor(5);
//		hErrorbar->SetFillStyle(3001);
//		hErrorbar->Draw("e2same");
//		f_lin->Draw("same");
//		hZllAccEff->Draw("EX0same");
	}
	
	// GenLevel Zll Pt, within acceptance, OS dilepton recoed
	if(fDoGenAccZllRecoShape){
	prediction->ChGenZllPtAccRecoed = new Channel("GenZllPtAccRecoed", "GenDiLeptPt(20,2.4,71,111,true)", cutStreamGenZllAcc_recoed.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPtMConly);
	prediction->ChGenZllPtAccRecoed->fVerbose =prediction->fVerbose;
	prediction->ChGenZllPtAccRecoed->GetShapes("GenZllPtAccRecoed", "GenZll Pt", 100, 150, 800);
	}
	if(fDoGenAccZllShape && fDoGenAccZllRecoShape){
		Bool_t binomial =true;
		TH1D* hZllRecoEff = prediction->GetRatio(prediction->ChGenZllPtAccRecoed->hZJetsToLL, prediction->ChGenZllPtAcc->hZJetsToLL, 4, binomial);
		DrawHisto(hZllRecoEff,hZllRecoEff->GetName(),"EX");
		TString rationame=hZllRecoEff->GetName();
		rationame +="_fittedRatio";
		TF1 *f_lin = new TF1(rationame,"pol0(0)", fZllRecoEffFitMin , fZllRecoEffFitMax);   f_lin->SetLineColor(8);
		if(fDoFits){ 
			hZllRecoEff->Fit(rationame,"0L","", fZllRecoEffFitMin, fZllRecoEffFitMax);    // set al weights to 1
			fZllRecoEff= f_lin->GetParameter(0);
		} else{
			fZllRecoEff= prediction->GetLimitedRatio(prediction->ChGenZllPtAccRecoed->hZJetsToLL,prediction->ChGenZllPtAcc->hZJetsToLL,
				                                fZllRecoEffFitMin, fZllRecoEffFitMax, true, fZllRecoEffRelErr);
			f_lin->SetParameter(0,fZllRecoEff);
		}
  		const int nBins= 3;
		const double Bins[nBins+1] = {150, fZllRecoEffFitMin>150?fZllRecoEffFitMin:150.001, fZllRecoEffFitMax<800? fZllRecoEffFitMax:799.99, 800};
		TH1D* hErrorbar = new TH1D(rationame.Data(), "", nBins,Bins);
		hErrorbar->SetBinContent(2,fZllRecoEff);
		hErrorbar->SetBinError(2,fZllRecoEffRelErr*fZllRecoEff);
		hErrorbar->SetBinContent(1,-1);
		hErrorbar->SetBinError(1,0);
		hErrorbar->SetFillColor(5);
		hErrorbar->SetFillStyle(3001);
		hErrorbar->Draw("e2same");
		f_lin->Draw("same");
		hZllRecoEff->Draw("EX0same");
	}
	
	// Photons Hadronic Search MT2
	if(fDoPhotonMT2Shape){
	prediction->ChPhotonsMT2 = new Channel("PhotonsMT2", "photon[0].lv.Pt()", cutStreamPhotonMT2.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPt);
	prediction->ChPhotonsMT2->fVerbose =prediction->fVerbose;
	prediction->ChPhotonsMT2->GetShapes("PhotonsMT2", "MET", 40, 0, 800);
	}

	// Znunu Hadronic Search MT2
	if(fDoZnunuMT2Shape){
	prediction->ChZnunuMT2 = new Channel("ZnunuMT2", "misc.MET", cutStreamZnunuMT2.str().c_str(), fTriggerStream.str().c_str(),fSamplesZnunu);
	prediction->ChZnunuMT2->fVerbose =prediction->fVerbose;
	prediction->ChZnunuMT2->GetShapes("ZnunuMT2", "MET", 40, 0, 800);
	}

	if(fDoZnunuMT2Shape && fDoPhotonMT2Shape){
	TH1D* ZnunuToPhotonMT2Ratio = prediction->GetRatio(prediction->ChZnunuMT2->hZJetsToNuNu, prediction->ChPhotonsMT2->hPhotons, 1);
	DrawHisto(ZnunuToPhotonMT2Ratio,ZnunuToPhotonMT2Ratio->GetName(),"EX0");
	}


	
	// Do Pt spectra comparison plot
	if(fDoPtSpectraComparison && fDoPhotonPtShape && fDoZllPtShape){
		*fLogStream<< "************************* produce pr spectra plot ****************************** " << endl;
		TH1D* hZllMC_cp      = prediction->GetScaledHisto(prediction->ChZllPt->hZJetsToLL, fDoPtSpectraComparisonScaling?(prediction->ChZllPt->hData->Integral())/(prediction->ChZllPt->hZJetsToLL->Integral())    :1, 0, 1);
		TH1D* hZllData_cp    = prediction->GetScaledHisto(prediction->ChZllPt->hData,    1, 0, 1) ;
		TH1D* hPhotonMC_cp   = prediction->GetScaledHisto(prediction->ChPhotonPt->hPhotons,fDoPtSpectraComparisonScaling?(prediction->ChPhotonPt->hData->Integral())/(prediction->ChPhotonPt->hPhotons->Integral()):1, 0, 1);
		TH1D* hPhotonData_cp = prediction->GetScaledHisto(prediction->ChPhotonPt->hData,    1, 0, 1);

		if(fDoPtSpectraComparisonAccCorr){
			TFile *f = new TFile("../RootMacros/ZllAcceptance.root", "OPEN");
			TH1D*  hZllAcc = (TH1D*) f->Get("ZJetsToLL_GenZllPtAcc_ZJetsToLL_GenZllPt_Ratio");
			if (hZllAcc==0) {cout << "WARNING: could not get histo ZJetsToLL_GenZllPtAcc_ZJetsToLL_GenZllPt_Ratio" << endl; exit(1);}
			for(int i=1; i<=hZllMC_cp->GetNbinsX(); ++i){
				if(hZllAcc->GetBinLowEdge(i) != hZllMC_cp->GetBinLowEdge(i)) {cout << "Zll Acc Correction: binnin does not match!!" << endl; exit(1);}
				if(hZllMC_cp  ->GetBinContent(i)<=0) continue;
				double acc_eff   = hZllAcc->GetBinContent(i);
				double orig_mc   = hZllMC_cp     ->GetBinContent(i);
				double orig_data = hZllData_cp   ->GetBinContent(i);
				cout << "bin i " << i << " acc eff " << acc_eff << " orig_mc " << orig_mc << " become " << orig_mc/acc_eff 
				     << " orig_data " << orig_data << " becomes " << orig_data/acc_eff << endl;
				hZllMC_cp   ->SetBinContent(i, orig_mc  /acc_eff);
				hZllData_cp ->SetBinContent(i, orig_data/acc_eff);
			}
			delete f;
		}
		
		hZllMC_cp->SetMarkerStyle(22);
		hZllMC_cp->SetLineColor(kOrange);
		hZllMC_cp->SetMarkerColor(kOrange);
		hZllMC_cp->SetMarkerSize(1.2);
		hZllData_cp->SetMarkerStyle(26);
		hZllData_cp->SetMarkerColor(kBlack);
		hZllData_cp->SetLineColor(kBlack);
		hPhotonMC_cp->SetLineColor(kMagenta+2);
		hPhotonMC_cp->SetMarkerColor(kMagenta+2);
		hPhotonMC_cp->SetMarkerStyle(20);
		hPhotonMC_cp->SetMarkerSize(1.2);
		hPhotonData_cp->SetMarkerStyle(4);
		hPhotonData_cp->SetMarkerColor(kBlack);
		hPhotonData_cp->SetLineColor(kBlack);

		TCanvas *col = new TCanvas("ZllToGammaPtSpectra", "", 0, 0, 500, 500);
		col->SetFillStyle(0);
		col->SetFrameFillStyle(0);
//		col->cd();
		gPad->SetFillStyle(0);
		gStyle->SetPalette(1);
		gPad->SetRightMargin(0.15);

		TLegend* leg2 = new TLegend(0.2, 0.6, 0.5, 0.9);	
		leg2->AddEntry(hPhotonMC_cp,"Gamma+Jets MC","p" );
		leg2->AddEntry(hPhotonData_cp,"Photon Data","p" );
		leg2->AddEntry(hZllMC_cp ,"Zll MC","p" );
		leg2->AddEntry(hZllData_cp,"Zll Data","p" );
		leg2 -> SetFillColor(0);
		leg2 -> SetBorderSize(0);
	//	
		hPhotonMC_cp->SetXTitle("V boson p_{T} (GeV)");
		hPhotonMC_cp->SetYTitle("Events / 7 GeV");
		hPhotonMC_cp->Draw("EX");
		hPhotonData_cp->Draw("EXsame");
		hZllMC_cp->Draw("EXsame");
		hZllData_cp->Draw("EXsame");
		leg2->Draw();
	
		TCanvas *c3 = new TCanvas("ZllToGammaPtSpectraRatio", "", 500, 500);
		TH1D* h_ratio         = (TH1D*) hZllMC_cp      ->Clone("h_ratio");	
		TH1D* h_ratioData     = (TH1D*) hZllData_cp    ->Clone("h_ratioData");	
		TH1D* hPhotonMC_cp2   = (TH1D*) hPhotonMC_cp   ->Clone("hPhotonMC_cp2");
		TH1D* hPhotonData_cp2 = (TH1D*) hPhotonData_cp ->Clone("hPhotonData_cp2");
		h_ratio->Rebin(1); h_ratioData->Rebin(1);
		h_ratio->SetYTitle("#frac{Z(ll)}{#gamma}");
		h_ratio->SetXTitle("boson p_{T} (GeV)");
		h_ratio    ->Divide(hPhotonMC_cp2->Rebin(1));
		h_ratioData->Divide(hPhotonData_cp2->Rebin(1));
		h_ratio    ->SetMarkerStyle(20);
		h_ratio    ->SetMarkerSize(1.2);
		h_ratio    ->SetLineColor(kMagenta+2);
		h_ratio    ->SetMarkerColor(kMagenta+2);
		h_ratioData->SetMarkerStyle(26);
		h_ratioData->SetMarkerColor(kBlack);
		h_ratio    ->Draw("EX0");
		h_ratioData->Draw("EX0same");
		
		TLegend* leg3 = new TLegend(0.2, 0.6, 0.5, 0.9);	
		leg3->AddEntry(h_ratioData,"Zll/photon Data","p" );
		leg3->AddEntry(h_ratio    ,"Zll/photon MC","p" );
		leg3 -> SetFillColor(0);
		leg3 -> SetBorderSize(0);
		leg3 ->Draw();
	}

	if(fDoMT2SpectraCompaison && fDoZnunuMT2Shape && fDoPhotonMT2Shape){
		*fLogStream<<  "************************* MT2 spectra comparison ***************  " << endl;
		TH1D* hZNunuMT2      = prediction->GetScaledHisto(prediction->ChZnunuMT2   ->hZJetsToNuNu, fDoMT2SpectraCompaisonScaling?(prediction->ChPhotonsMT2 ->hData->Integral())/(prediction->ChPhotonsMT2 ->hPhotons->Integral()):1, 0, 1);
		TH1D* hPhotonMT2     = prediction->GetScaledHisto(prediction->ChPhotonsMT2 ->hPhotons,     fDoMT2SpectraCompaisonScaling?(prediction->ChPhotonsMT2 ->hData->Integral())/(prediction->ChPhotonsMT2 ->hPhotons->Integral()):1, 0, 1);
		TH1D* hPhotonDataMT2 = prediction->GetScaledHisto(prediction->ChPhotonsMT2 ->hData, 1, 0, 1);
		
		hZNunuMT2->SetFillStyle(0);
		hZNunuMT2->SetLineWidth(3);

		TCanvas *col = new TCanvas("ZnunuToGammaPtSpectra", "", 0, 0, 500, 500);
		col->SetFillStyle(0);
		col->SetFrameFillStyle(0);
//		col->cd();
		gPad->SetFillStyle(0);
		gStyle->SetPalette(1);
		gPad->SetRightMargin(0.15);
		gPad->SetLogy(1);

		TLegend* leg2 = new TLegend(0.2, 0.6, 0.5, 0.9);	
		leg2->AddEntry(hPhotonMT2,"#gamma+jets MC","f" );
		leg2->AddEntry(hZNunuMT2,"Z(#nu#nu)+jets MC","l" );
		leg2->AddEntry(hPhotonDataMT2,"data","p" );
		leg2 -> SetFillColor(0);
		leg2 -> SetBorderSize(0);
	//	
		hPhotonMT2->SetXTitle("min #Delta #phi(jets,MET)");
		hPhotonMT2->SetYTitle("Events");
		hPhotonMT2->Draw("hist");
		hZNunuMT2->Draw("histsame");
		hPhotonDataMT2->Draw("EXsame");
		leg2->Draw();
//		gPad->RedrawAxis();
		// cout integral above 250 in MT2 and ratio
//		double sumPhotons=0;
//		double sumZnunu  =0;
//		for(int i=1;  i<=hPhotonMT2->GetNbinsX(); ++i){
//			if(hPhotonMT2->GetBinLowEdge(i)>=250){
//				sumPhotons+=hPhotonMT2->GetBinContent(i);
//				sumZnunu  +=hZNunuMT2 ->GetBinContent(i);
//			}
//		}
//		*fLogStream<< ">>> hPhotonMT2: integral above 250: " << sumPhotons << endl;
//		*fLogStream<< ">>> hZNunuMT2 : integral above 250: " << sumZnunu   << endl;
//		*fLogStream<< ">>> -> Ratio  : "                     << sumZnunu/sumPhotons << endl;
		
	}

	if(fDoZnunuGammaGenPtSpectraComparison){
		*fLogStream<< "*************************ZnunuGammaGenPtSpectraComparison**********" << endl;
		// gen photons
		prediction->ChGenPhotonPt = new Channel("GenPhotonPt", "GenPhoton[0].Pt()", cutStreamGenPhoton.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPtMConly);
		prediction->ChGenPhotonPt->fVerbose =prediction->fVerbose;
		prediction->ChGenPhotonPt->GetShapes("GenPhotonPt", "Gen-level #gamma Pt", 50, 150, 800);
		
		// Gen Znunu
		prediction->ChGenZnunuPt = new Channel("GenZnunuPt", "GenZ[0].Pt()", cutStreamGenZnunu.str().c_str(), fTriggerStream.str().c_str(),fSamplesZnunu);
		prediction->ChGenZnunuPt->fVerbose =prediction->fVerbose;
		prediction->ChGenZnunuPt->GetShapes("GenZnunuPt", "Gen-level Z(#nu#nu) Pt", 50, 150, 800);
		
		prediction->DrawHistos(prediction->ChGenPhotonPt->hPhotons, prediction->ChGenZnunuPt->hZJetsToNuNu,
				       "EX0"                              , "EX0same",
				       kViolet+3                          , kBlack,
				       20                                 ,4,
				       "#gamma Pt"                        ,"Z(#nu#nu)");

		TH1D* hGenPhotonToZnunuRatio = prediction->GetRatio(prediction->ChGenZnunuPt->hZJetsToNuNu, prediction->ChGenPhotonPt->hPhotons, 1, false);
		hGenPhotonToZnunuRatio->SetMarkerColor(kBlack);
		hGenPhotonToZnunuRatio->SetLineColor(kBlack);
		hGenPhotonToZnunuRatio->SetMarkerStyle(4);
		DrawHisto(hGenPhotonToZnunuRatio, "GenPhotonToZnunuRatio","EX0", prediction->ChGenPhotonPt);
	}

	if(fDoPhotonRecoEff){
		prediction->ChGenPhotonPtForRecoEff = new Channel("GenPhotonPtForRecoEff", "GenPhoton[0].Pt()", cutStream_GenPhotonforRecoEff.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPtMConly);
		prediction->ChGenPhotonPtForRecoEff->fVerbose =prediction->fVerbose;
		prediction->ChGenPhotonPtForRecoEff->GetShapes("GenPhotonPtForRecoEff", "Gen-level #gamma Pt", 50, 150, 800);
		
		prediction->ChPhotonPtForRecoEff = new Channel("PhotonPtForRecoEff", "GenPhoton[0].Pt()", cutStream_PhotonPtforRecoEff.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPtMConly);
		prediction->ChPhotonPtForRecoEff->fVerbose =prediction->fVerbose;
		prediction->ChPhotonPtForRecoEff->GetShapes("PhotonPtForRecoEff", "Gen-level #gamma Pt", 50, 150, 800);
		
		prediction->DrawHistos(prediction->ChGenPhotonPtForRecoEff->hPhotons, prediction->ChPhotonPtForRecoEff->hPhotons,
				       "EX0"                              , "EX0same",
				       kViolet+3                          , kBlack,
				       20                                 ,4,
				       "#all"                             ,"recoed");
		TH1D* hPhotonRecoEff = prediction->GetRatio(prediction->ChPhotonPtForRecoEff->hPhotons, prediction->ChGenPhotonPtForRecoEff->hPhotons, 1, false);
		hPhotonRecoEff->SetMarkerColor(kBlack);
		hPhotonRecoEff->SetLineColor(kBlack);
		hPhotonRecoEff->SetMarkerStyle(4);
		DrawHisto(hPhotonRecoEff, "PhotonRecoEff","EX0", prediction->ChPhotonPtForRecoEff);
	}

	// Prediction
	if(fDoPrediction){
		*fLogStream<< "************************* Prediction ****************************** " << endl;

		TH1D* MCZnunu = prediction->GetScaledHisto(prediction->ChZnunuMT2->hZJetsToNuNu,fLumiCorr,0);  // scale to lumi 4400
		double MCZnunuEst    = MCZnunu->GetBinContent(1);
		double MCZnunuEstErr = MCZnunu->GetBinError(1);
		delete MCZnunu;
		if(fDoData){ 
		double nGamma    = prediction->ChPhotonsMT2->hData->Integral();
		double nGammaErr = sqrt(nGamma);
		*fLogStream << "********** Data Prediction ***************************************************** " << endl;
		MakePrediction(nGamma, nGammaErr, fZllToPhotonRatio, fZllToPhotonRatioRelErr, fZllAccEff, fZllAccEffRelErr, fZllRecoEff, fZllRecoEffRelErr, MCZnunuEst, MCZnunuEstErr);
		}
		TH1D* hDummy =   prediction->GetScaledHisto(prediction->ChPhotonsMT2->hPhotons, 1, 0);
		float nGammaMC   =hDummy->GetBinContent(1);
		float nGammaMCErr=hDummy->GetBinError(1);
		*fLogStream << "********** MC Prediction ***************************************************** " << endl;
		MakePrediction(nGammaMC, nGammaMCErr, fZllToPhotonRatio, fZllToPhotonRatioRelErr, fZllAccEff, fZllAccEffRelErr, fZllRecoEff, fZllRecoEffRelErr, MCZnunuEst, MCZnunuEstErr);
	}

	// write -----------
	if(fWriteToFile){
		TString logname =fOutDir + ".log"; 
		ofstream f_log (logname.Data(), ios::app);
		f_log << fLogStream->str();
	} else{
		cout << fLogStream->str();
	}

//	fOutFile->Close();

}
Esempio n. 20
0
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

  setTDRStyle();
  writeExtraText = false; // for JEC paper CWR

  TDirectory *curdir = gDirectory;

  // Open jecdata.root produced by reprocess.C
  TFile *fin = new TFile("rootfiles/jecdata.root","UPDATE");
  assert(fin && !fin->IsZombie());
  
  const int ntypes = 3;
  const char* types[ntypes] = {"data", "mc", "ratio"};
  const int nmethods = 2;
  const char* methods[nmethods] = {"mpfchs1", "ptchs"};
  const int nsamples = (dodijet ? 4 : 3);
  const char* samples[4] = {"gamjet", "zeejet", "zmmjet", "dijet"};
  string sbin = Form("eta%02.0f-%02.0f",10*etamin,10*etamax);
  const char* bin = sbin.c_str();
  const int nalphas = 4;
  const int alphas[nalphas] = {30, 20, 15, 10};

  // Z+jet bins
  const double ptbins1[] = {30, 40, 50, 60, 75, 95, 125, 180, 300, 1000};
  const int npt1 = sizeof(ptbins1)/sizeof(ptbins1[0])-1;
  TH1D *hpt1 = new TH1D("hpt1","",npt1,&ptbins1[0]);
  TProfile *ppt1 = new TProfile("ppt1","",npt1,&ptbins1[0]);

  // gamma+jet bins
  const double ptbins2[] = {30, 40, 50, 60, 75, 100, 125, 155, 180,
			    210, 250, 300, 350, 400, 500, 600, 800};
  const int npt2 = sizeof(ptbins2)/sizeof(ptbins2[0])-1;
  TH1D *hpt2 = new TH1D("hpt2","",npt2,&ptbins2[0]);
  TProfile *ppt2 = new TProfile("ppt2","",npt2,&ptbins2[0]);

  // dijet bins
  const double ptbins4[] = {20, 62, 107, 175, 242, 310, 379, 467,
			    628, 839, 1121, 1497, 2000};
  const int npt4 = sizeof(ptbins4)/sizeof(ptbins4[0])-1;
  TH1D *hpt4 = new TH1D("hpt4","",npt4,&ptbins4[0]);
  TProfile *ppt4 = new TProfile("ppt4","",npt4,&ptbins4[0]);

  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.045);

  map<string,const char*> texlabel;
  texlabel["gamjet"] = "#gamma+jet";
  texlabel["zeejet"] = "Z#rightarrowee+jet";
  texlabel["zmmjet"] = "Z#rightarrow#mu#mu+jet";
  texlabel["dijet"] = "Dijet";
  texlabel["ptchs"] = "p_{T} balance (CHS)";
  texlabel["mpfchs"] = "MPF raw (CHS)";
  texlabel["mpfchs1"] = "MPF type-I (CHS)";

  // overlay of various alpha values
  TCanvas *c1 = new TCanvas("c1","c1",ntypes*400,nmethods*400);
  c1->Divide(ntypes,nmethods);

  TH1D *h1 = new TH1D("h1",";p_{T} (GeV);Response",1270,30,1300);

  // extrapolation vs alpha for each pT bin
  vector<TCanvas*> c2s(ntypes*nmethods);
  for (unsigned int icanvas = 0; icanvas != c2s.size(); ++icanvas) {
    TCanvas *c2 = new TCanvas(Form("c2_%d",icanvas),Form("c2_%d",icanvas),
			      1200,1200);
    c2->Divide(3,3);
    c2s[icanvas] = c2;
  }

  TH1D *h2 = new TH1D("h2",";#alpha;Response",10,0.,0.4);
  h2->SetMaximum(1.08);
  h2->SetMinimum(0.88);

  // krad corrections
  TCanvas *c3 = new TCanvas("c3","c3",ntypes*400,nmethods*400);
  c3->Divide(ntypes,nmethods);

  TH1D *h3 = new TH1D("h3",";p_{T,ref} (GeV);FSR sensitivity: -dR/d#alpha [%]",
		      1270,30,1300);

  cout << "Reading in data" << endl << flush;
  // Read in plots vs pT (and alpha)
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gemap;
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gamap;
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      for (int  isample = 0; isample != nsamples; ++isample) {

	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  fin->cd();
	  assert(gDirectory->cd(types[itype]));
	  assert(gDirectory->cd(bin));
	  TDirectory *d = gDirectory;

	  const char *ct = types[itype];
	  const char *cm = methods[imethod];
	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  // Get graph made vs pT
	  string s = Form("%s/%s/%s_%s_a%d",types[itype],bin,cm,cs,a);
	  TGraphErrors *g = (TGraphErrors*)fin->Get(s.c_str());
	  if (!g) cout << "Missing " << s << endl << flush;
	  assert(g);

	  // Clean out empty points
	  // as well as trigger-biased ones for dijets
	  // as well as weird gamma+jet high pT point
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetY()[i]==0 || g->GetEY()[i]==0 ||
		(string(cs)=="dijet" && g->GetX()[i]<70.) ||
		(string(cs)=="gamjet" && g->GetX()[i]>600. && etamin!=0))
	      g->RemovePoint(i);
	  }

	  gemap[ct][cm][cs][a] = g;
	  
	  // Sort points into new graphs vs alpha
	  TH1D *hpt = (isample==0 ? hpt2 : hpt1);
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { hpt = hpt4; ppt = ppt4; } // pas-v6
	  for (int i = 0; i != g->GetN(); ++i) {
	    
	    double pt = g->GetX()[i];
	    ppt->Fill(pt, pt);
	    int ipt = int(hpt->GetBinLowEdge(hpt->FindBin(pt))+0.5);
	    //int ipt = int(pt+0.5);
	    TGraphErrors *ga = gamap[ct][cm][cs][ipt];
	    if (!ga) {
	      ga = new TGraphErrors(0);
	      ga->SetMarkerStyle(g->GetMarkerStyle());
	      ga->SetMarkerColor(g->GetMarkerColor());
	      ga->SetLineColor(g->GetLineColor());
	      gamap[ct][cm][cs][ipt] = ga;
	    }
	    int n = ga->GetN();
	    ga->SetPoint(n, 0.01*a, g->GetY()[i]);
	    ga->SetPointError(n, 0, g->GetEY()[i]);
	  } // for i 

	} // for ialpha

      } // for isample
    } // for imethod
  } // for itype

  cout << "Drawing plots vs pT for each alpha" << endl << flush;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c1->cd(ipad);
      gPad->SetLogx();
      h1->SetMaximum(itype<2 ? 1.15 : 1.08);
      h1->SetMinimum(itype<2 ? 0.85 : 0.93);
      h1->SetYTitle(Form("Response (%s)",ct));
      h1->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3, #alpha=0.1--0.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {
	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  TGraphErrors *g = gemap[ct][cm][cs][a]; assert(g);

	  // Clean out points with very large uncertainty for plot readability
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetEY()[i]>0.02) g->RemovePoint(i);
	  }

	  g->Draw("SAME Pz");

	  if (ialpha==0) leg->AddEntry(g,texlabel[cs],"P");
	}
      } // for isample

      // Individual plots for JEC paper
      if ( true ) { // paper

	TH1D *h = new TH1D(Form("h_5%s_%s",ct,cm),
			   Form(";p_{T} (GeV);Response (%s)",ct),
			   1270,30,1300);
	h->GetXaxis()->SetMoreLogLabels();
	h->GetXaxis()->SetNoExponent();
	h->SetMinimum(0.88);
	h->SetMaximum(1.13);

	writeExtraText = true;
	extraText = (string(ct)=="mc" ? "Simulation" : "");
	lumi_8TeV = (string(ct)=="mc" ? "" : "19.7 fb^{-1}");
	TCanvas *c0 = tdrCanvas(Form("c0_%s_%s",cm,ct), h, 2, 11, true);
	c0->SetLogx();
	

	TLegend *leg = tdrLeg(0.55,0.68,0.85,0.83);
	tex->DrawLatex(0.55,0.85,texlabel[cm]);
	tex->DrawLatex(0.55,0.18,"|#eta| < 1.3, #alpha=0.3");
	//tex->DrawLatex(0.55,0.18,"Anti-k_{T} R=0.5");

	// Loop over Z+jet and gamma+jet (only, no dijet/multijet)
	for (int  isample = 0; isample != min(3,nsamples); ++isample) {
	  
	  const char *cs = samples[isample];
	  TGraphErrors *g = gemap[ct][cm][cs][30]; assert(g);
	  g->Draw("SAME Pz");
	  
	  leg->AddEntry(g,texlabel[cs],"P");
	} // for isample

	if (etamin==0) {
	  c0->SaveAs(Form("pdf/paper_softrad_%s_%s_vspt.pdf",ct,cm));
	  c0->SaveAs(Form("pdfC/paper_softrad_%s_%s_vspt.C",ct,cm));
	}
	else {
	  c0->SaveAs(Form("pdf/an_softrad_%s_%s_eta%1.0f-%1.0f_vspt.pdf",
			  ct,cm,10*etamin,10*etamax));
	}
      } // paper

    } // for imethod
  } // for itype
  
  c1->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c1, 2, 33);
  c1->SaveAs("pdf/softrad_2x6_vspt.pdf");


  cout << "Drawing plots vs alpha for each pT" << endl << flush;
  cout << "...and fitting slope vs alpha" << endl << flush;

  map<string, map<string, map<string, TGraphErrors* > > > gkmap;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      
      int icanvas = nmethods*imethod + itype; assert(icanvas<=6);
      TCanvas *c2 = c2s[icanvas]; assert(c2);

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      const int npads = 9;
      for (int ipad = 0; ipad != npads; ++ipad) {
	c2->cd(ipad+1);
	h2->SetYTitle(Form("Response (%s)",ct));
	h2->DrawClone("AXIS");
	tex->DrawLatex(0.20,0.85,texlabel[cm]);
	tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
	tex->DrawLatex(0.20,0.75,Form("%1.0f < p_{T} < %1.0f GeV",
				      hpt1->GetBinLowEdge(ipad+1),
				      hpt1->GetBinLowEdge(ipad+2)));
	TLegend *leg = tdrLeg(0.65,0.75,0.90,0.90);
	leg->AddEntry(gemap[ct][cm]["gamjet"][30], texlabel["gamjet"], "P");
	leg->AddEntry(gemap[ct][cm]["zeejet"][30], texlabel["zeejet"], "P");
	leg->AddEntry(gemap[ct][cm]["zmmjet"][30], texlabel["zmmjet"], "P");
	leg->AddEntry(gemap[ct][cm]["dijet"][30], texlabel["dijet"], "P");
      }

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];

	map<int, TGraphErrors*> &gam = gamap[ct][cm][cs];
	map<int, TGraphErrors*>::iterator itpt;
	for (itpt = gam.begin(); itpt != gam.end(); ++itpt) {

	  int ipt = itpt->first;
	  int jpt = hpt1->FindBin(ipt);
	  if (jpt>npads) continue;
	  assert(jpt<=npads);
	  c2->cd(jpt);
	  
	  TGraphErrors *ga = itpt->second; assert(ga);
	  
	  ga->Draw("SAME Pz");

	  // Fit slope
	  TF1 *f1 = new TF1(Form("f1_%s_%s_%s_%d",ct,cm,cs,ipt),
			    "(x<1)*([0]+[1]*x) + (x>1 && x<2)*[0] +"
			    "(x>2)*[1]",-1,1);
	  f1->SetLineColor(ga->GetLineColor());
	  f1->SetParameters(1,0);
	  const double minalpha = (isample==0 ? 10./ipt : 5./ipt);
	  // Constrain slope to within reasonable values
	  // in the absence of sufficient data using priors
	  if (true) { // use priors
	    int n = ga->GetN();
	    // For response, limit to 1+/-0.02 (we've corrected for L3Res
	    ga->SetPoint(n, 1.5, 1);
	    ga->SetPointError(n, 0, 0.02);
	    n = ga->GetN();
	    if (imethod==1) { // pT balance
	      // For pT balance, estimate slope of <vecpT2>/alpha from data
	      // => 7.5%/0.30 = 25%
	      // Approximate uncertainty on this to be
	      // 0.5%/0.30 ~ 1.5% for data, 0.5%/0.30 ~ 1.5% for Z+jet MC, and
	      // 2%/0.30 ~ 6% for gamma+jet MC (same as slope)
	      if (itype==0)               ga->SetPoint(n, 2.5, -0.250); // DT
	      if (itype==1 && isample!=0) ga->SetPoint(n, 2.5, -0.250); // MC
	      if (itype==1 && isample==0) ga->SetPoint(n, 2.5, -0.190);
	      if (itype==2 && isample!=0) ga->SetPoint(n, 2.5, -0.000); // rt
	      if (itype==2 && isample==0) ga->SetPoint(n, 2.5, -0.060); 
	      //
	      // BUG: found 2015-01-08 (no effect on ratio)
	      //if (itype==1)               ga->SetPointError(n, 0, -0.015);
	      if (itype==0)               ga->SetPointError(n, 0, -0.015); // DT
	      if (itype==1 && isample!=0) ga->SetPointError(n, 0, -0.015); // MC
	      if (itype==1 && isample==0) ga->SetPointError(n, 0, -0.060);
	      if (itype==2 && isample!=0) ga->SetPointError(n, 0, -0.015); // rt
	      if (itype==2 && isample==0) ga->SetPointError(n, 0, -0.060); 
	    }
	    if (imethod==0) { // MPF
	      // For MPF, expectation is no slope
	      // Maximal slope would be approximately
	      // (<vecpT2>/alpha ~ 25% from pT balance) times
	      // (response difference between pT1 and vecpT2~10%)
	      // => 0.25*0.10 = 2.5%
	      // For data/MC, estimate uncertainty as half of this
	      // => 1.25%
	      ga->SetPoint(n, 2.5, 0.);
	      if (itype!=2) ga->SetPointError(n, 0, 0.025);
	      if (itype==2) ga->SetPointError(n, 0, 0.0125);
	    } // MPF
	  } // use priors

	  if (ga->GetN()>2) {

	    f1->SetRange(minalpha, 3.);
	    ga->Fit(f1,"QRN");

	    if (f1->GetNDF()>=0) {
	      f1->DrawClone("SAME");
	      f1->SetRange(0,0.4);
	      f1->SetLineStyle(kDashed);
	      f1->DrawClone("SAME");

	      // Store results
	      TGraphErrors *gk = gkmap[ct][cm][cs];
	      if (!gk) {
		gk = new TGraphErrors(0);
		gk->SetMarkerStyle(ga->GetMarkerStyle());
		gk->SetMarkerColor(ga->GetMarkerColor());
		gk->SetLineColor(ga->GetLineColor());
		gkmap[ct][cm][cs] = gk;
	      }
	      int n = gk->GetN();
	      TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	      if (isample==3) { ppt = ppt4; } // pas-v6
	      double pt = ppt->GetBinContent(ppt->FindBin(ipt));
	      gk->SetPoint(n, pt, f1->GetParameter(1));
	      gk->SetPointError(n, 0, f1->GetParError(1));
	    } // f1->GetNDF()>=0
	  } // ga->GetN()>2
	} // for itpt
	
      } // for isample
      
      c2->SaveAs(Form("pdf/softrad_3x3_%s_%s_vsalpha.pdf",ct,cm));
      
    }
  }


  cout << "Drawing plots of kFSR vs pT" << endl;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      TMultiGraph *mgk = new TMultiGraph();

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c3->cd(ipad);
      gPad->SetLogx();
      h3->SetMaximum(imethod==0 ? 0.05 : (itype!=2 ? 0.1 : 0.25));
      h3->SetMinimum(imethod==0 ? -0.05 : (itype!=2 ? -0.4 : -0.25));
      h3->SetYTitle(Form("k_{FSR} = dR/d#alpha (%s)",ct));
      h3->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];
	TGraphErrors *gk = gkmap[ct][cm][cs]; assert(gk);
	
	leg->AddEntry(gk,texlabel[cs],"P");

	// Fit each sample separately for pT balance
	if (true) {

	  TF1 *fk = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			    "[0]+[1]*log(0.01*x)+[2]*pow(log(0.01*x),2)",
			    30,1300);
	  fk->SetParameters(-0.25,-0.5);
	  fk->SetLineColor(gk->GetLineColor());
	  gk->Fit(fk, "QRN");

	  tex->SetTextColor(fk->GetLineColor());
	  tex->DrawLatex(0.55,0.27-0.045*isample,
			 Form("#chi^{2}/NDF = %1.1f / %d",
			      fk->GetChisquare(), fk->GetNDF()));
	  tex->SetTextColor(kBlack);

	  // Error band
	  const int n = fk->GetNpar();
	  TMatrixD emat(n,n);
	  gMinuit->mnemat(emat.GetMatrixArray(), n);
	  TF1 *fke = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			     sr_fitError, 30, 1300, 1);
	  _sr_fitError_func = fk;
	  _sr_fitError_emat = &emat;

	  fke->SetLineStyle(kSolid);
	  fke->SetLineColor(fk->GetLineColor()-10);
	  fke->SetParameter(0,-1);
	  fke->DrawClone("SAME");
	  fke->SetParameter(0,+1);
	  fke->DrawClone("SAME");

	  fk->DrawClone("SAME");
	  gk->DrawClone("SAME Pz");

	  // Store soft radiation corrections in fsr subdirectory
	  assert(fin->cd(ct));
	  assert(gDirectory->cd(bin));
	  if (!gDirectory->FindObject("fsr")) gDirectory->mkdir("fsr");
	  assert(gDirectory->cd("fsr"));

	  TH1D *hk = (TH1D*)(isample==0 ? hpt2->Clone() : hpt1->Clone());
	  hk->SetName(Form("hkfsr_%s_%s",cm,cs));
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { ppt = ppt4; } // pas-v6
	  for (int i = 1; i != hk->GetNbinsX()+1; ++i) {
	    double pt = ppt->GetBinContent(i);
	    if (pt>30 && pt<1300) {
	      hk->SetBinContent(i, fk->Eval(pt));
	      hk->SetBinError(i, fabs(fke->Eval(pt)-fk->Eval(pt)));
	    }
	    else {
	      hk->SetBinContent(i, 0);
	      hk->SetBinError(i, 0);
	    }
	  }
	  
	  hk->Write(hk->GetName(), TObject::kOverwrite);

	  // Factorize error matrix into eigenvectors
	  // Remember: A = Q*Lambda*Q^-1, where
	  // A is emat, Q is eigmat, and Lambda is a diagonal matrix with
	  // eigenvalues from eigvec on the diagonal. For eigenmatrix
	  // Q^-1 = Q^T, i.e. inverse matrix is the original transposed
	  TVectorD eigvec(n);
	  TMatrixD eigmat = emat.EigenVectors(eigvec);

	  // Eigenvectors are the columns and sum of eigenvectors squared
	  // equals original uncertainty. Calculate histograms from the
	  // eigenvectors and store them
	  TF1 *fkeig = (TF1*)fk->Clone(Form("%s_eig",fk->GetName()));
	  fkeig->SetLineStyle(kDotted);
	  for (int ieig = 0; ieig != n; ++ieig) {

	    // Eigenvector functions
	    for (int i = 0; i != n; ++i) {
	      fkeig->SetParameter(i, fk->GetParameter(i)
				  + eigmat[i][ieig] * sqrt(eigvec[ieig]));
	    }
	    fkeig->DrawClone("SAMEL");

	    // Eigenvector histograms evaluated at bin mean pT
	    TH1D *hke = (TH1D*)hk->Clone(Form("%s_eig%d",hk->GetName(),ieig));
	    hke->Reset();

	    for (int i = 0; i != gk->GetN(); ++i) {

	      double pt = gk->GetX()[i];
	      int ipt = hke->FindBin(pt);
	      // Need to store central value as well, because
	      // uncertainty sources are signed
	      hke->SetBinContent(ipt, fkeig->Eval(pt)-fk->Eval(pt));
	      hke->SetBinError(ipt, fabs(fkeig->Eval(pt)-fk->Eval(pt)));
	    }
	    hke->Write(hke->GetName(), TObject::kOverwrite);
	  }

	  cout << "." << flush;
	} // if tree
      } // for isample
    } // for imethod
  } // for itype
  
  c3->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c3, 2, 33);
  c3->SaveAs("pdf/softrad_2x6_kfsr.pdf");

  fin->Close();
  curdir->cd();
} // softrad
Esempio n. 21
0
void HwwGenJetVetoEfficiency(const string inputFilename,  const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  cout << "here1\n";
  string label = "";
  cout << "here11\n";
  if (Label != "") label = "_" + Label;
  cout << "here12\n";

  TFile *file = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");
  cout << "here13\n";
  assert(file);
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPtFineBinning_ggHww160_PowhegToNNLL");
  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww160_PowhegToNNLL");
  cout << "here14\n";
//    TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww160_MCAtNLOToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww180_PowhegToNNLL");//  
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww200_PowhegToNNLL");
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww220_PowhegToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww250_PowhegToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww300_PowhegToNNLL");
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww400_PowhegToNNLL");
  assert(kFactorHiggsPt);
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
    
  cout << "here2\n";

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *genMet = new TH1D("genMet", ";  Met [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonPtMin = new TH1D("leptonPtMin", ";  Lepton p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonEta = new TH1D("leptonEta", "; Lepton #eta; Number of Events", 50, -5, 5);
  TH1D *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *leadingGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *secondGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *nGenJets = new TH1D("nGenJets", "; Mass [GeV/c^{2}]; Number of Events", 10, -0.5, 9.5);
  TH1D *leptonDeltaPhi = new TH1D("leptonDeltaPhi", "; #Delta #phi (l,l); Number of Events", 50, 0, 180);


  vector<Double_t> NEvents_0Jets;
  vector<Double_t> NEvents_1Jets;
  vector<Double_t> NEvents_2Jets;
  for(UInt_t k=0 ; k < 200; ++k) {
    NEvents_0Jets.push_back(0); 
    NEvents_1Jets.push_back(0); 
    NEvents_2Jets.push_back(0);
  }


  Double_t NEventsGenerated = 0;
  Double_t NEventsAccepted = 0;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  mithep::TGenInfo *genInfo    = new mithep::TGenInfo();

  cout << "here3\n";

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); assert(eventTree);
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Gen", &genInfo); TBranch *genInfoBr = eventTree->GetBranch("Gen");
   
  cout << "here4\n";

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    genInfoBr->GetEntry(ientry);
		
    NEventsGenerated++;

   mithep::FourVectorM lepton1;
    mithep::FourVectorM lepton2;
    lepton1.SetCoordinates(genInfo->pt_1, genInfo->eta_1, genInfo->phi_1, 0.51099892e-3 );
    lepton2.SetCoordinates(genInfo->pt_2, genInfo->eta_2, genInfo->phi_2, 0.51099892e-3 );
    mithep::FourVectorM dilepton = lepton1+lepton2;

    if (genInfo->pt_1 > 20.0 && genInfo->pt_2 > 20.0
        && fabs(genInfo->eta_1) < 2.5 && fabs(genInfo->eta_2) < 2.5
        && genInfo->met > 30.0
        && fabs(dilepton.M() - 91.2) > 15.0
      ) {
      Double_t scale = kFactorHiggsPt->GetBinContent(kFactorHiggsPt->GetXaxis()->FindFixBin(genInfo->ptBosonSystem));
      scale = 1;

      if (info->eventweight >= 0) {
        
        //don't use a scale factor for Higgs pt < 1.0, because HQT does negative.
        if (genInfo->ptBosonSystem < 1.25 ) scale = 1.0;

        //powheg
        if (genInfo->ptBosonSystem > 200) scale = 0.6;
        //MC@NLO
//          if (genInfo->ptBosonSystem > 200) scale = 1.5;        

         leadingGenJetPt->Fill(genInfo->jetpt_1,1.0);
         leadingGenJetPt_reweighted->Fill(genInfo->jetpt_1,scale);

         for(UInt_t k=0 ; k < 200; ++k) {
           if (genInfo->jetpt_1 > k && genInfo->jetpt_2 > k) {
             NEvents_2Jets[k] += scale;
           } else if (genInfo->jetpt_1 > k) {
             NEvents_1Jets[k] += scale; 
           } else {
             NEvents_0Jets[k] += scale;
           }                                
         }

      } else {       
        leadingGenJetPt_reweighted->Fill(genInfo->jetpt_1,-1*scale);
        leadingGenJetPt->Fill(genInfo->jetpt_1,-1*scale);
        
        for(UInt_t k=0 ; k < 200; ++k) {
          if (genInfo->jetpt_1 > k && genInfo->jetpt_2 > k) {
            NEvents_2Jets[k] += -1*scale;
          } else if (genInfo->jetpt_1 > k) {
            NEvents_1Jets[k] += -1*scale; 
          } else {
             NEvents_0Jets[k] += -1*scale;
          }                                
        }

      }
    }
  } //end loop over data     

  delete info;
  delete genInfo;

  //--------------------------------------------------------------------------------------------------------------
  // Compute Jet Veto Efficiency
  //==============================================================================================================
  TH1D *jetVetoEfficiency = (TH1D*)leadingGenJetPt->Clone((string("jetVetoEfficiency")+label).c_str()); 
  jetVetoEfficiency->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt->Integral(1,i);
    Int_t d = leadingGenJetPt->Integral(1,leadingGenJetPt->GetXaxis()->GetNbins()+1);
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    Int_t errorType = 2;
    mithep::MathUtils::CalcRatio(n , d, ratio, errLow, errHigh, errorType);

    jetVetoEfficiency->SetBinContent(i,ratio);
    jetVetoEfficiency->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }

  TH1D *jetVetoEfficiency_reweighted = (TH1D*)leadingGenJetPt_reweighted->Clone((string("jetVetoEfficiency_reweighted")+label).c_str()); 
  jetVetoEfficiency_reweighted->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency_reweighted->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency_reweighted->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt_reweighted->Integral(1,i);
    Int_t d = leadingGenJetPt_reweighted->Integral(1,leadingGenJetPt_reweighted->GetXaxis()->GetNbins()+1);
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    Int_t errorType = 2;
    mithep::MathUtils::CalcRatio(n , d, ratio, errLow, errHigh, errorType);

    jetVetoEfficiency_reweighted->SetBinContent(i,ratio);
    jetVetoEfficiency_reweighted->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency_reweighted->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }





  //*****************************************************************************************************
  //0,1,2 - Jet Fractions
  //*****************************************************************************************************
  const int nPoints = 100;
  double jetPtCut[nPoints];
  double jetPtCutError[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    jetPtCut[i] = i;
    jetPtCutError[i] = 0;     
  }

  double ZeroJetFraction[nPoints];
  double ZeroJetFractionErrLow[nPoints];
  double ZeroJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_0Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    ZeroJetFraction[i] = ratio;
    ZeroJetFractionErrLow[i] = errLow;
    ZeroJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *ZeroJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, ZeroJetFraction, jetPtCutError, jetPtCutError, ZeroJetFractionErrLow, ZeroJetFractionErrHigh);
  ZeroJetFractionVsJetPtCut->SetName(("ZeroJetFractionVsJetPtCut"+label).c_str());
  ZeroJetFractionVsJetPtCut->SetMarkerColor(kRed);
  ZeroJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  ZeroJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);



  double OneJetFraction[nPoints];
  double OneJetFractionErrLow[nPoints];
  double OneJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_1Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    OneJetFraction[i] = ratio;
    OneJetFractionErrLow[i] = errLow;
    OneJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *OneJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, OneJetFraction, jetPtCutError, jetPtCutError, OneJetFractionErrLow, OneJetFractionErrHigh);
  OneJetFractionVsJetPtCut->SetName(("OneJetFractionVsJetPtCut"+label).c_str());
  OneJetFractionVsJetPtCut->SetMarkerColor(kBlue);
  OneJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  OneJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);



  double TwoJetFraction[nPoints];
  double TwoJetFractionErrLow[nPoints];
  double TwoJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_2Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    TwoJetFraction[i] = ratio;
    TwoJetFractionErrLow[i] = errLow;
    TwoJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *TwoJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, TwoJetFraction, jetPtCutError, jetPtCutError, TwoJetFractionErrLow, TwoJetFractionErrHigh);
  TwoJetFractionVsJetPtCut->SetName(("TwoJetFractionVsJetPtCut"+label).c_str());
  TwoJetFractionVsJetPtCut->SetMarkerColor(kMagenta);
  TwoJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  TwoJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);




  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================

  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  TLegend *tmpLegend = new TLegend(0.73,0.55,0.93,0.70); 
  

  tmpLegend->SetTextSize(0.03);
  tmpLegend->SetBorderSize(1);
  tmpLegend->AddEntry(leadingGenJetPt, "Powheg", "LP");   
  tmpLegend->AddEntry(leadingGenJetPt_reweighted, "MC@NLO(reweighted)", "LP");   
  cv->SetLogy();
  leadingGenJetPt->Draw();
  leadingGenJetPt->SetLineColor(kRed);
  leadingGenJetPt_reweighted->Draw("same");
  tmpLegend->Draw();
  cv->SaveAs("leadingGenJetPt.gif");

  jetVetoEfficiency->Draw();
  cv->SaveAs("jetVetoEfficiency.gif");
 
  cv->SetLogy(0);
  tmpLegend->Clear();
  tmpLegend->AddEntry(ZeroJetFractionVsJetPtCut, "0Jet Fraction", "LP");   
  tmpLegend->AddEntry(OneJetFractionVsJetPtCut, "1Jet Fraction", "LP");   
  tmpLegend->AddEntry(TwoJetFractionVsJetPtCut, ">2 Jet Fraction", "LP");   
  ZeroJetFractionVsJetPtCut->GetYaxis()->SetRangeUser(0.0,1.0);
  ZeroJetFractionVsJetPtCut->Draw("AP");
  OneJetFractionVsJetPtCut->Draw("Psame");
  TwoJetFractionVsJetPtCut->Draw("Psame");
  cv->SaveAs("NJetFractions.gif");


  file->WriteTObject(leadingGenJetPt, leadingGenJetPt->GetName(), "WriteDelete");
  file->WriteTObject(leadingGenJetPt_reweighted, leadingGenJetPt_reweighted->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency, jetVetoEfficiency->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency_reweighted, jetVetoEfficiency_reweighted->GetName(), "WriteDelete");
  file->WriteTObject(ZeroJetFractionVsJetPtCut, ZeroJetFractionVsJetPtCut->GetName(), "WriteDelete");
  file->WriteTObject(OneJetFractionVsJetPtCut, OneJetFractionVsJetPtCut->GetName(), "WriteDelete");
  file->WriteTObject(TwoJetFractionVsJetPtCut, TwoJetFractionVsJetPtCut->GetName(), "WriteDelete");
//   file->Close();

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
 


        
  gBenchmark->Show("plotZ");       
} 
TH1D *recurseFile(TDirectory *indir, TDirectory *outdir, string hname,
                  bool atBottom, TH1D *_hpt, double etamid) {
    TDirectory *curdir = gDirectory;

    // Recurse over all directories
    TList *keys = indir->GetListOfKeys();
    TListIter itkey(keys);
    TObject *key, *obj;

    while ((key = itkey.Next())) {

        std::string classname = ((TKey *)key)->GetClassName();
        std::string kname = key->GetName();

        // Search for a directory or histogram
        if (classname == "TDirectoryFile" || kname == hname) {
            obj = ((TKey *)key)->ReadObj();
            assert(obj);
        } 
        else {
            continue;
        }

        // Found a subdirectory: copy it to output and go deeper
        if (classname == "TDirectoryFile" && obj->InheritsFrom("TDirectory")) {
            TDirectory *outdir2 = outdir;

            if (!atBottom) {
                if (outdir->FindKey(obj->GetName()) == 0)
                    outdir->mkdir(obj->GetName());
            
                assert(outdir->cd(key->GetName()));
                outdir2 = outdir->GetDirectory(key->GetName());
            
                assert(outdir2);
                outdir2->cd();
            
                if (_debug)
                    cout << key->GetName() << endl;
            
            } else if (_debug)
                std::cout << key->GetName() << " (at bottom)" << endl;

            assert(indir->cd(obj->GetName()));
            
            TDirectory *indir2 = indir->GetDirectory(obj->GetName());
            assert(indir2);
            indir2->cd();

            // Check if directory name contains information on eta bin width
            // If yes, the next level is the bottom level with triggers
            // set flag and reset the combined histogram pointer
            float etamin, etamax;
            int valuesRead = sscanf(indir2->GetName(), "Eta_%f-%f", &etamin, &etamax);
            
            if (valuesRead == 2 && etamax > etamin) {

                float etamid = 0.5 * (etamin + etamax);
                _hpt = recurseFile(indir2, outdir2, hname, true, _hpt, etamid);

                if (_hpt) {
                    outdir2->cd();
                    _hpt->Write();
                    _hpt = 0;
                }
            } else {
                _hpt = recurseFile(indir2, outdir2, hname, atBottom, _hpt, etamid);
            }

        } 

        // Serch for a histogram
        else if (kname == hname && obj->InheritsFrom("TH1")) {
            
            TH1D *hpt = (TH1D *)obj;

            if (_hpt == 0) {
                outdir->cd();
                _hpt = (TH1D *)hpt->Clone(hpt->GetName());
                _hpt->Reset();
                indir->cd();
                assert(_hpt);

                if (_debug)
                    cout << "Cloned _" << hpt->GetName() << endl;
            }

            assert(_ptranges.find(indir->GetName()) != _ptranges.end() && "pT range not found for directory ");
            
            double ptmin = _ptranges[indir->GetName()].first;
            double ptmax = _ptranges[indir->GetName()].second;

            // Copy histogram values to output
            for (int i = 1; i != _hpt->GetNbinsX() + 1; ++i) {   
                double pt = _hpt->GetBinCenter(i);
                if (ptmin < pt && pt < ptmax) {
                    _hpt->SetBinContent(i, hpt->GetBinContent(i));
                    _hpt->SetBinError(i, hpt->GetBinError(i));
                } 
            }     
        } 
        // Free memory
        obj->Delete();
    } 

    // Free memory
    if (indir == _top) {
        std::cout << ".";;
    }

    curdir->cd();

    return _hpt;
} 
Esempio n. 23
0
void drawSingleVariable(TH1D* theHist, int lowCent, int highCent, TString variable1, TCut addCut1, TString variable2, TCut addCut2, int normChoice,bool overDraw, TH1D* theMCSig) { 
   theHist->Reset();   
   if (addCut2 =="")  
      addCut2 = addCut1;
   if (variable2 =="")
      variable2 = variable1;

   cout << "addCut2 = " << addCut2.GetTitle() << endl;
   cout << "variable2 = "<< variable2 << endl;

   TString fname1 = "rootFiles/barrelHiForestPhoton35_Skim2011-Dec04-withTracks.root";//barrelHiForestPhoton35_Skim2011-v2.root";
   TFile *f1  =new TFile(fname1.Data());
   TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
   photon1->AddFriend("yEvt=yongsunHiEvt"    ,fname1.Data());
   photon1->AddFriend("yskim=yongsunSkimTree"   ,fname1.Data());
   photon1->AddFriend("yhlt=yongsunHltTree"     ,fname1.Data());

   TString fname2 = "rootFiles/barrelHiForestPhoton35_Skim2010.root";
   TFile *f2  =new TFile(fname2.Data());
   TTree *photon2 = (TTree*)f2->Get("yongsunPhotonTree");
   //  photon2->AddFriend("yEvt=yongsunHiEvt"    ,fname2.Data());
   photon2->AddFriend("yskim=yongsunSkimTree"   ,fname2.Data());
   photon2->AddFriend("yhlt=yongsunHltTree"     ,fname2.Data());
   
   TString fnameMC ;
   TFile *fMC;
   TTree *photonSig;
   if ( theMCSig){ 
      fnameMC = "rootFiles/barrelHiForestPhoton35_MCPhoton50_25k.root";
      fMC  =new TFile(fnameMC.Data());
      photonSig = (TTree*)fMC->Get("yongsunPhotonTree");
      photonSig->AddFriend("yEvt=yongsunHiEvt"    ,fnameMC.Data());
      cout << " MC is running " << endl;
   }
   //   photonSig->AddFriend("yskim=yongsunSkimTree"   ,fnameMC.Data());
   //  photonSig->AddFriend("yhlt=yongsunHltTree"     ,fnameMC.Data());
   
   //genMatchCut1 
   TCut collisionCut = "yskim.pcollisionEventSelection==1";
   
   TCut runCut1       = ""; //"yhlt.Run>= 181985 && yhlt.Run <=182099"; 
   
   TCut centCut1     = Form("(yEvt.hiBin >= %d) && (yEvt.hiBin<= %d)",lowCent,highCent);
   TCut centCut2     = Form("(cBin >= %d) && (cBin <= %d)",lowCent,highCent);
   
   TCut spikeCut1     = "abs(seedTime)<4 && swissCrx<0.90 && sigmaIetaIeta>0.002";
   TCut spikeCut2   = "abs(seedTime)<4 && (1 - (eRight+eLeft+eTop+eBottom)/eMax)<0.90 && sigmaIetaIeta>0.002";
   TCut spikeCutSig = "swissCrx<0.90 && sigmaIetaIeta>0.002";

   TCut nonElectron = "!isEle";
   
   TCut hltCut1       = "yhlt.HLT_HISinglePhoton30_v2==1"; // 181695 => H/E cut is removed from L1
   TCut hltCut2       = "yhlt.HLT_HIPhoton30==1";
      
   TCut basicCut1       = collisionCut && nonElectron && etaCut && spikeCut1 && centCut1 && runCut1 && hltCut1;
   TCut basicCut2       = collisionCut && nonElectron && etaCut && spikeCut2 && centCut2; //&& hltCut2;
   TCut basicCutSig     =                 nonElectron && etaCut && spikeCutSig && centCut1;
   
   
   TCut finalCut1     = basicCut1   && addCut1;
   TCut finalCut2     = basicCut2   && addCut2;
   TCut finalCutSig   = basicCutSig && addCut1 && genMatchCut1;
   
   TH1D* tempHist1 = (TH1D*)theHist->Clone("tempHist1");
   TH1D* tempHist2 = (TH1D*)theHist->Clone("tempHist2");
   TH1D* tempHistSig = (TH1D*)theHist->Clone("tempHistSig");
   
   
   photon1->Draw(Form("%s>>%s",variable1.Data(),tempHist1->GetName()),finalCut1);
   photon2->Draw(Form("%s>>%s",variable2.Data(),tempHist2->GetName()),finalCut2);
   if ( theMCSig) {
      photonSig->Draw(Form("%s>>%s",variable1.Data(),tempHistSig->GetName()),  Form("(%s)*ncoll",finalCutSig.GetTitle()));
      cout << " mc cut = " << finalCutSig.GetTitle() << endl;
   }

   tempHist1->Sumw2();
   tempHist2->Sumw2();
   if ( theMCSig)
      tempHistSig->Sumw2();
   
   handsomeTH1(tempHist1,2);
   handsomeTH1(tempHist2,1);
   tempHist2->SetMarkerStyle(24);
   if ( normChoice == 0) {
      scaleInt(tempHist1);
      scaleInt(tempHist2);
   }
   if ( normChoice == 1) {
      double nEvents1 = photon1->GetEntries("leading==1" && basicCut1 && "pt>40 && hadronicOverEm<0.2");
      double nEvents2 = photon2->GetEntries("leading==1" && basicCut2 && "pt>40 && hadronicOverEm<0.2");
      tempHist1->Scale(1./nEvents1);
      tempHist2->Scale(1./nEvents2);
      cout <<" this file is<<" << nEvents1/nEvents2 * 6.7 << "micro barn" << endl;
   }
   if ( normChoice == 2) {
      double nLumi1 = 17.4   ; //microb^-1
      double nLumi2 = 7.0  ;
      tempHist1->Scale(1./nLumi1);
      tempHist2->Scale(1./nLumi2);
   }
   
   cleverRange(tempHist2,1.5);
   if ( overDraw) 
      tempHist2->DrawCopy("same");//hist");
   else 
      tempHist2->DrawCopy("");//hist");                                                                                                  

   tempHist1->DrawCopy("same");
   
   TLegend* leg1 =  new TLegend(0.4012097,0.7584746,1,0.9300847,NULL,"brNDC");
   easyLeg(leg1,"");
   leg1->AddEntry(tempHist2,"2010 PbPb, 6.8 #mub^{-1}","pl");
   leg1->AddEntry(tempHist1,"2011 PbPb, 84  #mub^{-1}","pl");
   leg1->Draw();
   theHist->Reset();
   theHist->Add(tempHist1);
   if ( theMCSig)
      theMCSig->Add(tempHistSig);
   
}
Esempio n. 24
0
void mc2ibd_gtDiff(TChain *tMC, TFile *fBgnd, TCanvas *cv, const char *pdfname)
{
	char str[1024];
	TLatex *txt = new TLatex();
	TVirtualPad *pd;

	TH1D *hExp = (TH1D *) fBgnd->Get("hgtDiffA-diff");
	if (!hExp) {
		printf("Histogram hgtDiffA-diff not found in %s\n", fBgnd->GetName());
		return;
	}
	hExp->SetTitle("Time between prompt and delayed events (IBD);us;Events/us");
	hExp->SetLineColor(kBlack);
	hExp->SetMinimum(0);

	gROOT->cd();
	TH1D *hMC = new TH1D("hgtDiffMC", "Time between prompt and delayed events (MC);us;Events/us", 50, 0, 50);
	hMC->SetLineColor(kBlack);
	tMC->Project(hMC->GetName(), "gtDiff", cX && cY && cZ && cR && cGamma && cGammaMax && cPe && cN);
	hMC->Sumw2();
	hMC->Scale(hExp->Integral(2,50) / hMC->Integral(2,50));
//		Exp vs MC
	cv->Clear();
	cv->Divide(1, 2);
	cv->cd(1);
	hExp->SetLineColor(kBlack);
	hExp->SetLineWidth(3);
	hMC->SetLineColor(kBlue);
	hMC->SetLineWidth(1);
	hExp->Draw();
	hMC->Draw("hist,same");
	TLegend *lg = new TLegend(0.15, 0.2, 0.4, 0.35);
	lg->AddEntry(hExp, "IBD", "LE");
	lg->AddEntry(hMC, "MC", "L");
	lg->Draw();

	pd = cv->cd(2);
	hExp->SetMinimum(2000);
	hExp->Draw();
	hMC->Draw("hist,same");
	lg->Draw();
	pd->SetLogy(1);
	cv->Update();
	cv->SaveAs(pdfname);
	hExp->SetMinimum(0);
	hExp->SetLineWidth(1);
	hMC->SetLineColor(kBlack);
	
//		Fits
	TF1 *f2Exp = new TF1("f2Exp", "[0]*(exp(-x/[1]) - exp(-x/[2]))", 0, 100);
	f2Exp->SetParNames("Const.", "#tau_{capt}", "#tau_{th}");
	f2Exp->SetLineColor(kBlue);
	
	TF1 *fExp = new TF1("fExp", "expo", 0, 100);
	fExp->SetLineColor(kRed);
	
	cv->Clear();
	cv->Divide(1, 2);
	cv->cd(1);
	f2Exp->SetParameters(hExp->GetMaximum(), 13, 5);
	hExp->Fit(f2Exp, "", "", 1, 50);
	hExp->Fit(fExp, "+", "", 15, 50);
	lg = new TLegend(0.15, 0.2, 0.4, 0.35);
	lg->AddEntry(hExp, "Data", "LE");
	lg->AddEntry(f2Exp, "Fit with two exponents", "L");
	lg->AddEntry(fExp, "Capture exponent fit", "L");
	lg->Draw();
	sprintf(str, "#tau_{capt}=%5.2f us", -1/fExp->GetParameter(1));
	txt->DrawLatex(20, hExp->GetMaximum()/5, str);
	sprintf(str, "#chi^{2}/NDF=%6.1f/34", fExp->GetChisquare());
	txt->DrawLatex(20, hExp->GetMaximum()/10, str);
	
	cv->cd(2);
	f2Exp->SetParameters(hMC->GetMaximum(), 13, 5);
	hMC->Fit(f2Exp, "", "", 1, 50);
	hMC->Fit(fExp, "+", "", 15, 50);
	lg->Draw();
	sprintf(str, "#tau_{capt}=%5.2f us", -1/fExp->GetParameter(1));
	txt->DrawLatex(20, hMC->GetMaximum()/5, str);
	sprintf(str, "#chi^{2}/NDF=%6.1f/34", fExp->GetChisquare());
	txt->DrawLatex(20, hMC->GetMaximum()/10, str);
	cv->SaveAs(pdfname);
//		Tha same in log scale
	hExp->SetMinimum(2000);
	cv->Clear();
	cv->Divide(1, 2);
	pd = cv->cd(1);
	hExp->Draw();
	lg->Draw();
	pd->SetLogy(1);
	
	pd = cv->cd(2);
	hMC->Draw();
	lg->Draw();
	pd->SetLogy(1);
	cv->Update();
}
Esempio n. 25
0
void ZmmGenJetVetoEfficiency(const string inputFilename,  const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  string label = "";
  if (Label != "") label = "_" + Label;

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
    

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *genMet = new TH1D("genMet", ";  Met [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonPtMin = new TH1D("leptonPtMin", ";  Lepton p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonEta = new TH1D("leptonEta", "; Lepton #eta; Number of Events", 50, -5, 5);
  TH1D *bosonSystemPt = new TH1D((string("bosonSystemPt")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str(), "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *nGenJets = new TH1D("nGenJets", "; Mass [GeV/c^{2}]; Number of Events", 10, -0.5, 9.5);
  TH1D *leptonDeltaPhi = new TH1D("leptonDeltaPhi", "; #Delta #phi (l,l); Number of Events", 50, 0, 180);



  Double_t NEventsGenerated = 0;
  Double_t NEventsAccepted = 0;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  mithep::TGenInfo *genInfo    = new mithep::TGenInfo();


  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); assert(eventTree);
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Gen", &genInfo); TBranch *genInfoBr = eventTree->GetBranch("Gen");
   

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    genInfoBr->GetEntry(ientry);
		
    NEventsGenerated++;

    if (genInfo->pt_1 > 20.0 && genInfo->pt_2 > 20.0
        && fabs(genInfo->eta_1) < 2.5 && fabs(genInfo->eta_2) < 2.5
        && genInfo->vmass_1 > 76 && genInfo->vmass_1 < 106
      ) {
      leadingGenJetPt->Fill(genInfo->jetpt_1);
      bosonSystemPt->Fill(genInfo->ptBosonSystem);
    }
  } //end loop over data     

  delete info;
  delete genInfo;

  //--------------------------------------------------------------------------------------------------------------
  // Compute Jet Veto Efficiency
  //==============================================================================================================
  TH1D *jetVetoEfficiency = (TH1D*)leadingGenJetPt->Clone((string("jetVetoEfficiency")+label).c_str()); 
  jetVetoEfficiency->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt->Integral(1,i);
    Int_t d = leadingGenJetPt->Integral(1,leadingGenJetPt->GetXaxis()->GetNbins()+1);
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    Int_t errorType = 2;
    mithep::MathUtils::CalcRatio(n , d, ratio, errLow, errHigh, errorType);

    jetVetoEfficiency->SetBinContent(i,ratio);
    jetVetoEfficiency->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }

  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TFile *file = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");

  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  leadingGenJetPt->Draw();
  cv->SaveAs("leadingGenJetPt.gif");

  jetVetoEfficiency->Draw();
  cv->SaveAs("jetVetoEfficiency.gif");
 
  bosonSystemPt->Draw();
  cv->SaveAs("bosonSystemPt.gif");

  file->WriteTObject(leadingGenJetPt, leadingGenJetPt->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency, jetVetoEfficiency->GetName(), "WriteDelete");
  file->WriteTObject(bosonSystemPt, bosonSystemPt->GetName(), "WriteDelete");
  file->Close();

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
 


        
  gBenchmark->Show("plotZ");       
} 
Esempio n. 26
0
void CombineLLAAForDirectory(TDirectory *dataDir)
{
  // Run after merging centralities
  vector<TString> centBins = {"010", "1030", "3050"};
  vector<TString> pairTypes = {"LamLam", "ALamALam"};
  TString finalPairType = "LLAA";


  // Get merge dir
  TDirectory *mergeDir = dataDir->GetDirectory("Merged");
  if(!mergeDir) {
    cout<<"Merge directory does not exist. Cannot merge."<<endl;
    return;
  }

  for(UInt_t iCent = 0; iCent < centBins.size(); iCent++) {
    vector<TH1D*> cfs;
    vector<Double_t> counts;
    Double_t totalCounts = 0;
    for(UInt_t iType = 0; iType < pairTypes.size(); iType++) {
      TString cfName = "CF" + pairTypes[iType] + centBins[iCent];
      TH1D *cf = (TH1D*)mergeDir->Get(cfName);
      if(!cf) {
	cout<<"Could not find CF named "<<cfName<<" in "<<mergeDir->GetName()<<endl;
	return;
      }
      cfs.push_back(cf);
      TString countName = "Count" + pairTypes[iType] + centBins[iCent];
      TVectorD *count = (TVectorD*) mergeDir->Get(countName);
      totalCounts += count[0](0);
      counts.push_back(count[0](0));
    }

    // Finally, combine the CFs
    TH1D *combinedCF = CombineCFs(cfs, counts);
    if (!combinedCF) {
      cout << "Combine CF returned nothing. Continuing loop."
	   <<endl;
      continue;
    }
    TVectorD finalCount(1);
    finalCount[0] = totalCounts;

    // Set names
    TString combinedCFName = "CF" + finalPairType + centBins[iCent];
    TString combinedCountName = "Count" + finalPairType + centBins[iCent];
    combinedCF->SetName(combinedCFName);
    combinedCF->SetTitle(combinedCFName);

    // Set axis ranges
    combinedCF->SetAxisRange(0.9, 1.1, "Y");
    combinedCF->SetAxisRange(0., 1., "X");

    cout<<"Writing combined CF "<<combinedCF->GetName()
    	<<" to "<<mergeDir->GetName()<<endl;
    combinedCF->SetDirectory(0);
    mergeDir->cd();
    combinedCF->Write(combinedCF->GetName(), TObject::kOverwrite);
    finalCount.Write(combinedCountName, TObject::kOverwrite);
  
  }
}
Esempio n. 27
0
void CombineCFsInDataDir(TDirectory *f, vector<TString> dataSetNames)
{
  TString cfDirName = "CF";
  TString countDirName = "Count";
  vector<TDirectory*> cfDirs = GetDirectories(f, dataSetNames, cfDirName);
  vector<TDirectory*> countDirs = GetDirectories(f, dataSetNames, countDirName);
  TDirectory *mergeDir = (TDirectory*)f->GetDirectory("Merged");
  if(!mergeDir) {
    mergeDir = f->mkdir("Merged");
  }

  UInt_t nDirs = cfDirs.size();
  // Merge each centrality one at a time
  // Load the cfs and counts into vectors for that centrality
  // Find all the cfs and counts that match the name of the CF
  // in the first directory
  TIter iter(cfDirs[0]->GetListOfKeys());
  TObject *obj = NULL;

  while ( (obj = iter()) ) {
    TKey *key = dynamic_cast<TKey*>(obj);
    TH1D *cf = dynamic_cast<TH1D*>(key->ReadObj());
    if(!cf) {
      cout<<"Could not find a CF hist"<<endl;
      return;
    }
    //Figure out which CF we are trying to grab
    TString cfName = cf->GetName();
    TString countName = cfName;
    countName.ReplaceAll("CF","Count");

    //Grab the corresponding CFs and counts
    vector<TH1D*> cfs;
    vector<Double_t> counts;
    Double_t totalCounts = 0;
    for(UInt_t iDir = 0; iDir < nDirs; iDir++) {
      TH1D *thisCF = (TH1D*) cfDirs[iDir]->Get(cfName);
      if(!thisCF) {
	cout<<"Could not find CF matching "<<cfName
	    <<" in "<<cfDirs[iDir]->GetName()<<endl;
      }
      // TVectorD *count = dynamic_cast<TVectorD*>(countDirs[iDir]->Get(countName));
      TVectorD *count = (TVectorD*)countDirs[iDir]->Get(countName);
      // cout<<count->ClassName()<<endl;
      Double_t myCount = count[0](0);
      
      cfs.push_back(thisCF);
      counts.push_back(myCount);
      totalCounts += myCount;
    }
    // Finally, combine the CFs
    TH1D *combinedCF = CombineCFs(cfs, counts);
    if (!combinedCF) {
      cout << "Combine CF returned nothing. Continuing loop."
	   <<endl;
      continue;
    }
    TVectorD finalCount(1);
    finalCount[0] = totalCounts;

    cout<<"Writing combined CF "<<combinedCF->GetName()
    	<<" to "<<mergeDir->GetName()<<endl;
    combinedCF->SetDirectory(0);
    mergeDir->cd();
    combinedCF->Write(combinedCF->GetName(), TObject::kOverwrite);
    finalCount.Write(countName, TObject::kOverwrite);
  }
}
void plotphi(int top, bool phi=kFALSE){
  if (setup("vm","","pol__")==kFALSE) return;
  gStyle->SetOptFit(1111); //pcev = 1111
  //gStyle->SetTitleW(1.5);

  int itop = top-1;
  TFile* fy = _fyexp[itop];

  int nq2wbins = fy->GetNkeys();
  TIter nextkey(fy->GetListOfKeys());
  TKey *key;
  int iq2wbin = 0;
  while (key = (TKey*)nextkey()) {
    TString Q2Wdirname = key->GetName();
    if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
    cout << "Q2Wdirname = " << Q2Wdirname << endl;

    THStack* hs[10];
    TF1 *fphi = new TF1("fphi", "([0] + [1]*cos(x*TMath::DegToRad()) + [2]*cos(2*x*TMath::DegToRad()) + [3]*sin(x*TMath::DegToRad()))",0, 360);
    fphi->SetParameter(0,1);
    fphi->SetParameter(1,10);
    fphi->SetParameter(2,20);
    fphi->SetParameter(3,100);
    fphi->SetParName(0, "A");
    fphi->SetParName(1, "B");
    fphi->SetParName(2, "C");
    fphi->SetParName(3, "hPR");
    for (int i = 0; i < 10; i++)
    {
      TString hname_unp = TString::Format("%s/hPhi/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      TString hname_pos = TString::Format("%s/hPhi_POS/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      TString hname_neg = TString::Format("%s/hPhi_NEG/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      cout << "hname_unp = " << hname_unp << endl;
      cout << "hname_pos = " << hname_pos << endl;
      cout << "hname_neg = " << hname_neg << endl;
      TH1D* hunp = (TH1D*)fy->Get(hname_unp);
      TH1D* hpos = (TH1D*)fy->Get(hname_pos);
      TH1D* hneg = (TH1D*)fy->Get(hname_neg);
      if (hunp==NULL || hpos==NULL || hneg==NULL) cout << "histogram not found" << endl;
      hunp->SetLineColor(kBlack);
      hpos->SetLineColor(kRed);
      hneg->SetLineColor(kBlue);
      hunp->Fit(fphi);
      hpos->Fit(fphi);
      hneg->Fit(fphi);

      //! Modify titles
      TObjArray *tarr;
      char t[100];

      TPaveText *ptunp = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tunp = hunp->GetTitle();
      tarr = tunp.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptunp->AddText(tarr->At(0)->GetName());
      ptunp->AddText(t);
      hunp->SetTitle("");

      TPaveText *ptpos = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tpos = hpos->GetTitle();
      tarr = tpos.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptpos->AddText(tarr->At(0)->GetName());
      ptpos->AddText(t);
      hpos->SetTitle("");

      TPaveText *ptneg = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tneg = hneg->GetTitle();
      tarr = tneg.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptneg->AddText(tarr->At(0)->GetName());
      ptneg->AddText(t);
      hneg->SetTitle("");

      //! Draw histograms
      TCanvas *c = new TCanvas(hpos->GetName(),hpos->GetName(),900, 600);
      c->Divide(3,1);
      c->cd(1);
      hunp->Draw();
      ptunp->Draw();
      c->cd(2);
      hpos->Draw();
      ptpos->Draw();
      c->cd(3);
      hneg->Draw();
      ptneg->Draw();
      TString dir = TString::Format("./polobs/top%d/%s/Varset1/theta", top, Q2Wdirname.Data());
      gSystem->mkdir(dir,1);
      c->SaveAs(TString::Format("%s/%s.png", dir.Data(), c->GetName()));
      c->Close();
      c->Delete();
    }
  }
}
Esempio n. 29
0
void MakeMCHiggsPtDistribution( string inputFilename ,  const string Label) {

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
  string label = "";
  if (Label != "") label = "_" + Label;
 

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *genMet = new TH1D("genMet", ";  Met [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonPtMin = new TH1D("leptonPtMin", ";  Lepton p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonEta = new TH1D("leptonEta", "; Lepton #eta; Number of Events", 50, -5, 5);
  TH1D *bosonSystemPt = new TH1D((string("bosonSystemPt")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", 80, 1.25, 201.25);
  TH1D *bosonSystemPtFineBinning = new TH1D((string("bosonSystemPtFineBinning")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", 4000, 1.225, 201.225);
  TH1D *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *leadingGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *nGenJets = new TH1D("nGenJets", "; Mass [GeV/c^{2}]; Number of Events", 10, -0.5, 9.5);
  TH1D *leptonDeltaPhi = new TH1D("leptonDeltaPhi", "; #Delta #phi (l,l); Number of Events", 50, 0, 180);


  Double_t NEventsGenerated = 0;
  Double_t NEventsAccepted = 0;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  mithep::TGenInfo *genInfo    = new mithep::TGenInfo();

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); assert(eventTree);
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Gen", &genInfo); TBranch *genInfoBr = eventTree->GetBranch("Gen");

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    genInfoBr->GetEntry(ientry);
		
    NEventsGenerated++;

    mithep::FourVectorM lepton1;
    mithep::FourVectorM lepton2;
    lepton1.SetCoordinates(genInfo->pt_1, genInfo->eta_1, genInfo->phi_1, 0.51099892e-3 );
    lepton2.SetCoordinates(genInfo->pt_2, genInfo->eta_2, genInfo->phi_2, 0.51099892e-3 );
    mithep::FourVectorM dilepton = lepton1+lepton2;

    if (info->eventweight >= 0 && genInfo->ptBosonSystem <= 300) {
      bosonSystemPt->Fill(genInfo->ptBosonSystem);
      bosonSystemPtFineBinning->Fill(genInfo->ptBosonSystem);
    } else {
      bosonSystemPt->Fill(genInfo->ptBosonSystem, -1);
      bosonSystemPtFineBinning->Fill(genInfo->ptBosonSystem,-1);
    }


  } //end loop over data     

  delete info;
  delete genInfo;

  //--------------------------------------------------------------------------------------------------------------
  // Normalize Higgs Pt spectrum
  //==============================================================================================================
  Double_t norm = 0 ;
  for(int i=0; i<bosonSystemPt->GetXaxis()->GetNbins()+2 ; ++i) {
    norm += bosonSystemPt->GetBinContent(i);
  }
  for(int i=0; i<bosonSystemPt->GetXaxis()->GetNbins()+2 ; ++i) {
    bosonSystemPt->SetBinContent(i, bosonSystemPt->GetBinContent(i) / norm);
  }
//   for(int i=0; i<bosonSystemPt->GetXaxis()->GetNbins()+2 ; ++i) {
//     cout << "BosonPt " << i << " " << bosonSystemPt->GetBinContent(i) << endl;
//   }

  //smoothing - smooth to 1GeV bins
  double total = 0;
  for(int i=0; i<25 ; ++i) {
    total = 0;
    for (int j=0; j<20;j++) {
      total += bosonSystemPtFineBinning->GetBinContent(i*20 + j);
    }
    for (int j=0; j<20;j++) {
      bosonSystemPtFineBinning->SetBinContent(i*20 + j, total / 20);
    }
  }
  //smoothing - first big bin
  total = 0;
  for(int i=477; i<502 ; ++i) {
    total += bosonSystemPtFineBinning->GetBinContent(i);
  }
  for(int i=477; i<502 ; ++i) {
    bosonSystemPtFineBinning->SetBinContent(i,total / 26);
  }
  //smoothing - remaining big bins
  for (int i=10; i<80; ++i) {
    total = 0;
    for (int j=0; j<50;j++) {
      if (i*50 + 2 + j < 4001) {
        total += bosonSystemPtFineBinning->GetBinContent(i*50 + 2 + j);
      }
    }
    for (int j=0; j<50;j++) {
      if (i < 79) {        
        bosonSystemPtFineBinning->SetBinContent(i*50 + 2 + j, total / 50);
      } else {
        bosonSystemPtFineBinning->SetBinContent(i*50 + 2 + j, total / 49);
      }
    }
  }
  //normalize;
  norm = 0 ;
  for(int i=0; i<bosonSystemPtFineBinning->GetXaxis()->GetNbins()+2 ; ++i) {
    norm += bosonSystemPtFineBinning->GetBinContent(i);
  }
  for(int i=0; i<bosonSystemPtFineBinning->GetXaxis()->GetNbins()+2 ; ++i) {
    bosonSystemPtFineBinning->SetBinContent(i, bosonSystemPtFineBinning->GetBinContent(i) / norm);
  }

  TFile *file = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");
  file->WriteTObject(bosonSystemPt, bosonSystemPt->GetName(), "WriteDelete");
  file->WriteTObject(bosonSystemPtFineBinning, bosonSystemPtFineBinning->GetName(), "WriteDelete");
//   file->Close();

}
/*
 * this script takes 2 TStrings as root filenames as a parameters
 * basic functionality:
 * loop through all directories (the mass bins) in the root file
 * -> create difference plots
 * -> create global plots
 * -> create 2D diff vs mass plots
 * -> etc...
 */
void plotGlobalWeightedEvts_Kpipi(TString input_filename, TString output_filename) {
  setupBookies();

  gROOT->SetStyle("Plain");
  gStyle->SetTitleFont(10*13+2,"xyz");
  gStyle->SetTitleSize(0.06, "xyz");
  gStyle->SetTitleOffset(1.3,"y");
  gStyle->SetTitleOffset(1.3,"z");
  gStyle->SetLabelFont(10*13+2,"xyz");
  gStyle->SetLabelSize(0.06,"xyz");
  gStyle->SetLabelOffset(0.009,"xyz");
  gStyle->SetPadBottomMargin(0.16);
  gStyle->SetPadTopMargin(0.16);
  gStyle->SetPadLeftMargin(0.16);
  gStyle->SetPadRightMargin(0.16);
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();
  gStyle->SetFrameFillColor(0);
  gStyle->SetFrameFillStyle(0);
  TGaxis::SetMaxDigits(3);
  //IsPhDStyle = true;

  int massbins =0;
  double mass= 0.0, massstart =1000.0, massend=0.0;
  std::map<std::string, std::pair<double, std::pair<double, double> > > diffbounds;

  TFile* infile = TFile::Open(input_filename, "READ");
  TFile* outfile = new TFile(output_filename, "RECREATE");
  outfile->mkdir("global");

  TList *dirlist = infile->GetListOfKeys();
  massbins = dirlist->GetSize();
  infile->cd();
  TIter diriter(dirlist);
  TDirectory *dir;

  std::cout<< "scanning directories and creating overview canvases..." <<std::endl;
  while ((dir = (TDirectory *)diriter())) {
    std::string dirname = dir->GetName();
    // check if directory is mass bin dir
    unsigned int pointpos = dirname.find(".");
    if(pointpos == 0 || pointpos == dirname.size()) continue;
    std::string masslow = dirname.substr(0, pointpos+1);
    std::string masshigh = dirname.substr(pointpos+1);
    double massstarttemp = atof(masslow.c_str())/1000;
    double massendtemp = atof(masshigh.c_str())/1000;
    if((int)(massendtemp - massstarttemp) != massbinwidth)
      massbinwidth = (int)(massendtemp - massstarttemp);
    mass = (massstarttemp + massendtemp)/2;
    if(massstart > massstarttemp) massstart = massstarttemp;
    if(massend < massendtemp) massend = massendtemp;

    outfile->cd();
    outfile->mkdir(dir->GetName());
    infile->cd(dir->GetName());

    // make list of MC Histograms
    TList mclist;
    TList *histlist = gDirectory->GetListOfKeys();
    TIter histiter(histlist);
    TObject *obj;
    while ((obj = histiter())) {
      TString s(obj->GetName());
      if(s.EndsWith("MC"))
        mclist.Add(obj);
      else if(s.Contains("MC_"))
        mclist.Add(obj);
    }
    make1DOverviewCanvas(infile, outfile, &mclist, dirname);
    histiter = TIter(&mclist);
    TH1D *diffhist, *mchist;
    while ((mchist = (TH1D*)histiter())) {
      // generate difference histograms
      std::string hnamemc(mchist->GetName());
      // create new string with MC exchanged for Diff
      std::string hnamediff(hnamemc);
      int pos = hnamemc.find("MC");
      hnamediff.erase(pos, 2);
      hnamediff.insert(pos, "Diff");

      infile->GetObject((std::string(dir->GetName())+"/"+hnamediff).c_str(), diffhist);

      if (diffhist) {
        // get diff min max values
        std::pair<double, std::pair<double, double> > p;

        bool change =false;
        double maxdiff = diffhist->GetMaximum();
        double maxdifftemp = diffhist->GetMinimum();
        if(abs(maxdifftemp) > maxdiff) maxdiff = maxdifftemp;

        double diffmintemp = diffhist->GetXaxis()->GetXmin();
        double diffmaxtemp = diffhist->GetXaxis()->GetXmax();
        std::map<std::string, std::pair<double, std::pair<double, double> > >::iterator iter = diffbounds.find(
            diffhist->GetName());
        if (iter != diffbounds.end()) {
          p.first = iter->second.first;
          p.second.first = iter->second.second.first;
          p.second.second = iter->second.second.second;

          if (iter->second.first < maxdiff) {
            change = true;
            p.first = maxdiff;
          }
          if (iter->second.second.first > diffmintemp) {
            change = true;
            p.second.first = diffmintemp;
          }
          if (iter->second.second.second < diffmaxtemp) {
            change = true;
            p.second.second = diffmaxtemp;
          }

          if (change) {
            diffbounds[diffhist->GetName()] = p;
          }
        }
        else {
          p.first = maxdiff;
          p.second.first = diffmintemp;
          p.second.second = diffmaxtemp;
          diffbounds.insert(std::pair<std::string, std::pair<double, std::pair<double, double> > >(diffhist->GetName(),
              p));
        }
      }
    }
    histiter = TIter(&mclist);
    TH2D *reldiffhist2d, *diffhist2d, *mchist2d, *datahist2d;
    while ((mchist2d = (TH2D*) histiter())) {
      // generate difference histograms
      std::string hnamemc(mchist2d->GetName());
      // create new string with MC exchanged for Diff
      std::string hnamediff(hnamemc);
      int pos = hnamemc.find("MC");
      hnamediff.erase(pos, 2);
      hnamediff.insert(pos, "Diff");
      // create new string with MC exchanged for RelDiff
      std::string hnamereldiff(hnamemc);
      hnamereldiff.erase(pos, 2);
      hnamereldiff.insert(pos, "RelDiff");
      // create new string with MC exchanged for Data
      std::string hnamedata(hnamemc);
      hnamedata.erase(pos, 2);
      hnamedata.insert(pos, "Data");

      infile->GetObject((std::string(dir->GetName()) + "/" + hnamereldiff).c_str(), reldiffhist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamediff).c_str(), diffhist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata).c_str(), datahist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc).c_str(), mchist2d);

      outfile->cd(dir->GetName());
      make2DOverviewCanvas(mchist2d, datahist2d, diffhist2d, reldiffhist2d, mass);
    }
  }

  dirlist = infile->GetListOfKeys();
  infile->cd();
  diriter = TIter(dirlist);

  std::cout << "creating global histograms and 2D diff vs mass plots..." << std::endl;
  while ((dir = (TDirectory *) diriter())) {
    std::string dirname = dir->GetName();
    // check if directory is mass bin dir
    unsigned int pointpos = dirname.find(".");
    if (pointpos == 0 || pointpos == dirname.size())
      continue;

    infile->cd(dir->GetName());

    // make list of MC Histograms
    TList mclist;
    TList *histlist = gDirectory->GetListOfKeys();
    TIter histiter(histlist);
    TObject *obj;
    while ((obj = histiter())) {
      TString s(obj->GetName());
      if (s.EndsWith("MC"))
        mclist.Add(obj);
      else if (s.Contains("MC_"))
        mclist.Add(obj);
    }
    histiter = TIter(&mclist);
    TH1D *hist;
    TH1D *diffhist, *mchist, *datahist;
    while ((hist = (TH1D*) histiter())) {
      // generate difference histograms
      std::string hnamemc(hist->GetName());
      // create new string with MC exchanged for Diff
      std::string hname(hnamemc);
      int pos = hnamemc.find("MC");
      hname.erase(pos, 2);
      hname.insert(pos, "Diff");
      // create new string with MC exchanged for Data
      std::string hnamedata(hnamemc);
      hnamedata.erase(pos, 2);
      hnamedata.insert(pos, "Data");
      // create new string for MC Global Histogram
      std::string hnamemcglob(hnamemc);
      hnamemcglob.insert(pos + 2, "Global");
      // create new string for MC Global Histogram
      std::string hnamedataglob(hnamemc);
      hnamedataglob.erase(pos, 2);
      hnamedataglob.insert(pos, "DataGlobal");

      infile->GetObject((std::string(dir->GetName()) + "/" + hname + ";1").c_str(), diffhist);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata + ";1").c_str(), datahist);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc + ";1").c_str(), mchist);
      if (datahist) {
        // make global histograms in global folder
        outfile->cd("global");
        TH1D* hmcglob = (TH1D*) outfile->Get(std::string("global/"+hnamemcglob).c_str());
        if (hmcglob == NULL)
          hmcglob = new TH1D(hnamemcglob.c_str(), mchist->GetTitle(), mchist->GetNbinsX(),
              mchist->GetXaxis()->GetXmin(), mchist->GetXaxis()->GetXmax());
        hmcglob->Add(mchist);
        TH1D* hdataglob = (TH1D*) outfile->Get(std::string("global/"+hnamedataglob).c_str());
        if (hdataglob == NULL)
          hdataglob = new TH1D(hnamedataglob.c_str(), datahist->GetTitle(), datahist->GetNbinsX(),
              datahist->GetXaxis()->GetXmin(), datahist->GetXaxis()->GetXmax());
        hdataglob->Add(datahist);

        // make diff vs. mass plots
        fillDiffvsMassPlot(diffhist, dir->GetName(), massbins, massstart, massend, diffbounds, outfile);
      }
    }
    histiter = TIter(&mclist);
    TH2D *mchist2d, *datahist2d;
    while ((mchist2d = (TH2D*) histiter())) {
      // generate difference histograms
      std::string hnamemc(mchist2d->GetName());
      // create new string with MC exchanged for Diff
      std::string hnamediff(hnamemc);
      int pos = hnamemc.find("MC");
      hnamediff.erase(pos, 2);
      hnamediff.insert(pos, "Diff");
      // create new string with MC exchanged for Data
      std::string hnamedata(hnamemc);
      hnamedata.erase(pos, 2);
      hnamedata.insert(pos, "Data");
      // create new string for MC Global Histogram
      std::string hnamemcglob(hnamemc);
      hnamemcglob.insert(pos + 2, "Global");
      // create new string for MC Global Histogram
      std::string hnamedataglob(hnamemc);
      hnamedataglob.erase(pos, 2);
      hnamedataglob.insert(pos, "DataGlobal");

      infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata + ";1").c_str(), datahist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc + ";1").c_str(), mchist2d);
      if (datahist2d) {
        // make global histograms in global folder
        outfile->cd("global");
        TH2D* hmcglob = (TH2D*) outfile->Get(std::string("global/" + hnamemcglob).c_str());
        if (hmcglob == NULL) {
          hmcglob = new TH2D(hnamemcglob.c_str(), mchist2d->GetTitle(), mchist->GetNbinsX(),
              mchist2d->GetXaxis()->GetXmin(), mchist2d->GetXaxis()->GetXmax(), mchist2d->GetNbinsY(),
              mchist2d->GetYaxis()->GetXmin(), mchist2d->GetYaxis()->GetXmax());
          hmcglob->SetXTitle(mchist2d->GetXaxis()->GetTitle());
          hmcglob->SetYTitle(mchist2d->GetYaxis()->GetTitle());
        }
        hmcglob->Add(mchist2d);
        TH2D* hdataglob = (TH2D*) outfile->Get(std::string("global/" + hnamedataglob).c_str());
        if (hdataglob == NULL) {
          hdataglob = new TH2D(hnamedataglob.c_str(), datahist2d->GetTitle(), datahist2d->GetNbinsX(),
              datahist2d->GetXaxis()->GetXmin(), datahist2d->GetXaxis()->GetXmax(), datahist2d->GetNbinsY(),
              datahist2d->GetYaxis()->GetXmin(), datahist2d->GetYaxis()->GetXmax());
          hdataglob->SetXTitle(datahist2d->GetXaxis()->GetTitle());
          hdataglob->SetYTitle(datahist2d->GetYaxis()->GetTitle());
        }
        hdataglob->Add(datahist2d);
      }
    }
  }

  makeBookies();

  std::cout<< "saving to disk..." <<std::endl;
  outfile->Write();
  std::cout<< "done!" <<std::endl;

  /*// ok lets make a canvas and plug some plots into it -> add to booky
  TCanvas* c = new TCanvas("KineValidate" + massbin, "Weighted Events", 10, 10, 600, 800);
  c->Divide(4, 4);

  // first column contains neutral isobar histograms
  c->cd(1);

  double totMC = GJHB_neutral_isobar.isobar_mass[0]->Integral();
  double totDATA = GJHB_neutral_isobar.isobar_mass[1]->Integral();

  if (totMC != 0)
    GJHB_neutral_isobar.isobar_mass[0]->Scale(totDATA / totMC);
  GJHB_neutral_isobar.isobar_mass[0]->SetLineColor(kRed);
  GJHB_neutral_isobar.isobar_mass[0]->SetFillColor(kRed);
  GJHB_neutral_isobar.isobar_mass[0]->Draw("E4");

  TH1D* hDiffMIsobar = new TH1D(*GJHB_neutral_isobar.isobar_mass[0]);
  hDiffMIsobar->Add(GJHB_neutral_isobar.isobar_mass[1], -1.);
  GJHB_neutral_isobar.isobar_mass[1]->Draw("same");
  hDiffMIsobar->SetLineColor(kOrange - 3);
  hDiffMIsobar->Draw("same");

  GJHB_neutral_isobar.isobar_mass[0]->GetYaxis()->SetRangeUser(hDiffMIsobar->GetMinimum() * 1.5,
      GJHB_neutral_isobar.isobar_mass[0]->GetMaximum() * 1.2);
  gPad->Update();

  c->cd(5);
  totMC = GJHB_neutral_isobar.costheta_GJF[0]->Integral();
  totDATA = GJHB_neutral_isobar.costheta_GJF[1]->Integral();
  if (totMC != 0)
    GJHB_neutral_isobar.costheta_GJF[0]->Scale(totDATA / totMC);
  GJHB_neutral_isobar.costheta_GJF[0]->SetLineColor(kRed);
  GJHB_neutral_isobar.costheta_GJF[0]->SetFillColor(kRed);
  GJHB_neutral_isobar.costheta_GJF[0]->Draw("E4");

  GJHB_neutral_isobar.costheta_GJF[1]->Draw("same E");

  totMC = GJHB_neutral_isobar.costheta_GJF_MC_raw->Integral();
  GJHB_neutral_isobar.costheta_GJF_MC_raw->Scale(totDATA / totMC);
  GJHB_neutral_isobar.costheta_GJF_MC_raw->Draw("same");

  GJHB_neutral_isobar.costheta_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_neutral_isobar.costheta_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(9);
  totMC = GJHB_neutral_isobar.phi_GJF[0]->Integral();
  totDATA = GJHB_neutral_isobar.phi_GJF[1]->Integral();
  GJHB_neutral_isobar.phi_GJF[0]->Sumw2();
  if (totMC != 0)
    GJHB_neutral_isobar.phi_GJF[0]->Scale(totDATA / totMC);
  GJHB_neutral_isobar.phi_GJF[0]->SetLineColor(kRed);
  GJHB_neutral_isobar.phi_GJF[0]->SetFillColor(kRed);
  GJHB_neutral_isobar.phi_GJF[0]->Draw("E4");

  GJHB_neutral_isobar.phi_GJF[1]->Draw("same E");
  GJHB_neutral_isobar.phi_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_neutral_isobar.phi_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(13);
  totMC = HHB_neutral_isobar.costheta_HF[0]->Integral();
  totDATA = HHB_neutral_isobar.costheta_HF[1]->Integral();
  HHB_neutral_isobar.costheta_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_neutral_isobar.costheta_HF[0]->Scale(totDATA / totMC);
  HHB_neutral_isobar.costheta_HF[0]->SetLineColor(kRed);
  HHB_neutral_isobar.costheta_HF[0]->SetFillColor(kRed);
  HHB_neutral_isobar.costheta_HF[0]->Draw("E4");

  HHB_neutral_isobar.costheta_HF[1]->Draw("same E");
  HHB_neutral_isobar.costheta_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_neutral_isobar.costheta_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(15);
  totMC = HHB_neutral_isobar.phi_HF[0]->Integral();
  totDATA = HHB_neutral_isobar.phi_HF[1]->Integral();
  HHB_neutral_isobar.phi_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_neutral_isobar.phi_HF[0]->Scale(totDATA / totMC);
  HHB_neutral_isobar.phi_HF[0]->SetLineColor(kRed);
  HHB_neutral_isobar.phi_HF[0]->SetFillColor(kRed);
  HHB_neutral_isobar.phi_HF[0]->Draw("E4");

  HHB_neutral_isobar.phi_HF[1]->Draw("same E");
  HHB_neutral_isobar.phi_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_neutral_isobar.phi_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(2);

  totMC = GJHB_charged_isobar.isobar_mass[0]->Integral();
  totDATA = GJHB_charged_isobar.isobar_mass[1]->Integral();

  if (totMC != 0)
    GJHB_charged_isobar.isobar_mass[0]->Scale(totDATA / totMC);
  GJHB_charged_isobar.isobar_mass[0]->SetLineColor(kRed);
  GJHB_charged_isobar.isobar_mass[0]->SetFillColor(kRed);
  GJHB_charged_isobar.isobar_mass[0]->Draw("E4");

  TH1D* hDiffMIsobar2 = new TH1D(*GJHB_charged_isobar.isobar_mass[0]);
  hDiffMIsobar2->Add(GJHB_charged_isobar.isobar_mass[1], -1.);
  GJHB_charged_isobar.isobar_mass[1]->Draw("same");
  hDiffMIsobar2->SetLineColor(kOrange - 3);
  hDiffMIsobar2->Draw("same");

  GJHB_charged_isobar.isobar_mass[0]->GetYaxis()->SetRangeUser(hDiffMIsobar->GetMinimum() * 1.5,
      GJHB_charged_isobar.isobar_mass[0]->GetMaximum() * 1.2);
  gPad->Update();

  c->cd(6);
  totMC = GJHB_charged_isobar.costheta_GJF[0]->Integral();
  totDATA = GJHB_charged_isobar.costheta_GJF[1]->Integral();
  //hGJ[0]->Sumw2();
  if (totMC != 0)
    GJHB_charged_isobar.costheta_GJF[0]->Scale(totDATA / totMC);
  GJHB_charged_isobar.costheta_GJF[0]->SetLineColor(kRed);
  GJHB_charged_isobar.costheta_GJF[0]->SetFillColor(kRed);
  GJHB_charged_isobar.costheta_GJF[0]->Draw("E4");

  GJHB_charged_isobar.costheta_GJF[1]->Draw("same E");

  totMC = GJHB_charged_isobar.costheta_GJF_MC_raw->Integral();
  GJHB_charged_isobar.costheta_GJF_MC_raw->Scale(totDATA / totMC);
  GJHB_charged_isobar.costheta_GJF_MC_raw->Draw("same");

  GJHB_charged_isobar.costheta_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_charged_isobar.costheta_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(10);
  totMC = GJHB_charged_isobar.phi_GJF[0]->Integral();
  totDATA = GJHB_charged_isobar.phi_GJF[1]->Integral();
  GJHB_charged_isobar.phi_GJF[0]->Sumw2();
  if (totMC != 0)
    GJHB_charged_isobar.phi_GJF[0]->Scale(totDATA / totMC);
  GJHB_charged_isobar.phi_GJF[0]->SetLineColor(kRed);
  GJHB_charged_isobar.phi_GJF[0]->SetFillColor(kRed);
  GJHB_charged_isobar.phi_GJF[0]->Draw("E4");

  GJHB_charged_isobar.phi_GJF[1]->Draw("same E");
  GJHB_charged_isobar.phi_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_charged_isobar.phi_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(14);
  totMC = HHB_charged_isobar.costheta_HF[0]->Integral();
  totDATA = HHB_charged_isobar.costheta_HF[1]->Integral();
  HHB_charged_isobar.costheta_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_charged_isobar.costheta_HF[0]->Scale(totDATA / totMC);
  HHB_charged_isobar.costheta_HF[0]->SetLineColor(kRed);
  HHB_charged_isobar.costheta_HF[0]->SetFillColor(kRed);
  HHB_charged_isobar.costheta_HF[0]->Draw("E4");

  HHB_charged_isobar.costheta_HF[1]->Draw("same E");
  HHB_charged_isobar.costheta_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_charged_isobar.costheta_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(16);
  totMC = HHB_charged_isobar.phi_HF[0]->Integral();
  totDATA = HHB_charged_isobar.phi_HF[1]->Integral();
  HHB_charged_isobar.phi_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_charged_isobar.phi_HF[0]->Scale(totDATA / totMC);
  HHB_charged_isobar.phi_HF[0]->SetLineColor(kRed);
  HHB_charged_isobar.phi_HF[0]->SetFillColor(kRed);
  HHB_charged_isobar.phi_HF[0]->Draw("E4");

  HHB_charged_isobar.phi_HF[1]->Draw("same E");
  HHB_charged_isobar.phi_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_charged_isobar.phi_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  // add global diagrams

  c->cd(1);
  TLatex* Label = new TLatex();
  Label->PaintLatex(2, GJHB_neutral_isobar.isobar_mass[0]->GetMaximum() * 0.8, 0, 0.1, massbin.Data());

  c->Update();

  TList* Hlist = gDirectory->GetList();
  Hlist->Remove(mctr);
  Hlist->Remove(datatr);
  //Hlist->Remove("hWeights");

  TFile* outfile = TFile::Open(outfilename, "UPDATE");
  TString psFileName = outfilename;
  psFileName.ReplaceAll(".root", massbin);
  psFileName.Append(".ps");

  if (totMC != 0) {
    // get mass-integrated plots (or create them if not there)

    // neutral isobar
    TH1D* hMIsobarMCGlob = (TH1D*) outfile->Get("hMIsobarMCGlob");
    if (hMIsobarMCGlob == NULL)
      hMIsobarMCGlob = new TH1D("hMIsobarMCGlob", "2#pi neutral Isobar Mass (MC)", nbninsm, 0.2, 2.5);
    hMIsobarMCGlob->Add(GJHB_neutral_isobar.isobar_mass[0]);
    hMIsobarMCGlob->Write();
    TH1D* hMIsobarDataGlob = (TH1D*) outfile->Get("hMIsobarDataGlob");
    if (hMIsobarDataGlob == NULL)
      hMIsobarDataGlob = new TH1D("hMIsobarDataGlob", "2#pi neutral Isobar Mass (DATA)", nbninsm, 0.2, 2.5);
    hMIsobarDataGlob->Add(GJHB_neutral_isobar.isobar_mass[1]);
    hMIsobarDataGlob->Write();

    TH1D* hGJMCGlob = (TH1D*) outfile->Get("hGJMCGlob");
    if (hGJMCGlob == NULL)
      hGJMCGlob = new TH1D("hGJMCGlob", "Gottfried-Jackson Theta (MC)", nbinsang, -1, 1);
    hGJMCGlob->Add(GJHB_neutral_isobar.costheta_GJF[0]);
    hGJMCGlob->Write();
    TH1D* hGJDataGlob = (TH1D*) outfile->Get("hGJDataGlob");
    if (hGJDataGlob == NULL)
      hGJDataGlob = new TH1D("hGJDataGlob", "Gottfried-Jackson Theta (Data)", nbinsang, -1, 1);
    hGJDataGlob->Add(GJHB_neutral_isobar.costheta_GJF[1]);
    hGJDataGlob->Write();

    TH1D* hTYMCGlob = (TH1D*) outfile->Get("hTYMCGlob");
    if (hTYMCGlob == NULL)
      hTYMCGlob = new TH1D("hTYMCGlob", "Treiman-Yang Phi (MC)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYMCGlob->Add(GJHB_neutral_isobar.phi_GJF[0]);
    hTYMCGlob->Write();
    TH1D* hTYDataGlob = (TH1D*) outfile->Get("hTYDataGlob");
    if (hTYDataGlob == NULL)
      hTYDataGlob = new TH1D("hTYDataGlob", "Treiman-Yang Phi (Data)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYDataGlob->Add(GJHB_neutral_isobar.phi_GJF[1]);
    hTYDataGlob->Write();

    c->cd(3);
    hMIsobarMCGlob->SetLineColor(kRed);
    hMIsobarMCGlob->SetFillColor(kRed);
    hMIsobarMCGlob->Draw("E4");
    hMIsobarDataGlob->Draw("E SAME");

    c->cd(7);
    hGJMCGlob->SetLineColor(kRed);
    hGJMCGlob->SetFillColor(kRed);
    hGJMCGlob->Draw("E4");
    hGJDataGlob->Draw("E SAME");

    c->cd(11);
    hTYMCGlob->SetLineColor(kRed);
    hTYMCGlob->SetFillColor(kRed);
    hTYMCGlob->Draw("E4");
    hTYDataGlob->Draw("E SAME");


    // charged isobar
    TH1D* hMIsobarMCGlob2 = (TH1D*) outfile->Get("hMIsobarMCGlob2");
    if (hMIsobarMCGlob2 == NULL)
      hMIsobarMCGlob2 = new TH1D("hMIsobarMCGlob2", "2#pi charged Isobar Mass (MC)", nbninsm, 0.2,
          2.5);
    hMIsobarMCGlob2->Add(GJHB_charged_isobar.isobar_mass[0]);
    hMIsobarMCGlob2->Write();
    TH1D* hMIsobarDataGlob2 = (TH1D*) outfile->Get("hMIsobarDataGlob2");
    if (hMIsobarDataGlob2 == NULL)
      hMIsobarDataGlob2 = new TH1D("hMIsobarDataGlob2", "2#pi charged Isobar mass (DATA)", nbninsm,
          0.2, 2.5);
    hMIsobarDataGlob2->Add(GJHB_charged_isobar.isobar_mass[1]);
    hMIsobarDataGlob2->Write();

    TH1D* hGJMCGlob2 = (TH1D*) outfile->Get("hGJMCGlob2");
    if (hGJMCGlob2 == NULL)
      hGJMCGlob2 = new TH1D("hGJMCGlob2", "Gottfried-Jackson Theta (MC)", nbinsang, -1, 1);
    hGJMCGlob2->Add(GJHB_charged_isobar.costheta_GJF[0]);
    hGJMCGlob2->Write();
    TH1D* hGJDataGlob2 = (TH1D*) outfile->Get("hGJDataGlob2");
    if (hGJDataGlob2 == NULL)
      hGJDataGlob2 = new TH1D("hGJDataGlob2", "Gottfried-Jackson Theta (Data)", nbinsang, -1, 1);
    hGJDataGlob2->Add(GJHB_charged_isobar.costheta_GJF[1]);
    hGJDataGlob2->Write();

    TH1D* hTYMCGlob2 = (TH1D*) outfile->Get("hTYMCGlob2");
    if (hTYMCGlob2 == NULL)
      hTYMCGlob2 = new TH1D("hTYMCGlob2", "Treiman-Yang Phi (MC)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYMCGlob2->Add(GJHB_charged_isobar.phi_GJF[0]);
    hTYMCGlob2->Write();
    TH1D* hTYDataGlob2 = (TH1D*) outfile->Get("hTYDataGlob2");
    if (hTYDataGlob2 == NULL)
      hTYDataGlob2 = new TH1D("hTYDataGlob2", "Treiman-Yang Phi (Data)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYDataGlob2->Add(GJHB_charged_isobar.phi_GJF[1]);
    hTYDataGlob2->Write();

    c->cd(4);
    hMIsobarMCGlob2->SetLineColor(kRed);
    hMIsobarMCGlob2->SetFillColor(kRed);
    hMIsobarMCGlob2->Draw("E4");
    hMIsobarDataGlob2->Draw("E SAME");

    c->cd(8);
    hGJMCGlob2->SetLineColor(kRed);
    hGJMCGlob2->SetFillColor(kRed);
    hGJMCGlob2->Draw("E4");
    hGJDataGlob2->Draw("E SAME");

    c->cd(12);
    hTYMCGlob2->SetLineColor(kRed);
    hTYMCGlob2->SetFillColor(kRed);
    hTYMCGlob2->Draw("E4");
    hTYDataGlob2->Draw("E SAME");
  }

  c->Write();
  TCanvas dummyCanv("dummy", "dummy");
  c->Print((psFileName));*/
}