Example #1
0
void createNNLOplot(TString theory="ahrens")
{
  // theory="ahrens", "kidonakis"
  TString outputRootFile="test.root";
  // NB: add new datset name here
  if(theory.Contains("ahrens")   ){
    outputRootFile="AhrensNLONNLL";
    //if(theory.Contains("mtt")    ) outputRootFile+="mttbar" ;
    //else if(theory.Contains("pt")) outputRootFile+="pTttbar";
    outputRootFile+=".root";
  }
  else if(theory=="kidonakis") outputRootFile="KidonakisAproxNNLO.root";
  // general options
  gStyle->SetOptStat(0);
  bool usequad=true;
  bool divideByBinwidth=true;
  // list of variables
  std::vector<TString> xSecVariables_, xSecLabel_;
  // NB: add variables for new datset name here
  TString xSecVariablesUsedAhrens[]    ={"ttbarMass", "ttbarPt"};
  TString xSecVariablesUsedKidonakis[] ={"topPt"    , "topY"   };
  if(     theory.Contains("ahrens")   ) xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedAhrens   , xSecVariablesUsedAhrens    + sizeof(xSecVariablesUsedAhrens   )/sizeof(TString) );
  else if(theory=="kidonakis") xSecVariables_ .insert( xSecVariables_.begin(), xSecVariablesUsedKidonakis, xSecVariablesUsedKidonakis + sizeof(xSecVariablesUsedKidonakis)/sizeof(TString) );
  // get variable binning used for final cross sections 
  std::map<TString, std::vector<double> > bins_=makeVariableBinning();
  //std::vector<double> tempbins_;
  //double ttbarMassBins[]={345,445,545,745, 1045};
  //tempbins_.insert( tempbins_.begin(), ttbarMassBins, ttbarMassBins + sizeof(ttbarMassBins)/sizeof(double) );
  //bins_["ttbarMass"]=tempbins_;

  // loop all variables
  for(unsigned var=0; var<xSecVariables_.size(); ++var){
    TString variable=xSecVariables_[var];
    std::cout << "----------" << std::endl;
    std::cout << theory << ": " << variable << std::endl;
    // get bin boundaries
    double low =bins_[variable][0];
    double high=bins_[variable][bins_[variable].size()-1];
    // --------------------------
    // get raw nnlo theory points
    // --------------------------
    // NB: add new datset file names here
    TGraph * rawHist;
    TString predictionfolder="/afs/naf.desy.de/group/cms/scratch/tophh/CommonFiles/";
    if(theory=="ahrens"   ){
      if(variable.Contains("ttbarMass")) rawHist= new TGraph(predictionfolder+"AhrensTheory_Mttbar_8000_172.5_NLONNLL_norm.dat");//AhrensTheory_Mtt_7000_172.5_Mtt_fin.dat
      if(variable.Contains("ttbarPt"  )) rawHist= new TGraph(predictionfolder+"AhrensTheory_pTttbar_8000_172.5_NLONNLL_abs.dat");//AhrensTheory_pTttbar_7000_172.5_NLONNLL_abs.dat
    }
    else if(theory=="kidonakis"){
      if(variable.Contains("topPt")) rawHist= new TGraph(predictionfolder+"pttopnnloapprox8lhc173m.dat");//"ptnormalNNLO7lhc173m.dat" //"pttopnnloapprox8lhc173m.dat"
      if(variable.Contains("topY" )) rawHist= new TGraph(predictionfolder+"ytopnnloapprox8lhc173m.dat" );//"ynormalNNLO7lhc173m.dat"  //"ytopnnloapprox8lhc173m.dat"
    }
    // NB: say if points should be interpreted as single points with 
    //     nothing in between or as integrated value over the range
    bool points=true;
    if(theory.Contains("ahrens")) points=false;
    else if(theory=="kidonakis")  points=true;
    std::cout << "input: " << rawHist->GetTitle() << std::endl;
    std::cout << "interprete values as points?: " << points << std::endl;

    // --------------------
    // convertion to TH1F*
    // --------------------
    double *Xvalues = rawHist->GetX();
    int Nbins=rawHist->GetN();
    //double *Yvalues = rawHist->GetY(); // not working
    double xmax=-1;
    double xmin=-1;
    double binwidth=-1;
    //
    TH1F* hist;
    // NB: add additional binning for new theory here
    // NB: if loaded data should be interpreted as points with 
    //     nothing in between (like kidonakis), make suree you 
    //     choose a binning that is fine enough for the 
    //     data points loaded
    if(theory=="ahrens"){
      if(variable.Contains("ttbarMass")){
	xmin= 345.;
	xmax=2720.;
	binwidth=25.;// 5 for 8TeV, 25 for 7TeV
	if(TString(rawHist->GetTitle()).Contains("8000")) binwidth=5.;
      }
      else if(variable.Contains("ttbarPt")){
	xmin= 0.;
	xmax=1300.;
	binwidth=5.;
      }
    }
    else if(theory=="kidonakis"){ 
      if(variable.Contains("topPt")){
	xmin=   0.;
	xmax=1500.;
	binwidth=1.;
      }
      else if(variable.Contains("topY")){
	xmin=-3.8;
	xmax= 3.8;
	binwidth=0.01;
      }
    }
    // fill data in binned TH1F
    hist= new TH1F ( variable, variable, (int)((xmax-xmin)/binwidth), xmin, xmax);
    TH1F* ori=(TH1F*)hist->Clone("original points");
    std::cout << "fine binned theory prediction has " << hist->GetNbinsX() << " bins" << std::endl;
    std::cout << "loaded values from .dat file: " << std::endl;
    // list all data values loaded and the corresponding bin
    for(int bin=1; bin<=Nbins; ++bin){
      double x=-999;
      double y=-999;
      // NB: choose if loaded data is interpreted as points with nothing 
      //     between (like kidonakis) or as integrated over the bin range (like ahrens)
      if(points){
	// check if you are still inside the array
	//std::cout << "data point " << bin-1 << "/" << sizeof(Xvalues)/sizeof(double) << std::endl;
	if(rawHist->GetPoint(bin-1, x, y)!=-1){
	  //x=Xvalues[bin-1]; // get value from data points
	  x+=0.5*binwidth;  // add half the binwidth to get the center of the bin
	}
      }
      else{
	x=hist->GetBinCenter(bin);  // get bin center
	y=rawHist->GetY()[bin-1];
      }
      if(x!=-999){
	std::cout << "data point: " << bin;
	std::cout << "(<x>=" << x << ")-> bin";
	// get bin in target (fine binned) plot
	int bin2=bin;
	if(points) bin2=hist->FindBin(x);
	//double y=Yvalues[bin2-1];
	std::cout << bin2 << " (";
	std::cout << hist->GetBinLowEdge(bin2) << ".." << hist->GetBinLowEdge(bin2+1);
	std::cout << "): " << y << std::endl;
	// fill target (fine binned) plot
	if(!points) hist->SetBinContent(bin2, y);
	// mark bins coming from the original prediction
	ori->SetBinContent(bin2, 1.);
	// -------------------------------
	// fit range without data entries
	// -------------------------------
	// NB: needed if loaded data is interpreted as points with nothing 
	//     between (like kidonakis)
	if(points){
	  // perform a linear fit wrt previous point
	  // get the two points (this bin and the previous one)
	  int binPrev= (bin==1&&variable=="topPt") ? 0 : hist->FindBin(Xvalues[bin-2]+0.5*binwidth);
	  double x2=-1;
	  double x1= 0;
	  double y2=-1;
	  double y1= 0.;
	  rawHist->GetPoint(bin-1, x2, y2);
	  x2+=0.5*binwidth;
	  if(bin==1&&variable=="topPt"){
	    y1=0;
	    x1=0;
	  }
	  else{
	    rawHist->GetPoint(bin-2, x1, y1);
	    x1+=0.5*binwidth;
	  }
	  // calculate linear funtion
	  double a=(y2-y1)/(x2-x1);
	  double b=y1-a*x1;
	  TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2);
	  linInterpol->SetParameter(0,a);
	  linInterpol->SetParameter(1,b);
	  double xlow  = (bin==1&&variable=="topPt") ? 0. : hist->GetBinLowEdge(binPrev+1);
	  double xhigh = hist->GetBinLowEdge(bin2+1);
	  std::cout << " lin. interpolation [ (" << x1 << "," << y1 << ") .. (" << x2 << "," << y2 << ") ]: " << a << "*x+" << b << std::endl;
	  linInterpol->SetRange(xlow, xhigh);
	  hist->Add(linInterpol);
	}
      }
    }
    // check theory curve
    std::cout << std::endl << "analyze theory curve:" << std::endl;
    double integralRawTheory=hist->Integral(0.,hist->GetNbinsX()+1);
    std::cout << "Integral: " << integralRawTheory << std::endl;
    if(integralRawTheory==0.){
      std::cout << "ERROR: Integral can not be 0!" << std::endl;
      exit(0);
    }
    std::cout << "binwidth: " << binwidth << std::endl;
    std::cout << "Integral*binwidth: " << integralRawTheory*binwidth << std::endl;
    std::cout << "binRange: " << xmin << ".." << xmax << std::endl;
    std::cout << "   -> reco range: " << low << ".." << high << std::endl;
    std::vector<double> recoBins_=bins_[variable];
    for(unsigned int i=0; i<recoBins_.size(); ++i){
      i==0 ? std::cout << "(" : std::cout << ", ";
      std::cout << recoBins_[i];
      if(i==recoBins_.size()-1) std::cout << ")" << std::endl;
    }
    // check if you need to divide by binwidth
    if(std::abs(1.-integralRawTheory)<0.03){
      std::cout << "Integral is approx. 1 -> need to divide by binwidth!" << std::endl;
      hist->Scale(1./binwidth);
    }
    else if(std::abs(1-integralRawTheory*binwidth)<0.03){
      std::cout << "Integral*binwidth is approx. 1 -> no scaling needed!" << std::endl;
    }
    else{
      std::cout << "need to normalize and divide by binwidth";
      hist->Scale(1./(binwidth*integralRawTheory));
    }
    // styling
    hist->GetXaxis()->SetRangeUser(low,high);
    hist->SetMarkerColor(kMagenta);
    hist->SetLineColor(  kMagenta);
    hist->SetMarkerStyle(24);
    // create canvas
    std::cout << std::endl << "create canvas " << std::endl;
    TCanvas *canv = new TCanvas(variable,variable,800,600);
    canv->cd();
    std::cout << "draw original theory curve " << std::endl;
    //temp->Draw("axis");
    hist->Draw("p");
    //hist->Draw("hist same");
    // draw original points
    if(points){
      for(int bin=1; bin<ori->GetNbinsX(); ++bin){
	// create copy of original data points with the normalized values
	if(ori->GetBinContent(bin)!=0) ori->SetBinContent(bin, hist->GetBinContent(bin));
	ori->SetMarkerColor(kBlack);
	ori->SetMarkerStyle(29);
	ori->SetMarkerSize(1);
	ori->Draw("p same");
      }
    }
    // --------------------
    // create rebinned plot
    // --------------------
    std::cout << std::endl << "create rebinned curve:" << std::endl;
    TString name="";
    // NB: add name for dataset here
    name=variable;
    if(    theory=="kidonakis") name+="approxnnlo";
    else if(theory=="ahrens"  ) name+="nlonnll"   ;
    TH1F* binnedPlot=new TH1F(name, name, bins_[variable].size()-1, &bins_[variable][0]);
    for(int bin=1; bin<=hist->GetNbinsX(); ++bin){
      double y=hist->GetBinContent(bin)*hist->GetBinWidth(bin);
      double xlow =hist->GetBinLowEdge(bin);
      double xhigh=hist->GetBinLowEdge(bin+1);
      // search corresponding bin in rebinned curve
      bool found=false;
      //std::cout << "xlow: " << xlow << ", xhigh: " << xhigh << std::endl; // FIXME
      for(int binRebinned=0; binRebinned<=binnedPlot->GetNbinsX()+1; ++binRebinned){
	if(binnedPlot->GetBinLowEdge(binRebinned)<=xlow&&binnedPlot->GetBinLowEdge(binRebinned+1)>=xhigh){
	  found=true;
	  binnedPlot->SetBinContent(binRebinned, binnedPlot->GetBinContent(binRebinned)+y);
	  break;
	}
	//else{
	//  std::cout << "not in: " << binnedPlot->GetBinLowEdge(binRebinned) << ".." << binnedPlot->GetBinLowEdge(binRebinned+1)<< std::endl;
	//}
      }
      // --------------------
      // use linear interpolation for edge bins
      // --------------------
      if(hist->GetBinCenter(bin)<high&&!found){
	std::cout << "need interpolation for bin" << bin << "(<x>=" << hist->GetBinCenter(bin) << ")!"<< std::endl;
	// search for the two bins involved
	double binLow=0;
	double binHigh=0;
	for(int binRebinned=1; binRebinned<=binnedPlot->GetNbinsX(); ++binRebinned){
	  // search for bin in binned histo where upper border of is close to lower border of unbinned histo
	  if(std::abs(binnedPlot->GetBinLowEdge(binRebinned+1)-xlow)<binwidth){
	    binLow =binRebinned; 
	    binHigh=binRebinned+1;
	    break;
	  }
	}
	std::cout << "theory bin " << xlow << ".." << xhigh << "-> reco bins ";
	std::cout << binnedPlot->GetBinLowEdge(binLow) << ".." << binnedPlot->GetBinLowEdge(binLow+1) << " & ";
	std::cout << binnedPlot->GetBinLowEdge(binHigh) << ".." << binnedPlot->GetBinLowEdge(binHigh+1) << std::endl;
	// get the two points (this bin and the previous one)
	double x2=hist->GetBinCenter (bin  );
	double x1=hist->GetBinCenter (bin-1);
	double x3=hist->GetBinCenter (bin+1);
	double y2=hist->GetBinContent(bin  );
	double y1=hist->GetBinContent(bin-1);
	double y3=hist->GetBinContent(bin+1);	
	// calculate linear funtion
	double a=(y2-y1)/(x2-x1);
	double b=y1-a*x1;
	TF1* linInterpol=new TF1("linInterpol"+getTStringFromInt(bin), "[0]*x+[1]", x1, x2);
	linInterpol->SetParameter(0,a);
	linInterpol->SetParameter(1,b);
	// calculate the corresponding area of linear function to binned curve
	double contributionLowerBin=linInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh));
	double contributionUpperBin=linInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh);
	// draw interpolation function for checking
	linInterpol->SetRange(xlow,xhigh);
	linInterpol->SetLineColor(kMagenta);
	linInterpol->DrawClone("same");
	// eventually use quadratic interpolation for the first harens m(ttbar) bin
	if(theory=="ahrens"&&variable.Contains("ttbarMass")&&usequad&&x2<450){
	  // calculate quadratic funtion
	  double a2=(y2-((y3-y1))*(x2-x1)/(x3-x1))/(x2*x2-x1*x1-(x2-x1)*(x3*x3+x1*x1)/(x3-x1));
	  double b2=((y3-y1)-a2*(x3*x3-x1*x1))/(x3-x1);
	  double c2=y1-a2*x1*x1-b*x1;
	  TF1* quadInterpol=new TF1("quadInterpol"+getTStringFromInt(bin), "[0]*x*x+[1]*x+[2]", x1, x2);
	  quadInterpol->SetParameter(0,a2);
	  quadInterpol->SetParameter(1,b2);
	  quadInterpol->SetParameter(2,c2);
	  // draw quad interpolation function for checking
	  quadInterpol->SetRange(xlow,xhigh);
	  quadInterpol->SetLineColor(kGreen);
	  quadInterpol->SetLineStyle(2);
	  hist->Fit(quadInterpol, "", "same", x1, x3);
	  // calculate the corresponding area of linear function to binned curve
	  quadInterpol->DrawClone("same");
	  double areaLow =quadInterpol->Integral(xlow,binnedPlot->GetBinLowEdge(binHigh) );
	  double areaHigh=quadInterpol->Integral(binnedPlot->GetBinLowEdge(binHigh),xhigh);
	  std::cout << "ratio(high/low) linear/quadratic: " << contributionUpperBin/contributionLowerBin << "/"<< areaHigh/areaLow << std::endl;
	  contributionLowerBin=y2*binwidth*areaLow /(areaLow+areaHigh);
	  contributionUpperBin=y2*binwidth*areaHigh/(areaLow+areaHigh);
	}
	// add fitted result
	binnedPlot->SetBinContent(binLow , binnedPlot->GetBinContent(binLow )+contributionLowerBin);
	binnedPlot->SetBinContent(binHigh, binnedPlot->GetBinContent(binHigh)+contributionUpperBin);
      }
    }
    // ensure over/underflow is 0
    binnedPlot->SetBinContent(0, 0.);
    binnedPlot->SetBinContent(binnedPlot->GetNbinsX()+1, 0.);
    // ensure normalization
    binnedPlot->Scale(1./(binnedPlot->Integral(0.,binnedPlot->GetNbinsX()+1)));
    // divide by binwidth
    if(divideByBinwidth){
      for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){
	binnedPlot->SetBinContent(bin, binnedPlot->GetBinContent(bin)/binnedPlot->GetBinWidth(bin));
      }
    }
    std::cout << "-------------------------------------------" << std::endl;
    std::cout << "result: binned output histo" << std::endl;
    for(int bin=1; bin<=binnedPlot->GetNbinsX(); ++bin){
      std::cout << "content bin " << bin << " (" << binnedPlot->GetBinLowEdge(bin) << ".." << binnedPlot->GetBinLowEdge(bin+1) << ")= " << binnedPlot->GetBinContent(bin) << std::endl;
    }

    // styling
    binnedPlot->SetLineColor(kBlue);
    binnedPlot->SetLineWidth(2);
    std::cout << "draw rebinned theory curve " << std::endl;
    binnedPlot->Draw("hist same");
    // draw bin boundaries
    std::cout << "draw bin boundaries " << std::endl;
    int binColor=kRed;
    int binWidth=2;
    int binStyle=6;
    for(int bin=0; bin<(int)bins_.size(); ++bin){
      if(!variable.Contains("ttbarMass")||bins_[variable][bin]>=345.) drawLine(bins_[variable][bin], 0, bins_[variable][bin], hist->GetMaximum(), binColor, binWidth, binStyle);
    }
    TH1F* line=(TH1F*)hist->Clone("line");
    line->SetLineColor(binColor);
    line->SetLineWidth(binWidth);
    line->SetLineStyle(binStyle);
    // legend
    TLegend *leg = new TLegend(0.7, 0.6, 0.95, 0.9);
    legendStyle(*leg,theory);
    if(points) leg ->AddEntry(ori, "original data points","P");
    leg ->AddEntry(hist      , "theory prediction" ,"P");
    leg ->AddEntry(line      , "reco binning"      ,"L");
    leg ->AddEntry(hist      , "linear interpolation" ,"L");
    leg ->AddEntry(binnedPlot, "rebinned curve"    ,"L");
    leg->Draw("same");
    std::cout << "done" << std::endl;
    // save in png and rootfile
    std::cout << std::endl << "do saving..." << std::endl;
    canv->SaveAs(variable+"Norm_Theory.png");
    TH1F* out=(TH1F*)binnedPlot->Clone();
    out->SetTitle(variable);
    out->SetName (variable);
    out->GetXaxis()->SetTitle(xSecLabelName(variable));
    TString yTile="#frac{1}{#sigma} #frac{d#sigma}{d";
    if(variable=="ttbarMass") yTile+="m^{t#bar{t}}} [GeV^{-1}]";
    if(variable=="ttbarPt") yTile+="p_{T}^{t#bar{t}}} [GeV^{-1}]";
    if(variable=="topPt") yTile+="p_{T}^{t}} [GeV^{-1}]";
    if(variable=="topY" ) yTile+="y^{t}}";
    out->GetYaxis()->SetTitle(yTile);
    out->SetLineColor(kOrange+2);
    out->SetLineStyle(2);
    std::cout << std::endl << "draw final result " << std::endl;
    TCanvas *canv2 = new TCanvas(variable+"Rebinned",variable+"Rebinned",800,600);
    canv2->cd();
    out->Draw();
    saveToRootFile(outputRootFile, out    , true, 0,""      );
    saveToRootFile(outputRootFile, rawHist, true, 0,"graph" );
    saveToRootFile(outputRootFile, canv   , true, 0,"detail");
    std::cout << "done!" << std::endl;
  }
}
Example #2
0
void fit_h_Xm_extended() {
    TCanvas* c1;
	c1 = new TCanvas("c1","",1440,900);
	
    
	
    TFile *f;
	int mass[13]={600,800,1000,1200,1400,1600,1800,2000,2500,3000,3500,4000,4500};
	float width [4]={0.05,0.1,0.2,0.3};
	string widthdata[4]={"0.05","0.1","0.2","0.3"};
	
	//for(int i=0 ;i<4;i++){
		//for(int j=0)
	//}
for(int i=0;i<4;i++){
	for(int j=0;j<13;j++){

    


    f = TFile::Open(Form("offshell_root_files/Zprime_Zh_Zlephbb_w%s_M%d.root",widthdata[i].data(),mass[j]));
    TH1F* h =(TH1F*) f->FindObjectAny("h_Xm_extended");
	

    
    
	
	int bmin=0,bmax=0;

    for (int k=1;k<25001;k++){
		bmin=k;
		if (h->GetBinContent(k)!=0) break;
	}

	for (int k=25000;k>0;k--){
		bmax=k;
		if (h->GetBinContent(k)!=0) break;
	}
	if((bmin-300)<0)bmin=0;
	else bmin=bmin-300;
	bmax=bmax+bmax/10;
	
	
	cout <<bmin<<","<<bmax<<endl;
    //gStyle->SetOptFit(111111);
	//gStyle->SetStatW       (0.1);
    //gStyle->SetStatH       (0.1);
    //gStyle->SetStatX          (0.941349);
    //gStyle->SetStatY          (0.912491);
	
	fiveWidthLow= mass[j] -5* (width [i])*mass[j];
	fiveWidthUp= mass[j] +5* (width [i])*mass[j];
	
	float inte=h->Integral(fiveWidthLow,fiveWidthUp);
	inte=inte*100/(bmax-bmin);

	//h->Rebin((bmax-bmin)/100);
	int massfix=200;
	if(i>1&&j>8)massfix=400;
	if(i>2&&j>9)massfix=500;
	float widthfix=0;
	if(i>2&&j>9)widthfix=0.1;
	
	
	
	TF1* f1 = new TF1("f1","[2]*TMath::BreitWigner(x,[0],[1])");
	f1->SetNpx(2500);
	f1->SetParameters(mass[j],width [i]*mass[j],h->Integral());  
	//f1->SetLineColor(3);
	
	
	h->GetXaxis()->SetRangeUser(bmin,bmax);
    h->SetTitle(Form("offshell_root_files/Zprime_Zh_Zlephbb_w%s_M%d.root",widthdata[i].data(),mass[j]));
	TH1F*  h2=(TH1F*)  h->Clone("h2");
    //h->Fit(f1,"","",fiveWidthLow,fiveWidthUp);
	//h->Fit(f1,"L");
	TF1* f2 = new TF1("f2",fline,bmin,bmax,3);
	
	if(j>2)inte=h->Integral();
	f2->SetParameters(mass[j],width [i]*mass[j],h->Integral());  
	f2->SetNpx(2500);
	//f2->SetLineColor(3);
    //h2->Fit(f2);
	//TF1* fleft = new TF1("fleft","[2]*TMath::BreitWigner(x,[0],[1])");
    //TF1 *fleft = new TF1("fleft","[2]*TMath::BreitWigner(x,[0],[1])",bmin,bmax,3);
    //fleft->SetParameters(f2->GetParameters());
    //fleft->SetLineColor(3);
    h->SetMinimum(0);
    h->Draw();
	//fleft->Draw();
	//h2->Draw("same");
    //f1->Draw();
	if (i==0 && j==0)c1->Print("fit_h_Xm_extended.pdf(");
	else if (i==3 && j==12)c1->Print("fit_h_Xm_extended.pdf)");
    else c1->Print("fit_h_Xm_extended.pdf");
   
    
    c1->SaveAs(Form("png/Zprime_Zh_Zlephbb_w%s_M%d.png",widthdata[i].data(),mass[j]));
  

    //c1->Print("fit_h_Xm_extended.pdf)");
	
}
}

}
//------------------------------------------------------------------------------
// PlotHiggsRes_LP
//------------------------------------------------------------------------------
void RunMakeRazorPlots ( string signalfile, string signalLabel,  vector<string> bkgfiles,vector<string> bkgLabels, int boxOption = 0, int option = -1, string label = "", string latexlabel = "") {

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  double intLumi = 2100; //in units of pb^-1
  string Label = "";
  if (label != "") Label = "_" + label;

  vector<string> inputfiles;
  vector<string> processLabels;

  bool hasSignal = false;
  if (signalfile != "") {
    hasSignal = true;
    inputfiles.push_back(signalfile);
    processLabels.push_back(signalLabel);
  }
  assert(bkgfiles.size() == bkgLabels.size());
  for (int i=0; i < bkgfiles.size(); ++i) {
     inputfiles.push_back(bkgfiles[i]);
     processLabels.push_back(bkgLabels[i]);
  }

  //*******************************************************************************************
  //Define Histograms
  //*******************************************************************************************
  vector<TH1F*> histUnrolled; 
  float MRBinLowEdges[] = {500, 600, 700, 900, 1200, 1600, 2500, 4000}; // Multijet Bins
  float RsqBinLowEdges[] = {0.25, 0.30, 0.41, 0.52, 0.64, 1.5}; // Multijet Bins

  const int nMRBins = 7;
  const int nRsqBins = 5;

  TH1F* histMRAllBkg =  new TH1F( "MRAllBkg",";M_{R} [GeV/c^{2}];Number of Events", nMRBins, MRBinLowEdges);
  TH1F* histRsqAllBkg =  new TH1F( "RsqAllBkg", ";R^{2};Number of Events", nRsqBins, RsqBinLowEdges);
  histMRAllBkg->SetStats(false);
  histRsqAllBkg->SetStats(false);  
  histRsqAllBkg->Sumw2();
  histMRAllBkg->Sumw2();

  TH1F* histMRQCD =  new TH1F( "MRQCD",";M_{R} [GeV/c^{2}];Number of Events", nMRBins, MRBinLowEdges);
  TH1F* histRsqQCD =  new TH1F( "RsqQCD", ";R^{2};Number of Events", nRsqBins, RsqBinLowEdges);
  histMRQCD->SetStats(false);
  histRsqQCD->SetStats(false);  
  histRsqQCD->Sumw2();
  histMRQCD->Sumw2();

  TH1F* histMRData =  new TH1F( "MRData",";M_{R} [GeV/c^{2}];Number of Events", nMRBins, MRBinLowEdges);
  TH1F* histRsqData =  new TH1F( "RsqData", ";R^{2};Number of Events", nRsqBins, RsqBinLowEdges);

  vector<TH1F*> histMR;
  vector<TH1F*> histRsq; 
  vector<TH2F*> histMRRsq;

  histMRQCD->SetFillColor(kAzure+4);
  histMRAllBkg->SetFillColor(kMagenta);
  histMRQCD->SetFillStyle(1001);
  histMRAllBkg->SetFillStyle(1001);

  histMRQCD->SetLineColor(kAzure+4);
  histMRAllBkg->SetLineColor(kMagenta);

  assert (inputfiles.size() == processLabels.size());
  for (int i=0; i < inputfiles.size(); ++i) {    
    histMRRsq.push_back( new TH2F( Form("MRRsq_%s",processLabels[i].c_str()), ";M_{R} [GeV/c^{2}]; R^{2}", nMRBins, MRBinLowEdges, nRsqBins, RsqBinLowEdges));
    if (!hasSignal || i != 0) histMRRsq[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histMRRsq[i]->SetLineWidth(3);
    histMRRsq[i]->SetLineColor(color[i]);
    histMRRsq[i]->SetStats(false);
    histMRRsq[i]->Sumw2();

    histUnrolled.push_back( new TH1F( Form("Unrolled_%s",processLabels[i].c_str()), ";Bin Number ;Number of Events", nMRBins*nRsqBins, 0, nMRBins*nRsqBins));
    if (!hasSignal || i != 0) histUnrolled[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histUnrolled[i]->SetLineWidth(3);
    histUnrolled[i]->SetLineColor(color[i]);
    histUnrolled[i]->SetStats(false);     
  }
  THStack *stackUnrolled = new THStack();

  //*******************************************************************************************
  //Define Counts
  //*******************************************************************************************


  //*******************************************************************************************
  //Read files
  //*******************************************************************************************
  for (uint i=0; i < inputfiles.size(); ++i) {

    TFile* inputFile = new TFile(inputfiles[i].c_str(),"READ");
    assert(inputFile);
    TTree* tree = 0;
    tree = (TTree*)inputFile->Get("RazorInclusive");
  // if (box == 0) {
    //   tree = (TTree*)inputFile->Get("MultiJet");
    // } else if (box == 1) {
    //   tree = (TTree*)inputFile->Get("LooseLeptonMultiJet");
    // } else if (box == 2) {
    //   tree = (TTree*)inputFile->Get("MuMultiJet");
    // } else if (box == 3) {
    //   tree = (TTree*)inputFile->Get("EleMultiJet");
    // }
 
    float weight = 0;
    int box = -1;
    int nBTaggedJets = 0;
    float dPhiRazor = 0;
    float MR = 0;
    float Rsq = 0;
    float mT = 0;

    tree->SetBranchAddress("weight",&weight);
    tree->SetBranchAddress("box",&box);
    tree->SetBranchAddress("nBTaggedJets",&nBTaggedJets);
    tree->SetBranchAddress("dPhiRazor",&dPhiRazor);
    tree->SetBranchAddress("MR",&MR);
    tree->SetBranchAddress("Rsq",&Rsq);
    tree->SetBranchAddress("mT",&mT);

    cout << "Process : " << processLabels[i] << " : Total Events: " << tree->GetEntries() << "\n";
    for (int n=0;n<tree->GetEntries();n++) { 
     // for (int n=0;n<1000;n++) { 
   
      tree->GetEntry(n);
      if (n % 1000000 == 0) cout << "Processing Event " << n << "\n";       


      // if (intLumi*weight > 100) continue;

      //Box Options
      if (option == 0 ) {
	if (nBTaggedJets != 0) continue;
      }
      if (option == 1 ) {
	if (nBTaggedJets != 1) continue;
      }
      if (option == 2 ) {
	if (nBTaggedJets != 2) continue;
      }
      if (option == 3 ) {
	if (nBTaggedJets < 3) continue;
      }
      if (option == 4 ) {
	if (nBTaggedJets < 0) continue; // all b-tag categories combined
      }

      if (boxOption == 0) { // Multijet Box for Jamboree
	if( !(box == 11 || box == 12) ) continue;
      } 
      if (boxOption == 1) { // LeptonJet Box for Jamboree
	if( !(box == 3 || box == 4 || box == 6 || box == 7) ) continue;
      } 
      if (boxOption == 2) { // Multijet Box for Jamboree
	if( !(box == 14) ) continue;
      } 

      //apply baseline cuts
      if (!(MR > 400 && Rsq > 0.25)) continue;

      // if (!(MR < 500 )) continue;
      // if (!(Rsq < 0.3)) continue;

      if (!(fabs(dPhiRazor) > 2.8)) continue;

      if (!hasSignal || i>1) {
	histMRAllBkg->Fill(MR, intLumi*weight);
	histRsqAllBkg->Fill(Rsq, intLumi*weight);
	histMRRsq[i]->Fill(MR, Rsq, intLumi*weight);
      }

      if(i==1){
	if (intLumi*weight > 30) continue;
	float qcdweight = 1.56841;
	histMRQCD->Fill(MR, intLumi*weight*qcdweight);
	histRsqQCD->Fill(Rsq, intLumi*weight*qcdweight);	
  	histMRRsq[i]->Fill(MR, Rsq, intLumi*weight*qcdweight);
    }

      if (hasSignal && i==0) {
	histMRData->Fill(MR);
	histRsqData->Fill(Rsq);	
	histMRRsq[i]->Fill(MR, Rsq);
      }
    }

    inputFile->Close();
    delete inputFile;
  
  }
  
  std::cout<<"Data: "<<histMRData->Integral()<<", All Backgrounds: "<<histMRAllBkg->Integral()<<" , QCD: "<<histMRQCD->Integral()<<", Data2 "<< histMRRsq[0]->Integral() <<" QCD2 "<<histMRRsq[1]->Integral() <<std::endl;


  //*******************************************************************************************
  //Draw Plots
  //*******************************************************************************************
 // fill out the unrolled histograms 
  std::cout<<"Rsq bins: "<<nRsqBins<<" "<<nMRBins<<std::endl;
  for (uint i=0; i < histMRRsq.size(); ++i) {
    
    int binN = 0;

    for(int ii = 0; ii<nMRBins; ii++)
      for (int jj = 0; jj<nRsqBins; jj++)      
  	{      
  	  float value = (histMRRsq[i]->GetBinContent(ii+1, jj+1) > 0) ? histMRRsq[i]->GetBinContent(ii+1, jj+1) : 0. ;
	  
	  float Xrange = histMRRsq[i]->GetXaxis()->GetBinLowEdge(jj+2) - histMRRsq[i]->GetXaxis()->GetBinLowEdge(jj+1);
	  float Yrange = histMRRsq[i]->GetYaxis()->GetBinLowEdge(ii+2) - histMRRsq[i]->GetYaxis()->GetBinLowEdge(ii+1);

	  float area =1.;
	  
	  if(density) area = Xrange*Yrange; //normalize each bin by its area

	  histUnrolled[i]->SetBinContent(binN+1, value/area);
  	  binN++;
  	}

    histUnrolled[i]->SetMinimum(0.00001);

    if ( histUnrolled[i]->Integral() > 0) {
      if( !hasSignal || i > 0 )
	stackUnrolled->Add(histUnrolled[i]);
    }

    cout << "Process : " << processLabels[i] << "\n";	  
  }

  TCanvas *cv = 0;
  TLegend *legend = 0;
  TLatex *tex = 0;
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.7,0.53,0.90,0.88);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);

  for (Int_t i = histMRRsq.size()-1 ; i >= 0; --i) {
    if (hasSignal && i==0) {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "L");
    } else {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "F");
    }
  }

  /// Unrolled plots in bins of R&MR
  TLatex t1(0.1,0.92, "CMS Preliminary");
  TLatex t2(0.6,0.92, "#sqrt{s}=13 TeV, L = 2.1 fb^{-1}");
  TLatex t3(0.4,0.92, Form("%s",latexlabel.c_str()) );
  t1.SetNDC();
  t2.SetNDC();
  t3.SetNDC();
  t1.SetTextSize(0.05);
  t2.SetTextSize(0.05);
  t3.SetTextSize(0.02);
  t1.SetTextFont(42);
  t2.SetTextFont(42);
  t3.SetTextFont(42);
  stackUnrolled->Draw();
  stackUnrolled->SetMinimum(0.01);
  stackUnrolled->SetMaximum(1000);
  cv->SetLogy();
  stackUnrolled->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackUnrolled->GetHists()->At(0)))->GetXaxis()->GetTitle());
  stackUnrolled->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackUnrolled->GetHists()->At(0)))->GetYaxis()->GetTitle());
  stackUnrolled->Draw();
  if(hasSignal) histUnrolled[0]->Draw("same PE");
  legend->Draw();
  t1.Draw();
  t2.Draw();
  t3.Draw();
  cv->SaveAs(Form("Unrolled_QCD%s.root",Label.c_str()));
  ////

  //*******************************************************************************************
  //MR
  //*******************************************************************************************
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.50,0.54,0.90,0.84);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.030);
  tex->SetTextFont(42);
  tex->SetTextColor(kBlack);
  tex->DrawLatex(0.2, 0.92, Form("CMS Simulation #sqrt{s} = 13 TeV, #int L = %d fb^{-1}, %s",int(intLumi/1000), latexlabel.c_str()));

  THStack *stackMR = new THStack("stackMR", "");
  THStack *stackRsq = new THStack();

  //*******************************************************************************************
  //MR Before and After DPhi Cut
  //*******************************************************************************************
  //////////////////
  stackMR->Add(histMRAllBkg);
  stackMR->Add(histMRQCD);
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.50,0.54,0.90,0.84);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);
  stackMR->Draw();
  stackMR->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackMR->GetHists()->At(0)))->GetXaxis()->GetTitle());
  stackMR->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackMR->GetHists()->At(0)))->GetYaxis()->GetTitle());
  stackMR->Draw("");
  histMRData->Draw("same PE");
  legend->Draw();
  cv->SetLogy();
  cv->SaveAs(Form("MRStack_QCD_%s.pdf",Label.c_str()));

  ///////////////////////
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.50,0.54,0.90,0.84);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);

  histMRAllBkg->SetLineColor(kRed);
  histMRAllBkg->GetYaxis()->SetTitle("Number of Events");
  histMRAllBkg->GetYaxis()->SetTitleOffset(1.2);
  histMRData->SetMarkerStyle(8);

  legend->AddEntry(histMRAllBkg, "All Backgrounds", "L");
  legend->AddEntry(histMRData, "Data", "L");

  histMRAllBkg->Add(histMRQCD, 1.0);

  histMRAllBkg->Draw("hist");
  histMRData->Draw("PE same");

  legend->Draw();
  cv->SetLogy();
  cv->SaveAs(Form("MR_QCD_%s.pdf",Label.c_str()));


  //////

  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.50,0.54,0.90,0.84);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);

  histRsqAllBkg->SetLineColor(kRed);
  histRsqAllBkg->GetYaxis()->SetTitle("Number of Events");
  histRsqAllBkg->GetYaxis()->SetTitleOffset(1.2);
  histRsqData->SetMarkerStyle(8);

  legend->AddEntry(histRsqAllBkg, "All Backgrounds", "L");
  legend->AddEntry(histRsqData, "Data", "L");

  histRsqAllBkg->Add(histRsqQCD, 1.0);

  histRsqAllBkg->Draw("hist");
  histRsqData->Draw("PE same");

  legend->Draw();
  cv->SetLogy();
  cv->SaveAs(Form("Rsq_QCD_%s.pdf",Label.c_str()));

  //////////////////
  histRsqQCD->SetFillColor(kAzure+4);
  histRsqAllBkg->SetFillColor(kMagenta);

  stackRsq->Add(histRsqAllBkg);
  stackRsq->Add(histRsqQCD);
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.50,0.54,0.90,0.84);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);
  stackRsq->Draw();
  stackRsq->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackRsq->GetHists()->At(0)))->GetXaxis()->GetTitle());
  stackRsq->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackRsq->GetHists()->At(0)))->GetYaxis()->GetTitle());
  stackRsq->Draw();
  histRsqData->Draw("same PE");
  legend->Draw();
  cv->SetLogy();
  cv->SaveAs(Form("RsqStack_QCD_%s.pdf",Label.c_str()));
 
   //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  TFile *file = TFile::Open(("RazorPlots"+Label+".root").c_str(), "RECREATE");
  file->cd();

  for(int i=0; i<int(inputfiles.size()); i++) {
    file->WriteTObject(histMRRsq[i], Form("histMRRsq_%s",processLabels[i].c_str()), "WriteDelete");
    histUnrolled[i]->Write();  
  }
  
  stackUnrolled->Write();
 }
void ClusterWidthAnalysisTreeMaker::FitHistos(std::map<ULong64_t , std::vector<TH1F*> > &HistSoN, string output_file, 
 std::vector< TH1F* > commonHistos, std::map<ULong64_t, TProfile* > Monitors){

  TFile * myFile = new TFile(output_file.c_str(), "recreate");

  ULong64_t detid;
  double voltage;
  double errvoltage;
  double Mean;
  double errMean;
  double RMS;
  double errRMS;
  int index;
  int nhits;
  TTree *tree = new TTree("T", "summary information");

  tree->Branch("DetID",&detid, "DetID/l");
  tree->Branch("Voltage",&voltage,"Voltage/D");
  tree->Branch("Index",&index,"Index/I");
  tree->Branch("errVoltage",&errvoltage,"errVoltage/D");
  tree->Branch("Mean",&Mean,"Mean/D");
  tree->Branch("errMean",&errMean,"errMean/D");
  tree->Branch("RMS",&RMS,"RMS/D");
  tree->Branch("errRMS",&errRMS,"errRMS/D");
  tree->Branch("Nhits",&nhits,"Nhits/I");


  //TCanvas* c1 = new TCanvas();
  TH1F* hNhits = new TH1F("hNhits", "hNhits", 1000, 0,1000); // N hits per module
  
  unsigned int nfitrm=0;

  for(std::map<ULong64_t , std::vector<TH1F*> >::iterator iter = HistSoN.begin(); iter != HistSoN.end(); ++iter){
    
	unsigned int i=0; // voltage index    
    std::set< int >::iterator itVolt;
	std::set< int > Voltage = VSmaker.getVoltageList();
    for( itVolt=Voltage.begin(); itVolt!=Voltage.end(); itVolt++){
      
      //std::cout<<"going through the measurement: " << i << std::endl;
            
      TString thestring;
      thestring.Form("DetID_%llu_%u",iter->first,i);
 	  
	  
      //std::cout << "searching for " << thestring.Data() << std::endl;
      //TH1F*  SoNHisto= (TH1F*)gROOT->FindObject( thestring.Data() );
	  
	  if(i>=iter->second.size()) 
       { std::cout<<" Wrong number of voltage steps. "<<std::endl; i++; continue;}
 	  TH1F*  Histo = iter->second[i];
	  
	  if(!Histo) 
       { std::cout<<" Histo "<<thestring.Data()<<"_"<<i<<" not found."<<std::endl; i++; continue;}
 
      if(Histo->GetEntries()) hNhits->Fill(Histo->Integral());
	  
	  if(Histo->Integral()<20) //0.1
	   { //std::cout<<" Not enought entries for histo "<<thestring.Data()<<std::endl;
	    i++; continue;}
 
	  
	  detid = iter->first;

	  bool rmfit=false;

      if( rmfit || 
      // TIB modules
          // TIB - 1.4.2.5
      detid==369121605 || detid==369121606 || detid==369121614 || 
      detid==369121613 || detid==369121610 || detid==369121609 ||
          // TIB - 1.2.2.1
      detid==369121390 || detid==369121382 || detid==369121386 || 
      detid==369121385 || detid==369121389 || detid==369121381 ||
          // others in TIB  
      detid==369121437 || detid==369142077 || detid==369121722 || 
      detid==369125534 || detid==369137018 || detid==369121689 ||
      detid==369121765 || detid==369137045 || detid==369169740 ||
      detid==369121689 ||
      // TOB modules 
	      // TOB + 4.3.3.8
      detid/10==436281512 || detid/10==436281528 || detid/10==436281508 ||
      detid/10==436281524 || detid/10==436281520 || detid/10==436281516 ||
          // others in TOB  
      detid/10==436228249 || detid/10==436232694 || detid/10==436228805 ||
      detid/10==436244722 || detid/10==436245110 || detid/10==436249546 ||
      detid/10==436310808 || detid/10==436312136 || detid/10==436315600 ||
	      // without 'sensors' option 
      detid==436281512 || detid==436281528 || detid==436281508 ||
      detid==436281524 || detid==436281520 || detid==436281516 ||
      detid==436228249 || detid==436232694 || detid==436228805 ||
      detid==436244722 || detid==436245110 || detid==436249546 ||
      detid==436310808 || detid==436312136 || detid==436315600 || 
      // TID modules
      detid==402664070 || detid==402664110 ||
	  // TEC modules in small scans
      detid==470148196 || detid==470148200 || detid==470148204 ||
      detid==470148228 || detid==470148232 || detid==470148236 ||
      detid==470148240 || detid==470148261 || detid==470148262 ||
	  detid==470148265 || detid==470148266 || detid==470148292 ||
	  detid==470148296 || detid==470148300 || detid==470148304 ||
	  detid==470148324 || detid==470148328 || detid==470148332 ||
	  detid==470148336 || detid==470148340 )  { 
	    Histo->Write();
        std::cout << " Saving histo : " << thestring.Data() << std::endl;
      }  


	  if(rmfit) {nfitrm++; i++; continue;}

          int subdet = ((detid>>25)&0x7);
          int TECgeom=0;
          if(subdet==6) TECgeom = ((detid>>5)&0x7);

      // save values
	  detid = iter->first;
	  voltage  = *itVolt;
	  index = i;
	  errvoltage = 2 ;
	  Mean = Histo->GetMean();
	  errMean = Histo->GetMeanError();
	  RMS = Histo->GetRMS();
	  errRMS = Histo->GetRMSError();
	  nhits = (int) Histo->Integral();
	  tree->Fill();
	    
	  i++;

    }  

  }
  
  tree->Write();
  hNhits->Write();
  

  for(unsigned int ih=0; ih<commonHistos.size(); ih++) commonHistos[ih]->Write();

  std::map<ULong64_t, TProfile* >::iterator itMon;
  for(itMon=Monitors.begin(); itMon!=Monitors.end(); itMon++)
  {
    itMon->second->GetXaxis()->SetTimeDisplay(1);
	itMon->second->GetXaxis()->SetTimeFormat("%H:%M");
	itMon->second->GetXaxis()->SetTimeOffset(t_monitor_start);
	itMon->second->Write();
  }
  
  //// If you want to store all the individual detId histograms uncomments this line !!!!
  //myFile->Write();
  myFile->Close();

}
Example #5
0
void phi2(double pt1min, double pt2min, double METmin){


  TLegend* leg = new TLegend(0.13,0.6,0.87,0.87);
  leg->SetNColumns(3);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);

  TFile *data =  TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");
  TFile *sig1 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP600.root","READ");
  TFile *sig2 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP800.root","READ");
  TFile *sig3 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1000.root","READ");
  TFile *sig4 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1200.root","READ");
  TFile *sig5 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1400.root","READ");
  TFile *sig6 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1700.root","READ");
  TFile *sig7 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP2500.root","READ");


  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ"); 
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");
 
  TTree *tree_data = (TTree*) data->Get("DiPhotonTree");

  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree"); 
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree"); 
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree"); 
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree"); 
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree"); 
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");  


  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");

  TCanvas *c1 = new TCanvas("c1","",500,600);
  TPad *mainPad = new TPad("mainPad","",0,0.3,1,1); 
  TPad *smallPad = new TPad("smallPad","",0,0.05,1,0.3);
  mainPad->SetBottomMargin(0.015);
 
  
  smallPad->SetTopMargin(0.05); 
smallPad->SetBottomMargin(0.25); 

  c1->cd();
  
  mainPad->Draw();
  mainPad->cd(); 
 
  
  
  
  
  
  
  gPad->SetLogy();  
  
  TCut mggmax = "mgg<180";
  TCut mggmin = "mgg>100";
  TCut pt1Cut = Form("pt1/mgg>%lf",pt1min);
  TCut pt2Cut = Form("pt2/mgg>%lf",pt2min);
  TCut METCut = Form("t1pfmet>%lf",METmin);
  TCut eveto1 = "eleveto1 == 1";
  TCut eveto2 = "eleveto2 == 1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  
  tree_data->Draw("(phi2)>>hdata(20,-4,4)",(mggmax && mggmin && metF&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");
  
  
  tree_sig1->Draw("(phi2)>>h1(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("(phi2)>>h2(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("(phi2)>>h3(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("(phi2)>>h4(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("(phi2)>>h5(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("(phi2)>>h6(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("(phi2)>>h7(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");
  
  
  tree_bkg1->Draw("(phi2)>>hbkg1(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("(phi2)>>hbkg2(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));  
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("(phi2)>>hbkg3(20,-4,4)","weight"*(mggmin && mggmax && genmatch&& METCut &&pt1Cut && pt2Cut&& eveto));  
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
  tree_bkg4->Draw("(phi2)>>hbkg4(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto)); //weight also on BR = 0.002 if using the 50ns samples
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("(phi2)>>hbkg5(20,-4,4)","weight"*(mggmin && mggmax && genmatch&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("(phi2)>>hbkg6(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");
  tree_bkg7->Draw("(phi2)>>hbkg7(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");
  tree_bkg8->Draw("(phi2)>>hbkg8(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");
  tree_bkg9->Draw("(phi2)>>hbkg9(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");
  tree_bkg10->Draw("(phi2)>>hbkg10(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");
  tree_bkg11->Draw("(phi2)>>hbkg11(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");
  tree_bkg12->Draw("(phi2)>>hbkg12(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");
  
  hdata->SetMarkerColor(kBlack);
  hdata->SetMarkerStyle(20);
  hdata->SetLineColor(kBlack);
  
  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4);
  h6->SetLineColor(kPink+7);
  h7->SetLineColor(kMagenta+2);
 
  h1->SetLineWidth(2);
  h2->SetLineWidth(2);  
  h3->SetLineWidth(2);
  h4->SetLineWidth(2);
  h5->SetLineWidth(2);
 h6->SetLineWidth(2);
 h7->SetLineWidth(2);
  




  THStack *hs= new THStack("hs","");
  hbkg7->SetFillColor(kGreen+2);
  hbkg6->SetFillColor(kGreen);
  hbkg8->SetFillColor(kYellow);
  hbkg4->SetFillColor(kOrange);
  hbkg9->SetFillColor(kOrange+7);
  hbkg10->SetFillColor(kOrange+4);
  hbkg11->SetFillColor(kCyan);
  hbkg12->SetFillColor(kCyan+1);
  hbkg5->SetFillColor(kBlue+2);
  hbkg2->SetFillColor(kBlue);
  hbkg3->SetFillColor(kMagenta-2);
  hbkg1->SetFillColor(kViolet);

  hbkg1->SetLineColor(kBlack);
  hbkg2->SetLineColor(kBlack);
  hbkg3->SetLineColor(kBlack);
  hbkg4->SetLineColor(kBlack);
  hbkg5->SetLineColor(kBlack);
  hbkg6->SetLineColor(kBlack);
  hbkg7->SetLineColor(kBlack);
  hbkg8->SetLineColor(kBlack);
  hbkg9->SetLineColor(kBlack);
  hbkg10->SetLineColor(kBlack);
  hbkg11->SetLineColor(kBlack);
  hbkg12->SetLineColor(kBlack);

  hs->Add(hbkg7);
  hs->Add(hbkg6);
  hs->Add(hbkg8);
  hs->Add(hbkg4);
  hs->Add(hbkg9);
  hs->Add(hbkg10);
  hs->Add(hbkg11);
  hs->Add(hbkg12);
  hs->Add(hbkg2);
  hs->Add(hbkg5);
  hs->Add(hbkg3);
  hs->Add(hbkg1);






  
  TH1F *hsum = (TH1F*)hbkg1->Clone("hsum");
  hsum->Add(hbkg2);
  hsum->Add(hbkg3);
  hsum->Add(hbkg4);
  hsum->Add(hbkg5);
  hsum->Add(hbkg6);
  hsum->Add(hbkg7);
  hsum->Add(hbkg8);
  hsum->Add(hbkg9);
  hsum->Add(hbkg10);
  hsum->Add(hbkg11);
  hsum->Add(hbkg12);

  hs->SetMaximum(1000000);
  hs->SetMinimum(0.1);
  hs->SetTitle("");
  hs->Draw("HIST"); 

  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3002);
  hsum->Draw("same e2");
  h2->Draw("same hist");
  h3->Draw("same hist"); 
  h4->Draw("same hist");
  h1->Draw("same hist");
  h5->Draw("same hist"); 
 h6->Draw("same hist"); 
 h7->Draw("same hist"); 

  hdata->Draw("same E1");
  
  hs->GetXaxis()->SetLabelOffset(999);
  hs->GetYaxis()->SetTitle("Events/0.4");  
  hs->GetYaxis()->SetTitleOffset(1.2);  
  gPad->Modified();
  
  leg->AddEntry(hdata,"Data","lep");
     
  
  
  leg->AddEntry(hbkg1,"#gamma #gamma","f");
leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");                                                                               

  leg->AddEntry(hbkg2,"Drell Yann","f");
 
  leg->AddEntry(hbkg3,"#gamma + Jets","f");
leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");                                                                               

  leg->AddEntry(hbkg5,"QCD","f");
  
  leg->AddEntry(hbkg4,"ggH","f");
 leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");                                                                    
 
  leg->AddEntry(hbkg6,"VH","f");
 
  leg->AddEntry(hbkg7,"ttH","f");

 leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");                                                                    
  leg->AddEntry(hbkg8,"VBF H","f");
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");
leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l");                                                            
leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");
  leg->AddEntry(hbkg11,"#gamma+W","f");
leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l");     
  leg->AddEntry(hbkg12,"#gamma+Z","f");
  leg->AddEntry(hsum,"Bkg uncertainty","f");

 leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l");                            
 leg->Draw("same");
  
  c1->cd(); 
  smallPad->Draw(); 
  smallPad->cd();

  TGraphErrors *gr = new TGraphErrors(0);
  double integralData=hdata->Integral();
  double integralBKG=hsum->Integral();
  double error, ratio;
  for(int w=1; w<20; w++){
    if((hdata->GetBinContent(w)!=0) && (hsum->GetBinContent(w)!=0)){
      
      gr->SetPoint(w, hdata->GetBinCenter(w),(hdata->GetBinContent(w))/(hsum->GetBinContent(w)));
      ratio= (hdata->GetBinContent(w))/(hsum->GetBinContent(w));
      error= (hdata->GetBinContent(w)*sqrt(hsum->GetBinContent(w))/(hsum->GetBinContent(w)*hsum->GetBinContent(w)) + sqrt(hdata->GetBinContent(w))/hsum->GetBinContent(w));
      std::cout<<"VALUE: "<<ratio<<" ERROR: "<<error<<std::endl;
      gr->SetPointError(w, hdata->GetBinWidth(w)/2,error);
    }else{
      gr->SetPoint(w, hdata->GetBinCenter(w),10);
    } 
  }

  
  
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  gr->GetHistogram()->SetMaximum(2);
  gr->GetHistogram()->SetMinimum(0.1);
  
  gStyle->SetTextSize(14);
  gROOT->ForceStyle();
  
  gr->GetXaxis()->SetLabelFont(43);
  gr->GetXaxis()->SetLabelSize(15);
  gr->GetYaxis()->SetLabelFont(43);
  gr->GetYaxis()->SetLabelSize(15);
  
  gr->GetXaxis()->SetLimits(-4,4);
  
  
  gPad->SetGrid();
  gStyle->SetStripDecimals(kTRUE);
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(0.7);
  
  
  gr->Draw("AZP");
  gr->GetXaxis()->SetTitle("#phi_{2}");
  gr->GetXaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetNdivisions(505);
 
  gr->GetXaxis()->SetTitleOffset(1);
  gr->GetYaxis()->SetTitle("Data/MC"); 
  gr->GetYaxis()->SetTitleOffset(0.4);
  gr->SetTitle(""); 
  smallPad->Update();
  TF1* line = new TF1("line","1",-4,4);
  line->SetLineColor(kRed);
  line->SetLineWidth(2);
  line->Draw("L same");
  gr->Draw("ZP SAME");
  

  if(pt1min==0 && pt2min == 0 && METmin == 0){
    c1->SaveAs("./25ns_2246inv_v3/plots/kinematics/phi2.png");
    c1->SaveAs("./25ns_2246inv_v3/plots/kinematics/phi2.pdf");
  }
  if(pt1min==0.65 && pt2min == 0.25){
    c1->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/phi2_optcuts_MET%.0lf.png",METmin));
    c1->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/phi2_optcuts_MET%.0lf.pdf",METmin));
  }
  


}
void spectraSysTrig_dNdetashift() {

  // === General Settings ===

  // Note centrality is by 2.5% bins, low bin is inclusive, high bin is exclusive
  // i.e. for 0-10% use minCent=0, maxCent=4. 


  int minCent[12] = {0,2,4,6,8,10,12,14,16,20,24,28};
  int maxCent[12] = {2,4,6,8,10,12,14,16,20,24,28,32};
  
  // absolute values of eta are used, negative eta values are included
  // for full eta range set etaMin=0 etaMax=2.4
  Double_t  etaMin = 0.0;
  Double_t  etaMax = 0.4;

double dndeta[12]= {1612,1313,1082,893.9,731.6,596.8, 482.3,383.9, 266.5, 153.2,79.5, 36.3 };
double dndetaerr[12] = {55,45, 38, 31.4, 26.3, 23.1, 18.7, 16.2, 14.2, 9.7, 6.57, 3.99};

  double ptbins[20]={0.3,0.4,0.5,0.6,0.8,1.0,1.2,1.6,2.0,2.5,3.0,3.5,4.0,5.0,6.0,8.0,10.0,12.0,16.,22.};

  
  // Input File
  TFile *f = new TFile("LowPtSpectrum_fine_Full_d.root");
  TFile *fcorr = new TFile("validation3D_HydjetNoWedge_100k_flowSQ_vertexZ10.root");
  TFile *fcorrAMPT;
  TFile *fcorrDataMix = new TFile("validation3D_20pionBadWedge_SQ12_vertexZ10.root");
  // =========================

  gStyle->SetErrorX(0);
  gStyle->SetOptStat(0);


  set_plot_style();

  char dirname[256] = "spectrumGoodTightdz10chi40";
  TH1D * spec[10][12];
  TH1D * eff[10][12];
  TH1D * fak[10][12];
  TH1D * sim[10][12];
  TH1D * rec[10][12];

  TGraphErrors * gSpectrum[10][12];
  TF1 * f1[10][12];

  Double_t  meanpt[10][12];
  Double_t  meanpterr[10][12];

  double integral[4][12];
  
    Double_t px[100],py[100],pxe[100],pye[100];
  for( int c=0; c<12; c++)
  {
    for( int j=0; j<4; j++)
    {
      if ( j==0) spec[j][c] = getSpectrum( f, Form("%s/tracks3D",dirname), minCent[c], maxCent[c], etaMin, etaMax ); 
      if ( j==1) spec[j][c] = getSpectrum( f, Form("%s/tracks3D_c94",dirname), minCent[c], maxCent[c], etaMin, etaMax ); 
      if ( j==2) spec[j][c] = getSpectrum( f, Form("%s/tracks3D_c97",dirname), minCent[c], maxCent[c], etaMin, etaMax ); 
      if ( j==3) spec[j][c] = getSpectrum( f, Form("%s/tracks3D_c100",dirname), minCent[c], maxCent[c], etaMin, etaMax ); 
      eff[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/heff3D", minCent[c], maxCent[c], etaMin, etaMax );
      sim[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hsim3D", minCent[c], maxCent[c], etaMin, etaMax );
      fak[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hfak3D", minCent[c], maxCent[c], etaMin, etaMax );
      rec[j][c] = getSpectrum( fcorr, "hitrkPixelEffAnalyzer/hrec3D", minCent[c], maxCent[c], etaMin, etaMax );

      // determine correction factors


      TH1F * nevts;

      if( j==0)  nevts = (TH1F *) f->Get(Form("%s/nevts",dirname));
      if( j==1)  nevts = (TH1F *) f->Get(Form("%s/nevts_c94",dirname));
      if( j==2)  nevts = (TH1F *) f->Get(Form("%s/nevts_c97",dirname));
      if( j==3)  nevts = (TH1F *) f->Get(Form("%s/nevts_c100",dirname));
      double Nevt = nevts->Integral( nevts->GetXaxis()->FindBin(minCent[c]+0.001), 
                                     nevts->GetXaxis()->FindBin(maxCent[c]-0.001) );


      Double_t maxy = 0.;
      Double_t miny = 100000.;
    integral[j][c] = 0;
    for( int i=0; i<=19;i++)
    {
      double ptmin = ptbins[i]; double ptmax = ptbins[i+1];

      double iptmin = spec[j][c]->FindBin(ptmin+1e-3);
      double iptmax = spec[j][c]->FindBin(ptmax-1e-3);
      double icptmin = eff[j][c]->FindBin(ptmin+1e-3);
      double icptmax = eff[j][c]->FindBin(ptmax-1e-3);
      double pt = 0.;
      for( int k=iptmin;k<=iptmax;k++) pt += spec[j][c]->GetBinCenter(k) * spec[j][c]->GetBinContent(k);
      pt /= spec[j][c]->Integral(iptmin,iptmax);

      double yielderr;
      double yield = spec[j][c]->IntegralAndError(iptmin,iptmax,yielderr);
      yield /= (ptmax-ptmin) * Nevt * 2 * (etaMax-etaMin);
      yielderr /= (ptmax-ptmin) * Nevt * 2 * (etaMax-etaMin);

      double efmin = eff[j][c]->GetBinContent(icptmin)/sim[j][c]->GetBinContent(icptmin);
      double efmax = eff[j][c]->GetBinContent(icptmax)/sim[j][c]->GetBinContent(icptmax);
      double famin = fak[j][c]->GetBinContent(icptmin)/rec[j][c]->GetBinContent(icptmin);
      double famax = fak[j][c]->GetBinContent(icptmax)/rec[j][c]->GetBinContent(icptmax);

      double ef = (pt-ptmin)*(efmax-efmin)/(ptmax-ptmin)+efmin;
      double fa = (pt-ptmin)*(famax-famin)/(ptmax-ptmin)+famin;
      yield *= (1-fa)/ef;

      px[i] = pt;
      py[i] = yield;
      if( py[i] > maxy ) maxy = py[i];
      if( py[i] < miny ) miny = py[i];
      pxe[i] = 0.;
      pye[i] = yielderr;
      if ( yield > -1. ) integral[j][c] += yield;
    }


      gSpectrum[j][c] = new TGraphErrors( 19, px, py, pxe, pye );
      gSpectrum[j][c]->SetMarkerStyle(20);
      f1[j][c] = new TF1(Form("f1_%d_%d",c,j),"6.28318531 * x * [2]*pow((1+sqrt(0.01947978 + x*x)-0.13957) /[1],-[0])",0.3,3.1);
     f1[j][c]->SetParameters(10.8327,2.221289,dndeta[c]);
     if(j==3) f1[j][c]->SetParameters(10.8327,2.221289,dndeta[c]*2);
     f1[j][c]->SetParameters(10.8327,2.221289,dndeta[c]);
      f1[j][c]->SetLineColor(kBlue);
      f1[j][c]->SetLineWidth(1);
      f1[j][c]->SetLineStyle(1);
       gSpectrum[j][c]->Fit(Form("f1_%d_%d",c,j),"0RQNS");
      TF1 * fitptmx = new TF1("fitptmx","6.28318531 * x * x * [2]*pow((1+sqrt(0.01947978 + x*x)-0.13957) /[1],-[0])",0.0,3.1);
      fitptmx->SetParameters(f1[j][c]->GetParameter(0),f1[j][c]->GetParameter(1), f1[j][c]->GetParameter(2) );
    double numerator = fitptmx->Integral(0.0,0.3);
    double denominator = f1[j][c]->Integral(0.0,0.3);
    for( int p = 0; p<gSpectrum[j][c]->GetN(); p++)
    {
       Double_t  ppx, ppy;
       gSpectrum[j][c]->GetPoint(p,ppx,ppy);
       if ( 0.3 < ppx && ppx < 0.6 ) numerator += ppx * ppy * 0.1;
       if ( 0.6 < ppx && ppx < 1.2 ) numerator += ppx * ppy * 0.2;
       if ( 1.2 < ppx && ppx < 2.0 ) numerator += ppx * ppy * 0.4;
       if ( 2.0 < ppx && ppx < 4.0 ) numerator += ppx * ppy * 0.5;
       if ( 4.0 < ppx && ppx < 6.0 ) numerator += ppx * ppy * 1.0;
       if ( 0.3 < ppx && ppx < 0.6 ) denominator += ppy * 0.1;
       if ( 0.6 < ppx && ppx < 1.2 ) denominator += ppy * 0.2;
       if ( 1.2 < ppx && ppx < 2.0 ) denominator += ppy * 0.4;
       if ( 2.0 < ppx && ppx < 4.0 ) denominator += ppy * 0.5;
       if ( 4.0 < ppx && ppx < 6.0 ) denominator += ppy * 1.0;
    }
    meanpt[j][c] = numerator / denominator;


      meanpterr[j][c] = 0.;
    }
    
  }

 
  TH1D* hDumCen = new TH1D("hDumCen",";Centrality (%);<p_{T}> Ratio",40,0.,80.); 
  hDumCen->GetXaxis()->CenterTitle(); hDumCen->GetYaxis()->SetTitleOffset(1.1);
  hDumCen->SetMaximum(1.5); hDumCen->SetMinimum(0.5);

  TCanvas *c1 = new TCanvas("c1","Mean Pt",600,600);
 
  c1->cd();
  hDumCen->Draw();

  TGraphErrors * gmean[4];
  
  int colors[4] = {0,kRed, kBlack, kBlue};

  for( int j=1; j<4; j++)
  {
    Double_t mx[12], mxe[12], my[12], mye[12];
    for(int i=0;i<12;i++) 
    { 
      mx[i] = (double)(maxCent[i]+minCent[i]) * 1.25;
      mxe[i] = 0; 
      my[i] = meanpt[j][i] / meanpt[0][i];
      mye[i] = my[i] * sqrt( meanpterr[j][i]*meanpterr[j][i]/meanpt[j][i]/meanpt[j][i] 
                           + meanpterr[0][i]*meanpterr[0][i]/meanpt[0][i]/meanpt[0][i] );
    
    }  

    gmean[j] = new TGraphErrors(12, mx, my, mxe, mye);
    gmean[j]->SetMarkerStyle(20);
    gmean[j]->SetMarkerColor(colors[j]);
    gmean[j]->SetLineColor(colors[j]);
    gmean[j]->Draw("p");
  
  }
  TLegend *legPt = new TLegend(0.45,0.7,0.89,0.89);
  legPt->SetFillColor(0); legPt->SetBorderSize(0);
  legPt->AddEntry(gmean[1],"Trig 94","lp");
  legPt->AddEntry(gmean[2],"Trig 97","lp");
  legPt->AddEntry(gmean[3],"Trig 100","lp");

  legPt->Draw();

  TLatex *  tex = new TLatex(20,0.8,Form( "GoodTightMergedTracks, %4.1f < |#eta| < %4.1f",etaMin, etaMax ));
    tex->SetTextSize(0.035);
    tex->Draw();

  TH1D* hDumPt = new TH1D("hDumPt",";p_{T} [GeV/c];ratio 1/N_{evt} d^{2}N_{ch}/d#etadp_{T}",40,0.,6.); hDumPt->SetMaximum(1.5);
  hDumPt->GetXaxis()->CenterTitle(); hDumPt->GetYaxis()->SetTitleOffset(1.1);

  hDumPt->SetMaximum(1.25); hDumPt->SetMinimum(0.75);

  TCanvas *c8 = new TCanvas("c8","Spectrum",1000,800);
  c8->Divide(4,3,0,0);

  TGraphErrors * gRatio[4][12]; 

  for( int q=0;q<12; q++)
  {
    c8->cd(q+1);
    int i = q;
    hDumPt->Draw();
    for( int j=0; j<4; j++)
    { 
      Double_t rx[100],ry[100],rxe[100],rye[100];
      Double_t dx, nx, ny, dy, dye, nye; 
      for( int p=0;p<gSpectrum[0][i]->GetN();p++)
      {
        gSpectrum[0][i]->GetPoint(p,dx,dy);
        dye = gSpectrum[0][i]->GetErrorY(p);
        gSpectrum[j][i]->GetPoint(p,nx,ny);
        nye = gSpectrum[j][i]->GetErrorY(p);
        rx[p] = nx; rxe[p]=0;
        ry[p] = ny / dy;
        rye[p] = ry[p] * sqrt ( nye*nye/ny/ny + dye*dye/dy/dy);        
      }
      gRatio[j][i] = new TGraphErrors(gSpectrum[0][i]->GetN(), rx, ry, rxe, rye);
      gRatio[j][i]->SetMarkerStyle(20);
      gRatio[j][i]->SetMarkerColor(colors[j]);
      gRatio[j][i]->SetLineColor(colors[j]);
      gRatio[j][i]->Draw("p"); 
    tex = new TLatex(1,0.87,Form("%d-%d Cent.",(int)(minCent[i]*2.5),(int)(maxCent[i]*2.5)));
    tex->SetTextSize(0.045);
    tex->Draw();

    if( i==0) legPt->Draw();
  
    tex = new TLatex(1,0.85,Form("%4.1f < |#eta| < %4.1f",etaMin,etaMax));
    tex->SetTextSize(0.045);
    if( i==0) tex->Draw();
    tex = new TLatex(1,0.83,Form("GoodTightMergedTracks",etaMin,etaMax));
    tex->SetTextSize(0.045);
    if( i==0) tex->Draw();
    }
  } 

  cout << "Normalization Errors from Integrals\n\n\n";

  for( int c=0; c<12; c++)
  {
    cout << Form("%d-%d Cent.",(int)(minCent[c]*2.5),(int)(maxCent[c]*2.5)) << "  ";
    for( int j = 1; j<4; j++)
    {
      cout << integral[j][c] / integral[0][c] << "  ";
    }
    cout << endl;
  }

}
void 
//HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_et_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category_extra = "no b-tag";     }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category_extra = "b-tag";  }        
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra2 = "medium p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001); 
  TH1F* EWK0   = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK0 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(100,182,232), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#else
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#endif
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
  TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125"  , directory)), "ggH_SM125"); InitHist(ggH_SM125, "", "", kGreen+2, 1001);
  TH1F* qqH_SM125= refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125"  , directory)), "qqH_SM125"); InitHist(qqH_SM125, "", "", kGreen+2, 1001);
  TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125"   , directory)), "VH_SM125" ); InitHist(VH_SM125, "", "", kGreen+2, 1001);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK0 );
  ref->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK2 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK0 ->Integral();
  unscaled[1]+= EWK1 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK2 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK0 = refill(shape_histos(EWK0, datacard, "VV"), "VV"); 
    EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
    EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK = refill(shape_histos(EWK, datacard, "ZL"), "ZL");
#else
    //    EWK = refill(shape_histos(EWK, datacard, "ZLL"), "ZLL");
#endif
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
    Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/

    rescale(Fakes, 7); 
    rescale(EWK0 , 6); 
    rescale(EWK1 , 3); 
#ifdef EXTRA_SAMPLES
    rescale(EWK2 , 4); 
    rescale(EWK  , 5);
#else
    rescale(EWK  , 4);
#endif 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);
#endif  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK0 ->Integral()
					       +EWK1 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK2 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

#ifdef MSSM
  qqH_SM125->Add(ggH_SM125);
  VH_SM125->Add(qqH_SM125);
  Fakes->Add(VH_SM125);
#endif
  EWK0 ->Add(Fakes);
  EWK1 ->Add(EWK0 );
#ifdef EXTRA_SAMPLES
  EWK2 ->Add(EWK1 );
  EWK  ->Add(EWK2 );
#else
  EWK  ->Add(EWK1 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
#ifdef MSSM
  ggH  ->Add(bbH);
#endif
  if(log){
#ifdef MSSM
    //ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
#ifdef MSSM
    VH_SM125->Draw("histsame");
#endif   
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
#ifdef MSSM
    VH_SM125->Draw("histsame");
#endif
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{mod+} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Z#rightarrow ee"                , "F" );
  leg->AddEntry(EWK1 , "W+jets"                         , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
#ifdef MSSM
  leg->AddEntry(VH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("Zee"     );
  EWK1 ->Write("EWK"    );
  //EWK  ->Write("EWK"     );
  EWK1 ->Write("EWK1"    );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
  ggH_SM125->Write("ggH_SM125");
  qqH_SM125->Write("qqH_SM125");
  VH_SM125 ->Write("VH_SM125");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
void
HTT_MM_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="mumu_$CATEGORY")
{
    // define common canvas, axes pad styles
    SetStyle();
    gStyle->SetLineStyleString(11,"20 10");

    // determine category tag
    const char* category = "";
    const char* category_extra = "";
    const char* category_extra2 = "";
    if(std::string(directory) == std::string("mumu_0jet_low"             )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_0jet_low"             )) {
        category_extra = "0-jet low p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_0jet_high"            )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_0jet_high"            )) {
        category_extra = "0-jet high p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_1jet_low"          )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_1jet_low"          )) {
        category_extra = "1-jet low p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_1jet_high"          )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_1jet_high"          )) {
        category_extra = "1-jet high p_{T}^{#mu}";
    }
    if(std::string(directory) == std::string("mumu_vbf"            )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_vbf"            )) {
        category_extra = "2-jet";
    }
    if(std::string(directory) == std::string("mumu_nobtag"               )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_nobtag"               )) {
        category_extra = "no b-tag";
    }
    if(std::string(directory) == std::string("mumu_btag"                 )) {
        category = "#mu#mu";
    }
    if(std::string(directory) == std::string("mumu_btag"                 )) {
        category_extra = "b-tag";
    }

    const char* dataset;
#ifdef MSSM
    if(std::string(inputfile).find("7TeV")!=std::string::npos) {
        dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";
    }
    if(std::string(inputfile).find("8TeV")!=std::string::npos) {
        dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";
    }
#else
    if(std::string(inputfile).find("7TeV")!=std::string::npos) {
        dataset = "CMS, 4.9 fb^{-1} at 7 TeV";
    }
    if(std::string(inputfile).find("8TeV")!=std::string::npos) {
        dataset = "CMS, 19.7 fb^{-1} at 8 TeV";
    }
#endif

    TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
    TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
    TH1F* ZTT      = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     );
    InitHist(ZTT     , "", "", TColor::GetColor(248,206,104), 1001);
    TH1F* ZMM      = refill((TH1F*)input ->Get(TString::Format("%s/ZMM"     , directory)), "ZMM"     );
    InitHist(ZMM     , "", "", TColor::GetColor(100,182,232), 1001);
    TH1F* TTJ      = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     );
    InitHist(TTJ     , "", "", TColor::GetColor(155,152,204), 1001);
    TH1F* QCD      = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     );
    InitHist(QCD     , "", "", TColor::GetColor(250,202,255), 1001);
    TH1F* Dibosons = refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons");
    InitHist(Dibosons, "", "", TColor::GetColor(222,90,106), 1001);
    TH1F* WJets    = 0;
    if(!(std::string("mumu_nobtag") == std::string(directory))) {
        // template has been removed from nobtag categories
        WJets = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   );
        InitHist(WJets   , "", "", kGreen -4 , 1001);
    }
#ifdef MSSM
    TH1F* ggH      = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     );
    InitSignal(ggH);
    ggH->Scale($TANB);
    TH1F* bbH      = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     );
    InitSignal(bbH);
    bbH->Scale($TANB);
    // TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125"  , directory)), "ggH_SM125"); InitHist(ggH_SM125, "", "", kGreen+2, 1001);
//   TH1F* qqH_SM125= refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125"  , directory)), "qqH_SM125"); InitHist(qqH_SM125, "", "", kGreen+2, 1001);
//   TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125"   , directory)), "VH_SM125" ); InitHist(VH_SM125, "", "", kGreen+2, 1001);
    TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH_SM125");
    InitHist(ggH_SM125, "", "", kGreen+2, 1001);
    if(std::string(inputfile).find("7TeV")!=std::string::npos) ggH_SM125->Scale((15.13+1.222+0.3351+0.08632)*0.0632);
    if(std::string(inputfile).find("8TeV")!=std::string::npos) ggH_SM125->Scale((19.27+1.578+0.7046+0.4153)*0.0632);
#else
#ifndef DROP_SIGNAL
    TH1F* ggH      = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     );
    InitSignal(ggH);
    ggH->Scale(SIGNAL_SCALE);
    TH1F* qqH      = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     );
    InitSignal(qqH);
    qqH->Scale(SIGNAL_SCALE);
    TH1F* VH       = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      );
    InitSignal(VH );
    VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
    TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
    TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
    InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}");
    InitData(data);
#else
    InitHist(data, "#bf{D}", "#bf{dN/dD}"     );
    InitData(data);
#endif

    TH1F* ref=(TH1F*)ZTT->Clone("ref");
    ref->Add(ZMM);
    ref->Add(TTJ);
    ref->Add(QCD);
    ref->Add(Dibosons);
    if(WJets) {
        ref->Add(WJets);
    }
    double unscaled[9];
    unscaled[0] = ZTT->Integral();
    unscaled[1] = ZMM->Integral();
    unscaled[2] = TTJ->Integral();
    unscaled[3] = QCD->Integral();
    unscaled[4] = Dibosons->Integral();
    unscaled[5] = 0;
    if(WJets) {
        unscaled[5] = WJets->Integral();
    }
#ifdef MSSM
    unscaled[6] = ggH->Integral();
    unscaled[7] = bbH->Integral();
    unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
    unscaled[6] = ggH->Integral();
    unscaled[7] = qqH->Integral();
    unscaled[8] = VH ->Integral();
#endif
#endif

    if(scaled) {
        rescale(ZTT,  1);
        rescale(ZMM,  2);
        rescale(TTJ,  3);
        rescale(QCD,  4);
        rescale(Dibosons, 5);
        if(WJets) {
            rescale(WJets,  6);
        }
#ifdef MSSM
        rescale(ggH,  7);
        rescale(bbH,  8);
#else
#ifndef DROP_SIGNAL
        rescale(ggH,  7);
        rescale(qqH,  8);
        rescale(VH,   9);
#endif
#endif
    }

    TH1F* scales[9];
    scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
    scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
    scales[1] = new TH1F("scales-ZMM"  , "", 9, 0, 9);
    scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZMM->Integral()/unscaled[1]-1.)      : 0.);
    scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
    scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
    scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
    scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
    scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
    scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
    scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
    scales[5]->SetBinContent(6, 0.);
    if(WJets) {
        scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)  : 0.);
    }
#ifdef MSSM
    scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
    scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
    scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
    scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
    scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
    scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
    scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
    scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
    scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
    scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[7]-1.)      : 0.);
    scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
    scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[8]-1.)      : 0.);
#endif
#endif

#ifdef MSSM
    // qqH_SM125->Add(ggH_SM125);
//   VH_SM125->Add(qqH_SM125);
//   Dibosons->Add(VH_SM125);
    Dibosons->Add(ggH_SM125);
#endif
    if(WJets) {
        Dibosons->Add(WJets);
    }
    QCD->Add(Dibosons);
    TTJ->Add(QCD);
    ZTT->Add(TTJ);
    ZMM->Add(ZTT);
    if(log) {
#ifdef MSSM
        ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
        qqH  ->Add(VH );
        ggH  ->Add(qqH);
#endif
#endif
    }
    else {
#ifdef MSSM
        bbH  ->Add(ZMM);
        ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
        VH   ->Add(ZMM);
        qqH  ->Add(VH );
        ggH  ->Add(qqH);
#endif
#endif
    }


    /*
      mass plot before and after fit
    */
    TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
    canv->cd();
    if(log) {
        canv->SetLogy(1);
    }
#if defined MSSM
    if(!log) {
        data->GetXaxis()->SetRange(0, data->FindBin(345));
    }
    else {
        data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE));
    };
#else
    data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
    data->SetNdivisions(505);
    data->SetMinimum(min);
#ifndef DROP_SIGNAL
    data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZMM, log)), maximum(ggH, log)));
#else
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZMM, log)));
#endif
    data->Draw("e");

    TH1F* errorBand = (TH1F*)ZMM->Clone("errorBand");
    errorBand->SetMarkerSize(0);
    errorBand->SetFillColor(13);
    errorBand->SetFillStyle(3013);
    errorBand->SetLineWidth(1);
    for(int idx=0; idx<errorBand->GetNbinsX(); ++idx) {
        if(errorBand->GetBinContent(idx)>0) {
            std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
            break;
        }
    }
    if(log) {
        ZMM->Draw("histsame");
        ZTT->Draw("histsame");
        TTJ->Draw("histsame");
        QCD->Draw("histsame");
        Dibosons->Draw("histsame");
#ifdef MSSM
        //VH_SM125->Draw("histsame");
        ggH_SM125->Draw("histsame");
#endif
        $DRAW_ERROR
#ifndef DROP_SIGNAL
        ggH->Draw("histsame");
#endif

    }
    else {
#ifndef DROP_SIGNAL
        ggH  ->Draw("histsame");
#endif
        ZMM->Draw("histsame");
        ZTT->Draw("histsame");
        TTJ->Draw("histsame");
        QCD->Draw("histsame");
        Dibosons->Draw("histsame");
#ifdef MSSM
        //VH_SM125->Draw("histsame");
        ggH_SM125->Draw("histsame");
#endif
        $DRAW_ERROR
    }
    data->Draw("esame");
    canv->RedrawAxis();

    //CMSPrelim(dataset, "#tau_{#mu}#tau_{#mu}", 0.17, 0.835);
    CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
    TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
    TPaveText* chan     = new TPaveText(0.22, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.34, 0.75+0.161, "tlbrNDC");
#endif
    chan->SetBorderSize(   0 );
    chan->SetFillStyle(    0 );
    chan->SetTextAlign(   12 );
    chan->SetTextSize ( 0.05 );
    chan->SetTextColor(    1 );
    chan->SetTextFont (   62 );
    chan->AddText(category);
    chan->AddText(category_extra);
#if defined MSSM
#else
    chan->AddText(category_extra2);
#endif
    chan->Draw();

    /*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
      cat->SetBorderSize(   0 );
      cat->SetFillStyle(    0 );
      cat->SetTextAlign(   12 );
      cat->SetTextSize ( 0.05 );
      cat->SetTextColor(    1 );
      cat->SetTextFont (   62 );
      cat->AddText(category_extra);
      cat->Draw();
    */
#ifdef MSSM
    TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("MSSM m^{h}_{mod+} scenario");
    massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
    massA->Draw();
#endif

#ifdef MSSM
    TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
    SetLegendStyle(leg);
    leg->AddEntry(ggH  , "h,H,A#rightarrow#tau#tau" , "L" );
#else
    TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
    SetLegendStyle(leg);
#ifndef DROP_SIGNAL
    if(SIGNAL_SCALE!=1) {
        leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
    }
    else {
        leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
    }
#endif
#endif
#ifdef ASIMOV
    leg->AddEntry(data    , "sum(bkg) + H(125)"           , "LP");
#else
    leg->AddEntry(data    , "Observed"                    , "LP");
#endif
    leg->AddEntry(ZMM     , "Z#rightarrow#mu#mu"          , "F" );
    leg->AddEntry(ZTT     , "Z#rightarrow#tau#tau"        , "F" );
    leg->AddEntry(TTJ     , "t#bar{t}"                    , "F" );
    leg->AddEntry(QCD     , "QCD"                         , "F" );
    leg->AddEntry(Dibosons, "Electroweak"                 , "F" );
#ifdef MSSM
    leg->AddEntry(ggH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
    $ERROR_LEGEND
    leg->Draw();

    /*
      Ratio Data over MC
    */
    TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
    canv0->SetGridx();
    canv0->SetGridy();
    canv0->cd();

    TH1F* model = (TH1F*)ZMM ->Clone("model");
    TH1F* test1 = (TH1F*)data->Clone("test1");
    for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin) {
        //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
        model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
        model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
        test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
        test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
    }
    double chi2prob = test1->Chi2Test      (model,"PUW");
    std::cout << "chi2prob:" << chi2prob << std::endl;
    double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW");
    std::cout << "chi2ndf :" << chi2ndof << std::endl;
    double ksprob   = test1->KolmogorovTest(model);
    std::cout << "ksprob  :" << ksprob   << std::endl;
    double ksprobpe = test1->KolmogorovTest(model,"DX");
    std::cout << "ksprobpe:" << ksprobpe << std::endl;

    std::vector<double> edges;
    TH1F* zero = (TH1F*)ref ->Clone("zero");
    zero->Clear();
    TH1F* rat1 = (TH1F*)data->Clone("rat1");
    rat1->Reset("ICES");
    for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin) {
        if(data->GetBinContent(ibin+1) > 0) {
            rat1->SetBinContent(ibin+1, ZMM->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
            rat1->SetBinError  (ibin+1, ZMM->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
        }
        zero->SetBinContent(ibin+1, 0.);
        zero->SetBinError  (ibin+1, ZMM->GetBinContent(ibin+1)>0 ? ZMM ->GetBinError  (ibin+1)/ZMM->GetBinContent(ibin+1) : 0);
    }
    for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin) {
        if(rat1->GetBinContent(ibin+1)>0) {
            edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
            // catch cases of 0 bins, which would lead to 0-alpha*0-1
            rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
        }
    }
    float range = 0.1;
    std::sort(edges.begin(), edges.end());
    if (edges[edges.size()-2]>0.1) {
        range = 0.2;
    }
    if (edges[edges.size()-2]>0.2) {
        range = 0.5;
    }
    if (edges[edges.size()-2]>0.5) {
        range = 1.0;
    }
    if (edges[edges.size()-2]>1.0) {
        range = 1.5;
    }
    if (edges[edges.size()-2]>1.5) {
        range = 2.0;
    }
    rat1->SetLineColor(kBlack);
    rat1->SetFillColor(kGray );
    rat1->SetMaximum(+range);
    rat1->SetMinimum(-range);
    rat1->GetYaxis()->CenterTitle();
    rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
#ifdef MSSM
    rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
#else
    rat1->GetXaxis()->SetTitle("#bf{D}");
#endif
    rat1->Draw("E0");
    zero->SetFillStyle(  3013);
    zero->SetFillColor(kBlack);
    zero->SetLineColor(kBlack);
    zero->SetMarkerSize(0.1);
    zero->Draw("e2histsame");
    canv0->RedrawAxis();

    TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
    stat1->SetBorderSize(   0 );
    stat1->SetFillStyle(    0 );
    stat1->SetTextAlign(   12 );
    stat1->SetTextSize ( 0.05 );
    stat1->SetTextColor(    1 );
    stat1->SetTextFont (   62 );
    stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
    //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
    stat1->Draw();

    /*
      Ratio After fit over Prefit
    */
    TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
    canv1->SetGridx();
    canv1->SetGridy();
    canv1->cd();

    edges.clear();
    TH1F* rat2 = (TH1F*) ZMM->Clone("rat2");
    for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin) {
        rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZMM->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
        rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZMM->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
    }
    for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin) {
        if(rat2->GetBinContent(ibin+1)>0) {
            edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
            // catch cases of 0 bins, which would lead to 0-alpha*0-1
            rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
        }
    }
    range = 0.1;
    std::sort(edges.begin(), edges.end());
    if (edges[edges.size()-2]>0.1) {
        range = 0.2;
    }
    if (edges[edges.size()-2]>0.2) {
        range = 0.5;
    }
    if (edges[edges.size()-2]>0.5) {
        range = 1.0;
    }
    if (edges[edges.size()-2]>1.0) {
        range = 1.5;
    }
    if (edges[edges.size()-2]>1.5) {
        range = 2.0;
    }
#if defined MSSM
    if(!log) {
        rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
    }
    else {
        rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE));
    };
#else
    rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
    rat2->SetNdivisions(505);
    rat2->SetLineColor(kRed+3);
    rat2->SetMarkerColor(kRed+3);
    rat2->SetMarkerSize(1.1);
    rat2->SetMaximum(+range);
    rat2->SetMinimum(-range);
    rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
    rat2->GetYaxis()->CenterTitle();
#if defined MSSM
    rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
#else
    rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
    rat2->Draw();
    zero->SetFillStyle(  3013);
    zero->SetFillColor(kBlack);
    zero->SetLineColor(kBlack);
    zero->Draw("e2histsame");
    canv1->RedrawAxis();

    /*
      Relative shift per sample
    */
    TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
    canv2->SetGridx();
    canv2->SetGridy();
    canv2->cd();

    InitHist  (scales[0], "", "", TColor::GetColor(248,206,104), 1001);
    InitHist  (scales[1], "", "", TColor::GetColor(100,182,232), 1001);
    InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
    InitHist  (scales[3], "", "", TColor::GetColor(250,202,255), 1001);
    InitHist  (scales[4], "", "", TColor::GetColor(222,90,106), 1001);
    InitHist  (scales[5], "", "", kGreen   -  4, 1001);
#ifndef DROP_SIGNAL
    InitSignal(scales[6]);
    InitSignal(scales[7]);
    InitSignal(scales[8]);
#endif
    scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
    scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZMM}"  );
    scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
    scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
    scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
    scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
    scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
    scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
    scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
    scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
    scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
    scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
    scales[0]->SetMaximum(+0.5);
    scales[0]->SetMinimum(-0.5);
    scales[0]->GetYaxis()->CenterTitle();
    scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
    scales[0]->Draw();
    scales[1]->Draw("same");
    scales[2]->Draw("same");
    scales[3]->Draw("same");
    scales[4]->Draw("same");
    scales[5]->Draw("same");
#ifndef DROP_SIGNAL
    scales[6]->Draw("same");
    scales[7]->Draw("same");
    scales[8]->Draw("same");
#endif
    TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples");
    zero_samples->Clear();
    zero_samples->SetBinContent(1,0.);
    zero_samples->Draw("same");
    canv2->RedrawAxis();

    /*
      prepare output
    */
    bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
    canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    if(log || FULLPLOTS)
    {
        canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    }
    if((log && scaled) || FULLPLOTS)
    {
        canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
        canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    }

    TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
    output->cd();
    data ->Write("data_obs");
    ZTT->Write("Ztt"  );
    ZMM->Write("Zmm"  );
    TTJ->Write("ttbar");
    QCD->Write("Fakes");
    Dibosons->Write("EWK");
    if(WJets) {
        WJets->Write("WJets");
    }
#ifdef MSSM
    ggH  ->Write("ggH");
    bbH  ->Write("bbH");
    ggH_SM125->Write("ggH_SM125");
    //qqH_SM125->Write("qqH_SM125");
    //VH_SM125 ->Write("VH_SM125");
#else
#ifndef DROP_SIGNAL
    ggH  ->Write("ggH");
    qqH  ->Write("qqH");
    VH   ->Write("VH" );
#endif
#endif
    if(errorBand) {
        errorBand->Write("errorBand");
    }
    output->Close();

    delete errorBand;
    delete model;
    delete test1;
    delete zero;
    delete rat1;
    delete rat2;
    delete zero_samples;
    delete ref;
}
Example #9
0
int main(int argc, char **argv) {


  TFile *fshape = new TFile("mlb.root");
  TH1F *shapemlb = (TH1F *) fshape->Get("mlb");
  MassReconstructor theMass(100, shapemlb);

  TFile *f = new TFile(argv[1]);
  f->cd();
  TTree *tree = (TTree *)f->Get("events");
  setSetBranchAddresses(tree);

  Long64_t nentries = tree->GetEntriesFast();
  Long64_t nb = 0;
  //nentries = 5000;


  char w_char[50];
  sprintf(w_char, "%s_w", argv[2]); 
  char pt_char[50];
  sprintf(pt_char, "%s_pt", argv[2]); 
  char comp_char[50];
  sprintf(comp_char, "%s_comp", argv[2]); 

  
  TH1F *weights = new TH1F(w_char, "", 50, 0, 0.01);
  TH1F *pt_med = new TH1F(pt_char, "", 50, 0, 1000);
  TH1F *pt_med_meas = new TH1F("pt_med_meas", "", 50, 0, 1000);
  TH1F *pt_comp = new TH1F(comp_char, "", 50, -1, 1);
  TH2F *med_comp = new TH2F("med_res", "", 100, -1000, 1000, 100, -1000, 1000);


  nentries = 5000;

  for (Long64_t jentry=0; jentry<nentries;jentry++) {
      std::cout << "Starting event" << jentry << std::endl;
      nb = tree->GetEntry(jentry);

      //Loading into TLorentzVector    
      TLorentzVector med; med.SetPtEtaPhiM(ev.ptMED, ev.etaMED, ev.phiMED, ev.mMED);
      TLorentzVector t1; t1.SetPtEtaPhiM(ev.ptTOP1, ev.etaTOP1, ev.phiTOP1, ev.mTOP1);
      TLorentzVector t2; t2.SetPtEtaPhiM(ev.ptTOP2, ev.etaTOP2, ev.phiTOP2, ev.mTOP2);
      TLorentzVector l1; l1.SetPtEtaPhiM(ev.ptlep1, ev.etalep1, ev.philep1, ev.mlep1);
      TLorentzVector l2; l2.SetPtEtaPhiM(ev.ptlep2, ev.etalep2, ev.philep2, ev.mlep2);
      TLorentzVector j1; j1.SetPtEtaPhiM(ev.ptb1, ev.etab1, ev.phib1, ev.mb1);
      TLorentzVector j2; j2.SetPtEtaPhiM(ev.ptb2, ev.etab2, ev.phib2, ev.mb2);
      TLorentzVector n1; n1.SetPtEtaPhiM(ev.ptnu1, ev.etanu1, ev.phinu1, ev.mnu1);
      TLorentzVector n2; n2.SetPtEtaPhiM(ev.ptnu2, ev.etanu2, ev.phinu2, ev.mnu2);
      
      //Collections of jets
      std::vector<TLorentzVector> jets; 
      std::vector<TLorentzVector> bjets; bjets.push_back(j1); bjets.push_back(j2);

      //MET
      TVector2 origMET(ev.ptMET*cos(ev.phiMET), ev.ptMET*sin(ev.phiMET));
      TVector2 MET(ev.ptMET*cos(ev.phiMET), ev.ptMET*sin(ev.phiMET));
      //The tops
      TVector2 top1, top2;
      //And the weight
      Float_t w = 0;
      Float_t step = 0.1; 
      Float_t lambda = 1;
      for(unsigned int jtrial = 0; jtrial < 1000; ++jtrial) {    
          theMass.startVariations(l1, l2, bjets, jets, MET, top1, top2, w);
          if(w > 0) { 
              std::cout << "Solution was found" << std::endl;
              if(jtrial == 0) break;
              weights->Fill(w);
              TVector2 ptmed(med.Pt()*cos(med.Phi()), med.Pt()*sin(med.Phi()));
              TVector2 ptmed_meas = -1.0 * (top1 + top2);
              pt_med->Fill(ptmed.Mod());
              pt_med_meas->Fill(ptmed_meas.Mod());
              pt_comp->Fill((top1.Mod() - ev.ptTOP1)/ev.ptTOP1);
              TVector2 med2 = origMET - MET;
              med_comp->Fill(ptmed.X(), med2.X());
              med_comp->Fill(ptmed.Y(), med2.Y());
              break;
          } 
          vector<double> grad; 
          theMass.massSolver->gradient(MET, j1 , j2 , l1, l2, 80.385, 80.385, 173.34, 173.34, grad, step, lambda);
          TVector2 theGrad(grad[0], grad[1]);
          MET = MET + theGrad;
      }
      
  }  

  weights->Scale(1.0/weights->Integral());
  pt_med->Scale(1.0/pt_med->Integral());
  pt_comp->Scale(1.0/pt_comp->Integral());
  TFile *foutput = new TFile("output.root", "UPDATE");
  foutput->cd();
  weights->Write();
  pt_med_meas->Write();
  pt_med->Write();
  pt_comp->Write();
  med_comp->Write();
  foutput->Close();
  f->Close();
  fshape->Close();
  return 1;

}
Example #10
0
void syst_MCeta(double E = 0.9 , int cut = 5){
  
  int typeMC = 10;
  
  if(E==7){
    cout<<"This systematic can't be applied to 7 TeV Data. Exiting now ..."<<endl;
    return;
  }
 
  
  ostringstream outstr("");
  outstr << "hyp" << 1 << "_niter" << 0 << "_cut" << cut << "_DataType" << 0;
  
  TString tbase = fileManager(3,typeMC,E,1,0,0,outstr.str());
  TFile* fbase = TFile::Open(tbase,"READ");
  
  cout<<"Base file : "<<tbase<<endl;
  
  if(fbase==0){
    cout<<"ERROR !! The base file is not present. Please run the code after making the base files ! Exiting now ..."<<endl;
    return;  
  }
  
  TH1F* hbase = (TH1F*) fbase->Get("unfolding/nch_data_corrected");
  if(hbase==0){
    cout<<"ERROR !! The base plot is void. Exiting now ..."<<endl;
    return;
  }
  
  
  //------------------------------------------------------------------------------------
  //-------------------   Doing the eta dependence systematic  -------------------------
  //------------------------------------------------------------------------------------
  //   base = D6T , syst = 413 (mtx=ProQ20)
  
  
  //getting the syst base file
  outstr.str("");
  outstr << "hyp" << 1 << "_niter" << 0 << "_cut" << cut << "_DataType" << 10;
  
  TString tsyst1 = fileManager(3,10,0.9,1,0,0,outstr.str());
  TFile* fsyst1 = TFile::Open(tsyst1,"READ");
  
  cout<<"syst1 file : "<<tsyst1<<endl;
  
  if(fsyst1==0){
    cout<<"ERROR !! The syst1 file is not present. Please run the code after making the syst1 files ! Exiting now ..."<<endl;
    return;  
  }
  
  TH1F* hsyst1 = (TH1F*) fsyst1->Get("unfolding/nch_data_corrected");
  if(hsyst1==0){
    cout<<"ERROR !! The syst1 plot is void. Exiting now ..."<<endl;
    return;
  }
  
  //getting the syst syst file
  outstr.str("");
  outstr << "hyp" << 1 << "_niter" << 0 << "_cut" << cut << "_DataType" << 10;
  
  TString tsyst2 = fileManager(3,10,0.9,1,413,-1,outstr.str());
  TFile* fsyst2 = TFile::Open(tsyst2,"READ");
  
  cout<<"syst2 file : "<<tsyst2<<endl;
  
  if(fsyst2==0){
    cout<<"ERROR !! The syst2 file is not present. Please run the code after making the syst2 files ! Exiting now ..."<<endl;
    return;  
  }
  
  TH1F* hsyst2 = (TH1F*) fsyst2->Get("unfolding/nch_data_corrected");
  if(hsyst2==0){
    cout<<"ERROR !! The syst2 plot is void. Exiting now ..."<<endl;
    return;
  }
  
  TH1F* factor = new TH1F("factor","factor",hbase->GetNbinsX(),hbase->GetXaxis()->GetXbins()->GetArray());
  if(E==0.9){
    for(int i=1;i<=hbase->GetNbinsX();++i){
      if(hsyst1->GetBinContent(i)!=0)
        factor->SetBinContent(i,hsyst2->GetBinContent(i) / hsyst1->GetBinContent(i));
      else
        factor->SetBinContent(i,1.);
    }
  }
  else if(E==2.36){
    double start = -0.5;
    double ratio = 1;
    if((getEdgeLastFilledBin(hsyst1) - start)!=0)
      ratio = (getEdgeLastFilledBin(hbase) - start) / (getEdgeLastFilledBin(hsyst1) - start);
    
    //part with no stretching
    for( int i = 1 ; i < hbase->GetXaxis()->FindFixBin(start) ; ++i ){
      if(hsyst1->GetBinContent(i)!=0)
        factor->SetBinContent(i,hsyst2->GetBinContent(i) / hsyst1->GetBinContent(i));
      else
        factor->SetBinContent(i,1.);
    }
    
    //part with stretching
    for( int i = hbase->GetXaxis()->FindFixBin(start) ; i <= hbase->GetNbinsX() ; ++i ){
      int bin = hsyst1->GetXaxis()->FindFixBin( (hbase->GetBinCenter(i)-start) / ratio  +  start);
      
      if(hsyst1->GetBinContent(bin)!=0)
        factor->SetBinContent(i,hsyst2->GetBinContent(bin) / hsyst1->GetBinContent(bin));
      else
        factor->SetBinContent(i,1.);
    }
  }
  
  TH1F* hsyst = (TH1F*) hbase->Clone("eta_syst");
  hsyst->Multiply(factor);
  
  TMoments* msyst = new TMoments(hsyst);
  msyst->ComputeMoments();
  msyst->print();
  
  
  //Making output file
  
  outstr.str("");
  outstr << "hyp" << 1 << "_niter" << 0 << "_cut" << cut << "_DataType" << 0;
  
  TString toutput = fileManager(3,typeMC,E,1,500,-1,outstr.str());
  TFile* foutput  = TFile::Open(toutput,"RECREATE");
  cout<<"Output file : " << toutput << endl;
  
  
  //Making kno plot
  double knomean = hsyst->GetMean();
  
  TString tkno = toutput;
  tkno.ReplaceAll("plots/","plots/current_b1_2/");
  cout<<"Opening for kno mean the file : "<<tkno<<endl;
  TFile* fkno = TFile::Open(tkno,"READ");
  if(fkno!=0){
    TMoments* mom_kno = (TMoments*) fkno->Get("unfolding/moments/moments");
    knomean = mom_kno->mean->GetMean();
  }
  else{
    cout<<"WARNING !! The file does not exist, taking the mean of the hist instead"<<endl;
  }
  
  
  TH1F* kno = new TH1F("kno_corrected","kno_corrected;z = n_{ch} / < n_{ch} >;#psi(z)",hsyst->GetNbinsX(),Divide(hsyst->GetXaxis()->GetXbins(),knomean));
  kno->Sumw2();
  /*for( int k = 60 ; k <= nch_corrected->GetNbinsX() ; ++k)
    nch_corrected->SetBinContent(k,0);*/
  for( int k = 1 ; k <= hsyst->GetNbinsX() ; ++k){
    kno->SetBinContent(k , knomean * hsyst->GetBinContent(k) / hsyst->Integral());
    kno->SetBinError(k , knomean * hsyst->GetBinError(k) / hsyst->Integral());
  }
  
  
  foutput->cd();
  foutput->mkdir("unfolding");
  foutput->cd("unfolding");
  factor->Write();
  
  hsyst->Write("nch_data_corrected");
  kno->Write();
  
  gDirectory->mkdir("moments");
  gDirectory->cd("moments");
  msyst->Write("moments");
  
  foutput->Close();
  
  
  
  
}
Example #11
0
void fitTF1(TCanvas *canvas, TH1F h, double XMIN_, double XMAX_, double dX_, double params[], Color_t LC_=kBlack) { //double& FWHM_, double& x0_, double& x1_, double& x2_, double& y0_, double& y1_, double& INT_, double& YIELD_) {
//TCanvas* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) {
//TF1* fitTF1(TH1F h, double HSCALE_, double XMIN_, double XMAX_) {
	gROOT->ForceStyle();
	RooMsgService::instance().setSilentMode(kTRUE);
	for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE);

	//TCanvas *canvas = new TCanvas(TString::Format("canvas_%s",h.GetName()),TString::Format("canvas_%s",h.GetName()),1800,1200);

	RooDataHist *RooHistFit = 0;
	RooAddPdf *model = 0;

	RooWorkspace w = RooWorkspace("w","workspace");

	RooRealVar x("mbbReg","mbbReg",XMIN_,XMAX_);
	RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1);
	RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2);
	kJES.setConstant(kTRUE);
	kJER.setConstant(kTRUE);

	TString hname = h.GetName();

	RooHistFit = new RooDataHist("fit_"+hname,"fit_"+hname,x,&h);


	RooRealVar YieldVBF = RooRealVar("yield_"+hname,"yield_"+hname,h.Integral());
	RooRealVar m("mean_"+hname,"mean_"+hname,125,100,150);
	RooRealVar s("sigma_"+hname,"sigma_"+hname,12,3,30);
	RooFormulaVar mShift("mShift_"+hname,"@0*@1",RooArgList(m,kJES));
	RooFormulaVar sShift("sShift_"+hname,"@0*@1",RooArgList(m,kJER));
	RooRealVar a("alpha_"+hname,"alpha_"+hname,1,-10,10);
	RooRealVar n("exp_"+hname,"exp_"+hname,1,0,100);
	RooRealVar b0("b0_"+hname,"b0_"+hname,0.5,0.,1.);
	RooRealVar b1("b1_"+hname,"b1_"+hname,0.5,0.,1.);
	RooRealVar b2("b2_"+hname,"b2_"+hname,0.5,0.,1.);
	RooRealVar b3("b3_"+hname,"b3_"+hname,0.5,0.,1.);
	
	RooBernstein bkg("signal_bkg_"+hname,"signal_bkg_"+hname,x,RooArgSet(b0,b1,b2));
	RooRealVar fsig("fsig_"+hname,"fsig_"+hname,0.7,0.0,1.0);
	RooCBShape sig("signal_gauss_"+hname,"signal_gauss_"+hname,x,mShift,sShift,a,n);

	model = new RooAddPdf("signal_model_"+hname,"signal_model_"+hname,RooArgList(sig,bkg),fsig);

	//RooFitResult *res = model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");
	model->fitTo(*RooHistFit,RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");

	//res->Print();
	//model->Print();
	
	canvas->cd();
	canvas->SetTopMargin(0.1);
	RooPlot *frame = x.frame();
// no scale
	RooHistFit->plotOn(frame);
	model->plotOn(frame,RooFit::LineColor(LC_),RooFit::LineWidth(2));//,RooFit::LineStyle(kDotted));
	model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(LC_),RooFit::LineWidth(2),RooFit::LineStyle(kDashed));
// with scale
//	RooHistFit->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent));
//	model->plotOn(frame,RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent),RooFit::LineWidth(1));
//	model->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(1),RooFit::LineStyle(kDashed),RooFit::Normalization(HSCALE_,RooAbsReal::NumEvent));
	 
	frame->GetXaxis()->SetLimits(50,200);
	frame->GetXaxis()->SetNdivisions(505);
	frame->GetXaxis()->SetTitle("M_{b#bar{b}} (GeV)");
	frame->GetYaxis()->SetTitle("Events");
	frame->Draw();
	h.SetFillColor(kGray);
	h.Draw("hist,same");
	frame->Draw("same");
	gPad->RedrawAxis();

	TF1 *tmp = model->asTF(x,fsig,x);
	//tmp->Print();

	double y0_ = tmp->GetMaximum();
	double x0_ = tmp->GetMaximumX();
	double x1_ = tmp->GetX(y0_/2.,XMIN_,x0_);
	double x2_ = tmp->GetX(y0_/2.,x0_,XMAX_);
	double FWHM_ = x2_-x1_;
	double INT_ = tmp->Integral(XMIN_,XMAX_);
	double YIELD_= YieldVBF.getVal();
	double y1_ = dX_*0.5*y0_*(YieldVBF.getVal()/tmp->Integral(XMIN_,XMAX_));

	params[0] = x0_;
	params[1] = x1_;
	params[2] = x2_;
	params[3] = y0_;
	params[4] = y1_;
	params[5] = FWHM_;
	params[6] = INT_;
	params[7] = YIELD_;

	//cout<<"Int = "<<tmp->Integral(XMIN_,XMAX_)<<", Yield = "<<YieldVBF.getVal()<<", y0 = "<<y0_<<", y1 = "<<y1_ <<", x0 = "<< x0_ << ", x1 = "<<x1_<<", x2 = "<<x2_<<", FWHM = "<<FWHM_<<endl;

	TLine ln = TLine(x1_,y1_,x2_,y1_);
	ln.SetLineColor(kMagenta+3);
	ln.SetLineStyle(7);
	ln.SetLineWidth(2);
	ln.Draw();
	
	canvas->Update();
	canvas->SaveAs("testC.png");
	
//	tmp->Delete();
//	frame->Delete();
//	res->Delete();
//	TF1 *f1 = model->asTF(x,fsig,x);
//	return f1;
	
	////tmp->Delete();
	////ln->Delete();
	////model->Delete();
	////RooHistFit->Delete();
	////w->Delete();
	////YieldVBF->Delete();
	////frame->Delete();
	////res->Delete();
	//delete tmp;
	//delete ln;
	//delete model;
	//delete RooHistFit;
	//delete w;
	//delete YieldVBF;
	//delete frame;
	//delete res;

//	return canvas;
}
Example #12
0
void GenerateSusyFile( double flatDummyErr = 0.00001 ) {  //-- flat error in %.  If negative, use MC stat err.

  // define chain

  TChain chainT2tt("tree");
  chainT2tt.Add("tinyTrees/T2tt.root");

  gROOT->Reset();

  const int nJetsCut = 3 ;     // #jets >= nJetsCut
  const int MTbCut   = 0 ;   // MTb cut


  // get binning definition from "Binning.txt"

  int in_version, in_nBinsVar1, in_nBinsVar2, in_nBinsBjets ;
  TString label, in_Var1, in_Var2, in_Var3 ;

  ifstream inBinning ;
  inBinning.open("Binning.txt") ;

  inBinning >> label >> in_Var1 ;
  inBinning >> label >> in_Var2 ;
  inBinning >> label >> in_Var3 ;

  inBinning >> label >> in_nBinsVar1 ;
  inBinning >> label >> in_nBinsVar2 ;
  inBinning >> label >> in_nBinsBjets ;

  const int nBinsVar1  = in_nBinsVar1 ;
  const int nBinsVar2  = in_nBinsVar2 ;
  const int nBinsBjets = in_nBinsBjets ;

  float Mbins[nBinsVar1+1] ;
  float Hbins[nBinsVar2+1] ;

  for ( int i = 0 ; i < nBinsVar1 ; i++ ) {
    inBinning >> label >> Mbins[i] ;
    if ( i > 0 && Mbins[i] < Mbins[i-1] ) { cout << "\n\n Mismatch in Var1 binning, check Binning.txt! \n\n" ; return ; }
  }

  for ( int i = 0 ; i < nBinsVar2 ; i++ ) {
    inBinning >> label >> Hbins[i] ;
    if ( i > 0 && Hbins[i] < Hbins[i-1] ) { cout << "\n\n Mismatch in Var2 binning, check Binning.txt! \n\n" ; return ; }
  }

  const TString sVar1 = in_Var1 ;
  const TString sVar2 = in_Var2 ;

  TString aVar1 = in_Var1 ;
  TString aVar2 = in_Var2 ;
  if ( aVar1 == "MET/sqrt(HT)" ) aVar1 = "MET_div_sqrtHT" ;
  if ( aVar2 == "MET/sqrt(HT)" ) aVar2 = "MET_div_sqrtHT" ;

  TString s2DVars = sVar2;
  s2DVars += ":";
  s2DVars += sVar1;

  Mbins[nBinsVar1] = 999999. ;
  Hbins[nBinsVar2] = 999999. ;

  inBinning >> label >> in_version ;
  const int version = in_version ;

  if ( !label.Contains("version") ) {
    cout << "\n\n Found inconsistency in Binning.txt, check number of bins and Var1 and Var2 lower bounds\n\n" << endl ;
    return ;
  }

  inBinning.close();



  TString cBbins[nBinsBjets];
  
  cBbins[0] = "nB==1" ;

  if ( nBinsBjets == 2 ) {
    cBbins[1] = "nB>=2" ;
  }
  else if ( nBinsBjets == 3 ) {
    cBbins[1] = "nB==2" ;    
    cBbins[2] = "nB>=3" ;
  }
  else if ( nBinsBjets == 4 ) {
    cBbins[1] = "nB==2" ;    
    cBbins[2] = "nB==3" ;
    cBbins[3] = "nB>=4" ;
  }
  else {
    cout << "\n\n This number of #b-jets bins is not implemented! Exiting ... " << endl ;
    return ;
  }

  // jet pt thresholds
  double minLeadJetPt = 70. ;
  double min3rdJetPt = 50. ;


  int minGlMass = 200 ;
  int maxGlMass = 1400 ;
  double dummyCorr = 1. ;
  long dummyEvts = 10000 ;

  ofstream inFile;
  char outfile[10000] ;
  sprintf( outfile, "datfiles/T2tt-%s-%d-%s-%d-nB%d-v%d.dat", aVar1.Data(), nBinsVar1, aVar2.Data(), nBinsVar2, nBinsBjets, version ) ;
  inFile.open( outfile );



  // TH1F* ht = new TH1F("ht","ht",10,0,10000);
  TString cutsSig   = "minDelPhiN>4&&nMu==0&&nEl==0&&";
  TString cutsSLSig = "MT>100&&minDelPhiN>4&&( (nMu==1&&nEl==0) || (nEl==1&&nMu==0) )&&";
  TString cutsSL    = "MT<100&&minDelPhiN>4&&( (nMu==1&&nEl==0) || (nEl==1&&nMu==0) )&&";
  TString cutsLDP   = "minDelPhiN<4&&nMu==0&&nEl==0&&";

  char commoncuts[10000] ;
  sprintf( commoncuts, "maxChNMultDiff<40&&pfOcaloMET<2.0&&nJets>=%d&&MT_bestCSV>%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)&&",
           nJetsCut, MTbCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;

  cutsSig   += commoncuts ;
  cutsSLSig += commoncuts ;
  cutsSL    += commoncuts ;
  cutsLDP   += commoncuts ;


  TH2F* h_susy_sig[10] ;
  TH2F* h_susy_slsig[10] ;
  TH2F* h_susy_sl[10] ;
  TH2F* h_susy_ldp[10] ;
  for ( int bi=0; bi<nBinsBjets; bi++ ) {
     char hname[1000] ;
     sprintf( hname, "h_susy_sig_%db", bi+1 ) ;
     h_susy_sig[bi] = new TH2F( hname, hname, nBinsVar1, Mbins, nBinsVar2, Hbins ) ;
     h_susy_sig[bi] -> Sumw2() ;
     sprintf( hname, "h_susy_slsig_%db", bi+1 ) ;
     h_susy_slsig[bi] = new TH2F( hname, hname, nBinsVar1, Mbins, nBinsVar2, Hbins ) ;
     h_susy_slsig[bi] -> Sumw2() ;
     sprintf( hname, "h_susy_sl_%db", bi+1 ) ;
     h_susy_sl[bi] = new TH2F( hname, hname, nBinsVar1, Mbins, nBinsVar2, Hbins ) ;
     h_susy_sl[bi] -> Sumw2() ;
     sprintf( hname, "h_susy_ldp_%db", bi+1 ) ;
     h_susy_ldp[bi] = new TH2F( hname, hname, nBinsVar1, Mbins, nBinsVar2, Hbins ) ;
     h_susy_ldp[bi] -> Sumw2() ;
  }

  
  // the following is just an example, to run on a bunch of points
  // in the T2tt plane

  int mGls[9] = {350,450,500,550,600,650,700,750,800};
  int mLsps[9] = {0,0,0,0,0,0,0,0,0};

  for ( int iGl = 0 ; iGl < 9 ; iGl++ ) {

    int mGl = mGls[iGl] ;
    int mLsp = mLsps[iGl] ;

    TString cutSMS = "mgluino>";
    cutSMS += mGl-1;
    cutSMS += "&&mgluino<";
    cutSMS += mGl+1;
    cutSMS += "&&mlsp>";
    cutSMS += mLsp-1;
    cutSMS += "&&mlsp<";
    cutSMS += mLsp+1;


    TH1F *dummyHist = new TH1F("dummyHist","",100,0.,10000.);
    chainT2tt.Project("dummyHist","MET",cutSMS);

    inFile << mGl << " " << mLsp << " " << dummyHist->Integral() << " " ;
    printf(" mGl=%4d, mLsp=%4d\n", mGl, mLsp ) ; cout << flush ;

    cutSMS += "&&";

    
    printf("\n\n") ;
    for (int k = 0 ; k < nBinsBjets ; k++) {
      
      TString cut = cBbins[k] ;
      
      TString allSigCuts   = cutSMS+cutsSig+cut ;
      TString allSLSigCuts = cutSMS+cutsSLSig+cut ;
      TString allSLCuts    = cutSMS+cutsSL+cut ;
      TString allLDPCuts   = cutSMS+cutsLDP+cut ;
      
      char hname[1000] ;
      
      sprintf( hname, "h_susy_sig_%db", k+1 ) ;
      chainT2tt.Project( hname,s2DVars,allSigCuts);
      printf("   mGl=%d, mLsp=%d, nBjets = %d,  SIG selection %9.1f events.\n", mGl, mLsp, k+1, h_susy_sig[k]->Integral() ) ; cout << flush ;
      
      sprintf( hname, "h_susy_slsig_%db", k+1 ) ;
      chainT2tt.Project( hname,s2DVars,allSLSigCuts);
      printf("   mGl=%d, mLsp=%d, nBjets = %d,  SL Sig selection %6.1f events.\n", mGl, mLsp, k+1, h_susy_slsig[k]->Integral() ) ; cout << flush ;
      
      sprintf( hname, "h_susy_sl_%db", k+1 ) ;
      chainT2tt.Project( hname,s2DVars,allSLCuts);
      printf("   mGl=%d, mLsp=%d, nBjets = %d,  SL  selection %9.1f events.\n", mGl, mLsp, k+1, h_susy_sl[k]->Integral() ) ; cout << flush ;
      
      sprintf( hname, "h_susy_ldp_%db", k+1 ) ;
      chainT2tt.Project( hname,s2DVars,allLDPCuts);
      printf("   mGl=%d, mLsp=%d, nBjets = %d,  LDP selection %9.1f events.\n", mGl, mLsp, k+1, h_susy_ldp[k]->Integral() ) ; cout << flush ;
      
    } // k (nBjets)
    printf("\n\n") ;
    
    printf("----------------\n") ;
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  printf ( " Raw MC counts: mGl=%d, mLsp=%d: Var1,Var2 (%d,%d) nb=%d   SIG = %9.0f, SLSIG =%9.0f, SL=%9.0f, LDP=%9.0f\n",
		   mGl, mLsp, i+1, j+1, k+1,
		   h_susy_sig[k]  -> GetBinContent( i+1, j+1 ),
		   h_susy_slsig[k]-> GetBinContent( i+1, j+1 ),
		   h_susy_sl[k]   -> GetBinContent( i+1, j+1 ),
		   h_susy_ldp[k]  -> GetBinContent( i+1, j+1 )  ) ;
	  
	} // k
	printf("----------------\n") ;
      } // j
    } // i
    printf("\n\n") ;
    
    
    // 0-lep yields
    
    float totalSUSYyield = 0;
    printf("----------------\n") ;
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  inFile << h_susy_sig[k]  -> GetBinContent( i+1, j+1 ) << " " ;
	  
	  totalSUSYyield += h_susy_sig[k] -> GetBinContent( i+1, j+1 );
	    	     
	} // k
      } // j
    } // i
    printf("Total SUSY yield within current binning = %9.1f",totalSUSYyield);
    printf("\n\n") ;
    

    // SLSig yields:
    printf("----------------\n") ;
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  inFile << h_susy_slsig[k]-> GetBinContent( i+1, j+1 ) << " " ;
	  
	}
      }
    }
    

    // SL yields:
    printf("----------------\n") ;
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  inFile << h_susy_sl[k]   -> GetBinContent( i+1, j+1 ) << " " ;
	  
	  
	}
      }
    }
    

    // Ldp yields:
    printf("----------------\n") ;
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  inFile << h_susy_ldp[k]  -> GetBinContent( i+1, j+1 ) << " " ;

	  double nsel_sig   = h_susy_sig[k]  -> GetBinContent( i+1, j+1 ) ;
	  double nsel_slsig = h_susy_slsig[k]-> GetBinContent( i+1, j+1 ) ;
	  double nsel_sl    = h_susy_sl[k]   -> GetBinContent( i+1, j+1 ) ;
	  double nsel_ldp   = h_susy_ldp[k]  -> GetBinContent( i+1, j+1 ) ;
	  
	  double nevt_err_sig    = 1 ;
	  double nevt_err_slsig  = 1 ;
	  double nevt_err_sl     = 1 ;
	  double nevt_err_ldp    = 1 ;
	  
	  if ( nsel_sig    > 0. ) { nevt_err_sig   = sqrt(nsel_sig)   ; }
	  if ( nsel_slsig  > 0. ) { nevt_err_slsig = sqrt(nsel_slsig) ; }
	  if ( nsel_sl     > 0. ) { nevt_err_sl    = sqrt(nsel_sl )   ; }
	  if ( nsel_ldp    > 0. ) { nevt_err_ldp   = sqrt(nsel_ldp)   ; }
	  
	  printf ( "events: mGl=%d, mLsp=%d: Var1,Var2 (%d,%d) nb=%d   SIG = %6.1f +/- %4.1f,   SLSIG=%6.1f +/- %4.1f,   SL=%6.1f +/- %4.1f,   LDP=%6.1f +/- %4.1f\n",
		   mGl, mLsp, i+1, j+1, k+1,
		      h_susy_sig[k]  -> GetBinContent( i+1, j+1 ), nevt_err_sig,
		      h_susy_slsig[k]-> GetBinContent( i+1, j+1 ), nevt_err_slsig,
		      h_susy_sl[k]   -> GetBinContent( i+1, j+1 ), nevt_err_sl,
		      h_susy_ldp[k]  -> GetBinContent( i+1, j+1 ), nevt_err_ldp  ) ;
	     	     
	}
      }
    }
    
    


    //----------------------------------------------------------------------------
    
    printf("----------------\n") ;
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  if ( flatDummyErr < 0 ) {
	    
	    //-- compute approximate stat err.
	    //-- This is 100* sig_eff / eff = 100 * [sqrt(sel)/N]/[sel/N] = 100/sqrt(sel).
	    double nsel_sig   = h_susy_sig[k]  -> GetBinContent( i+1, j+1 ) ;
	    double nsel_slsig = h_susy_slsig[k]-> GetBinContent( i+1, j+1 ) ;
	    double nsel_sl    = h_susy_sl[k]   -> GetBinContent( i+1, j+1 ) ;
	    double nsel_ldp   = h_susy_ldp[k]  -> GetBinContent( i+1, j+1 ) ;
	    double frerr_sig   = 100 ;
	    double frerr_slsig = 100 ;
	    double frerr_sl    = 100 ;
	    double frerr_ldp   = 100 ;
	    if ( nsel_sig   > 0. ) { frerr_sig   = 100./sqrt(nsel_sig)    ; }
	    if ( nsel_slsig > 0. ) { frerr_slsig = 100./sqrt(nsel_slsig ) ; }
	    if ( nsel_sl    > 0. ) { frerr_sl    = 100./sqrt(nsel_sl )    ; }
	    if ( nsel_ldp   > 0. ) { frerr_ldp   = 100./sqrt(nsel_ldp)    ; }
	    
	    inFile << frerr_sig << " " << frerr_slsig << " " << frerr_sl << " " << frerr_ldp << " " ;
	    
	    printf ( " MC sig_eff/eff (%%): mGl=%d, mLsp=%d: Var1,Var2 (%d,%d) nb=%d   SIG = %5.1f,   SLSIG=%5.1f,   SL=%5.1f,   LDP=%5.1f\n",
		     mGl, mLsp, i+1, j+1, k+1,
		     frerr_sig, frerr_slsig, frerr_sl, frerr_ldp ) ;
	  }
	}
	printf("----------------\n") ;
      }
    }
    printf("\n\n") ;
    
    
    // dump the errors to file
    
    
    // Sig uncertainty
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  if ( flatDummyErr >= 0 ) {
	    inFile << flatDummyErr << " " ;
	  }
	  else {
	    inFile << frerr_sig << " " ;
	  }
	  
	}
      }
    }
    

    // SLSig uncertainty
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  if ( flatDummyErr >= 0 ) {
	    inFile << flatDummyErr << " " ;
	  }
	  else {
	    inFile << frerr_slsig << " " ;
	  }
	  
	}
      }
    }
    
    
    // SL uncertainty
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  if ( flatDummyErr >= 0 ) {
	    inFile << flatDummyErr << " " ;
	  }
	  else {
	    inFile << frerr_sl << " " ;
	  }
	  
	}
      }
    }
    
    
    // Ldp uncertainty
    for (int i = 0 ; i < nBinsVar1 ; i++) {
      for (int j = 0 ; j < nBinsVar2 ; j++) {
	for (int k = 0 ; k < nBinsBjets ; k++) {
	  
	  if ( flatDummyErr >= 0 ) {
	    inFile << flatDummyErr << " " ;
	  }
	  else {
	    inFile << frerr_ldp << " " ;
	  }
	  
	}
      }
    }
    
    
    inFile << endl ;
      
  } // end loop on signal points


  // print out header line:
  inFile << "Using Var2 bins:  " ;
  for (int j = 0 ; j <= nBinsVar2 ; j++ ) {
    inFile << Hbins[j] ;
    if ( j < nBinsVar2 ) inFile << "-" ;
  }

  inFile << "\t Using Var1 bins: " ;
  for (int i = 0 ; i <= nBinsVar1 ; i++ ) {
    inFile << Mbins[i] ;
    if ( i < nBinsVar1 ) inFile << "-" ;
  }
  inFile << endl ;


  return;

}
Example #13
0
void calccorr_sandv(string t){
float const PI = acos(-1.0);
const int ncent = 6;
const int npt = 10;
//TFile *f=TFile::Open("merged_AnaMWGppmb.root");
TFile *f=TFile::Open("merged.root");
//TFile *f=TFile::Open("merged_AnaMWGppfvtxand.root");
//TFile *f=TFile::Open("merged_AnaMWGppfvtxor.root");
TH1F* kforebbcw[ncent][npt];
TH1F* hforebbcw[ncent][npt];
TH1F* kbackbbcw2[ncent][npt];
TH1F* kforebbcw_In;
TH1F* hforebbcw_In;
TH1F* kbackbbcw2_In;
double ptbin[npt+1] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
//double centbin[ncent+1] = {200,8,7,6,5,4,3,2,1,0};
double centbin[ncent+1] = {200,5,4,3,2,1,0};
TString type = t.c_str();
if(type=="ptIn25_4"){
double selptbin[] = {2.5,4.0};
double selcentbin[] = {200,7,6,5,4,3,2,1,0};
}
else if(type=="ptIn"){
double selptbin[] = {1.0,3.0};
double selcentbin[] = {200,7,6,5,4,3,2,1,0};
}
else if(type=="ptcoarser"){
double selptbin[] = {0.2,1.0,2.0,3.0,5.0};
double selcentbin[] = {200,7,6,5,4,3,2,1,0};
}
else if(type=="ptfiner"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {200,7,6,5,4,3,2,1,0};
}
else if(type=="centIn"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {200,0};
}
else if(type=="ptccentc"){
double selptbin[] = {0.2,5.0};
double selcentbin[] = {200,0};
}
else{exit(0);};

/*double ptmin = 1.0; double ptmax = 3.0;//has to be boundary
for(int ipt=0; ipt<npt; ipt++){
if(ptmin >= ptbin[ipt] && ptmin < ptbin[ipt+1]){int xptmin = ipt; continue;}
if(ptmax >= ptbin[ipt] && ptmax < ptbin[ipt+1]){int xptmax = ipt; continue;}
}*/
  ofstream fsout(Form("stat_%s.txt",type.Data()));
  ofstream fout(Form("tryc1_c2_%s.dat",type.Data()));
for(int icent=0; icent<ncent; icent++){
for(int ipt=0; ipt<npt; ipt++){
kforebbcw[icent][ipt] = (TH1F*)f->Get(Form("kforenorthbbcw_%d_%d",icent,ipt));
htemp = (TH1F*)f->Get(Form("kforesouthbbcw_%d_%d",icent,ipt));
kforebbcw[icent][ipt]->Add(htemp);
hforebbcw[icent][ipt] = (TH1F*)f->Get(Form("hforenorthbbcw_%d_%d",icent,ipt));
htemp = (TH1F*)f->Get(Form("hforesouthbbcw_%d_%d",icent,ipt));
hforebbcw[icent][ipt]->Add(htemp);
kbackbbcw2[icent][ipt] = (TH1F*)f->Get(Form("kbacknorthbbcw2_%d_%d",icent,ipt));
htemp = (TH1F*)f->Get(Form("kbacksouthbbcw2_%d_%d",icent,ipt));
kbackbbcw2[icent][ipt]->Add(htemp);
}
}
int ncent_a = sizeof(selcentbin)/sizeof(double)-1;
int npt_a = sizeof(selptbin)/sizeof(double)-1;
for(int icent_a=0;icent_a<ncent_a;icent_a++){
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a] == centbin[icent_b]) break;
int xcentmin = icent_b;
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a+1] == centbin[icent_b]) break;
int xcentmax = icent_b;
if((xcentmin == ncent+1) || (xcentmax == ncent+1)) exit(0);
for(int ipt_a=0;ipt_a<npt_a;ipt_a++){
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a] == ptbin[ipt_b]) break;
int xptmin = ipt_b;
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a+1] == ptbin[ipt_b]) break;
int xptmax = ipt_b;
if((xptmin == npt+1) || (xptmax == npt+1)) exit(0);
cout<<xcentmin<<"\t"<<xcentmax<<"\t"<<endl;
cout<<xptmin<<"\t"<<xptmax<<"\t"<<endl;
kforebbcw_In = (TH1F*)kforebbcw[xcentmin][xptmin]->Clone();
hforebbcw_In = (TH1F*)hforebbcw[xcentmin][xptmin]->Clone();
kbackbbcw2_In = (TH1F*)kbackbbcw2[xcentmin][xptmin]->Clone();
kforebbcw_In->Reset();
hforebbcw_In->Reset();
kbackbbcw2_In->Reset();
for(int icent=xcentmin; icent<xcentmax; icent++){
for(int ipt=xptmin; ipt<xptmax; ipt++){
kforebbcw_In->Add(kforebbcw[icent][ipt]);
hforebbcw_In->Add(hforebbcw[icent][ipt]);
kbackbbcw2_In->Add(kbackbbcw2[icent][ipt]);
}
}
kforebbcw_In->Rebin(2);
hforebbcw_In->Rebin(2);
kbackbbcw2_In->Rebin(2);


TH1F* hpp;
TH1F* hbackpp;
  hpp = (TH1F*)kforebbcw_In->Clone();
  hbackpp = (TH1F*)kbackbbcw2_In->Clone();
  float nbackpp = hbackpp->Integral()/2.0/PI;
  float nforepp = hpp->Integral()/2.0/PI;
  //float ntrig0 = ptforedis_0->Integral(11,30);
   for(int i=0; i<20; i++){
     float pp_cont = 1.0*hpp->GetBinContent(i+1);
     //float pp0_err = 1.0*hpp->GetBinError(i+1);
     float weight2 = sqrt(1.0*hforebbcw_In->GetBinContent(i+1));

     float backpp_cont = 1.0*hbackpp->GetBinContent(i+1);
    
     float con = pp_cont/backpp_cont*nbackpp/nforepp;
     float err = weight2/backpp_cont*nbackpp/nforepp;

     hpp->SetBinContent(i+1, con);
     hpp->SetBinError(i+1, err);

     if(i==0) fsout<<pp_cont<<" "<<weight2<<" "<<con<<" "<<err<<endl;
   }
  TF1 *fun0 = new TF1("fun0","[0]*(1+2*[1]*cos(x)+2*[2]*cos(2*x)+2*[3]*cos(3*x)+2*[4]*cos(4*x))", -0.5*PI, 1.5*PI);

  fun0->SetLineColor(1);
  hpp->Fit("fun0","NORQ");

  TF1 *fun1 = new TF1("fun1","[0]*(1+2*[1]*cos(x))",   -0.5*PI, 1.5*PI);
  TF1 *fun2 = new TF1("fun2","[0]*(1+2*[1]*cos(2*x))", -0.5*PI, 1.5*PI);
  TF1 *fun3 = new TF1("fun3","[0]*(1+2*[1]*cos(3*x))", -0.5*PI, 1.5*PI);
  TF1 *fun4 = new TF1("fun4","[0]*(1+2*[1]*cos(4*x))", -0.5*PI, 1.5*PI);

  fout<<fun0->GetParameter(1)<<" "<<fun0->GetParError(1)<<" "
 // <<-fun0->GetParameter(2)/fun0->GetParameter(1)<<" "<<fun0->GetParameter(2)/fun0->GetParameter(1)*(sqrt((fun0->GetParError(2)/fun0->GetParameter(2))**2+(fun0->GetParError(1)/fun0->GetParameter(1))**2))<<" "
  <<fun0->GetParameter(2)<<" "<<fun0->GetParError(2)<<" "
  <<fun0->GetParameter(3)<<" "<<fun0->GetParError(3)<<endl;
}
}
  fout.close();
  fsout.close();

/*  
  cout<<"*************** v2 ***********"<<endl;
  float v2_0 = funvn0->GetParameter(1)/(zym_pp0 + funvn0->GetParameter(0));
  float v2_1 = funvn1->GetParameter(1)/(zym_pp1 + funvn1->GetParameter(0));
  float v2_2 = funvn2->GetParameter(1)/(zym_pp2 + funvn2->GetParameter(0));
  float v2_3 = funvn3->GetParameter(1)/(zym_pp3 + funvn3->GetParameter(0));
  

  cout<<v2_0<<" "<<v2_1<<" "<<v2_2<<" "<<v2_3<<endl;
 
  
  cout<<funvn0->GetParameter(0)*funvn0->GetParameter(1)<<" "
      <<funvn1->GetParameter(0)*funvn1->GetParameter(1)<<" "
      <<funvn2->GetParameter(0)*funvn2->GetParameter(1)<<" "
      <<funvn3->GetParameter(0)*funvn3->GetParameter(1)<<endl;
  

  cout<<"*************** v2 ***********"<<endl;
  cout<<funvn0->GetParameter(2)<<" "<<funvn1->GetParameter(2)<<" "<<funvn2->GetParameter(2)<<" "<<funvn3->GetParameter(2)<<endl;

  cout<<"*************** v3 ***********"<<endl;
  cout<<funvn0->GetParameter(3)<<" "<<funvn1->GetParameter(3)<<" "<<funvn2->GetParameter(3)<<" "<<funvn3->GetParameter(3)<<endl;
*/
}
Example #14
0
void dataCardSM(Int_t channel, Int_t cat, Int_t year, Int_t dataset, TString mass, TString path, TString tag, Int_t option=0){

  if(tag!="")path=path+"_"+tag;

  TString ChannelName;
  if(channel==1)ChannelName="muTau";
  else if(channel==2)ChannelName="eleTau";
  else return;
  cout<<"ChannelName "<<ChannelName<<endl;
  
  if(channel==1){
    TauMuPlotter * analysis=0;
    
    if(year==2011){
      analysis=configTauMu2011("analysis",path);
    }
    if(year==2012){
      if(dataset==1)analysis=configTauMu2012AB("analysis",path);
      if(dataset==2)analysis=configTauMu2012ABC("analysis",path);
      if(dataset==3)analysis=configTauMu2012D("analysis",path);
      if(dataset==4)analysis=configTauMu2012ABCD("analysis",path);
      if(dataset==5)analysis=configTauMu2012Summer13("analysis",path);
      if(dataset==6)analysis=configTauMu2012Summer13ReReco("analysis",path);
    }
  }
  if(channel==2){
    TauElePlotter * analysis=0;

    if(year==2011){
      analysis=configTauEle2011("analysis",path);
    }
    if(year==2012){
      if(dataset==1)analysis=configTauEle2012AB("analysis",path);
      if(dataset==2)analysis=configTauEle2012ABC("analysis",path);
      if(dataset==3)analysis=configTauEle2012D("analysis",path);
      if(dataset==4)analysis=configTauEle2012ABCD("analysis",path);
      if(dataset==5)analysis=configTauEle2012Summer13("analysis",path);
    }
  }
  
 
  bool Blind=0;
  analysis->nbins_=0;
  analysis->Isocat_=1;
  analysis->MTcat_=1; 
  analysis->Chcat_=1; 

  cout<<endl<<"optimizaion with option "<<option<<endl;

//   ///Simple isolation scan
//   char isocutoption[100];
//   if(option<10){
//     sprintf(isocutoption,"(tauisomva2raw>%.3f)",0.80+0.02*option);
//     analysis->tauIsoCutQCD_="(tauisomva2raw>0.5)";
//   }else if(option<20){
//     sprintf(isocutoption,"(tauiso3hitraw<%.3f)",2.2-0.2*(option-10));
//     analysis->tauIsoCutQCD_="(tauiso3hitraw<6.0)";
//   }
//   analysis->tauIsoCut_=isocutoption;

  
//   ////////////////////////optimization of mT cut
//   if(option>0){
//     //use the digits of the option for each variable
//     analysis->mTCut_=5+abs(option)*5;
//   }
//   //////////////////////////////////////////////////

  ////////////////////////optimization of 1Jet : with 2 tau pT categories
  if(option>0){

    //optimize tau pT without higgs pT cut
    if((option/10)==0)analysis->taupTCut_ = 20+(option)*5;//1->6
    ///optimize higgs pT cut at low Tau pT
    if((option/10)==1)analysis->higgspTCutLow_=(option%10-1)*20;//11->18
    ///optimize higgs pT cut at high Tau pT
    if((option/10)==2)analysis->higgspTCutHigh_=(option%10-1)*20;//21->28

    //optimize tau and higgs pT cuts at the same time
    if((option/100)==1){
      analysis->taupTCut_ = 20+((option%100)/10 - 1)*5;//first digit: 1->6
      analysis->higgspTCutHigh_=(option%10-1)*20;//second digit: 1->8
    }

  }
  //////////////////////////////////////////////////

  analysis->scaleSamplesLumi();
  TFile output(ChannelName+"_SM"+(long)cat+"_"+mass+"_"+tag+".root","recreate");
  for(long sm=0; sm<NCAT; sm++){
    if(cat==9)continue;
    if(cat==13 && (sm==2 || sm==4))continue;//skip boost_low and vbf
    if(cat==20 && (sm==3 || sm==4))continue;//skip boost_high and vbf
    if(cat==23 && (sm==4))continue;//skip vbf
    if(cat==15 && (sm==2 || sm==3))continue;//skip boost_low and boost_high

    TDirectory* dir = output.mkdir(ChannelName+"_"+catdirname[sm]);  
    gROOT->cd();

//     if(sm==0 || sm==1){
//       analysis->plotvar_="ditaumass";//switch to visible mass for 0jet
//       analysis->setVariableBinning(NXBINS0JET,xbinsValues0Jet);
//     }else{
    analysis->plotvar_=mass;
    if(sm==4)analysis->setVariableBinning(NXBINSVBF,xbinsValuesVBF);
    else analysis->setVariableBinning(NXBINS,xbinsValues);
    //    }
    
      ///Category definition
    analysis->extrasel_ = analysis->getSMcut(sm);
    //analysis->extrasel_ = analysis->getSMcutOpt(sm);//possible higgs pT cuts
    //analysis->extrasel_ = analysis->getSMcutSummer13(sm);//use higgs pT < 20 in control regions


//     if(option==0)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==0)";
//     if(option==1)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==1)";
//     if(option==10)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==10)";

//     //for ZTT decaymode ratios
//     analysis->mTCut_=40;
//     if(20<=option&&option<30) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==0)"+"*("+(long)(20+(option-20)*5)+"<taupt&&taupt<"+(long)(20+(option-20+1)*5)+")";
//     if(30<=option&&option<40) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==1)"+"*("+(long)(20+(option-30)*5)+"<taupt&&taupt<"+(long)(20+(option-30+1)*5)+")";
//     if(40<=option&&option<50) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==10)"+"*("+(long)(20+(option-40)*5)+"<taupt&&taupt<"+(long)(20+(option-40+1)*5)+")";


    TH1F* QCD = 0;
    if(channel==1){//mu-tau
      if(year==2011){
	if(sm==0 || sm==2 ) QCD=analysis->getQCDInc();
	if(sm==1 || sm==3 ) QCD=analysis->getQCDIncLooseShape();
	if(sm==4)           QCD=analysis->getQCDMike();
      }
      if(year==2012){
	if(sm==0) QCD=analysis->getQCDIncWNJet(); 
	if(sm==1) QCD=analysis->getQCDMuIsoSM(); 
	if(sm==2) QCD=analysis->getQCDIncLowPt(); 
	if(sm==3) QCD=analysis->getQCDMuIsoSM(); 
	if(sm==4) QCD=analysis->getQCDVBFHCP();
      }
    }
    if(channel==2){//e-tau
      if(year==2011){
	if(sm==0 || sm==2) QCD=analysis->getQCDInc();
	if(sm==1 || sm==3) QCD=analysis->getQCDIncLooseShape();
	if(sm==4)          QCD=analysis->getQCDMike();
      }
      if(year==2012){
	if(sm==0) QCD=analysis->getQCDIncWNJet(); 
	if(sm==1) QCD=analysis->getQCDMuIsoSM();
	if(sm==2) QCD=analysis->getQCDIncLowPt();//getQCDIncWNJet(); //
	if(sm==3) QCD=analysis->getQCDIncHighPt();
	if(sm==4) QCD=analysis->getQCDVBFHCP2();
      }
    }
    QCD->SetName("QCD");


    TH1F* W = 0;
    if(channel==1){//mu-tau
      if(year==2011){
	if(sm==0 || sm==1) W = analysis->getWJetsInc();
	if(sm==2 || sm==3) W = analysis->getWJetsInc();
	if(sm==4) W = analysis->getW3JetsVBF();
      }
      if(year==2012){
	if(sm==0) W = analysis->getWJetsNJet();
	if(sm==1) W = analysis->getWJetsNJetNoChCut();
	if(sm==2) W = analysis->getWJetsNJet();
	if(sm==3) W = analysis->getWJetsNJetNoChCut();
	if(sm==4) W = analysis->getWJetsNJetVBFHCP(); 
      }
    }
    if(channel==2){//e-tau
      if(year==2011){
	if(sm==0 || sm==1) W = analysis->getWJetsInc();
	if(sm==2 || sm==3) W = analysis->getWJetsInc();
	if(sm==4)  W = analysis->getW3JetsVBF();
      }
      if(year==2012){
	if(sm==0) W = analysis->getWJetsNJet();
	if(sm==1) W = analysis->getWJetsNJetNoChCut();
	if(sm==2) W = analysis->getWJetsNJetNoChCut();
	if(sm==3) W = analysis->getWJetsNJetNoChCut();
	if(sm==4) W = analysis->getWJetsNJetVBFHCP(); 
      }
    }
    W->SetName("W");
    
    TH1F* ZTT = 0;
    ZTT = analysis->getZToTauTau();
    ZTT->SetName("ZTT");

    TH1F* TT = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        TT=analysis->getTTJetsInc(); 
    if(sm==4)                                   TT=analysis->getTTJetsVBFHCP(); 
    TT->SetName("TT");

    TH1F* ZL =0;
    if(channel==1){//mu-Tau
      if(sm==0 || sm==2 || sm==1 || sm==3) 	ZL =analysis->getZLInc();
      if(sm==4)                            	ZL =analysis->getZLVBFHCP();
    }
    if(channel==2){//e-Tau
      if(sm==0 || sm==2 || sm==1) 	        ZL =analysis->getZL2012();//analysis->getZL2012Type2();//
      if(sm==3)                            	ZL =analysis->getZLBoost();
      if(sm==4)                            	ZL =analysis->getZLVBFHCP();
    }
    ZL->SetName("ZL");

    TH1F* ZJ = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        ZJ=analysis->getZToLJetInc();
    if(sm==4)                                   ZJ=analysis->getZToLJetVBFHCP();                   
    ZJ->SetName("ZJ");

    TH1F* VV = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        VV=analysis->getDiBoson();
    if(sm==4)                                   VV=analysis->getDiBosonVBFHCP();
    VV->SetName("VV");

    TH1F* ZLL=(TH1F*)ZL->Clone("ZLL");
    ZLL->SetName("ZLL");
    ZLL->Add(ZJ);

    //blind
    TString tmpsel=analysis->extrasel_;
    if(Blind)analysis->extrasel_ += "*(svfitmass<100||160<svfitmass)"; 
    TH1F* data_obs = analysis->getTotalData();
    data_obs->SetName("data_obs");
    analysis->extrasel_ =tmpsel;



    TH1F* MC=(TH1F*)ZTT->Clone("MC");//needed below
    MC->Add(ZL);
    MC->Add(ZJ);
    MC->Add(W);
    MC->Add(TT);
    MC->Add(VV);
    MC->Add(QCD);


    dir->cd();
  
    
    fix0Bins(ZTT); ZTT->Write(); 
    ZTT->SetName("ZTT125"); ZTT->Write();//needed for ZTT fits
    fix0Bins(ZL);  ZL->Write();
    fix0Bins(ZJ);  ZJ->Write();
    fix0Bins(ZLL); ZLL->Write();
    fix0Bins(W);   W->Write();
    fix0Bins(TT);  TT->Write();
    fix0Bins(VV);  VV->Write();
    fix0Bins(QCD); QCD->Write();
    data_obs->Write();
 
    gROOT->cd();
    
    delete ZTT ;
    delete ZL;
    delete ZJ;
    delete ZLL;
    delete W;
    delete TT;
    delete VV;
    delete QCD;

 
    for(Int_t m=0;m<NMASS;m++){
      long ma=massValues[m];

      //Nominal h 
      TH1F* SM = analysis->getSample(TString("HiggsGG")+ma);
      SM->SetName(TString("ggH")+ma);

      TH1F* VBF = analysis->getSample(TString("HiggsVBF")+ma);
      VBF->SetName(TString("qqH")+ma);

      TH1F* VH = analysis->getSample(TString("HiggsVH")+ma);
      VH->SetName(TString("VH")+ma);

      SM->Scale(1./analysis->findSample(TString("HiggsGG")+ma)->getCrossection());
      VBF->Scale(1./analysis->findSample(TString("HiggsVBF")+ma)->getCrossection());
      VH->Scale(1./analysis->findSample(TString("HiggsVH")+ma)->getCrossection());
      
      //check for empty histos
      if( SM->Integral()<=0.){  SM->SetBinContent(SM->GetNbinsX()/2,1e-4);    SM->SetBinError(SM->GetNbinsX()/2,1e-4); }
      if( VBF->Integral()<=0.){ VBF->SetBinContent(VBF->GetNbinsX()/2,1e-4);  VBF->SetBinError(VBF->GetNbinsX()/2,1e-4); }
      if( VH->Integral()<=0.){  VH->SetBinContent(VH->GetNbinsX()/2,1e-4);    VH->SetBinError(VH->GetNbinsX()/2,1e-4); }

      dir->cd();
      
     
      
      fixSignal(data_obs,MC,VH);  fix0Bins(VH);   VH->Write();
      fixSignal(data_obs,MC,SM);  fix0Bins(SM);   SM->Write();
      fixSignal(data_obs,MC,VBF); fix0Bins(VBF);  VBF->Write();
      gROOT->cd();

      delete VH;
      delete SM;
      delete VBF;

    }

    delete MC;
    delete data_obs;

  }
  
  output.ls();
  output.Close();
  gROOT->ProcessLine(".q");
}
Example #15
0
int IndResponse(double kPt=80,const char *ksp="pbpb")
{

  timer.Start();

  //! Load Lib
  gSystem->Load("hiForest_h.so");
  
  //! Load the hiforest input root file
  HiForest *c = 0;
  if(strcmp("pp",ksp)==0)c = new HiForest(Form("/net/hisrv0001/home/icali/hadoop/Pythia/Z2/ppDijet_merged/pp276Dijet%0.0f_merged.root",kPt),"pp2012",1,1);
  else  {
    if(kPt==30)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia30_HydjetDrum_mix01_HiForest2_v19.root","pbpb2012",0,1);
    else if(kPt==50)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia50_HydjetDrum_mix01_HiForest2_v19.root","pbpb2012",0,1);
    else if(kPt==80)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia80_HydjetDrum_mix01_HiForest2_v20.root","pbpb2012",0,1);
    else if(kPt==120)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia120_HydjetDrum_mix01_HiForest2_v21_ivan.root","pbpb2012",0,1);
    else if(kPt==170)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia170_HydjetDrum_mix01_HiForest2_v19.root","pbpb2012",0,1);
    else if(kPt==200)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia200_HydjetDrum_mix01_HiForest2_v21_ivan.root","pbpb2012",0,1);
    else if(kPt==250)c = new HiForest("/d102/yjlee/hiForest2MC/Pythia250_HydjetDrum_mix01_HiForest2_v21_ivan.root","pbpb2012",0,1);
    //c = new HiForest(Form("/net/hisrv0001/home/icali/hadoop/Hydjet1.8/Z2/Dijet_merged/Dijet%0.0f_merged.root",kPt),"pbpb2012",0,1);
  }


  double xsection=0;
  double xup=0;
  double xsub=0;
  double maxpthat=9999;
  if(kPt==15){
    maxpthat=30;
    xup=1.566e-01;
    xsub=1.079e-02;
  }
  else if(kPt==30){
    maxpthat=50;
    xup=1.079e-02;
    xsub=1.021e-03;
  }
  else if(kPt==50){
    maxpthat=80;
    xup=1.021e-03;
    xsub=9.913e-05;
  }
  else if(kPt==80){
    maxpthat=120;
    xup=9.913e-05;
    xsub=1.128e-05;
  }
  else if(kPt==120){
    maxpthat=170;
    xup=1.128e-05;
    xsub=1.470e-06;
  }
  else if(kPt==170){
    maxpthat=200;
    xup=1.470e-06;
    xsub=5.310e-07;
  }
  else if(kPt==200){
    maxpthat=250;
    xup=5.310e-07;
    xsub=1.192e-07;
  }
  else if(kPt==250){
    maxpthat=300;
    xup=1.192e-07;
    xsub=3.176e-08;
  }
  else if(kPt==300){
    maxpthat=9999;
    xup=3.176e-08;
    xsub=0;
  }
  xsection = xup-xsub;


  std::cout<<std::endl;
  std::cout<<std::endl;


  //! Don't want to loop over trees which is not used in the analysis
  //! event trees
  //c->hasEvtTree=0;

  //! jet trees
  //! Switch on only the jet trees which you  require
  const char *cjets[7] = {"icPu5","ak2PF","ak3PF","ak4PF","akPu2PF","akPu3PF","akPu4PF"};
  c->SelectJetAlgo(cjets,7);
  

  //! photon tree
  //c->hasPhotonTree=0;


  //! Select only the jet branches which you are going to use
  //! This increases the speed for running over trees with lot of branches.
  //! This is currently for only jet algos and evtTree  uniformly applied to all the 

  //! Event Tree 
  const char *evlist[]={"hiBin","vz","hiHF"};
  const int kevbr = sizeof(evlist)/sizeof(const char *);
  c->SelectBranches("evtTree",evlist,kevbr);

  //! jet Tree algorithms
  const char *jtlist[]={"nref","pthat","rawpt","jtpt","jteta","jtphi","jtpu","refpt","refeta","refphi","refdrjt","refparton_flavor",
			"ngen","gensubid","genmatchindex"
  };
  const int kjtbr = sizeof(jtlist)/sizeof(const char *);
  c->SelectBranches("JetTree",jtlist,kjtbr);

  std::cout<<"Selected the branches of need from evtTree and JetTrees : "<<std::endl;

  //! To get the jet object from hiforest
  Jets *iJet=0;
  const int knj = 7;//c->GetNAlgo(); //! # of jet algorithms in this hiforest 
  std::cout<<"Loaded all tree variables and # of jet algorithms : "<<knj<<std::endl;
  std::cout<<"\t"<<std::endl;

  //! Away-side jet definition
  const char *cdphi="2pi3";
  double kdphicut = 7.*pi/8.;
  if(strcmp(cdphi,"2pi3")==0)kdphicut=2.*pi/3.;
  else if(strcmp(cdphi,"1pi4")==0)kdphicut=1.*pi/4.;

  //! Open a output file for histos
  TFile *fout = new TFile(Form("Output/%s/Response_newHiForest_DJ_%0.0fGeV_%s_%d.root",ksp,kPt,ksp,iYear),"RECREATE");
  //TFile *fout = new TFile(Form("Output/%s/novtxcut/Response_newHiForest_DJ_%0.0fGeV_%s_%d.root",ksp,kPt,ksp,iYear),"RECREATE");
  //TFile *fout = new TFile(Form("test_newHiForest_DJ_%0.0fGeV_%s_%d.root",kPt,ksp,iYear),"RECREATE");

  std::cout<<"\t"<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"**************************************************** "<<std::endl;
  std::cout<<Form("Running for %s ",ksp)<<std::endl;
  std::cout<<Form("pT  cut for %0.3f ",kptrecocut)<<std::endl;
  std::cout<<Form("eta cut for %0.3f ",ketacut)<<std::endl;
  std::cout<<"My hiForest TTree : " <<c->GetName()<<std::endl;
  std::cout<<"Output file  "<<fout->GetName()<<std::endl;
  std::cout<<"**************************************************** "<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"\t"<<std::endl;


  //! 
  //! Define histograms here
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  TProfile::SetDefaultSumw2();

  ////////////////////////////////////////////////////////////////////////////////////////////////////////
  TH1F *hEvt    = new TH1F("hEvt","# of events ",4,0,4);
  TH1F *hVz     = new TH1F("hVz","# of events ",80,-20,20);
  TH1F *hBin    = new TH1F("hBin","Centrality bin",40,0,40);
  TH1F *hHF     = new TH1F("hHF","Centrality variable from HF",600,0,6000);
  TH1F *hTotEve = new TH1F("hTotEve","# of events in the skimmed files",4,0,4);

  TH1F *hgenpt [knj][ncen], *hrecopt[knj][ncen], *hrawpt[knj][ncen];
  TH1F *hgenptC [knj][ncen], *hrecoptC[knj][ncen], *hrawptC[knj][ncen];
  TH1F *hgeneta[knj][ncen], *hrecoeta[knj][ncen];
  TH1F *hgenphi[knj][ncen], *hrecophi[knj][ncen];

  //! Ratios of the pt distributions
  TProfile *hrecogen[knj][ncen], *hrecoraw[knj][ncen], *hrawgen[knj][ncen], *hrecoraw_ref[knj][ncen];

  //! Resposnse
  TH2F *hcorrptrefpt[knj][ncen], *hrawptrefpt[knj][ncen], *hcorrptrawpt[knj][ncen];
  TH2F *hrescrpt[knj][ncen], *hresrrpt[knj][ncen], *hresrcrpt[knj][ncen];
  TH2F *hratiorawrefpt[knj][ncen], *hratiocorrrefpt[knj][ncen], *hratiocorrrawpt[knj][ncen];
  TH2F *hratiorawrefpt_eta[knj][ncen][2], *hratiocorrrefpt_eta[knj][ncen][2];

  TH2F *hratiocorrrefpt_genm[knj][ncen];
  TH2F *hratiocorrrefpt_lead[knj][ncen], *hratiocorrrefpt_slead[knj][ncen], *hratiocorrrefpt_remain[knj][ncen];
  TH2F *hratiocorrrefpt_pthat[knj][ncen];


  TH2F *hpteta[knj][ncen][maxe], *hptphi[knj][ncen][maxph];

  TH2F *hgenjrecoj[knj][ncen];
  TH2F *hgenjrecoj_pflavor[knj][ncen];

  TH2F *hFracjets[knj][ncen];
  TH2F *hAvjets[knj][ncen];
  TH2F *hMeanPtjets[knj][ncen];
  TH1F *hNjets[knj][ncen];
  TH1F *hNevt [knj][ncen];

  //! Pileup effect study
  TH2F *hjetptpu[knj][ncen];             //! centrality                                                                       
  TH2F *hjetptpu_etab[knj][ncen][ketar]; //! eta dependence             

  //! Efficency histos
  TH1F *hPtAll [knj][ncen], *hPtSel[knj][ncen];
  TH1F *hEtaAll[knj][ncen], *hEtaSel[knj][ncen];
  TH1F *hPhiAll[knj][ncen], *hPhiSel[knj][ncen];

  //! Response vs deltar
  TH1F *hRspVsDeltaR[knj][ncen][25];

  //! DeltaR efficiency                                                                                                                                                              
  TH1F *hDeltaR[knj][ncen];
  TH1F *hDeltaRAll[knj][ncen];
  TH1F *hDeltaRSel[knj][ncen];

  for(int nj=0;nj<knj;nj++){
    //const char *algoname = c->GetAlgoName(nj);
    //char *algoname = cjets[nj];
    //strcpy(algoname,cjets[nj]);

    for(int icen=0;icen<ncen;icen++){
      hFracjets[nj][icen]   = new TH2F(Form("hFracjets%d_%d",nj,icen),Form("Fraction of jets in given pt hat cent %d %s",icen,cjets[nj]),500,0,1000,500,0.,1000.);
      hAvjets[nj][icen]     = new TH2F(Form("hAvjets%d_%d",nj,icen),Form("<#> of jets cent %d %s",icen,cjets[nj]),500,0,1000,30,0,30);
      hMeanPtjets[nj][icen] = new TH2F(Form("hMeanPtjets%d_%d",nj,icen),Form("<pT> of jets cent %d %s",icen,cjets[nj]),500,0,1000,500,0,1000);

      hNjets[nj][icen] = new TH1F(Form("hNjets%d_%d",nj,icen),Form("# of jets cent %d jets %s",icen,cjets[nj]),3,0.0,3.0);
      hNevt [nj][icen] = new TH1F(Form("hNevt%d_%d",nj,icen),Form("# of events cent %d %s",icen,cjets[nj]),40,-40,40);
      hgeneta[nj][icen] = new TH1F(Form("hgeneta%d_%d",nj,icen),Form("gen eta distribution jet centb %d %s",icen,cjets[nj]),60,-3.0,3.0);
      hrecoeta[nj][icen] = new TH1F(Form("hrecoeta%d_%d",nj,icen),Form("reco eta distribution jet centb %d %s",icen,cjets[nj]),60,-3.0,3.0);

      hgenphi[nj][icen] = new TH1F(Form("hgenphi%d_%d",nj,icen),Form("gen phi distribution jet centb %d %s",icen,cjets[nj]),36,-pi,pi);
      hrecophi[nj][icen] = new TH1F(Form("hrecophi%d_%d",nj,icen),Form("reco phi distribution jet centb %d %s",icen,cjets[nj]),36,-pi,pi);

      hgenpt[nj][icen]  = new TH1F(Form("hgenpt%d_%d",nj,icen),Form("gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
      hrecopt[nj][icen] = new TH1F(Form("hrecopt%d_%d",nj,icen),Form("reco p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
      hrawpt[nj][icen]  = new TH1F(Form("hrawpt%d_%d",nj,icen),Form("raw p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);

      //! with pt bins
      hgenptC[nj][icen]  = new TH1F(Form("hgenptC%d_%d",nj,icen),Form("gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),bins,ptbins);
      hrecoptC[nj][icen] = new TH1F(Form("hrecoptC%d_%d",nj,icen),Form("reco p_{T} distribution jet centb %d %s",icen,cjets[nj]),bins,ptbins);
      hrawptC[nj][icen]  = new TH1F(Form("hrawptC%d_%d",nj,icen),Form("raw p_{T} distribution jet centb %d %s",icen,cjets[nj]),bins,ptbins);

      //! Ratios
      hrecogen[nj][icen] = new TProfile(Form("hrecogen%d_%d",nj,icen),Form("reco/gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
      hrecoraw[nj][icen] = new TProfile(Form("hrecoraw%d_%d",nj,icen),Form("reco/raw p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
      hrecoraw_ref[nj][icen]  = new TProfile(Form("hrecoraw_ref%d_%d",nj,icen),Form("reco/raw : ref p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
      hrawgen[nj][icen]  = new TProfile(Form("hrawgen%d_%d",nj,icen),Form("raw/gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);


      hcorrptrefpt[nj][icen]= new TH2F(Form("hcorrptrefpt%d_%d",nj,icen),Form("Gen jet:Reco jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,500,0,1000);
      hrawptrefpt[nj][icen]= new TH2F(Form("hrawptrefpt%d_%d",nj,icen),Form("Gen jet:Raw jet p_{T}  distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,500,0,1000);
      hcorrptrawpt[nj][icen]= new TH2F(Form("hcorrptrawpt%d_%d",nj,icen),Form("Reco jet Corr:Raw jet p_{T}  distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,500,0,1000);

      hrescrpt[nj][icen]= new TH2F(Form("hrescrpt%d_%d",nj,icen),Form("Gen jet:(Reco/Gen) jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,150,rbinl,rbinh);
      hresrrpt[nj][icen]= new TH2F(Form("hresrrpt%d_%d",nj,icen),Form("Gen jet:(Raw/Gen) jet p_{T}  distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,150,rbinl,rbinh);
      hresrcrpt[nj][icen]= new TH2F(Form("hresrcrpt%d_%d",nj,icen),Form("Reco jet:(Reco/Raw) jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,150,rbinl,rbinh);

      hratiorawrefpt[nj][icen]= new TH2F(Form("hratiorawrefpt%d_%d",nj,icen),Form("Raw jet / Gen jet p_{T} (raw) distribution jet centb %d %s",icen,cjets[nj]),
					 bins,ptbins,rbins,rbinl,rbinh);
      hratiocorrrefpt[nj][icen]= new TH2F(Form("hratiocorrrefpt%d_%d",nj,icen),Form("Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
					  bins,ptbins,rbins,rbinl,rbinh);
      hratiocorrrawpt[nj][icen]= new TH2F(Form("hratiocorrrawpt%d_%d",nj,icen),Form("Correc. jet / Raw jet jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),
                                          bins,ptbins,rbins,rbinl,rbinh);

      hratiocorrrefpt_lead[nj][icen]= new TH2F(Form("hratiocorrrefpt_lead%d_%d",nj,icen),Form("Leading jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                               bins,ptbins,rbins,rbinl,rbinh);
      hratiocorrrefpt_slead[nj][icen]= new TH2F(Form("hratiocorrrefpt_slead%d_%d",nj,icen),Form("sub-Leading jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                                bins,ptbins,rbins,rbinl,rbinh);
      hratiocorrrefpt_remain[nj][icen]= new TH2F(Form("hratiocorrrefpt_remain%d_%d",nj,icen),Form("Remaing jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                                 bins,ptbins,rbins,rbinl,rbinh);
      hratiocorrrefpt_pthat[nj][icen]= new TH2F(Form("hratiocorrrefpt_pthat%d_%d",nj,icen),Form("pT hat jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                                bins,ptbins,rbins,rbinl,rbinh);
      hratiocorrrefpt_genm[nj][icen]= new TH2F(Form("hratiocorrrefpt_genm%d_%d",nj,icen),Form("Gen matched jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                               bins,ptbins,rbins,rbinl,rbinh);



      for(int ie=0;ie<2;ie++){
        hratiorawrefpt_eta[nj][icen][ie]= new TH2F(Form("hratiorawrefpt_eta%d_%d_%d",nj,icen,ie),
						   Form("Raw jet / Gen jet p_{T} (raw) distribution jet centb %d %s etabin%d",icen,cjets[nj],ie),
						   bins,ptbins,rbins,rbinl,rbinh);
        hratiocorrrefpt_eta[nj][icen][ie]= new TH2F(Form("hratiocorrrefpt_eta%d_%d_%d",nj,icen,ie),
						    Form("Reco jet / Gen jet p_{T} (raw) distribution jet centb %d %s etabin%d",icen,cjets[nj],ie),
						    bins,ptbins,rbins,rbinl,rbinh);
      }

      hjetptpu[nj][icen] = new TH2F(Form("hjetptpu%d_%d",nj,icen),Form("jet(pt:pu) distribution jet centb %d %s",icen,cjets[nj]),dbins,ptbins_data,100,0,300);
      for(int ie=0;ie<ketar;ie++){
        hjetptpu_etab[nj][icen][ie] = new TH2F(Form("hjetptpu_etab%d_%d_%d",nj,icen,ie),Form("jet(pt:pu) distribution jet %s etabin %d cen %d",cjets[nj],icen,ie),
					       dbins,ptbins_data,100,0,300);
      }
      
      for(int m=0;m<maxe;m++){
        hpteta[nj][icen][m] = new TH2F(Form("hpteta%d_%d_%d",nj,icen,m),Form("resolution  pt(eta) distribution cent %d jet %s etabin%d",icen,cjets[nj],m),
				       bins,ptbins,rbins,rbinl,rbinh);
      }
      
      for(int m=0;m<maxph;m++){
	hptphi[nj][icen][m] = new TH2F(Form("hptphi%d_%d_%d",nj,icen,m),Form("resolution pt(phi) distribution cent %d jet %s phibin%d",icen,cjets[nj],m),
				       bins,ptbins,rbins,rbinl,rbinh);
      }

      hgenjrecoj[nj][icen] =new TH2F(Form("hgenjrecoj%d_%d",nj,icen),Form("gen jet2 : reco jet2 %s cent %d",cjets[nj],icen),500,0.,1000.,500,0.,1000.);
      hgenjrecoj_pflavor[nj][icen] =new TH2F(Form("hgenjrecoj_pflavor%d_%d",nj,icen),Form("gen jet : reco jet with parton flavor %s cent %d",cjets[nj],icen),500,0.,1000.,500,0.,1000.);

      //! efficency histograms
      hPtAll [nj][icen] = new TH1F(Form("hPtAll%d_%d",nj,icen),Form("Denominator pT for algorithm %s cent %d",cjets[nj],icen),40,30,430);
      hEtaAll[nj][icen] = new TH1F(Form("hEtaAll%d_%d",nj,icen),Form("Denominator eta  for algorithm %s cent %d",cjets[nj],icen),20,-2.0,2.0);
      hPhiAll[nj][icen] = new TH1F(Form("hPhiAll%d_%d",nj,icen),Form("Denominator  phi  for algorithm %s cent %d",cjets[nj],icen),20,-pi,pi);
      
      hPtSel [nj][icen] = new TH1F(Form("hPtSel%d_%d",nj,icen),Form("Numerator pT for algorithm %s cent %d",cjets[nj],icen),40,30,430);
      hEtaSel[nj][icen] = new TH1F(Form("hEtaSel%d_%d",nj,icen),Form("Numerator eta  for algorithm %s cent %d",cjets[nj],icen),20,-2.0,2.0);
      hPhiSel[nj][icen] = new TH1F(Form("hPhiSel%d_%d",nj,icen),Form("Numerator  phi  for algorithm %s cent %d",cjets[nj],icen),20,-pi,pi);

      hDeltaR[nj][icen]    = new TH1F(Form("hDeltaR%d_%d",nj,icen),Form("#DeltaR for algorithm %s cent %d",cjets[nj],icen),100,0,1);
      hDeltaRAll[nj][icen] = new TH1F(Form("hDeltaRAll%d_%d",nj,icen),Form("#DeltaR (all) for algorithm %s cent %d",cjets[nj],icen),100,0,1);
      hDeltaRSel[nj][icen] = new TH1F(Form("hDeltaRSel%d_%d",nj,icen),Form("#DeltaR (sel) for algorithm %s cent %d",cjets[nj],icen),100,0,1);

      for(int ir=0;ir<25;ir++){
	//! Response vs DeltaR
        hRspVsDeltaR[nj][icen][ir] = new TH1F(Form("hRspVsDeltaR%d_%d_%d",nj,icen,ir),Form(" <recopt/refpt> vs. #DeltaR (%d) algorithm %s cent %d",ir,cjets[nj],icen),rbins,rbinl,rbinh);
      }
    }//! icen
  }//! nj
  std::cout<<"Initialized the histograms " <<std::endl;
  ///////////////////////////////////////////////////////////////////////////////////////// 


  //! Centrality reweighting function
  //TF1* fcen = new TF1("fcen","exp(-1.0*pow(x+1.11957e+01,2)/pow(1.34120e+01,2)/2)",0,40);
  TF1 *fcen = new TF1("fcen","[0]*exp([1]+[2]*x+[3]*x*x+[4]*x*x*x)",0,40);
  fcen->SetParameters(2.10653e-02,5.61607,-1.41493e-01,1.00586e-03,-1.32625e-04);

  //! vertex z reweighting
  TF1 *fVz = new TF1("fVz","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x");
  if(strcmp(ksp,"pp")==0) fVz->SetParameters(8.41684e-01,-2.58609e-02,4.86550e-03,-3.10581e-04,2.07918e-05);
  else  fVz->SetParameters(7.62788e-01,-1.13228e-02,5.85199e-03,-3.04550e-04,4.43440e-05);


  Long64_t nb = 0;
  Long64_t nentries = c->GetEntries();
  std::cout<<Form("# of entries in TTree for %s : ",ksp)<<nentries<<std::endl;
  std::cout<<std::endl;
  hEvt->Fill(2,nentries);

  //! weight  for the merging of the samples for different pT hat bins
  Float_t wxs = xsection/(nentries/100000.);
  
  Int_t iEvent=0; 
  for (Long64_t ievt=0; ievt<nentries;ievt++) {//! event loop
  //for (Long64_t ievt=0; ievt<1;ievt++) {//! event loop
    //! load the hiForest event
    nb += c->GetEntry(ievt);

    int hiBin       = c->evt.hiBin;
    float vz        = c->evt.vz;
    float hiHF      = c->evt.hiHF;

    //! testing
    //if(hiBin>4 && strcmp(ksp,"pbpb")==0)continue;

    //! apply vertex cut
    if(fabs(vz)>kVzcut)continue;


    //! Centrality bin
    if(hiBin<0 || hiBin>39)continue;
    int centb=-1;
    double wcen=1;
    double wvz=fVz->Eval(vz);
    if(strcmp(ksp,"pbpb")==0){
      centb=GetCentBin(hiBin);
      wcen = fcen->Eval(hiBin);
    }else{
      centb=ncen-1; //! pp
      wcen=1;
    }

    if(ievt%10000==0)std::cout<<" ********** Event # " <<ievt<<std::endl;
    //std::cout<<" ********** Event # " <<ievt<<"\t vz : "<<vz<<"\t hiBin : "<<hiBin<<"\t wxs : "<<wxs<<std::endl;


    //! Centrality from 0-90% 
    if(centb==-1 || centb==ncen)continue;


    int istat=0;
    for(int nj=0;nj<knj;nj++){ //! loop over different jet algorithms
      
      //! Get the jet object
      //iJet = c->GetJet(nj);
      iJet = c->GetJetByAlgo(cjets[nj]);
      
      //! xsec-weight
      double pthat = iJet->pthat;
      if(pthat > maxpthat)continue;
      istat=1;
      
      //std::cout<<"\t Jet Algorithm : "<<c->GetCjets[Nj](nj)<<"\t # of Jets  : "<<iJet->nref<<"\t pthat : "<<pthat<<std::endl;
      if(nj==0)hTotEve->Fill(1); //! akPu3PF      

      float njets=0.;
      float meanpt=0.;

      int *ljet = new int[2];
      FindLeadSubLeadJets(iJet,ljet);
      if(ljet[0]>=0){
	hratiocorrrefpt_lead[nj][centb]->Fill(iJet->refpt[ljet[0]],iJet->jtpt[ljet[0]]/iJet->refpt[ljet[0]],wxs*wcen*wvz);
      }
      if(ljet[1]>=0){
	hratiocorrrefpt_slead[nj][centb]->Fill(iJet->refpt[ljet[1]],iJet->jtpt[ljet[1]]/iJet->refpt[ljet[1]],wxs*wcen*wvz);
      }

      if(nj>3){
	//! Gen matched jets
	for(int igen=0; igen<iJet->ngen; igen++){
	  if( iJet->gensubid[igen] != 0) continue;
	  int gj = iJet->genmatchindex[igen];
	  
	  float refpt   = iJet->refpt[gj];
	  float recopt  = iJet->jtpt[gj];
	  float recoeta = iJet->jteta[gj];
	  float delr    = iJet->refdrjt[gj];
	  
	  if(recopt<kptrecocut || refpt<kptgencut || refpt==0 || fabs(recoeta)>ketacut || fabs(delr)>kdRcut)continue;
	  hratiocorrrefpt_genm[nj][centb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	}
      }


      for(int ij=0; ij<iJet->nref; ij++){
	//if(!selecJet(iJet,ij))continue;

	float refpt   = iJet->refpt[ij];
        float recopt  = iJet->jtpt[ij];
        float rawpt   = iJet->rawpt[ij];
	float refeta  = iJet->refeta[ij];
        float recoeta = iJet->jteta[ij];
        float refphi  = iJet->refphi[ij];
        float recophi = iJet->jtphi[ij];
	int refparton_flavor = iJet->refparton_flavor[ij];


	//! Matching criteria 
        float delr = iJet->refdrjt[ij];


	if(recopt<kptrecocut || refpt<kptgencut || refpt==0)continue;
	//std::cout<<"\t \t "<<ij<<"\t refpt : "<<refpt<<"\t recopt : "<<recopt<<"\t raw pT : "<<rawpt<<std::endl;

	if(fabs(refeta)<ketacut && refpt>80){
          //! Denominator for matching efficiency
	  hPtAll [nj][centb]->Fill(refpt,wxs*wcen*wvz);
          hEtaAll[nj][centb]->Fill(refeta,wxs*wcen*wvz);
          hPhiAll[nj][centb]->Fill(refphi,wxs*wcen*wvz);
	  
	  
	  //! Response
	  for (int idr=0;idr<25;idr++) {
	    double drcut = 0.0+idr*(0.25-0.00)/(25-1);
	    if (delr>drcut) continue;
	    hRspVsDeltaR[nj][centb][idr]->Fill(recopt/refpt,wxs*wcen*wvz);
	  }
	  
	  //! DeltaR efficiency
	  hDeltaR[nj][centb]->Fill(delr,wxs*wcen*wvz);
	  for (int idrmax=0;idrmax<100;idrmax++) {
	    float drmax = idrmax*0.01+0.005;
	    hDeltaRAll[nj][centb]->Fill(drmax,wxs*wcen*wvz);
	    if (delr<drmax) hDeltaRSel[nj][centb]->Fill(drmax,wxs*wcen*wvz);
	  }
        }

        //! Matching cut for gen-jet and reco-jet
	if(delr > kdRcut)continue;


        if(fabs(refeta)<ketacut && refpt>80){
          //! Numerator for matching efficiency
          hPtSel [nj][centb]->Fill(refpt,wxs*wcen*wvz);
          hEtaSel[nj][centb]->Fill(refeta,wxs*wcen*wvz);
          hPhiSel[nj][centb]->Fill(refphi,wxs*wcen*wvz);
        }

        //! pile up eta dependence
        //int ebin = GetDetEtaBin(fabs(recoeta));

	//! jet selction cut
        if(fabs(recoeta)>ketacut)continue;
	
	//istat=1;
	//! 1D distributions
	njets++;
	meanpt += refpt;
        hNjets [nj][centb]->Fill(1.);
        hgenpt [nj][centb]->Fill(refpt,wxs*wcen*wvz);
        hgeneta[nj][centb]->Fill(refeta,wxs*wcen*wvz);
	hgenphi[nj][centb]->Fill(refphi,wxs*wcen*wvz);


	hrecopt [nj][centb]->Fill(recopt,wxs*wcen*wvz);
        hrecoeta[nj][centb]->Fill(recoeta,wxs*wcen*wvz);
        hrecophi[nj][centb]->Fill(recophi,wxs*wcen*wvz);
        hrawpt [nj][centb]->Fill(rawpt,wxs*wcen*wvz);


        hgenptC [nj][centb]->Fill(refpt,wxs*wcen*wvz);
	hrecoptC [nj][centb]->Fill(recopt,wxs*wcen*wvz);
        hrawptC [nj][centb]->Fill(rawpt,wxs*wcen*wvz);

	hrecogen[nj][centb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
        hrawgen [nj][centb]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
        hrecoraw[nj][centb]->Fill(rawpt,recopt/rawpt,wxs*wcen*wvz);
        hrecoraw_ref [nj][centb]->Fill(refpt,recopt/rawpt,wxs*wcen*wvz);

	hFracjets[nj][centb]->Fill(pthat,refpt,wxs*wcen*wvz);


	//! Response  (ratio of recopt/refpt)
        hratiocorrrefpt[nj][centb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hratiorawrefpt [nj][centb]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hratiocorrrawpt [nj][centb]->Fill(recopt,recopt/rawpt,wxs*wcen*wvz);

	//! remaing jets
        bool iRemain = ij!=ljet[0] || ij!=ljet[1];
	if(iRemain)hratiocorrrefpt_remain[nj][centb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	
        //! pT hat
	hratiocorrrefpt_pthat[nj][centb]->Fill(pthat,recopt/refpt,wxs*wcen*wvz);



	//! 2D correlation between refpt and recopt
        hcorrptrefpt[nj][centb]->Fill(refpt,recopt,wxs*wcen*wvz);
        hrawptrefpt [nj][centb]->Fill(refpt,rawpt,wxs*wcen*wvz);
	hcorrptrawpt[nj][centb]->Fill(rawpt,recopt,wxs*wcen*wvz);

        //! Very fine bin in ref pt
	hrescrpt[nj][centb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hresrrpt[nj][centb]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hresrcrpt[nj][centb]->Fill(recopt,recopt/rawpt,wxs*wcen*wvz);

	int ieta=-1;
	if(fabs(recoeta)<1.3)ieta=0; //! barrel region
        else ieta=1; //! HCAL region
        if(ieta>=0){
          hratiocorrrefpt_eta[nj][centb][ieta]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
          hratiorawrefpt_eta [nj][centb][ieta]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	}

	//! pileup study
        hjetptpu[nj][centb]->Fill(recopt,iJet->jtpu[ij],wxs*wcen*wvz);

        //! Response in different eta and phi bins
        int etabin = GetEtaBin(fabs(refeta));
	int phibin = GetPhiBin(refphi);

	if(etabin < 0 || etabin>=maxe || phibin < 0 || phibin>=maxph)continue;

        //! Response in eta and phi bins
        hpteta[nj][centb][etabin]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
        hptphi[nj][centb][phibin]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);


        //! Gen:Reco correlation plots
	hgenjrecoj [nj][centb]->Fill(refpt,recopt,wxs*wcen*wvz);
	if(fabs(refparton_flavor)<=21)hgenjrecoj_pflavor [nj][centb]->Fill(refpt,recopt,wxs*wcen*wvz);

      }//! ij loop

      hNevt[nj][centb]->Fill(vz);
      if(njets>0){
	hAvjets[nj][centb]->Fill(pthat,njets,wxs*wcen*wvz);
	hMeanPtjets[nj][centb]->Fill(pthat,meanpt/njets,wxs*wcen*wvz);
      }
      delete [] ljet;
    }//! nj jet loop

    if(istat){
      hBin->Fill(hiBin,wxs*wcen*wvz);
      hVz->Fill(vz,wxs*wcen*wvz);
      hHF->Fill(hiHF,wxs*wcen*wvz);
      iEvent++;
    }
    //std::cout<<"Completed event #  "<<ievt<<std::endl; 
  }//! event loop ends
  
  std::cout<<std::endl;
  std::cout<<std::endl;
  std::cout<<std::endl;

  std::cout<<"Events which passed the pT hat cut : "<<hTotEve->Integral()<<" out of  : "<<hEvt->Integral()
	   <<" efficiency of all the cuts : " <<hTotEve->Integral()/hEvt->Integral()<<std::endl;
  std::cout<<std::endl;


  if(strcmp(ksp,"pp")==0){
    for(int nj=0;nj<knj;nj++){
      //std::cout<<"# of Events for : "<<c->GetCjets[Nj](nj)<<"\t"<<hNevt[nj][0]->Integral()<<"\t # of Jets : "<<hNjets[nj][0]->Integral()<<std::endl;
      std::cout<<"# of Events for : "<<cjets[nj]<<"\t"<<hNevt[nj][0]->Integral()<<"\t # of Jets : "<<hNjets[nj][0]->Integral()<<std::endl;
    }
  }else{
    for(int nj=0;nj<knj;nj++){
      for(int icen=0;icen<ncen;icen++){
	std::cout<<"# of Events for : "<<cjets[nj]<<"\t icen : "<<icen<<"\t"<<hNevt[nj][icen]->Integral()<<"\t # of Jets : "<<hNjets[nj][icen]->Integral()<<std::endl;
      }
      std::cout<<std::endl;
    }
  }

  //! Write to output file
  fout->cd();
  fout->Write();
  fout->Close();


  //! Check
  timer.Stop();
  float  mbytes = 0.000001*nb;
  double rtime  = timer.RealTime();
  double ctime  = timer.CpuTime();

  std::cout<<std::endl;
  std::cout<<Form("RealTime=%f seconds, CpuTime=%f seconds",rtime,ctime)<<std::endl;
  std::cout<<Form("You read %f Mbytes/RealTime seconds",mbytes/rtime)<<std::endl;
  std::cout<<Form("You read %f Mbytes/CpuTime  seconds",mbytes/ctime)<<std::endl;
  std::cout<<std::endl;
  std::cout<<"Good bye : " <<"\t"<<std::endl;
  return 1;
}
Example #16
0
void plotDistribution( TChain* data , TChain *mc , TCut sel , TCut vtxweight , char* var , int nbins , float xmin , float xmax , char* xtitle , char* plottitle = "" , bool printplot = false , bool residual = false , bool log = false ){

  //--------------------------------------
  // define histograms and TGraphs
  //--------------------------------------

  TH1F* hdata      = new TH1F(Form("hdata_%i"     , iplot),Form("hdata_%i"    , iplot),nbins,xmin,xmax);
  TH1F* hmc        = new TH1F(Form("hmc_%i"       , iplot),Form("hmc_%i"      , iplot),nbins,xmin,xmax);
  TH1F* hmc_novtx  = new TH1F(Form("hmc_novtx_%i" , iplot),Form("hmc_novtx%i" , iplot),nbins,xmin,xmax);

  hdata->Sumw2();
  hmc->Sumw2();

  TGraphAsymmErrors* grdata = new TGraphAsymmErrors();
  TGraphAsymmErrors* grmc   = new TGraphAsymmErrors();

  TH1F* hdata_denom = new TH1F(Form("hdata_denom_%i",iplot),"",nbins,xmin,xmax);
  TH1F* hmc_denom   = new TH1F(Form("hmc_denom_%i"  ,iplot),"",nbins,xmin,xmax);

  //--------------------------------------
  // set up canvas and pads
  //--------------------------------------

  TCanvas *can = new TCanvas(Form("can_%i",iplot),Form("can_%i",iplot),600,600);
  can->cd();
  if( log ) gPad->SetLogy();

  TPad *mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);

  if( residual ){
    mainpad->Draw();
    mainpad->cd();
    if( log ) mainpad->SetLogy();
  }

  //--------------------------------------
  // fill histos and TGraphs
  //--------------------------------------

  data->Draw(Form("min(%s,%f)>>hdata_%i"     , var,xmax-0.0001,iplot),sel);
  mc  ->Draw(Form("min(%s,%f)>>hmc_%i"       , var,xmax-0.0001,iplot),sel*vtxweight);
  mc  ->Draw(Form("min(%s,%f)>>hmc_novtx_%i" , var,xmax-0.0001,iplot),sel);

  for( int ibin = 1 ; ibin <= nbins ; ibin++ ){
    hdata_denom->SetBinContent(ibin,hdata->Integral());
    hmc_denom->SetBinContent(ibin,hmc->Integral());
  }

  grdata->BayesDivide(hdata,hdata_denom);
  grmc->BayesDivide(hmc_novtx,hmc_denom);

  //--------------------------------------
  // get efficiencies and errors
  //--------------------------------------

  /*
  float ndata1     = (float) hdata->GetBinContent(1);
  float ndata      = (float) hdata->Integral();
  float effdata    = 1-ndata1 / ndata;

  // TGraphAsymmErrors* grdata_temp = new TGraphAsymmErrors();
  // TH1F* hdata_num_temp = new TH1F(Form("hdata_num_temp_%i",iplot),"",1,0,1);
  // TH1F* hdata_den_temp = new TH1F(Form("hdata_den_temp_%i",iplot),"",1,0,1);
  // hdata_num_temp->SetBinContent(1,ndata-ndata1);
  // hdata_den_temp->SetBinContent(1,ndata);
  // grdata_temp->BayesDivide(hdata_num_temp,hdata_den_temp);

  //float effdataerr = sqrt(ndata1) / ndata;
  float effdataerr = 0.5 * ( grdata->GetErrorYlow(0) + grdata->GetErrorYhigh(0) );
  //float effdataerr = 0.5 * ( grdata_temp->GetErrorYlow(0) + grdata_temp->GetErrorYhigh(0) );

  float nmc1       = (float) hmc->GetBinContent(1);
  float nmc        = (float) hmc->Integral();
  float effmc      = 1-nmc1 / nmc;
  //float effmcerr   = hmc->GetBinError(1) / nmc;
  float effmcerr   = 0.5 * ( grmc->GetErrorYlow(0) + grmc->GetErrorYhigh(0) );


  float datatot = hdata->Integral();
  float mctot   = hmc->Integral();
  
  cout << endl;
  cout << plottitle << endl;

  cout << "Data eff  " << Form("%.2f +/- %.3f",effdata,effdataerr) << endl;
  cout << "MC   eff  " << Form("%.2f +/- %.3f",effmc  ,effmcerr)   << endl;
  cout << "Data/MC   " << Form("%.2f +/- %.2f",ratio  ,ratioerr)   << endl;
  */

  float ndata    = hdata->Integral();
  float ndata1   = hdata->Integral(2,20);
  float ndata2   = hdata->Integral(3,20);
  float ndata3   = hdata->Integral(4,20);
  float ndata4   = hdata->Integral(5,20);
  float ndata5   = hdata->Integral(6,20);

  float nmc      = hmc->Integral();
  float nmc1     = hmc->Integral(2,20);
  float nmc2     = hmc->Integral(3,20);
  float nmc3     = hmc->Integral(4,20);
  float nmc4     = hmc->Integral(5,20);
  float nmc5     = hmc->Integral(6,20);

  float effdata1 = ndata1/ndata;
  float effdata2 = ndata2/ndata;
  float effdata3 = ndata3/ndata;
  float effdata4 = ndata4/ndata;
  float effdata5 = ndata5/ndata;

  float effmc1   = nmc1/nmc;
  float effmc2   = nmc2/nmc;
  float effmc3   = nmc3/nmc;
  float effmc4   = nmc4/nmc;
  float effmc5   = nmc5/nmc;

  float effdata1err = getBinomialError(ndata1,ndata);
  float effdata2err = getBinomialError(ndata2,ndata);
  float effdata3err = getBinomialError(ndata3,ndata);
  float effdata4err = getBinomialError(ndata4,ndata);
  float effdata5err = getBinomialError(ndata5,ndata);

  float effmc1err   = getBinomialError(nmc1,nmc);
  float effmc2err   = getBinomialError(nmc2,nmc);
  float effmc3err   = getBinomialError(nmc3,nmc);
  float effmc4err   = getBinomialError(nmc4,nmc);
  float effmc5err   = getBinomialError(nmc5,nmc);

  float ratio1      = effdata1/effmc1;
  float ratio2      = effdata2/effmc2;
  float ratio3      = effdata3/effmc3;
  float ratio4      = effdata4/effmc4;
  float ratio5      = effdata5/effmc5;

  float ratio1err   = ratio1 * sqrt(pow(effdata1err/effdata1,2)+pow(effmc1err/effmc1,2));
  float ratio2err   = ratio2 * sqrt(pow(effdata2err/effdata2,2)+pow(effmc2err/effmc2,2));
  float ratio3err   = ratio3 * sqrt(pow(effdata3err/effdata3,2)+pow(effmc3err/effmc3,2));
  float ratio4err   = ratio4 * sqrt(pow(effdata4err/effdata4,2)+pow(effmc4err/effmc4,2));
  float ratio5err   = ratio5 * sqrt(pow(effdata5err/effdata5,2)+pow(effmc5err/effmc5,2));

  //cout << endl << endl << plottitle << endl;

  int left = 20;


  // char* delimstart = "|";
  // char* delim      = "|";
  // char* delimend   = "|";
  // char* pm         = "+/-";

  char* delimstart = "";
  char* delim      = "&";
  char* delimend   = "\\\\";
  char* pm         = "$\\pm$";
  char* hline      = "\\hline";

  cout << endl;
  cout << hline << endl;
  cout << hline << endl;
  cout << delimstart << setw(10) << histLabel(plottitle) << setw(4)
       << delim << setw(left) << "$>$ 1 GeV" << setw(4)
       << delim << setw(left) << "$>$ 2 GeV" << setw(4)
       << delim << setw(left) << "$>$ 3 GeV" << setw(4) 
       << delim << setw(left) << "$>$ 4 GeV" << setw(4)
       << delim << setw(left) << "$>$ 5 GeV" << setw(4) 
       << delimend << endl;

  cout << hline << endl;
  cout << delimstart << setw(10) << "data" << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata1,pm,effdata1err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata2,pm,effdata2err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata3,pm,effdata3err) << setw(4) 
       << delim << setw(left) << Form("%.3f %s %.4f",effdata4,pm,effdata4err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata5,pm,effdata5err) << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "mc" << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc1,pm,effmc1err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc2,pm,effmc2err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc3,pm,effmc3err) << setw(4) 
       << delim << setw(left) << Form("%.3f %s %.4f",effmc4,pm,effmc4err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc5,pm,effmc5err) << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "data/mc" << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio1,pm,ratio1err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio2,pm,ratio2err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio3,pm,ratio3err) << setw(4) 
       << delim << setw(left) << Form("%.2f %s %.2f",ratio4,pm,ratio4err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio5,pm,ratio5err) << setw(4) 
       << delimend << endl;

  //--------------------------------------
  // draw stuff
  //--------------------------------------

  hdata->Scale(1.0/hdata->Integral());
  hmc->Scale(1.0/hmc->Integral());

  if( log ) hmc->GetYaxis()->SetRangeUser(0.0001,5);  
  else      hmc->GetYaxis()->SetRangeUser(0.0,1);  

  hmc->GetXaxis()->SetTitle(xtitle);
  hmc->SetLineColor(2);
  hmc->SetMarkerColor(2);
  hmc->DrawNormalized("hist");
  hmc->DrawNormalized("sameE1");
  hdata->SetLineColor(4);
  hdata->SetMarkerColor(4);
  hdata->Draw("sameE1");

  grdata->SetLineColor(6);
  grmc->SetLineColor(7);
  //grdata->Draw("sameP");
  //grmc->Draw("sameP");

  TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
  leg->AddEntry(hdata , "data" , "lp");
  leg->AddEntry(hmc   , "MC"   , "lp");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);			       
  leg->Draw();

  TLatex *t = new TLatex();
  t->SetNDC();

  if( TString(plottitle).Contains("el") ) t->DrawLatex(0.6,0.6,"electrons");
  if( TString(plottitle).Contains("mu") ) t->DrawLatex(0.6,0.6,"muons");

  if( TString(plottitle).Contains("0j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 0");
  if( TString(plottitle).Contains("1j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 1");
  if( TString(plottitle).Contains("2j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 2");
  if( TString(plottitle).Contains("3j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 3");
  if( TString(plottitle).Contains("4j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 4");

  //--------------------------------------
  // draw residual plots
  //--------------------------------------

  if( residual ){
    can->cd();
  
    TPad *respad = new TPad("respad","respad",0.0,0.8,1.0,1.0);
    respad->Draw();
    respad->cd();
    respad->SetGridy();

    TH1F* hratio = (TH1F*) hdata->Clone(Form("hratio_%i",iplot));
    hratio->Divide(hmc);

    hratio->SetMarkerColor(1);
    hratio->SetLineColor(1);
    hratio->Draw();
    hratio->GetYaxis()->SetRangeUser(0.5,1.5);
    hratio->GetYaxis()->SetNdivisions(5);
    hratio->GetYaxis()->SetLabelSize(0.2);
    hratio->GetXaxis()->SetLabelSize(0.0);
  
    TLine line;
    line.DrawLine(xmin,1.0,xmax,1.0);
  }
  
  //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel+"tkisonew>20");
  //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel);

  if( printplot ) can->Print(Form("plots/%s.pdf",plottitle));

  iplot++;

  // TCanvas *c2 = new TCanvas();
  // c2->cd();
  // grdata->Draw("AP");

}
Example #17
0
void fill_minEE_class::Loop()
{


   TFile *fpyt = new TFile("files/pythiaD6T_ee_v1.root");
   TTree *tree_pyt = (TTree*)gDirectory->Get("tree_");


   //   TFile *fpom = (TFile*)gROOT->GetListOfFiles()->FindObject("files/DiffractiveMC.root");
   TFile *fpom = new TFile("files/DiffractiveMC_ee_v1.root");
   TTree *tree_pom = (TTree*)gDirectory->Get("tree_");

   //   TFile *fzee = (TFile*)gROOT->GetListOfFiles()->FindObject("files/ZetaSkim_ee.root");
   TFile *fzee = new TFile("files/ZetaSkim_ee_v1.root");
   //   TFile *fzee = new TFile("files/ZetaSkim_mm.root");
   TTree *tree_zee = (TTree*)gDirectory->Get("tree_");



   //   Int_t hnbin = 25;
   Float_t llow = 0.;
   Float_t lup = 250.;
   TH1F *Hpompyt = new TH1F("Hpompyt", "pompyt", hnbin, llow, lup);
   TH1F *Hpythia = new TH1F("Hpythia", "pythia", hnbin, llow, lup);
   TH1F *Hdata = new TH1F("Hdata", "data", hnbin, llow, lup);
   TH1F *HSum = new TH1F("HSum", "HSum", hnbin, llow, lup);

   NCanvas(1,1);
   //Go to  Pythia

   fChain =tree_pyt;
   Init(fChain);


   Long64_t nentries = fChain->GetEntriesFast();   
   cout << "number of entries in Pythia = " << nentries << endl; 
   
   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;     
     if (numberOfVertexes == 1){
     Hpythia->Fill(TMath::Min(energyTot_PF_EE_minus,energyTot_PF_EE_plus));
     }
   }


   // go to Pompyt

   fChain = tree_pom;
   Init(fChain);
   nentries = fChain->GetEntriesFast();
   cout << "number of entries in Pompyt = " << nentries << endl; 
   
   nbytes = 0, nb = 0;
   for (jentry=0; jentry<nentries;jentry++) {
     ientry = LoadTree(jentry);
     if (ientry < 0) break;
     
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;
     if (numberOfVertexes == 1){
       Hpompyt->Fill(TMath::Min(energyTot_PF_EE_minus,energyTot_PF_EE_plus));
     }
   }
   
   
   // go to  Zee

   fChain = tree_zee;
   Init(fChain);
   nentries = fChain->GetEntriesFast();
   cout << "number of entries in Zee = " << nentries << endl; 
   nbytes = 0, nb = 0;
   for (jentry=0; jentry<nentries;jentry++) {
     ientry = LoadTree(jentry);
     if (ientry < 0) break;
     
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;
     //      Zee->cd();
     if (numberOfVertexes == 1){
     Hdata->Fill(TMath::Min(energyTot_PF_EE_minus,energyTot_PF_EE_plus));
     }
   }
     


   // Show the results

   MyC->cd(1);

   Hpythia->Draw();
   Hpompyt->Draw("SAMES");
   Hdata->Draw("SAMES");
   


  //  cout << Pcdata->lenght() << endl;

  NHtoV(Hdata, Pcdata, Pedata);
  NHtoV(Hpompyt, Pcpompyt, Pepompyt);
  NHtoV(Hpythia, Pcpythia, Pepythia);


 cout << " the content of data[2] is = " << Pcdata[2] << "+-"<<Pedata[2] << endl ;
 cout << " the content of pythia[2] is = " << Pcpythia[2] << "+-"<<Pepythia[2] << endl ;
 cout << " the content of pythia[2] is = " << Pcpompyt[2] << "+-"<<Pepompyt[2] << endl ;


 // Here  we go: the minuit show
 
  TMinuit *gMinuit = new TMinuit(NPAR);  //initialize TMinuit with a maximum of NPAR params
  gMinuit->SetFCN(fcn);
  
  Double_t arglist[NPAR]; // ???
  Int_t ierflg = 0;

// Set starting values and step sizes for parameters

  Double_t vstart[NPAR] ;
  Double_t step[NPAR] ;
  Double_t par[NPAR] ,fpar[NPAR];
  char parName[NPAR];
  Int_t n;
  parName[0] = "Pythia";
  parName[1] = "Pompyt";

  par[0] = Hdata->Integral()/Hpythia->Integral();
  par[1] = 0.05*Hdata->Integral()/Hpompyt->Integral();


  for (n=0 ; n<NPAR ; n++)
    {
      vstart[n] = par[n]  ;
      step[n] = 0.5 ;
      sprintf(parName,"a%d",n);
      gMinuit->mnparm(n, parName, vstart[n], step[n], 0,0,ierflg);
    }

  cout << "par[0] set to = " << par[0] << " while par[1] = " << par[1] << endl;
  arglist[0] = 1;

  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);  
  gMinuit->mnexcm("SET PRINT", arglist,1,ierflg);

  //Scan on parameter = 1
  arglist[0] = 1;
  gMinuit->mnexcm("SCAN",  arglist,1,ierflg);
  
  //Maximum number of calls
  arglist[0] = 500;
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
 


  // Print results
  Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;

  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(3,amin);


  //Get the final fit parameters
  for (n=0 ; n<NPAR ; n++)
    {
      Double_t parameter, erro ;
      gMinuit->GetParameter(n,parameter,erro) ;
      fpar[n] = parameter ;
    }
  
  cout << " The final parameter values are: "<< fpar[0] << " , " << fpar[1] << endl;

  Float_t SD_frac = (fpar[1]*Hpompyt->Integral())/Hdata->Integral();
  //  Float_t NSD_events = fpar[0]*Hpythia->Integral();
  // Float_t Data_events = Hdata->Integral();

  cout << " The fraction of SD events is = " << SD_frac << endl;


  // }
  // void fill_minEE_class::show(){


  //Show the final plot

  MyC->cd(1);

  Hpythia->Scale(fpar[0]); 
  Hpompyt->Scale(fpar[1]); 

  Hdata->SetMarkerColor(2);
  Hdata->GetXaxis()->SetTitle("Min(EE-,EE+) Energy [GeV] ");
  Hdata->GetYaxis()->SetTitle("Entries");
  Hpompyt->SetLineColor(4);
  Hpythia->SetLineColor(6);
  Hpompyt->SetLineStyle(2);
  Hpythia->SetLineStyle(2);
   
  Float_t DMax = 1.2*Hdata->GetMaximum();
  Hdata->SetMaximum(DMax);
  Hdata->Draw("p");

  Hpythia->Draw("SAMES");
  Hpompyt->Draw("SAMES");
  
  HSum->Add(Hpythia);
  HSum->Add(Hpompyt);
  HSum->SetLineColor(1);
  HSum->SetLineStyle(1);
  HSum->Draw("SAMES");

}
Example #18
0
void compareMet(){

  gStyle->SetOptStat(0);

  bool isData = true;

  char* file = "output/v8/ZJets_baby.root";
  if( isData ) file = "../../metTemplate/output/v8/lepdata_skim_baby.root";
  //if( isData ) file = "../output/V00-00-00/lepdata_skim_baby.root";
  //if( isData ) file = "output/uaf/lepdata_skim_baby.root";
  //if( isData ) file = "output/v8/lepdata_skim_nov4_baby_nov4json.root";
  //if( isData ) file = "output/uaf/lepdata_skim_baby.root";
  //if( isData ) file = "lepdata_skim_Nov4_baby.root";

  cout << "Adding " << file << endl;

  TFile *f = TFile::Open( file );

  TH1F* hee = new TH1F("hee","",75,0,150);
  TH1F* hmm = new TH1F("hmm","",75,0,150);
  TH1F* hem = new TH1F("hem","",75,0,150);

  TCut sel("njets>-1");
 
  TCut ee("leptype==0&&jetptll-ptll>-5&&jetptlt-ptlt>-5&&dilmass>81&&dilmass<101");
  //TCut ee("leptype==0&&dilmass>81&&dilmass<101");
  TCut mm("leptype==1&&nmatchedpfmuons==2&&dilmasspf>81&&dilmasspf<101");
  TCut em("leptype==2&&nmatchedpfmuons==1&&dilmass>81&&dilmass<101");

  //TCut ee("leptype==0&&jetptll-ptll>-5&&jetptlt-ptlt>-5");
  //TCut mm("leptype==1&&nmatchedpfmuons==2");
  //TCut em("leptype==2&&nmatchedpfmuons==1");

  //TCut weight("weight");
  TCut weight("1");

  TCanvas *c1 = new TCanvas();
  c1->cd();

  TPad *plotpad = new TPad("plotpad","plotpad",0.0,0.0,1.0,0.8);
  plotpad->Draw();
  plotpad->cd();

  TTree* T1 = (TTree*) f->Get("T1");

  T1->Draw("TMath::Min(pfmet,149.99)>>hee",(sel+ee)*weight);
  T1->Draw("TMath::Min(pfmet,149.99)>>hmm",(sel+mm)*weight);
  T1->Draw("TMath::Min(pfmet,149.99)>>hem",(sel+em)*weight);

  hee->Sumw2();
  hmm->Sumw2();
  hem->Sumw2();

  hmm->Draw();
  hmm->GetXaxis()->SetTitle("pfmet (GeV)");
  hee->SetLineColor(2);
  hee->SetMarkerColor(2);
  hem->SetLineColor(4);
  hem->SetMarkerColor(4);
  hmm->SetMarkerStyle(20);
  hem->SetMarkerStyle(24);
  hmm->SetMarkerSize(0.7);
  hee->Draw("samehist");
  hem->Draw("same");
  gPad->SetLogy(1);

  TLegend *leg = new TLegend(0.6,0.65,0.8,0.85);
  leg->AddEntry(hee,"ee","l");
  leg->AddEntry(hmm,"#mu#mu");
  leg->AddEntry(hem,"e#mu");
  leg->SetFillColor(0);
  leg->SetBorderSize(1);
  leg->Draw();

//   TLatex *t = new TLatex();
//   t->SetNDC();
//   if( isData ){
//     t->DrawLatex(0.4,0.6,  "CMS");
//     //t->DrawLatex(0.4,0.53, "Selected Z+#geq2jet Events (DATA)");
//     t->DrawLatex(0.4,0.53, "Selected Z Events (DATA)");
//     t->DrawLatex(0.4,0.46, "34.0 pb^{-1} at #sqrt{s} = 7 TeV");
//   }else{
//     t->DrawLatex(0.4,0.6, "CMS");
//     t->DrawLatex(0.4,0.53,"Selected Z+0jet Events (Z+jets MC)");
//   }

  c1->cd();

  TPad *pullpad = new TPad("pullpad","pullpad",0.0,0.8,1.0,1.0);
  pullpad->Draw();
  pullpad->cd();

  TH1F* hratio = (TH1F*) hmm->Clone();
  hratio->Divide(hee);
  hratio->Draw();
  gPad->SetGridy();
  hratio->SetMinimum(0.8);
  hratio->SetMaximum(1.6);
  hratio->GetYaxis()->SetLabelSize(0.15);
  hratio->GetYaxis()->SetNdivisions(7);
  hratio->GetYaxis()->SetTitle("#mu#mu / ee  ");
  hratio->GetXaxis()->SetTitle("");
  hratio->GetYaxis()->SetTitleSize(0.2);
  hratio->GetYaxis()->SetTitleOffset(0.2);

  float cut1 = 30;
  float cut2 = 60;
  float cut3 = 120;

  int bin1 = hee->FindBin(cut1);
  int bin2 = hee->FindBin(cut2);
  int bin3 = hee->FindBin(cut3);
  
  cout << "ee tot         " << hee->Integral() << endl;
  cout << "ee met>30  GeV " << hee->Integral(bin1,1000) << endl;
  cout << "ee met>60  GeV " << hee->Integral(bin2,1000) << endl;
  cout << "ee met>120 GeV " << hee->Integral(bin3,1000) << endl;

  cout << "mm tot         " << hmm->Integral() << endl;
  cout << "mm met>30  GeV " << hmm->Integral(bin1,1000) << endl;
  cout << "mm met>60  GeV " << hmm->Integral(bin2,1000) << endl;
  cout << "mm met>120 GeV " << hmm->Integral(bin3,1000) << endl;

  int width1 = 15;
  int width2 =  5;

  cout << "|" << setw(width1) << ""               << setw(width2)
       << "|" << setw(width1) << Form("N(met>%.0f GeV)",cut1)  << setw(width2)
       << "|" << setw(width1) << Form("N(met>%.0f GeV)",cut2)  << setw(width2)
       << "|" << setw(width1) << Form("N(met>%.0f GeV)",cut3)  << setw(width2) 
       << "|" << endl;

  cout << "|" << setw(width1) << "ee"                       << setw(width2)
       << "|" << setw(width1) << hee->Integral(bin1,1000)  << setw(width2)
       << "|" << setw(width1) << hee->Integral(bin2,1000)  << setw(width2)
       << "|" << setw(width1) << hee->Integral(bin3,1000) << setw(width2) 
       << "|" << endl;

  cout << "|" << setw(width1) << "mm"                       << setw(width2)
       << "|" << setw(width1) << hmm->Integral(bin1,1000)  << setw(width2)
       << "|" << setw(width1) << hmm->Integral(bin2,1000)  << setw(width2)
       << "|" << setw(width1) << hmm->Integral(bin3,1000) << setw(width2) 
       << "|" << endl;

  cout << "|" << setw(width1) << "em"                       << setw(width2)
       << "|" << setw(width1) << hem->Integral(bin1,1000)  << setw(width2)
       << "|" << setw(width1) << hem->Integral(bin2,1000)  << setw(width2)
       << "|" << setw(width1) << hem->Integral(bin3,1000) << setw(width2) 
       << "|" << endl;
}
Example #19
0
void draw_tt(std::string var="mTT",int nbins=10, double xmin=0, double xmax=200,std::string xtitle="m_{#tau#tau}", std::string ytitle="Events")
{
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);

  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/vbf/ntuples/";
  double sigscale = 10;
  double sigscale1 = 10; 
  std::stringstream scale; scale << sigscale;
  std::stringstream scale1; scale1 << sigscale1;

  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(ptTau1>45 && ptTau2>45 && abs(etaTau1) <4.0 && abs(etaTau1)<4.0 )";
  std::string jetcut = objcut+"*(ptJet1>30 && ptJet2>30 && abs(etaJet1) <4.7 && abs(etaJet2) <4.7 )";
  std::string ththcut = jetcut+"*(tauCat1==1 && tauCat2==1 && mJJ>500 && abs(dEta)>3.5)";

  //signal region
  std::string vbfcut = ththcut+"*eventWeight*(eventType==0)*"+lumi.str();
  std::string zttcut = ththcut+"*eventWeight*(eventType==1)*"+lumi.str();
  std::string ttbarcut = ththcut+"*eventWeight*(eventType==3)*"+lumi.str();
  //std::string ewkcut = ththcut+"*eventWeight*(eventType==2)*"+lumi.str();
  std::string othercut = ththcut+"*eventWeight*(eventType==4 || eventType==2)*"+lumi.str();
  
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *tree = load(dir+"vbf_comb.root"); 

  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  TH1F *vbf = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  tree->Draw(vardraw.c_str(),vbfcut.c_str());
  InitSignal(vbf);
  vbf->SetLineColor(kBlack);
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  tree->Draw(vardraw.c_str(),ttbarcut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  TH1F *ztt = new TH1F("Ztt","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ztt";
  tree->Draw(vardraw.c_str(),zttcut.c_str());
  InitHist(ztt, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);
  //TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  //vardraw = var+">>"+"Ewk";
  //tree->Draw(vardraw.c_str(),ewkcut.c_str());
  //InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *other = new TH1F("Other","",nbins,xmin,xmax);
  vardraw = var+">>"+"Other";
  tree->Draw(vardraw.c_str(),othercut.c_str());
  InitHist(other, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  
  delete canv0;
  //----------------------------------------------------------------------------
  //Print out the yields
  Double_t error=0.0;
  ofstream outfile;
  outfile.open("yields_tt.txt");
  outfile << "Yields for the signal region." << std::endl;
  outfile << "VBF   "  << vbf->IntegralAndError(0,vbf->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "TTbar   "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(0,ztt->GetNbinsX(),error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "other   "  << other->IntegralAndError(0,other->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "S/sqrt(B)    "  << vbf->Integral()/(other->Integral()+ztt->Integral()+ttbar->Integral()/*+ewk->Integral()*/) << endl;
  //--------------------------------------------------------------------------
  //continue outputing
  //outfile << "Ewk total    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << endl << endl << endl;
  outfile << "In the signal region (100,150GeV)  " <<endl;
  outfile << "VBF   "  << vbf->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "TTbar    "  << ttbar->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(5,11,error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "other    "  << other->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile.close();
  //-----------------------------------------------------------------------
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //ewk->Add(other); ttbar->Add(ewk); 
  //ztt->Add(ttbar); vbf->Add(ztt);
  //Error band stat
  TH1F* errorBand = (TH1F*)vbf ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ztt->SetMaximum(1.2*std::max(maximum(ttbar, 0), maximum(ztt, 0)));
  //blind(vbf,75,150);
  ztt->Draw("hist");
  ttbar->Draw("histsame");
  //ewk->Draw("histsame");
  other->Draw("histsame");
  vbf->Draw("histsame");
  //errorBand->Draw("e2same");
  canv->RedrawAxis();
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(vbf , "VBF Signal"             , "F");
  leg->AddEntry(ztt  , "Z#rightarrow#tau#tau"  , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"              , "F" );
  //leg->AddEntry(ewk  , "Electroweak"           , "F" );
  leg->AddEntry(other, "Other"                 , "F" );
  //leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
  
  //CMS preliminary 
  const char* dataset = "CMS Preliminary, H#rightarrow#tau#tau, 3.0 ab^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_tt.png").c_str());
  
  /*
    Ratio Data over MC
    
    TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
    canv1->SetGridx();
    canv1->SetGridy();
    canv1->cd();
  */
  /*   TH1F* model = (TH1F*)ztt ->Clone("model");
       TH1F* test1 = (TH1F*)data->Clone("test1"); 
       for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
       //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
       model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
       //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
       model->SetBinError  (ibin+1, 0);
     test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
     test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
   }
   double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
   double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
   double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
   double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

   std::vector<double> edges;
   TH1F* zero = (TH1F*)ttbar->Clone("zero"); zero->Clear();
   TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
   for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
     rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
     rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
     zero->SetBinContent(ibin+1, 0.);
     zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
   }
   for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
     if(rat1->GetBinContent(ibin+1)>0){
       edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
       // catch cases of 0 bins, which would lead to 0-alpha*0-1
       rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
     }
   }
   float range = 0.1;
   std::sort(edges.begin(), edges.end());
   if (edges[edges.size()-2]>0.1) { range = 0.2; }
   if (edges[edges.size()-2]>0.2) { range = 0.5; }
   if (edges[edges.size()-2]>0.5) { range = 1.0; }
   if (edges[edges.size()-2]>1.0) { range = 1.5; }
   if (edges[edges.size()-2]>1.5) { range = 2.0; }
   rat1->SetLineColor(kBlack);
   rat1->SetFillColor(kGray );
   rat1->SetMaximum(+range);
   rat1->SetMinimum(-range);
   rat1->GetYaxis()->CenterTitle();
   rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
   rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
   rat1->Draw();
   zero->SetFillStyle(  3013);
   zero->SetFillColor(kBlack);
   zero->SetLineColor(kBlack);
   zero->SetMarkerSize(0.1);
   zero->Draw("e2histsame");
   canv1->RedrawAxis();

   TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
   stat1->SetBorderSize(   0 );
   stat1->SetFillStyle(    0 );
   stat1->SetTextAlign(   12 );
   stat1->SetTextSize ( 0.05 );
   stat1->SetTextColor(    1 );
   stat1->SetTextFont (   62 );
   stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
   //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
   //stat1->Draw();
   canv1->Print((var+"_ratio.png").c_str());*/
}
Example #20
0
void DeltaPhi(double pt1_cutIN,double pt2_cutIN,double MET_cutIN, double DPHI_cutIN){
  cout<<"#### DeltaPhi(MET,H) #####"<<endl;


 

  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  TLegend* leg = new TLegend(0.13,0.6,0.67,0.87);
  leg->SetNColumns(2);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  TLegend* leg_norm = new TLegend(0.20,0.5,0.74,0.87);
  leg_norm->SetNColumns(2);
  leg_norm->SetBorderSize(0);
leg_norm->SetFillStyle(0);


 TCanvas *c1 = new TCanvas("c1","",500,600);
 TPad *mainPad = new TPad("mainPad","",0,0.3,1,1);
 TPad *smallPad = new TPad("smallPad","",0,0.05,1,0.3);
 mainPad->SetBottomMargin(0.015);

 
 smallPad->SetTopMargin(0.05);
 smallPad->SetBottomMargin(0.25);
 
 c1->cd();
 
 mainPad->Draw();
 mainPad->cd();
 TCut mggmax = "mgg<180";
 TCut mggmin = "mgg>100";
 TCut mggblind = "((mgg<115)||(mgg>135))";
 TCut eveto1 = "eleveto1 == 1";
 TCut eveto2 = "eleveto2 == 1";
 TCut eveto = eveto1 && eveto2;
 TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  TCut pt1cut = Form("pt1/mgg>%lf",pt1_cutIN);
  TCut pt2cut = Form("pt2/mgg>%lf",pt2_cutIN);  
  TCut METcutD = Form("t1pfmetCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,1)>%lf",MET_cutIN);  
  TCut METcut = Form("t1pfmetCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0)>%lf",MET_cutIN);  
  TCut DPHIcut = Form("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>%lf",DPHI_cutIN);  
  TCut DPHIcutD = Form("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,1))>%lf",DPHI_cutIN);  
 
  
 

  TFile *data = TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");  
  TFile *sig1 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP600.root","READ");
  TFile *sig2 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP800.root","READ");
  TFile *sig3 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1000.root","READ");
  TFile *sig4 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1200.root","READ");
  TFile *sig5 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1400.root","READ");  
  TFile *sig6 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1700.root","READ");  
  TFile *sig7 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP2500.root","READ");  

 
  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ");  
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");  
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");  
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");  
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");  
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");

  cout<<"check1"<<endl; 

 
  TTree *tree_data = (TTree*) data->Get("DiPhotonTree");
  
  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree");
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree");
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree");
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree");
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree");
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");
  
  
  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10= (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");


  cout<<"check2"<<endl; 

  
  
  tree_data->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,1))>>hdata(15,0,3.5)",(mggmax && mggmin && metF && eveto && pt1cut && pt2cut && METcutD&& DPHIcutD));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");
  hdata->SetMarkerColor(kBlack);
  hdata->SetMarkerStyle(20);
  hdata->SetLineColor(kBlack);
    
 
 
  
  tree_sig1->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h1(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h2(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h3(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h4(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h5(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h6(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h7(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");
 
  tree_bkg1->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg1(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg2(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg3(15,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
  tree_bkg4->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg4(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut)); //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg5(15,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg6(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));   //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");
  tree_bkg7->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg7(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples   
   TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");
    tree_bkg8->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg8(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");
   tree_bkg9->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg9(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");
   tree_bkg10->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg10(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");
   tree_bkg11->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg11(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");
   tree_bkg12->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg12(15,0,3.5)","weight*(weight>0.)"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");

 
   cout<<"check3"<<endl; 


  /*  h1->Scale(0.00009338);
  h2->Scale(0.00010348);
  h3->Scale(0.00008394);
  h4->Scale(0.00006352);
  h5->Scale(0.00004712);
  h6->Scale(0.00003020);
  h7->Scale(0.00000972);
  */


  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4); //only for 15ns samples
  h6->SetLineColor(kPink+7); //only for 15ns samples
  h7->SetLineColor(kMagenta+2); //only for 15ns samples
  h1->SetLineWidth(2);
  h2->SetLineWidth(2);
  h3->SetLineWidth(2);
  h4->SetLineWidth(2);
  h5->SetLineWidth(2); //only for 15ns samples
  h6->SetLineWidth(2); //only for 15ns samples
  h7->SetLineWidth(2); //only for 15ns samples
  
  





  
  
   THStack *hs=new THStack("hs","");

   hbkg7->SetFillColor(kGreen+2);
   hbkg6->SetFillColor(kGreen);
   hbkg8->SetFillColor(kYellow);
   hbkg4->SetFillColor(kOrange);
   hbkg9->SetFillColor(kOrange+7);
   hbkg10->SetFillColor(kOrange+4);
   hbkg11->SetFillColor(kCyan);
   hbkg12->SetFillColor(kCyan+1);
   hbkg5->SetFillColor(kBlue+2);
   hbkg2->SetFillColor(kBlue);
   hbkg3->SetFillColor(kMagenta-2);
   hbkg1->SetFillColor(kViolet);


 


  hbkg1->SetLineColor(kBlack);
  hbkg2->SetLineColor(kBlack);
  hbkg3->SetLineColor(kBlack);
  hbkg4->SetLineColor(kBlack);
  hbkg5->SetLineColor(kBlack);
  hbkg6->SetLineColor(kBlack);
  hbkg7->SetLineColor(kBlack);
  hbkg8->SetLineColor(kBlack);
  hbkg9->SetLineColor(kBlack);
  hbkg10->SetLineColor(kBlack);
  hbkg11->SetLineColor(kBlack);
  hbkg12->SetLineColor(kBlack);
  

  hs->Add(hbkg7);
  hs->Add(hbkg6);
  hs->Add(hbkg8);
  hs->Add(hbkg4);
  hs->Add(hbkg9);
  hs->Add(hbkg10);
  hs->Add(hbkg11);
  hs->Add(hbkg12);
  hs->Add(hbkg2);
  hs->Add(hbkg5);
  hs->Add(hbkg3);
  hs->Add(hbkg1);


  cout<<"check4"<<endl;  

    TH1F *hsum = (TH1F*)hbkg1->Clone("hsum"); 
  hsum->Add(hbkg2);
  hsum->Add(hbkg3);
  hsum->Add(hbkg4);
  hsum->Add(hbkg9);
  hsum->Add(hbkg10);
  hsum->Add(hbkg11);
  hsum->Add(hbkg12);
  hsum->Add(hbkg5);
  hsum->Add(hbkg6);
  hsum->Add(hbkg7);
  hsum->Add(hbkg8);
  hdata->SetMaximum(5000);
  // hs->SetMinimum(0.0001);
  hdata->SetTitle("");
  hdata->Draw("e1"); 

  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3002);
  
  hs->Draw("same hist");
  hsum->Draw("same e2");
  h2->Draw("same hist");
  h3->Draw("same hist"); 
  h4->Draw("same hist");
  h1->Draw("same hist");
  h5->Draw("same hist"); //only for 15ns samples
  h6->Draw("same hist"); //only for 15ns samples
  h7->Draw("same hist"); //only for 15ns samples
  hdata->Draw("same e1");  
  

  hdata->GetXaxis()->SetLabelOffset(999);
  hdata->GetYaxis()->SetTitle("Events/0.4");
 

  hdata->GetYaxis()->SetTitleOffset(1.6);
  hdata->GetYaxis()->SetTitle("Events/0.23 GeV");  
  gPad->Modified();
  
  
  
  /*leg->AddEntry(h1,"m_{#chi} = 1 GeV","l");
    leg->AddEntry(h2,"m_{#chi} = 10 GeV","l");
    leg->AddEntry(h3,"m_{#chi} = 100 GeV","l");      
    leg->AddEntry(h4,"m_{#chi} = 1000 GeV","l");*/
 leg->AddEntry(hdata,"Data","elp");
 // leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");
  leg->AddEntry(hbkg1,"#gamma #gamma","f");         
  //  leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");
  leg->AddEntry(hbkg2,"Drell Yann","f");       
  // leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");      
  leg->AddEntry(hbkg3,"#gamma + Jets","f");      
  // leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");     
  leg->AddEntry(hbkg5,"QCD","f");    
  // leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l"); //only for 15ns samples    
    leg->AddEntry(hbkg4,"ggH","f");      
    // leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l"); //only for 15ns samples    
  leg->AddEntry(hbkg6,"VH","f");  
  // leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples      
  leg->AddEntry(hbkg7,"ttH","f");  
  leg->AddEntry(hbkg8,"VBF H","f");  
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");  
  leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");  
  leg->AddEntry(hbkg11,"#gamma+W","f");  
  leg->AddEntry(hbkg12,"#gamma+Z","f");  
  leg->AddEntry(hsum,"Bkg uncertainty","f");
  leg->Draw("same");
  
 cout<<"check5"<<endl; 

  gStyle->SetOptStat(0);  
  
  c1->cd();
  smallPad->Draw();
  smallPad->cd();

  TGraphErrors *gr = new TGraphErrors(0);
  double integralData=hdata->Integral();
  double integralBKG=hsum->Integral();
  double error, ratio;
  for(int w=1; w<15; w++){
    if((hdata->GetBinContent(w)!=0) && (hsum->GetBinContent(w)!=0)){

      gr->SetPoint(w, hdata->GetBinCenter(w),(hdata->GetBinContent(w))/(hsum->GetBinContent(w)));
      ratio= (hdata->GetBinContent(w))/(hsum->GetBinContent(w));
      error= (hdata->GetBinContent(w)*sqrt(hsum->GetBinContent(w))/(hsum->GetBinContent(w)*hsum->GetBinContent(w)) + sqrt(hdata->GetBinContent(w))/hsum->GetBinContent(w));
      std::cout<<"VALUE: "<<ratio<<" ERROR: "<<error<<std::endl;
      gr->SetPointError(w, hdata->GetBinWidth(w)/2,error);
    }else{
      gr->SetPoint(w, hdata->GetBinCenter(w),10);
    }
  }



  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  gr->GetHistogram()->SetMaximum(2);
  gr->GetHistogram()->SetMinimum(0.1);

  gStyle->SetTextSize(14);
  gROOT->ForceStyle();

  gr->GetXaxis()->SetLabelFont(43);
  gr->GetXaxis()->SetLabelSize(15);
  gr->GetYaxis()->SetLabelFont(43);
  gr->GetYaxis()->SetLabelSize(15);

  gr->GetXaxis()->SetLimits(0,3.5);
  gPad->SetGrid();
  gStyle->SetStripDecimals(kTRUE);
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(0.7);


  gr->Draw("AZP");
  gr->GetXaxis()->SetTitle("|#Delta#phi(#gamma#gamma,E^{miss}_{T})|");
  gr->GetXaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetNdivisions(505);

  gr->GetXaxis()->SetTitleOffset(1);
  gr->GetYaxis()->SetTitle("Data/MC");
  gr->GetYaxis()->SetTitleOffset(0.4);
  gr->SetTitle("");
  smallPad->Update();
  TF1* line = new TF1("line","1",0,3.5);
  line->SetLineColor(kRed);
  line->SetLineWidth(2);
  line->Draw("L same");
  gr->Draw("ZP SAME");

 

TCanvas *c2 = new TCanvas("c2","",500,500);
    

  tree_sig1->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h1_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h1_norm =(TH1F*)gPad->GetPrimitive("h1_norm");
  tree_sig2->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h2_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h2_norm =(TH1F*)gPad->GetPrimitive("h2_norm");
  tree_sig3->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h3_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h3_norm =(TH1F*)gPad->GetPrimitive("h3_norm");
  tree_sig4->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h4_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h4_norm =(TH1F*)gPad->GetPrimitive("h4_norm");
  tree_sig5->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h5_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h5_norm =(TH1F*)gPad->GetPrimitive("h5_norm");
  tree_sig6->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h6_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h6_norm =(TH1F*)gPad->GetPrimitive("h6_norm");
  tree_sig7->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h7_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h7_norm =(TH1F*)gPad->GetPrimitive("h7_norm");
  




  tree_bkg1->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg1_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg1_norm =(TH1F*)gPad->GetPrimitive("hbkg1_norm");
  tree_bkg2->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg2_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg2_norm =(TH1F*)gPad->GetPrimitive("hbkg2_norm");
  tree_bkg3->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg3_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg3_norm =(TH1F*)gPad->GetPrimitive("hbkg3_norm");
  tree_bkg4->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg4_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut)); //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg4_norm =(TH1F*)gPad->GetPrimitive("hbkg4_norm");
  tree_bkg5->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg5_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg5_norm =(TH1F*)gPad->GetPrimitive("hbkg5_norm");
  tree_bkg6->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg6_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));   //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg6_norm =(TH1F*)gPad->GetPrimitive("hbkg6_norm");
  tree_bkg7->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg7_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples   
   TH1F *hbkg7_norm =(TH1F*)gPad->GetPrimitive("hbkg7_norm");
    tree_bkg8->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg8_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg8_norm =(TH1F*)gPad->GetPrimitive("hbkg8_norm");
   tree_bkg9->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg9_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg9_norm =(TH1F*)gPad->GetPrimitive("hbkg9_norm");
   tree_bkg10->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg10_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg10_norm =(TH1F*)gPad->GetPrimitive("hbkg10_norm");
   tree_bkg11->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg11_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg11_norm =(TH1F*)gPad->GetPrimitive("hbkg11_norm");
   tree_bkg12->Draw("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg12_norm(15,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg12_norm =(TH1F*)gPad->GetPrimitive("hbkg12_norm");


   for(int i = 0; i<26;i++){
     if(hbkg1_norm->GetBinContent(i) < 0.) hbkg1_norm->SetBinContent(i,0.);
     if(hbkg2_norm->GetBinContent(i) < 0.) hbkg2_norm->SetBinContent(i,0.);
     if(hbkg3_norm->GetBinContent(i) < 0.) hbkg3_norm->SetBinContent(i,0.);
     if(hbkg4_norm->GetBinContent(i) < 0.) hbkg4_norm->SetBinContent(i,0.);
     if(hbkg5_norm->GetBinContent(i) < 0.) hbkg5_norm->SetBinContent(i,0.);
     if(hbkg6_norm->GetBinContent(i) < 0.) hbkg6_norm->SetBinContent(i,0.);
     if(hbkg7_norm->GetBinContent(i) < 0.) hbkg7_norm->SetBinContent(i,0.);
     if(hbkg8_norm->GetBinContent(i) < 0.) hbkg8_norm->SetBinContent(i,0.);
     if(hbkg9_norm->GetBinContent(i) < 0.) hbkg9_norm->SetBinContent(i,0.);
     if(hbkg10_norm->GetBinContent(i) < 0.) hbkg10_norm->SetBinContent(i,0.);
     if(hbkg11_norm->GetBinContent(i) < 0.) hbkg11_norm->SetBinContent(i,0.);
     if(hbkg12_norm->GetBinContent(i) < 0.) hbkg12_norm->SetBinContent(i,0.);
   }




  double norm = 1./h1_norm->Integral();
  h1_norm->Scale(norm);
  norm = 1./h2_norm->Integral();
  h2_norm->Scale(norm);
  norm = 1./h3_norm->Integral();
  h3_norm->Scale(norm);
  norm = 1./h4_norm->Integral();
  h4_norm->Scale(norm);  
  norm = 1./h5_norm->Integral(); //only for 50ns samples
  h5_norm->Scale(norm);  //only for 50ns samples
  norm = 1./h6_norm->Integral(); //only for 50ns samples
  h6_norm->Scale(norm);  //only for 50ns samples
  norm = 1./h7_norm->Integral(); //only for 50ns samples
  h7_norm->Scale(norm);  //only for 50ns samples
  


  norm = 1./hbkg1_norm->Integral();
  hbkg1_norm->Scale(norm);  
  norm = 1./hbkg2_norm->Integral();
  hbkg2_norm->Scale(norm);  
  norm = 1./hbkg3_norm->Integral();
  hbkg3_norm->Scale(norm);  
  norm = 1./hbkg4_norm->Integral();
  hbkg4_norm->Scale(norm);  
  norm = 1./hbkg5_norm->Integral();
  hbkg5_norm->Scale(norm);  
  norm = 1./hbkg6_norm->Integral();
  hbkg6_norm->Scale(norm);  
  norm = 1./hbkg7_norm->Integral();
  hbkg7_norm->Scale(norm);  
  norm = 1./hbkg8_norm->Integral();
  hbkg8_norm->Scale(norm);  
  norm = 1./hbkg9_norm->Integral();
  hbkg9_norm->Scale(norm);  
  norm = 1./hbkg10_norm->Integral();
  hbkg10_norm->Scale(norm);  
  norm = 1./hbkg11_norm->Integral();
  hbkg11_norm->Scale(norm);  
  norm = 1./hbkg12_norm->Integral();
  hbkg12_norm->Scale(norm);  
  
  
  h1_norm->SetLineColor(kRed+3);
  h2_norm->SetLineColor(kRed+1);
  h3_norm->SetLineColor(kRed);
  h4_norm->SetLineColor(kPink+2);
  h5_norm->SetLineColor(kPink+4); //only for 25ns samples
  h6_norm->SetLineColor(kPink+7); //only for 25ns samples
  h7_norm->SetLineColor(kMagenta+2); //only for 25ns samples
  h1_norm->SetLineWidth(2);
  h2_norm->SetLineWidth(2);
  h3_norm->SetLineWidth(2);
  h4_norm->SetLineWidth(2);
  h5_norm->SetLineWidth(2); //only for 25ns samples
  h6_norm->SetLineWidth(2); //only for 25ns samples
  h7_norm->SetLineWidth(2); //only for 25ns samples



  hbkg7_norm->SetLineColor(kGreen+2);
  hbkg6_norm->SetLineColor(kGreen);
  hbkg8_norm->SetLineColor(kYellow);
  hbkg4_norm->SetLineColor(kOrange);
  hbkg9_norm->SetLineColor(kOrange+7);
  hbkg10_norm->SetLineColor(kOrange+4);
  hbkg11_norm->SetLineColor(kCyan);
  hbkg12_norm->SetLineColor(kCyan+1);
  hbkg5_norm->SetLineColor(kBlue+3);
  hbkg2_norm->SetLineColor(kBlue);
  hbkg3_norm->SetLineColor(kMagenta-2);
  hbkg1_norm->SetLineColor(kViolet);

 
 
 
  
  
  hbkg1_norm->SetFillStyle(0);
  hbkg2_norm->SetFillStyle(0);
  hbkg3_norm->SetFillStyle(0);
  hbkg4_norm->SetFillStyle(0);
  hbkg5_norm->SetFillStyle(0);
  hbkg6_norm->SetFillStyle(0);
  hbkg7_norm->SetFillStyle(0); 
  hbkg8_norm->SetFillStyle(0);
  hbkg9_norm->SetFillStyle(0);
  hbkg10_norm->SetFillStyle(0);
  hbkg11_norm->SetFillStyle(0);
  hbkg12_norm->SetFillStyle(0);
  
  
   
  h1_norm->SetTitle("");
  
  h1_norm->SetMaximum(1);  
  h1_norm->SetMinimum(0.001);  
  h1_norm->Draw("HIST"); 
  
  hbkg1_norm->Draw("same HIST");  
  hbkg2_norm->Draw("same HIST"); 
  hbkg3_norm->Draw("same HIST"); 
  hbkg5_norm->Draw("same HIST"); 
  hbkg4_norm->Draw("same HIST"); 
  hbkg6_norm->Draw("same HIST"); 
  hbkg7_norm->Draw("same HIST"); 
  hbkg8_norm->Draw("same HIST"); 
  hbkg9_norm->Draw("same HIST"); 
  hbkg10_norm->Draw("same HIST"); 
  hbkg11_norm->Draw("same HIST"); 
  hbkg12_norm->Draw("same HIST"); 
  h1_norm->Draw("same hist"); 
  h2_norm->Draw("same hist");
  h3_norm->Draw("same hist"); 
  h4_norm->Draw("same hist");
  h5_norm->Draw("same hist");
  h6_norm->Draw("same hist");
  h7_norm->Draw("same hist");
  
  h1_norm->GetXaxis()->SetTitle("|#Delta#phi(#gamma#gamma,E_{T}^{miss})|");
  h1_norm->GetYaxis()->SetTitle("Normalized events");  
  h1_norm->GetYaxis()->SetTitleOffset(1.2);  
  gPad->Modified();
  gStyle->SetOptStat(0);
  
  
  //int iPos =0;                                                                                                                 
  //  CMS_lumi(p1,true,iPos,true);                                                                                               
  // CMS_lumi(p2,true,iPos,true);   
  
  leg_norm->AddEntry(h1_norm,"m_{Z'} = 600 GeV","l");
  leg_norm->AddEntry(hbkg1_norm,"#gamma #gamma","l");      
  leg_norm->AddEntry(h2_norm,"m_{Z'} = 800 GeV","l");
  leg_norm->AddEntry(hbkg2_norm,"Drell Yann","l");      
  leg_norm->AddEntry(h3_norm,"m_{Z'} = 1000 GeV","l");      
  leg_norm->AddEntry(hbkg3_norm,"#gamma + Jets","l");      
  leg_norm->AddEntry(h4_norm,"m_{Z'} = 1200 GeV","l");    
  leg_norm->AddEntry(hbkg5_norm,"QCD","l");     
  leg_norm->AddEntry(h5_norm,"m_{Z'} = 1400 GeV","l"); //only for 25ns samples    
  leg_norm->AddEntry(hbkg4_norm,"ggH","l");      
  leg_norm->AddEntry(h6_norm,"m_{Z'} = 1700 GeV","l"); //only for 25ns samples    
  leg_norm->AddEntry(hbkg6_norm,"VH","l");   
  leg_norm->AddEntry(h7_norm,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples      
  leg_norm->AddEntry(hbkg7_norm,"ttH","l");  
  leg_norm->AddEntry(hbkg8_norm,"VBF H","l");   
  leg_norm->AddEntry(hbkg9_norm,"t + #gamma + Jets","l");  
  leg_norm->AddEntry(hbkg10_norm,"tt + #gamma +Jets","l");  
  leg_norm->AddEntry(hbkg11_norm,"#gamma+W","l");  
  leg_norm->AddEntry(hbkg12_norm,"#gamma+Z","l");  
  leg_norm->Draw("same");
  
  if(pt1_cutIN==0. && pt2_cutIN == 0. && MET_cutIN == 0.){
    c1->SaveAs("./25ns_2246inv_v3/plots/kinematics/DeltaPhi_H_MET_MET0.png");
    c1->SaveAs("./25ns_2246inv_v3/plots/kinematics/DeltaPhi_H_MET_MET0.pdf");
 c2->SaveAs("./25ns_2246inv_v3/plots/kinematics/DeltaPhi_H_MET_MET0_norm.png");
    c2->SaveAs("./25ns_2246inv_v3/plots/kinematics/DeltaPhi_H_MET_MET0_norm.pdf");
  }
  
}
void compareSherpaMadgraph(std::string sherpafile, std::string madgraphfile,
                           std::string var,
                           float xmin=-9999.0, float xmax=-9999.0,
                           bool logScale=false,
                           std::string output="test")
{

    setTDRStyle();
    gStyle->SetOptStat(0);

    TH1F* hsherpa;
    TH1F* hmadgraph;

    char tempName[300];


    // first get the histogram files
    TFile *fsherpa = TFile::Open(sherpafile.data());
    TFile *fmadgraph   = TFile::Open(madgraphfile.data());

    hsherpa  = (TH1F*)(fsherpa->Get(var.data()));
    hmadgraph    = (TH1F*)(fmadgraph->Get(var.data()));

    TH1D* hscale =(TH1D*) hsherpa->Clone("hscale");
    hscale->SetYTitle("SHERPA/MADGRAPH");

    int nREBIN=2;
    if(var.find("pt")!= std::string::npos)
        nREBIN=4;

    hsherpa->GetXaxis()->SetNdivisions(5);
    hsherpa->GetYaxis()->SetDecimals();
    hsherpa->Rebin(nREBIN);

    hmadgraph->GetXaxis()->SetNdivisions(5);
    hmadgraph->GetYaxis()->SetDecimals();
    hmadgraph->Rebin(nREBIN);

    hscale->GetXaxis()->SetNdivisions(5);
    hscale->GetYaxis()->SetDecimals();
    hscale->Rebin(nREBIN);

    hsherpa->SetLineColor(2);
    hsherpa->SetMarkerColor(2);
    hsherpa->SetMarkerSize(1);
    hsherpa->SetMarkerStyle(24);


    hmadgraph->SetLineColor(4);
    hmadgraph->SetMarkerColor(4);
    hmadgraph->SetMarkerSize(1);
    hmadgraph->SetMarkerStyle(21);

    // if normalizing to the same area, set the scale

    int binLo = -1;
    int binHi = -1;
    int nbins = hsherpa->GetNbinsX();
    if(xmin>-9999.0 && xmax>-9999.0)
    {

        binLo = hsherpa->FindBin(xmin);
        binHi = hsherpa->FindBin(xmax)-1;

    }

    else
    {
        binLo = 1;
        binHi = nbins;
        xmin = hsherpa->GetBinLowEdge(1);
        xmax = hsherpa->GetBinLowEdge(nbins+1);
    }


    //   float scale_mc = (float)hsherpa->Integral(binLo,binHi)/(float)hmadgraph->Integral(binLo,binHi);
    //   cout << "binLo = " << binLo << ", binHi = " << binHi << endl;
    //   cout << "xmin = " << xmin << "xmax = " << xmax << endl;

    //   hmadgraph->Sumw2();
    //   hmadgraph->Scale(scale_mc);

    float scale_sherpa   = 1000.0*4.890*3048.0/4.71644910071102437e+06;

    float scale_madgraph = 1000.0*4.890*3048.0/3.59644320000000000e+07;

    hsherpa->Sumw2();
    hsherpa->Scale(scale_sherpa);

    hmadgraph->Sumw2();
    hmadgraph->Scale(scale_madgraph);

    cout << "hmadgraph integral = " << hmadgraph->Integral() << endl;
    cout << "hsherpa integral = "   << hsherpa->Integral() << endl;;

    // get the ratio
    double chi2 = 0;
    int realbin = 0;
    for(int i=1; i<= nbins; i++) {

        double nmc=hmadgraph->GetBinContent(i);
        double ndata=hsherpa->GetBinContent(i);
        double nmcerr=hmadgraph->GetBinError(i);
        double ndataerr=hsherpa->GetBinError(i);

        if(nmc<0 || ndata<0)continue;

        if(nmcerr==0 && ndataerr==0)continue;

        if(nmc==0 && ndata==0)continue;

        double chi2ndef = (nmc-ndata)*(nmc-ndata)/
                          ( nmcerr*nmcerr+ ndataerr*ndataerr);
        chi2 += chi2ndef;
        realbin++;

        cout << "Bin " << i << " : " << ndata << ", " << nmc;
        cout << " " << chi2ndef << endl;


        // now calculate the ratio
        if(nmc==0 || nmcerr==0 || ndata==0 || ndataerr==0)continue;
        cout << "Bin " << i << " ratio = " << ndata/nmc << endl;
        hscale->SetBinContent(i,ndata/nmc);
        double err = 0;
        err=
            (ndata/nmc)*sqrt(pow(nmcerr/nmc,2)+pow(ndataerr/ndata,2));
        hscale->SetBinError(i,err);

    }


    hsherpa->GetXaxis()->SetRangeUser(xmin,xmax);
    hmadgraph->GetXaxis()->SetRangeUser(xmin,xmax);
    hscale->GetXaxis()->SetRangeUser(xmin,xmax);


    TCanvas* c1 = new TCanvas("c1","",700,1000);
    c1->Divide(1,2,0.01,0);
    c1->cd(1);
    if(logScale)
        gPad->SetLogy(1);
    gPad->SetTopMargin(0.01);
    gPad->SetBottomMargin(0);
    gPad->SetRightMargin(0.04);


    float max_data  = hsherpa->GetBinError(hsherpa->GetMaximumBin()) + hsherpa->GetMaximum();
    float max_mc    = hmadgraph->GetBinError(hmadgraph->GetMaximumBin()) + hmadgraph->GetMaximum();

    if(max_data > max_mc)
    {
        hsherpa->Draw("e");
        hmadgraph->Draw("hesame");
    }
    else
    {   hmadgraph->Draw("he");
        hsherpa->Draw("esame");
    }


    float x1NDC = 0.691;
    float y1NDC = 0.757;
    float x2NDC = 0.894;
    float y2NDC = 0.973;

    TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);

    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    leg->SetTextSize(0.04);
    leg->SetBorderSize(0);
    leg->AddEntry(hsherpa, "SHERPA");
    leg->AddEntry(hmadgraph, "MADGRAPH");
    leg->Draw("same");



    c1->cd(2);
    gStyle->SetStatW       (0.3);
    gStyle->SetStatH       (0.3);
    gStyle->SetStatX       (0.879447);
    gStyle->SetStatY       (0.939033);
    gStyle->SetStatFontSize(0.05);
    gStyle->SetStatBorderSize(0);
    gPad->SetRightMargin(0.04);
    gPad->SetTopMargin(0);
    gPad->SetBottomMargin(0.2);
    gPad->SetTickx();
    gStyle->SetOptFit(1);
    hscale->SetTitle("");
    hscale->SetMaximum(3.0);
    hscale->SetMinimum(-0.5);
    hscale->SetTitleOffset(1.2,"Y");
    hscale->Draw("e1");
    TF1* fline = new TF1("fline","pol1");
    TLine* l2 = new TLine(xmin,1.,xmax,1.);
    l2->SetLineColor(4);
    l2->SetLineStyle(3);
    fline->SetLineWidth(3);
    fline->SetLineColor(6);
    fline->SetNpx(2500);
    hscale->Fit("fline","","");
    l2->Draw("same");


    string dirName = "compareSherpaMadgraph";
    gSystem->mkdir(dirName.data());

    std::string filename;
    std::string psname = dirName + "/" + var;
    if(output !="test")
        psname = dirName+ "/" + output;
    else
        psname = dirName+ "/" + var;
    filename = psname + ".eps";
    c1->Print(filename.data());
    filename = psname + ".gif";
    c1->Print(filename.data());
    filename = psname + ".pdf";
    c1->Print(filename.data());
    //   c1->Close();
}
Example #22
0
void Scan_opt_mass_4D_scaled(int sigMass, double ptLead_cutIN, double DPHI_cutIN, double maxDPHIJet_cutIN,double minDPHIJet_cutIN){

  TFile *data = TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");
  TFile *sig = TFile::Open(Form("./25ns_2246inv_v3/2HDM_mZP%d.root",sigMass),"READ");
  if(sig == NULL) cout<<"sig fails"<<endl;
  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ"); 
  if(bkg1 == NULL) cout<<"bkg1 fails"<<endl;
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");
  if(bkg2 == NULL) cout<<"bkg2 fails"<<endl;
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  if(bkg3 == NULL) cout<<"bkg3 fails"<<endl;
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");
  if(bkg4 == NULL) cout<<"bkg4 fails"<<endl;
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");
  if(bkg5 == NULL) cout<<"bkg5 fails"<<endl;
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");
  if(bkg6 == NULL) cout<<"bkg6 fails"<<endl;
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");


  TTree *tree_data = (TTree*) data->Get("DiPhotonTree"); 
  TTree *tree_sig = (TTree*) sig->Get("DiPhotonTree"); 
  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");

  TCut Cut_pt1;
  TCut Cut_pt2;
  TCut Cut_met;
 TCut Cut_ptgg;
  TCut mggmax = "mgg<130";
  TCut mggmin = "mgg>120";

  TCut eveto1 = "eleveto1==1";
  TCut eveto2 = "eleveto2==1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut DPHIcut = Form("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhiCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0))>%lf",DPHI_cutIN);
  TCut maxDPHIJetcut = Form("MAX(ptJetLead,phiJetLead,ptJetSubLead,phiJetSubLead,ptJet3,phiJet3,ptJet4,phiJet4,t1pfmetPhiCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0))<%lf",maxDPHIJet_cutIN);
  TCut minDPHIJetcut = Form("myMIN(ptJetLead,phiJetLead,ptJetSubLead,phiJetSubLead,ptJet3,phiJet3,ptJet4,phiJet4,t1pfmetPhiCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0))>%lf",minDPHIJet_cutIN);
  TCut nMuonCut = "nMuons ==0";
  TCut nEleCut = "nEle <= 1";
  
  TCanvas *canvas = new TCanvas("canvas","",600,400);   
  int i = 0;
  int j = 0;
  int k = 0;
  int l = 0;

  double  cut_pt1 = 0;
  double  cut_pt2 = 0;
  double  cut_met = 0;
 double  cut_ptgg = 0;
    
  double Stot=0;
 
  double S = 0;
  double F1 = 0;
  double F2 = 0;
  double F3 = 0;
  double F4 = 0;
  double F5 = 0;
  double F6 = 0;
  double F7 = 0;
  double F8 = 0;
  double F9 = 0;
  double F10 = 0;
  double F11 = 0;
  double F12 = 0; 
  double B = 0;
  double Eff = 0;
  int N = 0;
  double Sig3 = 0;
  double Sig5 = 0;
  int NstepsPt1 = 10; 
  int NstepsPt2 = 1; 
  int NstepsMET = 20; 
  int NstepsPtgg = 7; 
  double signMax = 0;
  double OldSig5 = 0;
  double optCut_pt1 = 0;
  double optCut_pt2 = 0;
  double optCut_met = 0;
  double optCut_ptgg = 0;
  double temp = 0;
  
  double firstCut[4];
  
  
  if(sigMass==600){
    firstCut[0]=0.3; 
    firstCut[1]=0.25; 
    firstCut[2]=50;
    firstCut[3]=0.;
    
  } 
  
  if(sigMass==800){
    firstCut[0]=0.3+0.4; 
    firstCut[1]=0.25; 
    firstCut[2]=140;
firstCut[3]=0.;
  } 
  
  
  if(sigMass==1000){
    firstCut[0]=0.3+0.4; 
    firstCut[1]=0.25; 
    firstCut[2]=140;
firstCut[3]=0.;
  }
  
  if(sigMass==1200){
    firstCut[0]=0.3+0.9; 
    firstCut[1]=0.25; 
    firstCut[2]=200;
    firstCut[3]=0.;
  }
  
  if(sigMass==1400){
    firstCut[0]=0.3+0.9; 
    firstCut[1]=0.25; 
    firstCut[2]=230;
firstCut[3]=0.;
  }

  if(sigMass==1700){
    firstCut[0]=0.3+0.9; 
    firstCut[1]=0.25; 
    firstCut[2]=220;
firstCut[3]=0.;
  }

  if(sigMass==2500){
    firstCut[0]=0.3+1.1; 
    firstCut[1]=0.25; 
    firstCut[2]=240;
firstCut[3]=0.;
  }
  
  
  cout<<"############Segnale M"<<sigMass<<endl;
  cout<<"120 < mgg < 130"<<endl;  
  ios_base::fmtflags oldflags = std::cout.flags();

  
  
  tree_sig->Draw("(pt1)>>tot(30,0,1000)","weight"*(mggmin && mggmax && eveto));
  	TH1F *tot =(TH1F*)gPad->GetPrimitive("tot"); 
	Stot = tot->Integral();
  for(i = 0; i<NstepsPt1;i++){
   
  
    cut_pt1 = firstCut[0] + 0.05*i;
    Cut_pt1 = Form("pt1/mgg>%lf",cut_pt1);
    cout<<"### Taglio pt1>"<<cut_pt1<<endl;
    for(j = 0; j<NstepsPt2;j++){
      
  
      cut_pt2 = firstCut[1] + 0.05*j;
      Cut_pt2 = Form("pt2/mgg>%lf",cut_pt2);
      cout<<"\t### Taglio pt2>"<<cut_pt2<<" , pt1 > "<<cut_pt1<<endl;

  
 
      for(k = 0; k<NstepsMET;k++){
	cout<<"\t\t#Taglio MET>"<<cut_met<<", pt1 > "<<cut_pt1<<"; pt2 > "<<cut_pt2<<endl;
	cut_met = firstCut[2] + 5*k;
	Cut_met = Form("t1pfmetCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0)>%lf",cut_met);
  cout<<"\t\t#Tagli ptgg, MET>"<<cut_met<<", pt1 > "<<cut_pt1<<"; pt2 > "<<cut_pt2<<"; Stot = "<<Stot<<endl;
     cout<<"\t\tcut\tS\tDiPho\tDY\tGJets\tggH\tQCD\tVH\tB\tEff\tSig(3sigma)\tSig(5sigma)"<<endl;

     for(l = 0; l<NstepsPtgg;l++){
       cut_ptgg = firstCut[3] + 0.1*l;
       Cut_ptgg = Form("ptgg/t1pfmetCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0)>%lf",cut_ptgg);
       // tree_data->Draw("(pt1)>>hdata(30,0,1000)","(mgg<115||mgg>135)*(mgg>100||mgg<180)"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
       // TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");
     //  N = hdata->GetEntries();
     //  cout<<"Ndata = "<<N<<endl;
     Sig5 = 0.;  
     /*      tree_bkg1->Draw("(pt1)>>tot_bkg1(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));   
      TH1F *tot_bkg1 =(TH1F*)gPad->GetPrimitive("tot_bkg1");                                                                    
        tree_bkg2->Draw("(pt1)>>tot_bkg2(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));                    
        TH1F *tot_bkg2 =(TH1F*)gPad->GetPrimitive("tot_bkg2");                                                
         tree_bkg3->Draw("(pt1)>>tot_bkg3(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg  && genmatch));                     
        TH1F *tot_bkg3 =(TH1F*)gPad->GetPrimitive("tot_bkg3");                     
        tree_bkg4->Draw("(pt1)>>tot_bkg4(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));  
        TH1F *tot_bkg4 =(TH1F*)gPad->GetPrimitive("tot_bkg4");                     
        tree_bkg5->Draw("(pt1)>>tot_bkg5(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg  && genmatch));                                  
        TH1F *tot_bkg5 =(TH1F*)gPad->GetPrimitive("tot_bkg5");                                                                   
        tree_bkg6->Draw("(pt1)>>tot_bkg6(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg )); 
        TH1F *tot_bkg6 =(TH1F*)gPad->GetPrimitive("tot_bkg6");                                                 
        tree_bkg7->Draw("(pt1)>>tot_bkg7(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));   
        TH1F *tot_bkg7 =(TH1F*)gPad->GetPrimitive("tot_bkg7");                                                       
   tree_bkg8->Draw("(pt1)>>tot_bkg8(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));   
        TH1F *tot_bkg8 =(TH1F*)gPad->GetPrimitive("tot_bkg8");                                                    
        tree_bkg9->Draw("(pt1)>>tot_bkg9(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg )); 
        TH1F *tot_bkg9 =(TH1F*)gPad->GetPrimitive("tot_bkg9");                        
        tree_bkg10->Draw("(pt1)>>tot_bkg10(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));          
TH1F *tot_bkg10 =(TH1F*)gPad->GetPrimitive("tot_bkg10");          
        tree_bkg11->Draw("(pt1)>>tot_bkg11(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));  
        TH1F *tot_bkg11 =(TH1F*)gPad->GetPrimitive("tot_bkg11");                                   
        tree_bkg12->Draw("(pt1)>>tot_bkg12(30,0,1000)","weight*((mgg<115)||(mgg>135))*((mgg>100)&&(mgg<180))"*(Cut_met && Cut_pt2 && Cut_pt1 &&  eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut && Cut_ptgg ));  
        TH1F *tot_bkg12 =(TH1F*)gPad->GetPrimitive("tot_bkg12");                             
        N = tot_bkg1->Integral();                        
	N += tot_bkg2->Integral();                           
	N += tot_bkg3->Integral();                                              
        N += tot_bkg4->Integral();                        
	N += tot_bkg5->Integral();                     
        N += tot_bkg6->Integral();                                                 
        N += tot_bkg7->Integral();                                             
        N += tot_bkg8->Integral();                                                 
        N += tot_bkg9->Integral();                                                                
        N += tot_bkg10->Integral();                                                                   
        N += tot_bkg11->Integral();                                         
	N += tot_bkg12->Integral();   
     */	
	

	
	
     if(N>=0){
       tree_sig->Draw("(pt1)>>pt1_1(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
       TH1F *pt1_1 =(TH1F*)gPad->GetPrimitive("pt1_1"); 
       tree_bkg1->Draw("(pt1)>>pt1_bkg1(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
       TH1F *pt1_bkg1 =(TH1F*)gPad->GetPrimitive("pt1_bkg1");
       tree_bkg2->Draw("(pt1)>>pt1_bkg2(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
       TH1F *pt1_bkg2 =(TH1F*)gPad->GetPrimitive("pt1_bkg2");
       tree_bkg3->Draw("(pt1)>>pt1_bkg3(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut  && genmatch));
       TH1F *pt1_bkg3 =(TH1F*)gPad->GetPrimitive("pt1_bkg3");
       tree_bkg4->Draw("(pt1)>>pt1_bkg4(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg4 =(TH1F*)gPad->GetPrimitive("pt1_bkg4");
       tree_bkg5->Draw("(pt1)>>pt1_bkg5(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut  && genmatch));
       TH1F *pt1_bkg5 =(TH1F*)gPad->GetPrimitive("pt1_bkg5");
       tree_bkg6->Draw("(pt1)>>pt1_bkg6(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg6 =(TH1F*)gPad->GetPrimitive("pt1_bkg6");
       tree_bkg7->Draw("(pt1)>>pt1_bkg7(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg7 =(TH1F*)gPad->GetPrimitive("pt1_bkg7");
       tree_bkg8->Draw("(pt1)>>pt1_bkg8(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg8 =(TH1F*)gPad->GetPrimitive("pt1_bkg8");	
       tree_bkg9->Draw("(pt1)>>pt1_bkg9(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg9 =(TH1F*)gPad->GetPrimitive("pt1_bkg9");
       tree_bkg10->Draw("(pt1)>>pt1_bkg10(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg10 =(TH1F*)gPad->GetPrimitive("pt1_bkg10");
       tree_bkg11->Draw("(pt1)>>pt1_bkg11(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg11 =(TH1F*)gPad->GetPrimitive("pt1_bkg11");
       tree_bkg12->Draw("(pt1)>>pt1_bkg12(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
       TH1F *pt1_bkg12 =(TH1F*)gPad->GetPrimitive("pt1_bkg12");

       
       
       S = pt1_1->Integral();
       F1 = pt1_bkg1->Integral();  
       F2 = pt1_bkg2->Integral();  
       F3 = pt1_bkg3->Integral();  
       F4 = pt1_bkg4->Integral();  
	F5 = pt1_bkg5->Integral();  
	F6 = pt1_bkg6->Integral();  
	F7 = pt1_bkg7->Integral();  
	F8 = pt1_bkg8->Integral();  
	F9 = pt1_bkg9->Integral();  
	F10 = pt1_bkg10->Integral();  
	F11 = pt1_bkg11->Integral();  	
	F12 = pt1_bkg12->Integral();  
	if(F2 < 0) F2 = 0;
	if(F9 < 0) F9 = 0;
	
	B = F1+F2+F3+F4+F5+F6+F7+F8+F9+F10+F11+F12;
	Eff = S/Stot;
	Sig3 = Eff/(1.5+sqrt(B));
	Sig5 = Eff/(2.5+sqrt(B));
	cout<<fixed<<setprecision(2);
	cout<<"\t\t"<<cut_ptgg<<"\t"<<S<<"\t"<<F1<<"\t"<<F2<<"\t"<<F3<<"\t"<<F4<<"\t"<<F5<<"\t"<<F6<<"\t"<<B<<"\t"<<Eff<<"\t";
	cout.flags(oldflags);
	cout.precision(7);
	cout<<"\t"<<Sig3<<"\t"<<Sig5<<endl;
     }
     if(Sig5>OldSig5){
       temp = Sig5;  
     }      
     if(temp > signMax){
       signMax = Sig5;
       optCut_pt1 = cut_pt1;
       optCut_pt2 = cut_pt2;
       optCut_met = cut_met; 
       optCut_ptgg = cut_ptgg; 
     }
	OldSig5 = Sig5;
     }  
     cout<<""<<endl;
      }
      cout<<""<<endl;
    }
 cout<<""<<endl;
  }
  
  canvas->cd();
  cout<<"##################"<<endl;
  cout<<"Optimal cuts:"<<endl;
  cout<<"pt1/mgg > "<<optCut_pt1<<endl;
  cout<<"pt2/mgg > "<<optCut_pt2<<endl;
  cout<<"MET > "<<optCut_met<<"GeV"<<endl;
  cout<<"ptgg/MET > "<<optCut_ptgg<<endl;
  Cut_pt1 = Form("pt1/mgg>%lf",optCut_pt1);
  Cut_pt2 = Form("pt2/mgg>%lf",optCut_pt2);
  Cut_met = Form("t1pfmetCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0)>%lf",optCut_met);
  Cut_ptgg = Form("ptgg/t1pfmetCorr(t1pfmet, t1pfmetPhi,t1pfmetSumEt, 0)>%lf",optCut_ptgg);
  cout<<"S\tStot\tDiPho\tDY\tGJets\tggH\tQCD\tVH\tB\tEff\tSig(3sigma)\tSig(5sigma)"<<endl;
  tree_sig->Draw("(pt1)>>pt1_1(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
  TH1F *pt1_1 =(TH1F*)gPad->GetPrimitive("pt1_1"); 
  
  tree_bkg1->Draw("(pt1)>>pt1_bkg1(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
  TH1F *pt1_bkg1 =(TH1F*)gPad->GetPrimitive("pt1_bkg1");
  tree_bkg2->Draw("(pt1)>>pt1_bkg2(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
  TH1F *pt1_bkg2 =(TH1F*)gPad->GetPrimitive("pt1_bkg2");
  tree_bkg3->Draw("(pt1)>>pt1_bkg3(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
  TH1F *pt1_bkg3 =(TH1F*)gPad->GetPrimitive("pt1_bkg3");
  tree_bkg4->Draw("(pt1)>>pt1_bkg4(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg4 =(TH1F*)gPad->GetPrimitive("pt1_bkg4");
  tree_bkg5->Draw("(pt1)>>pt1_bkg5(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));
  TH1F *pt1_bkg5 =(TH1F*)gPad->GetPrimitive("pt1_bkg5");
  tree_bkg6->Draw("(pt1)>>pt1_bkg6(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg6 =(TH1F*)gPad->GetPrimitive("pt1_bkg6");
  tree_bkg7->Draw("(pt1)>>pt1_bkg7(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg7 =(TH1F*)gPad->GetPrimitive("pt1_bkg7");
  tree_bkg8->Draw("(pt1)>>pt1_bkg8(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg8 =(TH1F*)gPad->GetPrimitive("pt1_bkg8");	
  tree_bkg9->Draw("(pt1)>>pt1_bkg9(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg9 =(TH1F*)gPad->GetPrimitive("pt1_bkg9");
  tree_bkg10->Draw("(pt1)>>pt1_bkg10(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg10 =(TH1F*)gPad->GetPrimitive("pt1_bkg10");
  tree_bkg11->Draw("(pt1)>>pt1_bkg11(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg11 =(TH1F*)gPad->GetPrimitive("pt1_bkg11");
  tree_bkg12->Draw("(pt1)>>pt1_bkg12(30,0,1000)","weight"*(Cut_met && Cut_ptgg && Cut_pt2 && Cut_pt1 && mggmin && mggmax && eveto && maxDPHIJetcut  && DPHIcut && minDPHIJetcut && nMuonCut && nEleCut ));  //weight on BR = 0.002 if usign 50ns samples 
  TH1F *pt1_bkg12 =(TH1F*)gPad->GetPrimitive("pt1_bkg12");
  
  S = pt1_1->Integral();
  F1 = pt1_bkg1->Integral();  
  F2 = pt1_bkg2->Integral();  
  F3 = pt1_bkg3->Integral();  
  F4 = pt1_bkg4->Integral();  
  F5 = pt1_bkg5->Integral();  
  F6 = pt1_bkg6->Integral();  
  F7 = pt1_bkg7->Integral();  
  F8 = pt1_bkg8->Integral();  
  F9 = pt1_bkg9->Integral();  
  F10 = pt1_bkg10->Integral();  
  F11 = pt1_bkg11->Integral();  	
  F12 = pt1_bkg12->Integral();  
  if(F2 < 0) F2 = 0;
  if(F9 < 0) F9 = 0;
  
  B = F1+F2+F3+F4+F5+F6+F7+F8+F9+F10+F11+F12;
  Eff = S/Stot;
  Sig3 = Eff/(1.5+sqrt(B));
  Sig5 = Eff/(2.5+sqrt(B));
  cout<<fixed<<setprecision(2);
  cout<<S<<"\t"<<Stot<<F1<<"\t"<<F2<<"\t"<<F3<<"\t"<<F4<<"\t"<<F5<<"\t"<<F6<<"\t"<<B<<"\t"<<Eff<<"\t";
  cout.flags(oldflags);
  cout.precision(7);
  cout<<"\t"<<Sig3<<"\t"<<Sig5<<endl;


 

  
}
Example #23
0
File: calccorr.C Project: XuQiao/HI
void calccorr(int i=1,string t="ptfiner"){
float const PI = acos(-1.0);
if(i==0){
const int ncent = 6;
const int npt = 25;
TString dire="north";
}
else if(i==1){
const int ncent = 6;
const int npt = 25;
TString dire="south";
}
else if(i==2){
const int ncent = 6;
const int npt = 1;
TString dire="sn";
}

TFile *f=TFile::Open("../../../work/20GeV/output_3corrF.root");
TH1F* kforebbcw[ncent][npt];
TH1F* hforebbcw[ncent][npt];
TH1F* kbackbbcw2[ncent][npt];
TH1F* kforebbcw_In;
TH1F* hforebbcw_In;
TH1F* kbackbbcw2_In;
double ptbin[26] = {0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
double centbin[7] = {0,0.05,0.1,0.2,0.4,0.6,1.0};
//double centbin[ncent+1] = {0,1,2};
TString type = t.c_str();
if(type=="ptIn25_4"){
double selptbin[] = {2.5,4.0};
double selcentbin[ncent+1] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptIn"){
    if(i==2){
double selptbin[] = {0.0,0.2};
    }
    else{
double selptbin[] = {0.4,3.0};
    }
double selcentbin[] = {0,0.05,0.1,0.2,0.4,0.6,1.0};
}
else if(type=="ptcoarser"){
double selptbin[] = {0.2,1.0,2.0,3.0,5.0};
double selcentbin[] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptfiner"){
double selptbin[] = {0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
double selcentbin[] = {0,0.05,0.1,0.2,0.4,0.6,1.0};
//double selcentbin[ncent+1] = {0,1,2};
}
else if(type=="centIn"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {0,1.0};
}
else if(type=="ptccentc"){
double selptbin[] = {0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
double selcentbin[] = {0,0.1};
}
else{exit(0);};

/*double ptmin = 1.0; double ptmax = 3.0;//has to be boundary
for(int ipt=0; ipt<npt; ipt++){
if(ptmin >= ptbin[ipt] && ptmin < ptbin[ipt+1]){int xptmin = ipt; continue;}
if(ptmax >= ptbin[ipt] && ptmax < ptbin[ipt+1]){int xptmax = ipt; continue;}
}*/
  ofstream fout(Form("c1_c2_central_%s_%s.dat",type.Data(),dire.Data()));
for(int icent=0; icent<ncent; icent++){
for(int ipt=0; ipt<npt; ipt++){
kforebbcw[icent][ipt] = (TH1F*)f->Get(Form("kfore%sbbcw_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("kforenorthbbcw_%d_%d",icent,ipt));
//kforebbcw[icent][ipt]->Add(htemp,-1);
hforebbcw[icent][ipt] = (TH1F*)f->Get(Form("hfore%sbbcw_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("hforenorthbbcw_%d_%d",icent,ipt));
//hforebbcw[icent][ipt]->Add(htemp,-1);
kbackbbcw2[icent][ipt] = (TH1F*)f->Get(Form("kback%sbbcw2_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("kbacknorthbbcw2_%d_%d",icent,ipt));
//kbackbbcw2[icent][ipt]->Add(htemp,-1);
}
}
int ncent_a = sizeof(selcentbin)/sizeof(double)-1;
int npt_a = sizeof(selptbin)/sizeof(double)-1;
for(int icent_a=0;icent_a<ncent+1;icent_a++){
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a] == centbin[icent_b]) break;
int xcentmin = icent_b;
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a+1] == centbin[icent_b]) break;
int xcentmax = icent_b;
if((xcentmin == ncent+1) || (xcentmax == ncent+1)) exit(0);
for(int ipt_a=0;ipt_a<npt_a;ipt_a++){
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a] == ptbin[ipt_b]) break;
int xptmin = ipt_b;
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a+1] == ptbin[ipt_b]) break;
int xptmax = ipt_b;
if((xptmin == npt+1) || (xptmax == npt+1)) exit(0);
cout<<xcentmin<<"\t"<<xcentmax<<"\t"<<endl;
cout<<xptmin<<"\t"<<xptmax<<"\t"<<endl;
kforebbcw_In = (TH1F*)kforebbcw[xcentmin][xptmin]->Clone();
hforebbcw_In = (TH1F*)hforebbcw[xcentmin][xptmin]->Clone();
kbackbbcw2_In = (TH1F*)kbackbbcw2[xcentmin][xptmin]->Clone();
kforebbcw_In->Reset();
hforebbcw_In->Reset();
kbackbbcw2_In->Reset();
for(int icent=xcentmin; icent<xcentmax; icent++){
for(int ipt=xptmin; ipt<xptmax; ipt++){
kforebbcw_In->Add(kforebbcw[icent][ipt]);
hforebbcw_In->Add(hforebbcw[icent][ipt]);
kbackbbcw2_In->Add(kbackbbcw2[icent][ipt]);
}
}
kforebbcw_In->Rebin(2);
hforebbcw_In->Rebin(2);
kbackbbcw2_In->Rebin(2);


TH1F* hpp;
TH1F* hbackpp;
  hpp = (TH1F*)kforebbcw_In->Clone();
  hbackpp = (TH1F*)kbackbbcw2_In->Clone();
  float nbackpp = hbackpp->Integral()/2.0/PI;
  float nforepp = hpp->Integral()/2.0/PI;
  //float ntrig0 = ptforedis_0->Integral(11,30);
   for(int i=0; i<20; i++){
     float pp_cont = 1.0*hpp->GetBinContent(i+1);
     //float pp0_err = 1.0*hpp->GetBinError(i+1);
     float weight2 = sqrt(1.0*hforebbcw_In->GetBinContent(i+1));

     float backpp_cont = 1.0*hbackpp->GetBinContent(i+1);
    
     float con = pp_cont/backpp_cont*nbackpp/nforepp;
     float err = weight2/backpp_cont*nbackpp/nforepp;

     hpp->SetBinContent(i+1, con);
     hpp->SetBinError(i+1, err);

   }
  TF1 *fun0 = new TF1("fun0","[0]*(1+2*[1]*cos(x)+2*[2]*cos(2*x)+2*[3]*cos(3*x)+2*[4]*cos(4*x))", -0.5*PI, 1.5*PI);

  fun0->SetLineColor(1);
  hpp->Fit("fun0","NORQ");

  TF1 *fun1 = new TF1("fun1","[0]*(1+2*[1]*cos(x))",   -0.5*PI, 1.5*PI);
  TF1 *fun2 = new TF1("fun2","[0]*(1+2*[1]*cos(2*x))", -0.5*PI, 1.5*PI);
  TF1 *fun3 = new TF1("fun3","[0]*(1+2*[1]*cos(3*x))", -0.5*PI, 1.5*PI);
  TF1 *fun4 = new TF1("fun4","[0]*(1+2*[1]*cos(4*x))", -0.5*PI, 1.5*PI);

//const double ptmean[npt] = {0.360943, 0.691833, 1.1911, 1.69654, 2.20117, 2.70571, 3.2097, 3.71372, 4.21814, 4.72014};
  fout<<fun0->GetParameter(1)<<" "<<fun0->GetParError(1)<<" "
      <<fun0->GetParameter(2)<<" "<<fun0->GetParError(2)<<" "//<<0.05*fun0->GetParameter(2)<<" "<<endl;
      <<fun0->GetParameter(3)<<" "<<fun0->GetParError(3)<<endl;
}
}
  fout.close();

/*  
  cout<<"*************** v2 ***********"<<endl;
  float v2_0 = funvn0->GetParameter(1)/(zym_pp0 + funvn0->GetParameter(0));
  float v2_1 = funvn1->GetParameter(1)/(zym_pp1 + funvn1->GetParameter(0));
  float v2_2 = funvn2->GetParameter(1)/(zym_pp2 + funvn2->GetParameter(0));
  float v2_3 = funvn3->GetParameter(1)/(zym_pp3 + funvn3->GetParameter(0));
  

  cout<<v2_0<<" "<<v2_1<<" "<<v2_2<<" "<<v2_3<<endl;
 
  
  cout<<funvn0->GetParameter(0)*funvn0->GetParameter(1)<<" "
      <<funvn1->GetParameter(0)*funvn1->GetParameter(1)<<" "
      <<funvn2->GetParameter(0)*funvn2->GetParameter(1)<<" "
      <<funvn3->GetParameter(0)*funvn3->GetParameter(1)<<endl;
  

  cout<<"*************** v2 ***********"<<endl;
  cout<<funvn0->GetParameter(2)<<" "<<funvn1->GetParameter(2)<<" "<<funvn2->GetParameter(2)<<" "<<funvn3->GetParameter(2)<<endl;

  cout<<"*************** v3 ***********"<<endl;
  cout<<funvn0->GetParameter(3)<<" "<<funvn1->GetParameter(3)<<" "<<funvn2->GetParameter(3)<<" "<<funvn3->GetParameter(3)<<endl;
*/
}
Example #24
0
void plotMuTau( Int_t mH_ = 120,
		string selection_ = "inclusive",
		string analysis_  = "",		  
		TString variable_ = "diTauVisMass",
		TString XTitle_ = "full mass",
		TString Unities_ = "GeV",
		Int_t nBins_ = 100, Float_t xMin_=0, Float_t xMax_=400,
		Float_t magnifySgn_ = 1.0,
		Float_t hltEff_ = 0.9967*0.997*0.968, // muID*muIso*muHLT
		Int_t logy_ = 0 ) 
{   

  // input txt file with bins
  ifstream is;

  char* c = new char[10];
  is.open(Form("bins/bins_muTau_mH%d_%s_%s.txt",mH_,selection_.c_str(),variable_.Data())); 
  if(nBins_<0 &&  !is.good()){
    cout << "Bins file not found" << endl;
    return;
  }

  int nBinsFromFile = 0;
  while (is.good())     
    {
      is.getline(c,999,',');     
      if (is.good()){
	nBinsFromFile++;
	//cout << c << endl;
      }
    }

  // choose the number of bins
  int nBins =  nBins_>0 ? nBins_ : nBinsFromFile-1 ;
  Float_t bins[nBins+1];
  cout << "Making histograms with " << nBins << " bins:" << endl;

  is.close();
  is.open(Form("bins/bins_muTau_mH%d_%s_%s.txt",mH_,selection_.c_str(),variable_.Data())); 
  
  nBinsFromFile = 0;

  if(nBins_>0){
    for( ; nBinsFromFile <= nBins ; nBinsFromFile++){
      bins[nBinsFromFile] =  xMin_ + nBinsFromFile*(xMax_-xMin_)/nBins_;
    }
  }
  else{
    while (is.good())  
      {
	is.getline(c,999,',');     
	if (is.good() && nBinsFromFile<=nBins) {
	  bins[nBinsFromFile] = atof(c);
	  cout << bins[nBinsFromFile] << ", " ;
	}
	nBinsFromFile++;
      }
    cout << endl;
  }

  // Luminosity analyzed & parameters
  float Lumi                     = (159.+887.+361.7+531.5)*1.00;
  float WcorrectionFactorOS      = 0.97;  
  float WcorrectionFactorSS      = 1.19;  
  float MutoTauCorrectionFactor  = 1.00;
  float JtoTauCorrectionFactor   = 0.80;
  float VbfExtrapolationFactor   = 1.03;


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

  TLegend* leg = new TLegend(0.55,0.42,0.85,0.85,NULL,"brNDC");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetFillColor(10);
  leg->SetTextSize(0.03);
  leg->SetHeader(Form("#splitline{CMS Preliminary}{#splitline{%.1f fb^{-1} #sqrt{s}=7 TeV}{#tau_{#mu}#tau_{had}}}", Lumi/1000. ));

  THStack* aStack = new THStack("aStack","");

  TH1F* hSiml  = new TH1F( "hSiml" ,"all"               , nBins , bins);
  TH1F* hSgn   = new TH1F( "hSgn " ,"vbf+ggf"           , nBins , bins);
  TH1F* hSgn1  = new TH1F( "hSgn1" ,"vbf"               , nBins , bins);
  TH1F* hSgn2  = new TH1F( "hSgn2" ,"ggf"               , nBins , bins);
  TH1F* hData  = new TH1F( "hData" ,"Observed"          , nBins , bins);
  TH1F* hW     = new TH1F( "hW"    ,"W+jets"            , nBins , bins);
  TH1F* hEWK   = new TH1F( "hEWK"  ,"EWK"               , nBins , bins);
  TH1F* hZtt   = new TH1F( "hZtt"  ,"Ztautau"           , nBins , bins);
  TH1F* hZmm   = new TH1F( "hZmm"  ,"Z+jets, mu to tau" , nBins , bins);
  TH1F* hZmj   = new TH1F( "hZmj"  ,"Z+jets, jet to tau", nBins , bins);
  TH1F* hTTb   = new TH1F( "hTTb"  ,"ttbar"             , nBins , bins);
  TH1F* hQCD   = new TH1F( "hQCD"  ,"QCD"               , nBins , bins);
  TH1F* hVV    = new TH1F( "hVV"   ,"Diboson"           , nBins , bins);

  // pZeta OS, N pZ sideband OS, pZeta SS, N sideband SS, N QCD SS, OS/SS
  TH1F* hParameters   = new TH1F( "hParameters", "" , 7, 0,7);

  // Open the files
  TFile *fData              
    = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleRun2011-Mu-All_run_Open_MuTauStream.root", "READ");  
  TFile *fSignalVBF         
    = new TFile(Form("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleVBFH%d-Mu-powheg-PUS4_run_Open_MuTauStream.root",mH_) ,"READ");  
  TFile *fSignalGGH         
    = new TFile(Form("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleGGFH%d-Mu-powheg-PUS4_run_Open_MuTauStream.root",mH_),"READ");  
  TFile *fBackgroundDY
    = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleDYJets-Mu-50-madgraph-PUS4_run_Open_MuTauStream.root","READ"); 
  TFile *fBackgroundWJets   
    = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleWJets-Mu-madgraph-PUS4_run_Open_MuTauStream.root","READ"); 
  TFile *fBackgroundTTbar  
    = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleTTJets-Mu-madgraph-PUS4_run_Open_MuTauStream.root","READ"); 
  TFile *fBackgroundOthers  
    = new TFile("/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStreamSummer11_fAna//nTupleOthers-Mu-PUS4_run_Open_MuTauStream.root","READ"); 

  // choose the analysis: Nominal "", jet up/Down "JetUp/Down" , elec up/down "MuUp/Down" , tau up/down "TauUp/Down"
  TString tree = "outTreePtOrd"+analysis_;

  TTree *data                = (TTree*)fData->Get("outTreePtOrd");
  TTree *signalVBF           = (TTree*)fSignalVBF->Get(tree);
  TTree *signalGGH           = (TTree*)fSignalGGH->Get(tree);

  // split the DY->ll into l=e/mu and l=tau (MC level) ===> temporary, need fix !!!
  TFile* dummy1 = new TFile("dummy1.root","RECREATE");
  cout << "Now copying g/Z -> tau+ tau- " << endl;
  TTree *backgroundDYTauTau  = ((TTree*)fBackgroundDY->Get(tree))->CopyTree("abs(genDecay)==(23*15)");                   // g/Z -> tau+ tau-
  cout << "Now copying g/Z -> mu+mu- mu->tau" << endl;
  TTree *backgroundDYMutoTau = ((TTree*)fBackgroundDY->Get(tree))->CopyTree("abs(genDecay)!=(23*15) && diTauCharge==0"); // g/Z -> mu+mu- mu->tau
  cout << "Now copying g/Z -> mu+mu- jet->tau" << endl;
  TTree *backgroundDYJtoTau  = ((TTree*)fBackgroundDY->Get(tree))->CopyTree("abs(genDecay)!=(23*15) && diTauCharge!=0"); // g/Z -> mu+mu- jet->tau

  cout << backgroundDYTauTau->GetEntries()  << " come from DY->tautau"      << endl;
  cout << backgroundDYMutoTau->GetEntries() << " come from DY->mumu, mu->tau"  << endl;
  cout << backgroundDYJtoTau->GetEntries()  << " come from DY->mumu, jet->tau"<< endl;

  TTree *backgroundTTbar     = (TTree*)fBackgroundTTbar->Get(tree);
  TTree *backgroundWJets     = (TTree*)fBackgroundWJets->Get(tree);
  TTree *backgroundOthers    = (TTree*)fBackgroundOthers->Get(tree);
 

  TCut lpt("ptL1>15");
  TCut tpt("ptL2>21");
  TCut tiso("tightestHPSDBWP>0");
  TCut liso("combRelIsoLeg1DBeta<0.1");
  TCut lveto("muFlag==0");
  TCut SS("diTauCharge!=0");
  TCut OS("diTauCharge==0");
  TCut oneJet("pt1>30");
  TCut twoJets("pt1>30 && pt2>30");
  TCut vbf("pt1>30 && pt2>30 && eta1*eta2<0 && Mjj>350 && Deta>3.5 && ptVeto<30");
  TCut novbf("pt2<30 || (pt1>30 && pt2>30 && ptVeto<30 && !(eta1*eta2<0 && Mjj>350 && Deta>3.5))");
  TCut hltevent("HLTx==1");
  TCut hltmatch("HLTmatch==1");
  TCut bTag("pt2<30 && ((pt1>20 && jetsBtagHE1>3.3) || (pt2>20 && jetsBtagHE2>3.3))");
  TCut nobTag("pt2<30 && jetsBtagHE1<3.3 && jetsBtagHE2<3.3");
  TCut pZ("(pZetaCorr-1.5*pZetaVisCorr)>-20");
  TCut apZ("(pZetaCorr-1.5*pZetaVisCorr)<-40");

  TCut sbin; TCut sbinPZetaRel; TCut sbinSS; TCut sbinPZetaRelSS; TCut sbinPZetaRev; TCut sbinPZetaRevSS;

  if(selection_.find("inclusive")!=string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch;
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch;
  }
  else if(selection_.find("oneJet")!=string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch && oneJet;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch && oneJet;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch && oneJet;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch && oneJet;
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch && oneJet;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch && oneJet;
  }
  else if(selection_.find("twoJets")!=string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch && twoJets;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch && twoJets;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch && twoJets;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch && twoJets;
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch && twoJets;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch && twoJets;
  }
  else if(selection_.find("vbf")!=string::npos && selection_.find("novbf")==string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch && vbf;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch && vbf;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch && vbf;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch && vbf;
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch && vbf;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch && vbf;
  }
  else if(selection_.find("novbf")!=string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch && novbf;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch && novbf;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch && novbf;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch && novbf;
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch && novbf;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch && novbf;
  }
  else if(selection_.find("bTag")!=string::npos && selection_.find("nobTag")==string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch && bTag;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch && bTag;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch && bTag;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch && bTag;    
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch && bTag;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch && bTag;
  }
  else if(selection_.find("nobTag")!=string::npos){
    sbin           =  lpt && tpt && tiso && liso && lveto && OS && pZ  && hltevent && hltmatch && nobTag;
    sbinPZetaRel   =  lpt && tpt && tiso && liso && lveto && OS        && hltevent && hltmatch && nobTag;
    sbinPZetaRev   =  lpt && tpt && tiso && liso && lveto && OS && apZ && hltevent && hltmatch && nobTag;
    sbinPZetaRevSS =  lpt && tpt && tiso && liso && lveto && SS && apZ && hltevent && hltmatch && nobTag;
    sbinSS         =  lpt && tpt && tiso && liso && lveto && SS && pZ  && hltevent && hltmatch && nobTag;
    sbinPZetaRelSS =  lpt && tpt && tiso && liso && lveto && SS        && hltevent && hltmatch && nobTag;
  }

  // estimate the W+jets in the selection bin using pZeta extrapolation

  TH1F* hWMt = new TH1F("hWMt","",200,-200,200);
  cout << "Histogramming the pZeta variable every " << hWMt->GetBinWidth(1) << " GeV" << endl;

  ///////////////////////////////////////// Doing OS first...
  hWMt->Reset();
  backgroundWJets->Draw("(pZetaCorr-1.5*pZetaVisCorr)>>hWMt","(sampleWeight*puWeight*HLTweightTau)"*sbinPZetaRel);
  cout << "Using  " << hWMt->Integral() << " entries from the W+jets OS sample" << endl;
  float OSWinSignalRegionMC = hWMt->Integral(91,200)*Lumi*hltEff_/1000.;
  float scaleFactorOS = (hWMt->Integral(0,80))/(hWMt->Integral(91,200));
  cout << "Extrapolation factor for W OS : P(pZetaCorr<-40)/P(pZetaCorr>-20) ==> " << scaleFactorOS << endl;
 
  hWMt->Reset();
  cout << "Estimating cobtribution from ttbar and others in OS low pZeta tail..." << endl;
  backgroundTTbar->Draw("(pZetaCorr-1.5*pZetaVisCorr)>>hWMt","(sampleWeight*puWeight*HLTweightTau)"*sbinPZetaRel);
  hWMt->Scale(Lumi*hltEff_/1000.);
  float ttbarExtrOS = hWMt->Integral(0,80);
  cout << "Contribution from ttbar in OS is " << ttbarExtrOS << endl;
  hWMt->Reset();
  backgroundOthers->Draw("(pZetaCorr-1.5*pZetaVisCorr)>>hWMt","(sampleWeight*puWeight*HLTweightTau)"*sbinPZetaRel);
  hWMt->Scale(Lumi*hltEff_/1000.);
  float othersExtrOS = hWMt->Integral(0,80);
  cout << "Contribution from single-t and di-boson in OS is " << othersExtrOS << endl;
  float OSWinSignalRegionDATA = data->GetEntries(sbinPZetaRev);
  cout << "Selected events in data in low pZeta tail " << OSWinSignalRegionDATA << endl;
  OSWinSignalRegionDATA -= ttbarExtrOS;
  OSWinSignalRegionDATA -= othersExtrOS;
  OSWinSignalRegionDATA /= scaleFactorOS;
  cout << "W+jets in signal region is estimated to be "  
       << OSWinSignalRegionDATA*scaleFactorOS << "/" << scaleFactorOS << " = " 
       << OSWinSignalRegionDATA <<  " +/- " << sqrt(OSWinSignalRegionDATA/scaleFactorOS)/scaleFactorOS << endl;
  cout << "  ===> the MC prediction was " << OSWinSignalRegionMC << endl;

  hParameters->SetBinContent(1, 1./scaleFactorOS );
  hParameters->SetBinContent(2, OSWinSignalRegionDATA*scaleFactorOS );

  ///////////////////////////////////////// Doing SS last...
  hWMt->Reset();
  backgroundWJets->Draw("(pZetaCorr-1.5*pZetaVisCorr)>>hWMt","(sampleWeight*puWeight*HLTweightTau)"*sbinPZetaRelSS);
  cout << "Using  " << hWMt->Integral() << " entries from the SS W+jets sample" << endl;
  float SSWinSignalRegionMC = hWMt->Integral(91,200)*Lumi*hltEff_/1000.;
  float scaleFactorSS = (hWMt->Integral(0,80))/(hWMt->Integral(91,200));
  cout << "Extrapolation factor for W SS : P(pZetaCorr<-40)/P(pZetaCorr>-20) ==> " << scaleFactorSS << endl;

  hWMt->Reset();
  cout << "Estimating cobtribution from ttbar and others in SS low pZeta tail..." << endl;
  backgroundTTbar->Draw("(pZetaCorr-1.5*pZetaVisCorr)>>hWMt","(sampleWeight*puWeight*HLTweightTau)"*sbinPZetaRelSS);
  hWMt->Scale(Lumi*hltEff_/1000.);
  float ttbarExtrSS = hWMt->Integral(0,80);
  cout << "Contribution from ttbar in SS is " << ttbarExtrSS << endl;
  hWMt->Reset();
  backgroundOthers->Draw("(pZetaCorr-1.5*pZetaVisCorr)>>hWMt","(sampleWeight*puWeight*HLTweightTau)"*sbinPZetaRelSS);
  hWMt->Scale(Lumi*hltEff_/1000.);
  float othersExtrSS = hWMt->Integral(0,80);
  cout << "Contribution from single-t and di-boson in SS is " << othersExtrSS << endl;
  float SSWinSignalRegionDATA = data->GetEntries(sbinPZetaRevSS);
  cout << "Selected events in data in low pZeta tail " << SSWinSignalRegionDATA << endl;
  SSWinSignalRegionDATA -= ttbarExtrSS;
  SSWinSignalRegionDATA -= othersExtrSS;
  SSWinSignalRegionDATA /= scaleFactorSS;
  cout << "W+jets in SS signal region is estimated to be "  
       << SSWinSignalRegionDATA*scaleFactorSS << "/" << scaleFactorSS << " = " 
       << SSWinSignalRegionDATA <<  " +/- " << sqrt(SSWinSignalRegionDATA/scaleFactorSS)/scaleFactorSS << endl;
  cout << "  ===> the MC prediction was " << SSWinSignalRegionMC << endl;

  hParameters->SetBinContent(3, 1./scaleFactorSS );
  hParameters->SetBinContent(4, SSWinSignalRegionDATA*scaleFactorSS );


  // here I choose the order in the stack
  std::vector<string> samples;
  samples.push_back("Data");
  samples.push_back("ggH115");
  samples.push_back("qqH115");
  samples.push_back("Others");
  samples.push_back("TTbar");
  samples.push_back("SS");
  samples.push_back("WJets");
  samples.push_back("DYMutoTau");
  samples.push_back("DYJtoTau");
  samples.push_back("DYToTauTau");

  

  // here I define the map between a sample name and its tree
  std::map<std::string,TTree*> tMap;
  tMap["Data"]      = data;
  tMap["ggH115"]    = signalGGH;
  tMap["qqH115"]    = signalVBF;
  tMap["DYToTauTau"]= backgroundDYTauTau;
  tMap["DYMutoTau"] = backgroundDYMutoTau;
  tMap["DYJtoTau"]  = backgroundDYJtoTau;
  tMap["WJets"]     = backgroundWJets;
  tMap["Others"]    = backgroundOthers;
  tMap["TTbar"]     = backgroundTTbar;
  tMap["SS"]        = data;


  
  std::map<TString,Float_t> vMap;


  for( unsigned iter=0; iter<samples.size(); iter++){

    cout << "Dealing with sample " << samples[iter] << endl;
    
    std::map<std::string,TTree*>::iterator it = tMap.find(samples[iter]);

    TString h1Name = "h1_"+it->first;
    TH1F* h1 = new TH1F( h1Name ,"" , nBins , bins);

    TTree* currentTree = 0;
    
    if((it->first).find("SS")!=string::npos){
      
      cout << "Remove W contamination from SS data sample ... " << endl;
      currentTree = (it->second);

      float error2OnQCD = 0.0;
      
      TH1F* hHelp = (TH1F*)h1->Clone("hHelp");
      hHelp->Reset();
      currentTree->Draw(variable_+">>hHelp", sbinSS);
      int SSevents = hHelp->GetEntries();
      cout << "Selected SS events in data " << hHelp->GetEntries() << endl;
      h1->Add(hHelp,1);

      hHelp->Reset();
      backgroundWJets->Draw(variable_+">>hHelp", "(sampleWeight*puWeight*HLTweightTau)"*sbinSS);
      cout << "We expect " << hHelp->Integral()*Lumi/1000*hltEff_ << " SS events from W+jets (from " << hHelp->GetEntries() << " entries)" << endl;
      float sFWSS = ( selection_.find("novbf")!=string::npos || selection_.find("nobTag")!=string::npos ) ? SSWinSignalRegionDATA/SSWinSignalRegionMC : WcorrectionFactorSS; // from the extrapolation factor DATA/MC
      hHelp->Scale(sFWSS*Lumi/1000*hltEff_);
      cout << "We estimate " << hHelp->Integral() << " SS events from W+jets by extrapolating" << endl;
      cout << " ==> removing W+jets from SS...." << endl;
      h1->Add(hHelp, -1 );
      if(hHelp->GetEntries()>0) error2OnQCD +=  pow( hHelp->Integral()/hHelp->GetEntries(), 2)*hHelp->GetEntries(); // error on MC W+jets SS events
      error2OnQCD +=  pow(WcorrectionFactorSS*0.06,2)*pow(hHelp->GetEntries(),2);        // error on W+jets extrapolation factor ==> 6% according to Artur
      cout << sqrt(error2OnQCD) << " <==  W" << endl;      

      hHelp->Reset();
      backgroundTTbar->Draw(variable_+">>hHelp", "(sampleWeight*puWeight*HLTweightTau)"*sbinSS);
      cout << "We expect " << hHelp->Integral()*Lumi/1000*hltEff_ << " SS events from TTbar (from " << hHelp->GetEntries() << " entries)" << endl;
      hHelp->Scale(1.0*Lumi/1000*hltEff_);
      cout << "We estimate " << hHelp->Integral() << " SS events from TTbar" << endl;
      cout << " ==> removing TTbar from SS...." << endl;
      h1->Add(hHelp, -1 );
      if(hHelp->GetEntries()>0) error2OnQCD +=  pow(hHelp->Integral()/hHelp->GetEntries(),2)*hHelp->GetEntries();   // error on MC TTbar SS events
      cout << sqrt(error2OnQCD) << " <== W + TTb" << endl;      

      hHelp->Reset();
      backgroundDYMutoTau->Draw(variable_+">>hHelp", "(sampleWeight*puWeight*HLTweightTau)"*sbinSS);
      cout << "We expect " << hHelp->Integral()*Lumi/1000*hltEff_ << " SS events from DY->mumu, mu->jet" << endl;
      hHelp->Scale(MutoTauCorrectionFactor*Lumi/1000*hltEff_);
      cout << "We estimate " << hHelp->Integral() << " SS events from DY->mumu, mu->tau" << endl;
      cout << " ==> removing DY->mumu, mu->tau from SS...." << endl;
      h1->Add(hHelp, -1 );
      if(hHelp->GetEntries()>0) error2OnQCD +=  pow(hHelp->Integral()/hHelp->GetEntries(),2)*hHelp->GetEntries();   // error on MC DY->mumu, mu->tau events
      cout << sqrt(error2OnQCD) << " <== W + TTb + DY(1)" << endl;      

      hHelp->Reset();
      backgroundDYJtoTau->Draw(variable_+">>hHelp", "(sampleWeight*puWeight*HLTweightTau)"*sbinSS);
      cout << "We expect " << hHelp->Integral()*Lumi/1000*hltEff_ << " SS events from DY->mumu, jet->tau" << endl;
      hHelp->Scale(JtoTauCorrectionFactor*Lumi/1000*hltEff_);
      cout << "We estimate " << hHelp->Integral() << " SS events from DY->mumu, jet->tau" << endl;
      cout << " ==> removing DY->mumu, mu->jet from SS...." << endl;
      h1->Add(hHelp, -1 );
      if(hHelp->GetEntries()>0) error2OnQCD +=  pow(hHelp->Integral()/hHelp->GetEntries(),2)*hHelp->GetEntries();   // error on MC DY->mumu, jet->tau events
      cout << sqrt(error2OnQCD) << " <== W + TTb + DY(1,2)" << endl;      

      //  OS/SS ratio
      h1->Scale(1.06);
      cout << "After removing the expected contribution from W+jets and rescaling by 1.06 we expect " 
	   << h1->Integral() << " events from QCD processes" << endl;

      hParameters->SetBinContent(5, SSevents);
      hParameters->SetBinContent(6, h1->Integral()/SSevents);

      cout << "Total unceratinty from bkg subtraction in SS region is " << sqrt(error2OnQCD) << endl;
      float totalRelErrorOnQCD = 0.02 + sqrt(error2OnQCD)/h1->Integral(); //0.02 ==> uncertainty on OS/SS ratio
      hParameters->SetBinContent(7,totalRelErrorOnQCD);

    }
    else{

      currentTree = (it->second);
      if((it->first).find("DYJtoTau")==string::npos)
	currentTree->Draw(variable_+">>"+h1Name, "(sampleWeight*puWeight*HLTweightTau)"*sbin);
      else
	currentTree->Draw(variable_+">>"+h1Name, "(sampleWeight*puWeight*HLTweightTau)"*sbinSS);

      // scale by correction factors
      if((it->first).find("Data")==string::npos)
	h1->Scale(Lumi/1000*hltEff_);

      // if W+jets, scale by extrapolation
      float sFWOS = 
	( selection_.find("novbf")!=string::npos || selection_.find("nobTag")!=string::npos ) ? OSWinSignalRegionDATA/OSWinSignalRegionMC : WcorrectionFactorOS;
      if((it->first).find("WJets")!=string::npos){
	h1->Scale( sFWOS );
	hW->Add(h1,1.0);
      }

      // if DY->tautau, and vbf scale by ratio data/MC
      if((it->first).find("DYToTauTau")!=string::npos && selection_.find("vbf")!=string::npos && selection_.find("novbf")==string::npos){
	cout << "DY->tautau will be rescaled by 1.03 according to the Z->mumu+vbf/Z->mumu ratio" << endl;
	h1->Scale( VbfExtrapolationFactor );
      }

      // if DY->mumu, mu->tau, scale by fake-rate
      if((it->first).find("DYMutoTau")!=string::npos){
	float sF = MutoTauCorrectionFactor;
	if(selection_.find("vbf")!=string::npos && selection_.find("novbf")==string::npos) sF *= VbfExtrapolationFactor;
	h1->Scale(sF);
	hZmm->Add(h1,1.0);
      }

      // if DY->mumu, jet->tau, scale by fake-rate
      if((it->first).find("DYJtoTau")!=string::npos){
	float sF = JtoTauCorrectionFactor;
	if(selection_.find("vbf")!=string::npos && selection_.find("novbf")==string::npos) sF *= VbfExtrapolationFactor;
	h1->Scale(sF);
	hZmj->Add(h1,2.0); // x2
      }

    }
  
    /////////////////////////////////////////////////////////////////////////////////////

    // Legend
    if( (it->first).find("DYMutoTau")!=string::npos ||  
	(it->first).find("DYJtoTau")!=string::npos || 
	(it->first).find("WJets")!=string::npos || 
	(it->first).find("Others")!=string::npos ) {
      hEWK->SetFillColor(kBlue);
      hEWK->Add(h1,1.0);

      if( (it->first).find("Others")!=string::npos )
	hVV->Add(h1,1.0);
    }

    if( (it->first).find("DYToTauTau")!=string::npos ) {
      hZtt->Add(h1,1.0);
      hZtt->SetFillColor(kWhite);
    }
    if( (it->first).find("TTbar")!=string::npos ) {
      hTTb->Add(h1,1.0);
      hTTb->SetFillColor(kMagenta);     
    }
    if( (it->first).find("SS")!=string::npos ) {
      hQCD->Add(h1,1.0);
      hQCD->SetFillColor(42);
    }
    if((it->first).find("qqH115")!=string::npos){
      hSgn1->Add(h1,1.0);
      hSgn1->Scale(magnifySgn_);
      h1->Scale(magnifySgn_);
      hSgn1->SetLineWidth(2);
      h1->SetFillColor(kBlack);
      h1->SetFillStyle(3004);
      h1->SetLineColor(kBlack);
    }
    if((it->first).find("ggH115")!=string::npos){
      hSgn2->Add(h1,1.0);
      hSgn2->Scale(magnifySgn_);
      h1->Scale(magnifySgn_);
      hSgn2->SetLineWidth(2);
      h1->SetFillColor(kBlack);
      h1->SetFillStyle(3005);
      h1->SetLineColor(kBlack);
    }
    if((it->first).find("Data")!=string::npos){
      hData->Add(h1,1.0);
      hData->Sumw2();
      hData->SetMarkerStyle(20);
      hData->SetMarkerSize(1.2);
      hData->SetMarkerColor(kBlack);
      hData->SetLineColor(kBlack);
      hData->SetXTitle(XTitle_+" ("+Unities_+")");
      hData->SetYTitle(Form(" Events/(%.1f %s)", hData->GetBinWidth(1), Unities_.Data() ) );
      hData->SetTitleSize(0.04,"X");
      hData->SetTitleSize(0.05,"Y");
      hData->SetTitleOffset(0.95,"Y");
    }

    // adding alltogether
    hSiml->Add(h1,1.0);

    if(VERBOSE) cout<<(it->first) << " ==> " 
		    << h1->Integral() << " +/- " 
		    << TMath::Sqrt(h1->GetEntries())*(h1->Integral()/h1->GetEntries())
		    << endl;
  }

  // all signal summed together:
  hSgn->Add(hSgn1,hSgn2,1,1);
  hSgn->SetFillColor(kRed);
  hSgn->SetLineWidth(2);

  //Adding to the stack
  aStack->Add(hQCD);
  aStack->Add(hEWK);
  aStack->Add(hTTb);
  aStack->Add(hZtt);
  aStack->Add(hSgn);

  // legend
  leg->AddEntry(hData,"Observed","P");
  leg->AddEntry(hSgn,Form("(%.0fx) H#rightarrow#tau#tau m_{H}=%d",magnifySgn_,mH_),"F");
  leg->AddEntry(hZtt,"Z#rightarrow#tau#tau","F");
  leg->AddEntry(hTTb,"t#bar{t}","F");
  leg->AddEntry(hEWK,"Electroweak","F");
  leg->AddEntry(hQCD,"QCD","F");
  
  hData->Draw("P");
  aStack->Draw("HISTSAME");
  hData->Draw("PSAME");
  
  TH1F* hStack = (TH1F*)aStack->GetHistogram();
  hStack->SetXTitle(XTitle_+" ("+Unities_+")");
  hStack->SetYTitle(Form(" Events/(%.0f %s)", hStack->GetBinWidth(1), Unities_.Data() ) );
  hStack->SetTitleSize(0.04,"X");
  hStack->SetTitleSize(0.05,"Y");
  hStack->SetTitleOffset(0.95,"Y");

  leg->Draw();

  c1->SaveAs(Form("plots/plot_muTau_mH%d_%s_%s_%s.png",mH_,selection_.c_str(),analysis_.c_str(),variable_.Data()));

  // templates for fitting
  TFile* fout = new TFile(Form("histograms/muTau_mH%d_%s_%s_%s.root",mH_,selection_.c_str(),analysis_.c_str(),variable_.Data()),"RECREATE");
  fout->cd();
  hQCD->Write();
  hZmm->Write();
  hZmj->Write();
  hTTb->Write();
  hZtt->Write();
  hW->Write();
  hVV->Write();
  hSgn1->Write();
  hSgn2->Write();
  hData->Write();
  hParameters->Write();
  fout->Write();
  fout->Close();

}
Example #25
0
void PlotPubHisto(TObjArray histograms,TEnv *params){
    // This is a modification of the AddHistos macro
    
    // Number of histos to plot:
    Int_t ntot = histograms.GetEntries();
    
    // Check we have what we expect (the order should be: data, qcd, wjets, etc...)
    for(Int_t i = 0; i<ntot; i++){
	if(histograms[i]==0) {
	    cout<<"Error in AddHistos: histogram "<<i<<" is a NULL pointer!"<<endl;
	    return;
	}
	TH1F * hthis = (TH1F*) histograms[i];
	// include the overflow/underflow bins:
	int numbins = hthis->GetNbinsX(); //this is the last bin plotted
	double hicontent = hthis->GetBinContent(numbins);
	double overflow  = hthis->GetBinContent(numbins+1);// this bin contains the overflow
	double locontent = hthis->GetBinContent(1);// this is the first bin plotted
	double underflow = hthis->GetBinContent(0);// this bin contains the underflow
	if (underflow>0 || overflow>0){
	    //printf("%-20s numbins=%4i hicontent=%4.2f over=%4.2f locontent=%4.2f underflow=%4.2f \n",
	    //	 title.Data(),numbins,hicontent,overflow,locontent,underflow);
	}
	hthis->SetBinContent(numbins,hicontent+overflow);
	hthis->SetBinContent(1,locontent+underflow);
    }
    
    // define a few additional line styles:
    gStyle->SetLineStyleString(5,"20 12 4 12");
    gStyle->SetLineStyleString(6,"20 12 4 12 4 12 4 12");
    gStyle->SetLineStyleString(7,"20 20");
    gStyle->SetLineStyleString(8,"20 12 4 12 4 12");
    gStyle->SetLineStyleString(9,"80 25");
    gStyle->SetLineStyleString(10,"50 10 10 10");
    gStyle->SetLineStyleString(17,"30 25");
    gStyle->SetLineStyleString(20,"60 20");
    gStyle->SetLineStyleString(21,"60 20 20 20");
    int lineStyle[20];
    for(int i=0;i<20;i++) {
	lineStyle[i]=i;
    }

    // the first histogram in the list:
    TH1F *h0=((TH1F*) histograms[0])->Clone();
    
    // histogram output filename
    TString oFileName=params->GetValue("Histo.Output.Filename","bogus.eps");
    
    // figure out the number of signals
    Int_t nsig=1;
    if(params->Defined("Histo.Signal.Title.1")) nsig=1;
    if(params->Defined("Histo.Signal.Title.2")) nsig=2;
    if(params->Defined("Histo.Signal.Title.3")) nsig=3;
    
    cout << " I will use nsig = " << nsig << " signal sources" << endl;
    
    // Do the cumulative summing, except for the data
    TObjArray addedhistos; addedhistos.Clear();
    TObjArray signalhistos; signalhistos.Clear();
    TString sampletitles[20];
    Int_t nbkg=0;
    for(Int_t i = 1; i<ntot; i++){// i runs over histograms[i], so data is for i=0
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+1 << ".";// Counting starts at 1: Files.1.Name: Data
	TString bSrcName(baseSrcName.str().c_str());
	// skip some if we want to show them as lines
	TString htitle=params->GetValue(bSrcName+"Title","");
	sampletitles[i-1]=htitle;
	if(params->GetValue("Histo.ShowSignalSeparately",0)==1 &&
	   // skip the last two if the signal title is not defined:
	   ( ( !(params->Defined("Histo.Signal.Title")||params->Defined("Histo.Signal.Title.1")) && i>=ntot-nsig) 
	     // skip the signal if the signal title is defined
	     || params->GetValue("Histo.Signal.Title",".")==htitle
	     || params->GetValue("Histo.Signal.Title.1",".")==htitle
	     || params->GetValue("Histo.Signal.Title.2",".")==htitle
	     || params->GetValue("Histo.Signal.Title.3",".")==htitle
	     ) ) {
	    TH1F * hthis = (TH1F*) histograms[i]->Clone();
	    cout<<" Found signal in location "<<i+1<<" with name "<<htitle.Data()<<endl;
	    signalhistos.Add(hthis);
	} else {
	    TH1F * hthis = (TH1F*) histograms[i]->Clone();
	    addedhistos.Add(hthis); // Fill in the new TObjArray with a copy 
	    //cout << " Adding bkg " << i << " " << htitle.Data() << " " << hthis->Integral() << endl;
	    // add all of the backgrounds
	    if (i>1) {// i=0 is the data, and we must start with the second
		      // background to add the previous
		TH1F * hprevious = (TH1F*) addedhistos[i-2];
		if ( hthis->GetXaxis()->GetNbins() != hprevious->GetXaxis()->GetNbins() ) {
		    // Protection against _whoran histogram. 
		    // We cannot add two histograms with different numbers of bins!
		    cout<<"Error in AddHistos: incompatible number of bins!"<<endl;  
		    return;
		}
		hthis->Add(hprevious); // Do the addition
		addedhistos.RemoveAt(i-1); // And substitute whatever we had 
		addedhistos.AddAt(hthis,i-1);
		nbkg++;
		//cout << "Substituing bkg " << i << " + " << i-1 << " in addedhistos["<< i-1 <<"]" << endl;
	    }	    
	} // end of: if adding histograms
    }
    cout << " nbkg = " << nbkg << endl; 
    
    // Rebin histos if necessary, but first calculate KS:
    TH1F *hbkg = (TH1F*) addedhistos[nbkg];
    double KS = h0->KolmogorovTest(hbkg);
    double chi2ndf = h0->Chi2Test(hbkg, "UWUFOFCHI2/NDF");
    //cout << title.Data() << " KS = " << KS << " chi2/NDF = " << chi2ndf << endl;
    // Rebin? Set nrebin = 0 to NOT do rebinning. 
    // Will rebin only histos whose maximum x axis value exceeds 20. 
    // Anything with less will most probably be already made of integers, so no
    // need to rebin that! 
    Int_t nbinsx = h0->GetXaxis()->GetNbins();
    Int_t nbinsy = 100;
    Int_t nrebin = 5;
    if ( nbinsx > 750 && nbinsx <= 1000) nrebin = 30;
    if ( nbinsx > 400 && nbinsx <= 750 ) nrebin = 25;//20
    if ( nbinsx > 300 && nbinsx <= 400 ) nrebin = 25;//15
    if ( nbinsx > 200 && nbinsx <= 300 ) nrebin = 25;//15
    if ( nbinsx > 150 && nbinsx <= 200 ) nrebin = 10;//10
    if ( nbinsx > 100 && nbinsx <= 150 ) nrebin = 10;//10
    if ( nbinsx > 50 && nbinsx <= 100 )  nrebin = 10;//10
    if ( nbinsx > 20 && nbinsx <= 50 )   nrebin = 2;
    if ( nbinsx <= 20 ) nrebin = 1;  
    
    printf(" Saw nbins =%4i, rebinning by nrebin =%2i to final %3i bins \n",nbinsx,nrebin,int(nbinsx/nrebin));	

    if ( nrebin != 0 ) {
	h0->Rebin(nrebin); // data
	for (Int_t i = 0; i<=nbkg; i++){
	    TH1F * h = (TH1F*) addedhistos[i];
	    h->Rebin(nrebin);
	}
	for (Int_t i = 0; i<nsig; i++){
	    TH1F * h = (TH1F*) signalhistos[i];
	    h->Rebin(nrebin);
	}
    }

    // default text size: 0.045
    // make it bigger for the paper
    float textSize = 0.045;
    if(params->GetValue("Histo.Preliminary","yes")==TString("paper")) textSize=0.07;
    if(params->Defined("Histo.TextSize")) textSize=params->GetValue("Histo.TextSize",0.07);
    
    // Now, check largest dimensions so that we can plot all histograms at once.
    Float_t xmin=9999., xmax=-9999., ymin=9999., ymax=-9999.;
    for(Int_t i = 0; i<=nbkg; i++){
	TH1F * h = (TH1F*) addedhistos[i];
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+1 << ".";
	TString bSrcName(baseSrcName.str().c_str());
	
	TAxis *axis = h->GetXaxis();
	if( axis->GetXmin() < xmin ) xmin = axis->GetXmin();
	if( axis->GetXmax() > xmax ) xmax = axis->GetXmax();
	if( h->GetMinimum() < ymin ) ymin = h->GetMinimum();
	if( h->GetMaximum() > ymax ) ymax = h->GetMaximum();
    }
    ymax = TMath::Nint(ymax*1.25+1); // Make enough room for the big legend
    TString title = h0->GetTitle();
    
    //
    // now check if we should simply use the ranges that was passed to us.
    if(params->Defined("Histo.Xmin")) xmin = params->GetValue("Histo.Xmin",0.);
    if(params->Defined("Histo.Xmax")) xmax = params->GetValue("Histo.Xmax",0.);
    if(params->Defined("Histo.Ymin")) ymin = params->GetValue("Histo.Ymin",0.);
    if(params->Defined("Histo.Ymax")) ymax = params->GetValue("Histo.Ymax",0.);
    
    // Now make the frame:
    TH2F * frame = new TH2F("frame","",nbinsx,xmin,xmax,nbinsy,ymin,ymax);
    cout<<" frame has xmin "<<xmin<<", xmax "<<xmax<<", ymax "<<ymax<<endl;
    
    // get the x- and y-axis titles
    TString ytitle=params->GetValue("Histo.YTitle","");
    if ( params->Defined("Histo.XTitle")) {
	frame->SetXTitle(params->GetValue("Histo.XTitle",""));
    } else {
	frame->SetXTitle(h0->GetTitle());
    }
    frame->SetYTitle(ytitle.Data()); 
    // also set the text size for the X and Y axis titles and numbers
    // do this globally for the style we are using
    float axisLabelSize=textSize;
    frame->GetXaxis()->SetLabelSize(axisLabelSize);
    frame->GetYaxis()->SetLabelSize(axisLabelSize);
    frame->GetXaxis()->SetTitleSize(axisLabelSize);
    frame->GetYaxis()->SetTitleSize(axisLabelSize);
    
    frame->SetStats(false);
    // reduce the axis title offset if the fonts are very large
    if(textSize>0.055) frame->GetXaxis()->SetTitleOffset(1.0);
    // also change the X axis title offset to move it farther away from the numbers
    if(params->Defined("Histo.XTitle.Offset")) {
	float xtitoffset=params->GetValue("Histo.XTitle.Offset",1.0);
	frame->GetXaxis()->SetTitleOffset(xtitoffset);
    }
    
    // also change the y axis title offset to move it farther away from the numbers
    frame->GetYaxis()->SetTitleOffset(1.0);
    // reduce the axis title offset if the fonts are very large
    if(textSize>0.055) frame->GetYaxis()->SetTitleOffset(1.0);
    
    // set the axes divisions
    frame->GetXaxis()->SetNdivisions(505,true);
    if(params->Defined("Histo.XNdivisions")) frame->GetXaxis()->SetNdivisions(params->GetValue("Histo.XNdivisions",505),kTRUE);
    if(params->Defined("Histo.YNdivisions")) frame->GetYaxis()->SetNdivisions(params->GetValue("Histo.YNdivisions",505),kTRUE);
    
    // make sure the X axis title and Y axis title are in black!
    frame->GetXaxis()->SetTitleColor(1);
    frame->GetYaxis()->SetTitleColor(1);

    // Could plot in log scale...
    //gPad->SetLogy();

    // finally: Draw
    frame->Draw();
    
    // Draw the background ones:
    for(Int_t i=nbkg; i>=0; i--){
	TH1F * h = (TH1F*) addedhistos[i];
	h->SetStats(kFALSE);
	
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+2 << ".";// to account for the data which is Files.1
	TString bSrcName(baseSrcName.str().c_str());
	Int_t hcolor=params->GetValue(bSrcName+"Color",1); 	
	h->SetLineColor(1);      
	h->SetFillColor(hcolor);
        if (i==nbkg) printf(" Data Yield = %5.2f ; SumBkg = %5.2f ; Data-SumBkg diff = %5.2f%% \n",
	   		     h0->Integral(),h->Integral(),(h0->Integral()-h->Integral())*100./h0->Integral());
	printf(" plotting bkg i=%2i name=%20.20s file=%2i integral=%5.1f color=%2i\n",
	       i,sampletitles[i].Data(),i+2,h->Integral(),hcolor);
	int fillStyle=params->GetValue(bSrcName+"FillStyle",1001);
	h->SetFillStyle(fillStyle);
	h->DrawCopy("Hist,Same");
    }
    //
    // and draw the signal ones
    // draw them in reverse order so that the last one will be on top.
    //for(Int_t i=ntot-3; i<ntot; i++){
    for(Int_t i=nsig-1; i>=0; i--){
	ostringstream baseSrcName;
	baseSrcName << "Files." << ntot+1-nsig+i << ".";
	TString bSrcName(baseSrcName.str().c_str());
	
	Int_t hcolor=params->GetValue(bSrcName+"Color",1);
	TH1F * h = (TH1F*) signalhistos[i];
       	if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=90"))        h->Add (h, 1.07874865  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=100"))  h->Add (h, 1.62317373  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=110"))  h->Add (h, 2.31347600  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=120"))  h->Add (h, 3.25275183  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=130"))  h->Add (h, 4.54142919  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=140"))  h->Add (h, 6.19195046  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=150"))  h->Add (h, 8.38307290  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=160"))  h->Add (h, 11.31721008 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=170"))  h->Add (h, 14.85376469 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=180"))  h->Add (h, 19.54537459 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=190"))  h->Add (h, 25.44594010 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=200"))  h->Add (h, 32.94784356 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=220"))  h->Add (h, 54.09499080 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=240"))  h->Add (h, 86.85079034 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=260"))  h->Add (h, 136.31406761-1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=280"))  h->Add (h, 210.70375053-1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=300"))  h->Add (h, 319.79533099-1.000);
	
	printf(" plotting sig i=%2i name=%20.20s file=%2i integral=%5.1f color=%2i\n",
	       i,sampletitles[ntot-1-nsig+i].Data(),ntot+1-nsig+i,h->Integral(),hcolor);
	// create a white background around each line (helps readibility):
	TH1F *h1=h->Clone();
	h1->SetStats(kFALSE);
	h1->SetLineWidth(6);
	h1->SetLineColor(0);h1->SetFillColor(0);
	h1->SetLineStyle(1);
	h1->SetFillStyle(0);
	h1->Draw("HIST,SAME");
	// now draw the proper line:
	h->SetStats(kFALSE);
	h->SetLineWidth(6);
	h->SetLineColor(hcolor);h->SetFillColor(0);	
	Int_t hlinestyle = params->GetValue(bSrcName+"LineStyle",1);
	h->SetLineStyle(hlinestyle);
	h->SetFillStyle(0);	
	// finally, draw!
	h->Draw("HIST,SAME");      
    } // end of: drawing signal as separate lines
    
    // Data is special: 
    // change the default size of the little bar at the end of the error bar here
    gStyle->SetEndErrorSize(3);
    // also, maybe don't display the error bars along the X axis:
    //gStyle->SetErrorX(0);  // X error bars not displayed
    gStyle->SetErrorX(0.5);  // X error bars have width of a bin
    // now set the rest
    h0->SetMarkerSize(2);
    // if there are too many points (>80), keep the marker size smaller
    if(h0->GetNbinsX()>=50) h0->SetMarkerSize(1);
    //if(h0->GetNbinsX()>=100) h0->SetMarkerSize(1);
    h0->SetLineWidth(3);
    h0->SetMarkerStyle(8);
    h0->SetMarkerColor(1);
    h0->Draw("E1,SAME");
    
    // Print some comparison:
    //ostringstream basefactor;
    //basefactor << "Files." << nbkg+3 << "." << "Factor";
    //TString timesfactor(basefactor.str().c_str()); 
    //Double_t nprod = params->GetValue(timesfactor,1.000);
    //printf("Data Yield = %5.2f ; SumBkg = %5.2f ; SumBkg+Sig = %5.2f ; Data-SumBkg diff = %5.2f%% \n",
    //        h0->Integral(),hbkg2->Integral,(hbkg2->Integral()+(signalhistos[0]->Integral()/nprod),
    //        (h0->Integral()-hbkg2->Integral)*100./h0->Integral()));

    //
    // Print D0 and lumi:
    //
    TText *t1 = new TText();
    t1->SetTextFont(62);
    t1->SetTextColor(1);   
    t1->SetNDC();
    t1->SetTextAlign(12);
    t1->SetTextSize(textSize);
    TString prelim="D\328 Preliminary";
    if(oFileName.EndsWith(".eps")) {
	prelim="D\349 Preliminary L=3.7 fb^-1#";
    }
    else if(oFileName.EndsWith(".gif")) {
	prelim="D\328 Preliminary L=3.7 fb^-1#";
    }
    t1->DrawTextNDC(0.13,0.965,prelim.Data());

    // a counter of how much text we have added from the top
    int nAddTextLines=0;
    
    // any additional text?
    for(int iText=1;iText<20;iText++) {
	ostringstream baseTextName;
	baseTextName << "Histo.AddText." << iText;
	TString bTextName(baseTextName.str().c_str());
	if(params->Defined(bTextName)) {
	    // we are adding a line of text
	    TLatex *t2 = new TLatex();
	    t2->SetTextFont(62);
	    t2->SetTextColor(13);   
	    t2->SetTextAlign(32);
	    t2->SetNDC();
	    t2->SetTextSize(textSize);
	    TString addText(params->GetValue(bTextName,"."));
	    float x0=0.94;
	    float y0=0.96-(nAddTextLines)*0.05;
	    
	    // check if the user specified an alternative location for the text
	    if(params->Defined(bTextName+".X0")) x0=params->GetValue(bTextName+".X0",0.94);
	    if(params->Defined(bTextName+".Y0")) y0=params->GetValue(bTextName+".Y0",0.8);
	    if(params->Defined(bTextName+".TextSize")) t2->SetTextSize(params->GetValue(bTextName+".TextSize",textSize));
	    
	    // and increment the counter keeping track of how much we added,
	    // but only if the user didn't move the label around.
	    if(!params->Defined(bTextName+".X0")) nAddTextLines++;
	    printf("AddText %4.2f %4.2f %s\n",x0,y0,addText.Data());
	    
	    t2->DrawLatex(x0,y0,addText.Data()); 
	}
    }// end additional text
    
    // now draw the frame axis again so that we can see the tick marks
    frame->Draw("sameaxis");
    
    // Legend:
    TString showLegend(params->GetValue("Histo.ShowLegend","."));
    if( showLegend != "no" ){ 
	float lgdxmin=.65, lgdxmax=.90, lgdymin=.50, lgdymax=.91;
	if(showLegend=="yes" || showLegend=="right") {
	    
	} else if (showLegend=="left"){
	    lgdxmin=.16;
	    lgdxmax=.42;
	}
	TLegend *lgd = new TLegend(lgdxmin,lgdymin,lgdxmax,lgdymax); 
	// This line makes the legend transparent (not grey, ewwww!): 
	lgd->SetBorderSize(0); lgd->SetTextSize(textSize*0.9);// 10% less size 
	lgd->SetTextFont(62); lgd->SetFillColor(0);
	// Plot the legend in reverse order (but data goes first):
	NiceAddEntry(lgd,h0,params->GetValue("Files.1.Title","Data"),"PL");
	for(Int_t i = nbkg; i>=0; i--){
	    TH1F * h = (TH1F*) addedhistos[i];
	    TString lgd_entry= sampletitles[i]; // sampletitles runs from 0 (firstbkg) to ntot-1
	    NiceAddEntry(lgd,h,lgd_entry.Data(),"F");	
	}
	for(Int_t i = nsig-1; i>=0; i--){
	    TH1F * h = (TH1F*) signalhistos[i];
	    TString lgd_entry = sampletitles[i+nbkg+1]; // sampletitles runs from 0 (firstbkg) to ntot-1
	    ostringstream basefactor;
	    basefactor << "Files." << i+nbkg+3 << "." << "Factor";
	    TString timesfactor(basefactor.str().c_str());
	    Double_t nprod = params->GetValue(timesfactor,1.000);
	    if (nprod != 1.0 ) lgd_entry.Form("%s x%2.0f",lgd_entry.Data(),nprod);
	    //cout << i+nbkg+3 << " " << nprod << " " << lgd_entry.Data() << endl;
	    NiceAddEntry(lgd,h,lgd_entry.Data(),"L"); 
	}
	lgd->Draw("SAME");	
    }// show legend


    // Draw the KS:
    TLatex *ks = new TLatex();
    ks->SetTextFont(62);
    ks->SetTextColor(1);   
    TString ks_val = Form("KS = %3.2f",KS);
    ks->SetTextAlign(11); ks->SetTextSize(0.03); // ks->SetTextAngle(90); 
    ks->DrawTextNDC(0.83,0.93,ks_val.Data());
    TString chi2_val = Form("#chi^{2}/ndf = %3.1f",chi2ndf);
    ks->SetNDC(true); ks->DrawLatex(0.83,0.97,chi2_val.Data());
    //
    // Voila!
    //
}
Example #26
0
void higgsMassFit(const int& mH, const std::string& mode = "exclusion", const bool& drawPlots = false, const int& nToys = 10000)
{
  using namespace RooFit;
  RooMsgService::instance().deleteStream(0);
  RooMsgService::instance().deleteStream(1);
  
  
  
  std::string varName = "lepNuW_m";
  
  int step = 16;
  char treeName[50];
  sprintf(treeName, "ntu_%d", step);
  
  float lumi = 1000.;
  
  int nBins = 50;
  double xMin = 0.;
  double xMax = 1000.;
  double xMin_signal = 0.;
  double xMax_signal = 0.;
  SetXSignal(xMin_signal,xMax_signal,mH);
  
  RooRealVar x("x",varName.c_str(),xMin,xMax);
  x.setRange("low",   xMin,       xMin_signal);
  x.setRange("signal",xMin_signal,xMax_signal);
  x.setRange("high",  xMax_signal,xMax);
  
  RooRealVar w("w","weight",0.,1000000000.);
  
  char signalCut[50];
  sprintf(signalCut,"x > %f && x < %f",xMin_signal,xMax_signal);
  
  
  
  //-------------------
  // define the outfile
  char outFileName[50];
  sprintf(outFileName,"higgsMassFit_H%d_%s.root",mH,mode.c_str());
  TFile* outFile = new TFile(outFileName,"RECREATE");
  outFile -> cd();
  
  
  
  //-------------------
  // define the infiles
  char higgsMass[50];
  sprintf(higgsMass,"%d",mH);
  
  std::string BKGPath = "/grid_mnt/vol__vol1__u/llr/cms/abenagli/COLLISIONS7TeV/Fall10/VBFAnalysisPackage/data/VBFAnalysis_AK5PF_H" + 
                        std::string(higgsMass) + 
                        "_ET30_maxDeta_minDeta_Spring11_EGMu_noHiggsMassCut/";
  
  std::string WJetsFolder = "WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_Spring11-PU_S1_START311_V1G1-v1/";
  std::string TTJetsFolder = "TTJets_TuneZ2_7TeV-madgraph-tauola_Spring11-PU_S1_START311_V1G1-v1/";
  //std::string ZJetsFolder = 
  //std::string GJets_HT40To100Folder 
  //std::string GJets_HT100To200Folder 
  //std::string GJets_HT200Folder 
  //std::string WWFolder 
  //std::string WZFolder 
  //std::string TJets_schannelFolder 
  //std::string TJets_tchannelFolder 
  //std::string TJets_tWchannelFolder 
  
  std::string GluGluHToLNuQQFolder   = "GluGluToHToWWToLNuQQ_M-"   + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  std::string GluGluHToTauNuQQFolder = "GluGluToHToWWToTauNuQQ_M-" + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  std::string VBFHToLNuQQFolder      = "VBF_HToWWToLNuQQ_M-"       + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  std::string VBFHToTauNuQQFolder    = "VBF_HToWWToTauNuQQ_M-"     + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  
  
  
  //---------------------------------------
  // define the background shape histograms
  int nBKG = 2;
  
  TH1F** BKGShapeHisto = new TH1F*[nBKG];
  TH1F* BKGTotShapeHisto = new TH1F("BKGTotShapeHisto","",nBins,xMin,xMax);
  THStack* BKGShapeStack = new THStack();
  RooDataSet** rooBKGDataSet = new RooDataSet*[nBKG];
  
  std::string* BKGNames = new std::string[nBKG];
  BKGNames[1]  = BKGPath+WJetsFolder+"VBFAnalysis_AK5PF.root";
  BKGNames[0]  = BKGPath+TTJetsFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[1]  = BKGPath+ZJetsFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[2]  = BKGPath+GJets_HT40To100Folder+"VBFAnalysis_AK5PF.root";
  //BKGNames[3]  = BKGPath+GJets_HT100To200Folder+"VBFAnalysis_AK5PF.root";
  //BKGNames[4]  = BKGPath+GJets_HT200Folder+"VBFAnalysis_AK5PF.root";
  //BKGNames[6]  = BKGPath+WWFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[7]  = BKGPath+WZFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[8]  = BKGPath+TJets_schannelFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[9]  = BKGPath+TJets_tchannelFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[10] = BKGPath+TJets_tWchannelFolder+"VBFAnalysis_AK5PF.root";
  
  std::string* BKGShortNames = new std::string[nBKG];
  BKGShortNames[1]  = "WJets";
  BKGShortNames[0]  = "TTJets";
  //BKGShortNames[1]  = "ZJets";
  //BKGShortNames[2]  = "GJets_HT40To100";
  //BKGShortNames[3]  = "GJets_HT100To200";
  //BKGShortNames[4]  = "GJets_HT200";
  //BKGShortNames[6]  = "WW";
  //BKGShortNames[7]  = "WZ";
  //BKGShortNames[8]  = "TJets_schannel";
  //BKGShortNames[9]  = "TJets_tchannel";
  //BKGShortNames[10] = "TJets_tWchannel";
  
  Color_t* BKGColors = new Color_t[nBKG];
  BKGColors[1]  = kOrange-708;
  BKGColors[0]  = kAzure-795;
  
  
  
  //-----------------------------------
  // define the signal shape histograms
  int nSIG = 2;
  
  TH1F* SIGShapeHisto = new TH1F("SIGShapeHisto","",4*nBins,xMin,xMax);
  SIGShapeHisto -> Sumw2();
  SIGShapeHisto -> SetLineWidth(1);
  SIGShapeHisto -> SetLineStyle(1);
  RooDataSet* rooSIGDataSet = new RooDataSet("rooSIGDataSet","",RooArgSet(x,w),WeightVar(w));
  
  std::string* SIGNames = new std::string[nSIG];
  SIGNames[0]  = BKGPath+GluGluHToLNuQQFolder+"VBFAnalysis_AK5PF.root";
  SIGNames[1]  = BKGPath+VBFHToLNuQQFolder+"VBFAnalysis_AK5PF.root";
  
  std::string* SIGShortNames = new std::string[nSIG];
  SIGShortNames[1]  = "ggH";
  SIGShortNames[0]  = "qqH";
  
  
  
  
  
  
  //----------------------
  // loop over backgrounds
  std::cout << "***********************************************************************" << std::endl;
  std::cout << ">>> Fill the background shapes" << std::endl;
    
  for(int i = 0; i < nBKG; ++i)
  {
    TFile* inFile_BKGShape = TFile::Open((BKGNames[i]).c_str());
    inFile_BKGShape -> cd();
    
    TTree* BKGShapeTree = (TTree*)(inFile_BKGShape -> Get(treeName));
    
    BKGShapeHisto[i] = new TH1F(("BKGShapeHisto_"+BKGShortNames[i]).c_str(),"",nBins,xMin,xMax);
    enum EColor color = (enum EColor)(BKGColors[i]);
    BKGShapeHisto[i] -> SetFillColor(color);
    BKGShapeHisto[i] -> Sumw2();
    
    rooBKGDataSet[i] = new RooDataSet(("rooBKGDataSet_"+BKGShortNames[i]).c_str(),"",RooArgSet(x,w),WeightVar(w)); 
    
    TH1F* eventsHisto;
    inFile_BKGShape -> GetObject("events", eventsHisto);
    float totEvents = eventsHisto -> GetBinContent(1);
    
    
    // set branch addresses
    float crossSection;
    float var;
    BKGShapeTree -> SetBranchAddress("crossSection", &crossSection);
    BKGShapeTree -> SetBranchAddress(varName.c_str(),&var);
    
    
    // loop over the entries
    for(int entry = 0; entry < BKGShapeTree->GetEntries(); ++entry)
    {
      BKGShapeTree -> GetEntry(entry);
      
      x = var;
      w = 1./totEvents*crossSection*lumi;
      
      BKGShapeHisto[i] -> Fill(var, 1./totEvents*crossSection*lumi);
      BKGTotShapeHisto    -> Fill(var, 1./totEvents*crossSection*lumi);
      rooBKGDataSet[i] -> add(RooArgSet(x,w));
    }
    
    BKGShapeStack -> Add(BKGShapeHisto[i]);
  }
  
  
  
  
  
  
  //------------------
  // loop over signals
  std::cout << ">>> Fill the signal shapes" << std::endl;
    
  for(int i = 0; i < nSIG; ++i)
  {
    TFile* inFile_SIGShape = TFile::Open((SIGNames[i]).c_str());
    inFile_SIGShape -> cd();
    
    TTree* SIGShapeTree = (TTree*)(inFile_SIGShape -> Get(treeName));
    
    TH1F* eventsHisto = (TH1F*)(inFile_SIGShape -> Get("events"));
    float totEvents = eventsHisto -> GetBinContent(1);
    
    
    // set branch addresses
    float crossSection;
    float var;
    SIGShapeTree -> SetBranchAddress("crossSection", &crossSection);
    SIGShapeTree -> SetBranchAddress(varName.c_str(),&var);
    
    
    // loop over the entries
    for(int entry = 0; entry < SIGShapeTree->GetEntries(); ++entry)
    {
      SIGShapeTree -> GetEntry(entry);
      
      x = var;
      w= 1./totEvents*crossSection*lumi;
      
      SIGShapeHisto -> Fill(var, 1./totEvents*crossSection*lumi);
      rooSIGDataSet -> add(RooArgSet(x,w));
    }
  }
  
  
  
  //-----------------------------------
  // draw the background + signal stack
  if( drawPlots )
  {
    TCanvas* c1 = new TCanvas("BKGShapeStack","BKGShapeStack");
    c1 -> SetGridx();
    c1 -> SetGridy();
    BKGShapeStack -> Draw("HIST");
    SIGShapeHisto -> Draw("HIST,same");  
    char pngFileName[50];
    sprintf(pngFileName,"BKGShapeStack_H%d_%s.png",mH,mode.c_str());
    c1 -> Print(pngFileName,"png");
  }  
  
  
  
  
  
  
  //---------------------------------
  // define the bkg shape with roofit
  std::cout << ">>> Define the background pdf" << std::endl;
    
  RooKeysPdf** rooBKGPdf = new RooKeysPdf*[nBKG];
  RooRealVar** rooNBKG = new RooRealVar*[nBKG];
  RooRealVar* rooNBKGTot = new RooRealVar("rooNBKGTot","",BKGTotShapeHisto->Integral(),0.,1000000.);
  
  for(int i = 0; i < nBKG; ++i)
  {  
    rooBKGPdf[i] = new RooKeysPdf(("rooBKGPdf_"+BKGShortNames[i]).c_str(),"",x,*rooBKGDataSet[i]);
    rooNBKG[i] = new RooRealVar(("rooNBKG_"+BKGShortNames[i]).c_str(),"",BKGShapeHisto[i]->Integral(),BKGShapeHisto[i]->Integral()),BKGShapeHisto[i]->Integral();
  }
  
  RooAddPdf* rooBKGTotPdf = new RooAddPdf("rooBKGTotPdf","",RooArgList(*rooBKGPdf[0],*rooBKGPdf[1]),RooArgList(*rooNBKG[0],*rooNBKG[1]));
  
  
  
  //---------------------------------
  // define the sig shape with roofit
  std::cout << ">>> Define the signal pdf" << std::endl;
    
  RooKeysPdf* rooSIGPdf = new RooKeysPdf("rooSIGPdf","",x,*rooSIGDataSet);
  RooRealVar* rooNSIG = new RooRealVar("rooNSIG","",1.,-1000000.,1000000.);
  
  
  
  //---------------------------------
  // define the tot shape with roofit
  std::cout << ">>> Define the total pdf" << std::endl;
  
  RooAddPdf* rooTotPdf = NULL;
  if( mode == "exclusion") rooTotPdf = new RooAddPdf("rooTotPdf","",RooArgList(*rooBKGTotPdf),RooArgList(*rooNBKGTot));
  if( mode == "discovery") rooTotPdf = new RooAddPdf("rooTotPdf","",RooArgList(*rooBKGTotPdf,*rooSIGPdf),RooArgList(*rooNBKGTot,*rooNSIG));
  
  
  
  
  
  
  //----
  // plot 
  if( drawPlots )
  {
    TCanvas* c2 = new TCanvas("rooTotPdf","rooTotPdf");
    c2 -> SetGridx();
    c2 -> SetGridy();
    
    RooPlot* rooBKGPlot = x.frame();
    rooBKGTotPdf -> plotOn(rooBKGPlot,LineColor(kBlack));
    enum EColor color = (enum EColor)(BKGColors[0]);
    rooBKGTotPdf -> plotOn(rooBKGPlot,Components(("rooBKGPdf_"+BKGShortNames[0]).c_str()),LineColor(color));
    color = (enum EColor)(BKGColors[1]);
    rooBKGTotPdf -> plotOn(rooBKGPlot,Components(("rooBKGPdf_"+BKGShortNames[1]).c_str()),LineColor(color));
    
    rooSIGPdf -> plotOn(rooBKGPlot,LineColor(kBlack),LineStyle(1),LineWidth(1));
    
    rooBKGPlot->Draw();
    
    TH1F* BKGShapeHistoNorm = (TH1F*) BKGTotShapeHisto -> Clone();
    BKGShapeHistoNorm -> Scale(1./BKGTotShapeHisto->Integral()/nBKG);
    BKGShapeHistoNorm -> Draw("HIST,same");

    char pngFileName[50];
    sprintf(pngFileName,"BKGShapeNorm_H%d_%s.png",mH,mode.c_str());
    c2 -> Print(pngFileName,"png");
  }
  
  
  
  
  
  
  //------------------------
  // generate toy experiment
  std::cout << "***********************************************************************" << std::endl;
  std::cout << ">>> 1st toy experiment - " << mode << " mode" << std::endl;  
  
  int NBKGToy = int(BKGTotShapeHisto->Integral());
  int NSIGToy = 0;
  if( mode == "discovery" ) NSIGToy = int(SIGShapeHisto->Integral());
  
  RooDataSet* rooBKGToyDataSet = rooBKGTotPdf->generate(RooArgSet(x),NBKGToy);
  RooDataSet* rooSIGToyDataSet = rooSIGPdf->generate(RooArgSet(x),NSIGToy);
  rooBKGToyDataSet -> append(*rooSIGToyDataSet);
  
  float NBKGToy_signal = rooBKGToyDataSet->sumEntries(signalCut);
  float NBKGToy_signal_fit = 0.;
  
  
  
  // fit
  if( mode == "exclusion" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1),Range("low,high"));
  if( mode == "discovery" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1));
  
  
  
  // count events
  if( mode == "exclusion" )
  {
    RooAbsReal* rooTotIntegral = rooTotPdf -> createIntegral(x,NormSet(x),Range("signal"));
    NBKGToy_signal_fit = rooTotIntegral->getVal() * rooNBKGTot->getVal();
    
    std::cout << ">>>>>> BKG toy events (true) in signal region in " << lumi << "/pb: " << NBKGToy_signal << std::endl;  
    std::cout << ">>>>>> BKG toy events (fit)  in signal region in " << lumi << "/pb: " << NBKGToy_signal_fit << std::endl;      
  }
  
  if( mode == "discovery" )
  {
    std::cout << ">>>>>> BKG toy events (true) in " << lumi << "/pb: " << NBKGToy << std::endl;  
    std::cout << ">>>>>> BKG toy events (fit)  in " << lumi << "/pb: " << rooNBKGTot->getVal() << std::endl;  
    std::cout << ">>>>>> SIG toy events (true) in " << lumi << "/pb: " << NSIGToy << std::endl;  
    std::cout << ">>>>>> SIG toy events (fit)  in " << lumi << "/pb: " << rooNSIG->getVal() << std::endl;  
  }
  
  if( drawPlots )
  {
    TCanvas* c3 = new TCanvas("TOY","TOY");
    c3 -> SetGridx();
    c3 -> SetGridy();
    
    RooPlot* rooTOYPlot = x.frame();
    rooBKGToyDataSet -> plotOn(rooTOYPlot,MarkerSize(0.7));
    rooTotPdf -> plotOn(rooTOYPlot, LineColor(kRed));
    rooTotPdf -> plotOn(rooTOYPlot, Components("rooSIGPdf"), LineColor(kRed));
    rooTOYPlot->Draw();
    
    char pngFileName[50];
    sprintf(pngFileName,"BKGToyFit_H%d_%s.png",mH,mode.c_str());
    c3 -> Print(pngFileName,"png");
  }
  
  
  
  
  
  
  //-------------------------
  // generate toy experiments
  
  TH1F* h_BKGRes = new TH1F("h_BKGRes","",200,-400,400);
  TH1F* h_SIGRes = new TH1F("h_SIGRes","",200,-400,400);
  
  TRandom3 B;
  TRandom3 S;
  for(int j = 0; j < nToys; ++j)
  {
    if( j%100 == 0 )
      std::cout << ">>>>>> generating toy experiment " << j << std::endl;
    
    NBKGToy = B.Poisson(BKGTotShapeHisto->Integral());
    NSIGToy = 0;
    if( mode == "discovery" ) NSIGToy = S.Poisson(SIGShapeHisto->Integral());
    
    rooBKGToyDataSet = rooBKGTotPdf->generate(RooArgSet(x),NBKGToy);
    rooSIGToyDataSet = rooSIGPdf->generate(RooArgSet(x),NSIGToy);
    rooBKGToyDataSet -> append(*rooSIGToyDataSet);
    
    NBKGToy_signal = rooBKGToyDataSet->sumEntries(signalCut);
    NBKGToy_signal_fit = 0.;
    
    
    
    // fit
    if( mode == "exclusion" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1),Range("low,high"));
    if( mode == "discovery" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1));    
    
    
    
    // count events
    if( mode == "exclusion" )
    {
      RooAbsReal* rooTotIntegral = rooTotPdf -> createIntegral(x,NormSet(x),Range("signal"));
      NBKGToy_signal_fit = rooTotIntegral->getVal() * rooNBKGTot->getVal();
      
      h_BKGRes -> Fill(NBKGToy_signal_fit - NBKGToy_signal);
      h_SIGRes -> Fill(0.);
    }
    
    if( mode == "discovery" )
    {
      h_BKGRes -> Fill(rooNBKGTot->getVal() - NBKGToy);
      h_SIGRes -> Fill(rooNSIG->getVal() - NSIGToy);
    }
    
  }
  
  
  
  outFile -> cd();
  
  h_BKGRes -> Write();
  h_SIGRes -> Write();
  
  outFile -> Close();
}
Example #27
0
/**
 * Loads a histogram from a ROOT-file, scales it, and either returns it as \c
 * returnedHistogram or adds it to \c returnedHistogram . The first if
 * \c returnedHistogram is \c NULL otherwise the latter.
 *
 * @param histogramName
 *                              name of the histogram.
 * @param inputFilename
 *                              name of the ROOT-file.
 * @param scale
 *                              scale factor for histogram.
 * @param returnedHistogram
 *                              the returned histogram (input, pass-by-reference does not work).
 * @param debug
 *                              switch on debug output, defaults to \c false
 *
 * @return
 *                              the returned histogram (output, pass-by-reference does not work).
 */
void
LoadHistogramTH1F(const TString& histogramName, const TString& inputFilename, double scale, TH1F*& returnedHistogram, bool debug = false)
{
// {{{
    TFile inputFile(inputFilename);
    if (!inputFile.IsOpen())
    {
        cerr << "Could not open '" << inputFilename << "' for reading." << endl;
    }
    else
    {
        TH1F* histogram = dynamic_cast<TH1F*>( inputFile.Get(histogramName) );
        if (!histogram)
        {
            cerr << "No histogram named '" << histogramName << "' in file '" << inputFilename << "'" << endl;
        }
        else
        {
            if (debug) cerr << inputFilename << " " << histogramName << " entries=" << histogram->GetEntries() << " integral=" << histogram->Integral() << " scale*integral=" << scale*histogram->Integral() << endl;
            histogram->Scale(scale);
            if (!returnedHistogram)
            {
                returnedHistogram = new TH1F(*histogram);
                returnedHistogram->SetDirectory(0); // otherwise "TFile inputFile" owns this returnedHistogram and deletes it when "TFile inputFile" goes out of scope
            }
            else
            {
                returnedHistogram->Add(histogram);
            }
        }
        inputFile.Close();
    }
// }}}
};
Example #28
0
void plottingmacro()
{
 setTDRStyle();
 gROOT->ForceStyle();
 initOptions();

 std::vector<Sample> s = samples();
 Sample data(1,"fake data","S1.root",0,true,1000);

 for(size_t i=0;i< s.size();i++) if(s[i].data) {data=s[i];break;}
 data.file()->ls(); 
 for(size_t i=0;i< s.size();i++) s[i].dump(data.lumi());

 std::vector<std::string> names;

 TList * subs = data.file()->GetListOfKeys();
 for(size_t i=0;i< subs->GetSize();i++)
  {
    TList * objs = ((TDirectoryFile *) data.file()->Get(subs->At(i)->GetName()))->GetListOfKeys();
     for(size_t j=0;j< objs->GetSize();j++)
     {
         names.push_back(subs->At(i)->GetName()+std::string("/")  + objs->At(j)->GetName());
 //      std::cout << subs->At(i)->GetName() << "/"  << objs->At(j)->GetName() << std::endl;
         //TODO: select plots via regexp
     }
    
  }

 for(size_t i = 0 ; i < names.size() ; i++) 
  {
   std::map<std::string,TH1F *> grouped;
   TString n=names[i];
   if(!n.Contains(TRegexp("V.*RegionH.*mu.*HiggsMass"))) continue;
   TCanvas *c = new TCanvas();
   c->SetLogy(true);
   c->SetTitle(names[i].c_str());
   TH1F *hd = ((TH1F*)data.file()->Get(names[i].c_str()));
   Options o=options[names[i]];
   hd->Rebin(o.rebin);
   hd->SetMarkerStyle(21);
   hd->Draw("E1");
   hd->SetYTitle(o.yaxis.c_str());
   THStack * sta = new THStack("sta",hd->GetTitle());
   TLegend * l = new TLegend(o.legendx1,o.legendy1,o.legendx2,o.legendy2); //0.7,0.1,0.9,0.6);
  
   l->AddEntry(hd, "Data","LP");

   for(size_t j=0;j< s.size() ;j++) 
   { 
       if(!s[j].data) 
      {
       TH1F * h = ((TH1F*)s[j].file()->Get(names[i].c_str()));
       h->Scale(s[j].scale(data.lumi()));
       h->SetLineColor(s[j].color);
       h->SetFillColor(s[j].color);
       h->Rebin(options[names[i]].rebin);
       if(grouped.find(s[j].name)==grouped.end()) {
          grouped[s[j].name]=(TH1F *)h->Clone(("_"+names[i]).c_str());
          l->AddEntry(h,s[j].name.c_str(),"F");
       }
       else
       {
        grouped[s[j].name]->Add(h);
       }
       sta->Add(h);
//     h->Draw("same");
      }
   }
   sta->Draw("same");
   hd->Draw("E1same");
   hd->GetYaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
   l->Draw();


   std::cout << names[i] << " d: " <<  hd->Integral() << " ";
   THStack * sta2 = new THStack("sta2",hd->GetTitle());
   float tot=0;
   float toterr2=0;

   for(std::map<std::string,TH1F *>::iterator it = grouped.begin(); it != grouped.end();it++)
   {
             std::cout << it->first << " " << it->second->Integral() << " | " ;
             if(it->second->GetEntries() > 0) {
             float er=1.*sqrt(it->second->GetEntries())/it->second->GetEntries()*it->second->Integral();
             toterr2+=er*er;
             }
	     tot+=it->second->Integral();
             sta2->Add(it->second);
   }   
    std::cout << " Tot: " << tot << "+-" << sqrt(toterr2) <<  " SF: " << hd->Integral()/tot << std::endl;
    c = new TCanvas();
    sta2->Draw();
    hd->Draw("E1,same");
    sta2->GetYaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
    hd->GetYaxis()->SetRangeUser(options[names[i]].min,options[names[i]].max);
    l->Draw();

   

  }

}
TH1F* AnalyzeDs1pToDstKs(TChain* fChain,TString DATAorMC,Int_t MatterOrAntiMatter,TString Mode,TString NtupleDir,Int_t WhichCuts){

  Int_t test;
  
  //
  Bool_t TruthMatch=false;
  if(DATAorMC=="MC")TruthMatch=true;
 
  // Declaration of leave types
  Float_t beamSX;
  Float_t beamSY;
  Float_t beamSZ;

  Int_t   nDs1p;
  Float_t Ds1pChi2[400];  
  Float_t Ds1pMass[400];  
  Float_t Ds1pcosth[400];  
  Float_t Ds1pcosthCM[400];  
  Float_t Ds1pp3CM[400];  
  Float_t Ds1pphiCM[400];  
  Int_t   Ds1pLund[400];  
  Int_t   Ds1pMCIdx[400];  
  Int_t   Ds1pd1Lund[400];  
  Int_t   Ds1pd1Idx[400];  
  Int_t   Ds1pd2Lund[400];  
  Int_t   Ds1pd2Idx[400];  
  Float_t Ds1pVtxx[500];  
  Float_t Ds1pVtxy[500];  
  Float_t Ds1pVtxz[500];     

  Int_t   nKs;
  Float_t KsMass[400]; 
  Float_t Ksp3CM[400]; 
  Int_t   KsLund[400]; 
  Int_t   Ksd1Lund[400]; 
  Int_t   Ksd1Idx[400]; 
  Int_t   Ksd2Lund[400]; 
  Int_t   Ksd2Idx[400];  
  Int_t   KsMCIdx[400];
  Float_t KsChi2[400];
  Int_t   KsnDof[400];
  Float_t KsVtxx[500]; 
  Float_t KsVtxy[500]; 
  Float_t KsVtxz[500]; 
  Float_t Kscosth[500]; 
  Float_t Ksphi[500]; 

  Int_t   nDstar;
  Float_t DstarMass[400];  
  Float_t DstarMassErr[400];  
  Float_t Dstarcosth[400];  
  Float_t Dstarp3[400];  
  Float_t Dstarp3CM[400];  
  Int_t   DstarLund[400];  
  Int_t   Dstard1Lund[400];  
  Int_t   Dstard1Idx[400];  
  Int_t   Dstard2Lund[400];  
  Int_t   Dstard2Idx[400];    
  Int_t   DstarMCIdx[400];
 
  Int_t   nD0;
  Float_t D0Mass[400];  
  Float_t D0MassErr[400];  
  Float_t D0p3CM[400];  
  Int_t   D0Lund[400];  
  Int_t   D0d1Lund[400];  
  Int_t   D0d1Idx[400];  
  Int_t   D0d2Lund[400];  
  Int_t   D0d2Idx[400];   
  Int_t   D0d3Lund[400];  
  Int_t   D0d3Idx[400];
  Int_t   D0d4Lund[400];     
  Int_t   D0d4Idx[400];
  Int_t   D0MCIdx[400];
  Float_t D0Chi2[400];
  Int_t   D0nDof[400];

  Int_t   nPi;
  Float_t Pip3[400];  
  Int_t   PiLund[400];   
  Int_t   PiMCIdx[400];
  Int_t   PiTrkIdx[400];
  Int_t   PiSelectorsMap[400];
  
  Int_t   nK;
  Float_t Kp3[400]; 
  Int_t   KLund[400]; 
  Int_t   KMCIdx[400];
  Int_t   KTrkIdx[400];

  Int_t   nPi0;
  Float_t Pi0Mass[400];
  Float_t Pi0p3[400];  
  Int_t   Pi0Lund[400];  
  Int_t   Pi0MCIdx[400];
  Int_t   Pi0d1Lund[400];
  Int_t   Pi0d1Idx[400];

  Float_t GammaECal[400];
  Int_t   GammaMCIdx[400];
  Int_t   GammaLund[400];

  Int_t TRKnSvt[400];
  Int_t TRKLund[400];
  

  ////MC block
  Int_t mcLen;
  Int_t mcLund[400];
  Int_t mothIdx[400];
  Int_t dauLen[400];
  Int_t dauIdx[400];
  Float_t mcmass[400]; 
  Float_t mccosth[400];
  Float_t mcp3[400];
  Float_t mccosthCM[400];
  Float_t mcp3CM[400]; 


 

  //////My derived variables
  Float_t D0Probab;
  Float_t KsProbab;
  Float_t KsCosine;  
  TVector3 Ksp3Direction;
  TVector3 KsFlightDirection;

  Int_t MCDs1pCounterPerEvent=0;
  Int_t MCDs1pCounterTotal=0;
  Int_t RecoDs1pCounterTotal=0;


  Int_t   Ds1pIdx;
  Int_t   DstarIdx;
  Int_t   KsIdx;
  Int_t   D0Idx;
  Int_t   PiIdx;
  Int_t   SlowPiIdx;
  Int_t   KIdx;
  Int_t   Pi0Idx;
  Int_t   GammaIdx;  
  Int_t   PitrkIdx;
  Int_t   SlowPitrkIdx;
  Int_t   KsPi1Idx;
  Int_t   KsPi2Idx;
  Int_t   KsPi1trkIdx;
  Int_t   KsPi2trkIdx;

  //TChain* fChain=DstToD0PiChain(firstfile,lastfile, DATAorMC,Mode, ModeSubDir);
  if(fChain==NULL){
    cout<<"No chain."<<endl;
    return NULL;
  }
  fChain->SetBranchAddress("beamSX",&beamSX);
  fChain->SetBranchAddress("beamSY",&beamSY);
  fChain->SetBranchAddress("beamSZ",&beamSZ);

  fChain->SetBranchAddress("nDs1p",&nDs1p);
  fChain->SetBranchAddress("Ds1pMass",Ds1pMass);
  fChain->SetBranchAddress("Ds1pcosthCM",Ds1pcosthCM);
  fChain->SetBranchAddress("Ds1pp3CM",Ds1pp3CM);
  fChain->SetBranchAddress("Ds1pLund",Ds1pLund); 
  fChain->SetBranchAddress("Ds1pd1Lund",Ds1pd1Lund);
  fChain->SetBranchAddress("Ds1pd1Idx",Ds1pd1Idx);
  fChain->SetBranchAddress("Ds1pd2Lund",Ds1pd2Lund);
  fChain->SetBranchAddress("Ds1pd2Idx",Ds1pd2Idx);
  fChain->SetBranchAddress("Ds1pVtxx",Ds1pVtxx);
  fChain->SetBranchAddress("Ds1pVtxy",Ds1pVtxy);
  fChain->SetBranchAddress("Ds1pVtxz",Ds1pVtxz);


  fChain->SetBranchAddress("nKs",&nKs);
  fChain->SetBranchAddress("KsMass",KsMass);
  fChain->SetBranchAddress("Ksp3CM",Ksp3CM);  
  fChain->SetBranchAddress("KsLund",KsLund);
  fChain->SetBranchAddress("Ksd1Lund",Ksd1Lund);
  fChain->SetBranchAddress("Ksd1Idx",Ksd1Idx);
  fChain->SetBranchAddress("Ksd2Lund",Ksd2Lund);
  fChain->SetBranchAddress("Ksd2Idx",Ksd2Idx);
  fChain->SetBranchAddress("KsChi2",KsChi2);
  fChain->SetBranchAddress("KsnDof",KsnDof);
  fChain->SetBranchAddress("KsMCIdx",KsMCIdx);
  fChain->SetBranchAddress("KsVtxx",KsVtxx);
  fChain->SetBranchAddress("KsVtxy",KsVtxy);
  fChain->SetBranchAddress("KsVtxz",KsVtxz);
  fChain->SetBranchAddress("Kscosth",Kscosth);
  fChain->SetBranchAddress("Ksphi",Ksphi);


  fChain->SetBranchAddress("nDstar",&nDstar);
  fChain->SetBranchAddress("DstarMass",DstarMass);
  fChain->SetBranchAddress("DstarLund",DstarLund);
  fChain->SetBranchAddress("Dstard1Lund",Dstard1Lund);
  fChain->SetBranchAddress("Dstard1Idx",Dstard1Idx);
  fChain->SetBranchAddress("Dstard2Lund",Dstard2Lund);
  fChain->SetBranchAddress("Dstard2Idx",Dstard2Idx);

  fChain->SetBranchAddress("nD0",&nD0);
  fChain->SetBranchAddress("D0Mass",D0Mass);
  fChain->SetBranchAddress("D0p3CM",D0p3CM);  
  fChain->SetBranchAddress("D0Lund",D0Lund);
  fChain->SetBranchAddress("D0d1Lund",D0d1Lund);
  fChain->SetBranchAddress("D0d1Idx",D0d1Idx);
  fChain->SetBranchAddress("D0d2Lund",D0d2Lund);
  fChain->SetBranchAddress("D0d2Idx",D0d2Idx);
  fChain->SetBranchAddress("D0Chi2",D0Chi2);
  fChain->SetBranchAddress("D0nDof",D0nDof);

  fChain->SetBranchAddress("nPi",&nPi);
  fChain->SetBranchAddress("Pip3",Pip3);
  fChain->SetBranchAddress("PiLund",PiLund);
  fChain->SetBranchAddress("PiTrkIdx",PiTrkIdx);

  fChain->SetBranchAddress("nK",&nK);
  fChain->SetBranchAddress("Kp3",Kp3);
  fChain->SetBranchAddress("KLund",KLund);
  fChain->SetBranchAddress("KTrkIdx",KTrkIdx);

  fChain->SetBranchAddress("TRKnSvt",TRKnSvt);
  fChain->SetBranchAddress("TRKLund",TRKLund);
  fChain->SetBranchAddress("piSelectorsMap",PiSelectorsMap);

 
  if(Mode=="D0ToKPiPi0"){
    fChain->SetBranchAddress("D0d3Lund",D0d3Lund);
    fChain->SetBranchAddress("D0d3Idx",D0d3Idx);
    fChain->SetBranchAddress("nPi0",&nPi0);
    fChain->SetBranchAddress("Pi0Mass",Pi0Mass);
    fChain->SetBranchAddress("Pi0p3",Pi0p3);
    fChain->SetBranchAddress("Pi0Lund",Pi0Lund);
    fChain->SetBranchAddress("Pi0d1Lund",Pi0d1Lund);
    fChain->SetBranchAddress("Pi0d1Idx",Pi0d1Idx);
    fChain->SetBranchAddress("GammaLund",GammaLund);
    fChain->SetBranchAddress("GammaECal",GammaECal);
 
    if(TruthMatch){
      fChain->SetBranchAddress("Pi0MCIdx",Pi0MCIdx);    
      fChain->SetBranchAddress("GammaMCIdx", GammaMCIdx);
   
    }

  }
  if(Mode=="D0ToK3Pi"){
    fChain->SetBranchAddress("D0d3Lund",D0d3Lund);
    fChain->SetBranchAddress("D0d3Idx",D0d3Idx);
    fChain->SetBranchAddress("D0d4Lund",D0d4Lund);
    fChain->SetBranchAddress("D0d4Idx",D0d4Idx);
  }

  if(TruthMatch){
    fChain->SetBranchAddress("Ds1pMCIdx",Ds1pMCIdx);
    fChain->SetBranchAddress("DstarMCIdx",DstarMCIdx);
    fChain->SetBranchAddress("D0MCIdx",D0MCIdx);
    fChain->SetBranchAddress("KMCIdx",KMCIdx);
    fChain->SetBranchAddress("PiMCIdx",PiMCIdx);
    fChain->SetBranchAddress("mcLund",mcLund);
    fChain->SetBranchAddress("mcLen",&mcLen);
    fChain->SetBranchAddress("mcp3",mcp3);
    fChain->SetBranchAddress("mccosth",mccosth);
    fChain->SetBranchAddress("mcp3CM",mcp3CM);
    fChain->SetBranchAddress("mccosthCM",mccosthCM); 
  }
  
 
  //Histosgrams
  Float_t DstarMassWindow=.090;  
  Float_t D0MassWindow=.090;
  Float_t KsMassWindow=.030;
  Int_t NMassBins=62;
  Float_t Ds1pMassLo=2.470;  
  Float_t Ds1pMassHi=2.600;  
  Int_t NDs1pMassBins=70;


  //////Cuts
  ///Loose
  Float_t D0p3CMCut=0.;
  Float_t D0ProbabCut=0.;
  Float_t KsProbabCut=0.;
  Float_t KsCosineCut=0.;

  ///Define Signal Region
  Float_t Ds1pMassCutLo=0.;
  Float_t Ds1pMassCutHi=0.;
  Float_t Ds1pMassResolution=0.;
  //////////////
  

  if(Mode=="D0ToKPi"){
    //loose
    if(WhichCuts==1){       
      D0p3CMCut=2.4; 
      D0ProbabCut=5e-3; 
      KsProbabCut=5e-3; 
      KsCosineCut=0; 
    }
    Ds1pMassResolution=.009;
    Ds1pMassCutLo=Ds1pPDGMass-4*Ds1pMassResolution;
    Ds1pMassCutHi=Ds1pPDGMass+4*Ds1pMassResolution;

  }
  if(Mode=="D0ToKPiPi0"){
    //loose
    if(WhichCuts==1){       
      D0p3CMCut=2.2; 
      D0ProbabCut=5e-3; 
      KsProbabCut=5e-3; 
      KsCosineCut=0; 
    }
    Ds1pMassResolution=.013;
    Ds1pMassCutLo=Ds1pPDGMass-4*Ds1pMassResolution;
    Ds1pMassCutHi=Ds1pPDGMass+4*Ds1pMassResolution;

  }

  if(Mode=="D0ToK3Pi"){
    //loose
    if(WhichCuts==1){       
      D0p3CMCut=2.2; 
      D0ProbabCut=5e-3; 
      KsProbabCut=5e-3; 
      KsCosineCut=0; 
    }
    Ds1pMassResolution=.006;
    Ds1pMassCutLo=Ds1pPDGMass-4*Ds1pMassResolution;
    Ds1pMassCutHi=Ds1pPDGMass+4*Ds1pMassResolution;

  }
  

  //////////////  
  //BeamPlots  
  TH1F HBeamRadius;
  SetHistoXY(&HBeamRadius,"Beam R",100,0,.5,"R (cm)","Entries/50#mu m");
  
  TH1F HBeamZ;
  SetHistoXY(&HBeamZ,"Beam Z",100,-4.,4.,"Z (cm)","Entries/1mm");
   
  ////Kaon
  TH1F HKMomentum;
  SetHistoXY(&HKMomentum,"K Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");

  TH1F HKMomentumTruthMatched;
  SetHistoXY(&HKMomentumTruthMatched,"K Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");
  
  /////pion 
  TH1F HPiMomentum;
  SetHistoXY(&HPiMomentum," Pion Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");

  TH1F HPiMomentumTruthMatched;
  SetHistoXY(&HPiMomentumTruthMatched," Pion Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");

  ///////////Mode dependent histos
  ////////////Mode=="D0ToKPiPi0"
  ////Gamma
  TH1F HGammaEnergy;
  SetHistoXY(&HGammaEnergy,"Gamma Energy",30,0,1.2,"calor. energy (GeV/c^{2})","Entries/40MeV");

  TH1F HGammaEnergyTruthMatched;
  SetHistoXY(&HGammaEnergyTruthMatched,"Gamma Energy",30,0,1.2,"calor. energy (GeV/c^{2})","Entries/40MeV");
  
  ////Pi0 
  TH1F HPi0MassPreCuts;
  SetHistoXY(&HPi0MassPreCuts,"Pi0 Mass After Cuts ",120,.075,.195," mass (GeV/c^{2})","Entries/1MeV");

  TH1F HPi0Mass;
  SetHistoXY(&HPi0Mass,"Pi0 Mass After Cuts ",120,.075,.195," mass (GeV/c^{2})","Entries/1MeV");

  TH1F HPi0MassTruthMatched;
  SetHistoXY(&HPi0MassTruthMatched,"Pi0 Mass After Cuts ",120,.075,.195," mass (GeV/c^{2})","Entries/1MeV");
  
 
  /////D0 
  TH1F HD0p3CM;
  SetHistoXY(&HD0p3CM,"D0 CM Momentum ",80,0,8,"p* (GeV/c)","Entries/100MeV");

  TH1F HD0MassPreCuts;
  SetHistoXY(&HD0MassPreCuts,"D0 Mass Before Cuts",NMassBins,D0PDGMass-D0MassWindow-.001,D0PDGMass+D0MassWindow+.001,"D0 Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HD0Mass;
  SetHistoXY(&HD0Mass,"D0 Mass After Cuts ",NMassBins,D0PDGMass-D0MassWindow-.001,D0PDGMass+D0MassWindow+.001,"D0 Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HD0MassTruthMatched;
  SetHistoXY(&HD0MassTruthMatched,"D0 Mass After Cuts ",NMassBins,D0PDGMass-D0MassWindow-.001,D0PDGMass+D0MassWindow+.001,"D0 Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HD0Probab;
  SetHisto(&HD0Probab,"D0 Vtx Probab ",200,-8,0,"log(p(#chi^{2}))");


  //slow pion
  TH1F HSlowPiMomentum;
  SetHistoXY(&HSlowPiMomentum,"Slow Pion Momentum ",30,0,1.2,"p (GeV/c)","Entries/40MeV");

  TH1F HSlowPiMomentumTruthMatched;
  SetHistoXY(&HSlowPiMomentumTruthMatched,"Slow Pion Momentum ",30,0,1.2,"p (GeV/c)","Entries/40MeV");

  ////Dstar
  TH1F HDstarMassPreCuts;
  SetHistoXY(&HDstarMassPreCuts,"D* Mass Before Cuts",NMassBins,DstarPDGMass-DstarMassWindow-.001,DstarPDGMass+DstarMassWindow+.001,"D* Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDstarMassPreCuts.SetLineColor(1);

  TH1F HDstarMass;
  SetHistoXY(&HDstarMass,"D* Mass After Cuts",NMassBins,DstarPDGMass-DstarMassWindow-.001,DstarPDGMass+DstarMassWindow+.001,"D* Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDstarMass.SetLineColor(1);
  
  TH1F HDstarMassTruthMatched;
  SetHistoXY(&HDstarMassTruthMatched,"D* Mass After Cuts and Truth Matched",NMassBins,DstarPDGMass-DstarMassWindow-.001,DstarPDGMass+DstarMassWindow+.001,"D* Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDstarMassTruthMatched.SetLineColor(1);

  TH1F HMassDiff;
  SetHistoXY(&HMassDiff,"#Delta M After Cuts",300,.139,.160,"D* Cand. Mass - D0 Cand. Mass (GeV/c^{2})","Entries/.1MeV");  


  /////pion1 
  TH1F HPi1Momentum;
  SetHistoXY(&HPi1Momentum," Pion1 Momentum ",100,0,2,"p (GeV/c)","Entries/20MeV");

  TH1F HPi1MomentumTruthMatched;
  SetHistoXY(&HPi1MomentumTruthMatched," Pion1 Momentum ",100,0,2,"p (GeV/c)","Entries/20MeV");

  /////Ks 
  TH1F HKsp3CM;
  SetHistoXY(&HKsp3CM,"Ks CM Momentum ",80,0,8,"p* (GeV/c)","Entries/100MeV");

  TH1F HKsMassPreCuts;
  SetHistoXY(&HKsMassPreCuts,"Ks Mass Before Cuts",NMassBins,K0PDGMass-KsMassWindow-.001,K0PDGMass+KsMassWindow+.001,"Ks Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HKsMass;
  SetHistoXY(&HKsMass,"Ks Mass After Cuts ",NMassBins,K0PDGMass-KsMassWindow-.001,K0PDGMass+KsMassWindow+.001,"Ks Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HKsMassTruthMatched;
  SetHistoXY(&HKsMassTruthMatched,"Ks Mass After Cuts ",NMassBins,K0PDGMass-KsMassWindow-.001,K0PDGMass+KsMassWindow+.001,"Ks Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HKsCosine;
  SetHistoXY(&HKsCosine,"Ks Direction",100,-1.00001,1.00001,"cos(#theta)","Entries/.02");

  TH1F HKsProbab;
  SetHisto(&HKsProbab,"Ks Vtx Probab ",200,-8,0,"log(p(#chi^{2}))");

 
  ////Ds1p
  TH1F HDs1pMassPreCuts;
  SetHistoXY(&HDs1pMassPreCuts,"D'_{s1} Mass Before Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassPreCuts.SetLineColor(1);

  TH1F HDs1pMassPID;
  SetHistoXY(&HDs1pMassPID,"D'_{s1} Mass After Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassPID.SetLineColor(1);

  TH1F HDs1pMass;
  SetHistoXY(&HDs1pMass,"D'_{s1} Mass After Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMass.SetLineColor(1);
  
  TH1F HDs1pMassSignal;
  SetHistoXY(&HDs1pMassSignal,"D'_{s1} Mass After Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassSignal.SetLineColor(1);

  TH1F HDs1pMassTruthMatched;
  SetHistoXY(&HDs1pMassTruthMatched,"D'_{s1} Mass After Cuts and Truth Matched",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassTruthMatched.SetLineColor(1);

  
  Float_t Ds1pp3CMmax=8;
  Float_t Ds1pp3CMmin=0;
  Int_t Ds1pp3CMNbins=80;
  if(TruthMatch){
    Ds1pp3CMmax=5;
    Ds1pp3CMmin=0;
    Ds1pp3CMNbins=50;
  }
  
  TH1F HDs1pp3CMPreCuts;
  SetHistoXY(&HDs1pp3CMPreCuts,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");

  TH1F HDs1pp3CM;
  SetHistoXY(&HDs1pp3CM,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");

  TH1F HDs1pp3CMPIDCut;
  SetHistoXY(&HDs1pp3CMPIDCut,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCut.SetLineColor(2);

  TH1F HDs1pp3CMPIDCutD0PCut;
  SetHistoXY(&HDs1pp3CMPIDCutD0PCut,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCutD0PCut.SetLineColor(3);

  TH1F HDs1pp3CMPIDCutD0PCutDeltaMCut;
  SetHistoXY(&HDs1pp3CMPIDCutD0PCutDeltaMCut,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCutD0PCutDeltaMCut.SetLineColor(4);

  TH1F HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab;
  SetHistoXY(&HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab.SetLineColor(6);    


  TH1F HDs1pcosthCMPreCuts;
  SetHistoXY(&HDs1pcosthCMPreCuts,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");

  TH1F HDs1pcosthCM;
  SetHistoXY(&HDs1pcosthCM,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");

  TH1F HDs1pcosthCMPIDCut;
  SetHistoXY(&HDs1pcosthCMPIDCut,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCut.SetLineColor(2);

  TH1F HDs1pcosthCMPIDCutD0PCut;
  SetHistoXY(&HDs1pcosthCMPIDCutD0PCut,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCutD0PCut.SetLineColor(3);

  TH1F HDs1pcosthCMPIDCutD0PCutDeltaMCut;
  SetHistoXY(&HDs1pcosthCMPIDCutD0PCutDeltaMCut,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCutD0PCutDeltaMCut.SetLineColor(4);

  TH1F HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab;
  SetHistoXY(&HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab.SetLineColor(6);
    
  TH2F H2Ds1pCMPvsTheta;
  SetHisto2D(&H2Ds1pCMPvsTheta," #theta* vs  p* ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)",100,-1,1,"cos(#theta)*","entries/(.01x100MeV)");


  /////////MC 
  TH1F HMCDs1pMass;
  SetHistoXY(&HMCDs1pMass,"MC D's1 Mass",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HMCDs1pp3CM;
  SetHistoXY(&HMCDs1pp3CM,"MC D's1 Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");

  TH1F HMCDs1pcosthCM;
  SetHistoXY(&HMCDs1pcosthCM,"MC D's1 Angular Distribution ",100,-1,1,"cos(#theta)*","Entries/.02");
  
  TH2F H2MCDs1pCMPvsTheta;
  SetHisto2D(&H2MCDs1pCMPvsTheta,"MC  #theta* vs p* ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)",100,-1,1,"cos(#theta*)","entries/(.02x100MeV)");


  TH1F HMCNDs1p;
  SetHistoXY(&HMCNDs1p,"MC Number of D's1 Generated",10,-.5,10.5,"nDs1p/event","Counts");
 
  //check particle id 
  TH1F HLundCheck;SetHisto(&HLundCheck,"Lund Id Check",15,-.5,14.5,"ParticleLund - LundExp");

  ////////+++++++++Important
  // Dstard1=D0,Dstard2=Pi;D0d1=K;D0d2=Pi
  //Lunds:

    
  
  //Start the event loop;
  Int_t eventid=0;
  while(fChain->GetEntry(eventid,0)>0){   
    eventid++;
    if(eventid%5000==0)cout<<eventid<<" Events done."<<endl;    
           
    HBeamRadius.Fill(sqrt( beamSX*beamSX + beamSY*beamSY));
    HBeamZ.Fill(beamSZ);     
         
    if(nDs1p>400){cout<<"Too many cands at event"<<eventid<<endl;continue;}
    ///Loop over the reconstructed
    Ds1pIdx=-1;
    while( Ds1pIdx< nDs1p-1){
      Ds1pIdx++;

      ////For Monte Carlo decide to analyze matter or antimatter
      if(!(Ds1pLund[Ds1pIdx]==MatterOrAntiMatter*myDs1pLund || MatterOrAntiMatter==0))continue;

      //Check that Im using proper indexes
      if(Mode=="D0ToKPi"||Mode=="D0ToK3Pi"){
	KsIdx=Ds1pd2Idx[Ds1pIdx];  
	KsPi1Idx=Ksd1Idx[KsIdx];
	KsPi2Idx=Ksd2Idx[KsIdx];    
	DstarIdx=Ds1pd1Idx[Ds1pIdx];
	SlowPiIdx=Dstard2Idx[DstarIdx];
	D0Idx=Dstard1Idx[DstarIdx];
	PiIdx=D0d2Idx[D0Idx];
	KIdx=D0d1Idx[D0Idx];

	PitrkIdx=PiTrkIdx[PiIdx];
	SlowPitrkIdx=PiTrkIdx[SlowPiIdx];
	KsPi1trkIdx=PiTrkIdx[KsPi1Idx];
	KsPi2trkIdx=PiTrkIdx[KsPi2Idx];

	if(abs(Dstard1Lund[DstarIdx]-D0Lund[D0Idx])>0)HLundCheck.Fill(1);
	else if(abs(Dstard2Lund[DstarIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(2);
	else if(abs(D0d1Lund[D0Idx]-KLund[KIdx])>0)HLundCheck.Fill(3);
	else if(abs(D0d2Lund[D0Idx]-PiLund[PiIdx])>0)HLundCheck.Fill(4);
	else if(abs(TRKLund[SlowPitrkIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(5);
	else if(abs(TRKLund[PitrkIdx]-PiLund[PiIdx])>0)HLundCheck.Fill(6);
	else if(abs(Ds1pd1Lund[Ds1pIdx]-DstarLund[DstarIdx])>0)HLundCheck.Fill(7);
	else if(abs(Ds1pd2Lund[Ds1pIdx]-KsLund[KsIdx])>0)HLundCheck.Fill(8);
	else if(abs(TRKLund[KsPi1trkIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(9);
	else if(abs(TRKLund[KsPi2trkIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(10);
	else if(abs(Ksd1Lund[KsIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(11);
	else if(abs(Ksd2Lund[KsIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(12);	
	else HLundCheck.Fill(0);
      }      


      if(Mode=="D0ToKPiPi0"){
	KsIdx=Ds1pd2Idx[Ds1pIdx]; 
	KsPi1Idx=Ksd1Idx[KsIdx];
	KsPi2Idx=Ksd2Idx[KsIdx]; 
	DstarIdx=Ds1pd1Idx[Ds1pIdx];
   	SlowPiIdx=Dstard2Idx[DstarIdx];
	D0Idx=Dstard1Idx[DstarIdx];
	PiIdx=D0d2Idx[D0Idx];
	KIdx=D0d1Idx[D0Idx];
	Pi0Idx=D0d3Idx[D0Idx];
	GammaIdx=Pi0d1Idx[Pi0Idx];

	PitrkIdx=PiTrkIdx[PiIdx];
	SlowPitrkIdx=PiTrkIdx[SlowPiIdx];
	KsPi1trkIdx=PiTrkIdx[KsPi1Idx];
	KsPi2trkIdx=PiTrkIdx[KsPi2Idx];


	if(abs(Dstard1Lund[DstarIdx]-D0Lund[D0Idx])>0)HLundCheck.Fill(1);
	else if(abs(Dstard2Lund[DstarIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(2);
	else if(abs(D0d1Lund[D0Idx]-KLund[KIdx])>0)HLundCheck.Fill(3);
	else if(abs(D0d2Lund[D0Idx]-PiLund[PiIdx])>0)HLundCheck.Fill(4);
	else if(abs(TRKLund[SlowPitrkIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(5);
	else if(abs(TRKLund[PitrkIdx]-PiLund[PiIdx])>0)HLundCheck.Fill(6);
	else if(abs(Ds1pd1Lund[Ds1pIdx]-DstarLund[DstarIdx])>0)HLundCheck.Fill(7);
	else if(abs(Ds1pd2Lund[Ds1pIdx]-KsLund[KsIdx])>0)HLundCheck.Fill(8);
	else if(abs(TRKLund[KsPi1trkIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(9);
	else if(abs(TRKLund[KsPi2trkIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(10);
	else if(abs(Ksd1Lund[KsIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(11);
	else if(abs(Ksd2Lund[KsIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(12);
	else if(abs(D0d3Lund[D0Idx]-Pi0Lund[Pi0Idx])>0)HLundCheck.Fill(13);
	else if(abs(Pi0d1Lund[Pi0Idx]-GammaLund[GammaIdx])>0)HLundCheck.Fill(14);	
	else HLundCheck.Fill(0);

      }


      ///compute some quantities
      D0Probab=TMath::Prob(D0Chi2[D0Idx],D0nDof[D0Idx]);     
      KsProbab=TMath::Prob(KsChi2[D0Idx],KsnDof[D0Idx]);     
         
      Ksp3Direction.SetXYZ(sin(acos(Kscosth[KsIdx]))*cos(Ksphi[KIdx]),
			   sin(acos(Kscosth[KsIdx]))*sin(Ksphi[KIdx]),
			   Kscosth[KsIdx]); 
      KsFlightDirection.SetXYZ(KsVtxx[KsIdx]-Ds1pVtxx[Ds1pIdx],
			       KsVtxy[KsIdx]-Ds1pVtxy[Ds1pIdx],
			       KsVtxz[KsIdx]-Ds1pVtxz[Ds1pIdx]);
      KsCosine=Ksp3Direction*KsFlightDirection/KsFlightDirection.Mag();

      ///Fill Distributions  
      if(Mode=="D0ToKPiPi0"){        
	HPi0MassPreCuts.Fill(Pi0Mass[Pi0Idx]);  
      }

      HD0p3CM.Fill(D0p3CM[D0Idx]);
      HD0MassPreCuts.Fill(D0Mass[D0Idx]);
      HD0Probab.Fill(log(D0Probab));

      HDstarMassPreCuts.Fill(DstarMass[DstarIdx]);   

      HKsMassPreCuts.Fill(KsMass[KsIdx]);
      HKsProbab.Fill(log(KsProbab));
      HKsCosine.Fill(KsCosine);

      HDs1pMassPreCuts.Fill(Ds1pMass[Ds1pIdx]);  


      //Apply Cuts       
      //     if((PiSelectorsMap[KsPi1trkIdx] & (1<<4) ) != 0 && (PiSelectorsMap[KsPi2trkIdx] & (1<<4) ) != 0){
      //	HDs1pMassPID.Fill(Ds1pMass[Ds1pIdx]);

      if(D0p3CM[D0Idx] > D0p3CMCut){
	if(D0Probab > D0ProbabCut){
	  if(KsProbab > KsProbabCut && KsCosine>KsCosineCut){

	    HDs1pMass.Fill(Ds1pMass[Ds1pIdx]);

	    ///Fill histograms only for the signal region of Ds1p
	    if(Ds1pMassCutLo<Ds1pMass[Ds1pIdx]&&Ds1pMass[Ds1pIdx]<Ds1pMassCutHi){

	      HDs1pMassSignal.Fill(Ds1pMass[Ds1pIdx]);
	      if(Ds1pMCIdx[Ds1pIdx]>0){
		HDs1pMassTruthMatched.Fill(Ds1pMass[Ds1pIdx]); 	
		HDs1pp3CM.Fill(Ds1pp3CM[Ds1pIdx]); 
		HDs1pcosthCM.Fill(Ds1pcosthCM[Ds1pIdx]); 		  
		H2Ds1pCMPvsTheta.Fill(Ds1pp3CM[Ds1pIdx],Ds1pcosthCM[Ds1pIdx]);	
	      }	  
	  
	      HKsMass.Fill(KsMass[KsIdx]);	   
	      if(KsMCIdx[KsIdx]>0){
		HKsMassTruthMatched.Fill(KsMass[KsIdx]); 		
	      }
	  
	      HPi1Momentum.Fill(Pip3[KsPi1Idx]);
	      if(PiMCIdx[KsPi1Idx]>0)
		HPi1MomentumTruthMatched.Fill(Pip3[KsPi1Idx]);	

	      HDstarMass.Fill(DstarMass[DstarIdx]); 		  
	      if(DstarMCIdx[DstarIdx]>0){
		HDstarMassTruthMatched.Fill(DstarMass[DstarIdx]); 		
	      }	  
	      HMassDiff.Fill(DstarMass[DstarIdx]-D0Mass[D0Idx]);   

	  
	      HD0Mass.Fill(D0Mass[D0Idx]); 
	      if(D0MCIdx[D0Idx]>0)
		HD0MassTruthMatched.Fill(D0Mass[D0Idx]); 

	      HSlowPiMomentum.Fill(Pip3[SlowPiIdx]);	
	      if(PiMCIdx[SlowPiIdx]>0)
		HSlowPiMomentumTruthMatched.Fill(Pip3[SlowPiIdx]);	    

	      HKMomentum.Fill(Kp3[KIdx]);
	      if(KMCIdx[KIdx]>0)
		HKMomentumTruthMatched.Fill(Kp3[KIdx]);

	      HPiMomentum.Fill(Pip3[PiIdx]);
	      if(PiMCIdx[PiIdx]>0)
		HPiMomentumTruthMatched.Fill(Pip3[PiIdx]);	

	      if(Mode=="D0ToKPiPi0"){ 
		HGammaEnergy.Fill(GammaECal[GammaIdx]);
		if(GammaMCIdx[GammaIdx]>0)
		  HGammaEnergyTruthMatched.Fill(GammaECal[GammaIdx]);

		HPi0Mass.Fill(Pi0Mass[Pi0Idx]);
		if(Pi0MCIdx[Pi0Idx]>0)
		  HPi0MassTruthMatched.Fill(Pi0Mass[Pi0Idx]);
	      }
	 

	      RecoDs1pCounterTotal++;
	    }//signal region
	  }//Ks Cuts
	}//D0Probab Cut     
      }//D0 p* cut  
      
    }//Ds1p loop
	 

    //now loop over MC    
    MCDs1pCounterPerEvent=0; 
    Int_t mcid=-1;
    while(mcid<mcLen){
      mcid++;

      if(mcLund[mcid]==MatterOrAntiMatter*myDs1pLund){
	MCDs1pCounterPerEvent++; 
	MCDs1pCounterTotal++;
		
	HMCDs1pMass.Fill(mcmass[mcid]);
	HMCDs1pp3CM.Fill(mcp3CM[mcid]); 
	HMCDs1pcosthCM.Fill(mccosthCM[mcid]); 	
	H2MCDs1pCMPvsTheta.Fill(mcp3CM[mcid],mccosthCM[mcid]);
      }
    }
    HMCNDs1p.Fill(MCDs1pCounterPerEvent);
        
  }

  //print summary
  cout<<"--------Summary-------"<<endl;
  cout<<"Total events="<<eventid<<endl;
  cout<<"Total Generated="<<MCDs1pCounterTotal<<" Reconstructed="<<RecoDs1pCounterTotal<<endl;
  cout<<"--------End Summary---"<<endl;

 
  ////Save histograms
  TString filename;
  filename=NtupleDir+"/"+"Plots.ps";
  TCanvas Canvas(filename,filename);
  Canvas.Print(filename+"[");

  TLine cutline;
  cutline.SetLineColor(2);

  //beam
  Canvas.Clear();
  HBeamRadius.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  HBeamZ.Draw();
  Canvas.Print(filename);    

  ///The Kaon 
  Canvas.Clear();
  HKMomentum.Draw();
  Canvas.Print(filename);
  TH1F* HKMomentumTruthDifference=(TH1F*)HKMomentum.Clone();
  HKMomentumTruthDifference->Add(&HKMomentumTruthMatched,-1.);
  HKMomentumTruthDifference->SetTitle("Truth Difference");
  HKMomentumTruthDifference->Draw();
  Canvas.Print(filename);

  //ThePion
  Canvas.Clear();
  HPiMomentum.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HPiMomentumTruthDifference=(TH1F*)HPiMomentum.Clone();
  HPiMomentumTruthDifference->Add(&HPiMomentumTruthMatched,-1.);
  HPiMomentumTruthDifference->SetTitle("Truth Difference");
  HPiMomentumTruthDifference->Draw();
  Canvas.Print(filename);

  
  if(Mode=="D0ToKPiPi0"){ 
    ///Gamma
    Canvas.Clear();
    HGammaEnergy.Draw();
    Canvas.Print(filename);
    Canvas.Clear();
    TH1F* HGammaEnergyTruthDifference=(TH1F*)HGammaEnergy.Clone();
    HGammaEnergyTruthDifference->Add(&HGammaEnergyTruthMatched,-1.);
    HGammaEnergyTruthDifference->SetTitle("Truth Difference");
    HGammaEnergyTruthDifference->Draw();
    Canvas.Print(filename);

    //The Pi0
    Canvas.Clear();
    HPi0MassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HPi0MassPreCuts.GetMaximum());
    HPi0MassPreCuts.Draw();
    HPi0Mass.Draw("same");
    Canvas.Print(filename);
    Canvas.Clear();
    TH1F* HPi0MassTruthDifference=(TH1F*)HPi0Mass.Clone();
    HPi0MassTruthDifference->Add(&HPi0MassTruthMatched,-1.);
    HPi0MassTruthDifference->SetTitle("Truth Difference");
    HPi0MassTruthDifference->Draw();
    Canvas.Print(filename);

  }

  //The D0 
  Canvas.Clear();
  HD0p3CM.Draw();
  cutline.DrawLine(D0p3CMCut,0,D0p3CMCut, HD0p3CM.GetMaximum());
  Canvas.Print(filename);
  Canvas.Clear();
  HD0MassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HD0MassPreCuts.GetMaximum());
  HD0MassPreCuts.Draw();
  HD0Mass.Draw("same");
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HD0MassTruthDifference=(TH1F*)HD0Mass.Clone();
  HD0MassTruthDifference->Add(&HD0MassTruthMatched,-1.);
  HD0MassTruthDifference->SetTitle("Truth Difference");
  HD0MassTruthDifference->Draw();
  Canvas.Print(filename);

  ///The Slow Pion
  Canvas.Clear();
  HSlowPiMomentum.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HSlowPiMomentumTruthDifference=(TH1F*)HSlowPiMomentum.Clone();
  HSlowPiMomentumTruthDifference->Add(&HSlowPiMomentumTruthMatched,-1.);
  HSlowPiMomentumTruthDifference->SetTitle("Truth Difference");
  HSlowPiMomentumTruthDifference->Draw();
  Canvas.Print(filename);


  ///The Dstar
  Canvas.Clear();
  HDstarMassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HDstarMassPreCuts.GetMaximum());
  HDstarMassPreCuts.Draw();
  HDstarMass.Draw("same");
  //HDstarMassTruthMatched.Draw("same");
  Canvas.Print(filename); 
  Canvas.Clear();
  TH1F* HDstarMassTruthDifference=(TH1F*)HDstarMass.Clone();
  HDstarMassTruthDifference->Add(&HDstarMassTruthMatched,-1.);
  HDstarMassTruthDifference->SetTitle("Truth Difference");
  HDstarMassTruthDifference->Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  HMassDiff.Draw();
  Canvas.Print(filename);


  //Pi1 and Pi2
  Canvas.Clear();
  HPi1Momentum.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HPi1MomentumTruthDifference=(TH1F*)HPi1Momentum.Clone();
  HPi1MomentumTruthDifference->Add(&HPi1MomentumTruthMatched,-1.);
  HPi1MomentumTruthDifference->SetTitle("Truth Difference");
  HPi1MomentumTruthDifference->Draw();
  Canvas.Print(filename);


  //Ks  
  Canvas.Clear();
  HKsProbab.Draw();
  Canvas.Print(filename); 
  Canvas.Clear();
  Canvas.SetLogy(1);
  HKsCosine.Draw();
  Canvas.Print(filename); 
  Canvas.SetLogy(0);
  Canvas.Clear();
  HKsMassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HKsMassPreCuts.GetMaximum());
  HKsMassPreCuts.Draw();
  HKsMass.Draw("same");  
  //HKsMassTruthMatched.Draw("same");
  Canvas.Print(filename); 
  Canvas.Clear();
  TH1F* HKsMassTruthDifference=(TH1F*)HKsMass.Clone();
  HKsMassTruthDifference->Add(&HKsMassTruthMatched,-1.);
  HKsMassTruthDifference->SetTitle("Truth Difference");
  HKsMassTruthDifference->Draw();
  Canvas.Print(filename);


  //Ds1p
  Canvas.Clear();
  HDs1pMassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HDs1pMassPreCuts.GetMaximum());
  HDs1pMassPreCuts.Draw();
  HDs1pMassPID.Draw("same");  
  HDs1pMass.Draw("same");
  cutline.DrawLine(Ds1pMassCutLo,0,Ds1pMassCutLo,HDs1pMass.GetMaximum());
  cutline.DrawLine(Ds1pMassCutHi,0,Ds1pMassCutHi,HDs1pMass.GetMaximum());  
  Canvas.Print(filename); 
  Canvas.Clear();
  Canvas.Divide(2,2);
  Canvas.cd(1);
  HDs1pMassSignal.Draw();
  HDs1pMassTruthMatched.Draw("same");
  Canvas.cd(2);
  TH1F* HDs1pMassTruthDifference=(TH1F*)HDs1pMassSignal.Clone();
  HDs1pMassTruthDifference->Add(&HDs1pMassTruthMatched,-1.);
  HDs1pMassTruthDifference->SetTitle("Truth Difference");
  HDs1pMassTruthDifference->Draw();
  Canvas.cd(3);
  TH1F* HDs1pMassTruthRatio=(TH1F*)HDs1pMassTruthMatched.Clone();
  HDs1pMassTruthRatio->Divide(&HDs1pMassSignal);
  HDs1pMassTruthRatio->SetTitle("Truth Ratio"); 
  HDs1pMassTruthRatio->GetYaxis()->SetTitle("TruthMatched/Reconstructed");
  HDs1pMassTruthRatio->Draw();
  Canvas.Print(filename);


  Canvas.Clear();
  if(TruthMatch){
    HMCDs1pp3CM.GetYaxis()->SetRangeUser(0,1.05*HMCDs1pp3CM.GetMaximum());
    HMCDs1pp3CM.Draw();  
    HDs1pp3CMPreCuts.Draw("same");
  }else {
    HDs1pp3CMPreCuts.GetYaxis()->SetRangeUser(1,1.05*HDs1pp3CMPreCuts.GetMaximum());
    HDs1pp3CMPreCuts.Draw();
  }       
  HDs1pp3CMPIDCut.Draw("same");
  HDs1pp3CMPIDCutD0PCut.Draw("same");
  HDs1pp3CMPIDCutD0PCutDeltaMCut.Draw("same");
  HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab.Draw("same");
  HDs1pp3CM.Draw("same");
  Canvas.Print(filename);

  //For bins were MC is less than 100 set efficiency to 0
  for(Int_t bin=0;bin<=HMCDs1pp3CM.GetNbinsX();bin++)
    if(HMCDs1pp3CM.GetBinContent(bin)<100)
      HMCDs1pp3CM.SetBinContent(bin,1e30);  

  Canvas.Clear();  
  TH1F HDs1pp3CMEfficiency0=*(TH1F*)HDs1pp3CMPreCuts.Clone();
  HDs1pp3CMEfficiency0.Divide(&HMCDs1pp3CM);
  HDs1pp3CMEfficiency0.SetTitle("CM Momentum Efficiency");
  HDs1pp3CMEfficiency0.GetYaxis()
    //->SetRangeUser(0,1.05*HDs1pp3CMEfficiency0.GetBinContent(HDs1pp3CMEfficiency0.GetMaximumBin()));
    ->SetRangeUser(0,1);
  HDs1pp3CMEfficiency0.Draw();
//   TH1F HDs1pp3CMEfficiency1=*(TH1F*)HDs1pp3CMPIDCut.Clone();
//   HDs1pp3CMEfficiency1.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency1.Draw("same");
//   TH1F HDs1pp3CMEfficiency2=*(TH1F*)HDs1pp3CMPIDCutD0PCut.Clone();
//   HDs1pp3CMEfficiency2.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency2.Draw("same");
//   TH1F HDs1pp3CMEfficiency3=*(TH1F*)HDs1pp3CMPIDCutD0PCutDeltaMCut.Clone();
//   HDs1pp3CMEfficiency3.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency3.Draw("same");
//   TH1F HDs1pp3CMEfficiency4=*(TH1F*)HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab.Clone();
//   HDs1pp3CMEfficiency4.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency4.Draw("same");  
  TH1F HDs1pp3CMEfficiencyFinal=*(TH1F*)HDs1pp3CM.Clone();
  HDs1pp3CMEfficiencyFinal.Divide(&HMCDs1pp3CM);  
  HDs1pp3CMEfficiencyFinal.Draw("same");
  Canvas.Print(filename);
  
  Canvas.Clear();
  if(TruthMatch){
    HMCDs1pcosthCM.GetYaxis()->SetRangeUser(0,1.05*HMCDs1pcosthCM.GetMaximum());
    HMCDs1pcosthCM.Draw();  
    HDs1pcosthCMPreCuts.Draw("same");
  }else {
    HDs1pcosthCMPreCuts.GetYaxis()->SetRangeUser(1,1.05*HDs1pcosthCMPreCuts.GetMaximum());
    HDs1pcosthCMPreCuts.Draw();
  }       
//   HDs1pcosthCMPIDCut.Draw("same");
//   HDs1pcosthCMPIDCutD0PCut.Draw("same");
//   HDs1pcosthCMPIDCutD0PCutDeltaMCut.Draw("same");
//   HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab.Draw("same");
  HDs1pcosthCM.Draw("same");
  Canvas.Print(filename);
  
  Canvas.Clear();  
  TH1F HDs1pcosthCMEfficiency0=*(TH1F*)HDs1pcosthCMPreCuts.Clone();
  HDs1pcosthCMEfficiency0.Divide(&HMCDs1pcosthCM);
  HDs1pcosthCMEfficiency0.SetTitle("Angular Efficiency");
  HDs1pcosthCMEfficiency0.GetYaxis()
    //->SetRangeUser(0,1.05*HDs1pcosthCMEfficiency0.GetBinContent(HDs1pcosthCMEfficiency0.GetMaximumBin()));
    ->SetRangeUser(0,1);
  HDs1pcosthCMEfficiency0.Draw();
//   TH1F HDs1pcosthCMEfficiency1=*(TH1F*)HDs1pcosthCMPIDCut.Clone();
//   HDs1pcosthCMEfficiency1.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency1.Draw("same");
//   TH1F HDs1pcosthCMEfficiency2=*(TH1F*)HDs1pcosthCMPIDCutD0PCut.Clone();
//   HDs1pcosthCMEfficiency2.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency2.Draw("same");
//   TH1F HDs1pcosthCMEfficiency3=*(TH1F*)HDs1pcosthCMPIDCutD0PCutDeltaMCut.Clone();
//   HDs1pcosthCMEfficiency3.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency3.Draw("same");
//   TH1F HDs1pcosthCMEfficiency4=*(TH1F*)HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab.Clone();
//   HDs1pcosthCMEfficiency4.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency4.Draw("same");  
  TH1F HDs1pcosthCMEfficiencyFinal=*(TH1F*)HDs1pcosthCM.Clone();
  HDs1pcosthCMEfficiencyFinal.Divide(&HMCDs1pcosthCM);  
  HDs1pcosthCMEfficiencyFinal.Draw("same");
  Canvas.Print(filename);

  Canvas.Clear();
  H2Ds1pCMPvsTheta.Draw("colz");
  Canvas.Print(filename);
  Canvas.Clear();
  H2MCDs1pCMPvsTheta.Draw("colz");
  Canvas.Print(filename);
  Canvas.Clear();
  //For bins were MC is less than 5 set efficiency to 0
  for(Int_t binx=0;binx<=H2MCDs1pCMPvsTheta.GetNbinsX();binx++)
    for(Int_t biny=0;biny<=H2MCDs1pCMPvsTheta.GetNbinsY();biny++)
      if(H2MCDs1pCMPvsTheta.GetBinContent(binx,biny)<20)
	H2MCDs1pCMPvsTheta.SetBinContent(binx,biny,1e30); 

  TH2F H2Ds1pPvsThetaEfficiency=*(TH2F*)H2Ds1pCMPvsTheta.Clone();
  H2Ds1pPvsThetaEfficiency.Divide(&H2MCDs1pCMPvsTheta);
  H2Ds1pPvsThetaEfficiency.SetTitle("D* Efficiency");
  H2Ds1pPvsThetaEfficiency.GetZaxis()->SetTitle("efficiency");
  H2Ds1pPvsThetaEfficiency.SetTitleOffset(.68,"Z");
  H2Ds1pPvsThetaEfficiency.SetStats(kFALSE);
  H2Ds1pPvsThetaEfficiency.Draw("colz");
  Canvas.Print(filename);





  ///Make plot of TruthMatched vs particle: 
  Float_t KTruthRatio=0;
  Float_t PiTruthRatio=0;
  Float_t GammaTruthRatio=0;
  Float_t Pi0TruthRatio=0;
  Float_t D0TruthRatio=0;
  Float_t SlowPiTruthRatio=0;
  Float_t DstarTruthRatio=0;
  Float_t Pi1TruthRatio=0;
  Float_t KsTruthRatio=0;
  Float_t Ds1pTruthRatio=0;

  if(HKMomentum.Integral()>0) KTruthRatio=HKMomentumTruthMatched.Integral()/HKMomentum.Integral();
  if(HPiMomentum.Integral()>0) PiTruthRatio=HPiMomentumTruthMatched.Integral()/HPiMomentum.Integral();
  if(HGammaEnergy.Integral()>0) GammaTruthRatio=HPiMomentumTruthMatched.Integral()/HPiMomentum.Integral();
  if(HPi0Mass.Integral()>0) Pi0TruthRatio=HPi0MassTruthMatched.Integral()/HPi0Mass.Integral();
  if(HD0Mass.Integral()>0) D0TruthRatio=HD0MassTruthMatched.Integral()/HD0Mass.Integral();
  if(HSlowPiMomentum.Integral()>0) SlowPiTruthRatio=HSlowPiMomentumTruthMatched.Integral()/HSlowPiMomentum.Integral();
  if(HDstarMass.Integral()>0) DstarTruthRatio=HDstarMassTruthMatched.Integral()/HDstarMass.Integral();
  if(HPi1Momentum.Integral()>0) Pi1TruthRatio=HPi1MomentumTruthMatched.Integral()/HPi1Momentum.Integral();
  if(HKsMass.Integral()>0) KsTruthRatio=HKsMassTruthMatched.Integral()/HKsMass.Integral();
  if(HDs1pMass.Integral()>0) Ds1pTruthRatio=HDs1pMassTruthMatched.Integral()/HDs1pMassSignal.Integral();
  

  TH1F HTruthRatioVsParticle;
  SetHistoXY(&HTruthRatioVsParticle,"Truth Match Ratios",10,.5,10.5,"Particle Type","TruthMatched/Reconstructed");
  HTruthRatioVsParticle.SetBinContent(1,KTruthRatio);
  HTruthRatioVsParticle.SetBinContent(2,PiTruthRatio);
  HTruthRatioVsParticle.SetBinContent(3,GammaTruthRatio);
  HTruthRatioVsParticle.SetBinContent(4,Pi0TruthRatio); 
  HTruthRatioVsParticle.SetBinContent(5,D0TruthRatio);
  HTruthRatioVsParticle.SetBinContent(6,SlowPiTruthRatio);
  HTruthRatioVsParticle.SetBinContent(7,DstarTruthRatio); 
  HTruthRatioVsParticle.SetBinContent(8,PiTruthRatio);   
  HTruthRatioVsParticle.SetBinContent(9,KsTruthRatio); 
  HTruthRatioVsParticle.SetBinContent(10,Ds1pTruthRatio); 
  HTruthRatioVsParticle.GetYaxis()->SetRangeUser(0,1);
  HTruthRatioVsParticle.SetStats(kFALSE);
  HTruthRatioVsParticle.SetBarWidth(.9);
  
  TText text;
  text.SetTextSize(.03);

  Canvas.Clear();
  HTruthRatioVsParticle.Draw("b");
  text.DrawText(1-.2,.1,"K");
  text.DrawText(2-.2,.1,"Pi");
  text.DrawText(3-.4,.1,"Gamma");
  text.DrawText(4-.2,.1,"Pi0");
  text.DrawText(5-.2,.1,"D0");
  text.DrawText(6-.4,.1,"SlowPi");
  text.DrawText(7-.2,.1,"D*");
  text.DrawText(8-.2,.1,"Pi1");
  text.DrawText(9-.2,.1,"Ks");
  text.DrawText(10-.2,.1,"Ds1");
  text.DrawText(1-.35,KTruthRatio*.9,TString("")+long(100*KTruthRatio)+"."+long(1000*KTruthRatio)%10+"%");
  text.DrawText(2-.35,PiTruthRatio*.9,TString("")+long(100*PiTruthRatio)+"."+long(1000*PiTruthRatio)%10+"%");
  text.DrawText(3-.35,GammaTruthRatio*.9,TString("")+long(100*GammaTruthRatio)+"."+long(1000*GammaTruthRatio)%10+"%");
  text.DrawText(4-.35,Pi0TruthRatio*.9,TString("")+long(100*Pi0TruthRatio)+"."+long(1000*Pi0TruthRatio)%10+"%");
  text.DrawText(5-.35,D0TruthRatio*.9,TString("")+long(100*D0TruthRatio)+"."+long(1000*D0TruthRatio)%10+"%");
  text.DrawText(6-.35,SlowPiTruthRatio*.9,TString("")+long(100*SlowPiTruthRatio)+"."+long(1000*SlowPiTruthRatio)%10+"%");
  text.DrawText(7-.35,DstarTruthRatio*.9,TString("")+long(100*DstarTruthRatio)+"."+long(1000*DstarTruthRatio)%10+"%");
  text.DrawText(8-.35,Pi1TruthRatio*.9,TString("")+long(100*Pi1TruthRatio)+"."+long(1000*Pi1TruthRatio)%10+"%");
  text.DrawText(9-.35,KsTruthRatio*.9,TString("")+long(100*KsTruthRatio)+"."+long(1000*KsTruthRatio)%10+"%");
  text.DrawText(10-.35,Ds1pTruthRatio*.9,TString("")+long(100*Ds1pTruthRatio)+"."+long(1000*Ds1pTruthRatio)%10+"%");
  Canvas.Print(filename);

  Canvas.Clear(); 
  HLundCheck.SetBarOffset(0);
  HLundCheck.SetBarWidth(.05);
  HLundCheck.Draw();
  Canvas.Print(filename);
   

  Canvas.Print(filename+"]");  
  return (TH1F*) HMassDiff.Clone(); 
}
Example #30
0
void Getvn2D(bool usingCNTEP=0){
    TString str;
    TFile *fin;
    int nrun = GetTotalRun();
    std::cout<<"Totally we have "<<nrun<<" runs/segments!"<<std::endl;
    FillGoodRun();
    std::cout<<"Filling Good run finished!"<<std::endl;

    if(nrun<0) exit(1);

     ofstream fout, foutraw, fout1, fout2;
     int iharE=0;
     if(nhar==1||nhar==2) iharE=1;
     for(int icent=0;icent<ncent;icent++){
      for(int ihar=0;ihar<nhar;ihar++){
          if(icent!=0) continue;
       for(int isub=0;isub<nsub;isub++){
        int n = ihar+1.0+iharE;
        str = choosesub(isub);
        TString UseCNTEP;
        if(str=="ABORT") continue;
        if(usingCNTEP)
         UseCNTEP = "UseCNTEP";
        else
         UseCNTEP = "NoUseCNTEP";
        std::cout<<UseCNTEP<<std::endl;
        std::cout<<"starting doing "<<str<<" v"<<n<<" analysis!"<<std::endl;
        cout<<Form("Result/%s/res%d_%d_%s.dat",UseCNTEP.Data(),n,icent,str.Data())<<endl;
         fout1.open(Form("Result/%s/res%d_%d_%s.dat",UseCNTEP.Data(),n,icent,str.Data())); //using str as event plane detector
         fout2.open(Form("Result/%s/psi%d_%d_%s.dat",UseCNTEP.Data(),n,icent,str.Data())); //using str as event plane detector
         float reso = GetReso(icent,ihar,isub,usingCNTEP);
         fout1<<reso<<std::endl;
         if(reso<0) {std::cout<<"resolution is wrong!"<<std::endl; reso = -9999;}
        for(int irun=0;irun<nrun;irun++){
         fout2<<GetRun(irun)<<" "<<GoodRunFit[icent][ihar][isub][irun]<<std::endl;
        }
         TH2F* hvobsall = new TH2F(Form("hvobs_%d_%d_%d",icent,ihar,isub),Form("hvobs_%d_%d_%d",icent,ihar,isub),60,0,6,220,-1.1,1.1);
        // TH2F* hvobsallsq = new TH2F(Form("hvobssq_%d_%d_%d",icent,ihar,isub),Form("hvobssq_%d_%d_%d",icent,ihar,isub),60,0,6,220,-1.1,1.1);
         
        for(int iphi=0;iphi<nphi+1;iphi++){
         TH2F* hvobs = new TH2F(Form("hvobs_%d_%d_%d_%d",icent,ihar,isub,iphi),Form("hvobs_%d_%d_%d_%d",icent,ihar,isub,iphi),60,0,6,220,-1.1,1.1);
        // TH2F* hvobssq = new TH2F(Form("hvobssq_%d_%d_%d_%d",icent,ihar,isub,iphi),Form("hvobssq_%d_%d_%d_%d",icent,ihar,isub,iphi),60,0,6,220,-1.1,1.1);
         string phistr = (iphi==0)?"_east":"_west";
         if(iphi==nphi) phistr = "";
         cout<<"open v2 file"<<endl;
         fout.open(Form("Result/%s/v%d_%d%s_%s.dat",UseCNTEP.Data(),n,icent,phistr.c_str(),str.Data())); //using str as event plane detector
         cout<<"open v2raw file"<<endl;
         foutraw.open(Form("Result/%s/v%draw_%d%s_%s.dat",UseCNTEP.Data(),n,icent,phistr.c_str(),str.Data())); //using str as event plane detector
         if(iphi<nphi){
        for(int irun=0;irun<nrun;irun++){
         //std::cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<irun<<" "<<phistr<<std::endl;
         //fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/%s%s/%d/data/%s.root",dataset.Data(),pro.Data(),taxi,GetRun(irun).Data()));
         //fin = TFile::Open(Form("/gpfs/mnt/gpfs02/phenix/plhf/plhf1/xuq/phenix/flow/Run16dAu/work/39GeV/output/%s",GetRun(irun).Data()));
         fin = TFile::Open(Form("/gpfs/mnt/gpfs02/phenix/plhf/plhf1/xuq/phenix/flow/Run16dAu/work/39GeV/treeout/%s",GetRun(irun).Data()));
         if(!(GoodRunFit[icent][ihar][isub][irun]>0.2 && GoodRunFit[icent][ihar][isub][irun]<3.0)){
         std::cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<GetRun(irun)<<" is bad run!"<<std::endl;
         fin->Close();
        continue;
         }
         TH2F* hvobstemp = (TH2F*)fin->Get(Form("vobs%s_0_0_%d_%d_%d",str.Data(),icent,ihar,iphi));
         //TH2F* hvobssqtemp = (TH2F*)fin->Get(Form("vobs%ssq_%d_%d_%d",str.Data(),icent,ihar,iphi));
         hvobs->Add(hvobstemp);
         //hvobssq->Add(hvobssqtemp);
         fin->Close();
        }
         }
        hvobsall->Add(hvobs);
        //hvobsallsq->Add(hvobssq);
        if(iphi==nphi){
        hvobs = hvobsall;
        //hvobssq = hvobsallsq;
        }
            TH1F* ptProj = (TH1F*)hvobs->ProjectionX(Form("hptProj"),0,-1);
         for(int ipt=0;ipt<npt-1;ipt++){
             int xbinmin = hvobs->GetXaxis()->FindBin(ptbin[ipt]+eps);
             int xbinmax = hvobs->GetXaxis()->FindBin(ptbin[ipt+1]-eps);
           //  std::cout<<xbinmin<<" "<<xbinmax<<std::endl;
           //  std::cout<<ptbin[ipt]<<" "<<ptbin[ipt+1]<<std::endl;
            TH1F* hvobsProj = (TH1F*)hvobs->ProjectionY(Form("hvobsProj_%d",ipt),xbinmin,xbinmax);
           // TH1F* hvobssqProj = (TH1F*)hvobssq->ProjectionY(Form("hvobssqProj_%d",ipt),xbinmin,xbinmax);
            float vobs = hvobsProj->GetMean();
            float Ntracks = hvobsProj->Integral();
           // float vobssq = hvobssqProj->GetMean();
            float v = vobs/reso;
            if(Ntracks>0)
            float verr = hvobsProj->GetRMS()/reso/sqrt(Ntracks);
            else verr = -9999;
           // float verr = sqrt(vobssq/reso/reso-(v*v))/sqrt(Ntracks);
            ptProj->GetXaxis()->SetRangeUser(ptbin[ipt]+eps,ptbin[ipt+1]-eps);
            float pt = ptProj->GetMean();
            fout<<pt<<" "<<v<<" "<<verr<<" "<<std::endl;
            foutraw<<pt<<" "<<vobs<<" "<<verr*reso<<" "<<std::endl;
         }
        fout.close();
        foutraw.close();
         }
        fout1.close();
        fout2.close();
        }
        }
     }
}