Beispiel #1
0
double runGraphicHistos(TString ifile = "tmpfitdirc.root", bool verbose_out=true, double ienergy = 5, int iupdown = 0)
{
	TCanvas *c1 = new TCanvas("myc1","myc1",1000,1200);

	if (verbose_out == false)
	{
		//supresses canvas message 
		//gErrorIgnoreLevl=kInfo;
		gROOT->ProcessLine( "gErrorIgnoreLevel = kWarning;");
	}

	double hmin = -100;
	double hmax = 100;

	hmin = -25;
	hmax = 25;

	double energy = ienergy;

	double pi_mass = .13957;
	double k_mass = .49367;

	double pi_beta = sqrt(1-pi_mass*pi_mass/(energy*energy));
	double k_beta = sqrt(1-k_mass*k_mass/(energy*energy));

	double quartz_index = 1.47;

	double pi_mrad = 1000*acos(1/(pi_beta*quartz_index));
	double k_mrad = 1000*acos(1/(k_beta*quartz_index));

	//double seperation = 5.2;
	double seperation = pi_mrad - k_mrad;
	double mean_pion = 0;
	double mean_kaon = mean_pion + seperation;
	if (verbose_out == true)
	{
		printf("Energy: %4.02f\n",energy);
		printf("Mrad Seperation: %8.03f\n",seperation);
	}
	//denominator pf spread

	TRandom3* randgen = new TRandom3();

	TFile *f1 = new TFile(ifile);
	TH1F *hpion;
	TH1F *hkaon;
	TH1F *phots_pion;
	if (iupdown == 0)
	{
		hpion = (TH1F*) f1->Get("ll_diff_pion");
		hkaon = (TH1F*) f1->Get("ll_diff_kaon");
		phots_pion = (TH1F*) f1->Get("phot_found_pion");
	}
	else if (iupdown == 1)
	{
		hpion = (TH1F*) f1->Get("ll_diff_pion_up");
		hkaon = (TH1F*) f1->Get("ll_diff_kaon_up");
		phots_pion = (TH1F*) f1->Get("phot_found_pion_up");
	}
	else if (iupdown == -1)
	{
		hpion = (TH1F*) f1->Get("ll_diff_pion_down");
		hkaon = (TH1F*) f1->Get("ll_diff_kaon_down");
		phots_pion = (TH1F*) f1->Get("phot_found_pion_down");
	}
	else
	{
		printf("Unrecognize updown arguement: %d \nFailing....\n",iupdown);
		return -1;
	}
	if (verbose_out == true)
	{
		printf("pion_ll mean, spread: %12.04f, %12.04f\n",hpion->GetMean(),hpion->GetRMS());
		printf("kaon_ll mean, spread: %12.04f, %12.04f\n",hkaon->GetMean(),hkaon->GetRMS());
	}
	double spread = seperation/2;
	double spreadsq2 = 2*spread*spread;
	//Swap kaon and pion numbers

	for (int i = 1; i < hpion->GetNbinsX()/2; i++)
	{
		double t_swap = hpion->GetBinContent(i);
		hpion->SetBinContent(i,hpion->GetBinContent(hpion->GetNbinsX() - i + 1));
		hpion->SetBinContent(hpion->GetNbinsX() - i + 1, t_swap);
	}
	for (int i = 1; i < hkaon->GetNbinsX()/2; i++)
	{
		double t_swap = hkaon->GetBinContent(i);
		hkaon->SetBinContent(i,hkaon->GetBinContent(hkaon->GetNbinsX() - i + 1));
		hkaon->SetBinContent(hkaon->GetNbinsX() - i + 1, t_swap);
	}

	double titlesize=1.2*.04;

	int rebin = 20;
	rebin = 160;
	hpion->Rebin(rebin);
	hkaon->Rebin(rebin);

	hpion->SetAxisRange(hmin,hmax);
	hkaon->SetAxisRange(hmin,hmax);

	hkaon->GetXaxis()->SetTitle("Loglikelihood difference");
	hkaon->GetYaxis()->SetTitle("A.U.");
	hkaon->GetXaxis()->SetTitleSize(titlesize);
	hkaon->GetYaxis()->SetTitleSize(titlesize);

	hpion->SetStats(false);
	hkaon->SetStats(false);

	hpion->SetLineColor(kCyan);
	//hpion->SetFillColorAlpha(kRed,.5);

	hkaon->SetLineColor(kBlue);
	//hkaon->SetFillColorAlpha(kBlue,.5);

	TLegend *leg_ll = new TLegend(.6,.6,.8,.8);
	leg_ll->AddEntry(hpion,"Pion");
	leg_ll->AddEntry(hkaon,"Kaon");
	leg_ll->SetBorderSize(0);


	hkaon->SetTitle("log(P(Pi)/P(K)) for actual Pi (red) and K (blue) at 5 GeV");



	TH1F *pion_veto_eff = new TH1F(*hpion);
	TH1F *kaon_missid = new TH1F(*hkaon);

	pion_veto_eff->SetName("pion_veto_eff");
	pion_veto_eff->SetTitle("");

	kaon_missid->SetName("kaon_missid");
	kaon_missid->SetTitle("");



	for (int i = 0; i < pion_veto_eff->GetNbinsX(); i++)
	{
		pion_veto_eff->SetBinContent(i,hpion->Integral(0,i));
		kaon_missid->SetBinContent(i,hkaon->Integral(i,kaon_missid->GetNbinsX()));
		//	printf("%12.04f %12.04f %d\n",1,1,i);
	}

	pion_veto_eff->SetAxisRange(0,10000,"Y");

	double scale_int = 1/hpion->Integral(0,pion_veto_eff->GetNbinsX());
	pion_veto_eff->Scale(scale_int);
	scale_int = 1/hkaon->Integral(0,kaon_missid->GetNbinsX());
	kaon_missid->Scale(scale_int);

	hkaon->SetTitle("");
	hpion->SetTitle("");


	if (verbose_out == true)
	{
		hkaon->Draw();
		hpion->Draw("SAME H");
		leg_ll->Draw("SAME");
		c1->SetWindowSize(1000,800);

		c1->Print("overlap.pdf");
	}

	if (verbose_out == true)
	{
		pion_veto_eff->Draw("");
		kaon_missid->Draw("SAME H");

		c1->SetWindowSize(1000,800);
		c1->Print("overlap_integral.pdf");
	}

	double linewidth=6;
	TGraph* roc_graph;
	int roc_n = pion_veto_eff->GetNbinsX();
	TVectorF xr(roc_n);//gross
	TVectorF yr(roc_n);
	double ival = 0;

	for (int i = 0; i < pion_veto_eff->GetNbinsX(); i++)
	{
		xr[i] = pion_veto_eff->GetBinContent(i);
		yr[i] = kaon_missid->GetBinContent(i);

		//	printf("%8.04f %8.04f\n",xr[i],yr[i]);	
	}

	double y1,y2,x1,x2;
	x1 = pion_veto_eff->GetBinContent(0);
	double last_x = pion_veto_eff->GetBinContent(0);
	double last_y = kaon_missid->GetBinContent(0);

	for (int i = 0; i < pion_veto_eff->GetNbinsX()-1; i++)
	{
		ival += (yr[i]+last_y)*(xr[i] - last_x)/2;
                //printf("%6d %12.09f %12.04f %12.04f %12.04f %12.04f\n",i,ival,xr[i],yr[i],last_x,last_y);
		last_x = xr[i];
		last_y = yr[i];
		
	}

	if (verbose_out == true)
	{
		printf("ROC integral: %12.04f\n",ival);
	}

	roc_graph = new TGraph(xr,yr);
	roc_graph->SetLineColor(2);
	roc_graph->SetLineWidth(4);
	//roc_graph->SetMarkerColor(4);
	//roc_graph->SetMarkerStyle(21);
	roc_graph->SetTitle("");
	roc_graph->GetXaxis()->SetTitle("Kaon Efficiency");
	roc_graph->GetYaxis()->SetTitle("Pion Rejection");
	roc_graph->GetXaxis()->SetTitleSize(titlesize);
	roc_graph->GetYaxis()->SetTitleSize(titlesize);
	roc_graph->GetXaxis()->SetLimits(0,1.01);
	roc_graph->SetMinimum(0);
	roc_graph->SetMaximum(1.01);
	roc_graph->SetLineWidth(linewidth);

	if (verbose_out == true)
	{
		roc_graph->Draw("ACP");
		c1->Print("roc_curve.gif");
	}
	spread = find_sig_val(seperation,ival,spread); 


	//FAKE version stuff below
	/*---------------------------------------------------------------------------------------------------------------------------*/




	TH1F *fhpion = (TH1F*) f1->Get("ll_diff_pion");
	TH1F *fhkaon = (TH1F*) f1->Get("ll_diff_kaon");

	fhpion->Reset();
	fhkaon->Reset();

	fhpion->SetBins(1000,hmin,hmax);
	fhkaon->SetBins(1000,hmin,hmax);

	double pion_obs, kaon_obs;
	double pion_ll_diff, kaon_ll_diff;

	for (int ii = 0; ii < 10000; ii++)
	{
		pion_obs = randgen->Gaus(mean_pion,spread);
		kaon_obs = randgen->Gaus(mean_kaon,spread);

		pion_ll_diff = -1*(pion_obs - mean_pion)*(pion_obs - mean_pion);
		pion_ll_diff += (pion_obs - mean_kaon)*(pion_obs - mean_kaon);
		pion_ll_diff /= spreadsq2;

		kaon_ll_diff = - (kaon_obs - mean_pion)*(kaon_obs - mean_pion);
		kaon_ll_diff += (kaon_obs - mean_kaon)*(kaon_obs - mean_kaon);
		kaon_ll_diff /= spreadsq2;

		fhpion->Fill(pion_ll_diff);
		fhkaon->Fill(kaon_ll_diff);
	}


	fhpion->SetAxisRange(hmin,hmax);
	fhkaon->SetAxisRange(hmin,hmax);

	fhpion->SetLineColor(kRed);
	//hpion->SetFillColorAlpha(kRed,.5);

	fhkaon->SetLineColor(kBlue);
	//hkaon->SetFillColorAlpha(kBlue,.5);

	fhkaon->SetTitle("");

	TH1F *fpion_veto_eff = new TH1F(*fhpion);
	TH1F *fkaon_missid = new TH1F(*fhkaon);

	fpion_veto_eff->SetName("pion_veto_eff");
	fpion_veto_eff->SetTitle("");

	fkaon_missid->SetName("kaon_missid");
	fkaon_missid->SetTitle("");

	for (int i = 0; i < fpion_veto_eff->GetNbinsX(); i++)
	{
		fpion_veto_eff->SetBinContent(i,fhpion->Integral(i,fpion_veto_eff->GetNbinsX()));
		fkaon_missid->SetBinContent(i,fhkaon->Integral(0,i));
	}

	fpion_veto_eff->SetAxisRange(0,10000,"Y");

	double fscale_int = 1/fhpion->Integral(0,fpion_veto_eff->GetNbinsX());
	fpion_veto_eff->Scale(fscale_int);
	fscale_int = 1/fhkaon->Integral(0,fkaon_missid->GetNbinsX());
	fkaon_missid->Scale(fscale_int);




	TGraph* froc_graph;
	int froc_n = fpion_veto_eff->GetNbinsX();
	TVectorF fxr(froc_n);
	TVectorF fyr(froc_n);

	double fival = 0;
	double flast_x = fpion_veto_eff->GetBinContent(0);
	double flast_y = fkaon_missid->GetBinContent(0);
	for (int i = 0; i < fpion_veto_eff->GetNbinsX(); i++)
	{
		fxr[i] = fpion_veto_eff->GetBinContent(i);
		fyr[i] = fkaon_missid->GetBinContent(i);


		fival -= (fyr[i]+flast_y)*(fxr[i] - flast_x)/2;
		flast_x = fxr[i];
		flast_y = fyr[i];
	}
	ival = 0;
	flast_x = fpion_veto_eff->GetBinContent(0);
	flast_y = fkaon_missid->GetBinContent(0);
	for (int i = 0; i < fpion_veto_eff->GetNbinsX(); i++)
	{

		//Why oh why is Erf not the standard definition
		double t = hmin + i*(hmax-hmin)/fpion_veto_eff->GetNbinsX();
		fxr[i] = .5 + TMath::Erf(t/(sqrt(2)*spread))/2;
		fyr[i] = .5 - TMath::Erf((t-seperation)/(sqrt(2)*spread))/2;

		fival -= (fyr[i]+flast_y)*(fxr[i] - flast_x)/2;
		flast_x = fxr[i];
		flast_y = fyr[i];
	}	
	//printf("Fake ROC integral: %12.04f\n",fival);


	froc_graph = new TGraph(fxr,fyr);
	if (verbose_out == true)
	{
		froc_graph->SetLineColor(4);
		froc_graph->SetLineWidth(linewidth);
		froc_graph->SetLineStyle(2);
		froc_graph->SetTitle("");
		froc_graph->GetXaxis()->SetTitle("\"Kaon Efficiency\"");
		froc_graph->GetYaxis()->SetTitle("\"Pion Rejection\"");
		froc_graph->GetXaxis()->SetTitleSize(titlesize);
		froc_graph->GetYaxis()->SetTitleSize(titlesize);
		froc_graph->GetXaxis()->SetLimits(0,1.01);
		froc_graph->SetMinimum(0);
		froc_graph->SetMaximum(1.01);


		roc_graph->SetFillColorAlpha(kWhite,1);
		froc_graph->SetFillColorAlpha(kWhite,1);
		TLegend *leg_roc = new TLegend(.3,.5,.7,.7);
		leg_roc->AddEntry(roc_graph,"ROC Curve");
		leg_roc->AddEntry(froc_graph,"Matched Gaussian ROC Curve");
		leg_roc->SetBorderSize(0);
		leg_roc->SetTextSize(0.04*1.1);

		froc_graph->Draw("SAME");
		leg_roc->Draw("SAME");
		c1->Print("roc_curve_overlay.pdf");
	}



	if (verbose_out == true)
	{
		printf("Matching resolution: %6.03f\n",spread);
		printf("Matching resolution per photon: %6.03f\n",spread*sqrt(phots_pion->GetMean()));
	}
	else
	{
		printf("%6.04f\n",spread);
	}
	return spread;

}
Beispiel #2
0
void MakeSystPlot(const TString& channel, TFile * input, RooWorkspace * ws, const RooArgList * obs, 
                  const Int_t p, const Int_t up, const Int_t down)
{
    TString pdfname = g_pdfname;
    pdfname.ReplaceAll("$CHANNEL", channel);

    const TString& process = g_processes[p];
    TString systUp = g_systematics[up];
    systUp.ReplaceAll("$CHANNEL", channel);
    systUp.ReplaceAll("$PROCESS", process);
    
    TString systDown = g_systematics[down];
    systDown.ReplaceAll("$CHANNEL", channel);
    systDown.ReplaceAll("$PROCESS", process);

    if (process != "Wj0b" && process != "Wj1b" && process != "Wj2b") {
        if (systUp.Contains("WJModel") || systDown.Contains("WJModel") || systUp.Contains("WJSlope") || systDown.Contains("WJSlope"))
            return;
    }

    if (process != "Zj0b" && process != "Zj1b" && process != "Zj2b") {
        if (systUp.Contains("ZJModel") || systDown.Contains("ZJModel") || systUp.Contains("ZJSlope") || systDown.Contains("ZJSlope"))
            return;
    }
    
    if (process != "TT") {
        if (systUp.Contains("TTModel") || systDown.Contains("TTModel"))
            return;
    }
    
    TH1F * h = (TH1F *) input->Get(channel + "/" + process);
    TH1F * hUp = (TH1F *) input->Get(channel + "/" + process + "_" + systUp);
    TH1F * hDown = (TH1F *) input->Get(channel + "/" + process + "_" + systDown);
    if ((h->Integral() > 0. && hUp->Integral() <= 0.) || h->Integral() <= 0.) {
        TString clonename = hUp->GetName();
        delete hUp;
        hUp = (TH1F*) h->Clone(clonename);
    }
    if ((h->Integral() > 0. && hDown->Integral() <= 0.) || h->Integral() <= 0.) {
        TString clonename = hDown->GetName();
        delete hDown;
        hDown = (TH1F*) h->Clone(clonename);
    }
    if (process == "WH" || process == "ZH" || process == "VH") {
        if (systUp.Contains("eff_b"))
            systUp.ReplaceAll("eff_b", "eff_b_SIG");
        if (systDown.Contains("eff_b"))
            systDown.ReplaceAll("eff_b", "eff_b_SIG");
    }
    RooDataHist * dhUp = new RooDataHist(process + "_" + systUp, "", *obs, hUp);
    ws->import(*dhUp);
    RooDataHist * dhDown = new RooDataHist(process + "_" + systDown, "", *obs, hDown);
    ws->import(*dhDown);
    
    h->SetStats(0);
    h->SetTitle("; BDT");
    h->SetLineColor(1);
    h->SetLineWidth(2);
    h->SetFillColor(0);
    h->SetMarkerStyle(20);
    h->SetMinimum(0.01);
    h->GetXaxis()->CenterTitle();
    
    hUp->SetLineColor(g_upcol);
    hUp->SetLineWidth(2);
    hUp->SetFillColor(0);
    
    hDown->SetLineColor(g_downcol);
    hDown->SetLineWidth(2);
    hDown->SetFillColor(0);
    
    h->Draw("e1");
    hUp->Draw("hist same");
    hDown->Draw("hist same");
    h->Draw("e1 same");
    
    TLegend * leg = new TLegend(0.35, 0.20, 0.92, 0.35);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    leg->SetLineColor(0);
    leg->SetShadowColor(0);
    leg->SetTextFont(62);
    //leg->SetTextSize(0.015);
    leg->AddEntry(h, process, "pl");
    leg->AddEntry(hUp, systUp, "l");
    leg->AddEntry(hDown, systDown, "l");
    leg->Draw();

    gPad->RedrawAxis();
    gPad->Modified();
    gPad->Update();
    gPad->Print(pdfname);
    
    delete dhUp;
    delete dhDown;
    delete leg;
    
    return;
}
void Demo_TryExtrapolationInXT_Exp0_LogLogFits(Bool_t xt=kTRUE, Float_t expo=0.)
{
        SetStyle();
        gStyle->SetOptFile(0);
        gStyle->SetOptStat(0);
        gStyle->SetOptFit(0);
 
        xt=kTRUE;

	//define dummy histogram and some style parameters
	TH1F *dum;
 	dum = new TH1F("dum","",160,5e-4,0.3); 
	dum->SetMinimum(1e-14);
	dum->SetMaximum(1);
	dum->SetTitle(Form(";x_{T};#sqrt{s}^{%0.1f}  E d^{3}#sigma/dp^{3}",expo));
	dum->SetLineWidth(0);
	dum->SetStats(0);
	dum->GetXaxis()->CenterTitle();
	dum->GetYaxis()->CenterTitle();
	dum->GetXaxis()->SetTitleSize(0.05);
	dum->GetYaxis()->SetTitleSize(0.05);
	dum->GetXaxis()->SetTitleOffset(1.17);
	dum->GetYaxis()->SetTitleOffset(1.3);

	gROOT->LoadMacro("/net/hidsk0001/d00/scratch/krajczar/ppRefForpPb_PilotRun/interpolation_HIN10005_kk/data_table_to_graph.C");

	//get 7 TeV points
	TGraphErrors *cms_7000_g = data_table_to_graph("cms",7000,xt,expo);
	cms_7000_g->SetMarkerColor(kBlack);
	
	TF1 *cms_7000_fit = new TF1("cms_7000_fit","[0]*pow(1.0+(x/[1]),[2])",10.*2./7000.,0.1);//Fit from 10 GeV/c
	cms_7000_fit->SetLineWidth(1);
	cms_7000_fit->SetParameters(3e22,2.5e-4,-7);
	cms_7000_g->Fit(cms_7000_fit,"REMW0");
	
	//get 2.36 TeV points
//	TGraphErrors *cms_2360_g = data_table_to_graph("cms",2360,xt,expo);
//	cms_2360_g->SetMarkerColor(kMagenta+3);
	
//	TF1 *cms_2360_fit = new TF1("cms_2360_fit","[0]*pow(1.0+(x/[1]),[2])",2e-3,0.1);
//	cms_2360_fit->SetLineWidth(1);
//	cms_2360_fit->SetParameters(3e22,2.5e-4,-7);
//	cms_2360_g->Fit(cms_2360_fit,"REMW0");

	//get 2.76 TeV points (KK using existing txt files)
	TGraphErrors *cms_2760_g = data_table_to_graph("cms",2760,xt,expo);
	cms_2760_g->SetMarkerColor(kMagenta+3);
	TF1 *cms_2760_fit = new TF1("cms_2760_fit","[0]*pow(1.0+(x/[1]),[2])",10.*2./2760.,0.1);//Fit from 10 GeV/c
	cms_2760_fit->SetLineColor(kMagenta+3);
	cms_2760_fit->SetLineWidth(1);
	cms_2760_fit->SetParameters(3e22,2.5e-4,-7);
	cms_2760_g->Fit(cms_2760_fit,"REMW0");
	
	//get 1.96 TeV points
	TGraphErrors *cdf_1960_g = data_table_to_graph("cdf",1960,xt,expo);
	cdf_1960_g->SetMarkerColor(kOrange-3);
	cdf_1960_g->SetMarkerStyle(30);
	
	//TGraphErrors *cdfold_1960_g = data_table_to_graph("cdfold",1960,xt);
	//cdfold_1960_g->SetMarkerColor(kBlue);
	//cdfold_1960_g->SetMarkerStyle(30);
	
	TF1 *cdf_1960_fit = new TF1("cdf_1960_fit","[0]*pow(1.0+(x/[1]),[2])",2.*10./1960.,0.1);//Fit from 10 GeV/c
	cdf_1960_fit->SetLineColor(kOrange-3);
	cdf_1960_fit->SetLineWidth(1);
	cdf_1960_fit->SetParameters(3e22,2.5e-4,-7);
	cdf_1960_g->Fit(cdf_1960_fit,"REMW0");
	
	//get 1.8 TeV points
	TGraphErrors *cdf_1800_g = data_table_to_graph("cdf",1800,xt,expo);
	cdf_1800_g->SetMarkerColor(kGreen+3);
	cdf_1800_g->SetMarkerStyle(28);

	TF1 *cdf_1800_fit = new TF1("cdf_1800_fit","[0]*pow(1.0+(x/[1]),[2])",2.*10./1800.,0.1);//Fit from 10 GeV/c
	cdf_1800_fit->SetLineColor(kGreen+3);
	cdf_1800_fit->SetLineWidth(1);
	cdf_1800_fit->SetParameters(3e22,2.5e-4,-7.2);
	cdf_1800_fit->FixParameter(2,-7.2);
	cdf_1800_g->Fit(cdf_1800_fit,"REMW0");
	
	//get 0.9 TeV points
	TGraphErrors *cms_900_g = data_table_to_graph("cms",900,xt,expo);
	cms_900_g->SetMarkerColor(kRed);
	
	TF1 *cms_900_fit = new TF1("cms_900_fit","[0]*pow(1.0+(x/[1]),[2])",2.*10./900.,0.01);//Fit from 10 GeV/c
	cms_900_fit->SetLineColor(kRed);
	cms_900_fit->SetLineWidth(1);
	cms_900_fit->SetParameters(3e22,2.5e-4,-7);
	cms_900_g->Fit(cms_900_fit,"REMW0");
	
//	TGraphErrors *ua1_900_g = data_table_to_graph("ua1",900,xt,expo);
//	ua1_900_g->SetMarkerColor(kCyan+1);
//	ua1_900_g->SetMarkerStyle(26);

	// get 0.63 TeV points
	TGraphErrors *cdf_630_g = data_table_to_graph("cdf",630,xt,expo);
	cdf_630_g->SetMarkerColor(kOrange+3);
	cdf_630_g->SetMarkerStyle(27);

	//draw graphs to canvas
	TCanvas *c1 = new TCanvas("c1","spectra interpolation",600,600);
	dum->Draw();
        //Fits are already drawn, no draw the points on top of the fits
	cdf_1960_g->Draw("pz");
	//cdfold_1960_g->Draw("pz");
//	cdf_1800_g->Draw("pz");
//	if(!xt) ua1_900_g->Draw("pz"); // abs(eta) within 2.5 changes high xt behavior
//	cdf_630_g->Draw("pz");
	cms_900_g->Draw("pz");         // draw the CMS points on top
//	cms_2360_g->Draw("pz");
	cms_2760_g->Draw("pz"); //KK
	cms_7000_g->Draw("pz");

	//make legend
	TLegend *leg1 = new TLegend(0.2,0.21,0.50,0.51,"p+p(#bar{p})");
	leg1->SetBorderSize(0);
	leg1->SetFillStyle(1);
	leg1->SetFillColor(0);
	leg1->AddEntry(cms_7000_g,"7 TeV  (CMS)","lp");
	leg1->AddEntry(cms_2760_g,"2.76 TeV (CMS)","lp");
//	leg1->AddEntry(cms_2360_g,"2.36 TeV (CMS)","lp");
	leg1->AddEntry(cdf_1960_g,"1.96 TeV  (CDF)","lp");
//	leg1->AddEntry(cdf_1800_g,"1.8 TeV  (CDF)","lp");
	leg1->AddEntry(cms_900_g,"0.9 TeV  (CMS)","lp");
//	if(!xt) leg1->AddEntry(ua1_900_g,"0.9 TeV  (UA1)  |#eta|<2.5","lp");
//	leg1->AddEntry(cdf_630_g,"0.63 TeV  (CDF)","lp");
	leg1->Draw();
	
	gPad->SetLogy();
	//if(xt) gPad->SetLogx();
	gPad->SetLogx();
	
	cms_7000_fit->Draw("same");
	cms_2760_fit->Draw("same");
	cdf_1960_fit->Draw("same");
//	cdf_1800_fit->Draw("same");
	cms_900_fit->Draw("same");

	TCanvas *c3 = new TCanvas("c3","Individual xT fits, residuals",600,500);
	TH1F *hratio = new TH1F("hratio",";x_{T};ratio",160,0.0003,0.07); //was 0.003-0.04
	hratio->SetMaximum(2.0);
	hratio->SetMinimum(0.0);
	hratio->SetStats(0);
	hratio->Draw();
		
	TGraphErrors* ratio_cdf_1960_g = divide_graph_by_function(cdf_1960_g,cdf_1960_fit);
	ratio_cdf_1960_g->SetName("ratio_cdf_1960_g");
	ratio_cdf_1960_g->SetLineColor(kOrange-9);
	ratio_cdf_1960_g->SetMarkerSize(0.9);
	ratio_cdf_1960_g->Draw("samepz");
		
	TF1 *fit1960 = new TF1("fit1960","[0]+[1]*log(x)+[2]/x/x",0.001,0.035);
	fit1960->SetLineWidth(2);
	fit1960->SetLineColor(kOrange-3);
	ratio_cdf_1960_g->Fit(fit1960,"REMW");
	fit1960->Draw("same");
		
//	TGraphErrors* ratio_cdf_1800_g = divide_graph_by_function(cdf_1800_g,cdf_1800_fit);
//	ratio_cdf_1800_g->Draw("samepz");
		
//	TGraphErrors* ratio_cdf_630_g = divide_graph_by_function(cdf_630_g,merge_fit);
	//ratio_cdf_630_g->Draw("pz");
	
	TGraphErrors* ratio_cms_7000_g = divide_graph_by_function(cms_7000_g,cms_7000_fit);
	ratio_cms_7000_g->SetName("ratio_cms_7000_g");
	ratio_cms_7000_g->Draw("samepz");
		
	TF1 *fit7000 = new TF1("fit7000","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.001,0.1);
	fit7000->SetLineWidth(2);
	ratio_cms_7000_g->Fit(fit7000,"REMW");

	TGraphErrors* ratio_cms_2760_g = divide_graph_by_function(cms_2760_g,cms_2760_fit);
	ratio_cms_2760_g->SetName("ratio_cms_2760_g");
	ratio_cms_2760_g->SetLineColor(kMagenta+3);
	ratio_cms_2760_g->Draw("samepz");
		
        TF1 *fit2760 = new TF1("fit2760","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.001,0.1);
	fit2760->SetLineWidth(2);
	fit2760->SetLineColor(kMagenta+3);
	ratio_cms_2760_g->Fit(fit2760,"REM");//REMW
		
	TGraphErrors* ratio_cms_900_g = divide_graph_by_function(cms_900_g,cms_900_fit);
	ratio_cms_900_g->SetName("ratio_cms_900_g");
	ratio_cms_900_g->Draw("samepz");
		
        TF1 *fit900 = new TF1("fit900","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.007,0.1);
        fit900->SetParameters(5.61766e-01,5.24904e+01,-2.27817e+03,3.43955e+04);
	fit900->SetLineWidth(2);
	fit900->SetLineColor(2);
	ratio_cms_900_g->Fit(fit900,"REM");//REMW
	ratio_cms_900_g->SetLineColor(kRed);
		
	TGaxis *A1 = new TGaxis(0.0003,7.0,0.07,7.0,2510*0.0003,2510*0.07,410,"-");
	A1->SetTitle("p_{T} for #sqrt{s}=5.02 TeV");
	A1->Draw();

        //Real fit should be the fit*resid
	TH1D *h900 = new TH1D("h900","900 GeV fitted spectra;x_{T}",30400,0.005,0.05);
	h900->SetLineColor(kRed);
	TH1D *h1960 = new TH1D("h1960","1.96 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h1960->SetLineColor(kOrange-3);
	TH1D *h7000 = new TH1D("h7000","7 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	TH1D *h1800 = new TH1D("h1800","1.8 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h1800->SetLineColor(kGreen+3);
	TH1D *h630 = new TH1D("h630","0.63 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h630->SetLineColor(kOrange+3);
	TH1D *h2760_EdTxt = new TH1D("h2760_EdTxt","2.76 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h2760_EdTxt->SetLineColor(kMagenta+3);

	for(int hbin=1; hbin<=30400; hbin++) {
		float xtbin = h900->GetBinCenter(hbin);
		h900->SetBinContent(hbin,cms_900_fit->Eval(xtbin)*fit900->Eval(xtbin));
		h1960->SetBinContent(hbin,cdf_1960_fit->Eval(xtbin)*fit1960->Eval(xtbin));
		h7000->SetBinContent(hbin,cms_7000_fit->Eval(xtbin)*fit7000->Eval(xtbin));
		h2760_EdTxt->SetBinContent(hbin,cms_2760_fit->Eval(xtbin)*fit2760->Eval(xtbin));
	}

	TCanvas *c5 = new TCanvas("c5","final x_{T} fits",600,500);
	TH1D* dumDirectInt = new TH1D("dumDirectInt","Final fits; x_{T} (GeV/c)",120,5e-4,0.3);
	dumDirectInt->SetMaximum(1);
	dumDirectInt->SetMinimum(1e-14);
	dumDirectInt->GetXaxis()->SetRangeUser(0.5,120.);
	dumDirectInt->SetStats(0);
	dumDirectInt->GetYaxis()->SetTitle("Ed^{3}#sigma/dp^{3}");
	dumDirectInt->Draw();
	h900->Draw("same");
	h1960->Draw("same");
	h7000->Draw("same");
	h2760_EdTxt->Draw("same");
	gPad->SetLogy();
	gPad->SetLogx();

	// inspect direct interpolations
	TCanvas *c6 = new TCanvas("c6","interpolations",600,500);
	c6->Divide(3,4);
	float s[6]; float xs[6]; float es[6]={0.0,0.0,0.0,0.0,0.0,0.0}; float exs[6];   TGraphErrors *gXS[12];
        float s_log[6]; float xs_log[6]; float es_log[6]={0.0,0.0,0.0,0.0,0.0,0.0}; float exs_log[6];
        TGraphErrors *gXS_log[12]; //KK test
        TGraphErrors *gXS_log_lemma[12]; //KK test
	float s1[1]={2.76}; float xs1[1]; float ex1[1]={0.0}; float ey1[1]; 		TGraphErrors *gXS1[12];
	float s1_5020[1]={5.02}; float xs1_5020[1]; float ex1_5020[1]={0.0}; float ey1_5020[1]; TGraphErrors *gXS1_5020[12];
	float s2[1]={2.76}; float xs2[1]; float ex2[1]={0.0}; float ey2[1]; 		TGraphErrors *gXS2[12];
	float s2_5020[1]={5.02}; float xs2_5020[1]; float ex2_5020[1]={0.0}; float ey2_5020[1]; TGraphErrors *gXS2_5020[12];
	float s900[1]={0.9}; float xs900[1]; float ex900[1]={0.0}; float ey900[1]; TGraphErrors *gXS900[12];
	float s1960[1]={1.96}; float xs1960[1]; float ex1960[1]={0.0}; float ey1960[1]; TGraphErrors *gXS1960[12];
	float s2760[1]={2.76}; float xs2760[1]; float ex2760[1]={0.0}; float ey2760[1]; TGraphErrors *gXS2760[12];
	float s7000[1]={7.0}; float xs7000[1]; float ex7000[1]={0.0}; float ey7000[1]; TGraphErrors *gXS7000[12];

	TF1 *fitXS[12];  TH1F *dumXS[12];
        TF1 *fitXS_log[12];
	float xtbins[12]={0.0051,0.007,0.01,0.015,0.02,0.025,0.03,0.035,0.04,0.042,0.045,0.049};
        //2pT/sqrt(s) = xT ==>> xT=0.0051 -> pT=12.8 GeV/c; xT=0.049 -> pT=123 GeV/c

        //errors        
        TMVA::TSpline1 *err_cms_900_xt = errors_from_graph(cms_900_g,0.115);
        TMVA::TSpline1 *err_cms_2760_xt = errors_from_graph(cms_2760_g,0.11);
        TMVA::TSpline1 *err_cms_7000_xt = errors_from_graph(cms_7000_g,0.04);	
        TMVA::TSpline1 *err_cdf_1960_xt = errors_from_graph(cdf_1960_g,0.06);

	for(Int_t ipt=0; ipt<=11; ipt++) {
						
		c6->cd(ipt+1);
		int npoints=0;

		xs[npoints]=h900->GetBinContent(h900->FindBin(xtbins[ipt])); s[npoints]=0.9; exs[npoints]=err_cms_900_xt->Eval(xtbins[ipt])*xs[npoints]; xs900[0]=xs[npoints]; ey900[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;

		xs[npoints]=h1960->GetBinContent(h1960->FindBin(xtbins[ipt])); s[npoints]=1.96; exs[npoints]=err_cdf_1960_xt->Eval(xtbins[ipt])*xs[npoints]; xs1960[0]=xs[npoints]; ey1960[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;
 
		xs[npoints]=h2760_EdTxt->GetBinContent(h2760_EdTxt->FindBin(xtbins[ipt])); s[npoints]=2.76; exs[npoints]=err_cms_2760_xt->Eval(xtbins[ipt])*xs[npoints]; xs2760[0]=xs[npoints]; ey2760[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;

		xs[npoints]=h7000->GetBinContent(h7000->FindBin(xtbins[ipt])); s[npoints]=7.0; exs[npoints]=err_cms_7000_xt->Eval(xtbins[ipt])*xs[npoints]; xs7000[0]=xs[npoints]; ey7000[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;
			
		dumXS[ipt] = new TH1F(Form("dumXS%d",ipt),Form("p_{T} = %0.0f GeV/c;#sqrt{s} [TeV]",xtbins[ipt]),100,0,20);
		dumXS[ipt]->SetMinimum(0.25*xs[npoints-1]);
		dumXS[ipt]->SetMaximum(4.0*xs[0]);
		dumXS[ipt]->SetStats(0);
		dumXS[ipt]->GetXaxis()->SetRangeUser(0.5,10.0);
              	dumXS[ipt]->GetXaxis()->CenterTitle();
               	dumXS[ipt]->GetYaxis()->CenterTitle();
               	dumXS[ipt]->GetYaxis()->SetTitle("Ed#sigma^{3}/dp^{3}");
               	dumXS[ipt]->GetXaxis()->SetTitleSize(0.10);
               	dumXS[ipt]->GetYaxis()->SetTitleSize(0.10);
               	dumXS[ipt]->GetYaxis()->SetLabelSize(0.10);
               	dumXS[ipt]->GetXaxis()->SetLabelSize(0.10);
               	dumXS[ipt]->GetXaxis()->SetTitleOffset(0.6);
               	dumXS[ipt]->GetYaxis()->SetTitleOffset(0.8);
		dumXS[ipt]->Draw();
		gPad->SetLogy();  
                gPad->SetLogx();

                std::cerr<< "npoints: " << npoints << std::endl;

		gXS[ipt] = new TGraphErrors(npoints,s,xs,es,exs);  gXS[ipt]->SetName(Form("gXS%d",ipt));
		gXS[ipt]->SetMarkerStyle(20);
		gXS_log[ipt] = new TGraphErrors(npoints,s_log,xs_log,es_log,exs_log); gXS_log[ipt]->SetName(Form("gXS_log%d",ipt));

		gXS900[ipt] = new TGraphErrors(1,s900,xs900,ex900,ey900); gXS900[ipt]->SetName(Form("gXS900_%d",ipt)); 
		gXS900[ipt]->SetMarkerStyle(20);  gXS900[ipt]->SetMarkerColor(kRed); gXS900[ipt]->Draw("pz");

		gXS1960[ipt] = new TGraphErrors(1,s1960,xs1960,ex1960,ey1960); gXS1960[ipt]->SetName(Form("gXS1960_%d",ipt)); 
		gXS1960[ipt]->SetMarkerStyle(30);  gXS1960[ipt]->SetMarkerColor(kOrange-3); gXS1960[ipt]->Draw("pz");

		gXS2760[ipt] = new TGraphErrors(1,s2760,xs2760,ex2760,ey2760); gXS2760[ipt]->SetName(Form("gXS2760_%d",ipt)); 
		gXS2760[ipt]->SetMarkerStyle(20);  gXS2760[ipt]->SetMarkerColor(kMagenta+3); gXS2760[ipt]->Draw("pz");	

		gXS7000[ipt] = new TGraphErrors(1,s7000,xs7000,ex7000,ey7000); gXS7000[ipt]->SetName(Form("gXS7000_%d",ipt)); 
		gXS7000[ipt]->SetMarkerStyle(20);  gXS7000[ipt]->SetMarkerColor(kBlack); gXS7000[ipt]->Draw("pz");	
			
		fitXS_log[ipt] = new TF1(Form("fitXS_log%d",ipt),"pol2",-0.52288,0.85733);
		gXS_log[ipt]->Fit(fitXS_log[ipt], "REM0"); //"REMW");

		// full covariance errors on fit
		TVirtualFitter *fitter = TVirtualFitter::GetFitter();
		TMatrixD matrix(3,3,fitter->GetCovarianceMatrix());
		Double_t e00 = fitter->GetCovarianceMatrixElement(0,0);
		Double_t e11 = fitter->GetCovarianceMatrixElement(1,1);
		Double_t e22 = fitter->GetCovarianceMatrixElement(2,2);
		Double_t e01 = fitter->GetCovarianceMatrixElement(0,1);
		Double_t e02 = fitter->GetCovarianceMatrixElement(0,2);
		Double_t e12 = fitter->GetCovarianceMatrixElement(1,2);

                //Due to properties of the covariance matrix:
                Double_t e10 = e01;
                Double_t e20 = e02;
                Double_t e21 = e12;

                gXS_log_lemma[ipt] = new TGraphErrors(); gXS_log_lemma[ipt]->SetName(Form("gXS_log_lemma%d",ipt));
                int kkk = 0;
                for(int kk = log10(0.8*s[0])*10000.; kk <= log10(1.3*s[npoints-1])*10000.; kk++) {
                      float kk_lemma = kk/10000.;
                      float value = fitXS_log[ipt]->Eval(kk_lemma);
                      gXS_log_lemma[ipt]->SetPoint(kkk,TMath::Power(10,kk_lemma),TMath::Power(10,value));
                      kkk++;
                }
                gXS_log_lemma[ipt]->SetLineColor(2);
                gXS_log_lemma[ipt]->Draw("same");
			
		cout << "cov(0,0) = " << e00 
		<< "\ncov(1,1) = " << e11 
		<< "\ncov(2,2) = " << e22 
		<< "\ncov(0,1) = " << e01 
		<< "\ncov(0,2) = " << e02 
		<< "\ncov(1,2) = " << e12 
		<< endl;
			
                //0.7007 = log10(5.02)
		Double_t fullerr2 = e00 + e11*0.7007*0.7007 + e22*0.7007*0.7007*0.7007*0.7007 + 2*e01*0.7007 + 2*e02*0.7007*0.7007 + 2*e12*0.7007*0.7007*0.7007;
                //Plan (1.,0.7007,0.7007^2)(COV)(1.,0.7007,0.7007^2):
                Double_t where = 0.7007;
                Double_t fullerr2_alternative = e00 + 2.*e01*where + 2.*e02*where*where + 2.*e12*where*where*where + e11*where*where + e22*where*where*where*where;
			
		cout << "full covariance error = " << TMath::Sqrt(fullerr2) << endl;
		cout << "full covariance error alternative: = " << TMath::Sqrt(fullerr2_alternative) << endl;
                float error_in_percentage = 100.*(TMath::Power(10,TMath::Sqrt(fullerr2))-1.);
                cout << "   on " << fitXS_log[ipt]->Eval(0.7007) << std::endl;
                cout << "   error in percentage: " << error_in_percentage << std::endl;

                //5020
		xs2_5020[0] = TMath::Power(10,fitXS_log[ipt]->Eval(0.7007));
		ey2_5020[0] = error_in_percentage*0.01*xs2_5020[0];
		gXS2_5020[ipt] = new TGraphErrors(1,s2_5020,xs2_5020,ex2_5020,ey2_5020); gXS2_5020[ipt]->SetName(Form("gXS2_5020_%d",ipt));
		gXS2_5020[ipt]->SetMarkerColor(7);
		gXS2_5020[ipt]->SetLineColor(7);
		gXS2_5020[ipt]->SetMarkerStyle(kOpenSquare);
		gXS2_5020[ipt]->Draw("pz");
	}
}
void addNuisanceWithToys(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,bool iVarBin=false,int iFitModel=1,int iFitModel1=1,double iFirst=150,double iLast=1500,std::string iSigMass="800",double iSigScale=0.1,int iNToys=1000) { 
  std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl;  
  if(iVarBin) std::cout << "option not implemented yet!";
  if(iVarBin) return;
  //double lFirst = 200;
  //double lLast  = 1500;
  double lFirst = iFirst;
  double lLast  = iLast;

  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "Using Initial fit model: " << iFitModel << ", fitting range: " << iFirst << "-" << iLast << " , using alternative fit model: " << iFitModel1 << std::endl; 
  std::cout << "===================================================================================================================================================" <<std::endl;

  TFile *lFile = new TFile(iFileName.c_str());
  TH1F  *lH0   = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str());
  TH1F  *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str());
  TH1F  *lSig = 0;

  // for now, use bbH signal for testing in b-tag and ggH in no-btag
  if(iDir.find("_btag") != std::string::npos) lSig = (TH1F*)lFile->Get((iDir+"/bbH"+iSigMass+"_fine_binning").c_str());
  else lSig = (TH1F*)lFile->Get((iDir+"/ggH"+iSigMass+"_fine_binning").c_str());

  TH1F *lH0Clone = (TH1F*)lH0->Clone("lH0Clone");     // binning too fine as of now? start by rebinning
  TH1F *lDataClone = (TH1F*)lData->Clone("lDataClone");   
  TH1F *lSigClone = (TH1F*)lSig->Clone("lSigClone");  
 // lH0Clone->Rebin(2);
 // lDataClone->Rebin(2);
 // lSigClone->Rebin(2);

  lSig->Rebin(10);  

  //Define the fit function
  RooRealVar lM("m","m" ,0,5000);
  lM.setRange(lFirst,lLast);
  RooRealVar lA("a","a" ,50,  0.1,200);
  RooRealVar lB("b","b" ,0.0 , -10.5,10.5);
  RooRealVar lA1("a1","a1" ,50,  0.1,1000);
  RooRealVar lB1("b1","b1" ,0.0 , -10.5,10.5);

  RooDataHist *pH0  =  new RooDataHist("Data","Data" ,RooArgList(lM),lH0);
  double lNB0 = lH0->Integral(lH0->FindBin(lFirst),lH0->FindBin(lLast));
  double lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast));
 //lNB0=500;
// lNSig0=500;
 lSig->Scale(iSigScale*lNB0/lNSig0);                                         // scale signal to iSigScale*(Background yield), could try other options
 lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast));        // readjust norm of signal hist   
  
  //Generate the "default" fit model 

  RooGenericPdf *lFit  = 0; lFit = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFit = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) {lA.setVal(0.3); lB.setVal(0.5);}
  if(iFitModel == 2) lFit = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 2) {lA.setVal(0.01); lA.setRange(0,10); }
  if(iFitModel == 3) lFit = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));
 
  // Generate the alternative model
  
  RooGenericPdf *lFit1  = 0; lFit1 = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) lFit1 = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) {lA1.setVal(0.3); lB1.setVal(0.5);}
  if(iFitModel1 == 2) lFit1 = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 2) {lA1.setVal(0.01); lA1.setRange(0,10); }
  if(iFitModel1 == 3) lFit1 = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1));
  
  //=============================================================================================================================================
  //Perform the tail fit and generate the shift up and down histograms
  //=============================================================================================================================================

  RooFitResult  *lRFit = 0;
  lRFit = lFit->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast),RooFit::Strategy(0)); 
  TMatrixDSym lCovMatrix   = lRFit->covarianceMatrix(); 
  TMatrixD  lEigVecs(2,2);    lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors();
  TVectorD  lEigVals(2);      lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues();
  cout << " Ve---> " << lEigVecs(0,0) << " -- " << lEigVecs(1,0) << " -- " << lEigVecs(0,1) << " -- " << lEigVecs(1,1) << endl;
  cout << " Co---> " << lCovMatrix(0,0) << " -- " << lCovMatrix(1,0) << " -- " << lCovMatrix(0,1) << " -- " << lCovMatrix(1,1) << endl;
  double lACentral = lA.getVal();
  double lBCentral = lB.getVal();
  lEigVals(0) = sqrt(lEigVals(0));
  lEigVals(1) = sqrt(lEigVals(1));
  cout << "===> " << lEigVals(0) << " -- " << lEigVals(1) << endl;
  
  TH1F* lH     = (TH1F*) lFit->createHistogram("fit" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral + lEigVals(0)*lEigVecs(1,0));
  TH1F* lHUp   = (TH1F*) lFit->createHistogram("Up"  ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral - lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral - lEigVals(0)*lEigVecs(1,0));
  TH1F* lHDown = (TH1F*) lFit->createHistogram("Down",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral + lEigVals(1)*lEigVecs(1,1));
  TH1F* lHUp1   = (TH1F*) lFit->createHistogram("Up1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral - lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral - lEigVals(1)*lEigVecs(1,1));
  TH1F* lHDown1 = (TH1F*) lFit->createHistogram("Down1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  std::string lNuisance1 =  iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy;
  std::string lNuisance2 =  iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy;
  lHUp    = merge(lNuisance1 + "Up"   ,lFirst,lH0,lHUp);
  lHDown  = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown);
  lHUp1   = merge(lNuisance2 + "Up"   ,lFirst,lH0,lHUp1);
  lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1);
  lH      = merge(lH0->GetName()      ,lFirst,lH0,lH);

  //=============================================================================================================================================
  //=============================================================================================================================================
  
  //Set the variables A and B to the final central values from the tail fit

  lA.setVal(lACentral);
  lB.setVal(lBCentral);
 // lA.removeRange();
 // lB.removeRange();
 
  //Generate the background pdf corresponding to the final result of the tail fit
 
 RooGenericPdf *lFitFinal  = 0; lFitFinal = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFitFinal = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 2) lFitFinal = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 3) lFitFinal = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));



  //=============================================================================================================================================
  //Perform the tail fit with the alternative fit function (once initially, before allowing tail fit to float in toy fit).
  //=============================================================================================================================================

  RooFitResult  *lRFit1 = 0;
 //lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(iFirst,iLast),RooFit::Strategy(0));  
 lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(200,1500),RooFit::Strategy(0));  
  
  //Generate the background pdf corresponding to the result of the alternative tail fit

  RooGenericPdf *lFit1Final  = 0; lFit1Final = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) lFit1Final = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 2) lFit1Final = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 3) lFit1Final = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1));

 // lA1.removeRange();
 // lB1.removeRange();
  
  //=============================================================================================================================================

  //Define RooRealVar for the normalization of the signal and background, starting from the initial integral of the input histograms

  lM.setRange(300,1500);  

  RooRealVar lNB("nb","nb",lNB0,0,10000);
  RooRealVar lNSig("nsig","nsig",lNSig0,-1000,1000);

  //Define a PDF for the signal histogram lSig
  
  RooDataHist  *pS      = new RooDataHist("sigH","sigH",RooArgList(lM),lSig);
  RooHistPdf   *lSPdf   = new RooHistPdf ("sigPdf","sigPdf",lM,*pS);
 
  //Define generator and fit functions for the RooMCStudy

  RooAddPdf    *lGenMod = new RooAddPdf  ("genmod","genmod",RooArgList(*lFitFinal ,*lSPdf),RooArgList(lNB,lNSig));
  RooAddPdf    *lFitMod = new RooAddPdf  ("fitmod","fitmod",RooArgList(*lFit1Final,*lSPdf),RooArgList(lNB,lNSig));

  //Generate plot of the signal and background models going into the toy generation   

  RooPlot* plot=lM.frame();
  lGenMod->plotOn(plot);
  lGenMod->plotOn(plot,RooFit::Components(*lSPdf),RooFit::LineColor(2));
  TCanvas* lC11 = new TCanvas("pdf","pdf",600,600) ;
  lC11->cd();
  plot->Draw();
  lC11->SaveAs(("SBModel_"+iBkg+"_" + iDir + "_" + iEnergy+".pdf").c_str());

  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "FIT PARAMETERS BEFORE ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl;  
  std::cout << "===================================================================================================================================================" <<std::endl;


  RooMCStudy   *lToy    = new RooMCStudy(*lGenMod,lM,RooFit::FitModel(*lFitMod),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(kTRUE),RooFit::Verbose(kTRUE),RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::Strategy(0)));

  // Generate and fit iNToys toy samples
  
  std::cout << "Number of background events: " << lNB0 << " Number of signal events: " << lNSig0 << " Sum: " << lNB0+lNSig0 << std::endl;
  
  //=============================================================================================================================================
  // Generate and fit toys
  //============================================================================================================================================= 
    
  lToy->generateAndFit(iNToys,lNB0+lNSig0,kTRUE);
 
  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "FIT PARAMETERS AFTER ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl;  
  std::cout << "===================================================================================================================================================" <<std::endl;
  

  //=============================================================================================================================================
  // Generate plots relevant to the toy fit
  //=============================================================================================================================================

  RooPlot* lFrame1 = lToy->plotPull(lNSig,-5,5,100,kTRUE);
  lFrame1->SetTitle("distribution of pulls on signal yield from toys");
  lFrame1->SetXTitle("N_{sig} pull");
  
  TCanvas* lC00 = new TCanvas("pulls","pulls",600,600) ;
  lC00->cd();
  lFrame1->GetYaxis()->SetTitleOffset(1.2); 
  lFrame1->GetXaxis()->SetTitleOffset(1.0); 
  lFrame1->Draw() ;
  lC00->SaveAs(("sig_pulls_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame2 = lToy->plotParam(lA1);
  lFrame2->SetTitle("distribution of values of parameter 1 (a) after toy fit");
  lFrame2->SetXTitle("Parameter 1 (a)");
  TCanvas* lC01 = new TCanvas("valA","valA",600,600) ;
  lFrame2->Draw() ;
  lC01->SaveAs(("valA_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame3 = lToy->plotParam(lB1);
  lFrame3->SetTitle("distribution of values of parameter 2 (b) after toy fit");
  lFrame3->SetXTitle("Parameter 2 (b)");
  TCanvas* lC02 = new TCanvas("valB","valB",600,600) ;
  lFrame3->Draw() ;
  lC02->SaveAs(("valB_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
  
  RooPlot* lFrame6 = lToy->plotNLL(0,1000,100);
  lFrame6->SetTitle("-log(L)");
  lFrame6->SetXTitle("-log(L)");
  TCanvas* lC05 = new TCanvas("logl","logl",600,600) ;
  lFrame6->Draw() ;
  lC05->SaveAs(("logL_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame7 = lToy->plotParam(lNSig);
  lFrame7->SetTitle("distribution of values of N_{sig} after toy fit");
  lFrame7->SetXTitle("N_{sig}");
  TCanvas* lC06 = new TCanvas("Nsig","Nsig",600,600) ;
  lFrame7->Draw() ;
  lC06->SaveAs(("NSig_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
  
  RooPlot* lFrame8 = lToy->plotParam(lNB);
  lFrame8->SetTitle("distribution of values of N_{bkg} after toy fit");
  lFrame8->SetXTitle("N_{bkg}");
  TCanvas* lC07 = new TCanvas("Nbkg","Nbkg",600,600) ;
  lFrame8->Draw() ;
  lC07->SaveAs(("Nbkg_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
 

  if(iRebin) { 
    const int lNBins = lData->GetNbinsX();
    double *lAxis    = getAxis(lData);
    lH0     = rebin(lH0    ,lNBins,lAxis);
    lH      = rebin(lH     ,lNBins,lAxis);
    lHUp    = rebin(lHUp   ,lNBins,lAxis);
    lHDown  = rebin(lHDown ,lNBins,lAxis);
    lHUp1   = rebin(lHUp1  ,lNBins,lAxis);
    lHDown1 = rebin(lHDown1,lNBins,lAxis);
  }

  // we dont need this bin errors since we do not use them (fit tails replaces bin-by-bin error!), therefore i set all errors to 0, this also saves us from modifying the add_bbb_error.py script in which I otherwise would have to include a option for adding bbb only in specific ranges
  int lMergeBin = lH->GetXaxis()->FindBin(iFirst);
  for(int i0 = lMergeBin; i0 < lH->GetNbinsX()+1; i0++){
    lH->SetBinError  (i0,0);
    lHUp->SetBinError  (i0,0);
    lHDown->SetBinError  (i0,0);
    lHUp1->SetBinError  (i0,0);
    lHDown1->SetBinError  (i0,0);
  }


  TFile *lOutFile =new TFile("Output.root","RECREATE");
  cloneFile(lOutFile,lFile,iDir+"/"+iBkg);
  lOutFile->cd(iDir.c_str());
  lH     ->Write();
  lHUp   ->Write(); 
  lHDown ->Write(); 
  lHUp1  ->Write(); 
  lHDown1->Write(); 

  // Debug Plots
  lH0->SetStats(0);
  lH->SetStats(0);
  lHUp->SetStats(0);
  lHDown->SetStats(0);
  lHUp1->SetStats(0);
  lHDown1->SetStats(0);
  lH0    ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle);
  lH     ->SetLineColor(kGreen);
  lHUp   ->SetLineColor(kRed);
  lHDown ->SetLineColor(kRed);
  lHUp1  ->SetLineColor(kBlue);
  lHDown1->SetLineColor(kBlue);
  TCanvas *lC0 = new TCanvas("Can","Can",800,600);
  lC0->Divide(1,2); lC0->cd();  lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ; 
  lH0->Draw();
  lH     ->Draw("hist sames");
  lHUp   ->Draw("hist sames");
  lHDown ->Draw("hist sames");
  lHUp1  ->Draw("hist sames");
  lHDown1->Draw("hist sames");
  gPad->SetLogy();
  
  TLegend* leg1;
  /// setup the CMS Preliminary
  leg1 = new TLegend(0.7, 0.80, 1, 1); 
  leg1->SetBorderSize( 0 );
  leg1->SetFillStyle ( 1001 );
  leg1->SetFillColor (kWhite);
  leg1->AddEntry( lH0 , "orignal",  "PL" );
  leg1->AddEntry( lH , "cental fit",  "L" );
  leg1->AddEntry( lHUp , "shift1 up",  "L" );
  leg1->AddEntry( lHDown , "shift1 down",  "L" );
  leg1->AddEntry( lHUp1 , "shift2 up",  "L" );
  leg1->AddEntry( lHDown1 , "shift2 down",  "L" );
  leg1->Draw("same");


  lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ;
  drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1);
  lH0->SetStats(0);
  lC0->Update();
  lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str());
  //lFile->Close();
  return;
}
void addNuisance(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,bool iVarBin=false,int iFitModel=1,double iFirst=150,double iLast=1500) { 
  std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl;  
  if(iVarBin) addVarBinNuisance(iFileName,iChannel,iBkg,iEnergy,iName,iDir,iRebin,iFitModel,iFirst,iLast);
  if(iVarBin) return;

  TFile *lFile = new TFile(iFileName.c_str());
  TH1F  *lH0   = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str());
  TH1F  *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str());

  //Define the fit function
  RooRealVar lM("m","m" ,0,5000);   //lM.setBinning(lBinning);
  RooRealVar lA("a","a" ,50,  0.1,100);
  RooRealVar lB("b","b" ,0.0 , -10.5,10.5); //lB.setConstant(kTRUE);
  RooDataHist *pH0  =  new RooDataHist("Data","Data" ,RooArgList(lM),lH0);
  RooGenericPdf *lFit  = 0; lFit = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFit = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) {lA.setVal(0.3); lB.setVal(0.5);}
  if(iFitModel == 2) lFit = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 3) lFit = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));
  RooFitResult  *lRFit = 0;
  double lFirst = iFirst;
  double lLast  = iLast;
  //lRFit = lFit->chi2FitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast));
  lRFit = lFit->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast),RooFit::Strategy(0)); 
  TMatrixDSym lCovMatrix   = lRFit->covarianceMatrix(); 
  TMatrixD  lEigVecs(2,2);    lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors();
  TVectorD  lEigVals(2);      lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues();
  cout << " Ve---> " << lEigVecs(0,0) << " -- " << lEigVecs(1,0) << " -- " << lEigVecs(0,1) << " -- " << lEigVecs(1,1) << endl;
  cout << " Co---> " << lCovMatrix(0,0) << " -- " << lCovMatrix(1,0) << " -- " << lCovMatrix(0,1) << " -- " << lCovMatrix(1,1) << endl;
  double lACentral = lA.getVal();
  double lBCentral = lB.getVal();
  lEigVals(0) = sqrt(lEigVals(0));
  lEigVals(1) = sqrt(lEigVals(1));
  cout << "===> " << lEigVals(0) << " -- " << lEigVals(1) << endl;
  
  TH1F* lH     = (TH1F*) lFit->createHistogram("fit" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));
  lA.setVal(lACentral + lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral + lEigVals(0)*lEigVecs(1,0));
  TH1F* lHUp   = (TH1F*) lFit->createHistogram("Up"  ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));
  lA.setVal(lACentral - lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral - lEigVals(0)*lEigVecs(1,0));
  TH1F* lHDown = (TH1F*) lFit->createHistogram("Down",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral + lEigVals(1)*lEigVecs(1,1));
  TH1F* lHUp1   = (TH1F*) lFit->createHistogram("Up1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));
  lA.setVal(lACentral - lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral - lEigVals(1)*lEigVecs(1,1));
  TH1F* lHDown1 = (TH1F*) lFit->createHistogram("Down1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  std::string lNuisance1 =  iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy;
  std::string lNuisance2 =  iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy;
  lHUp    = merge(lNuisance1 + "Up"   ,lFirst,lH0,lHUp);
  lHDown  = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown);
  lHUp1   = merge(lNuisance2 + "Up"   ,lFirst,lH0,lHUp1);
  lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1);
  lH      = merge(lH0->GetName()      ,lFirst,lH0,lH);

  if(iRebin) { 
    const int lNBins = lData->GetNbinsX();
    double *lAxis    = getAxis(lData);
    lH0     = rebin(lH0    ,lNBins,lAxis);
    lH      = rebin(lH     ,lNBins,lAxis);
    lHUp    = rebin(lHUp   ,lNBins,lAxis);
    lHDown  = rebin(lHDown ,lNBins,lAxis);
    lHUp1   = rebin(lHUp1  ,lNBins,lAxis);
    lHDown1 = rebin(lHDown1,lNBins,lAxis);
  }

  // we dont need this bin errors since we do not use them (fit tails replaces bin-by-bin error!), therefore i set all errors to 0, this also saves us from modifying the add_bbb_error.py script in which I otherwise would have to include a option for adding bbb only in specific ranges
  int lMergeBin = lH->GetXaxis()->FindBin(iFirst);
  for(int i0 = lMergeBin; i0 < lH->GetNbinsX()+1; i0++){
    lH->SetBinError  (i0,0);
    lHUp->SetBinError  (i0,0);
    lHDown->SetBinError  (i0,0);
    lHUp1->SetBinError  (i0,0);
    lHDown1->SetBinError  (i0,0);
  }


  TFile *lOutFile =new TFile("Output.root","RECREATE");
  cloneFile(lOutFile,lFile,iDir+"/"+iBkg);
  lOutFile->cd(iDir.c_str());
  lH     ->Write();
  lHUp   ->Write(); 
  lHDown ->Write(); 
  lHUp1  ->Write(); 
  lHDown1->Write(); 

  // Debug Plots
  lH0->SetStats(0);
  lH->SetStats(0);
  lHUp->SetStats(0);
  lHDown->SetStats(0);
  lHUp1->SetStats(0);
  lHDown1->SetStats(0);
  lH0    ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle);
  lH     ->SetLineColor(kGreen);
  lHUp   ->SetLineColor(kRed);
  lHDown ->SetLineColor(kRed);
  lHUp1  ->SetLineColor(kBlue);
  lHDown1->SetLineColor(kBlue);
  TCanvas *lC0 = new TCanvas("Can","Can",800,600);
  lC0->Divide(1,2); lC0->cd();  lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ; 
  lH0->Draw();
  lH     ->Draw("hist sames");
  lHUp   ->Draw("hist sames");
  lHDown ->Draw("hist sames");
  lHUp1  ->Draw("hist sames");
  lHDown1->Draw("hist sames");
  gPad->SetLogy();
  
  TLegend* leg1;
  /// setup the CMS Preliminary
  leg1 = new TLegend(0.7, 0.80, 1, 1); 
  leg1->SetBorderSize( 0 );
  leg1->SetFillStyle ( 1001 );
  leg1->SetFillColor (kWhite);
  leg1->AddEntry( lH0 , "orignal",  "PL" );
  leg1->AddEntry( lH , "cental fit",  "L" );
  leg1->AddEntry( lHUp , "shift1 up",  "L" );
  leg1->AddEntry( lHDown , "shift1 down",  "L" );
  leg1->AddEntry( lHUp1 , "shift2 up",  "L" );
  leg1->AddEntry( lHDown1 , "shift2 down",  "L" );
  leg1->Draw("same");


  lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ;
  drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1);
  lH0->SetStats(0);
  lC0->Update();
  lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str());
  //lFile->Close();
  return;
}
void v_beam_asymmetry(){

	TString Q2 = "1.0";

	int HeRunNumberL = 1686;
	int endHeRunNumberL = 1958;
	int HeRunNumberR = 20596;
	int endHeRunNumberR = 20789;
// NOTE: There is a problem with the charge scalar in runs 20812-20879. When this is fixed,
// uncomment the line below. Until then, we stop at run 20789.
//	int endHeRunNumberR = 20879;
	
	double bins = 50;
	double xmin = 0.6;
	double xmax = 1.6;

	// Defines Right Arm Cuts
	TCut cutR = "";
	TCut kinematicsR = "PriKineR.Q2<10 && GoodElectron==1 && PriKineR.nu<10";
	TCut eventtypeR = "(D.evtypebits&2)==2";
	TCut goldR = "ExTgtCor_R.dp>-0.04 && ExTgtCor_R.dp<0.053";
	TCut targetR = "ReactPt_R.z>-0.17 && ReactPt_R.z<0.175";
	TCut thetaphiR = "abs(ExTgtCor_R.ph)<0.03 && abs(ExTgtCor_R.th)<0.06";

	TCut cutsR = cutR && kinematicsR && eventtypeR && goldR && targetR && thetaphiR;

	// Defines Left Arm Cuts
	TCut cutL = "";
	TCut kinematicsL = "PriKineL.Q2<10 && GoodElectron==1 && PriKineL.nu<10";
//	TCut eventtypeL = "(D.evtypebits&2)==2";
	TCut eventtypeL = "";
	TCut goldL = "ExTgtCor_L.dp>-0.04 && ExTgtCor_L.dp<0.053";
	TCut targetL = "ReactPt_L.z>-0.17 && ReactPt_L.z<0.175";
	TCut thetaphiL = "abs(ExTgtCor_L.ph)<0.03 && abs(ExTgtCor_L.th)<0.06";

	TCut cutsL = cutL && kinematicsL && eventtypeL && goldL && targetL && thetaphiL;


	TChain* chainHeR = new TChain("T");
	TChain* chainHeL = new TChain("T");

	TString filenameHeR;
	TString filenameHeL;

// ******************* The section below adds files to the Right arm chain from the RHRS ********************
	for (int thisHeRunNumberR=HeRunNumberR; thisHeRunNumberR<(endHeRunNumberR+1); thisHeRunNumberR++)
	{
		// Skipping Vertical Carbon & Deuterium Runs
		if(thisHeRunNumberR==20591){thisHeRunNumberR=20596;}
		if(thisHeRunNumberR==20731){thisHeRunNumberR=20738;}
		if(thisHeRunNumberR==20732){thisHeRunNumberR=20738;}
		if(thisHeRunNumberR==20733){thisHeRunNumberR=20738;}
		if(thisHeRunNumberR==20734){thisHeRunNumberR=20738;}
		if(thisHeRunNumberR==20736){thisHeRunNumberR=20738;}
		if(thisHeRunNumberR==20737){thisHeRunNumberR=20738;}
		if(thisHeRunNumberR==20762){thisHeRunNumberR=20789;}
		if(thisHeRunNumberR==20763){thisHeRunNumberR=20789;}
		if(thisHeRunNumberR==20764){thisHeRunNumberR=20789;}
		if(thisHeRunNumberR==20791){thisHeRunNumberR=20814;}
		if(thisHeRunNumberR==20792){thisHeRunNumberR=20814;}

		// Skipping Longitudinal Carbon Runs
		if(thisHeRunNumberR==22380){thisHeRunNumberR=22393;}
		if(thisHeRunNumberR==22389){thisHeRunNumberR=22393;}
		if(thisHeRunNumberR==22425){thisHeRunNumberR=22436;}
		if(thisHeRunNumberR==22426){thisHeRunNumberR=22436;}

		// Skipping Transverse Carbon Runs
		if(thisHeRunNumberR==22461){thisHeRunNumberR=22465;}

		// Adds runs to the chain
		for (int t=0; t<1000; t++)
		{
			filenameHeR = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
			filenameHeR += thisHeRunNumberR;
			if (t != 0)
			{
				filenameHeR += "_";
				filenameHeR += t;
			}
			filenameHeR += ".root";
			ifstream ifileHeR(filenameHeR);
			if (ifileHeR)
			{
				cout << "Adding file to chainHeR: " << filenameHeR << endl;
				chainHeR->Add(filenameHeR);
			}
			else
			{
				cout << "File " << filenameHeR << " does not exist. Ending here." << endl;
				t=999999999;
			}
		}
//		 Use the line below only for debugging purposes. It will only add the first file.
//		 thisHeRunNumberR=999999;
	}
// ***********************************************************************************************************

// ************************** The section below adds files to the Left arm chain from the LHRS ***************
	for (int thisHeRunNumberL=HeRunNumberL; thisHeRunNumberL<(endHeRunNumberL+1); thisHeRunNumberL++)
	{
		// Skipping Vertical Carbon and Deuterium Runs
		if(thisHeRunNumberL==1699){thisHeRunNumberL=1705;}
		if(thisHeRunNumberL==1825){thisHeRunNumberL=1832;}
		if(thisHeRunNumberL==1826){thisHeRunNumberL=1832;}
		if(thisHeRunNumberL==1827){thisHeRunNumberL=1832;}
		if(thisHeRunNumberL==1828){thisHeRunNumberL=1832;}
		if(thisHeRunNumberL==1830){thisHeRunNumberL=1832;}
		if(thisHeRunNumberL==1831){thisHeRunNumberL=1832;}
		if(thisHeRunNumberL==1884){thisHeRunNumberL=1905;}
		if(thisHeRunNumberL==1885){thisHeRunNumberL=1905;}

		// Skipping Longitudinal Carbon Runs
		if(thisHeRunNumberL==22380){thisHeRunNumberL=22393;}
		if(thisHeRunNumberL==22389){thisHeRunNumberL=22393;}
		if(thisHeRunNumberL==22425){thisHeRunNumberL=22436;}
		if(thisHeRunNumberL==22426){thisHeRunNumberL=22436;}

		// Skipping Transverse Carbon Runs
		if(thisHeRunNumberL==22461){thisHeRunNumberL=22465;}

		// Adds runs to the chain
		for (int t=0; t<1000; t++)
		{
			filenameHeL = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_L_";
			filenameHeL += thisHeRunNumberL;
			if (t != 0)
			{
				filenameHeL += "_";
				filenameHeL += t;
			}
			filenameHeL += ".root";
			ifstream ifileHeL(filenameHeL);
			if (ifileHeL)
			{
				cout << "Adding file to chainHeL: " << filenameHeL << endl;
				chainHeL->Add(filenameHeL);
			}
			else
			{
				cout << "File " << filenameHeL << " does not exist. Ending here." << endl;
				t=999999999;
			}
		}
//		 Use the line below only for debugging purposes. It will only add the first file.
//		 thisHeRunNumberL=999999;
	}
// ****************************************************************************************************************




	gStyle->SetPalette(1);
	
	// Defines Canvas
	TCanvas *c1 = new TCanvas("c1","Asymmetry",1360,810); //x,y
	pad1  =  new  TPad("pad1","pad1",0.0000,0.6666,0.2500,1.0000,0,0,0);
	pad2  =  new  TPad("pad2","pad2",0.2500,0.6666,0.5000,1.0000,0,0,0);
	pad3  =  new  TPad("pad3","pad3",0.5000,0.6666,0.7500,1.0000,0,0,0);
	pad4  =  new  TPad("pad4","pad4",0.7500,0.6666,1.0000,1.0000,0,0,0);
	pad5  =  new  TPad("pad5","pad5",0.0000,0.3333,0.2000,0.6666,0,0,0);
	pad6  =  new  TPad("pad6","pad6",0.2000,0.3333,0.4000,0.6666,0,0,0);
	pad7  =  new  TPad("pad7","pad7",0.4000,0.3333,0.6000,0.6666,0,0,0);
	pad8  =  new  TPad("pad8","pad8",0.6000,0.3333,0.8000,0.6666,0,0,0);
	pad9  =  new  TPad("pad9","pad9",0.8000,0.3333,1.0000,0.6666,0,0,0);
	pad10 = new TPad("pad10","pad10",0.0000,0.0000,0.5000,0.3333,0,0,0);
	pad11 = new TPad("pad11","pad11",0.5000,0.0000,1.0000,0.3333,0,0,0);
	pad1->Draw();pad2->Draw();pad3->Draw();pad4->Draw();pad5->Draw();pad6->Draw();pad7->Draw();pad8->Draw();pad9->Draw();pad10->Draw();pad11->Draw();



	// Everything below here makes graphs for each section of the canvas

	pad1->cd();
	TString titledp = "dp Cut";
	cout << "Drawing " << titledp << "..." << endl;
	TH1F *HedpNoCut = new TH1F("HedpNoCut",titledp,400,-0.08,0.08);
	TH1F *HedpCut = new TH1F("HedpCut",titledp,400,-0.08,0.08);
	chainHeR->Draw("ExTgtCor_R.dp>>HedpNoCutR(400,-0.08,0.08)", "", "");
	chainHeR->Draw("ExTgtCor_R.dp>>HedpCutR(400,-0.08,0.08)", goldR, "");
	chainHeL->Draw("ExTgtCor_L.dp>>HedpNoCutL(400,-0.08,0.08)", "", "");
	chainHeL->Draw("ExTgtCor_L.dp>>HedpCutL(400,-0.08,0.08)", goldL, "");
	HedpNoCut->Add(HedpNoCutR,HedpNoCutL);
	HedpNoCut->SetTitle(titledp);
	HedpNoCut->Draw();
	HedpCut->Add(HedpCutR,HedpCutL);
	HedpCut->SetLineColor(kBlack);
	HedpCut->SetFillColor(kViolet);
	HedpCut->Draw("same");

	pad2->cd();
	cout << "Drawing Target Cut..." << endl;
	TString titleTarget = "Target Cut";
	TH1F *HeReactZNoCut = new TH1F("HeReactZNoCut",titleTarget,400,-0.3,0.3);
	TH1F *HeReactZCut = new TH1F("HeReactZCut",titleTarget,400,-0.3,0.3);
	chainHeR->Draw("ReactPt_R.z>>HeReactZNoCutR(400,-0.3,0.3)", "", "");
	chainHeR->Draw("ReactPt_R.z>>HeReactZCutR(400,-0.3,0.3)", targetR, "");
	chainHeL->Draw("ReactPt_L.z>>HeReactZNoCutL(400,-0.3,0.3)", "", "");
	chainHeL->Draw("ReactPt_L.z>>HeReactZCutL(400,-0.3,0.3)", targetL, "");
	HeReactZNoCut->Add(HeReactZNoCutR,HeReactZNoCutL);
	HeReactZNoCut->SetTitle(titleTarget);
	HeReactZNoCut->Draw();
	HeReactZCut->Add(HeReactZCutR,HeReactZCutL);
	HeReactZCut->SetLineColor(kBlack);
	HeReactZCut->SetFillColor(kViolet);
	HeReactZCut->Draw("same");

	pad3->cd();
	cout << "Drawing Theta and Phi..." << endl;
	TString titleThetaPhiNoCut = "Theta and Phi, No Cut";
	TH2F *HeThetaPhiNoCut = new TH2F("HeThetaPhiNoCut",titleThetaPhiNoCut,100,-0.05,0.05,100,-0.1,0.1);
	chainHeR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>HeThetaPhiNoCutR(100,-0.05,0.05,100,-0.1,0.1)", targetR, "");
	chainHeL->Draw("ExTgtCor_L.th:ExTgtCor_L.ph>>HeThetaPhiNoCutL(100,-0.05,0.05,100,-0.1,0.1)", targetL, "");
	HeThetaPhiNoCut->Add(HeThetaPhiNoCutR,HeThetaPhiNoCutL);
	HeThetaPhiNoCut->SetTitle(titleThetaPhiNoCut);
	HeThetaPhiNoCut->SetStats(kFALSE);
	HeThetaPhiNoCut->Draw("COLZ");

	pad4->cd();
	cout << "Drawing Theta and Phi Cut..." << endl;
	TString titleThetaPhi = "Theta and Phi Cut";
	TH2F *HeThetaPhiCut = new TH2F("HeThetaPhiCut",titleThetaPhi,100,-0.05,0.05,100,-0.1,0.1);
	chainHeR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>HeThetaPhiCutR(100,-0.05,0.05,100,-0.1,0.1)", targetR && thetaphiR, "");
	chainHeL->Draw("ExTgtCor_L.th:ExTgtCor_L.ph>>HeThetaPhiCutL(100,-0.05,0.05,100,-0.1,0.1)", targetL && thetaphiL, "");
	HeThetaPhiCut->Add(HeThetaPhiCutR,HeThetaPhiCutL);
	HeThetaPhiCut->SetTitle(titleThetaPhi);
	HeThetaPhiCut->SetStats(kFALSE);
	HeThetaPhiCut->Draw("COLZ");

	pad5->cd();
	TString titleQ2 = "Q2";
	TH1F *histQ2 = new TH1F("histQ2",titleQ2,400,0,1.6);
	cout << "Drawing " << titleQ2 << "..." << endl;
	chainHeR->Draw("PriKineR.Q2>>histQ2R(400,0,1.6)", cutsR, "");	
	chainHeL->Draw("PriKineL.Q2>>histQ2L(400,0,1.6)", cutsL, "");
	histQ2->Add(histQ2R,histQ2L);
	histQ2->SetTitle(titleQ2);
	histQ2->SetStats(kFALSE);
	histQ2->Draw();

	pad6->cd();
	TString titleNu = "Nu";
	cout << "Drawing " << titleNu << "..." << endl;
	TH1F *histNu = new TH1F("histNu",titleNu,100,0.3,0.8);
	chainHeR->Draw("PriKineR.nu>>histNuR(100,0.3,0.8)", cutsR, "");
	chainHeL->Draw("PriKineL.nu>>histNuL(100,0.3,0.8)", cutsL, "");
	histNu->Add(histNuR,histNuL);
	histNu->SetTitle(titleNu);
	histNu->SetStats(kFALSE);
	histNu->Draw();

	pad7->cd();
	TString titleHel = "Helicity vs. Bjorken x";
	cout << "Drawing " << titleHel << "..." << endl;
	TH2F *histHelR = new TH2F("histHelR",titleHel,bins,xmin,xmax,7,-2,2);
	TH2F *histHelL = new TH2F("histHelL",titleHel,bins,xmin,xmax,7,-2,2);
	TH2F *histHel = new TH2F("histHel",titleHel,bins,xmin,xmax,7,-2,2);
	chainHeR->Draw("g0hel.R.helicity:(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histHelR", cutsR, "");
	chainHeL->Draw("g0hel.L.helicity:(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histHelL", cutsL, "");
	histHel->Add(histHelR,histHelL);
	histHel->Draw("COLZ");


	// Note: For all plots below, Positive Helicity is defined as g0hel.R.helicity==1 when the BHWP is In
	// and g0hel.R.helicity==-1 when the BHWP is Out
	pad8->cd();
	TString titlePosHelx = "# of Positive Helicity Events vs. Bjorken x";
	cout << "Drawing " << titlePosHelx << "..." << endl;
	TH1F *histPosHelxIn1R = new TH1F("histPosHelxIn1R",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxIn2R = new TH1F("histPosHelxIn2R",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxInR = new TH1F("histPosHelxInR",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxOut1R = new TH1F("histPosHelxOut1R",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxOut2R = new TH1F("histPosHelxOut2R",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxOutR = new TH1F("histPosHelxOutR",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxIn1L = new TH1F("histPosHelxIn1L",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxIn2L = new TH1F("histPosHelxIn2L",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxInL = new TH1F("histPosHelxInL",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxOut1L = new TH1F("histPosHelxOut1L",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxOut2L = new TH1F("histPosHelxOut2L",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxOutL = new TH1F("histPosHelxOutL",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxR = new TH1F("histPosHelxL",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelxL = new TH1F("histPosHelxR",titlePosHelx,bins,xmin,xmax);
	TH1F *histPosHelx = new TH1F("histPosHelx",titlePosHelx,bins,xmin,xmax);
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histPosHelxIn1R", cutsR && "g0hel.R.helicity==1" && "fEvtHdr.fRun>20576" && "fEvtHdr.fRun<20684", "");
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histPosHelxIn2R", cutsR && "g0hel.R.helicity==1" && "fEvtHdr.fRun>20728" && "fEvtHdr.fRun<20813", "");
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histPosHelxOut1R", cutsR && "g0hel.R.helicity==-1" && "fEvtHdr.fRun>20683" && "fEvtHdr.fRun<20728", "");
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histPosHelxOut2R", cutsR && "g0hel.R.helicity==-1" && "fEvtHdr.fRun>20813" && "fEvtHdr.fRun<20879", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histPosHelxIn1L", cutsL && "g0hel.L.helicity==1" && "fEvtHdr.fRun>1685" && "fEvtHdr.fRun<1778", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histPosHelxIn2L", cutsL && "g0hel.L.helicity==1" && "fEvtHdr.fRun>1822" && "fEvtHdr.fRun<1905", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histPosHelxOut1L", cutsL && "g0hel.L.helicity==-1" && "fEvtHdr.fRun>1777" && "fEvtHdr.fRun<1823", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histPosHelxOut2L", cutsL && "g0hel.L.helicity==-1" && "fEvtHdr.fRun>1905" && "fEvtHdr.fRun<1960", "");
	histPosHelxInR->Add(histPosHelxIn1R,histPosHelxIn2R);
	histPosHelxOutR->Add(histPosHelxOut1R,histPosHelxOut2R);
	histPosHelxR->Add(histPosHelxInR,histPosHelxOutR);
	histPosHelxInL->Add(histPosHelxIn1L,histPosHelxIn2L);
	histPosHelxOutL->Add(histPosHelxOut1L,histPosHelxOut2L);
	histPosHelxL->Add(histPosHelxInL,histPosHelxOutL);
	histPosHelx->Add(histPosHelxR,histPosHelxL);
	histPosHelx->Draw();

	pad9->cd();
	TString titleNegHelx = "# of Negative Helicity Events vs. Bjorken x";
	cout << "Drawing " << titleNegHelx << "..." << endl;
	TH1F *histNegHelxIn1R = new TH1F("histNegHelxIn1R",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxIn2R = new TH1F("histNegHelxIn2R",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxInR = new TH1F("histNegHelxInR",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxOut1R = new TH1F("histNegHelxOut1R",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxOut2R = new TH1F("histNegHelxOut2R",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxOutR = new TH1F("histNegHelxOutR",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxR = new TH1F("histNegHelxR",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxIn1L = new TH1F("histNegHelxIn1L",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxIn2L = new TH1F("histNegHelxIn2L",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxInL = new TH1F("histNegHelxInL",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxOut1L = new TH1F("histNegHelxOut1L",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxOut2L = new TH1F("histNegHelxOut2L",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxOutL = new TH1F("histNegHelxOutL",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelxL = new TH1F("histNegHelxL",titleNegHelx,bins,xmin,xmax);
	TH1F *histNegHelx = new TH1F("histNegHelx",titleNegHelx,bins,xmin,xmax);
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histNegHelxIn1R", cutsR && "g0hel.R.helicity==-1" && "fEvtHdr.fRun>20576" && "fEvtHdr.fRun<20684", "");
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histNegHelxIn2R", cutsR && "g0hel.R.helicity==-1" && "fEvtHdr.fRun>20728" && "fEvtHdr.fRun<20813", "");
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histNegHelxOut1R", cutsR && "g0hel.R.helicity==1" && "fEvtHdr.fRun>20683" && "fEvtHdr.fRun<20728", "");
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histNegHelxOut2R", cutsR && "g0hel.R.helicity==1" && "fEvtHdr.fRun>20813" && "fEvtHdr.fRun<20879", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histNegHelxIn1L", cutsL && "g0hel.L.helicity==-1" && "fEvtHdr.fRun>1685" && "fEvtHdr.fRun<1778", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histNegHelxIn2L", cutsL && "g0hel.L.helicity==-1" && "fEvtHdr.fRun>1822" && "fEvtHdr.fRun<1905", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histNegHelxOut1L", cutsL && "g0hel.L.helicity==1" && "fEvtHdr.fRun>1777" && "fEvtHdr.fRun<1823", "");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histNegHelxOut2L", cutsL && "g0hel.L.helicity==1" && "fEvtHdr.fRun>1905" && "fEvtHdr.fRun<1960", "");
	histNegHelxInR->Add(histNegHelxIn1R,histNegHelxIn2R);
	histNegHelxInL->Add(histNegHelxIn1L,histNegHelxIn2L);
	histNegHelxOutR->Add(histNegHelxOut1R,histNegHelxOut2R);
	histNegHelxOutL->Add(histNegHelxOut1L,histNegHelxOut2L);
	histNegHelxR->Add(histNegHelxInR,histNegHelxOutR);
	histNegHelxL->Add(histNegHelxInL,histNegHelxOutL);
	histNegHelx->Add(histNegHelxR,histNegHelxL);
	histNegHelx->Draw();

	pad10->cd();
	TString titlex = "Bjorken x ";
	titlex += " (x=Q^2/[2m*nu])";
	cout << "Drawing " << titlex << "..." << endl;
	TH1F *histxR = new TH1F("histxR",titlex,bins,xmin,xmax);
	TH1F *histxL = new TH1F("histxL",titlex,bins,xmin,xmax);
	TH1F *histx = new TH1F("histx",titlex,bins,xmin,xmax);
	histx->Sumw2();
	chainHeR->Draw("(PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315))>>histxR", cutsR, "E");
	chainHeL->Draw("(PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315))>>histxL", cutsL, "E");
	histx->Add(histxR,histxL);
	histx->Draw();


	// Note: Asymmetry is defined as (Pos - Neg)/(Pos + Neg)
	pad11->cd();
	TString titleAsym = "Beam Asymmetry (%) vs. Bjorken x for Q2 of ";
	titleAsym += Q2;
	cout << "Drawing " << titleAsym << "..." << endl;
	histAsym = histPosHelx->GetAsymmetry(histNegHelx);
	histAsym->Scale(100);
	histAsym->SetTitle(titleAsym);
	histAsym->Draw();

	TString imagename = "Asymmetries/Vertical_Beam_Asymmetry_for_Q2_of_";
	imagename += Q2;
	imagename += ".png";
	c1->Print(imagename);


	cout << "All done!" << endl;


}
Beispiel #7
0
void ootpu_comparison(TString files, TString var, TString title, int nbins, float low, float high, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hA = new TH1F("hA",title, nbins, low, high);
  TH1F* hB = new TH1F("hB",title, nbins, low, high);
  TH1F* hC = new TH1F("hC",title, nbins, low, high);
  TH1F* hD = new TH1F("hD",title, nbins, low, high);
  hA->SetStats(0);
  hA->GetYaxis()->SetLabelSize(0.04);
  //hA->GetYaxis()->SetTitleOffset(1.3);
  hA->GetXaxis()->SetTitleOffset(1.1);
  hA->GetXaxis()->SetTitleFont(132);
  hA->GetXaxis()->SetTitleSize(0.042);
  hA->GetXaxis()->SetLabelSize(0.04);
  hA->SetLineWidth(2);

  //  hA->StatOverflows(true);
  //  hB->StatOverflows(true);
  //  hC->StatOverflows(true);
  //  hD->StatOverflows(true);

  int n1(0), n2(0), n3(0), n4(0), n5(0);
  if (files.Contains("20bx25")) {
    n1=5;
    n2=17;
    n3=21;
    n4=25;
    n5=40;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=25;
    n3=40;
    n4=55;
    n5=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=15;
    n3=22;
    n4=32;
    n5=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  //if (files.Contains("PU_S10")) {
  TString cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n1,n2);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hA", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n2,n3);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hB", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n3,n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hC", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d)",mu.Data(),n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hD", var, cuts);
  // }
  // else {
  //  }
  
  float avg1(hA->GetMean());
  float avg2(hB->GetMean());
  float avg3(hC->GetMean());
  float avg4(hD->GetMean());

  hA->Scale(1/hA->Integral());
  hB->Scale(1/hB->Integral());
  hC->Scale(1/hC->Integral());
  hD->Scale(1/hD->Integral());

  hA->SetLineColor(1);
  hB->SetLineColor(2);
  hC->SetLineColor(3);
  hD->SetLineColor(4);

  hA->SetLineWidth(2);
  hB->SetLineWidth(2);
  hC->SetLineWidth(2);
  hD->SetLineWidth(2);

  TCanvas* c1 = new TCanvas();
  float max = TMath::Max(hA->GetMaximum(), hB->GetMaximum());
  if (hC->GetMaximum()>max) max = hC->GetMaximum();
  if (hD->GetMaximum()>max) max = hD->GetMaximum();

  hA->SetMaximum(max*1.1);
  hA->Draw("e1");
  hB->Draw("e1,same");
  hC->Draw("e1,same");
  hD->Draw("e1,same");

  TLegend* leg = new TLegend(0.42,0.6,0.9,0.9);
  leg->SetFillStyle(0);
  char label[1000];
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n1,n2,avg1);
  leg->AddEntry(hA,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n2,n3,avg2);
  leg->AddEntry(hB,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n3,n4,avg3);
  leg->AddEntry(hC,label,"lp");
  sprintf(label,"Early Ints.>%d (#mu=%3.3f)",n4,avg4);
  leg->AddEntry(hD,label,"lp");
  // leg->Draw();

  TString plotTitle ="relIso_vs_OOTPU_"+var+comments+".pdf";
  c1->Print(plotTitle);

  cout << "Rejection rates" << endl;
  Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  left = hA->IntegralAndError(1,12,lerror);
  right = hA->IntegralAndError(13,31,rerror);
  float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hB->IntegralAndError(1,12,lerror);
  right = hB->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hC->IntegralAndError(1,12,lerror);
  right = hC->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hD->IntegralAndError(1,12,lerror);
  right = hD->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}