Esempio n. 1
0
//---------------------
// FitSection
//---------------------
TF1* FitSection(int order, TTree *Bfield, const char *Bi, Double_t z_min_inches, Double_t z_max_inches, Double_t r, const char *fname)
{
	cout<<"Fitting "<<fname<<" at r="<<r<<endl;

	// The following should be defined based on the grid spacing/location
	// of points in the Bfield tree. 
	Double_t delta_z = 2.54; // in cm
	Double_t delta_r = 2.54; // in cm

	// Determine proper histogram limits 
	Double_t z_min = z_min_inches*delta_z - delta_z/2.0;
	Double_t z_max = z_max_inches*delta_z + delta_z/2.0;
	Double_t epsilon = delta_z/1000.0; // used to prevent round-off problems
	UInt_t NbinsZ = floor((z_max - z_min + epsilon)/delta_z);

	// Note that here we explicitly set the limits to be -1 to +1 so that the
	// histogram conforms to the requirements of the chebyshev_FindBestFunction
	// function.
	TH1D *Bi_vs_znorm = new TH1D("Bi_vs_znorm", "Bi as function of modified z coordinate", NbinsZ, z_min, z_max);

	// Make varexp that properly converts from the lab z-coordinates,
	// to the "Chebyshev compatible" coordinates where z_min=-1 and
	// z_max=+1.
	stringstream cut;
	cut<<Bi<<"*(abs(r-"<<r<<")<"<<delta_r/10.0<<")"; // select a single r bin
	Bfield->Project("Bi_vs_znorm", "z", cut.str().c_str());

	TF1 *func = chebyshev_Fit(Bi_vs_znorm, order);
	TF1 *myfunc = (TF1*)func->Clone(fname);

	delete Bi_vs_znorm;
	
	return myfunc;
}
Esempio n. 2
0
void fitmmp(TH1 *hmmp, bool verbose = false) {
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,2,true);
  hmmp->Fit(fbg,options.Data(),"",0.42,2);
  //printf("%s\n",gMinuit->fCstatu.Data());
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,2,false);
    fbg2->SetParameters(fbg->GetParameters());
    //fbg2->Draw("same");
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    //htmp->Draw();
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,2);
    htmp->Fit(fgaus,options.Data(),"",0.74,0.85);
    TF1 *f = f_pol4gaus("f",0.4,2,fbg2,fgaus);
    f->SetNpx(500);
    hmmp->Fit(f,options.Data(),"",0.42,2);
    fgaus->SetRange(0.4,2);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}
Esempio n. 3
0
void fitDstar(char *infname = "/data/wangj/MC2015/Dntuple/PbPb/ntD_Pythia8_5020GeV_DstarD0kpipipi_755patch3_GEN_SIM_PU_20151120_Dstar5p_tkPt2_20151126_Evt_All.root") {

    TFile *inf = new TFile(infname);
    //TTree *ntmix=(TTree*)inf->Get("ntDD0kpipipipi");
    TTree *ntmix=(TTree*)inf->Get("ntDD0kpipi");
    TH1D *h = new TH1D("h","",100,0.139,0.159);
    TCut cutTrk = "";//"trk1PixelHit>=2&&trk1StripHit>=10&&trk1Chi2ndf<5&&trk2PixelHit>=2&&trk2StripHit>=10&&trk2Chi2ndf<5";

    TCanvas *c = new TCanvas("c","",750,750);
    ntmix->Draw("Dmass-DtktkResmass>>h","abs(DtktkResmass-1.86486)<0.015&&Dpt>10&&(DsvpvDistance/DsvpvDisErr)>0.&&Dchi2cl>0.05&&Dalpha<1."&&cutTrk,"",10000000);
    //ntmix->Draw("Dmass-DtktkResmass>>h","abs(DtktkResmass-1.86486)<0.015&&Dpt>10&&Dtrk1Pt>0.5&&DRestrk1Pt>0.5&&DRestrk2Pt>0.5&&DRestrk3Pt>0.5&&DRestrk4Pt>0.5&&Dchi2cl>0.1&&Dalpha<0.2&&(DsvpvDistance/DsvpvDisErr)>.0"&&cutTrk,"",10000000);
    h->Sumw2();
    //   TF1 *f = new TF1("f","(1-exp(-(x-[8])/[0]))*(((x)/[8])**[1]+[2]*(((x)/[8])-1))*[3]+[4]*(TMath::Voigt(x-[5],[6],[7]))");
    TF1* f = new TF1("f","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x+[5]*((1-[8])*TMath::Gaus(x,[6],[7])/(sqrt(2*3.14159)*[7])+[8]*TMath::Gaus(x,[6],[9])/(sqrt(2*3.14159)*[9]))",minmass3prong,maxmass3prong);
//   TF1 *f = new TF1("f","(1-exp(-(x-0.13957018)/[0]))*(((x)/0.13957018)**[1]+[2]*(((x)/0.13957018)-1))*[3]+[4]*(TMath::Gaus(x,[5],[6]))");
    //TF1 *f = new TF1("f","(1-exp(-(x-1.86486-0.13957018)/[0]))*(((x-1.86486)/0.13957018)**[1]+[2]*(((x-1.86486)/0.13957018)-1))*[3]+[4]*TMath::Gaus(x,[5],[6])");
    f->SetLineColor(4);
//   f->SetParameters(-2.3825e6,-7.99713e-1,-1.42957,-5.50069e10,5.33573,1.45491e-1,2.78677e-6,1.43145e-3,0.13957018);
//   f->SetParameters(-7.3e5,-2.2e1,5.24e-1,-7.18e9,2e2,1.45491e-1,9e-4,0.1,8e-4);
    f->SetParameters(0,0,0,0,0,2e2,1.45491e-1,9e-4,0.1,8e-4);
    f->FixParameter(9,15e-4);
    f->FixParameter(6,0.145491);
    f->FixParameter(7,8e-4);
    f->SetParLimits(8,0,1);
    h->Fit("f","LL");
    h->Fit("f","LL");
    h->Fit("f","LL","",0.142,0.147);
    f->ReleaseParameter(6);
    f->ReleaseParameter(7);
    f->ReleaseParameter(9);
    f->SetParLimits(7,1e-4,9e-4);
    f->SetParLimits(9,1e-4,9e-4);
    h->Fit("f","LL","",0.142,0.148);
    h->Fit("f","LL","",0.142,0.16);
    h->Fit("f","LL","",0.142,0.16);
    h->Fit("f","LL","",0.141,0.16);
    h->Fit("f","LL","",0.141,0.16);
    h->Fit("f","LL","",0.141,0.16);

    h->SetXTitle("M_{K#pi#pi#pi#pi}-M_{K#pi#pi#pi} (GeV/c^{2})");
    h->SetYTitle("Entries");
    h->SetStats(0);
    h->SetAxisRange(1,h->GetMaximum()*1.3,"Y");
    TF1 *f2 = (TF1*)f->Clone("f2");
    f2->SetParameter(5,0);
    f2->SetRange(0.141,0.16);
    TF1 *f3 = (TF1*)f->Clone("f3");
    f3->SetParameter(0,0);
    f3->SetParameter(1,0);
    f3->SetParameter(2,0);
    f3->SetParameter(3,0);
    f3->SetParameter(4,0);

    f->SetLineColor(4);
    f2->SetLineColor(4);
    f2->SetLineStyle(2);
    f3->SetLineStyle(2);
    f2->Draw("same");
    f3->SetLineColor(2);
    f3->SetFillStyle(3004);
    f3->SetFillColor(2);
    f3->Draw("same");

    c->SaveAs("canvasDstar.pdf");
}
Esempio n. 4
0
void mk_sigaccanplots(string flavor = "112", bool tdrstyle = false)
{
	setTDRStyle(tdrstyle);
	// gStyle->SetOptFit(1100); // chi2 and prob, not parameters
	gStyle->SetOptFit(0); // chi2 and prob, not parameters
	// gStyle->SetOptStat("irme"); // integral, RMS, mean, # of entries
	gStyle->SetStatFontSize(0.005);
	gStyle->SetStatY(0.4);
	float unused = 0.9, simtxt_y = 0.97;
	if (tdrstyle == false) {
		simtxt_y = 0.93;
	}
	TLatex *tex = new TLatex(unused, simtxt_y, "CMS simulation at #sqrt{s} = 8 TeV");
	tex->SetNDC();
	tex->SetTextAlign(12); // Left-adjusted
	tex->SetTextFont(42);
	float textsiz = 0.06;
	tex->SetTextSize(0.05);
	tex->SetLineWidth(2);
  // for(int k=0; k<3; k++){	
  // for(int k=0; k<2; k++){	
  for(int k=2; k<3; k++){	
  //Which plots to make
  //define input variables
  vector <TFile* > filelist_kin;

  // string uncert="btagup";
  // if(k==1) uncert="btagdown";
  string uncert="up";
  if(k==1) uncert="down";
  if(k==2) uncert="";
  
  // filelist_kin.push_back(TFile::Open(("Acc_Gluino_NoLumi_pt110_8TeVxsec_BtagMap_2500GeV"+uncert+".root").c_str()));
  // filelist_kin.push_back(TFile::Open("Acc_Gluino_NoLumi_pt60_pt110_8TeVxsec_BtagMap.root"));
  // filelist_kin.push_back(TFile::Open(("Acc_RPV112" + uncert + ".root").c_str()));
  filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + uncert + "_Sph4.root").c_str()));
//   filelist_kin.push_back(TFile::Open(("Acc_Gluino_NoLumi_pt60_pt110_8TeVxsec_BtagMap" + uncert + ".root").c_str()));
  
  TFile f1(("RPV_" + flavor + "_accandwdithtest"+uncert+".root").c_str(), "recreate");
  f1.cd();
  
  
  
  string nameIN;
  string cuts;
  string prefix;
  string postfix;
  string folder;
  string ptcut;
  folder="plots_paper/";
  postfix=".pdf";
  /////////////Plots for each Mass separatly//////////////
  /////////////----------------------------------------/////////////
  
  for (int p = 0; p < 2; p++) {
    // ptcut="112";
    // if(p==1) ptcut="" + flavor;
     ptcut="60";
    if (p==1) {
		ptcut="110";
		textsiz = 0.045;
    }
    // string histname = string("GausWidth_vs_Mass_112") + ptcut;
      string histname = string("GausWidth_vs_Mass_" + flavor) + "_" + ptcut;
      cout<< histname << endl;
      TGraphErrors *h_GluinoHist_Fit = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
      histname = string("GausAcceptance_vs_Mass_" + flavor) + "_" + ptcut;
      // histname = string("GausAcceptance_vs_Mass_112") + ptcut;
      cout<< histname << endl;
      TGraphErrors *h_GluinoHist_MCcomb = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
      
      // histname = string("FullAcceptance_vs_Mass_" + flavor) + "_" + ptcut;
      histname = string("GausMean_vs_Mass_" + flavor) + "_" + ptcut;
      // histname = string("GausAcceptance_vs_Mass_112") + ptcut;
      cout<< histname << endl;
      // TGraphErrors *h_FullAccept = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
      TGraph *h_FullAccept = (TGraph*) filelist_kin[0]->Get(histname.c_str())->Clone();
     
      histname = string("GausMeanOffset_vs_Mass_" + flavor) + "_" + ptcut;
      cout<< histname << endl;
      TGraph *h_MeanOffset = (TGraph*) filelist_kin[0]->Get(histname.c_str())->Clone();
     
      TCanvas * cGluinoFitsOpti = new TCanvas(("RPV_"+flavor +ptcut).c_str(), ("RPV_" + ptcut+"_"+cuts).c_str(), 800, 600);
      //h_GluinoHist_Fit->SetFillColor(kOrange-2);
      // h_GluinoHist_Fit->SetLineColor(kBlack);
		string title;
		string systematic = "pile-up";
		// title="Gaussian Width vs. Mass for Light-ptcut RPV";
		string tag = "qqb", sphericity = " Sphericity #geq 0.4";
		if (flavor.compare("112") == 0)
			tag = "qqq";
		else if (ptcut.compare("60") == 0)
			sphericity = "";
		string titlepart = "Hadronic RPV #tilde{g} #rightarrow " + tag;
		string titleln2 = "\\Delta = 110 GeV";
		string titleln3 = "6^{th}-jet p_{T} #geq " + ptcut + " GeV";
		title = titlepart;
		// title = "Width for " + titlepart;
		/*
		if(k==0){
		title="RPV gluino #bf{" + systematic + " up} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
      if (i>=5 || p==0) title="RPV gluino #bf{" + systematic + " up} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
		}
		
				if(k==1){
		title="RPV gluino #bf{" + systematic + " down} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
      if (i>=5 || p==0) title="RPV gluino #bf{" + systematic + " down} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
				}
		
						if(k==2){
		title="RPV gluino m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
      if (i>=5 || p==0) title="RPV gluino m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
						}
						*/
      h_GluinoHist_Fit->SetTitle(title.c_str());
      float titpos = 0.2, titly = 0.89, headpos = 0.64;
	  if (tdrstyle == false) {
	  	titpos -= 0.05;
	  	titly -= 0.05;
	  	headpos = 0.45;
	  }
			TLatex *tex2 = new TLatex(titpos, titly, title.c_str());
			tex2->SetNDC();
			tex2->SetTextAlign(12); // Left-adjusted
			tex2->SetTextFont(42);
			tex2->SetTextSize(textsiz);
			tex2->SetLineWidth(2);
			TLatex *tex3 = new TLatex(titpos, titly - 0.07, titleln2.c_str());
			tex3->SetNDC();
			tex3->SetTextAlign(12);
			tex3->SetTextFont(42);
			tex3->SetTextSize(textsiz);
			tex3->SetLineWidth(2);
			TLatex *tex3a = new TLatex(titpos, titly - 0.14, titleln3.c_str());
			tex3a->SetNDC();
			tex3a->SetTextAlign(12);
			tex3a->SetTextFont(42);
			tex3a->SetTextSize(textsiz);
			tex3a->SetLineWidth(2);
			TLatex *tex4 = NULL;
			if (sphericity.size() > 0) {
				tex4 = new TLatex(titpos - 0.01, titly - 0.22, sphericity.c_str());
				tex4->SetNDC();
				tex4->SetTextAlign(12);
				tex4->SetTextFont(42);
				tex4->SetTextSize(textsiz);
				tex4->SetLineWidth(2);
			}
			float legx = 0.65;
			 if (tdrstyle == false) {
			 	 legx = 0.56;
			 }
			TLegend *leg = new TLegend(legx, 0.2, legx + 0.3, 0.4);
			leg->SetBorderSize(1);
			leg->SetTextFont(62);
			leg->SetLineColor(kBlack);
			leg->SetLineStyle(1);
			leg->SetLineWidth(1);
			leg->SetFillColor(0);
			leg->SetFillStyle(1001);
			//leg->SetHeader();


			// leg->AddEntry(h_GluinoHist_Fit, "#splitline{Acceptance as function}{of gluino mass}","l");	
      h_GluinoHist_Fit->SetMarkerStyle(1);
      h_GluinoHist_Fit->SetMarkerColor(kWhite);
      // h_GluinoHist_Fit->SetMarkerColor(kGreen + 3);
      h_GluinoHist_Fit->SetMarkerSize(0.004);
     // h_GluinoHist_Fit->SetTitleSize(0.01);
      TF1 *fitfunc = h_GluinoHist_Fit->GetFunction("GausWidth");
      string fitnamew = "fitcopy" + ptcut;
      TF1* fitfunccopy = (TF1 *) fitfunc->Clone(fitnamew.c_str());
      if (fitfunc == NULL)
     	 cout << "Can't get fit func\n";
      else {
      	fitfunc->Delete();
      	fitfunccopy->SetLineWidth(3);
      	fitfunccopy->SetLineColor(kGreen + 3);
		// fitfunc->SetLineStyle(3); // Dotted
      }
	 float labsiz = 0.055;
      h_GluinoHist_Fit->GetXaxis()->SetLabelFont(62);
      h_GluinoHist_Fit->GetXaxis()->SetTitleFont(62);
      h_GluinoHist_Fit->GetYaxis()->SetLabelFont(62);
      h_GluinoHist_Fit->GetYaxis()->SetTitleFont(62);
      h_GluinoHist_Fit->GetYaxis()->SetTitle("Gaussian width [GeV]");
      float offset = 0.8;
	  if (tdrstyle == false) {
		h_GluinoHist_Fit->GetXaxis()->SetTitleOffset(offset);
		h_GluinoHist_Fit->GetYaxis()->SetTitleOffset(offset);
	 }
      h_GluinoHist_Fit->GetXaxis()->SetTitle("Gluino mass [GeV]");
      h_GluinoHist_Fit->GetXaxis()->SetTitleSize(labsiz);
      h_GluinoHist_Fit->GetYaxis()->SetTitleSize(labsiz);
	  if (tdrstyle == false) {
		float axsize = 0.04;
		h_GluinoHist_Fit->GetXaxis()->SetLabelSize(axsize);
		h_GluinoHist_Fit->GetYaxis()->SetLabelSize(axsize);
     }
     if (flavor.compare("113_223") == 0 && ptcut == "60")
		h_GluinoHist_Fit->GetYaxis()->SetRangeUser(14.0,  50.0);
       h_GluinoHist_Fit->Draw("APX");	// X eliminates error bars
       // h_GluinoHist_Fit->Draw("AP");	
      // TH1 *fithist = (TH1 *) fitfunccopy->GetHistogram()->Clone(fitnamew.c_str());
      TH1 *fithist = (TH1 *) fitfunccopy->GetHistogram()->Clone();
      int fillcolor = kGreen + 2;
      int fillstyle = 3013;
      if (fithist != NULL) {
      	int numBins = fithist->GetNbinsX();
      	for (int cnt = 1; cnt <= numBins; ++cnt) {
      		setErr(fithist, cnt, flavor, "width");
      	}
      	fithist->SetFillColor(fillcolor);
      	fithist->SetFillStyle(fillstyle);
      	fithist->Draw("CE3SAME");
      }
      fitfunccopy->Draw("CSAME");
      // h_GluinoHist_Fit->Draw("P");	// Draw points over fit line
      leg->AddEntry(fitfunccopy, "Gaussian width", "L");
      leg->AddEntry(fithist, "Uncertainty", "F");
	 leg->Draw();
      tex->SetX(headpos);
      tex->Draw();
      tex2->Draw();
      tex3->Draw();
      tex3a->Draw();
      if (tex4 != NULL)
		tex4->Draw();
      cGluinoFitsOpti->Write();
      cGluinoFitsOpti->SaveAs((folder + "RPVwidth" +flavor + ptcut+uncert+postfix).c_str());

      TCanvas * cGluinoFitsOpt2 = new TCanvas(("RPVacc_"+flavor +ptcut).c_str(), ("RPV_" + ptcut+"_"+cuts).c_str(), 800, 600);
	 // title="Acc. x Eff. for " + titlepart;
	 title= titlepart;
	 tex2->SetText(titpos,titly, title.c_str());
	 TLegend *leg2 = new TLegend(legx, 0.2, legx + 0.3, 0.4);
	 leg2->SetBorderSize(1);
	 leg2->SetTextFont(62);
	 leg2->SetTextSize(0.04);
	 leg2->SetLineColor(kBlack);
	 leg2->SetLineStyle(1);
	 leg2->SetLineWidth(1);
	 leg2->SetFillColor(0);
	 leg2->SetFillStyle(1001);

      TF1 *fitfuncA = h_GluinoHist_MCcomb->GetFunction("total");
      string fitname = "fitcopyA" + ptcut;
      TF1* fitfunccopyA = (TF1 *) fitfuncA->Clone(fitname.c_str());
      if (fitfuncA == NULL)
     	 cout << "Can't get fit func\n";
      else {
      	fitfuncA->Delete();
      	fitfunccopyA->SetLineWidth(3);
      	fitfunccopyA->SetLineColor(kGreen + 3);
		// fitfunc->SetLineStyle(3); // Dotted
      }
      h_GluinoHist_MCcomb->SetMarkerStyle(1);
      // h_GluinoHist_MCcomb->SetMarkerColor(kBlack);
      h_GluinoHist_MCcomb->SetMarkerColor(kWhite);
      h_GluinoHist_MCcomb->SetTitle(title.c_str());
      h_GluinoHist_MCcomb->GetXaxis()->SetLabelFont(62);
      h_GluinoHist_MCcomb->GetXaxis()->SetTitleFont(62);
      h_GluinoHist_MCcomb->GetYaxis()->SetLabelFont(62);
      // h_GluinoHist_MCcomb->GetYaxis()->SetLabelSize(62);
h_GluinoHist_MCcomb->GetYaxis()->SetTitleFont(62);
      h_GluinoHist_MCcomb->GetYaxis()->SetTitle("Acceptance x Efficiency");
	  if (tdrstyle == false) {
		h_GluinoHist_MCcomb->GetXaxis()->SetTitleOffset(offset);
		h_GluinoHist_MCcomb->GetYaxis()->SetTitleOffset(offset + 0.35);
	  }
      // h_GluinoHist_MCcomb->GetYaxis()->SetTitleOffset(1.4);
      h_GluinoHist_MCcomb->GetXaxis()->SetTitle("Gluino mass [GeV]");
      h_GluinoHist_MCcomb->GetXaxis()->SetTitleSize(labsiz);
	  if (tdrstyle == false)
	  	labsiz -= 0.01;
      h_GluinoHist_MCcomb->GetYaxis()->SetTitleSize(labsiz);
	  if (tdrstyle == false) {
		float axsize = 0.035;
		 h_GluinoHist_MCcomb->GetXaxis()->SetLabelSize(axsize);
		 h_GluinoHist_MCcomb->GetYaxis()->SetLabelSize(axsize);
	  }
      if (flavor.compare("113_223") == 0) {
		float ylimit = 0.05;
		if ( ptcut == "110")
			ylimit = 0.022;
		// gStyle->SetStatY(0.8);
		h_GluinoHist_MCcomb->GetYaxis()->SetRangeUser(0.0, ylimit);
	}

      // h_GluinoHist_MCcomb->Draw("AL");	
      h_GluinoHist_MCcomb->Draw("APX");
      // fitfunccopyA->Draw("C same");
      // TH1 *fithistA = (TH1 *) fitfunccopyA->GetHistogram()->Clone(fitname.c_str());
      TH1 *fithistA = (TH1 *) fitfunccopyA->GetHistogram()->Clone();
      if (fithistA != NULL) {
      	int numBins = fithistA->GetNbinsX();
      	for (int cnt = 1; cnt <= numBins; ++cnt) {
      		setErr(fithistA, cnt, flavor, "acceptance");
      	}
      	fithistA->SetFillColor(fillcolor);
      	fithistA->SetFillStyle(fillstyle);
      	fithistA->Draw("CE3SAME");
      }
      fitfunccopyA->Draw("CSAME");
      // h_GluinoHist_MCcomb->Draw("P");	// Draw points over fit line
      tex->SetX(headpos);
      tex->Draw();
      tex2->Draw();
      tex3->Draw();
      tex3a->Draw();
      leg2->AddEntry(fitfunccopyA, "Acc. x Eff.", "L");
      leg2->AddEntry(fithistA, "Uncertainty", "F");
	 leg2->Draw();
       if (tex4 != NULL)
		tex4->Draw();
 
      cGluinoFitsOpt2->Write();
      cGluinoFitsOpt2->SaveAs((folder + "RPVacc" +flavor + ptcut+uncert+postfix).c_str());

			/*
      gStyle->SetStatY(0.4);
      TCanvas * cGluinoFitsOpt3 = new TCanvas(("RPVfullacc_"+flavor +ptcut).c_str(), ("RPVfull_" + ptcut+"_"+cuts).c_str(), 800, 600);
			title="Gaussian Mean for " + titlepart;
			tex2->SetText(titpos, 0.89, title.c_str());
			// title="Full Acceptance for " + titlepart;
      h_FullAccept->SetMarkerStyle(1);
      // h_FullAccept->SetMarkerColor(kWhite);
      h_FullAccept->SetLineColor(kRed);
      h_FullAccept->SetLineWidth(2.0);
      // h_FullAccept->SetTitle(title.c_str());
      // h_FullAccept->GetYaxis()->SetTitle("Acceptance");
      h_FullAccept->GetYaxis()->SetTitle("Gaussian Mean [GeV]");
      h_FullAccept->GetXaxis()->SetTitleOffset(1.3);
      h_FullAccept->GetXaxis()->SetTitle("Gluino Mass [GeV]");
      h_FullAccept->GetXaxis()->SetTitleSize(labsiz);
      h_FullAccept->GetYaxis()->SetTitleSize(labsiz);
      h_FullAccept->GetXaxis()->SetLabelSize(axsize);
      h_FullAccept->GetYaxis()->SetLabelSize(axsize);
      h_FullAccept->Draw("AL");	
      // h_FullAccept->Draw("APX");	
			// leg->Draw();
      
      // h_GluinoHist_MCcomb->SetFillColor(10);
      // h_GluinoHist_MCcomb->SetLineColor(kBlack);
      //   h_GluinoHist_MCcomb->Draw("samehist");
      // f_GluinoGauss->SetLineColor(kRed);
      //f_GluinoGauss->Draw("same");
      
      //f_GluinoP4->Draw("same");
      tex->SetX(titpos);
      tex->Draw();
      tex2->Draw();
      tex3->Draw();
      tex3a->Draw();
      if (tex4 != NULL)
		tex4->Draw();
      f1.cd();
      cGluinoFitsOpt3->Write();
      cGluinoFitsOpt3->SaveAs((folder + "RPVmean" +flavor + ptcut+uncert+postfix).c_str());

      gStyle->SetStatY(0.4);
      TCanvas *cMeanOffset = new TCanvas(("RPVMeanOffset_"+flavor +ptcut).c_str(),
      	("RPVMeanOffset_" + ptcut + "_" + cuts).c_str(), 800, 600);
      axsize = 0.035;
			title="Mass Deviation for " + titlepart;
			titpos = 0.35;
			tex2->SetText(titpos, 0.89, title.c_str());
      h_MeanOffset->SetMarkerStyle(1);
      h_MeanOffset->SetLineColor(kRed);
      h_MeanOffset->SetLineWidth(2.0);
      h_MeanOffset->GetYaxis()->SetTitleOffset(1.3);
      h_MeanOffset->GetYaxis()->SetTitle("Fractional Mass Deviation");
      h_MeanOffset->GetXaxis()->SetTitleOffset(1.3);
      h_MeanOffset->GetXaxis()->SetTitle("Gluino Mass [GeV]");
      h_MeanOffset->GetXaxis()->SetTitleSize(labsiz);
      h_MeanOffset->GetYaxis()->SetTitleSize(labsiz);
      h_MeanOffset->GetXaxis()->SetLabelSize(axsize);
      h_MeanOffset->GetYaxis()->SetLabelSize(axsize);
      TLine *max = new TLine(0.5, 0.1, 0.5, 0.9);
			max->SetLineColor(kGreen + 2);
			max->SetLineWidth(3);
      h_MeanOffset->Draw("AL");	
			max->DrawLineNDC(0.16, 0.49, 0.98, 0.49);
      tex->SetX(titpos);
      tex->Draw();
      tex2->Draw();
      tex3->SetX(titpos);
      tex3->Draw();
      tex3a->SetX(titpos);
      tex3a->Draw();
      if (tex4 != NULL) {
      	tex4->SetX(titpos);
				tex4->Draw();
			 }
      f1.cd();
      cMeanOffset->Write();
      cMeanOffset->SaveAs((folder + "RPVmassdev" +flavor + ptcut+uncert+postfix).c_str());
			*/
      }
  }
}
void fitmmp(TH1 *hmmp, float step_x0 = 2, float step_x1 = 2.1, float wval = 0, bool verbose = false) {
  float fnrangemax = 1.1;
  float mmplow = 0.4;
  //float bgp2 = 2.1e8;
  float gsig = -0.0065+0.013*wval;
  float pol2cutoff = 4; //wval under which to use pol2
  float fitcutoff = 1.1;
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,fnrangemax,true);
  fbg->FixParameter(7,step_x0);
  fbg->FixParameter(8,step_x1);
  if (wval<pol2cutoff) {
    fitcutoff = 1.1;
    fbg->FixParameter(3,0);
    fbg->FixParameter(4,0);
  } else fitcutoff = 2;
  hmmp->Fit(fbg,options.Data(),"",mmplow,fitcutoff);
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,fnrangemax,false);
    fbg2->SetParameters(fbg->GetParameters());
    fbg2->FixParameter(7,step_x0);
    fbg2->FixParameter(8,step_x1);
    if (wval<pol2cutoff) {
      fbg2->FixParameter(3,0);
      fbg2->FixParameter(4,0);
    }
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,fnrangemax);
    fgaus->FixParameter(2,gsig);
    fgaus->FixParameter(1,0.783);
    float gmax = 0.85;
    if (gmax > step_x0) gmax = step_x0;
    htmp->Fit(fgaus,options.Data(),"",0.74,gmax);
    TF1 *f = f_pol4gaus("f",0.4,fnrangemax,fbg2,fgaus);
    f->FixParameter(8,step_x0);
    f->FixParameter(9,step_x1);
    if (wval<pol2cutoff) {
      f->FixParameter(3,0);
      f->FixParameter(4,0);
    }
    f->SetNpx(500);
    f->FixParameter(6,0.783);
    f->FixParameter(7,gsig);
    hmmp->Fit(f,options.Data(),"",mmplow,fitcutoff);

    //f->FixParameter(2,0.9*f->GetParameter(2));
    //hmmp->Fit(f,options.Data(),"",mmplow,fitcutoff);

    fgaus->SetRange(0.4,fnrangemax);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    float ymax = 1.1*hmmp->GetMaximum();
    hmmp->GetYaxis()->SetRangeUser(0,ymax);
    TLine *l1 = new TLine(step_x0,0,step_x0,ymax);
    TLine *l2 = new TLine(step_x1,0,step_x1,ymax);
    l1->SetLineColor(kBlue+1);
    l2->SetLineColor(kBlue+1);
    hmmp->GetListOfFunctions()->Add(l1);
    hmmp->GetListOfFunctions()->Add(l2);
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}
void fit(float bgpar2smudge=1.0) {
  TF1 *fsig = new TF1("fsig",&d_sig,0.4,2,5);
  FILE *ofile;
  ofile = fopen("xsect-integrated-me.txt","w");
  TFile *_file0 = TFile::Open("h3maker-hn.root","update");
  _file0->Delete("*_f;*");
  TH2 *h2xsect = new TH2("hq2wXsect","Q^2:W",32,1.6,3.2,7,1.5,5.1);
  Double_t qbinedges[] = { 1.5, 1.6, 1.8, 2.1, 2.4, 2.76, 3.3, 5.1 };
  h2xsect->GetYaxis()->Set(7,qbinedges);
  TH3 *h3 = (TH3*)_file0->Get("hq2wmmp");
  int qbins = h3->GetZaxis()->GetNbins();
  //int wbins = h3->GetYaxis()->GetNbins();
  fprintf(ofile, "W\tQ2\txsect\terror\tpol4p0\tpol4p1\tpol4p2\tpol4p3\tpol4p4\tgN\tgM\tgS\tstepx0\tstepx1\txsectFn\n");
  for (int iq = 0; iq < qbins; iq++) {
    TString hsn = TString::Format("hs%d",iq);
    THStack *hs = (THStack*)_file0->Get(hsn.Data());
    TIter next(hs->GetHists());
    //while (TObject *obj = next()) {
    //TH1 *h = (TH1*)obj;
    while (TH1 *h = (TH1*)next()) {
      float *wq = getwq(h);
      float wval = wq[0];
      float qval = wq[1];
      delete [] wq;
      int wbin = h3->GetYaxis()->FindBin(wval);
      float wlow = h3->GetYaxis()->GetBinLowEdge(wbin);
      float step_x0 = sqrt(wlow*wlow+MASS_P*MASS_P-2*wlow*MASS_P);
      float whigh = h3->GetYaxis()->GetBinLowEdge(wbin+1);
      float step_x1 = sqrt(whigh*whigh+MASS_P*MASS_P-2*whigh*MASS_P);
      fitmmp(h,step_x0,step_x1,wval);
      TH1 *htmp = (TH1*)h->Clone("hbgsubtracted");
      TF1 *fbg = (TF1*)h->GetListOfFunctions()->FindObject("fbg");
      htmp->Add(fbg,-1);
      double N = htmp->Integral(34,43);
      double qwidth = h3->GetZaxis()->GetBinWidth(iq+1);
      //int wbin = h3->GetYaxis()->FindBin(wval);
      double wwidth = h3->GetYaxis()->GetBinWidth(wbin);

      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      fsig->SetParameter(0,ftmp->GetParameter(5));
      fsig->SetParameter(1,ftmp->GetParameter(6));
      fsig->SetParameter(2,ftmp->GetParameter(7));
      fsig->SetParameter(3,step_x0);
      fsig->SetParameter(4,step_x1);
      fsig->SetLineWidth(2);
      fsig->SetLineColor(kBlue+1);
      h->GetListOfFunctions()->Add((TF1*)fsig->Clone("fsig"));
      //fsig->Print();
      double Nfn = 0;
      for (int b = 1; b < h->GetNbinsX(); b++) {
        double x = h->GetXaxis()->GetBinCenter(b);
        Nfn += fsig->Eval(x);
      }
      //printf("**** %.3e\t\%.3e\n",Nfn,N);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double xsectFn = Nfn/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile,"\t%.3e",xsectFn/(1e6));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// root -l       computeDrellYanPtllWeight.C+
// root -l -b -q computeDrellYanPtllWeight.C+
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void computeDrellYanPtllWeight(TString fname = "h_pt2l_mm")
{
  gInterpreter->ExecuteMacro("PaperStyle.C");

  TFile* file = TFile::Open("figures/Control/01_DY/" + fname + ".root");

  TH1D* ratio = (TH1D*)file->Get("ratio");


  // Draw the ratio
  //----------------------------------------------------------------------------
  TCanvas* c1 = new TCanvas("c1", "c1");

  ratio->SetMinimum(0.85);
  ratio->SetMaximum(1.20);

  ratio->Draw("ep");

  TString ytitle = Form("data / MC ratio / %.0f GeV", ratio->GetBinWidth(0));

  SetAxis(ratio, ratio->GetXaxis()->GetTitle(), ytitle, 1.7, 1.8);


  // Draw the old function
  //----------------------------------------------------------------------------
  TF1* fOld = new TF1("fOld", "[3]*(0.95 - [0]*TMath::Erf((x-[1])/[2]))", 0, 90);

  fOld->SetLineColor  (kGreen+2);
  fOld->SetMarkerColor(kGreen+2);

  // https://github.com/latinos/PlotsConfigurations/blob/master/Configurations/ggH/nuisances_iteos.py#L969-L977
  fOld->SetParameter(0,     0.1);
  fOld->SetParameter(1,    14.0);
  fOld->SetParameter(2,     8.8);
  fOld->SetParameter(3, 1.08683);

  fOld->Draw("same");


  // Draw the old function error band
  //------------------------------------------------------------------------------
  if (errorband)
    {
      TF1* fOld_down = (TF1*)fOld->Clone("fOld_down");
      TF1* fOld_up   = (TF1*)fOld->Clone("fOld_up");

      fOld_down->SetParameter(0, 13.6);
      fOld_down->SetParameter(1,  8.6);

      fOld_up->SetParameter(0, 14.4);
      fOld_up->SetParameter(1,  9.0);

      fOld_down->Draw("same");
      fOld_up  ->Draw("same");
    }


  // Update the fit parameters of the old function
  //
  //   1  p0           6.85257e-02   2.99341e-01   1.42129e-05   4.16760e-04
  //   2  p1           1.24518e+01   4.76906e+01   3.55312e-03   6.41625e-07
  //   3  p2           5.40627e+00   7.83907e+01   6.49546e-03  -1.96376e-06
  //   4  p3           1.05396e+00   3.48880e-01   1.58779e-05  -3.97115e-05
  //
  //----------------------------------------------------------------------------
  TF1* fNew = new TF1("fNew", "[3]*(0.95 - [0]*TMath::Erf((x-[1])/[2]))", 0, 90);

  fNew->SetLineColor  (kRed+1);
  fNew->SetMarkerColor(kRed+1);

  fNew->SetParameter(0, 0.1);
  fNew->SetParameter(1,  10);
  fNew->SetParameter(2,   1);
  fNew->SetParameter(3,   1);

  ratio->Fit(fNew, "mlr0");

  fNew->Draw("same");


  // Draw the updated error band
  //------------------------------------------------------------------------------
  if (errorband)
    {
      TF1* fNew_down = (TF1*)fNew->Clone("fNew_down");
      TF1* fNew_up   = (TF1*)fNew->Clone("fNew_up");

      fNew_down->SetParameter(0, 0.97 * fNew->GetParameter(0));
      fNew_down->SetParameter(1, 0.97 * fNew->GetParameter(1));

      fNew_up->SetParameter(0, 1.03 * fNew->GetParameter(0));
      fNew_up->SetParameter(1, 1.03 * fNew->GetParameter(1));

      fNew_down->Draw("same");
      fNew_up  ->Draw("same");
    }


  // Fit Lorenzo's function
  //
  //   1  p0           1.17864e-01   7.44869e-01   1.03478e-05   1.79528e-03
  //   2  p1           1.34231e+01   6.10789e+01   2.78074e-03   6.38697e-06
  //   3  p2           9.76801e+00   1.03947e+02   5.51661e-03  -2.28998e-06
  //   4  p3           1.01367e+00   6.56154e-01   1.29644e-05  -1.36428e-04
  //   5  p4           2.50141e-03   2.62347e-02   1.53669e-07  -1.11290e-01
  //   6  p5           1.10637e-05   1.42769e-04   1.32442e-09   1.17953e+01
  //
  //----------------------------------------------------------------------------
  TF1* fLo = new TF1("fLo", "([3] + [4]*x - [5]*x*x) * (0.95 - [0]*TMath::Erf((x-[1])/[2]))", 0, 150);

  fLo->SetLineColor  (kBlue);
  fLo->SetMarkerColor(kBlue);

  fLo->SetParameter(0,    0.131835);
  fLo->SetParameter(1,     14.1972);
  fLo->SetParameter(2,     10.1525);
  fLo->SetParameter(3,    0.876979);
  fLo->SetParameter(4, 4.11598e-03);
  fLo->SetParameter(5, 2.35520e-05);

  ratio->Fit(fLo, "mlr0");


  // Get the point where the first derivative is closest to zero
  //
  //   fLo = 0.9608 and d(fLo)/d(ptll) = -0.000110 for ptll = 119 GeV
  //
  //----------------------------------------------------------------------------
  float smallest_derivative_value = 999;
  float smallest_derivative_x     = 999;

  for (int x=90; x<120; x++)
    {
      if (fLo->Derivative(x) < smallest_derivative_value)
	{
	  smallest_derivative_value = fLo->Derivative(x);
	  smallest_derivative_x     = x;
	}
    }

  printf("\n fLo = %.4f and d(fLo)/d(ptll) = %f for ptll = %.0f GeV\n\n",
	 fLo->Eval(smallest_derivative_x),
	 fLo->Derivative(smallest_derivative_x),
	 smallest_derivative_x);


  // Draw Lorenzo's function in two ranges
  //----------------------------------------------------------------------------
  fLo->SetRange(0, smallest_derivative_x);

  fLo->Draw("same");

  TF1* fHi = new TF1("fHi", "[0]", smallest_derivative_x, 150);

  fHi->SetLineColor  (kBlue);
  fHi->SetMarkerColor(kBlue);

  fHi->SetParameter(0, fLo->Eval(smallest_derivative_x));

  fHi->Draw("same");


  // Legend
  //----------------------------------------------------------------------------
  DrawLegend(0.69, 0.83, (TObject*)fOld, " old fit");
  DrawLegend(0.69, 0.77, (TObject*)fNew, " new fit");
  DrawLegend(0.69, 0.71, (TObject*)fLo,  " Lorenzo's fit");


  // Save
  //----------------------------------------------------------------------------
  ratio->Draw("ep,same");

  c1->SaveAs(fname + "_ratio_fit.png");
}
Esempio n. 8
0
//void testFit(int count=3,Double_t ptmin=30.,Double_t ptmax=40,TString sample="PbPb")
void compareUpgrade(int option=2)
{

  int count; Double_t ptmin; Double_t ptmax; TString sample;
  int nmin,nmax,mymaxhisto;
  
  if (option==1)
  {count=3; ptmin=30.; ptmax=40; sample="PbPb"; mymaxhisto=2000;  };
  if (option==2)
  {count=1; ptmin=2.; ptmax=3; sample="PbPbMB"; mymaxhisto=600000;};


  TCanvas* c= new TCanvas(Form("c%d",count),"",600,600);
  TFile *file=new TFile(Form("FitsFiles/Fits_%s_%d.root",sample.Data(), count));
  TH1D* h = (TH1D*)file->Get(Form("h-%d",count));
  TH1D* hMCSignal = (TH1D*)file->Get(Form("hMCSignal-%d",count));
  TH1D* hMCSwapped = (TH1D*)file->Get(Form("hMCSwapped-%d",count));
    
  TF1* f = new TF1(Form("f%d",count),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10]))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*x*x+[6]*x*x*x", 1.7, 2.0);

  f->SetParLimits(4,-1000,1000);
  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  f->FixParameter(5,0);
  f->FixParameter(6,0);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
 
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);
  
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->ReleaseParameter(5);
  f->ReleaseParameter(6);

  f->SetLineColor(kRed);
  

  /*
  TCanvas*mycanvas=new TCanvas("mycanvas","mycanvas",1000,500);
  mycanvas->Divide(2,1);
  mycanvas->cd(1);
  hMCSignal->Draw();
  mycanvas->cd(2);
  hMCSwapped->Draw();
  mycanvas->SaveAs("mycanvas.pdf");
*/
  
  h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  //f->ReleaseParameter(2);                                     // you need to release these two parameters if you want to perform studies on the sigma shape
  //f->ReleaseParameter(10);                                   // you need to release these two parameters if you want to perform studies on the sigma shape
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L q","",minhisto,maxhisto);
  h->Fit(Form("f%d",count),"L m","",minhisto,maxhisto);
  
  std::cout<<"parameter 10="<<f->GetParameter(10)<<std::endl;

  TF1* background = new TF1(Form("background%d",count),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetParameter(2,f->GetParameter(5));
  background->SetParameter(3,f->GetParameter(6));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass%d",count),"[0]*([3]*([4]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[4])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5])))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  TF1* massSwap = new TF1(Form("fmassSwap%d",count),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);
  
  h->SetXTitle("m_{#piK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw("e");

  background->Draw("same");   
  mass->SetRange(minhisto,maxhisto);	
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");
  
  Double_t yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldtotal = f->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"yield signal="<<yield<<std::endl;
  std::cout<<"total counts="<<yieldtotal<<std::endl;

  TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  TLatex Tl;
  Tl.SetNDC();
  Tl.SetTextAlign(12);
  Tl.SetTextSize(0.04);
  Tl.SetTextFont(42);
  Tl.DrawLatex(0.18,0.93, "#scale[1.25]{CMS} Performance");
  Tl.DrawLatex(0.65,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));

  TLatex* tex;

  tex = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

  tex = new TLatex(0.22,0.83,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();

  h->GetFunction(Form("f%d",count))->Delete();
  TH1F* histo_copy_nofitfun = ( TH1F * ) h->Clone("histo_copy_nofitfun");
  histo_copy_nofitfun->Draw("esame");

 TH1D* hTest = new TH1D("hTest","",nbinsmasshisto,minhisto,maxhisto);

 for (int m=0;m<yieldtotal;m++){
 double r = f->GetRandom();
 hTest->Fill(r);
 
 }

 TF1* ffaketotal=(TF1*)f->Clone("ffake");
 TF1* ffakemass=(TF1*)mass->Clone("ffakemass");
 TF1* ffakebackground=(TF1*)background->Clone("ffakebackground");
 TF1* ffakemassSwap=(TF1*)massSwap->Clone("ffakemassSwap");
 
 Double_t yieldtotal_original = ffaketotal->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldmass_original = ffakemass->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldbackground_original = ffakebackground->Integral(minhisto,maxhisto)/binwidthmass;
 Double_t yieldswapped_original = ffakemassSwap->Integral(minhisto,maxhisto)/binwidthmass;

 TH1D* hTestFake = new TH1D("hTestFake","",nbinsmasshisto,minhisto,maxhisto);
  ffakemass->SetParameter(2,ffaketotal->GetParameter(2)*0.8);
  ffakemass->SetParameter(10,ffaketotal->GetParameter(10)*0.8);
 
Double_t yieldmass_modified= ffakemass->Integral(minhisto,maxhisto)/binwidthmass;

cout<<"mass original="<<yieldmass_original<<endl;
cout<<"mass modified="<<yieldmass_modified<<endl;

 for (int m=0;m<yieldmass_original*scalefactor;m++){
   double r = ffakemass->GetRandom();
   hTestFake->Fill(r);
 }

  for (int m=0;m<(int)(yieldbackground_original*scalefactor*bkgreduction);m++){
   double r = ffakebackground->GetRandom();
   hTestFake->Fill(r);
 }
 
 for (int m=0;m<(int)(yieldswapped_original*scalefactor*bkgreduction);m++){
   double r = ffakemassSwap->GetRandom();
   hTestFake->Fill(r);
 }

 TCanvas*c2=new TCanvas("c2","c2",500,500);
 c2->cd();
 hTest->SetMaximum(2000);
  hTest->SetXTitle("m_{#piK} (GeV/c^{2})");
  hTest->SetYTitle("Entries / (5 MeV/c^{2})");
  hTest->GetXaxis()->CenterTitle();
  hTest->GetYaxis()->CenterTitle();
  hTest->SetAxisRange(0,hTest->GetMaximum()*1.*1.2,"Y");
  hTest->GetXaxis()->SetTitleOffset(1.3);
  hTest->GetYaxis()->SetTitleOffset(1.8);
  hTest->GetXaxis()->SetLabelOffset(0.007);
  hTest->GetYaxis()->SetLabelOffset(0.007);
  hTest->GetXaxis()->SetTitleSize(0.045);
  hTest->GetYaxis()->SetTitleSize(0.045);
  hTest->GetXaxis()->SetTitleFont(42);
  hTest->GetYaxis()->SetTitleFont(42);
  hTest->GetXaxis()->SetLabelFont(42);
  hTest->GetYaxis()->SetLabelFont(42);
  hTest->GetXaxis()->SetLabelSize(0.04);
  hTest->GetYaxis()->SetLabelSize(0.04);
  hTest->SetMarkerSize(0.8);
  hTest->SetMarkerStyle(20);
  hTest->SetStats(0);
  hTest->Draw("e");

 hTest->SetLineColor(1);
 hTest->SetMarkerColor(1);
  hTestFake->SetLineColor(2);
 hTestFake->SetMarkerColor(2);

 
 hTest->Draw("ep");
 hTestFake->Draw("epsame");

  TLegend* myleg = new TLegend(0.2177419,0.6292373,0.6633065,0.7266949,NULL,"brNDC");
  myleg->SetBorderSize(0);
  myleg->SetTextSize(0.04);
  myleg->SetTextFont(42);
  myleg->SetFillStyle(0);
  myleg->AddEntry(hTest,"Current CMS, |y|<1, L_{int}=0.5/nb","pl");
  myleg->AddEntry(hTestFake,"Upgraded CMS, |y|<2, L_{int}=1.5/nb","l");
  myleg->Draw("same");

  TLatex* mytex;

  mytex = new TLatex(0.22,0.83,Form("%.0f < p_{T} < %.0f GeV/c",ptmin,ptmax));
  mytex->SetNDC();
  mytex->SetTextFont(42);
  mytex->SetTextSize(0.04);
  mytex->SetLineWidth(2);
  mytex->Draw();
  
  TLatex* mychannel;

  mychannel = new TLatex(0.22,0.765,"D^{0} #rightarrow K#pi");
  mychannel->SetNDC();
  mychannel->SetTextFont(42);
  mychannel->SetTextSize(0.055);
  mychannel->SetLineWidth(2);
  mychannel->Draw();

  TLatex myTl;
  myTl.SetNDC();
  myTl.SetTextAlign(12);
  myTl.SetTextSize(0.04);
  myTl.SetTextFont(42);
  myTl.DrawLatex(0.2,0.90, "#scale[1.25]{CMS} Performance");
  myTl.DrawLatex(0.63,0.90, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  
  
  TFile*foutput=new TFile(Form("foutput_%s.root",sample.Data()),"recreate");
  foutput->cd();
  hTest->SetName("hTest");
  hTestFake->SetName("hTestFake");
  hTest->SetMaximum(mymaxhisto);
  hTest->Write();
  hTestFake->SetMaximum(mymaxhisto);
  hTestFake->Write();
  hMCSignal->Write();
  hMCSwapped->Write();
  c2->SaveAs(Form("PlotsUpgrade/canvasPerformance%s.pdf",sample.Data()));
  c2->SaveAs(Form("PlotsUpgrade/canvasPerformance%s.png",sample.Data()));

 
}
Esempio n. 9
0
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

  setTDRStyle();
  writeExtraText = false; // for JEC paper CWR

  TDirectory *curdir = gDirectory;

  // Open jecdata.root produced by reprocess.C
  TFile *fin = new TFile("rootfiles/jecdata.root","UPDATE");
  assert(fin && !fin->IsZombie());
  
  const int ntypes = 3;
  const char* types[ntypes] = {"data", "mc", "ratio"};
  const int nmethods = 2;
  const char* methods[nmethods] = {"mpfchs1", "ptchs"};
  const int nsamples = (dodijet ? 4 : 3);
  const char* samples[4] = {"gamjet", "zeejet", "zmmjet", "dijet"};
  string sbin = Form("eta%02.0f-%02.0f",10*etamin,10*etamax);
  const char* bin = sbin.c_str();
  const int nalphas = 4;
  const int alphas[nalphas] = {30, 20, 15, 10};

  // Z+jet bins
  const double ptbins1[] = {30, 40, 50, 60, 75, 95, 125, 180, 300, 1000};
  const int npt1 = sizeof(ptbins1)/sizeof(ptbins1[0])-1;
  TH1D *hpt1 = new TH1D("hpt1","",npt1,&ptbins1[0]);
  TProfile *ppt1 = new TProfile("ppt1","",npt1,&ptbins1[0]);

  // gamma+jet bins
  const double ptbins2[] = {30, 40, 50, 60, 75, 100, 125, 155, 180,
			    210, 250, 300, 350, 400, 500, 600, 800};
  const int npt2 = sizeof(ptbins2)/sizeof(ptbins2[0])-1;
  TH1D *hpt2 = new TH1D("hpt2","",npt2,&ptbins2[0]);
  TProfile *ppt2 = new TProfile("ppt2","",npt2,&ptbins2[0]);

  // dijet bins
  const double ptbins4[] = {20, 62, 107, 175, 242, 310, 379, 467,
			    628, 839, 1121, 1497, 2000};
  const int npt4 = sizeof(ptbins4)/sizeof(ptbins4[0])-1;
  TH1D *hpt4 = new TH1D("hpt4","",npt4,&ptbins4[0]);
  TProfile *ppt4 = new TProfile("ppt4","",npt4,&ptbins4[0]);

  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.045);

  map<string,const char*> texlabel;
  texlabel["gamjet"] = "#gamma+jet";
  texlabel["zeejet"] = "Z#rightarrowee+jet";
  texlabel["zmmjet"] = "Z#rightarrow#mu#mu+jet";
  texlabel["dijet"] = "Dijet";
  texlabel["ptchs"] = "p_{T} balance (CHS)";
  texlabel["mpfchs"] = "MPF raw (CHS)";
  texlabel["mpfchs1"] = "MPF type-I (CHS)";

  // overlay of various alpha values
  TCanvas *c1 = new TCanvas("c1","c1",ntypes*400,nmethods*400);
  c1->Divide(ntypes,nmethods);

  TH1D *h1 = new TH1D("h1",";p_{T} (GeV);Response",1270,30,1300);

  // extrapolation vs alpha for each pT bin
  vector<TCanvas*> c2s(ntypes*nmethods);
  for (unsigned int icanvas = 0; icanvas != c2s.size(); ++icanvas) {
    TCanvas *c2 = new TCanvas(Form("c2_%d",icanvas),Form("c2_%d",icanvas),
			      1200,1200);
    c2->Divide(3,3);
    c2s[icanvas] = c2;
  }

  TH1D *h2 = new TH1D("h2",";#alpha;Response",10,0.,0.4);
  h2->SetMaximum(1.08);
  h2->SetMinimum(0.88);

  // krad corrections
  TCanvas *c3 = new TCanvas("c3","c3",ntypes*400,nmethods*400);
  c3->Divide(ntypes,nmethods);

  TH1D *h3 = new TH1D("h3",";p_{T,ref} (GeV);FSR sensitivity: -dR/d#alpha [%]",
		      1270,30,1300);

  cout << "Reading in data" << endl << flush;
  // Read in plots vs pT (and alpha)
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gemap;
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gamap;
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      for (int  isample = 0; isample != nsamples; ++isample) {

	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  fin->cd();
	  assert(gDirectory->cd(types[itype]));
	  assert(gDirectory->cd(bin));
	  TDirectory *d = gDirectory;

	  const char *ct = types[itype];
	  const char *cm = methods[imethod];
	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  // Get graph made vs pT
	  string s = Form("%s/%s/%s_%s_a%d",types[itype],bin,cm,cs,a);
	  TGraphErrors *g = (TGraphErrors*)fin->Get(s.c_str());
	  if (!g) cout << "Missing " << s << endl << flush;
	  assert(g);

	  // Clean out empty points
	  // as well as trigger-biased ones for dijets
	  // as well as weird gamma+jet high pT point
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetY()[i]==0 || g->GetEY()[i]==0 ||
		(string(cs)=="dijet" && g->GetX()[i]<70.) ||
		(string(cs)=="gamjet" && g->GetX()[i]>600. && etamin!=0))
	      g->RemovePoint(i);
	  }

	  gemap[ct][cm][cs][a] = g;
	  
	  // Sort points into new graphs vs alpha
	  TH1D *hpt = (isample==0 ? hpt2 : hpt1);
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { hpt = hpt4; ppt = ppt4; } // pas-v6
	  for (int i = 0; i != g->GetN(); ++i) {
	    
	    double pt = g->GetX()[i];
	    ppt->Fill(pt, pt);
	    int ipt = int(hpt->GetBinLowEdge(hpt->FindBin(pt))+0.5);
	    //int ipt = int(pt+0.5);
	    TGraphErrors *ga = gamap[ct][cm][cs][ipt];
	    if (!ga) {
	      ga = new TGraphErrors(0);
	      ga->SetMarkerStyle(g->GetMarkerStyle());
	      ga->SetMarkerColor(g->GetMarkerColor());
	      ga->SetLineColor(g->GetLineColor());
	      gamap[ct][cm][cs][ipt] = ga;
	    }
	    int n = ga->GetN();
	    ga->SetPoint(n, 0.01*a, g->GetY()[i]);
	    ga->SetPointError(n, 0, g->GetEY()[i]);
	  } // for i 

	} // for ialpha

      } // for isample
    } // for imethod
  } // for itype

  cout << "Drawing plots vs pT for each alpha" << endl << flush;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c1->cd(ipad);
      gPad->SetLogx();
      h1->SetMaximum(itype<2 ? 1.15 : 1.08);
      h1->SetMinimum(itype<2 ? 0.85 : 0.93);
      h1->SetYTitle(Form("Response (%s)",ct));
      h1->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3, #alpha=0.1--0.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {
	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  TGraphErrors *g = gemap[ct][cm][cs][a]; assert(g);

	  // Clean out points with very large uncertainty for plot readability
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetEY()[i]>0.02) g->RemovePoint(i);
	  }

	  g->Draw("SAME Pz");

	  if (ialpha==0) leg->AddEntry(g,texlabel[cs],"P");
	}
      } // for isample

      // Individual plots for JEC paper
      if ( true ) { // paper

	TH1D *h = new TH1D(Form("h_5%s_%s",ct,cm),
			   Form(";p_{T} (GeV);Response (%s)",ct),
			   1270,30,1300);
	h->GetXaxis()->SetMoreLogLabels();
	h->GetXaxis()->SetNoExponent();
	h->SetMinimum(0.88);
	h->SetMaximum(1.13);

	writeExtraText = true;
	extraText = (string(ct)=="mc" ? "Simulation" : "");
	lumi_8TeV = (string(ct)=="mc" ? "" : "19.7 fb^{-1}");
	TCanvas *c0 = tdrCanvas(Form("c0_%s_%s",cm,ct), h, 2, 11, true);
	c0->SetLogx();
	

	TLegend *leg = tdrLeg(0.55,0.68,0.85,0.83);
	tex->DrawLatex(0.55,0.85,texlabel[cm]);
	tex->DrawLatex(0.55,0.18,"|#eta| < 1.3, #alpha=0.3");
	//tex->DrawLatex(0.55,0.18,"Anti-k_{T} R=0.5");

	// Loop over Z+jet and gamma+jet (only, no dijet/multijet)
	for (int  isample = 0; isample != min(3,nsamples); ++isample) {
	  
	  const char *cs = samples[isample];
	  TGraphErrors *g = gemap[ct][cm][cs][30]; assert(g);
	  g->Draw("SAME Pz");
	  
	  leg->AddEntry(g,texlabel[cs],"P");
	} // for isample

	if (etamin==0) {
	  c0->SaveAs(Form("pdf/paper_softrad_%s_%s_vspt.pdf",ct,cm));
	  c0->SaveAs(Form("pdfC/paper_softrad_%s_%s_vspt.C",ct,cm));
	}
	else {
	  c0->SaveAs(Form("pdf/an_softrad_%s_%s_eta%1.0f-%1.0f_vspt.pdf",
			  ct,cm,10*etamin,10*etamax));
	}
      } // paper

    } // for imethod
  } // for itype
  
  c1->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c1, 2, 33);
  c1->SaveAs("pdf/softrad_2x6_vspt.pdf");


  cout << "Drawing plots vs alpha for each pT" << endl << flush;
  cout << "...and fitting slope vs alpha" << endl << flush;

  map<string, map<string, map<string, TGraphErrors* > > > gkmap;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      
      int icanvas = nmethods*imethod + itype; assert(icanvas<=6);
      TCanvas *c2 = c2s[icanvas]; assert(c2);

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      const int npads = 9;
      for (int ipad = 0; ipad != npads; ++ipad) {
	c2->cd(ipad+1);
	h2->SetYTitle(Form("Response (%s)",ct));
	h2->DrawClone("AXIS");
	tex->DrawLatex(0.20,0.85,texlabel[cm]);
	tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
	tex->DrawLatex(0.20,0.75,Form("%1.0f < p_{T} < %1.0f GeV",
				      hpt1->GetBinLowEdge(ipad+1),
				      hpt1->GetBinLowEdge(ipad+2)));
	TLegend *leg = tdrLeg(0.65,0.75,0.90,0.90);
	leg->AddEntry(gemap[ct][cm]["gamjet"][30], texlabel["gamjet"], "P");
	leg->AddEntry(gemap[ct][cm]["zeejet"][30], texlabel["zeejet"], "P");
	leg->AddEntry(gemap[ct][cm]["zmmjet"][30], texlabel["zmmjet"], "P");
	leg->AddEntry(gemap[ct][cm]["dijet"][30], texlabel["dijet"], "P");
      }

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];

	map<int, TGraphErrors*> &gam = gamap[ct][cm][cs];
	map<int, TGraphErrors*>::iterator itpt;
	for (itpt = gam.begin(); itpt != gam.end(); ++itpt) {

	  int ipt = itpt->first;
	  int jpt = hpt1->FindBin(ipt);
	  if (jpt>npads) continue;
	  assert(jpt<=npads);
	  c2->cd(jpt);
	  
	  TGraphErrors *ga = itpt->second; assert(ga);
	  
	  ga->Draw("SAME Pz");

	  // Fit slope
	  TF1 *f1 = new TF1(Form("f1_%s_%s_%s_%d",ct,cm,cs,ipt),
			    "(x<1)*([0]+[1]*x) + (x>1 && x<2)*[0] +"
			    "(x>2)*[1]",-1,1);
	  f1->SetLineColor(ga->GetLineColor());
	  f1->SetParameters(1,0);
	  const double minalpha = (isample==0 ? 10./ipt : 5./ipt);
	  // Constrain slope to within reasonable values
	  // in the absence of sufficient data using priors
	  if (true) { // use priors
	    int n = ga->GetN();
	    // For response, limit to 1+/-0.02 (we've corrected for L3Res
	    ga->SetPoint(n, 1.5, 1);
	    ga->SetPointError(n, 0, 0.02);
	    n = ga->GetN();
	    if (imethod==1) { // pT balance
	      // For pT balance, estimate slope of <vecpT2>/alpha from data
	      // => 7.5%/0.30 = 25%
	      // Approximate uncertainty on this to be
	      // 0.5%/0.30 ~ 1.5% for data, 0.5%/0.30 ~ 1.5% for Z+jet MC, and
	      // 2%/0.30 ~ 6% for gamma+jet MC (same as slope)
	      if (itype==0)               ga->SetPoint(n, 2.5, -0.250); // DT
	      if (itype==1 && isample!=0) ga->SetPoint(n, 2.5, -0.250); // MC
	      if (itype==1 && isample==0) ga->SetPoint(n, 2.5, -0.190);
	      if (itype==2 && isample!=0) ga->SetPoint(n, 2.5, -0.000); // rt
	      if (itype==2 && isample==0) ga->SetPoint(n, 2.5, -0.060); 
	      //
	      // BUG: found 2015-01-08 (no effect on ratio)
	      //if (itype==1)               ga->SetPointError(n, 0, -0.015);
	      if (itype==0)               ga->SetPointError(n, 0, -0.015); // DT
	      if (itype==1 && isample!=0) ga->SetPointError(n, 0, -0.015); // MC
	      if (itype==1 && isample==0) ga->SetPointError(n, 0, -0.060);
	      if (itype==2 && isample!=0) ga->SetPointError(n, 0, -0.015); // rt
	      if (itype==2 && isample==0) ga->SetPointError(n, 0, -0.060); 
	    }
	    if (imethod==0) { // MPF
	      // For MPF, expectation is no slope
	      // Maximal slope would be approximately
	      // (<vecpT2>/alpha ~ 25% from pT balance) times
	      // (response difference between pT1 and vecpT2~10%)
	      // => 0.25*0.10 = 2.5%
	      // For data/MC, estimate uncertainty as half of this
	      // => 1.25%
	      ga->SetPoint(n, 2.5, 0.);
	      if (itype!=2) ga->SetPointError(n, 0, 0.025);
	      if (itype==2) ga->SetPointError(n, 0, 0.0125);
	    } // MPF
	  } // use priors

	  if (ga->GetN()>2) {

	    f1->SetRange(minalpha, 3.);
	    ga->Fit(f1,"QRN");

	    if (f1->GetNDF()>=0) {
	      f1->DrawClone("SAME");
	      f1->SetRange(0,0.4);
	      f1->SetLineStyle(kDashed);
	      f1->DrawClone("SAME");

	      // Store results
	      TGraphErrors *gk = gkmap[ct][cm][cs];
	      if (!gk) {
		gk = new TGraphErrors(0);
		gk->SetMarkerStyle(ga->GetMarkerStyle());
		gk->SetMarkerColor(ga->GetMarkerColor());
		gk->SetLineColor(ga->GetLineColor());
		gkmap[ct][cm][cs] = gk;
	      }
	      int n = gk->GetN();
	      TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	      if (isample==3) { ppt = ppt4; } // pas-v6
	      double pt = ppt->GetBinContent(ppt->FindBin(ipt));
	      gk->SetPoint(n, pt, f1->GetParameter(1));
	      gk->SetPointError(n, 0, f1->GetParError(1));
	    } // f1->GetNDF()>=0
	  } // ga->GetN()>2
	} // for itpt
	
      } // for isample
      
      c2->SaveAs(Form("pdf/softrad_3x3_%s_%s_vsalpha.pdf",ct,cm));
      
    }
  }


  cout << "Drawing plots of kFSR vs pT" << endl;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      TMultiGraph *mgk = new TMultiGraph();

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c3->cd(ipad);
      gPad->SetLogx();
      h3->SetMaximum(imethod==0 ? 0.05 : (itype!=2 ? 0.1 : 0.25));
      h3->SetMinimum(imethod==0 ? -0.05 : (itype!=2 ? -0.4 : -0.25));
      h3->SetYTitle(Form("k_{FSR} = dR/d#alpha (%s)",ct));
      h3->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];
	TGraphErrors *gk = gkmap[ct][cm][cs]; assert(gk);
	
	leg->AddEntry(gk,texlabel[cs],"P");

	// Fit each sample separately for pT balance
	if (true) {

	  TF1 *fk = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			    "[0]+[1]*log(0.01*x)+[2]*pow(log(0.01*x),2)",
			    30,1300);
	  fk->SetParameters(-0.25,-0.5);
	  fk->SetLineColor(gk->GetLineColor());
	  gk->Fit(fk, "QRN");

	  tex->SetTextColor(fk->GetLineColor());
	  tex->DrawLatex(0.55,0.27-0.045*isample,
			 Form("#chi^{2}/NDF = %1.1f / %d",
			      fk->GetChisquare(), fk->GetNDF()));
	  tex->SetTextColor(kBlack);

	  // Error band
	  const int n = fk->GetNpar();
	  TMatrixD emat(n,n);
	  gMinuit->mnemat(emat.GetMatrixArray(), n);
	  TF1 *fke = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			     sr_fitError, 30, 1300, 1);
	  _sr_fitError_func = fk;
	  _sr_fitError_emat = &emat;

	  fke->SetLineStyle(kSolid);
	  fke->SetLineColor(fk->GetLineColor()-10);
	  fke->SetParameter(0,-1);
	  fke->DrawClone("SAME");
	  fke->SetParameter(0,+1);
	  fke->DrawClone("SAME");

	  fk->DrawClone("SAME");
	  gk->DrawClone("SAME Pz");

	  // Store soft radiation corrections in fsr subdirectory
	  assert(fin->cd(ct));
	  assert(gDirectory->cd(bin));
	  if (!gDirectory->FindObject("fsr")) gDirectory->mkdir("fsr");
	  assert(gDirectory->cd("fsr"));

	  TH1D *hk = (TH1D*)(isample==0 ? hpt2->Clone() : hpt1->Clone());
	  hk->SetName(Form("hkfsr_%s_%s",cm,cs));
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { ppt = ppt4; } // pas-v6
	  for (int i = 1; i != hk->GetNbinsX()+1; ++i) {
	    double pt = ppt->GetBinContent(i);
	    if (pt>30 && pt<1300) {
	      hk->SetBinContent(i, fk->Eval(pt));
	      hk->SetBinError(i, fabs(fke->Eval(pt)-fk->Eval(pt)));
	    }
	    else {
	      hk->SetBinContent(i, 0);
	      hk->SetBinError(i, 0);
	    }
	  }
	  
	  hk->Write(hk->GetName(), TObject::kOverwrite);

	  // Factorize error matrix into eigenvectors
	  // Remember: A = Q*Lambda*Q^-1, where
	  // A is emat, Q is eigmat, and Lambda is a diagonal matrix with
	  // eigenvalues from eigvec on the diagonal. For eigenmatrix
	  // Q^-1 = Q^T, i.e. inverse matrix is the original transposed
	  TVectorD eigvec(n);
	  TMatrixD eigmat = emat.EigenVectors(eigvec);

	  // Eigenvectors are the columns and sum of eigenvectors squared
	  // equals original uncertainty. Calculate histograms from the
	  // eigenvectors and store them
	  TF1 *fkeig = (TF1*)fk->Clone(Form("%s_eig",fk->GetName()));
	  fkeig->SetLineStyle(kDotted);
	  for (int ieig = 0; ieig != n; ++ieig) {

	    // Eigenvector functions
	    for (int i = 0; i != n; ++i) {
	      fkeig->SetParameter(i, fk->GetParameter(i)
				  + eigmat[i][ieig] * sqrt(eigvec[ieig]));
	    }
	    fkeig->DrawClone("SAMEL");

	    // Eigenvector histograms evaluated at bin mean pT
	    TH1D *hke = (TH1D*)hk->Clone(Form("%s_eig%d",hk->GetName(),ieig));
	    hke->Reset();

	    for (int i = 0; i != gk->GetN(); ++i) {

	      double pt = gk->GetX()[i];
	      int ipt = hke->FindBin(pt);
	      // Need to store central value as well, because
	      // uncertainty sources are signed
	      hke->SetBinContent(ipt, fkeig->Eval(pt)-fk->Eval(pt));
	      hke->SetBinError(ipt, fabs(fkeig->Eval(pt)-fk->Eval(pt)));
	    }
	    hke->Write(hke->GetName(), TObject::kOverwrite);
	  }

	  cout << "." << flush;
	} // if tree
      } // for isample
    } // for imethod
  } // for itype
  
  c3->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c3, 2, 33);
  c3->SaveAs("pdf/softrad_2x6_kfsr.pdf");

  fin->Close();
  curdir->cd();
} // softrad
Esempio n. 10
0
void MakePi0Analysis(){

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

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

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

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

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

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


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

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

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

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

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

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

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

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