TCanvas* overlay_Merged_RecoSmeared(const vector<string>& folders, 
								const hist_t& h
								)
{

	TLegend *leg  = new TLegend(0.6,0.65,0.9,0.9);
	leg->SetTextFont(42);
	vector<TH1*> hists;
	
	vector<string> jetcoll;
	jetcoll.push_back("reco");
	jetcoll.push_back("gen");
	jetcoll.push_back("smeared");

	stringstream title;
	const string njets("3-5");
	//const string eta("2.5");
	const string eta("5.0");
	title << njets
			<< " Jets, MHT from Jets with P_{T}>30 GeV, |#eta |<" 
			<< eta << ", L = 10 fb^{-1}" << ";" << h.title ;

	for (unsigned j=0; j< jetcoll.size(); ++j)
	{
		TH1* Hist = 0;
		for (unsigned i = 0; i < folders.size(); ++i)
		{
			stringstream histname;
			histname << folders.at(i) << "/" << jetcoll.at(j) << h.name;
			cout << __LINE__ << ": Looking for hist: " << histname.str().c_str() << endl;
			TH1* htemp = GetHist(histname.str());
			
			if (Hist == 0) Hist = htemp;
			else Hist->Add(htemp);
		}
		
		Hist->Rebin(h.rebin);
		Hist->SetTitle(title.str().c_str());
		Hist->SetMarkerStyle(20+j);
		Hist->SetLineWidth(2);
		Hist->SetStats(0);

		stringstream legname;
		if (j==0) 
		{
			legname << "Reco"; 
		} else if (j==1) 
		{
			legname << "Gen"; 
			Hist->SetLineColor(kBlue);
			Hist->SetMarkerColor(kBlue);
		} else if (j==2)
		{
			legname << "Smeared"; 
			Hist->SetLineColor(kRed);
			Hist->SetMarkerColor(kRed);
		}

		const double sum = Hist->Integral(); 
		legname << " (" << sum << ")";
		if (j!=1) leg->AddEntry(Hist, legname.str().c_str());

		hists.push_back(Hist);

	} //end jetcoll
	
	TH1* ratio = dynamic_cast<TH1*> (hists.at(2)->Clone("ratio"));
	ratio->GetYaxis()->SetTitle("Smeared/Reco");
	ratio->SetTitle("");
	ratio->Divide(hists.at(0));
	ratio->GetYaxis()->SetRangeUser(-0.01,2.01);
	//ratio->SetTickLength (+0.01,"Y");

   //TCanvas *c1 = new TCanvas("c1", "c1",15,60,550,600);
   TCanvas *c1 = new TCanvas("c1");
   c1->Range(0,0,1,1);
   c1->SetBorderSize(2);
   c1->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	c1_1->SetLogy();
   
	hists.at(0)->GetYaxis()->CenterTitle(1);
	hists.at(0)->SetLabelFont(42,"XYZ");
	hists.at(0)->SetTitleFont(42,"XYZ");
	hists.at(0)->GetYaxis()->SetTitleOffset(0.8);
	hists.at(0)->SetLabelSize(0.05,"XYZ");
	hists.at(0)->SetTitleSize(0.06,"XYZ");
   hists.at(0)->Draw("P");
   hists.at(2)->Draw("same P");
	leg->Draw();

   c1_1->Modified();
   c1->cd();
  
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
   
	ratio->GetYaxis()->SetTitleOffset(0.4);
	ratio->GetXaxis()->SetTitleOffset(0.9);
	ratio->GetYaxis()->CenterTitle(1);
	ratio->GetXaxis()->CenterTitle(1);
	ratio->SetLabelSize(0.125,"XYZ");
	ratio->SetTitleSize(0.125,"XYZ");
//	ratio->SetLabelFont(labelfont,"XYZ");
//	ratio->SetTitleFont(titlefont,"XYZ");
   ratio->GetXaxis()->SetTickLength(0.07);
   ratio->Draw("");
   
   c1_2->Modified();
   c1->cd();
   //c1->Modified();
   //c1->cd();
   //c1->SetSelected(c1);
	return c1;

}
void check1SLimits(
                   const char* workDir, // workDir: usual tag where to look for files in Output
                   const char* lFileName="cLimits_683_NominalABCD_Asym_2SPL_woSyst.csv", // file name to save limits results
                   bool dosyst = false,
                   int mode = 1, // mode=0 -> pass, mode=1 -> prompt, mode=2 -> nonprompt
                   const char* workDirFail=""
)
{
  TString slFileName(lFileName);
  if ( dosyst && !slFileName.Contains("wSys") )
  {
    cout << "Comparison requires systematics but limits file does not contain them" << endl;
    return;
  }
  
  // list of files
  set<anabin> thebins = allbins();
  const char* ppp = "../Fitter";
  
  // systematic uncertainties for fit
  map<anabin, syst> syst_All;
  if ( dosyst )
  {
     if (mode==0) syst_All = readSyst_all_pass("",ppp,workDir);
     if (mode==1) syst_All = readSyst_all_prompt("",ppp,workDir,workDirFail);
     if (mode==2) syst_All = readSyst_all_nonprompt("",ppp,workDir,workDirFail);
  }
  
  // bin edges
  float ptmin, ptmax, ymin, ymax, centmin, centmax;
  
  // histo for 1sigma limits checks
  TH1* hCL = new TH1D("hOneSigmaCLComparison","",thebins.size(),0,thebins.size());
  hCL->GetYaxis()->SetTitle("CL_{1#sigma}/#sigma");
  hCL->GetYaxis()->SetTitleOffset(1.15);
  hCL->SetStats(0);
  hCL->SetDirectory(0);
  hCL->SetMarkerColor(1);
  hCL->SetMarkerStyle(20);
  hCL->SetMarkerSize(1);
  hCL->SetLineColor(1);
  
  TLine* l1 = new TLine(0.,1.,hCL->GetXaxis()->GetXmax(),1.);
  l1->SetLineWidth(3);
  
  hCL->GetListOfFunctions()->Add(l1);

  map<anabin,limits> maplim = readLimits(Form("csv/%s",slFileName.Data()));
  
  int cnt=1;
  for (set<anabin>::const_iterator it=thebins.begin(); it!=thebins.end(); it++)
  {
     cout << "Checking 1 sigma limits for analysis bin " << cnt << endl;

     anabin thebin = *it;
     ptmin = thebin.ptbin().low();
     ptmax = thebin.ptbin().high();
     ymin = thebin.rapbin().low();
     ymax = thebin.rapbin().high();
     centmin = thebin.centbin().low();
     centmax = thebin.centbin().high();

     double sigmaDoubleR = 0;
     double doubleR = 0;
     if (mode==0) {
        doubleR = doubleratio_pass_nominal(workDir,thebin,ppp);
        sigmaDoubleR = doubleratio_pass_stat(workDir,thebin,ppp);
     }
     if (mode==1) {
        doubleR = doubleratio_prompt_nominal(workDir,workDirFail,thebin,ppp);
        sigmaDoubleR = doubleratio_prompt_stat(workDir,workDirFail,thebin,ppp);
     }
     if (mode==2) {
        doubleR = doubleratio_nonprompt_nominal(workDir,workDirFail,thebin,ppp);
        sigmaDoubleR = doubleratio_nonprompt_stat(workDir,workDirFail,thebin,ppp);
     }

     double systAll=0;
     if ( dosyst )
     {
        systAll = syst_All[thebin].value_dR;
        sigmaDoubleR = sqrt(pow(sigmaDoubleR,2)+pow(systAll,2));
     }

     limits lim = maplim[thebin];

     TString binName(Form("Pt[%.1f,%.1f]-Y[%.1f,%.1f]-C[%.1f,%.1f]",ptmin,ptmax,ymin,ymax,centmin,centmax));

     double comp = -1.;
     if ( sigmaDoubleR != 0 ) comp = (lim.val.second-lim.val.first)/(2.*sigmaDoubleR);
     hCL->SetBinContent(cnt,comp);
     hCL->GetXaxis()->SetBinLabel(cnt,binName.Data());

     cnt++;
  } // loop on the files

  TFile* fSave = new TFile("oneSigmaCLComparison.root","RECREATE");
  
  TCanvas* c = new TCanvas("cOneSigmaCLComparison","",90,116,1265,535);
  c->Range(-3.690909,-0.01066472,33.30606,0.01252061);
  c->SetFillColor(0);
  c->SetBorderMode(0);
  c->SetBorderSize(2);
  c->SetRightMargin(0.1163896);
  c->SetTopMargin(0.03732809);
  c->SetBottomMargin(0.1630648);
  c->SetFrameBorderMode(0);
  c->SetFrameBorderMode(0);
  gPad->SetGridx();
  gPad->SetGridy();
  hCL->Draw("p");
  
  c->Write("cOneSigmaCLComparison", TObject::kOverwrite | TObject::kSingleKey);
  fSave->Close(); delete fSave;
  
}
Esempio n. 3
0
TH1 *
UnfoldMe_MB2(const Char_t *data, const Char_t *mc, const Char_t *anatag, Int_t bin, Bool_t useMBcorr , Bool_t usecorrfit , Bool_t ismc , Float_t smooth , Int_t iter , Int_t regul , Float_t weight , Bool_t bayesian , Int_t nloop )
{

  // MF comments:
  // usedMBcorr: changes the matrix used for unfonding, from effMatrix to bin matrix (I think this is just to use mult dependent v s mb correction_)
  // usecorrfit: if I understand correctly, fits the response matrix and uses fit to extrapolate it

  
  TFile *fdt =0;
  if (ismc)
    fdt =  TFile::Open(data);
  else
    fdt = TFile::Open(data);
  TFile *fmc = TFile::Open(mc);

  TList *ldt = (TList *)fdt->Get(Form("%s", anatag));
  TList *lmc = (TList *)fmc->Get(Form("%s", anatag));
  
  TH2 *hmatdt = (TH2 *)ldt->FindObject(Form(responseMatrix, bin));
  TH2 *hmatmc = 0;
  if (useMBcorr){
     hmatmc = (TH2 *)lmc->FindObject("effMatrix");
     std::cout << "USING MB" << std::endl;
     
  }
  else {
    hmatmc = (TH2 *)lmc->FindObject(Form(responseMatrix, bin));
  }

  TH1 *hdata = hmatdt->ProjectionY("hdata");
//  TH1 *hdata = hmatdt->ProjectionY("htrue");  // For truth Only Calculations

  hdata->Sumw2();
  hdata->SetBinContent(1, 0.);
  hdata->SetBinError(1, 0.);
  //  hdata->Scale(1. / hdata->Integral());
  hdata->SetMarkerStyle(25);
  TH1 *htrue = hmatdt->ProjectionX("htrue");
  htrue->Sumw2();
  //  htrue->Scale(1. / htrue->Integral());
  htrue->SetMarkerStyle(7);
  htrue->SetMarkerColor(2);
  htrue->SetBinContent(1, 0.);
  htrue->SetBinError(1, 0.);

  TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr");
  TH1 *hinit = (TH1 *)hdata->Clone("hinit");
  TH1 *hresu = (TH1 *)hdata->Clone("hresu");
  TH1 *hbias = (TH1 *)hdata->Clone("hbias");
  hresu->SetMarkerStyle(20);
  hresu->SetMarkerColor(4);
  hresu->Reset();

  TH1 *hnum = hcorr->ProjectionY("hnum");
  TH1 *hden = hcorr->ProjectionY("hden");
  TH1 *heff = hcorr->ProjectionY("heff");
  hnum->Reset();
  hnum->Sumw2();
  hden->Reset();
  hden->Sumw2();
  heff->Reset();
  for (Int_t i = 0; i < heff->GetNbinsX(); i++) {
    Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1);
    if (int1 <= 0.) continue;
    Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1);
    hnum->SetBinContent(i + 1, int2);
    hnum->SetBinError(i + 1, TMath::Sqrt(int2));
    hden->SetBinContent(i + 1, int1);
    hden->SetBinError(i + 1, TMath::Sqrt(int1));
  }
  TCanvas *cEfficiency = new TCanvas("cEfficiency", "cEfficiency");
  cEfficiency->SetLogx();
  cEfficiency->SetLogy();

  heff->Divide(hnum, hden, 1., 1., "B");
  heff->Draw();
#if 0
  for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) {
    heff->SetBinContent(ii + 1, 1.);
    heff->SetBinError(ii + 1, 0.);
  }
#endif

  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    hcorr->SetBinContent(i + 1, 1, 0.);
    hcorr->SetBinError(i + 1, 1, 0.);
  }
  for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) {
    hcorr->SetBinContent(1, i + 1, 0.);
    hcorr->SetBinError(1, i + 1, 0.);
  }
  TH2 *hcorrfit = ReturnCorrFromFit(hcorr);
  // Docs from AliUnfolding
  //Int_t AliUnfolding::Unfold(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result, Bool_t check)
  // unfolds with unfolding method fgMethodType
  //
  // parameters:
  //  correlation: response matrix as measured vs. generated
  //  efficiency:  (optional) efficiency that is applied on the unfolded spectrum, i.e. it has to be in unfolded variables. If 0 no efficiency is applied.
  //  measured:    the measured spectrum
  //  initialConditions: (optional) initial conditions for the unfolding. if 0 the measured spectrum is used as initial conditions.
  //  result:      target for the unfolded result
  //  check:       depends on the unfolding method, see comments in specific functions

  for (Int_t iloop = 0; iloop < nloop; iloop++) {
    if (bayesian) {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian);
      AliUnfolding::SetBayesianParameters(smooth, iter);
    } else {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization);
      AliUnfolding::SetChi2Regularization(AliUnfolding::RegularizationType(regul), weight);
    }
    AliUnfolding::SetSkip0BinInChi2(kTRUE);
    AliUnfolding::SetSkipBinsBegin(1);
    AliUnfolding::SetNbins(150, 150);
    AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu);
    hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop));
  }

  printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1));
  printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1));


  TCanvas *cUnfolded = new TCanvas ("cUnfolded", "cUnfolded", 400, 800);
  cUnfolded->Divide(1, 2);
  cUnfolded->cd(1)->SetLogx();
  cUnfolded->cd(1)->SetLogy();
  hdata->Draw();
  hresu->Draw("same");
  htrue->Draw("same");
  cUnfolded->cd(2)->SetLogx();
  cUnfolded->cd(2)->DrawFrame(1., 0, 300., 10);
  TH1 *hrat = (TH1 *)hresu->Clone("hrat");
  hrat->Divide(htrue);
  hrat->Draw("same");

  TH1 *htrig = (TH1 *)hresu->Clone("htrig");
  htrig->Multiply(heff); 
  

  Float_t dndeta_resu = 0.;
  Float_t integr_resu = 0.;
  Float_t dndeta_trig = 0.;
  Float_t integr_trig = 0.;
  for (Int_t i = 1; i < hresu->GetNbinsX(); i++) {
    dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1);
    integr_resu += hresu->GetBinContent(i + 1);
    dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1);
    integr_trig += htrig->GetBinContent(i + 1);
  }

  cUnfolded->SaveAs("unfold_efficiency.pdf");

  integr_eff = integr_trig / integr_resu;
  integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu);
  dndeta_eff = dndeta_trig / dndeta_resu;
  dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu);

  printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err);
  printf("dN/dEta correction:  %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err);

  return hresu;
}
Esempio n. 4
0
//void makeHist(const int sample, const int dataset=1)
void makeHist(const string title="")
{
	vector<Hist> hist2print;
	TPaveText *tx = new TPaveText(.05,.1,.95,.8);
//	tx->AddText("Using Deafult JERs for all jets");
//	tx->AddText("Using b-Jet JERs");

/*	string title("QCD MG:");

	//if (sample==1) title += "NJet(70/50/30>=2/4/5), #slash{E}_{T}>175, Triplet>1, 80<TopMass<270, TOP+0.5*BJET>500, MT2>300, #Delta#Phi(.5,.5,.3), BJets>=1";
	if (sample==1)      title += "All Stop cuts applied (use default JERs for all jets)";
	else if (sample==2) title += "All Stop cuts applied + Inverted #Delta#Phi (use default JERs for all jets)";
	else if (sample==3) title += "All Stop cuts applied (use b-Jet JERs)";
	else if (sample==4) title += "All Stop cuts applied + Inverted #Delta#Phi (use b-Jet JERs)";
	else if (sample==5) title += "No cuts applied";
*/
	unsigned bitMaskArray[] = {0,1,2,3,129,130,131,195,257,258,269,323};
	vector<unsigned> vBitMaskArray(bitMaskArray, bitMaskArray + sizeof(bitMaskArray) / sizeof(unsigned));



	stringstream unclmet_title;
	unclmet_title << title << "Unclutered MET";
	hist2print.push_back(Hist("met",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("unclmet",unclmet_title.str().c_str(),2,0.0, 100.0,1));
	hist2print.push_back(Hist("mht",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("ht",title,2,0,2000,1));
	hist2print.push_back(Hist("njet30eta5p0",title,1,0,15,1));
	hist2print.push_back(Hist("nbjets",title,1,0,10,1));
//	hist2print.push_back(Hist("bjetPt",title,2));
	hist2print.push_back(Hist("M123",title,2));
//	hist2print.push_back(Hist("M23overM123",title));
	hist2print.push_back(Hist("MT2",title,2));
	hist2print.push_back(Hist("MTb",title,4));
	hist2print.push_back(Hist("MTt",title,4));
	hist2print.push_back(Hist("MTb_p_MTt",title,2,400,1000,1));
	//hist2print.push_back(Hist("jet1_pt",title,2));
	//hist2print.push_back("bjetPt");
//	hist2print.push_back(Hist("bjetMass",title,2,0,200));
//	hist2print.push_back(Hist("dphimin",title,4));


	TFile *outRootFile = new TFile("Merged.root");

	/*TPad *c1=0, *c2=0;
	TCanvas *c = GetCanvas(c1, c2);
	if (c ==NULL|| c1 == 0 ||c2 == 0)
	{
		cout << " A drawing pad is null !"<< endl;
		cout << "c = " << c << endl;
		cout << "c1 = " << c1 << endl;
		cout << "c2 = " << c2 << endl;
		assert(false);
	}*/
   TCanvas *c = new TCanvas("c1");
   c->Range(0,0,1,1);
   c->SetBorderSize(2);
   c->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	//c1_1->SetLogy();
  
  c->cd();
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
	c->cd();
	gStyle->SetOptStat(0);
	gPad->Print("samples.eps[");

	for (unsigned i=0;i<vBitMaskArray.size(); ++i)
	{
		unsigned mask = vBitMaskArray.at(i);
		for (unsigned ihist=0; ihist < hist2print.size(); ++ihist)
		{
			stringstream path, reco_hist_name, gen_hist_name, smear_hist_name;
			stringstream reco_hist, gen_hist, smear_hist;
			stringstream folder;
			folder << "Hist/Mask"<< mask << "HT0to8000MHT0to8000/";
			//cout << "folder = " << folder.str() << endl;

			/*	if ((hist2print.at(ihist).Name()).find("Jet"))
				{
				reco_hist_name << folder.str() << "reco" << hist2print.at(ihist).Name() << "_copy";
				reco_hist << folder.str() << "reco" << hist2print.at(ihist).Name();
				smear_hist_name << folder.str() << "smeared" << hist2print.at(ihist).Name() << "_copy";
				smear_hist << folder.str() << "smeared" << hist2print.at(ihist).Name();
				gen_hist_name << folder.str() << "gen" << hist2print.at(ihist).Name() << "_copy";
				gen_hist << folder.str() << "gen" << hist2print.at(ihist).Name();
				} else
				*/	{
					reco_hist_name << folder.str() << "reco_" << hist2print.at(ihist).Name() << "_copy";
					reco_hist << folder.str() << "reco_" << hist2print.at(ihist).Name();
					smear_hist_name << folder.str() << "smeared_" << hist2print.at(ihist).Name() << "_copy";
					smear_hist << folder.str() << "smeared_" << hist2print.at(ihist).Name();
					gen_hist_name << folder.str() << "gen_" << hist2print.at(ihist).Name() << "_copy";
					gen_hist << folder.str() << "gen_" << hist2print.at(ihist).Name();
				}

				TH1* hreco = (TH1*) (outRootFile->Get(reco_hist.str().c_str()));
				if (hreco == NULL) { cout << "hreco = " << reco_hist.str() << " was not found!" << endl; assert(false); } 
				hreco->SetDirectory(0);
				TH1* hsmear = (TH1*) (outRootFile->Get(smear_hist.str().c_str()));
				if (hsmear == NULL) { cout << "hsmear = " << smear_hist.str() << " was not found!" << endl; assert(false); } 
				hsmear->SetDirectory(0);
				TH1* hgen = (TH1*) (outRootFile->Get(gen_hist.str().c_str()));
				//->Clone(gen_hist_name.str().c_str()));
				if (hgen == NULL) { cout << "hgen = " << gen_hist.str() << " was not found!" << endl; assert(false); } 
				hgen->SetDirectory(0);

				hreco->Sumw2();
				hsmear->Sumw2();
				hgen->Sumw2();

				const int rebin = hist2print.at(ihist).Rebin();
				const string title = hist2print.at(ihist).Title();
				const double xmin = hist2print.at(ihist).Xmin();
				const double xmax = hist2print.at(ihist).Xmax();

				if (rebin>1)
				{
					hreco->Rebin(rebin);
					hsmear->Rebin(rebin);
					hgen->Rebin(rebin);
				}
				if (title.length()>0)
				{
					hreco->SetTitle(title.c_str());
					hsmear->SetTitle(title.c_str());
					hgen->SetTitle(title.c_str());
				}
				if (xmin != LargeNegNum || xmax != LargeNegNum)
				{
					hreco->GetXaxis()->SetRangeUser(xmin,xmax);
					hsmear->GetXaxis()->SetRangeUser(xmin,xmax);
					hgen->GetXaxis()->SetRangeUser(xmin,xmax);
				}

				const double reco_max_y  = hreco->GetBinContent(hreco->GetMaximumBin());
				const double smear_max_y = hsmear->GetBinContent(hsmear->GetMaximumBin());
				const double y_max = max(reco_max_y, smear_max_y);
				double y_min = 9999.0;
				for (unsigned bin=1; bin<hreco->GetNbinsX(); ++bin)
				{
					const double v1 = hreco->GetBinContent(bin);
					const double v2 = hsmear->GetBinContent(bin);
					const double minv = min(v1,v2);
					if (minv != 0 && minv < y_min) y_min = minv;
					
				}

				cout << hreco->GetName() << "->ymin/max = " << y_min << "(" << y_min/2.0 << ")/" << y_max << "(" << y_max*2.0 << ")" << endl;
				hreco->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);
				hsmear->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);


				hgen->SetLineColor(kBlue);
				hgen->SetMarkerColor(kBlue);
				hgen->SetMarkerStyle(24);
				hgen->SetLineWidth(2);
				hsmear->SetLineColor(kRed);
				hsmear->SetMarkerColor(kRed);
				hsmear->SetMarkerStyle(24);
				hsmear->SetLineWidth(2);
				hreco->SetLineWidth(2);
				hreco->SetMarkerStyle(kDot);
				hreco->SetLineColor(kBlack);
				hreco->SetMarkerColor(kBlack);
				//hreco->GetXaxis()->SetRangeUser(0,300);
				//hsmear->GetXaxis()->SetRangeUser(0,300);


				hreco->GetYaxis()->CenterTitle(1);
				hreco->SetLabelFont(42,"XYZ");
				hreco->SetTitleFont(42,"XYZ");
				hreco->GetYaxis()->SetTitleOffset(0.8);
				hreco->SetLabelSize(0.05,"XYZ");
				hreco->SetTitleSize(0.06,"XYZ");


				TH1 *hsmeartoreco_ratio = (TH1*) (hsmear->Clone("hsmear_copy"));
				hsmeartoreco_ratio->Divide(hreco);
				hsmeartoreco_ratio->SetTitle("");
				hsmeartoreco_ratio->GetYaxis()->SetTitle("Smear/Reco");
				hsmeartoreco_ratio->GetYaxis()->SetRangeUser(0,2.);

				hsmeartoreco_ratio->GetYaxis()->SetTitleOffset(0.4);
				hsmeartoreco_ratio->GetXaxis()->SetTitleOffset(0.9);
				hsmeartoreco_ratio->GetYaxis()->CenterTitle(1);
				hsmeartoreco_ratio->GetXaxis()->CenterTitle(1);
				hsmeartoreco_ratio->SetLabelSize(0.125,"XYZ");
				hsmeartoreco_ratio->SetTitleSize(0.125,"XYZ");
				//	hsmeartoreco_ratio->SetLabelFont(labelfont,"XYZ");
				//	hsmeartoreco_ratio->SetTitleFont(titlefont,"XYZ");
				hsmeartoreco_ratio->GetXaxis()->SetTickLength(0.07);



				stringstream recoleg,smearleg, genleg;
				const double sum_reco  = hreco->Integral(1, hreco->GetNbinsX()+1);
				const double sum_smear = hsmear->Integral(1, hsmear->GetNbinsX()+1);
				const double sum_gen   = hgen->Integral(1, hgen->GetNbinsX()+1);
				const double err_reco  = StatErr(hreco);
				const double err_smear = StatErr(hsmear);


				cout << setprecision(1) << fixed;

				recoleg << "Reco (" << sum_reco << "#pm" << err_reco << ")";
				smearleg << "Smear (" << sum_smear << "#pm" << err_smear << ")";
				genleg << "Gen (" << sum_gen << ")";
				cout <<  smear_hist_name.str() << "::reco/smear = " << sum_reco << "/" << sum_smear << endl;

				TLegend *l2 = new TLegend(0.6,0.6,0.9,0.9);
				l2->AddEntry(hreco, recoleg.str().c_str());
				//l2->AddEntry(hgen, genleg.str().c_str());
				l2->AddEntry(hsmear, smearleg.str().c_str());

				c1_1->cd();
				gPad->SetLogy(hist2print.at(ihist).LogY());

				hreco->DrawCopy();
				//hgen->DrawCopy("same");
				hsmear->DrawCopy("same");
				l2->Draw();
				//tx->Draw();
				c1_2->cd();
				hsmeartoreco_ratio->DrawCopy();
				c->cd();
				gPad->Print("samples.eps");

		}
	}

	gPad->Print("samples.eps]");
}
//------------------------------------------------------------------------------
void  PlotAlignmentValidation::setHistStyle( TH1& hist,const char* titleX, const char* titleY, int color)
{
  std::stringstream titel_Xaxis;
  std::stringstream titel_Yaxis;
  TString titelXAxis=titleX;
  TString titelYAxis=titleY;
  
  if ( titelXAxis.Contains("Phi") )titel_Xaxis<<titleX<<"[rad]";
  else if( titelXAxis.Contains("meanX") )titel_Xaxis<<"#LTx'_{pred}-x'_{hit}#GT[cm]";
  else if( titelXAxis.Contains("meanY") )titel_Xaxis<<"#LTy'_{pred}-y'_{hit}#GT[cm]";
  else if( titelXAxis.Contains("rmsX") )titel_Xaxis<<"RMS(x'_{pred}-x'_{hit})[cm]";
  else if( titelXAxis.Contains("rmsY") )titel_Xaxis<<"RMS(y'_{pred}-y'_{hit})[cm]";
  else if( titelXAxis.Contains("meanNormX") )titel_Xaxis<<"#LTx'_{pred}-x'_{hit}/#sigma#GT";
  else if( titelXAxis.Contains("meanNormY") )titel_Xaxis<<"#LTy'_{pred}-y'_{hit}/#sigma#GT";
  else if( titelXAxis.Contains("rmsNormX") )titel_Xaxis<<"RMS(x'_{pred}-x'_{hit}/#sigma)";
  else if( titelXAxis.Contains("rmsNormY") )titel_Xaxis<<"RMS(y'_{pred}-y'_{hit}/#sigma)";
  else if( titelXAxis.Contains("meanLocalX") )titel_Xaxis<<"#LTx_{pred}-x_{hit}#GT[cm]";
  else if( titelXAxis.Contains("rmsLocalX") )titel_Xaxis<<"RMS(x_{pred}-x_{hit})[cm]";
  else if( titelXAxis.Contains("meanNormLocalX") )titel_Xaxis<<"#LTx_{pred}-x_{hit}/#sigma#GT[cm]";
  else if( titelXAxis.Contains("rmsNormLocalX") )titel_Xaxis<<"RMS(x_{pred}-x_{hit}/#sigma)[cm]";
  else if( titelXAxis.Contains("medianX") )titel_Xaxis<<"median(x'_{pred}-x'_{hit})[cm]";
  else if( titelXAxis.Contains("medianY") )titel_Xaxis<<"median(y'_{pred}-y'_{hit})[cm]";
  else titel_Xaxis<<titleX<<"[cm]";
  
  if (hist.IsA()->InheritsFrom( TH1F::Class() ) )hist.SetLineColor(color);
  if (hist.IsA()->InheritsFrom( TProfile::Class() ) ) {
    hist.SetMarkerStyle(20);
    hist.SetMarkerSize(0.8);
    hist.SetMarkerColor(color);
  }
  
  hist.GetXaxis()->SetTitle( (titel_Xaxis.str()).c_str() );
  hist.GetXaxis()->SetTitleSize  ( 0.05 );
  hist.GetXaxis()->SetTitleColor (    1 );
  hist.GetXaxis()->SetTitleOffset(  1.2   );
  hist.GetXaxis()->SetTitleFont  (   62 );
  hist.GetXaxis()->SetLabelSize  ( 0.05 );
  hist.GetXaxis()->SetLabelFont  (   62 );
  //hist.GetXaxis()->CenterTitle   (      );
  hist.GetXaxis()->SetNdivisions (  505 );

  if /*( titelYAxis.Contains("meanX") )titel_Yaxis<<"#LTx'_{pred}-x'_{hit}#GT[cm]";
  else if ( titelYAxis.Contains("rmsX") )titel_Yaxis<<"RMS(x'_{pred}-x'_{hit})[cm]";
  else if( titelYAxis.Contains("meanNormX") )titel_Yaxis<<"#LTx'_{pred}-x'_{hit}/#sigma#GT";
  else if( titelYAxis.Contains("rmsNormX") )titel_Yaxis<<"RMS(x_'{pred}-x'_{hit}/#sigma)";
  else if( titelYAxis.Contains("meanLocalX") )titel_Yaxis<<"#LTx_{pred}-x_{hit}#GT[cm]";
  else if( titelYAxis.Contains("rmsLocalX") )titel_Yaxis<<"RMS(x_{pred}-x_{hit})[cm]";
  else if*/ ( (titelYAxis.Contains("layer") && titelYAxis.Contains("subDetId"))
	      || titelYAxis.Contains("#modules") )titel_Yaxis<<"#modules";
  else if ( (titelYAxis.Contains("ring") && titelYAxis.Contains("subDetId"))
	    || titelYAxis.Contains("#modules") )titel_Yaxis<<"#modules";
  else titel_Yaxis<<titleY<<"[cm]";

  hist.GetYaxis()->SetTitle( (titel_Yaxis.str()).c_str()  );
  //hist.SetMinimum(1);
  hist.GetYaxis()->SetTitleSize  ( 0.05 );
  hist.GetYaxis()->SetTitleColor (    1 );
  if ( hist.IsA()->InheritsFrom( TH2::Class() ) ) hist.GetYaxis()->SetTitleOffset( 0.95 );
  else hist.GetYaxis()->SetTitleOffset( 1.2 );
  hist.GetYaxis()->SetTitleFont  (   62 );
  hist.GetYaxis()->SetLabelSize  ( 0.03 );
  hist.GetYaxis()->SetLabelFont  (   62 );

}
void makePlot(TCanvas* canvas, const std::string& outputFileName, TTree* testTree, const std::string& varName, 
	      unsigned numBinsX, double xMin, double xMax)
{
  std::cout << "creating histogramTauIdPassed..." << std::endl;
  TString histogramTauIdPassedName = TString("histogramTauIdPassed").Append("_").Append(varName.data());
  TH1* histogramTauIdPassed = fillHistogram(testTree, varName, "type==1", "",
					    histogramTauIdPassedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdPassed = " << histogramTauIdPassed << ":" 
	    << " integral = " << histogramTauIdPassed->Integral() << std::endl;

  std::cout << "creating histogramTauIdFailed..." << std::endl;
  TString histogramTauIdFailedName = TString("histogramTauIdFailed").Append("_").Append(varName.data());
  TH1* histogramTauIdFailed = fillHistogram(testTree, varName, "type==0", "",
					    histogramTauIdFailedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdFailed = " << histogramTauIdFailed 
	    << " integral = " << histogramTauIdFailed->Integral() << std::endl;

  std::cout << "creating histogramTauIdDenominator..." << std::endl;
  TString histogramTauIdDenominatorName = TString("histogramTauIdDenominator").Append("_").Append(varName.data());
  TH1* histogramTauIdDenominator = new TH1F(histogramTauIdDenominatorName.Data(), 
					    histogramTauIdDenominatorName.Data(), numBinsX, xMin, xMax);
  histogramTauIdDenominator->Add(histogramTauIdPassed);
  histogramTauIdDenominator->Add(histogramTauIdFailed);
  std::cout << "--> histogramTauIdDenominator = " << histogramTauIdDenominator 
	    << " integral = " << histogramTauIdDenominator->Integral() << std::endl;

  std::cout << "creating histogramFakeRate..." << std::endl;
  TString histogramFakeRateName = TString("histogramFakeRate").Append("_").Append(varName.data());
  TH1* histogramFakeRate = new TH1F(histogramFakeRateName.Data(), 
				    histogramFakeRateName.Data(), numBinsX, xMin, xMax);
  histogramFakeRate->Add(histogramTauIdPassed);
  histogramFakeRate->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRate = " << histogramFakeRate 
	    << " integral = " << histogramFakeRate->Integral() << std::endl;

  std::cout << "creating histogramFakeRateWeighted..." << std::endl;
  TString histogramFakeRateWeightedName = TString("histogramFakeRateWeighted").Append("_").Append(varName.data());
  TH1* histogramFakeRateWeighted = fillHistogram(testTree, varName, "", "MVA_KNN", 
						 histogramFakeRateWeightedName.Data(), numBinsX, xMin, xMax);
  histogramFakeRateWeighted->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRateWeighted = " << histogramFakeRateWeighted 
	    << " entries = " << histogramFakeRateWeighted->GetEntries() << ","
	    << " integral = " << histogramFakeRateWeighted->Integral() << std::endl;
  // Scale the weighted fake rate histogram

  histogramFakeRate->SetTitle(varName.data());
  histogramFakeRate->SetStats(false);
  histogramFakeRate->SetMinimum(1.e-4);
  histogramFakeRate->SetMaximum(1.e+1);
  histogramFakeRate->SetLineColor(2);
  histogramFakeRate->SetLineWidth(2);
  histogramFakeRate->SetMarkerStyle(20);
  histogramFakeRate->SetMarkerColor(2);
  histogramFakeRate->SetMarkerSize(1);
  histogramFakeRate->Draw("e1p");

  histogramFakeRateWeighted->SetLineColor(4);
  histogramFakeRateWeighted->SetLineWidth(2);
  histogramFakeRateWeighted->SetMarkerStyle(24);
  histogramFakeRateWeighted->SetMarkerColor(4);
  histogramFakeRateWeighted->SetMarkerSize(1);
  histogramFakeRateWeighted->Draw("e1psame");

  TLegend legend(0.11, 0.73, 0.31, 0.89);
  legend.SetBorderSize(0);
  legend.SetFillColor(0);
  legend.AddEntry(histogramFakeRate, "Tau id. discr.", "p");
  legend.AddEntry(histogramFakeRateWeighted, "Fake-Rate weight", "p");
  legend.Draw();

  canvas->Update();
  canvas->Print(outputFileName.data());
}
void dNdEta_ThreeMethods_FullTrackingRebinned_DividedByMidRapidValue() {
//=========Macro generated from canvas: MyCanvas/MyCanvas
//=========  (Thu Dec 10 11:52:00 2009) by ROOT version5.22/00d

   gROOT->Reset();
   gROOT->ProcessLine(".x rootlogon.C");

   gStyle->SetTitleYOffset(1.4);


   TCanvas *MyCanvas = new TCanvas("MyCanvas", "Final result",1,360,550,600); 
   TH1 *corr_result_all = new TH1D("corr_result_all","",14,-3.5,3.5);
   corr_result_all->GetXaxis()->SetRange(2,13);

   // ========================= Cluster Counting =======================

   corr_result_all->SetBinContent(4,4.043821);  // -2.0 to -1.5
   corr_result_all->SetBinContent(5,3.821537);  // -1.5 to -1.0 
   corr_result_all->SetBinContent(6,3.611029); // -1.0 to -0.5
   corr_result_all->SetBinContent(7,3.501129); // -0.5 to 0.0
   corr_result_all->SetBinContent(8,3.51732);      
   corr_result_all->SetBinContent(9,3.632249);      
   corr_result_all->SetBinContent(10,3.747706);    
   corr_result_all->SetBinContent(11,4.01596);  

   corr_result_all->SetBinError(4,0.177928124);
   corr_result_all->SetBinError(5,0.168147628);
   corr_result_all->SetBinError(6,0.158885276);
   corr_result_all->SetBinError(7,0.154049676);
   corr_result_all->SetBinError(8,0.15476208);
   corr_result_all->SetBinError(9,0.159818956);
   corr_result_all->SetBinError(10,0.164899064);
   corr_result_all->SetBinError(11,0.17670224);

   /*
   corr_result_all->SetBinContent(4,3.954);  // -2.0 to -1.5    
   corr_result_all->SetBinContent(5,3.770);  // -1.5 to -1.0
   corr_result_all->SetBinContent(6,3.607); // -1.0 to -0.5
   corr_result_all->SetBinContent(7,3.548); // -0.5 to 0.0

   corr_result_all->SetBinContent(8,3.567); 
   corr_result_all->SetBinContent(9,3.681); 
   corr_result_all->SetBinContent(10,3.791); 
   corr_result_all->SetBinContent(11,4.025); 

   corr_result_all->SetBinError(4,0.1779);
   corr_result_all->SetBinError(5,0.1697);
   corr_result_all->SetBinError(6,0.1623);
   corr_result_all->SetBinError(7,0.1597);
   corr_result_all->SetBinError(8,0.1605);
   corr_result_all->SetBinError(9,0.1657);
   corr_result_all->SetBinError(10,0.1706);
   corr_result_all->SetBinError(11,0.1811);
   */

   corr_result_all->SetMarkerStyle(20);  
   //corr_result_all->SetMarkerSize(1.5); // use rootlogon size 
   corr_result_all->SetMarkerColor(kRed);
   corr_result_all->SetLineColor(2);

   corr_result_all->GetYaxis()->SetTitle("dN_{ch}/d#eta/dN_{ch,mid}/d#eta");
   corr_result_all->GetXaxis()->SetTitle("#eta"); 
   corr_result_all->GetXaxis()->CenterTitle();
   corr_result_all->GetYaxis()->CenterTitle();
   corr_result_all->GetXaxis()->SetNdivisions(405);
   //corr_result_all->GetYaxis()->SetNdivisions(1005);
   corr_result_all->GetYaxis()->SetNdivisions(506);

   Float_t midrapid = 0.5*(corr_result_all->GetBinContent(7)+corr_result_all->GetBinContent(8));
   cout<<"mid rapid value = "<<midrapid<<endl;

   corr_result_all->Scale(1/midrapid);

   corr_result_all->SetMinimum(0.95);
   corr_result_all->SetMaximum(1.3);

   corr_result_all->Draw("pz");

   // ======= YJ Tracklet three layer combination averaged (updated with dead modules..) ======
   //                        1     2   3     4   5     6  7    8  9   10 11   12
   Double_t xAxis5[13] = {-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3}; 
   
   TH1 *hMeasuredFinal = new TH1D("hMeasuredFinal","",12, xAxis5);

   hMeasuredFinal->SetBinContent(3,3.7459);
   hMeasuredFinal->SetBinContent(4,3.65462);
   hMeasuredFinal->SetBinContent(5,3.55475);
   hMeasuredFinal->SetBinContent(6,3.45008);

   hMeasuredFinal->SetBinContent(7,3.44329);
   hMeasuredFinal->SetBinContent(8,3.5244);
   hMeasuredFinal->SetBinContent(9,3.59575);
   hMeasuredFinal->SetBinContent(10,3.6612);

   hMeasuredFinal->SetBinError(3,0.142344);
   hMeasuredFinal->SetBinError(4,0.138876);
   hMeasuredFinal->SetBinError(5,0.13508);
   hMeasuredFinal->SetBinError(6,0.131103);
   hMeasuredFinal->SetBinError(7,0.130845);
   hMeasuredFinal->SetBinError(8,0.133927);
   hMeasuredFinal->SetBinError(9,0.136638);
   hMeasuredFinal->SetBinError(10,0.139126);

   hMeasuredFinal->SetMarkerColor(kBlue);   
   hMeasuredFinal->SetLineColor(4);
   hMeasuredFinal->SetMarkerStyle(21); 
   //hMeasuredFinal->SetMarkerSize(1.5); // use rootlogon size 

   midrapid = 0.5*(hMeasuredFinal->GetBinContent(6)+hMeasuredFinal->GetBinContent(7));
   cout<<"mid rapid value = "<<midrapid<<endl;

   hMeasuredFinal->Scale(1/midrapid);
   hMeasuredFinal->Draw("pzsame");

   /// ==================================================== Ferenc's dN/dEta   (rebinned)
   Double_t xAxis6[13] = {-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3}; 
   TH1 *hMeasuredFinal2 = new TH1D("hMeasuredFinal2","",12, xAxis6);

   // Hight Stat
   hMeasuredFinal2->SetBinContent(2,3.65413);
   hMeasuredFinal2->SetBinContent(3,3.68883);
   hMeasuredFinal2->SetBinContent(4,3.73805);
   hMeasuredFinal2->SetBinContent(5,3.62817);
   hMeasuredFinal2->SetBinContent(6,3.52704);

   hMeasuredFinal2->SetBinContent(7,3.47443);
   hMeasuredFinal2->SetBinContent(8,3.63319);
   hMeasuredFinal2->SetBinContent(9,3.7577);
   hMeasuredFinal2->SetBinContent(10,3.67975);
   hMeasuredFinal2->SetBinContent(11,3.65413);

   // Systematic error of 3.1%  --> to 2.4%
   hMeasuredFinal2->SetBinError(2,0.08769912);
   hMeasuredFinal2->SetBinError(3,0.08853192);
   hMeasuredFinal2->SetBinError(4,0.0897132);
   hMeasuredFinal2->SetBinError(5,0.08707608);
   hMeasuredFinal2->SetBinError(6,0.08464896);
   hMeasuredFinal2->SetBinError(7,0.08338632);
   hMeasuredFinal2->SetBinError(8,0.08719656);
   hMeasuredFinal2->SetBinError(9,0.0901848);
   hMeasuredFinal2->SetBinError(10,0.088314);
   hMeasuredFinal2->SetBinError(11,0.08769912);

   /*
   // Systematic error of 3.1%  --> to 2.3%
   hMeasuredFinal2->SetBinError(2,0.084045);
   hMeasuredFinal2->SetBinError(3,0.0848431);
   hMeasuredFinal2->SetBinError(4,0.0859752);
   hMeasuredFinal2->SetBinError(5,0.0834479);
   hMeasuredFinal2->SetBinError(6,0.0811219);
   hMeasuredFinal2->SetBinError(7,0.0799119);
   hMeasuredFinal2->SetBinError(8,0.0835634);
   hMeasuredFinal2->SetBinError(9,0.0864271);
   hMeasuredFinal2->SetBinError(10,0.0846342);
   hMeasuredFinal2->SetBinError(11,0.084045);
   */

   hMeasuredFinal2->SetMarkerColor(kBlack);
   hMeasuredFinal2->SetLineColor(1);
   hMeasuredFinal2->SetMarkerStyle(22);
   //hMeasuredFinal2->SetMarkerSize(1.5); use root logon size

   midrapid = 0.5*(hMeasuredFinal2->GetBinContent(6)+hMeasuredFinal2->GetBinContent(7));
   cout<<"mid rapid value = "<<midrapid<<endl;


   hMeasuredFinal2->Scale(1/midrapid);
   hMeasuredFinal2->Draw("pzsame");
   
   // ================== 2.36 TeV
   // ========================= Cluster Counting ======================= 
   TH1 *corr_result_all236 = new TH1D("corr_result_all236","",14,-3.5,3.5);
   corr_result_all236->GetXaxis()->SetRange(2,13);

   corr_result_all236->SetBinContent(4,5.203552);
   corr_result_all236->SetBinContent(5,4.913457);
   corr_result_all236->SetBinContent(6,4.710017);
   corr_result_all236->SetBinContent(7,4.44485);
   corr_result_all236->SetBinContent(8,4.448675);
   corr_result_all236->SetBinContent(9,4.659581);
   corr_result_all236->SetBinContent(10,4.856712);
   corr_result_all236->SetBinContent(11,5.065867);

   corr_result_all236->SetBinError(4,0.23416);
   corr_result_all236->SetBinError(5,0.221106);
   corr_result_all236->SetBinError(6,0.211951);
   corr_result_all236->SetBinError(7,0.200018);
   corr_result_all236->SetBinError(8,0.20019);
   corr_result_all236->SetBinError(9,0.209681);
   corr_result_all236->SetBinError(10,0.218552);
   corr_result_all236->SetBinError(11,0.227964);

   corr_result_all236->SetMarkerColor(kRed);
   corr_result_all236->SetLineColor(2);
   corr_result_all236->SetMarkerStyle(24);

   midrapid = 0.5*(corr_result_all236->GetBinContent(7)+corr_result_all236->GetBinContent(8));
   cout<<"mid rapid value = "<<midrapid<<endl;

   corr_result_all236->Scale(1./midrapid);
   corr_result_all236->Draw("pzsame");



   /// ==================================================== Yenjie 2.36 TeV
   //                        1     2   3     4   5     6  7    8  9   10 11   12
   TH1 *hTracklet236 = new TH1D("hTracklet236","",12, xAxis5);

   hTracklet236->SetBinContent(3,4.73663);
   hTracklet236->SetBinContent(4,4.69978);
   hTracklet236->SetBinContent(5,4.61061);
   hTracklet236->SetBinContent(6,4.40814);

   hTracklet236->SetBinContent(7,4.38437);
   hTracklet236->SetBinContent(8,4.51905);
   hTracklet236->SetBinContent(9,4.6502);
   hTracklet236->SetBinContent(10,4.80977);
   
   // 4.8 % Systematic Error 
   hTracklet236->SetBinError(3,0.179992);
   hTracklet236->SetBinError(4,0.178592);
   hTracklet236->SetBinError(5,0.175203);
   hTracklet236->SetBinError(6,0.167509);
   hTracklet236->SetBinError(7,0.166606);
   hTracklet236->SetBinError(8,0.171724);
   hTracklet236->SetBinError(9,0.176707);
   hTracklet236->SetBinError(10,0.182771);

   hTracklet236->SetMarkerColor(4);   
   hTracklet236->SetLineColor(4);
   hTracklet236->SetMarkerStyle(kOpenSquare); 
   //hTracklet236->SetMarkerSize(1.5); // use rootlogon size

   midrapid = 0.5*(hTracklet236->GetBinContent(6)+hTracklet236->GetBinContent(7));
   cout<<"mid rapid value = "<<midrapid<<endl;

   hTracklet236->Scale(1./midrapid);
   hTracklet236->Draw("pzsame");

   /// ==================================================== Ferenc's dN/dEta   (rebinned) 
   Double_t xAxis7[13] = {-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3};
   TH1 *hMeasuredFinal2236 = new TH1D("hMeasuredFinal2","",12, xAxis7);

   hMeasuredFinal2236->SetBinContent(2,4.9689);
   hMeasuredFinal2236->SetBinContent(3,4.93581);
   hMeasuredFinal2236->SetBinContent(4,4.67197);
   hMeasuredFinal2236->SetBinContent(5,4.70044);
   hMeasuredFinal2236->SetBinContent(6,4.52142);

   hMeasuredFinal2236->SetBinContent(7,4.55674);
   hMeasuredFinal2236->SetBinContent(8,4.61255);
   hMeasuredFinal2236->SetBinContent(9,4.67611);
   hMeasuredFinal2236->SetBinContent(10,4.87402);
   hMeasuredFinal2236->SetBinContent(11,4.96891);


   // Systematic error of 3.1% --> 2.3%
   hMeasuredFinal2236->SetBinError(2,0.114285);
   hMeasuredFinal2236->SetBinError(3,0.113524);
   hMeasuredFinal2236->SetBinError(4,0.107455);
   hMeasuredFinal2236->SetBinError(5,0.10811);
   hMeasuredFinal2236->SetBinError(6,0.103993);
   hMeasuredFinal2236->SetBinError(7,0.104805);
   hMeasuredFinal2236->SetBinError(8,0.106089);
   hMeasuredFinal2236->SetBinError(9,0.107551);
   hMeasuredFinal2236->SetBinError(10,0.112102);
   hMeasuredFinal2236->SetBinError(11,0.114285);


   hMeasuredFinal2236->SetMarkerColor(kBlack);
   hMeasuredFinal2236->SetLineColor(1);
   hMeasuredFinal2236->SetMarkerStyle(26);
   //hMeasuredFinal2->SetMarkerSize(1.5); use root logon size                                                              

   midrapid = 0.5*(hMeasuredFinal2236->GetBinContent(6)+hMeasuredFinal2236->GetBinContent(7));
   cout<<"mid rapid value = "<<midrapid<<endl;

   hMeasuredFinal2236->Scale(1./midrapid);

   //hMeasuredFinal2236->Scale(1/4.53908);
   hMeasuredFinal2236->Draw("pzsame");
   


   /// ====================================================  UA5 Data

   TH1F* hEta_UA5_NSD = new TH1F("hEta_UA5_NSD",";#eta;dN/d#eta",50,-3,3);

   // positive eta
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(0.125),3.48);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(0.375),3.38);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(0.625),3.52);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(0.875),3.68);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(1.125),3.71);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(1.375),3.86);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(1.625),3.76);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(1.875),3.66);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(2.125),3.72);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(2.375),3.69);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(2.625),3.56);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(2.875),3.41);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(3.125),3.15);

   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(0.125),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(0.375),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(0.625),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(0.875),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(1.125),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(1.375),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(1.625),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(1.875),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(2.125),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(2.375),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(2.625),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(2.875),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(3.125),0.07);


   //negative eta
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-0.125),3.48);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-0.375),3.38);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-0.625),3.52);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-0.875),3.68);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-1.125),3.71);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-1.375),3.86);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-1.625),3.76);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-1.875),3.66);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-2.125),3.72);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-2.375),3.69);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-2.625),3.56);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-2.875),3.41);
   hEta_UA5_NSD->SetBinContent(hEta_UA5_NSD->FindBin(-3.125),3.15);

   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-0.125),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-0.375),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-0.625),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-0.875),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-1.125),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-1.375),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-1.625),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-1.875),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-2.125),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-2.375),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-2.625),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-2.875),0.07);
   hEta_UA5_NSD->SetBinError(hEta_UA5_NSD->FindBin(-3.125),0.07);

   hEta_UA5_NSD->SetMarkerStyle(25);
   hEta_UA5_NSD->SetMarkerSize(1.0);
   //hEta_UA5_NSD->Draw("psame");

   //TLegend *leg = new TLegend(0.20,0.27,0.53,0.47,NULL,"brNDC");
   //TLegend *leg = new TLegend(0.20,0.35,0.53,0.47,NULL,"brNDC"); 
   Float_t ywidth = 0.045*4;

   //TLegend *leg = new TLegend(0.27,0.26,0.70,0.26+ywidth,NULL,"brNDC");
   //TLegend *leg = new TLegend(0.39,0.21,0.82,0.21+ywidth,NULL,"brNDC");
   TLegend *leg = new TLegend(0.45,0.753,0.892,0.93,NULL,"brNDC");


   //leg->SetNColumns(2);
   leg->SetBorderSize(0);
   leg->SetMargin(0.5);
   leg->SetTextFont(62);
   leg->SetLineColor(1);
   leg->SetLineStyle(1);
   leg->SetLineWidth(1);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetTextSize(0.03); 
   leg->SetHeader("      2.36 TeV");
   leg->AddEntry(corr_result_all236,"Hit counting","P");
   leg->AddEntry(hTracklet236,"Tracklet","P");
   leg->AddEntry(hMeasuredFinal2236,"Global tracking","P");


   //cout<<"Number of column "<<leg->GetNColumns()<<endl;
   /*
   leg->AddEntry(corr_result_all236,"","P");
   leg->AddEntry(hTracklet236,"","P"); 
   leg->AddEntry(hMeasuredFinal2236,"","P");
   */

   //TLegend *leg2 = new TLegend(0.20,0.22,0.53,0.35,NULL,"brNDC");
   //TLegend *leg2 = new TLegend(0.50,0.26,0.93,0.47,NULL,"brNDC");
   //TLegend *leg2 = new TLegend(0.39,0.26,0.82,0.26+ywidth,NULL,"brNDC");
   //TLegend *leg2 = new TLegend(0.27,0.21,0.70,0.21+ywidth,NULL,"brNDC"); 
   TLegend *leg2 = new TLegend(0.35,0.75,0.782,0.932,NULL,"brNDC"); 
   leg2->SetMargin(0.37);
   leg2->SetBorderSize(0);
   leg2->SetTextFont(62);
   leg2->SetLineColor(1);
   leg2->SetLineStyle(1);
   leg2->SetLineWidth(1);
   leg2->SetFillColor(0);
   //leg2->SetFillStyle(1001);
   leg2->SetFillStyle(0); 
   leg2->SetTextSize(0.03);
   leg2->SetHeader("   0.9 TeV");
   leg2->AddEntry(corr_result_all,"","P");
   leg2->AddEntry(hMeasuredFinal,"","P"); 
   leg2->AddEntry(hMeasuredFinal2,"","P");

   leg->Draw();
   leg2->Draw();

   printFinalCanvases(MyCanvas,"dNdeta_ThreeMethods_Divided",0,2);
}
void stackPlotter::moveDirHistsToStacks(TDirectory* tdir, TString histname, int color){
	if(debug)
		std::cout << "stackPlotter::moveDirHistsToStacks" << std::endl;

	// get metainfo from directory, else exit TODO
	metaInfo tMI;
	tMI.extractFrom(tdir);

	if(debug) {
		std::cout << "stackPlotter::moveDirHistsToStacks || metaInfo color=" << tMI.color << std::endl;
		std::cout << "stackPlotter::moveDirHistsToStacks || metaInfo legendname=" << tMI.legendname<< std::endl;
		std::cout << "stackPlotter::moveDirHistsToStacks || metaInfo legendorder=" << tMI.legendorder << std::endl;
	}


	TIter    histIter(tdir->GetListOfKeys());
	TObject* cHistObj;
	TKey*    cHistKey;

	if(debug)
		std::cout << "stackPlotter::moveDirHistsToStacks || Iterating through histograms." << std::endl;

	// loop through keys in the directory
	while((cHistKey = (TKey*) histIter())) {
        if(histname != cHistKey->GetName()) continue;
		cHistObj=tdir->Get(cHistKey->GetName());
		if(!cHistObj->InheritsFrom(TH1::Class())) continue;

		if(debug)
			std::cout << "stackPlotter::moveDirHistsToStacks || Found histogram "
			<< cHistKey->GetName() << std::endl;

		// prepare the histogram to be added to the stack
		TH1* cHist = (TH1*) cHistObj->Clone();
		cHist->SetDirectory(0);
		TString mapName = cHist->GetName();

		std::pair<Int_t,TH1*> newEntry(tMI.legendorder,cHist);

		// initialize the stack info if needed
		if(!stacksLegEntries_.count(mapName)) {
			std::vector<std::pair<Int_t,TH1*> > legInfo(0);
			legInfo.push_back(newEntry);
			stacksLegEntries_[mapName] = legInfo;
		}

		cHist->SetFillColor(color);
		cHist->SetFillStyle(1001);
		cHist->SetMarkerStyle(kNone);
		cHist->SetMarkerColor(kBlack);
		cHist->SetLineColor(kBlack);
		cHist->SetTitle(mapName);
		cHist->SetName(tMI.legendname);

		std::vector<std::pair<Int_t,TH1*> > legEntries = stacksLegEntries_[mapName];
		if(debug)
			std::cout << "stackPlotter::moveDirHistsToStacks || legEntries size is " << legEntries.size() << std::endl;
		for(size_t i=0; i < legEntries.size(); i++) {
			if(legEntries.at(i).second == cHist && legEntries.at(i).first == tMI.legendorder) break;

			if(legEntries.at(i).first >= tMI.legendorder) {
				if(debug)
					std::cout << "stackPlotter::moveDirHistsToStacks || i is " << i << std::endl;
				stacksLegEntries_[mapName].insert(stacksLegEntries_[mapName].begin()+i,newEntry);
				break;
			}

			if(i==legEntries.size()-1) {
				stacksLegEntries_[mapName].push_back(newEntry);
				break;
			}
		}

		if(debug)
			std::cout << "stackPlotter::moveDirHistsToStacks || legEntries size is " << legEntries.size() << std::endl;
	}

}
void makePlot(double canvasSizeX, double canvasSizeY,
	      TH1* histogramTTH, 
	      TH1* histogramData, 
	      TH1* histogramTT,
	      TH1* histogramTTV,
	      TH1* histogramEWK,
	      TH1* histogramRares,
	      TH1* histogramBgrSum,
	      TH1* histogramBgrUncertainty,		
	      const std::string& xAxisTitle, double xAxisOffset,
	      bool useLogScale, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset,
	      const std::string& outputFileName)
{
  TH1* histogramTTH_density = 0;
  if ( histogramTTH ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTH, histogramData);
    histogramTTH_density = divideHistogramByBinWidth(histogramTTH);
  }
  TH1* histogramData_density = 0;
  if ( histogramData ) {
    histogramData_density = divideHistogramByBinWidth(histogramData);      
  }
  TH1* histogramTT_density = 0;
  if ( histogramTT ) {
    if ( histogramData ) checkCompatibleBinning(histogramTT, histogramData);
    histogramTT_density = divideHistogramByBinWidth(histogramTT);
  } 
  TH1* histogramTTV_density = 0;
  if ( histogramTTV ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTV, histogramData);
    histogramTTV_density = divideHistogramByBinWidth(histogramTTV);
  }    
  TH1* histogramEWK_density = 0;
  if ( histogramEWK ) {
    if ( histogramData ) checkCompatibleBinning(histogramEWK, histogramData);
    histogramEWK_density = divideHistogramByBinWidth(histogramEWK);
  }
  TH1* histogramRares_density = 0;
  if ( histogramRares ) {
    if ( histogramData ) checkCompatibleBinning(histogramRares, histogramData);
    histogramRares_density = divideHistogramByBinWidth(histogramRares);
  }    
  TH1* histogramBgrSum_density = 0;
  if ( histogramBgrSum ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrSum, histogramData);
    histogramBgrSum_density = divideHistogramByBinWidth(histogramBgrSum); 
  }
  TH1* histogramBgrUncertainty_density = 0;
  if ( histogramBgrUncertainty ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrUncertainty, histogramData);
    histogramBgrUncertainty_density = divideHistogramByBinWidth(histogramBgrUncertainty);
  }
  
  TCanvas* canvas = new TCanvas("canvas", "", canvasSizeX, canvasSizeY);
  canvas->SetFillColor(10);
  canvas->SetFillStyle(4000);
  canvas->SetFillColor(10);
  canvas->SetTicky();
  canvas->SetBorderSize(2);  
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);
  
  TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.065);
  topPad->SetLeftMargin(0.15);
  topPad->SetBottomMargin(0.03);
  topPad->SetRightMargin(0.05);
  topPad->SetLogy(useLogScale);
  
  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.02);
  bottomPad->SetLeftMargin(0.15);
  bottomPad->SetBottomMargin(0.31);
  bottomPad->SetRightMargin(0.05);
  bottomPad->SetLogy(false);
  
  canvas->cd();
  topPad->Draw();
  topPad->cd();
  
  TAxis* xAxis_top = histogramData_density->GetXaxis();
  xAxis_top->SetTitle(xAxisTitle.data());
  xAxis_top->SetTitleOffset(xAxisOffset);
  xAxis_top->SetLabelColor(10);
  xAxis_top->SetTitleColor(10);
    
  TAxis* yAxis_top = histogramData_density->GetYaxis();
  yAxis_top->SetTitle(yAxisTitle.data());
  yAxis_top->SetTitleOffset(yAxisOffset);
  yAxis_top->SetTitleSize(0.085);
  yAxis_top->SetLabelSize(0.05);
  yAxis_top->SetTickLength(0.04);  
  
  TLegend* legend = new TLegend(0.66, 0.45, 0.94, 0.92, NULL, "brNDC");
  legend->SetFillStyle(0);
  legend->SetBorderSize(0);
  legend->SetFillColor(10);
  legend->SetTextSize(0.055);
  
  histogramData_density->SetTitle("");
  histogramData_density->SetStats(false);
  histogramData_density->SetMaximum(yMax);
  histogramData_density->SetMinimum(yMin);
  histogramData_density->SetMarkerStyle(20);
  histogramData_density->SetMarkerSize(2);
  histogramData_density->SetMarkerColor(kBlack);
  histogramData_density->SetLineColor(kBlack);
  legend->AddEntry(histogramData_density, "Observed", "p");    
  
  histogramData_density->Draw("ep");
  
  legend->AddEntry(histogramTTH_density, "t#bar{t}H", "l");

  histogramTT_density->SetTitle("");
  histogramTT_density->SetStats(false);
  histogramTT_density->SetMaximum(yMax);
  histogramTT_density->SetMinimum(yMin);
  histogramTT_density->SetFillColor(kMagenta - 10); 
  legend->AddEntry(histogramTT_density, "t#bar{t}+jets", "f");

  histogramTTV_density->SetFillColor(kOrange - 4);
  legend->AddEntry(histogramTTV_density, "t#bar{t}+V", "f");

  histogramEWK_density->SetFillColor(kRed + 2); 
  legend->AddEntry(histogramEWK_density, "EWK", "f");

  histogramRares_density->SetFillColor(kBlue - 8); 
  legend->AddEntry(histogramRares_density, "Rares", "f");

  THStack* histogramStack_density = new THStack("stack", "");
  histogramStack_density->Add(histogramRares_density);
  histogramStack_density->Add(histogramEWK_density);
  histogramStack_density->Add(histogramTTV_density);
  histogramStack_density->Add(histogramTT_density);
  histogramStack_density->Draw("histsame");
  
  histogramBgrUncertainty_density->SetFillColor(kBlack);
  histogramBgrUncertainty_density->SetFillStyle(3344);    
  histogramBgrUncertainty_density->Draw("e2same");
  legend->AddEntry(histogramBgrUncertainty_density, "Uncertainty", "f");

  histogramTTH_density->SetLineWidth(2);
  histogramTTH_density->SetLineStyle(1);
  histogramTTH_density->SetLineColor(kBlue);
  histogramTTH_density->Draw("histsame");
  
  histogramData_density->Draw("epsame");
  histogramData_density->Draw("axissame");
  
  legend->Draw();
  
  addLabel_CMS_luminosity(0.2050, 0.9225, 0.6850);
  
  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();
  
  TH1* histogramRatio = (TH1*)histogramData->Clone("histogramRatio");
  histogramRatio->Reset();
  if ( !histogramRatio->GetSumw2N() ) histogramRatio->Sumw2();
  checkCompatibleBinning(histogramRatio, histogramBgrSum);
  histogramRatio->Divide(histogramData, histogramBgrSum);
  int numBins_bottom = histogramRatio->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins_bottom; ++iBin ) {
    double binContent = histogramRatio->GetBinContent(iBin);
    if ( histogramData && histogramData->GetBinContent(iBin) >= 0. ) histogramRatio->SetBinContent(iBin, binContent - 1.0);
    else histogramRatio->SetBinContent(iBin, -10.);
  }
  histogramRatio->SetTitle("");
  histogramRatio->SetStats(false);
  histogramRatio->SetMinimum(-0.50);
  histogramRatio->SetMaximum(+0.50);
  histogramRatio->SetMarkerStyle(histogramData_density->GetMarkerStyle());
  histogramRatio->SetMarkerSize(histogramData_density->GetMarkerSize());
  histogramRatio->SetMarkerColor(histogramData_density->GetMarkerColor());
  histogramRatio->SetLineColor(histogramData_density->GetLineColor());
  histogramRatio->Draw("ep");
  
  TAxis* xAxis_bottom = histogramRatio->GetXaxis();
  xAxis_bottom->SetTitle(xAxis_top->GetTitle());
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleOffset(1.20);
  xAxis_bottom->SetTitleSize(0.13);
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.10);
  xAxis_bottom->SetTickLength(0.055);
  
  TAxis* yAxis_bottom = histogramRatio->GetYaxis();
  yAxis_bottom->SetTitle("#frac{Data - Simulation}{Simulation}");
  yAxis_bottom->SetTitleOffset(0.80);
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.09);
  yAxis_bottom->SetLabelSize(0.10);
  yAxis_bottom->SetTickLength(0.04);  
  
  TH1* histogramRatioUncertainty = (TH1*)histogramBgrUncertainty->Clone("histogramRatioUncertainty");
  if ( !histogramRatioUncertainty->GetSumw2N() ) histogramRatioUncertainty->Sumw2();
  checkCompatibleBinning(histogramRatioUncertainty, histogramBgrUncertainty);
  histogramRatioUncertainty->Divide(histogramBgrSum);
  int numBins = histogramRatioUncertainty->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    double binContent = histogramRatioUncertainty->GetBinContent(iBin);
    histogramRatioUncertainty->SetBinContent(iBin, binContent - 1.0);
  }
  histogramRatioUncertainty->SetFillColor(histogramBgrUncertainty_density->GetFillColor());
  //histogramRatioUncertainty->SetFillStyle(histogramBgrUncertainty_density->GetFillStyle());    
  histogramRatioUncertainty->SetFillStyle(3644);    
  
  TF1* line = new TF1("line","0", xAxis_bottom->GetXmin(), xAxis_bottom->GetXmax());
  line->SetLineStyle(3);
  line->SetLineWidth(1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  
  histogramRatioUncertainty->Draw("e2same");
  
  histogramRatio->Draw("epsame");
  
  canvas->Update();
  size_t idx = outputFileName.find(".");
  std::string outputFileName_plot(outputFileName, 0, idx);
  if ( useLogScale ) outputFileName_plot.append("_log");
  else outputFileName_plot.append("_linear");
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());
  
  delete histogramTTH_density;
  delete histogramData_density;
  delete histogramTT_density;
  delete histogramTTV_density;
  delete histogramEWK_density;
  delete histogramRares_density;
  delete histogramBgrSum_density;
  //delete histogramBgrUncertainty_density;
  delete histogramStack_density;
  delete legend;
  delete topPad;
  delete histogramRatio;
  delete histogramRatioUncertainty;
  delete line;
  delete bottomPad;    
  delete canvas;
}
Esempio n. 10
0
void boostcontrolplots( TDirectory *boostdir ) {

   const Int_t nPlots = 4;

   Int_t width  = 900;
   Int_t height = 900;
   char cn[100];
   const TString titName = boostdir->GetName();
   sprintf( cn, "cv_%s", titName.Data() );
   TCanvas *c = new TCanvas( cn,  Form( "%s Control Plots", titName.Data() ),
                             width, height ); 
   c->Divide(2,3);


   const TString titName = boostdir->GetName();

   TString hname[nPlots]={"Booster_BoostWeight","Booster_MethodWeight","Booster_ErrFraction","Booster_OrigErrFraction"};

   for (Int_t i=0; i<nPlots; i++){
      Int_t color = 4; 
      TPad * cPad = (TPad*)c->cd(i+1);
      TH1 *h = (TH1*) boostdir->Get(hname[i]);
      TString plotname = h->GetName();
      h->SetMaximum(h->GetMaximum()*1.3);
      h->SetMinimum( 0 );
      h->SetMarkerColor(color);
      h->SetMarkerSize( 0.7 );
      h->SetMarkerStyle( 24 );
      h->SetLineWidth(2);
      h->SetLineColor(color);
      h->Draw();
      c->Update();
   }

   // draw combined ROC plots

   TString hname_roctest[2] ={"Booster_ROCIntegral_test",  "Booster_ROCIntegralBoosted_test"};
   TString hname_roctrain[2]={"Booster_ROCIntegral_train", "Booster_ROCIntegralBoosted_train"};
   TString htitle[2] = {"ROC integral of single classifier", "ROC integral of boosted method"}

   for (Int_t i=0; i<2; i++){
      Int_t color = 4; 
      TPad * cPad = (TPad*)c->cd(nPlots+i+1);
      TH1 *htest  = (TH1*) boostdir->Get(hname_roctest[i]);
      TH1 *htrain = (TH1*) boostdir->Get(hname_roctrain[i]);

      // check if filled 
      Bool_t histFilled = (htest->GetMaximum() > 0 || htrain->GetMaximum() > 0);

      htest->SetTitle(htitle[i]);
      htest->SetMaximum(1.0);
      htest->SetMinimum(0.0);
      htest->SetMarkerColor(color);
      htest->SetMarkerSize( 0.7 );
      htest->SetMarkerStyle( 24 );
      htest->SetLineWidth(2);
      htest->SetLineColor(color);
      htest->Draw();
      htrain->SetMaximum(1.0);
      htrain->SetMinimum(0.0);
      htrain->SetMarkerColor(color-2);
      htrain->SetMarkerSize( 0.7 );
      htrain->SetMarkerStyle( 24 );
      htrain->SetLineWidth(2);
      htrain->SetLineColor(color-2);
      htrain->Draw("same");

      if (histFilled) {
         TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                       0.2 + cPad->GetBottomMargin(),
                                       cPad->GetLeftMargin() + 0.6, 
                                       cPad->GetBottomMargin() );
         legend->AddEntry(htest,  TString("testing sample"),  "L");
         legend->AddEntry(htrain, TString("training sample (orig. weights)"), "L");
         legend->SetFillStyle( 1 );
         legend->SetBorderSize(1);
         legend->SetMargin( 0.3 );
         legend->Draw("same");
      }
      else {
         TText* t = new TText();
         t->SetTextSize( 0.056 );
         t->SetTextColor( 2 );
         t->DrawText( 1, 0.6, "Use MethodBoost option: \"DetailedMonitoring\" " );        
         t->DrawText( 1, 0.51, "to fill this histograms" );        
      }

      c->Update();
   }

   // write to file
   TString fname = Form( "plots/%s_ControlPlots", titName.Data() );
   TMVAGlob::imgconv( c, fname );
   
}
Esempio n. 11
0
void makeEffToys(Int_t seed, TString veto="D") {
//	r.SetSeed(seed);
	r = RooRandom::randomGenerator();
	r->SetSeed(seed);

	TFile* fin = TFile::Open(veto+"veto_200.root");

	TString fName("toys/"); fName+=seed; fName+="/"+veto+"veto_200.root";

	TFile* fout = new TFile(fName,"RECREATE");

	for(Int_t j=0; j<21; ++j) {
		TString hName  = "efficiency_"; hName+=j;
		TString hName2 = "efficiencyHist_"; hName2+=j;
		TEfficiency* hin = dynamic_cast<TEfficiency*>(fin->Get(hName));

		TH1* hout = dynamic_cast<TH1*>(hin->GetTotalHistogram()->Clone(hName2));

		std::vector<Int_t> corrBins;

		Int_t n = hout->GetNbinsX();
		for(Int_t i=0; i<n; ++i) {
			Double_t eff = hin->GetEfficiency(i+1);
			Double_t erm = hin->GetEfficiencyErrorLow(i+1);
			Double_t erp = hin->GetEfficiencyErrorUp(i+1);

			Bool_t fluctuate = kTRUE;

			// don't fluctuate if the veto hasn't affected this bin
			// also ignore the odd missing entry - not sure what causes these but they don't seem reasonable
			if((eff > 0.99 && eff + erp > 0.999) //efficiency close to 1 and not significantly different
			|| ((i<1 || hin->GetEfficiency(i) == 1) && (i>n-1 || hin->GetEfficiency(i+2) == 1))) { //single bin dip (careful with this one)
				eff = 1;
				fluctuate = kFALSE;
			}
			if(eff < 0.01 && eff - erm < 0.001) {//efficiency close to 0 and not significantly different
				eff = 0;
				fluctuate = kFALSE;
			}

			//otherwise we're fluctuating the bin
			if(fluctuate) {
				//if the errors are roughly symmetric then we can symmetrise them and introduce some correlation between neighbouring bins
				//this is difficult to do with asymmetric errors so if asymmetry > 10% lets just ignore correlations
				//note that a large asymmetry in neighbouring bins will also lead to same-sign fluctuations anyway
				if((erm - erp) / (erm + erp) < 0.1) {
					//correlation is more important than asymmetry

					//add bin to the list to be fluctuated later
					corrBins.push_back(i+1);

				} else {
					//asymmetry is more important than correlation

					//first catch any cases on a limit (the previous checks for eff > 0.99 and eff < 0.01 should catch these but play it safe)
					if(erm <= 0) {
						//vary with a half Gaussian
						eff += TMath::Abs(r->Gaus(0.,erp));
					} else if(erp <= 0) {
						//vary with a half Gaussian
						eff -= TMath::Abs(r->Gaus(0.,erm));
					} else {
						//vary with a bifurcated Gaussian
						RooRealVar effVar( "effVar", "",-1.,2.);
						RooRealVar muVar(  "muVar",  "",eff);
						RooRealVar sigmVar("sigmVar","",erm);
						RooRealVar sigpVar("sigpVar","",erp);

						RooBifurGauss pdf("pdf","",effVar,muVar,sigmVar,sigpVar);
						RooDataSet* ds = pdf.generate(RooArgSet(effVar),1);
						eff = ds->get(0)->getRealValue("effVar");
						delete ds;
					}
				}
			}
			if(eff > 1.0) eff = 1.0; //std::cout << i << "\t" << eff << "\t" << erp << "\t" << erm << std::endl;
//			std::cout << hin->GetEfficiency(i+1) << "\t" << eff << std::endl;

			hout->SetBinContent(i+1, eff);
		}

		//now deal with the correlated efficiencies
		Double_t corrFactor(0.01);

		while(!doCorrelatedBinFluctuation(hin,hout,corrBins,corrFactor)) {
			corrFactor /= 2.;
		}

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

		TCanvas c;
		hin->Draw();
		hout->SetMarkerColor(kRed);
		hout->SetMarkerStyle(4);
		hout->Draw("Psame");
		TString pName = "plots/toys/"; pName+=seed; pName+="/"+veto+"veto_Q"; pName+=j; pName+=".pdf";
		c.SaveAs(pName);
	}

	hout->Write();
	fout->Close();
}
Esempio n. 12
0
void MakePi0Analysis(){

  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.01);
  gStyle->SetPadTopMargin(0.09);
  gStyle->SetPadBottomMargin(0.11);
  //gStyle->SetOptStat(0);
  //gStyle->SetOptTitle(1);
  //gStyle->SetPadTickX(1);
  //gStyle->SetPadTickY(1);
  TGaxis::SetMaxDigits(3);
  
  Double_t bins[] = {1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0, 3.2, 3.4, 3.6,3.8,4.0,4.5, 5.0, 5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,10.0,11,12}; //Nicolas LHC12d PHI
  const Int_t binnum = sizeof(bins)/sizeof(Double_t) - 1;
  
  TString cwd = gSystem->WorkingDirectory();

  TH1F* fHistPeakMean  = new TH1F("fHistPeakMean","",binnum,bins);
  TH1F* fHistPeakWidth = new TH1F("fHistPeakWidth","",binnum,bins);
  TH1F* fHistRawYield  = new TH1F("fHistRawYield","",binnum,bins);
  TH1F* fHistRawYieldPerEvent  = new TH1F("fHistRawYieldPerEvent","",binnum,bins);
  
  TCanvas *c1[binnum];
  TCanvas *c2[binnum];
  TCanvas *c3;

  TFile* ef     = TFile::Open("../AnalysisResults.root");
  TList* list   = (TList*)ef->Get("list_kINT7_Pi0");
  TList *listEv = (TList*)ef->Get("list_kINT7_Event");
  
  TH1F* fHistEvents = (TH1F*)listEv->FindObject("fHistAnalyzedEvents");
  Double_t nEvt = fHistEvents->GetEntries();
  
  TString tofName[] = {"","_TOFcut1","_TOFcut2"};
  TString fitName[] = {"CrystalBall","AsymmGauss"};
  TString modName[] = {"","_M1","_M3"};
  
  Int_t ntof = 3;
  
  Double_t signal_range_min=0.11;
  Double_t signal_range_max=0.15;
  Double_t bg_range_min=0.050;
  Double_t bg_range_max=0.250;
  
  for(Int_t itof=0; itof<ntof; ++itof){
    for(Int_t iMod=0; iMod<1; iMod++){
      for(Int_t iFit=0; iFit<2; iFit++){
	for(Int_t iPol=0; iPol<3; iPol++){
	  
	  Int_t pol = iPol;

	  TString fNameSame = "fHistMassTwoGammas"+tofName[itof]+modName[iMod];
	  TString fNameMix  = "fHistMixMassTwoGammas"+tofName[itof]+modName[iMod];
	  
	  THnSparse *fTHnSparseRecPi0;
	  THnSparse *fTHnSparseRecMixPi0;
	  THnSparse *fTHnSparseGeneratePi0;
	  
	  TH2* hPi0A08    = 0x0;
	  TH2* hMixPi0A08 = 0x0;
	  hPi0A08    = (TH2*)list->FindObject(fNameSame)->Clone();
	  hMixPi0A08 = (TH2*)list->FindObject(fNameMix)->Clone();

	  Int_t sbin = 0;
	  Int_t lbin = 0;
      
	  TH1F* fHistFinalRatio[binnum];
	  TH1F* fHistFinalSame[binnum];
	  TH1F* fHistFinalBG[binnum];
	  TH1F* fHistFinalSignal[binnum];
	  TH1F* fHistOnlyFitSignal[binnum];
	  
	  TF1* fFitFinalRatio[binnum];
	  TF1* fFitFinalSignal[binnum];
	  TF1* fFitOnlyFitSignal[binnum];

	  for(Int_t i=0; i<binnum; i++){    
	    
	    Double_t bin_width = (bins[i+1]-bins[i]);
	    Double_t bin_mean  = (bins[i+1]+bins[i])/2;
	    
	    Int_t rebin = 1;
	    
	    if(bin_mean>5.0){
	      rebin=10;
	    }
	    else{
	      rebin=5;
	    }
	    
	    Int_t sproj_bin = hPi0A08->GetYaxis()->FindBin(bins[i]);
	    Int_t lproj_bin = hPi0A08->GetYaxis()->FindBin(bins[i+1])-1;
	    
	    TH1* fHistBasicSame = (TH1*)hPi0A08   ->ProjectionX(Form("fHistBasicSame_No%d",i+1),sproj_bin,lproj_bin,""); 
	    TH1* fHistBasicMix  = (TH1*)hMixPi0A08->ProjectionX(Form("fHistBasicMix_No%d",i+1),sproj_bin,lproj_bin,""); 
	    fHistBasicSame->Rebin(rebin);
	    fHistBasicMix->Rebin(rebin);
	    fHistBasicSame->Sumw2();
	    fHistBasicMix->Sumw2();
	    fHistBasicSame->GetYaxis()->SetTitle(Form("dN/dM per %.0f MeV/c^{2}",fHistBasicSame->GetBinWidth(1)*1000));
	    fHistBasicMix->GetYaxis()->SetTitle(Form("dN/dM per %.0f MeV/c^{2}",fHistBasicSame->GetBinWidth(1)*1000));
	    fHistBasicSame->GetXaxis()->SetRange(fHistBasicSame->GetXaxis()->FindBin(0.),fHistBasicSame->GetXaxis()->FindBin(0.3)-1);
	    fHistBasicMix->GetXaxis()->SetRange(fHistBasicSame->GetXaxis()->FindBin(0.),fHistBasicSame->GetXaxis()->FindBin(0.3)-1);
	    fHistBasicSame->SetMarkerStyle(20);
	    fHistBasicMix->SetMarkerStyle(24);
	    fHistBasicSame->SetMarkerColor(kBlack);
	    fHistBasicMix->SetMarkerColor(kBlue);
	    fHistBasicSame->SetLineColor(kBlack);
	    fHistBasicMix->SetLineColor(kBlue);
	    
	    fHistFinalSame[i]     = (TH1F*)fHistBasicSame->Clone();
	    fHistOnlyFitSignal[i] = (TH1F*)fHistBasicSame->Clone();
	    fHistOnlyFitSignal[i]->SetName(Form("fHistOnlyFitSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);


	    TH1F* fHistOnlyFit_Signal = (TH1F*)fHistOnlyFitSignal[i]->Clone();
	    TH1F* fHistOnlyFit_BG     = (TH1F*)fHistOnlyFitSignal[i]->Clone();
	    
	    TH1F* fHistRatio     = (TH1F*)fHistBasicSame->Clone();
	    fHistRatio->Divide(fHistBasicMix);
	    fHistRatio->SetName(Form("cRatioSameBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    
	    TH1F* fHistRatio_Signal = (TH1F*)fHistRatio->Clone();
	    TH1F* fHistRatio_BG     = (TH1F*)fHistRatio->Clone();
	    
	    Int_t ssignal_bin = fHistRatio_Signal->GetXaxis()->FindBin(signal_range_min);
	    Int_t lsignal_bin = fHistRatio_Signal->GetXaxis()->FindBin(signal_range_max);
	    Int_t sbg_bin = fHistRatio_BG->GetXaxis()->FindBin(bg_range_min);
	    Int_t lbg_bin = fHistRatio_BG->GetXaxis()->FindBin(bg_range_max);
	    
	    for(Int_t j=ssignal_bin; j<lsignal_bin; ++j){
	      fHistRatio_BG->SetBinContent(j,0);
	      fHistRatio_BG->SetBinError(j,0);
	      fHistOnlyFit_BG->SetBinContent(j,0);
	      fHistOnlyFit_BG->SetBinError(j,0);
	    }
	    for(Int_t j=sbg_bin; j<ssignal_bin; ++j){
	      fHistRatio_Signal->SetBinContent(j,0);
	      fHistRatio_Signal->SetBinError(j,0);
	      fHistOnlyFit_Signal->SetBinContent(j,0);
	      fHistOnlyFit_Signal->SetBinError(j,0);
	    }
	    for(Int_t j=lsignal_bin; j<lbg_bin; ++j){
	      fHistRatio_Signal->SetBinContent(j,0);
	      fHistRatio_Signal->SetBinError(j,0);
	      fHistOnlyFit_Signal->SetBinContent(j,0);
	      fHistOnlyFit_Signal->SetBinError(j,0);
	    }
	    
	    ///////////////////////////////////////////////////////////////////////////////////////////////////
	    // Combinatrial background analysis
	    ///////////////////////////////////////////////////////////////////////////////////////////////////
	    
	    TF1 *fFitRatio_Signal = NULL;
	    if(iFit==0){
	      fFitRatio_Signal = new TF1("fFitRatio_Signal",
					 "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]",
					 signal_range_min,signal_range_max);
	      fFitRatio_Signal->SetParameters(1.,6.,0.135,0.005,0.01);
	      fFitRatio_Signal->FixParameter(0,1.16053);
	      fFitRatio_Signal->FixParameter(1,6.);
	      fFitRatio_Signal->SetParLimits(2,0.130,0.140);
	      fFitRatio_Signal->SetParLimits(3,0.005,0.03);
	    }
	    else if(iFit==1){//[0]=A, [1]=M_pi0, [2]=sigma, [3]=lamda
	      fFitRatio_Signal = new TF1("fFitRatio_Signal",
					 "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) )",
					 signal_range_min,signal_range_max);
	      fFitRatio_Signal->SetParameters(1,0.135,6.46624e-03,7.47626e-03);
	      fFitRatio_Signal->SetParLimits(1,0.130,0.140);
	      fFitRatio_Signal->SetParLimits(2,0.001,0.03);
	      fFitRatio_Signal->SetParLimits(3,0.001,0.03);
	    }
	    
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    
	    TF1 *fFitRatio_BG = 0x0;
	    if(pol==0){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]",0,1);
	    }
	    else if(pol==1){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]+[1]*x",0,1);
	    }
	    else if(pol==2){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]+[1]*x+[2]*x*x",0,1);
	    }
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    
	    TF1 *fFitRatio_SignalBG = 0x0;
	    TF1 *fFitScale = 0x0;
	    
	    if(iFit==0){
	      if(pol==0){
		fFitRatio_SignalBG= new TF1("fFitRatio_SignalBG",
					    "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]",0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol0",0.,1);
	      }
	      else if(pol==1){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]+[6]*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol1",0,1);
	      }
	      else if(pol==2){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]+[6]*x+[7]*x*x",0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(6,fFitRatio_BG->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(7,fFitRatio_BG->GetParameter(2));
		fFitScale = new TF1("fFitScale","pol2",0,1);
	      }
	      
	      fFitRatio_SignalBG->FixParameter(0,1.16053);
	      fFitRatio_SignalBG->FixParameter(1,6.);
	      fFitRatio_SignalBG->SetParLimits(2,0.130,0.140);
	      fFitRatio_SignalBG->SetParLimits(3,0.005,0.03);
	    }
	    
	    if(iFit==1){
	      if(pol==0){
		fFitRatio_SignalBG= new TF1("fFitRatio_SignalBG",
					    "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]",
					    0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol0",0,1);
	      }
	      else if(pol==1){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]+[5]*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(1));
		fFitScale = new TF1("fFitScale","pol1",0,1);
	      }
	      else if(pol==2){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]+[5]*x+[6]*x*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(6,fFitRatio_BG->GetParameter(2));
		fFitScale = new TF1("fFitScale","pol2",0,1);
	      }
	      fFitRatio_SignalBG->SetParLimits(1,0.130,0.140);
	      fFitRatio_SignalBG->SetParLimits(2,0.005,0.03);
	      fFitRatio_SignalBG->SetParLimits(3,0.005,0.03);
	    }

	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    
	    fHistFinalRatio[i] = (TH1F*)fHistRatio->Clone();;
	    fFitFinalRatio[i]  = (TF1*)fFitRatio_SignalBG->Clone();
	    
	    if(iFit==0){
	      if(pol==0){
		fFitScale->SetParameter(0,fFitRatio_SignalBG->GetParameter(5));
	      }
	      else if(pol==1){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6));
	      }
	      else if(pol==2){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6),fFitRatio_SignalBG->GetParameter(7));
	      }
	    }	
	    if(iFit==1){
	      if(pol==0){
		fFitScale->SetParameter(0,fFitRatio_SignalBG->GetParameter(4));
	      }
	      else if(pol==1){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(4),fFitRatio_SignalBG->GetParameter(5));
	      }
	      else if(pol==2){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(4),fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6));
	      }
	    }	
	    
	    c3 = new TCanvas("c3","c3",600,600);
	    c3->cd();
	    fHistRatio->Draw();
	    fFitRatio_SignalBG->Draw("same");
	    fFitScale->Draw("same");
	    c3->SetName(Form("cRatioSameBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    tfout->WriteTObject(c3);

	    TH1F* fHistScaledMix = (TH1F*)fHistBasicMix->Clone();
	    fHistScaledMix->Multiply(fFitScale);
	    fHistFinalBG[i] = (TH1F*)fHistScaledMix->Clone();;
	    
	    TH1F* fHistSignal = (TH1F*)fHistBasicSame->Clone();
	    fHistSignal->SetName(Form("fHistSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistScaledMix->SetName(Form("fHistScaledMix_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    tfout->WriteTObject(fHistSignal);
	    tfout->WriteTObject(fHistScaledMix);
	    
	    for(Int_t j=0; j<fHistBasicSame->GetXaxis()->FindBin(0.3); ++j){
	      Double_t same   = fHistSignal->GetBinContent(j);
	      Double_t e_same = fHistSignal->GetBinError(j);
	      Double_t mix    = fHistScaledMix->GetBinContent(j);
	      Double_t e_mix  = fHistScaledMix->GetBinError(j);
	      
	      Double_t signal   = same - mix;
	      Double_t e_signal = sqrt(pow(e_same,2)+pow(e_mix,2));
	      
	      if(same>0){
		signal   = same - mix;
		e_signal = sqrt(pow(e_same,2)+pow(e_mix,2));
	      }
	      else{
		signal   = same;
		e_signal = e_same;
	      }
	      
	      fHistSignal->SetBinContent(j,signal);
	      fHistSignal->SetBinError(j,e_signal);
	    }
	    
	    fHistFinalSignal[i] = (TH1F*)fHistSignal->Clone();
	    fHistFinalSignal[i]->SetTitle(Form("%.2f < #it{p}_{T} %.2f (GeV/c)", bins[i], bins[i+1]));

	    TF1 *fFitSignal = NULL;
	    
	    if(iFit==0){
	      fFitSignal = new TF1("fFitSignal", "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])",
				   0,0.3);
	      fFitSignal->SetParameters(1.,6.,0.135,0.005,0.01);

	      fFitSignal->FixParameter(0,1.16053);
	      fFitSignal->FixParameter(1,6.);

	      fFitSignal->SetParLimits(2,0.120,0.140);
	      fFitSignal->SetParLimits(3,0.005,0.03);
	    
	    }	
	    else if(iFit==1){
	      fFitSignal = new TF1("fFitSignal",
				   "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) )",
				   0,0.3);
	      fFitSignal->SetParameters(1,0.135,6.46624e-03,7.47626e-03);
	      fFitSignal->SetParLimits(1,0.125,0.140);
	      fFitSignal->SetParLimits(2,0.001,0.01);
	      fFitSignal->SetParLimits(3,0.001,0.01);
	    }
	    
	    fHistSignal->Fit(fFitSignal,"RNQ","",signal_range_min,signal_range_max);
	    fHistSignal->Fit(fFitSignal,"RNQ","",0.12,signal_range_max);
	    
	    
	    if(iFit==0){
	      fHistSignal->Fit(fFitSignal,"RNQ","",0.12,0.150);
	    }	
	    else{
	      fHistSignal->Fit(fFitSignal,"RNQ","",0.12,0.150);
	    }

	    fFitFinalSignal[i]  = (TF1*)fFitSignal->Clone();
	    
	    Double_t mean   = 0;
	    Double_t e_mean = 0;
	    Double_t signal_sigma   = 0;
	    Double_t e_signal_sigma = 0;
	    Double_t signal_window_min = 0;
	    Double_t signal_window_max = 0;
	    
	    if(iFit==0){
	      mean   = fFitSignal->GetParameter(2);
	      e_mean = fFitSignal->GetParError(2);
	      signal_sigma   = fabs(fFitSignal->GetParameter(3));
	      e_signal_sigma = fabs(fFitSignal->GetParError(3));
	      
	      signal_window_min = mean - signal_sigma*5;
	      signal_window_max = mean + signal_sigma*3;
	      
	    }
	    else if(iFit==1){
	      mean   = fFitSignal->GetParameter(1);
	      e_mean = fFitSignal->GetParError(1);
	      signal_sigma   = fabs(fFitSignal->GetParameter(2));
	      e_signal_sigma = fabs(fFitSignal->GetParError(2));
	      signal_window_min = mean - signal_sigma*5;
	      signal_window_max = mean + signal_sigma*3;
	    }
	  
	    fHistPeakMean->SetBinContent(i+1,mean);
	    fHistPeakMean->SetBinError(i+1,e_mean);
	    fHistPeakWidth->SetBinContent(i+1,signal_sigma);
	    fHistPeakWidth->SetBinError(i+1,e_signal_sigma);
	    
	    Int_t signal_window_bin_min = fHistSignal->GetXaxis()->FindBin(signal_window_min);
	    Int_t signal_window_bin_max = fHistSignal->GetXaxis()->FindBin(signal_window_max);
	    
	    Double_t num_pi0 = 0;
	    Double_t e_num_pi0 = 0;
	    
	    for(Int_t j=signal_window_bin_min; j<signal_window_bin_max; ++j){
	      num_pi0   += fHistSignal->GetBinContent(j);
	      e_num_pi0 += pow(fHistSignal->GetBinError(j),2);
	    }
	    e_num_pi0 = sqrt(e_num_pi0);
	    
	    fHistRawYield->SetBinContent(i+1,num_pi0/bin_width);
	    fHistRawYield->SetBinError(i+1,e_num_pi0/bin_width);
	    
	  }

	  fHistRawYield->SetName(Form("fHistRawYieldPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistRawYield);
	  
	  fHistRawYieldPerEvent = (TH1F*)fHistRawYield->Clone();
	  fHistRawYieldPerEvent->Scale(1./nEvt);
	  fHistRawYieldPerEvent->SetName(Form("fHistRawYieldPerEventPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistRawYieldPerEvent);
	  
	  fHistPeakMean->SetName(Form("fHistPeakMeanPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  fHistPeakWidth->SetName(Form("fHistPeakWidthPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistPeakMean);
	  tfout->WriteTObject(fHistPeakWidth);
	  
	  c1[itof] = new TCanvas("c1"+fitName[iFit]+tofName[itof],"",1200,1800);
	  c2[itof] = new TCanvas("c2"+fitName[iFit]+tofName[itof],"",1200,1800);
	  
	  c1[itof]->Divide(4,6);
	  for(Int_t i=0; i<binnum; ++i){
	    c1[itof]->cd(i+1);
	    fHistFinalSignal[i]->Draw();
	    fFitFinalSignal[i]->Draw("same");
	  }
	  
	  c1[itof]->SaveAs(Form("cInvariantMassSpectrumPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]+".eps");
	  
	  c2[itof]->Divide(4,6);
	  for(Int_t i=0; i<binnum; ++i){
	    c2[itof]->cd(i+1);
	    fHistFinalSame[i]->Draw();
	    fHistFinalBG[i]->Draw("same");
	  }
	  c2[itof]->SaveAs(Form("cSameScaledMixPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]+".eps");
	  
	  for(Int_t i=0; i<binnum; ++i){
	    
	    fHistFinalSignal[i]->SetName(Form("fHistFinalSignal_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fFitFinalSignal[i]->SetName(Form("fFitFinalSignal_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistFinalSame[i]->SetName(Form("fHistFinalSame_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistFinalBG[i]->SetName(Form("fHistFinalBG_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    
	    tfout->WriteTObject(fHistFinalSignal[i]);
	    tfout->WriteTObject(fFitFinalSignal[i]);
	    tfout->WriteTObject(fHistFinalSame[i]);
	    tfout->WriteTObject(fHistFinalBG[i]);
	    
	    c3 = new TCanvas("c3","",600,600);
	    c3->cd(1);
	    fHistFinalSame[i]->Draw();
	    fHistFinalBG[i]->Draw("same");
	    c3->SetName(Form("cRawSignalBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    //tfout->WriteTObject(c3);
	  }
	  for(Int_t i=0; i<binnum; ++i){
	    c3 = new TCanvas("c3","",600,600);
	    c3->cd(1);
	    fHistFinalSignal[i]->Draw("");
	    fFitFinalSignal[i]->Draw("same");
	    c3->SetName(Form("cRawSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    //tfout->WriteTObject(c3);
	  }
	  
	}	
      }
    }
  }  
  
}
Esempio n. 13
0
void bdtcontrolplots( TDirectory *bdtdir ) {

   const Int_t nPlots = 6;

   Int_t width  = 900;
   Int_t height = 600;
   char cn[100], cn2[100];
   const TString titName = bdtdir->GetName();
   sprintf( cn, "cv_%s", titName.Data() );
   TCanvas *c = new TCanvas( cn,  Form( "%s Control Plots", titName.Data() ),
                             width, height ); 
   c->Divide(3,2);




   TString hname[nPlots]={"BoostMonitor","BoostWeight","BoostWeightVsTree","ErrFractHist","NodesBeforePruning",titName+"_FOMvsIterFrame"};

   Bool_t BoostMonitorIsDone=kFALSE;

   for (Int_t i=0; i<nPlots; i++){
      Int_t color = 4; 
      TPad * cPad;
      cPad = (TPad*)c->cd(i+1);
      TH1 *h = (TH1*) bdtdir->Get(hname[i]);
      
      if (h){
         h->SetMaximum(h->GetMaximum()*1.3);
         h->SetMinimum( 0 );
         h->SetMarkerColor(color);
         h->SetMarkerSize( 0.7 );
         h->SetMarkerStyle( 24 );
         h->SetLineWidth(1);
         h->SetLineColor(color);
         if(hname[i]=="NodesBeforePruning")h->SetTitle("Nodes before/after pruning");
         h->Draw();
         if(hname[i]=="NodesBeforePruning"){
            TH1 *h2 = (TH1*) bdtdir->Get("NodesAfterPruning");
            h2->SetLineWidth(1);
            h2->SetLineColor(2);
            h2->Draw("same");
         }
         if(hname[i]=="BoostMonitor"){ // a plot only available in case DoBoostMontior option has bee set
            TGraph *g = (TGraph*) bdtdir->Get("BoostMonitorGraph");
            g->Draw("LP*");
            BoostMonitorIsDone = kTRUE;
         }
         if(hname[i]==titName+"_FOMvsIterFrame"){ // a plot only available in case DoBoostMontior option has bee set
            TGraph *g = (TGraph*) bdtdir->Get(titName+"_FOMvsIter");
            g->Draw();
         }
         c->Update();
      }
   }
   
   
   TCanvas *c2 = NULL;
   if (BoostMonitorIsDone){
      sprintf( cn2, "cv2_%s", titName.Data() );
      c2 = new TCanvas( cn2,  Form( "%s BoostWeights", titName.Data() ),
                                 1200, 1200 ); 
      c2->Divide(5,5);
      Int_t ipad=1;
      
      TIter keys( bdtdir->GetListOfKeys() );
      TKey *key;
      //      gDirectory->ls();
      while ( (key = (TKey*)keys.Next()) && ipad < 26) {
         TObject *obj=key->ReadObj();
         if (obj->IsA()->InheritsFrom(TH1::Class())){   
            TH1F *hx = (TH1F*)obj;
            TString hname(Form("%s",obj->GetTitle()));
            if (hname.Contains("BoostWeightsInTreeB")){ 
               c2->cd(ipad++);
               hx->SetLineColor(4);
               hx->Draw();
               hname.ReplaceAll("TreeB","TreeS");
               bdtdir->GetObject(hname.Data(),hx);
               if (hx) {
                  hx->SetLineColor(2);
                  hx->Draw("same");
               }
            }
            c2->Update();
         }
      }
               
   }

   // write to file
   TString fname = Form( "plots/%s_ControlPlots", titName.Data() );
   TMVAGlob::imgconv( c, fname );
   
   if (c2){
      fname = Form( "plots/%s_ControlPlots2", titName.Data() );
      TMVAGlob::imgconv( c2, fname );
   }

   TCanvas *c3 = NULL;
   if (BoostMonitorIsDone){
      sprintf( cn2, "cv3_%s", titName.Data() );
      c3 = new TCanvas( cn2,  Form( "%s Variables", titName.Data() ),
                        1200, 1200 ); 
      c3->Divide(5,5);
      Int_t ipad=1;
      
      TIter keys( bdtdir->GetListOfKeys() );
      TKey *key;
      //      gDirectory->ls();
      while ( (key = (TKey*)keys.Next()) && ipad < 26) {
         TObject *obj=key->ReadObj();
         if (obj->IsA()->InheritsFrom(TH1::Class())){   
            TH1F *hx = (TH1F*)obj;
            TString hname(Form("%s",obj->GetTitle()));
            if (hname.Contains("SigVar0AtTree")){ 
               c3->cd(ipad++);
               hx->SetLineColor(4);
               hx->Draw();
               hname.ReplaceAll("Sig","Bkg");
               bdtdir->GetObject(hname.Data(),hx);
               if (hx) {
                  hx->SetLineColor(2);
                  hx->Draw("same");
               }
            }
            c3->Update();
         }
      }
               
   }


}
Esempio n. 14
0
histoBook* histoBook::set( string param, double p1, double p2, double p3, double p4  ){


	transform(param.begin(), param.end(), param.begin(), ::tolower);

    TH1* h = get( styling );
    if ( h ){

	    if ( "linecolor" == param ){

	    	h->SetLineColor( (int) p1 );
	    } else if ( "domain" == param ){
	    	double min = p1;
	    	double max = p2;
		    h->GetXaxis()->SetRangeUser( min, max );
	    } else if ( "dynamicdomain" == param ){
	    	double thresh = p1;
	    	int min = (int)p2;
	    	int max = (int)p3;
	    	int axis = (int)p4;		// 1 = x, 2 = y

	    	if ( 1 != axis && 2 != axis )
	    		axis = 1;
	    	
	    	if ( thresh >= 0) {
	    		if ( -1 >= min )
	    			min = h->FindFirstBinAbove( thresh, axis );
	    		if ( -1 >= max )
	    			max = h->FindLastBinAbove( thresh, axis );
	    	}
	    	
	    	if ( 1 == axis )
		  	  h->GetXaxis()->SetRange( min, max );
		  	else if ( 2 == axis )
		  		h->GetYaxis()->SetRange( min, max );

	    }  else if ( "range" == param ){

	    	double min = p1;
	    	double max = p2;
	    	
	    	h->GetYaxis()->SetRangeUser( min, max );
	    } else if ( "markercolor" == param ) {
	    	h->SetMarkerColor( (int)p1 );
	    } else if ( "markerstyle" == param ) {
	    	h->SetMarkerStyle( (int)p1 );
	    } else if ( "legend" == param ){
	    	// p1 - alignmentX
	    	// p2 - alignmentY
	    	// p3 - width
	    	// p4 - height

	    	// make sure option is valid
	    	if ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )
	    		p1 = legendAlignment::best;
	    	if ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )
	    		p2 = legendAlignment::best;
	    	placeLegend( p1, p2, p3, p4 );
	    } else if ( "numberofticks" == param ){
	    	// p1 - # of primary divisions
	    	// p2 - # of secondary divisions
	    	// p3 - axis : 0 or 1 = x, 2 = y
	    	
	    	if ( p2 == -1 )
	    		p2 = 0;

		    if ( 2 == (int)p3 )
		    	h->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );
		    else 
		    	h->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );
	    }

    }
    
    
    


	return this;
}
Esempio n. 15
0
void plotter::draw_output_data(TH1* output_, TH1* stat_, std::vector<TH1D*> truth_, std::vector<TString> legnames, bool norm, TString file_name){

  TH1* output = (TH1*) output_->Clone("output");
  TH1* stat = (TH1*) stat_->Clone("stat");

  std::vector<TH1D*> truth;
  for(auto t: truth_){
    truth.push_back( (TH1D*) t->Clone() );
  }

  double max = output->GetMaximum();
  for(auto t: truth){
    if(t->GetMaximum() > max) max = t->GetMaximum();
  }
  double ymax = 1.5 * max;

  TCanvas *c = new TCanvas("c","",600,600);
  gPad->SetLeftMargin(0.15);
  TGaxis::SetMaxDigits(3);
  output->SetTitle(" ");
  output->GetYaxis()->SetRangeUser(0., ymax);
  output->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
  if(norm) output->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{d#sigma}{dm_{jet}} [#frac{1}{GeV}]");
  else output->GetYaxis()->SetTitle("#frac{d#sigma}{dm_{jet}} [#frac{fb}{GeV}]");
  output->GetYaxis()->SetTitleOffset(1.1);
  output->GetXaxis()->SetTitleOffset(0.9);
  output->GetYaxis()->SetTitleSize(0.05);
  output->GetXaxis()->SetTitleSize(0.05);
  output->GetYaxis()->SetNdivisions(505);
  output->SetLineColor(kBlack);
  output->SetMarkerColor(kBlack);
  output->SetMarkerStyle(8);
  output->SetMarkerSize(1);
  output->Draw("E1");
  stat->SetLineColor(kBlack);
  stat->SetMarkerColor(kBlack);
  stat->SetMarkerStyle(8);
  stat->SetMarkerSize(1);
  gStyle->SetEndErrorSize(5);
  Color_t color[] = {kRed-4, kAzure+7, kGreen, 798};
  Int_t style[] = {1, 2, 9, 7};
  for(unsigned int i=0; i<truth.size(); i++){
    truth[i]->SetLineWidth(3);
    truth[i]->SetLineColor(color[i]);
    truth[i]->SetLineStyle(style[i]);
    truth[i]->Draw("HIST SAME");
  }
  stat->Draw("E1 SAME");
  output->Draw("E1 SAME");

  TLegend *l=new TLegend(0.55,0.67,0.85,0.87);
  l->SetBorderSize(0);
  l->SetFillStyle(0);
  l->AddEntry(output,"data unfolded","pl");
  for(unsigned int i=0; i<truth.size(); i++){
    l->AddEntry(truth[i],legnames[i],"l");
  }
  l->SetTextSize(0.03);
  l->Draw();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
void likelihoodrefs( TDirectory *lhdir ) {
   Bool_t newCanvas = kTRUE;
   
   const UInt_t maxCanvas = 200;
   TCanvas** c = new TCanvas*[maxCanvas];
   Int_t width  = 670;
   Int_t height = 380;

   // avoid duplicated printing
   std::vector<std::string> hasBeenUsed;
   const TString titName = lhdir->GetName();
   UInt_t ic = -1;   

   TIter next(lhdir->GetListOfKeys());
   TKey *key;
   while ((key = TMVAGlob::NextKey(next,"TH1"))) { // loop over all TH1
      TH1 *h = (TH1*)key->ReadObj();
      TH1F *b( 0 );
      TString hname( h->GetName() );

      // avoid duplicated plotting
      Bool_t found = kFALSE;
      for (UInt_t j = 0; j < hasBeenUsed.size(); j++) {
         if (hasBeenUsed[j] == hname.Data()) found = kTRUE;
      }
      if (!found) {

         // draw original plots
         if (hname.EndsWith("_sig_nice")) {

            if (newCanvas) {
               char cn[20];
               sprintf( cn, "cv%d_%s", ic+1, titName.Data() );
               ++ic;
               TString n = hname;	  
               c[ic] = new TCanvas( cn, Form( "%s reference for variable: %s", 
                                              titName.Data(),(n.ReplaceAll("_sig","")).Data() ), 
                                    ic*50+50, ic*20, width, height ); 
               c[ic]->Divide(2,1);
               newCanvas = kFALSE;
            }      

            // signal
            Int_t color = 4; 
            TPad * cPad = (TPad*)c[ic]->cd(1);
            TString plotname = hname;

            h->SetMaximum(h->GetMaximum()*1.3);
            h->SetMinimum( 0 );
            h->SetMarkerColor(color);
            h->SetMarkerSize( 0.7 );
            h->SetMarkerStyle( 24 );
            h->SetLineWidth(1);
            h->SetLineColor(color);
            color++;
            h->Draw("e1");
            Double_t hSscale = 1.0/(h->GetSumOfWeights()*h->GetBinWidth(1));

            TLegend *legS= new TLegend( cPad->GetLeftMargin(), 
                                        1-cPad->GetTopMargin()-.14, 
                                        cPad->GetLeftMargin()+.77, 
                                        1-cPad->GetTopMargin() );
            legS->SetBorderSize(1);
            legS->AddEntry(h,"Input data (signal)","p");

            // background
            TString bname( hname );	
            b = (TH1F*)lhdir->Get( bname.ReplaceAll("_sig","_bgd") );
            cPad = (TPad*)c[ic]->cd(2);
            color = 2;
            b->SetMaximum(b->GetMaximum()*1.3);
            b->SetMinimum( 0 );
            b->SetLineWidth(1);
            b->SetLineColor(color);
            b->SetMarkerColor(color);
            b->SetMarkerSize( 0.7 );
            b->SetMarkerStyle( 24 );
            b->Draw("e1");       
            Double_t hBscale = 1.0/(b->GetSumOfWeights()*b->GetBinWidth(1));
            TLegend *legB= new TLegend( cPad->GetLeftMargin(), 
                                        1-cPad->GetTopMargin()-.14, 
                                        cPad->GetLeftMargin()+.77, 
                                        1-cPad->GetTopMargin() );
            legB->SetBorderSize(1);
            legB->AddEntry(b,"Input data (backgr.)","p");

            // register
            hasBeenUsed.push_back( bname.Data() );

            // the PDFs --------------

            // check for splines
            h = 0;
            b = 0;
            TString pname = hname; pname.ReplaceAll("_nice","");            
            for (int i=0; i<= 5; i++) {
               TString hspline = pname + Form( "_smoothed_hist_from_spline%i", i );
               h = (TH1F*)lhdir->Get( hspline );
               if (h) {
                  b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") );
                  break;
               }
            }

            // check for KDE
            if (h == 0 && b == 0) {
               TString hspline = pname +"_smoothed_hist_from_KDE";
               h = (TH1F*)lhdir->Get( hspline );
               if (h) {
                  b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") );
               }
            }
               
            // found something ?
            if (h == 0 || b == 0) {
               cout << "--- likelihoodrefs.C: did not find spline for histogram: " << pname.Data() << endl;
            }
            else {
               
               Double_t pSscale = 1.0/(h->GetSumOfWeights()*h->GetBinWidth(1));
               h->Scale( pSscale/hSscale );
               color = 4;
               c[ic]->cd(1);
               h->SetLineWidth(2);
               h->SetLineColor(color);
               legS->AddEntry(h,"Estimated PDF (norm. signal)","l");
               h->Draw("histsame");
               legS->Draw();
	  
               Double_t pBscale = 1.0/(b->GetSumOfWeights()*b->GetBinWidth(1));
               b->Scale( pBscale/hBscale );
               color = 2;
               c[ic]->cd(2);
               b->SetLineColor(color);
               b->SetLineWidth(2);
               legB->AddEntry(b,"Estimated PDF (norm. backgr.)","l");
               b->Draw("histsame");

               // draw the legends
               legB->Draw();
	  
               hasBeenUsed.push_back( pname.Data() );
            }	  

            c[ic]->Update();

            // write to file
            TString fname = Form( "root_mva/plots/%s_refs_c%i", titName.Data(), ic+1 );
            TMVAGlob::imgconv( c[ic], fname );
            //	c[ic]->Update();

            newCanvas = kTRUE;
            hasBeenUsed.push_back( hname.Data() );
         }
      }
   }
}
Esempio n. 17
0
void plotter::draw_output_mass(TH1* output_,  TH1* stat_, std::vector<TH1D*> mtop_templates_, std::vector<bool> show, bool norm, TString file_name){

  TH1* output = (TH1*) output_->Clone("output");
  TH1* stat = (TH1*) stat_->Clone("stat");

  std::vector<TH1D*> mtop_templates;
  for(unsigned int i = 0; i < mtop_templates_.size(); i++){
    mtop_templates.push_back((TH1D*) mtop_templates_[i]->Clone(""));
  }

  TCanvas *c = new TCanvas("c","",600,600);
  gPad->SetLeftMargin(0.15);

  double max = output->GetMaximum();
  for(unsigned int i = 0; i < mtop_templates.size(); i++){
    if(show[i]){
      double max_temp = mtop_templates[i]->GetMaximum();
      if(max_temp > max) max = max_temp;
    }
  }
  double ymax = 1.5 * max;

  TGaxis::SetMaxDigits(3);
  output->SetTitle(" ");
  output->GetYaxis()->SetRangeUser(0., ymax);
  output->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
  if(norm) output->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{d#sigma}{dm_{jet}} [#frac{1}{GeV}]");
  else output->GetYaxis()->SetTitle("events");
  output->GetYaxis()->SetTitleOffset(1.1);
  output->GetXaxis()->SetTitleOffset(0.9);
  output->GetYaxis()->SetTitleSize(0.05);
  output->GetXaxis()->SetTitleSize(0.05);
  output->GetYaxis()->SetNdivisions(505);
  output->SetLineColor(kBlack);
  output->SetMarkerColor(kBlack);
  output->SetMarkerStyle(8);
  output->SetMarkerSize(1);
  output->Draw("E1 SAME");
  stat->SetLineColor(kBlack);
  stat->SetMarkerColor(kBlack);
  stat->SetMarkerStyle(8);
  stat->SetMarkerSize(1);
  gStyle->SetEndErrorSize(5);

  mtop_templates[0]->SetLineColor(kRed);
  mtop_templates[1]->SetLineColor(kRed);
  mtop_templates[2]->SetLineColor(kRed);
  mtop_templates[3]->SetLineColor(13);
  mtop_templates[4]->SetLineColor(kAzure+7);
  mtop_templates[5]->SetLineColor(kAzure+7);
  mtop_templates[6]->SetLineColor(kAzure+7);

  for(unsigned int i = 0; i < mtop_templates.size(); i++){
    mtop_templates[i]->SetLineWidth(3);
    if(show[i]) mtop_templates[i]->Draw("HIST SAME");
  }
  stat->Draw("E1 SAME");
  output->Draw("E1 SAME"); // draw again to set markers in front
  TLegend *l=new TLegend(0.56,0.65,0.78,0.85);
  l->SetBorderSize(0);
  l->SetFillStyle(0);
  l->AddEntry(output,"data unfolded","pl");
  if(show[0]) l->AddEntry(mtop_templates[0],"m_{top}^{MC} = 166.5 GeV","pl");
  if(show[1]) l->AddEntry(mtop_templates[1],"m_{top}^{MC} = 169.5 GeV","pl");
  if(show[2]) l->AddEntry(mtop_templates[2],"m_{top}^{MC} = 171.5 GeV","pl");
  if(show[3]) l->AddEntry(mtop_templates[3],"m_{top}^{MC} = 172.5 GeV","pl");
  if(show[4]) l->AddEntry(mtop_templates[4],"m_{top}^{MC} = 173.5 GeV","pl");
  if(show[5]) l->AddEntry(mtop_templates[5],"m_{top}^{MC} = 175.5 GeV","pl");
  if(show[6]) l->AddEntry(mtop_templates[6],"m_{top}^{MC} = 178.5 GeV","pl");
  l->SetTextSize(0.04);
  l->Draw();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Esempio n. 18
0
int ratio5() {

  // Constants and arrays

  Int_t multi = 2;

  const Int_t n_at = 3;
  Int_t at[n_at] = { 500, 510, 550 };
  //for ( int ii = 0; ii < n_at; ++ii ) { at[ii] = 500 + ii * 10; }

  TString eq = "Gt";

  const Int_t n = 4;
  float pt[n]     = { 50., 40., 30., 20. };
  Int_t colour[n] = { 1, 2, 3, 4 };

  const Int_t m = 2;
  Int_t style[m]  = { kOpenSquare, kFullSquare };
  
  const Int_t ngr = 1000;
  double x3[ngr];
  double r[ngr];

  int count = 0;

  // General style

  gStyle->SetOptStat(0);
  
//   // Canvas for RECO curves 
//   TCanvas* reco_canvas = new TCanvas("Reco");
//   reco_canvas->SetFillColor(0);
//   reco_canvas->SetLineColor(0); 
//   reco_canvas->SetLogy();
//   TLegend* reco_legend = new TLegend( 0.5, 0.7, 0.88, 0.88, NULL, "brNDC" );
//   reco_legend->SetFillColor(0);
//   reco_legend->SetLineColor(0); 
//   bool empty = true;
//   double reco_max = 1.e-15.;
//   double reco_min = 1.e15;
  
  // Loop through pt bins

  for ( Int_t i = 0; i < 1; ++i ) {

    std::stringstream pt_can;
    pt_can << "PtBin" << pt[i];
    
    // Canvas for Pt bin
    TCanvas* pt_canvas = new TCanvas(TString(pt_can.str()),"");
    pt_canvas->SetFillColor(0);
    pt_canvas->SetLineColor(0); 
    pt_canvas->SetLogy();
    TLegend* pt_legend = new TLegend( 0.82, 0.5, 0.98, 0.9, NULL, "brNDC" );

    pt_legend->SetFillColor(0);
    pt_legend->SetLineColor(0); 
    bool empty = true;
    double pt_max = 1.e-15.;
    double pt_min = 1.e15;
    std::vector<TH1*> pt_ratio;

    pt_canvas->SetRightMargin(0.2);

    // Open files
    std::stringstream ss;
    ss << "results/4/Reco" << pt[i] << "_QCDPythia6.root";
    TString name(ss.str());
    TFile* file = new TFile(name);
    if ( file->IsZombie() || !(file->IsOpen()) ) { continue; }
    file->cd();
    
    // Loop through AlphaT thresolds
    for ( Int_t iat = 0; iat < n_at; ++iat ) {
    
      // Loop through RECO and GEN
      for ( Int_t j = 0; j < m; ++j ) {
	
	// Define names of histos to open 
	std::stringstream pre;
	std::stringstream post;
	if ( j == 0 ) {
	  pre << "Ratio" << at[iat] << "/GenHt" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/GenHt" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	} else if ( j == 1 ) {
	  pre << "Ratio" << at[iat] << "/Ht" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/Ht" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	}
	
	// Create ratio histo
	TH1* denominator = his( (TH1*)file->Get(TString(pre.str())), 45, 200., 650. );
	TH1* numerator = his( (TH1*)file->Get(TString(post.str())), 45, 200., 650. );
	int rebin = 5;
	numerator->Rebin(rebin);
	denominator->Rebin(rebin);
	TH1* ratio = (TH1*)numerator->Clone();
	ratio->Divide(denominator);
	//ratio->Divide(numerator,denominator,1.,1.,"b"); //@@ poisson errors
	ratio->SetMarkerStyle(style[j]);
	ratio->SetMarkerSize(1.2);
	ratio->SetMarkerColor(iat+1);//colour[iat]);
	ratio->SetBarOffset(0.1*i);
	//ratio->GetXaxis()->SetRangeUser(100.,550.);
	ratio->GetYaxis()->SetRangeUser(1.e-7,1.e-1);

	ratio->GetXaxis()->SetTitle("HT_{reco} [GeV]");
	ratio->GetYaxis()->SetTitle("R(#alpha_{T})");
	
 	if ( ratio->GetMaximum() > 0. &&
 	     ratio->GetMaximum() > pt_max ) {
 	  pt_max = ratio->GetMaximum();
 	}
 	if ( ratio->GetMinimum() > 0. && 
 	     ratio->GetMinimum() < pt_min ) {
 	  pt_min = ratio->GetMinimum();
 	}

	pt_ratio.push_back(ratio);

	if ( empty ) { ratio->Draw(""); empty = false; }
        else { ratio->Draw("same"); }

	//ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);


	// Text for legend
	std::stringstream pt_leg;
	if ( j == 0 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", GEN"; }
	else if ( j == 1 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", RECO"; }
	pt_legend->AddEntry( ratio, TString(pt_leg.str()), "lep" );
	
// 	// Draw histos on canvas for RECO only
// 	if ( j == 1 ) {
// 	  reco_canvas->cd();
// 	  if ( i == 0 ) ratio->Draw("");
// 	  else ratio->Draw("same");
// 	  std::stringstream reco_leg;
// 	  reco_leg << "p_{T}^{min} = " << pt[i];
// 	reco_legend->AddEntry( ratio, TString(reco_leg.str()), "lep" );
// 	}
	
      }
    }

//       if (0) {

// 	int nbins = ratio->GetNbinsX();
// 	int bin_width = ratio->GetBinWidth(1);
      
// 	double lower = 0.;
// 	double upper = 1400.;
      
// 	int bin_lower = int( ( lower - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_lower; ii < ratio->GetNbinsX()-1; ++ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    lower = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	int bin_upper = int( ( upper - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_upper; ii > 0; --ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    upper = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	if (0) {
// 	  std::cout << " bin_width: " << bin_width
// 		    << " bin_lower: " << bin_lower
// 		    << " bin_upper: " << bin_upper
// 		    << " lower: " << lower
// 		    << " upper: " << upper
// 		    << std::endl;
// 	}

// 	TF1* fit = new TF1(sample[i],"expo",lower,upper); 
// 	fit->SetLineColor(colour[i]);
// 	fit->SetLineWidth(1);
// 	ratio->Fit(sample[i],"QR","same");

//       }
      
     pt_canvas->cd();
//      for ( Int_t iii = 0; iii < pt_ratio.size(); ++iii ) {
//        TH1* ratio = pt_ratio[iii];
//        if ( !ratio ) { continue; }
//        if ( ii == 0 ) { ratio->Draw(""); }
//        else { ratio->Draw("same"); }
//        ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);
//      }
     pt_legend->Draw("same");
     pt_canvas->Update();
     pt_canvas->SaveAs(TString(pt_can.str()+".png"));
//       pt_canvas->SaveAs(TString(pt_can.str()+".C"));
      
    }

//   reco_canvas->cd();
//   reco_legend->Draw("same");
//   reco_canvas->Update();
//   reco_canvas->SaveAs(TString("Reco.png"));
//   reco_canvas->SaveAs(TString("Reco.C"));
  
//   TCanvas* c2 = new TCanvas("C2");
//   c2->SetLogy();
//   c2->SetFillColor(0);
//   gStyle->SetOptStat(0);
//   if ( count > 0 ) {
//     TGraph* graph = new TGraph(count,x3,r); 
//     graph->Draw("a*");
//   }

  
}
Esempio n. 19
0
histoBook* histoBook::set( string opt, vector<string> params ){

	//cout  << "Setting : " << opt << endl;
	//for ( int i = 0; i < params.size(); i++ ){
	//	cout << params[ i ] << " ";
	//}
	//cout << endl;
	// force the param name to lowercase
	transform(opt.begin(), opt.end(), opt.begin(), ::tolower);

    TH1* h = get( styling );
    if ( h ){

	    if ( "title" == opt ){
	    	h->SetTitle( cParam(params, 0) );
	    } else if ( "x" == opt ){
	    	h->GetXaxis()->SetTitle( cParam(params, 0) );
	    } else if ( "y" == opt ){
	    	h->GetYaxis()->SetTitle( cParam(params, 0) );
	    } else if ( "legend" == opt ){
	    	legend->AddEntry( h, cParam(params, 0), cParam(params, 1, "lpf") );
			legend->Draw();
	    } else if ( "draw" == opt ){
	    	drawOption = cParam(params, 0);
	    } else if ( "linecolor" == opt ){
	    	int c = color( cParam( params, 0) );
	    	if ( c  < 0 )
	    		c = (int) dParam( params, 0);
	    	h->SetLineColor( c );
	    } else if ( "fillcolor" == opt ){
	    	int c = color( cParam( params, 0) );
	    	if ( c  < 0 )
	    		c = (int) dParam( params, 0);
	    	h->SetFillColor( c );
	    } else if ( "linewidth" == opt ){
	    	h->SetLineWidth( dParam( params, 0) );
	    } else if ( "domain" == opt ){
	    	double min = dParam( params, 0);
	    	double max = dParam( params, 1);
		    h->GetXaxis()->SetRangeUser( min, max );
	    } else if ( "dynamicdomain" == opt ){
	    	double thresh = dParam( params, 0);
	    	int min = (int)dParam( params, 1);
	    	int max = (int)dParam( params, 2);
	    	int axis = (int)dParam( params, 3);		// 1 = x, 2 = y

	    	if ( 1 != axis && 2 != axis )
	    		axis = 1;
	    	
	    	if ( thresh >= 0) {
	    		if ( -1 >= min )
	    			min = h->FindFirstBinAbove( thresh, axis );
	    		if ( -1 >= max )
	    			max = h->FindLastBinAbove( thresh, axis );
	    	}
	    	
	    	if ( 1 == axis )
		  	  h->GetXaxis()->SetRange( min, max );
		  	else if ( 2 == axis )
		  		h->GetYaxis()->SetRange( min, max );

	    }  else if ( "range" == opt ){

	    	double min = dParam( params, 0);
	    	double max = dParam( params, 1);
	    	
	    	h->GetYaxis()->SetRangeUser( min, max );
	    } else if ( "markercolor" == opt ) {
	    	int c = color( cParam( params, 0) );
	    	if ( c  < 0 )
	    		c = (int) dParam( params, 0);
	    	h->SetMarkerColor( c );
	    } else if ( "markerstyle" == opt ) {
	    	h->SetMarkerStyle( (int)dParam( params, 0) );
	    } else if ( "legend" == opt ){
	    	// p1 - alignmentX
	    	// p2 - alignmentY
	    	// p3 - width
	    	// p4 - height

	    	// make sure option is valid
	    	double p1 = dParam( params, 0);
	    	double p2 = dParam( params, 1);
	    	if ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )
	    		p1 = legendAlignment::best;
	    	if ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )
	    		p2 = legendAlignment::best;
	    	placeLegend( p1, p2, dParam( params, 3), dParam( params, 3) );
	    } else if ( "numberofticks" == opt ){
	    	// p1 - # of primary divisions
	    	// p2 - # of secondary divisions
	    	// p3 - axis : 0 or 1 = x, 2 = y
	    	double p1 = dParam( params, 0);
	    	double p2 = dParam( params, 1);
	    	double p3 = dParam( params, 2);

	    	if ( p2 == -1 )
	    		p2 = 0;

		    if ( 2 == (int)p3 )
		    	h->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );
		    else 
		    	h->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );
	    } else if ( "logy" == opt ){
	    	gPad->SetLogy( (int)dParam( params, 0 ) );
	    } else if ( "logx" == opt ){
	    	gPad->SetLogx( (int)dParam( params, 0 ) );
	    } else if ( "logz" == opt ){
	    	gPad->SetLogz( (int)dParam( params, 0 ) );
	    }




	}

	return this;



}
Esempio n. 20
0
void PlotAll(TString wsname)
{
	char* binLabels[19] = {"60","70","80","90","100","110","120","130","140","150","160","170","180","190","200","250","300","400","1000"};	

	//get the stuff from the workspace:
	
	TFile* file=TFile::Open(wsname);
	RooWorkspace* ws = (RooWorkspace*)file->Get("combined");
	ModelConfig  *mc = (ModelConfig*)ws->obj("ModelConfig");
	RooAbsData   *data = ws->data("obsData");
	RooSimultaneous* simPdf=(RooSimultaneous*)(mc->GetPdf());
	RooAbsReal* nll=simPdf->createNLL(*data);

	// FPT 0 **************************************	
	// EM channel
	
	RooCategory* chanCat = (RooCategory*) (&simPdf->indexCat());
        TIterator* iterat = chanCat->typeIterator() ;
        RooCatType* ttype = (RooCatType*)iterat->Next();

	RooAbsPdf  *pdf_stateEM  = simPdf->getPdf(ttype->GetName()) ;
	RooArgSet  *obstmpEM  = pdf_stateEM->getObservables( *mc->GetObservables() ) ;
	
	// get EM data
       	RooAbsData *dataEM = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));
		
	RooRealVar *obsEM     = ((RooRealVar*) obstmpEM->first());
	TString chanName1(ttype->GetName());

	// create data histogram
	TH1* hdataEM = dataEM->createHistogram("Data "+chanName1,*obsEM);
	// set errors to gaussian
        for (int ib=0 ; ib<hdataEM->GetNbinsX()+1 ; ib++) hdataEM->SetBinError(ib, sqrt(hdataEM->GetBinContent(ib)));

	double EMnorm = pdf_stateEM->expectedEvents(*obsEM);
	
	//****************************
	// ME channel
	ttype = (RooCatType*)iterat->Next();
	RooAbsPdf* pdf_stateME  = simPdf->getPdf(ttype->GetName()) ;
        RooArgSet* obstmpME  = pdf_stateME->getObservables( *mc->GetObservables() ) ;

	// get ME data
	RooAbsData *dataME = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));	
	RooRealVar* obsME = ((RooRealVar*) obstmpME->first());
	TString chanName2(ttype->GetName());

        // create data histogram
        TH1* hdataME = dataME->createHistogram("Data "+chanName2,*obsME);
        // set errors to gaussian
        for (int ib=0 ; ib<hdataME->GetNbinsX()+1 ; ib++) hdataME->SetBinError(ib, sqrt(hdataME->GetBinContent(ib)));
        
	
	// get initial BG histogram
	//TH1* h_initial_BG_EM = pdf_stateEM->createHistogram("initial_BG_EM",*obsEM);
	//TH1* h_initial_BG_ME = pdf_stateME->createHistogram("initial_BG_ME",*obsME);
	
	double MEnorm = pdf_stateME->expectedEvents(*obsME);
	cout << "EM expected events = " << EMnorm << ", ME expected events = " << MEnorm << "." << endl;
	//h_initial_BG_EM->Scale(EMnorm);
	//h_initial_BG_ME->Scale(MEnorm);	

	// get initial gammas
	int nbins = hdataEM->GetNbinsX();
        double InitGamma[nbins];
        for (int i=0; i<nbins; i++)
        {
               	TString varname = "gamma_B0_l1pt0_bin_"+NumberToString(i);
               	InitGamma[i] = ws->var(varname)->getVal();
               	cout << "initial gamma"+NumberToString(i)+" = " << InitGamma[i] << endl;
        }
        double InitFpt = ws->var("fl1pt_l1pt0")->getVal();
        cout << "initial fpt_l1pt0 = " << InitFpt <<  endl;


	// DO THE GLOBAL FIT
	
	minimize(nll);	
       
	// get final BG histograms
	TH1* h_final_BG_EM = pdf_stateEM->createHistogram("final_BG_EM",*obsEM);
        TH1* h_final_BG_ME = pdf_stateME->createHistogram("final_BG_ME",*obsME); 
	h_final_BG_EM->Scale(EMnorm);
	h_final_BG_ME->Scale(MEnorm);
	
	// uncertainty bands
	TH1D* BuncertaintyEM = new TH1D("BuncertaintyEM","BuncertaintyEM",nbins,0,nbins);
	TH1D* BuncertaintyME = new TH1D("BuncertaintyME","BuncertaintyME",nbins,0,nbins);
	for (int i=1; i<=nbins; i++){
		double sigbEM = h_final_BG_EM->GetBinError(i);
		double bEM = h_final_BG_EM->GetBinContent(i);
		BuncertaintyEM->SetBinError(i,sigbEM); BuncertaintyEM->SetBinContent(i,bEM);
		double sigbME = h_final_BG_ME->GetBinError(i);
                double bME = h_final_BG_ME->GetBinContent(i);
                BuncertaintyME->SetBinError(i,sigbME); BuncertaintyME->SetBinContent(i,bME);
	}
	//BuncertaintyEM->SetFillStyle(3004); 
	BuncertaintyEM->SetFillColor(kGreen-9);
	BuncertaintyEM->SetLineColor(kBlack); BuncertaintyEM->SetLineStyle(2);
	//BuncertaintyME->SetFillStyle(3004); 
	BuncertaintyME->SetFillColor(kBlue-9);
        BuncertaintyME->SetLineColor(kBlack); BuncertaintyME->SetLineStyle(2);

	// get gammas after fit
	double FinalGamma[nbins];
	//TH1* h_initBG_times_gamma = (TH1*)h_initial_BG_EM->Clone("initBGEM_times_gamma");
	for (int i=0; i<nbins; i++)
       	{
               	TString varname = "gamma_B0_l1pt0_bin_"+NumberToString(i);
               	FinalGamma[i] = ws->var(varname)->getVal();
               	cout << "Final gamma in bin "+NumberToString(i)+" = " << FinalGamma[i] << endl;
       	//	h_initBG_times_gamma->SetBinContent(i+1,h_initial_BG_EM->GetBinContent(i+1)*FinalGamma[i]);
	}
	//double FinalFpt = ws->var("fl1pt_l1pt0")->getVal();
	
	// get final alpha (pull)
	RooRealVar* alphaVar = ws->var("alpha_l1ptsys_l1pt0");
	double alpha, alphaErr;
	if (alphaVar != NULL) {
		alpha = ws->var("alpha_l1ptsys_l1pt0")->getVal();
		alphaErr = ws->var("alpha_l1ptsys_l1pt0")->getError();
	}

	//FOR UNCONSTRAINED FPT - get final fpts
	double FinalFpt[5];
	double FinalFptErr[5];
	for (int k=0; k<5; k++){
		TString varname = "fl1pt_l1pt"+NumberToString(k);
		FinalFpt[k] = ws->var(varname)->getVal();
		FinalFptErr[k] =  ws->var(varname)->getError();
		cout << varname << " = "  << FinalFpt[k] << " +- " << FinalFptErr[k] << endl;
	}
	
	// get POI value
	double mu = ws->var("mu_BR_htm")->getVal();
	double muErr = ws->var("mu_BR_htm")->getError();
	
	// Draw
	TCanvas* c1 = new TCanvas("BG and Data "+chanName1+" "+chanName2,"BG and Data "+chanName1+" "+chanName2,600,600);
	BuncertaintyEM->Draw("E3 sames"); BuncertaintyME->Draw("E3 sames");
	//h_initial_BG_EM->SetLineColor(kGreen+2); h_initial_BG_EM->SetLineStyle(2); h_initial_BG_EM->Draw("sames");
	hdataEM->SetLineColor(kGreen+2); hdataEM->SetMarkerStyle(20); hdataEM->SetMarkerColor(kGreen+2);
	hdataEM->Draw("e1 sames");
	//h_initial_BG_ME->SetLineColor(kBlue); h_initial_BG_ME->SetLineStyle(2); h_initial_BG_ME->Draw("sames");
        hdataME->SetLineColor(kBlue); hdataME->SetMarkerStyle(20);  hdataME->SetMarkerColor(kBlue);
	hdataME->Draw("e1 sames");

	h_final_BG_EM->SetLineColor(kGreen+2); h_final_BG_EM->SetLineWidth(2); h_final_BG_EM->Draw("sames");
	h_final_BG_ME->SetLineColor(kBlue); h_final_BG_ME->SetLineWidth(2); h_final_BG_ME->Draw("sames");

	TLegend* leg = new TLegend(0.5,0.45,0.85,0.65);
        leg->SetFillColor(kWhite); leg->SetBorderSize(1); leg->SetLineColor(0); //leg->SetTextFont(14);
        leg->SetTextSize(.03);

	leg->AddEntry(hdataME,"DATA #mue","lep");
	leg->AddEntry(hdataEM,"DATA e#mu","lep");
	//leg->AddEntry(h_initial_BG_ME,"Initial #mue PDF","l");
	//leg->AddEntry(h_initial_BG_EM,"Initial e#mu PDF","l");
	leg->AddEntry(h_final_BG_ME,"#mue PDF = #gamma_{i}B_{i} + #muS_{i}","l");
	leg->AddEntry(h_final_BG_EM,"e#mu PDF = f(1+#alpha#sigma)(#gamma_{i}B_{i}+#muW_{i})","l");
	leg->Draw();

	cout << " ********************* Fit Values **************************** " <<  endl;
	if (alphaVar != NULL){cout << "alpha = " << alpha << " +- " << alphaErr << endl;}
	cout << "mu    = " << mu << " +- " << muErr << endl;

	TString WriteDownAlphaValue;
	TString WriteDownMuValue;
	WriteDownAlphaValue = "Fpt0 = ";
	WriteDownMuValue = "#mu = ";
	WriteDownAlphaValue += Form("%4.4f",FinalFpt[0]);
	WriteDownAlphaValue += "#pm";
	WriteDownAlphaValue += Form("%4.4f",FinalFptErr[0]);
	WriteDownMuValue += Form("%4.4f",mu);
        WriteDownMuValue += "#pm";
        WriteDownMuValue += Form("%4.4f",muErr);

	TLatex *texl = new TLatex(12,25,WriteDownAlphaValue);
   	texl->SetTextAlign(22); texl->SetTextSize(0.03); 
   	TLatex *texl2 = new TLatex(12,23,WriteDownMuValue);
        texl2->SetTextAlign(22); texl2->SetTextSize(0.03);
	texl->Draw(); 
	texl2->Draw();



	//FPT 1 ***********************************
	ttype = (RooCatType*)iterat->Next();

        RooAbsPdf  *pdf_stateEM1  = simPdf->getPdf(ttype->GetName()) ;
        RooArgSet  *obstmpEM1  = pdf_stateEM1->getObservables( *mc->GetObservables() ) ;
	RooAbsData *dataEM1 = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));

        RooRealVar *obsEM1     = ((RooRealVar*) obstmpEM1->first());
        TString chanName11(ttype->GetName());	
	TH1* hdataEM1 = dataEM1->createHistogram("Data "+chanName11,*obsEM1);
	for (int ib=0 ; ib<hdataEM1->GetNbinsX()+1 ; ib++) hdataEM1->SetBinError(ib, sqrt(hdataEM1->GetBinContent(ib)));

        double EMnorm1 = pdf_stateEM1->expectedEvents(*obsEM1);
	ttype = (RooCatType*)iterat->Next();
        RooAbsPdf* pdf_stateME1  = simPdf->getPdf(ttype->GetName()) ;
        RooArgSet* obstmpME1  = pdf_stateME1->getObservables( *mc->GetObservables() ) ;
	RooAbsData *dataME1 = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));
        RooRealVar* obsME1 = ((RooRealVar*) obstmpME1->first());
        TString chanName21(ttype->GetName());
	TH1* hdataME1 = dataME1->createHistogram("Data "+chanName21,*obsME1);

	for (int ib=0 ; ib<hdataME1->GetNbinsX()+1 ; ib++) hdataME1->SetBinError(ib, sqrt(hdataME1->GetBinContent(ib)));
	double MEnorm1 = pdf_stateME1->expectedEvents(*obsME1);
	TH1* h_final_BG_EM1 = pdf_stateEM1->createHistogram("final_BG_EM1",*obsEM1);
        TH1* h_final_BG_ME1 = pdf_stateME1->createHistogram("final_BG_ME1",*obsME1);
        h_final_BG_EM1->Scale(EMnorm1);
        h_final_BG_ME1->Scale(MEnorm1);
	TH1D* BuncertaintyEM1 = new TH1D("BuncertaintyEM1","BuncertaintyEM1",nbins,0,nbins);
        TH1D* BuncertaintyME1 = new TH1D("BuncertaintyME1","BuncertaintyME1",nbins,0,nbins);
        for (int i=1; i<=nbins; i++){
                double sigbEM = h_final_BG_EM1->GetBinError(i);
                double bEM = h_final_BG_EM1->GetBinContent(i);
                BuncertaintyEM1->SetBinError(i,sigbEM); BuncertaintyEM1->SetBinContent(i,bEM);
                double sigbME = h_final_BG_ME1->GetBinError(i);
                double bME = h_final_BG_ME1->GetBinContent(i);
                BuncertaintyME1->SetBinError(i,sigbME); BuncertaintyME1->SetBinContent(i,bME);
        }
	BuncertaintyEM1->SetFillColor(kGreen-9);
        BuncertaintyEM1->SetLineColor(kBlack); BuncertaintyEM1->SetLineStyle(2);
	BuncertaintyME1->SetFillColor(kBlue-9);
        BuncertaintyME1->SetLineColor(kBlack); BuncertaintyME1->SetLineStyle(2);
	double FinalGamma1[nbins];
        for (int i=0; i<nbins; i++)
        {
                TString varname = "gamma_B0_l1pt1_bin_"+NumberToString(i);
                FinalGamma1[i] = ws->var(varname)->getVal();
                cout << "Final gamma in bin "+NumberToString(i)+" = " << FinalGamma1[i] << endl;
        }
	TCanvas* c2 = new TCanvas("BG and Data "+chanName11+" "+chanName21,"BG and Data "+chanName11+" "+chanName21,600,600);
        BuncertaintyEM1->Draw("E3 sames"); BuncertaintyME1->Draw("E3 sames");
        hdataEM1->SetLineColor(kGreen+2); hdataEM1->SetMarkerStyle(20); hdataEM1->SetMarkerColor(kGreen+2);
        hdataEM1->Draw("e1 sames");
        hdataME1->SetLineColor(kBlue); hdataME1->SetMarkerStyle(20);  hdataME1->SetMarkerColor(kBlue);
        hdataME1->Draw("e1 sames");

        h_final_BG_EM1->SetLineColor(kGreen+2); h_final_BG_EM1->SetLineWidth(2); h_final_BG_EM1->Draw("sames");
        h_final_BG_ME1->SetLineColor(kBlue); h_final_BG_ME1->SetLineWidth(2); h_final_BG_ME1->Draw("sames");

        leg->Draw();

        cout << " ********************* Fit Values **************************** " <<  endl;
        cout << "mu    = " << mu << " +- " << muErr << endl;
	TString WriteDownAlphaValue1;
        WriteDownAlphaValue1 = "Fpt1 = ";
        WriteDownAlphaValue1 += Form("%4.4f",FinalFpt[1]);
        WriteDownAlphaValue1 += "#pm";
        WriteDownAlphaValue1 += Form("%4.4f",FinalFptErr[1]);

        TLatex *texl11 = new TLatex(12,25,WriteDownAlphaValue1);
        texl11->SetTextAlign(22); texl11->SetTextSize(0.03);
        texl11->Draw(); 
        texl2->Draw();

}
Esempio n. 21
0
File: QA.C Progetto: ktf/AliPhysics
void QAtracklets(const Char_t *fdata, const Char_t *fmc)
{

  style();
  
  TFile *fdtin = TFile::Open(fdata);
  TList *ldtin = (TList *)fdtin->Get("clist");
  TH2 *hdtin = (TH2 *)ldtin->FindObject("etaphiTracklets");
  TH1 *pdtin = (TH1 *)hdtin->ProjectionY("pdtin_tracklets");
  pdtin->SetMarkerStyle(20);
  pdtin->SetMarkerSize(1.);
  pdtin->SetMarkerColor(kAzure-3);
  hdtin->Scale(1. / hdtin->GetEntries());
  pdtin->Scale(1. / hdtin->GetEntries());
  
  TFile *fmcin = TFile::Open(fmc);
  TList *lmcin = (TList *)fmcin->Get("clist");

  if(!lmcin) {
      std::cout << "NOLIST" << std::endl;

  }
  lmcin->ls();
  TH2 *hmcin = (TH2 *)lmcin->FindObject("etaphiTracklets");
  if(!hmcin) {
    std::cout << "NO H!! etaphiTracklets" << std::endl;
    
  }
  TH1 *pmcin = (TH1 *)hmcin->ProjectionY("pmcin_tracklets");
  pmcin->SetLineColor(kRed+1);
  pmcin->SetFillStyle(1001);
  pmcin->SetFillColorAlpha(kRed+1, 0.1);
  hmcin->Scale(1. / hmcin->GetEntries());
  pmcin->Scale(1. / hmcin->GetEntries());
  

  /*  
  pdtin->Scale(pmcin->Integral(pmcin->FindBin(0. + 0.001),
			       pmcin->FindBin(1. - 0.001))
	       / pdtin->Integral(pdtin->FindBin(0. + 0.001),
				 pdtin->FindBin(1. - 0.001)));
  */  
  
  TCanvas *cData = new TCanvas("cTrackletData", "cTrackletData", 800, 800);
  //  cData->SetLogz();
  TH1 * hfr = cData->DrawFrame(-2.5, 0., 2.5, 2. * TMath::Pi());
  hfr->SetTitle(";#eta;#varphi");
  hdtin->Draw("same,col");
  cData->SaveAs(canvasPrefix+"trackletData.pdf");

  TCanvas *cMC = new TCanvas("cTrackletMC", "cTrackletMC", 800, 800);
  //  cMC->SetLogz();
  hfr = cMC->DrawFrame(-2.5, 0., 2.5, 2. * TMath::Pi());
  hfr->SetTitle(";#eta;#varphi");
  hmcin->Draw("same,col");
  cMC->SaveAs(canvasPrefix+"trackletMC.pdf");
  
  TCanvas *cPhi = new TCanvas("cTrackletPhi", "cTrackletPhi", 800, 800);
  //  cPhi->SetLogy();
  hfr = cPhi->DrawFrame(0., 0., 2. * TMath::Pi(), 0.01);
  hfr->SetTitle(";#varphi;");
  pdtin->DrawCopy("same");
  pmcin->DrawCopy("same,histo");
  TLegend *legend = new TLegend(0.20, 0.18+0.63, 0.50, 0.30+0.63);
  legend->SetFillColor(0);
  legend->SetBorderSize(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.04);
  legend->AddEntry(pdtin, "data", "pl");
  legend->AddEntry(pmcin, "Monte Carlo", "l");
  legend->Draw("same");
  cPhi->SaveAs(canvasPrefix+"trackletPhi.pdf");
  
  TCanvas *cPhir = new TCanvas("cTrackletPhir", "cTrackletPhir", 800, 800);
  //  cPhi->SetLogy();
  hfr = cPhir->DrawFrame(0., 0.5, 2. * TMath::Pi(), 1.5);
  hfr->SetTitle(";#varphi;data / Monte Carlo");
  pdtin->Divide(pmcin);
  pdtin->Draw("same");
  cPhir->SaveAs(canvasPrefix+"trackletPhir.pdf");

  
  
}
Esempio n. 22
0
// Plot the closure test
void plotHadTau3(double scale = 1.,
		 const TString &fileName = "HadTau_WJetMC_PredGen.root") {
  gROOT->ProcessLine(".L ../utils/StyleMatters.h+");
  StyleMatters::init();

  bool isMCPred = false;
  if( fileName.Contains("MC") ) isMCPred = true;
  bool isGenPred = false;
  if( isMCPred && fileName.Contains("Gen") ) isGenPred = true;

  
  // Get histograms from file
  const unsigned int kNDists = 3;
  TH1* hTrue[kNDists];
  TH1* hPred[kNDists];
  TH1* hMuonPt = 0;
  TFile file(fileName,"READ");
  for(unsigned int i = 0; i < kNDists; ++i) {
    TString name = "";
    if( i == 0 )      name = "TauJetPt";
    else if( i == 1 ) name = "Ht";
    else if( i == 2 ) name = "Mht";
    file.GetObject("hPred"+name,hPred[i]);
    if( !hPred[i] ) {
      std::cerr << "ERROR: Histograms not found" << std::endl;
      exit(-1);
    }
    hPred[i]->SetDirectory(0);
    hPred[i]->UseCurrentStyle();
    if( isMCPred ) {
      file.GetObject("hTrue"+name,hTrue[i]);
      if( !hTrue[i] ) {
	std::cerr << "ERROR: Histograms not found" << std::endl;
	exit(-1);
      }
      hTrue[i]->SetDirectory(0);
      hTrue[i]->UseCurrentStyle();
    }
  }
  file.GetObject("hMuonPt",hMuonPt);
  if( !hMuonPt ) {
    std::cerr << "ERROR: Histogram not found" << std::endl;
    exit(-1);
  }
  hMuonPt->SetDirectory(0);
  hMuonPt->UseCurrentStyle();
  file.Close();
  
  
  // Apply correction factors
  for(unsigned int i = 0; i < kNDists; ++i) {
    hPred[i]->Scale(scale);
  }


  // Set style
  for(unsigned int i = 0; i < kNDists; ++i) {
    TString xTitle = "";
    if( i == 0 )      xTitle = "p_{T}(#tau) [GeV]";
    else if( i == 1 ) xTitle = "H_{T} [GeV]";
    else if( i == 2 ) xTitle = "#slash{H}_{T} [GeV]";

    TString yTitle = "N(events) / ";
    yTitle += static_cast<int>(hPred[i]->GetXaxis()->GetBinWidth(1));
    yTitle += " GeV";

    hPred[i]->GetXaxis()->SetTitle(xTitle);
    hPred[i]->GetYaxis()->SetTitle(yTitle);
    hPred[i]->SetMarkerStyle(20);
    hPred[i]->SetMarkerColor(kRed);
    hPred[i]->SetLineColor(hPred[i]->GetMarkerColor());

    if( isMCPred ) {
      hTrue[i]->GetXaxis()->SetTitle(xTitle);
      hTrue[i]->GetYaxis()->SetTitle(yTitle);
      hTrue[i]->SetLineColor(kBlue);
    }
  }
  if( isGenPred ) hMuonPt->GetXaxis()->SetTitle("p_{T}(#mu^{gen}) [GeV]");
  else            hMuonPt->GetXaxis()->SetTitle("p_{T}(#mu) [GeV]");
  hMuonPt->SetMarkerStyle(20);
  hMuonPt->SetMarkerColor(kBlack);
  hMuonPt->SetLineColor(hMuonPt->GetMarkerColor());


  // Create legend
  TLegend* leg = new TLegend(0.4,0.75,0.9,0.89);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.05);
  if( isMCPred ) {
    leg->AddEntry(hTrue[0],"MC Expectation");
    if( isGenPred ) leg->AddEntry(hPred[0],"Gen-Based Pred.");
    else            leg->AddEntry(hPred[0],"Data-Based Pred.");
  }


  // Draw
  for(unsigned int i = 0; i < kNDists; ++i) {
    TString name = "";
    if( i == 0 )      name = "TauJetPt";
    else if( i == 1 ) name = "HT";
    else if( i == 2 ) name = "MHT";

    TCanvas* can = new TCanvas(name,name,600,600);
    can->cd();
    if( isMCPred ) {
      hTrue[i]->Draw("HISTE");
      hPred[i]->Draw("PE1same");
      leg->Draw("same");
      if( isGenPred ) name = "hGenClosure"+name;
      else            name = "hRecoClosure"+name;
    } else {
      hPred[i]->Draw("PE1");
      name = "hDataPred"+name;
    }
    gPad->SetLogy();
    can->SaveAs(name+".eps","eps");
  }

  TCanvas* can = new TCanvas("can","muon pt",600,600);
  can->cd();
  hMuonPt->Draw("PE1");
  gPad->SetLogy();
  TString name = "MuonPt";
  if( isMCPred ) {
    if( isGenPred ) name = "hGenClosure"+name;
    else            name = "hRecoClosure"+name;
  } else {
    name = "hDataPred"+name;
  }
  can->SaveAs(name+".eps","eps");
}
void patBJetVertex_efficiencies()
{
	// define proper canvas style
	setNiceStyle();
	gStyle->SetOptStat(0);

	// open file
	TFile* file = new TFile("analyzePatBJetVertex.root");

	unsigned int j = 0;
	for(const char **algo = algos; *algo; algo++, j++) {
		TLegend *legend[3] = { 0, 0, 0 };

		// draw canvas with efficiencies
		TCanvas *canv;
		canv = new TCanvas(*algo, Form("%s efficiencies", algoNames[j]), 800, 300);
		canv->Divide(3, 1);

		TH1 *total = (TH1*)file->Get(Form("%s/flavours", directory));
		TH1 *effVsCutB = 0;
		unsigned int i = 0;
		for(const char **flavour = flavours; *flavour; flavour++, i++) {
			TH1 *h = (TH1*)file->Get(Form("%s/%s_%s", directory, *algo, *flavour));
			TH1 *discrShape = (TH1*)h->Clone(Form("%s_discrShape", h->GetName()));
			discrShape->Scale(1.0 / discrShape->Integral());
			discrShape->SetMaximum(discrShape->GetMaximum() * 5);
			TH1 *effVsCut = computeEffVsCut(h, total->GetBinContent(4 - i));
			TH1 *effVsBEff = 0;

			if (flavour == flavours)	// b-jets
				effVsCutB = effVsCut;
			else
				effVsBEff = computeEffVsBEff(effVsCut, effVsCutB);

			discrShape->SetTitle("discriminator shape");
			effVsCut->SetTitle("efficiency versus discriminator cut");
			if (effVsBEff)
				effVsBEff->SetTitle("mistag versus b efficiency");

			setHistStyle(discrShape);
			setHistStyle(effVsCut);
			setHistStyle(effVsBEff);

			canv->cd(1);
			gPad->SetLogy(1);
			gPad->SetGridy(1);
			discrShape->SetLineColor(i + 1);
			discrShape->SetMarkerColor(i + 1);
			discrShape->Draw(i > 0 ? "same" : "");
			if (!legend[0])
				legend[0] = new TLegend(0.5, 0.7, 0.78, 0.88);
			legend[0]->AddEntry(discrShape, *flavour);

			canv->cd(2);
			gPad->SetLogy(1);
			gPad->SetGridy(1);
			effVsCut->SetLineColor(i + 1);
			effVsCut->SetMarkerColor(i + 1);
			effVsCut->Draw(i > 0 ? "same" : "");
			if (!legend[1])
				legend[1] = new TLegend(0.3, 0.4, 0.58, 0.58);
			legend[1]->AddEntry(effVsCut, *flavour);

			if (!effVsBEff)
				continue;
			canv->cd(3);
			gPad->SetLogy(1);
			gPad->SetGridx(1);
			gPad->SetGridy(1);
			effVsBEff->SetLineColor(i + 1);
			effVsBEff->SetMarkerColor(i + 1);
			effVsBEff->Draw(i > 1 ? "same" : "");
			if (!legend[2])
				legend[2] = new TLegend(0.12, 0.7, 0.40, 0.88);
			legend[2]->AddEntry(effVsBEff, *flavour);
		}

		canv->cd(1);
		legend[0]->Draw();

		canv->cd(2);
		legend[1]->Draw();

		canv->cd(3);
		legend[2]->Draw();
	}
}
Esempio n. 24
0
  /** 
   * Process a single eta bin 
   * 
   * @param measured     Input collection of measured data
   * @param corrections  Input collection of correction data
   * @param method       Unfolding method to use 
   * @param regParam     Regularisation parameter
   * @param out          Output directory. 
   *
   * @return Stack of histograms or null 
   */
  THStack* ProcessBin(TCollection* measured, 
		      TCollection* corrections, 
		      UInt_t       method,
		      Double_t     regParam, 
		      TDirectory*  out)
  {
    Printf("   Processing %s ...", measured->GetName());
    // Try to get the data 
    TH1* inRaw    = GetH1(measured,    "rawDist");
    TH1* inTruth  = GetH1(corrections, "truth");
    TH1* inTruthA = GetH1(corrections, "truthAccepted");
    TH1* inTrgVtx = GetH1(corrections, "triggerVertex");
    TH2* inResp   = GetH2(corrections, "response");
    if (!inRaw || !inTruth || !inTruthA || !inTrgVtx || !inResp) 
      return 0;
    
    // Make output directory
    TDirectory* dir = out->mkdir(measured->GetName());
    dir->cd();

    // Copy the input to the output 
    TH1* outRaw    = static_cast<TH1*>(inRaw    ->Clone("measured"));
    TH1* outTruth  = static_cast<TH1*>(inTruth  ->Clone("truth"));
    TH1* outTruthA = static_cast<TH1*>(inTruthA ->Clone("truthAccepted"));
    TH1* outTrgVtx = static_cast<TH1*>(inTrgVtx ->Clone("triggerVertex"));
    TH2* outResp   = static_cast<TH2*>(inResp   ->Clone("response"));

    // Make our response matrix 
    RooUnfoldResponse matrix(0, 0, inResp);
    
    // Store regularization parameter 
    Double_t             r        = regParam;
    RooUnfold::Algorithm algo     = (RooUnfold::Algorithm)method;
    RooUnfold*           unfolder = RooUnfold::New(algo, &matrix, inRaw, r);
    unfolder->SetVerbose(0);

    // Do the unfolding and get the result
    TH1* res = unfolder->Hreco();
    res->SetDirectory(0);

    // Make a copy to store on the output 
    TH1* outUnfold = static_cast<TH1*>(res->Clone("unfolded"));
    TString tit(outUnfold->GetTitle());
    tit.ReplaceAll("Unfold Reponse matrix", "Unfolded P(#it{N}_{ch})");
    outUnfold->SetTitle(tit);

    // Clone the unfolded results and divide by the trigger/vertex
    // bias correction
    TH1* outCorr   = static_cast<TH1*>(outUnfold->Clone("corrected"));
    outCorr->Divide(inTrgVtx);
    tit.ReplaceAll("Unfolded", "Corrected");
    outCorr->SetTitle(tit);

    // Now normalize the output to integral=1 
    TH1*  hists[] = { outRaw, outUnfold, outCorr, 0 };
    TH1** phist   = hists;
    while (*phist) { 
      TH1* h = *phist;
      if (h) { 
	Double_t intg = h->Integral(1, h->GetXaxis()->GetXmax());
	h->Scale(1. / intg, "width");
      }
      phist++;
    }
    
    // And make ratios
    TH1* ratioTrue = static_cast<TH1*>(outCorr->Clone("ratioCorrTruth"));
    tit = ratioTrue->GetTitle();
    tit.ReplaceAll("Corrected", "Corrected/MC 'truth'");
    ratioTrue->SetTitle(tit);
    ratioTrue->Divide(outTruth);
    ratioTrue->SetYTitle("P_{corrected}(#it{N}_{ch})/P_{truth}(#it{N}_{ch})");

    TH1* ratioAcc  = static_cast<TH1*>(outUnfold->Clone("ratioUnfAcc"));
    tit = ratioAcc->GetTitle();
    tit.ReplaceAll("Unfolded", "Unfolded/MC selected");
    ratioAcc->SetTitle(tit);
    ratioAcc->Divide(outTruthA);
    ratioAcc->SetYTitle("P_{unfolded}(#it{N}_{ch})/P_{MC}(#it{N}_{ch})");
    

    // Make a stack 
    tit = measured->GetName();
    tit.ReplaceAll("m", "-");
    tit.ReplaceAll("p", "+");
    tit.ReplaceAll("d", ".");
    tit.ReplaceAll("_", "<#it{#eta}<");
    THStack* stack = new THStack("all", tit);
    stack->Add(outTruth,  "E2");
    stack->Add(outTruthA, "E2");
    stack->Add(outRaw,    "E1");
    stack->Add(outUnfold, "E1");
    stack->Add(outCorr,   "E1");
    dir->Add(stack);

    // Rest of the function is devoted to making the output look nice 
    outRaw   ->SetDirectory(dir); 
    outTruth ->SetDirectory(dir);  
    outTruthA->SetDirectory(dir);  
    outTrgVtx->SetDirectory(dir);  
    outResp  ->SetDirectory(dir);  
    outUnfold->SetDirectory(dir);   
    outCorr  ->SetDirectory(dir); 

    outRaw   ->SetMarkerStyle(20);  // Measured is closed
    outTruth ->SetMarkerStyle(24);  // MC is open
    outTruthA->SetMarkerStyle(24);  // MC is open
    outTrgVtx->SetMarkerStyle(20);  // Derived is closed
    outUnfold->SetMarkerStyle(20);  // Derived is closed   
    outCorr  ->SetMarkerStyle(20);  // Derived is closed 

    outRaw   ->SetMarkerSize(0.9); 
    outTruth ->SetMarkerSize(1.6);  
    outTruthA->SetMarkerSize(1.4);  
    outTrgVtx->SetMarkerSize(1.0);  
    outUnfold->SetMarkerSize(0.9);   
    outCorr  ->SetMarkerSize(1.0);
 
    outRaw   ->SetMarkerColor(kColorMeasured); 
    outTruth ->SetMarkerColor(kColorTruth);  
    outTruthA->SetMarkerColor(kColorAccepted);  
    outTrgVtx->SetMarkerColor(kColorTrgVtx);  
    outUnfold->SetMarkerColor(kColorUnfolded);   
    outCorr  ->SetMarkerColor(kColorCorrected); 

    outRaw   ->SetFillColor(kColorError);     
    outTruth ->SetFillColor(kColorError);  
    outTruthA->SetFillColor(kColorError);  
    outTrgVtx->SetFillColor(kColorError);  
    outUnfold->SetFillColor(kColorError);   
    outCorr  ->SetFillColor(kColorError); 

    outRaw   ->SetFillStyle(0); 
    outTruth ->SetFillStyle(1001);  
    outTruthA->SetFillStyle(1001);  
    outTrgVtx->SetFillStyle(0);  
    outUnfold->SetFillStyle(0);   
    outCorr  ->SetFillStyle(0);

    outRaw   ->SetLineColor(kBlack); 
    outTruth ->SetLineColor(kBlack);  
    outTruthA->SetLineColor(kBlack);  
    outTrgVtx->SetLineColor(kBlack);  
    outUnfold->SetLineColor(kBlack);   
    outCorr  ->SetLineColor(kBlack); 

    // Legend 
    TLegend* l = StackLegend(stack);
    l->AddEntry(outRaw,     "Raw",                 "lp");
    l->AddEntry(outTruth,   "MC 'truth'",          "fp");
    l->AddEntry(outTruthA,  "MC 'truth' accepted", "fp");
    l->AddEntry(outUnfold,  "Unfolded",            "lp");
    l->AddEntry(outCorr,    "Corrected",           "lp");

    return stack;
  }
void makePlot(const std::string& inputFilePath, const std::string& canvasName, const std::string& sample, int massPoint, const std::string& channel, double k, 
	      const std::string& inputFileName, const std::string& outputFilePath, const std::string& outputFileName)
{
  std::string inputFileName_full = Form("%s%s", inputFilePath.data(), inputFileName.data());
  TFile* inputFile = new TFile(inputFileName_full.data());
  if ( !inputFile ) {
    std::cerr << "Failed to open input file = " << inputFileName_full << " !!" << std::endl;
    assert(0);
  }

  inputFile->ls();

  TCanvas* canvas = dynamic_cast<TCanvas*>(inputFile->Get(canvasName.data()));
  if ( !canvas ) {
    std::cerr << "Failed to load canvas = " << canvasName << " !!" << std::endl;
    assert(0);
  }

  int idxPad = -1;
  if ( massPoint ==  90 ) idxPad = 1;
  if ( massPoint == 125 ) idxPad = 2;
  if ( massPoint == 200 ) idxPad = 3;
  if ( massPoint == 300 ) idxPad = 4;
  if ( massPoint == 500 ) idxPad = 5;
  if ( massPoint == 800 ) idxPad = 6;  
  if ( !(idxPad >= 1 && idxPad <= 6) ) {
    std::cerr << "Invalid sample = " << sample << " !!" << std::endl;
    assert(0);
  }
  TVirtualPad* pad = canvas->GetPad(idxPad);
  std::cout << "pad = " << pad << ": ClassName = " << pad->ClassName() << std::endl;

  TCanvas* canvas_new = new TCanvas("canvas_new", "canvas_new", 900, 800);
  canvas_new->SetFillColor(10);
  canvas_new->SetBorderSize(2);
  canvas_new->SetTopMargin(0.065);
  canvas_new->SetLeftMargin(0.17);
  canvas_new->SetBottomMargin(0.165);
  canvas_new->SetRightMargin(0.015);
  canvas_new->SetLogx(true);
  canvas_new->SetLogy(true);
  canvas_new->Draw();
  canvas_new->cd();

  //TList* pad_primitives = canvas->GetListOfPrimitives();
  TList* pad_primitives = pad->GetListOfPrimitives();

  TH1* histogramCA            = 0;
  TH1* histogramSVfit         = 0;
  TH1* histogramSVfitMEMkEq0  = 0;
  TH1* histogramSVfitMEMkNeq0 = 0;

  TIter pad_nextObj(pad_primitives);
  while ( TObject* obj = pad_nextObj() ) {
    std::string objName = "";
    if ( dynamic_cast<TNamed*>(obj) ) objName = (dynamic_cast<TNamed*>(obj))->GetName();    
    std::cout << "obj = " << obj << ": name = " << objName << ", type = " << obj->ClassName() << std::endl;

    TH1* tmpHistogram = dynamic_cast<TH1*>(obj);
    if ( tmpHistogram ) {
      std::cout << "tmpHistogram:" 
		<< " fillColor = " << tmpHistogram->GetFillColor() << ", fillStyle = " << tmpHistogram->GetFillStyle() << ","
		<< " lineColor = " << tmpHistogram->GetLineColor() << ", lineStyle = " << tmpHistogram->GetLineStyle() << ", lineWidth = " << tmpHistogram->GetLineWidth() << ","
		<< " markerColor = " << tmpHistogram->GetMarkerColor() << ", markerStyle = " << tmpHistogram->GetMarkerStyle() << ", markerSize = " << tmpHistogram->GetMarkerSize() << ","
		<< " integral = " << tmpHistogram->Integral() << std::endl;
      std::cout << "(mean = " << tmpHistogram->GetMean() << ", rms = " << tmpHistogram->GetRMS() << ": rms/mean = " << (tmpHistogram->GetRMS()/tmpHistogram->GetMean()) << ")" << std::endl;
      if ( tmpHistogram->GetLineColor() == 416 ) histogramCA            = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 600 ) histogramSVfit         = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 616 ) histogramSVfitMEMkEq0  = tmpHistogram;
      if ( tmpHistogram->GetLineColor() == 632 ) histogramSVfitMEMkNeq0 = tmpHistogram;
    }
  }

  if ( !(histogramCA && histogramSVfit && histogramSVfitMEMkEq0 && histogramSVfitMEMkNeq0) ) {
    std::cerr << "Failed to load histograms !!" << std::endl;
    assert(0);
  }

  //gStyle->SetLineStyleString(2,"40 10 10 10 10 10 10 10");
  //gStyle->SetLineStyleString(3,"25 15");
  //gStyle->SetLineStyleString(4,"60 25");

  //int colors[4] = { kBlack, kGreen - 6, kBlue - 7, kMagenta - 7  };
  int colors[4] = { 28, kGreen - 6, kBlue - 7, kBlack };
  //int lineStyles[4] = { 2, 3, 4, 1 };
  int lineStyles[4] = { 7, 1, 1, 1 };
  //int lineWidths[4] = { 3, 3, 4, 3 };
  int lineWidths[4] = { 3, 3, 1, 1 };
  int markerStyles[4] = { 20, 25, 21, 24 };
  int markerSizes[4] = { 2, 2, 2, 2 };

  histogramCA->SetFillColor(0);
  histogramCA->SetFillStyle(0);
  histogramCA->SetLineColor(colors[0]);
  histogramCA->SetLineStyle(lineStyles[0]);
  histogramCA->SetLineWidth(lineWidths[0]);
  histogramCA->SetMarkerColor(colors[0]);
  histogramCA->SetMarkerStyle(markerStyles[0]);
  histogramCA->SetMarkerSize(markerSizes[0]);

  histogramSVfit->SetFillColor(0);
  histogramSVfit->SetFillStyle(0);
  histogramSVfit->SetLineColor(colors[1]);
  histogramSVfit->SetLineStyle(lineStyles[1]);
  histogramSVfit->SetLineWidth(lineWidths[1]);
  histogramSVfit->SetMarkerColor(colors[1]);
  histogramSVfit->SetMarkerStyle(markerStyles[1]);
  histogramSVfit->SetMarkerSize(markerSizes[1]);

  histogramSVfitMEMkEq0->SetFillColor(0);
  histogramSVfitMEMkEq0->SetFillStyle(0);
  histogramSVfitMEMkEq0->SetLineColor(colors[2]);
  histogramSVfitMEMkEq0->SetLineStyle(lineStyles[2]);
  histogramSVfitMEMkEq0->SetLineWidth(lineWidths[2]);
  histogramSVfitMEMkEq0->SetMarkerColor(colors[2]);
  histogramSVfitMEMkEq0->SetMarkerStyle(markerStyles[2]);
  histogramSVfitMEMkEq0->SetMarkerSize(markerSizes[2]);
  // CV: fix pathological bins at high mass for which dN/dm increases
  int numBins = histogramSVfitMEMkEq0->GetNbinsX();
  for ( int idxBin = 1; idxBin <= numBins; ++idxBin ) {
    double binCenter = histogramSVfitMEMkEq0->GetBinCenter(idxBin);
    if ( (channel == "#tau_{h}#tau_{h}" && massPoint == 500 && binCenter > 1500.) ||
	 (channel == "#tau_{h}#tau_{h}" && massPoint == 800 && binCenter > 2000.) ||
	 (channel == "#mu#tau_{h}"      && massPoint == 500 && binCenter > 1500.) ||
	 (channel == "#mu#tau_{h}"      && massPoint == 800 && binCenter > 2500.) ) {
      histogramSVfitMEMkEq0->SetBinContent(idxBin, 0.);
    }
  }

  histogramSVfitMEMkNeq0->SetFillColor(0);
  histogramSVfitMEMkNeq0->SetFillStyle(0);
  histogramSVfitMEMkNeq0->SetLineColor(colors[3]);
  histogramSVfitMEMkNeq0->SetLineStyle(lineStyles[3]);
  histogramSVfitMEMkNeq0->SetLineWidth(lineWidths[3]);
  histogramSVfitMEMkNeq0->SetMarkerColor(colors[3]);
  histogramSVfitMEMkNeq0->SetMarkerStyle(markerStyles[3]);
  histogramSVfitMEMkNeq0->SetMarkerSize(markerSizes[3]);

  TAxis* xAxis = histogramCA->GetXaxis();
  xAxis->SetTitle("m_{#tau#tau} [GeV]");
  xAxis->SetTitleOffset(1.15);
  xAxis->SetTitleSize(0.070);
  xAxis->SetTitleFont(42);
  xAxis->SetLabelOffset(0.010);
  xAxis->SetLabelSize(0.055);
  xAxis->SetLabelFont(42);
  xAxis->SetTickLength(0.040);
  xAxis->SetNdivisions(510);

  //double xMin = 20.;
  //double xMax = xAxis->GetXmax();
  //xAxis->SetRangeUser(xMin, xMax);

  TAxis* yAxis = histogramCA->GetYaxis();
  yAxis->SetTitle("dN/dm_{#tau#tau} [1/GeV]");
  yAxis->SetTitleOffset(1.20);
  yAxis->SetTitleSize(0.070);
  yAxis->SetTitleFont(42);
  yAxis->SetLabelOffset(0.010);
  yAxis->SetLabelSize(0.055);
  yAxis->SetLabelFont(42);
  yAxis->SetTickLength(0.040);  
  yAxis->SetNdivisions(505);

  double massPoint_double = 0.;
  if ( massPoint == 90 ) massPoint_double = 91.2;
  else massPoint_double = massPoint;
  double dLog = (TMath::Log(5.*massPoint_double) - TMath::Log(50.))/25.; // xMin = 50, xMax = 5*massPoint, numBins = 25
  double binWidth = TMath::Exp(TMath::Log(massPoint_double) + 0.5*dLog) - TMath::Exp(TMath::Log(massPoint_double) - 0.5*dLog);
  double sf_binWidth = 1./binWidth;
  std::cout << "massPoint = " << massPoint << ": sf_binWidth = " << sf_binWidth << std::endl;

  histogramCA->SetTitle("");
  histogramCA->SetStats(false);
  histogramCA->SetMaximum(sf_binWidth*0.79);
  histogramCA->SetMinimum(sf_binWidth*1.1e-4);
  histogramCA->Draw("hist");
  histogramSVfit->Draw("histsame");
  //histogramSVfitMEMkEq0->Draw("histsame");
  histogramSVfitMEMkEq0->Draw("epsame");
  //histogramSVfitMEMkNeq0->Draw("histsame");
  histogramSVfitMEMkNeq0->Draw("epsame");
  histogramCA->Draw("axissame");

  //TPaveText* label_sample = new TPaveText(0.21, 0.86, 0.46, 0.94, "NDC");
  TPaveText* label_sample = new TPaveText(0.1700, 0.9475, 0.4600, 1.0375, "NDC");
  label_sample->SetFillStyle(0);
  label_sample->SetBorderSize(0);
  label_sample->AddText(sample.data());
  label_sample->SetTextFont(42);
  label_sample->SetTextSize(0.055);
  label_sample->SetTextColor(1);
  label_sample->SetTextAlign(13);
  label_sample->Draw();

  //TLegend* legend_new = new TLegend(0.225, 0.52, 0.41, 0.82, NULL, "brNDC");
  TLegend* legend_new = new TLegend(0.30, 0.30, 0.80, 0.80, NULL, "brNDC");
  legend_new->SetFillColor(10);
  legend_new->SetFillStyle(0);
  legend_new->SetBorderSize(0);
  legend_new->SetTextFont(42);
  legend_new->SetTextSize(0.055);
  legend_new->SetTextColor(1);
  legend_new->SetMargin(0.20);
  legend_new->AddEntry(histogramCA, "CA", "l");
  legend_new->AddEntry(histogramSVfit, "SVfit", "l");
  //legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "l");
  legend_new->AddEntry(histogramSVfitMEMkEq0, "SVfitMEM (k=0)", "p");
  //legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM(k=%1.0f)", k), "l");
  legend_new->AddEntry(histogramSVfitMEMkNeq0, Form("SVfitMEM (k=%1.0f)", k), "p");
  //legend_new->Draw();

  double label_channel_y0;
  if      ( channel == "e#mu"             ) label_channel_y0 = 0.9275;
  else if ( channel == "#mu#tau_{h}"      ) label_channel_y0 = 0.9400;
  else if ( channel == "#tau_{h}#tau_{h}" ) label_channel_y0 = 0.9350;
  else {
    std::cerr << "Invalid channel = " << channel << " !!" << std::endl;
    assert(0);
  }
  TPaveText* label_channel = new TPaveText(0.895, label_channel_y0, 0.975, label_channel_y0 + 0.055, "NDC");
  label_channel->SetFillStyle(0);
  label_channel->SetBorderSize(0);
  label_channel->AddText(channel.data());
  label_channel->SetTextFont(62);
  label_channel->SetTextSize(0.055);
  label_channel->SetTextColor(1);
  label_channel->SetTextAlign(31);
  label_channel->Draw();

  canvas_new->Update();

  std::string outputFileName_full = Form("%s%s", outputFilePath.data(), outputFileName.data());
  size_t idx = outputFileName_full.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName_full, 0, idx);
  canvas_new->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas_new->Print(std::string(outputFileName_plot).append(".root").data());

  std::string channel_string;
  if      ( channel == "e#mu"             ) channel_string = "emu";
  else if ( channel == "#mu#tau_{h}"      ) channel_string = "muhad";
  else if ( channel == "#tau_{h}#tau_{h}" ) channel_string = "hadhad";
  else {
    std::cerr << "Invalid channel = " << channel << " !!" << std::endl;
    assert(0);
  }
  std::string outputFileName_legend = Form("makeSVfitMEM_PerformancePlots_legend_%s.pdf", channel_string.data());
  makePlot_legend(legend_new, outputFilePath, outputFileName_legend);

  delete label_sample;
  delete legend_new;
  delete label_channel;
  delete canvas_new;

  delete inputFile;
}
Esempio n. 26
0
TH1* GetCentK(TDirectory* top, Double_t c1, Double_t c2, Int_t s,
	      TLegend* l)
{
  TString dname; dname.Form("cent%06.2f_%06.2f", c1, c2);
  dname.ReplaceAll(".", "d");
  TDirectory* d = top->GetDirectory(dname);
  if (!d) {
    Warning("GetCetnK", "Directory %s not found in %s",
	    dname.Data(), top->GetName());
    return;
  }

  TDirectory* det = d->GetDirectory("details");
  if (!det) {
    Warning("GetCetnK", "Directory details not found in %s",
	    d->GetName());
    d->ls();
    return;
  }

  TObject* o = det->Get("scalar");
  if (!o) {
    Warning("GetCetnK", "Object scalar not found in %s",
	    det->GetName());
    return;
  }

  if (!o->IsA()->InheritsFrom(TH1::Class())) {
    Warning("GetCetnK", "Object %s is not a TH1, but a %s",
	    o->GetName(), o->ClassName());
    return;
  }
  TH1* h = static_cast<TH1*>(o->Clone());
  Color_t col = cc[(s-1)%10];
  h->SetLineColor(col);
  h->SetMarkerColor(col);
  h->SetFillColor(col);
  h->SetFillStyle(1001);
  // h->SetTitle(Form("%5.2f-%5.2f%% #times %d", c1, c2, s));
  h->SetTitle(Form("%2.0f-%2.0f%% + %d", c1, c2, s-1));
  TF1* f = new TF1("", "[0]",-2.2,2.2);
  f->SetParameter(0,s-1);
  f->SetLineColor(col);
  f->SetLineStyle(7);
  f->SetLineWidth(1);
  // h->Scale(s);
  h->Add(f);
  h->GetListOfFunctions()->Add(f);
  f->SetParameter(0,s);
  for (Int_t i = 1; i <= h->GetNbinsX(); i++) {
    if (TMath::Abs(h->GetBinCenter(i)) > 2) {
      h->SetBinContent(i,0);
      h->SetBinError(i,0);
    }
  }
  
  TLegendEntry* e = l->AddEntry(h, h->GetTitle(), "f");
  e->SetFillColor(col);
  e->SetFillStyle(1001);
  e->SetLineColor(col);

  return h;
}
Esempio n. 27
0
TH1 *
UnfoldMe(Char_t *data, Char_t *mc, Char_t *anatag, Int_t bin, Bool_t useMBcorr = kTRUE, Bool_t usecorrfit = kFALSE, Bool_t ismc = kFALSE, Float_t smooth = 0.001, Int_t iter = 50, Int_t regul = AliUnfolding::kPowerLaw, Float_t weight = 100., Bool_t bayesian = kTRUE, Int_t nloop = 1)
{

  if (ismc)
    TFile *fdt = TFile::Open(data);
  else
    TFile *fdt = TFile::Open(data);
  TFile *fmc = TFile::Open(mc);
  
  TList *ldt = (TList *)fdt->Get(Form("clist_%s", anatag));
  TList *lmc = (TList *)fmc->Get(Form("clist_%s", anatag));
  
  TH2 *hmatdt = (TH2 *)ldt->FindObject(Form("b%d_corrMatrix", bin));
  if (useMBcorr)
    TH2 *hmatmc = (TH2 *)lmc->FindObject("effMatrix");
  else
    TH2 *hmatmc = (TH2 *)lmc->FindObject(Form("b%d_corrMatrix", bin));
 
  TH1 *hdata = hmatdt->ProjectionY("hdata");
  hdata->Sumw2();
  hdata->SetBinContent(1, 0.);
  hdata->SetBinError(1, 0.);
  //  hdata->Scale(1. / hdata->Integral());
  hdata->SetMarkerStyle(25);
  TH1 *htrue = hmatdt->ProjectionX("htrue");
  htrue->Sumw2();
  //  htrue->Scale(1. / htrue->Integral());
  htrue->SetMarkerStyle(7);
  htrue->SetMarkerColor(2);
  htrue->SetBinContent(1, 0.);
  htrue->SetBinError(1, 0.);
  TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr");
  TH1 *hinit = (TH1 *)hdata->Clone("hinit");
  TH1 *hresu = (TH1 *)hdata->Clone("hresu");
  TH1 *hbias = (TH1 *)hdata->Clone("hbias");
  hresu->SetMarkerStyle(20);
  hresu->SetMarkerColor(4);
  hresu->Reset();

  TH1 *hnum = hcorr->ProjectionY("hnum");
  TH1 *hden = hcorr->ProjectionY("hden");
  TH1 *heff = hcorr->ProjectionY("heff");
  hnum->Reset();
  hnum->Sumw2();
  hden->Reset();
  hden->Sumw2();
  heff->Reset();
  for (Int_t i = 0; i < heff->GetNbinsX(); i++) {
    Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1);
    if (int1 <= 0.) continue;
    Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1);
    hnum->SetBinContent(i + 1, int2);
    hnum->SetBinError(i + 1, TMath::Sqrt(int2));
    hden->SetBinContent(i + 1, int1);
    hden->SetBinError(i + 1, TMath::Sqrt(int1));
  }
  new TCanvas("cEfficiency");
  heff->Divide(hnum, hden, 1., 1., "B");
  heff->Draw();
#if 0
  for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) {
    heff->SetBinContent(ii + 1, 1.);
    heff->SetBinError(ii + 1, 0.);
  }
#endif
  
  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    hcorr->SetBinContent(i + 1, 1, 0.);
    hcorr->SetBinError(i + 1, 1, 0.);
  }
  for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) {
    hcorr->SetBinContent(1, i + 1, 0.);
    hcorr->SetBinError(1, i + 1, 0.);
  }
  TH2 *hcorrfit = ReturnCorrFromFit(hcorr);

  for (Int_t iloop = 0; iloop < nloop; iloop++) {
    if (bayesian) {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian);
      AliUnfolding::SetBayesianParameters(smooth, iter);
    } else {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization);
      AliUnfolding::SetChi2Regularization(regul, weight);
    }
    AliUnfolding::SetSkip0BinInChi2(kTRUE);
    AliUnfolding::SetSkipBinsBegin(1);
    AliUnfolding::SetNbins(150, 150);
    AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu);
    hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop));
  }

  printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1));
  printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1));
  
  
  TCanvas *cUnfolded = new TCanvas ("cUnfolded", "", 400, 800);
  cUnfolded->Divide(1, 2);
  cUnfolded->cd(1)->SetLogx();
  cUnfolded->cd(1)->SetLogy();
  hdata->Draw();
  hresu->Draw("same");
  htrue->Draw("same");
  cUnfolded->cd(2)->SetLogx();
  cUnfolded->cd(2)->DrawFrame(1., 0.75, 300., 1.25);
  TH1 *hrat = (TH1 *)hresu->Clone("hrat");
  hrat->Divide(htrue);
  hrat->Draw("same");

  TH1 *htrig = (TH1 *)hresu->Clone("htrig");
  htrig->Multiply(heff);

  Float_t dndeta_resu = 0.;
  Float_t integr_resu = 0.;
  Float_t dndeta_trig = 0.;
  Float_t integr_trig = 0.;
  for (Int_t i = 1; i < hresu->GetNbinsX(); i++) {
    dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1);
    integr_resu += hresu->GetBinContent(i + 1);
    dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1);
    integr_trig += htrig->GetBinContent(i + 1);
  }
  //  dndeta_resu /= integr_resu;
  //  dndeta_trig /= integr_trig;

  integr_eff = integr_trig / integr_resu;
  integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu);
  dndeta_eff = dndeta_trig / dndeta_resu;
  dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu);
  
  printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err);
  printf("dN/dEta correction:  %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err);

  return hresu;
}
Esempio n. 28
0
void PerformanceSpectrumUncorr(const Char_t *fname = "HFEtask.root"){

  gROOT->SetStyle("Plain");
  gStyle->SetTitleFillColor(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetTitleX(0.1);
  gStyle->SetTitleY(0.96);

  TFile *in = TFile::Open(fname);
  TList *res = (TList *)in->Get("HFE_Results");
  TList *qa = (TList *)in->Get("HFE_QA");
  gROOT->cd();
  AliHFEcontainer *tcont = dynamic_cast<AliHFEcontainer *>(res->FindObject("trackContainer"));
  AliCFContainer *c = tcont->GetCFContainer("recTrackContReco");
  AliCFContainer *cb = tcont->GetCFContainer("hadronicBackground");

  TH1 *spec = c->Project(c->GetNStep() - 1, 0);
  spec->GetXaxis()->SetTitle("p_{T} / GeV/c");
  spec->GetYaxis()->SetTitle("#frac{dN}{dp_{T}} / (GeV/c)^{-1}");
  spec->GetXaxis()->SetRangeUser(ptmin, ptmax);
  spec->GetYaxis()->SetTitleOffset(1.1);
  spec->SetTitle();
  spec->SetStats(kFALSE);

  spec->SetLineColor(kBlue);
  spec->SetLineWidth(1);
  spec->SetMarkerColor(kBlue);
  spec->SetMarkerStyle(22);

  // Produce background subtracted spectrum
  AliCFDataGrid tracks("tracks", "track grid", *c, c->GetNStep() - 1);
  AliCFDataGrid background("background", "background grid", *cb, 1);
  tracks.ApplyBGCorrection(background);
  TH1 *spec_subtracted = tracks.Project(0);
  spec_subtracted->GetXaxis()->SetTitle("p_{T} / GeV/c");
  spec_subtracted->GetYaxis()->SetTitle("#frac{dN}{dp_{T}} / (GeV/c)^{-1}");
  spec_subtracted->GetXaxis()->SetRangeUser(ptmin, ptmax);
  spec_subtracted->GetYaxis()->SetTitleOffset(1.1);
  spec_subtracted->SetTitle();
  spec_subtracted->SetStats(kFALSE);
  spec_subtracted->SetLineColor(kRed);
  spec_subtracted->SetLineWidth(1);
  spec_subtracted->SetMarkerColor(kRed);
  spec_subtracted->SetMarkerStyle(22);

  TLegend *leg = new TLegend(0.2, 0.25, 0.4, 0.35);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  leg->AddEntry(spec, "Raw Spectrum", "p");
  leg->AddEntry(spec_subtracted, "Spectrum after background subtraction", "p");
 
  TCanvas *c1 = new TCanvas("cspec", "Single-inclusive electron spectrum", 1200, 750);
  c1->cd();
  c1->SetLogy();
  c1->SetGridx(kFALSE);
  c1->SetGridy(kFALSE);
  spec->Draw("ep");
  spec_subtracted->Draw("epsame");
  leg->Draw();
  ALICEWorkInProgress(c1, "today");

  // PID
  TList *pidqa = (TList *)qa->FindObject("HFEpidQA");
  AliHFEtpcPIDqa *tpcqa = (AliHFEtpcPIDqa *)pidqa->FindObject("TPCQA");
  AliHFEtofPIDqa *tofqa = (AliHFEtofPIDqa *)pidqa->FindObject("TOFQA");

  // Make Plots for TPC
  // Create histograms by projecting the THnSparse
  TH2 *hTPCall = tpcqa->MakeSpectrumdEdx(AliHFEdetPIDqa::kBeforePID);
  TH2 *hTPCselected = tpcqa->MakeSpectrumdEdx(AliHFEdetPIDqa::kAfterPID);
  TH2 *hTPCsigmaAll = tpcqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kBeforePID);
  TH2* hTPCsigmaSelected = tpcqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kAfterPID);
  // Make Plots for TOF
  TH2 *hTOFsigmaAll = tofqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kBeforePID);
  TH2 *hTOFsigmaSelected = tofqa->MakeSpectrumNSigma(AliHFEdetPIDqa::kAfterPID);

  hTPCsigmaAll->SetTitle("TPC n#sigma around the electron line");
  hTPCsigmaSelected->SetTitle("TPC n#sigma around the electron line for selected tracks");
  hTOFsigmaAll->SetTitle("TOF n#sigma around the electron line");
  hTOFsigmaSelected->SetTitle("TOF n#sigma around the electron line for selected tracks");
  DefineTPChisto(hTPCall, "TPC Signal / a.u");
  DefineTPChisto(hTPCselected, "TPC Signal / a.u.");
  DefineTPChisto(hTPCsigmaAll, "TPC Sigma");
  DefineTPChisto(hTPCsigmaSelected, "TPC Sigma");

  // Also make nice histograms for TOF
  DefineTPChisto(hTOFsigmaAll, "TOF Sigma");
  DefineTPChisto(hTOFsigmaSelected, "TOF Sigma");

  // Plot them
  TCanvas *c2 = new TCanvas("cTPCall", "TPC Signal for all tracks", 640, 480);
  c2->cd();
  c2->SetGridx(kFALSE);
  c2->SetGridy(kFALSE);
  c2->SetLogx();
  c2->SetLogz();
  hTPCall->GetYaxis()->SetRangeUser(40., 100.);
  hTPCall->Draw("colz");
  ALICEWorkInProgress(c2, "today");

  TCanvas *c3 = new TCanvas("cTPCsel", "TPC Signal for selected tracks", 640, 480);
  c3->cd();
  c3->SetGridx(kFALSE);
  c3->SetGridy(kFALSE);
  c3->SetLogx();
  c3->SetLogz();
  hTPCselected->GetYaxis()->SetRangeUser(40., 100.);
  hTPCselected->Draw("colz");
  ALICEWorkInProgress(c3, "today");

  TCanvas *c4 = new TCanvas("cTPCsigAll", "TPC Sigma for all tracks", 640, 480);
  c4->cd();
  c4->SetGridx(kFALSE);
  c4->SetGridy(kFALSE);
  c4->SetLogx();
  c4->SetLogz();
  //hTPCsigmaAll->GetYaxis()->SetRangeUser(-3.5, 5.);
  hTPCsigmaAll->Draw("colz");
  ALICEWorkInProgress(c4, "today");

  TCanvas *c5 = new TCanvas("cTPCsigSel", "TPC Sigma for selected tracks", 640, 480);
  c5->cd();
  c5->SetGridx(kFALSE);
  c5->SetGridy(kFALSE);
  c5->SetLogx();
  c5->SetLogz();
  hTPCsigmaSelected->GetYaxis()->SetRangeUser(-3.5, 5.);
  hTPCsigmaSelected->Draw("colz");
  ALICEWorkInProgress(c5, "today");

  TCanvas *c6 = new TCanvas("cTOFsigAll", "TOF Sigma for all tracks", 640, 480);
  c6->cd();
  c6->SetGridx(kFALSE);
  c6->SetGridy(kFALSE);
  c6->SetLogx();
  c6->SetLogz();
  hTOFsigmaAll->Draw("colz");
  ALICEWorkInProgress(c6, "today");

  TCanvas *c7 = new TCanvas("cTOFsigSel", "TOF Sigma for selected tracks", 640, 480);
  c7->cd();
  c7->SetGridx(kFALSE);
  c7->SetGridy(kFALSE);
  c7->SetLogx();
  c7->SetLogz();
  //hTOFsigmaSelected->GetYaxis()->SetRangeUser(-3, 3);
  hTOFsigmaSelected->Draw("colz");
  ALICEWorkInProgress(c7, "today");

  TFile *output = new TFile("Performance.root", "RECREATE");
  output->cd();
  spec->Write();
  hTPCall->Write();
  hTPCselected->Write();
  hTPCsigmaAll->Write();
  hTPCsigmaSelected->Write();
  c1->Write();
  c2->Write();
  c3->Write();
  c4->Write();
  c5->Write();
  c6->Write();
  c7->Write();
  output->Close();
  delete output;
}
Esempio n. 29
0
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void mvas( TString fin = "TMVA.root", HistType htype = MVAType, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas *c = 0;

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if( ! gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory") ) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);

      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {
         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         cout << "--- Found directory for method: " << methodName << "::" << methodTitle << flush;
         TString hname = "MVA_" + methodTitle;
         if      (htype == ProbaType  ) hname += "_Proba";
         else if (htype == RarityType ) hname += "_Rarity";
         TH1* sig = dynamic_cast<TH1*>(titDir->Get( hname + "_S" ));
         TH1* bgd = dynamic_cast<TH1*>(titDir->Get( hname + "_B" ));

         if (sig==0 || bgd==0) {
            if     (htype == MVAType)     
               cout << "mva distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == ProbaType)   
               cout << "probability distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == RarityType)  
               cout << "rarity distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == CompareType) 
               cout << "overtraining check not available (this is normal for Cut classifier)" << endl;
            else cout << endl;
         } 
         else {
            cout << endl;
            // chop off useless stuff
            sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
            if      (htype == ProbaType) 
               sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) );
            else if (htype == RarityType) 
               sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) );
            else if (htype == CompareType) 
               sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) );
         
            // create new canvas
            TString ctitle = ((htype == MVAType) ? 
                              Form("TMVA response %s",methodTitle.Data()) : 
                              (htype == ProbaType) ? 
                              Form("TMVA probability %s",methodTitle.Data()) :
                              (htype == CompareType) ? 
                              Form("TMVA comparison %s",methodTitle.Data()) :
                              Form("TMVA Rarity %s",methodTitle.Data()));
         
            TString cname = ((htype == MVAType) ? 
                             Form("output_%s",methodTitle.Data()) : 
                             (htype == ProbaType) ? 
                             Form("probability_%s",methodTitle.Data()) :
                             (htype == CompareType) ? 
                             Form("comparison_%s",methodTitle.Data()) :
                             Form("rarity_%s",methodTitle.Data()));

            c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, 
                             countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); 
    
            // set the histogram style
            TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
   
            // normalise both signal and background
            TMVAGlob::NormalizeHists( sig, bgd );
   
            // frame limits (choose judicuous x range)
            Float_t nrms = 4;
            cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl;
            cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl;
            Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
                                                  bgd->GetMean() - nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmin() );
            Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
                                                  bgd->GetMean() + nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmax() );
            Float_t ymin = 0;
            Float_t maxMult = (htype == CompareType) ? 1.3 : 1.2;
            Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
   
            // build a frame
            Int_t nb = 500;
            TString hFrameName(TString("frame") + methodTitle);
            TObject *o = gROOT->FindObject(hFrameName);
            if(o) delete o;
            TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                                    nb, xmin, xmax, nb, ymin, ymax );
            frame->GetXaxis()->SetTitle( methodTitle + ((htype == MVAType || htype == CompareType) ? " response" : "") );
            if      (htype == ProbaType  ) frame->GetXaxis()->SetTitle( "Signal probability" );
            else if (htype == RarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" );
            frame->GetYaxis()->SetTitle("Normalized");
            TMVAGlob::SetFrameStyle( frame );
   
            // eventually: draw the frame
            frame->Draw();  
    
            c->GetPad(0)->SetLeftMargin( 0.105 );
            frame->GetYaxis()->SetTitleOffset( 1.2 );

            // Draw legend               
            TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                          c->GetLeftMargin() + (htype == CompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() );
            legend->SetFillStyle( 1 );
            legend->AddEntry(sig,TString("Signal")     + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->AddEntry(bgd,TString("Background") + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->SetBorderSize(1);
            legend->SetMargin( (htype == CompareType ? 0.2 : 0.3) );
            legend->Draw("same");

            // overlay signal and background histograms
            sig->Draw("samehist");
            bgd->Draw("samehist");
   
            if (htype == CompareType) {
               // if overtraining check, load additional histograms
               TH1* sigOv = 0;
               TH1* bgdOv = 0;

               TString ovname = hname += "_Train";
               sigOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_S" ));
               bgdOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_B" ));
      
               if (sigOv == 0 || bgdOv == 0) {
                  cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl;
               }
               else {
                  cout << "--- Found comparison histograms for overtraining check" << endl;

                  TLegend *legend2= new TLegend( 1 - c->GetRightMargin() - 0.42, 1 - c->GetTopMargin() - 0.12,
                                                 1 - c->GetRightMargin(), 1 - c->GetTopMargin() );
                  legend2->SetFillStyle( 1 );
                  legend2->SetBorderSize(1);
                  legend2->AddEntry(sigOv,"Signal (training sample)","P");
                  legend2->AddEntry(bgdOv,"Background (training sample)","P");
                  legend2->SetMargin( 0.1 );
                  legend2->Draw("same");
               }
               Int_t col = sig->GetLineColor();
               sigOv->SetMarkerColor( col );
               sigOv->SetMarkerSize( 0.7 );
               sigOv->SetMarkerStyle( 20 );
               sigOv->SetLineWidth( 1 );
               sigOv->SetLineColor( col );
               sigOv->Draw("e1same");
      
               col = bgd->GetLineColor();
               bgdOv->SetMarkerColor( col );
               bgdOv->SetMarkerSize( 0.7 );
               bgdOv->SetMarkerStyle( 20 );
               bgdOv->SetLineWidth( 1 );
               bgdOv->SetLineColor( col );
               bgdOv->Draw("e1same");

               ymax = TMath::Max( ymax, TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult );
               frame->GetYaxis()->SetLimits( 0, ymax );
      
               // for better visibility, plot thinner lines
               sig->SetLineWidth( 1 );
               bgd->SetLineWidth( 1 );

               // perform K-S test
               cout << "--- Perform Kolmogorov-Smirnov tests" << endl;
               Double_t kolS = sig->KolmogorovTest( sigOv );
               Double_t kolB = bgd->KolmogorovTest( bgdOv );
               cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl;

               TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB );
               TText* tt = new TText( 0.12, 0.74, probatext );
               tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); 
            }

            // redraw axes
            frame->Draw("sameaxis");

            // text for overflows
            Int_t    nbin = sig->GetNbinsX();
            Double_t dxu  = sig->GetBinWidth(0);
            Double_t dxo  = sig->GetBinWidth(nbin+1);
            TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                                   sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                                   sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
            TText* t = new TText( 0.975, 0.115, uoflow );
            t->SetNDC();
            t->SetTextSize( 0.030 );
            t->SetTextAngle( 90 );
            t->AppendPad();    
   
            // update canvas
            c->Update();

            // save canvas to file

            TMVAGlob::plot_logo(1.058);
            if (Save_Images) {
               if      (htype == MVAType)     TMVAGlob::imgconv( c, Form("plots/mva_%s",     methodTitle.Data()) );
               else if (htype == ProbaType)   TMVAGlob::imgconv( c, Form("plots/proba_%s",   methodTitle.Data()) ); 
               else if (htype == CompareType) TMVAGlob::imgconv( c, Form("plots/overtrain_%s", methodTitle.Data()) ); 
               else                           TMVAGlob::imgconv( c, Form("plots/rarity_%s",  methodTitle.Data()) ); 
            }
            countCanvas++;
         }
      }
   }
}
void makePlot(TH1* histogram_data, bool doKeepBlinded,
	      TH1* histogram_ttH, 
	      TH1* histogram_ttZ,
	      TH1* histogram_ttW,
	      TH1* histogram_EWK,
	      TH1* histogram_Rares,
	      TH1* histogram_fakes,
	      TH1* histogramSum_mc,
	      TH1* histogramErr_mc,		
	      const std::string& xAxisTitle, 
	      const std::string& yAxisTitle, double yMin, double yMax,
	      bool showLegend,
	      const std::string& label,
	      const std::string& outputFileName,
	      bool useLogScale)
{
  TH1* histogram_data_density = 0;
  if ( histogram_data ) {
    histogram_data_density = divideHistogramByBinWidth(histogram_data);      
  }
  histogram_data_density->SetMarkerColor(1);
  histogram_data_density->SetMarkerStyle(20);
  histogram_data_density->SetMarkerSize(2);
  histogram_data_density->SetLineColor(1);
  histogram_data_density->SetLineWidth(1);
  histogram_data_density->SetLineStyle(1);

  TH1* histogram_ttH_density = 0;
  if ( histogram_ttH ) {
    if ( histogram_data ) checkCompatibleBinning(histogram_ttH, histogram_data);
    histogram_ttH_density = divideHistogramByBinWidth(histogram_ttH);
  }
  histogram_ttH_density->SetFillColor(628);
  histogram_ttH_density->SetLineColor(1);
  histogram_ttH_density->SetLineWidth(1);

  TH1* histogram_ttZ_density = 0;
  if ( histogram_ttZ ) {
    if ( histogram_data ) checkCompatibleBinning(histogram_ttZ, histogram_data);
    histogram_ttZ_density = divideHistogramByBinWidth(histogram_ttZ);
  }
  histogram_ttZ_density->SetFillColor(822);
  histogram_ttZ_density->SetLineColor(1);
  histogram_ttZ_density->SetLineWidth(1);

  TH1* histogram_ttW_density = 0;
  if ( histogram_ttW ) {
    if ( histogram_data ) checkCompatibleBinning(histogram_ttW, histogram_data);
    histogram_ttW_density = divideHistogramByBinWidth(histogram_ttW);
  }
  histogram_ttW_density->SetFillColor(823);
  histogram_ttW_density->SetLineColor(1);
  histogram_ttW_density->SetLineWidth(1);

  TH1* histogram_EWK_density = 0;
  if ( histogram_EWK ) {
    if ( histogram_data ) checkCompatibleBinning(histogram_EWK, histogram_data);
    histogram_EWK_density = divideHistogramByBinWidth(histogram_EWK);
  }
  histogram_EWK_density->SetFillColor(610);
  histogram_EWK_density->SetLineColor(1);
  histogram_EWK_density->SetLineWidth(1);

  TH1* histogram_Rares_density = 0;
  if ( histogram_Rares ) {
    if ( histogram_data ) checkCompatibleBinning(histogram_Rares, histogram_data);
    histogram_Rares_density = divideHistogramByBinWidth(histogram_Rares);
  }
  histogram_Rares_density->SetFillColor(851);
  histogram_Rares_density->SetLineColor(1);
  histogram_Rares_density->SetLineWidth(1);

  TH1* histogram_fakes_density = 0;
  if ( histogram_fakes ) {
    if ( histogram_data ) checkCompatibleBinning(histogram_fakes, histogram_data);
    histogram_fakes_density = divideHistogramByBinWidth(histogram_fakes);
  }
  histogram_fakes_density->SetFillColor(1);
  histogram_fakes_density->SetFillStyle(3005);
  histogram_fakes_density->SetLineColor(1);
  histogram_fakes_density->SetLineWidth(1);
  
  TH1* histogramSum_mc_density = 0;
  if ( histogramSum_mc ) {
    if ( histogram_data ) checkCompatibleBinning(histogramSum_mc, histogram_data);
    histogramSum_mc_density = divideHistogramByBinWidth(histogramSum_mc);
  }
  std::cout << "histogramSum_mc_density = " << histogramSum_mc_density << std::endl;
  dumpHistogram(histogramSum_mc_density);

  TH1* histogramErr_mc_density = 0;
  if ( histogramErr_mc ) {
    if ( histogram_data ) checkCompatibleBinning(histogramErr_mc, histogram_data);
    histogramErr_mc_density = divideHistogramByBinWidth(histogramErr_mc);
  }
  setStyle_uncertainty(histogramErr_mc_density);

  TCanvas* canvas = new TCanvas("canvas", "canvas", 950, 1100);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);
  canvas->Draw();

  TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.34, 1.00, 0.995);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.065);
  topPad->SetLeftMargin(0.20);
  topPad->SetBottomMargin(0.00);
  topPad->SetRightMargin(0.04);
  topPad->SetLogy(useLogScale);
  
  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.01, 1.00, 0.335);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.085);
  bottomPad->SetLeftMargin(0.20);
  bottomPad->SetBottomMargin(0.35);
  bottomPad->SetRightMargin(0.04);
  bottomPad->SetLogy(false);

  canvas->cd();
  topPad->Draw();
  topPad->cd();

  THStack* histogramStack_mc = new THStack();
  histogramStack_mc->Add(histogram_fakes_density);
  histogramStack_mc->Add(histogram_Rares_density);
  histogramStack_mc->Add(histogram_EWK_density);
  histogramStack_mc->Add(histogram_ttW_density);
  histogramStack_mc->Add(histogram_ttZ_density);
  histogramStack_mc->Add(histogram_ttH_density);

  TH1* histogram_ref = histogram_data_density;
  histogram_ref->SetTitle("");
  histogram_ref->SetStats(false);
  histogram_ref->SetMaximum(yMax);
  histogram_ref->SetMinimum(yMin);

  TAxis* xAxis_top = histogram_ref->GetXaxis();
  assert(xAxis_top);
  if ( xAxisTitle != "" ) xAxis_top->SetTitle(xAxisTitle.data());
  xAxis_top->SetTitleOffset(1.20);
  xAxis_top->SetLabelColor(10);
  xAxis_top->SetTitleColor(10);

  TAxis* yAxis_top = histogram_ref->GetYaxis();
  assert(yAxis_top);
  if ( yAxisTitle != "" ) yAxis_top->SetTitle(yAxisTitle.data());
  yAxis_top->SetTitleOffset(1.20);
  yAxis_top->SetTitleSize(0.080);
  yAxis_top->SetLabelSize(0.065);
  yAxis_top->SetTickLength(0.04);  

  histogram_ref->Draw("axis");

  // CV: calling THStack::Draw() causes segmentation violation ?!
  //histogramStack_mc->Draw("histsame");

  // CV: draw histograms without using THStack instead;
  //     note that order in which histograms need to be drawn needs to be reversed 
  //     compared to order in which histograms were added to THStack !!
  histogram_ttH_density->Add(histogram_ttZ_density);
  histogram_ttH_density->Add(histogram_ttW_density);
  histogram_ttH_density->Add(histogram_EWK_density);
  histogram_ttH_density->Add(histogram_Rares_density);
  histogram_ttH_density->Add(histogram_fakes_density);
  histogram_ttH_density->Draw("histsame");
  std::cout << "histogram_ttH_density = " << histogram_ttH_density << ":" << std::endl;
  dumpHistogram(histogram_ttH_density);

  histogram_ttZ_density->Add(histogram_ttW_density);
  histogram_ttZ_density->Add(histogram_EWK_density);
  histogram_ttZ_density->Add(histogram_Rares_density);
  histogram_ttZ_density->Add(histogram_fakes_density);
  histogram_ttZ_density->Draw("histsame");

  histogram_ttW_density->Add(histogram_EWK_density);
  histogram_ttW_density->Add(histogram_Rares_density);
  histogram_ttW_density->Add(histogram_fakes_density);
  histogram_ttW_density->Draw("histsame");

  histogram_EWK_density->Add(histogram_Rares_density);
  histogram_EWK_density->Add(histogram_fakes_density);
  histogram_EWK_density->Draw("histsame");

  histogram_Rares_density->Add(histogram_fakes_density);
  histogram_Rares_density->Draw("histsame");

  TH1* histogram_fakes_density_cloned = (TH1*)histogram_fakes_density->Clone();
  histogram_fakes_density_cloned->SetFillColor(10);
  histogram_fakes_density_cloned->SetFillStyle(1001);
  histogram_fakes_density_cloned->Draw("histsame");
  histogram_fakes_density->Draw("histsame");

  if ( histogramErr_mc_density ) {    
    histogramErr_mc_density->Draw("e2same");
  }
  
  if ( !doKeepBlinded ) {
    histogram_data_density->Draw("e1psame");
  }

  histogram_ref->Draw("axissame");

  double legend_y0 = 0.6950;
  if ( showLegend ) {
    TLegend* legend1 = new TLegend(0.2600, legend_y0, 0.5350, 0.9250, NULL, "brNDC");
    legend1->SetFillStyle(0);
    legend1->SetBorderSize(0);
    legend1->SetFillColor(10);
    legend1->SetTextSize(0.050);    
    TH1* histogram_data_forLegend = (TH1*)histogram_data_density->Clone();
    histogram_data_forLegend->SetMarkerSize(2);
    legend1->AddEntry(histogram_data_forLegend, "Observed", "p");
    legend1->AddEntry(histogram_ttH_density, "t#bar{t}H", "f");
    legend1->AddEntry(histogram_ttZ_density, "t#bar{t}Z", "f");
    legend1->AddEntry(histogram_ttW_density, "t#bar{t}W", "f");
    legend1->Draw();
    TLegend* legend2 = new TLegend(0.6600, legend_y0, 0.9350, 0.9250, NULL, "brNDC");
    legend2->SetFillStyle(0);
    legend2->SetBorderSize(0);
    legend2->SetFillColor(10);
        legend2->SetTextSize(0.050); 
    legend2->AddEntry(histogram_EWK_density, "Electroweak", "f");
    legend2->AddEntry(histogram_Rares_density, "Rares", "f");
    legend2->AddEntry(histogram_fakes_density, "Fakes", "f");    
    if ( histogramErr_mc ) legend2->AddEntry(histogramErr_mc_density, "Uncertainty", "f");
    legend2->Draw();
  }

  //addLabel_CMS_luminosity(0.2100, 0.9700, 0.6350);
  addLabel_CMS_preliminary(0.2100, 0.9700, 0.6350);

  TPaveText* label_category = 0;
  if ( showLegend ) label_category = new TPaveText(0.6600, legend_y0 - 0.0550, 0.9350, legend_y0, "NDC");
  else label_category = new TPaveText(0.2350, 0.8500, 0.5150, 0.9100, "NDC");
  label_category->SetTextAlign(13);
  label_category->AddText(label.data());
  label_category->SetTextSize(0.055);
  label_category->SetTextColor(1);
  label_category->SetFillStyle(0);
  label_category->SetBorderSize(0);
  label_category->Draw();

  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();
 
  TH1* histogramRatio = (TH1*)histogram_data_density->Clone("histogramRatio");
  if ( !histogramRatio->GetSumw2N() ) histogramRatio->Sumw2();
  histogramRatio->SetTitle("");
  histogramRatio->SetStats(false);
  histogramRatio->SetMinimum(-0.99);
  histogramRatio->SetMaximum(+0.99);
  histogramRatio->SetMarkerColor(histogram_data_density->GetMarkerColor());
  histogramRatio->SetMarkerStyle(histogram_data_density->GetMarkerStyle());
  histogramRatio->SetMarkerSize(histogram_data_density->GetMarkerSize());
  histogramRatio->SetLineColor(histogram_data_density->GetLineColor());

  TH1* histogramRatioUncertainty = (TH1*)histogram_data_density->Clone("histogramRatioUncertainty");
  if ( !histogramRatioUncertainty->GetSumw2N() ) histogramRatioUncertainty->Sumw2();
  histogramRatioUncertainty->SetMarkerColor(10);
  histogramRatioUncertainty->SetMarkerSize(0);
  setStyle_uncertainty(histogramRatioUncertainty);

  int numBins_bottom = histogramRatio->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins_bottom; ++iBin ) {
    double binContent_data = histogram_data_density->GetBinContent(iBin);
    double binError_data = histogram_data_density->GetBinError(iBin);
    double binContent_mc = 0;
    double binError_mc = 0;
    if ( histogramSum_mc && histogramErr_mc ) {
      binContent_mc = histogramSum_mc_density->GetBinContent(iBin);
      binError_mc = histogramErr_mc_density->GetBinError(iBin);
    } else {
      TList* histograms = histogramStack_mc->GetHists();
      TIter nextHistogram(histograms);
      double binError2_mc = 0.;
      while ( TH1* histogram_density = dynamic_cast<TH1*>(nextHistogram()) ) {
        binContent_mc += histogram_density->GetBinContent(iBin);
        binError2_mc += square(histogram_density->GetBinError(iBin));
      }
      binError_mc = TMath::Sqrt(binError2_mc);
    }
    if ( binContent_mc > 0. ) {
      histogramRatio->SetBinContent(iBin, binContent_data/binContent_mc - 1.0);
      histogramRatio->SetBinError(iBin, binError_data/binContent_mc);

      histogramRatioUncertainty->SetBinContent(iBin, 0.);
      histogramRatioUncertainty->SetBinError(iBin, binError_mc/binContent_mc);
    }
  }
  std::cout << "histogramRatio = " << histogramRatio << std::endl;
  dumpHistogram(histogramRatio);
  std::cout << "histogramRatioUncertainty = " << histogramRatioUncertainty << std::endl;
  dumpHistogram(histogramRatioUncertainty);

  TAxis* xAxis_bottom = histogramRatio->GetXaxis();
  assert(xAxis_bottom);
  xAxis_bottom->SetTitle(xAxis_top->GetTitle());
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleOffset(1.05);
  xAxis_bottom->SetTitleSize(0.16);
  xAxis_bottom->SetTitleFont(xAxis_top->GetTitleFont());
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.12);
  xAxis_bottom->SetTickLength(0.065);
  xAxis_bottom->SetNdivisions(505);

  TAxis* yAxis_bottom = histogramRatio->GetYaxis();
  assert(yAxis_bottom);
  yAxis_bottom->SetTitle("#frac{Data - Expectation}{Expectation}");
  yAxis_bottom->SetLabelColor(1);
  yAxis_bottom->SetTitleColor(1);
  yAxis_bottom->SetTitleOffset(0.95);
  yAxis_bottom->SetTitleFont(yAxis_top->GetTitleFont());
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.095);
  yAxis_bottom->SetLabelSize(0.110);
  yAxis_bottom->SetTickLength(0.04);  

  histogramRatio->Draw("axis");

  TF1* line = new TF1("line","0", xAxis_bottom->GetXmin(), xAxis_bottom->GetXmax());
  line->SetLineStyle(3);
  line->SetLineWidth(1.5);
  line->SetLineColor(kBlack);
  line->Draw("same");

  histogramRatioUncertainty->Draw("e2same"); 

  if ( !doKeepBlinded ) {
    histogramRatio->Draw("epsame");
  }

  histogramRatio->Draw("axissame");

  canvas->Update();

  size_t idx = outputFileName.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName, 0, idx);
  if ( useLogScale ) outputFileName_plot.append("_log");
  else outputFileName_plot.append("_linear");
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());

  //delete label_cms;
  delete topPad;
  delete label_category;
  delete histogramRatio;
  delete histogramRatioUncertainty;
  delete line;
  delete bottomPad;    
  delete canvas;
}