std::pair<float,float> getFitRange(TH1D& hist) {
  int maxBin = hist.GetMaximumBin();
  float targetVal = hist.GetBinContent( maxBin ) /2.;


  int nBins = hist.GetNbinsX();
  
  std::pair<float,float> results = {hist.GetBinLowEdge(1),hist.GetBinLowEdge(nBins+1)};

  int diff=0;
  while( maxBin-(++diff) >0) {
    if( hist.GetBinContent(maxBin-diff) < targetVal ){
      results.first = hist.GetBinCenter(maxBin-diff);
      break;
    }
  }

  diff=0;
  while( maxBin+(++diff) <=nBins) {
    if( hist.GetBinContent(maxBin+diff) < targetVal ){
      results.second = hist.GetBinCenter(maxBin+diff);
      break;
    }
  }
  
  
  return results;
}
Esempio n. 2
0
TH1D* GetFinalCorrFunc1D(int itrg, int jass)
{
                    TH1D* hbackground_phi = (TH1D*)GetRawBackground1D(itrg,jass);
		    TH1D* hcorrphi = (TH1D*)GetJetCorrFunc1D_ZYAM(itrg,jass);
                    hcorrphi->Multiply(hbackground_phi);
                    float max = hcorrphi->GetBinContent(hcorrphi->GetMaximumBin());
		    hcorrphi->SetAxisRange(ymin,max*1.5,"Y");
                    hcorrphi->SetYTitle("#frac{1}{N^{trg}}#frac{d^{2}N}{d#Delta#phi}");
                    return hcorrphi;
}
Esempio n. 3
0
TH1D* GetRawCorrFunc1D_ratio(int itrg, int jass)
{
                    TH1D* hsignalphi = GetRawSignal1D(itrg,jass);
                    TH1D* hcorrphi = (TH1D*)hsignalphi->Clone(Form("corrphi_trg%d_ass%d",itrg,jass));
		    hcorrphi->SetYTitle("C(#Delta#phi)");  
		    TH1D* hbackphi = GetRawBackground1D(itrg,jass);
		    hcorrphi->Divide(hbackphi); 
                    float max = hcorrphi->GetBinContent(hcorrphi->GetMaximumBin());
//		    hcorrphi->SetAxisRange(ymin,max*1.3,"Y");
                    return hcorrphi;
}
Esempio n. 4
0
void ReFit(int lo, int hi) {
	TF1* floo = (TF1*) gROOT->FindObject("floo");
	if (floo == 0) return;
	TH1D* hCe = (TH1D*) gROOT->FindObject("hCe");
	if (hCe == 0) return;
	hCe->GetXaxis()->SetRangeUser(lo,hi);
	double max = hCe->GetMaximum();
	int binmax = hCe->GetMaximumBin();
	double xmax = hCe->GetXaxis()->GetBinCenter(binmax);
	floo->SetParameters(max,xmax,10,max*0.1,50,20,5);
	hCe->Fit(floo,"Q","",lo,hi);
}
Esempio n. 5
0
TH1D *create1Dhisto(TTree *tree,TString intLumi,TString cuts,TString branch,int bins,float xmin,float xmax,bool useLog) {
  TH1::SetDefaultSumw2(kTRUE);
  
  //  TString cut ="(wgt*"+intLumi+")*("+cuts+")";
   TString cut ="("+intLumi+")*("+cuts+")";


  TH1D *hTemp = new TH1D("hTemp","hTemp",bins,xmin,xmax);
  tree->Project("hTemp",branch,cut);
  
  if (useLog) {
    hTemp->GetYaxis()->SetRangeUser(0.1,50.*(hTemp->GetBinContent(hTemp->GetMaximumBin())));
  } 
  else if (!useLog) {
    hTemp->GetYaxis()->SetRangeUser(0.,2.*(hTemp->GetBinContent(hTemp->GetMaximumBin())));
  }
  hTemp->SetLineWidth(3);
  hTemp->GetXaxis()->SetTitle(branch);
  
  return hTemp;
} //~ end of create1Dhisto
Esempio n. 6
0
void timeWindow( TFile *infile, double w0, double w1, double w2, double w3)
{
	// w0 -> w1 = time window around peak of time-expt
	// w2 -> w0 = window to left of w01
	// w1 -> w3 = window to right of w01

	// grab trees from infile
	TTree *dirc = infile->Get("dirc");
	TTree *reco = infile->Get("reco");

	// get lens, bar angle, and beam momentum
	int lens(0);
	double alpha(0),beam(0);
	dirc->SetBranchAddress("lens",&lens);
	dirc->SetBranchAddress("theta",&alpha);
	dirc->GetEntry(0);

	// define histograms of diff, outside diff, and counters
	TH1D *diff = new TH1D("diff","diff",1000,-50,50);
	TH1D *dout = new TH1D("dout","dout",1000,-50,50);
	TH1D *tof1 = new TH1D("time-tof1","time-tof1",1000,0,1000);
	TH1D *tof2 = new TH1D("time-tof2","time-tof2",1000,0,1000);
	TH1D *trig = new TH1D("time-trig","time-trig",1000,0,1000);

	// project to histograms
	reco->Project("diff","diff");
	reco->Project("dout","diff");
	reco->Project("time-tof1","time-tof1");
	reco->Project("time-tof2","time-tof2");
	reco->Project("time-trig","time-trig");

	// get diff value at peak and define initial cut
	double diffpeak = diff->GetMaximumBin();
	diffpeak = (diffpeak-500)/10;
	char *diffcut = Form("%f<diff-%f && diff-%f<%f",w0,diffpeak,diffpeak,w1);
	cout << "Initial cut\t" << diffcut << endl;
	
	
}
Esempio n. 7
0
//Fit a peak in an energy spectrum
void FitPeak(int run, int decay, int shaping, int top) {
	TH1D* hCe = (TH1D*) gROOT->FindObject("hCe");
	if (hCe != 0) delete hCe;
	hCe = new TH1D("hCe","hCe",3000,0,6000);

	trapf.SetPath("Files/Dec15/Fixed");
	if (!trapf.Open(run,decay,shaping,top)) return;
	for (int i = 0; i < trapf.GetNumEvents(); i++) {
		trapf.GetEvent(i);
		if (trapf.Trap_event.ch == 9 && trapf.Trap_event.AveE > 0) {
			hCe->Fill(trapf.Trap_event.AveE);
		}
	}
	gROOT->cd();
	hCe->GetXaxis()->SetRangeUser(abslo,abshi); //avoid low energy stuffs
	hCe->Draw();
	double max = hCe->GetMaximum();
	int binmax = hCe->GetMaximumBin();
	double xmax = hCe->GetXaxis()->GetBinCenter(binmax);
	TF1* floo = (TF1*) gROOT->FindObject("floo");
	if (floo != 0) delete floo;
	floo = new TF1("floo", floof, 0, 6000, 7);
	floo->SetParameters(max,xmax,10,max*0.1,50,20,5);
	floo->SetParLimits(0,0,2*max);
	floo->SetParLimits(3,0,2*max);
	floo->SetParLimits(4,0,500);
	floo->SetParName(2,"sigma");
	hCe->Fit(floo,"Q","",1000,xmax+60);
	double mean, fwhm;
	double lo, hi;
	GetFWHM(floo,mean,fwhm);
	lo = mean-8.5*fwhm; hi = mean+3*fwhm;
	if (lo < abslo) lo = abslo;
	ReFit(lo,hi);
	GetFWHM(floo,mean,fwhm);
	lo = mean-8.5*fwhm; hi = mean+3*fwhm;
	if (lo < abslo) lo = abslo;
	ReFit(lo,hi);
	GetFWHM(floo,mean,fwhm);
	lo = mean-8.5*fwhm; hi = mean+3*fwhm;
	if (lo < abslo) lo = abslo;
	ReFit(lo,hi);
	GetFWHM(floo,mean,fwhm);
	//draw parts
	TF1* part1 = (TF1*) gROOT->FindObject("part1");
	if (part1 != 0) delete part1;
	part1 = new TF1("part1", gaussian, 0, 6000, 3);
	for (int i=0;i<3;i++)
		part1->SetParameter(i,floo->GetParameter(i));
	part1->SetLineColor(kViolet);
	part1->Draw("same");
	TF1* part2 = (TF1*) gROOT->FindObject("part2");
	if (part2 != 0) delete part2;
	part2 = new TF1("part2", hypermet, 0, 6000, 4);
	part2->SetParameter(0,floo->GetParameter(3));
	part2->SetParameter(1,floo->GetParameter(1));
	part2->SetParameter(2,floo->GetParameter(2));
	part2->SetParameter(3,floo->GetParameter(4));
	part2->SetLineColor(kBlue);
	part2->Draw("same");
	TF1* part3 = (TF1*) gROOT->FindObject("part3");
	if (part3!= 0) delete part3;
	part3 = new TF1("part3", stepbkgd, 0, 6000, 4);
	part3->SetParameter(0,floo->GetParameter(5));
	part3->SetParameter(1,floo->GetParameter(6));
	part3->SetParameter(2,floo->GetParameter(1));
	part3->SetParameter(3,floo->GetParameter(2));
	part3->SetLineColor(kGreen);
	part3->Draw("same");
	fgt->SetLineColor(kBlack);
	fgt->Draw("same");
}
Esempio n. 8
0
// -----------------------------------------------------------------------------
//
TCanvas* createPlot( TString path, 
		     TString canvas_name, 
		     TString name, 
		     TString dirmame, 
		     int rebin, 
		     bool norm, 
		     bool log,
		     TDirectory* file )
{

  // SetSomeStyles();

  float lumi = 250.0;// 15.04;//10.9;//6.8;
 
  // Create legend
  TLegend* legend = new TLegend(0.75, 0.6, 0.99, 0.99, "", "brNDC" );
  legend->SetFillColor(0);
  legend->SetLineColor(0); 
  legend->SetShadowColor(0);
  TLatex* prelim = new TLatex(0.6,0.54,"#scale[0.8]{CMS preliminary 2010}");
  prelim->SetNDC();
  TLatex* alumi = new TLatex(0.6,.45,"#scale[0.8]{#int L dt = 35 pb^{-1}, #sqrt{s} = 7 TeV}");
  alumi->SetNDC();

  // Create canvas 
  TCanvas* aCanvas = createCanvas( canvas_name, file, log );

  // Create histogram
  TString aname("nAll");
  // TH1D* data1    = getHisto( path+"S14datacleaned/Edward_Data_Skim/",name,"data.root",aname,rebin);
  // TH1D* data    = getHisto( path+"S14datacleaned/Edward_Data_Skim/",name,"data.root",dirmame,rebin);
 
  TH1D* data    = getHisto( path+"", name, "tt.root", dirmame, rebin );
  TH1D* qcd     = getHisto( path+"", name, "lm1.root", dirmame, rebin );
  TH1D* w_jets  = getHisto( path+"", name, "w.root", dirmame, rebin );
  TH1D* tt_jets = getHisto( path+"", name, "tt.root", dirmame, rebin );
  TH1D* z_jets  = getHisto( path+"", name, "z.root", dirmame, rebin );
  TH1D* lm3     = getHisto( path+"", name, "lm3.root", dirmame, rebin );
  TH1D* lm1     = getHisto( path+"", name, "lm1.root", dirmame, rebin );
  TH1D* lm6     = getHisto( path+"", name, "data.root", dirmame, rebin );
  TH1D* wm     = getHisto( path+"", name, "w.root", dirmame, rebin );
  data->Scale(lumi/100.);
  qcd->Scale(lumi/100.);
  tt_jets->Scale(lumi/100);
  w_jets->Scale(lumi/100);
  //  w_jets->Scale(10);
  //  z_inv->Scale(lumi/100);
  //  lm6->Scale(lumi/100);
  lm1->Scale(lumi/100);
  lm3->Scale(lumi/100);
  z_jets->Scale(lumi/100);
  wm->Scale(lumi/100);
  // Combine Z+jets and Z->inv
  // TH1D* z_all = z_inv->Clone(); 
  //  z_all->Add(z_jets,1);
  //z_jets->Add(z_inv,1);
  TH1D* total = tt_jets->Clone();
  total->Add(w_jets);
  total->Add(z_jets);

  // total->
 
  Int_t binMax =   total->GetNbinsX();
  Double_t& err = new Double_t(0.);
  total->IntegralAndError(10,binMax ,err);
  Double_t& errW = new Double_t(0.);
  w_jets->IntegralAndError(10,binMax ,errW);
  Double_t& errtt = new Double_t(0.);
  tt_jets->IntegralAndError(10,binMax ,errtt);
  Double_t& errZ = new Double_t(0.);
  z_jets->IntegralAndError(10,binMax ,errZ);
  Double_t& errQCD = new Double_t(0.);
  qcd->IntegralAndError(10,binMax ,errQCD );


  cout  <<endl;
  //  cout << "MC:" <<  total->IntegralAndError(11,binMax ,err) <<" && " <<  w_jets->Integral(11,binMax)<<" && "<<tt_jets->Integral(11,binMax) << "&&  "<<z_jets->Integral(11,binMax)<<" && "<< "\/\ /\hline"<<endl;
  //  cout << total->IntegralAndError(0,binMax ,err) <<" & " << lm1->Integral(0,binMax) <<" & " << lm3->Integral(0,binMax)<<" & " << lm6->Integral(0,binMax)   <<"\\\\ \\hline"<<endl;
  //  cout <<"270: " <<  total->IntegralAndError(27,binMax ,err) <<" & " << lm1->Integral(27,binMax) <<" & " << lm3->Integral(27,binMax)<<" & " << lm6->Integral(27,binMax)   <<"\\\\ \\hline"<<endl;


  cout <<"250& " <<  total->IntegralAndError(6,binMax ,err) <<" & " << lm1->Integral(6,binMax) <<" & " << lm3->Integral(6,binMax)<<" & " << lm6->Integral(6,binMax)   <<"\\\\ \\hline"<<endl;
 
  // cout << "300: " <<  total->IntegralAndError(7,binMax ,err) <<" & " << lm1->Integral(7,binMax) <<" & " << lm3->Integral(7,binMax)<<" &" << lm6->Integral(7,binMax)   <<"\\\\ \\hline"<<endl;

  cout <<"350& " <<  total->IntegralAndError(8,binMax ,err) <<" & " << lm1->Integral(8,binMax) <<" & " << lm3->Integral(8,binMax)<<" & " << lm6->Integral(8,binMax)    <<"\\\\ \\hline"<<endl;

  //   cout << "400: " <<  total->IntegralAndError(9,binMax ,err) <<" & " << lm1->Integral(9,binMax) <<" & " << lm3->Integral(9,binMax)<<" & " << lm6->Integral(9,binMax)    <<"\\\\ \\hline"<<endl;

cout << "450& " <<  total->IntegralAndError(10,binMax ,err) <<" & " << lm1->Integral(10,binMax) <<" & " << lm3->Integral(10,binMax)<<" & " << lm6->Integral(10,binMax)    <<"\\\\ \\hline"<<endl;

//cout << "500: " <<   total->IntegralAndError(11,binMax ,err) <<" & " << lm1->Integral(11,binMax) <<" & " << lm3->Integral(11,binMax)<<" & " << lm6->Integral(11,binMax)    <<"\\\\ \\hline"<<endl;

  cout <<"550& " <<  total->IntegralAndError(12,binMax ,err) <<" & " << lm1->Integral(12,binMax) <<" & " << lm3->Integral(12,binMax)<<" & " << lm6->Integral(12,binMax)    <<"\\\\ \\hline"<<endl;
  /*
 cout << "MC:" <<  total->IntegralAndError(7,binMax ,err) <<" && " << lm1->Integral(7,binMax) <<" && " << lm3->Integral(7,binMax)<<" && " << lm6->Integral(6,binMax)   <<"/\/\ /\hline"<<endl;
  cout << "MC:" <<  total->IntegralAndError(8,binMax ,err) <<" && " << lm1->Integral(8,binMax) <<" && " << lm3->Integral(8,binMax)<<" && " << lm6->Integral(7,binMax)   <<"/\/\ /\hline"<<endl;
  cout << "MC:" <<  total->IntegralAndError(10,binMax ,err) <<" && " << lm1->Integral(10,binMax) <<" && " << lm3->Integral(10,binMax)<<" && " << lm6->Integral(10,binMax)   <<"/\/\ /\hline"<<endl;
 cout << "MC:" <<  total->IntegralAndError(11,binMax ,err) <<" && " << lm1->Integral(11,binMax) <<" && " << lm3->Integral(11,binMax)<<" && " << lm6->Integral(11,binMax)   <<"/\/\ /\hline"<<endl;
 cout << "MC:" <<  total->IntegralAndError(12,binMax ,err) <<" && " << lm1->Integral(12,binMax) <<" && " << lm3->Integral(12,binMax)<<" && " << lm6->Integral(12,binMax)   <<"/\/\ /\hline"<<endl;
  // cout << "MC:" << err  <<", W: " << errW<<", tt: "<<errtt << ", Z: "<<errZ<<", QCD: "<<  errQCD<< endl;
  */

  //  cout << "data:" << data->Integral() << endl;


  TH1D* hcen = total->Clone();
  TH1D* herr = total->Clone();
  
  herr->SetLineColor(kTeal+3);
  herr->SetMarkerColor(kAzure+6);
  herr->SetFillColor(kAzure+6);
  herr->SetLineWidth(3);
  
  total->SetLineWidth(3);
  total->SetFillColor(kAzure+2);
  total->SetLineColor(kAzure+2);
  total->SetFillStyle(3245);
 
  hcen->SetFillStyle(0);
  hcen->SetMarkerColor(kTeal+3);
  hcen->SetLineColor(kTeal+3);
  hcen->SetLineWidth(3);

  // Merge Z+jets and Z->inv
  bool combine = false;
  
  // Line colour and fill
  qcd->SetLineColor(kPink+4);
  qcd->SetLineWidth(3);
  tt_jets->SetLineColor(kBlue+1);
  tt_jets->SetLineWidth(3);
  
  w_jets->SetLineColor(kPink+7);
  w_jets->SetLineWidth(3);

  z_jets->SetLineWidth(3);
  z_jets->SetLineColor(kTeal-7);
  
  if ( combine ) {
    z_all->SetLineColor(kBlack);
    z_all->SetLineStyle(3);
    z_all->SetLineWidth(1);
  } else {
    data->SetLineColor(1);
    data->SetLineStyle(1);
    data->SetLineWidth(3);
    data->SetMarkerStyle(20);
    data->SetFillColor(0);
  }
  //  lm0->SetLineColor(kRed);
  //  lm0->SetLineWidth(3);
  // lm1->SetLineColor(kRed+3);
  // lm1->SetLineWidth(3);

  // Populate legend
  // legend->AddEntry( data, "tt fully leptonic/", "LP" );
   legend->AddEntry( herr, "full SM", "LP" );
    legend->AddEntry( z_jets, " Z+jets ", "LP" );
    legend->AddEntry( w_jets, " W+jets", "LP" );
    legend->AddEntry( tt_jets, " t#bar{t}", "LP" );
    //  legend->AddEntry( lm3, " SUSY LM3", "LP" );
    //   legend->AddEntry( lm1, " SUSY LM1", "LP" );
    legend->AddEntry( lm6, " data", "LP" );
    // legend->AddEntry(wm,"W Mad","lp");
    
  // Calc maximum number of entries
  double aMax = 0.;
  if( data->GetMaximum()     > aMax ) { aMax = data->GetMaximum()+data->GetBinError(data->GetMaximumBin()); }
  if ( qcd->GetMaximum()     > aMax ) { aMax = qcd->GetMaximum(); }
  //  if ( lm0->GetMaximum()     > aMax ) { aMax = lm0->GetMaximum(); }
  //  if ( lm1->GetMaximum()     > aMax ) { aMax = lm1->GetMaximum(); }
  if ( tt_jets->GetMaximum() > aMax ) { aMax = tt_jets->GetMaximum(); }  
  if ( w_jets->GetMaximum()  > aMax ) { aMax = w_jets->GetMaximum(); }  
  if ( combine ) {
    if ( z_all->GetMaximum()  > aMax ) { aMax = z_all->GetMaximum(); }  
  } else {
    //   if ( data->GetMaximum()   > aMax ) { aMax = z_inv->GetMaximum(); }  
    if ( z_jets->GetMaximum()  > aMax ) { aMax = z_jets->GetMaximum(); }  
  }

  // Calc minimum number of entries
  double aMin = 1.e12;
  if ( qcd->GetMinimum(1.e-12)     < aMin ) { aMin = qcd->GetMinimum(1.e-12); }
  //  if ( lm0->GetMinimum(1.e-12)     < aMin ) { aMin = lm0->GetMinimum(1.e-12); }
  //  if ( lm1->GetMinimum(1.e-12)     < aMin ) { aMin = lm1->GetMinimum(1.e-12); }
  if ( tt_jets->GetMinimum(1.e-12) < aMin ) { aMin = tt_jets->GetMinimum(1.e-12); }  
  if ( w_jets->GetMinimum(1.e-12)  < aMin ) { aMin = w_jets->GetMinimum(1.e-12); }  
  if ( combine ) {
    if ( z_all->GetMinimum(1.e-12)   < aMin ) { aMin = z_all->GetMinimum(1.e-12); }  
  } else {
    // if ( data->GetMinimum(1.e-12)   < aMin ) { aMin = z_inv->GetMinimum(1.e-12); }  
    if ( z_jets->GetMinimum(1.e-12)  < aMin ) { aMin = z_jets->GetMinimum(1.e-12); }  
  }

  if ( qcd ) qcd->GetYaxis()->SetTitleOffset(1.43);
  if ( qcd ) qcd->GetYaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleOffset(0.9);

 
  if ( log ) {
    if ( qcd ) herr->SetMaximum( aMax * 10. );
    //   if ( qcd ) herr->SetMinimum( aMin * 0.1 );
    if ( qcd ) herr->SetMinimum( 0.005);
  } else {
    if ( qcd ) herr->SetMaximum( aMax * 1.1 );
    //   if ( qcd ) herr->SetMinimum( aMin * 0.9 );
  if ( qcd ) herr->SetMinimum( 0.005);

  }

  /*  TPad* mainPad = new TPad("","",0.01,0.25,0.99,0.99);
  mainPad->SetNumber(1);
  mainPad->SetFillColor(0);
  // mainPad->Range(-288.2483,-2.138147,1344.235,6.918939);
  mainPad->SetFillColor(0);
  mainPad->SetBorderMode(0);
  mainPad->SetBorderSize(2);
  if ( log == true)mainPad->SetLogy();
   mainPad->SetLeftMargin(0.1765705);
  mainPad->SetRightMargin(0.05772496);
  mainPad->SetTopMargin(0.04778761);
  mainPad->SetBottomMargin(0.1256637);
  mainPad->SetFrameFillStyle(0);
  mainPad->SetFrameLineWidth(2);
  mainPad->SetFrameBorderMode(0);
  mainPad->SetFrameFillStyle(0);
  mainPad->SetFrameLineWidth(2);
  mainPad->SetFrameBorderMode(0);
  if ( log == true)mainPad->SetLogy();
  mainPad->Draw();
  TPad*  ratioPad = new TPad("","",0.01,0.01,0.99,0.25);
  ratioPad->SetNumber(2);
  ratioPad->SetFillColor(0);
  ratioPad->SetFillColor(0);
  ratioPad->SetBorderMode(0);
  ratioPad->SetBorderSize(2);
  // if ( log == true)ratioPad->SetLogy();
   ratioPad->SetLeftMargin(0.1765705);
  ratioPad->SetRightMargin(0.05772496);
  ratioPad->SetTopMargin(0.04778761);
  ratioPad->SetBottomMargin(0.1256637);
  ratioPad->SetFrameFillStyle(0);
  ratioPad->SetFrameLineWidth(2);
  ratioPad->SetFrameBorderMode(0);
  ratioPad->SetFrameFillStyle(0);
  ratioPad->SetFrameLineWidth(2);
  ratioPad->SetFrameBorderMode(0);
  //  if ( log == true)ratioPad->SetLogy();
  ratioPad->Draw();
 

  aCanvas->cd(1);
  */

  herr->GetYaxis()->SetTitle("events");


  if ( norm ) {
    if ( qcd ) qcd->DrawNormalized("Ehist");
    // if ( lm0->GetEntries() > 0. )     { lm0->DrawNormalized("hsame"); }
    if ( lm1->GetEntries() > 0. )     { lm1->DrawNormalized("hsame"); }
    if ( tt_jets->GetEntries() > 0. ) { tt_jets->DrawNormalized("hsame"); }
    if ( w_jets->GetEntries() > 0. )  { w_jets->DrawNormalized("hsame"); }
    if ( combine ) {
      if ( z_all->GetEntries() > 0. )   { z_all->DrawNormalized("hsame"); }
    } else {
      if ( data->GetEntries() > 0. )   { z_inv->DrawNormalized("hsame"); }
      if ( z_jets->GetEntries() > 0. )  { z_jets->DrawNormalized("hsame"); }
    }
  } else {
     herr->Draw("hist");
   
   
     // qcd->SetFillStyle(3240);
     // qcd->SetFillColor(kPink+4);
    // qcd->Draw("hist");
    w_jets->Draw("hSameh");
    z_jets->Draw("9Sameh");
    w_jets->Draw("9Sameh");
    tt_jets->Draw("9SAMEh");
    //data1->Draw("9SAMEh");
     //lm0->Draw("9SAMEh");
     lm1->SetLineColor(12);
     lm1->SetLineStyle(2);
     lm1->SetLineWidth(2);
     //     lm1->Draw("9SAMEh");
     lm3->SetLineColor(14);
     lm3->SetLineStyle(2);
     lm3->SetLineWidth(2);
     //  lm3->Draw("9SAMEh");
     lm6->Draw("9SAMEh");
     wm->SetLineStyle(2);
     wm->SetLineColor(kPink+7);
     // wm->Draw("9Sameh");

     // total->DrawNormalized("9E2same");
     //      data->Draw("SAMEh");
    //  tt_jets->Divide(data);
    //  tt_jets->Draw("h");
  //  data->SetLineColor(kRed);
  //  data->Draw("sameh");
     //     data1->SetLineColor(kRed);
     //  data1->Draw("9SAMEP");
  }
  
    legend->Draw();
  // prelim->Draw();
  // alumi->Draw();



  /*  TH1D* ratioBottom = total->Clone();
  TH1D* ratioTop = data->Clone();
  ratioTop->GetYaxis()->SetTitle("data / sim");
  ratioTop->Divide(ratioBottom);
  
  aCanvas->cd(1)->Update();
 
  aCanvas->cd(2);

  ratioTop->SetTitleSize(0.1, "XYZ");
  ratioTop->SetTitleOffset(0.55, "X");
  ratioTop->SetTitleOffset(0.3, "Y");
  ratioTop->SetLabelSize(0.06,"XY");
    
  // ratioTop->GetXaxis().SetRangeUser(MinX,MaxX);
  ratioTop->GetYaxis()->SetRangeUser(0.,2.0);
  ratioTop->Draw();*/
  /* TBox* unity = TBox(ratioTop->GetXaxis()->GetBinLowEdge(ratioTop->GetXaxis()->GetFirst()), 0.89,ratioTop->GetXaxis()->GetBinLowEdge(ratioTop->GetXaxis()->GetLast()), 1.11);
  unity->SetLineWidth(2);
   
  unity->SetLineColor(2);
  unity->SetFillColor(2);
  unity->SetFillStyle(3002);
  unity->Draw();

  */
  file->cd();
 
  aCanvas->SaveAs( std::string(canvas_name+".pdf").c_str() );
  aCanvas->Write();



  //   aCanvas->Print(".png");
 return aCanvas;

}
int CompareAllHistos(TString input1 = "../../QCD_ref.root", TString input2 = "../../QCD_filter.root", TString outdir="../plots/QCD/", TString leg1="no cut", TString leg2="jet filter", TString name="RelValQCD", bool MakeTotal=false) {
	
	gROOT->Reset();             
  //SetAtlasStyle();
  setTDRStyle();
  gStyle->SetPalette(1);
  gStyle->SetErrorX(0.5);
  gROOT->ProcessLine(".!mkdir -p "+outdir);
  gROOT->ProcessLine(".!mkdir -p "+outdir+"/pdf");
  gROOT->ProcessLine(".!mkdir -p "+outdir+"/png");

  
  TString Names[2] = { input1, input2};
  
//  TString outdir = "../plots/QCD/";
  const uint nFiles = 2;
  TFile * f[nFiles];  	

  
  std::stringstream indexes;
  for(uint iFile = 0; iFile < nFiles; iFile++)
  {
	indexes.str("");
  	indexes << Names[iFile];
  	
	std::string input_file=indexes.str();
	f[iFile] = TFile::Open(input_file.c_str());
	if(!f[iFile]) {
		std::cerr << "Error: file " << input_file << " could not be opened." << std::endl; 
    return 1;
	}
	else std::cout << "File " << input_file << " succesfully opened!" << std::endl;
  
  }
 // const uint nProfile12=8;
  const uint nProfile=4;
 // const uint nWP=3;
 // const uint n123=3;
  const uint n12=5;
  
  TString dirNames[1] = { "tauDifferenceAnalyzer"}; //"mmet_zh","mmmt_zh","mmme_zh","eett_zh","eemt_zh","eeet_zh","eeem_zh"};
 // TString profileNames_12[nProfile12] = {"pt_DM","eta_DM","vx_DM","phi_DM","pt_DMall","eta_DMall","vx_DMall","phi_DMall"};
  TString prefix_12 = "h_eff_id_";
  TString suffix_12[n12] = {"_DM","_DMall","_loose","_medium","_tight"};
  
  TString profileX[nProfile] = {"pt","eta","vx","phi"};
  const uint nTotal=nProfile*n12;
  //~ TString profile123_prefix="h_eff_id_";
  //~ TString profile123_WP[nWP]={"_loose","_medium","_tight"};
  //~ TString profile123_suffix[n123]={"","_2","_3"};
  //~ 
  TProfile* profileHist1[nTotal][nFiles];
// TProfile* profileHist2[nTotal][nFiles];
  
  //TProfile* profileHist[n123][nProfile*nWP][nFiles];
  //~ TProfile* profileHistB[nProfile*nWP][nFiles];
  //~ TProfile* profileHistC[nProfile*nWP][nFiles];
  //~ 
  
  
 // std::stringstream name;
 for(uint iFile = 0; iFile < nFiles; iFile++)
  {
	for(uint iSuff=0; iSuff < n12; iSuff++)
	{		
		for(uint iProf12=0; iProf12< nProfile; iProf12++)
		{
			profileHist1[iProf12+iSuff*nProfile][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+prefix_12+profileX[iProf12]+suffix_12[iSuff]));
		//	profileHist2[iProf12+iSuff*nProfile][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+prefix_12+profileX[iProf12]+suffix_12[iSuff]));
		}
	}
  }
  
  //~ for(uint iFile = 0; iFile < nFiles; iFile++)
  //~ {
	//~ for(uint iWP=0; iWP<nWP; iWP++)
		//~ {
			//~ for(uint iProf123=0; iProf123< nProfile; iProf123++)
			//~ {
				//~ for(uint i123=0; i123 < n123; i123++)
				//~ {
					//~ std::cout << dirNames[0]+"/"+profile123_prefix+profileX[iProf123]+profile123_WP[iWP]+profile123_suffix[i123] << std::endl;
					//~ profileHist[i123][iWP*nProfile+iProf123][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+profile123_prefix+profileX[iProf123]+profile123_WP[iWP]+profile123_suffix[i123]));
				//~ }
			//~ }
		//~ }
  //~ }
  
  
  
  
  TCanvas *c1 = new TCanvas("c1","",5,30,1024,1024);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);
  
  TPad* histPad = new TPad("histPad","histPad",0.01,0.25,0.99,0.99);
  histPad->SetBottomMargin(0.02);
  histPad->Draw();
  
  TPad* diffPad = new TPad("diffPad","diffPad",0.01,0.01,0.99,0.25);
  diffPad->SetBottomMargin(0.3);
  diffPad->SetTopMargin(0.0);
  diffPad->Draw();
  
  // plotting
  
	TString XTitle[4] = {"True P_{T} [GeV]","True #eta", "nVx","True #phi"};
   // c1->SetLogy();
	std::cout << "hej hola " << std::endl;
	for(uint iProf12=0; iProf12< nTotal; iProf12++)
	{
		 int title_id=iProf12%4;
		
		 if(title_id!=2){
			 profileHist1[iProf12][0]->Rebin(5);
			 profileHist1[iProf12][1]->Rebin(5);
		 }
	
		 TH1D* baseHist = (TH1D*)profileHist1[iProf12][0]->Clone();
		 TH1D* overHist = (TH1D*)profileHist1[iProf12][1]->Clone();
		 
		 if(MakeTotal && iProf12>7){ 
			 double binLow = baseHist->GetXaxis()->GetBinLowEdge(baseHist->GetXaxis()->GetFirst());
			 double binUp = baseHist->GetXaxis()->GetBinUpEdge(baseHist->GetXaxis()->GetLast());
			 int nBins = baseHist->GetXaxis()->GetNbins();
			 
			 TH1D* newBaseHist = new TH1D(TString(baseHist->GetName())+"TOT",baseHist->GetTitle(),nBins,binLow,binUp);
			 TH1D* newDMHist = new TH1D("newDMHist","",nBins,binLow,binUp);
			 TH1D* newOverHist = new TH1D(TString(overHist->GetName())+"TOTover",baseHist->GetTitle(),nBins,binLow,binUp);
			 TH1D* newDMHist2 = new TH1D("newDMHist2","",nBins,binLow,binUp);
			 
			 
			 for(int iBin=0; iBin <= baseHist->GetNbinsX(); iBin++)
			 {
				newBaseHist->SetBinContent(iBin,baseHist->GetBinContent(iBin));
				newBaseHist->SetBinError(iBin,baseHist->GetBinError(iBin));
				newDMHist->SetBinContent(iBin,profileHist1[title_id][0]->GetBinContent(iBin));
				newDMHist->SetBinError(iBin,profileHist1[title_id][0]->GetBinError(iBin));
				newOverHist->SetBinContent(iBin,overHist->GetBinContent(iBin));
				newOverHist->SetBinError(iBin,overHist->GetBinError(iBin));
				newDMHist2->SetBinContent(iBin,profileHist1[title_id][1]->GetBinContent(iBin));
				newDMHist2->SetBinError(iBin,profileHist1[title_id][1]->GetBinError(iBin));	
				
			 }
			 newBaseHist->Multiply(newDMHist);
			 newOverHist->Multiply(newDMHist2);
			 baseHist=newBaseHist;
			 overHist=newOverHist;
			 delete newDMHist;
			 delete newDMHist2;
		 }
	
		 if(title_id==0) baseHist->GetXaxis()->SetRangeUser(0,100);
		 baseHist->GetXaxis()->SetLabelOffset(0.1);		
		 baseHist->GetXaxis()->SetTitle(XTitle[title_id]);
		 baseHist->GetYaxis()->SetTitle("Fake rate");
		 baseHist->SetMarkerStyle(20);
		 baseHist->SetMarkerSize(2);
		 baseHist->SetLineWidth(2);
		 
		 overHist->SetMarkerColor(kRed);
		 overHist->SetMarkerStyle(25);
		 overHist->SetMarkerSize(2);
		 overHist->SetLineWidth(2);
		 overHist->SetLineStyle(2);
		 overHist->SetLineColor(kRed);
		
		 int binmax = baseHist->GetMaximumBin();
	     double max = 1.2*(baseHist->GetBinContent(binmax)+baseHist->GetBinError(binmax));
	     int binmax2 = overHist->GetMaximumBin();
	     double max2 = 1.2*(overHist->GetBinContent(binmax2)+overHist->GetBinError(binmax2));
	     max = max2 > max ? max2 : max;
	 
	     baseHist->SetMaximum(10.0);
	     baseHist->SetMinimum(1e-3);
	     
		 
		 histPad->cd();	
			 histPad->SetLogy();
		 baseHist->Draw();
		 overHist->Draw("same");	
		 
		TLegend* leg = new TLegend(0.8,0.80,0.9,0.9,NULL,"brNDC");
		leg->SetFillColor(0);
		leg->SetTextSize(0.035);
		leg->SetBorderSize(0);
		
		leg->AddEntry(baseHist, leg1, "lp");
		leg->AddEntry(overHist, leg2, "lp");
		
		leg->Draw();
		 //~ 
		 
    TString lumist="";
	TPaveText *ll = new TPaveText(0.15, 0.95, 0.95, 0.99, "NDC");
	ll->SetTextSize(0.03);
	ll->SetTextFont(62);
	ll->SetFillColor(0);
	ll->SetBorderSize(0);
	ll->SetMargin(0.01);
	ll->SetTextAlign(12); // align left
	TString text = name;
	ll->AddText(0.01,0.7,text);
	text = "#sqrt{s} = 13 TeV";
	text = text + lumist;
	//  ll->SetTextAlign(32); // align right
	ll->AddText(0.7, 0.5, text);
	ll->Draw("same");
	  
	
	c1->Update();
	
	TH1D* h_diff=(TH1D*)baseHist->Clone();
	h_diff->Divide(overHist);
	diffPad->cd();
	diffPad->SetGridy();
	diffPad->SetGridx();
	
	h_diff->GetYaxis()->SetLabelSize(0.1);
    h_diff->GetYaxis()->SetTitleOffset(0.55);
    h_diff->GetYaxis()->SetTitleSize(0.12);
    h_diff->GetYaxis()->SetTitle("Ratio");
    h_diff->GetXaxis()->SetLabelSize(0.12);
    h_diff->GetXaxis()->SetLabelOffset(0.01);
    h_diff->GetXaxis()->SetTitleSize(0.15);
	h_diff->GetYaxis()->SetNdivisions(509);
	h_diff->SetMinimum(0.9);
	h_diff->SetMaximum(1.1);
	
	h_diff->Draw("hist");
	c1->Print(outdir+"/pdf/"+profileHist1[iProf12][0]->GetName()+".pdf");
	c1->Print(outdir+"/png/"+profileHist1[iProf12][0]->GetName()+".png");
	
	
	}
  
  
	return 0;
}
Esempio n. 10
0
void allCutFlow(){
setTDRStyle();
gROOT->SetBatch();

//stuff to choose
bool logPlot = true; //true for log plot

TString Cut = "EventCount/";

TString Nbtags = "";
TString Obj = "";
TString RefSelection = "";
TString Type = "";
TString Next = "";
int RebinFact = 1;

TString Systematic = "central/";

//TString Variable = "TTbarMuMuRefSelection"; 
//TString Variable = "TTbarMuMuRefSelectionUnweighted";
//TString Variable = "TTbarEERefSelection";  
//TString Variable = "TTbarEERefSelectionUnweighted";
TString Variable = "TTbarEMuRefSelection"; 
//TString Variable = "TTbarEMuRefSelectionUnweighted";

 
TString Xtitle = "Cuts";

//if( Variable == "TTbarMuMuRefSelection" || Variable == "TTbarEERefSelection" )
//TString step[10] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "m(Z) veto", "#geq 1 jet", "#geq 2 jets", "#slash{E_{T}} cut", "#geq1 CSV b-tag", "#geq1 Good Photon" , "1 Good Photon"};
//TString step_latex[10] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "m(Z) veto", "$\\geq$ 1 jets", "$\\geq$ 2 jets", "$\\slash{E_{T}}$ cut", "$\\geq$ 1 CSV b-tag", "$\\geq$ 1 Good Photon" , "1 Good Photon"};
//if( Variable == "TTbarEMuRefSelection" )
TString step[8] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "#geq 1 jets", "#geq 2 jets", "#geq1 CSV b-tag", "#geq1 Good Photon", "1 Good Photon" };		
TString step_latex[8] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "$\\geq$ 1 jets", "$\\geq$ 2 jets", "$\\geq$ 1 CSV b-tag", "$\\geq$ 1 Good Photon" , "1 Good Photon"};


//Data
if( Variable == "TTbarMuMuRefSelection" || Variable == "TTbarMuMuRefSelectionUnweighted" )
TH1D* data = getSample("DoubleMu", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
if( Variable == "TTbarEERefSelection" || Variable == "TTbarEERefSelectionUnweighted" )
TH1D* data = getSample("DoubleElectron", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
if( Variable == "TTbarEMuRefSelection" || Variable == "TTbarEMuRefSelectionUnweighted" )
TH1D* data = getSample("MuEG", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//MC
TH1D* ttgamma = getSample("TTGamma", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* tt = getSample("TTJet", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* wjets = getSample("WJetsToLNu", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* DY1 = getSample("DYJetsToLL_M-10To50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* DY2 = getSample("DYJetsToLL_M-50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* T_tW = getSample("T_tW-channel", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* Tbar_tW = getSample("Tbar_tW-channel",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* ZZ = getSample("ZZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* WW = getSample("WWtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* WZ = getSample("WZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//QCD
TH1D* QCD_Pt_20_30_BCtoE = getSample("QCD_Pt_20_30_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_20_30_EMEnriched = getSample("QCD_Pt_20_30_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_20_MuEnrichedPt_15 = getSample("QCD_Pt_20_MuEnrichedPt_15",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_30_80_BCtoE = getSample("QCD_Pt_30_80_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_30_80_EMEnriched = getSample("QCD_Pt_30_80_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_80_170_BCtoE = getSample("QCD_Pt_80_170_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_80_170_EMEnriched = getSample("QCD_Pt_80_170_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

TH1D* QCD_all = getSample("QCD_Pt_20_MuEnrichedPt_15",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  QCD_all->Add(QCD_Pt_20_30_BCtoE);
  QCD_all->Add(QCD_Pt_20_30_EMEnriched);
  QCD_all->Add(QCD_Pt_30_80_BCtoE);
  QCD_all->Add(QCD_Pt_30_80_EMEnriched);
  QCD_all->Add(QCD_Pt_80_170_BCtoE);
  QCD_all->Add(QCD_Pt_80_170_EMEnriched);
  
TH1D* DY = getSample("DYJetsToLL_M-10To50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  DY->Add(DY2);
  
TH1D* Diboson = getSample("ZZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  Diboson->Add(WW);
  Diboson->Add(WZ);
  
TH1D* SingleTop = getSample("T_tW-channel", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  SingleTop->Add(Tbar_tW); 
 
cout << "got samples" << endl;

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

  hs->Add(QCD_all);
  hs->Add(wjets);
  hs->Add(WZ); 
  hs->Add(WW);
  hs->Add(ZZ);
  hs->Add(DY1);
  hs->Add(DY2);
  hs->Add(T_tW); 
  hs->Add(Tbar_tW);
  hs->Add(tt);
  hs->Add(ttgamma);
  

TH1D* allMC = (TH1D*)ttgamma->Clone("ratio");
  allMC->Add(tt);
  allMC->Add(wjets);
  allMC->Add(DY1);
  allMC->Add(DY2);
  allMC->Add(T_tW);
  allMC->Add(Tbar_tW);
  allMC->Add(ZZ);
  allMC->Add(WW);
  allMC->Add(WZ);
  allMC->Add(QCD_all);
  
TH1D* dataEff = new TH1D("data eff","data eff",9,0,9);
TH1D* mcEff = new TH1D("mc eff","mc eff",9,0,9);

mcEff->Sumw2();
dataEff->Sumw2();

for(int q =1; q<ttgamma->GetNbinsX(); q++){
mcEff->GetXaxis()->SetBinLabel(q, step[q]);
dataEff->SetBinContent(q, data->GetBinContent(q+1)/data->GetBinContent(q));
dataEff->SetBinError(q, dataEff->GetBinContent(q)*sqrt(pow(data->GetBinError(q+1)/data->GetBinContent(q+1),2)+pow(data->GetBinError(q)/data->GetBinContent(q),2)));
mcEff->SetBinContent(q, allMC->GetBinContent(q+1)/allMC->GetBinContent(q));

}  

	
	TCanvas *c2 = new TCanvas("cutflow eff","cutflow eff",600, 500);
  	
	mcEff->SetLineColor(kRed);
	mcEff->Draw();
	dataEff->Draw("Esame");
	
	TLegend *tleg3;
	tleg3 = new TLegend(0.7,0.7,0.8,0.9);
	tleg3->SetTextSize(0.04);
	tleg3->SetBorderSize(0);
	tleg3->SetFillColor(10);
	tleg3->AddEntry(dataEff , "data", "l");
	tleg3->AddEntry(mcEff , "mc", "l");
	
	tleg3->Draw("same");
	
	c2->SaveAs("plots/cutFlow/cutEff_"+Variable+".pdf");
	c2->SaveAs("plots/cutFlow/cutEff_"+Variable+".png");
	delete c2;

  //draw histos to files
  TCanvas *c1 = new TCanvas("cutflow","cutflow",900, 600);

  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);
  
  if(logPlot ==true)
  hs->SetMinimum(10.);

  hs->Draw("hist");
  
  for(int q =0; q<ttgamma->GetNbinsX(); q++)
  hs->GetXaxis()->SetBinLabel(q+1, step[q]);
  
  data->Draw("E same");
  data->SetMarkerStyle(20);
  
//  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(ttgamma , "t#bar{t}+gamma", "lf");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(T_tW, "single top", "lf");
	tleg2->AddEntry(DY1 , "Drell-Yan", "lf");
	tleg2->AddEntry(ZZ , "Di-boson", "lf");
	tleg2->AddEntry(wjets , "w+jets", "lf");
	tleg2->AddEntry(QCD_all , "QCD", "lf");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	TText* textstuff = dostuff(0.22,0.96, Variable);
	textstuff->Draw();
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("plots/cutFlow/");
  
  if(logPlot ==true){
    plotName += Variable+"_Log";
    plotName += Nbtags;
    
  }else{
    plotName += Variable+"";  
    plotName += Nbtags;
  }
 
 
  c1->SaveAs(plotName+".png");
  c1->SaveAs(plotName+".pdf");
  delete c1;
 
 //print out
 
    std::cout.setf(std::ios::fixed);
    std::cout.precision(0);

 cout << "& ttgamma & ttbar & single-t  & wjets & zjets & diboson & qcd & all MC & data  \\\\" << endl; 
 
 for(int q = 0; q < ttgamma->GetNbinsX(); q++){
 cout << step_latex[q] << " & " << ttgamma->GetBinContent(q+1) << " $\\pm$ " << ttgamma->GetBinError(q+1)  << " & " <<
 tt->GetBinContent(q+1) << " $\\pm$ " << tt->GetBinError(q+1)  << " & " << SingleTop->GetBinContent(q+1) << " $\\pm$ " <<
 SingleTop->GetBinError(q+1)  << " & " << DY->GetBinContent(q+1) << " $\\pm$ " << DY->GetBinError(q+1)  << " & " <<
 Diboson->GetBinContent(q+1) << " $\\pm$ " << Diboson->GetBinError(q+1)  << " & "<< wjets->GetBinContent(q+1) << " $\\pm$ "
 << wjets->GetBinError(q+1)  << " & " << QCD_all->GetBinContent(q+1) << " $\\pm$ " << QCD_all->GetBinError(q+1)  << " & " <<
 allMC->GetBinContent(q+1) << " $\\pm$ " << allMC->GetBinError(q+1)  << " & " << data->GetBinContent(q+1) << " $\\pm$ " <<
 data->GetBinError(q+1) << " \\\\ " << endl;
 
 }

// for(int r = 0; r < ttgamma->GetNbinsX(); r++){
// std::cout << ttgamma->GetBinContent(r+1) << std::endl;
// }
  	
}
Esempio n. 11
0
void doPlotsMuon(){
setTDRStyle();

//loop over variables
for(int i = 0; i<1; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("SingleMu", 1, Obj, Variable, Isolation, rebinFact, "central");

//MC
TH1D* tt = getSample("TTJet", lumi*225.2/6920475, Obj, Variable, Isolation, rebinFact, Systematic);

//ttbar individual
// TH1D* tt_semi = getSample("TTJet_SemiLept", lumi*225.2/6920475, Obj, Variable, Isolation, rebinFact, Systematic);
// TH1D* tt_lep = getSample("TTJet_FullLept", lumi*225.2/6920475, Obj, Variable, Isolation, rebinFact, Systematic);
// TH1D* tt_had = getSample("TTJet_Hadronic", lumi*225.2/6920475, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* wjets = getSample("W1Jet", lumi*37509/57708550, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w1jets = getSample("W1Jet", lumi*5400.0/23140779, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w2jets = getSample("W2Jets", lumi*1750.0/34041404, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w3jets = getSample("W3Jets", lumi*519.0/15536443, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w4jets = getSample("W4Jets", lumi*214.0/13370904, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* zjets = getSample("DY1JetsToLL", lumi*5745.25/30457954, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z1jets = getSample("DY1JetsToLL", lumi*561.0/24042904, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z2jets = getSample("DY2JetsToLL", lumi*181.0/21835749, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z3jets = getSample("DY3JetsToLL", lumi*51.1/11010628, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z4jets = getSample("DY4JetsToLL", lumi*23.04/6391785, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",     lumi*34679.3/8500505, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd1 = getSample("QCD_Pt-15to20_MuEnrichedPt5",   lumi*7.022e8 * 0.0039/1722678, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd2 = getSample("QCD_Pt-20to30_MuEnrichedPt5",   lumi*2.87e8 * 0.0065/8486893, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd3 = getSample("QCD_Pt-30to50_MuEnrichedPt5",   lumi*6.609e7 * 0.0122/8928999, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd4 = getSample("QCD_Pt-50to80_MuEnrichedPt5",   lumi*8082000.0 * 0.0218/7256011, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd5 = getSample("QCD_Pt-80to120_MuEnrichedPt5",  lumi*1024000.0 * 0.0395/9030624, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd6 = getSample("QCD_Pt-120to170_MuEnrichedPt5", lumi*157800.0 * 0.0473/8500505, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd7 = getSample("QCD_Pt-170to300_MuEnrichedPt5", lumi*34020.0 * 0.0676/7662483, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd8 = getSample("QCD_Pt-300to470_MuEnrichedPt5", lumi*1757.0 * 0.0864/7797481, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd9 = getSample("QCD_Pt-470to600_MuEnrichedPt5", lumi*115.2 * 0.1024/2995767, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd10 = getSample("QCD_Pt-800to1000_MuEnrichedPt5",lumi*3.57 * 0.1033/4047142, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd11 = getSample("QCD_Pt-1000_MuEnrichedPt5",     lumi*0.774 * 0.1097/3807263, Obj, Variable, Isolation, rebinFact, Systematic);


TH1D* top_t = getSample("T_t-channel", lumi*56.4/3757707, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* top_tw = getSample("T_tW-channel", lumi*11.1/497395, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* top_s = getSample("T_s-channel", lumi*3.79/249516, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_t = getSample("Tbar_t-channel", lumi*30.7/1934817, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_tw = getSample("Tbar_tW-channel", lumi*11.1/493239, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_s = getSample("Tbar_s-channel", lumi*1.76/139948, Obj, Variable, Isolation, rebinFact, Systematic);

//make combined top and single top template
TH1D* sing_top = (TH1D*)top_t->Clone("top");
sing_top->Add(top_tw);sing_top->Add(top_s); sing_top->Add(tbar_t); sing_top->Add(tbar_tw);sing_top->Add(tbar_s);

  if(inclQ == true){
  qcd->Add(qcd);
  }else{
  qcd1->Add(qcd2);
  qcd1->Add(qcd3);
  qcd1->Add(qcd4);
  qcd1->Add(qcd5);
  qcd1->Add(qcd6);
  qcd1->Add(qcd7);
  qcd1->Add(qcd8);
  qcd1->Add(qcd9);
  qcd1->Add(qcd10);
  qcd1->Add(qcd11);
  }
  
TH1D* qcd_data = getQCD(Obj, Variable, rebinFact);
qcd_data->Scale(qcd1->Integral());

THStack *hs = new THStack("hs","test");
  if(inclQ == true){
  hs->Add(qcd_data);
  }else{
  hs->Add(qcd_data);
  }
    
  zjets->Add(z2jets);
  zjets->Add(z3jets);
  zjets->Add(z4jets);  

  wjets->Add(w2jets);
  wjets->Add(w3jets);
  wjets->Add(w4jets);
  
  hs->Add(zjets);
  hs->Add(wjets);
      
  hs->Add(top_t);
  hs->Add(top_tw);
  hs->Add(top_s);
  hs->Add(tbar_t);
  hs->Add(tbar_tw);
  hs->Add(tbar_s);
  
  hs->Add(tt);
  
  TH1D* allMC = (TH1D*)tt->Clone("allMC");
  allMC->Add(sing_top); allMC->Add(wjets); allMC->Add(zjets); allMC->Add(qcd1);
  
  cout << "tt: " << tt->Integral()  << " wjets: " << wjets->Integral() << " zjets: " << zjets->Integral() << " single top: " << sing_top->Integral() << " qcd: " << qcd1->Integral() << " all: " << allMC->Integral() << " data: " << data->Integral() << endl;
  	
  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);

  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);

  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);
  
  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.6,0.6,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t} l+jets", "lf");
	//tleg2->AddEntry(tt_lep , "t#bar{t} di-lepton", "lf");
	tleg2->AddEntry(top_t, "single top", "lf");
	tleg2->AddEntry(wjets , "w+jets", "lf");
	tleg2->AddEntry(zjets , "z+jets", "lf");
	tleg2->AddEntry(qcd , "QCD", "lf");

	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	

	TText* textPrelim = doPrelim(0.12,0.96);
	textPrelim->Draw();

  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("plots/Control/Muon/");
  
  if(logPlot ==true){
    plotName += Variable+"Log";
    plotName += Nbtags+".pdf";
    
  }else{
    plotName += Variable;  
    plotName += Nbtags+".pdf";
  }
 
 
  c1->SaveAs(plotName);
  delete c1;
  
  }
  	
}
void DoTDeriMax1090Correction(TString SpectrumFileInput = "/lustre/miifs05/scratch/him-specf/hyp/steinen/COSYBeamtestAna/COSYnewMogon/June2014/COSYJune2014Dataset11_200,100,0,5339_SR1.root", TString FitFileInput = "/lustre/miifs05/scratch/him-specf/hyp/steinen/COSYBeamtestAna/COSYnewMogon/Fit/FitCOSYJune2014Dataset11_200,100,0,5339_SR1.root")
{
	TH2D *hSpectrumTDeriMax1090_EnergyChannel;
	TH2D *hSpectrumTDeriMax1090Rel_EnergyChannel;
	
	TH2D *hSpectrumT1090_EnergyChannelCorr1;
	TNtuple *DataNTuple;
	TFile *SpectrumInput = new TFile(SpectrumFileInput.Data());
	
	hSpectrumTDeriMax1090_EnergyChannel = (TH2D*) SpectrumInput->Get("Histograms/Energy_DeriMaxT90/Energy_DeriMaxT90_01");
	hSpectrumTDeriMax1090_EnergyChannel->SetDirectory(0);
	hSpectrumTDeriMax1090Rel_EnergyChannel = (TH2D*) SpectrumInput->Get("Histograms/Energy_DeriMaxT90Rel/Energy_DeriMaxT90Rel_01");
	hSpectrumTDeriMax1090Rel_EnergyChannel->SetDirectory(0);
	hSpectrumT1090_EnergyChannelCorr1 = (TH2D*) SpectrumInput->Get("Histograms/EnergyRt1090/EnergyRt1090CorrectionRt_01");
	hSpectrumT1090_EnergyChannelCorr1->SetDirectory(0);
	SpectrumInput->Close();
	//hSpectrumTDeriMax1090_EnergyChannel->Draw("colz");
	
	
	TFile *FitInput = new TFile(FitFileInput.Data(),"Update");
	DataNTuple = (TNtuple*)FitInput->Get("DataNTuple");
	DataNTuple->Scan();
	
	Int_t entries = (Int_t)DataNTuple->GetEntries();
	cout<<"Number of Entries: "<<entries<< endl;
	const int entriesArrayValue =entries;
	TF1 *FitFunc[entriesArrayValue];
	float Energy=0;
	float ChannelPeakPos=0;
	float ChannelRangeMin=0;
	float ChannelRangeMax=0;
	DataNTuple->SetBranchAddress("Energy",&Energy);
	DataNTuple->SetBranchAddress("ChannelPeakPos",&ChannelPeakPos);
	DataNTuple->SetBranchAddress("ChannelRangeMin",&ChannelRangeMin);
	DataNTuple->SetBranchAddress("ChannelRangeMax",&ChannelRangeMax);
	
	TCanvas* can=new TCanvas();
	gPad->SetLogz();
	hSpectrumTDeriMax1090_EnergyChannel->GetXaxis()->SetRangeUser(-30,250);
	hSpectrumTDeriMax1090Rel_EnergyChannel->GetXaxis()->SetRangeUser(-0.1,0.95);
	
	for (Int_t ki=0;ki<entries;ki++)
	{
		DataNTuple->GetEntry(ki);
		//if (int(Energy) == 1332)
		//if (int(Energy) == 510)
		//if (ki == entries-1)
		{
			cout << ChannelRangeMin << " " << ChannelRangeMax << endl;
			
			
			//first correction via TDeriMaxT90Rel
			hSpectrumTDeriMax1090_EnergyChannel->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
			hSpectrumTDeriMax1090Rel_EnergyChannel->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
			//TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+pol0(3)",ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParameters(1000,ChannelPeakPos-10,4,10);
			//FitFuncSlices->SetParLimits(1,ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParLimits(2,0,10);
			//FitFuncSlices->SetParLimits(3,0,100);
	
			//gDirectory->ls();
			
			TH1D *hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually=new TH1D("hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually","",hSpectrumTDeriMax1090Rel_EnergyChannel->GetNbinsX(),-0.3,1.3);
			//cout <<hSpectrumTDeriMax1090_EnergyChannel_MaxPos->GetEntries()<< endl;
			for(int binX = hSpectrumTDeriMax1090Rel_EnergyChannel->GetXaxis()->FindBin(-0.1);binX <= hSpectrumTDeriMax1090Rel_EnergyChannel->GetXaxis()->FindBin(0.90);binX++)
			{
				cout << "binx " << binX << endl;
				TH1D *hProfileY =hSpectrumTDeriMax1090Rel_EnergyChannel->ProjectionY("_py",binX,binX);	
				double MaxValue=hProfileY->GetBinCenter(hProfileY->GetMaximumBin());
				TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+[3]",MaxValue-20,MaxValue+20);
				TF1* FitFuncGausSlices = new TF1("FitFuncGausSlices","gaus(0)",MaxValue-20,MaxValue+20);
				FitFuncGausSlices->SetParameters(hProfileY->GetBinContent(hProfileY->GetMaximumBin()),MaxValue,4);
				
				hProfileY->Fit(FitFuncGausSlices,"RNQ");
				
				FitFuncSlices->SetParameters(FitFuncGausSlices->GetParameter(0),FitFuncGausSlices->GetParameter(1),FitFuncGausSlices->GetParameter(2),10);
				
				FitFuncSlices->SetParLimits(0,0,10000);
				FitFuncSlices->SetParLimits(1,MaxValue-10,MaxValue+10);
				FitFuncSlices->SetParLimits(2,0,10);
				FitFuncSlices->SetParLimits(3,0,100);
				hProfileY->Fit(FitFuncSlices,"RNQ");
				
				cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetParError(1) <<endl;
				hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->SetBinContent(binX, FitFuncSlices->GetParameter(1));
				hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->SetBinError(binX, FitFuncSlices->GetParError(1));
				
				
			}
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->GetYaxis()->SetRangeUser(ChannelPeakPos-100,ChannelPeakPos+50);
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->GetXaxis()->SetRangeUser(-0.05,0.9);
			TF1 * funcCorrConst = new TF1("funcCorrConst","pol0",-0.03,0.03);
			funcCorrConst->SetLineColor(kRed);
			TF1 * funcCorrPol = new TF1("funcCorrPol",PolPiecewise,-0.05,0.9,6);
			
			funcCorrPol->SetLineColor(kBlue);
			funcCorrPol->SetParameter(0,0.04);
			funcCorrPol->SetParameter(1,ChannelPeakPos);
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->Fit(funcCorrConst,"R");
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->Fit(funcCorrPol,"R+");
			TCanvas* can2=new TCanvas();
			gPad->SetLogz();
			
			hSpectrumTDeriMax1090Rel_EnergyChannel->Draw("colz");
			funcCorrPol->DrawCopy("same");
			for(int i = 7;i>0;i--)
				funcCorrPol->SetParameter(i,funcCorrPol->GetParameter(i)/funcCorrPol->GetParameter(1));
			funcCorrPol->Print();
			char buf[20];
			sprintf(buf, "funcCorrNorm_%d",ki);
			funcCorrPol->Write(buf,TObject::kOverwrite);
			
			funcCorrConst->Delete();
			funcCorrPol->Delete();
			
			
			//second correction via T1090 (after first)
			
			hSpectrumT1090_EnergyChannelCorr1->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
			
			//TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+pol0(3)",ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParameters(1000,ChannelPeakPos-10,4,10);
			//FitFuncSlices->SetParLimits(1,ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParLimits(2,0,10);
			//FitFuncSlices->SetParLimits(3,0,100);
	
			//gDirectory->ls();
			
			TH1D *hSpectrumT1090_EnergyChannelCorr1_MaxPosManually=new TH1D("hSpectrumT1090_EnergyChannelCorr1_MaxPosManually","",hSpectrumT1090_EnergyChannelCorr1->GetNbinsX(),0,1000);
			//cout <<hSpectrumTDeriMax1090_EnergyChannel_MaxPos->GetEntries()<< endl;
			for(int binX = hSpectrumT1090_EnergyChannelCorr1->GetXaxis()->FindBin(30);binX <= hSpectrumT1090_EnergyChannelCorr1->GetXaxis()->FindBin(500);binX++)
			{
				cout << "binx " << binX << endl;
				TH1D *hProfileY =hSpectrumT1090_EnergyChannelCorr1->ProjectionY("_py",binX,binX);
				//hProfileY->Draw();
				//return 0;
				double MaxValue=hProfileY->GetBinCenter(hProfileY->GetMaximumBin());
				FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+[3]",MaxValue-20,MaxValue+20);
				FitFuncGausSlices = new TF1("FitFuncGausSlices","gaus(0)",MaxValue-20,MaxValue+20);
				FitFuncGausSlices->SetParameters(hProfileY->GetBinContent(hProfileY->GetMaximumBin()),MaxValue,4);
				
				hProfileY->Fit(FitFuncGausSlices,"RNQ");
				
				FitFuncSlices->SetParameters(FitFuncGausSlices->GetParameter(0),FitFuncGausSlices->GetParameter(1),FitFuncGausSlices->GetParameter(2),10);
				
				FitFuncSlices->SetParLimits(0,0,10000);
				FitFuncSlices->SetParLimits(1,MaxValue-10,MaxValue+10);
				FitFuncSlices->SetParLimits(2,0,10);
				FitFuncSlices->SetParLimits(3,0,100);
				hProfileY->Fit(FitFuncSlices,"RNQ");
				
				cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetParError(1) <<endl;
				hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->SetBinContent(binX, FitFuncSlices->GetParameter(1));
				hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->SetBinError(binX, FitFuncSlices->GetParError(1));
				
			}
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->GetYaxis()->SetRangeUser(ChannelPeakPos-100,ChannelPeakPos+50);
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->GetXaxis()->SetRangeUser(30,500);
			new TCanvas();
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->Draw();
			
			TF1 * funcCorrConst = new TF1("funcCorrConst","pol0",50,350);
			funcCorrConst->SetLineColor(kRed);
			TF1 * funcCorrPol = new TF1("funcCorrPol","pol6",50,300);
			
			funcCorrPol->SetLineColor(kBlue);
			funcCorrPol->SetParameter(0,0.04);
			funcCorrPol->SetParameter(1,ChannelPeakPos);
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->Fit(funcCorrConst,"R");
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->Fit(funcCorrPol,"R+");
			
			TCanvas* can2=new TCanvas();
			gPad->SetLogz();
			
			hSpectrumT1090_EnergyChannelCorr1->Draw("colz");
			funcCorrPol->DrawCopy("same");
			for(int i = 7;i>=0;i--)
				funcCorrPol->SetParameter(i,funcCorrPol->GetParameter(i)/funcCorrConst->GetParameter(0));
			funcCorrPol->Print();
			char buf[20];
			sprintf(buf, "funcCorr2Norm_%d",ki);
			funcCorrPol->Write(buf,TObject::kOverwrite);
			
			funcCorrConst->Delete();
			funcCorrPol->Delete();
			//return 0;
			
		}
	}
	//can->ls();
	gDirectory->Delete("ncCorrPol;1");
	
	FitInput->ls();
	//TCanvas* can3=new TCanvas();
	//hSpectrumTDeriMax1090_EnergyChannel->ProfileX()->Draw();
	//hSpectrumTDeriMax1090Rel_EnergyChannel->ProfileX()->Draw();
	//hSpectrumTDeriMax1090Rel_EnergyChannel->Fit("pol3");
	FitInput->Close();
	
	
}
void doControlPlotsMET(){
setTDRStyle();
gROOT->SetBatch();
gStyle->SetErrorX(0.5);

//loop over variables
for(int i = 0; i<N; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];
int RebinFact = RebinFacts[i];

//Data
TH1D* data;
if(Obj == "MuMu/")
data = getSample("DoubleMu", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
if(Obj == "EE/")
data = getSample("DoubleElectron", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
if(Obj == "EMu/")
data = getSample("MuEG", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//MC
TH1D* ttgamma = getSample("TTGamma", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//this to get all ttbar

TH1D* tt;
TH1D* tt_lep;
TH1D* tt_sig;
if(inclTop == false){
//fake ttgamma
tt = getSample("TTJet", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut, "fake");
tt_lep = getSample("TTJet", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut, "lep");
tt_sig = getSample("TTJet", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut, "sig");
}else{
tt = getSample("TTJet", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
}

TH1D* wjets = getSample("WJetsToLNu", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* DY1 = getSample("DYJetsToLL_M-10To50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* DY2 = getSample("DYJetsToLL_M-50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* T_tW = getSample("T_tW-channel", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* Tbar_tW = getSample("Tbar_tW-channel",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* ZZ = getSample("ZZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* WW = getSample("WWtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* WZ = getSample("WZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//QCD
TH1D* QCD_Pt_20_30_BCtoE = getSample("QCD_Pt_20_30_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_20_30_EMEnriched = getSample("QCD_Pt_20_30_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
//TH1D* QCD_Pt_20_MuEnrichedPt_15 = getSample("QCD_Pt_20_MuEnrichedPt_15",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_30_80_BCtoE = getSample("QCD_Pt_30_80_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_30_80_EMEnriched = getSample("QCD_Pt_30_80_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_80_170_BCtoE = getSample("QCD_Pt_80_170_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_80_170_EMEnriched = getSample("QCD_Pt_80_170_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

TH1D* QCD_all = getSample("QCD_Pt_20_MuEnrichedPt_15",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  QCD_all->Add(QCD_Pt_20_30_BCtoE);
  QCD_all->Add(QCD_Pt_20_30_EMEnriched);
  QCD_all->Add(QCD_Pt_30_80_BCtoE);
  QCD_all->Add(QCD_Pt_30_80_EMEnriched);
  QCD_all->Add(QCD_Pt_80_170_BCtoE);
  QCD_all->Add(QCD_Pt_80_170_EMEnriched);
  

TH1D* allMC = (TH1D*)ttgamma->Clone("ratio");
  allMC->Add(tt);
  
  if(inclTop == false){
  allMC->Add(tt_lep);
  allMC->Add(tt_sig);
  }

  allMC->Add(wjets);
  allMC->Add(DY1);
  allMC->Add(DY2);
  allMC->Add(T_tW);
  allMC->Add(Tbar_tW);
  allMC->Add(ZZ);
  allMC->Add(WW);
  allMC->Add(WZ);
  allMC->Add(QCD_all);
  
  allMC->SetFillColor(kBlack);
  allMC->SetFillStyle(3354);
  allMC->SetMarkerSize(0.);
  allMC->SetStats(0);

THStack *hs = new THStack("hs","test");
  hs->Add(QCD_all);
  hs->Add(wjets);
  hs->Add(WZ); 
  hs->Add(WW);
  hs->Add(ZZ);
  hs->Add(DY1);
  hs->Add(DY2);
  hs->Add(T_tW); 
  hs->Add(Tbar_tW);
  hs->Add(tt); 

  if(inclTop == false){
  hs->Add(tt_lep);
  hs->Add(tt_sig);
  }

  hs->Add(ttgamma);
  

std::cout << "Total number of events" << std::endl;
std::cout << "Data: " << data->Integral() << std::endl;
std::cout << "ttbar + gamma: " << ttgamma->Integral() << std::endl;
std::cout << "Inclusive ttbar: " << tt->Integral() << std::endl;
std::cout << "W+Jets: " << wjets->Integral() << std::endl;
std::cout << "Drell-Yan1: " << DY1->Integral() << std::endl;
std::cout << "Drell-Yan2: " << DY2->Integral() << std::endl;
std::cout << "Single top: " << T_tW->Integral() << std::endl;
std::cout << "Anti-Single top: " << Tbar_tW->Integral() << std::endl;
std::cout << "ZZ: " << ZZ->Integral() << std::endl;
std::cout << "WW: " << WW->Integral() << std::endl;
std::cout << "WZ: " << WZ->Integral() << std::endl;
std::cout << "QCD: " << QCD_all->Integral() << std::endl;


  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
  TPad *pad1 = new TPad("pad1","pad1",0,0.3,1,1);
  pad1->SetBottomMargin(0);
  pad1->Draw();
  pad1->cd();	  

  data->Draw("e x0");
  data->SetAxisRange(MinX, MaxX, "X");

  hs->Draw("hist");
  allMC->Draw("same e2");
	
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);

  data->Draw("E same");
  data->SetMarkerStyle(20);
  
  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
   
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7, 0.6, 0.8, 0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(ttgamma , "t#bar{t}#gamma", "lf");

	if(inclTop == false){
        tleg2->AddEntry(tt_sig , "t#bar{t}#gamma (MG)", "lf");
        tleg2->AddEntry(tt_lep , "t#bar{t} l #rightarrow #gamma (MG)", "lf");
        tleg2->AddEntry(tt , "t#bar{t} fake (MG)", "lf");
        }else{
        tleg2->AddEntry(tt , "t#bar{t}", "lf");
        }
	tleg2->AddEntry(T_tW, "Single Top"      , "lf");
//	tleg2->AddEntry(Tbar_tW, "anti-single-tW"      , "lf");	
	tleg2->AddEntry(DY1 , "Z+Jets", "lf");
//	tleg2->AddEntry(DY2 , "DYJetsToLL", "lf");
	tleg2->AddEntry(ZZ, "Diboson", "lf");
//	tleg2->AddEntry(WW, "WW", "lf");
//	tleg2->AddEntry(WZ , "WZ", "lf");
	tleg2->AddEntry(wjets , "W+Jets", "lf");
	tleg2->AddEntry(QCD_all, "QCD", "lf");
	
 	tleg2->Draw("same");	

	TText* textPrelim = doPrelim(0.20, 0.96, Cut, Obj);
        textPrelim->Draw();

  c1->cd();

  if(logPlot == true){
     c1->SetLogy();
  }

   TPad *pad2 = new TPad("pad2","pad2",0,0,1,0.3);
   pad2->SetTopMargin(0);
   pad2->SetBottomMargin(0.4);
   pad2->Draw();
   pad2->cd();

   TH1D * ratio = (TH1D*)data->Clone("ratio plot");
   //ratio->Sumw2();
   ratio->SetStats(0);
   ratio->Divide(allMC);
   ratio->SetMinimum(0);
   ratio->SetMaximum(2);
   ratio->SetFillColor(kBlack);
   ratio->SetFillStyle(3354);
   ratio->SetMarkerSize(0.);

   cout << "width: " << ratio->GetBinWidth(1) << std::endl;
   
   if(MaxX <= 0.1){
   ratio->SetAxisRange(MinX, MaxX);
   }else{ 
   ratio->SetAxisRange(MinX, MaxX-ratio->GetBinWidth(1));
   }

   ratio->SetLabelSize(0.1, "X");
   ratio->SetTitleOffset(0.5, "Y");
   ratio->GetYaxis()->SetTitle("data/MC");ratio->GetYaxis()->SetTitleSize(0.1);
   ratio->GetXaxis()->SetTitle(Xtitle);ratio->GetXaxis()->SetTitleSize(0.15);
   ratio->Draw("ep");

   TLine *line;
   if(MaxX <= 0.1){
   line = new TLine(MinX,1,MaxX,1);
   }else{
   line = new TLine(MinX,1,MaxX-ratio->GetBinWidth(1),1);
   }
   
   line->Draw();

  TString plotName("plots/Control/"+ Obj + Cut  + Type + Next );
  
  if(logPlot == true){
    plotName += Variable+"ge1b_Log.pdf";   
  }else{
    plotName += Variable+"ge1b";  
  }
 
  c1->SaveAs(plotName+".pdf");
  c1->SaveAs(plotName+".png");
  
  delete c1;
  
  }
  	
}
Esempio n. 14
0
PostProcessQAV0(Bool_t lAttemptInvMassFit = kTRUE,
                Char_t *output            = "pdf"                          // "eps", "png" or "pdf"
               ){


  CustomGStyleSettings();  

  //==============================================================
  //Open Output File
  TFile* file = TFile::Open("AnalysisResults.root"), "READ");
  if (!file){
    cout<<"Output file not found!"<<endl;
    return;
  }
	file->cd("PWGLFQAV0_QA");
	TList* clist  = (TList*)file->FindObjectAny("clist");
  if (!clist){
    cout<<"File does not seem to hold QA list output!"<<endl;
    return;
  }  
  //==============================================================

  //==============================================================
  //Open Event Histogram: first canvas
  TH1D* fHistEvent = (TH1D*)clist->FindObject("fHistEvent");
  TCanvas *cHistEvent = new TCanvas("cHistEvent","",800,670); 
  cHistEvent->SetTopMargin(0.15);
  cHistEvent->SetGridx(); 
  cHistEvent->SetGridy();
  fHistEvent->Draw();

  fHistEvent->SetMarkerSize(1.35);
  fHistEvent->GetXaxis()->SetTitleOffset(1.2);
  fHistEvent->GetYaxis()->SetTitleOffset(1.2);
  fHistEvent->Draw("same text00");

  TLatex Tl;
  Tl.SetNDC();
  Tl.SetTextSize(0.05);
  Tl.DrawLatex(.35, .9277, "Event Counters")  ;  
  if      (output == "png") cHistEvent->SaveAs("LF_QAanalysis_V0_page1.png");  
  else if (output == "eps") cHistEvent->SaveAs("LF_QAanalysis_V0_page1.eps");
  else if (output == "pdf") cHistEvent->SaveAs("LF_QAanalysis_V0.pdf(");    

  //==============================================================

  //==============================================================
  //Invariant Mass Plots: Base, no dE/dx
  /*
  TH2D *f2dHistInvMassK0Short    = (TH2D*)clist->FindObject("f2dHistInvMassK0Short");
  TH2D *f2dHistInvMassLambda     = (TH2D*)clist->FindObject("f2dHistInvMassLambda");
  TH2D *f2dHistInvMassAntiLambda = (TH2D*)clist->FindObject("f2dHistInvMassAntiLambda");
    
  f2dHistInvMassK0Short     -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  f2dHistInvMassLambda      -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  f2dHistInvMassAntiLambda  -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );

  TCanvas *cInvMassK0Short = new TCanvas ( "cInvMassK0Short", "", 1200,800); 
  cInvMassK0Short->Divide(1,2); 
  cInvMassK0Short->cd(2)->Divide(3,1); 
  cInvMassK0Short->cd(1); 
  cInvMassK0Short->cd(1)->SetLogz();
  cInvMassK0Short->cd(1)->SetLeftMargin(0.065);
  cInvMassK0Short->cd(1)->SetTopMargin(0.13);
  cInvMassK0Short->cd(1)->SetBottomMargin(0.11);

  f2dHistInvMassK0Short->GetYaxis()->SetTitleSize(0.05);
  f2dHistInvMassK0Short->GetYaxis()->SetTitleOffset(0.6);
  f2dHistInvMassK0Short->GetXaxis()->SetTitleSize(0.05);
  f2dHistInvMassK0Short->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  f2dHistInvMassK0Short->GetZaxis()->SetTitle("Counts / Event");
  f2dHistInvMassK0Short->GetZaxis()->SetTitleOffset(0.7);
  f2dHistInvMassK0Short->GetZaxis()->SetRangeUser( f2dHistInvMassK0Short->GetMinimum(1e-10)*0.9, f2dHistInvMassK0Short->GetMaximum()*1.2 );
  f2dHistInvMassK0Short->Draw("colz");
  Tl.DrawLatex(.35, .9277, "Mass under K^{0}_{S} hypothesis, no TPC dE/dx")  ;   

  TH1D *fLowPtK0ShortSample = (TH1D*) f2dHistInvMassK0Short->ProjectionY( "fLowPtK0ShortSample", 
    f2dHistInvMassK0Short->GetXaxis()->FindBin(0.5001),
    f2dHistInvMassK0Short->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtK0ShortSample = (TH1D*) f2dHistInvMassK0Short->ProjectionY( "fMidPtK0ShortSample", 
    f2dHistInvMassK0Short->GetXaxis()->FindBin(1.5001),
    f2dHistInvMassK0Short->GetXaxis()->FindBin(2.4999) );

  TH1D *fHiPtK0ShortSample = (TH1D*) f2dHistInvMassK0Short->ProjectionY( "fHiPtK0ShortSample", 
    f2dHistInvMassK0Short->GetXaxis()->FindBin(5.0001),
    f2dHistInvMassK0Short->GetXaxis()->FindBin(9.9999) );

  for(Int_t ic = 1; ic<4; ic++){ 
    cInvMassK0Short->cd(2)->cd(ic)->SetTopMargin(0.14);
    cInvMassK0Short->cd(2)->cd(ic)->SetLeftMargin(0.15);
    cInvMassK0Short->cd(2)->cd(ic)->SetBottomMargin(0.11);
    cInvMassK0Short->cd(2)->cd(ic)->SetGridx(); 
    cInvMassK0Short->cd(2)->cd(ic)->SetGridy();
  }

  cInvMassK0Short->cd(2)->cd(1); 
  fLowPtK0ShortSample->GetXaxis()->SetTitleOffset(1.1);
  fLowPtK0ShortSample->GetYaxis()->SetTitleOffset(2.33);
  fLowPtK0ShortSample->GetYaxis()->SetTitle("Counts/Event");
  fLowPtK0ShortSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "0.5 < p_{T} (GeV/c^{2}) < 1.0");

  cInvMassK0Short->cd(2)->cd(2); 
  fMidPtK0ShortSample->GetXaxis()->SetTitleOffset(1.1);
  fMidPtK0ShortSample->GetYaxis()->SetTitleOffset(2.33);
  fMidPtK0ShortSample->GetYaxis()->SetTitle("Counts/Event");
  fMidPtK0ShortSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "1.5 < p_{T} (GeV/c^{2}) < 2.5");

  cInvMassK0Short->cd(2)->cd(3); 
  fHiPtK0ShortSample->GetXaxis()->SetTitleOffset(1.1);
  fHiPtK0ShortSample->GetYaxis()->SetTitleOffset(2.33);
  fHiPtK0ShortSample->GetYaxis()->SetTitle("Counts/Event");
  fHiPtK0ShortSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "5 < p_{T} (GeV/c^{2}) < 10");  
  if      (output == "png") cInvMassK0Short->SaveAs("LF_QAanalysis_V0_pageX.png");
  else if (output == "eps") cInvMassK0Short->SaveAs("LF_QAanalysis_V0_pageX.eps");
  else if (output == "pdf") cInvMassK0Short->SaveAs("LF_QAanalysis_V0.pdf");

  */
  //==============================================================

  //==============================================================
  //Invariant Mass Plots: WITH dE/dx
  TH2D *f2dHistInvMassWithdEdxK0Short    = (TH2D*)clist->FindObject("f2dHistInvMassWithdEdxK0Short");
  TH2D *f2dHistInvMassWithdEdxLambda     = (TH2D*)clist->FindObject("f2dHistInvMassWithdEdxLambda");
  TH2D *f2dHistInvMassWithdEdxAntiLambda = (TH2D*)clist->FindObject("f2dHistInvMassWithdEdxAntiLambda");
    
  f2dHistInvMassWithdEdxK0Short     -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  f2dHistInvMassWithdEdxLambda      -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  f2dHistInvMassWithdEdxAntiLambda  -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );

  TCanvas *cInvMassK0ShortWithdEdx = new TCanvas ( "cInvMassK0ShortWithdEdx", "", 1200,800); 
  cInvMassK0ShortWithdEdx->Divide(1,2); 
  cInvMassK0ShortWithdEdx->cd(2)->Divide(3,1); 
  cInvMassK0ShortWithdEdx->cd(1); 
  cInvMassK0ShortWithdEdx->cd(1)->SetLogz();
  cInvMassK0ShortWithdEdx->cd(1)->SetLeftMargin(0.065);
  cInvMassK0ShortWithdEdx->cd(1)->SetTopMargin(0.13);
  cInvMassK0ShortWithdEdx->cd(1)->SetBottomMargin(0.11);

  f2dHistInvMassWithdEdxK0Short->GetYaxis()->SetTitleSize(0.05);
  f2dHistInvMassWithdEdxK0Short->GetYaxis()->SetTitleOffset(0.6);
  f2dHistInvMassWithdEdxK0Short->GetXaxis()->SetTitleSize(0.05);
  f2dHistInvMassWithdEdxK0Short->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  f2dHistInvMassWithdEdxK0Short->GetZaxis()->SetTitle("Counts / Event");
  f2dHistInvMassWithdEdxK0Short->GetZaxis()->SetTitleOffset(0.7);
  f2dHistInvMassWithdEdxK0Short->GetZaxis()->SetRangeUser( f2dHistInvMassWithdEdxK0Short->GetMinimum(1e-10)*0.9, f2dHistInvMassWithdEdxK0Short->GetMaximum()*1.2 );
  f2dHistInvMassWithdEdxK0Short->Draw("colz");
  Tl.DrawLatex(.35, .9277, "Mass under K^{0}_{S} hypothesis, With TPC dE/dx")  ;   

  TH1D *fLowPtK0ShortSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxK0Short->ProjectionY( "fLowPtK0ShortSampleWithdEdx", 
    f2dHistInvMassWithdEdxK0Short->GetXaxis()->FindBin(0.5001),
    f2dHistInvMassWithdEdxK0Short->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtK0ShortSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxK0Short->ProjectionY( "fMidPtK0ShortSampleWithdEdx", 
    f2dHistInvMassWithdEdxK0Short->GetXaxis()->FindBin(1.5001),
    f2dHistInvMassWithdEdxK0Short->GetXaxis()->FindBin(2.4999) );

  TH1D *fHiPtK0ShortSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxK0Short->ProjectionY( "fHiPtK0ShortSampleWithdEdx", 
    f2dHistInvMassWithdEdxK0Short->GetXaxis()->FindBin(5.0001),
    f2dHistInvMassWithdEdxK0Short->GetXaxis()->FindBin(9.9999) );

  for(Int_t ic = 1; ic<4; ic++){ 
    cInvMassK0ShortWithdEdx->cd(2)->cd(ic)->SetTopMargin(0.14);
    cInvMassK0ShortWithdEdx->cd(2)->cd(ic)->SetLeftMargin(0.15);
    cInvMassK0ShortWithdEdx->cd(2)->cd(ic)->SetBottomMargin(0.11);
    cInvMassK0ShortWithdEdx->cd(2)->cd(ic)->SetGridx(); 
    cInvMassK0ShortWithdEdx->cd(2)->cd(ic)->SetGridy();
  }

  cInvMassK0ShortWithdEdx->cd(2)->cd(1); 
  fLowPtK0ShortSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fLowPtK0ShortSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fLowPtK0ShortSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fLowPtK0ShortSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "0.5 < p_{T} (GeV/c^{2}) < 1.0");

  cInvMassK0ShortWithdEdx->cd(2)->cd(2); 
  fMidPtK0ShortSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fMidPtK0ShortSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fMidPtK0ShortSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fMidPtK0ShortSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "1.5 < p_{T} (GeV/c^{2}) < 2.5");

  cInvMassK0ShortWithdEdx->cd(2)->cd(3); 
  fHiPtK0ShortSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fHiPtK0ShortSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fHiPtK0ShortSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fHiPtK0ShortSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "5 < p_{T} (GeV/c^{2}) < 10");  

  TLatex Tli;
  Tli.SetNDC();
  Tli.SetTextSize(0.05);  

  if( lAttemptInvMassFit ){ 
    //Attempt rough signal extraction   
    TF1 *f1 = new TF1("f1","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",0.435, 0.565);
    //Reasonable first guess
    f1->SetParameter(0, fLowPtK0ShortSampleWithdEdx -> GetBinContent( fLowPtK0ShortSampleWithdEdx->FindBin(0.497-0.01) ) );
    f1->SetParameter(1, 0 );
    f1->SetParameter(2, 0 );
    f1->SetParameter(3, 0.5*fLowPtK0ShortSampleWithdEdx->GetMaximum() ); 
    f1->SetParameter(4, 0.497);
    f1->SetParameter(5, 0.0045);
    cout<<"Will now fit, please wait!"<<endl;
    fLowPtK0ShortSampleWithdEdx->Fit("f1","REM0");
    cInvMassK0ShortWithdEdx->cd(2)->cd(1); 
    f1->Draw("same"); 
    //Peak Position, Width: printout 
    fLowPtK0ShortSampleWithdEdx->GetYaxis()->SetRangeUser(0,fLowPtK0ShortSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",f1->GetParameter(4),f1->GetParameter(5)) ) ;
    
    //Attempt rough signal extraction   
    TF1 *f2 = new TF1("f2","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",0.375, 0.635);
    //Reasonable first guess
    f2->SetParameter(0, fMidPtK0ShortSampleWithdEdx -> GetBinContent( fMidPtK0ShortSampleWithdEdx->FindBin(0.497-0.01) ) );
    f2->SetParameter(1, 0 );
    f2->SetParameter(2, 0 );
    f2->SetParameter(3, 0.5*fMidPtK0ShortSampleWithdEdx->GetMaximum() ); 
    f2->SetParameter(4, 0.497);
    f2->SetParameter(5, 0.0045);
    cout<<"Will now fit, please wait!"<<endl;
    fMidPtK0ShortSampleWithdEdx->Fit("f2","REM0");
    cInvMassK0ShortWithdEdx->cd(2)->cd(2); 
    f2->Draw("same"); 
    //Peak Position, Width: printout 
    fMidPtK0ShortSampleWithdEdx->GetYaxis()->SetRangeUser(0,fMidPtK0ShortSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",f2->GetParameter(4),f2->GetParameter(5)) ) ;

    //Attempt rough signal extraction   
    TF1 *f3 = new TF1("f3","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",0.375, 0.665);
    //Reasonable first guess
    f3->SetParameter(0, fHiPtK0ShortSampleWithdEdx -> GetBinContent( fHiPtK0ShortSampleWithdEdx->FindBin(0.497-0.01) ) );
    f3->SetParameter(1, 0 );
    f3->SetParameter(2, 0 );
    f3->SetParameter(3, 0.5*fHiPtK0ShortSampleWithdEdx->GetMaximum() ); 
    f3->SetParameter(4, 0.497);
    f3->SetParameter(5, 0.0045);
    cout<<"Will now fit, please wait!"<<endl;
    fHiPtK0ShortSampleWithdEdx->Fit("f3","REM0");
    cInvMassK0ShortWithdEdx->cd(2)->cd(3); 
    f3->Draw("same"); 
    //Peak Position, Width: printout 
    fHiPtK0ShortSampleWithdEdx->GetYaxis()->SetRangeUser(0,fHiPtK0ShortSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",f3->GetParameter(4),f3->GetParameter(5)) ) ;
  }

  if      (output == "png") cInvMassK0ShortWithdEdx->SaveAs("LF_QAanalysis_V0_page2.png");      
  else if (output == "eps") cInvMassK0ShortWithdEdx->SaveAs("LF_QAanalysis_V0_page2.eps");
  else if (output == "pdf") cInvMassK0ShortWithdEdx->SaveAs("LF_QAanalysis_V0.pdf"); 

  //==============================================================  


  //==============================================================
  //Invariant Mass Plots: Base, no dE/dx
  /*
  TCanvas *cInvMassLambda = new TCanvas ( "cInvMassLambda", "", 1200,800); 
  cInvMassLambda->Divide(1,2); 
  cInvMassLambda->cd(2)->Divide(3,1); 
  cInvMassLambda->cd(1); 
  cInvMassLambda->cd(1)->SetLogz();
  cInvMassLambda->cd(1)->SetLeftMargin(0.065);
  cInvMassLambda->cd(1)->SetTopMargin(0.13);
  cInvMassLambda->cd(1)->SetBottomMargin(0.11);

  f2dHistInvMassLambda->GetYaxis()->SetTitleSize(0.05);
  f2dHistInvMassLambda->GetYaxis()->SetTitleOffset(0.6);
  f2dHistInvMassLambda->GetXaxis()->SetTitleSize(0.05);
  f2dHistInvMassLambda->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  f2dHistInvMassLambda->GetZaxis()->SetTitle("Counts / Event");
  f2dHistInvMassLambda->GetZaxis()->SetTitleOffset(0.7);
  f2dHistInvMassLambda->GetZaxis()->SetRangeUser( f2dHistInvMassLambda->GetMinimum(1e-10)*0.9, f2dHistInvMassLambda->GetMaximum()*1.2 );
  f2dHistInvMassLambda->Draw("colz");
  Tl.DrawLatex(.35, .9277, "Mass under #Lambda hypothesis, no TPC dE/dx")  ;   

  TH1D *fLowPtLambdaSample = (TH1D*) f2dHistInvMassLambda->ProjectionY( "fLowPtLambdaSample", 
    f2dHistInvMassLambda->GetXaxis()->FindBin(0.5001),
    f2dHistInvMassLambda->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtLambdaSample = (TH1D*) f2dHistInvMassLambda->ProjectionY( "fMidPtLambdaSample", 
    f2dHistInvMassLambda->GetXaxis()->FindBin(1.5001),
    f2dHistInvMassLambda->GetXaxis()->FindBin(2.4999) );

  TH1D *fHiPtLambdaSample = (TH1D*) f2dHistInvMassLambda->ProjectionY( "fHiPtLambdaSample", 
    f2dHistInvMassLambda->GetXaxis()->FindBin(5.0001),
    f2dHistInvMassLambda->GetXaxis()->FindBin(9.9999) );

  for(Int_t ic = 1; ic<4; ic++){ 
    cInvMassLambda->cd(2)->cd(ic)->SetTopMargin(0.14);
    cInvMassLambda->cd(2)->cd(ic)->SetLeftMargin(0.15);
    cInvMassLambda->cd(2)->cd(ic)->SetBottomMargin(0.11);
    cInvMassLambda->cd(2)->cd(ic)->SetGridx(); 
    cInvMassLambda->cd(2)->cd(ic)->SetGridy();
  }

  cInvMassLambda->cd(2)->cd(1); 
  fLowPtLambdaSample->GetXaxis()->SetTitleOffset(1.1);
  fLowPtLambdaSample->GetYaxis()->SetTitleOffset(2.33);
  fLowPtLambdaSample->GetYaxis()->SetTitle("Counts/Event");
  fLowPtLambdaSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "0.5 < p_{T} (GeV/c^{2}) < 1.0");

  cInvMassLambda->cd(2)->cd(2); 
  fMidPtLambdaSample->GetXaxis()->SetTitleOffset(1.1);
  fMidPtLambdaSample->GetYaxis()->SetTitleOffset(2.33);
  fMidPtLambdaSample->GetYaxis()->SetTitle("Counts/Event");
  fMidPtLambdaSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "1.5 < p_{T} (GeV/c^{2}) < 2.5");

  cInvMassLambda->cd(2)->cd(3); 
  fHiPtLambdaSample->GetXaxis()->SetTitleOffset(1.1);
  fHiPtLambdaSample->GetYaxis()->SetTitleOffset(2.33);
  fHiPtLambdaSample->GetYaxis()->SetTitle("Counts/Event");
  fHiPtLambdaSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "5 < p_{T} (GeV/c^{2}) < 10");  
  if      (output == "png") cInvMassLambda->SaveAs("LF_QAanalysis_V0_pageY.png");
  else if (output == "eps") cInvMassLambda->SaveAs("LF_QAanalysis_V0_pageY.eps");
  else if (output == "pdf") cInvMassLambda->SaveAs("LF_QAanalysis_V0.pdf");

  */
  //==============================================================

  //==============================================================
  //Invariant Mass Plots: WITH dE/dx
  TCanvas *cInvMassLambdaWithdEdx = new TCanvas ( "cInvMassLambdaWithdEdx", "", 1200,800); 
  cInvMassLambdaWithdEdx->Divide(1,2); 
  cInvMassLambdaWithdEdx->cd(2)->Divide(3,1); 
  cInvMassLambdaWithdEdx->cd(1); 
  cInvMassLambdaWithdEdx->cd(1)->SetLogz();
  cInvMassLambdaWithdEdx->cd(1)->SetLeftMargin(0.065);
  cInvMassLambdaWithdEdx->cd(1)->SetTopMargin(0.13);
  cInvMassLambdaWithdEdx->cd(1)->SetBottomMargin(0.11);

  f2dHistInvMassWithdEdxLambda->GetYaxis()->SetTitleSize(0.05);
  f2dHistInvMassWithdEdxLambda->GetYaxis()->SetTitleOffset(0.6);
  f2dHistInvMassWithdEdxLambda->GetXaxis()->SetTitleSize(0.05);
  f2dHistInvMassWithdEdxLambda->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  f2dHistInvMassWithdEdxLambda->GetZaxis()->SetTitle("Counts / Event");
  f2dHistInvMassWithdEdxLambda->GetZaxis()->SetTitleOffset(0.7);
  f2dHistInvMassWithdEdxLambda->GetZaxis()->SetRangeUser( f2dHistInvMassWithdEdxLambda->GetMinimum(1e-10)*0.9, f2dHistInvMassWithdEdxLambda->GetMaximum()*1.2 );
  f2dHistInvMassWithdEdxLambda->Draw("colz");
  Tl.DrawLatex(.35, .9277, "Mass under #Lambda hypothesis, With TPC dE/dx")  ;   

  TH1D *fLowPtLambdaSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxLambda->ProjectionY( "fLowPtLambdaSampleWithdEdx", 
    f2dHistInvMassWithdEdxLambda->GetXaxis()->FindBin(0.5001),
    f2dHistInvMassWithdEdxLambda->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtLambdaSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxLambda->ProjectionY( "fMidPtLambdaSampleWithdEdx", 
    f2dHistInvMassWithdEdxLambda->GetXaxis()->FindBin(1.5001),
    f2dHistInvMassWithdEdxLambda->GetXaxis()->FindBin(2.4999) );

  TH1D *fHiPtLambdaSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxLambda->ProjectionY( "fHiPtLambdaSampleWithdEdx", 
    f2dHistInvMassWithdEdxLambda->GetXaxis()->FindBin(5.0001),
    f2dHistInvMassWithdEdxLambda->GetXaxis()->FindBin(9.9999) );

  for(Int_t ic = 1; ic<4; ic++){ 
    cInvMassLambdaWithdEdx->cd(2)->cd(ic)->SetTopMargin(0.14);
    cInvMassLambdaWithdEdx->cd(2)->cd(ic)->SetLeftMargin(0.15);
    cInvMassLambdaWithdEdx->cd(2)->cd(ic)->SetBottomMargin(0.11);
    cInvMassLambdaWithdEdx->cd(2)->cd(ic)->SetGridx(); 
    cInvMassLambdaWithdEdx->cd(2)->cd(ic)->SetGridy();
  }

  cInvMassLambdaWithdEdx->cd(2)->cd(1); 
  fLowPtLambdaSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fLowPtLambdaSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fLowPtLambdaSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fLowPtLambdaSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "0.5 < p_{T} (GeV/c^{2}) < 1.0");

  cInvMassLambdaWithdEdx->cd(2)->cd(2); 
  fMidPtLambdaSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fMidPtLambdaSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fMidPtLambdaSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fMidPtLambdaSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "1.5 < p_{T} (GeV/c^{2}) < 2.5");

  cInvMassLambdaWithdEdx->cd(2)->cd(3); 
  fHiPtLambdaSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fHiPtLambdaSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fHiPtLambdaSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fHiPtLambdaSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "5 < p_{T} (GeV/c^{2}) < 10"); 

  if( lAttemptInvMassFit ){ 
    //Attempt rough signal extraction   
    TF1 *fl1 = new TF1("fl1","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",1.095, 1.14);
    //Reasonable first guess
    fl1->SetParameter(0, fLowPtLambdaSampleWithdEdx -> GetBinContent( fLowPtLambdaSampleWithdEdx->FindBin(1.116+0.01) ) );
    fl1->SetParameter(1, 0 );
    fl1->SetParameter(2, 0 );
    fl1->SetParameter(3, 0.35*fLowPtLambdaSampleWithdEdx->GetMaximum() ); 
    fl1->SetParameter(4, 1.115683);
    fl1->SetParLimits(4,1.116-0.01,1.116+0.01);
    fl1->SetParameter(5, 0.002);
    fl1->SetParLimits(5,0.0005,0.01);
    cout<<"Will now fit, please wait!"<<endl;
    fLowPtLambdaSampleWithdEdx->Fit("fl1","REM0");
    cInvMassLambdaWithdEdx->cd(2)->cd(1); 
    fl1->Draw("same"); 
    //Peak Position, Width: printout 
    fLowPtLambdaSampleWithdEdx->GetYaxis()->SetRangeUser(0,fLowPtLambdaSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",fl1->GetParameter(4),fl1->GetParameter(5)) ) ;
    
    //Attempt rough signal extraction   
    TF1 *fl2 = new TF1("fl2","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",1.085, 1.15);
    //Reasonable first guess
    fl2->SetParameter(0, fMidPtLambdaSampleWithdEdx -> GetBinContent( fMidPtLambdaSampleWithdEdx->FindBin(1.116+0.01) ) );
    fl2->SetParameter(1, 0 );
    fl2->SetParameter(2, 0 );
    fl2->SetParameter(3, 0.6*fMidPtLambdaSampleWithdEdx->GetMaximum() ); 
    fl2->SetParLimits(4,1.116-0.01,1.116+0.01);
    fl2->SetParameter(4, 1.116);
    fl2->SetParameter(5, 0.0025);
    fl2->SetParLimits(5,0.0005,0.01);
    cout<<"Will now fit, please wait!"<<endl;
    fMidPtLambdaSampleWithdEdx->Fit("fl2","REM0");
    cInvMassLambdaWithdEdx->cd(2)->cd(2); 
    fl2->Draw("same"); 
    //Peak Position, Width: printout 
    fMidPtLambdaSampleWithdEdx->GetYaxis()->SetRangeUser(0,fMidPtLambdaSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",fl2->GetParameter(4),fl2->GetParameter(5)) ) ;

    //Attempt rough signal extraction   
    TF1 *fl3 = new TF1("fl3","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",1.095, 1.15);
    //Reasonable first guess
    fl3->SetParameter(0, fHiPtLambdaSampleWithdEdx -> GetBinContent( fHiPtLambdaSampleWithdEdx->FindBin(1.116+0.01) ) );
    fl3->SetParameter(1, 0 );
    fl3->SetParameter(2, 0 );
    fl3->SetParameter(3, 0.6*fHiPtLambdaSampleWithdEdx->GetMaximum() ); 
    fl3->SetParameter(4, 1.116);
    fl3->SetParLimits(4,1.116-0.005,1.116+0.005);
    fl3->SetParameter(5, 0.0035);
    fl3->SetParLimits(5,0.0005,0.01);
    cout<<"Will now fit, please wait!"<<endl;
    fHiPtLambdaSampleWithdEdx->Fit("fl3","REM0");
    cInvMassLambdaWithdEdx->cd(2)->cd(3); 
    fl3->Draw("same"); 
    //Peak Position, Width: printout 
    fHiPtLambdaSampleWithdEdx->GetYaxis()->SetRangeUser(0,fHiPtLambdaSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",fl3->GetParameter(4),fl3->GetParameter(5)) ) ;
  }

 
  if      (output == "png") cInvMassLambdaWithdEdx->SaveAs("LF_QAanalysis_V0_page3.png");
  else if (output == "eps") cInvMassLambdaWithdEdx->SaveAs("LF_QAanalysis_V0_page3.eps");
  else if (output == "pdf") cInvMassLambdaWithdEdx->SaveAs("LF_QAanalysis_V0.pdf");
  //==============================================================  

  //==============================================================
  //Invariant Mass Plots: Base, no dE/dx
  /*
  TCanvas *cInvMassAntiLambda = new TCanvas ( "cInvMassAntiLambda", "", 1200,800); 
  cInvMassAntiLambda->Divide(1,2); 
  cInvMassAntiLambda->cd(2)->Divide(3,1); 
  cInvMassAntiLambda->cd(1); 
  cInvMassAntiLambda->cd(1)->SetLogz();
  cInvMassAntiLambda->cd(1)->SetLeftMargin(0.065);
  cInvMassAntiLambda->cd(1)->SetTopMargin(0.13);
  cInvMassAntiLambda->cd(1)->SetBottomMargin(0.11);

  f2dHistInvMassAntiLambda->GetYaxis()->SetTitleSize(0.05);
  f2dHistInvMassAntiLambda->GetYaxis()->SetTitleOffset(0.6);
  f2dHistInvMassAntiLambda->GetXaxis()->SetTitleSize(0.05);
  f2dHistInvMassAntiLambda->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  f2dHistInvMassAntiLambda->GetZaxis()->SetTitle("Counts / Event");
  f2dHistInvMassAntiLambda->GetZaxis()->SetTitleOffset(0.7);
  f2dHistInvMassAntiLambda->GetZaxis()->SetRangeUser( f2dHistInvMassAntiLambda->GetMinimum(1e-10)*0.9, f2dHistInvMassAntiLambda->GetMaximum()*1.2 );
  f2dHistInvMassAntiLambda->Draw("colz");
  Tl.DrawLatex(.35, .9277, "Mass under #bar{#Lambda} hypothesis, no TPC dE/dx")  ;   

  TH1D *fLowPtAntiLambdaSample = (TH1D*) f2dHistInvMassAntiLambda->ProjectionY( "fLowPtAntiLambdaSample", 
    f2dHistInvMassAntiLambda->GetXaxis()->FindBin(0.5001),
    f2dHistInvMassAntiLambda->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtAntiLambdaSample = (TH1D*) f2dHistInvMassAntiLambda->ProjectionY( "fMidPtAntiLambdaSample", 
    f2dHistInvMassAntiLambda->GetXaxis()->FindBin(1.5001),
    f2dHistInvMassAntiLambda->GetXaxis()->FindBin(2.4999) );

  TH1D *fHiPtAntiLambdaSample = (TH1D*) f2dHistInvMassAntiLambda->ProjectionY( "fHiPtAntiLambdaSample", 
    f2dHistInvMassAntiLambda->GetXaxis()->FindBin(5.0001),
    f2dHistInvMassAntiLambda->GetXaxis()->FindBin(9.9999) );

  for(Int_t ic = 1; ic<4; ic++){ 
    cInvMassAntiLambda->cd(2)->cd(ic)->SetTopMargin(0.14);
    cInvMassAntiLambda->cd(2)->cd(ic)->SetLeftMargin(0.15);
    cInvMassAntiLambda->cd(2)->cd(ic)->SetBottomMargin(0.11);
    cInvMassAntiLambda->cd(2)->cd(ic)->SetGridx(); 
    cInvMassAntiLambda->cd(2)->cd(ic)->SetGridy();
  }

  cInvMassAntiLambda->cd(2)->cd(1); 
  fLowPtAntiLambdaSample->GetXaxis()->SetTitleOffset(1.1);
  fLowPtAntiLambdaSample->GetYaxis()->SetTitleOffset(2.33);
  fLowPtAntiLambdaSample->GetYaxis()->SetTitle("Counts/Event");
  fLowPtAntiLambdaSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "0.5 < p_{T} (GeV/c^{2}) < 1.0");

  cInvMassAntiLambda->cd(2)->cd(2); 
  fMidPtAntiLambdaSample->GetXaxis()->SetTitleOffset(1.1);
  fMidPtAntiLambdaSample->GetYaxis()->SetTitleOffset(2.33);
  fMidPtAntiLambdaSample->GetYaxis()->SetTitle("Counts/Event");
  fMidPtAntiLambdaSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "1.5 < p_{T} (GeV/c^{2}) < 2.5");

  cInvMassAntiLambda->cd(2)->cd(3); 
  fHiPtAntiLambdaSample->GetXaxis()->SetTitleOffset(1.1);
  fHiPtAntiLambdaSample->GetYaxis()->SetTitleOffset(2.33);
  fHiPtAntiLambdaSample->GetYaxis()->SetTitle("Counts/Event");
  fHiPtAntiLambdaSample->Draw(); 
  Tl.DrawLatex(.25, .9277, "5 < p_{T} (GeV/c^{2}) < 10");  
  if      (output == "png") cInvMassAntiLambda->SaveAs("LF_QAanalysis_V0_pageZ.png");
  else if (output == "eps") cInvMassAntiLambda->SaveAs("LF_QAanalysis_V0_pageZ.eps");
  else if (output == "pdf") cInvMassAntiLambda->SaveAs("LF_QAanalysis_V0.pdf");

  */
  //==============================================================

  //==============================================================
  //Invariant Mass Plots: WITH dE/dx
  TCanvas *cInvMassAntiLambdaWithdEdx = new TCanvas ( "cInvMassAntiLambdaWithdEdx", "", 1200,800); 
  cInvMassAntiLambdaWithdEdx->Divide(1,2); 
  cInvMassAntiLambdaWithdEdx->cd(2)->Divide(3,1); 
  cInvMassAntiLambdaWithdEdx->cd(1); 
  cInvMassAntiLambdaWithdEdx->cd(1)->SetLogz();
  cInvMassAntiLambdaWithdEdx->cd(1)->SetLeftMargin(0.065);
  cInvMassAntiLambdaWithdEdx->cd(1)->SetTopMargin(0.13);
  cInvMassAntiLambdaWithdEdx->cd(1)->SetBottomMargin(0.11);

  f2dHistInvMassWithdEdxAntiLambda->GetYaxis()->SetTitleSize(0.05);
  f2dHistInvMassWithdEdxAntiLambda->GetYaxis()->SetTitleOffset(0.6);
  f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->SetTitleSize(0.05);
  f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  f2dHistInvMassWithdEdxAntiLambda->GetZaxis()->SetTitle("Counts / Event");
  f2dHistInvMassWithdEdxAntiLambda->GetZaxis()->SetTitleOffset(0.7);
  f2dHistInvMassWithdEdxAntiLambda->GetZaxis()->SetRangeUser( f2dHistInvMassWithdEdxAntiLambda->GetMinimum(1e-10)*0.9, f2dHistInvMassWithdEdxAntiLambda->GetMaximum()*1.2 );
  f2dHistInvMassWithdEdxAntiLambda->Draw("colz");
  Tl.DrawLatex(.35, .9277, "Mass under #bar{#Lambda} hypothesis, With TPC dE/dx")  ;   

  TH1D *fLowPtAntiLambdaSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxAntiLambda->ProjectionY( "fLowPtAntiLambdaSampleWithdEdx", 
    f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->FindBin(0.5001),
    f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtAntiLambdaSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxAntiLambda->ProjectionY( "fMidPtAntiLambdaSampleWithdEdx", 
    f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->FindBin(1.5001),
    f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->FindBin(2.4999) );

  TH1D *fHiPtAntiLambdaSampleWithdEdx = (TH1D*) f2dHistInvMassWithdEdxAntiLambda->ProjectionY( "fHiPtAntiLambdaSampleWithdEdx", 
    f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->FindBin(5.0001),
    f2dHistInvMassWithdEdxAntiLambda->GetXaxis()->FindBin(9.9999) );

  for(Int_t ic = 1; ic<4; ic++){ 
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(ic)->SetTopMargin(0.14);
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(ic)->SetLeftMargin(0.15);
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(ic)->SetBottomMargin(0.11);
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(ic)->SetGridx(); 
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(ic)->SetGridy();
  }

  cInvMassAntiLambdaWithdEdx->cd(2)->cd(1); 
  fLowPtAntiLambdaSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fLowPtAntiLambdaSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fLowPtAntiLambdaSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fLowPtAntiLambdaSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "0.5 < p_{T} (GeV/c^{2}) < 1.0");

  cInvMassAntiLambdaWithdEdx->cd(2)->cd(2); 
  fMidPtAntiLambdaSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fMidPtAntiLambdaSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fMidPtAntiLambdaSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fMidPtAntiLambdaSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "1.5 < p_{T} (GeV/c^{2}) < 2.5");

  cInvMassAntiLambdaWithdEdx->cd(2)->cd(3); 
  fHiPtAntiLambdaSampleWithdEdx->GetXaxis()->SetTitleOffset(1.1);
  fHiPtAntiLambdaSampleWithdEdx->GetYaxis()->SetTitleOffset(2.33);
  fHiPtAntiLambdaSampleWithdEdx->GetYaxis()->SetTitle("Counts/Event");
  fHiPtAntiLambdaSampleWithdEdx->Draw(); 
  Tl.DrawLatex(.25, .9277, "5 < p_{T} (GeV/c^{2}) < 10"); 

  if( lAttemptInvMassFit ){ 
    //Attempt rough signal extraction   
    TF1 *fal1 = new TF1("fal1","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",1.095, 1.14);
    //Reasonable first guess
    fal1->SetParameter(0, fLowPtAntiLambdaSampleWithdEdx -> GetBinContent( fLowPtAntiLambdaSampleWithdEdx->FindBin(1.116+0.01) ) );
    fal1->SetParameter(1, 0 );
    fal1->SetParameter(2, 0 );
    fal1->SetParameter(3, 0.35*fLowPtAntiLambdaSampleWithdEdx->GetMaximum() ); 
    fal1->SetParameter(4, 1.115683);
    fal1->SetParLimits(4,1.116-0.01,1.116+0.01);
    fal1->SetParameter(5, 0.002);
    fal1->SetParLimits(5,0.0005,0.01);
    cout<<"Will now fit, please wait!"<<endl;
    fLowPtAntiLambdaSampleWithdEdx->Fit("fal1","REM0");
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(1); 
    fal1->Draw("same"); 
    //Peak Position, Width: printout 
    fLowPtAntiLambdaSampleWithdEdx->GetYaxis()->SetRangeUser(0,fLowPtAntiLambdaSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",fal1->GetParameter(4),fal1->GetParameter(5)) ) ;
    
    //Attempt rough signal extraction   
    TF1 *fal2 = new TF1("fal2","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",1.085, 1.15);
    //Reasonable first guess
    fal2->SetParameter(0, fMidPtAntiLambdaSampleWithdEdx -> GetBinContent( fMidPtAntiLambdaSampleWithdEdx->FindBin(1.116+0.01) ) );
    fal2->SetParameter(1, 0 );
    fal2->SetParameter(2, 0 );
    fal2->SetParameter(3, 0.6*fMidPtAntiLambdaSampleWithdEdx->GetMaximum() ); 
    fal2->SetParLimits(4,1.116-0.01,1.116+0.01);
    fal2->SetParameter(4, 1.116);
    fal2->SetParameter(5, 0.0025);
    fal2->SetParLimits(5,0.0005,0.01);
    cout<<"Will now fit, please wait!"<<endl;
    fMidPtAntiLambdaSampleWithdEdx->Fit("fal2","REM0");
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(2); 
    fal2->Draw("same"); 
    //Peak Position, Width: printout 
    fMidPtAntiLambdaSampleWithdEdx->GetYaxis()->SetRangeUser(0,fMidPtAntiLambdaSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",fal2->GetParameter(4),fal2->GetParameter(5)) ) ;

    //Attempt rough signal extraction   
    TF1 *fal3 = new TF1("fal3","[0]+[1]*x+[2]*x*x+[3]*TMath::Gaus(x,[4],[5])",1.095, 1.15);
    //Reasonable first guess
    fal3->SetParameter(0, fHiPtAntiLambdaSampleWithdEdx -> GetBinContent( fHiPtAntiLambdaSampleWithdEdx->FindBin(1.116+0.01) ) );
    fal3->SetParameter(1, 0 );
    fal3->SetParameter(2, 0 );
    fal3->SetParameter(3, 0.6*fHiPtAntiLambdaSampleWithdEdx->GetMaximum() ); 
    fal3->SetParameter(4, 1.116);
    fal3->SetParLimits(4,1.116-0.005,1.116+0.005);
    fal3->SetParameter(5, 0.0035);
    fal3->SetParLimits(5,0.0005,0.01);
    cout<<"Will now fit, please wait!"<<endl;
    fHiPtAntiLambdaSampleWithdEdx->Fit("fal3","REM0");
    cInvMassAntiLambdaWithdEdx->cd(2)->cd(3); 
    fal3->Draw("same"); 
    //Peak Position, Width: printout 
    fHiPtAntiLambdaSampleWithdEdx->GetYaxis()->SetRangeUser(0,fHiPtAntiLambdaSampleWithdEdx->GetMaximum() * 1.2);
    Tli.DrawLatex(0.2,0.8,Form("peak = %.4f #pm %.4f MeV/c^{2}",fal3->GetParameter(4),fal3->GetParameter(5)) ) ;
  }

 
  if      (output == "png") cInvMassAntiLambdaWithdEdx->SaveAs("LF_QAanalysis_V0_page4.png");
  else if (output == "eps") cInvMassAntiLambdaWithdEdx->SaveAs("LF_QAanalysis_V0_page4.eps");
  else if (output == "pdf") cInvMassAntiLambdaWithdEdx->SaveAs("LF_QAanalysis_V0.pdf");

  //==============================================================  

  //==============================================================  
  // Strict Lambda Analysis for dE/dx Calibration Check 
  TH2D *f2dHistdEdxSignalPionFromLambda    = (TH2D*)clist->FindObject("f2dHistdEdxSignalPionFromLambda");
  TH2D *f2dHistdEdxSignalProtonFromLambda  = (TH2D*)clist->FindObject("f2dHistdEdxSignalProtonFromLambda");
  TH2D *f2dHistResponsePionFromLambda      = (TH2D*)clist->FindObject("f2dHistResponsePionFromLambda");
  TH2D *f2dHistResponseProtonFromLambda    = (TH2D*)clist->FindObject("f2dHistResponseProtonFromLambda");

  f2dHistdEdxSignalPionFromLambda->Rebin2D(2,10);
  f2dHistdEdxSignalProtonFromLambda->Rebin2D(2,10);
    
  
  TH1D *fLowPtPionResponse = (TH1D*) f2dHistResponsePionFromLambda->ProjectionY( "fLowPtPionResponse", 
    f2dHistResponsePionFromLambda->GetXaxis()->FindBin(0.5001),
    f2dHistResponsePionFromLambda->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtPionResponse = (TH1D*) f2dHistResponsePionFromLambda->ProjectionY( "fMidPtPionResponse", 
    f2dHistResponsePionFromLambda->GetXaxis()->FindBin(1.5001),
    f2dHistResponsePionFromLambda->GetXaxis()->FindBin(2.4999) );

  TH1D *fLowPtProtonResponse = (TH1D*) f2dHistResponseProtonFromLambda->ProjectionY( "fLowPtProtonResponse", 
    f2dHistResponseProtonFromLambda->GetXaxis()->FindBin(0.5001),
    f2dHistResponseProtonFromLambda->GetXaxis()->FindBin(0.9999) );

  TH1D *fMidPtProtonResponse = (TH1D*) f2dHistResponseProtonFromLambda->ProjectionY( "fMidPtProtonResponse", 
    f2dHistResponseProtonFromLambda->GetXaxis()->FindBin(1.5001),
    f2dHistResponseProtonFromLambda->GetXaxis()->FindBin(2.4999) );



  TCanvas *cdEdxPure = new TCanvas("cdEdxPure","",1500,800);
  cdEdxPure->Divide(4,2); 

  for(Int_t ic = 1; ic<9; ic++){ 
    cdEdxPure->SetLeftMargin(0.15);
    cdEdxPure->cd(ic)->SetLogz();
    //cdEdxPure->cd(ic)->SetTopMargin(0.133);
    if( ic%4 == 1 || ic%4 == 2){
      cdEdxPure->cd(ic)->SetRightMargin(0.133);
    }
    if( ic%4 != 1 && ic%4 != 2){
      cdEdxPure->cd(ic)->SetGridx();
      cdEdxPure->cd(ic)->SetGridy();
    }
  }



  cdEdxPure->cd(1); 
  f2dHistdEdxSignalPionFromLambda->Draw("colz"); 
  cdEdxPure->cd(2); 
  f2dHistResponsePionFromLambda->Draw("colz"); 
  cdEdxPure->cd(3); 
  fLowPtPionResponse->Draw();
  cdEdxPure->cd(4); 
  fMidPtPionResponse->Draw();

  cdEdxPure->cd(5); 
  f2dHistdEdxSignalProtonFromLambda->Draw("colz"); 
  cdEdxPure->cd(6); 
  f2dHistResponseProtonFromLambda->Draw("colz"); 
  cdEdxPure->cd(7); 
  fLowPtProtonResponse->Draw();
  cdEdxPure->cd(8); 
  fMidPtProtonResponse->Draw();



  //Write explanations on canvases
  cdEdxPure->cd(1); Tl.DrawLatex(.25, .9277, "#pi^{-} from #Lambda: TPC Signal");
  cdEdxPure->cd(2); Tl.DrawLatex(.15, .9277, "#pi^{-} from #Lambda: AliPIDResponse Value");
  cdEdxPure->cd(3); Tl.DrawLatex(.21, .9277, "#pi^{-} N#sigma, 0.5 < p_{T} (GeV/c) < 1.0");
  cdEdxPure->cd(4); Tl.DrawLatex(.21, .9277, "#pi^{-} N#sigma, 1.5 < p_{T} (GeV/c) < 2.5");

  cdEdxPure->cd(5); Tl.DrawLatex(.25, .9277, "p from #Lambda: TPC Signal");
  cdEdxPure->cd(6); Tl.DrawLatex(.15, .9277, "p from #Lambda: AliPIDResponse Value");
  cdEdxPure->cd(7); Tl.DrawLatex(.21, .9277, "p N#sigma, 0.5 < p_{T} (GeV/c) < 1.0");
  cdEdxPure->cd(8); Tl.DrawLatex(.21, .9277, "p N#sigma, 1.5 < p_{T} (GeV/c) < 2.5");

  Double_t lLowPtPeakPion         = fLowPtPionResponse->GetBinCenter( fLowPtPionResponse->GetMaximumBin() );
  Double_t lMidPtPeakPion         = fMidPtPionResponse->GetBinCenter( fMidPtPionResponse->GetMaximumBin() );
  Double_t lLowPtPeakProton       = fLowPtProtonResponse->GetBinCenter( fLowPtProtonResponse->GetMaximumBin() );
  Double_t lMidPtPeakProton       = fMidPtProtonResponse->GetBinCenter( fMidPtProtonResponse->GetMaximumBin() );

  //List Maximal Values
  cout<<"Maximal Value for pion from Lambda at low pt...............: " <<lLowPtPeakPion<<endl;
  cout<<"Maximal Value for pion from Lambda at mid pt...............: " <<lMidPtPeakPion<<endl;
  cout<<"Maximal Value for proton from Lambda at low pt.............: " <<lLowPtPeakProton<<endl;
  cout<<"Maximal Value for proton from Lambda at mid pt.............: " <<lMidPtPeakProton<<endl;

  if( TMath::Abs( lLowPtPeakPion ) > 0.3)   cout<<"*** WARNING: Check Low Pt pion PID Response! ***"<<endl;
  if( TMath::Abs( lMidPtPeakPion ) > 0.3)   cout<<"*** WARNING: Check Mid Pt pion PID Response! ***"<<endl;
  if( TMath::Abs( lLowPtPeakProton ) > 0.3) cout<<"*** WARNING: Check Low Pt proton PID Response! ***"<<endl;
  if( TMath::Abs( lMidPtPeakProton ) > 0.3) cout<<"*** WARNING: Check Mid Pt proton PID Response! ***"<<endl;

  TLatex Tlq;
  Tlq.SetNDC();
  Tlq.SetTextSize(0.06);

  //Draw Arrows to be sure!
  Double_t lFractionHeight = 0.33;
  cdEdxPure->cd(3);  
  TArrow *ar1 = new TArrow(lLowPtPeakPion,lFractionHeight * fLowPtPionResponse->GetMaximum(),lLowPtPeakPion,0.0, 0.008 ,"|>");
  ar1->SetLineWidth(2);
  ar1->Draw();
  if( TMath::Abs( lLowPtPeakPion ) < 0.3) {
    Tlq.SetTextColor(8); 
    Tlq.DrawLatex ( 0.15,0.8, "OK!");
  } else { 
    Tlq.SetTextColor(kRed); 
    Tlq.DrawLatex ( 0.15,0.8, "Prob.! Check dEd/x!");
  }

  cdEdxPure->cd(4);  
  TArrow *ar2 = new TArrow(lMidPtPeakPion,lFractionHeight * fMidPtPionResponse->GetMaximum(),lLowPtPeakPion,0.0, 0.008 ,"|>");
  ar2->SetLineWidth(2);
  ar2->Draw();
  if( TMath::Abs( lMidPtPeakPion ) < 0.3) {
    Tlq.SetTextColor(8); 
    Tlq.DrawLatex ( 0.15,0.8, "OK!");
  } else { 
    Tlq.SetTextColor(kRed); 
    Tlq.DrawLatex ( 0.15,0.8, "Prob.! Check dEd/x!");
  }
  
  cdEdxPure->cd(7);  
  TArrow *ar3 = new TArrow(lLowPtPeakProton,lFractionHeight * fLowPtProtonResponse->GetMaximum(),lLowPtPeakPion,0.0, 0.008 ,"|>");
  ar3->SetLineWidth(2);
  ar3->Draw();
  if( TMath::Abs( lLowPtPeakProton ) < 0.3) {
    Tlq.SetTextColor(8); 
    Tlq.DrawLatex ( 0.15,0.8, "OK!");
  } else { 
    Tlq.SetTextColor(kRed); 
    Tlq.DrawLatex ( 0.15,0.8, "Prob.! Check dEd/x!");
  }

  cdEdxPure->cd(8);  
  TArrow *ar4 = new TArrow(lMidPtPeakProton,lFractionHeight * fMidPtProtonResponse->GetMaximum(),lLowPtPeakPion,0.0, 0.008 ,"|>");
  ar4->SetLineWidth(2);
  ar4->Draw();
  if( TMath::Abs( lMidPtPeakProton ) < 0.3) {
    Tlq.SetTextColor(8); 
    Tlq.DrawLatex ( 0.15,0.8, "OK!");
  } else { 
    Tlq.SetTextColor(kRed); 
    Tlq.DrawLatex ( 0.15,0.8, "Prob.! Check dEd/x!");
  }

  if      (output == "png") cdEdxPure->SaveAs("LF_QAanalysis_V0_page5.png");
  else if (output == "eps") cdEdxPure->SaveAs("LF_QAanalysis_V0_page5.eps");
  else if (output == "pdf") cdEdxPure->SaveAs("LF_QAanalysis_V0.pdf");


  //==============================================================

  //==============================================================    
  //Topological variable QA
  // FIXME: This is still only a rough first version. 
  // Adjustments will be required for easy / long-term operation.
  TH1D *fHistTopDCAPosToPV      = (TH1D*)clist->FindObject("fHistSelectedTopDCAPosToPV");
  TH1D *fHistTopDCANegToPV      = (TH1D*)clist->FindObject("fHistSelectedTopDCANegToPV");
  TH1D *fHistTopDCAV0Daughters  = (TH1D*)clist->FindObject("fHistSelectedTopDCAV0Daughters");
  TH1D *fHistTopCosinePA        = (TH1D*)clist->FindObject("fHistSelectedTopCosinePA");
  TH1D *fHistTopV0Radius        = (TH1D*)clist->FindObject("fHistSelectedTopV0Radius");

  //Zoom in on selection in Cosine of pointing angle...
  Int_t iLowBin=-1; 
  Int_t iLowBin2 = -1; 
  Int_t iLowBin3 = -1; 

  //Normalize to per-event 
  fHistTopDCAPosToPV      -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  fHistTopDCANegToPV      -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  fHistTopDCAV0Daughters  -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  fHistTopCosinePA        -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );
  fHistTopV0Radius        -> Scale ( 1. / ((Double_t)fHistEvent->GetBinContent(4) ) );

  fHistTopDCAPosToPV      -> GetYaxis() -> SetTitle("Counts / Event");
  fHistTopDCANegToPV      -> GetYaxis() -> SetTitle("Counts / Event");
  fHistTopDCAV0Daughters  -> GetYaxis() -> SetTitle("Counts / Event");
  fHistTopCosinePA        -> GetYaxis() -> SetTitle("Counts / Event");
  fHistTopV0Radius        -> GetYaxis() -> SetTitle("Counts / Event");

  fHistTopDCAPosToPV      -> GetYaxis() -> SetTitleSize(0.05);
  fHistTopDCANegToPV      -> GetYaxis() -> SetTitleSize(0.05);
  fHistTopDCAV0Daughters  -> GetYaxis() -> SetTitleSize(0.05);
  fHistTopCosinePA        -> GetYaxis() -> SetTitleSize(0.05);
  fHistTopV0Radius        -> GetYaxis() -> SetTitleSize(0.05);

  fHistTopDCAPosToPV      -> GetXaxis() -> SetTitleSize(0.05);
  fHistTopDCANegToPV      -> GetXaxis() -> SetTitleSize(0.05);
  fHistTopDCAV0Daughters  -> GetXaxis() -> SetTitleSize(0.05);
  fHistTopCosinePA        -> GetXaxis() -> SetTitleSize(0.05);
  fHistTopV0Radius        -> GetXaxis() -> SetTitleSize(0.05);

  Double_t lMinimumCosPADraw = 1.-1.25*(1.-GetXForMinValue ( fHistTopCosinePA ) ); //assumes monotonically increasing dist
  cout<<"Function test: "<< lMinimumCosPADraw <<endl;
  fHistTopCosinePA->GetXaxis()->SetRangeUser(lMinimumCosPADraw,1.001);  

  Double_t lmin[5]; 
  Double_t lminPrecision[5]; 
  lmin[3] = GetXForMinValue ( fHistTopCosinePA );
  lmin[4] = GetXForMinValue ( fHistTopV0Radius );
  lmin[0] = GetXForMaxValue ( fHistTopDCAPosToPV );
  lmin[1] = GetXForMaxValue ( fHistTopDCANegToPV );
  lmin[2] = GetXForMinValue ( fHistTopDCAV0Daughters );

  lminPrecision[3] = fHistTopCosinePA        -> GetBinWidth(1);
  lminPrecision[4] = fHistTopV0Radius        -> GetBinWidth(1);
  lminPrecision[0] = fHistTopDCAPosToPV      -> GetBinWidth(1);
  lminPrecision[1] = fHistTopDCANegToPV      -> GetBinWidth(1);
  lminPrecision[2] = fHistTopDCAV0Daughters  -> GetBinWidth(1);

  cout<<"Minimum Values Found: "<<endl;
  cout<<"Cosine of Pointing Angle...........: "<<GetXForMinValue (fHistTopCosinePA )<<" precision = "<<lminPrecision[3]<<endl;
  cout<<"DCA Neg Daughter to PV.............: "<<GetXForMaxValue (fHistTopDCAPosToPV )<<" precision = "<<lminPrecision[1]<<endl;
  cout<<"DCA Pos Daughter to PV.............: "<<GetXForMaxValue (fHistTopDCANegToPV )<<" precision = "<<lminPrecision[0]<<endl;
  cout<<"DCA V0 Daughers....................: "<<GetXForMinValue (fHistTopDCAV0Daughters )<<" precision = "<<lminPrecision[2]<<endl;
  cout<<"V0 Decay Radius....................: "<<GetXForMinValue (fHistTopV0Radius )<<" precision = "<<lminPrecision[4]<<endl;


  TCanvas *cTopo = new TCanvas ("cTopo","",1200,800);
  cTopo->Divide(3,2); 
  for(Int_t ic = 1; ic<7; ic++){ 
    cTopo->cd(ic)->SetLeftMargin(0.15);
    cTopo->cd(ic)->SetGridx(); 
    cTopo->cd(ic)->SetGridy(); 
  }

  cTopo->cd(1);   
  fHistTopDCAPosToPV->Draw(); 
  cTopo->cd(2);   
  fHistTopDCANegToPV->Draw(); 
  cTopo->cd(3);   
  fHistTopDCAV0Daughters->Draw(); 
  cTopo->cd(4);   
  fHistTopCosinePA->Draw(); 
  cTopo->cd(5);   
  fHistTopV0Radius->Draw(); 

  TLatex Tlt;
  Tlt.SetNDC();
  Tlt.SetTextSize(0.05);
  cTopo->cd(6);
    
  Tlt.DrawLatex(.22, .9, "Boundary Checks")  ;


        
  TString lCut[5];
  lCut [ 0 ] = "Min DCA Pos D. To PV (cm)";
  lCut [ 1 ] = "Min DCA Neg D. To PV (cm)";
  lCut [ 2 ] = "Max DCA V0 Daughters (#sigma)";
  lCut [ 3 ] = "Min Cosine PA";
  lCut [ 4 ] = "Min 2D Decay Radius (cm)";

  TString lCutVal[5]; 
  TString lCutValPrec[5]; 
    
  Tlt.SetTextSize(0.04);
  Tlt.SetTextFont(42);

  Tlt.DrawLatex(.01, .80, "Topological Var.")  ;
  Tlt.DrawLatex(.6, .80, "Value")  ;
  Tlt.DrawLatex(.75, .80, "Precision")  ;

  for (Int_t il=0;il<5;il++){ 
    Tlt.DrawLatex(.01,0.72-((double)il)*0.075, lCut[il].Data() );
    lCutVal[il] = Form( "%.4f", lmin[il] );
    Tlt.DrawLatex(.5925,0.72-((double)il)*0.075, lCutVal[il].Data() );
    lCutValPrec[il] = Form( "%.4f", lminPrecision[il] );
    Tlt.DrawLatex(.7675,0.72-((double)il)*0.075, lCutValPrec[il].Data() );
  }

  Tlt.SetTextSize(0.05);
  Tlt.SetTextFont(42);

  //Try to make a wild guess... 
  if ( TMath::Abs( lmin[0] - 0.100 ) < 2*lminPrecision[0] &&
       TMath::Abs( lmin[1] - 0.100 ) < 2*lminPrecision[1] &&
       TMath::Abs( lmin[2] - 1.000 ) < 2*lminPrecision[2] &&
       TMath::Abs( lmin[3] - 0.998 ) < 2*lminPrecision[3] &&
       TMath::Abs( lmin[4] - 0.500 ) < 2*lminPrecision[4] ){
    Tlt.DrawLatex( 0.17, 0.275, "#bf{Autodetect Interpretation}: "); 
    Tlt.DrawLatex( 0.1, 0.2, "Typical #bf{Pb-Pb} Reconstruction Cuts");
  }
  if ( TMath::Abs( lmin[0] - 0.020 ) < 2*lminPrecision[0] &&
       TMath::Abs( lmin[1] - 0.020 ) < 2*lminPrecision[1] &&
       TMath::Abs( lmin[2] - 1.500 ) < 2*lminPrecision[2] &&
       TMath::Abs( lmin[3] - 0.98 )  < 2*lminPrecision[3] &&
       TMath::Abs( lmin[4] - 0.500 ) < 2*lminPrecision[4] ){
    Tlt.DrawLatex( 0.15, 0.29, "#bf{Autodetect Interpretation}: ");  
    Tlt.DrawLatex( 0.1, 0.2, "Typical pp Reconstruction Cuts"); //To be checked
  }

  if      (output == "png") cTopo->SaveAs("LF_QAanalysis_V0_page6.png");
  else if (output == "eps") cTopo->SaveAs("LF_QAanalysis_V0_page6.eps");
  else if (output == "pdf") cTopo->SaveAs("LF_QAanalysis_V0.pdf)");


}
Esempio n. 15
0
void doPlotsBtag_Log(bool logPlot){
setTDRStyle();

double lumi = 5800;
//stuff to choose
//bool logPlot = false; //true for log plot
int rebinFact = 1;

//isolation selection
//TString Isolation = "QCD No Iso/";
TString Isolation = "Ref selection/";
//TString Isolation = "QCD mu+jets PFRelIso/";
//TString Isolation = "QCD non iso mu+jets/";

TString Systematic = "central";

// number of btags
TString Nbtags = "2btags";  //standard  "2btags" , qcd "0btag"

//choose object
TString Obj = "";
//TString Obj = "MET/";

//muon variables
const int N = 2;
TString Variable;
TString Variables[N] = {"N_BJets", "N_BJets_reweighted"};
double MinXs[N] = {-0.5,-0.5};
double MaxXs[N] = {7.5,7.5};
TString XTitles[N] = {"B-tag Multiplicity", "B-tag Multiplicity"};



//loop over variables
for(int i = 0; i<2; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("SingleMu", 1, Obj, Variable, Isolation, rebinFact, "central");

//MC
TH1D* tt = getSample("TTJet", lumi*225.2/6920475, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* wjets = getSample("W1Jet", lumi*37509/57708550, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w2jets = getSample("W2Jets", lumi*1750.0/34041404, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w3jets = getSample("W3Jets", lumi*519.0/15536443, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w4jets = getSample("W4Jets", lumi*214.0/13370904, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* zjets = getSample("DY1JetsToLL", lumi*5745.25/30457954, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z2jets = getSample("DY2JetsToLL", lumi*181.0/21835749, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z3jets = getSample("DY3JetsToLL", lumi*51.1/11010628, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z4jets = getSample("DY4JetsToLL", lumi*23.04/6391785, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",     lumi*34679.3/8500505, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd2 = getSample("QCD_Pt-20to30_MuEnrichedPt5",   lumi*2.87e8 * 0.0065/8486893, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd3 = getSample("QCD_Pt-30to50_MuEnrichedPt5",   lumi*6.609e7 * 0.0122/8928999, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd4 = getSample("QCD_Pt-50to80_MuEnrichedPt5",   lumi*8082000.0 * 0.0218/7256011, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd5 = getSample("QCD_Pt-80to120_MuEnrichedPt5",  lumi*1024000.0 * 0.0395/9030624, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd6 = getSample("QCD_Pt-120to170_MuEnrichedPt5", lumi*157800.0 * 0.0473/8500505, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd7 = getSample("QCD_Pt-170to300_MuEnrichedPt5", lumi*34020.0 * 0.0676/7662483, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd8 = getSample("QCD_Pt-300to470_MuEnrichedPt5", lumi*1757.0 * 0.0864/7797481, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd9 = getSample("QCD_Pt-470to600_MuEnrichedPt5", lumi*115.2 * 0.1024/2995767, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd10 = getSample("QCD_Pt-800to1000_MuEnrichedPt5",lumi*3.57 * 0.1033/4047142, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd11 = getSample("QCD_Pt-1000_MuEnrichedPt5",     lumi*0.774 * 0.1097/3807263, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* top_t = getSample("T_t-channel", lumi*56.4/3757707, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* top_tw = getSample("T_tW-channel", lumi*11.1/497395, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* top_s = getSample("T_s-channel", lumi*3.79/249516, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_t = getSample("Tbar_t-channel", lumi*30.7/1934817, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_tw = getSample("Tbar_tW-channel", lumi*11.1/493239, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_s = getSample("Tbar_s-channel", lumi*1.76/139948, Obj, Variable, Isolation, rebinFact, Systematic);

//make combined top and single top template
TH1D* sing_top = (TH1D*)top_t->Clone("top");
sing_top->Add(top_tw);sing_top->Add(top_s); sing_top->Add(tbar_t); sing_top->Add(tbar_tw);sing_top->Add(tbar_s);

zjets->Add(z2jets);
zjets->Add(z3jets);
zjets->Add(z4jets);  

wjets->Add(w2jets);
wjets->Add(w3jets);
wjets->Add(w4jets);

//make combined top and single top template
TH1D* qcd_all = (TH1D*)qcd->Clone("qcd_all");
qcd_all->Add(qcd2);
qcd_all->Add(qcd3);
qcd_all->Add(qcd4);
qcd_all->Add(qcd5);
qcd_all->Add(qcd6);
qcd_all->Add(qcd7);
qcd_all->Add(qcd8);
qcd_all->Add(qcd9);
qcd_all->Add(qcd10);
qcd_all->Add(qcd11);
  
THStack *hs = new THStack("hs","test");

qcd_all->SetLineColor(kBlack);
zjets->SetLineColor(kBlack);
wjets->SetLineColor(kBlack);	
sing_top->SetLineColor(kBlack);
tt->SetLineColor(kBlack);	

  hs->Add(qcd_all);
  hs->Add(zjets);
  hs->Add(wjets);
  hs->Add(sing_top);
  hs->Add(tt);

  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
		
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.2);
  hs->SetMinimum(1.);
  
  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);

//events:
cout << "ttbar: " << tt->Integral() << endl;
cout << "data: " << data->Integral() << endl;
  
  if(logPlot == true){
  hs->GetXaxis()->SetLimits(MinX, MaxX);
  }else{
  hs->GetXaxis()->SetLimits(MinX, 4.5);
  }
  
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t}", "f");
	tleg2->AddEntry(sing_top, "single top", "f");
	tleg2->AddEntry(wjets , "w+jets", "f");
	tleg2->AddEntry(zjets , "z+jets", "f");
	tleg2->AddEntry(qcd_all , "QCD", "f");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	if(logPlot == true){
  	TText* textPrelim = doPrelim(0.12,0.96, "#geq 0 btags");
	textPrelim->Draw();
  	}else{
	TText* textPrelim = doPrelim(0.2,0.96, "");
	textPrelim->Draw();
	}
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("Plots/TTbarPlusVarAnalysis/Nbtags/");
  
  if(logPlot ==true){
    plotName += Variable+"_Log";  
  }else{
    plotName += Variable;  
  }
 
 
  c1->SaveAs(plotName+".pdf");
  c1->SaveAs(plotName+".png");
  delete c1;
  
  }
  	
}
Esempio n. 16
0
void allCutFlow(){
setTDRStyle();

//loop over variables
for(int i = 0; i<1; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("SingleMu", 1);

//MC
TH1D* tt = getSample("TTJet", lumi*225.2/6920475);

//TH1D* wjets = getSample("W1Jet", lumi*37509/57708550);
TH1D* wjets = getSample("W1Jet", lumi*5400.0/23140779);
TH1D* w2jets = getSample("W2Jets", lumi*1750.0/34041404);
TH1D* w3jets = getSample("W3Jets", lumi*519.0/15536443);
TH1D* w4jets = getSample("W4Jets", lumi*214.0/13370904);

//TH1D* zjets = getSample("DY1JetsToLL", lumi*5745.25/30457954);
TH1D* zjets = getSample("DY1JetsToLL", lumi*561.0/24042904);
TH1D* z2jets = getSample("DY2JetsToLL", lumi*181.0/21835749);
TH1D* z3jets = getSample("DY3JetsToLL", lumi*51.1/11010628);
TH1D* z4jets = getSample("DY4JetsToLL", lumi*23.04/6391785);

//TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",     lumi*34679.3/8500505);
TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",   lumi*7.022e8 * 0.0039/1722678);
TH1D* qcd2 = getSample("QCD_Pt-20to30_MuEnrichedPt5",   lumi*2.87e8 * 0.0065/8486893);
TH1D* qcd3 = getSample("QCD_Pt-30to50_MuEnrichedPt5",   lumi*6.609e7 * 0.0122/8928999);
TH1D* qcd4 = getSample("QCD_Pt-50to80_MuEnrichedPt5",   lumi*8082000.0 * 0.0218/7256011);
TH1D* qcd5 = getSample("QCD_Pt-80to120_MuEnrichedPt5",  lumi*1024000.0 * 0.0395/9030624);
TH1D* qcd6 = getSample("QCD_Pt-120to170_MuEnrichedPt5", lumi*157800.0 * 0.0473/8500505);
TH1D* qcd7 = getSample("QCD_Pt-170to300_MuEnrichedPt5", lumi*34020.0 * 0.0676/7662483);
TH1D* qcd8 = getSample("QCD_Pt-300to470_MuEnrichedPt5", lumi*1757.0 * 0.0864/7797481);
TH1D* qcd9 = getSample("QCD_Pt-470to600_MuEnrichedPt5", lumi*115.2 * 0.1024/2995767);
TH1D* qcd10 = getSample("QCD_Pt-800to1000_MuEnrichedPt5",lumi*3.57 * 0.1033/4047142);
TH1D* qcd11 = getSample("QCD_Pt-1000_MuEnrichedPt5",     lumi*0.774 * 0.1097/3807263);

TH1D* single_t = getSample("T_t-channel", lumi*56.4/3757707);
TH1D* top_t = getSample("T_t-channel", lumi*56.4/3757707);
TH1D* top_tw = getSample("T_tW-channel", lumi*11.1/497395);
TH1D* top_s = getSample("T_s-channel", lumi*3.79/249516);
TH1D* tbar_t = getSample("Tbar_t-channel", lumi*30.7/1934817);
TH1D* tbar_tw = getSample("Tbar_tW-channel", lumi*11.1/493239);
TH1D* tbar_s = getSample("Tbar_s-channel", lumi*1.76/139948);

TH1D* all_MC = getSample("TTJet", lumi*225.2/6920475);

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

  qcd->Add(qcd2);
  qcd->Add(qcd3);
  qcd->Add(qcd4);
  qcd->Add(qcd5);
  qcd->Add(qcd6);
  qcd->Add(qcd7);
  qcd->Add(qcd8);
  qcd->Add(qcd9);
  qcd->Add(qcd10);
  qcd->Add(qcd11);

  hs->Add(qcd);  

  zjets->Add(z2jets);
  zjets->Add(z3jets);
  zjets->Add(z4jets);  
    
  hs->Add(zjets);


  wjets->Add(w2jets);
  wjets->Add(w3jets);
  wjets->Add(w4jets);  

  hs->Add(wjets);
      
  hs->Add(top_t);
  hs->Add(top_tw);
  hs->Add(top_s);
  hs->Add(tbar_t);
  hs->Add(tbar_tw);
  hs->Add(tbar_s);
  
  single_t->Add(top_tw);
  single_t->Add(top_s);
  single_t->Add(tbar_t);
  single_t->Add(tbar_tw);
  single_t->Add(tbar_s);
  
  hs->Add(tt);

TH1D * allMC = (TH1D*) tt->Clone("all");
allMC->Add(wjets);allMC->Add(zjets);allMC->Add(single_t);allMC->Add(qcd);

TH1D* dataEff = new TH1D("cut eff","cut eff",10,0,10);
TH1D* mcEff = new TH1D("cut eff","cut eff",10,0,10);


 TString step[11] = {"Skim" ,"Cleaning and HLT","one isolated #mu", "loose #mu veto", "loose e veto", "#geq 1 jets", "#geq 2 jets","#geq 3 jets", "#geq 4 jets", "#geq1 CSV b-tag", "#geq2 CSV b-tag" };
 		
dataEff->Sumw2();
for(int i =1; i<11; i++){
mcEff->GetXaxis()->SetBinLabel(i, step[i]);
dataEff->SetBinContent(i, data->GetBinContent(i+1)/data->GetBinContent(i));
dataEff->SetBinError(i, sqrt(pow(data->GetBinContent(i+1),2)+pow(data->GetBinContent(i),2)));
mcEff->SetBinContent(i, allMC->GetBinContent(i+1)/allMC->GetBinContent(i));

}  

	
	TCanvas *c2 = new TCanvas("cutflow eff","cutflow eff",600, 500);
  	
	mcEff->SetLineColor(kRed);
	mcEff->Draw();
	dataEff->Draw("Esame");
	
	TLegend *tleg3;
	tleg3 = new TLegend(0.7,0.7,0.8,0.9);
	tleg3->SetTextSize(0.04);
	tleg3->SetBorderSize(0);
	tleg3->SetFillColor(10);
	tleg3->AddEntry(dataEff , "data", "l");
	tleg3->AddEntry(mcEff , "mc", "l");
	
	tleg3->Draw("same");
	
	c2->SaveAs("plots/cutFlow/cutEff_data.png");
	delete c2;

  //draw histos to files
  TCanvas *c1 = new TCanvas("cutflow","cutflow",900, 600);

  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);
  
  if(logPlot ==true)
  hs->SetMinimum(10000.);

  hs->Draw();
  for(int i =0; i<tt->GetNbinsX(); i++)
  hs->GetXaxis()->SetBinLabel(i+1, step[i]);
  
  data->Draw("E same");
  data->SetMarkerStyle(20);
  
//  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(top_t, "single top", "lf");
	tleg2->AddEntry(wjets , "w+jets", "lf");
	tleg2->AddEntry(zjets , "z+jets", "lf");
	tleg2->AddEntry(qcd , "QCD", "lf");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	TText* textPrelim = doPrelim(0.17,0.96);
	textPrelim->Draw();
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("plots/cutFlow/");
  
  if(logPlot ==true){
    plotName += Variable+"_Log";
    plotName += Nbtags+".png";
    
  }else{
    plotName += Variable+"";  
    plotName += Nbtags+".png";
  }
 
 
  c1->SaveAs(plotName);
  delete c1;
 
 //print out
 
    std::cout.setf(std::ios::fixed);
    std::cout.precision(0);

 cout << " & ttbar & wjets & zjets & single-t & qcd & all MC & data " << endl; 
 
 for(int i = 0; i < tt->GetNbinsX(); i++){
 cout << step[i] << " & " << tt->GetBinContent(i+1) << " $\\pm$ " << tt->GetBinError(i+1)  << " & " << wjets->GetBinContent(i+1) << " $\\pm$ " << wjets->GetBinError(i+1)  << " & " << zjets->GetBinContent(i+1) << " $\\pm$ " << zjets->GetBinError(i+1)  << " & " << single_t->GetBinContent(i+1) << " $\\pm$ " << single_t->GetBinError(i+1)  << " & " << qcd->GetBinContent(i+1) << " $\\pm$ " << qcd->GetBinError(i+1)  << " & " << allMC->GetBinContent(i+1) << " $\\pm$ " << allMC->GetBinError(i+1)  << " & " << data->GetBinContent(i+1) << " $\\pm$ " << data->GetBinError(i+1)  << endl;
 
 }
 
  
  }
  	
}
Esempio n. 17
0
void reconstruction(TString infile = "../build/reco_spr.root", 
					int num_events = 10000, 
					char *runtype = "data", 
					double tdiff = 1.5)
{
	gErrorIgnoreLevel = kWarning; // ignore 'Info in...' messages
	gStyle->SetOptFit(1111); // show fit parameters
	gStyle->SetOptStat(0);   // remove stats box
	TGaxis::SetMaxDigits(4); // put axis in scientific notation

	TFile *f = TFile::Open(infile); 
	TTree *t = (TTree*)f->Get("reco"); //Lee's Tree
	TTree *d = (TTree*)f->Get("dirc"); //Roman's Tree

	// set value of lens and alpha from dirc tree
	int lens(0);
	double angle(0),beam(0),yield(0),nph(0);
	d->SetBranchAddress("lens",&lens);
	d->SetBranchAddress("theta",&angle);
	d->SetBranchAddress("beam",&beam);
	d->SetBranchAddress("yield",&yield);
	d->SetBranchAddress("nph",&nph);
	d->GetEntry(0);

	// get time-expt peak value
	TH1D *diff = new TH1D("diff","diff",100,-5,5);
	t->Project("diff","diff");
	double diffmax = diff->GetBinCenter(diff->GetMaximumBin());

	// define cuts and save path
	char *sim_cut  = Form("abs(diff-%f)<%f",diffmax,tdiff);
	char *data_cut = Form("abs(diff-%f)<%f",diffmax,tdiff);
	char *savepath = "../macro/timecuts";

	// define cut and project from tree to histogram w/ proper cuts
	theta = new TH1D("theta","theta",100,0.6,1.0);
	if(runtype=="data") // do all the data things
	{
		// make counter histograms for cut
		TH1D *tof1 = new TH1D("time-tof1","time-tof1",1000,0,1000);
		TH1D *tof2 = new TH1D("time-tof2","time-tof2",1000,0,1000);
		TH1D *trig = new TH1D("time-trig","time-trig",1000,0,1000);

		// project onto counter histograms
		t->Project("time-tof1","time-tof1");
		t->Project("time-tof2","time-tof2");
		t->Project("time-trig","time-trig");
	
		// make cuts w/ counters
		cntrCut(tof1, data_cut, "time-tof1");
		cntrCut(tof2, data_cut, "time-tof2");
		cntrCut(trig, data_cut, "time-trig");
		//cout << "data cut\t" << data_cut << endl;

		/*
		// make counter hists pretty (and distinguishable)
		tof1->SetTitle(data_cut);
		tof1->SetTitleSize(0.5);
		tof1->SetLineColor(kBlue);
		tof2->SetLineColor(kRed);
		trig->SetLineColor(kGreen);

		// draw histograms and save canvas
		char *cname = Form("%s/reco_%s_%d_%d_ccuts.png",
					  savepath,runtype,lens,(int)angle);
		TCanvas *ccanv = new TCanvas();
		gPad->SetLogy();
		tof1->Draw();
		tof2->Draw("same");
		trig->Draw("same");
		ccanv->Print(cname);
		*/

		t->Project("theta","theta",data_cut);
	}
	else
		t->Project("theta","theta",sim_cut);

	// preliminary paramters for fit of theta
	double height = theta->GetMaximum();
	double center = theta->GetBinCenter(theta->GetMaximumBin());
	double sigma  = 0.015;
	double slope  = 1.0;
	double shift  = height/3;

	// define custom fit, set parameters, and fit to data
	TF1 *gaus0 = new TF1("gaus0", "gaus+[3]*x+[4]", 
						 center-0.05, center+0.05);
	gaus0->SetParameters(height,center,sigma,slope,shift);
	gaus0->SetParNames("height","mean","sigma","slope","const");
	theta->Fit("gaus0","QR");
	double truesig = 1000*gaus0->GetParameter("sigma");
	
	// define strings for picture and root file names
	char *namt = Form("theta_{c} lens %d angle %d diff %1.2f",
					  lens,(int)angle,tdiff);
	char *pict = Form("%s/reco_%s_%d_%d_%1.2f.png",
					  savepath,runtype,lens,(int)angle,tdiff);

	/*
	// format histogram for saving
	TCanvas *c1 = new TCanvas();
	c1->cd();
	double max = 1.1*theta->GetMaximum();
	theta->SetTitle("");
	theta->GetXaxis()->SetLabelSize(0.06);
	theta->GetYaxis()->SetLabelSize(0.06);
	theta->GetXaxis()->SetRangeUser(0.61,1);
	theta->GetYaxis()->SetRangeUser(0,max);
	theta->Draw();
	c1->Print(pict);

	// save histogram again without fit parameters
   	gStyle->SetOptFit(0);
	c1->cd();
	theta->Draw();
	pict = Form("%s/reco_%s_%d_%d_%1.2f_nofit.png",
				savepath,runtype,lens,(int)angle,tdiff);
	c1->Print(pict);
	*/

	// print relevant info to screen and file
	char *outnm = Form("../macro/timecut_%s.tsv",runtype);
	ofstream out;
	out.open(outnm, fstream::in | fstream::out | fstream::app);
	out << angle 
		<< "\t" << lens  
		<< "\t" << tdiff
		<< "\t" << truesig
		<< "\t" << yield 
		<< "\t" << nph << endl;
	out.close();
	cout << "\033[1;31m" 
		 << "\nangle:\t" << angle
		 << "\nlens:\t"  << lens
		 << "\ndiff:\t"  << tdiff
		 << "\npeak:\t"  << diffmax
		 << "\nsigma:\t" << truesig
		 << "\nhits/e:\t" << nph
		 << "\nphts/e:\t" << yield 
		 << "\033[0m" <<  endl;
	TFile *tfile = new TFile(Form("timecut_%1.1f_%d_%1.2f.root",
								  angle,lens,tdiff),"create");
	TTree *ttree = new TTree("tcut","tcut");
	ttree->Branch("angle",&angle,"angle/D");
	ttree->Branch("lens",&lens,"lens/I");
	ttree->Branch("tcut",&tdiff,"tcut/D");
	ttree->Branch("sigma",&truesig,"truesig/D");
	ttree->Branch("nph",&yield,"yield/D");

	ttree->Fill();
	ttree->Write();
	tfile->Delete();
}
Esempio n. 18
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
//                                         //
// This one is supposed to make plots for  //
// the paper draft                         //
// *************************************** //
TCanvas* drawPlots::plotAll_VLQ_paperStyle(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, std::vector<TH1D*> signal, TH1D* data, TGraphAsymmErrors* err, bool doLogAxis, std::string extraTag){

   const unsigned int CANVAS_WIDTH  = 720;
   const unsigned int CANVAS_HEIGHT = 750;
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.75;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.09;  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 1.6;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.09;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   //canvas->cd();
   
   SetAtlasStyle();
   gStyle->SetHistLineWidth(1.);
   gStyle->SetErrorX(0);

   err->SetLineColor(kWhite);
   err->SetLineWidth(0);

   // create histogram to store all backgrounds
   TH1D* allBackgrounds;
   bool gotSomething=false;
   for(int c=0; c<signal.size(); c++){
     if(signal[c]){
       allBackgrounds = (TH1D*)signal[c]->Clone("all_backgrounds");
       gotSomething=true;
     }
   }

   if(!gotSomething && data){
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
     gotSomething=true;
   }
   if(!gotSomething){
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }
   }

   if(!gotSomething){
     std::cout << "Error: could not find any background, data, or signal for this plot" << std::endl;
     return canvas;
   }
   
   // set all bins to zero
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
     allBackgrounds->SetBinContent(i,0);

   // go through histos and combine the histograms that need to be combined
   // WZ stays separate, ttV stays separate, all others become "Other bkg"
   TH1D* otherBkgs=0; TH1D* ttbarX=0; TH1D* WZ_Sherpa=0;
   for(int cc=0; cc<histos.size(); cc++){
     if(histos[cc]){
       for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	 double binContent=allBackgrounds->GetBinContent(j)+histos[cc]->GetBinContent(j);
	 allBackgrounds->SetBinContent(j,binContent);
       }
       
       if(names[cc]=="ttbarX")
	 ttbarX=(TH1D*)histos[cc]->Clone("ttbarX_new");
       else if(names[cc]=="WZ_Sherpa")
	 WZ_Sherpa=(TH1D*)histos[cc]->Clone("WZ_new");
       else{

	 if(!otherBkgs)
	   otherBkgs=(TH1D*)histos[cc]->Clone("other_bkg_new");
	 else
	   otherBkgs->Add(histos[cc]);
       }
     }
   }

   // make stack of backgrounds, fill backgrounds histogram
   THStack* Stack = new THStack();
   if(ttbarX){
     ttbarX->SetLineColor(kGray);
     ttbarX->SetFillColor(kGray);
     Stack->Add(ttbarX);
   }
   if(WZ_Sherpa){
     WZ_Sherpa->SetLineColor(kBlue-9);
     WZ_Sherpa->SetFillColor(kBlue-9);
     Stack->Add(WZ_Sherpa);
   }
   if(otherBkgs){
     otherBkgs->SetLineColor(kOrange-2);
     otherBkgs->SetFillColor(kOrange-2);
     Stack->Add(otherBkgs);
   }

   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");

   // create main pad
   const double mainPad_ylow  = 0.3;
   const double mainPad_yhigh = 0.95;
   const double mainPad_xlow = 0.;
   const double mainPad_xhigh = 0.95;
   const double pad_margin_left = 0.2;
   const double pad_margin_right  = 0.02;
   double main_y_max = -99;
   double main_y_min = -99;

   TPad* mainPad = new TPad("main","main",mainPad_xlow,mainPad_ylow,mainPad_xhigh,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   // find max y
   if(allBackgrounds){
     int maxBinBkg = allBackgrounds->GetMaximumBin();
     double bkgYmax = allBackgrounds->GetBinContent(maxBinBkg);
     main_y_max = bkgYmax;
   }
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }
   if(main_y_max < .002) main_y_max = .1;

   if(doLogAxis){
     mainPad->SetLogy();
     main_y_min = 0.07;
     main_y_max*=60;
   }else{
     main_y_min = 0.001;
     main_y_max*=1.6;
   }

   // draw axis
   allBackgrounds->SetMaximum(main_y_max);
   allBackgrounds->SetMinimum(main_y_min);
   std::string title = std::string(";") + axisName + ";Events";
   std::stringstream binw; 
   
   binw<<allBackgrounds->GetBinWidth(1);
   std::string width = binw.str();
   if (axisName.find("GeV") != std::string::npos){
     width += " GeV";
     title += " / "+width;
   }
   allBackgrounds->SetTitle(title.c_str());   
   allBackgrounds->GetYaxis()->SetTitleOffset(1.4);
   allBackgrounds->GetYaxis()->SetTitleSize(0.06);
   allBackgrounds->GetXaxis()->SetTitleOffset(1.2);
   allBackgrounds->GetYaxis()->SetLabelSize(0.04);
   allBackgrounds->GetXaxis()->SetLabelSize(0.04);
   allBackgrounds->Draw("hist");

   // draw stack with error
   Stack->Draw("hist same");
   if(err){
     err->Draw("E2 same");
   }

   // make error histograms for the ratio plot
   TGraphAsymmErrors* ratioErr = tools::getRatio(err, backgroundsForRatio);

   // draw data
   if(data)
      data->Draw("e same");

   // draw signal
   if(signal[0]){
     signal[0]->SetLineStyle(2);
     signal[0]->SetLineColor(kRed+2);//kGreen+3 before
     signal[0]->SetLineWidth(5);
     signal[0]->Draw("hist same");
   }
   if(signal.size() > 1){
     if(signal[1]){
       //signal[1]->SetLineStyle(2);
       signal[1]->SetLineColor(kRed+2);
       signal[1]->SetLineWidth(4);
       signal[1]->Draw("hist same");
     }
     if(signal.size() > 2){
       if(signal[2]){
	 //signal[2]->SetLineStyle(2);
	 signal[2]->SetLineColor(kBlue+2);
	 signal[2]->SetLineWidth(4);
	 signal[2]->Draw("hist same");
       }
     }
   }
   allBackgrounds->Draw("axis same");

   // draw legend
   float leg_height = 0.3;
   float leg_width = 0.2;
   float leg_xoffset = 0.74;
   float leg_yoffset = 0.77;
   
   TLegend* leg = new TLegend(leg_xoffset,leg_yoffset-leg_height/2,leg_xoffset+leg_width,leg_yoffset+leg_height/2);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(52);
   leg->SetTextSize(0.033);
   
   // currently assuming first signal is Tbq (single T production), second is TTS, third is BBS
   leg->AddEntry(data, "data 2012");
   leg->AddEntry(otherBkgs, "Other bkg.", "f");
   leg->AddEntry(WZ_Sherpa, "WZ", "f");
   leg->AddEntry(ttbarX, "t#bar{t}+X", "f");
   if(signal.size()>1){
     if(signal[2])
       leg->AddEntry(signal[2], "B#bar{B} (650 GeV)", "l");
     if(signal[1])
       leg->AddEntry(signal[1], "T#bar{T} (650 GeV)", "l");
   }   
   if(signal[0])
     leg->AddEntry(signal[0], "T#bar{b}q (650 GeV)", "l");
   
   
   leg->AddEntry( err, "Uncertainty", "f");


   leg->Draw("lpe");
   
   ATLAS_LABEL(0.24,0.86,1);
   myText(0.36, 0.86, 1, .05, "Internal");
   char text[]="#sqrt{s}=8 TeV";
   myText(0.55,0.77,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.5, 0.84,1, .04, text_L);
   if(extraTag!=""){
     char tag_txt[extraTag.size()];
     strcpy(tag_txt, extraTag.c_str());
     if(extraTag.size()>15)
       myText(0.7, 0.56, 1, .04, tag_txt);
     else
       myText(0.75, 0.56, 1, .04, tag_txt);
   }
   char text_tri[]="Trilepton";
   myText(0.55, 0.70, 1, .04, text_tri);

   /*
   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   int t;
   char inText[100];
   if(back_int > 10000.)
     t=sprintf(inText, "N_{B} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{B} = %.1f", back_int);
   myText(0.24, 0.6, 1, .04, inText);
   if(data)
     t=sprintf(inText, "N_{D} = %.0f", data->Integral(0,data->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{D} = %.0f", 0.);
   myText(0.24, 0.7, 1, .04, inText);
   */
   canvas->cd();
   
   // Draw Ratio plot
   // 1.6 and .4 are the normal ones
   double ratio_max = 3.2;
   double ratio_min = -.9;
  
   double pad_xlow = 0.;
   double pad_xhigh = 0.95;
   double pad_ylow = 0.0;
   double pad_yhigh = 0.3;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);

   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,0.46,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data)
     ratioPlot = (TH1D*)data->Clone("ratio");
   else if (signal[0]) 
     ratioPlot = (TH1D*)signal[0]->Clone("ratio"); // just for getting the axis
   else if (signal[1])
     ratioPlot = (TH1D*)signal[1]->Clone("ratio");
   else
     return canvas;

   ratioPlot->SetTitle("");
   ratioPlot->Divide(allBackgrounds);
   ratioPlot->GetYaxis()->SetTitle("Data / bkg");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());

   if (data){
     
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double minDeviation=10.;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       double binContent = ratioPlot->GetBinContent(ibin);
       tempDev=0;
       if(binContent>0 && binContent < 10) tempDev = std::abs(binContent-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
       if(tempDev < minDeviation) minDeviation = tempDev;
     }
     if(maxDeviation < 0.6){
       ratio_max = 1.6;
       ratio_min = 0.4;
     }
     else if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     if(minDeviation > 1.5){
       if(minDeviation > 2.)
	 ratio_max = 2.7;
       else
	 ratio_max = 2.2;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }     

   if(ratioPlot->GetXaxis()->GetNdivisions() > ratioPlot->GetNbinsX())
     ratioPlot->GetXaxis()->SetNdivisions(ratioPlot->GetNbinsX());
   if(ratioPlot->GetXaxis()->GetNdivisions() > 11)
     ratioPlot->GetXaxis()->SetNdivisions(11);
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErr->Draw("E2 same");
   }else{ // there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.15,text);
   }
   
   return canvas;
}
Esempio n. 19
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
//                                         //
// This one is supposed to match the plots //
// make by JP                              //
// *************************************** //
TCanvas* drawPlots::plotAll_VLQ(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, std::vector<TH1D*> signal, TH1D* data, TGraphAsymmErrors* err, bool isSignalRegion, bool doLogAxis, std::string channel){

   const unsigned int CANVAS_WIDTH  = 720;
   const unsigned int CANVAS_HEIGHT = 750;
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.75;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.09;  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 1.6;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.09;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   canvas->cd();
   
   SetAtlasStyle();
   gStyle->SetHistLineWidth(1.);
   
   // create histogram to store all backgrounds
   TH1D* allBackgrounds;
   bool gotSomething=false;
   for(int c=0; c<signal.size(); c++){
     if(signal[c]){
       allBackgrounds = (TH1D*)signal[c]->Clone("all_backgrounds");
       gotSomething=true;
     }
   }
   if(!gotSomething && data)
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
   if(!gotSomething){
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }
   }

   if(!gotSomething){
     std::cout << "Error: could not find any background, data, or signal for this plot" << std::endl;
     return canvas;
   }
   
   // set all bins to zero
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
     allBackgrounds->SetBinContent(i,0);
   
   // make stack of backgrounds, fill backgrounds histogram
   THStack* Stack = new THStack();
   for(int b=0; b<histos.size(); b++){
     if(histos[b]){
       if(histos[b]->GetEntries() > 0.){
	 histos[b]->SetLineColor(1);
	 histos[b]->SetFillColor(tools::setColor(names[b]));
	 Stack->Add(histos[b]);
	 for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	   double binContent=allBackgrounds->GetBinContent(j)+histos[b]->GetBinContent(j);
	   allBackgrounds->SetBinContent(j,binContent);
	 }
       }
     }
   } 
   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");

   // create main pad
   const double mainPad_ylow  = 0.3;
   const double mainPad_yhigh = 0.95;
   const double mainPad_xlow = 0.;
   const double mainPad_xhigh = 0.95;
   const double pad_margin_left = 0.2;
   const double pad_margin_right  = 0.02;
   double main_y_max = -99;
   double main_y_min = -99;

   TPad* mainPad = new TPad("main","main",mainPad_xlow,mainPad_ylow,mainPad_xhigh,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   // find max y
   if(allBackgrounds){
     int maxBinBkg = allBackgrounds->GetMaximumBin();
     double bkgYmax = allBackgrounds->GetBinContent(maxBinBkg);
     main_y_max = bkgYmax;
   }
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }
   if(main_y_max < .002) main_y_max = .1;

   if(doLogAxis){
     mainPad->SetLogy();
     main_y_min = 0.007;
     main_y_max*=600;
   }else{
     main_y_min = 0.001;
     main_y_max*=1.6;
   }

   // draw axis
   allBackgrounds->SetMaximum(main_y_max);
   allBackgrounds->SetMinimum(main_y_min);
   std::string title = std::string(";") + axisName + ";events/bin";
   allBackgrounds->SetTitle(title.c_str());   
   allBackgrounds->GetYaxis()->SetTitleOffset(1.4);
   allBackgrounds->GetYaxis()->SetTitleSize(0.06);
   allBackgrounds->GetXaxis()->SetTitleOffset(1.2);
   allBackgrounds->GetYaxis()->SetLabelSize(0.04);
   allBackgrounds->GetXaxis()->SetLabelSize(0.04);
   allBackgrounds->Draw("hist");

   // draw stack with error
   Stack->Draw("hist same");
   if(err){
     err->Draw("E2 same");
   }

   // make error histograms for the ratio plot
   TGraphAsymmErrors* ratioErr = tools::getRatio(err, backgroundsForRatio);

   // draw data
   if(!isSignalRegion && data)
      data->Draw("e same");

   // draw signal
   if(signal[0]){
     signal[0]->SetLineStyle(2);
     signal[0]->SetLineColor(kRed);
     signal[0]->SetLineWidth(5);
     signal[0]->Draw("hist same");
   }
   if(signal.size() > 1){
     if(signal[1]){
       signal[1]->SetLineStyle(2);
       signal[1]->SetLineColor(kOrange+7);
       signal[1]->SetLineWidth(4);
       signal[1]->Draw("hist same");
     }
     if(signal.size() > 2){
       if(signal[2]){
	 signal[2]->SetLineStyle(2);
	 signal[2]->SetLineColor(kPink-6);
	 signal[2]->SetLineWidth(4);
	 signal[2]->Draw("hist same");
       }
     }
   }
   allBackgrounds->Draw("axis same");

   // draw legend
   float leg_height = 0.45;
   float leg_width = 0.2;
   float leg_xoffset = 0.74;
   float leg_yoffset = 0.7;
   
   TLegend* leg = new TLegend(leg_xoffset,leg_yoffset-leg_height/2,leg_xoffset+leg_width,leg_yoffset+leg_height/2);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(52);
   leg->SetTextSize(0.033);
   
   // currently assuming first signal is Tbq (single T production), second is TTS, third is BBS
   if(signal[0])
     leg->AddEntry(signal[0], "Tbq (650 GeV)", "l");
   if(signal.size()>1){
     if(signal[1])
       leg->AddEntry(signal[1], "TT_{S} (650 GeV)", "l");
     if(signal[2])
       leg->AddEntry(signal[2], "BB_{S} (650 GeV)", "l");
   }
   if(!isSignalRegion)
     leg->AddEntry(data, "data 2012");
   for(int q=0; q<histos.size(); q++){
     if(histos[q]){
       if(histos[q]->GetEntries() > 0.)
	 leg->AddEntry(histos[q], plotLists::GetLegendName(names[q]).c_str(), "f");
     }
   }
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.24,0.86,1);
   myText(0.36, 0.86, 1, .05, "Internal");
   char text[]="#sqrt{s}=8 TeV";
   myText(0.55,0.77,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.5, 0.84,1, .04, text_L);
   if(channel!=""){
     char chan_txt[channel.size()-1];
     strcpy(chan_txt, (channel.substr(1)).c_str());
     myText(0.5, 0.7, 1, .06, chan_txt);
   }
   char inText[100];
   int t;
   if(signal[0])
     t=sprintf(inText, "N_{Tbq} = %.1f", signal[0]->Integral(0,signal[0]->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{Tbq} = %.1f", 0.);
   myText(0.24, 0.7, 1, .04, inText);
   if(signal.size()>1){
     if(signal[1])
       t=sprintf(inText, "N_{TTS} = %.1f", signal[1]->Integral(0,signal[1]->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{TTS} = %.1f", 0.);
     myText(0.24, 0.65, 1, .04, inText);
     if(signal.size()>2){
       if(signal[2])
	 t=sprintf(inText, "N_{BBS} = %.1f", signal[2]->Integral(0,signal[2]->GetNbinsX()+1));
       else
	 t=sprintf(inText, "N_{BBS} = %.1f", 0.);
       myText(0.24, 0.6, 1, .04, inText);
     }
   }

   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   if(back_int > 10000.)
     t=sprintf(inText, "N_{B} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{B} = %.1f", back_int);
   myText(0.24, 0.75, 1, .04, inText);
   if(!isSignalRegion){
     if(data)
       t=sprintf(inText, "N_{D} = %.0f", data->Integral(0,data->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{D} = %.0f", 0.);
     myText(0.24, 0.8, 1, .04, inText);
   }
   
   canvas->cd();
   
   // Draw Ratio plot
   double ratio_max = 1.6;
   double ratio_min = 0.4;
  
   double pad_xlow = 0.;
   double pad_xhigh = 0.95;
   double pad_ylow = 0.0;
   double pad_yhigh = 0.3;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);

   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,0.46,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data)
     ratioPlot = (TH1D*)data->Clone("ratio");
   else if (signal[0]) 
     ratioPlot = (TH1D*)signal[0]->Clone("ratio"); // just for getting the axis

   ratioPlot->SetTitle("");
   ratioPlot->Divide(allBackgrounds);
   ratioPlot->GetYaxis()->SetTitle("Data/MC");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());

   if (data){
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       tempDev = std::abs(ratioPlot->GetBinContent(ibin)-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
     }
     if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }     

   if(ratioPlot->GetXaxis()->GetNdivisions() > ratioPlot->GetNbinsX())
     ratioPlot->GetXaxis()->SetNdivisions(ratioPlot->GetNbinsX());
   if(ratioPlot->GetXaxis()->GetNdivisions() > 11)
     ratioPlot->GetXaxis()->SetNdivisions(11);
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(!isSignalRegion && data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErr->Draw("E2 same");
   }else if(isSignalRegion){
     ratioPlot->Draw("axis");
     char text[]="DATA IS BLIND HERE";
     myText(0.4,0.6,1,.15,text);
   }else{ // in this case it is not the signal region but there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.15,text);
   }
   
   return canvas;
}
Esempio n. 20
0
void plotRazor(const string preselection, const string subsample, const string combo, TString algo, TString syst)
{
  //--------------------------------------------------------------------------------------------------------------
  // Settings
  //==============================================================================================================

  const bool doBlind = true;

  // Create output directory 
  const string outputDir("smallrazorplots/"+preselection+"_"+subsample+"_"+combo+"_"+algo);
  gSystem->mkdir(outputDir.c_str(), true);
  CPlot::sOutDir = outputDir;

  //
  // Samples
  // Note: macro assumes samplev[0] is data
  //
  vector<CSample*> samplev;
  //cout <<"preselection = " <<  preselection.c_str() << endl;
  samplev.push_back(new CSample("data",0,0));
  if (preselection.compare("Had")==0) samplev.back()->fnamev.push_back("../razorbits/dummy.root");
 // if (preselection.compare("Had")==0) samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/HTMHT.root");
  if (preselection.compare("MET")==0) samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/MET.root"); 
  if (preselection.compare("Muo")==0 || preselection.compare("Zmm")==0)  samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/SingleMuon.root");
  if (preselection.compare("Ele")==0 || preselection.compare("Zee")==0)  samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/SingleElectron.root");
  if (preselection.compare("Pho")==0) { samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/SinglePhoton.root");
  samplev.push_back(new CSample("QCD", kMagenta - 10, kMagenta - 10));
  samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/QCD.root");
  }
  if (preselection.compare("Pho")!=0) {
    samplev.push_back(new CSample("QCD", kMagenta - 10, kMagenta - 10));
    samplev.back()->fnamev.push_back("../razorbits/QCD.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/QCD.root");
    samplev.push_back(new CSample("Single Top",kBlue - 2,kBlue - 2));
    samplev.back()->fnamev.push_back("../razorbits/T.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/T.root");
    samplev.push_back(new CSample("t#bar{t}",kPink - 2,kPink - 2));
    samplev.back()->fnamev.push_back("../razorbits/TT.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/TT.root");
    samplev.push_back(new CSample("Diboson",kRed - 2,kRed - 2));
    samplev.back()->fnamev.push_back("../razorbits/WW.root");
    samplev.back()->fnamev.push_back("../razorbits/WZ.root");
    samplev.back()->fnamev.push_back("../razorbits/ZZ.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/WW.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/WZ.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/ZZ.root");
    samplev.push_back(new CSample("W+jets",kGreen - 2,kGreen - 2));
    samplev.back()->fnamev.push_back("../razorbits/WHF.root");
    samplev.back()->fnamev.push_back("../razorbits/WLF.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/WHF.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/WLF.root");
    samplev.push_back(new CSample("Z+jets", kAzure - 2, kAzure - 2));
    samplev.back()->fnamev.push_back("../razorbits/ZHF.root");
    samplev.back()->fnamev.push_back("../razorbits/ZLF.root");
    samplev.back()->fnamev.push_back("../razorbits/DYHF.root");
    samplev.back()->fnamev.push_back("../razorbits/DYLF.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/ZHF.root");   
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/ZLF.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/DYHF.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/DYLF.root");
  }
  if (preselection.compare("Pho")==0){
    samplev.push_back(new CSample("#gamma+jets", kAzure + 7, kAzure + 7));
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/GHF.root");
//    samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/GLF.root");
  }
  // if (subsample.compare("SR")==0){   
  //   samplev.push_back(new CSample("????", kBlue, kBlue));
  //   samplev.back()->fnamev.push_back("root://eoscms.cern.ch//store/group/phys_susy/razor/thong/razorbits/????.root");
  // }

  // integrated luminosity to scale MC
  const double LUMI = 12.9;
  
  // histograms for various corrections
  const string cmssw_base = getenv("CMSSW_BASE");

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code
  //==============================================================================================================

  //
  // Declare histograms
  //
  char hname[100];
  vector<TH2Poly*> hPolyMrRsqv;
  vector<TH1D*> hMETv, hMETLogv;
  vector<TH1D*> hHTv, hMHTv;
  vector<TH1D*> hNJetsv;
  vector<TH1D*> hMRv, hRsqv, hdeltaPhiv;
  vector<double> neventsv;
  const Int_t NBINS = 5;
  Double_t edges[NBINS + 1] = {250,300,350,400,500,1000};
  for(unsigned int isam=0; isam<samplev.size(); isam++) 
  {
    sprintf(hname,"hPolyMrRsq_%i",isam);      hPolyMrRsqv.push_back(new TH2Poly(hname,"",60,5050,-0.05,1.75));
  //          hPolyMrRsqv[isam]->Sumw2();

            hPolyMrRsqv[isam]->AddBin(100,0.,200,0.15);
            hPolyMrRsqv[isam]->AddBin(200,0.,300,0.15);
            hPolyMrRsqv[isam]->AddBin(300,0.,400,0.15);
            hPolyMrRsqv[isam]->AddBin(400,0.,600,0.15);
            hPolyMrRsqv[isam]->AddBin(600,0.,1200,0.15);
            hPolyMrRsqv[isam]->AddBin(1200,0.,5000,0.15);
            hPolyMrRsqv[isam]->AddBin(100,0.15,200,0.35);
            hPolyMrRsqv[isam]->AddBin(200,0.15,300,0.35);
            hPolyMrRsqv[isam]->AddBin(300,0.15,400,0.35);
            hPolyMrRsqv[isam]->AddBin(400,0.15,600,0.35);
            hPolyMrRsqv[isam]->AddBin(600,0.15,1200,0.35);
            hPolyMrRsqv[isam]->AddBin(1200,0.15,5000,0.35);
            hPolyMrRsqv[isam]->AddBin(100,0.35,200,0.42);
            hPolyMrRsqv[isam]->AddBin(200,0.35,300,0.42);
            hPolyMrRsqv[isam]->AddBin(300,0.35,400,0.42);
            hPolyMrRsqv[isam]->AddBin(400,0.35,600,0.42);
            hPolyMrRsqv[isam]->AddBin(600,0.35,1200,0.42);
            hPolyMrRsqv[isam]->AddBin(1200,0.35,5000,0.42);
            hPolyMrRsqv[isam]->AddBin(100,0.42,200,0.5);
            hPolyMrRsqv[isam]->AddBin(200,0.42,300,0.5);
            hPolyMrRsqv[isam]->AddBin(300,0.42,400,0.5);
            hPolyMrRsqv[isam]->AddBin(400,0.42,600,0.5);
            hPolyMrRsqv[isam]->AddBin(600,0.42,1200,0.5);
            hPolyMrRsqv[isam]->AddBin(1200,0.42,5000,0.5);
            hPolyMrRsqv[isam]->AddBin(100,0.5,200,0.6);
            hPolyMrRsqv[isam]->AddBin(200,0.5,300,0.6);
            hPolyMrRsqv[isam]->AddBin(300,0.5,400,0.6);
            hPolyMrRsqv[isam]->AddBin(400,0.5,600,0.6);
            hPolyMrRsqv[isam]->AddBin(600,0.5,1200,0.6);
            hPolyMrRsqv[isam]->AddBin(1200,0.5,5000,0.6);
            hPolyMrRsqv[isam]->AddBin(100,0.6,200,0.75);
            hPolyMrRsqv[isam]->AddBin(200,0.6,300,0.75);
            hPolyMrRsqv[isam]->AddBin(300,0.6,400,0.75);
            hPolyMrRsqv[isam]->AddBin(400,0.6,600,0.75);
            hPolyMrRsqv[isam]->AddBin(600,0.6,1200,0.75);
            hPolyMrRsqv[isam]->AddBin(1200,0.6,5000,0.75);
            hPolyMrRsqv[isam]->AddBin(100,0.75,200,0.9);
            hPolyMrRsqv[isam]->AddBin(200,0.75,300,0.9);
            hPolyMrRsqv[isam]->AddBin(300,0.75,400,0.9);
            hPolyMrRsqv[isam]->AddBin(400,0.75,600,0.9);
            hPolyMrRsqv[isam]->AddBin(600,0.75,1200,0.9);
            hPolyMrRsqv[isam]->AddBin(1200,0.75,5000,0.9);
            hPolyMrRsqv[isam]->AddBin(100,0.9,200,1.7);
            hPolyMrRsqv[isam]->AddBin(200,0.9,300,1.7);
            hPolyMrRsqv[isam]->AddBin(300,0.9,400,1.7);
            hPolyMrRsqv[isam]->AddBin(400,0.9,600,1.7);
            hPolyMrRsqv[isam]->AddBin(600,0.9,1200,1.7);
            hPolyMrRsqv[isam]->AddBin(1200,0.9,5000,1.7);
 
//    sprintf(hname,"hMET_%i",isam);            hMETv.push_back(new TH1D(hname,"",100,0,3000));            hMETv[isam]->Sumw2();
//    sprintf(hname,"hMETLog_%i",isam);         hMETLogv.push_back(new TH1D(hname,"",100,0,3000));         hMETLogv[isam]->Sumw2();
    sprintf(hname,"hMET_%i",isam);            hMETv.push_back(new TH1D(hname,"",NBINS,edges));            hMETv[isam]->Sumw2();
    sprintf(hname,"hMETLog_%i",isam);         hMETLogv.push_back(new TH1D(hname,"",NBINS,edges));         hMETLogv[isam]->Sumw2();
    sprintf(hname,"hHT_%i",isam);             hHTv.push_back(new TH1D(hname,"",100,100,600));              hHTv[isam]->Sumw2();
    sprintf(hname,"hMHT_%i",isam);            hMHTv.push_back(new TH1D(hname,"",100,100,1000));            hMHTv[isam]->Sumw2();
    sprintf(hname,"hNJets_%i",isam);          hNJetsv.push_back(new TH1D(hname,"",10,0,10));              hNJetsv[isam]->Sumw2();
    ///sprintf(hname,"halphaT_%i",isam);         halphaTv.push_back(new TH1D(hname,"",20,0,2.5));            halphaTv[isam]->Sumw2();
    //sprintf(hname,"hmindFPhi_%i",isam);       hmindFPhiv.push_back(new TH1D(hname,"",20,0,3.14));         hmindFPhiv[isam]->Sumw2();
    sprintf(hname,"hMR_%i",isam);             hMRv.push_back(new TH1D(hname,"",100,200.,1000.));             hMRv[isam]->Sumw2();
    sprintf(hname,"hRsq_%i",isam);            hRsqv.push_back(new TH1D(hname,"",100,0.2,1.2));             hRsqv[isam]->Sumw2();
    sprintf(hname,"hdeltaPhi_%i",isam);       hdeltaPhiv.push_back(new TH1D(hname,"",60,0,3.14));         hdeltaPhiv[isam]->Sumw2();

    neventsv.push_back(0);
  }
  TH2Poly *hPolyMrRsqMC      = (TH2Poly*) hPolyMrRsqv[0]->Clone("hPolyMrRsq");
  TH1D *hMETMC             = (TH1D*)hMETv[0]->Clone("hMETMC");
  TH1D *hMETLogMC          = (TH1D*)hMETLogv[0]->Clone("hMETLogMC");
  TH1D *hHTMC              = (TH1D*)hHTv[0]->Clone("hHTMC");
  TH1D *hMHTMC             = (TH1D*)hMHTv[0]->Clone("hMHTMC");
  TH1D *hNJetsMC           = (TH1D*)hNJetsv[0]->Clone("hNJetsMC");
  //TH1D *halphaTMC          = (TH1D*)halphaTv[0]->Clone("halphaTMC");
  //TH1D *hmindFPhiMC        = (TH1D*)hmindFPhiv[0]->Clone("hmindFPhiMC");
  TH1D *hMRMC              = (TH1D*)hMRv[0]->Clone("hMRMC");
  TH1D *hRsqMC             = (TH1D*)hRsqv[0]->Clone("hRsqMC");
  TH1D *hdeltaPhiMC        = (TH1D*)hdeltaPhiv[0]->Clone("hdeltaPhiMC");

  // TH1D *hMETSig1           = (TH1D*)hMETv[0]->Clone("hMETSig1");
  // TH1D *hMETSig2           = (TH1D*)hMETv[0]->Clone("hMETSig2");
  // TH1D *hMETSig3           = (TH1D*)hMETv[0]->Clone("hMETSig3");
  // TH1D *hMETSig4           = (TH1D*)hMETv[0]->Clone("hMETSig4");                                                                                                                                      
  // TH1D *hMETSig5           = (TH1D*)hMETv[0]->Clone("hMETSig5");                                                                                                                                      
  // TH1D *hMETSig6           = (TH1D*)hMETv[0]->Clone("hMETSig6"); 

  double neventsMC = 0;
  TFile *infile=0;
  TTree *intree=0;
  // Loop over samples

  for(unsigned int isam=0; isam<samplev.size(); isam++) {
    CSample *sample = samplev[isam];
    cout << "Sample: " << sample->label << endl;
    bool isData    = (isam==0);
    // bool isSignal  = (isam==samplev.size()-1 || isam==samplev.size()-2);
    // bool isSignal1 = (isam==samplev.size()-1);
    // bool isSignal2 = (isam==samplev.size()-2);
    // bool isSignal3 = (isam==samplev.size()-3);
    // bool isSignal4 = (isam==samplev.size()-4);
    // bool isSignal5 = (isam==samplev.size()-5);
    // bool isSignal6 = (isam==samplev.size()-6);
    for(unsigned int ifile=0; ifile<sample->fnamev.size(); ifile++) {
      string infilename = sample->fnamev[ifile];
      cout << " ==> Processing " << infilename << "... "; cout.flush();
      infile = TFile::Open(infilename.c_str()); assert(infile);
      infile->ls();
      intree = (TTree*)infile->Get("Events"); assert(intree);
      fBits  = new RazorBitsLoader(intree,algo,syst,preselection);
      double nevts=0;
      int noweight=0;
      double wgt = 0;
      std::cout << "NEntries: " << intree->GetEntries() << std::endl;
      for(unsigned int ientry=0; ientry<intree->GetEntries(); ientry++) {
        intree->GetEntry(ientry);
	if(!doBlind && subsample.compare("SR")==0 && ientry % 5 != 0) continue;
	if(!fBits->selectJetAlgoAndSize(algo)) continue;
	// common selection
	if(fBits->metfilter!=0)                   continue;
	//preselection
	if(!fBits->passPreSelection(preselection)) continue;
	//selection
	//if(!fBits->passRazorSR(preselection, isData)) continue;
	if(!fBits->passSelection(preselection, subsample, combo, isData)) continue;
	//if(!fBits->passMonojetSelection()) continue;

	// Apply weigths                                                                                                                                                                            
        wgt = 1;
        wgt *= fBits->getWgt(isData,algo,LUMI);

	nevts += wgt;
	noweight++;
	
        neventsv[isam]+=wgt;
        hMETv[isam]            ->Fill(fBits->vmetpt,       wgt);
        hMETLogv[isam]         ->Fill(fBits->vmetpt,       wgt);
        hHTv[isam]             ->Fill(fBits->HT,                              wgt);
        hMHTv[isam]            ->Fill(fBits->MHT,                             wgt);
        hNJetsv[isam]          ->Fill(fBits->njets,                           wgt);
       // halphaTv[isam]         ->Fill(fBits->alphaT,                          wgt);
       // hmindFPhiv[isam]       ->Fill(fBits->mindFPhi,                        wgt);
        hMRv[isam]             ->Fill(fBits->MR,                              wgt);
        hRsqv[isam]            ->Fill(fBits->Rsq,                             wgt);
        hdeltaPhiv[isam]       ->Fill(fBits->deltaPhi,                        wgt);
        hPolyMrRsqv[isam]      ->Fill(fBits->MR, fBits->Rsq, wgt);
	//	if((!isData && subsample.compare("SR")!=0) || (!isData  && !isSignal && subsample.compare("SR")==0)){
	if(!isData){
          neventsMC+=wgt;
          hMETMC            ->Fill(fBits->vmetpt,       wgt);
          hMETLogMC         ->Fill(fBits->vmetpt,       wgt);
	  hHTMC             ->Fill(fBits->HT,                              wgt);
	  hMHTMC             ->Fill(fBits->MHT,                             wgt);
	  hNJetsMC          ->Fill(fBits->njets,                           wgt);
	  //halphaTMC         ->Fill(fBits->alphaT,                          wgt);
	 // hmindFPhiMC       ->Fill(fBits->mindFPhi,                        wgt);
	  hMRMC             ->Fill(fBits->MR,                              wgt);
	  hRsqMC            ->Fill(fBits->Rsq,                             wgt);
	  hdeltaPhiMC       ->Fill(fBits->deltaPhi,                        wgt);
        hPolyMrRsqMC      ->Fill(fBits->MR, fBits->Rsq, wgt);
        }
	// if(!isData){
	//   if(isSignal1) hMETSig1->Fill(fBits->vmetpt,       wgt);
	//   if(isSignal2) hMETSig2->Fill(fBits->vmetpt,       wgt);
	//   // if(isSignal3) hMETSig3->Fill(fBits->vmetpt,       wgt);
	//   // if(isSignal4) hMETSig4->Fill(fBits->vmetpt,       wgt);
	//   // if(isSignal5) hMETSig5->Fill(fBits->vmetpt,       wgt);
        //   // if(isSignal6) hMETSig6->Fill(fBits->vmetpt,       wgt);
	// }

      }
      if (!isData && doBlind) 
      {
        cout << nevts << " " << noweight  << " " << wgt << endl;
      }
      
      delete infile;
      infile=0;
      intree=0;
      }
      

  }
  //
  // Make pull histograms
  //
  TH1D *hMETPull            = makePullHist(hMETv[0],            hMETMC,            "hMETPull",             doBlind);
  TH1D *hMETLogPull         = makePullHist(hMETLogv[0],         hMETLogMC,         "hMETLogPull",          doBlind);
  TH1D *hHTPull             = makePullHist(hHTv[0],             hHTMC,             "hHTPull",              doBlind);
  TH1D *hMHTPull            = makePullHist(hMHTv[0],            hMHTMC,            "hMHTPull",             doBlind);
  TH1D *hNJetsPull          = makePullHist(hNJetsv[0],          hNJetsMC,          "hNJetsPull",           doBlind);
 // TH1D *halphaTPull         = makePullHist(halphaTv[0],         halphaTMC,         "halphaTPull",          doBlind);
 // TH1D *hmindFPhiPull       = makePullHist(hmindFPhiv[0],       hmindFPhiMC,       "hmindFPhiPull",        doBlind);
  TH1D *hMRPull             = makePullHist(hMRv[0],             hMRMC,             "hMRPull",              doBlind);
  TH1D *hRsqPull            = makePullHist(hRsqv[0],            hRsqMC,            "hRsqPull",             doBlind);
  TH1D *hdeltaPhiPull       = makePullHist(hdeltaPhiv[0],       hdeltaPhiMC,       "hdeltaPhiPull",        doBlind);

  //                                                                                                                                                                                                    
  // Calculate significance                                                                                                                                                                               
  //                 
  // vector<float> significance;                                                                                                                                                                                
  // significance.push_back(CalcSig(hMETSig1, hMETMC));
  // significance.push_back(CalcSig(hMETSig2, hMETMC));
  // significance.push_back(CalcSig(hMETSig3, hMETMC));
  // significance.push_back(CalcSig(hMETSig4, hMETMC));
  // significance.push_back(CalcSig(hMETSig5, hMETMC));
  // significance.push_back(CalcSig(hMETSig6, hMETMC));

  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  

  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << endl;
  ofstream txtfile;
  char txtfname[200];
  sprintf(txtfname,"%s/summary.txt",outputDir.c_str());
  txtfile.open(txtfname);
  txtfile << setprecision(2) << fixed;
  float max = samplev.size();
  if (subsample.compare("SR")==0) max = samplev.size()-2;    
  for(unsigned int isam=1; isam<max; isam++) {
    txtfile << setw(35) << samplev[isam]->label;
    txtfile << setw(15) << neventsv[isam] << endl;
  }
  txtfile << "---------------------------------------------"  << endl;
  txtfile << setw(35) << "SM Expected:" << setw(15) << neventsMC << endl;
  if(!doBlind) { txtfile << setw(35) << "Observed:" << setw(15) << neventsv[0] << endl; }
  if(subsample.compare("SR")==0){
    txtfile << "---------------------------------------------"  << endl;
    for(unsigned int isam=max; isam<samplev.size(); isam++) {
      txtfile << setw(35) << samplev[isam]->label;
      txtfile << setw(15) << neventsv[isam] << endl;
      txtfile << setw(35) << "Significance: ";
      //txtfile << setw(15) << significance[samplev.size()-isam-1] << endl;
    }
  }
  //   txtfile << setw(35) << "S/sqrt(B)["+samplev[isam]->label+"]:" << setw(15) << neventsv[isam]/sqrt(neventsMC) << endl;
  txtfile.close();
   //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  
  // Save all into a ROOT file
  char outf[200];
  sprintf(outf,"%s/Output.root",outputDir.c_str());
  TFile outputFile(outf,"recreate");
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0);
  c->cd(1)->SetLeftMargin(0.15);
  c->cd(1)->SetRightMargin(0.07);
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);

  // c->SetTopMargin(0.1);
  // c->SetBottomMargin(0.15);
  // c->SetLeftMargin(0.15);
  // c->SetRightMargin(0.07);
  // c->SetTickx(1);
  // c->SetTicky(1);

  char ylabel[100];

  sprintf(ylabel,"Events / GeV");
  makePlot(c, "metl", "U [GeV]", ylabel, hMETv, samplev, hMETMC, hMETPull, doBlind, LUMI, false, 0.0, -0.03,
           0.1, 2.1*(hMETMC->GetBinContent(hMETMC->GetMaximumBin()))/(hMETMC->GetBinWidth(hMETMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / GeV");
  makePlot(c, "met", "U [GeV]", ylabel, hMETLogv, samplev, hMETLogMC, hMETLogPull, doBlind, LUMI, true, 0.0, -0.03,
           2e-5*(hMETLogMC->GetBinContent(hMETLogMC->GetMaximumBin()))/(hMETLogMC->GetBinWidth(hMETLogMC->GetMaximumBin())), 
	   4e2*(hMETLogMC->GetBinContent(hMETLogMC->GetMaximumBin()))/(hMETLogMC->GetBinWidth(hMETLogMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / GeV");
  makePlot(c, "ht", "H_{T} [GeV]", ylabel, hHTv, samplev, hHTMC, hHTPull, doBlind, LUMI, false, 0.0, -0.03,
           0.1, 2.1*(hHTMC->GetBinContent(hHTMC->GetMaximumBin()))/(hHTMC->GetBinWidth(hHTMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / GeV");
  makePlot(c, "mht", "H_{T}^{miss} [GeV]", ylabel, hMHTv, samplev, hMHTMC, hMHTPull, doBlind, LUMI, false, 0.0, -0.03,
           0.1, 2.1*(hMHTMC->GetBinContent(hMHTMC->GetMaximumBin()))/(hMHTMC->GetBinWidth(hHTMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / %i ",int(hNJetsv[0]->GetBinWidth(1)));
  makePlot(c, "njets", "N_{jets} (AK4)", "Events", hNJetsv, samplev, hNJetsMC, hNJetsPull, doBlind, LUMI, false, 0.0, -0.03,
           0.1, 2.1*(hNJetsMC->GetBinContent(hNJetsMC->GetMaximumBin()))/(hNJetsMC->GetBinWidth(hNJetsMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / GeV");
//  makePlot(c, "alphat", "#alpha_{T} [GeV]", ylabel, halphaTv, samplev, halphaTMC, halphaTPull, doBlind, LUMI, false, 0.0, -0.03,
 //          0.1, 2.1*(halphaTMC->GetBinContent(halphaTMC->GetMaximumBin()))/(halphaTMC->GetBinWidth(halphaTMC->GetMaximumBin())), subsample);

//  sprintf(ylabel,"Events / %.1f ",hmindFPhiv[0]->GetBinWidth(1));
//  makePlot(c, "mindfphi", "#Delta#phi*_{min}", ylabel, hmindFPhiv, samplev, hmindFPhiMC, hmindFPhiPull, doBlind, LUMI, false, -0.4, -0.15,
//           0.1, 2.1*(hmindFPhiMC->GetBinContent(hmindFPhiMC->GetMaximumBin()))/(hmindFPhiMC->GetBinWidth(hmindFPhiMC->GetMaximumBin())), subsample);
  gStyle->SetPaintTextFormat("3.2e");
  sprintf(ylabel,"Events / %.1f ",hMRv[0]->GetBinWidth(1));
  makePlot(c, "mr", "M_{R} [GeV]", ylabel, hMRv, samplev, hMRMC, hMRPull, doBlind, LUMI, false, -0.4, -0.15,
           0.1, 2.1*(hMRMC->GetBinContent(hMRMC->GetMaximumBin()))/(hMRMC->GetBinWidth(hMRMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / %.1f ",hRsqv[0]->GetBinWidth(1));
  makePlot(c, "rsq", "R^{2}", ylabel, hRsqv, samplev, hRsqMC, hRsqPull, doBlind, LUMI, false, -0.4, -0.15,
           0.1, 2.1*(hRsqMC->GetBinContent(hRsqMC->GetMaximumBin()))/(hRsqMC->GetBinWidth(hRsqMC->GetMaximumBin())), subsample);

  sprintf(ylabel,"Events / %.1f ",hdeltaPhiv[0]->GetBinWidth(1));
  makePlot(c, "deltaphi", "#Delta#phi*", ylabel, hdeltaPhiv, samplev, hdeltaPhiMC, hdeltaPhiPull, doBlind, LUMI, false, -0.4, -0.15,
           0.1, 2.1*(hdeltaPhiMC->GetBinContent(hdeltaPhiMC->GetMaximumBin()))/(hdeltaPhiMC->GetBinWidth(hdeltaPhiMC->GetMaximumBin())), subsample);
  
  TCanvas *c2 = MakeCanvas("c2","c2",900,800);
  c2->cd()->SetPad(0,0.3,1.0,1.0);
  c2->cd()->SetTopMargin(0.1);
  c2->cd()->SetBottomMargin(0.17);
  c2->cd()->SetLeftMargin(0.15);
  c2->cd()->SetRightMargin(0.17);
  c2->cd()->SetTickx(1);
  c2->cd()->SetTicky(1);
  makePlotPoly(c2, "PolyMrRsqMC", "M_{R}", "R^{2}", hPolyMrRsqMC, LUMI);
  
  for (unsigned int isam=0; isam<samplev.size(); isam++) 
  {
      std::stringstream ss;
      ss << "PolyMrRsq_" << samplev[isam]->label;
      makePlotPoly(c2, ss.str().c_str(), "M_{R}", "R^{2}", hPolyMrRsqv[isam], LUMI);  
  }

  cout << endl;
  cout << " <> Output saved in " << outputDir << endl;
  cout << endl; 
}
Esempio n. 21
0
// Called once for each event in the main event loop
// Return non-zero to indicate a problem and terminate the event loop
int TemplateCreator::ProcessEntry(TGlobalData* gData, const TSetupData* setup){

  // Prepare a few variables
  std::string bankname, detname;
  PulseIslandList thePulseIslands;
  StringPulseIslandMap::const_iterator it;

  // Loop over each detector
  for(it = gData->fPulseIslandToChannelMap.begin(); it != gData->fPulseIslandToChannelMap.end(); ++it){

    // Get the bank and detector names for this detector
    bankname = it->first;
    detname = setup->GetDetectorName(bankname);

    // See if we already have a converged template for this detector
    if (fConvergedStatuses[detname] == true) {
      continue;
    }

    // Create the pulse candidate finder for this detector
    PulseCandidateFinder* pulse_candidate_finder = new PulseCandidateFinder(detname, fOpts);

    // Create the TemplateFitter that we will use for this channel
    fTemplateFitter = new TemplateFitter(detname, fRefineFactor);

    // Get the TPIs
    thePulseIslands = it->second;
    if (thePulseIslands.size() == 0) continue; // no pulses here..

    // Try and get the template (it may have been created in a previous event)
    std::string template_name = "hTemplate_" + detname;
    TH1D* hTemplate = NULL;
    if (fTemplates.find(detname) != fTemplates.end()) {
      hTemplate = fTemplates[detname];
    }

    // Store a couple of numbers to get an idea of how many successful fits there are
    int& n_fit_attempts = fNFitAttempts[detname]; // number of pulses we try to fit to
    int& n_successful_fits = fNSuccessfulFits[detname];
    int& n_pulses_in_template = fNPulsesInTemplate[detname];

    // Loop through all the pulses
    for (PulseIslandList::iterator pulseIter = thePulseIslands.begin(); pulseIter != thePulseIslands.end(); ++pulseIter) {

      // First we will see how many candidate pulses there are on the TPI
      pulse_candidate_finder->FindPulseCandidates(*pulseIter);
      int n_pulse_candidates = pulse_candidate_finder->GetNPulseCandidates();

      // only continue if there is one pulse candidate on the TPI
      if (n_pulse_candidates == 1) {

	TPulseIsland* pulse = *pulseIter;

        // Add the first pulse directly to the template (although we may try and choose a random pulse to start with)
	if (hTemplate == NULL) {
	  std::string histname = "hTemplate_" + detname;
	  std::string histtitle = "Template Histogram for the " + detname + " channel";

	  int pulse_length = pulse->GetSamples().size();
	  if (pulse->GetPeakSample() >= pulse_length - pulse_length/5.0) {
	    if (Debug()) {
	      std::cout << "TemplateCreator: Pulse #" << pulseIter - thePulseIslands.begin() << " is too close to one end of the island and so won't be used as the first pulse in the template." << std::endl;
	    }
	    continue;
	  }
	  hTemplate = CreateRefinedPulseHistogram(pulse, histname.c_str(), histtitle.c_str(), true);
	  ++n_pulses_in_template;

	  if (Debug()) {
	    std::cout << "TemplateCreator: Adding " << detname << " Pulse #" << pulseIter - thePulseIslands.begin() << " directly to the template" << std::endl;
	  }
	  fTemplates[detname] = hTemplate;
	  continue;
	}

	// Get the samples so we can check for digitiser overflow
	const std::vector<int>& theSamples = (pulse)->GetSamples();
	int n_samples = theSamples.size();

	// Calculate the maximum ADC value for this digitiser
	int n_bits = TSetupData::Instance()->GetNBits(bankname);
	double max_adc_value = std::pow(2, n_bits);

	// Loop through the samples and check for digitizer overflow
	bool overflowed = false;
	for (int i = 0; i < n_samples; ++i) {
	  int sample_value = theSamples.at(i);
	  if (sample_value >= max_adc_value-1 && sample_value <= max_adc_value+1) {
	    if (Debug()) {
	      std::cout << "TemplateCreator: Pulse #" << pulseIter - thePulseIslands.begin() << " has overflowed the digitizer and won't be added to the template" << std::endl;
	    }
	    overflowed = true;
	    break;
	  }
	  else if (sample_value == 0) {
	    if (Debug()) {
	      std::cout << "TemplateCreator: Pulse #" << pulseIter - thePulseIslands.begin() << " has underflowed the digitizer and won't be added to the template" << std::endl;
	    }
	    overflowed = true;
	    break;
	  }
	}
	if (overflowed) {
	  continue; // skip this pulse
	}

	// Create the refined pulse waveform
	TH1D* hPulseToFit = CreateRefinedPulseHistogram(pulse, "hPulseToFit", "hPulseToFit", false);

	// Create some histograms that monitor the progression of the template
	if (fErrorVsPulseAddedHistograms.find(detname) == fErrorVsPulseAddedHistograms.end()) {
	  std::string error_histname = "hErrorVsPulseAdded_" + detname;
	  std::string error_histtitle = "Plot of the Error as each new Pulse is added to the template for the " + detname + " channel";
	  int n_bins = 10000;
	  TH1D* error_hist = new TH1D(error_histname.c_str(), error_histtitle.c_str(), n_bins,0,n_bins);
	  fErrorVsPulseAddedHistograms[detname] = error_hist;
	}

	// all the other pulses will be fitted to the template and then added to it
	// Get some initial estimates for the fitter
	double template_pedestal = hTemplate->GetBinContent(1);
	double template_amplitude;
	double template_time;

	double pulse_pedestal = hPulseToFit->GetBinContent(1);
	double pulse_amplitude;
	double pulse_time;

	double pedestal_offset_estimate = pulse_pedestal; // now we're dealing with actual pulses since we subtract the template_pedestal in the transformation
	double amplitude_scale_factor_estimate;
	double time_offset_estimate;
	if (TSetupData::Instance()->GetTriggerPolarity(bankname) == 1) { 
	  template_amplitude = (hTemplate->GetMaximum() - template_pedestal);
	  template_time = hTemplate->GetMaximumBin() - 1; // go from bin numbering (1, n_samples) to clock ticks (0, n_samples-1)

	  pulse_amplitude = (hPulseToFit->GetMaximum() - pulse_pedestal);
	  pulse_time = hPulseToFit->GetMaximumBin() - 1;

	  amplitude_scale_factor_estimate = pulse_amplitude / template_amplitude;  // estimated scale factor
	  time_offset_estimate = pulse_time - template_time;
	}
	else if (TSetupData::Instance()->GetTriggerPolarity(bankname) == -1) {
	  template_amplitude = (template_pedestal - hTemplate->GetMinimum());
	  template_time = hTemplate->GetMinimumBin() - 1; // go from bin numbering (1, n_samples) to clock ticks (0, n_samples-1)

	  pulse_amplitude = (pulse_pedestal - hPulseToFit->GetMinimum());
	  pulse_time = hPulseToFit->GetMinimumBin() - 1; // go from bin numbering (1, n_samples) to clock ticks (0, n_samples-1)

	  amplitude_scale_factor_estimate = pulse_amplitude / template_amplitude;  // estimated scale factor
	  time_offset_estimate = pulse_time - template_time;
	}

	fTemplateFitter->SetInitialParameterEstimates(pedestal_offset_estimate, amplitude_scale_factor_estimate, time_offset_estimate);
	
	if (Debug()) {
	  std::cout << "TemplateCreator: " << detname << "(" << bankname << "): Pulse #" << pulseIter - thePulseIslands.begin() << ": " << std::endl
		    << "TemplateCreator: Template: pedestal = " << template_pedestal << ", amplitude = " << template_amplitude << ", time = " << template_time << std::endl
		    << "TemplateCreator: Pulse: pedestal = " << pulse_pedestal << ", amplitude = " << pulse_amplitude << ", time = " << pulse_time << std::endl
		    << "TemplateCreator: Initial Estimates: pedestal = " << pedestal_offset_estimate << ", amplitude = " << amplitude_scale_factor_estimate 
		    << ", time = " << time_offset_estimate << std::endl;
	}

	int fit_status = fTemplateFitter->FitPulseToTemplate(hTemplate, hPulseToFit, bankname);
	++n_fit_attempts;
	if (fit_status != 0) {
	  if (Debug()) {
	    std::cout << "TemplateCreator: Problem with fit (status = " << fit_status << ")" << std::endl;
	  }
	  delete hPulseToFit; // delete this here since it is no longer needed
	  continue;
	}
	++n_successful_fits;

	if (Debug()) {
	  std::cout << "Template Creator: Fitted Parameters: PedOffset = " << fTemplateFitter->GetPedestalOffset() << ", AmpScaleFactor = " << fTemplateFitter->GetAmplitudeScaleFactor()
	            << ", TimeOffset = " << fTemplateFitter->GetTimeOffset() << ", Chi2 = " << fTemplateFitter->GetChi2() << ", NDoF = " << fTemplateFitter->GetNDoF() 
		    << ", Prob = " << TMath::Prob(fTemplateFitter->GetChi2(), fTemplateFitter->GetNDoF()) << std::endl << std::endl;
	}

	if (fPulseDebug) {
	  // Print out some templates as we go along
	  if (n_pulses_in_template <= 10 || 
	      (n_pulses_in_template <= 100 && n_pulses_in_template%10 == 0) ||
	      (n_pulses_in_template%100 == 0) ) {
	    std::stringstream newhistname;
	    newhistname << "hTemplate_" << n_pulses_in_template << "Pulses_" << detname;
	    TH1D* new_template = (TH1D*) hTemplate->Clone(newhistname.str().c_str());
	  }
	}

	// Add the pulse to the template (we'll do correct the sample values there)
	AddPulseToTemplate(hTemplate, hPulseToFit, bankname);
	++n_pulses_in_template;
	

	if (fPulseDebug) {
	  // Print out the uncorrected and corrected pulse that has been added to the template

	  // Create the histograms that we will use to plot the corrected and uncorrected pulses
	  std::stringstream histname;
	  histname << template_name << "_Event" << EventNavigator::Instance().EntryNo() << "_Pulse" << pulseIter - thePulseIslands.begin() << "_" << n_pulses_in_template << "Added";
	  TH1D* hUncorrectedPulse = (TH1D*) hPulseToFit->Clone(histname.str().c_str());
	  histname << "_Corrected";
	  TH1D* hCorrectedPulse = (TH1D*) hPulseToFit->Clone(histname.str().c_str());
	  hCorrectedPulse->SetEntries(0); // set entries back to 0
	  
	  double pedestal_error = SetupNavigator::Instance()->GetNoise(bankname);

	  // Loop through the bins of the uncorrected pulse and set the values in the corrected pulse histogram
	  for (int iPulseBin = 1; iPulseBin <= hPulseToFit->GetNbinsX(); ++iPulseBin) {
	    
	    double uncorrected_value = hPulseToFit->GetBinContent(iPulseBin);
	    double corrected_value = CorrectSampleValue(uncorrected_value, template_pedestal);
	    
	    hCorrectedPulse->SetBinContent(iPulseBin +0.5 - fTemplateFitter->GetTimeOffset(), corrected_value); 
	    hCorrectedPulse->SetBinError(iPulseBin +0.5 - fTemplateFitter->GetTimeOffset(), pedestal_error);
	  }
	}

	delete hPulseToFit;

	// we keep on adding pulses until adding pulses has no effect on the template
	bool converged = CheckConvergence(hTemplate, bankname);
	if (converged) {
	  fConvergedStatuses[detname] = true;
	  std::cout << "TemplateCreator: " << detname << " template terminated at iteration " << n_pulses_in_template << std::endl;
	  break; // break from the for loop
	}
      } // end if only one pulse candidate
    } //end for loop through channels
  }

  return 0;
}
Esempio n. 22
0
  // DATA vs MC comparison
void createDataVsMCcompRatio(double intLumi,TFile *fQCD,TFile *fZ,TFile *fW,TFile *fTT,TFile *flm1,TFile *fDATA,TCanvas *cCanvas,int cPad,int maxPads,
			     TString folderName,TString histoName,int rebin,float xMin,float xMax,TString xName, TString yName,bool useLog) {
  

  ostringstream tmpLumi;
  tmpLumi << intLumi;
  TString lumi = tmpLumi.str();
  


  cCanvas->cd(cPad);
  
  if (useLog) { gPad->SetLogy(); }
  
  
  // SM backgrounds
  TH1D *hQCD = plot1Dhisto(intLumi,fQCD,folderName,histoName,kYellow+3,rebin,xMin,xMax,xName,yName,"QCD",true); // hQCD->SetName("hQCD");
  TH1D *hZ   = plot1Dhisto(intLumi,fZ,folderName,histoName,kMagenta,rebin,xMin,xMax,xName,yName,"Z",true); // hQCD->SetName("hQCD");
  TH1D *hW   = plot1Dhisto(intLumi,fW,folderName,histoName,4,rebin,xMin,xMax,xName,yName,"W",true); // hQCD->SetName("hQCD");
  TH1D *hTT  = plot1Dhisto(intLumi,fTT,folderName,histoName,kGreen+2,rebin,xMin,xMax,xName,yName,"TT",true); // hQCD->SetName("hQCD");
  TH1D *hSM  = (TH1D*)hTT->Clone("hSM"); hSM->SetName("hSM");  hSM->Add(hW); hSM->Add(hQCD); hSM->Add(hZ);
  hSM->SetLineWidth(4); hSM->SetLineColor(kGray+3); hSM->SetMarkerSize(0.);
  
  // Data
  TH1D *hData = plot1Dhisto(intLumi,fDATA,folderName,histoName,1,rebin,xMin,xMax,xName,yName,"Data",false); // hQCD->SetName("hQCD");
  hData->SetMarkerSize(1); hData->SetMarkerColor(1); hData->SetMarkerStyle(21);
  
  // Signal
  TH1D *hLM1 = plot1Dhisto(intLumi,flm1,folderName,histoName,2,rebin,xMin,xMax,xName,yName,"LM1",true); // hQCD->SetName("hQCD");


  
  // y-axis range
  if (useLog) { hData->GetYaxis()->SetRangeUser(0.1,30.*(hData->GetBinContent(hData->GetMaximumBin()))); }
  else { hData->GetYaxis()->SetRangeUser(0.1,1.4*(hData->GetBinContent(hData->GetMaximumBin()))); }


  
  // Draw the histograms
  hData->Draw("P E0");
  hSM->Draw("HIST E0 sames");
  hQCD->Draw("HIST E0 sames");
  hZ->Draw("HIST E0 sames");
  hW->Draw("HIST E0 sames");                                                                                                                                                                               
  hTT->Draw("HIST E0 sames");
  hLM1->Draw("HIST E0 sames");                                                                                                                                                                             
  hData->Draw("P E0 sames"); // re-draw to be on top
  
  
  
  // Draw Legend
  TLegend *lSamples = legendRAW();
  lSamples->AddEntry(hData,"DATA","PL");
  lSamples->AddEntry(hQCD,"QCD","FL");
  lSamples->AddEntry(hZ,"Z","FL");
  lSamples->AddEntry(hW,"W","FL");
  lSamples->AddEntry(hTT,"TTbar","FL");
  lSamples->AddEntry(hLM1,"LM1","FL");
  lSamples->AddEntry(hSM,"SM","FL");
  lSamples->Draw("same");
  
  
  
  TLatex *lPreliminary = new TLatex(0.2,0.82,"Preliminary 2011");
  //    TLatex *lIntLumi = new TLatex(0.2,0.89,"#scale[0.8]{#int L dt = " +intLumi+"pb^{-1}, #sqrt{s} = 7 TeV}");
  TLatex *lIntLumi = new TLatex(0.2,0.89,"#scale[0.8]{#int L dt = "+lumi+" pb^{-1}, #sqrt{s} = 7 TeV}");
  lPreliminary->SetNDC();
  lIntLumi->SetNDC();
  lPreliminary->Draw("same");
  lIntLumi->Draw("same");
  
  cCanvas->cd(cPad+maxPads);
  //  cCanvas->cd(cPad+1);
  
  gPad->SetGridx(); gPad->SetGridy();
  TH1D *hRatio = (TH1D*)hData->Clone("hRatio");
  //  hRatio->Sumw2();
  hRatio->Divide(hData,hSM);
  hRatio->GetYaxis()->SetTitle("DATA / MC [SM]");
  hRatio->GetXaxis()->SetTitle("");
  hRatio->GetYaxis()->SetRangeUser(0.,2.);
  hRatio->SetTitleSize(0.1, "XYZ");
  hRatio->SetTitleOffset(0.65, "X");
  hRatio->SetTitleOffset(0.6, "Y");
  hRatio->SetLabelSize(0.08,"XY");
  
  
  
  //Draw a line though the perfectly matching point
  TBox *unity = new TBox(hRatio->GetXaxis()->GetBinLowEdge(hRatio->GetXaxis()->GetFirst()),
			 0.89,hRatio->GetXaxis()->GetXmax(), 1.11);
  unity->SetLineWidth(2);
  //unity.SetLineStyle(Root.kDashed);
  unity->SetLineColor(2);
  unity->SetFillColor(2);
  unity->SetFillStyle(3002);
  unity->Draw();
  
  hRatio->Draw("P E0");
  unity->Draw();
  
  cCanvas->Update();
  
  
} // ~ end of createDataVsMCcompRatio function
Esempio n. 23
0
TF1* fit(float ptmin, float ptmax, int s, int b, int widVar)
{

    static int count=0;
    count++;

  TCanvas* c = new TCanvas(Form("c_%.0f_%.0f",ptmin,ptmax),"",400,400);
  TFile* infile = new TFile(Form("%s/%s_%.0f_%.0f.root",infname.Data(),collisionsystem.Data(),ptmin,ptmax));
  TH1D* h = (TH1D*)infile->Get("h");                    h->SetName(Form("h_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");    hMCSignal->SetName(Form("hMCSignal_%.0f_%.0f",ptmin,ptmax));
    
  TF1* f;  
  TF1* background;
  TF1* bkpi;
  TF1* mass;

  if(b==0) f = new TF1(Form("f%d",count),Form("%s+%s+%s",sig[s].Data(),sig_bkg[s].Data(),bkgerf.Data()), 5.0, 6.0);
  else f = new TF1(Form("f%d",count),Form("%s+%s+%s",sig[s].Data(),bkg[b].Data(),bkgerf.Data()), 5.0, 6.0);

    clean0(h);
    h->Draw();

    double hmin = h->GetBinContent(h->GetMinimumBin());
    double hmax = h->GetBinContent(h->GetMaximumBin());
    double havg = h->Integral();

    double mcmin = hMCSignal->GetBinContent(h->GetMinimumBin());
    double mcmax = hMCSignal->GetBinContent(h->GetMaximumBin());
    double mcavg = hMCSignal->Integral();

    f->SetParLimits(0,0,2*hmax);
    f->SetParLimits(1,5.27,5.29);
    f->SetParLimits(2,0.01,0.05);
    f->SetParLimits(8,0.01,0.05);
    f->SetParLimits(7,0,1);
    f->SetParLimits(6,0,1);
    if(s==1) f->SetParLimits(9,0,1);
    //if(s==2) f->SetParLimits(10,1,10);
    if(b==0 && sigmax[s]==8)
    {
	//f->SetParLimits(9,0.5*hmin,1.5*hmax);
	f->SetParLimits(10,-1000,0);
    }
    if(b==0 && sigmax[s]==10)
    {
	//f->SetParLimits(11,0.5*hmin,1.5*hmax);
	f->SetParLimits(12,-1000,0);
    }
    if(b==3)
    {
	//f->SetParLimits(9,0,1.5*hmax);
	f->SetParLimits(10,-100,0);
    }

    f->SetParLimits(3,0,1000);
    f->FixParameter(4,NPpar[0]);
    f->FixParameter(5,NPpar[1]);

    f->SetParameter(0,100);
    f->SetParameter(1,5.28);
    f->SetParameter(2,0.05);
    f->SetParameter(8,0.03);

    f->FixParameter(1,5.279);
    f->FixParameter(3,0);
    if(s==2) f->FixParameter(7,0);

    if(s>0 && bkgmax[b]>=11) f->FixParameter(11,0);
    if(s>0 && bkgmax[b]>=12) f->FixParameter(12,0); 
 
    h->GetEntries();
    hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
    hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
    f->ReleaseParameter(1);
    f->SetParLimits(1,5.27,5.29);
    hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
    hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
    hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
    hMCSignal->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);

    f->FixParameter(1,f->GetParameter(1));
    f->FixParameter(2,f->GetParameter(2));  
    f->FixParameter(7,f->GetParameter(7)); 
    f->FixParameter(8,f->GetParameter(8));
    f->FixParameter(6,f->GetParameter(6));
    if(sigmax[s]>=9) f->FixParameter(9,f->GetParameter(9));
    if(sigmax[s]>=10) f->FixParameter(10,f->GetParameter(10));

    if(s==2) 
    {
	f->ReleaseParameter(7);
	f->SetParLimits(7,0,1);
    }
 
    if(s>0 && bkgmax[b]>=11) f->ReleaseParameter(11);
    if(s>0 && bkgmax[b]>=12) f->ReleaseParameter(12); 
    f->ReleaseParameter(3);
    f->SetParLimits(3,0,1000);
 
    h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
    h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
    f->ReleaseParameter(1);
    f->SetParLimits(1,5.27,5.29);
    h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
    h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
    h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
    h->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
    
    if(b==0)
    {
	background = new TF1(Form("background%d",count),bkg_new[b].Data(),minhisto,maxhisto);
	background->SetParameter(0,f->GetParameter(sigmax[s]+1));
	background->SetParameter(1,f->GetParameter(sigmax[s]+2));
    }
    else
    {
	background = new TF1(Form("background%d",count),bkg_new[b].Data(),minhisto,maxhisto);
	background->SetParameter(0,f->GetParameter(9));
	background->SetParameter(1,f->GetParameter(10));
	if(bkgmax[b]>=11) background->SetParameter(2,f->GetParameter(11));
	if(bkgmax[b]>=12) background->SetParameter(3,f->GetParameter(12));
    }

    bkpi = new TF1(Form("bpki%d",count),bkgerf_new.Data(),minhisto,maxhisto);
    bkpi->SetParameter(0,f->GetParameter(3));
    bkpi->SetParameter(1,NPpar[0]);
    bkpi->SetParameter(2,NPpar[1]);

    mass = new TF1(Form("fmass%d",count),sig_new[s].Data(),minhisto,maxhisto);
    if(s==0 || s==3) mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(8),f->GetParameter(6));
    if(s==1) mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(8),f->GetParameter(6),f->GetParameter(9));
    if(s==2) mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(8),f->GetParameter(6),f->GetParameter(9),f->GetParameter(10));

    mass->SetParError(0,f->GetParError(0));
    mass->SetParError(1,f->GetParError(1));
    mass->SetParError(2,f->GetParError(2));
    mass->SetParError(3,f->GetParError(7));
    mass->SetParError(4,f->GetParError(8));
    mass->SetParError(5,f->GetParError(6));
    if(sigmax[s]>=9) mass->SetParError(6,f->GetParError(9));
    if(sigmax[s]>=10) mass->SetParError(7,f->GetParError(10));

      f->SetLineColor(kRed);
      f->SetLineWidth(2);

   background->SetLineColor(4);
   background->SetLineStyle(2);
   background->SetLineWidth(3);
   background->SetRange(minhisto,maxhisto);
   
   bkpi->SetFillColor(kGreen+4);
   bkpi->SetFillStyle(3005);
   bkpi->SetLineColor(kGreen+4);
   bkpi->SetLineWidth(3);

   mass->SetLineColor(kOrange-3);
   mass->SetLineStyle(2);
   mass->SetLineWidth(3);
   mass->SetFillColor(kOrange-3);
   mass->SetFillStyle(3002);

  h->SetXTitle("m_{#mu#muK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.0);
  h->GetYaxis()->SetTitleOffset(1.5);
  h->GetXaxis()->SetLabelOffset(0.008);
  h->GetYaxis()->SetLabelOffset(0.008);
  h->GetXaxis()->SetTitleSize(0.060);
  h->GetYaxis()->SetTitleSize(0.060);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.06);
  h->GetYaxis()->SetLabelSize(0.06);
  h->Draw("e");
  
  double axisymin = -0.05;
  h->SetAxisRange(axisymin,h->GetMaximum()*1.2,"Y");
  h->GetXaxis()->SetNdivisions(-50205);
  int ci = TColor::GetColor("#000099");
  h->SetLineColor(ci);
  h->SetStats(0);
  
      h->SetMarkerStyle(20); // 24?
      h->SetMarkerSize(0.8);

   h->Draw("e");
   bkpi->Draw("same");
   background->Draw("same");   
   mass->SetRange(minhisto,maxhisto);
   mass->Draw("same");
   f->Draw("same");

   yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
   yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);

  TLegend* leg = new TLegend(0.55,0.45,0.875,0.76,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.05);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"B^{+} Signal","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->AddEntry(bkpi,"B #rightarrow J/#psi X","f");
  leg->Draw("same");

  TLatex* texCms = new TLatex(0.225,0.87, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  texCms->Draw();

  TLatex* texCol;
  if(collisionsystem=="pp"||collisionsystem=="PP") texCol= new TLatex(0.39,0.94, Form("25.8 pb^{-1} (%s #sqrt{s_{NN}} = 5.02 TeV)","pp"));
  else texCol= new TLatex(0.35,0.94, Form("345 #mub^{-1} (%s #sqrt{s_{NN}} = 5.02 TeV)","PbPb"));
  texCol->SetNDC();
  texCol->SetTextSize(0.05);
  texCol->SetLineWidth(2);
  texCol->SetTextFont(42);
  texCol->Draw();

  TLatex* tex;
  
  tex = new TLatex(0.53,0.85,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.05);
  tex->SetLineWidth(2);
  tex->Draw();
  
  if(centmax>0){
  TString texper="%";
  tex = new TLatex(0.225,0.78,Form("Centrality %.0f-%.0f%s",centmin,centmax,texper.Data()));//0.2612903,0.8425793
  tex->SetNDC();
  tex->SetTextColor(1);
  tex->SetTextFont(42);
  tex->SetTextSize(0.05);
  tex->SetLineWidth(2);
  tex->Draw();
  }

  tex = new TLatex(0.77,0.78,"|y_{lab}| < 2.4");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.05);
  tex->SetLineWidth(2);
  tex->Draw();

  tex = new TLatex(0.30,0.54,"B^{+}");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.06);
  tex->SetLineWidth(2);
  tex->Draw();

    if(widVar==0) 
      c->SaveAs(Form("SystPDF/%s_%s_%s_%.0f_%.0f.pdf",collisionsystem.Data(),signame[s].Data(),bkgname[b].Data(),ptmin,ptmax));
    else
      c->SaveAs(Form("SystPDF/%s_%s_%.0f_%.0f.pdf",collisionsystem.Data(),"widvar",ptmin,ptmax));

    return mass;
}
Esempio n. 24
0
void doPlotsBtag(){
setTDRStyle();

//loop over variables
for(int i = 0; i<2; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("SingleMu", 1);

//MC
TH1D* tt = getSample("TTJet", lumi*225.2/6920475);

TH1D* wjets = getSample("W1Jet", lumi*37509/57708550);
TH1D* w1jets = getSample("W1Jet", lumi*5400.0/23140779);
TH1D* w2jets = getSample("W2Jets", lumi*1750.0/34041404);
TH1D* w3jets = getSample("W3Jets", lumi*519.0/15536443);
TH1D* w4jets = getSample("W4Jets", lumi*214.0/13370904);

TH1D* zjets = getSample("DY1JetsToLL", lumi*5745.25/30457954);
TH1D* z1jets = getSample("DY1JetsToLL", lumi*561.0/24042904);
TH1D* z2jets = getSample("DY2JetsToLL", lumi*181.0/21835749);
TH1D* z3jets = getSample("DY3JetsToLL", lumi*51.1/11010628);
TH1D* z4jets = getSample("DY4JetsToLL", lumi*23.04/6391785);

TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",     lumi*34679.3/8500505);
TH1D* qcd1 = getSample("QCD_Pt-15to20_MuEnrichedPt5",   lumi*7.022e8 * 0.0039/1722678);
TH1D* qcd2 = getSample("QCD_Pt-20to30_MuEnrichedPt5",   lumi*2.87e8 * 0.0065/8486893);
TH1D* qcd3 = getSample("QCD_Pt-30to50_MuEnrichedPt5",   lumi*6.609e7 * 0.0122/8928999);
TH1D* qcd4 = getSample("QCD_Pt-50to80_MuEnrichedPt5",   lumi*8082000.0 * 0.0218/7256011);
TH1D* qcd5 = getSample("QCD_Pt-80to120_MuEnrichedPt5",  lumi*1024000.0 * 0.0395/9030624);
TH1D* qcd6 = getSample("QCD_Pt-120to170_MuEnrichedPt5", lumi*157800.0 * 0.0473/8500505);
TH1D* qcd7 = getSample("QCD_Pt-170to300_MuEnrichedPt5", lumi*34020.0 * 0.0676/7662483);
TH1D* qcd8 = getSample("QCD_Pt-300to470_MuEnrichedPt5", lumi*1757.0 * 0.0864/7797481);
TH1D* qcd9 = getSample("QCD_Pt-470to600_MuEnrichedPt5", lumi*115.2 * 0.1024/2995767);
TH1D* qcd10 = getSample("QCD_Pt-800to1000_MuEnrichedPt5",lumi*3.57 * 0.1033/4047142);
TH1D* qcd11 = getSample("QCD_Pt-1000_MuEnrichedPt5",     lumi*0.774 * 0.1097/3807263);

TH1D* top_t = getSample("T_t-channel", lumi*56.4/3757707);
TH1D* top_tw = getSample("T_tW-channel", lumi*11.1/497395);
TH1D* top_s = getSample("T_s-channel", lumi*3.79/249516);
TH1D* tbar_t = getSample("Tbar_t-channel", lumi*30.7/1934817);
TH1D* tbar_tw = getSample("Tbar_tW-channel", lumi*11.1/493239);
TH1D* tbar_s = getSample("Tbar_s-channel", lumi*1.76/139948);

THStack *hs = new THStack("hs","test");
  if(inclQ == true){
  hs->Add(qcd);
  }else{
  hs->Add(qcd1);
  hs->Add(qcd2);
  hs->Add(qcd3);
  hs->Add(qcd4);
  hs->Add(qcd5);
  hs->Add(qcd6);
  hs->Add(qcd7);
  hs->Add(qcd8);
  hs->Add(qcd9);
  hs->Add(qcd10);
  hs->Add(qcd11);
  }
  
  
  if(inclZ == true){
  hs->Add(zjets);
  }else{
  hs->Add(z1jets);
  hs->Add(z2jets);
  hs->Add(z3jets);
  hs->Add(z4jets);  
  }
  
  if(inclW == true){
  hs->Add(wjets);
  }else{
  hs->Add(w1jets);
  hs->Add(w2jets);
  hs->Add(w3jets);
  hs->Add(w4jets);  
  }
      
  hs->Add(top_t);
  hs->Add(top_tw);
  hs->Add(top_s);
  hs->Add(tbar_t);
  hs->Add(tbar_tw);
  hs->Add(tbar_s);
  
  hs->Add(tt);

  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
		
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.2);

  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);

//events:
cout << "ttbar: " << tt->Integral() << endl;
cout << "data: " << data->Integral() << endl;
  
  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(top_t, "single top", "lf");
	tleg2->AddEntry(wjets , "w+jets", "lf");
	tleg2->AddEntry(zjets , "z+jets", "lf");
	tleg2->AddEntry(qcd , "QCD", "lf");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	TText* textPrelim = doPrelim(0.17,0.96);
	textPrelim->Draw();
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("plots/Control/Btags/");
  
  if(logPlot ==true){
    plotName += Variable+"Test_Log";
    plotName += ".pdf";
    
  }else{
    plotName += Variable;  
    plotName += ".pdf";
  }
 
 
  c1->SaveAs(plotName);
  delete c1;
  
  }
  	
}
TF1* GeneralCorrectionFunction(
								double ChannelRangeMin, double ChannelRangeMax,double ChannelPeakPos ,
								TH2D *h2DInputForCorrection ,
								int LineIndex,
								TString InputType="T10DeriMaxEnergy",
								TString CorrNumber="1",
								double XRangeMin=0, double XRangeMax=300,
								TString FitFuncCorr="pol2",
								double FitCorrRangeMin=10, double FitCorrRangeMax= 270,
								double TresholdForCorrection=10,
								TString FitFuncSlicesString="gaus(0)+[3]+gaus(4)"
								
								
)
{
	h2DInputForCorrection->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
	char buf[60];
	sprintf(buf, "hMaxCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TH1D *hMaxPosManually=new TH1D(buf,"",h2DInputForCorrection->GetNbinsX(),h2DInputForCorrection->GetXaxis()->GetXmin(),h2DInputForCorrection->GetXaxis()->GetXmax());
	sprintf(buf, "hMaxFitCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TH1D *hMaxPosManuallyFit=new TH1D(buf,"",h2DInputForCorrection->GetNbinsX(),h2DInputForCorrection->GetXaxis()->GetXmin(),h2DInputForCorrection->GetXaxis()->GetXmax());
	sprintf(buf, "hGausSigmaCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TH1D *hGausSigmaManually=new TH1D(buf,"",h2DInputForCorrection->GetNbinsX(),h2DInputForCorrection->GetXaxis()->GetXmin(),h2DInputForCorrection->GetXaxis()->GetXmax());
	for(int binX = h2DInputForCorrection->GetXaxis()->FindBin(XRangeMin);binX <= h2DInputForCorrection->GetXaxis()->FindBin(XRangeMax);binX++)
	//for(int binX = h2DInputForCorrection->GetXaxis()->FindBin(200);binX <= h2DInputForCorrection->GetXaxis()->FindBin(200);binX++)
	{
		TH1D *hProfileY =h2DInputForCorrection->ProjectionY("_py",binX,binX);	
		double MaxValue=hProfileY->GetBinCenter(hProfileY->GetMaximumBin());
		
		//hMaxPosManually->SetBinContent(binX, MaxValue);
		//h2DInputForCorrection
		//cout <<hProfileY->GetEntries()<<endl;
		//TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+[3]",MaxValue-20,MaxValue+20);
		//cout << TMath::Max(MaxValue-20,double(ChannelRangeMin)) << "\t" << TMath::Min(MaxValue+20,double(ChannelRangeMax)) << "\t"<<endl;
		TF1* FitFuncGausSlices = new TF1("FitFuncGausSlices","gaus(0)",TMath::Max(MaxValue-20,double(ChannelRangeMin)),TMath::Min(MaxValue+20,double(ChannelRangeMax)));
		FitFuncGausSlices->SetParameters(hProfileY->GetBinContent(hProfileY->GetMaximumBin()),MaxValue,4);
		
		hProfileY->Fit(FitFuncGausSlices,"RNIQ");
		TF1* FitFuncSlices = new TF1("FitFuncSlices",FitFuncSlicesString.Data(),TMath::Max(MaxValue-3*FitFuncGausSlices->GetParameter(2),double(ChannelRangeMin)),TMath::Min(MaxValue+3*FitFuncGausSlices->GetParameter(2),double(ChannelRangeMax)));
		FitFuncSlices->SetParameters(FitFuncGausSlices->GetParameter(0),FitFuncGausSlices->GetParameter(1),FitFuncGausSlices->GetParameter(2),10,10,FitFuncGausSlices->GetParameter(1)-5,5);
		
		FitFuncSlices->SetParLimits(0,FitFuncGausSlices->GetParameter(0)*0.8,FitFuncGausSlices->GetParameter(0)*1.5);
		FitFuncSlices->SetParLimits(1,TMath::Max(FitFuncGausSlices->GetParameter(1)-10,double(ChannelRangeMin)),TMath::Min(FitFuncGausSlices->GetParameter(1)+10,double(ChannelRangeMax)));
		FitFuncSlices->SetParLimits(2,0,FitFuncGausSlices->GetParameter(2)*2);
		FitFuncSlices->SetParLimits(3,0,500);
		FitFuncSlices->SetParLimits(4,0,FitFuncGausSlices->GetParameter(0)*0.3);
		
		FitFuncSlices->SetParLimits(5,TMath::Max(FitFuncGausSlices->GetParameter(1)-10,double(ChannelRangeMin)),TMath::Min(MaxValue-1,double(ChannelRangeMax)));
		FitFuncSlices->SetParLimits(6,0,10);
		hProfileY->Fit(FitFuncSlices,"RINQ");
		//hProfileY->DrawCopy();
		
		//cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetParError(1) <<endl;
		//cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetMaximumX() <<endl;
		hMaxPosManually->SetBinContent(binX, (FitFuncSlices->GetParameter(1))/ChannelPeakPos);
		hMaxPosManually->SetBinError(binX, FitFuncSlices->GetParError(1)/ChannelPeakPos);
		hGausSigmaManually->SetBinContent(binX, FitFuncSlices->GetParameter(2));
		hGausSigmaManually->SetBinError(binX, FitFuncSlices->GetParError(2));
		if(FitFuncSlices->GetParameter(2)<TresholdForCorrection && FitFuncSlices->GetParError(2)<5)
		{
			hMaxPosManuallyFit->SetBinContent(binX, (FitFuncSlices->GetParameter(1))/ChannelPeakPos);
			hMaxPosManuallyFit->SetBinError(binX, FitFuncSlices->GetParError(1)/ChannelPeakPos);
		}
		//hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->SetBinError(binX, FitFuncSlices->GetParameter(2)/ChannelPeakPos);
		hProfileY->Delete();
		//cin.ignore();
	}
	//write histos to file
		
	//sprintf(buf, "hMaxCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	hMaxPosManually->Write(0,TObject::kOverwrite);
	//sprintf(buf, "hGausSigmaCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	hGausSigmaManually->Write(0,TObject::kOverwrite);
	hMaxPosManuallyFit->Write(0,TObject::kOverwrite);
	sprintf(buf, "funcCorr%s_%sNorm_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	//fit corr function and write it to file
	TF1 *funcCorrNorm = new TF1(buf,FitFuncCorr.Data(),FitCorrRangeMin,FitCorrRangeMax);
	funcCorrNorm->SetParameters(1,0,-0);
	
	funcCorrNorm->SetParLimits(0,0.8,1);
	//funcCorrNorm->SetParLimits(2,-1E5,0);
	//if(LineIndex==2)
	//	hMaxPosManuallyFit->Fit(funcCorrNorm,"RBI");
	//else
		hMaxPosManuallyFit->Fit(funcCorrNorm,"RBQI");
	sprintf(buf, "funcCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TF1 *funcCorr = new TF1(buf,FitFuncCorr.Data(),FitCorrRangeMin,FitCorrRangeMax);
	for(int i= 0; i<funcCorr->GetNpar();i++)
	{
		funcCorr->SetParameter(i,funcCorrNorm->GetParameter(i)*ChannelPeakPos);
	}
	//sprintf(buf, "funcCorr%s_%sNorm_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	funcCorrNorm->Write(0,TObject::kOverwrite);
	//sprintf(buf, "funcCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	funcCorr->Write(0,TObject::kOverwrite);
	h2DInputForCorrection->GetYaxis()->UnZoom();
	return funcCorr;
}
Esempio n. 26
0
void pc3matching() {

  TFile *f = TFile::Open("output_perform.root");

  ofstream fout("run16dAupc3matching.h");
  ofstream fout2("run16dAupc3matchingfirst.h");
  fout << "float pc3dphimean[2][2][5][50];" << endl;
  fout << "float pc3dphisigma[2][2][5][50];" << endl;
  fout << "float pc3dzmean[2][2][5][50];" << endl;
  fout << "float pc3dzsigma[2][2][5][50];" << endl;
  fout << "float pc3dphimeanerr[2][2][5][50];" << endl;
  fout << "float pc3dphisigmaerr[2][2][5][50];" << endl;
  fout << "float pc3dzmeanerr[2][2][5][50];" << endl;
  fout << "float pc3dzsigmaerr[2][2][5][50];" << endl;
  fout << " " << endl;
  fout << "void fetchpc3dphidz();" << endl;
  fout << " " << endl;
  fout << "void fetchpc3dphidz() {" << endl;


  float max = 0.0;
  float sigma = 0.0;
  float mean = 0.0;

  for (Int_t iarm = 0; iarm < 2; iarm++) {
    for (Int_t ich = 0; ich < 2; ich++) {
      for (Int_t ipt = 0; ipt < 50; ipt++) {
        for(Int_t ivz = 0; ivz < 5; ivz++) {
           // if(ipt!=3 || iarm!=0 || ich!=0 || ivz!=0)continue;
            cout<<iarm<<" "<<ich<<" "<<ipt<<" "<<ivz<<endl;
          double sigmaerr=0.0;
	  double meanerr=0.0;
          TString ch = "";
            if(ich == 0) ch = "pos";
            if(ich == 1) ch = "neg";
	  TString histname = Form("pc3dphidz_arm%d_%s_z%d_%d",iarm,ch.Data(),ivz*2,ipt);
	  TString histname1 = Form("pc3dphidz_arm%d_%s_z%d_%d",iarm,ch.Data(),ivz*2+1,ipt);
          TH2D *hist = (TH2D*) f->Get(histname);
          TH2D *hist1 = (TH2D*) f->Get(histname1);
          hist->Add(hist1);

          TH1D *dphi = (TH1D*) hist->ProjectionX(Form("pc3dphi_%d_%d_%d_%d",iarm,ich,ipt,ivz));
          TH1D *dz = (TH1D*) hist->ProjectionY(Form("pc3dz_%d_%d_%d_%d",iarm,ich,ipt,ivz));

	  dphi->GetXaxis()->SetRangeUser(-0.1,0.1);

          gStyle->SetOptFit(1101);

          TF1 *fphi1 = new TF1("fphi1","gaus",-0.1,0.1);
          TF1 *fz1 = new TF1("fz1","gaus",-10,10);
          TF1 *fphi2 = new TF1("fphi2","gaus(0)+gaus(3)",-0.1,0.1);
          TF1 *fz2 = new TF1("fz2","gaus(0)+gaus(3)",-10,10);
          TF1 *phi_gaus1 = new TF1("phi_gaus1","gaus",-0.1,0.1);
          TF1 *phi_gaus2 = new TF1("phi_gaus2","gaus",-0.1,0.1);
          TF1 *z_gaus1 = new TF1("z_gaus1","gaus",-10,10);
          TF1 *z_gaus2 = new TF1("z_gaus2","gaus",-10,10);


          Float_t Xbins = dphi->GetNbinsX();
          Float_t Xmin = dphi->GetXaxis()->GetXmin();
          Float_t Xmax = dphi->GetXaxis()->GetXmax();
          mean = (dphi->GetMaximumBin() * (Xmax-Xmin))/Xbins + Xmin;
          max = dphi->GetMaximum();
          fphi1->SetRange(mean-0.01,mean+0.01);
	  fphi1->SetParameters(max,mean);

          TCanvas *c = new TCanvas("c","c",500,500);
	  //dphi->Scale(1./dphi->Integral());
	  dphi->SetTitle("dphi matching");
	  dphi->GetXaxis()->SetTitle("dphi");
	  dphi->GetYaxis()->SetTitle("# tracks");
	  if (iarm == 1 && ich ==0) dphi->Rebin(2);
	//  dphi->Rebin(2);
	  dphi->SetMarkerSize(1);
	  dphi->SetMarkerStyle(kFullCircle);
          dphi->Draw("P");
          dphi->Fit("fphi1","RQ0");
          double dphi_par[6];
          fphi1->GetParameters(dphi_par);
          dphi_par[3] = 0.1*dphi_par[0];
          dphi_par[4] = dphi_par[1];
          dphi_par[5] = 8*dphi_par[2];
          fphi2->SetParameters(dphi_par);
	  fphi2->SetParLimits(3,0,5*dphi_par[3]);
	  fphi2->SetParLimits(4,-1,1);
	  fphi2->SetParLimits(5,0,100*dphi_par[2]);
          dphi->Fit("fphi2","RQ0");
	  fphi2->Draw("same");
          fphi2->GetParameters(dphi_par);
	  meanerr = fphi2->GetParError(1);
	  sigmaerr = fphi2->GetParError(2);

          fout << "pc3dphimean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << dphi_par[1] << ";" << endl;
          fout << "pc3dphisigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  dphi_par[2] << ";" << endl;
          fout << "pc3dphimeanerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << meanerr << ";" << endl;
          fout << "pc3dphisigmaerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  sigmaerr << ";" << endl;
          if(ipt == 2){
            fout2 << "PC3_dphifirst_mean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " << dphi_par[1] << ";" << endl;
            fout2 << "PC3_dphifirst_sigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " <<  dphi_par[2] << ";" << endl;
          }

          phi_gaus1->SetParameters(dphi_par[0],dphi_par[1],dphi_par[2]);
          phi_gaus1->SetLineColor(1);
          phi_gaus1->Draw("SAME");
          phi_gaus2->SetParameters(dphi_par[3],dphi_par[4],dphi_par[5]);
          phi_gaus2->SetLineColor(6);
          phi_gaus2->Draw("SAME");

          //c->Print(Form("matching/pc3dphi_%d_%d_%d_%d.png",iarm,ich,ipt,ivz));
          delete c;



          Float_t Xbins = dz->GetNbinsX();
          Float_t Xmin = dz->GetXaxis()->GetXmin();
          Float_t Xmax = dz->GetXaxis()->GetXmax();
          mean = (dz->GetMaximumBin() * (Xmax-Xmin))/Xbins + Xmin;
          max = dz->GetMaximum();
          fz1->SetRange(mean-4,mean+4);
	  fz1->SetParameters(max,mean);

          TCanvas *c = new TCanvas("c","c",500,500);
	  //dz->Scale(1./dz->Integral());
	  dz->SetTitle("dz matching");
	  dz->GetXaxis()->SetTitle("dz");
	  dz->GetYaxis()->SetTitle("# tracks");
	  dz->Rebin(5);
          dz->SetMarkerSize(1);
	  dz->SetMarkerStyle(kFullCircle);
	  dz->Draw("P");
          dz->Fit("fz1","RQ0");
          double dz_par[6];
          fz1->GetParameters(dz_par);
          dz_par[3] = 0.1*dz_par[0];
          dz_par[4] = dz_par[1];
          dz_par[5] = 7*dz_par[2];
          fz2->SetParameters(dz_par);
	  fz2->SetParLimits(3,0,5*dz_par[3]);
	  fz2->SetParLimits(4,-1,1);
	  fz2->SetParLimits(5,2*dz_par[2],8*dz_par[2]);
          dz->Fit("fz2","RQ0");
	  fz2->Draw("same");
          fz2->GetParameters(dz_par);
	  meanerr = fz2->GetParError(1);
	  sigmaerr = fz2->GetParError(2);


          fout << "pc3dzmean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << dz_par[1] << ";" << endl;
          fout << "pc3dzsigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  dz_par[2] << ";" << endl;
          fout << "pc3dzmeanerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << meanerr << ";" << endl;
          fout << "pc3dzsigmaerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  sigmaerr << ";" << endl;
          if(ipt == 2){
            fout2 << "PC3_dzfirst_mean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " << dz_par[1] << ";" << endl;
            fout2 << "PC3_dzfirst_sigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " <<  dz_par[2] << ";" << endl;
          }

          z_gaus1->SetParameters(dz_par[0],dz_par[1],dz_par[2]);
          z_gaus1->SetLineColor(1);
          z_gaus1->Draw("SAME");
          z_gaus2->SetParameters(dz_par[3],dz_par[4],dz_par[5]);
          z_gaus2->SetLineColor(6);
          z_gaus2->Draw("SAME");

          //c->Print(Form("matching/pc3dz_%d_%d_%d_%d.png",iarm,ich,ipt,ivz));
          delete c;
	}
      }
    }
  }
  fout << "}" << endl;

}
Esempio n. 27
0
//______________________________________________________________________________
void CheckPulsers(const Char_t* loc)
{
    // Some old pedestal checking method.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // number of channels
    Int_t nCh = gReadAR->GetNelements();

    // create arrays
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/pulser.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d_%s", i, gReadAR->GetElement(i)->GetTDC());
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("gausfunc", "gaus", 0 , 200);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();

        // loop over TDCs
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d_%s", j, gReadAR->GetElement(j)->GetTDC());
            fROOTout->cd(t);
            sprintf(t, "ADC%s", gReadAR->GetElement(j)->GetTDC());
            TH1D* h = (TH1D*) f->Get(t);
            
            // fit gaussian to pulser
            Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
            func->SetParameters(1, maxPos, 0.1);
            func->SetRange(maxPos - 2, maxPos + 2);
            h->Fit(func, "RBQ");
            maxPos = func->GetParameter(1);
            
            // save position in file and memory
            pedPos[j][i] = maxPos;

            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            h->Draw();
            
            TLine* tline = new TLine(maxPos, 0, maxPos, 10000);
            tline->SetLineColor(kRed);
            tline->SetLineWidth(2);
            tline->Draw();
            
            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            delete tline;
        }
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating pedestal graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d_%s", j, gReadAR->GetElement(j)->GetTDC());
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
void doControlPlotsMuons(){
setTDRStyle();

//loop over variables
for(int i = 0; i<N; i++){
//double MinX = MinXs[i];
//double MaxX = MaxXs[i];
RebinFact = RebinFacts[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("DoubleMu", 1, Obj, Next, Variable, RebinFact, Systematic);

std::cout << data->Integral() << std::endl;

//MC
TH1D* tt = getSample("TTJet", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* wjets = getSample("WJetsToLNu", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* DY1 = getSample("DYJetsToLL_M-10To50", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* DY2 = getSample("DYJetsToLL_M-50", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* T_tW = getSample("T_tW-channel", 1, Obj, Next, Variable, RebinFact, Systematic);
TH1D* Tbar_tW = getSample("Tbar_tW-channel",1, Obj, Next, Variable, RebinFact, Systematic);

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

  hs->Add(wjets);
  hs->Add(DY1);
  hs->Add(DY2);
  hs->Add(T_tW); 
  hs->Add(Tbar_tW);
  hs->Add(tt); 
  
  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
		
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);

  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);
  
//  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
   
   
  if(logPlot == true){
  c1->SetLogy();
  }	
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.6,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(T_tW, "single-t", "lf");
	tleg2->AddEntry(Tbar_tW, "single-#bar{t}", "lf");	
	tleg2->AddEntry(DY1 , "DYJetsToLL-10To50", "lf");
	tleg2->AddEntry(DY2 , "DYJetsToLL-50", "lf");
	tleg2->AddEntry(wjets , "W+jets", "lf");
	
 	tleg2->Draw("same");	

  TString plotName("plots/Control/PassesCutsUpTo1Btag/Muons/");
  
  if(logPlot == true){
    plotName += Variable+"Log.pdf";
//    plotName += Nbtags+".pdf";
    
  }else{
    plotName += Variable+".pdf";  
//    plotName += Nbtags+".pdf";
  }
 
  TText* textPrelim = doPrelim(0.16,0.96); 
  textPrelim->Draw();
  
  c1->SaveAs(plotName);
  delete c1;
  
  }
  	
}
Esempio n. 29
0
void doit(const char *basename, const int nbins, const double lofit, const double hifit)
{

  // --- read in the data and create a vector with all the values
  // --- note that this code requires an duplicates to have already been cleaned out
  // --- this is automatically fixed with the new version of the DAQ/stepper code
  // --- but the user would do well do double check all output files anyway
  ifstream fin1(Form("TEMP/%s_Unaveraged_VMin1.txt",basename));
  double content;
  vector<double> voltage1;
  while(fin1>>content)
    {
      voltage1.push_back(content);
    }
  fin1.close();
  cout << voltage1.size() << endl;

  // --- do the same for SiPM2
  ifstream fin2(Form("TEMP/%s_Unaveraged_VMin2.txt",basename));
  vector<double> voltage2;
  while(fin2>>content)
    {
      voltage2.push_back(content);
    }
  fin2.close();
  cout << voltage2.size() << endl;

  // --- get the number of entries and the min and max
  int number = voltage1.size();
  double max = *max_element(voltage1.begin(),voltage1.end());
  double min = *min_element(voltage1.begin(),voltage1.end());
  cout << max << endl;
  cout << min << endl;
  // --- use the min and max to calculate a range for the histogram
  double newmax = min*-0.95;
  double newmin = max*-1.05 - newmax*0.1;
  // --- create the new histogram
  TH1D *h1 = new TH1D("h1","",nbins,newmin,newmax);
  TH1D *h2 = new TH1D("h2","",nbins,newmin,newmax);
  TH1D *hsum = new TH1D("hsum","",nbins,2*newmin,2*newmax);
  TH2D *hh1v2 = new TH2D("hh1v2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA = new TH2D("hhSvA","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  TH2D *hh1v2_cut1 = new TH2D("hh1v2_cut1","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA_cut1 = new TH2D("hhSvA_cut1","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  TH2D *hh1v2_cut2 = new TH2D("hh1v2_cut2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA_cut2 = new TH2D("hhSvA_cut2","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  vector<double> sum;
  vector<double> asym;
  // --- loop over the vector to fill the histogram
  for(int i=0; i<number; i++)
    {
      // --- SiPM1
      h1->Fill(-voltage1[i]);
      // --- SiPM2
      h2->Fill(-voltage2[i]);
      // --- SiPM1 vs SiPM2
      hh1v2->Fill(-voltage1[i],-voltage2[i]);
      // --- sum vs asymmetry
      double tempsum = -voltage1[i] + -voltage2[i];
      double tempasym = (voltage1[i] - voltage2[i]) / (-voltage1[i] + -voltage2[i]);
      hsum->Fill(tempsum);
      hhSvA->Fill(tempsum,tempasym);
      sum.push_back(tempsum);
      asym.push_back(tempasym);
      // --- now do some cuts...
      if(fabs(tempasym)<0.4)
	{
	  hh1v2_cut1->Fill(-voltage1[i],-voltage2[i]);
	  hhSvA_cut1->Fill(tempsum,tempasym);
	}
      if((voltage1[i]<(voltage2[i]+20*peconvert))&&(voltage2[i]<(voltage1[i]+20*peconvert)))
	{
	  hh1v2_cut2->Fill(-voltage1[i],-voltage2[i]);
	  hhSvA_cut2->Fill(tempsum,tempasym);
	}
    }

  // --- make a canvas and draw the histogram
  TCanvas *c1 = new TCanvas("c1","",800,800);

  // --- rescale the histograms from volts to photoelectrons
  h1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  h1->GetXaxis()->SetTitle("Number of photoelectrons");
  h1->GetYaxis()->SetTitle("Counts");

  // --- define Landau function and draw
  // --- don't fit yet because the data have tons of ugly low voltage1 background
  double height = 1049;
  double mu = 23;
  double sigma = 3;
  //TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",newmin/peconvert,newmax/peconvert);
  TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",2*newmin/peconvert,2*newmax/peconvert);
  fun->SetParameter(0,height);
  fun->SetParameter(1,mu);
  fun->SetParameter(2,sigma);


  double bgscale = 650; // guess...





  c1->SetLogy(0);
  c1->Clear();
  hh1v2->Draw("colz");
  hh1v2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2->GetYaxis()->SetTitle("#pe SiPM2");
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_log.pdf",basename));

  hhSvA->Draw("colz");
  hhSvA->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA->GetXaxis()->SetTitle("Sum");
  hhSvA->GetYaxis()->SetTitle("Asymmetry");
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_log.pdf",basename));


  // --- now for some cuts...

  c1->SetLogz(0);
  hh1v2_cut1->Draw("colz");
  hh1v2_cut1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut1->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut1->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2_cut1->GetYaxis()->SetTitle("#pe SiPM2");
  TLatex *tex1 = new TLatex(0.2,0.8,"|Asymmetry|<0.4");
  tex1->SetTextSize(0.05);
  tex1->SetNDC(kTRUE);
  tex1->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.pdf",basename));

  hhSvA_cut1->Draw("colz");
  hhSvA_cut1->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA_cut1->GetXaxis()->SetTitle("Sum");
  hhSvA_cut1->GetYaxis()->SetTitle("Asymmetry");
  tex1->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.pdf",basename));




  c1->SetLogz(0);
  hh1v2_cut2->Draw("colz");
  hh1v2_cut2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut2->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2_cut2->GetYaxis()->SetTitle("#pe SiPM2");
  TLatex *tex2 = new TLatex(0.2,0.8,"SiPMA < SiPMB + 20");
  tex2->SetTextSize(0.05);
  tex2->SetNDC(kTRUE);
  tex2->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.pdf",basename));

  hhSvA_cut2->Draw("colz");
  hhSvA_cut2->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA_cut2->GetXaxis()->SetTitle("Sum");
  hhSvA_cut2->GetYaxis()->SetTitle("Asymmetry");
  tex2->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.pdf",basename));



  hsum->SetLineColor(kBlack);
  hsum->SetLineWidth(2);
  hsum->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  //hsum->GetXaxis()->SetRangeUser(0.0,120.0);
  hsum->GetXaxis()->SetTitle("Number of photoelectrons SiPM1+SiPM2");
  hsum->Draw();
  c1->Print(Form("Cosmics/%s_temp.png",basename));
  c1->Print(Form("Cosmics/%s_temp.pdf",basename));
  hsum->SetMaximum(30);
  c1->Print(Form("Cosmics/%s_templow.png",basename));
  c1->Print(Form("Cosmics/%s_templow.pdf",basename));
  c1->SetLogy();
  hsum->SetMaximum(1.1*h1->GetBinContent(hsum->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templog.png",basename));
  c1->Print(Form("Cosmics/%s_templog.pdf",basename));


  // ---------------------------------------------------------
  bgscale = 100;
  h1->Fit(fun,"","",lofit,hifit);
  fun->SetLineColor(kRed);
  fun->SetLineWidth(2);
  fun->Draw("same");

  cout << fun->GetChisquare() << "/" << fun->GetNDF() << endl;

  c1->SetLogy(0);
  c1->Print(Form("Cosmics/%s_tempfit.png",basename));
  c1->Print(Form("Cosmics/%s_tempfit.pdf",basename));
  h1->SetMaximum(175);
  c1->Print(Form("Cosmics/%s_templowfit.png",basename));
  c1->Print(Form("Cosmics/%s_templowfit.pdf",basename));
  h1->SetMaximum(100);
  c1->Print(Form("Cosmics/%s_tempLOWfit.png",basename));
  c1->Print(Form("Cosmics/%s_tempLOWfit.pdf",basename));
  c1->SetLogy(1);
  h1->SetMaximum(1.1*h1->GetBinContent(h1->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templogfit.png",basename));
  c1->Print(Form("Cosmics/%s_templogfit.pdf",basename));

  c1->Clear();
  h1->Draw();
  double hax = fun->GetParameter(0);
  double mux = fun->GetParameter(1);
  double six = fun->GetParameter(2);
  fun->SetParameter(0,0.95*hax);
  fun->SetParameter(1,mux);
  fun->SetParameter(2,1.1*six);
  //fun->Draw("same");
  //h1->Fit(simplefun,"","",0,60);

  TF1 *fun2 = new TF1("fun2","([0]/sqrt(6.28))*TMath::Exp(-0.5*((x-[1])/[2] + TMath::Exp(-(x-[1])/[2])))",2*newmin/peconvert,2*newmax/peconvert);
  // fun2->SetParameter(0,hax);
  // fun2->SetParameter(1,mux);
  // fun2->SetParameter(2,six);
  // fun2->SetParameter(0,93);
  // fun2->SetParameter(1,35);
  // fun2->SetParameter(2,5);
  fun2->SetParameter(0,93);
  fun2->SetParameter(1,500);
  fun2->SetParameter(2,100);
  //fun2->SetLineColor(kBlack);

  h1->Fit(fun2,"","",lofit,hifit);
  fun2->Draw("same");

  cout << fun2->GetChisquare() << "/" << fun2->GetNDF() << endl;

  double par1 = fun2->GetParameter(1);
  TLine line(par1,0,par1,0.24*fun2->GetParameter(0));
  line.Draw();

  c1->SetLogy(0);
  c1->Print(Form("Cosmics/%s_tempffit.png",basename));
  c1->Print(Form("Cosmics/%s_tempffit.pdf",basename));
  h1->SetMaximum(25);
  c1->Print(Form("Cosmics/%s_templowffit.png",basename));
  c1->Print(Form("Cosmics/%s_templowffit.pdf",basename));
  h1->SetMaximum(0.3*fun2->GetParameter(0));
  TLatex *tex = new TLatex(0.6,0.8,Form("MPV = %.1f #pm %.1f",fun2->GetParameter(1),fun2->GetParError(1)));
  tex->SetNDC();
  tex->SetTextSize(0.05);
  tex->Draw();
  //h1->GetXaxis()->SetRangeUser(0.0,130.0); // new...
  c1->Print(Form("Cosmics/SmallTileCosmics_%s_tempLOWffit.png",basename));
  c1->Print(Form("Cosmics/SmallTileCosmics_%s_tempLOWffit.pdf",basename));
  c1->SetLogy(1);
  h1->SetMaximum(1.1*h1->GetBinContent(h1->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templogffit.png",basename));
  c1->Print(Form("Cosmics/%s_templogffit.pdf",basename));



}
int main(int argc, char* argv[]) {

  std::string outputDir = "Plot";                 
  mkdir(outputDir.c_str(), 0777); 

  TString dataFileName_DoubleMu;
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts_pTCut10GeV_FinerPtBin_DoubleMu.root");
  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts_pTCut10GeV_ChangedEtaPtBin_DoubleMu.root");
  TFile* dataFile_DoubleMu = TFile::Open(dataFileName_DoubleMu);
  if (dataFile_DoubleMu) {
    std::cout << "Opened data file '" << dataFileName_DoubleMu << "'." << std::endl;
  }
  TString dataFileName_HT450;
  //  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts_pTCut10GeV_FinerPtBin_HT450.root");
  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts_pTCut10GeV_ChangedEtaPtBin_HT450.root");
  TFile* dataFile_HT450 = TFile::Open(dataFileName_HT450);
  if (dataFile_HT450) {
    std::cout << "Opened data file '" << dataFileName_HT450 << "'." << std::endl;
  }

  gErrorIgnoreLevel = kWarning;

  //////////////////////// disegno pTBias 1D
  EtaBinning mEtaBinning;
  size_t etaBinningSize = mEtaBinning.size();
  PtBinning mPtBinning;
  size_t pTBinningSize = mPtBinning.size();

  cout<< etaBinningSize << endl;

  for (size_t ii = 0; ii < etaBinningSize; ii++) {
    for (size_t jj = 0; jj < pTBinningSize; jj++) {

      std::string etaName = mEtaBinning.getBinName(ii);
      std::pair<float, float> ptBins = mPtBinning.getBinValue(jj);	       
      
      std::string HistoName = TString::Format("AK4_pTBias_%s_pT_%i_%i", etaName.c_str(), (int) ptBins.first, (int) ptBins.second ).Data();

      cout<< HistoName.c_str() << endl;

      TH1D *h;
      if( jj < 2){ // pT<300
	h = (TH1D*)dataFile_DoubleMu->Get( HistoName.c_str() );
	cout << " Lo prendo dal DoubleMu" << endl;
      }else if(jj < 6){ // pT<700 due to low statistics
	h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
	cout << " Lo prendo dal HT450" << endl;
      }else{ continue; }
      
      TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
      h -> SetMarkerStyle(20);
      h -> SetMarkerSize(1.5);
      h->GetXaxis()->SetRangeUser(-0.4, 0.4);
      h -> Draw();
      c1->SaveAs( Form("Plot/%s.png", HistoName.c_str() ) );

      /////////////////////////////////////////////////

      int pTMin = ptBins.first;
      int pTMax = ptBins.second;
      double pTMean= (pTMin + pTMax) /2. ;
      double BinMax      = h->GetMaximumBin();
      double pTBiasMax      = h->GetMaximum();
      double pTBias      = h->GetBinCenter(BinMax);
      double pTBiasErr  = h->GetBinError(BinMax);

      cout<< "pT mean = "<< pTMean <<endl;
      cout<< "pT Bias maximum = "<< pTBiasMax <<endl;
      cout<< "pT Bias = "<< pTBias <<endl;
      cout<< "sigma(pT Bias) = "<< pTBiasErr <<endl;


      std::string TGraphName = TString::Format("Test_AK4_pTBias_vs_pT_etabin_%i", ii).Data();
      CreateAndFillUserTGraph(TGraphName.c_str(), jj, pTMean, pTBias, 0, 0);

    }
  }

  for(int ii = 1; ii < (etaBinningSize+1) ; ii++){ 
   
    std::string TGraphName = TString::Format("Test_AK4_pTBias_vs_pT_etabin_%i", ii).Data();
    map<std::string , TGraphErrors*>::iterator nh_h = userTGraphs_.find( TGraphName );
    if( nh_h == userTGraphs_.end()) continue;

    TF1* functionFit = new TF1( "functionFit", "-[0]*(log(x)*log(x)) + [1]*log(x)", 30,700); // quadratica log
    // functionFit->SetParLimits(0, 0., 10000);
    // functionFit->SetParLimits(1, 0., 10000);

    TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
    nh_h->second->SetMarkerStyle(20);
    nh_h->second->SetMarkerSize(1.5);
    //    nh_h->second->Fit(functionFit, "R");
    nh_h->second->Draw("ZAP");
    c1->SaveAs( Form("Plot/%s.png", TGraphName.c_str() ) );
  }




  /////////////////////////////////////////////////////////////////////
  // creating TGraph
  // PtBinning mPtBinning;
  //  size_t pTBinningSize = mPtBinning.size();

  for(int ii = 1; ii < (etaBinningSize+1) ; ii++){ //# bins in eta
    cout<< "Bin in eta # "<< ii << endl;
    for(size_t jj=0; jj < pTBinningSize; jj++){

      std::pair<float, float> ptBins = mPtBinning.getBinValue(jj);	       
      std::string Histo = TString::Format("AK4_pTBias_vs_Eta_VariableBin_pT_%i_%i", (int) ptBins.first, (int) ptBins.second ).Data();
      cout<< Histo.c_str() << endl;

      int pTMin = ptBins.first;
      int pTMax = ptBins.second;
      double pTMean= (pTMin + pTMax) /2. ;

      TH1D *h;
      if( jj < 2){ // pT<300
	h = (TH1D*)dataFile_DoubleMu->Get( Histo.c_str() );
	cout << " Lo prendo dal DoubleMu" << endl;
      }else if(jj < 6){ // pT<700 due to low statistics
	h = (TH1D*)dataFile_HT450->Get( Histo.c_str() );
	cout << " Lo prendo dal HT450" << endl;
      }else{ continue; }
      
      TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
      h->SetTitle("");
      h->SetXTitle("#eta");
      h->SetYTitle("pTBias");
      h->SetStats(0);
      h -> SetMarkerStyle(20);
      h -> SetMarkerSize(1.5);
      //      h->GetXaxis()->SetRangeUser(-0.4, 0.4);
      h -> Draw();
      c1->SaveAs( Form("Plot/%s.png", Histo.c_str() ) );


      double pTBias      = h->GetBinContent(ii);
      double pTBiasErr = h->GetBinError(ii);

      cout<< "pT mean = "<< pTMean <<endl;
      cout<< "pT Bias = "<< pTBias <<endl;
      cout<< "sigma(pT Bias) = "<< pTBiasErr <<endl;

      std::string TGraphName = TString::Format("AK4_pTBias_vs_pT_etabin_%i", ii).Data();
      CreateAndFillUserTGraph(TGraphName.c_str(), jj, pTMean, pTBias, 0, pTBiasErr);

    }// for sui pT
  }// for bin in eta
  /////////////////////////////// costruiti i TGraph da fittare

  for(int ii = 1; ii < (etaBinningSize+1) ; ii++){ 
   
    std::string TGraphName = TString::Format("AK4_pTBias_vs_pT_etabin_%i", ii).Data();
    map<std::string , TGraphErrors*>::iterator nh_h = userTGraphs_.find( TGraphName );
    if( nh_h == userTGraphs_.end()) continue;

    //    TF1* functionFit = new TF1( "functionFit", "[0] + [1]* TMath::Log(x)", 30,700); // linearLog
    TF1* functionFit = new TF1( "functionFit", "-[0]*(log(x)*log(x)) + [1]*log(x)", 30,700); // quadratica log
    //    TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)) + [1]*log(x)", 30,700); // quadratica log
    // TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)) + [1]*log(x) +[2]", 30,700); // quadratica log

    // functionFit->SetParLimits(0, 0., 10000);
    // functionFit->SetParLimits(1, 0., 10000);

    TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
    nh_h->second->SetMarkerStyle(20);
    nh_h->second->SetMarkerSize(1.5);
    //    nh_h->second->Fit(functionFit, "R");
    nh_h->second->Draw("ZAP");
    c1->SaveAs( Form("Plot/%s.png", TGraphName.c_str() ) );
    
    double Par0       =  functionFit->GetParameter(0);
    double Par1       =  functionFit->GetParameter(1);
    //    double Par2       =  functionFit->GetParameter(2);
    cout<< "Par 0 = " << Par0 << endl;
    cout<< "Par 1 = " << Par1 << endl;
    //    cout<< "Par 2 = " << Par2 << endl;

    for(int jj=0; jj < binnum; jj++){
      
      int pTMin = pTMeanArray[jj];
      int pTMax = pTMeanArray[jj+1];
      double pTMean= (pTMin + pTMax) /2. ;
      cout<<"pT Mean = " << pTMean <<endl;

      //   double pTBiasFit = Par0 + Par1* TMath::Log(pTMean);
      //      double pTBiasFit = -Par0*(log(pTMean)*log(pTMean)) + Par1*log(pTMean) +Par2;
      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)) + Par1*log(pTMean);
      cout<<"pT Bias from fit = " << pTBiasFit <<endl;

      Histo_Corrections->SetBinContent(ii, jj+1, pTBiasFit);

    } //pT bin
  } // eta bin


    TCanvas *c2 = new TCanvas("c2", "c2", 900, 800);
    Histo_Corrections->SetStats(0);
    gStyle->SetPalette(55);
    Histo_Corrections->SetContour(100);
    Histo_Corrections->Draw("colz");
    c2->SetRightMargin(0.13);
    c2->SaveAs("Plot/Corrections.png");


    TFile* outputFile= new TFile("Corrections_JEC_HLT_v7.root","RECREATE");
    outputFile->cd();
    Histo_Corrections -> Write();
    outputFile->Close();


    return 0;
  
}