Esempio n. 1
0
	void CreateDrawAndSaveHistogram(TH2* &histo, TString outputdir, TString outputname, bool saveoutput, bool close){

				/** @brief  saves Histogramm as *.root and *.png and if wanted closes the histograms at the end
				*	@details This mehtod create a histogramm and save it as root and png file. If you choose close, the canvas is closed after the histogram was saved
				*/

				setPandaStyle();

				TString name = TString(histo->GetName());
				TString title = TString(histo->GetTitle());


				TCanvas * canvas = new TCanvas("c_"+name, title, 0,0,1500,1000);

				histo->Draw("COLZ");

				PandaSmartLabel("L");


				if (saveoutput){
					canvas->Print(outputdir + "root-files/" + outputname + ".root");
					canvas->Print(outputdir + "png-files/" + outputname + ".png");
					canvas->Print(outputdir + "pdf-files/" + outputname + ".pdf");
				}

				if (close) canvas->Close();


			}
Esempio n. 2
0
	void CreateDrawAndSaveHistogramBreitWignerFit(TH1* &histo, TString outputdir, TString outputname, bool saveoutput, bool close, double range=1){
		setPandaStyle();

		TString name = TString(histo->GetName());
		TString title = TString(histo->GetTitle());

		TCanvas * canvas = new TCanvas("c_"+name, title, 0,0,1500,1000);
		histo->Draw();

//		canvas->Update();

		TF1 * bw;

		bw = GetVoigtFit(histo, range);

		bw->SetLineColor(kRed);
		bw->SetLineStyle(7);
		bw->SetLineWidth(3);
		bw->Draw("SAME");

		PandaSmartLabel("L");

		if (saveoutput){
			canvas->Print(outputdir + "root-files/" + outputname + ".root");
			canvas->Print(outputdir + "png-files/" + outputname + ".png");
			canvas->Print(outputdir + "pdf-files/" + outputname + ".pdf");
		}

		if (close) canvas->Close();

	}
//------------------------------------------------------------------------------
void PlotAlignmentValidation::plotHitMaps()
{
  
  setNiceStyle(); 
  //gStyle->SetOptStat(0);
  
  TCanvas *c = new TCanvas("c", "c", 1200,400);
  setCanvasStyle( *c );
  c->Divide(3,1);
  //ps->NewPage();

  //-------------------------------------------------
  //plot Hit map
  //-------------------------------------------------
  std::string histName_="Entriesprofile";
  c->cd(1);
  TTree *tree= (*sourceList.begin())->getTree();
  tree->Draw("entries:posR:posZ","","COLZ2Prof");
  c->cd(2);
  tree->Draw("entries:posY:posX","","COLZ2Prof");
  c->cd(3);
  tree->Draw("entries:posR:posPhi","","COLZ2Prof");
  
  char PlotName[1000];
  sprintf( PlotName, "%s/%s.eps", outputDir.c_str(), histName_.c_str() );
  
  c->Print(PlotName);
  //   //c->Update();
  c->Close();  
  //----------------------------------------------------
  
}
Esempio n. 4
0
void myana::WriteHistos()
{

                TFile *myfirstanalysis = new TFile("myfirstanalysis.root", "RECREATE");
                TCanvas *cnvPlots = new TCanvas();

                trigJT015y1->Write();
                trigJT025y1->Write();
                trigJT045y1->Write();
                trigJT065y1->Write();
                trigJT095y1->Write();
                trigJT125y1->Write();
               
                trigJT015y2->Write();
                trigJT025y2->Write();
                trigJT045y2->Write();
                trigJT065y2->Write();
                trigJT095y2->Write();
                trigJT125y2->Write();

                trigJT015y3->Write();
                trigJT025y3->Write();
                trigJT045y3->Write();
                trigJT065y3->Write();
                trigJT095y3->Write();
                trigJT125y3->Write();

		cnvPlots->Close();
		myfirstanalysis->Close();
		delete cnvPlots;
		delete myfirstanalysis;
}
Esempio n. 5
0
	void CreateDrawAndSaveHistogramFWHM(TH1* &histo, TString outputdir, TString outputname, bool saveoutput, bool close, bool log=false){

		/** @brief  saves Histogramm as *.root and *.png and if wanted closes the histograms at the end
		*	@details This mehtod create a histogramm and save it as root and png file. If you choose close, the canvas is closed after the histogram was saved
		*/

		setPandaStyle();

//		gStyle->SetOptStat(1111);
		TString name = TString(histo->GetName());
		TString title = TString(histo->GetTitle());



		TCanvas * canvas = new TCanvas("c_"+name, title, 0,0,1500,1000);


		histo->Draw();

		//***** FWHM ******

		double max = histo->GetMaximum();

		int bin1 = histo->FindFirstBinAbove(max/2);
		int bin2 = histo->FindLastBinAbove(max/2);

		double lowerbin =  histo->GetBinCenter(bin1);
		double upperbin = histo->GetBinCenter(bin2) ;

		double FWHM =  upperbin - lowerbin;


		TPaveText * text = new TPaveText(0.2,1500,1,3500);
		TString name = TString::Format("FWHM  %.4f", FWHM);
		text->InsertText(name);
		text->SetFillColor(kWhite);
		text->SetTextFont(4);
		text->SetTextSize(30);
		text->SetTextAlign(12);
		text->Draw("SAME");

		if(log) canvas->SetLogy();

		PandaSmartLabel("L");


		if (saveoutput){
			canvas->Print(outputdir + "root-files/" + outputname + ".root");
			canvas->Print(outputdir + "png-files/" + outputname + ".png");
			canvas->Print(outputdir + "pdf-files/" + outputname + ".pdf");
		}

		if (close) canvas->Close();


	}
bool plot_nhists(vector<TH1F*> histo, TString epsname, TString* type)
{

  set_style();

  TCanvas* can = new TCanvas("can", "can", 600, 600); 
  can->cd();

  can->Print(epsname+"[");
  can->SetLogy();
  
  TLegend * legend = new TLegend(0.7,0.8,.92,0.99);
  legend->SetTextFont(72);
  legend->SetTextSize(0.04);
  legend->SetFillColor(kWhite);
  
  TString  histo_titel = histo[0]->GetTitle();
  int b =0;

  for(unsigned int i = 0; i<histo.size(); ++i){ 
    if(histo_titel==histo[i]->GetTitle()){
      histo[i]->SetMaximum(histo[i]->GetMaximum()<1 ? 1.2 : 1.4*histo[i]->GetMaximum());
      histo[i]->Draw("same");
      histo[i]->SetLineColor(b+2);
      legend->AddEntry(histo[i],type[b]);
      b+=1;
    }
    else{
      
      legend->Draw();
      can->Print(epsname);
      legend->Clear();
      b=0;
      histo[i]->SetMaximum(histo[i]->GetMaximum()<1 ? 1.2 : 1.4*histo[i]->GetMaximum());
      histo[i]->Draw();
      histo[i]->SetLineColor(b+2);
      legend->AddEntry(histo[i],type[b]);
      b+=1;
      histo_titel=histo[i]->GetTitle();
    }
  }

  legend->Draw();
  can->Print(epsname);

  can->Print(epsname+"]");
  can->Close();
  
  return true;


}
void KVSpiderIdentificator::SaveAsPdf(Option_t* opt_, const Char_t* path_)
{
   Draw(opt_);
   TCanvas* cc = (TCanvas*) gROOT->FindObject(_htot->GetName());
   _htot->RebinX(4);
   _htot->RebinY(4);

   CheckPath(path_);

   cc->Print(Form("%s/%s.pdf", path_, cc->GetName()), "pdf");
   cc->Close();
   delete cc;
}
int RampCorrellation_single(std::string file_name, TGraphErrors &graph, TGraphErrors &graph2, vector<double> &vec_errors)
{

	TTree *t = new TTree();
	const std::string file_path = "/home/jlab/github/MagCloak_Analysis/calibration/data-calib/DATA_MegaVIEW/";
//	std::string file_name = "DataFile_2016-12-08_06-59-11.csv";
	std::string file = file_path+file_name;

	t->ReadFile(file.c_str());
//	t->Print();

	TCanvas *c = new TCanvas();
	t->Draw("TMath::Abs(B1/B2):time");
	TGraph *gh = (TGraph*)c->GetListOfPrimitives()->FindObject("Graph");
	double ratio_mean = gh->GetMean(2);
	double ratio_std = gh->GetRMS(2);

	t->Draw("Bnom:time");
	TGraph *gh1 = (TGraph*)c->GetListOfPrimitives()->FindObject("Graph");
	double nom_mean = gh1->GetMean(2);
	double nom_std = 0;

//	cout << "At " << nom_mean << " mT, B1/B2 is: " << ratio_mean << " +/- " << ratio_std << endl;
	
	c->Close();

	int n = graph.GetN();
	graph.SetPoint(n,nom_mean,ratio_mean);
	graph.SetPointError(n,nom_std,ratio_std);

//-------------------------------------------------------------------------------

	TCanvas *c2 = new TCanvas();
	t->Draw("B3:time");
	TGraph *gh2 = (TGraph*)c2->GetListOfPrimitives()->FindObject("Graph");
	double B3_mean = -1*(gh2->GetMean(2));
	double B3_std = gh2->GetRMS(2);
	
	int n2 = graph2.GetN();
	graph2.SetPoint(n2, nom_mean, B3_mean);
	graph2.SetPointError(n2, nom_std, B3_std);
	
	c2->Close();

	if(nom_mean < 500) vec_errors.push_back(B3_std);

	return 0;
}
TH1D *plotIso(TTree *tSig,TString var,TString weight, TString etcut, TString htcut, TString njetcut, TString ph, TString bin,Double_t xmax, Int_t icol)
{
  TCut etcut20=weight+" * ("+etcut+htcut+" && "+njetcut+")";

  TCut conv1=weight+" * ("+etcut+htcut+" &&"+njetcut+" && mHits<=1)";
  TCut conv2=weight+" * ("+etcut+htcut+" && "+njetcut+"&& mHits<=1)";
  TCut conv3=weight+" * ("+etcut+htcut+" && "+njetcut+"&& mHits<=1 && (dcot>0.02 || dcot<-0.02 || dist>0.02 || dist<-0.02))";
  
  TCanvas *c = getaCanvas(ph+var+etcut+htcut+"hsqrti");

  tSig->Draw(var+">>hsqrti"+bin,conv3);
  TH1D *hsqrt = (TH1D*)gDirectory->Get("hsqrti");
  hsqrt->SetName(ph+var+htcut+"hsqrti");

  hsqrt->SetLineColor(icol);
  hsqrt->SetLineWidth(3);
  c->Close();
  return hsqrt;
}
Esempio n. 10
0
	  void CreateDrawAndSaveNHistograms(TH1* &h1, TH1* &h2, TH1* &h3, TString leg1="", TString leg2="", TString leg3="", TString outputdir, TString outputname, bool saveoutput, bool close,bool prelim=false){
	  // should be added to common_jenny.cpp

	  	/** @brief  saves 3 histograms in same file as *.root and *.png and if wanted closes the canvas at the end
	  	*	@details This mehtod create 3 histograms and save it as root and png file. If you choose close, the canvas is closed after the histograms are saved
	  	*/

		  setPandaStyle();

	  	TString name = TString(h1->GetName());
	  	TString title = TString(h1->GetTitle());

	  	h1->SetLineColor(kBlue);
	  	h2->SetLineColor(kRed);
	  	h3->SetLineColor(kBlack);

	  	TLegend * legend = new TLegend(0.7,0.62,0.86,0.795, "");
	  	legend->AddEntry(h1, leg1, "l");
	  	legend->AddEntry(h2, leg2, "l");
	  	legend->AddEntry(h3, leg3, "l");


	  	TCanvas * canvas = new TCanvas("c_"+name, title, 0,0,1500,1000);

	  	h1->Draw();
	  	h2->Draw("SAME");
	  	h3->Draw("SAME");
	  	legend->Draw();

	  	PandaSmartLabel("L");


	  	if (saveoutput){
	  		canvas->Print(outputdir + "root-files/" + outputname + ".root");
	  		canvas->Print(outputdir + "png-files/" + outputname + ".png");
			canvas->Print(outputdir + "pdf-files/" + outputname + ".pdf");
	  	}

	  	if (close) canvas->Close();

	  }
Esempio n. 11
0
void TMRCScanner::SuperImpose64ch(const char * what,const char * vs,int geoaddr)
{
	ffile = new TFile(foutfile);
	if (ffile->IsOpen()) {
		ftree = (TTree*) ffile->Get("T"); 
		ftree->SetMarkerStyle(23);
		
		char nomeout[256];
		TCanvas* mycanv = new TCanvas("mycanv");
		
		for (int ch=0; ch<64; ch++) {
			int channel = geoaddr*64+ch;
			/* Superimpose
			ftree->SetMarkerColor(ch%16); // modify! change color depending on channel something like (ch_id%8)==0
			ftree->SetMarkerStyle((ch%8)+20);
			if (ch==0) {
				ftree->Draw(Form("RatioHITADC[%d]:DAC",channel));
			}else {
				ftree->Draw(Form("RatioHITADC[%d]:DAC",channel),"","SAME");
			}
			*/
			/* Print on File (.eps)*/
			ftree->Draw(Form("%s[%d]:%s",what,channel,vs));
			sprintf(nomeout,"%s%s_%s_CH%d.eps",foutfile,what,vs,channel); 
			mycanv->Print(nomeout);
			
		}
		mycanv->Close();
		
	}else {
		printf("File %s not opened, first call OpenFile() \n",foutfile);
	}
	//ftree->Print();	
	delete ffile;

}
Esempio n. 12
0
void drawCtauMass2DPlot(RooWorkspace& myws,   // Local workspace
                        string outputDir,     // Output directory
                        struct KinCuts cut,   // Variable with current kinematic cuts
                        string plotLabel,     // The label used to define the output file name
                        // Select the type of datasets to fit
                        string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                        bool isPbPb,          // Define if it is PbPb (True) or PP (False)\
                        // Select the drawing options
                        map<string, double> binWidth={} // User-defined Location of the fit results
                        ) 
{

  gStyle->SetOptStat(0);

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  double minRangeCtau = -0.5;
  double maxRangeCtau = 2.0;
  int nBinsCtau = min(int( round((maxRangeCtau - minRangeCtau)/binWidth["CTAU"]*2) ), 1000);
  //  myws.var("ctau")->setBin(nBinsCtau, Binning(nBinsCtau, minRangeCtau, maxRangeCtau));

  double minRangeMass = cut.dMuon.M.Min;
  double maxRangeMass = cut.dMuon.M.Max;
  int nBinsMass = min(int( round((maxRangeMass - minRangeMass)/binWidth["MASS"]) ), 1000);
  //  myws.var("invMass")->setBin(nBinsCtau, Binning(nBinsCtau, minRangeCtau, maxRangeCtau));
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  TH1* hPDF = ((RooAbsReal*)myws.pdf(pdfTotName.c_str()))->createHistogram("PDF 2D",*myws.var("ctau"), Extended(kTRUE), Binning(nBinsCtau, minRangeCtau, maxRangeCtau), YVar(*myws.var("invMass"), Binning(nBinsMass, minRangeMass, maxRangeMass)));

  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  TH1* hDATA = ((RooDataSet*)myws.data(dsOSName.c_str()))->createHistogram("DATA 2D",*myws.var("ctau"), Binning(nBinsCtau, minRangeCtau, maxRangeCtau), YVar(*myws.var("invMass"), Binning(nBinsMass, minRangeMass, maxRangeMass)));
  
  // Create the main canvas
  TCanvas *cFigPDF   = new TCanvas(Form("cCtauMassPDF_%s", (isPbPb?"PbPb":"PP")), "cCtauMassPDF",2000,2000);
  cFigPDF->cd();

  hPDF->GetYaxis()->CenterTitle(kTRUE);
  hPDF->GetYaxis()->SetTitleOffset(2.1);
  hPDF->GetYaxis()->SetTitleSize(0.035);
  hPDF->GetYaxis()->SetLabelSize(0.025);
  hPDF->GetYaxis()->SetTitle("Mass [GeV/c]");
  hPDF->GetXaxis()->CenterTitle(kTRUE);
  hPDF->GetXaxis()->SetTitleOffset(2.1);
  hPDF->GetXaxis()->SetTitleSize(0.035);
  hPDF->GetXaxis()->SetLabelSize(0.025);
  hPDF->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  hPDF->GetZaxis()->SetTitleOffset(2.0);
  hPDF->GetZaxis()->SetTitleSize(0.035);
  hPDF->GetZaxis()->SetLabelSize(0.025);
  hPDF->GetYaxis()->SetRangeUser(minRangeMass, maxRangeMass);
  hPDF->GetXaxis()->SetRangeUser(minRangeCtau, maxRangeCtau);
  cFigPDF->SetLogz(kTRUE);

  hPDF->Draw("LEGO2");

  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf2D/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFigPDF->SaveAs(Form("%sctauMass/%s/plot/pdf2D/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAUMASSPDF", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));

  cFigPDF->Clear();
  cFigPDF->Close();

  // Create the main canvas
  TCanvas *cFigDATA   = new TCanvas(Form("cCtauMassPDF_%s", (isPbPb?"PbPb":"PP")), "cCtauMassPDF",2000,2000);
  cFigDATA->cd();

  hDATA->GetYaxis()->CenterTitle(kTRUE);
  hDATA->GetYaxis()->SetTitleOffset(2.1);
  hDATA->GetYaxis()->SetTitleSize(0.035);
  hDATA->GetYaxis()->SetLabelSize(0.025);
  hDATA->GetYaxis()->SetTitle("Mass [GeV/c]");
  hDATA->GetXaxis()->CenterTitle(kTRUE);
  hDATA->GetXaxis()->SetTitleOffset(2.1);
  hDATA->GetXaxis()->SetTitleSize(0.035);
  hDATA->GetXaxis()->SetLabelSize(0.025);
  hDATA->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  hDATA->GetZaxis()->SetTitleOffset(2.0);
  hDATA->GetZaxis()->SetTitleSize(0.035);
  hDATA->GetZaxis()->SetLabelSize(0.025);
  hDATA->GetYaxis()->SetRangeUser(minRangeMass, maxRangeMass);
  hDATA->GetXaxis()->SetRangeUser(minRangeCtau, maxRangeCtau);
  cFigDATA->SetLogz(kTRUE);

  hDATA->Draw("LEGO2");

  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf2D/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFigDATA->SaveAs(Form("%sctauMass/%s/plot/pdf2D/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAUMASSDATA", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));

  cFigDATA->Clear();
  cFigDATA->Close();
  
  delete hPDF;
  delete hDATA;

};
void drawSpectra2D(const TString configFile, const TString inputFile, const TString outputFile, const TString outputFigureName)
{
    std::cout<<"running drawSpectra2D()"<<std::endl;
    std::cout<<"configFile  = "<< configFile.Data() <<std::endl;
    std::cout<<"inputFile   = "<< inputFile.Data()  <<std::endl;
    std::cout<<"outputFile  = "<< outputFile.Data() <<std::endl;

    InputConfiguration configInput = InputConfigurationParser::Parse(configFile.Data());
    CutConfiguration configCuts = CutConfigurationParser::Parse(configFile.Data());

    if (!configInput.isValid) {
        std::cout << "Input configuration is invalid." << std::endl;
        std::cout << "exiting" << std::endl;
        return;
    }
    if (!configCuts.isValid) {
        std::cout << "Cut configuration is invalid." << std::endl;
        std::cout << "exiting" << std::endl;
        return;
    }

    /*
     * drawing behavior :
     *      1. If N = # formulas and N = # selections, then N histograms will be drawn,
     *      2. If 1 = # formulas and N = # selections, then N histograms will be drawn with the same formula.
     *      3. If N = # formulas and 1 = # selections, then N histograms will be drawn with the same selection.
     *      4. else, exit.
     */
    // input for mode
    int mode = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_mode];

    // input for TTree
    std::vector<std::string> treePaths = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treePath]);
    std::vector<std::string> treeFriendsPath = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeFriendPath]);
    std::vector<std::string> treeFriendsPathIndividual = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeFriendPathIndividual]);
    std::vector<std::string> formulas = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeFormula]);
    std::string selectionBase = configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeSelectionBase];
    std::vector<std::string> selections = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeSelection]);
    std::vector<std::string> selectionSplitter = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeSelectionSplitter]);
    std::vector<std::string> weights = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_weight]);

    // input for TH1
    std::vector<std::string> titles = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_title]));
    std::vector<std::string> titlesX = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_titleX]));
    std::vector<std::string> titlesY = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_titleY]));
    // nBinsx, xLow, xUp, nBinsy, yLow, yUp for a TH2D histogram
    std::vector<std::vector<float>> TH2D_Bins_List = ConfigurationParser::ParseListTH2D_Bins(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH2D_Bins_List]);
    float titleOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_titleOffsetX];
    float titleOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_titleOffsetY];
    float markerSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_markerSize];
    int drawNormalized = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_drawNormalized];
    std::vector<std::string> drawOptions = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_drawOption]);
    std::vector<std::string> markerStyles = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_markerStyle]);
    std::vector<std::string> lineStyles = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_lineStyle]);
    std::vector<std::string> fillStyles = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_fillStyle]);
    std::vector<std::string> colors = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_color]);
    std::vector<std::string> fillColors = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_fillColor]);
    std::vector<std::string> lineColors = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_lineColor]);
    int lineWidth = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_lineWidth];

    // input for TLegend
    std::vector<std::string> legendEntryLabels = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_legendEntryLabel]));
    std::string legendPosition = configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_legendPosition];
    float legendOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendOffsetX];
    float legendOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendOffsetY];
    int legendBorderSize = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_legendBorderSize];
    float legendWidth = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendWidth];
    float legendHeight = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendHeight];
    float legendTextSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendTextSize];

    // input for text objects
    std::string tmpText = ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_text]);
    std::vector<std::string> textLines = ConfigurationParser::ParseList(tmpText);
    int textFont = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_textFont];
    float textSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textSize];
    std::string textPosition = configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_textPosition];
    float textOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textOffsetX];
    float textOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textOffsetY];

    std::string tmpTextOverPad = ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_textAbovePad]);
    std::vector<std::string> textsOverPad = ConfigurationParser::ParseList(tmpTextOverPad);
    std::vector<std::string> textsOverPadAlignments = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_textAbovePadAlign]);
    int textAbovePadFont = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_textAbovePadFont];
    float textAbovePadSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textAbovePadSize];
    float textAbovePadOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textAbovePadOffsetX];
    float textAbovePadOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textAbovePadOffsetY];

    // input for TLine
    // y-axis positions of the horizontal lines to be drawn
    std::vector<float> TLines_horizontal = ConfigurationParser::ParseListFloat(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TLine_horizontal]);
    std::vector<std::string> lineStyles_horizontal = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_LineStyle_horizontal]);
    // x-axis positions of the vertical lines to be drawn
    std::vector<float> TLines_vertical = ConfigurationParser::ParseListFloat(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TLine_vertical]);
    std::vector<std::string> lineStyles_vertical = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_LineStyle_vertical]);

    // input for TCanvas
    int windowWidth = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_windowWidth];
    int windowHeight = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_windowHeight];
    float leftMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_leftMargin];
    float rightMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_rightMargin];
    float bottomMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_bottomMargin];
    float topMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_topMargin];
    int setLogx = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_setLogx];
    int setLogy = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_setLogy];
    int setLogz = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_setLogz];

    // set default values
    if (selections.size() == 0) selections.push_back("1");
    if (weights.size() == 0)    weights.push_back(INPUT_DEFAULT::TH1_weight.c_str());   // default weight = 1.
    if (titleOffsetX == 0) titleOffsetX = INPUT_DEFAULT::titleOffsetX;
    if (titleOffsetY == 0) titleOffsetY = INPUT_DEFAULT::titleOffsetY;
    if (drawNormalized >= INPUT_TH1::kN_TYPE_NORM) drawNormalized = INPUT_DEFAULT::drawNormalized;
    if (lineWidth == 0)  lineWidth = INPUT_DEFAULT::lineWidth;

    if (markerSize == 0)  markerSize = INPUT_DEFAULT::markerSize;

    if (textFont == 0)  textFont = INPUT_DEFAULT::textFont;
    if (textSize == 0)  textSize = INPUT_DEFAULT::textSize;

    if (windowWidth  == 0)  windowWidth = INPUT_DEFAULT::windowWidth;
    if (windowHeight == 0)  windowHeight = INPUT_DEFAULT::windowHeight;
    if (leftMargin == 0) leftMargin = INPUT_DEFAULT::leftMargin;
    if (rightMargin == 0) rightMargin = INPUT_DEFAULT::rightMargin;
    if (bottomMargin == 0) bottomMargin = INPUT_DEFAULT::bottomMargin;
    if (topMargin == 0) topMargin = INPUT_DEFAULT::topMargin;

    int nTrees = treePaths.size();
    int nFriends = treeFriendsPath.size();
    int nFriendsIndividual = treeFriendsPathIndividual.size();
    int nFormulas = formulas.size();
    int nSelections = selections.size();
    int nSelectionSplitter = selectionSplitter.size();
    int nWeights = weights.size();
    int nTitles = titles.size();
    int nTitlesX = titlesX.size();
    int nTitlesY = titlesY.size();
    int nTH2D_Bins_List = TH2D_Bins_List[0].size();
    int nDrawOptions = drawOptions.size();
    int nMarkerStyles = markerStyles.size();
    int nLineStyles = lineStyles.size();
    int nFillStyles = fillStyles.size();
    int nColors = colors.size();
    int nFillColors = fillColors.size();
    int nLineColors = lineColors.size();
    int nLegendEntryLabels = legendEntryLabels.size();
    int nTextLines = textLines.size();
    int nTextsOverPad = textsOverPad.size();
    int nTextsOverPadAlignments = textsOverPadAlignments.size();
    int nTLines_horizontal = TLines_horizontal.size();
    int nLineStyles_horizontal = lineStyles_horizontal.size();
    int nTLines_vertical = TLines_vertical.size();
    int nLineStyles_vertical = lineStyles_vertical.size();

    // verbose about input configuration
    std::cout<<"Input Configuration :"<<std::endl;
    std::cout << "mode = " << mode << std::endl;
    if (mode == INPUT_MODE::k_comparison) {
        // in comparison mode "inputFile" should have the following format
        // inputFile = <inputFile1>,<inputFile2>,...
        // there should be no single space between <inputFile1> and <inputFile2>.
        // the idea is to feed the input samples as a single argument and split them in the macro.
        std::cout << "comparison mode : Spectra from two input samples are going to be compared." << std::endl;
    }
    std::cout << "nTrees = " << nTrees << std::endl;
    for (int i=0; i<nTrees; ++i) {
        std::cout << Form("treePaths[%d] = %s", i, treePaths.at(i).c_str()) << std::endl;
    }
    std::cout << "nFriends = " << nFriends << std::endl;
    for (int i=0; i<nFriends; ++i) {
        std::cout << Form("treeFriendsPath[%d] = %s", i, treeFriendsPath.at(i).c_str()) << std::endl;
    }
    std::cout << "nFriendsIndividual = " << nFriendsIndividual << std::endl;
    for (int i=0; i<nFriendsIndividual; ++i) {
        std::cout << Form("treeFriendsPathIndividual[%d] = %s", i, treeFriendsPathIndividual.at(i).c_str()) << std::endl;
    }
    std::cout << "nFormulas     = " << nFormulas << std::endl;
    for (int i=0; i<nFormulas; ++i) {
        std::cout << Form("formulas[%d]   = %s", i, formulas.at(i).c_str()) << std::endl;
    }
    std::cout << "selectionBase = " << selectionBase.c_str() << std::endl;
    std::cout << "nSelections   = " << nSelections << std::endl;
    for (int i=0; i<nSelections; ++i) {
        std::cout << Form("selections[%d] = %s", i, selections.at(i).c_str()) << std::endl;
    }
    std::cout << "nSelectionSplitter = " << nSelectionSplitter << std::endl;
    for (int i=0; i<nSelectionSplitter; ++i) {
        std::cout << Form("selectionSplitter[%d] = %s", i, selectionSplitter.at(i).c_str()) << std::endl;
    }
    std::cout << "nWeights   = " << nWeights << std::endl;
    for (int i=0; i<nWeights; ++i) {
        std::cout << Form("weights[%d] = %s", i, weights.at(i).c_str()) << std::endl;
    }

    std::cout << "nTitles   = " << nTitles << std::endl;
    for (int i=0; i<nTitles; ++i) {
        std::cout << Form("titles[%d] = %s", i, titles.at(i).c_str()) << std::endl;
    }
    std::cout << "nTitlesX   = " << nTitlesX << std::endl;
    for (int i=0; i<nTitlesX; ++i) {
        std::cout << Form("titlesX[%d] = %s", i, titlesX.at(i).c_str()) << std::endl;
    }
    std::cout << "nTitlesY   = " << nTitlesY << std::endl;
    for (int i=0; i<nTitlesY; ++i) {
        std::cout << Form("titlesY[%d] = %s", i, titlesY.at(i).c_str()) << std::endl;
    }
    std::cout << "nTH2D_Bins_List = " << nTH2D_Bins_List << std::endl;
    for (int i=0; i<nTH2D_Bins_List; ++i) {
        std::cout << Form("TH2D_Bins_List[%d] = { ", i);
        std::cout << Form("%.0f, ", TH2D_Bins_List[0].at(i));
        std::cout << Form("%f, ", TH2D_Bins_List[1].at(i));
        std::cout << Form("%f }", TH2D_Bins_List[2].at(i));
        std::cout << " { ";
        std::cout << Form("%.0f, ", TH2D_Bins_List[3].at(i));
        std::cout << Form("%f, ", TH2D_Bins_List[4].at(i));
        std::cout << Form("%f }", TH2D_Bins_List[5].at(i)) << std::endl;;
    }
    std::cout << "titleOffsetX = " << titleOffsetX << std::endl;
    std::cout << "titleOffsetY = " << titleOffsetY << std::endl;
    std::cout << "markerSize = " << markerSize << std::endl;
    std::cout << "drawNormalized = " << drawNormalized << std::endl;
    std::cout << "nDrawOptions   = " << nDrawOptions << std::endl;
    for (int i = 0; i<nDrawOptions; ++i) {
        std::cout << Form("drawOptions[%d] = %s", i, drawOptions.at(i).c_str()) << std::endl;
    }
    std::cout << "nMarkerStyles  = " << nMarkerStyles << std::endl;
    for (int i = 0; i<nMarkerStyles; ++i) {
        std::cout << Form("markerStyles[%d] = %s", i, markerStyles.at(i).c_str()) << std::endl;
    }
    std::cout << "nLineStyles   = " << nLineStyles << std::endl;
    for (int i = 0; i<nLineStyles; ++i) {
        std::cout << Form("lineStyles[%d] = %s", i, lineStyles.at(i).c_str()) << std::endl;
    }
    std::cout << "nFillStyles   = " << nFillStyles << std::endl;
    for (int i = 0; i<nFillStyles; ++i) {
        std::cout << Form("fillStyles[%d] = %s", i, fillStyles.at(i).c_str()) << std::endl;
    }
    std::cout << "nColors   = " << nColors << std::endl;
    for (int i = 0; i<nColors; ++i) {
        std::cout << Form("colors[%d] = %s", i, colors.at(i).c_str()) << std::endl;
    }
    std::cout << "nFillColors = " << nFillColors << std::endl;
    for (int i = 0; i<nFillColors; ++i) {
        std::cout << Form("fillColors[%d] = %s", i, fillColors.at(i).c_str()) << std::endl;
    }
    std::cout << "nLineColors = " << nLineColors << std::endl;
    for (int i = 0; i<nLineColors; ++i) {
        std::cout << Form("lineColors[%d] = %s", i, lineColors.at(i).c_str()) << std::endl;
    }
    std::cout << "lineWidth = " << lineWidth << std::endl;

    std::cout << "nLegendEntryLabels   = " << nLegendEntryLabels << std::endl;
    for (int i = 0; i<nLegendEntryLabels; ++i) {
        std::cout << Form("legendEntryLabels[%d] = %s", i, legendEntryLabels.at(i).c_str()) << std::endl;
    }
    if (nLegendEntryLabels > 0) {
        std::cout << "legendPosition   = " << legendPosition.c_str() << std::endl;
        if (legendPosition.size() == 0) std::cout<< "No position is provided, legend will not be drawn." <<std::endl;
        std::cout << "legendOffsetX    = " << legendOffsetX << std::endl;
        std::cout << "legendOffsetY    = " << legendOffsetY << std::endl;
        std::cout << "legendBorderSize = " << legendBorderSize << std::endl;
        std::cout << "legendWidth      = " << legendWidth << std::endl;
        std::cout << "legendHeight     = " << legendHeight << std::endl;
        std::cout << "legendTextSize   = " << legendTextSize << std::endl;
    }

    std::cout << "nTextLines   = " << nTextLines << std::endl;
    for (int i = 0; i<nTextLines; ++i) {
        std::cout << Form("textLines[%d] = %s", i, textLines.at(i).c_str()) << std::endl;
    }
    if (nTextLines > 0) {
        std::cout << "textFont = " << textFont << std::endl;
        std::cout << "textSize = " << textSize << std::endl;
        std::cout << "textPosition = " << textPosition << std::endl;
        std::cout << "textOffsetX  = " << textOffsetX << std::endl;
        std::cout << "textOffsetY  = " << textOffsetY << std::endl;
    }

    std::cout << "nTextsOverPad = " << nTextsOverPad << std::endl;
    for (int i = 0; i<nTextsOverPad; ++i) {
        std::cout << Form("textsOverPad[%d] = %s", i, textsOverPad.at(i).c_str()) << std::endl;
    }
    if (nTextsOverPad > 0) {
        std::cout << "nTextsOverPadAlignments = " << nTextsOverPadAlignments << std::endl;
        for (int i = 0; i<nTextsOverPadAlignments; ++i) {
            std::cout << Form("textsOverPadAlignments[%d] = %s", i, textsOverPadAlignments.at(i).c_str()) << std::endl;
        }
        std::cout << "textAbovePadFont = " << textAbovePadFont << std::endl;
        std::cout << "textAbovePadSize = " << textAbovePadSize << std::endl;
        std::cout << "textAbovePadOffsetX  = " << textAbovePadOffsetX << std::endl;
        std::cout << "textAbovePadOffsetY  = " << textAbovePadOffsetY << std::endl;
    }

    std::cout << "nTLines_horizontal = " << nTLines_horizontal << std::endl;
    for (int i = 0; i<nTLines_horizontal; ++i) {
        std::cout << Form("TLines_horizontal[%d] = %f", i, TLines_horizontal.at(i)) << std::endl;
    }
    if (nTLines_horizontal > 0) {
        std::cout << "nLineStyles_horizontal = " << nLineStyles_horizontal << std::endl;
        for (int i = 0; i<nLineStyles_horizontal; ++i) {
            std::cout << Form("lineStyles_horizontal[%d] = %s", i, lineStyles_horizontal.at(i).c_str()) << std::endl;
        }
    }
    std::cout << "nTLines_vertical = " << nTLines_vertical << std::endl;
    for (int i = 0; i<nTLines_vertical; ++i) {
        std::cout << Form("TLines_vertical[%d] = %f", i, TLines_vertical.at(i)) << std::endl;
    }
    if (nTLines_vertical > 0) {
        std::cout << "nLineStyles_vertical = " << nLineStyles_vertical << std::endl;
        for (int i = 0; i<nLineStyles_vertical; ++i) {
            std::cout << Form("lineStyles_vertical[%d] = %s", i, lineStyles_vertical.at(i).c_str()) << std::endl;
        }
    }

    std::cout << "windowWidth = " << windowWidth << std::endl;
    std::cout << "windowHeight = " << windowHeight << std::endl;
    std::cout << "leftMargin   = " << leftMargin << std::endl;
    std::cout << "rightMargin  = " << rightMargin << std::endl;
    std::cout << "bottomMargin = " << bottomMargin << std::endl;
    std::cout << "topMargin    = " << topMargin << std::endl;
    std::cout << "setLogx = " << setLogx << std::endl;
    std::cout << "setLogy = " << setLogy << std::endl;
    std::cout << "setLogz = " << setLogz << std::endl;

    // cut configuration

    // verbose about cut configuration
    std::cout<<"Cut Configuration :"<<std::endl;

    std::cout<<"Input handling :"<< std::endl;

    std::vector<std::string> inputFileArguments = InputConfigurationParser::ParseFileArgument(inputFile.Data());
    int nInputFileArguments = inputFileArguments.size();
    // if no mode is specified (which is what happens most of the time), then it is expected that nInputFileArguments = 1.
    std::cout<<"nInputFileArguments (number of input file arguments) = "<< nInputFileArguments << std::endl;
    for (int i = 0; i < nInputFileArguments; ++i) {
        std::cout << Form("inputFileArguments[%d] = %s", i, inputFileArguments.at(i).c_str()) << std::endl;
    }

    std::vector<std::vector<std::string>> inputFiles(nInputFileArguments);
    std::cout<<"#####"<< std::endl;
    for (int i = 0; i < nInputFileArguments; ++i) {

        if (nInputFileArguments > 1) {
            std::cout<<"###"<< std::endl;
            std::cout<<"inputFileArgument = " << inputFileArguments.at(i).c_str() << std::endl;
        }

        inputFiles[i] = InputConfigurationParser::ParseFiles(inputFileArguments.at(i));
        std::cout<<"input ROOT files : num = " << inputFiles[i].size() << std::endl;
        for (std::vector<std::string>::iterator it = inputFiles[i].begin() ; it != inputFiles[i].end(); ++it) {
            std::cout<<(*it).c_str()<< std::endl;
        }
    }
    std::cout<<"##### END #####"<< std::endl;

    // check consistency of the input file arguments with the mode
    if (mode == INPUT_MODE::k_noMode && nInputFileArguments > 1) {
        std::cout<<"no specific mode is chosen. more than one input samples are provided."<< std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }
    if (mode == INPUT_MODE::k_comparison && nInputFileArguments == 1) {
        std::cout<<"comparison mode is chosen. But only one input sample is provided."<< std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }

    if (nTrees == 1 && nFriendsIndividual > 0) {
        std::cout<<"nTrees = "<< nTrees <<", nFriendsIndividual = " << nFriendsIndividual << std::endl;
        std::cout<<"There is only one tree to be plotted, it does not make sense to use individual friend trees."<< std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }
    else if (nTrees > 1 && nFriendsIndividual > 0 && nTrees != nFriendsIndividual) {
        std::cout<<"nTrees = "<< nTrees <<", nFriendsIndividual = " << nFriendsIndividual << std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }

    if (nSelectionSplitter == 1) {
        std::cout << "nSelectionSplitter = "<< nSelectionSplitter << std::endl;
        std::cout << "selectionSplitter has been set to have exactly one selection"<< std::endl;
        std::cout << "selectionSplitter is allowed to be either empty or to have more than one selections"<< std::endl;
        std::cout << "exiting"<< std::endl;
        return;
    }
    int nSplits = 1;
    if (nSelectionSplitter > 1)  nSplits = nSelectionSplitter;

    int nSelectionsTot = nSelections * nSplits;
    int nFormulasTot = nFormulas * nSplits;

    TH1::SetDefaultSumw2();
    int nHistos = nFormulasTot;
    if (nFormulas == 1 && nSelections > nFormulas) nHistos = nSelectionsTot;
    else if (nFormulas == 1 && nSelections == 1 && nTrees > nFormulas) nHistos = nTrees * nSplits;
    else if (nFormulas > 1 && nSelections > 1 && nFormulas != nSelections) {
        std::cout << "mismatch of number of formulas and number of selections"<< std::endl;
        std::cout << "nHistos     = "<< nHistos << std::endl;
        std::cout << "nSelections = "<< nSelections << std::endl;
        std::cout << "exiting " << std::endl;
        return;
    }
    else if (nFormulas > 1 && nTrees > 1 && nFormulas != nTrees) {
        std::cout << "mismatch of number of formulas and number of trees"<< std::endl;
        std::cout << "nHistos = "<< nHistos << std::endl;
        std::cout << "nTrees  = "<< nTrees << std::endl;
        std::cout << "exiting " << std::endl;
        return;
    }
    else if (nSelections > 1 && nTrees > 1 && nSelections != nTrees) {
        std::cout << "mismatch of number of selections and number of trees"<< std::endl;
        std::cout << "nHistos     = "<< nHistos << std::endl;
        std::cout << "nSelections = "<< nSelections << std::endl;
        std::cout << "nTrees      = "<< nTrees << std::endl;
        std::cout << "exiting " << std::endl;
        return;
    }
    TFile* output = TFile::Open(outputFile.Data(),"RECREATE");
    output->cd();

    int nHistosInput = nHistos/nSplits;     // number of histograms without considering selectionSplitter
    std::cout << "nHistos = " << nHistos << std::endl;
    TH2D* h[nHistos];
    for (int i=0; i<nHistos; ++i) {
        int nBinsx  = (int)TH2D_Bins_List[0].at(0);
        float xLow = TH2D_Bins_List[1].at(0);
        float xUp  = TH2D_Bins_List[2].at(0);
        int nBinsy  = (int)TH2D_Bins_List[3].at(0);
        float yLow = TH2D_Bins_List[4].at(0);
        float yUp  = TH2D_Bins_List[5].at(0);
        if (nTH2D_Bins_List == nHistosInput) {
            nBinsx = (int)TH2D_Bins_List[0].at(i%nTH2D_Bins_List);
            xLow  = TH2D_Bins_List[1].at(i%nTH2D_Bins_List);
            xUp   = TH2D_Bins_List[2].at(i%nTH2D_Bins_List);
            nBinsy = (int)TH2D_Bins_List[3].at(i%nTH2D_Bins_List);
            yLow  = TH2D_Bins_List[4].at(i%nTH2D_Bins_List);
            yUp   = TH2D_Bins_List[5].at(i%nTH2D_Bins_List);
        }
        std::string title = "";
        if (nTitles == 1)  {
            if (titles.at(0).compare(CONFIGPARSER::nullInput) != 0)  title = titles.at(0).c_str();
        }
        else if (nTitles == nHistosInput)  {
            if (titles.at(i%nTitles).compare(CONFIGPARSER::nullInput) != 0)  title = titles.at(i%nTitles).c_str();
        }
        else if (nTitles == nHistos)  {
            if (titles.at(i).compare(CONFIGPARSER::nullInput) != 0)  title = titles.at(i).c_str();
        }

        std::string titleX = "";
        if (nTitlesX == 1) titleX = titlesX.at(0).c_str();
        else if (nTitlesX == nHistosInput) titleX = titlesX.at(i%nTitlesX).c_str();
        else if (nTitlesX == nHistos)      titleX = titlesX.at(i).c_str();

        std::string titleY = "";
        if (nTitlesY == 1) titleY = titlesY.at(0).c_str();
        else if (nTitlesY == nHistosInput) titleY = titlesY.at(i%nTitlesY).c_str();
        else if (nTitlesY == nHistos)      titleY = titlesY.at(i).c_str();

        h[i] = new TH2D(Form("h2D_%d", i),Form("%s;%s;%s", title.c_str(), titleX.c_str(), titleY.c_str()), nBinsx, xLow, xUp, nBinsy, yLow, yUp);
    }

    // if no mode is specified (which is what happens most of the time), then it is expected that nInputFileArguments = 1.
    // so in that case : 1.) the "TTree*" objects below are effectively 1D, not 2D. 2.) the loops below have effective depth 1, not 2.
    TTree* trees[nTrees][nInputFileArguments];
    TTree* treeFriends[nFriends][nInputFileArguments];
    TTree* treeFriendsIndividual[nFriendsIndividual][nInputFileArguments];
    TTree* treeHiForestInfo[nInputFileArguments];

    Long64_t entries[nInputFileArguments];
    Long64_t entriesSelected[nHistos];
    std::fill_n(entriesSelected, nHistos, 0);

    int nFiles[nInputFileArguments];
    TFile* fileTmp = 0;

    std::cout << "initial reading to get the number of entries (if there is only one input file) and HiForest info" << std::endl;
    for (int iInFileArg = 0; iInFileArg < nInputFileArguments; ++iInFileArg) {

        nFiles[iInFileArg] = inputFiles[iInFileArg].size();
        if (nInputFileArguments > 1) {
            std::cout <<"iInFileArg = " << iInFileArg << " , "<< std::endl;
        }

        // read the first file only to get the HiForest info
        std::string inputPath = inputFiles[iInFileArg].at(0).c_str();
        fileTmp = new TFile(inputPath.c_str(), "READ");

        bool treeExists = true;
        if (nFiles[iInFileArg] == 1) {
            // read one tree only to get the number of entries
            trees[0][iInFileArg] = (TTree*)fileTmp->Get(treePaths.at(0).c_str());
            if (!trees[0][iInFileArg]) {
                std::cout << "tree is not found in the path : "<< treePaths.at(0).c_str() <<". skipping file." << std::endl;
                treeExists = false;
            }
            if (treeExists) {
                entries[iInFileArg] = trees[0][iInFileArg]->GetEntries();
                std::cout << "entries = " << entries[iInFileArg] << std::endl;
            }
        }

        if (treeExists) {
            treeHiForestInfo[0] = (TTree*)fileTmp->Get("HiForest/HiForestInfo");
            if (!treeHiForestInfo[0]) {
                std::cout << "HiForest/HiForestInfo tree is not found." << std::endl;
                treeExists = false;
            }
            if (treeExists) {
                HiForestInfoController hfic(treeHiForestInfo[0]);
                if (iInFileArg == 0)  std::cout<<"### HiForestInfo Tree ###"<< std::endl;
                else                  std::cout<<"### HiForestInfo Tree, input "<< iInFileArg+1 << " ###" << std::endl;
                hfic.printHiForestInfo();
                std::cout<<"###"<< std::endl;
            }
        }

        fileTmp->Close();
    }

    std::cout << "TTree::Draw()" <<std::endl;
    for (int iInFileArg = 0; iInFileArg < nInputFileArguments; ++iInFileArg) {

        if (nInputFileArguments > 1) {
            std::cout <<"iInFileArg = " << iInFileArg << std::endl;
        }

        entries[iInFileArg] = 0;
        for (int iFile = 0; iFile < nFiles[iInFileArg]; ++iFile) {

            std::string inputPath = inputFiles[iInFileArg].at(iFile).c_str();
            std::cout <<"iFile = " << iFile << " , " ;
            std::cout <<"reading input file : " << inputPath.c_str() << std::endl;
            fileTmp = new TFile(inputPath.c_str(), "READ");

            // check if the file is usable, if not skip the file.
            if (isGoodFile(fileTmp) != 0) {
                std::cout << "File is not good. skipping file." << std::endl;
                continue;
            }

            bool treeExists = true;
            for (int i=0; i<nTrees; ++i) {
                trees[i][iInFileArg] = (TTree*)fileTmp->Get(treePaths.at(i).c_str());
                if (!trees[i][iInFileArg]) {
                    std::cout << "tree is not found in the path : "<< treePaths.at(i).c_str() <<". skipping file." << std::endl;
                    treeExists = false;
                }
            }
            for (int i=0; i<nFriends; ++i) {
                treeFriends[i][iInFileArg] = (TTree*)fileTmp->Get(treeFriendsPath.at(i).c_str());
                if (!treeFriends[i][iInFileArg]) {
                    std::cout << "tree is not found in the path : "<< treeFriendsPath.at(i).c_str() <<". skipping file." << std::endl;
                    treeExists = false;
                }
            }
            if (!treeExists)  continue;

            // add friends
            for (int i=0; i<nTrees; ++i) {
                for (int j=0; j<nFriends; ++j) {
                    trees[i][iInFileArg]->AddFriend(treeFriends[j][iInFileArg], Form("t%d", j));
                }
            }
            for (int i=0; i < nFriendsIndividual; ++i) {
                if (treeFriendsPathIndividual.at(i).compare(CONFIGPARSER::nullInput) != 0) {
                    treeFriendsIndividual[i][iInFileArg] = (TTree*)fileTmp->Get(treeFriendsPathIndividual.at(i).c_str());
                }
            }
            if (nFriendsIndividual > 0) {
                for (int i=0; i<nTrees; ++i) {
                    if (treeFriendsPathIndividual.at(i).compare(CONFIGPARSER::nullInput) != 0) {
                        trees[i][0]->AddFriend(treeFriendsIndividual[i][0], Form("tSelf%d", i));
                    }
                }
            }

            Long64_t entriesTmp = trees[0][iInFileArg]->GetEntries();      // assume all the trees have same number of entries
            entries[iInFileArg] += entriesTmp;

            if (nInputFileArguments == 1)  {
                std::cout << "entries in File = " << entriesTmp << std::endl;
            }
            else {
                std::cout << Form("entries[%d] = ", iInFileArg) << entriesTmp << std::endl;
            }

            output->cd();
            for (int i=0; i<nHistos; ++i) {

                int treeIndex = 0;
                if (nHistosInput == nTrees)  treeIndex = i%nTrees;
                // std::cout << "treePath = " << treePaths.at(treeIndex).c_str() << ", ";

                int iInFileArg = 0;
                if (mode == INPUT_MODE::k_comparison) {
                    iInFileArg = i%nInputFileArguments;
                    std::cout << "iInFileArg = " << iInFileArg << ", ";
                }

                std::string formula = formulas.at(0).c_str();
                std::string selection = selections.at(0).c_str();
                std::string weight = weights.at(0).c_str();
                if (nHistosInput == nFormulas)  formula = formulas.at(i%nFormulas).c_str();
                if (nHistosInput == nSelections)  selection = selections.at(i%nSelections).c_str();
                if (nHistosInput == nWeights)  weight = weights.at(i%nWeights).c_str();

                std::string selectionSplit = "";
                if (nSelectionSplitter > 1)  selectionSplit = selectionSplitter.at(i/ (nHistos/nSelectionSplitter)).c_str();

                // std::cout << "drawing histogram i = " << i << ", ";

                TCut selectionFinal = selectionBase.c_str();
                selectionFinal = selectionFinal && selection.c_str();
                if (selectionSplit.size() > 0)  selectionFinal = selectionFinal && selectionSplit.c_str();
                Long64_t entriesSelectedTmp = trees[treeIndex][iInFileArg]->GetEntries(selectionFinal.GetTitle());
                // std::cout << "entriesSelected in file = " << entriesSelectedTmp << std::endl;
                entriesSelected[i] += entriesSelectedTmp;

                TCut weight_AND_selection = Form("(%s)*(%s)", weight.c_str(), selectionFinal.GetTitle());
                trees[treeIndex][iInFileArg]->Draw(Form("%s >>+ %s", formula.c_str(), h[i]->GetName()), weight_AND_selection.GetTitle(), "goff");
            }
            fileTmp->Close();
        }
    }
    std::cout << "TTree::Draw() ENDED" <<std::endl;
    for (int i = 0; i < nInputFileArguments; ++i) {

        if (nInputFileArguments == 1)  {
            std::cout << "entries = " << entries[0] << std::endl;
        }
        else {
            std::cout << Form("entries[%d] = ", i) << entries[i] << std::endl;
        }
    }
    std::cout << "### selected entries" << std::endl;
    for (int i = 0; i < nHistos; ++i) {

        std::cout << "TH1D i = " << i << ", ";
        int treeIndex = 0;
        if (nHistosInput == nTrees)  treeIndex = i%nTrees;
        std::cout << "treePath = " << treePaths.at(treeIndex).c_str() << ", ";

        std::cout << "entriesSelected = " << entriesSelected[i] << std::endl;
    }
    std::cout << "###" << std::endl;

    // print info about histograms
    for (int i=0; i<nHistos; ++i) {
        std::cout << "#####" << std::endl;
        std::cout << Form("h[%d]", i) << std::endl;
        std::string summary = summaryTH1(h[i]);
        std::cout << summary.c_str() << std::endl;
    }

    output->cd();

    TH2D* h_normInt[nHistos];
    TH2D* h_normEvents[nHistos];
    for (int i=0; i<nHistos; ++i) {
        h[i]->Write();

        h_normInt[i] = (TH2D*)h[i]->Clone(Form("%s_normInt", h[i]->GetName()));
        h_normInt[i]->Scale(1./h[i]->Integral());
        h_normInt[i]->Write();

        h_normEvents[i] = (TH2D*)h[i]->Clone(Form("%s_normEvents", h[i]->GetName()));
        h_normEvents[i]->Scale(1./entriesSelected[i]);
        h_normEvents[i]->Write();
    }
    // histograms are written. After this point changes to the histograms will not be reflected in the output ROOT file.

    // set the style of the histograms for canvases to be written
    for (int i=0; i<nHistos; ++i) {
        h[i]->SetTitleOffset(titleOffsetX,"X");
        h[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normInt[i]->SetTitleOffset(titleOffsetX,"X");
        h_normInt[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normEvents[i]->SetTitleOffset(titleOffsetX,"X");
        h_normEvents[i]->SetTitleOffset(titleOffsetY,"Y");

        // default marker style and color
        h[i]->SetMarkerStyle(kFullCircle);
        h[i]->SetMarkerColor(kBlack);
        h_normInt[i]->SetMarkerStyle(kFullCircle);
        h_normInt[i]->SetMarkerColor(kBlack);
        h_normEvents[i]->SetMarkerStyle(kFullCircle);
        h_normEvents[i]->SetMarkerColor(kBlack);

        // no stats box in the final plots
        h[i]->SetStats(false);
        h_normInt[i]->SetStats(false);
        h_normEvents[i]->SetStats(false);
    }

    // write canvases
    TCanvas* c;
    for (int i=0; i<nHistos; ++i) {
        c = new TCanvas(Form("cnv_%d",i),"",windowWidth,windowHeight);
        c->SetTitle(h[i]->GetTitle());
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();

        h[i]->SetTitleOffset(titleOffsetX,"X");
        h[i]->SetTitleOffset(titleOffsetY,"Y");
        h[i]->SetStats(false);
        h[i]->Draw("colz");
        c->Write();
        c->Close();         // do not use Delete() for TCanvas.

        // normalized to 1.
        c = new TCanvas(Form("cnv_%d_normInt",i),"",windowWidth,windowHeight);
        c->SetTitle(h_normInt[i]->GetTitle());
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();

        h_normInt[i]->SetTitleOffset(titleOffsetX,"X");
        h_normInt[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normInt[i]->SetStats(false);
        h_normInt[i]->Draw("colz");
        c->Write();
        c->Close();         // do not use Delete() for TCanvas.

        // normalized by number of events
        c = new TCanvas(Form("cnv_%d_normEvents",i),"",windowWidth,windowHeight);
        c->SetTitle(h_normEvents[i]->GetTitle());
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();

        h_normEvents[i]->SetTitleOffset(titleOffsetX,"X");
        h_normEvents[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normEvents[i]->SetStats(false);
        h_normEvents[i]->Draw("colz");
        c->Write();
        c->Close();         // do not use Delete() for TCanvas.
    }
    // canvases are written.

    // set style of the histograms for the canvases to be saved as picture
    for(int i=0; i<nHistos; ++i) {
        std::string drawOption = "colz";
        if (nDrawOptions == 1) {
            if (drawOptions.at(0).compare(CONFIGPARSER::nullInput) != 0)  drawOption = drawOptions.at(0).c_str();
        }
        else if (nDrawOptions == nHistosInput) {
            if (drawOptions.at(i).compare(CONFIGPARSER::nullInput) != 0)  drawOption = drawOptions.at(i%nDrawOptions).c_str();
        }
        // https://root.cern.ch/doc/master/classTObject.html#abe2a97d15738d5de00cd228e0dc21e56
        // TObject::SetDrawOption() is not suitable for the approach here.

        int markerStyle = GRAPHICS::markerStyle;
        if (nMarkerStyles == 1) markerStyle = GraphicsConfigurationParser::ParseMarkerStyle(markerStyles.at(0));
        else if (nMarkerStyles == nHistosInput) markerStyle = GraphicsConfigurationParser::ParseMarkerStyle(markerStyles.at(i%nMarkerStyles));
        h[i]->SetMarkerStyle(markerStyle);
        h_normInt[i]->SetMarkerStyle(markerStyle);
        h_normEvents[i]->SetMarkerStyle(markerStyle);

        int lineStyle = GRAPHICS::lineStyle;
        if (nLineStyles == 1)  lineStyle = GraphicsConfigurationParser::ParseLineStyle(lineStyles.at(0));
        else if (nLineStyles == nHistosInput)  lineStyle = GraphicsConfigurationParser::ParseLineStyle(lineStyles.at(i%nLineStyles));
        h[i]->SetLineStyle(lineStyle);
        h_normInt[i]->SetLineStyle(lineStyle);
        h_normEvents[i]->SetLineStyle(lineStyle);

        int fillStyle = GRAPHICS::fillStyle;
        if (nFillStyles == 1)  fillStyle = GraphicsConfigurationParser::ParseLineStyle(fillStyles.at(0));
        else if (nFillStyles == nHistosInput)  fillStyle = GraphicsConfigurationParser::ParseLineStyle(fillStyles.at(i%nFillStyles));
        h[i]->SetFillStyle(fillStyle);
        h_normInt[i]->SetFillStyle(fillStyle);
        h_normEvents[i]->SetFillStyle(fillStyle);

        int color = GRAPHICS::colors[i];
        if (nColors == 1) color = GraphicsConfigurationParser::ParseColor(colors.at(0));
        else if (nColors == nHistosInput) color = GraphicsConfigurationParser::ParseColor(colors.at(i%nColors));
        h[i]->SetMarkerColor(color);
        h[i]->SetLineColor(color);
        h_normInt[i]->SetMarkerColor(color);
        h_normInt[i]->SetLineColor(color);
        h_normEvents[i]->SetMarkerColor(color);
        h_normEvents[i]->SetLineColor(color);

        int fillColor = -1;
        if (nFillColors == 1) fillColor = GraphicsConfigurationParser::ParseColor(fillColors.at(0));
        else if (nFillColors == nHistosInput) fillColor = GraphicsConfigurationParser::ParseColor(fillColors.at(i%nFillColors));
        if (fillColor != -1)
        {
            h[i]->SetFillColor(fillColor);
            h_normInt[i]->SetFillColor(fillColor);
            h_normEvents[i]->SetFillColor(fillColor);
        }

        int lineColor = -1;
        if (nLineColors == 1) lineColor = GraphicsConfigurationParser::ParseColor(lineColors.at(0));
        else if (nLineColors == nHistosInput) lineColor = GraphicsConfigurationParser::ParseColor(lineColors.at(i%nLineColors));
        if (nLineColors != -1)
        {
            h[i]->SetLineColor(lineColor);
            h_normInt[i]->SetLineColor(lineColor);
            h_normEvents[i]->SetLineColor(lineColor);
        }

        if(lineWidth != INPUT_DEFAULT::lineWidth) {
            if (drawOption.find("hist") != std::string::npos) {
                h[i]->SetLineWidth(lineWidth);
                h_normInt[i]->SetLineWidth(lineWidth);
                h_normEvents[i]->SetLineWidth(lineWidth);
            }
        }

        h[i]->SetMarkerSize(markerSize);
        h_normInt[i]->SetMarkerSize(markerSize);
        h_normEvents[i]->SetMarkerSize(markerSize);
    }

    TH1D* h_draw[nHistos];
    for (int i=0; i<nHistos; ++i) {
        if (drawNormalized == INPUT_TH1::k_normInt) {
            h_draw[i] = (TH1D*)h_normInt[i]->Clone(Form("h_%d_draw", i));
        }
        else if (drawNormalized == INPUT_TH1::k_normEvents) {
            h_draw[i] = (TH1D*)h_normEvents[i]->Clone(Form("h_%d_draw", i));
        }
        else {  // no normalization
            h_draw[i] = (TH1D*)h[i]->Clone(Form("h_%d_draw", i));
        }
    }

    for (int i = 0; i<nHistos; ++i) {

        c = new TCanvas(Form("cnv_drawSpectra2D_%d", i),"",windowWidth,windowHeight);
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();
        TLegend* leg = new TLegend();

        std::string drawOption = "";
        if (nDrawOptions == 1)  drawOption = drawOptions.at(0).c_str();
        else if (nDrawOptions == nHistosInput) drawOption = drawOptions.at(i%nDrawOptions).c_str();

        h_draw[i]->Draw(drawOption.c_str());

        if (nLegendEntryLabels == nHistosInput) {
            std::string label = legendEntryLabels.at(i%nLegendEntryLabels).c_str();
            std::string legendOption = "lpf";
            if (drawOption.find("hist") != std::string::npos)  legendOption = "lf";
            if (label.compare(CONFIGPARSER::nullInput) != 0)  leg->AddEntry(h_draw[i], label.c_str(), legendOption.c_str());
        }

        if (legendTextSize != 0)  leg->SetTextSize(legendTextSize);
        leg->SetBorderSize(legendBorderSize);
        double height = calcTLegendHeight(leg);
        double width = calcTLegendWidth(leg);
        if (legendHeight != 0)  height = legendHeight;
        if (legendWidth != 0)  width = legendWidth;
        if (legendPosition.size() > 0) {    // draw the legend if really a position is provided.
            setLegendPosition(leg, legendPosition, c, height, width, legendOffsetX, legendOffsetY);
            leg->Draw();
        }

        // add Text
        TLatex* latex = 0;
        if (nTextLines > 0) {
            latex = new TLatex();
            latex->SetTextFont(textFont);
            latex->SetTextSize(textSize);
            setTextAlignment(latex, textPosition);
            std::vector<std::pair<float,float>> textCoordinates = calcTextCoordinates(textLines, textPosition, c, textOffsetX, textOffsetY);
            for (int i = 0; i<nTextLines; ++i) {
                float x = textCoordinates.at(i).first;
                float y = textCoordinates.at(i).second;
                latex->DrawLatexNDC(x, y, textLines.at(i).c_str());
            }
        }

        // add Text above the pad
        TLatex* latexOverPad = 0;
        if (nTextsOverPad > 0) {
            latexOverPad = new TLatex();
            latexOverPad->SetTextFont(textAbovePadFont);
            latexOverPad->SetTextSize(textAbovePadSize);
            for (int i = 0; i < nTextsOverPad; ++i) {
                int textOverPadAlignment = GRAPHICS::textAlign;
                if (nTextsOverPadAlignments == 1) textOverPadAlignment = GraphicsConfigurationParser::ParseTextAlign(textsOverPadAlignments.at(0));
                else if (nTextsOverPadAlignments == nTextsOverPad) textOverPadAlignment = GraphicsConfigurationParser::ParseTextAlign(textsOverPadAlignments.at(i));

                latexOverPad->SetTextAlign(textOverPadAlignment);
                setTextAbovePad(latexOverPad, c, textAbovePadOffsetX, textAbovePadOffsetY);

                latexOverPad->DrawLatexNDC(latexOverPad->GetX(), latexOverPad->GetY(), textsOverPad.at(i).c_str());
            }
        }

        // add TLine
        TLine* line_horizontal[nTLines_horizontal];
        for (int iLine = 0; iLine<nTLines_horizontal; ++iLine) {
            // draw horizontal line
            double xmin = h[i]->GetXaxis()->GetBinLowEdge(h[i]->GetXaxis()->GetFirst());
            double xmax = h[i]->GetXaxis()->GetBinLowEdge(h[i]->GetXaxis()->GetLast()+1);

            int lineStyle_horizontal = GRAPHICS::lineStyle_horizontal;
            if (nLineStyles_horizontal == 1)
                lineStyle_horizontal = GraphicsConfigurationParser::ParseLineStyle(lineStyles_horizontal.at(0));
            else if (nLineStyles_horizontal == nTLines_horizontal)
                lineStyle_horizontal = GraphicsConfigurationParser::ParseLineStyle(lineStyles_horizontal.at(iLine));

            line_horizontal[iLine] = new TLine(xmin, TLines_horizontal.at(iLine), xmax, TLines_horizontal.at(iLine));
            line_horizontal[iLine]->SetLineStyle(lineStyle_horizontal);   // https://root.cern.ch/doc/master/TAttLine_8h.html#a7092c0c4616367016b70d54e5c680a69
            line_horizontal[iLine]->Draw();
        }
        // add TLine
        TLine* line_vertical[nTLines_vertical];
        for (int iLine = 0; iLine<nTLines_vertical; ++iLine) {
            // draw vertical line
            double ymin = h[i]->GetYaxis()->GetBinLowEdge(h[i]->GetYaxis()->GetFirst());
            double ymax = h[i]->GetYaxis()->GetBinLowEdge(h[i]->GetYaxis()->GetLast()+1);

            int lineStyle_vertical = GRAPHICS::lineStyle_vertical;
            if (nLineStyles_vertical == 1)
                lineStyle_vertical = GraphicsConfigurationParser::ParseLineStyle(lineStyles_vertical.at(0));
            else if (nLineStyles_vertical == nTLines_vertical)
                lineStyle_vertical = GraphicsConfigurationParser::ParseLineStyle(lineStyles_vertical.at(iLine));

            line_vertical[iLine] = new TLine(TLines_vertical.at(iLine), ymin, TLines_vertical.at(iLine), ymax);
            line_vertical[iLine]->SetLineStyle(lineStyle_vertical);   // https://root.cern.ch/doc/master/TAttLine_8h.html#a7092c0c4616367016b70d54e5c680a69
            line_vertical[iLine]->Draw();
        }
        c->Write();

        // save histograms as picture if a figure name is provided.
        // for now 2D canvases are not drawn on top, they are drawn separately.
        if (!outputFigureName.EqualTo("")) {
            std::string tmpOutputFigureName = outputFigureName.Data();
            if (tmpOutputFigureName.find(".") != std::string::npos) {     // file extension is specified
                if (nHistos > 1) {
                    // modify outputFile name
                    // if i=1, then "output.ext" becomes "output_2.ext"
                    size_t pos = tmpOutputFigureName.find_last_of(".");
                    tmpOutputFigureName.replace(pos,1, Form("_%d.", i+1));
                }
                c->SaveAs(tmpOutputFigureName.c_str());
            }
            else {  // file extension is NOT specified
                if (nHistos > 1) {
                    // modify outputFile name
                    // if i=1, then "output" becomes "output_2"
                    tmpOutputFigureName = Form("%s_%d", tmpOutputFigureName.c_str(), i+1);
                }

                c->SaveAs(Form("%s.C", tmpOutputFigureName.c_str()));
                c->SaveAs(Form("%s.png", tmpOutputFigureName.c_str()));
                c->SaveAs(Form("%s.pdf", tmpOutputFigureName.c_str()));
            }
        }

        leg->Delete();
        c->Close();
    }

    output->Close();
}
Esempio n. 14
0
void makePlots (string configFilePath){

  if (( nHistList % inputRootFile.size() == 0 )) 
    {
      for (int i=0; i<numHistos; i++) 
        {
	 
          TCanvas *c = new TCanvas(theHistNameStrings.at(i).c_str(), "", 81,58,500,602);
 
          TH1* h_mc;        // histograms for MC
          TH1* h_mc_clone;  // histograms for MC 
          TH1* h_data;      // histogram to store data points 
	  TH1* h_data_clone;
          TLegend *legend = new TLegend(0.2, 0.85-.035*inputLegend.size(), 0.5, 0.90,NULL,"brNDC");
          int whichHisto = 0;
	  
          for (int j=1;j<inputRootFile.size();j++)
	    {
	      
	      whichHisto=j*numHistos; 
	      
	      int a = 0;
	      bool foundHisto = false;
              
	      if (theHistNameStrings.at(i) == theHistNameStrings.at(i+whichHisto)) 
		{
		  foundHisto=true; 
		  a=i;
		}
	      
	      else 
		{
		  for (a = 0; a < numHistos; a++)
		    {
		      if (theHistNameStrings.at(i) == theHistNameStrings.at(a+whichHisto))
			{
			  foundHisto = true;
			  break;
			}
		    }
		}
	      //-----------------------------------------------------------
              
	      string hist2name = listHistos->At(a+whichHisto)->GetName();
	      if (foundHisto == true)
		{
                  h_data = (TH1*)listHistos->At(i);
                  h_data->SetMarkerStyle(inputMarkerStyle.at(0));
                  h_data = SetStyleh(h_data);
                  h_data->Sumw2();
                  int thelineStyle = inputSetLineStyle.at(j);
                  int thelineWidth = inputSetLineWidth.at(j);
                  int setcolor = inputColor.at(j);
                  int marker   = inputMarkerStyle.at(j);
                  h_data->SetMarkerColor(inputColor.at(0));
                  h_data->SetLineColor(inputColor.at(0));
                  if (j == 1) 
                    { 
		       if ( h_data->IsA()->InheritsFrom( "TH2" ) ) {
			 //n.b. that ProfileX will do nothing if the
			 //name you choose is alreayd taken!  so each
			 //profileX needs a unique name
			 TString profileName = TString::Format("%s_data_pfx",h_data->GetName());
			 TProfile *dataProf = ((TH2*)h_data)->ProfileX(profileName.Data());
			 dataProf->SetMinimum(h_data->GetMinimum()); //min/max values were stored in the original hist
			 dataProf->SetMaximum(h_data->GetMaximum());
			 dataProf->Draw("");
			 
			 //profileX cretaes a clone, so no need to
			 //clone again here.  Need to set the hist
			 //name so root doesn't complain
			 TString cloneName = TString::Format("%s_data_pfx_clone",h_data->GetName());
			 TString cloneName2 = TString::Format("%s_data_pfx_clone_px",h_data->GetName());
			 h_data_clone = ((TH2*)h_data)->ProfileX(cloneName.Data())->ProjectionX(cloneName2.Data());
		       }
		       else { //1d case
                         Float_t ymaxc = gPad->GetUymax();
                         //h_data->SetMaximum(ymaxc+0.15*ymaxc);
			 h_data->Draw("ep1");
			 h_data_clone = (TH1*)h_data->Clone();
		       }
                       //h_data->SetLineColor(1);
                       h_data->SetLineStyle(thelineStyle);
                       h_data->SetLineWidth(thelineWidth);
                       float rms_data = h_data->GetRMS();
                       float mean_data = h_data->GetMean();
                       std::stringstream legend_data;
                       legend_data.str("");
                       legend_data << inputLegend.at(0).c_str() << ": mean=" << setprecision(3)
                                   <<mean_data <<", rms=" << setprecision(3) <<rms_data<< endl;
                       legend->AddEntry(h_data,legend_data.str().c_str(), "lep");

                    }
		  h_mc = (TH1*)listHistos->At(a+whichHisto);
                  h_mc = SetStyleh(h_mc);
		  h_mc->SetName(hist2name.c_str());
                  //cout<<"NAME "<<h_mc->GetName()<<endl;
		  // Style
                  
		  string processlegend = (inputLegend.at(j)).c_str();
 
		  h_mc->SetLineStyle(thelineStyle);
		  h_mc->SetLineWidth(thelineWidth);
		  h_mc->SetLineColor(setcolor);
                  h_mc->SetMarkerStyle(marker);
                  h_mc->SetMarkerColor(setcolor);                 
 
                  string processlegend = (inputLegend.at(j)).c_str(); 

		  if ( h_mc->IsA()->InheritsFrom( "TH2" ) ) {
		    TString profileName = TString::Format("%s_mc_pfx", h_mc->GetName());
		    ((TH2*)h_mc)->ProfileX(profileName.Data())->Draw("SAME");
		    //profileX cretaes a clone, so no need to
		    //clone again here.  Need to set the hist
		    //name so root doesn't complain
		    TString cloneName = TString::Format("%s_mc_pfx_clone",h_mc->GetName());
		    TString cloneName2 = TString::Format("%s_mc_pfx_clone_px",h_mc->GetName());
		    h_mc_clone = ((TH2*)h_mc)->ProfileX(cloneName.Data())->ProjectionX(cloneName2.Data());
		  } else { //1d case
                    Float_t ymaxc = gPad->GetUymax();
                    h_mc->SetMaximum(ymaxc+0.15*ymaxc);
		    h_mc->Draw("epsame");
		    h_mc_clone = (TH1*)h_mc->Clone();
		  }
                  h_mc_clone->SetMarkerStyle(marker);
                  h_mc_clone->SetMarkerColor(setcolor);
                  float rms_mc = h_mc->GetRMS();
                  float mean_mc = h_mc->GetMean();
		  std::stringstream legend_mc;
                  legend_mc.str("");
                  legend_mc << processlegend.c_str() << " - "<< "mean: " << setprecision(3)
                              <<mean_mc <<" , rms: " << setprecision(3) <<rms_mc<< endl;
                  legend->AddEntry(h_mc, legend_mc.str().c_str(), "lep"); 
		}// close if (foundHisto)
 
	      legend->SetTextFont(42);
              legend->SetTextSize(.04);
              legend->SetMargin(0.15);
              legend->SetLineColor(1);
              legend->SetLineStyle(1);
              legend->SetLineWidth(1);
              legend->SetFillColor(0);
              legend->SetFillStyle(0);
              legend->SetBorderSize(0);
              legend->SetFillColor(kWhite);
              legend->Draw();
 
	      c->cd();
 	      
              if (j == 1)
                {
	           float startxbin = h_data_clone->GetXaxis()->GetBinWidth(h_data_clone->GetXaxis()->GetFirst()) * 
		      (h_data_clone->GetXaxis()->GetFirst() - 1);
	           float lastxbin  = h_data_clone->GetXaxis()->GetBinCenter(h_data_clone->GetXaxis()->GetNbins());
	      
	            double x1 = 0;
	            double x2 = lastxbin + h_data_clone->GetXaxis()->GetBinWidth(h_data_clone->GetXaxis()->GetNbins())/2.;
	      
	            if (h_data_clone->GetXaxis()->GetBinCenter(0) <= 0)
		        x1 = h_data_clone->GetXaxis()->GetBinCenter(0) + h_data_clone->GetXaxis()->GetBinWidth(0)/2. + startxbin;
	            else 
		        x1 = h_data_clone->GetXaxis()->GetBinCenter(0) - h_data_clone->GetXaxis()->GetBinWidth(0)/2. - startxbin;
	        } 
	  
	    } // close for loop inputRootFile
	  
	  TFile *hfile = (TFile*)gROOT->FindObject(HistosOutputRootFile.c_str());
	  if (hfile) {hfile->Close();}
	  hfile = new TFile(HistosOutputRootFile.c_str(),"UPDATE");

          for (int o = 0; o < inputHistoName.size(); o++)
             {
                if ( c->GetName() == inputHistoName.at(o) )
                  {
                     string save = configFilePath+"/"+inputHistoName.at(o)+".pdf";  
                     c->SaveAs(save.c_str());
                     c->Write();    
                     break;
                  }
             }

	  hfile->Close();
          c->Close();
	  
	}  // close foor loop numHistos     
      
    } // close if numHistos % inputRootFile.size() == 0
} // close  makePlots function
Esempio n. 15
0
void plot_BSM_MCFM(int SignalOnly=0){
  gROOT->ProcessLine(".x tdrstyle.cc");
  double mPOLE = 125.6;

  TString OUTPUT_NAME;
  OUTPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMPlots";
  if (SignalOnly==0) OUTPUT_NAME.Append(".root");
  else OUTPUT_NAME.Append("_SignalOnly.root");
  TString coutput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/Plots/";
  gSystem->Exec("mkdir -p " + coutput_common);
  TString coutput = coutput_common + OUTPUT_NAME;
  TFile* foutput = new TFile(coutput, "recreate");

  foutput->cd();

  float ZZMass = 0;
  float p0plus_VAJHU;
  float p0hplus_VAJHU;
  float p0minus_VAJHU;
  float p0_g1prime2_VAJHU;
  float p0_g1prime4_VAJHU;
  float pg1g2_VAJHU;
  float pg1g4_VAJHU;
  float pg1g1prime2_VAJHU;
  float pg1g1prime4_VAJHU;

  TChain* tc[2][3][4];
  TH1F* hfill[4][9];
  int nbinsx = 73;
  double xlimits[2]={ 160, 1620 };
  if (SignalOnly==1){
    xlimits[0]=100;
    nbinsx = 76;
  }
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      hfill[t][ac]= new TH1F(Form("hSum_BSI%i_Hypo%i", t, ac), "", nbinsx, xlimits[0], xlimits[1]);
      hfill[t][ac]->SetXTitle("m_{4l} (GeV)");
      hfill[t][ac]->SetYTitle(Form("Events / %.0f GeV", (xlimits[1]-xlimits[0])/nbinsx));
    }
  }
  double nCounted[2][3][9]={ { { 0 } } };
  double nCountedScaled[2][3][9]={ { { 0 } } };
  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      TString comstring;
      comstring.Form("%iTeV", erg_tev);
      TString erg_dir;
      erg_dir.Form("LHC_%iTeV/", erg_tev);

      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;
      TString cinput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/";
      cinput_common.Append(+erg_dir);
      cinput_common += user_folder[folder] + "/";
      cout << cinput_common << endl;
      for (int t=0; t<4; t++){
        TString INPUT_NAME;
        INPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMTrees_";
        INPUT_NAME += sample_suffix[t] + ".root";
        INPUT_NAME.Prepend(cinput_common);

        tc[EnergyIndex][folder][t] = new TChain("GenTree");
        if (t!=3) tc[EnergyIndex][folder][t]->Add(INPUT_NAME);
        tc[EnergyIndex][folder][t]->SetBranchAddress("ZZMass", &ZZMass);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0plus_VAJHU", &p0plus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0hplus_VAJHU", &p0hplus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0minus_VAJHU", &p0minus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime2_VAJHU", &p0_g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime4_VAJHU", &p0_g1prime4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g2_VAJHU", &pg1g2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g4_VAJHU", &pg1g4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime2_VAJHU", &pg1g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime4_VAJHU", &pg1g1prime4_VAJHU);
      }

      double nsig_counted[9] ={ 0 };
      for (int ev=0; ev<tc[EnergyIndex][folder][0]->GetEntries(); ev++){
        tc[EnergyIndex][folder][0]->GetEntry(ev);
        if (fabs(ZZMass-mPOLE)<0.1){
          nsig_counted[0] += p0plus_VAJHU;
          nsig_counted[1] += p0hplus_VAJHU;
          nsig_counted[2] += p0minus_VAJHU;
          nsig_counted[3] += p0_g1prime2_VAJHU;
          nsig_counted[4] += p0_g1prime4_VAJHU;
          nsig_counted[5] += (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU);
          nsig_counted[6] += pg1g4_VAJHU;
          nsig_counted[7] += pg1g1prime2_VAJHU;
          nsig_counted[8] += pg1g1prime4_VAJHU;
        }
      }

      for (int ac=0; ac<9; ac++) nCounted[EnergyIndex][folder][ac] = nsig_counted[ac];

    }
  }


  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;

      double nsig_SM = nSM_ScaledPeak[EnergyIndex][folder];
      double SMscale = nsig_SM/nCounted[EnergyIndex][folder][0];
      double scale=1;
      for (int t=0; t<4; t++){
        for (int ev=0; ev<tc[EnergyIndex][folder][t]->GetEntries(); ev++){
          tc[EnergyIndex][folder][t]->GetEntry(ev);
          if (ZZMass<xlimits[0]) continue;
          if (ZZMass>=xlimits[1]) ZZMass=xlimits[1]*0.999;

          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][0] = nCounted[EnergyIndex][folder][0]*scale;
          hfill[t][0]->Fill(ZZMass, p0plus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][1] = nCounted[EnergyIndex][folder][1]*scale;
          hfill[t][1]->Fill(ZZMass, p0hplus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][2] = nCounted[EnergyIndex][folder][2]*scale;
          hfill[t][2]->Fill(ZZMass, p0minus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][3] = nCounted[EnergyIndex][folder][3]*scale;
          hfill[t][3]->Fill(ZZMass, p0_g1prime2_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][4] = nCounted[EnergyIndex][folder][4]*scale;
          hfill[t][4]->Fill(ZZMass, p0_g1prime4_VAJHU*scale);
          scale = SMscale;
          if (t>0){
            hfill[t][5]->Fill(ZZMass, pg1g2_VAJHU*scale);
          }
          else{
            scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][5]+nCounted[1][2][5]);
            hfill[t][5]->Fill(ZZMass, (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU)*scale);
          }
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][5] = nCounted[EnergyIndex][folder][5]*scale;
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][6]+nCounted[1][2][6]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][6] = nCounted[EnergyIndex][folder][6]*scale;
          hfill[t][6]->Fill(ZZMass, pg1g4_VAJHU*scale);
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][7]+nCounted[1][2][7]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][7] = nCounted[EnergyIndex][folder][7]*scale;
          hfill[t][7]->Fill(ZZMass, pg1g1prime2_VAJHU*scale);
          scale = SMscale;
          //          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][8]+nCounted[1][2][8]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][8] = nCounted[EnergyIndex][folder][8]*scale;
          hfill[t][8]->Fill(ZZMass, pg1g1prime4_VAJHU*scale);
        }
        delete tc[EnergyIndex][folder][t];
      }
    }
  }
  for (int ac=1; ac<9; ac++){
    double nTotal[2]={ 0 };
    for (int erg_tev=7; erg_tev<9; erg_tev++){
      for (int folder=0; folder<3; folder++){
        int EnergyIndex = 1;
        if (erg_tev == 7) EnergyIndex = 0;

        nTotal[0] += nCountedScaled[EnergyIndex][folder][0];
        nTotal[1] += nCountedScaled[EnergyIndex][folder][ac];
      }
    }
    if (ac!=8) hfill[0][ac]->Scale(nTotal[0]/nTotal[1]);
    else hfill[0][ac]->Scale(0.5);
  }


  double maxplot=0;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      if (SignalOnly==0 && ac<5) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      else if (SignalOnly==1 && !(ac<5 && ac>0) && t==0) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      hfill[t][ac]->SetLineWidth(2);
      if (t==0 && ac>=5){
        hfill[t][ac]->SetLineStyle(7);
        //        hfill[t][ac]->Add(hfill[1][ac]);
      }
      if (t==1) hfill[t][ac]->SetLineStyle(3);
      if (t==3) hfill[t][ac]->SetLineStyle(9);
      hfill[t][ac]->GetXaxis()->SetLabelFont(42);
      hfill[t][ac]->GetXaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetXaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetXaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetXaxis()->SetTitleOffset(0.9);
      hfill[t][ac]->GetXaxis()->SetTitleFont(42);
      hfill[t][ac]->GetYaxis()->SetNdivisions(505);
      hfill[t][ac]->GetYaxis()->SetLabelFont(42);
      hfill[t][ac]->GetYaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetYaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetYaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetYaxis()->SetTitleOffset(1.1);
      hfill[t][ac]->GetYaxis()->SetTitleFont(42);
    }
  }

  TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
  pt->SetBorderSize(0);
  pt->SetFillStyle(0);
  pt->SetTextAlign(12);
  pt->SetTextFont(42);
  pt->SetTextSize(0.045);
  TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
  text->SetTextSize(0.044);
  text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
  text->SetTextSize(0.0315);
  TString cErgTev = "#font[42]{19.7 fb^{-1} (8 TeV) + 5.1 fb^{-1} (7 TeV)}";
  text = pt->AddText(0.537, 0.45, cErgTev);
  text->SetTextSize(0.0315);

  float lxmin = 0.22;
  float lxwidth = 0.38;
  float lymax = 0.9;
  float lywidth = 0.3;
  float lxmax = lxmin + lxwidth;
  float lymin = lymax;
  if (SignalOnly==0) lymin -= lywidth*4./5.;
  else lymin -= lywidth;

  float lxmin2 = 0.22+0.39;
  float lymax2 = lymax;
  float lxmax2 = lxmin2 + lxwidth;
  float lymin2 = lymax2;
  if (SignalOnly==0) lymin2 -= lywidth*2./5.;
  else lymin2 -= lywidth*4./5.;

  if (SignalOnly==1){
    float lxmin3 = lxmin2;
    float lymax3 = lymax2;
    float lxmax3 = lxmax2;
    float lymin3 = lymin2;

    lxmin2 = lxmin;
    lxmax2 = lxmax;
    lymin2 = lymin;
    lymax2 = lymax;
    lxmin = lxmin3;
    lxmax = lxmax3;
    lymin = lymin3;
    lymax = lymax3;
  }

  float pxmin = 0.756;
  float pymin = 0.76;
  float pxmax = 0.85;
  if (SignalOnly==1){
    pymin -= 0.12;
  }
  float pymax = pymin+0.05;
  TPaveText* ptx = new TPaveText(pxmin, pymin, pxmax, pymax, "brNDC");
  ptx->SetBorderSize(0);
  ptx->SetTextFont(42);
  ptx->SetTextSize(0.04);
  ptx->SetLineColor(1);
  ptx->SetLineStyle(1);
  ptx->SetLineWidth(1);
  ptx->SetFillColor(0);
  ptx->SetFillStyle(0);
  text = ptx->AddText(0.01, 0.01, "gg#rightarrow4l");
  text->SetTextSize(0.04);

  TString canvasname = "cCanvas_MCFMBSM_GenLevel";
  if (SignalOnly==1) canvasname.Append("_SignalOnly");
  TCanvas* cc = new TCanvas(canvasname, "", 8, 30, 800, 800);
  cc->cd();
  gStyle->SetOptStat(0);
  cc->SetFillColor(0);
  cc->SetBorderMode(0);
  cc->SetBorderSize(2);
  cc->SetTickx(1);
  cc->SetTicky(1);
  cc->SetLeftMargin(0.17);
  cc->SetRightMargin(0.05);
  cc->SetTopMargin(0.07);
  cc->SetBottomMargin(0.13);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetLogy();

  TLegend* ll;
  TLegend* ll2;

  ll = new TLegend(lxmin2, lymin2, lxmax2, lymax2);
  ll2 = new TLegend(lxmin, lymin, lxmax, lymax);

  ll->SetBorderSize(0);
  ll->SetTextFont(42);
  ll->SetTextSize(0.04);
  ll->SetLineColor(1);
  ll->SetLineStyle(1);
  ll->SetLineWidth(1);
  ll->SetFillColor(0);
  ll->SetFillStyle(0);
  ll2->SetBorderSize(0);
  ll2->SetTextFont(42);
  ll2->SetTextSize(0.04);
  ll2->SetLineColor(1);
  ll2->SetLineStyle(1);
  ll2->SetLineWidth(1);
  ll2->SetFillColor(0);
  ll2->SetFillStyle(0);

  TString strACtitle[9]={ "",
    "f_{a2}=1", "f_{a3}=1", "f_{#Lambda1}=1", "f_{#LambdaQ}=1",
    "f_{a2}=0.5, #phi_{#lower[-0.2]{a2}}=#pi", "f_{a3}=0.5", "f_{#Lambda1}=0.5", "f_{#LambdaQ}=0.5"
  };

  int iDraw = 2 - 2*SignalOnly;

  if (SignalOnly==0) hfill[iDraw][0]->GetYaxis()->SetRangeUser(7e-3, maxplot*15.);
  else{
    double histmin = 7e-3;
    if (hfill[iDraw][0]->GetMinimum()>0) histmin = hfill[iDraw][0]->GetMinimum();
    hfill[iDraw][0]->GetYaxis()->SetRangeUser(histmin, maxplot*2000.);
  }
  hfill[iDraw][0]->GetXaxis()->SetRangeUser(xlimits[0], 800.);

  hfill[iDraw][0]->SetLineColor(kBlack);
  if (SignalOnly==0){
    hfill[iDraw][0]->SetFillColor(kAzure-2);
    hfill[iDraw][0]->SetFillStyle(1001);
  }
  hfill[iDraw][0]->Draw("hist");

  hfill[iDraw][1]->SetLineColor(kBlue);
  hfill[iDraw][1]->Draw("histsame");

  hfill[iDraw][2]->SetLineColor(kRed);
  hfill[iDraw][2]->Draw("histsame");

  hfill[iDraw][3]->SetLineColor(kViolet);
  hfill[iDraw][3]->Draw("histsame");

  hfill[iDraw][4]->SetLineColor(kGreen+2);
  hfill[iDraw][4]->Draw("histsame");

  if (SignalOnly==1){
    hfill[iDraw][5]->SetLineColor(kBlue);
    hfill[iDraw][5]->Draw("histsame");

    hfill[iDraw][6]->SetLineColor(kRed);
    hfill[iDraw][6]->Draw("histsame");

    hfill[iDraw][7]->SetLineColor(kViolet);
    hfill[iDraw][7]->Draw("histsame");

    hfill[iDraw][8]->SetLineColor(kGreen+2);
    hfill[iDraw][8]->Draw("histsame");
  }

  if (SignalOnly==0){
    hfill[1][0]->SetLineColor(kBlack);
    hfill[1][0]->SetLineStyle(3);
    hfill[1][0]->Draw("histsame");
  }

  hfill[iDraw][0]->Draw("histsame");

  TLegendEntry* legendtext;
  if (SignalOnly==0){
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM total", "f");
    legendtext = ll->AddEntry(hfill[1][0], "SM bkg.", "f");
    legendtext->SetFillStyle(1001);
    legendtext->SetFillColor(hfill[1][0]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM signal", "f");
    legendtext->SetFillStyle(3001);
  }

  if (SignalOnly==0){
    legendtext = ll2->AddEntry(hfill[iDraw][4], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[4].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][2], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[2].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][1], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[1].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][3], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[3].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][4], strACtitle[4].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][2], strACtitle[2].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][1], strACtitle[1].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][3], strACtitle[3].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  if (SignalOnly==1){
    legendtext = ll2->AddEntry(hfill[iDraw][8], strACtitle[8].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][8]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][5], strACtitle[5].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][5]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][7], strACtitle[7].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][7]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][6], strACtitle[6].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][6]->GetFillColor());
  }

  ll->Draw("same");
  ll2->Draw("same");
  ptx->Draw();
  pt->Draw();
  cc->RedrawAxis();
  cc->Update();

  canvasname.Prepend(coutput_common);
  TString canvasname_pdf = canvasname;
  TString canvasname_eps = canvasname;
  TString canvasname_png = canvasname;
  TString canvasname_root = canvasname;
  TString canvasname_c = canvasname;
  canvasname_pdf.Append(".pdf");
  canvasname_eps.Append(".eps");
  canvasname_png.Append(".png");
  canvasname_root.Append(".root");
  canvasname_c.Append(".C");
  cc->SaveAs(canvasname_pdf);
  cc->SaveAs(canvasname_eps);
  cc->SaveAs(canvasname_png);
  cc->SaveAs(canvasname_root);
  cc->SaveAs(canvasname_c);

  foutput->WriteTObject(cc);
  delete ll2;
  delete ll;
  cc->Close();
  delete ptx;
  delete pt;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<5; ac++){
      foutput->WriteTObject(hfill[t][ac]);
      delete hfill[t][ac];
    }
  }
  foutput->Close();
}
void plotphi(int top, bool phi=kFALSE){
  if (setup("vm","","pol__")==kFALSE) return;
  gStyle->SetOptFit(1111); //pcev = 1111
  //gStyle->SetTitleW(1.5);

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

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

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

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

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

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

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

      //! Draw histograms
      TCanvas *c = new TCanvas(hpos->GetName(),hpos->GetName(),900, 600);
      c->Divide(3,1);
      c->cd(1);
      hunp->Draw();
      ptunp->Draw();
      c->cd(2);
      hpos->Draw();
      ptpos->Draw();
      c->cd(3);
      hneg->Draw();
      ptneg->Draw();
      TString dir = TString::Format("./polobs/top%d/%s/Varset1/theta", top, Q2Wdirname.Data());
      gSystem->mkdir(dir,1);
      c->SaveAs(TString::Format("%s/%s.png", dir.Data(), c->GetName()));
      c->Close();
      c->Delete();
    }
  }
}
void advancedNoiseAnalysis( unsigned int runNumber, unsigned int loop = 1) {
  
  string inputFileName = "./histo/run00" + toString( runNumber ) + "-ped-histo.root";
  string outputFileName = "./histo/run00" + toString( runNumber ) + "-adv-noise.root";
  

  // before opening the input and the output files, try to see if they
  // are not opened yet and in case close them before continue   
  TList * listOfOpenedFile = (TList*) gROOT->GetListOfFiles();
  for ( int i = 0; i < listOfOpenedFile->GetSize() ; ++i ) {
    TFile * file = (TFile*) listOfOpenedFile->At( i ) ;
    TString fileName(file->GetName());
    TString inputFileName1( inputFileName.c_str() );
    TString outputFileName1( outputFileName.c_str() );

    if (  ( fileName.Contains( inputFileName1 ) ) ||
	  ( inputFileName1.Contains( fileName ) ) ||
	  ( fileName.Contains( outputFileName1 ) ) ||
	  ( outputFileName1.Contains( fileName ) ) ) {
      cout << "Closing " << fileName << " before reopen " << endl;
      file->Close();
    }
  }


  // close also all the previously opened canvas
  TList * listOfOpenedCanvas = (TList*) gROOT->GetListOfCanvases();
  for ( int i = 0 ; i < listOfOpenedCanvas->GetSize() ; ++i ) {
    TCanvas * canvas = (TCanvas*) listOfOpenedCanvas->At( i );
    TString canvasName2 = canvas->GetName();
    if ( canvasName2.Contains( "det" ) ) {
      canvas->Close();
    }
  }

	 
  // now safely open the file
  TFile * inputFile = TFile::Open( inputFileName.c_str() ) ;
  TFile * outputFile = TFile::Open( outputFileName.c_str(), "RECREATE") ;
  TList * outputHistoList = new TList;

  // look into the inputFile for a folder named
  string pedeProcessorFolderName = "PedestalAndNoiseCalculator";
  TDirectoryFile * pedeProcessorFolder = (TDirectoryFile*) inputFile->Get( pedeProcessorFolderName.c_str() );
  
  if ( pedeProcessorFolder == 0 ) { 
    cerr << "No pedestal processor folder found in file " << inputFileName << endl;
    return ;
  }

  // this folder should contain one folder for each loop.
  string loopFolderName = "loop-" + toString( loop );
  TDirectoryFile * loopFolder = (TDirectoryFile *) pedeProcessorFolder->Get( loopFolderName.c_str() );
  
  if ( loopFolder == 0 ) {
    cerr << "No " << loopFolderName << " found in file " << inputFileName << endl;
    return ;
  }

  // guess the number of sensors from the number of subfolder in the loopfolder
  size_t nDetector = loopFolder->GetListOfKeys()->GetSize();
  cout << "This file contains " << nDetector << " detectors" << endl;

  // prepare arrays to store the mean and the rms of the noise distribution
  if ( noiseMean == NULL ) {
    delete [] noiseMean;
    noiseMean = NULL;
  }
  if ( noiseRMS == NULL ) {
    delete [] noiseRMS;
    noiseRMS = NULL;
  }
  if ( channel == NULL ) {
    delete [] channel;
    channel = NULL;
  }

  noiseMean = new double[ nDetector * kNChan ];
  noiseRMS  = new double[ nDetector * kNChan ];
  channel   = new double[ kNChan ];

  string canvasName = "comparison";
  string canvasTitle = "Noise comparison";

  TCanvas * comparisonCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  comparisonCanvas->Divide(1,2);
  
  TPad * topPad = (TPad*) comparisonCanvas->cd(1);
  topPad->Divide( nDetector );
  
  TPad * middlePad = (TPad *) comparisonCanvas->cd(2);
  middlePad->Divide( kNChan );


  // for each detector we have to get the noise map and to prepare 4
  // separe histos and maps
  for ( unsigned int iDetector = 0; iDetector < nDetector; iDetector++ ) {

    // get the noise map.
    string noiseMapName = "detector-" + toString( iDetector ) ;
    noiseMapName += "/NoiseMap-d" + toString( iDetector )  ;
    noiseMapName += "-l" + toString( loop ) ;
 
    TH2D * noiseMap = ( TH2D* ) loopFolder->Get( noiseMapName.c_str() ); 
    

    // create a folder in the output file
    TDirectory * subfolder = outputFile->mkdir( string( "detector_" + toString( iDetector ) ).c_str(),
						string( "detector_" + toString( iDetector ) ).c_str()
						);
    subfolder->cd();

    
    string canvasName = "det" + toString( iDetector );
    string canvasTitle = "Detector " + toString( iDetector );
    
    TCanvas * canvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
    canvas->Divide( kNChan, 2 );

    // ok now start the loop on channels
    for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) { 
	
      if ( iDetector == 0 ) channel[iChan] = iChan - 0.5;

      string tempName = "NoiseMap_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      string tempTitle = "NoiseMap Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ;

      TH2D * noiseMapCh = new TH2D ( tempName.c_str() , tempTitle.c_str(), 
				     kXPixel / kNChan , -0.5 + xLimit[ iChan ] , -0.5 + xLimit[ iChan + 1 ],
				     kYPixel, -0.5, -0.5 + kYPixel );
      noiseMapCh->SetXTitle("X [pixel]");
      noiseMapCh->SetYTitle("Y [pixel]");
      noiseMapCh->SetZTitle("Noise [ADC]");
      noiseMapCh->SetStats( false );
      outputHistoList->Add( noiseMapCh ) ;

      tempName = "NoiseDist_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      
      tempTitle = "NoiseDist Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ; 

      TH1D * noiseDistCh = new TH1D( tempName.c_str(), tempTitle.c_str(), 50, 0., 10. );
      noiseDistCh->SetXTitle("Noise [ADC]");
      noiseDistCh->SetLineColor( kColor[iDetector]  );
      noiseDistCh->SetLineStyle( iChan + 2 );
      noiseDistCh->SetLineWidth( 2 );
      outputHistoList->Add( noiseDistCh );

      // let's start looping on pixels now
      for ( size_t yPixel = 1 ; yPixel <= kYPixel ; ++yPixel ) {
	for ( size_t xPixel = xLimit[ iChan ] + 1; xPixel <= xLimit[ iChan +1 ] ; ++xPixel ) {
	  double noise = noiseMap->GetBinContent( xPixel , yPixel );
	  noiseMapCh->Fill( xPixel - 1 , yPixel - 1, noise );
	  noiseDistCh->Fill( noise );
	  
	}
      }

      canvas->cd( iChan + 1 ) ;
      noiseMapCh->Draw("colz");
      canvas->cd( iChan + kNChan + 1  );
      noiseDistCh->Draw();
      
      topPad->cd( iDetector + 1 );
      if ( iChan == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }

      middlePad->cd( iChan + 1 );
      if ( iDetector == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }


      noiseMean[ kNChan * iDetector + iChan ] = noiseDistCh->GetMean();
      noiseRMS[ kNChan * iDetector  + iChan ] = noiseDistCh->GetRMS();
    }
    canvas->Write();

  }

  canvasName = "summary";
  canvasTitle = "Noise summary";

  TCanvas * summaryCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  summaryCanvas->SetGridx(1);
  TLegend * legend = new TLegend(0.5, 4.8, 1.5, 4.3,"","br");;
  

  for ( size_t iDetector = 0 ; iDetector < nDetector ; ++iDetector ) {
    
    TGraphErrors * gr = new TGraphErrors( kNChan, channel, &noiseMean[ iDetector * kNChan ], NULL, &noiseRMS[ iDetector * kNChan ] );
    gr->SetName( string( "NoisePerChannel_d" + toString( iDetector )).c_str());
    gr->SetTitle(string("Detector " + toString( iDetector )).c_str());
    gr->GetXaxis()->SetTitle("Channel #");
    gr->GetYaxis()->SetTitle("Noise [ADC]");
    gr->GetXaxis()->SetNdivisions( 5 );
    gr->GetXaxis()->SetLabelSize( 0 );
    gr->SetMarkerStyle( iDetector + 1 );
    gr->SetMarkerColor( kColor[iDetector] );
    gr->SetLineColor( kColor[iDetector] );
    gr->SetLineWidth( 2 );

    
    legend->AddEntry( gr, string("Detector " + toString( iDetector )).c_str(), "LP");

    if ( iDetector == 0 ) {
      gr->Draw("ALP");
    } else {
      gr->Draw("LP");
    }
    

  }

  
  
  legend->Draw();

  for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) {
    
    TPaveLabel * label = new TPaveLabel( iChan - 0.75 , 3.2 , iChan -0.25 , 3, string("Ch " + toString( iChan ) ).c_str());
    label->Draw();
  }


  summaryCanvas->Write();
  comparisonCanvas->Write();

  outputHistoList->Write();

  

 
} 
Esempio n. 18
0
void LeakageSubtractor(const std::vector<float> *time, std::vector<float> *cathode, const std::vector<float> *hv, const std::vector<float> *led, std::string file, std::vector<float>& cathode_out, chi2& fit ){

// 1 -> tries different values
// 2 -> uses the value of the last fit as input to the next
int type_minimization = 2;

string str_volt;

gStyle->SetOptFit(1);
int skipAtLedChange = 4;
int size = 0;
float chi2 = 0;
int spike = 0;

std::vector<float> cathode_ye;

float error = (0.5/16.6)*10E-12;

size = cathode->size(); //the number pf voltages stored in the cathode vector
//cout << "size: " << size<< endl;
  
//declare the values of the voltage to fit
std::vector<double> fitX;
std::vector<double> fitXe;
std::vector<double> fitY;
std::vector<double> fitYe;

//int nstep = 7;
int step[7]={800, 900, 1000, 1200, 1400, 1600, 1800}; 
//write the endex of the beginning and the end of the hv regions into an array
int voltageStep[7] = {0,0,0,0,0,0,0};
int index_begin[7] = {0,0,0,0,0,0,0};
int index_end[7] = {0,0,0,0,0,0,0};
int istep, i; 

int fcount=0;
bool repeate=true;
double ini1[5] = {1.0e-12, 1.0e-11, 1.0e-10, 1.0e-9, 1.0e-8};
double shifts_begin[8] = {0, 50, 100, 150, 200, 250, 300, 350};
double shifts_end[6] = {0, 50, 100, 150, 200, 250};
double ini3[5] = {100, 200, 300, 400, 500};
double ini2[6] = {1.0e-12, 1.0e-11, 1.0e-10, 1.0e-9, 1.0e-8, 1.0e-7};
int ini2_count = 0;
int ini3_count = 0;
int begin_count = 0;
int end_count = 0;
float better_chi2 = 0.0;
int better[5] = {0, 0, 0, 0};
double par[3] = {0, 0, 0};

  for (i = 0; i < size; i++)
  {
    cathode_ye.push_back(error);
    cathode_out.push_back(cathode->at(i));
  }


  //for (i = 0; i < size-1; i++)
  //{
  //  cout << i << " " << size << " " << time->at(i) << " " << hv->at(i) << " " << led->at(i) << " " << cathode->at(i) << endl;
  //}


  //the different hight voltage steps in volt

   for(istep = 0; istep < 7; istep++){
    int index1 = 1;
    int index2 = 1;
    
    //cout<<"trying voltage: "<<step[istep]<<endl;
    
    while((abs(hv->at(index1-1)) > step[istep] + 20 or abs(hv->at(index1-1)) < step[istep] - 20) and index1 < size-1){
      index1++;
      //cout << "begin " <<index1-1 << " " << size << " " << abs(hv->at(index1-1)) << endl;
    }
    //cout << "out of begin" << endl;
    index_begin[istep] = index1;
    //cout << "index_begin " <<index_begin[istep] << endl;
    if (index1 < size) { index2 = index1;
    while((abs(hv->at(index2)) < step[istep] + 20 and abs(hv->at(index2)) > step[istep] - 20) and index2 < size-1){
      index2++;
      //cout << "end " << index2 << " " << size << " " << abs(hv->at(index2)) << endl;
    }
    index_end[istep] = index2;
    //cout << "index_end " << index_end[istep] << endl;
    }
    voltageStep[istep] = index_end[istep] - index_begin[istep];
    //cout << "voltage Step " << voltageStep[istep] << endl;
   //write the voltages into the vector
   // copy the x,y values for one voltage set and only where LED was off 
     
     
   if (voltageStep[istep] > 20)
   {      
    for(i = index_begin[istep]; i < index_end[istep]; i++){
    if (i < size - skipAtLedChange)
    {
    //cout << i << " " << size << " " << time->at(i) << " " << led->at(i) << " " << hv->at(i) << " " << cathode->at(i) << " " << cathode_ye[i] << endl;
    spike_check(i, cathode, spike);
     if(led->at(i) == 0 && led->at(i-skipAtLedChange) == 0 && led->at(i+skipAtLedChange) == 0 && abs(hv->at(i)) < step[istep] + 20 && abs(hv->at(i)) > step[istep] - 20 && cathode->at(i) > 0 && spike == 0){
     	  //cout << "in" << endl;
          if (time->at(i) < 0) { cout << "warning: negative time " << i << " " << time->at(i) << endl; }   
          fitX.push_back(time->at(i)); 
	  fitY.push_back(cathode->at(i));
          fitYe.push_back(cathode_ye[i]);
          fitXe.push_back(0.);
    }
    spike = 0;
    }
   }
	// cout << "========" << hv[index_begin[istep]] << "===========" << endl


   // TGraphErrors has to be defined befor TF1 (the fit function)
   TGraphErrors *gc0 = new TGraphErrors(fitX.size(),&fitX.front(),&fitY.front(),NULL,&fitYe.front());

	TCanvas * c = new TCanvas("c","c",800,600);
      	//gPad->SetLogy();
	str_volt = str_volt + ";Time [s];Current [V]";
	TF1 *ff = 0;

    TVirtualFitter::SetMaxIterations(3000);

if (type_minimization == 2)
{
	float par_temp[3] = {1e-9, 1e-7, 300.};
	par[0] = 0;
	par[1] = 0;
	par[2] = 0;
	int max_tries = 70;
	int tries = 0;

while (repeate && tries < max_tries && fitX.size() > 100) {

	//cout << "fcount = " << fcount << " begin_count = " << begin_count << "end_count = " << end_count << endl;
      ff = new TF1("ff", fexp, time->at(index_begin[istep]) + 100, time->at(index_end[istep]) - 50, 3);
      ff->SetLineColor(4);
      ff->SetParameter(0, par_temp[0]);
      ff->SetParameter(1, par_temp[1]);
      ff->SetParameter(2, par_temp[2]);
      //cout << "ini par[1] = " << ini1[fcount] << " begin_shift = " << shifts_begin[begin_count] << " end_shift = " << - shifts_end[end_count] << endl;
      gc0->Fit("ff","ERQ");
      //cout << "=> " << gMinuit->fCstatu.Data() << endl;
      chi2 = ff->GetChisquare()/float(ff->GetNDF());
      //cout << "chi2 = " << chi2 << endl;
      repeate = ( (gMinuit->fCstatu.Data()[0]!='S') || (ff->GetParameter(1)<0) || (ff->GetParameter(0)<0) || chi2 > 2.0);
	
	if (better_chi2 == 0.0 and gMinuit->fCstatu.Data()[0]=='S' and ff->GetParameter(1)>0 and ff->GetParameter(0)>0)
	{
	better_chi2 = chi2;
	par[0] = ff->GetParameter(0);
	par[1] = ff->GetParameter(1);
	par[2] = ff->GetParameter(2);
	par_temp[0] = ff->GetParameter(0);
	par_temp[1] = ff->GetParameter(1);
	par_temp[2] = ff->GetParameter(2);
	//cout << "Chi2 of the first approach = " << chi2 << endl;
	}
	if (better_chi2 > chi2 and gMinuit->fCstatu.Data()[0]=='S' and ff->GetParameter(1)>0 and ff->GetParameter(0)>0)
	{
	//cout << "ini par = " << ini1[fcount] << " begin_shift = " << shifts_begin[begin_count] << " end_shift = " << - shifts_end[end_count] << " ini3 = " << ini3[ini3_count]<< endl;
	//cout << "=> " << gMinuit->fCstatu.Data() << endl;
	//cout << "chi2 = " << chi2 << endl;
	better_chi2 = chi2;
	par[0] = ff->GetParameter(0);
	par[1] = ff->GetParameter(1);
	par[2] = ff->GetParameter(2);
	par_temp[0] = ff->GetParameter(0);
	par_temp[1] = ff->GetParameter(1);
	par_temp[2] = ff->GetParameter(2);
	}
	else
	{
	if (tries%6 == 0) { par_temp[0] = par[0] * 1.1; }
	if (tries%6 == 1) { par_temp[0] = par[0] * 0.9; }
	if (tries%6 == 2) { par_temp[1] = par[1] * 1.1; }
	if (tries%6 == 3) { par_temp[1] = par[1] * 0.9; }
	if (tries%6 == 4) { par_temp[2] = par[2] * 1.1; }
	if (tries%6 == 5) { par_temp[2] = par[2] * 0.9; }
	}
	tries = tries + 1;
	//cout << tries << " > " << better_chi2 << " ~ " << par[0] << " ; " << par[1] << " ; " << par[2] << endl;
	}


if (type_minimization == 1 or chi2 > 5.0)
{

if (chi2 > chi2_threshold)
{
par[0] = 0.0;
par[1] = 0.0;
par[2] = 0.0;
better_chi2 = 0.0;
}

    while (repeate && fcount < 5 && begin_count < 8 && end_count < 6 && ini3_count < 5 && ini2_count < 6 && fitX.size() > 100) {

	//cout << "fcount = " << fcount << " begin_count = " << begin_count << "end_count = " << end_count << endl;
      ff = new TF1("ff", fexp, time->at(index_begin[istep]) + shifts_begin[begin_count], time->at(index_end[istep]) - shifts_end[end_count], 3);
      ff->SetLineColor(3);

      ff->SetParameter(0, ini1[fcount]);
      ff->SetParameter(1, ini2[ini2_count]);
      ff->SetParameter(2, ini3[ini3_count]);

      //cout << "ini par[1] = " << ini1[fcount] << " begin_shift = " << shifts_begin[begin_count] << " end_shift = " << - shifts_end[end_count] << endl;
      gc0->Fit("ff","ERQ");
      //cout << "=> " << gMinuit->fCstatu.Data() << endl;
      chi2 = ff->GetChisquare()/float(ff->GetNDF());
      //cout << "chi2 = " << chi2 << endl;
      repeate = ( (gMinuit->fCstatu.Data()[0]!='S') || (ff->GetParameter(1)<0) || (ff->GetParameter(0)<0) || chi2 > 2.0);
	
	if (better_chi2 == 0.0 and gMinuit->fCstatu.Data()[0]=='S' and ff->GetParameter(1)>0 and ff->GetParameter(0)>0)
	{
	better_chi2 = chi2;
	better[0] = fcount;
	better[1] = begin_count;
	better[2] = end_count;
	better[3] = ini3_count;
	better[4] = ini2_count;
	par[0] = ff->GetParameter(0);
	par[1] = ff->GetParameter(1);
	par[2] = ff->GetParameter(2);
	cout << "Chi2 of the first approach = " << chi2 << endl;
	}
	if (better_chi2 > chi2 and gMinuit->fCstatu.Data()[0]=='S' and ff->GetParameter(1)>0 and ff->GetParameter(0)>0)
	{
	//cout << "ini par = " << ini1[fcount] << " begin_shift = " << shifts_begin[begin_count] << " end_shift = " << - shifts_end[end_count] << " ini3 = " << ini3[ini3_count]<< endl;
	//cout << "=> " << gMinuit->fCstatu.Data() << endl;
	//cout << "chi2 = " << chi2 << endl;
	better_chi2 = chi2;
	better[0] = fcount;
	better[1] = begin_count;
	better[2] = end_count;
	better[3] = ini3_count;
	better[4] = ini2_count;
	par[0] = ff->GetParameter(0);
	par[1] = ff->GetParameter(1);
	par[2] = ff->GetParameter(2);
	}
	ini2_count++;
	if (ini2_count == 6) { ini3_count++; ini2_count = 0; }
	if (ini3_count == 5) { end_count++; ini3_count = 0; }
	if (end_count == 6) { begin_count++; end_count = 0; }
	if (begin_count == 8) { fcount++; begin_count = 0; }
	}

	if (better_chi2 > 2.0)
	{
	cout << "none of the fits was very good, using the best one!" << endl;
        int sb = shifts_begin[better[1]];
	int se = shifts_end[better[2]];
	float ig = ini1[better[0]];
	float i3 = ini3[better[3]];
	float i2 = ini2[better[4]];
	cout << better[0] << " " << better[1] << " " << better[2] << " " << better[3] << " " << better[4] << endl;
	cout << ig << " " << sb << " " << se << " " << i3 << " " << i2 << endl;
	ff = new TF1("ff", fexp, time->at(index_begin[istep]) + sb, time->at(index_end[istep]) - se, 3);
	ff->SetLineColor(2);
	if (better_chi2 < 15.0) { ff->SetLineColor(3); }
      	ff->SetParameter(0, ig);
	ff->SetParameter(1, i2);
      	ff->SetParameter(2, i3);
	gc0->Fit("ff","ERQ");
   	cout << "=> " << gMinuit->fCstatu.Data() << endl;
      	chi2 = ff->GetChisquare()/float(ff->GetNDF());
	if (chi2 < chi2_threshold and gMinuit->fCstatu.Data()[0]=='S' and ff->GetParameter(1)>0 and ff->GetParameter(0)>0)
        {
        ff->SetLineColor(3);
	better_chi2 = chi2;
	par[0] = ff->GetParameter(0);
	par[1] = ff->GetParameter(1);
	par[2] = ff->GetParameter(2);
	}
	else
	{
        cout << "the fit was bad!" << endl;
	}
      	cout << "chi2 = " << chi2 << endl;
	}
}


	cout << "parameters : " << par[0] << " " << par[1] << " " << par[2] << endl;
	
	if (better_chi2 < chi2_threshold and better_chi2 != 0.0 and par[0]>0 ) // and par[1]>0)
	{
	cout<<"good fit = " << better_chi2 << " subtracting backgroung now!" << endl;
	for (i = index_begin[istep]; i < index_end[istep]; i++)
  	{
  	double t = time->at(i);
  	double val = cathode->at(i) - fexp(&t, par); 
    	cathode_out.at(i) = val;
  	}
	}
	else
	{
	cout << "The fit was bad, no background subtraction will be done" << endl;
	}
}	

	if (chi2 == 0) { cout << "No fit was sucessfull at all!" << endl; chi2 = 1000; }
      	str_volt = "unknownvoltage";
      	if (hv->at(index_begin[istep]) > -820 and hv->at(index_begin[istep]) < -780)
	{ fit.c_800V = chi2; str_volt = "800V"; }
      	if (hv->at(index_begin[istep]) > -920 and hv->at(index_begin[istep]) < -880)
	{ fit.c_900V = chi2; str_volt = "900V"; }
      	if (hv->at(index_begin[istep]) > -1020 and hv->at(index_begin[istep]) < -980)
	{ fit.c_1000V = chi2; str_volt = "1000V"; }
      	if (hv->at(index_begin[istep]) > -1220 and hv->at(index_begin[istep]) < -1180)
	{ fit.c_1200V = chi2; str_volt = "1200V"; }
      	if (hv->at(index_begin[istep]) > -1420 and hv->at(index_begin[istep]) < -1380)
	{ fit.c_1400V = chi2; str_volt = "1400V"; }
      	if (hv->at(index_begin[istep]) > -1620 and hv->at(index_begin[istep]) < -1580)
	{ fit.c_1600V = chi2; str_volt = "1600V"; }
      	if (hv->at(index_begin[istep]) > -1820 and hv->at(index_begin[istep]) < -1780)
	{ fit.c_1800V = chi2; str_volt = "1800V"; }

        gc0->SetTitle(str_volt.c_str());
	gc0->SetMaximum(2*par[0]);
	gc0->SetMinimum(0);
      	gc0->Draw("AP");
        c->Print(file.c_str());
	c->Close();


	par[0] = 0.0;
	par[1] = 0.0;
	par[2] = 0.0;
	better_chi2 = 0.0;
	better[0] = 0;
	better[1] = 0;
	better[2] = 0;
	better[3] = 0;
	fcount = 0;
	repeate = true;
	ini3_count = 0;
	begin_count = 0;
	end_count = 0;
	delete(gc0);
	fitX.clear(); 
	fitY.clear();
        fitYe.clear();
        fitXe.clear();
       }
       else
       { cout << "voltage not found!" << endl;
       }
 
}

  //for (i = 0; i < size; ++i)
  //{
  //  cathode_out.push_back(cathode->at(i));
  //}

}
Esempio n. 19
0
int main(int argc, char **argv) {

  // This allows you to view ROOT-based graphics in your C++ program
  // If you don't want view graphics (eg just read/process/write data files), 
  // this can be ignored
  TApplication theApp("App", &argc, argv);

  TCanvas* canvas = new TCanvas();
  // ***************************************
  // not important for this exmple
  // Set a bunch of parameters to make the plot look nice
  canvas->SetFillColor(0);
  canvas->UseCurrentStyle();
  canvas->SetBorderMode(0);        // still leaves red frame bottom and right
  canvas->SetFrameBorderMode(0);   // need this to turn off red hist frame!
  gROOT->SetStyle("Plain");
  canvas->UseCurrentStyle();
  gROOT->ForceStyle();
  canvas->Divide(2, 1);

  gStyle->SetOptStat(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetTitleSize(0.04);
  gStyle->SetTitleFont(42, "hxy");      // for histogram and axis titles
  gStyle->SetLabelFont(42, "xyz");      // for axis labels (values)
  gROOT->ForceStyle();
  // ***************************************

  TFile *f=new TFile("fitInputs.root");
  TH2F *hist1 = (TH2F*)f->Get("hdata");
  TH2F *hback = (TH2F*)f->Get("hbkg"); 
 
  double xmin = 0.0;
  double xmax = 6.0;
  double ymin = 0.0;
  double ymax=6.0;  
  // Initialize minuit, set initial values etc. of parameters.
  const int npar = 6;              // the number of parameters
 
  TMinuit minuit(npar);
  minuit.SetFCN(fcn);              // the fcn to be minized 
  // (eg calculates chi^2 or NLL, not the
  // parameterization of the data!


  TF2* myfunc = new TF2("myfunc", gausPdf, xmin, xmax, ymin, ymax, npar);  
  // use this to fit the data and get results
  double par[npar];               // the start values
  double stepSize[npar];          // step sizes 
  double minVal[npar];            // minimum bound on parameter 
  double maxVal[npar];            // maximum bound on parameter
  TString parName[npar];

  par[0] = hback->GetMaximum();       // guesses for starting the fit
  par[1] = hist1->GetMaximum();                     
  par[2] = 3.555;                     //use mean and rms values from histogram
  par[3] = 1.17;                      //as initial guesses for parameters 
  par[4] = 1.879;
  par[5] = 1.229;
  stepSize[0] = TMath::Abs(par[0]*0.1);   
  stepSize[1] = TMath::Abs(par[1]*0.1);   // step size MUST be positive!
  stepSize[2] = TMath::Abs(par[2]*0.1);
  stepSize[3] = TMath::Abs(par[3]*0.1);
  stepSize[4] = TMath::Abs(par[4]*0.1);
  stepSize[5] = TMath::Abs(par[5]*0.1);
  minVal[0] = 0;      // if min and max values = 0, parameter is unbounded.
  maxVal[0] = 0;
  minVal[1] = 0; 
  maxVal[1] = 0;
  minVal[2] = 0;
  maxVal[2] = 6;
  minVal[3] = 0;
  maxVal[3] = 6;
  minVal[4] = 0;
  maxVal[4] = 6;
  minVal[5] = 0;
  maxVal[5] = 6;

  parName[0] = "Bkg";
  parName[1] = "A";
  parName[2] = "x0";
  parName[3] = "sigma_x";
  parName[4] = "y0";
  parName[5] = "sigma_y";

  for (int i=0; i<npar; i++){
    minuit.DefineParameter(i, parName[i].Data(), 
			   par[i], stepSize[i], minVal[i], maxVal[i]);
  }


  // here we define the pointers to pass information to Minuit's fcn
  // not pretty, but works well
  hdata=hist1;
  hback->Scale(1.0/3600.0); //scale over total number of entries first
  hb=hback;
  fparam=myfunc;

  // Do the minimization!
  minuit.Migrad();       // Minuit's best minimization algorithm
  double outpar[npar], err[npar];
  for (int i=0; i<npar; i++){
    minuit.GetParameter(i,outpar[i],err[i]);
  }
  TH2F *residual = new TH2F("residual", "Residuals Plot: data-fit", 
			    50, 0, 6, 50, 0, 6);
  myfunc->SetParameters(outpar);
  for (int i=1; i<=hist1->GetNbinsX(); i++){
    for(int j=1; j<=hist1->GetNbinsY(); j++){
      double x = hist1->GetBinCenter(i);
      double y = hist1->GetBinCenter(j);
      double f= myfunc->Eval(x, y);
      double r = hist1->GetBinContent(i, j) -f;
      residual->Fill(x, y, r);
    }
  }


  canvas->cd(1);
  residual->GetXaxis()->SetTitle("x");
  residual->GetYaxis()->SetTitle("y");
  residual->GetXaxis()->CenterTitle();
  residual->GetYaxis()->CenterTitle();
  residual->GetXaxis()->SetTitleOffset(1.25);
  residual->GetYaxis()->SetTitleOffset(1.25);
  residual->Draw("colz");
  canvas->cd(2);
  hist1->Add(hback, -outpar[0]);
  hist1->SetTitle("Data Signal with Fitted Background Subtracted");
  hist1->GetXaxis()->SetTitle("x");
  hist1->GetYaxis()->SetTitle("y");
  hist1->GetZaxis()->SetTitle("signal value");
  hist1->GetXaxis()->CenterTitle();
  hist1->GetYaxis()->CenterTitle();
  hist1->GetXaxis()->SetTitleOffset(1.25);
  hist1->GetYaxis()->SetTitleOffset(1.25);
  hist1->Draw("lego");

 
  cout << "To exit, quit ROOT from the File menu of the plot (or use control-C)" << endl;
  theApp.Run(true);
  canvas->Close();

  return 0;

}
Esempio n. 20
0
void drawCtauPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  int  nBins,           // Number of bins used for plotting
                  bool paperStyle=false,// if true, print less info
                  bool saveWS=true      // save the workspace into a file
                  ) 
{
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  
  // Create the main plot of the fit
  // RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(-1,3));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
    
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setRange(myws, frame, dsOSName, setLogScale, cut.dMuon.AbsRap.Min);
  if (paperStyle) {
     double Ydown = 0.1;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
     } else {
        t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.20, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;}
  else {t->DrawLatex(0.20, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;}
  t->DrawLatex(0.20, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.20, 0.86-dy, Form("%g < M^{#mu#mu} < %g GeV/c^{2}",cut.dMuon.M.Min,cut.dMuon.M.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.20, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  dy+=0.5*0.045; t->DrawLatex(0.20, 0.86-dy, "#mu in acceptance"); dy+=0.045;

  // Drawing the Legend
  double ymin = 0.7802;
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe");
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 


  // Save the plot in different formats
  gSystem->mkdir(Form("%splot/%s/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%splot/%s/root/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(),  "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%splot/%s/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%splot/%s/png/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%splot/%s/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%splot/%s/pdf/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
  
  // Save the workspace
  if (saveWS) {
     gSystem->mkdir(Form("%sresult/%s/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
     TFile *file = NULL;
     file = new TFile(Form("%sresult/%s/FIT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End), "RECREATE");  
     if (!file) { 
        cout << "[ERROR] Output root file with fit results could not be created!" << endl; 
     } else {
        file->cd();    
        myws.Write("workspace"); 
        file->Write(); file->Close(); delete file;
     }
  }
}
void Closure_corrected_comparestack(const char* titleh, const char* namevariable, const int rebin, const double x_min, const double x_max){

  // Usage is: .L comparestack.C++
  //       ie: comparestack("SelectedPhotons_Pt_1_", "p_{T}^{#gamma1} [GeV/#font[12]{c}]", 1);

	setMYStyle();

	// ==================================== choose the tools

	string folder = "Closure_22_results_2013_12_03";         // analysis folder

	char geo[100] = "barrel";                // "barrel", "endcaps" or "total"
	                                         
	bool logX = true;											   // log X scale for p_T plot	
	bool inv_sigmaietaieta = false;          // inverted sigmaietaieta cut
	bool inv_isolation = false;              // inverted isolation set cut

	bool signal_MAD = true;                  // true: signal = MADGRAPH; false: signal = PYTHIA
	bool background_QCD = false;             // true: background = MADGRAPH not filtered (QCD HT)
	                                         // false: background = PYTHIA filtered (QCD EMEnriched + BCtoE); 

	Int_t itype = 22;                        // it identifies histos with different analysis 


	// ==================================== string names

	stringstream ss_g;
	string Geo;
	ss_g << geo;
	ss_g >> Geo;
	string geo_s = Geo + "/";
	string folder_s = folder + "/";
	string SB_folder;
	if (signal_MAD && background_QCD) {
		SB_folder = "sM1_bQ1/";
	}
	else if (signal_MAD && !background_QCD) {
		SB_folder = "sM1_bQ0/";
	}
	else if (!signal_MAD && background_QCD) {
		SB_folder = "sM0_bQ1/";
	}
	else {
		SB_folder = "sM0_bQ0/";
	}
	string out_files = "output_files/";
	string pdf_folder = "pdf_plots/";
	string pdf_string = ".pdf";
	string root_folder = "root_plots/";
	string root_string = ".root";
	string txt_folder = "txt_plots/";
	string txt_string = ".txt";
	string inverted = "_inv";
	string sigmaietaieta_s = "_sigmaietaieta";
	string isolation_s = "_isolation";
	if (inv_sigmaietaieta && !inv_isolation) {
		root_string = inverted + sigmaietaieta_s + root_string;	
	}	
	else if (!inv_sigmaietaieta && inv_isolation) {
		root_string = inverted + isolation_s + root_string;
		}		
	else {
		root_string = root_string;
	}	
	
	stringstream ss_r;
	char root_char[200];
	ss_r << root_string;
	ss_r >> root_char;

	string address = folder_s + geo_s + out_files;


	// ==================================== exception controls

	if (inv_sigmaietaieta && inv_isolation){
		cout << "ERROR: you are trying to invert both SIGMAIETAIETA and ISOLATION cuts" << endl << endl;
		throw cms::Exception("WrongBool");
	}
	if (!(Geo == "barrel" || Geo == "endcaps" || Geo == "total")) {
		cout << "ERROR: Wrong geometry string (only \"barrel\" or \"endcaps\" or \"total\"). You wrote: \"" << geo << "\"" << endl << endl;
		throw cms::Exception("WrongString");
	}	


	// ==================================== assign files names

	Char_t PSEUDODATA_GJets_HT_40To100_name[100];
	Char_t PSEUDODATA_GJets_HT_100To200_name[100];	
	Char_t PSEUDODATA_GJets_HT_200To400_name[100];
	Char_t PSEUDODATA_GJets_HT_400ToInf_name[100];

	Char_t PSEUDODATA_DiPhotonJets_name[100];

	Char_t PSEUDODATA_QCD_Pt_20_30_EMEnriched_name[100];
	Char_t PSEUDODATA_QCD_Pt_30_80_EMEnriched_name[100];
	Char_t PSEUDODATA_QCD_Pt_80_170_EMEnriched_name[100];
	Char_t PSEUDODATA_QCD_Pt_170_250_EMEnriched_name[100];
	Char_t PSEUDODATA_QCD_Pt_250_350_EMEnriched_name[100];
	Char_t PSEUDODATA_QCD_Pt_350_EMEnriched_name[100];

	Char_t PSEUDODATA_QCD_Pt_20_30_BCtoE_name[100];
	Char_t PSEUDODATA_QCD_Pt_30_80_BCtoE_name[100];
	Char_t PSEUDODATA_QCD_Pt_80_170_BCtoE_name[100];
	Char_t PSEUDODATA_QCD_Pt_170_250_BCtoE_name[100];
	Char_t PSEUDODATA_QCD_Pt_250_350_BCtoE_name[100];
	Char_t PSEUDODATA_QCD_Pt_350_BCtoE_name[100];
					
	Char_t GJets_HT_40To100_name[100];
	Char_t GJets_HT_100To200_name[100];	
	Char_t GJets_HT_200To400_name[100];
	Char_t GJets_HT_400ToInf_name[100];

	Char_t G_Pt_15to30_name[100];
	Char_t G_Pt_30to50_name[100];
	Char_t G_Pt_50to80_name[100];
	Char_t G_Pt_80to120_name[100];	
	Char_t G_Pt_120to170_name[100];
	Char_t G_Pt_170to300_name[100];	
	Char_t G_Pt_300to470_name[100];
	Char_t G_Pt_470to800_name[100];
	Char_t G_Pt_800to1400_name[100];
	Char_t G_Pt_1400to1800_name[100];
	Char_t G_Pt_1800_name[100];

	Char_t DiPhotonJets_name[100];


	sprintf(PSEUDODATA_GJets_HT_40To100_name,"PSEUDODATA_MC_GJets_HT-40To100_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_GJets_HT_100To200_name,"PSEUDODATA_MC_GJets_HT-100To200_histos_%d_%s%s",itype, geo, root_char);	
	sprintf(PSEUDODATA_GJets_HT_200To400_name,"PSEUDODATA_MC_GJets_HT-200To400_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_GJets_HT_400ToInf_name,"PSEUDODATA_MC_GJets_HT-400ToInf_histos_%d_%s%s",itype, geo, root_char);

	cout << "PSEUDODATA GJets file 121 is: " << PSEUDODATA_GJets_HT_40To100_name << endl;
	cout << "PSEUDODATA GJets file 122 is: " << PSEUDODATA_GJets_HT_100To200_name << endl;	
	cout << "PSEUDODATA GJets file 123 is: " << PSEUDODATA_GJets_HT_200To400_name << endl;
	cout << "PSEUDODATA GJets file 124 is: " << PSEUDODATA_GJets_HT_400ToInf_name << endl;
	cout << endl;
	
	sprintf(PSEUDODATA_DiPhotonJets_name,"PSEUDODATA_MC_DiPhotonJets_histos_%d_%s%s",itype, geo, root_char);
	cout << "PSEUDODATA DiPhotonJets file 151 is: " << PSEUDODATA_DiPhotonJets_name << endl;
	cout << endl;

	sprintf(PSEUDODATA_QCD_Pt_20_30_EMEnriched_name,"PSEUDODATA_MC_QCD_Pt_20_30_EMEnriched_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_30_80_EMEnriched_name,"PSEUDODATA_MC_QCD_Pt_30_80_EMEnriched_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_80_170_EMEnriched_name,"PSEUDODATA_MC_QCD_Pt_80_170_EMEnriched_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_170_250_EMEnriched_name,"PSEUDODATA_MC_QCD_Pt_170_250_EMEnriched_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_250_350_EMEnriched_name,"PSEUDODATA_MC_QCD_Pt_250_350_EMEnriched_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_350_EMEnriched_name,"PSEUDODATA_MC_QCD_Pt_350_EMEnriched_histos_%d_%s%s",itype, geo, root_char);

	cout << "PSEUDODATA QCD EMEnriched file 161 is: " << PSEUDODATA_QCD_Pt_20_30_EMEnriched_name << endl;
	cout << "PSEUDODATA QCD EMEnriched file 162 is: " << PSEUDODATA_QCD_Pt_30_80_EMEnriched_name << endl;
	cout << "PSEUDODATA QCD EMEnriched file 163 is: " << PSEUDODATA_QCD_Pt_80_170_EMEnriched_name << endl;
	cout << "PSEUDODATA QCD EMEnriched file 164 is: " << PSEUDODATA_QCD_Pt_170_250_EMEnriched_name << endl;
	cout << "PSEUDODATA QCD EMEnriched file 165 is: " << PSEUDODATA_QCD_Pt_250_350_EMEnriched_name << endl;
	cout << "PSEUDODATA QCD EMEnriched file 166 is: " << PSEUDODATA_QCD_Pt_350_EMEnriched_name << endl;
	cout << endl;	
	
	sprintf(PSEUDODATA_QCD_Pt_20_30_BCtoE_name,"PSEUDODATA_MC_QCD_Pt_20_30_BCtoE_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_30_80_BCtoE_name,"PSEUDODATA_MC_QCD_Pt_30_80_BCtoE_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_80_170_BCtoE_name,"PSEUDODATA_MC_QCD_Pt_80_170_BCtoE_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_170_250_BCtoE_name,"PSEUDODATA_MC_QCD_Pt_170_250_BCtoE_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_250_350_BCtoE_name,"PSEUDODATA_MC_QCD_Pt_250_350_BCtoE_histos_%d_%s%s",itype, geo, root_char);
	sprintf(PSEUDODATA_QCD_Pt_350_BCtoE_name,"PSEUDODATA_MC_QCD_Pt_350_BCtoE_histos_%d_%s%s",itype, geo, root_char);

	cout << "PSEUDODATA QCD BCtoE file 171 is: " << PSEUDODATA_QCD_Pt_20_30_BCtoE_name << endl;
	cout << "PSEUDODATA QCD BCtoE file 172 is: " << PSEUDODATA_QCD_Pt_30_80_BCtoE_name << endl;
	cout << "PSEUDODATA QCD BCtoE file 173 is: " << PSEUDODATA_QCD_Pt_80_170_BCtoE_name << endl;
	cout << "PSEUDODATA QCD BCtoE file 174 is: " << PSEUDODATA_QCD_Pt_170_250_BCtoE_name << endl;
	cout << "PSEUDODATA QCD BCtoE file 175 is: " << PSEUDODATA_QCD_Pt_250_350_BCtoE_name << endl;
	cout << "PSEUDODATA QCD BCtoE file 176 is: " << PSEUDODATA_QCD_Pt_350_BCtoE_name << endl;	
	cout << endl;
	

	if(signal_MAD){
		sprintf(GJets_HT_40To100_name,"MC_GJets_HT-40To100_histos_%d_%s%s",itype, geo, root_char);
		sprintf(GJets_HT_100To200_name,"MC_GJets_HT-100To200_histos_%d_%s%s",itype, geo, root_char);	
		sprintf(GJets_HT_200To400_name,"MC_GJets_HT-200To400_histos_%d_%s%s",itype, geo, root_char);
		sprintf(GJets_HT_400ToInf_name,"MC_GJets_HT-400ToInf_histos_%d_%s%s",itype, geo, root_char);

		cout << "GJets file 21 is: " << GJets_HT_40To100_name << endl;
		cout << "GJets file 22 is: " << GJets_HT_100To200_name << endl;	
		cout << "GJets file 23 is: " << GJets_HT_200To400_name << endl;
		cout << "GJets file 24 is: " << GJets_HT_400ToInf_name << endl;
		cout << endl;
	}
	else {
		sprintf(G_Pt_15to30_name,"MC_G_Pt-15to30_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_30to50_name,"MC_G_Pt-30to50_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_50to80_name,"MC_G_Pt-50to80_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_80to120_name,"MC_G_Pt-80to120_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_120to170_name,"MC_G_Pt-120to170_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_170to300_name,"MC_G_Pt-170to300_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_300to470_name,"MC_G_Pt-300to470_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_470to800_name,"MC_G_Pt-470to800_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_800to1400_name,"MC_G_Pt-800to1400_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_1400to1800_name,"MC_G_Pt-1400to1800_histos_%d_%s%s",itype, geo, root_char);
		sprintf(G_Pt_1800_name,"MC_G_Pt-1800_histos_%d_%s%s",itype, geo, root_char);

		cout << "G file 31 is: " << G_Pt_15to30_name << endl;
		cout << "G file 32 is: " << G_Pt_30to50_name << endl;
		cout << "G file 33 is: " << G_Pt_50to80_name << endl;
		cout << "G file 34 is: " << G_Pt_80to120_name << endl;
		cout << "G file 35 is: " << G_Pt_120to170_name << endl;
		cout << "G file 36 is: " << G_Pt_170to300_name << endl;
		cout << "G file 37 is: " << G_Pt_300to470_name << endl;
		cout << "G file 38 is: " << G_Pt_470to800_name << endl;
		cout << "G file 39 is: " << G_Pt_800to1400_name << endl;
		cout << "G file 40 is: " << G_Pt_1400to1800_name << endl;
		cout << "G file 41 is: " << G_Pt_1800_name << endl;
		cout << endl;	
	}
	
	sprintf(DiPhotonJets_name,"MC_DiPhotonJets_histos_%d_%s%s",itype, geo, root_char);
	cout << "DiPhotonJets file 51 is: " << DiPhotonJets_name << endl;
	cout << endl;



	// ==================================== load TFiles

	TFile *PSEUDODATA_GJets_HT_40To100_file;
	TFile *PSEUDODATA_GJets_HT_100To200_file;	
	TFile *PSEUDODATA_GJets_HT_200To400_file;
	TFile *PSEUDODATA_GJets_HT_400ToInf_file;

	TFile *PSEUDODATA_DiPhotonJets_file;

	TFile *PSEUDODATA_QCD_Pt_20_30_EMEnriched_file; 
	TFile *PSEUDODATA_QCD_Pt_30_80_EMEnriched_file;
	TFile *PSEUDODATA_QCD_Pt_80_170_EMEnriched_file;
	TFile *PSEUDODATA_QCD_Pt_170_250_EMEnriched_file;
	TFile *PSEUDODATA_QCD_Pt_250_350_EMEnriched_file;
	TFile *PSEUDODATA_QCD_Pt_350_EMEnriched_file;

	TFile *PSEUDODATA_QCD_Pt_20_30_BCtoE_file; 
	TFile *PSEUDODATA_QCD_Pt_30_80_BCtoE_file;
	TFile *PSEUDODATA_QCD_Pt_80_170_BCtoE_file;
	TFile *PSEUDODATA_QCD_Pt_170_250_BCtoE_file;
	TFile *PSEUDODATA_QCD_Pt_250_350_BCtoE_file;
	TFile *PSEUDODATA_QCD_Pt_350_BCtoE_file;

	TFile *GJets_HT_40To100_file;
	TFile *GJets_HT_100To200_file;	
	TFile *GJets_HT_200To400_file;
	TFile *GJets_HT_400ToInf_file;

	TFile *G_Pt_15to30_file;
	TFile *G_Pt_30to50_file;
	TFile *G_Pt_50to80_file;
	TFile *G_Pt_80to120_file;
	TFile *G_Pt_120to170_file;
	TFile *G_Pt_170to300_file;
	TFile *G_Pt_300to470_file;
	TFile *G_Pt_470to800_file;
	TFile *G_Pt_800to1400_file;
	TFile *G_Pt_1400to1800_file;
	TFile *G_Pt_1800_file;

	TFile *DiPhotonJets_file;


	PSEUDODATA_GJets_HT_40To100_file = new TFile((address+PSEUDODATA_GJets_HT_40To100_name).c_str());	
	PSEUDODATA_GJets_HT_100To200_file = new TFile((address+PSEUDODATA_GJets_HT_100To200_name).c_str());	
	PSEUDODATA_GJets_HT_200To400_file = new TFile((address+PSEUDODATA_GJets_HT_200To400_name).c_str());
	PSEUDODATA_GJets_HT_400ToInf_file = new TFile((address+PSEUDODATA_GJets_HT_400ToInf_name).c_str()); 

	PSEUDODATA_DiPhotonJets_file = new TFile((address+PSEUDODATA_DiPhotonJets_name).c_str());
	
	PSEUDODATA_QCD_Pt_20_30_EMEnriched_file = new TFile((address+PSEUDODATA_QCD_Pt_20_30_EMEnriched_name).c_str()); 
	PSEUDODATA_QCD_Pt_30_80_EMEnriched_file = new TFile((address+PSEUDODATA_QCD_Pt_30_80_EMEnriched_name).c_str());
	PSEUDODATA_QCD_Pt_80_170_EMEnriched_file = new TFile((address+PSEUDODATA_QCD_Pt_80_170_EMEnriched_name).c_str());
	PSEUDODATA_QCD_Pt_170_250_EMEnriched_file = new TFile((address+PSEUDODATA_QCD_Pt_170_250_EMEnriched_name).c_str());
	PSEUDODATA_QCD_Pt_250_350_EMEnriched_file = new TFile((address+PSEUDODATA_QCD_Pt_250_350_EMEnriched_name).c_str());
	PSEUDODATA_QCD_Pt_350_EMEnriched_file = new TFile((address+PSEUDODATA_QCD_Pt_350_EMEnriched_name).c_str());

	PSEUDODATA_QCD_Pt_20_30_BCtoE_file = new TFile((address+PSEUDODATA_QCD_Pt_20_30_BCtoE_name).c_str()); 
	PSEUDODATA_QCD_Pt_30_80_BCtoE_file = new TFile((address+PSEUDODATA_QCD_Pt_30_80_BCtoE_name).c_str());
	PSEUDODATA_QCD_Pt_80_170_BCtoE_file = new TFile((address+PSEUDODATA_QCD_Pt_80_170_BCtoE_name).c_str());
	PSEUDODATA_QCD_Pt_170_250_BCtoE_file = new TFile((address+PSEUDODATA_QCD_Pt_170_250_BCtoE_name).c_str());
	PSEUDODATA_QCD_Pt_250_350_BCtoE_file = new TFile((address+PSEUDODATA_QCD_Pt_250_350_BCtoE_name).c_str());
	PSEUDODATA_QCD_Pt_350_BCtoE_file = new TFile((address+PSEUDODATA_QCD_Pt_350_BCtoE_name).c_str());
	
	if(signal_MAD){	
		GJets_HT_40To100_file = new TFile((address+GJets_HT_40To100_name).c_str());	
		GJets_HT_100To200_file = new TFile((address+GJets_HT_100To200_name).c_str());	
		GJets_HT_200To400_file = new TFile((address+GJets_HT_200To400_name).c_str());
		GJets_HT_400ToInf_file = new TFile((address+GJets_HT_400ToInf_name).c_str()); 
	}
	else {	
		G_Pt_15to30_file = new TFile((address+G_Pt_15to30_name).c_str());
		G_Pt_30to50_file = new TFile((address+G_Pt_30to50_name).c_str());
		G_Pt_50to80_file = new TFile((address+G_Pt_50to80_name).c_str());
		G_Pt_80to120_file = new TFile((address+G_Pt_80to120_name).c_str());
		G_Pt_120to170_file = new TFile((address+G_Pt_120to170_name).c_str());
		G_Pt_170to300_file = new TFile((address+G_Pt_170to300_name).c_str());
		G_Pt_300to470_file = new TFile((address+G_Pt_300to470_name).c_str());
		G_Pt_470to800_file = new TFile((address+G_Pt_470to800_name).c_str());
		G_Pt_800to1400_file = new TFile((address+G_Pt_800to1400_name).c_str());
		G_Pt_1400to1800_file = new TFile((address+G_Pt_1400to1800_name).c_str());	
		G_Pt_1800_file = new TFile((address+G_Pt_1800_name).c_str());
	}

	DiPhotonJets_file = new TFile((address+DiPhotonJets_name).c_str());
	

	// ==================================== load TH1F

	Char_t titlehisto[100];

	strcpy(titlehisto,titleh);

	cout << "========================" <<endl;	
	cout << endl;	

	cout << "Analyzing Histogram " << titlehisto << endl;

	cout << endl;	
	cout << "========================" <<endl;	
	cout << endl;	

	TH1F *PSEUDODATA_GJets_HT_40To100_histo;
	TH1F *PSEUDODATA_GJets_HT_100To200_histo;
	TH1F *PSEUDODATA_GJets_HT_200To400_histo;
	TH1F *PSEUDODATA_GJets_HT_400ToInf_histo;
	TH1F *PSEUDODATA_GJets_HT_xToy_total_histo;

	TH1F *PSEUDODATA_DiPhotonJets_histo;
	TH1F *PSEUDODATA_DiPhotonJets_total_histo;

	TH1F *PSEUDODATA_QCD_Pt_20_30_EMEnriched_histo;
	TH1F *PSEUDODATA_QCD_Pt_30_80_EMEnriched_histo;
	TH1F *PSEUDODATA_QCD_Pt_80_170_EMEnriched_histo;
	TH1F *PSEUDODATA_QCD_Pt_170_250_EMEnriched_histo;
	TH1F *PSEUDODATA_QCD_Pt_250_350_EMEnriched_histo;
	TH1F *PSEUDODATA_QCD_Pt_350_EMEnriched_histo;
	TH1F *PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo;

	TH1F *PSEUDODATA_QCD_Pt_20_30_BCtoE_histo;
	TH1F *PSEUDODATA_QCD_Pt_30_80_BCtoE_histo;
	TH1F *PSEUDODATA_QCD_Pt_80_170_BCtoE_histo;
	TH1F *PSEUDODATA_QCD_Pt_170_250_BCtoE_histo;
	TH1F *PSEUDODATA_QCD_Pt_250_350_BCtoE_histo;
	TH1F *PSEUDODATA_QCD_Pt_350_BCtoE_histo;;
	TH1F *PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo;

	TH1F *PSEUDODATA_total_histo;

	TH1F *GJets_HT_40To100_histo;
	TH1F *GJets_HT_100To200_histo;
	TH1F *GJets_HT_200To400_histo;
	TH1F *GJets_HT_400ToInf_histo;
	TH1F *GJets_HT_xToy_total_histo;

	TH1F *G_Pt_15to30_histo;
	TH1F *G_Pt_30to50_histo;
	TH1F *G_Pt_50to80_histo;
	TH1F *G_Pt_80to120_histo;
	TH1F *G_Pt_120to170_histo;
	TH1F *G_Pt_170to300_histo;
	TH1F *G_Pt_300to470_histo;
	TH1F *G_Pt_470to800_histo;
	TH1F *G_Pt_800to1400_histo;
	TH1F *G_Pt_1400to1800_histo;
	TH1F *G_Pt_1800_histo;
	TH1F *G_Pt_XtoY_total_histo;

	TH1F *DiPhotonJets_histo;
	TH1F *DiPhotonJets_total_histo;

	
	//--- PSEUDODATA MC signal GJets_HT-xToy ----------------------------------------------

	PSEUDODATA_GJets_HT_40To100_histo=(TH1F*)PSEUDODATA_GJets_HT_40To100_file->Get(titlehisto);
	PSEUDODATA_GJets_HT_40To100_histo->Rebin(rebin);
		
	PSEUDODATA_GJets_HT_100To200_histo=(TH1F*)PSEUDODATA_GJets_HT_100To200_file->Get(titlehisto);
	PSEUDODATA_GJets_HT_100To200_histo->Rebin(rebin);

	PSEUDODATA_GJets_HT_200To400_histo=(TH1F*)PSEUDODATA_GJets_HT_200To400_file->Get(titlehisto);
	PSEUDODATA_GJets_HT_200To400_histo->Rebin(rebin);

	PSEUDODATA_GJets_HT_400ToInf_histo=(TH1F*)PSEUDODATA_GJets_HT_400ToInf_file->Get(titlehisto);
	PSEUDODATA_GJets_HT_400ToInf_histo->Rebin(rebin);

	cout << "PSEUDODATA_GJets_HT_40To100 entries = " << PSEUDODATA_GJets_HT_40To100_histo->Integral() << endl;
	cout << "PSEUDODATA_GJets_HT_100To200 entries = " << PSEUDODATA_GJets_HT_100To200_histo->Integral() << endl;	
	cout << "PSEUDODATA_GJets_HT_200To400 entries = " << PSEUDODATA_GJets_HT_200To400_histo->Integral() << endl;
	cout << "PSEUDODATA_GJets_HT_400ToInf entries = " << PSEUDODATA_GJets_HT_400ToInf_histo->Integral() << endl;
	cout << endl;
		
	PSEUDODATA_GJets_HT_xToy_total_histo = (TH1F*) PSEUDODATA_GJets_HT_40To100_histo->Clone("PSEUDODATA_GJets_HT_xToy_total_histo");
	//--- PSEUDODATA_GJets_HT_xToy_total_histo->Sumw2();
	PSEUDODATA_GJets_HT_xToy_total_histo->Add(PSEUDODATA_GJets_HT_100To200_histo);
	PSEUDODATA_GJets_HT_xToy_total_histo->Add(PSEUDODATA_GJets_HT_200To400_histo);
	PSEUDODATA_GJets_HT_xToy_total_histo->Add(PSEUDODATA_GJets_HT_400ToInf_histo);  
	PSEUDODATA_GJets_HT_xToy_total_histo->SetLineColor(1);
	PSEUDODATA_GJets_HT_xToy_total_histo->SetFillColor(5);  //for colors comment out Sumw2 in code
		
	// PSEUDODATA MC signal DiPhotonJets --------------------------------------------------
	PSEUDODATA_DiPhotonJets_histo=(TH1F*)PSEUDODATA_DiPhotonJets_file->Get(titlehisto);
	PSEUDODATA_DiPhotonJets_histo->Rebin(rebin);
	
	cout << "PSEUDODATA_DiPhotonJets entries = " << PSEUDODATA_DiPhotonJets_histo->Integral() << endl;
	cout << endl;

	PSEUDODATA_DiPhotonJets_total_histo = (TH1F*) PSEUDODATA_DiPhotonJets_histo->Clone("PSEUDODATA_DiPhotonJets_total_histo");
	//--- PSEUDODATA_DiPhotonJets_total_histo->Sumw2();
	PSEUDODATA_DiPhotonJets_total_histo->SetLineColor(1);
	PSEUDODATA_DiPhotonJets_total_histo->SetFillColor(kGray+2);  //for colors comment out Sumw2 in code

	//--- PSEUDODATA MC background QCD_Pt_x_y EMEnriched ----------------------------------	
	PSEUDODATA_QCD_Pt_20_30_EMEnriched_histo=(TH1F*)PSEUDODATA_QCD_Pt_20_30_EMEnriched_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_20_30_EMEnriched_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_30_80_EMEnriched_histo=(TH1F*)PSEUDODATA_QCD_Pt_30_80_EMEnriched_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_30_80_EMEnriched_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_80_170_EMEnriched_histo=(TH1F*)PSEUDODATA_QCD_Pt_80_170_EMEnriched_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_80_170_EMEnriched_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_170_250_EMEnriched_histo=(TH1F*)PSEUDODATA_QCD_Pt_170_250_EMEnriched_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_170_250_EMEnriched_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_250_350_EMEnriched_histo=(TH1F*)PSEUDODATA_QCD_Pt_250_350_EMEnriched_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_250_350_EMEnriched_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_350_EMEnriched_histo=(TH1F*)PSEUDODATA_QCD_Pt_350_EMEnriched_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_350_EMEnriched_histo->Rebin(rebin);

	cout << "PSEUDODATA_QCD_Pt_20_30_EMEnriched entries = " << PSEUDODATA_QCD_Pt_20_30_EMEnriched_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_30_80_EMEnriched entries = " << PSEUDODATA_QCD_Pt_30_80_EMEnriched_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_80_170_EMEnriched entries = " << PSEUDODATA_QCD_Pt_80_170_EMEnriched_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_170_250_EMEnriched entries = " << PSEUDODATA_QCD_Pt_170_250_EMEnriched_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_250_350_EMEnriched entries = " << PSEUDODATA_QCD_Pt_250_350_EMEnriched_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_350_EMEnriched entries = " << PSEUDODATA_QCD_Pt_350_EMEnriched_histo->Integral() << endl;
	cout << endl;

	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo = (TH1F*) PSEUDODATA_QCD_Pt_20_30_EMEnriched_histo->Clone("PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo");
	//	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Sumw2();
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Add(PSEUDODATA_QCD_Pt_30_80_EMEnriched_histo);
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Add(PSEUDODATA_QCD_Pt_80_170_EMEnriched_histo);  
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Add(PSEUDODATA_QCD_Pt_170_250_EMEnriched_histo);  
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Add(PSEUDODATA_QCD_Pt_250_350_EMEnriched_histo);  
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Add(PSEUDODATA_QCD_Pt_350_EMEnriched_histo);  
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->SetLineColor(1);
	PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->SetFillColor(kMagenta+2);


	//--- PSEUDODATA MC background PSEUDODATA_QCD_Pt_x_y BCtoE ----------------------------------
	PSEUDODATA_QCD_Pt_20_30_BCtoE_histo=(TH1F*)PSEUDODATA_QCD_Pt_20_30_BCtoE_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_20_30_BCtoE_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_30_80_BCtoE_histo=(TH1F*)PSEUDODATA_QCD_Pt_30_80_BCtoE_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_30_80_BCtoE_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_80_170_BCtoE_histo=(TH1F*)PSEUDODATA_QCD_Pt_80_170_BCtoE_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_80_170_BCtoE_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_170_250_BCtoE_histo=(TH1F*)PSEUDODATA_QCD_Pt_170_250_BCtoE_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_170_250_BCtoE_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_250_350_BCtoE_histo=(TH1F*)PSEUDODATA_QCD_Pt_250_350_BCtoE_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_250_350_BCtoE_histo->Rebin(rebin);

	PSEUDODATA_QCD_Pt_350_BCtoE_histo=(TH1F*)PSEUDODATA_QCD_Pt_350_BCtoE_file->Get(titlehisto);
	PSEUDODATA_QCD_Pt_350_BCtoE_histo->Rebin(rebin);

	cout << "PSEUDODATA_QCD_Pt_20_30_BCtoE entries = " << PSEUDODATA_QCD_Pt_20_30_BCtoE_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_30_80_BCtoE entries = " << PSEUDODATA_QCD_Pt_30_80_BCtoE_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_80_170_BCtoE entries = " << PSEUDODATA_QCD_Pt_80_170_BCtoE_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_170_250_BCtoE entries = " << PSEUDODATA_QCD_Pt_170_250_BCtoE_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_250_350_BCtoE entries = " << PSEUDODATA_QCD_Pt_250_350_BCtoE_histo->Integral() << endl;
	cout << "PSEUDODATA_QCD_Pt_350_BCtoE entries = " << PSEUDODATA_QCD_Pt_350_BCtoE_histo->Integral() << endl;
	cout << endl;

	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo = (TH1F*) PSEUDODATA_QCD_Pt_20_30_BCtoE_histo->Clone("PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo");
	//	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->Sumw2();
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->Add(PSEUDODATA_QCD_Pt_30_80_BCtoE_histo);
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->Add(PSEUDODATA_QCD_Pt_80_170_BCtoE_histo);  
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->Add(PSEUDODATA_QCD_Pt_170_250_BCtoE_histo);  
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->Add(PSEUDODATA_QCD_Pt_250_350_BCtoE_histo);  
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->Add(PSEUDODATA_QCD_Pt_350_BCtoE_histo);  
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->SetLineColor(1);
	PSEUDODATA_QCD_Pt_x_y_BCtoE_total_histo->SetFillColor(kBlue-7);

	PSEUDODATA_total_histo = (TH1F*) PSEUDODATA_GJets_HT_xToy_total_histo->Clone("PSEUDODATA_total_histo");
	PSEUDODATA_total_histo->Add(PSEUDODATA_DiPhotonJets_total_histo);
	PSEUDODATA_total_histo->Add(PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo);
	PSEUDODATA_total_histo->Add(PSEUDODATA_QCD_Pt_350_BCtoE_histo);
	
	if(signal_MAD){				
		//--- MC signal GJets_HT-xToy ----------------------------------------------

		GJets_HT_40To100_histo=(TH1F*)GJets_HT_40To100_file->Get(titlehisto);
		GJets_HT_40To100_histo->Rebin(rebin);
		
		GJets_HT_100To200_histo=(TH1F*)GJets_HT_100To200_file->Get(titlehisto);
		GJets_HT_100To200_histo->Rebin(rebin);

		GJets_HT_200To400_histo=(TH1F*)GJets_HT_200To400_file->Get(titlehisto);
		GJets_HT_200To400_histo->Rebin(rebin);

		GJets_HT_400ToInf_histo=(TH1F*)GJets_HT_400ToInf_file->Get(titlehisto);
		GJets_HT_400ToInf_histo->Rebin(rebin);

		cout << "GJets_HT_40To100 entries = " << GJets_HT_40To100_histo->Integral() << endl;
		cout << "GJets_HT_100To200 entries = " << GJets_HT_100To200_histo->Integral() << endl;	
		cout << "GJets_HT_200To400 entries = " << GJets_HT_200To400_histo->Integral() << endl;
		cout << "GJets_HT_400ToInf entries = " << GJets_HT_400ToInf_histo->Integral() << endl;
		cout << endl;
		
		GJets_HT_xToy_total_histo = (TH1F*) GJets_HT_40To100_histo->Clone("GJets_HT_xToy_total_histo");
		//--- GJets_HT_xToy_total_histo->Sumw2();
		GJets_HT_xToy_total_histo->Add(GJets_HT_100To200_histo);	
		GJets_HT_xToy_total_histo->Add(GJets_HT_200To400_histo);
		GJets_HT_xToy_total_histo->Add(GJets_HT_400ToInf_histo);  
		GJets_HT_xToy_total_histo->SetLineColor(1);
		GJets_HT_xToy_total_histo->SetFillColor(5);  //for colors comment out Sumw2 in code
	}

	else {	
		// MC signal G_Pt-XtoY --------------------------------------------------	
		G_Pt_15to30_histo=(TH1F*)G_Pt_15to30_file->Get(titlehisto);
		G_Pt_15to30_histo->Rebin(rebin);

		G_Pt_30to50_histo=(TH1F*)G_Pt_30to50_file->Get(titlehisto);
		G_Pt_30to50_histo->Rebin(rebin);

		G_Pt_50to80_histo=(TH1F*)G_Pt_50to80_file->Get(titlehisto);
		G_Pt_50to80_histo->Rebin(rebin);

		G_Pt_80to120_histo=(TH1F*)G_Pt_80to120_file->Get(titlehisto);
		G_Pt_80to120_histo->Rebin(rebin);

		G_Pt_120to170_histo=(TH1F*)G_Pt_120to170_file->Get(titlehisto);
		G_Pt_120to170_histo->Rebin(rebin);
	
		G_Pt_170to300_histo=(TH1F*)G_Pt_170to300_file->Get(titlehisto);
		G_Pt_170to300_histo->Rebin(rebin);

		G_Pt_300to470_histo=(TH1F*)G_Pt_300to470_file->Get(titlehisto);
		G_Pt_300to470_histo->Rebin(rebin);

		G_Pt_470to800_histo=(TH1F*)G_Pt_470to800_file->Get(titlehisto);
		G_Pt_470to800_histo->Rebin(rebin);

		G_Pt_800to1400_histo=(TH1F*)G_Pt_800to1400_file->Get(titlehisto);
		G_Pt_800to1400_histo->Rebin(rebin);

		G_Pt_1400to1800_histo=(TH1F*)G_Pt_1400to1800_file->Get(titlehisto);
		G_Pt_1400to1800_histo->Rebin(rebin);

		G_Pt_1800_histo=(TH1F*)G_Pt_1800_file->Get(titlehisto);
		G_Pt_1800_histo->Rebin(rebin);

		cout << "G_Pt_15to30 entries = " << G_Pt_15to30_histo->Integral() << endl;
		cout << "G_Pt_30to50 entries = " << G_Pt_30to50_histo->Integral() << endl;
		cout << "G_Pt_50to80 entries = " << G_Pt_50to80_histo->Integral() << endl;
		cout << "G_Pt_80to120 entries = " << G_Pt_80to120_histo->Integral() << endl;
		cout << "G_Pt_120to170 entries = " << G_Pt_120to170_histo->Integral() << endl;
		cout << "G_Pt_170to300 entries = " << G_Pt_170to300_histo->Integral() << endl;
		cout << "G_Pt_300to470 entries = " << G_Pt_300to470_histo->Integral() << endl;
		cout << "G_Pt_470to800 entries = " << G_Pt_470to800_histo->Integral() << endl;
		cout << "G_Pt_800to1400 entries = " << G_Pt_800to1400_histo->Integral() << endl;
		cout << "G_Pt_1400to1800 entries = " << G_Pt_1400to1800_histo->Integral() << endl;
		cout << "G_Pt_1800 entries = " << G_Pt_1800_histo->Integral() << endl;
		cout << endl;
	
		G_Pt_XtoY_total_histo = (TH1F*) G_Pt_15to30_histo->Clone("G_Pt_XtoY_total_histo");
		//--- G_Pt_XtoY_total_histo->Sumw2();
		G_Pt_XtoY_total_histo->Add(G_Pt_30to50_histo);
		G_Pt_XtoY_total_histo->Add(G_Pt_50to80_histo);  
		G_Pt_XtoY_total_histo->Add(G_Pt_80to120_histo);  
		G_Pt_XtoY_total_histo->Add(G_Pt_120to170_histo);  
		G_Pt_XtoY_total_histo->Add(G_Pt_170to300_histo);  
		G_Pt_XtoY_total_histo->Add(G_Pt_300to470_histo);  
		G_Pt_XtoY_total_histo->Add(G_Pt_470to800_histo);  		
		G_Pt_XtoY_total_histo->Add(G_Pt_800to1400_histo);
		G_Pt_XtoY_total_histo->Add(G_Pt_1400to1800_histo);	  	
		G_Pt_XtoY_total_histo->Add(G_Pt_1800_histo);	  	
		G_Pt_XtoY_total_histo->SetLineColor(1);
		G_Pt_XtoY_total_histo->SetFillColor(kGreen+2);  //for colors comment out Sumw2 in code
	}
	
	// MC signal DiPhotonJets --------------------------------------------------
	DiPhotonJets_histo=(TH1F*)DiPhotonJets_file->Get(titlehisto);
	DiPhotonJets_histo->Rebin(rebin);
	
	cout << "DiPhotonJets entries = " << DiPhotonJets_histo->Integral() << endl;
	cout << endl;

	DiPhotonJets_total_histo = (TH1F*) DiPhotonJets_histo->Clone("DiPhotonJets_total_histo");
	//--- DiPhotonJets_total_histo->Sumw2();
	DiPhotonJets_total_histo->SetLineColor(1);
	DiPhotonJets_total_histo->SetFillColor(kGray+2);  //for colors comment out Sumw2 in code



	// ==================================== print Entries number

	cout << "========================" <<endl;	
	cout << endl;
	
  double S, B, T, f;
	S = PSEUDODATA_GJets_HT_xToy_total_histo->Integral() + PSEUDODATA_DiPhotonJets_total_histo->Integral();
	B = PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->Integral() + PSEUDODATA_QCD_Pt_350_BCtoE_histo->Integral();
	T = PSEUDODATA_total_histo->Integral();
	f = S/T;

	cout << "PSEUDODATA Signal entries = " << S << endl;
	cout << "PSEUDODATA Background entries = "<< B << endl;
	cout << "PSEUDODATA Total entries = " << T << endl;
	cout << "PSEUDODATA Signal/Total = " << f << endl;
	cout << endl;

	double NumBins;
	NumBins = PSEUDODATA_total_histo->GetNbinsX();

	vector<double> Signal, Background, Total;
	for (int n = 1; n <= NumBins; n++) {
	 	double S_bin, B_bin, T_bin;
		S_bin = PSEUDODATA_GJets_HT_xToy_total_histo->GetBinContent(n) + PSEUDODATA_DiPhotonJets_total_histo->GetBinContent(n);
		B_bin = PSEUDODATA_QCD_Pt_x_y_EMEnriched_total_histo->GetBinContent(n) + PSEUDODATA_QCD_Pt_350_BCtoE_histo->GetBinContent(n);
		T_bin = PSEUDODATA_total_histo->GetBinContent(n);
		Signal.push_back(S_bin);
		Background.push_back(B_bin);
		Total.push_back(T_bin);
	}

	for (int k = 1; k < NumBins; k++) {
		cout << "Signal bin " << k << " = " << Signal.at(k) << endl; 
		cout << "Background bin " << k << " = " << Background.at(k) << endl; 
		cout << "Total bin " << k << " = " << Total.at(k) << endl; 
		cout << "Signal/Total bin " << k << " = " << Signal.at(k)/Total.at(k) << endl; 
		cout << "@@@@@@@@@@@@@@@@@@@@@@@" <<endl;	
	}

	cout << endl;
	if(signal_MAD) cout << "GJets total entries = " << GJets_HT_xToy_total_histo->Integral() << endl;  
	else cout << "G total entries = " << G_Pt_XtoY_total_histo->Integral() << endl;

	cout << endl;
	cout << "DiPhotonJets total entries = " << DiPhotonJets_total_histo->Integral() << endl;
	cout << endl;

	cout << "========================" <<endl;	
	cout << endl;
		
	// ==================================== load Canvas
	
  TCanvas *Canva = new TCanvas(titlehisto,titlehisto);  
	TPad* upperPad = new TPad("upperPad", "upperPad",.005, .25, .995, .995);
  TPad* lowerPad = new TPad("lowerPad", "lowerPad",.005, .005, .995, .2475);
  upperPad->Draw(); 			       
  lowerPad->Draw(); 

	THStack *MC_stack= new THStack();

	//signal
	MC_stack->Add(DiPhotonJets_total_histo);
	if(signal_MAD){
		MC_stack->Add(GJets_HT_xToy_total_histo);
	}
	else{
		MC_stack->Add(G_Pt_XtoY_total_histo);
	}

	TH1F *ratio_histo_NUM = new TH1F();
	ratio_histo_NUM = (TH1F*) PSEUDODATA_total_histo->Clone("ratio_histo_NUM");	
	ratio_histo_NUM->Sumw2();


	TH1F *ratio_histo_DEN = new TH1F;
	ratio_histo_DEN = (TH1F*) DiPhotonJets_total_histo->Clone("ratio_histo_DEN");
	if(signal_MAD){
		ratio_histo_DEN->Add(GJets_HT_xToy_total_histo);
	}
	else {
		ratio_histo_DEN->Add(G_Pt_XtoY_total_histo);	
	}
	ratio_histo_DEN->Sumw2();

	
	TH1F *ratio_histo = (TH1F*) ratio_histo_NUM->Clone("ratio_histo");
	ratio_histo->Sumw2();
	ratio_histo->Divide(ratio_histo_DEN);

	int Nbins;
	double X_min, X_max;

	Nbins = ratio_histo->GetNbinsX();

	// upper Pad
  upperPad->cd();

	if (x_min != -999 && x_max != -999){
		if (x_max == PSEUDODATA_total_histo->GetXaxis()->GetXmax()) X_max = x_max;
		else X_max = x_max - (x_max-x_min)/Nbins;
		if (x_min == PSEUDODATA_total_histo->GetXaxis()->GetXmin()) X_min = x_min;
		else X_min = x_min + (x_max-x_min)/Nbins;

		PSEUDODATA_total_histo->GetXaxis()->SetRangeUser(X_min,X_max);
	}
	
	PSEUDODATA_total_histo->SetMarkerSize(0.7);
	PSEUDODATA_total_histo->SetMarkerStyle(20);
	PSEUDODATA_total_histo->SetMinimum(0.1);
	PSEUDODATA_total_histo->Draw("E");

	if (x_min != -999 && x_max != -999){
		if (x_max == MC_stack->GetMaximum()) X_max = x_max;
		else X_max = x_max - (x_max-x_min)/Nbins;
		if (x_min == MC_stack->GetMinimum()) X_min = x_min;
		else X_min = x_min + (x_max-x_min)/Nbins;

		MC_stack->Draw("SAME");
		MC_stack->SetMinimum(X_min);
		MC_stack->SetMaximum(X_max);
	}
	
	MC_stack->Draw("SAME");
	PSEUDODATA_total_histo->Draw("ESAME");
	gPad->SetLogy();
	if (logX){
		gPad->SetLogx(); // for p_T plot	
	}	
	PSEUDODATA_total_histo->Draw("AXIS X+ Y+ SAME");
	PSEUDODATA_total_histo->Draw("AXIS SAME");
	PSEUDODATA_total_histo->GetXaxis()->SetTitle(namevariable);
	PSEUDODATA_total_histo->GetXaxis()->SetTitleSize(0.05);
	PSEUDODATA_total_histo->GetYaxis()->SetTitle("Events corrected");

	TLegend *leg =new TLegend(0.6525,0.6923,0.8322,0.8777);
	leg->SetFillColor(0); 
  leg->SetFillStyle(0); 
  leg->SetBorderSize(0);
 	leg->AddEntry(PSEUDODATA_total_histo,"Pseudo-Data","pL");
		if(signal_MAD){
		leg->AddEntry(GJets_HT_xToy_total_histo,"#gamma + jets","f");
	}
	else{
		leg->AddEntry(G_Pt_XtoY_total_histo,"#gamma + jets","f");
	}
	leg->AddEntry(DiPhotonJets_total_histo,"2#gamma + jets","f");
/*
	if (!background_QCD){
		leg->AddEntry(QCD_Pt_x_y_EMEnriched_total_histo,"QCD EM Enriched","f");
		leg->AddEntry(QCD_Pt_x_y_BCtoE_total_histo,"QCD b,c #rightarrow e","f");
	}
	else {
		leg->AddEntry(QCD_HT_xToy_total_histo,"QCD","f");
	}
*/
	leg->Draw();

  TPaveText* text_1 = new TPaveText(0.1194,0.9310,0.3313,0.9780,"NDC");
  text_1->SetFillColor(0);
  text_1->SetFillStyle(0);
  text_1->SetBorderSize(0);
  text_1->AddText("CMS Preliminary");
  text_1->SetTextAlign(11);
  text_1->Draw();

  TPaveText* text_2 = new TPaveText(0.5627,0.9310,0.8678,0.9780,"NDC");
  text_2->SetFillColor(0);
  text_2->SetFillStyle(0);
  text_2->SetBorderSize(0);
  text_2->AddText("#sqrt{s} = 8 TeV, L = 19.71 fb^{-1}");
  text_2->SetTextAlign(11);
  text_2->Draw();

	
	// lower Pad
	lowerPad-> cd();
	if (logX){
		gPad->SetLogx(); // for p_T plot	
	}
	float xbox_min,xbox_max;
	if (x_min == -999 && x_max == -999){
		xbox_min = ratio_histo->GetXaxis()->GetXmin();
		xbox_max = ratio_histo->GetXaxis()->GetXmax();
	}
	else {
		xbox_min = x_min;
		xbox_max = x_max;
	}	

	ratio_histo->Draw("");
	TBox *box_1 = new TBox(xbox_min,0.9,xbox_max,1.1);
	box_1->SetFillColor(22);
	box_1->Draw();

	TBox *box_2 = new TBox(xbox_min,0.95,xbox_max,1.05);
	box_2->SetFillColor(14);
	box_2->Draw();

  TLine *line = new TLine(xbox_min,1,xbox_max,1);
  line->SetLineColor(kBlack);
  line->Draw();

	if (x_min != -999 && x_max != -999){
		if (x_max == ratio_histo->GetXaxis()->GetXmax()) X_max = x_max;
		else X_max = x_max - (x_max-x_min)/Nbins;
		if (x_min == ratio_histo->GetXaxis()->GetXmin()) X_min = x_min;
		else X_min = x_min + (x_max-x_min)/Nbins;

	ratio_histo->GetXaxis()->SetRangeUser(X_min,X_max);
	}
	
	ratio_histo->Draw("P E0 SAME");
	ratio_histo->Draw("AXIS X+ Y+ SAME");
	ratio_histo->Draw("AXIS SAME");
  ratio_histo->GetXaxis()->SetTitle("");
	ratio_histo->GetYaxis()->SetTitle("Pseudo-Data/MC");
	ratio_histo->GetYaxis()->SetTitleSize(0.10);
	ratio_histo->GetYaxis()->SetTitleOffset(0.6);
	ratio_histo->GetYaxis()->SetLabelSize(0.1);
	ratio_histo->GetXaxis()->SetLabelSize(0.1);
	ratio_histo->GetYaxis()->SetRangeUser(0.75,1.25);
	ratio_histo->GetYaxis()->SetNdivisions(505, "kTRUE");
	ratio_histo->SetMarkerStyle(20);
	ratio_histo->SetMarkerColor(kBlue);
	ratio_histo->SetMarkerSize(0.7);
	ratio_histo->SetLineColor(kBlue);

	root_string = ".root";
	pdf_string = ".pdf";
  Canva->SaveAs((folder_s + geo_s + SB_folder + pdf_folder + titleh + pdf_string).c_str());
  Canva->SaveAs((folder_s + geo_s + SB_folder + root_folder + titleh + root_string).c_str());
	Canva->Close();

	// ==================================== close files

		PSEUDODATA_GJets_HT_40To100_file->Close();	
		PSEUDODATA_GJets_HT_100To200_file->Close();	
		PSEUDODATA_GJets_HT_200To400_file->Close();
		PSEUDODATA_GJets_HT_400ToInf_file->Close(); 
	
		PSEUDODATA_DiPhotonJets_file->Close();

		PSEUDODATA_QCD_Pt_20_30_EMEnriched_file->Close();
		PSEUDODATA_QCD_Pt_30_80_EMEnriched_file->Close();
		PSEUDODATA_QCD_Pt_80_170_EMEnriched_file->Close();
		PSEUDODATA_QCD_Pt_170_250_EMEnriched_file->Close();
		PSEUDODATA_QCD_Pt_250_350_EMEnriched_file->Close();
		PSEUDODATA_QCD_Pt_350_EMEnriched_file->Close();

		PSEUDODATA_QCD_Pt_20_30_BCtoE_file->Close();
		PSEUDODATA_QCD_Pt_30_80_BCtoE_file->Close();
		PSEUDODATA_QCD_Pt_80_170_BCtoE_file->Close();
		PSEUDODATA_QCD_Pt_170_250_BCtoE_file->Close();
		PSEUDODATA_QCD_Pt_250_350_BCtoE_file->Close();
		PSEUDODATA_QCD_Pt_350_BCtoE_file->Close();
	
	if(signal_MAD){	
		GJets_HT_40To100_file->Close();	
		GJets_HT_100To200_file->Close();	
		GJets_HT_200To400_file->Close();
		GJets_HT_400ToInf_file->Close(); 
	}
	else{
		G_Pt_15to30_file->Close();
		G_Pt_30to50_file->Close();
		G_Pt_50to80_file->Close();
		G_Pt_80to120_file->Close();
		G_Pt_120to170_file->Close();			
		G_Pt_170to300_file->Close();	
		G_Pt_300to470_file->Close();	
		G_Pt_470to800_file->Close();	
		G_Pt_800to1400_file->Close();
		G_Pt_1400to1800_file->Close();		
		G_Pt_1800_file->Close();
	}
	
	DiPhotonJets_file->Close();
	
}
Esempio n. 22
0
void EventDisplayForBaby(bool sig=false, bool truth=true, bool fatjet=true, int event=-1)
{

    gInterpreter->ExecuteMacro("~/macros/rootlogon.C");
    
    // chain      
    TChain *ch        = new TChain("tree");
    if(!sig) ch->Add("babies/small_quick_cfA_746p1_nleps1_trig0ON.root");
    if(sig) ch->Add("~/scratch/plots/1d_2015d_13Jan2016/2d/48ipb/*.root");
    
    InitBaby(ch); 
   
    Int_t nentries = (Int_t)ch->GetEntries();
    for(int i = 0; i<nentries; i++)
    {
        ch->GetEntry(i); 

        // apply selections (event==-1 && mj_>xxx && ht_>yyy && ...)
        // or 
        // select an event (event!=-1 && event_=xxxxxx)
        // "event" is one of the arguments  
        
        if(event>0 && event_!=event) continue; 

        // 
        //  Event Display
        // 
        float start=0.62;
        float nextline = start;
        float increment = 0.04;
        float offset=0.02;
        int npert;
        int LSPcol[2] = {kCyan+1,kOrange-4};
        if(!sig) npert = 5;
        else npert=3;
        float xalign = 0.82;
        vector<TMarker> constituents, genpart;
        TEllipse *cone[fjets_pt_->size()]; 
        TH2F *h_fatjets = new TH2F("h_fatjets","h_fatjets", 230, -5.0, 5.0, 144, -3.141592, 3.141592); 
        cout << event_ << endl;
        for(int ifj = 0; ifj< (int)fjets_pt_->size(); ifj++)
        {   if(ifj==0) cout << "... Fatjets info(pT, eta, phi, mj)" << endl;
            h_fatjets->Fill(fjets_eta_->at(ifj),fjets_phi_->at(ifj), fjets_m_->at(ifj));
            cout << fjets_pt_->at(ifj) << " " << fjets_eta_->at(ifj) << " " 
                 <<  fjets_phi_->at(ifj) << " " << fjets_m_->at(ifj) << endl;
        }

        TString cname = Form("Event_%lli_",event_);
        TCanvas *c = new TCanvas(cname,cname,1640,760);
        gPad->SetRightMargin(0.35);
        h_fatjets->SetZTitle("m_{j} [GeV]");
        h_fatjets->GetZaxis()->SetTitleSize(0.05);
        h_fatjets->GetZaxis()->SetTitleOffset(0.55);
        h_fatjets->GetYaxis()->SetTitleOffset(0.6);
        h_fatjets->Draw("colz");
        h_fatjets->GetZaxis()->SetRangeUser(0,1.1*h_fatjets->GetMaximum());
        h_fatjets->Draw("colz");
        gPad->Update();

        TPaletteAxis *palette = (TPaletteAxis*)h_fatjets->GetListOfFunctions()->FindObject("palette");
        for(int ifj = 0; ifj< (int)fjets_pt_->size(); ifj++)
        {
            cone[ifj] = new TEllipse(fjets_eta_->at(ifj),fjets_phi_->at(ifj), 1.2, 1.2);
            //  cone[ifj]->SetFillStyle(3003);
            cone[ifj]->SetFillStyle(0);
            Int_t binx,biny,binz;
            h_fatjets->GetBinXYZ(h_fatjets->FindBin(fjets_eta_->at(ifj),fjets_phi_->at(ifj)),binx,biny,binz);
            //cout<<"bin x bin y "<<binx<<" "<<biny<<endl;
            //cout<<"content "<<h_fatjets->GetBinContent(binx,biny)<<endl;

            //cout<<palette<<endl;
            Int_t ci = palette->GetBinColor(binx,biny);
            if(ifj==0) ci = palette->GetBinColor(binx,biny);
            //cout<<"color"<<ci<<endl;
            cone[ifj]->SetFillColor(kGray);
            cone[ifj]->SetLineColor(ci);
        }


        float lepPt, lepEta, lepPhi; 
        if(nels_==1)  
        {
            for(int i=0; i<(int)els_pt_->size(); i++) 
            {
                if(els_miniso_->at(i)>0.1) continue;
                if(els_sigid_->at(i)!=1) continue;
                if(els_pt_->at(i)<20) continue; 
                lepPt   =els_pt_->at(i);
                lepEta  =els_eta_->at(i);
                lepPhi  =els_phi_->at(i); 
            }
        }
        if(nmus_==1)  
        {
            for(int i=0; i<(int)mus_pt_->size(); i++) 
            {
                if(mus_miniso_->at(i)>0.2) continue;
                if(mus_sigid_->at(i)!=1) continue;
                if(mus_pt_->at(i)<20) continue;
                lepPt   =mus_pt_->at(i);
                lepEta  =mus_eta_->at(i);
                lepPhi  =mus_phi_->at(i); 
            }
        }



        myText(xalign+0.01,0.96,Form("H_{T} = %.0f GeV",ht_),1,0.04);
        myText(xalign+0.01,0.91,Form("M_{J} = %.0f GeV",mj_),1,0.04);
        myText(xalign+0.01,0.86,Form("#slash{E}_{T} = %.0f GeV",met_),1,0.04);
        myText(xalign+0.01,0.81,Form("m_{T} = %.0f GeV",mt_),1,0.04);
        myText(xalign+0.01,0.76,Form("reco %s p_{T} = %.0f GeV", nmus_==1?"#mu":"e", lepPt), kBlack, 0.04); 
        nextline=0.76;
        TMarker recolep = TMarker(lepEta, lepPhi, 27);
        recolep.SetMarkerSize(4);
        recolep.SetMarkerColor(kRed);
        genpart.push_back(recolep);
        TMarker mumark = TMarker(xalign,nextline,27);
        mumark.SetNDC();
        mumark.SetX(xalign);
        mumark.SetY(nextline+0.01);
        mumark.SetMarkerSize(2);
        mumark.SetMarkerColor(kRed);
        genpart.push_back(mumark);
        myText(xalign+0.01,0.71,Form("-- large-R jets --"),1,0.04); 
        myText(xalign+0.01,0.67,Form("(pT, eta, phi, mass)"),1,0.03); 
        nextline=0.635;
        for(int ifj = 0; ifj< (int)fjets_pt_->size(); ifj++)
        {
            myText(xalign+0.01,nextline,Form("%3.0f, %2.1f, %2.1f, %3.0f",
                   fjets_pt_->at(ifj),fjets_eta_->at(ifj),fjets_phi_->at(ifj),fjets_m_->at(ifj)),1,0.03); 
            nextline=nextline-0.035;
        } 
        nextline=nextline-0.015;
        myText(xalign+0.01,nextline,Form("-- AK4 jets --"),1,0.04); 
        nextline=nextline-0.04;
        myText(xalign+0.01,nextline,Form("(pT, eta, phi)"),1,0.03); 
        nextline=nextline-0.035;
        for(int ij = 0; ij< (int)jets_pt_->size(); ij++)
        {            
            if(jets_islep_->at(ij)==1) continue;
            myText(xalign+0.01,nextline,Form("%3.0f, %2.1f, %2.1f",
                   jets_pt_->at(ij),jets_eta_->at(ij),jets_phi_->at(ij)),1,0.03); 
            nextline=nextline-0.035;
        }
        
        if(truth) myText(xalign,0.68,"Gen  p_{T} [GeV]",1,0.04);



        
        if(truth) myText(xalign,0.68,"Gen  p_{T} [GeV]",1,0.04);



        TArrow line1 = TArrow();
        if(truth)line1.DrawLineNDC(xalign-0.02,start+0.035,xalign+0.14,start+0.035);
        TMarker met = TMarker(0, met_phi_, 27);
        met.SetMarkerSize(4);
        met.SetMarkerColor(kMagenta);
        genpart.push_back(met);
        TMarker metmark = TMarker(0.81,0.86,27);
        metmark.SetNDC();
        metmark.SetX(xalign);
        metmark.SetY(0.87);
        metmark.SetMarkerSize(2);
        metmark.SetMarkerColor(kMagenta);
        genpart.push_back(metmark);

        TMarker jetmark = TMarker(0.5,0.5,20);
        jetmark.SetNDC();
        jetmark.SetMarkerSize(1.2);
        jetmark.SetX(0.12);
        jetmark.SetY(0.2);
        genpart.push_back(jetmark);
        myText(0.13,0.19,"AK4 Jets",kBlack,0.04);
        TMarker bjetmark = TMarker(0.5,0.5,20);
        bjetmark.SetNDC();
        bjetmark.SetMarkerSize(1.2);
        bjetmark.SetMarkerColor(8);
        bjetmark.SetX(0.12);
        bjetmark.SetY(0.16);
        genpart.push_back(bjetmark);
        myText(0.13,0.15,"CSVM AK4",kBlack,0.04);
        myText(0.08,0.94,"Ring color indicates FJ mass",kBlack,0.04);

        // if(sig) nextline = start - (4*npert+2)*increment-0.02-offset;
        //else nextline = start - 2*npert*increment-offset;


        for(int ij=0;ij<(int)jets_pt_->size();ij++)
        {
            if(jets_islep_->at(ij)==1) continue;
            if(ij==0) cout << "... skinny jet info (pT eta phi)" << endl;
            cout << jets_pt_->at(ij) << " " << jets_eta_->at(ij) << " " <<  jets_phi_->at(ij) << endl;
                TMarker jet = TMarker(jets_eta_->at(ij),jets_phi_->at(ij),20);
                jet.SetMarkerSize(1.2);
                if(jets_csv_->at(ij)>0.890) jet.SetMarkerColor(8);
                constituents.push_back(jet);
        }

/*
        bool drawn=false;
        for(int ifj = 0; ifj< (int)fjets.size(); ifj++){
            vector<fastjet::PseudoJet> cons = fjets[ifj].constituents();
            for(int ics = 0; ics<(int)cons.size();ics++){
                for(int ifj2=0; ifj2<(int)fjets.size(); ifj2++){
                    if(ifj2==ifj) continue;
                    TArrow first = TArrow(cons[ics].eta(),cons[ics].phi_std(), fjets[ifj].eta(),fjets[ifj].phi_std(),0.04,">");
                    if(deltaR(cons[ics].eta(),cons[ics].phi_std(), fjets[ifj2].eta(),fjets[ifj2].phi_std()) < 1.25){
                        //cout<<"type 1 line: con eta phi FJ eta phi"<<cons[ics].eta()<<" "<<cons[ics].phi_std()<<" "<<fjets[ifj2].eta()<<" "<<fjets[ifj2].phi_std()<<endl;
                        first.DrawArrow(cons[ics].eta(),cons[ics].phi_std(), fjets[ifj].eta(),fjets[ifj].phi_std(),0.0045,"|>");
                        drawn=true;
                        break;
                    }
                    else if(deltaR(cons[ics].eta(),cons[ics].phi_std(), fjets[ifj].eta(),fjets[ifj].phi_std()) > 1.15){
                        //cout<<"type 2 line: con eta phi FJ eta phi"<<cons[ics].eta()<<" "<<cons[ics].phi_std()<<" "<<fjets[ifj].eta()<<" "<<fjets[ifj].phi_std()<<endl;
                        first.DrawArrow(cons[ics].eta(),cons[ics].phi_std(), fjets[ifj].eta(),fjets[ifj].phi_std(),0.0045,"|>");
                        drawn=true;
                        break;}
                }
            }
            cons.clear();
        }
        if(drawn) myText(0.12,0.04,"Arrows indicate ambiguous clustering ownership",kBlack,0.03);

*/

        if(truth)
        {
            int col[4] = {30,38,44,46};
            if(!sig) col[1]=46;
            int LSP,top,b,W,Wda,gl;
            LSP=0;top=0;b=0;W=0;Wda=0;gl=0;
            TLorentzVector vgl[2];
            TLorentzVector vt[4];
            TLorentzVector vLSP[2];

            for(unsigned int imc = 0; imc < mc_id_->size(); imc++)
            {
                int id= (int)mc_id_->at(imc);
                int absid = abs(id);
                int mid = (int)mc_mom_->at(imc);
                int absmid= abs(mid);
                if(id!=mid)
                {
                    int marknum=0;
                    TString partname;
                    int color=0;
                    bool flag=false;
                    if(id==1000021){
                        if(gl<2) vgl[gl].SetPtEtaPhiM(mc_pt_->at(imc), mc_eta_->at(imc), mc_phi_->at(imc), 1500);
                        gl++;
                    }  

                    if(id==1000022)
                    {
                        color = LSPcol[LSP];
                        partname = "#tilde{#chi}^{0}_{1}";
                        if(LSP==0) nextline=start-2*npert*increment;
                        else nextline = start - (4*npert+1)*increment-offset;
                        LSP++;
                        flag=true;
                        marknum=25;//27;

                    }
                    if(absid == 6)
                    {
                        //top
                        marknum=22;
                        partname = "t";
                        flag =true;
                        nextline = start - npert*top*increment;
                        color = col[top];
                        if(!sig) {}
                        if(sig) {if(top>1){ nextline-=(increment+offset);}}
                        if(top<4)vt[top].SetPtEtaPhiM(mc_pt_->at(imc), mc_eta_->at(imc), mc_phi_->at(imc), 172.5); 
                        top++;
                    }

                    if(absid==5  && (mid==6 || mid==(-6)))
                    {
                        //b from top
                        marknum=23;
                        partname="b";
                        flag=true;
                        color = col[b];
                        nextline = start - npert*b*increment - 2*increment;
                        // if(!sig){}
                        if(sig) {if(b>1){ nextline-=(increment+offset);}}
                        b++;

                    }
                    if(absid==24  && (mid==6 || mid==(-6)))
                    {
                        //W
                        marknum=34;
                        partname = "W";
                        flag=true;
                        color = col[W];
                        nextline = start - npert*W*increment - increment;
                        // if(!sig){}
                        if(sig){if(W>1){ nextline-=(increment+offset);}}
                        W++;
                    }


                    if((absid==13 || absid== 11 || absid==15) && absmid==24)
                    {
                        marknum=29;
                        if(absid==13) partname = "#mu";
                        else if(absid==11) partname = "e";
                        else partname = "#tau";
                        if(!sig) flag =true;
                        color = col[TMath::FloorNint(Wda/2)];
                        nextline = start - npert*increment*TMath::FloorNint(Wda/2)-3*increment;
                        if(TMath::FloorNint(Wda/2) != Wda/2) nextline-=increment;
                        Wda++;

                    }

                    if((absid==12 || absid== 14 || absid==16) && absmid==24)
                    {
                        marknum=30;
                        partname = "#nu";     
                        if(!sig) flag =true;
                        color = col[TMath::FloorNint(Wda/2)];
                        nextline = start - npert*increment*TMath::FloorNint(Wda/2)-4*increment;
                        //if(TMath::FloorNint(Wda/2) != Wda/2) nextline-=increment;
                        Wda++;

                    }
                    if((absid>0 && absid<5) && absmid==24)
                    {
                        marknum=3;
                        if(absid==1) partname="d";
                        if(absid==2) partname="u";
                        if(absid==3) partname="s";
                        if(absid==4) partname="c";

                        if(!sig) flag =true;
                        color = col[TMath::FloorNint(Wda/2)];
                        nextline = start - npert*increment*TMath::FloorNint(Wda/2)-3*increment;
                        // if(TMath::FloorNint(Wda/2) != Wda/2) nextline-=increment;
                        if(absid % 2 ==1) nextline-=increment; 
                        Wda++;

                    }

                    if(flag)
                    {
                        TMarker temp = TMarker(mc_eta_->at(imc),mc_phi_->at(imc), marknum);
                        TMarker legmark = TMarker(0.81,nextline,marknum);
                        legmark.SetNDC();
                        legmark.SetX(xalign+0.01);
                        legmark.SetY(nextline+0.011);
                        TString label = partname + "  " + Form("%.0f",mc_pt_->at(imc));
                        myText(xalign+0.03,nextline,partname,color,0.04);
                        myText(xalign+0.07,nextline,Form("%.0f",mc_pt_->at(imc)),color,0.04);
                        temp.SetMarkerColor(color);
                        legmark.SetMarkerColor(color);
                        temp.SetMarkerSize(2);
                        legmark.SetMarkerSize(2);

                        if(absid==6 || absid==13 || absid==1000022){ temp.SetMarkerSize(3);} 
                        genpart.push_back(temp);
                        genpart.push_back(legmark);
                        flag=false;
                    }
                }
            }
            if(sig && LSP==0){
                int color = LSPcol[LSP];
                TString partname = "#tilde{#chi}^{0}_{1}";
                if(LSP==0) nextline=start-2*npert*increment;
                else nextline = start - (4*npert+1)*increment-offset;
                LSP++;
                int  marknum=25;//27;
                // TMarker temp = TMarker(mc_doc_eta->at(imc),mc_doc_phi->at(imc), marknum);
                vLSP[0]= vgl[0]-vt[0]-vt[1];
                TMarker temp = TMarker(vLSP[0].Eta(),vLSP[0].Phi(), marknum);
                TMarker legmark = TMarker(0.81,nextline,marknum);
                legmark.SetNDC();
                legmark.SetX(xalign+0.01);
                legmark.SetY(nextline+0.011);
                TString label = partname + "  " + Form("%.0f",vLSP[0].Pt());
                myText(xalign+0.03,nextline,partname,color,0.04);
                myText(xalign+0.07,nextline,Form("%.0f",vLSP[0].Pt()),color,0.04);
                temp.SetMarkerColor(color);
                legmark.SetMarkerColor(color);
                temp.SetMarkerSize(3);
                legmark.SetMarkerSize(2);


                genpart.push_back(temp);
                genpart.push_back(legmark);

            }
            if(sig && LSP==1){
                int color = LSPcol[LSP];
                TString partname = "#tilde{#chi}^{0}_{1}";
                if(LSP==0) nextline=start-2*npert*increment;
                else nextline = start - (4*npert+1)*increment-offset;
                LSP++;
                int marknum=25;//27;
                // TMarker temp = TMarker(mc_doc_eta->at(imc),mc_doc_phi->at(imc), marknum);
                vLSP[1]= vgl[1]-vt[2]-vt[3];
                TMarker temp = TMarker(vLSP[1].Eta(),vLSP[1].Phi(), marknum);
                TMarker legmark = TMarker(0.81,nextline,marknum);
                legmark.SetNDC();
                legmark.SetX(xalign+0.01);
                legmark.SetY(nextline+0.011);
                TString label = partname + "  " + Form("%.0f",vLSP[1].Pt());
                myText(xalign+0.03,nextline,partname,color,0.04);
                myText(xalign+0.07,nextline,Form("%.0f",vLSP[1].Pt()),color,0.04);
                temp.SetMarkerColor(color);
                legmark.SetMarkerColor(color);
                temp.SetMarkerSize(3);
                legmark.SetMarkerSize(2);


                genpart.push_back(temp);
                genpart.push_back(legmark);

            }
        }

        for(int ix=0;ix<(int)genpart.size();ix++)
        {
            genpart[ix].Draw("same");
        }
        for(int iy=0;iy<(int)constituents.size();iy++)
        {
            constituents[iy].Draw("same");
        }

        for(int ifj = 0; ifj< (int)fjets_pt_->size(); ifj++)
        {
            if(fatjet) cone[ifj]->Draw();
        }
        h_fatjets->Draw("colz same");
        h_fatjets->SetTitle(Form("Event %lli",event_));

        h_fatjets->SetStats(0); 
        h_fatjets->SetXTitle("#eta"); 
        h_fatjets->SetYTitle("#phi"); 

        TString savename;
        if(!sig) savename = "fig/EventDisplay_"+cname+Form("%i_FJ",nfjets_); 
        else  savename = "fig/EventDisplay_"+cname+Form("%i_FJ",nfjets_);
        if(truth) savename+="_truth";
        else savename+="_notruth";	  
        if(fatjet) savename+="_fatjet";
        else savename+="_nofatjet";
        c->Print(savename+".pdf");
        //c->Print(savename+".C");

        c->Close();
        h_fatjets->Delete();
    }
}
Esempio n. 23
0
void drawMassFrom2DPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  map<string, string>  parIni,   // Variable containing all initial parameters
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the type of object to fit
                  bool incJpsi,         // Includes Jpsi model
                  bool incPsi2S,        // Includes Psi(2S) model
                  bool incBkg,          // Includes Background model                  
                  // Select the fitting options
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  double  binWidth,     // Bin width
                  bool paperStyle=false // if true, print less info
                  ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;
  
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
  
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiPRName  = Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiNoPRName  = Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SPRName  = Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SNoPRName  = Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  bool isMC = (DSTAG.find("MC")!=std::string::npos);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  
  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

 
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
 
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet(*myws.pdf(Form("pdfMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                       FillStyle(paperStyle ? 0 : 1001), FillColor(kAzure-9), VLines(), DrawOption("LCF"), LineColor(kBlue), LineStyle(kDashed)
                                       );
  if (!paperStyle) {
    if (incJpsi) {
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
    }
    if (incPsi2S) {
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }      
    } 
  }
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  // Create the pull distribution of the fit 
  RooPlot* frameTMP = (RooPlot*)frame->Clone("TMP");
  int nBinsTMP = nBins;
  RooHist *hpull = frameTMP->pullHist(0, 0, true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("invMass")->frame(Title("Pull Distribution"), Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  frame2->addPlotable(hpull, "PX"); 
  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setMassFrom2DRange(myws, frame, dsOSName, setLogScale);
  if (paperStyle) {
     double Ydown = 0.;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printMassFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.20, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } else {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.5175, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;}
  else {t->DrawLatex(0.5175, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=0.045;}
  t->DrawLatex(0.5175, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.5175, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  if (frame->findObject("dOS")) { leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); }
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if (frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","l"); }
  if (frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"Prompt J/#psi","l"); }
  if (frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"Non-Prompt J/#psi","l"); }
  if (incBkg && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background",paperStyle ? "l" : "fl"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  if (!paperStyle) {
     //---plot pull
     pad2->Draw();
     pad2->cd();

     frame2->SetTitle("");
     frame2->GetYaxis()->CenterTitle(kTRUE);
     frame2->GetYaxis()->SetTitleOffset(0.4);
     frame2->GetYaxis()->SetTitleSize(0.1);
     frame2->GetYaxis()->SetLabelSize(0.1);
     frame2->GetYaxis()->SetTitle("Pull");
     frame2->GetXaxis()->CenterTitle(kTRUE);
     frame2->GetXaxis()->SetTitleOffset(1);
     frame2->GetXaxis()->SetTitleSize(0.12);
     frame2->GetXaxis()->SetLabelSize(0.1);
     frame2->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

     frame2->Draw(); 

     // *** Print chi2/ndof 
     printChi2(myws, pad2, frameTMP, "invMass", dsOSName.c_str(), pdfTotName.c_str(), nBinsTMP, false);

     pline->Draw("same");
     pad2->Update();
  }

  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
};
int main(int argc, char **argv){
	std::cout.precision(4);
	// Counting time
	Double_t initialTime = clock();

	/*
	 * Histograms
	 */
	// All jets
	TH1 *h_numberJet = new TH1F("Number Jets","Number Jets",11,-0.5,10.5);

	// Non Isr jets
	TH1 *h_jet_PT = new TH1F("Jet PT","Jet PT", 201,0.0,600.0);
	TH1 *h_jet_Eta = new TH1F("Jet Eta","Jet Eta", 171,-5.0,5.0);
	TH1 *h_jet_Phi = new TH1F("Jet Phi","Jet Phi", 375,-3.5,3.5);
	TH1 *h_jet_DPhi_MET = new TH1F("Jet - MET Delta_Phi","Jet - MET Delta_Phi",300,0.0,4.0);
	TH1 *h_jet_DPhi_MET_hpt = new TH1F("Jet - MET Delta_Phi_hpt","Jet - MET Delta_Phi_hpt",300,0.0,4.0);
	TH1 *h_jet_MT = new TH1F("Jet Transverse mass","Jet Transverse Mass",201,0.0,600.0);
	TH1 *h_jet_Delta_PT = new TH1F("Jet Delta-PT","Non ISR Delta-PT", 201,0.0,300.0);
	TH1 *h_jet_PT_HT = new TH1F("Jet PT-HT ratio","Jet PT-HT ratio",201,-0.0025,1.0025);
	TH1 *h_jet_PT_over_PT_others = new TH1F("Jet PT/PT_others","Jet PT/PT_others",401,-0.0025,2.0025);
	TH1 *h_jet_Eta_over_Eta_others = new TH1F("Jet Eta/Eta_others","Jet Eta/Eta_others",401,-0.0025,2.0025);
	TH1 *h_jet_DPhi_over_Phi_others = new TH1F("Jet Phi/Phi_others","Jet Phi/Phi_others",401,-0.0025,2.0025);
	TH1 *h_jet_Delta_Eta = new TH1F("Jet Delta-Eta","Jet Delta-Eta", 171,0.0,5.0);
	TH1 *h_jet_DPhi_MET_other = new TH1F("Jet - MET Delta_Phi other","Jet - MET Delta_Phi other",300,0.0,4.0);
	TH1 *h_jet_multiplicity = new TH1F("Jet - Multiplicity","Jet - Multiplicity",101,-0.5,100.5);
	TH1 *h_jet_DeltaR = new TH1F ("Jet - Delta_R","Jet - Delta_R",201,-0.0025,0.8025);
	TH1 *h_jet_Delta_PT_leading = new TH1F("Delta PT: leading - Jet","Delta PT: leading - Jet", 201,0.0,600.0);
	TH1 *h_jet_Delta_Eta_leading = new TH1F("Delta Eta: Jet - leading","Delta Eta: Jet - leading", 171,0.0,8.0);

	TH2 *h2_jet_PTEta=new TH2F("Non_ISR_Jet_PT_Eta","Non ISR Jet PT Vs. Eta",201,-1.25,501.25,201,-4.02,4.02);

	// ISR jets
	TH1 *h_ISR_PT = new TH1F("ISR PT","ISR PT", 201,0.0,600.0);
	TH1 *h_ISR_Eta = new TH1F("ISR Eta","ISR Eta", 171,-5.0,5.0);
	TH1 *h_ISR_Phi = new TH1F("ISR Phi","ISR Phi", 375,-3.5,3.5);
	TH1 *h_ISR_DPhi_MET = new TH1F("ISR - MET Delta_Phi","ISR - MET Delta_Phi",300,0.0,4.0);
	TH1 *h_ISR_DPhi_MET_hpt = new TH1F("ISR - MET Delta_Phi_hpt","ISR - MET Delta_Phi_hpt",300,0.0,4.0);
	TH1 *h_ISR_MT = new TH1F("ISR Transverse mass","ISR Transverse Mass",201,0.0,600.0);
	TH1 *h_ISR_Delta_PT = new TH1F("ISR Delta-PT","ISR Delta-PT", 201,0.0,300.0);
	TH1 *h_ISR_PT_HT = new TH1F("ISR PT-HT ratio","ISR PT-HT ratio",201,-0.0025,1.0025);
	TH1 *h_ISR_PT_over_PT_others = new TH1F("ISR PT/PT_others","ISR PT/PT_others",401,-0.0025,2.0025);
	TH1 *h_ISR_Eta_over_Eta_others = new TH1F("ISR Eta/Eta_others","ISR Eta/Eta_others",401,-0.0025,2.0025);
	TH1 *h_ISR_DPhi_over_Phi_others = new TH1F("ISR Phi/Phi_others","ISR Phi/Phi_others",401,-0.0025,2.0025);
	TH1 *h_ISR_Delta_Eta = new TH1F("ISR Delta-Eta","ISR Delta-Eta", 171,0.0,5.0);
	TH1 *h_ISR_DPhi_MET_other = new TH1F("ISR - MET Delta_Phi other","ISR - MET Delta_Phi other",300,0.0,4.0);
	TH1 *h_ISR_multiplicity = new TH1F("ISR - Multiplicity","ISR - Multiplicity",101,-0.5,100.5);
	TH1 *h_ISR_DeltaR = new TH1F ("ISR - Delta_R","ISR - Delta_R",201,-0.0025,0.8025);
	TH1 *h_ISR_Delta_PT_leading = new TH1F("Delta PT: leading - ISR","Delta PT: leading - ISR", 201,0.0,600.0);
	TH1 *h_ISR_Delta_Eta_leading = new TH1F("Delta Eta: ISR - leading","Delta Eta: ISR - leading", 171,0.0,8.0);

	TH2 *h2_ISR_PTEta=new TH2F("ISR_Jet_PT_Eta","ISR Jet PT Vs. Eta",201,-1.25,501.25,201,-4.02,4.02);

	// MET
	TH1 *h_MET = new TH1F("Missing ET","Missing ET",200,0,600);
	TH1 *h_MET_hpt1 = new TH1F("Missing ET high_ISR_pt-1","Missing ET high_ISR_pt-1",200,0.0,600.0);
	TH1 *h_MET_hpt2 = new TH1F("Missing ET high_ISR_pt-2","Missing ET high_ISR_pt-2",200,0.0,600.0);
	TH1 *h_MET_hpt3 = new TH1F("Missing ET high_ISR_pt-3","Missing ET high_ISR_pt-3",200,0.0,600.0);
	TH1 *h_MET_hpt4 = new TH1F("Missing ET high_ISR_pt-4","Missing ET high_ISR_pt-4",200,0.0,600.0);

	TH2 *h2_dif_PTEta=new TH2F("FSR_ISR_Jet_PT_Eta_Difference","Difference between FSR and ISR Jet PT Vs. Eta distributions",201,-1.25,501.25,201,-4.02,4.02);
	TH2 *h2_dif_lead_PTEta=new TH2F("Lead_ISR_Jet_PT_Eta_Difference","Difference between Lead and ISR Jet PT Vs. Eta distributions",201,-1.25,501.25,201,-4.02,4.02);

	// Leading PT
	TH1 *h_leading_PT = new TH1F("Leading PT","Leading PT", 201,0.0,600.0);
	TH1 *h_leading_MT = new TH1F("Leading Transverse mass","Leading Transverse Mass",201,0.0,600.0);
	TH1 *h_leading_Eta = new TH1F("Leading Eta","Leading Eta", 171,-5.0,5.0);
	TH1 *h_leading_DPhi_MET = new TH1F("Leading - MET Delta_Phi","Leading - MET Delta_Phi",300,0.0,4.0);

	TH2 *h2_leading_PTEta=new TH2F("Leading_Jet_PT_Eta","Leading Jet PT Vs. Eta",201,-1.25,501.25,201,-4.02,4.02);

	// Other variables
	TH1 *h_HT = new TH1F("HT","HT",201,0.0,600.0);
	TH1 *h_HT_R1 = new TH1F("HT_R1","HT_R1",51,-0.01,1.01);
	TH1 *h_HT_R2 = new TH1F("HT_R2","HT_R2",51,-0.01,1.01);

	// B tagging
	TH1 *h_BTag = new TH1F("BTag","BTag",5,-0.5,4.5);
	TH1 *h_BTag_PT = new TH1F("BTag PT","BTag PT", 201,0.0,600.0);
	TH1 *h_BTag_Eta = new TH1F("BTag Eta","BTag Eta", 171,-5.0,5.0);
	TH1 *h_BTag_DPhi_MET = new TH1F("BTag - MET Delta_Phi","BTag - MET Delta_Phi",300,0.0,4.0);
	TH1 *h_BTags_per_Event = new TH1F("BTags per event","BTags per event",5,-0.5,4.5);

	// Further analysis
	TH1 *h_ISR_PT_comp = new TH1F("ISR PT for comparison","ISR PT for comparison with histo", 20,0.0,800.0);
	TH1 *h_ISR_Eta_comp = new TH1F("ISR Eta for comparison","ISR Eta for comparison with histo", 20,-4.2,4.2);
	TH1 *h_ISR_DPhi_MET_comp = new TH1F("ISR Phi for comparison","ISR Phi for comparison with histo", 20,0,PI);

	// To check the histograms' creation
	TH1 *hist_ISR_PT = new TH1F("ISR PT comp","ISR PT comp", 20,0.0,800.0);
	TH1 *hist_ISR_Abs_Eta = new TH1F("ISR Abs Eta comp","ISR Abs Eta comp", 20,0.0,5.2);
	TH1 *hist_ISR_DPhi_MET = new TH1F("ISR Delta Phi comp","ISR Delta Phi comp", 20,0.0,PI);
	TH1 *hist_ISR_PT_ratio = new TH1F("ISR PT/PT_others comp","ISR PT/PT_others comp",20,0.0,8.0);
	TH1 *hist_ISR_Delta_Eta = new TH1F("ISR Delta-Eta comp","ISR Delta-Eta comp", 20,0.0,7.0);
	TH1 *hist_ISR_DPhi_MET_other = new TH1F("ISR - MET Delta_Phi other comp","ISR - MET Delta_Phi other comp",20,0.0,PI);
	TH1 *hist_ISR_Delta_PT_leading = new TH1F("Delta PT: leading - ISR comp","Delta PT: leading - ISR comp", 20,0.0,500.0);
	TH1 *hist_ISR_Delta_Eta_leading = new TH1F("Delta Eta: ISR - leading comp","Delta Eta: ISR - leading comp", 20,0.0,6.5);
	TH1 *hist_jet_PT = new TH1F("Jet PT comp","Jet PT comp", 20,0.0,800.0);
	TH1 *hist_jet_Abs_Eta = new TH1F("Jet Abs Eta comp","Jet Abs Eta comp", 20,0.0,5.2);
	TH1 *hist_jet_DPhi_MET = new TH1F("Jet Delta Phi comp","Jet Delta Phi comp", 20,0.0,PI);
	TH1 *hist_jet_PT_ratio = new TH1F("Jet PT/PT_others comp","Jet PT/PT_others comp",20,0.0,7.0);
	TH1 *hist_jet_Delta_Eta = new TH1F("Jet Delta-Eta comp","Jet Delta-Eta comp", 20,0.0,8.0);
	TH1 *hist_jet_DPhi_MET_other = new TH1F("Jet - MET Delta_Phi other comp","Jet - MET Delta_Phi other comp",20,0.0,PI);
	TH1 *hist_jet_Delta_PT_leading = new TH1F("Delta PT: leading - Jet comp","Delta PT: leading - Jet comp", 20,0.0,500.0);
	TH1 *hist_jet_Delta_Eta_leading = new TH1F("Delta Eta: Jet - leading comp","Delta Eta: Jet - leading comp", 20,0.0,6.5);

	for(int iRun = 1; iRun < 11; iRun ++){
		// Create chains of root trees
		TChain chain_Delphes("Delphes");

		// Loading simulations from Delphes
		Char_t *local_path;
		local_path = (Char_t*) malloc(512*sizeof(Char_t));
		if (atServer)
			strcpy(local_path,"/home/af.garcia1214/PhenoMCsamples/Simulations/MG_pythia8_delphes_parallel/"); // At the server
		else
			strcpy(local_path,"/home/afgarcia1214/Documentos/Simulations/"); // At the University's pc

		Char_t *head_folder;
		head_folder = (Char_t*) malloc(512*sizeof(Char_t));
		if (Matching)
			strcpy(head_folder,"_Tops_Events_WI_Matching/");
		else
			strcpy(head_folder,"_Tops_Events_WI/");
		head_folder[0] = channel;
		head_folder[13] = ISR_or_NOT[0];
		head_folder[14] = ISR_or_NOT[1];

		Char_t current_folder[] = "_Tops_MG_1K_AG_WI_003/";
		current_folder[0] = channel;
		current_folder[15] = ISR_or_NOT[0];
		current_folder[16] = ISR_or_NOT[1];

		Char_t unidad = 0x30 + iRun%10;
		Char_t decena = 0x30 + int(iRun/10)%10;
		Char_t centena = 0x30 + int(iRun/100)%10;

		current_folder[18] = centena;
		current_folder[19] = decena;
		current_folder[20] = unidad;

		Char_t *file_delphes;
		file_delphes = (Char_t*) malloc(512*sizeof(Char_t));
		strcpy(file_delphes,local_path);
		strcat(file_delphes,head_folder);
		strcat(file_delphes,current_folder);
		strcat(file_delphes,"Events/run_01/output_delphes.root");

		cout << "\nReading the file: \nDelphes: " << file_delphes << endl;

		chain_Delphes.Add(file_delphes);
		// Objects of class ExRootTreeReader for reading the information
		ExRootTreeReader *treeReader_Delphes = new ExRootTreeReader(&chain_Delphes);

		Long64_t numberOfEntries = treeReader_Delphes->GetEntries();

		// Get pointers to branches used in this analysis
		TClonesArray *branchJet = treeReader_Delphes->UseBranch("Jet");
		TClonesArray *branchMissingET = treeReader_Delphes->UseBranch("MissingET");

		cout << endl;
		cout << " Number of Entries Delphes = " << numberOfEntries << endl;
		cout << endl;

		// particles, jets and vectors
		MissingET *METpointer;
		TLorentzVector *vect_currentJet = new TLorentzVector;
		TLorentzVector *vect_auxJet = new TLorentzVector;
		TLorentzVector *vect_leading = new TLorentzVector;
		Jet *currentJet = new Jet;
		Jet *auxJet = new Jet;
		TRefArray array_temp;

		// Temporary variables
		Double_t MET = 0.0; // Missing transverse energy
		Double_t delta_phi = 0.0; // difference between the phi angle of MET and the jet
		Double_t transverse_mass = 0.0; // Transverse mass
		Double_t HT = 0.0; // Sum of jets' PT
		Double_t HT_R1 = 0.0; // Sum of jets' PT which are in the same hemisphere of the ISR jet hemisphere
		Double_t HT_R2 = 0.0; // Sum of jets' PT which are in the opposite hemisphere of the ISR jet hemisphere
		Double_t ISR_Eta = 0.0; // Pseudorapidity of the ISR jet
		Int_t number_Btags = 0; // Number of B jets per event
		Int_t ISR_Btags = 0; // Number of BTags which are also ISR jets
		Double_t delta_PT_jet = 0.0; // |PT-<PT>|
		Double_t PT_sum = 0.0; // sum(PT)
		Double_t PT_aver = 0.0; // <PT>
		Double_t Delta_eta_aver = 0.0; // sum_i|eta-eta_i|/(Nj-1)
		Double_t Delta_phi_sum = 0.0; // sum delta_phi
		Double_t Delta_phi_other_jets = 0.0; // Average of delta phi of other jets
		Double_t PT_ratio = 0.0; // PT/PT_others
		Double_t Eta_ratio = 0.0; // Eta/Eta_others
		Double_t Eta_sum = 0.0; // sum(Eta)
		Double_t Delta_R = 0.0; // Size of the jet
		Double_t Delta_phi_ratio = 0.0; // Delta_phi/Delta_phi_others
		Double_t Delta_PT_leading = 0.0; // PT - PT_leading
		Double_t Delta_Eta_leading = 0.0; // |Eta - Eta_leading|

		/*
		 * Some variables used through the code
		 */
		Int_t ISR_jets[numberOfEntries];
		Int_t NumJets = 0;

	    Char_t *local_path_binary;
	    local_path_binary = (Char_t*) malloc(512*sizeof(Char_t));
	    if (atServer)
	    	strcpy(local_path_binary,"/home/af.garcia1214/PhenoMCsamples/Results/matching_Results/"); // At the server
	    else
	    	strcpy(local_path_binary,"/home/afgarcia1214/Documentos/Results_and_data/matching_Results/"); // At the University's pc

		Char_t *head_folder_binary;
		head_folder_binary = (Char_t*) malloc(512*sizeof(Char_t));
		if (Matching)
			strcpy(head_folder_binary,"_Tops_matchs_WI_Matching/");
		else
			strcpy(head_folder_binary,"_Tops_matchs_WI/");
	    head_folder_binary[0] = channel;
	    head_folder_binary[13] = ISR_or_NOT[0];
	    head_folder_binary[14] = ISR_or_NOT[1];

	    Char_t matching_name[] = "ISR_jets_Tops_WI_003.bn";
	    matching_name[8] = channel;
	    matching_name[14] = ISR_or_NOT[0];
	    matching_name[15] = ISR_or_NOT[1];

		matching_name[17] = centena;
		matching_name[18] = decena;
		matching_name[19] = unidad;

	    Char_t * fileName;
	    fileName = (Char_t*) malloc(512*sizeof(Char_t));
	    strcpy(fileName,local_path_binary);
	    strcat(fileName,head_folder_binary);
	    strcat(fileName,matching_name);

		ifstream ifs(fileName,ios::in | ios::binary);

		for (Int_t j = 0; j<numberOfEntries; j++){
				ifs.read((Char_t *) (ISR_jets+j),sizeof(Int_t));
		}
		ifs.close();

		// Jet with greatest PT
		Double_t PT_max = 0;
		Int_t posLeadingPT = -1;
		Int_t ISR_greatest_PT = 0;
		Double_t MT_leading_jet = 0.0; // Transverse mass

		/*
		 * Main cycle of the program
		 */
		numberOfEntries = 100000;
		for (Int_t entry = 0; entry < numberOfEntries; ++entry){
			// Progress
			if(numberOfEntries>10 && (entry%((int)numberOfEntries/10))==0.0){
				cout<<"progress = "<<(entry*100/numberOfEntries)<<"%\t";
				cout<< "Time :"<< (clock()-initialTime)/double_t(CLOCKS_PER_SEC)<<"s"<<endl;
			}

			// Load selected branches with data from specified event
			treeReader_Delphes->ReadEntry(entry);

			// MET
			METpointer = (MissingET*) branchMissingET->At(0);
			MET = METpointer->MET;
			h_MET->Fill(MET);

			NumJets=branchJet->GetEntries();
			h_numberJet->Fill(NumJets);

			// checking the ISR
			if (ISR_jets[entry] == -1 || NumJets < 3)
				continue;

			PT_max = 0;
			posLeadingPT = -1;
			HT = 0;
			HT_R1 = 0;
			HT_R2 = 0;
			number_Btags = 0;

			delta_PT_jet = 0.0;
			PT_aver = 0.0;
			PT_sum = 0.0;
			Delta_eta_aver = 0.0;
			Delta_phi_sum = 0.0;
			Delta_phi_other_jets = 0.0;
			Delta_phi_ratio = 0.0;
			Delta_PT_leading = 0.0;
			Delta_Eta_leading = 0.0;

			PT_ratio = 0.0;
			Eta_ratio = 0.0;
			Eta_sum = 0.0;

			Delta_R = 0.0;

			if (ISR_jets[entry] >= NumJets){
				cout << "Error en el matching" << endl;
				return 1;
			}

			// Preliminary for. It is used to calculate PT_aver and Delta_phi_sum
			for (Int_t iJet = 0; iJet<NumJets; iJet++){
				currentJet = (Jet*) branchJet->At(iJet);
				vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
				delta_phi = deltaAng(vect_currentJet->Phi(), METpointer->Phi);
				PT_sum += vect_currentJet->Pt();
				Eta_sum += vect_currentJet->Eta();
				Delta_phi_sum += delta_phi;
				// HT
				HT += vect_currentJet->Pt();
				// HT ratios
				if((vect_currentJet->Eta()*ISR_Eta) > 0)
					HT_R1 += vect_currentJet->Pt();
				else
					HT_R2 += vect_currentJet->Pt();
				// PT Leading jet
				if(PT_max < vect_currentJet->Pt()){
					PT_max = vect_currentJet->Pt();
					posLeadingPT = iJet;
				}
			}

			//PT_aver
			PT_aver = PT_sum/NumJets;

			// Leading PT
			currentJet = (Jet*) branchJet->At(posLeadingPT);
			vect_leading->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);

			// ISR jet
			currentJet = (Jet*) branchJet->At(ISR_jets[entry]);
			vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
			ISR_Eta = vect_currentJet->Eta();

			for (Int_t iJet = 0; iJet<NumJets; iJet++){
				currentJet = (Jet*) branchJet->At(iJet);
				vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
				delta_phi = deltaAng(vect_currentJet->Phi(), METpointer->Phi);
				transverse_mass = sqrt(2*vect_currentJet->Pt()*MET*(1-cos(delta_phi)));

				// Correlated variables
				delta_PT_jet = TMath::Abs(vect_currentJet->Pt()-PT_aver);
				Delta_phi_other_jets = (Delta_phi_sum-delta_phi)/(NumJets-1);
				PT_ratio = vect_currentJet->Pt()*(NumJets-1)/(PT_sum-vect_currentJet->Pt());
				Eta_ratio = vect_currentJet->Eta()*(NumJets-1)/(Eta_sum-vect_currentJet->Eta());
				Delta_phi_ratio = delta_phi*(NumJets-1)/(Delta_phi_sum-delta_phi);

				Delta_Eta_leading = TMath::Abs(vect_currentJet->Eta()-vect_leading->Eta());
				Delta_PT_leading = vect_leading->Pt()-vect_currentJet->Pt();

				Delta_eta_aver = 0.0;
				// For cycle used to calculate Delta_eta_aver
				for(Int_t iJet2 = 0; iJet2<NumJets; iJet2++){
					auxJet = (Jet*) branchJet->At(iJet2);
					vect_auxJet->SetPtEtaPhiM(auxJet->PT,auxJet->Eta,auxJet->Phi,auxJet->Mass);
					if (iJet2 != iJet) Delta_eta_aver += TMath::Abs(vect_auxJet->Eta()-vect_currentJet->Eta());
				}
				Delta_eta_aver = Delta_eta_aver/(NumJets-1);
				Delta_R = sqrt(pow(currentJet->DeltaEta,2)+pow(currentJet->DeltaPhi,2));

				// Multiplicity
				array_temp = (TRefArray) currentJet->Constituents;

				if (iJet != ISR_jets[entry]){ // Non ISR
					h_jet_PT->Fill(vect_currentJet->Pt());
					h_jet_Eta->Fill(vect_currentJet->Eta());
					h_jet_Phi->Fill(vect_currentJet->Phi());
					h_jet_DPhi_MET->Fill(delta_phi);
					h_jet_MT->Fill(transverse_mass);
					h_jet_Delta_PT->Fill(delta_PT_jet);
					h_jet_Delta_Eta->Fill(Delta_eta_aver);
					h_jet_DPhi_MET_other->Fill(Delta_phi_other_jets);
					h_jet_PT_HT->Fill(vect_currentJet->Pt()/HT);
					h_jet_multiplicity->Fill(array_temp.GetEntries());
					h_jet_PT_over_PT_others->Fill(PT_ratio);
					h_jet_Eta_over_Eta_others->Fill(Eta_ratio);
					h_jet_DeltaR->Fill(Delta_R);
					h_jet_DPhi_over_Phi_others->Fill(Delta_phi_ratio);
					h_jet_Delta_PT_leading->Fill(Delta_PT_leading);
					h_jet_Delta_Eta_leading->Fill(Delta_Eta_leading);
					if (vect_currentJet->Pt()>240)
						h_jet_DPhi_MET_hpt->Fill(delta_phi);
					h2_jet_PTEta->Fill(vect_currentJet->Pt(),vect_currentJet->Eta());

					// For testing creating histo
					hist_jet_PT->Fill(vect_currentJet->Pt());
					hist_jet_Abs_Eta->Fill(TMath::Abs(vect_currentJet->Eta()));
					hist_jet_DPhi_MET->Fill(delta_phi);
					hist_jet_PT_ratio->Fill(PT_ratio);
					hist_jet_Delta_Eta->Fill(Delta_eta_aver);
					hist_jet_DPhi_MET_other->Fill(Delta_phi_other_jets);
					hist_jet_Delta_PT_leading->Fill(Delta_PT_leading);
					hist_jet_Delta_Eta_leading->Fill(Delta_Eta_leading);
				}
				else{ //ISR
					h_ISR_PT->Fill(vect_currentJet->Pt());
					h_ISR_Eta->Fill(vect_currentJet->Eta());
					h_ISR_Phi->Fill(vect_currentJet->Phi());
					h_ISR_DPhi_MET->Fill(delta_phi);
					h_ISR_Eta_comp->Fill(vect_currentJet->Eta());
					h_ISR_PT_comp->Fill(vect_currentJet->Pt());
					h_ISR_DPhi_MET_comp->Fill(delta_phi);
					h_ISR_Delta_PT->Fill(delta_PT_jet);
					h_ISR_Delta_Eta->Fill(Delta_eta_aver);
					h_ISR_DPhi_MET_other->Fill(Delta_phi_other_jets);
					h_ISR_PT_HT->Fill(vect_currentJet->Pt()/HT);
					h_ISR_multiplicity->Fill(array_temp.GetEntries());
					h_ISR_PT_over_PT_others->Fill(PT_ratio);
					h_ISR_Eta_over_Eta_others->Fill(Eta_ratio);
					h_ISR_DeltaR->Fill(Delta_R);
					h_ISR_DPhi_over_Phi_others->Fill(Delta_phi_ratio);
					h_ISR_Delta_PT_leading->Fill(Delta_PT_leading);
					h_ISR_Delta_Eta_leading->Fill(Delta_Eta_leading);
					if (vect_currentJet->Pt()>120)
						h_MET_hpt1->Fill(MET);
					if (vect_currentJet->Pt()>200)
						h_MET_hpt2->Fill(MET);
					if (vect_currentJet->Pt()>240){
						h_MET_hpt3->Fill(MET);
						h_ISR_DPhi_MET_hpt->Fill(delta_phi);
					}
					if (vect_currentJet->Pt()>300)
						h_MET_hpt4->Fill(MET);
					h2_ISR_PTEta->Fill(vect_currentJet->Pt(),vect_currentJet->Eta());
					// Transverse mass
					h_ISR_MT->Fill(transverse_mass);

					// For testing creating histo
					hist_ISR_PT->Fill(vect_currentJet->Pt());
					hist_ISR_Abs_Eta->Fill(TMath::Abs(vect_currentJet->Eta()));
					hist_ISR_DPhi_MET->Fill(delta_phi);
					hist_ISR_PT_ratio->Fill(PT_ratio);
					hist_ISR_Delta_Eta->Fill(Delta_eta_aver);
					hist_ISR_DPhi_MET_other->Fill(Delta_phi_other_jets);
					hist_ISR_Delta_PT_leading->Fill(Delta_PT_leading);
					hist_ISR_Delta_Eta_leading->Fill(Delta_Eta_leading);
				}

				// BTag
				h_BTag->Fill(currentJet->BTag);
				if (currentJet->BTag == 1){ // The current jet is B Tagged
					h_BTag_PT->Fill(vect_currentJet->Pt());
					h_BTag_Eta->Fill(vect_currentJet->Eta());
					h_BTag_DPhi_MET->Fill(delta_phi);
					number_Btags++;

					if (iJet == ISR_jets[entry]){ // If the ISR jet is also a B jet
						ISR_Btags++;
					}
				}
			}

			// Jet with greatest PT
			if (posLeadingPT != -1){
				h_leading_PT->Fill(PT_max);
				if(posLeadingPT == ISR_jets[entry]) ISR_greatest_PT++;

				currentJet = (Jet*) branchJet->At(posLeadingPT);
				vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
				delta_phi = deltaAng(vect_currentJet->Phi(), METpointer->Phi);
				MT_leading_jet = sqrt(2*vect_currentJet->Pt()*MET*(1-cos(delta_phi)));
				h_leading_MT->Fill(MT_leading_jet);

				h_leading_Eta->Fill(vect_currentJet->Eta());
				h_leading_DPhi_MET->Fill(delta_phi);

				h2_leading_PTEta->Fill(vect_currentJet->Pt(),vect_currentJet->Eta());
			}

			// HT
			if (1 < HT_R1/HT || 1 < HT_R2/HT){
				cout << "Error en el evento: " << entry << endl;
				cout << "HT: " << HT << "\tHT_R1: " << HT_R1 << "\tHT_R2: " << HT_R2 << endl;
				return 1;
			}

			h_HT->Fill(HT);
			h_HT_R1->Fill(HT_R1/HT);
			h_HT_R2->Fill(HT_R2/HT);
			h_BTags_per_Event->Fill(number_Btags);

		}

		cout<<"progress = 100%\t";
		cout<< "Time :"<< (clock()-initialTime)/double_t(CLOCKS_PER_SEC)<<"s"<<endl;
		cout<< "Percentage of events where the ISR jet is the jet with greatest PT: " << (Double_t) (ISR_greatest_PT*100)/numberOfEntries << "%\n";
		cout<< "Percentage of events where the ISR jet is tagged as Bjet: " << (Double_t) (ISR_Btags*100)/numberOfEntries << "%\n";

	} // End run's for cicle

	TFile* hfile = new TFile("./histos/histos.root", "RECREATE");
	h_jet_DPhi_MET->Write();
	h_jet_Eta->Write();
	h_jet_PT->Write();
	h_jet_Phi->Write();
	h_jet_MT->Write();
	h_jet_Delta_PT->Write();
	h_jet_Delta_Eta->Write();
	h_jet_DPhi_MET_other->Write();
	h_jet_PT_HT->Write();
	h_jet_multiplicity->Write();
	h_jet_PT_over_PT_others->Write();
	h_jet_Eta_over_Eta_others->Write();
	h_jet_DeltaR->Write();
	h_jet_DPhi_over_Phi_others->Write();
	h_jet_Delta_Eta_leading->Write();
	h_jet_Delta_PT_leading->Write();

	h_ISR_DPhi_MET->Write();
	h_ISR_Eta->Write();
	h_ISR_PT->Write();
	h_ISR_Phi->Write();
	h_ISR_MT->Write();
	h_ISR_Delta_PT->Write();
	h_ISR_Delta_Eta->Write();
	h_ISR_DPhi_MET_other->Write();
	h_ISR_PT_HT->Write();
	h_ISR_multiplicity->Write();
	h_ISR_PT_over_PT_others->Write();
	h_ISR_Eta_over_Eta_others->Write();
	h_ISR_DeltaR->Write();
	h_ISR_DPhi_over_Phi_others->Write();
	h_ISR_Delta_Eta_leading->Write();
	h_ISR_Delta_PT_leading->Write();

	h_MET->Write();
	h_MET_hpt1->Write();
	h_MET_hpt2->Write();
	h_MET_hpt3->Write();

	h_leading_MT->Write();
	h_leading_PT->Write();
	h_leading_Eta->Write();
	h_leading_DPhi_MET->Write();

	h_HT->Write();
	h_HT_R1->Write();
	h_HT_R2->Write();

	h_numberJet->Write();

	h_BTag->Write();
	h_BTag_PT->Write();
	h_BTag_Eta->Write();
	h_BTag_DPhi_MET->Write();
	h_BTags_per_Event->Write();

	h2_ISR_PTEta->Write();
	h2_jet_PTEta->Write();
	h2_dif_PTEta->Add(h2_ISR_PTEta,h2_jet_PTEta,1,-1);
	h2_dif_PTEta->Write();

	h2_dif_lead_PTEta->Add(h2_ISR_PTEta,h2_leading_PTEta,1,-1);
	h2_dif_lead_PTEta->Write();

	{
        TCanvas *C = new TCanvas("Eta","Pseudorapidity",1280,720);
		Present(h_ISR_Eta,h_jet_Eta,C,1,"h","Num. Jets / Total",122);
		C->Write();
		C->Close();

        C = new TCanvas("Eta ISR vs BTag","Pseudorapidity ISR vs BTag",1280,720);
		Present(h_ISR_Eta,h_BTag_Eta,C,1,"h","Num. Jets / Total",122);
		C->Write();
		C->Close();

        C = new TCanvas("Eta ISR vs Leading","Pseudorapidity ISR vs Leading",1280,720);
		Present(h_ISR_Eta,h_leading_Eta,C,1,"h","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum","Transverse momentum",1280,720);
		Present(h_ISR_PT,h_jet_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR vs Leading","Transverse momentum ISR vs Leading",1280,720);
		Present(h_ISR_PT,h_leading_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR vs B_Tag","Transverse momentum ISR vs B_Tag",1280,720);
		Present(h_ISR_PT,h_BTag_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR, B_Tag, Leading","Transverse momentum ISR, B_Tag, Leading",1280,720);
		Present_3(h_ISR_PT,h_BTag_PT,h_leading_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR, B_Tag, Leading LOG","Transverse momentum ISR, B_Tag, Leading LOG",1280,720);
		Present_3(h_ISR_PT,h_BTag_PT,h_leading_PT,C,2,"PT [GeV]","Num. Jets / Total",12,12,true);
		C->Write();
		C->Close();

		C = new TCanvas("Transverse mass Leading vs ISR Jet","Transverse mass Leading vs ISR Jet",1280,720);
		Present(h_ISR_MT,h_leading_MT,C,2,"MT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse mass ISR vs Jet","Transverse mass ISR vs Jet",1280,720);
		Present(h_ISR_MT,h_jet_MT,C,2,"MT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Phi","Phi",1280,720);
		Present(h_ISR_Phi,h_jet_Phi,C,3,"f","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Delta Phi - Jet - MET","Delta Phi - Jet - MET",1280,720);
		Present(h_ISR_DPhi_MET,h_jet_DPhi_MET,C,3,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Delta Phi - Jet - MET - Btag","Delta Phi - Jet - MET - Btag",1280,720);
		Present(h_ISR_DPhi_MET,h_BTag_DPhi_MET,C,3,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Delta Phi - Jet - MET - leading","Delta Phi - Jet - MET - leading",1280,720);
		Present(h_ISR_DPhi_MET,h_leading_DPhi_MET,C,1,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("MET > 120","MET > 120",1280,720);
		Present(h_MET,h_MET_hpt1,C,2,"MET","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("MET > 200","MET > 200",1280,720);
		Present(h_MET,h_MET_hpt2,C,2,"MET","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("MET > 240","MET > 240",1280,720);
		Present(h_MET,h_MET_hpt3,C,2,"MET","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("HT ratio comparison","HT ratio comparison",1280,720);
		Present(h_HT_R1,h_HT_R2,C,2,"HT","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("PT vs ETA - ISR","PT vs ETA - ISR",1280,720);
		Plot_Single_2D(h2_ISR_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - Jet","PT vs ETA - Jet",1280,720);
		Plot_Single_2D(h2_jet_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - Diff with any jet","PT vs ETA - Diff with any jet",1280,720);
		Plot_Single_2D(h2_dif_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - leading","PT vs ETA - leading",1280,720);
		Plot_Single_2D(h2_leading_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - Diff with leading","PT vs ETA - Diff with leading",1280,720);
		Plot_Single_2D(h2_dif_lead_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("HT","HT",1280,720);
		Plot_Single(h_HT,C,2, "HT [GeV]", "Num. Jets / Total", 12, 12);
        C->Write();
        C->Close();

		C = new TCanvas("Number_of_B_Tags","Number of B Tags",1280,720);
		Plot_Single(h_BTags_per_Event,C,2, "B Tags / event", "Num. Jets / Total", 12, 12);
        C->Write();
        C->Close();

		C = new TCanvas("Jet_multiplitcity","Jet multiplicity",1280,720);
        Present(h_ISR_multiplicity,h_jet_multiplicity,C,2,"Tracks","Num. Jets / Total");
        C->Write();
        C->Close();

		C = new TCanvas("Delta_R_-_Jet_size","Delta R - Jet Size",1280,720);
		Present(h_ISR_DeltaR,h_jet_DeltaR,C,1,"Delta_R","Num. Jets / Total");
		C->Write();
		C->Close();

        // Correlated variables
        C = new TCanvas("Cor_Delta_PT_Jet", "Delta PT jet",1280,720);
        Present(h_ISR_Delta_PT,h_jet_Delta_PT,C,2,"PT [GeV]","Num. Jets / Total");
        C->Write();
        C->Close();

		C = new TCanvas("Cor_PT_proportion","PT proportion",1280,720);
		Present(h_ISR_PT_HT,h_jet_PT_HT,C,2,"PT/HT","Num. Jets / Total");
		C->Write();
		C->Close();

        C = new TCanvas("Cor_Delta_Eta_Average","Delta Eta Average",1280,720);
		Present(h_ISR_Delta_Eta,h_jet_Delta_Eta,C,2,"Dh","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Cor_Delta_Phi_Jet_MET_other_jets","Delta Phi - Jet MET - other jets",1280,720);
		Present(h_ISR_DPhi_MET_other,h_jet_DPhi_MET_other,C,2,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Cor_PT_over_<PT_other>","PT/<PT_other>",1280,720);
		Present(h_ISR_PT_over_PT_others,h_jet_PT_over_PT_others,C,2,"PT/<PT>","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Cor_Eta_over_<Eta_other>","Eta/<Eta_other>",1280,720);
		Present(h_ISR_Eta_over_Eta_others,h_jet_Eta_over_Eta_others,C,3,"h/<h>","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Cor_Delta_Phi_over_<Delta_Phi_other>","Delta_Phi/<Delta_Phi_other>",1280,720);
		Present(h_ISR_DPhi_over_Phi_others,h_jet_DPhi_over_Phi_others,C,3,"Df/<Df>","Num. Jets / Total",122);
		C->Write();
		C->Close();

		// Comparison with the leading Jet
		C = new TCanvas("Leading_Delta_PT","Delta PT: PT_leading-PT",1280,720);
		Present(h_ISR_Delta_PT_leading,h_jet_Delta_PT_leading,C,2,"(PT_leading - PT)","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Leading_Delta_Eta","Delta Eta: |Eta-Eta_leading|",1280,720);
		Present(h_ISR_Delta_Eta_leading,h_jet_Delta_Eta_leading,C,2,"|Eta - Eta_leading|","Num. Jets / Total");
		C->Write();
		C->Close();

	}

	hfile->Close();

	TFile* hfile2 = new TFile("./histos/histos2.root", "RECREATE");
	h_ISR_PT_comp->Write();
	h_ISR_Eta_comp->Write();
	h_ISR_DPhi_MET_comp->Write();

	hist_ISR_PT->Write();
	hist_ISR_Abs_Eta->Write();
	hist_ISR_DPhi_MET->Write();
	hist_ISR_PT_ratio->Write();
	hist_ISR_Delta_Eta->Write();
	hist_ISR_DPhi_MET_other->Write();
	hist_ISR_Delta_PT_leading->Write();
	hist_ISR_Delta_Eta_leading->Write();

	hist_jet_PT->Write();
	hist_jet_Abs_Eta->Write();
	hist_jet_DPhi_MET->Write();
	hist_jet_PT_ratio->Write();
	hist_jet_Delta_Eta->Write();
	hist_jet_DPhi_MET_other->Write();
	hist_jet_Delta_PT_leading->Write();
	hist_jet_Delta_Eta_leading->Write();

	hfile2->Close();

	return 0;
}
Esempio n. 25
0
void makePlots (string configFilePath){
  if ((  inputRootFileNum.size() > 0 )) 
    {
      for (int i=0; i<numHistos; i++) 
        {
          double y_max = 0.0;	 
          TCanvas *c = new TCanvas(theHistNameStrings.at(i).c_str(), "", 81,58,500,602);
 
          TH1* h_num;        // histograms for Numerator
          TH1* h_den;        // histohrams for Denominator
          int whichHisto = 0;

	  TMultiGraph *mg = new TMultiGraph();
          for (int j=0;j<inputRootFileNum.size();j++)
	    {
             whichHisto=j*numHistos; 
	      
	      int a = 0;
	      bool foundHisto = false;
	      if (theHistNameStrings.at(i) == theHistNameStrings.at(i+whichHisto)) 
		{
		  foundHisto=true; 
		  a=i;
		}
	      else 
		{
		  for (a = 0; a < numHistos; a++)
		    {
		      if (theHistNameStrings.at(i) == theHistNameStrings.at(a+whichHisto))
			{
			  foundHisto = true;
			  break;
			}
		    }
		}
	      //-----------------------------------------------------------
	      string hist2name = listHistosNum->At(a+whichHisto)->GetName();
	      if (foundHisto == true)
		{
                  h_num = (TH1*)listHistosNum->At(i+whichHisto);
                  h_den = (TH1*)listHistosDen->At(a+whichHisto);

                  TH1F* H_bins_num;
                  TH1F* H_bins_den;
                  int id = 0;
                  for (int k = 0; k < inputXtitle.size(); k++)
                   {
                     if (hist2name == inputHistoName.at(k)){
                      id=k;
                    }
                   }
                  if (inputdifferentBinSize.at(id)==1){
                     int Nbins = h_num->GetXaxis()->GetNbins();
                     int arrayD = (int*)inputNbins.at(id);
                     float *BINS = new float [arrayD];
                     for (int b = 0; b <= arrayD; b++ )
                       {
                          if (b < (arrayD-1))
                           {
                             BINS[b] = (float)b*(h_num->GetXaxis()->GetBinWidth(b));
                           }
                          else {
                             BINS[b] = (float)inputBinSize.at(id);
                          }
                       }
                     H_bins_num = new TH1F("h_NUM", "h_NUM", inputNbinMax.at(id), BINS);
                     H_bins_den = new TH1F("h_DEN", "h_DEN", inputNbinMax.at(id), BINS);
                     for (int b = 0; b <= (Nbins+1); b++ )
                       {
                         H_bins_num->SetBinContent(b, h_num->GetBinContent(b));
                         H_bins_den->SetBinContent(b, h_den->GetBinContent(b));
                       }
                  }

                  if (inputdifferentBinSize.at(id)==1){
                     TGraphAsymmErrors* gr1 = new TGraphAsymmErrors( H_bins_num, H_bins_den, "b(1,1) mode" );
                  } else{
                    cout << "h_num "<<h_num->GetXaxis()->GetNbins() << "  h_den "<<h_den->GetXaxis()->GetNbins()<<endl;
                    cout << "h_num "<<h_num->Integral() << "  h_den "<<h_den->Integral()<<endl;
                    TGraphAsymmErrors* gr1 = new TGraphAsymmErrors( h_num, h_den, "b(1,1) mode" );
                  }
		  int setcolor = inputColor.at(j);
		  int marker   = inputMarkerStyle.at(j);
                  string processlegend = (inputLegend.at(j)).c_str();
                  gr1->SetMarkerStyle(marker);
                  gr1->SetMarkerColor(setcolor);
                  gr1->SetTitle(processlegend.c_str());
                  gr1->SetFillStyle(0);
                  mg->SetTitle(hist2name.c_str());
                  mg->Add(gr1);
		}// close if (foundHisto)
 
	      c->cd();
 	      c->SetGrid(); 
	    } // close for loop inputRootFile

          mg->Draw("APsame");
          for (int k = 0; k < inputXtitle.size(); k++)
           {
              if (hist2name == inputHistoName.at(k))
               {
                 mg->GetXaxis()->SetTitle((inputXtitle.at(k)).c_str());
                 mg->GetYaxis()->SetTitle((inputYtitle.at(k)).c_str());
                 mg->GetXaxis()->SetTitleSize(0.05);
                 mg->GetYaxis()->SetTitleSize(0.05);
                 mg->SetMaximum((float)inputYrangeMax.at(k));
               }
           }
          c->Update();
          TLegend* legend = c->BuildLegend(0.55,0.8,0.90,0.94);
          //TLegend *legend = new TLegend(0.2, 0.85-.035*inputLegend.size(), 0.5, 0.90,NULL,"brNDC");
          legend->SetTextFont(42);
          legend->SetLineColor(1);
          legend->SetLineStyle(1);
          legend->SetLineWidth(1);
          legend->SetFillColor(0);
          legend->SetFillStyle(1001);
          legend->SetBorderSize(0);
          legend->SetFillColor(kWhite);

	  TFile *hfile = (TFile*)gROOT->FindObject(HistosOutputRootFile.c_str());
	  if (hfile) {hfile->Close();}
	  hfile = new TFile(HistosOutputRootFile.c_str(),"UPDATE");

          for (int o = 0; o < inputHistoName.size(); o++)
             {
                if ( c->GetName() == inputHistoName.at(o) )
                  {
                     string save = configFilePath+"/"+inputHistoName.at(o)+".pdf";  
                     c->SaveAs(save.c_str());
                     c->Write();    
                     break;
                  }
             }

	  hfile->Close();
          c->Close();
	  
	}  // close foor loop numHistos     
      
    } // close if numHistos % inputRootFile.size() == 0
} // close  makePlots function
Esempio n. 26
0
void drawCtauFrom2DPlot(RooWorkspace& myws,   // Local workspace
                        string outputDir,     // Output directory
                        struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                        struct KinCuts cut,   // Variable with current kinematic cuts
                        map<string, string>  parIni,   // Variable containing all initial parameters
                        string plotLabel,     // The label used to define the output file name
                        // Select the type of datasets to fit
                        string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                        bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                        // Select the type of object to fit
                        bool incJpsi,         // Includes Jpsi model
                        bool incPsi2S,        // Includes Psi(2S) model
                        bool incBkg,          // Includes Background model     
                        // Select the fitting options
                        // Select the drawing options
                        bool setLogScale,     // Draw plot with log scale
                        bool incSS,           // Include Same Sign data
                        double binWidth       // Bin width
                        ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string hOSName = Form("dhCTAUERRTot_Tot_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameBkg  = Form("dhCTAUERR_Bkg_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameJpsi = Form("dhCTAUERR_Jpsi_%s", (isPbPb?"PbPb":"PP"));
  string hOSNamePsi2S = Form("dhCTAUERR_Psi2S_%s", (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  vector<double> range; range.push_back(cut.dMuon.ctau.Min); range.push_back(cut.dMuon.ctau.Max);

  double minRange = -4.0;
  double maxRange = 7.0;
  Double_t outTot = myws.data(dsOSName.c_str())->numEntries();
  Double_t outErr = myws.data(dsOSName.c_str())->reduce(Form("(ctau>%.6f || ctau<%.6f)", range[1], range[0]))->numEntries();
  int nBins = min(int( round((maxRange - minRange)/binWidth) ), 1000);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  double normJpsi  = 1.0;  if (myws.data(hOSNameJpsi.c_str()))  { normJpsi  = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameJpsi.c_str())->sumEntries();  }
  double normPsi2S = 1.0;  if (myws.data(hOSNamePsi2S.c_str())) { normPsi2S = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNamePsi2S.c_str())->sumEntries(); }
  double normBkg   = 1.0;  if (myws.data(hOSNameBkg.c_str()))   { normBkg   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameBkg.c_str())->sumEntries();   }
  double normTot   = 1.0;  if (myws.data(hOSName.c_str()))  { normTot   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSName.c_str())->sumEntries();  }

  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(minRange, maxRange));
  frame->updateNormVars(RooArgSet(*myws.var("invMass"), *myws.var("ctau"), *myws.var("ctauErr"))) ;
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kViolet+6), VLines(), DrawOption("LF"), NumCPU(32), LineColor(kBlack)
                                       );
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))) )),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kAzure-9), VLines(), DrawOption("LF"), NumCPU(32)
                                       );
  if (incJpsi) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }
  if (incPsi2S) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SNo_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }  
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDFLINE"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent), 
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  
  // set the CMS style
  setTDRStyle();

  // Create the pull distribution of the fit 
  RooHist *hpull = frame->pullHist(0, "PDF", true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("ctau")->frame(Title("Pull Distribution"), Bins(nBins), Range(minRange, maxRange));
  frame2->addPlotable(hpull, "PX"); 
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cCtauFig_%s", (isPbPb?"PbPb":"PP")), "cCtauFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(minRange, 0.0, maxRange, 0.0);
  
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  frame->GetXaxis()->SetTitleSize(0.045);
  frame->GetXaxis()->SetTitleFont(42);
  frame->GetXaxis()->SetTitleOffset(3);
  frame->GetXaxis()->SetLabelOffset(3);
  frame->GetYaxis()->SetLabelSize(0.04);
  frame->GetYaxis()->SetTitleSize(0.04);
  frame->GetYaxis()->SetTitleOffset(1.7);
  frame->GetYaxis()->SetTitleFont(42);
  setCtauFrom2DRange(myws, frame, dsOSNameCut, setLogScale, range, outErr);
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printCtauFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
  if (isPbPb) {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } else {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } 
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq p_{T}^{#mu#mu} < %.1f GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.21, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  if (outErr>0.0) {
    t->DrawLatex(0.21, 0.86-dy, Form("Excl: (%.4f%%) %.0f evts", (outErr*100.0/outTot), outErr)); dy+=1.5*0.045;
  }

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe");
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if(frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","fl"); }
  if((incBkg && (incJpsi || incPsi2S)) && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background","fl");  }
  if(incBkg && incJpsi && frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"J/#psi Prompt","l"); }
  if(incBkg && incJpsi && frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"J/#psi Non-Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SPR")) { leg->AddEntry(frame->findObject("PSI2SPR"),"#psi(2S) Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SNOPR")) { leg->AddEntry(frame->findObject("PSI2SNOPR"),"#psi(2S) Non-Prompt","l"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  //CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  //---plot pull
  pad2->Draw();
  pad2->cd();
    
  frame2->SetTitle("");
  frame2->GetYaxis()->CenterTitle(kTRUE);
  frame2->GetYaxis()->SetTitleOffset(0.4);
  frame2->GetYaxis()->SetTitleSize(0.1);
  frame2->GetYaxis()->SetLabelSize(0.1);
  frame2->GetYaxis()->SetTitle("Pull");
  frame2->GetXaxis()->CenterTitle(kTRUE);
  frame2->GetXaxis()->SetTitleOffset(1);
  frame2->GetXaxis()->SetTitleSize(0.12);
  frame2->GetXaxis()->SetLabelSize(0.1);
  frame2->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

  frame2->Draw(); 
  
  // *** Print chi2/ndof 
  printChi2(myws, pad2, frame, "ctau", dsOSName.c_str(), pdfTotName.c_str(), nBins, false);
  
  pline->Draw("same");
  pad2->Update();
  
  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  

  cFig->Clear();
  cFig->Close();

}
Esempio n. 27
0
void plotInfoByRun(){
  setTDRStyle();
  gROOT->ForceStyle();
  TFile *data = TFile::Open("test.root"); 
  TTree *tree=(TTree*) data->Get("tree");

  int nrunsmax=100;
  int nruns;
  int runnumberTMP[nrunsmax];
  double lumiTMP[nrunsmax];
  int NumOfJetsTMP[nrunsmax];
  double SumJetPtTMP[nrunsmax];
  int SelectedEvtsTMP[nrunsmax];
  int NumOfJets_dijetsTMP[nrunsmax];
  double SumJetPt_dijetsTMP[nrunsmax];
  int SelectedEvts_dijetsTMP[nrunsmax];


  tree->SetBranchAddress("nruns",&nruns);
  tree->SetBranchAddress("runnumber",&runnumberTMP);
  tree->SetBranchAddress("lumi",&lumiTMP);
  tree->SetBranchAddress("SumJetPt",&SumJetPtTMP);
  tree->SetBranchAddress("NumOfJets",&NumOfJetsTMP);
  tree->SetBranchAddress("SelectedEvts",&SelectedEvtsTMP);
  tree->SetBranchAddress("SumJetPt_dijets",&SumJetPt_dijetsTMP);
  tree->SetBranchAddress("NumOfJets_dijets",&NumOfJets_dijetsTMP);
  tree->SetBranchAddress("SelectedEvts_dijets",&SelectedEvts_dijetsTMP);
  tree->GetEntry(0);

  for(int i=0; i<nruns; i++){
    cout<<"runnumberTMP["<< i<<"]= "<<runnumberTMP[i] << endl;
  }

  int runnum[nruns];
  double lumi[nruns];
  int selEv[nruns];
  int Njets[nruns];
  double JetSumPt[nruns];
  int selEv_dj[nruns];
  int Njets_dj[nruns];
  double JetSumPt_dj[nruns];

  //reorder the runnnumbers
  int NewI=0;
  int minRN;
  int minRNfix=3*runnumberTMP[0];
  while(NewI<nruns){
    cout<< " runnumberTMP[0] "<< runnumberTMP[0] << endl;
  int MinI=999;
  minRN=minRNfix;
  for(int i=0; i<nruns; i++) {
    if(runnumberTMP[i]<minRN && runnumberTMP[i]!=-1){
      minRN=runnumberTMP[i];
      MinI=i;
    }
  }
  runnum[NewI]=runnumberTMP[MinI];
  lumi[NewI]=lumiTMP[MinI];
  selEv[NewI]=SelectedEvtsTMP[MinI];
  Njets[NewI]=NumOfJetsTMP[MinI];
  JetSumPt[NewI]=SumJetPtTMP[MinI];
  selEv_dj[NewI]=SelectedEvts_dijetsTMP[MinI];
  Njets_dj[NewI]=NumOfJets_dijetsTMP[MinI];
  JetSumPt_dj[NewI]=SumJetPt_dijetsTMP[MinI];
  cout<< "NewI " <<NewI << " runnum[NewI] "<<runnum[NewI] <<" lumi[NewI]  " << lumi[NewI]<< endl;
  NewI++;
  runnumberTMP[MinI]=-1;
}

  TString names[nrunsmax];
  char arg[100];

  for(int n=0; n<nruns; n++){
    cout<< "runnum "<< runnum[n] << endl;
    sprintf(arg,"%d",runnum[n]);
    names[n]=(TString)arg;
  }
  

  //define histos with right number of bins

  int nbins=nruns;

  TH1D *SelectedEvts = new TH1D("SelectedEvts","SelectedEvts",nbins,0.,nbins-1);
  TH1D *AvJetPt = new TH1D("AvJetPt","AvJetPt",nbins,0.,nbins-1);
  TH1D *SelectedEvts_dijets = new TH1D("SelectedEvts_dijets","SelectedEvts_dijets",nbins,0.,nbins-1);
  TH1D *AvJetPt_dijets = new TH1D("AvJetPt_dijets","AvJetPt_dijets",nbins,0.,nbins-1);

  for(int h=0; h<nbins;h++){

    cout<<"name "<< names[h] << "  value "<<  selEv[h]<<"/"<<lumi[h] << endl;
    if(lumi[h]<=0.) continue;

    SelectedEvts->GetXaxis()->SetBinLabel(h+1,names[h]);
    SelectedEvts->SetBinContent(h+1,selEv[h]/lumi[h]);
    //    if(selEv[h]>0)    SelectedEvts->SetBinError(h+1,sqrt(selEv[h])/lumi[h]);
    //
    SelectedEvts_dijets->GetXaxis()->SetBinLabel(h+1,names[h]);
    SelectedEvts_dijets->SetBinContent(h+1,selEv_dj[h]/lumi[h]);
    //
    AvJetPt->GetXaxis()->SetBinLabel(h+1,names[h]);
    if(Njets[h]>0) AvJetPt->SetBinContent(h+1,JetSumPt[h]/Njets[h]);
    //
    AvJetPt_dijets->GetXaxis()->SetBinLabel(h+1,names[h]);
    if(Njets_dj[h]>0) AvJetPt_dijets->SetBinContent(h+1,JetSumPt_dj[h]/Njets_dj[h]);
  }
  //style
    SelectedEvts->SetYTitle("Events/lumi [nb]");
    SelectedEvts->LabelsOption("v","X");
    SelectedEvts->SetMaximum(1.5*SelectedEvts->GetMaximum());
    //
    SelectedEvts_dijets->SetYTitle("Events/lumi [nb]");
    SelectedEvts_dijets->LabelsOption("v","X");
    SelectedEvts_dijets->SetMaximum(1.5*SelectedEvts_dijets->GetMaximum());
    //
    AvJetPt->SetYTitle("Average Jet p_{T} [GeV]");
    AvJetPt->LabelsOption("v","X");
    AvJetPt->SetMaximum(1.5*AvJetPt->GetMaximum());
    //
    AvJetPt_dijets->SetYTitle("Average Jet p_{T}[GeV]");
    AvJetPt_dijets->LabelsOption("v","X");
    AvJetPt_dijets->SetMaximum(1.5*AvJetPt_dijets->GetMaximum());



  TCanvas *c = new TCanvas("c","",600,600);
  TPaveText *title = new TPaveText(0.5,0.75,0.9,0.9,"blNDC");
  title->SetFillStyle(4000);
  title->SetFillColor(kWhite);
  title->SetBorderSize(0.1);
  title->SetTextFont(42);
  title->AddText("JPT jets");
  title->AddText("p_{T}>25 GeV , | #eta|<2.6");
  //
  TPaveText *titledj = new TPaveText(0.5,0.75,0.9,0.9,"blNDC");
  titledj->SetFillStyle(4000);
  titledj->SetFillColor(kWhite);
  titledj->SetBorderSize(0.1);
  titledj->SetTextFont(42);
  titledj->AddText("JPT dijets");
  titledj->AddText("p_{T}>25 GeV , | #eta|<3 , #Delta#phi>2.1");
  //


  SelectedEvts->Draw();
  title->Draw();
  c->SaveAs("SelectedEvts.gif");
  AvJetPt->Draw();
  title->Draw();
  c->SaveAs("AvJetPt.gif");
  title->Draw();
  SelectedEvts_dijets->Draw();
  titledj->Draw();
  c->SaveAs("SelectedEvts_dijets.gif");
  AvJetPt_dijets->Draw();
  titledj->Draw();
  c->SaveAs("AvJetPt_dijets.gif");
  c->Close();

}
void plotVBFVHReweighted(){
  gROOT->ProcessLine(".x tdrstyle.cc");
  gStyle->SetOptStat(0);

  TString INPUT_NAME = "HtoZZ4l_Phantom_125p6_VHDistributions_GenLevel.root";
  TString OUTPUT_NAME = "HtoZZ4l_Phantom_125p6_VHReweightingPlots_GenLevel.root";

  double mPOLE = 125.6;
  float ZZMass_PeakCut[2] ={ 125.1, 126.1 }; // Spin 0 analysis

  float templateWeight = 1;
  float GenDiJetMass;
  float MC_weight;
  float ZZMass = 0;

  TString coutput_common = user_TemplateswithTrees_dir + "../VHContributions/Plots/GenLevel/";
  gSystem->Exec("mkdir -p " + coutput_common);
  TString coutput = coutput_common + OUTPUT_NAME;
  TFile* foutput = new TFile(coutput, "recreate");

  const int kNumTemplates = 3;
  TString templatetitles[kNumTemplates] ={ "VBF Sig", "VBF Bkg", "VBF Int" };
  TString templatenames[kNumTemplates] ={ "VBF_Sig", "VBF_Bkg", "VBF_Int" };
  TH1F* hVBF_onshell_LC[kNumTemplates] ={ 0 };
  TH1F* hVBF_offshell_LC[kNumTemplates] ={ 0 };
  TH1F* hVBF_onshell_scaled[kNumTemplates] ={ 0 };
  TH1F* hVBF_offshell_scaled[kNumTemplates] ={ 0 };
  TH1F* hVBF_onshell_scaled_wVBF[kNumTemplates] ={ 0 };
  TH1F* hVBF_offshell_scaled_wVBF[kNumTemplates] ={ 0 };

  for (int erg_tev=7; erg_tev<=8; erg_tev++){
    for (int folder=0; folder<3; folder++){
      TString comstring;
      comstring.Form("%i", erg_tev);
      TString erg_dir;
      erg_dir.Form("LHC_%iTeV/", erg_tev);
      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;
      TString cinput_common = user_TemplateswithTrees_dir + "../VHContributions/" + erg_dir;
      cinput_common += user_folder[folder] + "/";
      TString cinput = cinput_common + INPUT_NAME;
      TFile* finput = new TFile(cinput, "read");
      if (finput->IsZombie()){
        delete finput;
        continue;
      }
      else if (finput==0) continue;

      cout << "Opened file " << finput->GetName() << endl;
      for (int tr=0; tr<kNumTemplates; tr++){
        TString templatename = "VBF_";
        templatename += templatenames[tr];

        TH1F* hVBF_onshell_LC_temp = (TH1F*)finput->Get(Form("%s_onshell_LC", templatename.Data()));
        TH1F* hVBF_offshell_LC_temp = (TH1F*)finput->Get(Form("%s_offshell_LC", templatename.Data()));
        TH1F* hVBF_onshell_scaled_temp = (TH1F*)finput->Get(Form("%s_onshell_scaled", templatename.Data()));
        TH1F* hVBF_offshell_scaled_temp = (TH1F*)finput->Get(Form("%s_offshell_scaled", templatename.Data()));
        TH1F* hVBF_onshell_scaled_wVBF_temp = (TH1F*)finput->Get(Form("%s_onshell_scaled_wVBF", templatename.Data()));
        TH1F* hVBF_offshell_scaled_wVBF_temp = (TH1F*)finput->Get(Form("%s_offshell_scaled_wVBF", templatename.Data()));

        foutput->cd();
        gStyle->SetOptStat(0);
        if (hVBF_onshell_LC[tr]==0) hVBF_onshell_LC[tr] = (TH1F*)hVBF_onshell_LC_temp->Clone(Form("%s_clone", hVBF_onshell_LC_temp->GetName()));
        else hVBF_onshell_LC[tr]->Add(hVBF_onshell_LC_temp);
        delete hVBF_onshell_LC_temp;

        if (hVBF_onshell_scaled[tr]==0) hVBF_onshell_scaled[tr] = (TH1F*)hVBF_onshell_scaled_temp->Clone(Form("%s_clone", hVBF_onshell_scaled_temp->GetName()));
        else hVBF_onshell_scaled[tr]->Add(hVBF_onshell_scaled_temp);
        delete hVBF_onshell_scaled_temp;

        if (hVBF_onshell_scaled_wVBF[tr]==0) hVBF_onshell_scaled_wVBF[tr] = (TH1F*)hVBF_onshell_scaled_wVBF_temp->Clone(Form("%s_clone", hVBF_onshell_scaled_wVBF_temp->GetName()));
        else hVBF_onshell_scaled_wVBF[tr]->Add(hVBF_onshell_scaled_wVBF_temp);
        delete hVBF_onshell_scaled_wVBF_temp;

        if (hVBF_offshell_LC[tr]==0) hVBF_offshell_LC[tr] = (TH1F*)hVBF_offshell_LC_temp->Clone(Form("%s_clone", hVBF_offshell_LC_temp->GetName()));
        else hVBF_offshell_LC[tr]->Add(hVBF_offshell_LC_temp);
        delete hVBF_offshell_LC_temp;

        if (hVBF_offshell_scaled[tr]==0) hVBF_offshell_scaled[tr] = (TH1F*)hVBF_offshell_scaled_temp->Clone(Form("%s_clone", hVBF_offshell_scaled_temp->GetName()));
        else hVBF_offshell_scaled[tr]->Add(hVBF_offshell_scaled_temp);
        delete hVBF_offshell_scaled_temp;

        if (hVBF_offshell_scaled_wVBF[tr]==0) hVBF_offshell_scaled_wVBF[tr] = (TH1F*)hVBF_offshell_scaled_wVBF_temp->Clone(Form("%s_clone", hVBF_offshell_scaled_wVBF_temp->GetName()));
        else hVBF_offshell_scaled_wVBF[tr]->Add(hVBF_offshell_scaled_wVBF_temp);
        delete hVBF_offshell_scaled_wVBF_temp;
      }
      finput->Close();
    }
  }

  TH1F* hVBF_sig[2][3]={
    { hVBF_onshell_LC[0], hVBF_onshell_scaled[0], hVBF_onshell_scaled_wVBF[0] },
    { hVBF_offshell_LC[0], hVBF_offshell_scaled[0], hVBF_offshell_scaled_wVBF[0] }
  };
  TH1F* hVBF_bkg[2][3]={
    { hVBF_onshell_LC[1], hVBF_onshell_scaled[1], hVBF_onshell_scaled_wVBF[1] },
    { hVBF_offshell_LC[1], hVBF_offshell_scaled[1], hVBF_offshell_scaled_wVBF[1] }
  };
  TH1F* hVBF_int[2][3]={
    { hVBF_onshell_LC[2], hVBF_onshell_scaled[2], hVBF_onshell_scaled_wVBF[2] },
    { hVBF_offshell_LC[2], hVBF_offshell_scaled[2], hVBF_offshell_scaled_wVBF[2] }
  };
  double max_plot[2][3] ={ { 0 } };
  double min_plot[2][3] ={ { 0 } };
//  TString strmzztitle[2]={ "105.6<m_{4l}<140.6 GeV", "220<m_{4l}<1600 GeV" };
  TString strmzztitle[2]={ "On-shell", "Off-shell" };
  TString strmzzname[2]={ "Onshell", "Offshell" };
  TString strBSItitle[3]={ "Signal", "Background", "Interference" };
  TString strBSIname[3]={ "Signal", "Background", "Interference" };
  TString strScaleSchemeTitle[3]={ " (Default Phantom)", " (VH Rescaling)", " (+VBF Rescaling)" };
  cout << "Set up canvas gadgets" << endl;
  for (int os=0; os<2; os++){
    cout << strmzzname[os] << endl;
    for (int sc=0; sc<3; sc++){
      cout << strBSItitle[0] << strScaleSchemeTitle[sc] << " mJJ>=130 GeV / mJJ<130 GeV: " << hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX()) << " / " << (hVBF_sig[os][sc]->Integral() - hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX())) << " = " << hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX())/(hVBF_sig[os][sc]->Integral() - hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX())) << endl;
      cout << strBSItitle[1] << strScaleSchemeTitle[sc] << " mJJ>=130 GeV / mJJ<130 GeV: " << hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX()) << " / " << (hVBF_bkg[os][sc]->Integral() - hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX())) << " = " << hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX())/(hVBF_bkg[os][sc]->Integral() - hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX())) << endl;
      cout << strBSItitle[2] << strScaleSchemeTitle[sc] << " mJJ>=130 GeV / mJJ<130 GeV: " << hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX()) << " / " << (hVBF_int[os][sc]->Integral() - hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX())) << " = " << hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX())/(hVBF_int[os][sc]->Integral() - hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX())) << endl;

      hVBF_sig[os][sc]->SetTitle("");
      hVBF_bkg[os][sc]->SetTitle("");
      hVBF_int[os][sc]->SetTitle("");
      hVBF_sig[os][sc]->GetXaxis()->SetRangeUser(22, 129.9);
      hVBF_bkg[os][sc]->GetXaxis()->SetRangeUser(22, 129.9);
      hVBF_int[os][sc]->GetXaxis()->SetRangeUser(22, 129.9);
      hVBF_sig[os][sc]->GetXaxis()->SetTitle("m^{true}_{jj} (GeV)");
      hVBF_bkg[os][sc]->GetXaxis()->SetTitle("m^{true}_{jj} (GeV)");
      hVBF_int[os][sc]->GetXaxis()->SetTitle("m^{true}_{jj} (GeV)");
      double binwidth = hVBF_sig[os][sc]->GetBinWidth(1);
      hVBF_sig[os][sc]->GetYaxis()->SetTitleOffset(1.5);
      hVBF_bkg[os][sc]->GetYaxis()->SetTitleOffset(1.5);
      hVBF_int[os][sc]->GetYaxis()->SetTitleOffset(1.5);
      hVBF_sig[os][sc]->GetYaxis()->SetTitle(Form("Events / %.0f GeV", binwidth));
      hVBF_bkg[os][sc]->GetYaxis()->SetTitle(Form("Events / %.0f GeV", binwidth));
      hVBF_int[os][sc]->GetYaxis()->SetTitle(Form("Events / %.0f GeV", binwidth));
      hVBF_sig[os][sc]->SetLineWidth(2);
      hVBF_bkg[os][sc]->SetLineWidth(2);
      hVBF_int[os][sc]->SetLineWidth(2);
      hVBF_sig[os][sc]->SetLineStyle(1);
      hVBF_bkg[os][sc]->SetLineStyle(1);
      hVBF_int[os][sc]->SetLineStyle(1);
      if (sc==0){
        hVBF_sig[os][sc]->SetLineColor(kRed);
        hVBF_bkg[os][sc]->SetLineColor(kRed);
        hVBF_int[os][sc]->SetLineColor(kRed);
      }
      if (sc==1){
        hVBF_sig[os][sc]->SetLineColor(kViolet);
        hVBF_bkg[os][sc]->SetLineColor(kViolet);
        hVBF_int[os][sc]->SetLineColor(kViolet);
      }
      else if (sc==2){
        hVBF_sig[os][sc]->SetLineColor(kBlue);
        hVBF_bkg[os][sc]->SetLineColor(kBlue);
        hVBF_int[os][sc]->SetLineColor(kBlue);
      }
      for (int bin=1; bin<hVBF_sig[os][sc]->GetNbinsX(); bin++){
        double bcsig = hVBF_sig[os][sc]->GetBinContent(bin);
        double bcbkg = hVBF_bkg[os][sc]->GetBinContent(bin);
        double bcint = hVBF_int[os][sc]->GetBinContent(bin);

        max_plot[os][0] = max(max_plot[os][0], bcsig);
        min_plot[os][0] = min(min_plot[os][0], bcsig);
        max_plot[os][1] = max(max_plot[os][1], bcbkg);
        min_plot[os][1] = min(min_plot[os][1], bcbkg);
        max_plot[os][2] = max(max_plot[os][2], bcint);
        min_plot[os][2] = min(min_plot[os][2], bcint);
      }
      cout << "Set up region " << os << " scheme " << sc << " complete." << endl;
    }
    for (int sc=0; sc<3; sc++){
      hVBF_sig[os][sc]->GetYaxis()->SetRangeUser(min_plot[os][0]*1.5, max_plot[os][0]*1.5);
      hVBF_bkg[os][sc]->GetYaxis()->SetRangeUser(min_plot[os][1]*1.5, max_plot[os][1]*1.5);
      hVBF_int[os][sc]->GetYaxis()->SetRangeUser(min_plot[os][2]*1.5, max_plot[os][2]*1.5);
    }
  }

  foutput->cd();

  for (int os=0; os<2; os++){
    for (int bsi=0; bsi<3; bsi++){
      cout << "Begin plot of region " << os << endl;

      TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
      pt->SetBorderSize(0);
      pt->SetFillStyle(0);
      pt->SetTextAlign(12);
      pt->SetTextFont(42);
      pt->SetTextSize(0.045);
      TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
      text->SetTextSize(0.044);
      text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
      text->SetTextSize(0.0315);
//      TString cErgTev = "#font[42]{19.7 fb^{-1} (8 TeV) + 5.1 fb^{-1} (7 TeV)}";
      TString cErgTev = "#font[42]{              2e+2#mu 19.7 fb^{-1} (8 TeV)}";
      text = pt->AddText(0.537, 0.45, cErgTev);
      text->SetTextSize(0.0315);

      TString appendName;
      appendName = "_";
      appendName += strmzzname[os];
      appendName += strBSIname[bsi];
      TString canvasname = "cCompareMJJ_GenLevel";
      canvasname.Append(appendName);
      TCanvas* cc = new TCanvas(canvasname, "", 8, 30, 800, 800);
      gStyle->SetOptStat(0);
      cc->cd();
      gStyle->SetOptStat(0);
      cc->SetFillColor(0);
      cc->SetBorderMode(0);
      cc->SetBorderSize(2);
      cc->SetTickx(1);
      cc->SetTicky(1);
      cc->SetLeftMargin(0.17);
      cc->SetRightMargin(0.05);
      cc->SetTopMargin(0.07);
      cc->SetBottomMargin(0.13);
      cc->SetFrameFillStyle(0);
      cc->SetFrameBorderMode(0);
      cc->SetFrameFillStyle(0);
      cc->SetFrameBorderMode(0);

      TLegend *ll;
      ll = new TLegend(0.22, 0.70, 0.60, 0.90);
      ll->SetBorderSize(0);
      ll->SetTextFont(42);
      ll->SetTextSize(0.03);
      ll->SetLineColor(1);
      ll->SetLineStyle(1);
      ll->SetLineWidth(1);
      ll->SetFillColor(0);
      ll->SetFillStyle(0);

      for (int sc=0; sc<3; sc++){
        if (bsi==0){
          TString legendLabel = strBSItitle[bsi] + strScaleSchemeTitle[sc];
          ll->AddEntry(hVBF_sig[os][sc], legendLabel, "l");
          if (sc==0) hVBF_sig[os][sc]->Draw("hist");
          else hVBF_sig[os][sc]->Draw("histsame");
        }
        else if (bsi==1){
          TString legendLabel = strBSItitle[bsi] + strScaleSchemeTitle[sc];
          ll->AddEntry(hVBF_bkg[os][sc], legendLabel, "l");
          if (sc==0) hVBF_bkg[os][sc]->Draw("hist");
          else hVBF_bkg[os][sc]->Draw("histsame");
        }
        else if (bsi==2){
          TString legendLabel = strBSItitle[bsi] + strScaleSchemeTitle[sc];
          ll->AddEntry(hVBF_int[os][sc], legendLabel, "l");
          if (sc==0) hVBF_int[os][sc]->Draw("hist");
          else hVBF_int[os][sc]->Draw("histsame");
        }
      }

      ll->Draw("same");
      pt->Draw();

      TPaveText *pt10 = new TPaveText(0.80, 0.86, 0.90, 0.90, "brNDC");
      pt10->SetBorderSize(0);
      pt10->SetTextAlign(12);
      pt10->SetTextSize(0.03);
      pt10->SetFillStyle(0);
      pt10->SetTextFont(42);
      TText* text10;
      text10 = pt10->AddText(0.01, 0.01, strmzztitle[os]);
      pt10->Draw();

      foutput->WriteTObject(cc);

      delete pt10;
      delete ll;
      cc->Close();
      delete pt;

      cout << "End plot of region " << os << endl;
    }
  }

  for (int tr = 0; tr < kNumTemplates; tr++){
    delete hVBF_onshell_LC[tr];
    delete hVBF_offshell_LC[tr];
    delete hVBF_onshell_scaled[tr];
    delete hVBF_offshell_scaled[tr];
    delete hVBF_onshell_scaled_wVBF[tr];
    delete hVBF_offshell_scaled_wVBF[tr];
  }
  foutput->Close();
}
Esempio n. 29
0
void
DrawPlot::printHist(const TString& fullName, const TString& sectorName, const bool normalise, const bool plotZeroApe){
  if(thesisMode_)gStyle->SetOptStat(0);
  
  TH1* hist(0);
  TH1* histZeroApe(0);
  TH1* designHist(0);
  if(file_)file_->GetObject(fullName + ";1", hist);
  if(fileZeroApe_)fileZeroApe_->GetObject(fullName + ";1", histZeroApe);
  designFile_->GetObject(fullName + ";1", designHist);
  if(hist && !plotZeroApe)histZeroApe = 0;
  if(!(hist || histZeroApe) || !designHist){std::cout<<"Histogram not found in file: "<<fullName<<"\n"; return;}
  else std::cout<<"Drawing histogram: "<<fullName<<"\n";
    
  std::vector<TH1*> v_hist;
  v_hist.push_back(designHist);
  if(histZeroApe)v_hist.push_back(histZeroApe);
  if(hist)v_hist.push_back(hist);
  
  if(normalise)this->scale(v_hist, 100.);
  
  const double maxY(this->maximumY(v_hist));
  //const double minY(this->minimumY(v_hist));
  this->setRangeUser(v_hist, 0., 1.1*maxY);
  
  
  const double maxYAxis(1.1*maxY);
  if(maxYAxis<10.)TGaxis::SetMaxDigits(3);
  else TGaxis::SetMaxDigits(4);
  if(sectorName.Contains("h_weightX") || sectorName.Contains("h_weightY")){
    if(maxYAxis<0.6){
      if(hist)hist->SetNdivisions(506, "Y");
      if(histZeroApe)histZeroApe->SetNdivisions(506, "Y");
      if(designHist)designHist->SetNdivisions(506, "Y");
    }
    if(maxYAxis<0.3){
      if(hist)hist->SetNdivisions(503, "Y");
      if(histZeroApe)histZeroApe->SetNdivisions(503, "Y");
      if(designHist)designHist->SetNdivisions(503, "Y");
    }
  }
  if(sectorName.Contains("h_d0BeamspotErr")){
    if(hist)hist->GetXaxis()->SetNdivisions(506);
    if(histZeroApe)histZeroApe->GetXaxis()->SetNdivisions(506);
    if(designHist)designHist->GetXaxis()->SetNdivisions(506);
  }
  if(sectorName.Contains("h_hitsPixel")){
    TGaxis::SetMaxDigits(3);
  }
  
  this->setLineWidth(v_hist, 2);
  if(histZeroApe)histZeroApe->SetLineColor(2);
  if(histZeroApe)histZeroApe->SetLineStyle(2);
  if(hist)hist->SetLineColor(4);
  if(hist)hist->SetLineStyle(4);
  
  TCanvas* canvas = new TCanvas("canvas");
  canvas->cd();
  
  this->draw(v_hist);
  if(delta0_){
    const double xLow(designHist->GetXaxis()->GetXmin());
    const double xUp(designHist->GetXaxis()->GetXmax());
    TLine* baseline(0);
    baseline = new TLine(xLow,*delta0_,xUp,*delta0_);
    baseline->SetLineStyle(2);
    baseline->SetLineWidth(2);
    //baseline = new TLine(0.0005,*delta0_,0.01,*delta0_); baseline->Draw("same");
    baseline->DrawLine(xLow,*delta0_,xUp,*delta0_);
    delete baseline;
  }
  canvas->Modified();
  canvas->Update();
  
  //TPaveStats* stats =(TPaveStats*) hist->GetListOfFunctions()->At(1);
  TPaveStats* statsZeroApe(0);
  if(histZeroApe)statsZeroApe = (TPaveStats*)histZeroApe->GetListOfFunctions()->FindObject("stats");
  if(statsZeroApe){
    statsZeroApe->SetY1NDC(0.58);
    statsZeroApe->SetY2NDC(0.78);
    statsZeroApe->SetLineColor(2);
    statsZeroApe->SetTextColor(2);
  }
  TPaveStats* stats(0);
  if(hist)stats = (TPaveStats*)hist->GetListOfFunctions()->FindObject("stats");
  if(stats){
    stats->SetY1NDC(0.37);
    stats->SetY2NDC(0.57);
    stats->SetLineColor(4);
    stats->SetTextColor(4);
  }
  canvas->Modified();
  canvas->Update();
  
  TLegend* legend(0);
  const LegendEntries& legendEntries = this->adjustLegendEntry(sectorName, hist, histZeroApe, designHist);
  legend = new TLegend(legendXmin_, legendYmin_, legendXmax_, legendYmax_);
  this->adjustLegend(legend);
  legend->AddEntry(designHist, legendEntries.designLegendEntry, "l");
  if(histZeroApe)legend->AddEntry(histZeroApe, legendEntries.legendEntryZeroApe, "l");
  if(hist)legend->AddEntry(hist, legendEntries.legendEntry, "l");
  legend->Draw("same");
  
  canvas->Modified();
  canvas->Update();
  
  const TString plotName(outpath_->Copy().Append(sectorName));
  canvas->Print(plotName + ".eps");
  canvas->Print(plotName + ".png");
  
  if(legend)legend->Delete();
  if(stats)stats->Delete();
  if(canvas)canvas->Close();
  this->cleanup(v_hist);
  if(designHist)designHist->Delete();
  if(histZeroApe)histZeroApe->Delete();
  if(hist)hist->Delete();
}
Esempio n. 30
0
///
/// Process a directory recursively.
///
void html_a_directory(TDirectory *f, TString path, TEnv *params)
{
  TCanvas *c_h1 = 0;
  if (c_h1 == 0) {
    int x = params->GetValue("H1.XSize", 150);
    int y = params->GetValue("H1.YSize", 100);
    c_h1 = new TCanvas ("c_h1", "1d plots", x, y);
  }

  ///
  /// Check how to make gif plots
  ///

  char command[512];
  sprintf(command, "which pstoimg &> /dev/null");
  bool UsePstoimg = ! system(command);

  ///
  /// Generate the output directory
  ///

  gSystem->MakeDirectory (path);

  ///
  /// Get the html started
  ///

  ofstream html (path + "/index.html");
  html << "<html><head><title>" << f->GetName() << "</title></head>" << endl;
  html << "<body>" << endl;
  html << "<h1>" << f->GetName() << "</h1>" << endl;
  cout << "Processing directory " << f->GetName() << endl;

  ///
  /// Now loop over all the keys in the directory
  ///

  f->cd();
  TList *objlist = f->GetListOfKeys();
  objlist->Sort(); // order alphabetically, instead of order in which they were written
  TIterator *itr = objlist->MakeIterator();
  TKey *key;
  while ((key = static_cast<TKey*>(itr->Next())) != 0) {
    TObject *obj = key->ReadObj();

    if (obj->IsA()->InheritsFrom("TDirectory")) {
      TDirectory *d = static_cast<TDirectory*>(obj);
      html << "<br><a href=\"" << d->GetName() << "/\">" << d->GetName() << "</a>" << endl;
      html_a_directory(d, path + "/" + d->GetName(), params);
    }

    else if (obj->IsA()->InheritsFrom("TObjString")) {
      TObjString *s = static_cast<TObjString*>(obj);
      html << "<p><h2>" << key->GetName() << "</h2>" << endl;
      //html << "<blockquote><pre>" << static_cast<char*>(s->GetString())
	  // << "</pre></blockquote></p>"
	  // << endl;
      html << "<blockquote><pre>" << (s->GetString()).Data() << "</pre></blockquote></p>"<< endl;
      

    }

    //    else if (obj->IsA()->InheritsFrom("CutFlowTable")) {
    //      CutFlowTable *c = static_cast<CutFlowTable*> (obj);
    //      
    //      html << "<p><h2>" << key->GetName() << "</h2>" << endl;
    //
    //      CFTPrinterHTML txt (html);
    //      f->cd();
    //      c->PrintGlobal (txt, "All Events", "");
    //      html << "</p>" << endl;
    //    }

    else if (obj->IsA()->InheritsFrom("TCanvas")) {
      TCanvas *cnv = static_cast<TCanvas*>(obj);

      cnv->Draw();
      cnv->SaveAs(path + "/" + key->GetName() + ".eps");
      if (UsePstoimg) {
	sprintf(command, "pstoimg -type=gif %s &> /dev/null",(path + "/" + key->GetName() + ".eps").Data());
	if (system(command) != 0) {
	  cout<<"Could not convert to gif: "<<path + "/" + key->GetName() + ".eps"<<endl;
	  abort();
	}
      } else cnv->SaveAs(path + "/" + key->GetName() + ".gif");

      cnv->Close();

      html << "<p><a href=\"" << key->GetName() << ".eps\">";
      html << "<img src=\"" << key->GetName() << ".gif\">";
      html << "</a> <br> " << key->GetName() << ".gif </p>" << endl;								   
    }

    else if (obj->IsA()->InheritsFrom("TH1") && !(obj->IsA()->InheritsFrom("TH2"))) {
      TH1 *h = static_cast<TH1*> (obj);

      c_h1->cd();
      h->Draw();
      c_h1->SaveAs(path + "/" + key->GetName() + ".eps");
      if (UsePstoimg) {
	sprintf(command, "pstoimg -type=gif %s &> /dev/null",(path + "/" + key->GetName() + ".eps").Data());
	if (system(command) != 0) {
	  cout<<"Could not convert to gif: "<<path + "/" + key->GetName() + ".eps"<<endl;
	  abort();
	}
      } else c_h1->SaveAs(path + "/" + key->GetName() + ".gif");

      html << "<p><a href=\"" << key->GetName() << ".eps\">";
      html << "<img src=\"" << key->GetName() << ".gif\">";
      html << "</a> <br> " << key->GetName() << ".gif </p>" << endl;
    }
    f->cd();
  }

  ///
  /// Done!
  ///

  html << "</body></html>" << endl;
  html.close();
}