void plotMttResolution() {

  setTDRStyle();

  TCanvas *c = new TCanvas("c", "c", 800, 800);

  TH1F *mtt = (TH1F*) _file0->Get("mtt_resolution_mva");
  mtt->SetTitle("");
  mtt->SetName("m_{t#bar{t}}");
  mtt->GetXaxis()->SetTitle("m_{t#bar{t}} - m_{t#bar{t}}^{gen} (GeV)");
  mtt->SetLineColor(TColor::GetColor("#542437"));
  mtt->SetLineColor(TColor::GetColor("#8A9B0F"));
  mtt->SetLineColor(TColor::GetColor("#C02942"));
  mtt->SetFillColor(mtt->GetLineColor());
  mtt->SetFillStyle(3004);
  mtt->GetXaxis()->SetTitleOffset(1.2);

  TF1 *voigt = new TF1("voigt", "gaus", -100, 100);
	voigt->SetParName(0, "amp");
	voigt->SetParName(2, "mean");
	voigt->SetParName(1, "sigma");

  voigt->SetParameter(0, mtt->GetMaximum());
	voigt->SetParameter(2, 0);
	voigt->SetParameter(1, 100);

  mtt->Fit(voigt, "RVN");

  voigt->SetLineColor(TColor::GetColor("#8A9B0F"));
  voigt->SetLineWidth(2);

  mtt->Draw();
  voigt->Draw("same");

  TLatex* latex = new TLatex();
  latex->SetTextFont(42);
  latex->SetTextSize(0.033);
  latex->DrawLatexNDC(0.25, 0.84, TString::Format("mean = %.2f", voigt->GetParameter(1)));
  latex->DrawLatexNDC(0.25, 0.8, TString::Format("#sigma = %.2f", voigt->GetParameter(2)));

  gPad->Modified();
  gPad->Update();

  c->Print("mtt_resolution.pdf");
}
Exemple #2
0
void GetRandomTest(){
	double k0=1.39;
	double k1 = 0.425;
	double theta0 = 3.41;
	double theta1 = 1.30;
	int iNpart=2;
	double k_=k0+k1*(iNpart-2);
        double theta_=theta0+theta1*TMath::Log(iNpart-1);
	TF1 *f = new TF1("f","TMath::GammaDist(x,[0],0,[1])",0,200);
	f->SetParameters(k1,theta_);
	cout<<"Value at 0 = "<<f->Eval(0)<<endl;
	cout<<"Value at 1e-11 = "<<f->Eval(1e-11)<<endl;
	cout<<"Integral 1= "<<f->Integral(f->GetXmin(),f->GetXmax())<<endl;
	f->SetRange(1e-12,200);
	cout<<"Integral 2= "<<f->Integral(f->GetXmin(),f->GetXmax())<<endl;
	cout<<"fXmin = "<<f->GetXmin()<<"\tfXmax = "<<f->GetXmax()<<"\tfNpx = "<<f->GetNpx()<<endl;
	f->SetNpx(1e5);
	TCanvas *c1 = new TCanvas();
	c1->SetLogy();
	cout<<"f mean = "<<f->Mean(0,200)<<endl;
	cout<<"math mean = "<<f->GetParameter(0)*f->GetParameter(1)<<endl;
	TH1D* h = new TH1D("h","h",1000,0,200);
	for(int i=0;i<1e6;i++){
		double para = f->GetRandom();
		h->Fill(para);
	}
	h->Scale(1.0/h->Integral()*1000/200);
	h->GetYaxis()->SetRangeUser(1e-10,1);
	h->SetMarkerStyle(24);
	h->SetMarkerColor(4);
	h->SetMarkerSize(1.1);
	TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
        leg->SetFillColor(0);
        leg->SetFillStyle(0);
        leg->SetBorderSize(0);
        leg->SetTextFont(42);
        leg->SetTextSize(0.03);
        leg->AddEntry(f,"function","lp");
        leg->AddEntry(h,"filled histogram","lp");
	h->Draw("P");
	f->Draw("same");
        leg->Draw("same");
	cout<<"h mean = "<<h->GetMean(1)<<endl;
	c1->Print("TestGetRandom.png");
	}
Exemple #3
0
void plotter::draw_chi2(TF1 * fit_, std::vector<double> masses_, std::vector<double> chi2_, double mass, double uncert, TString file_name){
  TF1 * fit = (TF1*)fit_->Clone("fit");
  TVectorD masses(masses_.size());
  TVectorD chi2(chi2_.size());
  for(int i=0; i<masses_.size(); i++) masses[i] = masses_[i];
  for(int i=0; i<chi2_.size(); i++) chi2[i] = chi2_[i];

  TGraph* chi_hist = new TGraph(masses,chi2);
  TCanvas *c = new TCanvas("Chi2", "", 600, 600);
  gPad->SetLeftMargin(0.15);
  TGaxis::SetMaxDigits(3);
  chi_hist->SetTitle(" ");
  chi_hist->GetXaxis()->SetTitle("m_{top}^{MC} [GeV]");
  chi_hist->GetYaxis()->SetTitle("#chi^{2}");
  chi_hist->GetYaxis()->SetTitleOffset(1.1);
  chi_hist->GetXaxis()->SetTitleOffset(0.9);
  chi_hist->GetYaxis()->SetTitleSize(0.05);
  chi_hist->GetXaxis()->SetTitleSize(0.05);
  chi_hist->GetXaxis()->SetNdivisions(505);
  chi_hist->GetYaxis()->SetNdivisions(505);
  chi_hist->SetMarkerStyle(20);
  chi_hist->SetMarkerSize(1.5);
  chi_hist->SetLineColor(1);
  chi_hist->Draw("AP");
  fit->Draw("SAME");

  // write extracted mass value into plot
  TLatex text;
  text.SetNDC(kTRUE);
  text.SetTextFont(43);
  text.SetTextSize(18);
  char mass_text[32];
  sprintf(mass_text, "%.5g", mass);
  char uncert_text[32];
  if(uncert < 1) sprintf(uncert_text, "%.3g", uncert);
  else           sprintf(uncert_text, "%.4g", uncert);
  TString masstext = "m_{top}^{MC} = ";
  masstext += mass_text;
  masstext += " #pm ";
  masstext += uncert_text;
  text.DrawLatex(.4,.6, masstext);
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
  return;
}
Exemple #4
0
void quick() {

  //setTDRStyle();

  TCanvas *canv = MakeCanvas("canv", "histograms", 800, 600);
  canv->cd();

  double eff_points[10] = { 0.55, 0.57, 0.59, 0.61, 0.63, 0.65, 0.67, 0.69, 0.71, 0.73 };
  double eff_points_2[10] = { 0.55, 0.57, 0.59, 0.61, 0.63, 0.65, 0.67, 0.69, 0.71, 0.73 };

  double sig_up[10] = { 1.22484, 1.20737, 1.19085, 1.17521, 1.16035, 1.14622, 1.13276, 1.11993, 1.10767, 1.09593 };


  TF1 *fxn = new TF1("fxn", "[0]*TMath::Sqrt([1]*x+[2])/([3]*x+[4])", 0.4, 0.9);
  fxn->SetParameter(0,114.622/10.7759);
  fxn->SetParameter(1,11548);
  fxn->SetParameter(2,658);
  fxn->SetParameter(3,12.9);
  fxn->SetParameter(4,0);

  for (Int_t i=0; i<10; i++) {
    sig_up[i]*=100;
    eff_points_2[i]/=0.65;
  }

  TGraph *gr = new TGraph(10, eff_points, sig_up);
  //TGraphAsymmErrors gr2(10, eff_points, sig_cent, 0, 0, sig_down, sig_up);

  gr->SetLineColor(kRed);
  //gr->SetLineWidth(2);
  fxn->SetLineColor(kBlue);
  //fxn->SetLineWidth(2);
  //gr2->SetFillColor(kGreen);

  gr->GetXaxis()->SetTitle("Hadronic #tau Efficiency");
  gr->GetYaxis()->SetTitle("Uncertainty on #sigma_{HH}");
  gr->Draw("alp");


  cout << fxn->Eval(0.65) << endl;

  fxn->Draw("same R");


}
Exemple #5
0
void v()
{

    TF1 *signal = new TF1("DGauss", DGauss, 0, 800, 7);
    signal->SetParameter(0, 50);
    signal->SetParameter(1, 1);
    signal->SetParameter(2, 2);
    signal->SetParameter(3, 100);
    signal->SetParameter(4, -20);

    signal->SetParameter(5, 22.374);
    signal->SetParameter(6, 5.55);
    signal->SetNpx(10000);


    signal->Draw();

}
Exemple #6
0
void langaus() {
   // Fill Histogram
   Int_t data[100] = {0,0,0,0,0,0,2,6,11,18,18,55,90,141,255,323,454,563,681,
                    737,821,796,832,720,637,558,519,460,357,291,279,241,212,
                    153,164,139,106,95,91,76,80,80,59,58,51,30,49,23,35,28,23,
                    22,27,27,24,20,16,17,14,20,12,12,13,10,17,7,6,12,6,12,4,
                    9,9,10,3,4,5,2,4,1,5,5,1,7,1,6,3,3,3,4,5,4,4,2,2,7,2,4};
   TH1F *hSNR = new TH1F("snr","Signal-to-noise",400,0,400);

   for (Int_t i=0; i<100; i++) hSNR->Fill(i,data[i]);

   // Fitting SNR histo
   printf("Fitting...\n");

   // Setting fit range and start values
   Double_t fr[2];
   Double_t sv[4], pllo[4], plhi[4], fp[4], fpe[4];
   fr[0]=0.3*hSNR->GetMean();
   fr[1]=3.0*hSNR->GetMean();

   pllo[0]=0.5; pllo[1]=5.0; pllo[2]=1.0; pllo[3]=0.4;
   plhi[0]=5.0; plhi[1]=50.0; plhi[2]=1000000.0; plhi[3]=5.0;
   sv[0]=1.8; sv[1]=20.0; sv[2]=50000.0; sv[3]=3.0;

   Double_t chisqr;
   Int_t    ndf;
   TF1 *fitsnr = langaufit(hSNR,fr,sv,pllo,plhi,fp,fpe,&chisqr,&ndf);

   Double_t SNRPeak, SNRFWHM;
   langaupro(fp,SNRPeak,SNRFWHM);

   printf("Fitting done\nPlotting results...\n");

   // Global style settings
   gStyle->SetOptStat(1111);
   gStyle->SetOptFit(111);
   gStyle->SetLabelSize(0.03,"x");
   gStyle->SetLabelSize(0.03,"y");

   hSNR->GetXaxis()->SetRange(0,70);
   hSNR->Draw();
   fitsnr->Draw("lsame");
}
Exemple #7
0
void ShowErrorRange(TGraphErrors* graph)
{
  // de = 0
  TF1 *fcon = new TF1("fcon","0",0.99,1.01);
  fcon->SetLineColor(3);
  
  // fit function
  TF1 *fit = graph->GetFunction("facfit");
  double fac = fit->GetParameter(0);
  double slo = fit->GetParameter(1);
  double de = graph->GetErrorY(graph->GetN()/2);
  
  // construct edge functions
  TF1 *f2 = new TF1("f2","[1]*(x-[0])",0.99,1.01);
  TF1 *f3 = new TF1("f3","[1]*(x-[0])",0.99,1.01);
  f2->SetParameters(fac-de/slo,slo);
  f3->SetParameters(fac+de/slo,slo);
  
  f2->SetLineStyle(2);
  f3->SetLineStyle(2);

  double fmin = f2->GetX(0);
  double fmax = f3->GetX(0);
  TArrow *arr0 = new TArrow(fac ,-0.002,fac ,0);
  TArrow *arr1 = new TArrow(fmin,-0.002,fmin,0);
  TArrow *arr2 = new TArrow(fmax,-0.002,fmax,0);
  arr0->SetArrowSize(0.035);
  arr1->SetArrowSize(0.035);
  arr2->SetArrowSize(0.035);
  arr0->SetLineWidth(2);
  arr1->SetLineWidth(2);
  arr2->SetLineWidth(2);

  graph->Draw();
  f2->Draw("same");
  f3->Draw("same");
  fcon->Draw("same");
  
  arr0->Draw();
  arr1->Draw();
  arr2->Draw();
}
Exemple #8
0
void bichdX() {
  if (gClassTable->GetID("StBichsel") < 0) {
//     gSystem->Load("libStar");
//     gSystem->Load("St_base");
//     gSystem->Load("StarClassLibrary");
    gSystem->Load("StBichsel");
  }
  if (!m_Bichsel) m_Bichsel = Bichsel::Instance();
  TCanvas *c1 = new TCanvas("c1");
  c1->SetLogx();
  c1->SetLogy();
  //  TH1F *hr = c1->DrawFrame(2.e-2,1,1.e3,1.e2);
  //  TH1F *hr = c1->DrawFrame(1.e-2,1,1.e3,1.e2);
  TH1F *hr = c1->DrawFrame(1.e-1,1,1.e4,2.e2);
  //  hr->SetXTitle("Momentum (GeV/c)");
  hr->SetTitle("dE/dx Bichsel predictions for different dX");
  hr->SetXTitle("#beta#gamma                             ");
  hr->SetYTitle("dE/dx (keV/cm)");  
  //                     Mass Type Length  log2(dx)
  Double_t params[4] = {  1.0,  0.,   60., 1.};  
  TLegend *leg = new TLegend(0.72,0.7,0.9,0.9,"");//TLegend(0.79,0.91,0.89,0.89,"");
  Int_t h = 0;
  //  for (Int_t f = 0; f< NF; f++) {
  for (Int_t f = 5; f <= 5; f++) {
    Int_t icol = 2;
    for (Int_t dx = 0; dx < Nlog10dx; dx++) { 
      params[3] = log10dx[dx];
      Char_t *FunName = Form("%s%s%i",FNames[f],Names[h],dx);
      TF1 *func = func = new TF1(FunName,Rbichsel70,1.e-1,1.e4,4);
      if (! func) continue;
      func->SetLineColor(icol);
      //      func->SetLineStyle(f+1);
      icol++;
      if (icol == 5) icol++;
      func->SetParameters(params); 
      func->Draw("same");
      leg->AddEntry(func,Form("%s dX = %4.1f (cm)",FNames[f],TMath::Power(2.,params[3])),"L");
    }
  }
  leg->Draw();
}
Exemple #9
0
void plotter::draw_smearFit(TH1D* variation, TF1* fit_, TString file_name){
  TH1D* var = (TH1D*) variation->Clone();
  TF1* fit = (TF1*) fit_->Clone();
  TCanvas *c= new TCanvas("","",600,600);
  gPad->SetLeftMargin(0.15);
  double ymax = var->GetMaximum() * 1.5;
  var->GetYaxis()->SetRangeUser(0., ymax);
  var->GetXaxis()->SetTitle("bin content");
  var->GetYaxis()->SetTitle("events");
  var->GetYaxis()->SetTitleOffset(1.5);
  var->GetYaxis()->SetNdivisions(505);
  var->SetFillColor(kGray);
  var->SetLineColor(kBlack);
  var->Draw("HIST");
  fit->SetLineColor(kRed);
  fit->SetLineWidth(4);
  fit->Draw("SAME");
  gPad->RedrawAxis();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Exemple #10
0
// This is the main program
void slits() {
  float r,ns;

  // request user input
  cout << "slit width / g ? ";
  scanf("%f",&r);
  cout << "# of slits? ";
  scanf("%f",&ns);
  cout <<"interference pattern for "<< ns
       <<" slits, width/distance: "<<r<<endl;

  // define function and set options
  TF1 *Fnslit  = new TF1("Fnslit",nslit,-5.001,5.,2);
  Fnslit->SetNpx(500);
    
  // set parameters, as read in above
  Fnslit->SetParameter(0,r);
  Fnslit->SetParameter(1,ns);
    
  // draw the interference pattern for a grid with n slits
  Fnslit->Draw();
}
void angle_correlation_daughter_particles(){

	TStopwatch timer;

	TString inPath ="";// "/home/ikp1/puetz/panda/mysimulations/test/boxgenerator/lambda0/10000_events/";

	TFile * inFile = new TFile(inPath + "output_ana.root", "READ");
	TTree * lambda0 = (TTree*) inFile->Get("fntpLambda0");

	gStyle->SetOptStat(0);

	TF1 * f = new TF1("f", "x", -1, 1);


	TH2D * h_cos_tht = new TH2D("h_cos_tht", "Correlation for tht of daughters; cos(tht_{d0});cos(tht_{d1})", 1000,-1,1, 1000,-1,1);
	lambda0->Project("h_cos_tht", "cos(Lambda0_d1tht):cos(Lambda0_d0tht)", "McTruthMatch==1");

	TH1D * h_tht = new TH1D("h_tht", "Correlation for tht of daughters; tht_{d0}-tht_{d1}/rad; counts", 100,-2,2);
	lambda0->Project("h_tht", "cos(Lambda0_d1tht)-cos(Lambda0_d0tht)", "McTruthMatch==1 && abs(Lambda0_d1phi-Lambda0_d0phi)<0.002");


	TH1D * h_phi = new TH1D("h_phi", "Correlation for phi of daughters; phi_{d0}-phi_{d1}/rad; counts", 100,-0.1,0.1);
	lambda0->Project("h_phi", "Lambda0_d1phi-Lambda0_d0phi", "McTruthMatch==1 && abs(Lambda0_d1phi-Lambda0_d0phi)<0.002");

	TCanvas * c_cos_tht = new TCanvas("c_cos_tht", "c_cos_tht", 0,0,800,500);
	h_cos_tht->Draw("COLZ");
	f->Draw("SAME");

	TCanvas * c_tht = new TCanvas("c_tht", "c_tht", 0,0,800,500);

	h_tht->Draw();



	TCanvas * c_phi = new TCanvas("c_phi", "c_phi", 0,0,800,500);

	h_phi->Draw();

}
Exemple #12
0
void plotMVALeadVsLeadCharg(){

  TFile* f_Ztautau = new TFile("../");
  f_Ztautau->cd();
  TTree* tree_Ztautau = (TTree*) gDirectory->Get("tauFakeRateAnalyzerHPS/tree"); 
  TH2F* h2 = new TH2F("h2","",220,0,1.1,220,0,1.1);

  float vxF[45];
  float vyF[45];

  float ZtautauAll = (float)tree_Ztautau->GetEntries("");

  for(int i = 0; i<=44; i++){
    float cut = 0.025*i;
    float ZtautauCutLeadPi    = (float) tree_Ztautau->GetEntries(Form("leadPFCandMva<=%f",-0.1+cut));
    float ZtautauCutLeadCh    = (float) tree_Ztautau->GetEntries(Form("leadPFChargedHadrMva<=%f",-0.1+cut));
    vxF[i]=ZtautauCutLeadCh/ZtautauAll;
    vyF[i]=ZtautauCutLeadPi/ZtautauAll;
  }

  h2->SetXTitle("efficiency of mva<X cut on lead charged");
  h2->SetYTitle("efficiency of mva<X cut on lead candidate");
  h2->SetAxisRange(0.95,1.02,"X");
  h2->SetAxisRange(0.95,1.02,"Y");
  
  h2->Draw();

  TVectorF vx(45,vxF);
  TVectorF vy(45,vyF);
  TGraph* graph = new TGraph(vx,vy);
  graph->SetMarkerStyle(kFullCircle);
  graph->SetMarkerColor(kRed);  
  graph->SetMarkerSize(1.0);
  graph->Draw("P");

  TF1* line = new TF1("line","x",0.9,1.2);
  line->Draw("SAME");

}
void langaus() {
  // Fill Histogram
  
  TFile *f=new TFile("fitInputs.root");
  TH1F *hSNR = (TH1F*)f->Get("hxsobs");

  // Fitting SNR histo
  printf("Fitting...\n");

  // Setting fit range and start values
  Double_t fr[2];
  Double_t sv[4], pllo[4], plhi[4], fp[4], fpe[4];
  fr[0]=0.3*hSNR->GetMean();
  fr[1]=3.0*hSNR->GetMean();

  pllo[0]=0.5; pllo[1]=5.0; pllo[2]=1.0; pllo[3]=0.4;
  plhi[0]=5.0; plhi[1]=50.0; plhi[2]=1000000.0; plhi[3]=5.0;
  sv[0]=1.8; sv[1]=20.0; sv[2]=50000.0; sv[3]=3.0;

  Double_t chisqr;
  Int_t    ndf;
  TF1 *fitsnr = langaufit(hSNR,fr,sv,pllo,plhi,fp,fpe,&chisqr,&ndf);
   
  Double_t SNRPeak, SNRFWHM;
  langaupro(fp,SNRPeak,SNRFWHM);

  printf("Fitting done\nPlotting results...\n");

  // Global style settings
  gStyle->SetOptStat(1111);
  gStyle->SetOptFit(111);
  gStyle->SetLabelSize(0.03,"x");
  gStyle->SetLabelSize(0.03,"y");

  hSNR->GetXaxis()->SetRange(0,70);
  hSNR->Draw();
  fitsnr->Draw("lsame");
}
Exemple #14
0
//______________________________________________________________________________
void Fit(TH1* h, Double_t* outPos, Double_t* outFWHM)
{
    // Perform fit.
    
    Char_t tmp[256];

    // delete old function
    TF1* func = new TF1(tmp, "pol1+gaus(2)");
    func->SetLineColor(2);
    
    // estimate peak position
    Double_t fPi0Pos = h->GetBinCenter(h->GetMaximumBin());

    // configure fitting function
    func->SetRange(fPi0Pos - 0.8, fPi0Pos + 0.8);
    func->SetLineColor(2);
    func->SetParameters( 0.1, 0.1, h->GetMaximum(), 0, 0.1);
    Int_t fitres = h->Fit(func, "RB0Q");
    
    // get position and FWHM
    fPi0Pos = func->GetParameter(3);
    *outPos = fPi0Pos;
    *outFWHM = 2.35*func->GetParameter(4);

    // indicator line
    TLine* line = new TLine();
    line->SetX1(fPi0Pos);
    line->SetX2(fPi0Pos);
    line->SetY1(0);
    line->SetY2(h->GetMaximum());

    // draw 
    h->GetXaxis()->SetRangeUser(-3, 3);
    h->Draw();
    func->Draw("same");
    line->Draw("same");
}
void test_mc_rejection_method_lin()
{
  const int    N     = 500000;
  const int    nbins = 300;
  const double ymax  = 1.1;
  const double xmin  = 0;
  const double xmax  = 10;
  const double dx    = xmax-xmin;

  TRandom rg;

  TF1 *  func = new TF1  ("func","1/(x+1)",0,10);
  TH1D * hgen = new TH1D ("hgen","generated",nbins,xmin,xmax);

  for(int i=0; i<N; i++) {
     cout << "..................." << i << endl;
     bool selected=false;
     while(1) {
       double xg = xmin + rg.Uniform() * dx;
       double yg = ymax * rg.Uniform();
       double yc = func->Eval(xg);
       selected = (yg<yc);
       if(selected) {
           hgen->Fill(xg);
           break;
       }
     }
  }

  double IF = func->Integral(xmin,xmax);
  double IH = hgen->Integral("width");
  double sc = IF/IH;
  hgen->Scale(sc);

  hgen->Draw();
  func->Draw("same");
}
Exemple #16
0
void doit(const char *basename, const int nbins, const double lofit, const double hifit)
{

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

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

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

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

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

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


  double bgscale = 650; // guess...





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

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


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

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

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




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

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



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


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

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

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

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

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

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

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

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

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



}
void fitGausExample()
{
	int bins = 100;
	int min = 0;
	int max = 1600;
	sigMin = 500;
	sigMax = 800;
	double bgMin = 100;
	double bgMax = 1300;
	double xpos;
	
	TCanvas *testCanvas = new TCanvas("testCanvas","testCanvas",600,400); //x,y
	pad1  =  new  TPad("pad1","pad1",0.0000,0.0000,1.0000,1.0000,0,0,0);
	pad1->Draw();

	pad1->cd();
	TH1F *h1 = new TH1F("h1","Fitting Example",bins,min,max);	
	TH1F *h2 = new TH1F("h2","h2",bins,min,max);	
	TH1F *h3 = new TH1F("h3","Fitting Example",bins,min,max);	
	TH1F *bg = new TH1F("bg","bg",bins,min,max);	

	// The section below will fill h1 with a guassian
	// function with a mean of 670 and a sigma of 20
	// and fill h2 with a "uniform" random background
	// from bgMin<x<bgMax
	for (int i=0; i<10000000; i++)
	{
//		h1->Fill(gRandom->Uniform(10,1400));
		h1->Fill(gRandom->Uniform(0,1600));
		h1->Fill(gRandom->Exp(1400));
	}
	for (int i=0; i<100000; i++)
	{
//		h1->Fill(gRandom->Uniform(1400,1500));
	}
	for (int i=0; i<50000; i++)
	{
		h1->Fill(gRandom->Gaus(670,20));
	}
	for (int i=0; i<bins; i++)
	{
//		xpos = i*((max-min)/bins)+min;
//		cout << "xpos: " << xpos << endl;
//		h1->Fill(xpos,100*exp((-1)*xpos));
//		h2->Fill(i*((max-min)/bins)+min,i*500);
	}



//	h1->Add(h2,-1);
	h1->SetMinimum(0);
	h1->SetMaximum(300000);
	h1->Draw();

	TF1 *bgFit = new TF1("bgFit","[0]+[1]*x",bgMin,bgMax);
//	TF1 *bgFit = new TF1("bgFit","expo",bgMin,bgMax);
//	TF1 *bgFit = new TF1("bgFit","exp([1]*x+[0])+[2]",bgMin,bgMax);
	TF1 *bgFit = new TF1("bgFit",fline,bgMin,sigMin,3);
	bgFit->SetLineColor(kOrange);
	bgFit->SetParameter(0,1);
	bgFit->SetParameter(1,1/1600);
	bgFit->SetParameter(2,1);
	bgFit->SetParName(0,"Offset");
	bgFit->SetParName(1,"Tau");
	bgFit->SetParName(2,"Background");
	reject = kTRUE;
	h1->Fit(bgFit,"R");
	reject = kFALSE;
	TF1 *fleft = new TF1("fleft",fline,bgMin,sigMin,3);
	fleft->SetLineColor(kOrange);
	fleft->SetParameters(bgFit->GetParameters());
	h1->GetListOfFunctions()->Add(fleft);
	gROOT->GetListOfFunctions()->Remove(fleft);
	TF1 *fright = new TF1("fright",fline,sigMax,bgMax,3);
	fright->SetLineColor(kOrange);
	fright->SetParameters(bgFit->GetParameters());
	h1->GetListOfFunctions()->Add(fright);
	gROOT->GetListOfFunctions()->Remove(fright);
//	h1->SetMaximum(300000);
	h1->Draw();

	double fitOffset = bgFit->GetParameter(0);
	double fitTau = bgFit->GetParameter(1);
//	double fitBackground = bgFit->GetParameter(2);
	double fitOffsetErr = bgFit->GetParError(0);
	double fitTauErr = bgFit->GetParError(1);
//	double fitBackgroundErr = bgFit->GetParError(2);

	cout << "Number of Bins: " << h1->GetSize()-2 << endl;;
	cout << "fitOffset: " << fitOffset << endl;;
	cout << "fitTau: " << fitTau << endl;;
	for (int i=0; i<(h1->GetSize()-2); i++)
	{
		xpos = i*((max-min)/bins)+min;
//		h2->Fill(xpos,i*500);
		bg->Fill(xpos,(fitOffset + fitTau*xpos));
//		bg->Fill(xpos,(exp(fitTau*xpos + fitOffset) + fitBackground));
	}
	bg->SetLineColor(kBlue);
	bg->Draw("same");

	h3->Add(h1);
	h3->Add(bg,-1);
	h3->SetLineColor(kRed);
	h3->SetMinimum(0);
	h3->Draw("same");


	cout << "sigMin: " << sigMin << ", sigMax: " << sigMax << endl;
	TF1 *sigFit = new TF1("sigFit","gaus",sigMin,sigMax);
	sigFit->SetLineColor(kBlue);
	sigFit->SetParameter(0,1000);
	sigFit->SetParameter(1,690);
	sigFit->SetParameter(2,20);
	sigFit->SetParameter(3,1);
	sigFit->SetParName(0,"Weight");
	sigFit->SetParName(1,"Mean");
	sigFit->SetParName(2,"Sigma");
//	sigFit->SetParName(3,"Background");
	h3->SetMaximum(300000);
	h3->Fit(sigFit,"R");
	sigFit->Draw("same");	
	

	double fitWeight = sigFit->GetParameter(0);
	double fitMean = sigFit->GetParameter(1);
	double fitSigma = sigFit->GetParameter(2);
	double fitWeightErr = sigFit->GetParError(0);
	double fitMeanErr = sigFit->GetParError(1);
	double fitSigmaErr = sigFit->GetParError(2);
	fitResults = new TPaveText(0.11,0.70,0.4,0.89,"NDC");
	TString WeightStr = "Weight = ";
	WeightStr += fitWeight;
	WeightStr += " ± ";
	WeightStr += fitWeightErr;
	TString MeanStr = "Mean = ";
	MeanStr += fitMean;
	MeanStr += " ± ";
	MeanStr += fitMeanErr;  
	TString SigmaStr = "Sigma = ";
	SigmaStr += sqrt(fitSigma*fitSigma);
	SigmaStr += " ± ";
	SigmaStr += fitSigmaErr; 
	TString OffsetStr = "Offset = ";
	OffsetStr += fitOffset;
	OffsetStr += " ± ";
	OffsetStr += fitOffsetErr; 
	TString TauStr = "Tau = ";
	TauStr += fitTau;
	TauStr += " ± ";
	TauStr += fitTauErr; 
	TString BackgroundStr = "BackgroundConst = ";
	BackgroundStr += fitBackground;
	BackgroundStr += " ± ";
	BackgroundStr += fitBackgroundErr; 
	TText *t1 = fitResults->AddText(WeightStr);
	TText *t2 = fitResults->AddText(MeanStr);
	TText *t3 = fitResults->AddText(SigmaStr);
	TText *t4 = fitResults->AddText(BackgroundStr);
	TText *t5 = fitResults->AddText(TauStr);
	TText *t6 = fitResults->AddText(OffsetStr);

	h1->Draw("same");
	TString theFitStr = "(";
	theFitStr += fitWeight;
	theFitStr += "*exp(-0.5*((x-";
	theFitStr += fitMean;
	theFitStr += ")/";
	theFitStr += fitSigma;
	theFitStr += ")^2))+";
	theFitStr += fitBackground;
	theFitStr += "+exp(";
	theFitStr += fitTau;
	theFitStr += "*x+";
	theFitStr += fitOffset;
	theFitStr += ")";
	TF1 *theFit = new TF1("theFit",theFitStr,bgMin,bgMax);
	theFit->SetLineColor(kMagenta);
	theFit->Draw("same");

        double integralOfPeak;
        integralOfPeak = sigFit->Integral((fitMean - 3*sqrt(fitSigma*fitSigma)),(fitMean + 3*sqrt(fitSigma*fitSigma)));
        TString peakInt = "Integral of Peak: ";
        peakInt +=  integralOfPeak;
        cout << peakInt << endl;
        TText *t7 = fitResults->AddText(peakInt);

	pad1->Update();

	TString outputPlotsHere = "/home/ellie/physics/e05-102/analysis-scripts/devel/test_stuff/";
        TString testOutTitle = outputPlotsHere;
        testOutTitle += "test_out_step_1";
	testOutTitle += ".svg";


	fitResults->Draw("same");

}
void long_Ay_nu_05() {
  gROOT->SetStyle("HALLA");
  TCanvas *cn = new TCanvas("cn","cn",540,360);
  cn->Draw();
  cn->UseCurrentStyle();
  TH1F *frm = new TH1F("frm","",100,0.,10.);
  frm->GetXaxis()->SetTitle("#nu (GeV)");
  frm->GetYaxis()->SetTitle("Ay for Q2=0.456 (GeV/c)2");
  frm->SetMinimum(0);
//  frm->SetMinimum(0);
//  frm->SetMaximum(1.0);
  frm->SetMaximum(0.35);
  frm->UseCurrentStyle();
  frm->Draw();
  frm->SetAxisRange(0.120,0.350,"X");
//  frm->SetAxisRange(0.5,1.1,"X");

//  TF1* galster = new TF1("galster","x/(4.*0.938*.938)*1.91/(1.+x/.71)^2/(1.+5.6*x/(4.*.938*.938))",0.,4.);
//  galster->SetLineColor(6);
//  galster->SetLineStyle(3);
//  galster->SetLineWidth(2);


  TF1 *genf = new TF1("genf",genff,1.,10.,1);
  genf->SetLineColor(2);
  genf->SetLineStyle(2);
  genf->SetParameter(0,1.);
  // match to Madey point just below 1.5
  // genf->SetParameter(0,.0411/genf->Eval(1.45));
  genf->SetParameter(0,-0.558645);

//  TF1 *bbba05 = new TF1("BBBA05",gen_bbba05,0.,10.,0);
//  bbba05->SetLineColor(7);
//  bbba05->SetLineStyle(3);

  
  TMultiGraph* mgrDta = new TMultiGraph("Data","G_{E}^{n}");
  TLegend *legDta = new TLegend(.54,.6,.875,.90,"","brNDC");

  TMultiGraph* wgr = mgrDta;
  TLegend *wlg = legDta;

   // the data
  legDta->SetBorderSize(0); // turn off border
  legDta->SetFillStyle(0);
  
  datafile_t *f = datafiles;
  TGraph* gr=0;
  while ( f && f->filename ) {
    gr=OneGraph(f);
    if (gr) {
      if (f->lnpt) {
	mgrDta->Add(gr,f->lnpt);
	legDta->AddEntry(gr,f->label,f->lnpt);
      }
      else if (gr->GetMarkerStyle()>=20) {
	mgrDta->Add(gr,"p");
	legDta->AddEntry(gr,f->label,"p");
      }	
      else {
	mgrDta->Add(gr,"l");
	legDta->AddEntry(gr,f->label,"l");
      }
    }
    f++;
  }
    

  mgrDta->Draw("p");
//  legDta->Draw();
  TF1 *theFit = new TF1("theFit","pol0");
  gr->Fit(theFit);
  theFit->Draw("same");  
  TMultiGraph* mgrThry = new TMultiGraph("Theory","G_{E}^{n}");
  TLegend *legThry = new TLegend(.54,.3,.875,.6,"","brNDC");

  wgr = mgrThry;
  wlg = legThry;

  // the theory
  wlg->SetBorderSize(0); // turn off border
  wlg->SetFillStyle(0);
  
  f = theoryfiles1;
  gr=0;
  while ( f && f->filename ) {
    gr=OneGraph(f);
    if (gr) {
      TGraphAsymmErrors *egr = dynamic_cast<TGraphAsymmErrors*>(gr);
      if (egr && egr->GetN()>1 && egr->GetEYhigh() && egr->GetEYhigh()[1]>0) {
	gr = toerror_band(egr);
	gr->SetFillStyle(3000+f->style);
      }
      if (f->lnpt) {
	wgr->Add(gr,f->lnpt);
	wlg->AddEntry(gr,f->label,f->lnpt);
      }
      else if (gr->GetMarkerStyle()>=20) {
	wgr->Add(gr,"p");
	wlg->AddEntry(gr,f->label,"p");
      }	
      else {
	wgr->Add(gr,"l");
	wlg->AddEntry(gr,f->label,"l");
      }
    }
    f++;
  }

//  genf->Draw("same");
  mgrThry->Draw("c");
//  galster->Draw("same");
//  bbba05->Draw("same");
//  legThry->AddEntry(genf,"F_{2}/F_{1} #propto ln^{2}(Q^{2}/#Lambda^{2})/Q^{2}","l");
//  legThry->AddEntry(galster,"Galster fit","l");
//  legThry->AddEntry(bbba05,"BBBA05","l");
//  legThry->Draw();
//  legDta->Draw();
  
  // draw a line at 1
  cn->Modified();

  cn->Update();
  cn->SaveAs(Form("%s.eps",psfile));
  cn->SaveAs(Form("%s.root",psfile));
  gSystem->Exec(Form("./replace_symbols.pl %s.eps",psfile));

  return;  // LEAVING HERE

  // now an overlay, hopefully matching dimensions

  // remove everything but the graph
  cn->Update();
  TList *clist = cn->GetListOfPrimitives();
  TFrame* frame = cn->GetFrame();
  for (int i=0; i<clist->GetSize(); ) {
    if (clist->At(i) != frame) {
      clist->RemoveAt(i);
    } else i++;
  }
  // draw markers in the corners
  TMarker *mkr = new TMarker(frame->GetX1(),frame->GetY1(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX2(),frame->GetY1(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX1(),frame->GetY2(),2);
  mkr->Draw();
  mkr = new TMarker(frame->GetX2(),frame->GetY2(),2);
  mkr->Draw();
  frame->SetLineColor(10);
  cn->Update();

  datafile_t miller = { "figure_input/Miller/lattice.GEn.rtf","Miller",
			"[0]","[1]","[1]-[3]","[2]-[1]",0,0,1,3,"F" };

  gr = OneGraph(&miller);
  TGraphAsymmErrors* egr = dynamic_cast<TGraphAsymmErrors*>(gr);
  if (egr && egr->GetEYhigh() && egr->GetEYhigh()[egr->GetN()/2]>0) {
    gr = toerror_band(egr);
    gr->SetLineStyle(1);
    gr->SetFillColor(gr->GetLineColor());
    gr->SetFillStyle(3000+miller.style);
  }
  
  gr->Draw("F");

  cn->Update();
  cn->SaveAs("gen_Miller_Overlay.eps");
  cn->SaveAs("gen_Miller_Overlay.root");
  
}
//___________________________________________________________________________
Double_t* Ifit(int shift, Double_t& dataResult, Double_t& dataErr, std::string dataFile, 
	       TH1D* hsig, TH1D* hbkg, TH1D* hEGdata, Double_t* FitPar,
	       int ptbin=30, char EBEE[10]="EB", int fit_data=2)
{
  
  printf(" *** calling Ifit for %s , ptbin %d *** \n\n", EBEE,ptbin);

  cout << "The number of bins are: " << endl;
  cout << "hdata nbins = " << hEGdata->GetNbinsX() << endl;
  cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
  cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;
  

  TCanvas *c1 = new TCanvas("HF1", "Histos1", 0, 0, 600, 600);
  gStyle->SetOptFit(0);

  if(fit_data != 3) dataColl.clear();
  sigColl.clear();
  bkgColl.clear();

  totalColl.clear();
  ctauColl.clear();
  Para.clear();
  Para_err.clear();

  info.clear();
  info_err.clear();

  float ptmax=0.;  
  if(ptbin== 21) ptmax= 23;
  if(ptbin== 23) ptmax= 26;
  if(ptbin== 26) ptmax= 30;
  if(ptbin== 30) ptmax= 35;
  if(ptbin== 35) ptmax= 40;
  if(ptbin== 40) ptmax= 45;
  if(ptbin== 45) ptmax= 50;
  if(ptbin== 50) ptmax= 60;
  if(ptbin== 60) ptmax= 85;
  if(ptbin== 85) ptmax= 120;
  if(ptbin== 120) ptmax= 300;
  if(ptbin== 300) ptmax= 500;



  Double_t* fitted = new Double_t[6];
  fitted[0] = 0.;    fitted[1] = 0.;    fitted[2] = 0.;    fitted[3] = 0.;
  fitted[4] = 0.;    fitted[5] = 0.;

  char hname[30];


  hsig->SetLineColor(1);
  hbkg->SetLineColor(1);
  hsig->SetNdivisions(505,"XY");
  hbkg->SetNdivisions(505,"XY");
  hsig->SetTitle("");
  hbkg->SetTitle("");
  hsig->SetXTitle("combined ISO (GeV)");
  hbkg->SetXTitle("combined ISO (GeV)");

  TH1F *hsum = (TH1F*)hsig->Clone();  
  hsum->Add(hbkg,1);
  float ntemplate = 1.;
  if (hsum->Integral()>1.) ntemplate = hsum->Integral();
  float sigfrac = hsig->Integral()/ntemplate*0.8;

  TH1F *hsum_norm = (TH1F*)hsum->Clone();  
  hsum_norm->Scale(1./hsum->Integral());

  TH1F *hdata = new TH1F();
  int ndata=0;
  if ( fit_data==1 ) {
    hdata = (TH1F*)hEGdata->Clone();
    ndata = (int)hdata->Integral();    
    for(int ibin=1; ibin<=hdata->GetNbinsX(); ibin++){
      for(int ipoint=0; ipoint<hdata->GetBinContent(ibin); ipoint++) {
	dataColl.push_back(hdata->GetBinCenter(ibin));
      }
    }
    ndata = dataColl.size();
  }else if (fit_data==2 ){
      hdata = (TH1F*)hEGdata->Clone();
    hdata -> Reset();
    dataColl.clear();
    FILE *infile =  fopen(dataFile.data(),"r");  
    float xdata, xdata1, xdata2; // combined isolation, pt, eta

    int flag = 1;
    while (flag!=-1){
      flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
      if( xdata1 >= ptbin && xdata1 < ptmax && xdata<20.) {
	if((strcmp(EBEE,"EB")==0 && TMath::Abs(xdata2)<1.45) ||
	   (strcmp(EBEE,"EE")==0 && TMath::Abs(xdata2)<2.5 && TMath::Abs(xdata2)>1.7) ) {
 	  dataColl.push_back(xdata);
	  hdata->Fill(xdata);
 	}
      } 
    }// keep reading files as long as text exists
    ndata = dataColl.size();

    printf("test print data 2 %2.3f \n", dataColl[2]);    
//     cout << "ndata in dataColl = " << ndata << endl;
    if ( ndata == 0 ) {
      printf(" no data to fit \n");
      return fitted;
    }
  }

  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    return fitted;
  }
    
  //test fit the template and get PDFs
  TCanvas *c10 = new TCanvas("c10","c10",1000,500);
  c10->Divide(2,1);
  c10->cd(1);

  double par[20] = {hsig->GetMaximum(), 1., 0.6, 0.3,
		    hbkg->GetMaximum(), -.45, -0.05, 0.03, 1., 1., 1., 1.};

  if(strcmp(EBEE,"EE")==0) { par[2]=-0.1, par[3]=0.2; par[6]=-0.15; par[7]=0.02; };
  int fit_status;

  TF1 *f1 = new TF1("f1", exp_conv, -1., 20., 11);
  TF1 *fmcsigfit = new TF1("fmcsigfit", exp_conv, -1., 20., 11);
  fmcsigfit->SetLineColor(4);
  fmcsigfit->SetLineWidth(2);

  f1->SetNpx(10000);
  f1->SetParameters(par);
  f1->SetLineWidth(2);
  c10->cd(1);
  fit_status = hsig->Fit(f1,"","",-1., 5.);

  hsig->Draw();
  f1->Draw("same");
  if ( fit_status > 0 ) {
     printf("fit signal template failed. QUIT \n");
     return fitted;
  }
  if(para_index>0 && para_index<4){
    double tmppar = f1->GetParameter(para_index);
    f1->SetParameter(para_index, tmppar+para_sigma*f1->GetParError(para_index));
  }

  TF1 *fmcsig = (TF1*)f1->Clone();
  TF1 *fmcsigcorr = (TF1*)f1->Clone();
  fmcsig->SetNpx(10000);
  fmcsigcorr->SetNpx(10000);
  fmcsigfit->SetNpx(10000);
  
  TCanvas *c101 = new TCanvas("c101","c101",1000,500);
  c101->Divide(2,1);
  c101->cd(1);

  fmcsig->SetLineColor(1);
//   fmcsig->Draw();
//   f1->Draw("same");
  TH1F *htmp1 = (TH1F*)fmcsig->GetHistogram();
//   TH1F *htmp2 = (TH1F*)fmcsigcorr->GetHistogram();
  
  TH2F *htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

//   htmp2->Draw();
//   htmp1->Draw("same");
//   htmp2->Add(htmp1,-1);
//   htmp2->Divide(htmp1);
  htmp2->GetXaxis()->SetRangeUser(-1., 10.);
  htmp2->SetMinimum(-1.);
  //htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcsig->Draw("same");
//   fmcsigcorr->Draw("same");
  
  TLegend *tleg1 = new TLegend(0.5, 0.7, 0.93, 0.92);
  tleg1->SetHeader("");
  tleg1->SetFillColor(0);
  tleg1->SetShadowColor(0);
  tleg1->SetBorderSize(0);
  tleg1->AddEntry(fmcsig,"Zee data","l");
  //tleg1->AddEntry(fmcsigcorr,"corrected shape","l");
  tleg1->AddEntry(fmcsigfit,"shape from data","l");
  tleg1->Draw();

  //return fitted;
       
  SigPDFnorm = f1->Integral(-1.,20.);
  printf("status %d, sig area %3.3f \n", fit_status,f1->Integral(-1., 20.));


  f1->SetParameter(2,f1->GetParameter(2)+0.2);
  f1->SetParameter(3,f1->GetParameter(3)+0.1);

  Para.push_back(f1->GetParameter(0));
  Para.push_back(f1->GetParameter(1));
  Para.push_back(f1->GetParameter(2));
  Para.push_back(f1->GetParameter(3));

  Para_err.push_back(f1->GetParError(0));
  Para_err.push_back(f1->GetParError(1));
  Para_err.push_back(f1->GetParError(2));
  Para_err.push_back(f1->GetParError(3));

  c10->cd(2);
  TF1 *fbkgfit = new TF1("fbkgfit", expinv_power, -1., 20., 11);  

  TF1 *f3 = new TF1("f3", expinv_power, -1., 20., 11);
  fbkgfit->SetNpx(10000);  
  fbkgfit->SetLineColor(4);
  fbkgfit->SetLineWidth(2);

  f3->SetNpx(10000);
  f3->SetLineWidth(2);
  f3->SetParameters(f1->GetParameters());
    
  f3->SetParLimits(5,-5.,0.);
  f3->SetParLimits(6,-0.5,0.);
  f3->SetParLimits(7,0.001,0.2);
  f3->SetParLimits(8,0.5,5.);
  if ( strcmp(EBEE,"EB")==0 ){  
//     f3->FixParameter(8,1.);
//     f3->FixParameter(6,-0.1);
    f3->SetParLimits(8,1.,1.5);
  }

  float bkg_bend_power = 1.;
  if ( ptbin==21 ) bkg_bend_power = 4.5;
  if ( ptbin==23 ) bkg_bend_power = 4.;
  if ( ptbin==26 ) bkg_bend_power = 3.5;
  if ( ptbin==30 ) bkg_bend_power = 2.6;
  if ( ptbin==35 ) bkg_bend_power = 2.2;
  if ( ptbin==40 ) bkg_bend_power = 2.;
  if ( ptbin==45 ) bkg_bend_power = 2.;
  if ( ptbin==50 ) bkg_bend_power = 1.8;
  if ( ptbin==60 ) bkg_bend_power = 1.5;
  if ( ptbin==85 ) bkg_bend_power = 1.;
  if ( ptbin==120 ) bkg_bend_power = 1.;


  if ( strcmp(EBEE,"EE")==0 ){  
    f3->SetParameter(8,bkg_bend_power);
    f3->SetParLimits(8,bkg_bend_power-1., bkg_bend_power+1.);
  }

  f3->FixParameter(0,f3->GetParameter(0));
  f3->FixParameter(1,f3->GetParameter(1));
  f3->FixParameter(2,f3->GetParameter(2));
  f3->FixParameter(3,f3->GetParameter(3));

  hbkg->SetMaximum(hbkg->GetMaximum()*3.);
  fit_status = hbkg->Fit(f3,"b","",-1., 20.);
  hbkg->Draw();
  if ( fit_status > 0 ) {
    printf("fit background template failed. QUIT \n");    
    return fitted;
  }else {
    f3->Draw("same");
  }

  TF1 *fmcbkg = (TF1*)f3->Clone();
  fmcbkg->SetLineColor(1);
  c101->cd(2);

  htmp1 = (TH1F*)fmcbkg->GetHistogram();
  htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

  htmp2->GetXaxis()->SetRangeUser(-1., 20.);
  htmp2->SetMinimum(-1.);
  htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcbkg->Draw("same");

  TLegend *tleg2 = new TLegend(0.25, 0.2, 0.6, 0.42);
  tleg2->SetHeader("");
  tleg2->SetFillColor(0);
  tleg2->SetShadowColor(0);
  tleg2->SetBorderSize(0);
  if ( strcmp(EBEE,"EB")==0 ){  
    tleg2->AddEntry(fmcbkg,"MC shape","l");
  }else {
    tleg2->AddEntry(fmcbkg,"Data SB shape","l");
  }
  tleg2->AddEntry(fbkgfit,"shape from data","l");
  tleg2->Draw();
  
  if(para_index>4){
    double tmppar = f3->GetParameter(para_index);
    f3->SetParameter(para_index, tmppar+para_sigma*f3->GetParError(para_index));
  }

//   f3->SetParameter(5,-0.5);
//   f3->SetParameter(6,-0.05);
//   f3->SetParameter(7,0.02);
//   f3->SetParameter(8,1.);

  Para.push_back(f3->GetParameter(4));
  Para.push_back(f3->GetParameter(5));
  Para.push_back(f3->GetParameter(6));
  Para.push_back(f3->GetParameter(7)); 
  Para.push_back(f3->GetParameter(8)); 

  Para_err.push_back(f3->GetParError(4));
  Para_err.push_back(f3->GetParError(5));
  Para_err.push_back(f3->GetParError(6));
  Para_err.push_back(f3->GetParError(7));
  Para_err.push_back(f3->GetParError(8));

  BkgPDFnorm = f3->Integral(-1., 20.);
  printf("status %d, bkg area %3.3f \n", fit_status,f3->Integral(-1., 20.)/hdata->GetBinWidth(2));

  //test PDFs
  TCanvas *c11 = new TCanvas("c11","c11",1000,500);
  c11->Divide(2,1);
  c11->cd(1);
  TF1 *f11 = new TF1("f11",exp_conv_norm, -1., 20., 11);
  f11->SetNpx(10000);
  f11->SetParameters(f3->GetParameters());
  f11->Draw();
  printf(" SIG PDF area %2.3f \n", f11->Integral(-1., 20.));

  c11->cd(2);
  TF1 *f12 = new TF1("f12",expinv_power_norm, -1., 20., 11);
  f12->SetNpx(10000);
  f12->SetParameters(f3->GetParameters());
  f12->Draw();
  printf(" BKG PDF area %2.3f \n", f12->Integral(-1., 20.));

  //c1->cd();

  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
  printf("Purity %2.3f, init size %4.3f,  fit sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");



  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(),
	  sigColl.size(), bkgColl.size() );  

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[11] = {1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
  for (int ii=0; ii<9; ii++) {    
    vstart[ii+2] = Para[ii]; //8 shape parameters
  }
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[11];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 1.,1.,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,};

  for ( int ii=0; ii<9; ii++){
    printf(" para %d, %.5f, err %.5f \n", ii, Para[ii], Para_err[ii]);
  }

  float sigma = 3.;
  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.01,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.01,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3],  0.01,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.01,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.01,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.01,  0.001                    , 0.1                      , ierflg);
// //   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  0.5                       , 5.                       , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// //   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.1) ,  0.8    , 1.3    , ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.1) ,  -0.7   , -0.3   , ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);

  gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
  gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.00,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
  gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.00,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
  gMinuit->mnparm(5,  "exg width"    , Para[3],  0.00,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
  gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
  gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.00,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
  gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.00,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
  gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.00,  0.001                    , 0.1                      , ierflg);
  gMinuit->mnparm(10, "bg bend power", Para[8],  0.00,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 500; // number of iteration
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
  //can do scan
//   arglist[0] = 0;
//   gMinuit->mnexcm("SCAN", arglist,1,ierflg);

  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %d \n", ierflg);

  double para[NPAR+1],errpara[NPAR+1];

  double tmp_errpara[NPAR+1];

  for(int j=0; j<=NPAR-1;j++) { tmp_errpara[j]=0.1; }
  for(int j=2; j<=NPAR-1;j++) { 
    if(Para_err[j-2]!=0.) tmp_errpara[j]=TMath::Abs(Para_err[j-2]); 
  }
  
  int ni=6;       if ( strcmp(EBEE,"EE")==0 ) { ni=6; }//if(ptbin==21) ni=0;}
  
  if ( ierflg == 0 ) {
    for(int i=0; i<ni; i++) {
      float istep[10] = {0.,0.,0.,0.,0.,0.,0.};
      if (i<(ni-1)) {
	istep[i] = 0.001;
      }else {
	for (int j=0; j<ni-1; j++) {istep[j] = 0.001;}
      }

      for(int j=0; j<=NPAR-1;j++) {
	gMinuit->GetParameter(j, para[j], errpara[j]);
	if (errpara[j] != 0. ) {
	  tmp_errpara[j] = TMath::Abs(errpara[j]);
	}
      }

      if ( strcmp(EBEE,"EB")==0 ) {

	sigma = 10.;

 	if ( i==(ni-1) ) { sigma=5.;istep[1]=istep[4]=0.; }
	if ( ptbin==21 && i==1 ){ sigma=3.; }
 	if ( ptbin==21 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==23 && i==0 ){ para[7]=-0.5; }
	if ( ptbin==23 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin==23 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==23 && i==(ni-1) ){ sigma=20.; }
 	if ( ptbin==26 && i==1 ){ sigma=5.; }	
	if ( ptbin==26 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==30 && i==(ni-1) ){ sigma=3.; }
 	if ( ptbin==35 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==40 && i==(ni-1) ) { sigma=5.; istep[4]=0.01; }
 	if ( ptbin==45 && i==(ni-1) ) { sigma=10.; }
	if ( ptbin==60 && i==0 ) { para[3]=1.; para[4]=0.6; para[5]=0.32; para[7]=-0.45; para[9]=0.025; para[10] = 1.;}
 	if ( ptbin==60 && i==(ni-1) ) { sigma=5.; istep[4]=0.01;}
	if ( ptbin>=85 && i==(ni-1) ){ sigma=3.; }
	if ( ptbin==300 ) { istep[2]=istep[3]=istep[4]=0.; }// para[7] = -5.11907e-02; istep[1]=0.; }
	float tmp8=0.;
	
// 	if( i!= (ni-1) ) {
	  gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	  gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(2,  "constant"     , para[2],  0., para[2]-100.*tmp_errpara[2], para[2]+100.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(6,  "constant"     , para[6],  0., para[6]-100.*tmp_errpara[6], para[6]+100.*tmp_errpara[6], ierflg);
	  gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	  gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	  gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	  gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	  gMinuit->mnparm(8,  "bg x offset  ", para[8],  tmp8    ,  para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	  gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);      
	  float sigma10=5.;
	  if ( para[10]-sigma10*tmp_errpara[10] < 1. )// && i!=(ni-1))
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], 1.,  para[10]+sigma10*tmp_errpara[10], ierflg);      
	  else
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);      
// 	}else {
// 	  gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
// 	  //gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// 	  gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.0) ,  0.8    , 1.3    , ierflg);
// 	  gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
// 	  gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
// 	  gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
// 	  gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.0) ,  -0.7   , -0.3   , ierflg);
// 	  gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
// 	  gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
// 	  gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);
// 	}


	if( ptbin >=300 ) { 
	  gMinuit->mnparm(3,  "exp tail"  , 1.257281,  0.0,  para[1]-3.*tmp_errpara[1], para[1]+3.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(4,  "exg mean"  , 0.856906,  0.0,  para[2]-3.*tmp_errpara[2], para[2]+3.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(5,  "exg width" , 0.320847,  0.0,  para[3]-3.*tmp_errpara[3], para[3]+3.*tmp_errpara[3], ierflg);
	}      

    }else{	

	sigma=10.;
	if ( i==0 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 0.3; }
 	if ( i==(ni-1) ) { sigma=3.;istep[1]=istep[4]=0.; } //test of not changing signal template
     	if ( i==(ni-1) ) { istep[4]=0.;}

   	if ( ptbin==21 && i==(ni-1) ) { sigma=20.;}
  	if ( ptbin==23 && i==0 ) { sigma=5.;}
  	if ( ptbin==23 && i==(ni-1) ) { sigma=10.;}
	if ( ptbin<30 && ptbin>21 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin<30 && ptbin>21 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==26 && i==1 ) { para[7] = -0.8; }
	if ( ptbin==26 && i==(ni-1) ) { sigma=10.; }
  	if ( ptbin==30 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==35) {para[7] = -0.75;}
 	if ( ptbin==40 && i==0) {para[7] = -0.65; para[10] = 2.;}
	if ( ptbin==45 && i==(ni-1) ) {sigma=5.;}
	if ( ptbin==85 && i==(ni-1) ) {sigma=10.; istep[4]=0.01;}
	if (ptbin >= 85 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 1.; }

	if ( ptbin==120 ) { para[7] = -0.615255; istep[1]=0.;}

	
//     	if ( ptbin==120 && i==0 ) { 
// 	  para[3] = 1.446454; para[4]=-0.016373; para[5]=0.163238;
// 	  istep[2]=istep[3]=istep[4]=0.; sigma=5.; tmp_errpara[10]=0.2;
// 	}
//     	if ( ptbin==120 && i==(ni-1) ) { istep[2]=istep[3]=istep[4]=0.; sigma=5.;}

	gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	gMinuit->mnparm(2,  "constant"     , para[2],  0.,  para[2], para[2] , ierflg);
	gMinuit->mnparm(6,  "constant"     , para[6],  0.,  para[6], para[6], ierflg);	
	gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	gMinuit->mnparm(8,  "bg x offset  ", para[8],  0.00,      para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);	
  
	float minerr=1.;
	//if ( tmp_errpara[10] > 0.5) tmp_errpara[10] = 0.5;
	float sigma10=5.;
	if ( para[10]-sigma10*tmp_errpara[10] < 1. ) 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], minerr,  para[10]+sigma10*tmp_errpara[10], ierflg);
	else 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);

      }
      printf(" ************ \n");
      printf("  do %d th fit  \n", i);
      if(i==5 && dataFile.find("toy")    != std::string::npos)
	{
	  cout << "dataResult = " << dataResult << "\t dataErr = " << dataErr << endl;
	  // fixed turn on at +- 1 sigma
	  gMinuit->mnparm(7,  "bg exp turnon", dataResult-(float)shift*dataErr,  0.00,  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);

	}
      else if(dataFile.find("toy")    == std::string::npos)
	{
	  dataResult = para[7];
	  dataErr    = tmp_errpara[7];
	}
      arglist[0] = 500; // number of iteration
      gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);      
      if ( ierflg != 0 ) {
  	printf("fit failed at %d iteration \n", i);
  	c1->cd();	c1->Draw();  	hdata->Draw("phe");
  	return fitted;
      }
    }
  }
 
  Double_t amin,edm,errdef; 
  if ( ierflg == 0 ) {
    for(int j=0; j<=NPAR-1;j++) {
      gMinuit->GetParameter(j, para[j],errpara[j]);
      info.push_back(para[j]);
      info_err.push_back(errpara[j]);
      printf("Parameter  %d = %f +- %f\n",j,para[j],errpara[j]);	
    }
    para[NPAR] = dataColl.size();
    printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );
    
    info.push_back(sigColl.size());
    
    for(int j=0; j<=NPAR-1;j++) {
      tmp_errpara[j] = errpara[j];
      if( tmp_errpara[j] == 0. ) tmp_errpara[j] = par[j]*.1;      
    }
    //do minos if fit sucessed.

  }
  if (ierflg != 0 )  {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;

    c1->cd();
    c1->Draw();  
    //gPad->SetLogy();
    hdata->SetNdivisions(505,"XY");
    hdata->SetXTitle("comb. ISO (GeV)");
    hdata->SetYTitle("Entries");
    hdata->SetTitle("");
    hdata->SetMarkerStyle(8);
    hdata->SetMinimum(0.);
    if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
    else hdata->SetMaximum(hdata->GetMaximum()*1.25);
    if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.25);
   
    hdata->Draw("phe");  

    return fitted;    
  }

  
  // Print results
//   Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  //use new PDF form
  double tmppar[12];
  for(int ii=0; ii<9; ii++){
    tmppar[ii] = para[ii+2];
    fmcsigfit->SetParameter(ii,tmppar[ii]);
    fbkgfit->SetParameter(ii,tmppar[ii]);
  }

  c101->cd(1);
  
  //fmcsigfit->SetParameters(tmppar);
  //fmcsigfit->SetParameter(2,0.1);
  //fmcsigfit->SetLineStyle(2);

  fmcsigfit->Draw("same");
  c101->cd(2);

  fbkgfit->SetParameter(4,fbkgfit->GetParameter(4)*fmcbkg->Integral(-1., 20.)/fbkgfit->Integral(-1., 20.));
  fbkgfit->Draw("same");

  char fname[100];
  sprintf(fname,"plots/template_Ifit%s_%d.pdf",EBEE,ptbin);
  c101->SaveAs(fname);


  f11->SetParameters(tmppar);
  SigPDFnorm = f11->Integral(-1., 20.);
  f12->SetParameters(tmppar);
  BkgPDFnorm = f12->Integral(-1., 20.);


  // plot
  c1->cd();
  c1->Draw();  
  //gPad->SetLogy();
   hdata->SetNdivisions(505,"XY");
   hdata->SetXTitle("comb. ISO (GeV)");
   hdata->SetYTitle("Entries");
   hdata->SetTitle("");
   hdata->SetMarkerStyle(8);
   hdata->SetMinimum(0.);
   if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
   else hdata->SetMaximum(hdata->GetMaximum()*1.5);
   if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.2);

   hdata->Draw("p e ");

  f11->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f11->SetFillColor(5);
  f11->SetLineColor(4);
  //f11->SetFillColor(603);
  f11->SetLineWidth(2);
//   f11->SetFillStyle(3001);
  f11->Draw("same");

  f12->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f12->SetFillColor(8);
  f12->SetLineColor(2);
  //f12->SetFillColor(603);
  f12->SetLineWidth(2);
//   f12->SetFillStyle(3013);
  f12->Draw("same");

  TF1 *f13 = new TF1("f13",sum_norm, -1., 20 ,11);
  f13->SetNpx(10000);
  f13->SetParameters(f12->GetParameters());
  f13->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
  f13->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));  
  f13->SetLineWidth(2);
  f13->SetLineColor(1);
  f13->Draw("same");
  f11->Draw("same");
  hdata->Draw("pe same");

//   cout << "The number of bins are: " << endl;
//   cout << "hdata nbins = " << hdata->GetNbinsX() << endl;
//   cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
//   cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;

  // get chi2/NDF
  double chi2ForThisBin=0;
  int nbinForThisBin=0;
  chi2Nbins(f13, hdata, chi2ForThisBin, nbinForThisBin);
  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f11 parameter " << epar << " = " << 
// 	f11->GetParameter(epar) << endl;
      FitPar[epar] = f11->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f12 parameter " << epar << " = " << 
// 	f12->GetParameter(epar) << endl;
      FitPar[epar+11] = f12->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f13 parameter " << epar << " = " << 
// 	f13->GetParameter(epar) << endl;
      FitPar[epar+22] = f13->GetParameter(epar);

    }

//   cout << "hdata integral = " << hdata->Integral() << endl;
//   cout << endl;

//   printf("fit area %3.2f; sig area %3.2f; bg area %3.2f\n", f13->Integral(-1., 20.)/hdata->GetBinWidth(2),  f11->Integral(-1., 20.)/hdata->GetBinWidth(2),f12->Integral(-1., 20.)/hdata->GetBinWidth(2));

//   for(int i=0; i<12; i++){
//     printf(" fit para %d = %4.3f \n", i, f13->GetParameter(i));
//   }

   TLegend *tleg = new TLegend(0.5, 0.7, 0.93, 0.92);
   char text[50];
   sprintf(text,"%s Pt %d ~ %.0f GeV",EBEE, ptbin, ptmax);
   tleg->SetHeader(text);
   tleg->SetFillColor(0);
   tleg->SetShadowColor(0);
   tleg->SetBorderSize(0);
   sprintf(text,"#chi^{2}/NDF = %.1f/%d",chi2ForThisBin,nbinForThisBin);
   tleg->AddEntry(hdata,text,"");
   sprintf(text,"Data %.1f events",hdata->Integral());
   tleg->AddEntry(hdata,text,"pl");
   sprintf(text,"Fitted %.1f events",para[0]+para[1]);//f13->Integral(-1., 20.)/hdata->GetBinWidth(2));
   tleg->AddEntry(f13,text,"l");
   sprintf(text,"SIG %.1f #pm %.1f events",para[0], errpara[0]);
   tleg->AddEntry(f11,text,"f");
   sprintf(text,"BKG %.1f #pm %.1f events",para[1], errpara[1]);
   tleg->AddEntry(f12,text,"f");
   tleg->Draw();


   gPad->RedrawAxis();

   printf("%s, ptbin %d, Data %.1f events \n",EBEE, ptbin, hdata->Integral());
   printf("Fitted %.1f (in 5GeV) %.1f events \n",para[0]+para[1],f13->Integral(-1.,5.));
   printf("SIG %.1f #pm %.1f events \n",para[0], errpara[0]);
   printf("SIG (in 5GeV) %.1f #pm %.1f events \n",f11->Integral(-1.,5.)/hdata->GetBinWidth(2), f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2));
   printf("BKG %.1f #pm %.1f events \n",para[1], errpara[1]);
   printf("BKG (in 5GeV) %.1f #pm %.1f events \n",f12->Integral(-1.,5.)/hdata->GetBinWidth(2), f12->Integral(-1.,5.)*errpara[1]/para[1]/hdata->GetBinWidth(2));
   
   float purity = f11->Integral(-1.,5.)/hdata->GetBinWidth(2)/(f11->Integral(-1.,5.)/hdata->GetBinWidth(2)+f12->Integral(-1.,5.)/hdata->GetBinWidth(2));
   float purity_err = purity*errpara[0]/para[0];
   printf("Purity (in 5GeV) %.3f #pm %.3f  \n", purity, purity_err);


//   hsig->Scale(para[0]/hsig->Integral());
//   hbkg->Scale(para[1]/hbkg->Integral());
//   hbkg->Add(hsig);

//   hsig->SetLineColor(1);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);


//   hsig->Draw("same");
//   hbkg->Draw("same");


  sprintf(fname,"plots/unbinned_free_Ifit%s_%d.pdf",EBEE,ptbin);
  if (para_index>0) sprintf(fname,"plots/unbinned_Ifit%s_%d_para%d_sigma%1.0f.pdf",EBEE,ptbin,para_index,para_sigma);
  if(Opt_SavePDF == 1) {
    c1->SaveAs(fname);


  } else {

   c1->Close();
   c10->Close();
   c101->Close();
   c11->Close();

  }

  printf("----- fit results with signal projection   ----------- \n");

  fitted[0] = para[0];
  fitted[1] = errpara[0];
  fitted[2] = para[1];
  fitted[3] = errpara[1];
  fitted[4] = f11->Integral(-1.,5.)/hdata->GetBinWidth(2);
  fitted[5] = f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2);

  return fitted;
}
void chicent_sys_ratio()
{
  gROOT->Reset();
  gROOT->SetStyle("MyStyle");
//  gROOT->LoadMacro("v2pt_12cen_MyDef.C");
  // gROOT->LoadMacro("MyDef.C");
  gStyle->SetTextFont(43);
  gStyle->SetLabelFont(43,"x");
  gStyle->SetLabelFont(43,"y");
  gStyle->SetLabelFont(43,"z");
  gStyle->SetTitleFont(43,"x");
  gStyle->SetTitleFont(43,"y");
  gStyle->SetTitleFont(43,"z");
  gStyle->SetEndErrorSize(0);

  double textsize = 19;

//int   mcol[8]={kRed,kMagenta,kBlue,kCyan,kGreen,kYellow,kOrange,kGray};
int   mcol[8]={kRed,kOrange+1,kBlue,kGreen+1,kCyan,kYellow,kOrange,kGray};
int   mcol2[4]={6,2,4,8};

//int   msty[8][2]={{20,20},{25,24},{22,22},{28,26},{29,30},{33,27},{34,28},{20,24}};
int   msty[8][2]={{20,20},{21,24},{22,29},{23,30},{24,30},{25,27},{28,28},{30,24}};


//float msiz[8]={1.11,0.9,1.2,1.24,1.5,1,1,1};
float msiz[8]={1.11,1.0,1.5,1.2,1.2,1.2,1.2,1.6};
float msiz2[4]={1.5,1.5,1.5,1.5};
//
// arrays
//
const int Mfiles=50;
int   ndp[Mfiles];
char *cfn[Mfiles];
char *cft[Mfiles];
const int Mpoints=40;
double xa[Mfiles][Mpoints],xe[Mfiles][Mpoints];
double ya[Mfiles][Mpoints],ye[Mfiles][Mpoints];

double nAxa[Mfiles][Mpoints],nAxe[Mfiles][Mpoints];
double nAya[Mfiles][Mpoints],nAye[Mfiles][Mpoints];
double nBxa[Mfiles][Mpoints],nBxe[Mfiles][Mpoints];
double nBya[Mfiles][Mpoints],nBye[Mfiles][Mpoints];
double nARxa[Mfiles][Mpoints],nARxe[Mfiles][Mpoints];
double nARya[Mfiles][Mpoints],nARye[Mfiles][Mpoints];
double nBRxa[Mfiles][Mpoints],nBRxe[Mfiles][Mpoints];
double nBRya[Mfiles][Mpoints],nBRye[Mfiles][Mpoints];

double aexl[Mfiles][Mpoints],aexh[Mfiles][Mpoints];
double aeyl[Mfiles][Mpoints],aeyh[Mfiles][Mpoints];


double ra[Mfiles][Mpoints],re[Mfiles][Mpoints];

const int Mpads=14;


char  *htit[Mpads];
char  *atit[Mpads][3];
double ptit[Mpads][2];
double hxmin[Mpads],hxmax[Mpads];
double hymin[Mpads],hymax[Mpads];
double lxmin[Mpads],lxmax[Mpads];
double lymin[Mpads],lymax[Mpads];


 
  //
  // Data input
  //
  char *cjob="v2pt_12cen_4x3";
  int i=-1;


  // histogram parameter
  htit[0]="(a) #chi_{422}";
  htit[1]="(b) #chi_{523}";
  htit[2]="(c) #chi_{6222}";
  htit[3]="(d) #chi_{633}";
  htit[4]="(e) #chi_{7223}";
  htit[5]="25-30%";
  htit[6]="30-35%";
  htit[7]="35-40%";
  htit[8]="40-50%";
  htit[9]="50-60%";
  htit[10]="60-70%";
  htit[11]="70-80%";
  for (int ip=0;ip<Mpads;ip++)
  {
    hxmin[ip]=0.0001; hxmax[ip]=62.8;
    hymin[ip]=-0.3; hymax[ip]=6.99;
    lxmin[ip]=0.24; lxmax[ip]=0.88;
    lymin[ip]=0.65; lymax[ip]=0.94;
    ptit[ip][0]=3.0; ptit[ip][1]=-1.;// position legends 
    atit[ip][0]="Centrality (%)"; atit[ip][1]="#chi";
  }
  //
  // Read data and create vector files
  //

  double sysXYZ[5]={6,7,8,8,9};
  //double sysXYZ[5]={9,9,13,13,15};
  //double sysXYZ[5]={8,9,20,20,20};
  double sysEach[5]={0.0002, 0.0002, 0.0002, 0.0003, 0.0002};
  double tmp;
  const int nw=5;
  const int npt=14;
  const int npt_oli=8;
  ifstream inEP;
  inEP.open("./data_vncent5020_integral.txt");
  for(int i=0; i<nw; i++){
    for(int j=0; j<npt; j++){
      inEP>>xa[i][j]; inEP>>ya[i][j]; inEP>>ye[i][j]; 
      xe[i][j]=0.0;
    }
  }
  inEP.close();
  ifstream inEP;
  inEP.open("./data_vncent5020_integral_vzA.txt");
  for(int i=0; i<nw; i++){
    for(int j=0; j<npt; j++){
      inEP>>nAxa[i][j]; inEP>>nAya[i][j]; inEP>>nAye[i][j];
      nAxe[i][j]=0.0;

      nARxa[i][j]=nAxa[i][j];
      nARxe[i][j]=nAxe[i][j];
      nARye[i][j]=nAya[i][j]/ya[i][j]*sqrt(ye[i][j]*ye[i][j]/ya[i][j]/ya[i][j] + nAye[i][j]*nAye[i][j]/nAya[i][j]/nAya[i][j] - 2.0*ye[i][j]*ye[i][j]/ya[i][j]/nAya[i][j] );
      nARya[i][j]=nAya[i][j]/ya[i][j];
    }
  }
  inEP.close();
  ifstream inEP;
  inEP.open("./data_vncent5020_integral_vzB.txt");
  for(int i=0; i<nw; i++){
    for(int j=0; j<npt; j++){
      inEP>>nBxa[i][j]; inEP>>nBya[i][j]; inEP>>nBye[i][j];
      nBxe[i][j]=0.0;

      nBRxa[i][j]=nBxa[i][j];
      nBRxe[i][j]=nBxe[i][j];
      nBRye[i][j]=nBya[i][j]/ya[i][j]*sqrt(ye[i][j]*ye[i][j]/ya[i][j]/ya[i][j] + nBye[i][j]*nBye[i][j]/nBya[i][j]/nBya[i][j] - 1.7*nBye[i][j]*nBye[i][j]/ya[i][j]/nBya[i][j] );
      nBRya[i][j]=nBya[i][j]/ya[i][j];
cout<<"ratio A: "<<nARya[i][j]<<",  Aerr = "<<nARye[i][j]<<",  ratio B="<<nBRya[i][j]<<",  Berr = "<<nBRye[i][j]<<endl;
    }
  }
  inEP.close();



  TCanvas *can=new TCanvas("can","can",10,10,1050*0.8*1.3,800*0.3*1.3 * 1.5);

  can->Divide(5,2,0,0); //sticks the pads with no space inbetween 
  
  TH1D *h1[nw];
  for (int iw=0;iw<nw;iw++)
  {
    can->cd(iw+1);
    if(iw==4) gPad->SetRightMargin(0.02);
    //gPad->SetLogy();
    char ch1[8];
    sprintf(ch1,"h1_%d",iw);
    h1[iw] = new TH1D(ch1,"",500,hxmin[iw],hxmax[iw]);
    h1[iw]->SetMinimum(hymin[iw]); h1[iw]->SetMaximum(hymax[iw]);
    h1[iw]->SetXTitle(atit[iw][0]); h1[iw]->SetYTitle(atit[iw][1]);
    h1[iw]->GetXaxis()->CenterTitle(1);
    h1[iw]->GetYaxis()->CenterTitle(1);

    // futz with the axes
    h1[iw]->GetYaxis()->SetNdivisions(606);
    h1[iw]->GetXaxis()->SetNdivisions(606);

      h1[iw]->GetYaxis()->SetTitleSize(textsize);
      h1[iw]->GetYaxis()->SetTitleOffset(1.8);
      h1[iw]->GetYaxis()->SetLabelSize(textsize);
      h1[iw]->GetXaxis()->SetTitleSize(textsize);
      h1[iw]->GetXaxis()->SetTitleOffset(1.3);
      h1[iw]->GetXaxis()->SetLabelSize(textsize);
     // h1[iw]->GetXaxis()->SetLabelOffset(1.2);

    h1[iw]->Draw();
  }
  //
  // Draw! 
  //
  cout << "Now Draw!" << endl;
  TGraphErrors *ge, *geB, *ge2;
  for (int iw=0;iw<nw;iw++)
  {
    can->cd(iw+1);

    //
    if (iw==3)
    {
      tex=new TLatex(11,0.0100,"CMS Preliminary");
      tex->SetTextSize(textsize*1.0);
      //tex->Draw();
    }
    if (iw==0)
    {
      tex=new TLatex(5,0.00015,"Hydro. at #sqrt{s_{NN}}=2.76TeV");
      tex->SetTextSize(textsize*0.85);
      //tex->Draw();
      tex=new TLatex(7,0.00033,"|#eta|<2.4");
      tex->SetTextSize(textsize*1.0);
      //tex->Draw();
      tex=new TLatex(7,0.00012,"0.3<p_{T}<3.0 GeV/c");
      tex->SetTextSize(textsize*1.0);
      //tex->Draw();
    }
    //if (iw < 4) tex=new TLatex(ptit[iw][0]+2,0.27,htit[iw]);
    tex=new TLatex(ptit[iw][0],ptit[iw][1],htit[iw]);
    if ( iw == 0)   tex->SetTextSize(textsize);
    else if (iw == 8) tex->SetTextSize(textsize);
    else  tex->SetTextSize(textsize);
    tex->Draw();


    //
    // Read data
    //
    TLegend *leg = new TLegend(lxmin[iw]*0.3,lymin[iw]*1.05,lxmax[iw]*1.15,lymax[iw]*1.02);
    leg->SetFillStyle(0);
    leg->SetFillColor(0);
    leg->SetTextSize(textsize);

    for (int im=0;im<1;im++)
    {
      int j=im*5+iw;
      int col=2;
      //if (ndp[j]==0) continue;
      ge=new TGraphErrors(10,&nAxa[j][0],&nAya[j][0],&nAxe[j][0],&nAye[j][0]);
      ///drawSysBoxValue(ge,16,1.6, ye5sys[j]);
      //drawSysBox(ge,16,2., sysXYZ[j]);
      ge->SetTitle("");
      ge->SetMarkerStyle(24);
      //      ge->SetMarkerStyle(msty[im]);
      ge->SetMarkerSize(msiz[im]);
      ge->SetMarkerColor(col);
      ge->SetLineWidth(1.2);
      ge->SetLineColor(col);
      //ge->Draw("pe");
      leg->AddEntry(ge,"Tight","pl");
    }
    for (int im=0;im<1;im++)
    { 
      int j=im*5+iw;
      int col=4;
      //if (ndp[j]==0) continue;
      geB=new TGraphErrors(10,&nBxa[j][0],&nBya[j][0],&nBxe[j][0],&nBye[j][0]);
      ///drawSysBoxValue(ge,16,1.6, ye5sys[j]);
      //drawSysBox(ge,16,2., sysXYZ[j]);
      geB->SetTitle("");
      geB->SetMarkerStyle(25);
      //      ge->SetMarkerStyle(msty[im]);
      geB->SetMarkerSize(msiz[im]);
      geB->SetMarkerColor(col);
      geB->SetLineWidth(1.2);
      geB->SetLineColor(col);
      //ge->Draw("pe");
      leg->AddEntry(geB,"Loose","pl");
    }
    for (int im=0;im<1;im++)
    {
      int j=im*5+iw;
      int col=1;
      //if (ndp[j]==0) continue;
      ge2=new TGraphErrors(10,&xa[j][0],&ya[j][0],&xe[j][0],&ye[j][0]);
      ///drawSysBoxValue(ge2,16,1.6, yesys[j]);
      //drawSysBox(ge2,16,2., sysXYZ[j]);
      ge2->SetTitle("");
      ge2->SetMarkerStyle(20);
      //      ge2->SetMarkerStyle(msty[im]);
      ge2->SetMarkerSize(msiz[im]);
      ge2->SetMarkerColor(col);
      ge2->SetLineWidth(1.2);
      ge2->SetLineColor(col);
      //ge2->Draw("pe");
      leg->AddEntry(ge2,"Default","pl");
    }
    ge2->Draw("pe");
    ge->Draw("pe");
    geB->Draw("pe");
    if (iw==2) leg->Draw();

  }

//start new
  TH1D *h2[nw];
  for (int iw=0;iw<nw;iw++)
  { 
    can->cd(iw+1+5);
    if(iw==4) gPad->SetRightMargin(0.02);
    //gPad->SetLogy();
    char ch2[8];
    sprintf(ch2,"h2_%d",iw);
    h2[iw] = new TH1D(ch2,"",500,hxmin[iw],hxmax[iw]);
    h2[iw]->SetMinimum(0.5); h2[iw]->SetMaximum(1.5);
    h2[iw]->SetXTitle(atit[iw][0]); h2[iw]->SetYTitle(atit[iw][1]);
    h2[iw]->GetXaxis()->CenterTitle(1);
    h2[iw]->GetYaxis()->CenterTitle(1);
    h2[iw]->GetYaxis()->SetNdivisions(606);
    h2[iw]->GetXaxis()->SetNdivisions(606);
      h2[iw]->GetYaxis()->SetTitleSize(textsize);
      h2[iw]->GetYaxis()->SetTitleOffset(1.8);
      h2[iw]->GetYaxis()->SetLabelSize(textsize);
      h2[iw]->GetXaxis()->SetTitleSize(textsize);
      h2[iw]->GetXaxis()->SetTitleOffset(1.3);
      h2[iw]->GetXaxis()->SetLabelSize(textsize);
    
    h2[iw]->Draw();
  }
  for (int iw=0;iw<nw;iw++)
  {
    can->cd(iw+5+1);

    //
    if (iw==3+5)
    {
      tex=new TLatex(11,0.0100,"CMS Preliminary");
      tex->SetTextSize(textsize*1.0);
      //tex->Draw();
    }
    if (iw==0+5)
    {
      tex=new TLatex(5,0.00015,"Hydro. at #sqrt{s_{NN}}=2.76TeV");
      tex->SetTextSize(textsize*0.85);
      //tex->Draw();
      tex=new TLatex(7,0.00033,"|#eta|<2.4");
      tex->SetTextSize(textsize*1.0);
      //tex->Draw();
      tex=new TLatex(7,0.00012,"0.3<p_{T}<3.0 GeV/c");
      tex->SetTextSize(textsize*1.0);
      //tex->Draw();
    }
    //if (iw < 4) tex=new TLatex(ptit[iw][0]+2,0.27,htit[iw]);
    //tex=new TLatex(10,0.9,htit[iw]);
    tex=new TLatex(10,0.9,"CMS");
    if ( iw == 0)   tex->SetTextSize(textsize);
    else if (iw == 8) tex->SetTextSize(textsize);
    else  tex->SetTextSize(textsize);
    //tex->Draw();


    //
    // Read data
    //
    TLegend *leg2 = new TLegend(lxmin[iw]*0.3,lymin[iw]*1.16,lxmax[iw]*1.15,lymax[iw]*1.02);
    leg2->SetFillStyle(0);
    leg2->SetFillColor(0);
    leg2->SetTextSize(textsize);

    for (int im=0;im<1;im++)
    {
      int j=im*5+iw;
      int col=2;
      //if (ndp[j]==0) continue;
      ge=new TGraphErrors(10,&nARxa[j][0],&nARya[j][0],&nARxe[j][0],&nARye[j][0]);
      ///drawSysBoxValue(ge,16,1.6, ye5sys[j]);
      //drawSysBox(ge,16,2., sysXYZ[j]);
      ge->SetTitle("");
      ge->SetMarkerStyle(24);
      //      ge->SetMarkerStyle(msty[im]);
      ge->SetMarkerSize(msiz[im]);
      ge->SetMarkerColor(col);
      ge->SetLineWidth(1.2);
      ge->SetLineColor(col);
      //ge->Draw("pe");
      leg2->AddEntry(ge,"Tight/Default","pl");
    }
    for (int im=0;im<1;im++)
    { 
      int j=im*5+iw;
      int col=4;
      //if (ndp[j]==0) continue;
      geB=new TGraphErrors(10,&nBRxa[j][0],&nBRya[j][0],&nBRxe[j][0],&nBRye[j][0]);
      ///drawSysBoxValue(ge,16,1.6, ye5sys[j]);
      //drawSysBox(ge,16,2., sysXYZ[j]);
      geB->SetTitle("");
      geB->SetMarkerStyle(25);
      //      ge->SetMarkerStyle(msty[im]);
      geB->SetMarkerSize(msiz[im]);
      geB->SetMarkerColor(col);
      geB->SetLineWidth(1.2);
      geB->SetLineColor(col);
      //ge->Draw("pe");
      leg2->AddEntry(geB,"Loose/Default","pl");
    }
    ge->Draw("pe");
    geB->Draw("pe");
    if (iw==2) leg2->Draw();

    TLine *lines = new TLine(0,1,60,1);
    lines->SetLineStyle(2);
    lines->SetLineWidth(1); 
    lines->Draw();

if(iw==0||iw==0){
    TF1 *fitFun = new TF1("fitFun","pol4", 0, 60);
    fitFun->SetLineColor(4);
    geB->Fit("fitFun","R+");
    fitFun->Draw("same");
cout<<fitFun->Eval(2.5)<<",  "<<fitFun->Eval(7.5)<<",  "<<fitFun->Eval(45)<<",  "<<fitFun->Eval(55)<<endl;
}
else {
    TF1 *fitFun = new TF1("fitFun","pol0", 0, 60);
    fitFun->SetLineColor(4);
    geB->Fit("fitFun","R+");
    fitFun->Draw("same");
cout<<fitFun->Eval(2.5)<<",  "<<fitFun->Eval(7.5)<<",  "<<fitFun->Eval(45)<<",  "<<fitFun->Eval(55)<<endl;
}

    double chi2 = fitFun->GetChisquare();
    double ndf = fitFun->GetNDF();
   TLatex *tex = new TLatex(10.06,0.6,Form("#chi^{2}/ndf = %2.1f", chi2/ndf));
   //tex->SetNDC();
   //tex->SetTextFont(42);
   tex->SetTextColor(2);
   tex->SetTextSize(16);
   //tex->SetLineWidth(2);
   tex->Draw("same");


   //TLatex *text = new TLatex();
   //text->DrawTextNDC(10.12, 1.14, "D0 Preliminary");

/*
    double p0 = fitFun->GetParameter(0);
    double p0Err = fitFun->GetParError(0);
    TLine *linesErrP = new TLine(0,p0+p0Err,60,p0+p0Err);
    linesErrP->SetLineStyle(2);
    linesErrP->SetLineWidth(1);
    linesErrP->SetLineColor(2);
    linesErrP->Draw();
    TLine *linesErrM = new TLine(0,p0-p0Err,60,p0-p0Err);
    linesErrM->SetLineStyle(2);
    linesErrM->SetLineWidth(1);
    linesErrM->SetLineColor(2);
    linesErrM->Draw();
*/
  }
//end new

   can->cd();
   TLatex *   tex = new TLatex(0.06,0.97,"CMS");
   tex->SetNDC();
   tex->SetTextFont(42);
   tex->SetTextSize(0.034);
   tex->SetLineWidth(2);
   tex->Draw();
   TLatex *   tex = new TLatex(0.108,0.97,"Preliminary");
   tex->SetNDC();
   tex->SetTextFont(42);
   tex->SetTextSize(0.044);
   tex->SetLineWidth(2);
   //tex->Draw();
   TLatex *   tex = new TLatex(0.24,0.970,"0.3<p_{T}<3.0 GeV/c         |#eta|<0.8");
   tex->SetNDC();
   tex->SetTextFont(42);
   tex->SetTextSize(0.044);
   tex->SetLineWidth(2);
   tex->Draw();

  cout << "end of process" << endl;
  can->cd();
  can->Print("./figures/plot_chicent_trkSys_ratio.png");
  can->Print("./figures/plot_chicent_trkSys_ratio.pdf");

}
Exemple #21
0
void fit(const char *run="428211_429133_5s",
	 int key=1, int bmin=10, bool draw=true, bool pa=false) {
  int minentries=1000;
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  int state = findstate(key);
  printf("state %d\n",state);
  // data
  TString inname = Form("%s/adc/HI_KEY%05d.root",run,key);
  TString outname = Form("HI_KEY%05d",key);
  TFile *file = new TFile( inname.Data() );
  cout << inname.Data() << endl;

  TH1D *out = (TH1D*) file->Get("out");
  double xfit_min=out->GetBinLowEdge(bmin);
  double xfit_max=122.5;
  int bmax = out->GetXaxis()->FindBin(xfit_max);
  int entries = out->Integral(bmin,bmax);
  if(entries<minentries) {
    cout << "not enough entries: ";
    cout << entries << endl;
    return;
  }

  // fit
  TCanvas *main = new TCanvas("main","main");
  int pkt=0;
  if(pa)
    pkt = (key%(8*4*12*64))/(4*12*64);
  TF1 *fitH = GetFit( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) ,pkt,xfit_min);
  out->Fit(fitH,"MELIR","",xfit_min,xfit_max);
  TF1 *MIPH1 = GetMIP(fitH,1,kCyan-3);
  TF1 *MIPH2 = GetMIP(fitH,2,kGreen-3);
  TF1 *MIPH3 = GetMIP(fitH,3,kOrange-3);
  TF1 *MIPH4 = GetMIP(fitH,4,kMagenta-3);
  TF1 *BGR = GetBGR(fitH,xfit_min);

  double amp = fitH->GetParameter(0);
  double eamp= fitH->GetParError(0);
  double lda = fitH->GetParameter(1);
  double elda= fitH->GetParError(1);
  double sg1 = fitH->GetParameter(2);
  double esg1= fitH->GetParError(2);
  double fr2 = fitH->GetParameter(3);
  double efr2= fitH->GetParError(3);
  double fr3 = fitH->GetParameter(4);
  double efr3= fitH->GetParError(4);
  double fr4 = fitH->GetParameter(5);
  double efr4= fitH->GetParError(5);
  double fr1 = 1 - fr2 - fr3 - fr4;
  double ncs = fitH->GetChisquare()/fitH->GetNDF();
  double ba = fitH->GetParameter(6);
  double eba= fitH->GetParError(6);
  double bsl = fitH->GetParameter(7);
  double ebsl= fitH->GetParError(7);

  // saving fit
  ofstream outfit;
  outfit.open( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) );
  outfit << amp << " " << eamp << endl;
  outfit << lda << " " << elda << endl;
  outfit << sg1 << " " << esg1 << endl;
  outfit << fr2 << " " << efr2 << endl;
  outfit << fr3 << " " << efr3 << endl;
  outfit << fr4 << " " << efr4 << endl;
  outfit << ba  << " " << eba  << endl;
  outfit << bsl << " " << ebsl << endl;
  outfit << ncs << endl;
  outfit.close();
  cout << "Parameters saved to ";
  cout << outname.Data() << ".dat" << endl;

  // draw
  if(!draw) return;

  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  out->Draw("HE");
  double ymax = out->GetBinContent( out->FindBin(xfit_min) )*1.5;
  out->GetYaxis()->SetRangeUser(0.5,ymax);
  out->GetXaxis()->SetRangeUser(-5,125);
  out->Sumw2();
  out->SetLineColor(kBlack);
  out->SetMarkerStyle(20);
  out->SetTitle("");
  out->GetXaxis()->SetTitle("ADC-PED (a.u.)");
  BGR->Draw("SAME");
  MIPH1->Draw("SAME");
  MIPH2->Draw("SAME");
  MIPH3->Draw("SAME");
  MIPH4->Draw("SAME");
  fitH->SetRange(xfit_min,xfit_max);
  fitH->Draw("SAME");
  TLatex *text = new TLatex();
  text->DrawLatex(0, (1.03*(ymax)), inname.Data() );
  text->DrawLatex(30, (0.83*(ymax)), Form("Entries  %d",entries) );
  text->DrawLatex(30, (0.73*(ymax)), Form("State  %d",state) );
  text->DrawLatex(30, (0.53*(ymax)), Form("#lambda  %.1f #pm %.1f",lda,elda) );
  text->DrawLatex(30, (0.43*(ymax)), Form("#sigma  %.1f #pm %.1f",sg1,esg1) );
  text->SetTextColor(kRed-3);
  text->DrawLatex(30, (0.63*(ymax)), Form("#Chi^{2} / NDF  %.2f",ncs) );
  text->SetTextColor(kBlue-3);
  text->DrawLatex(75, (0.73*(ymax)), Form("#Alpha  %.0f #pm %.0f",fitH->GetParameter(0),fitH->GetParError(0)) );
  text->SetTextColor(kCyan-3);
  text->DrawLatex(75, (0.63*(ymax)), Form("f_{1}  %.2f",fr1) );
  text->SetTextColor(kGreen-3);
  text->DrawLatex(75, (0.53*(ymax)), Form("f_{2}  %.2f #pm %.2f",fr2,efr2) );
  text->SetTextColor(kOrange-3);
  text->DrawLatex(75, (0.43*(ymax)), Form("f_{3}  %.2f #pm %.2f",fr3,efr3) );
  text->SetTextColor(kMagenta-3);
  text->DrawLatex(75, (0.33*(ymax)), Form("f_{4}  %.2f #pm %.2f",fr4,efr4) );
  text->SetTextColor(kGray);
  text->DrawLatex(75, (0.83*(ymax)), Form("b  %.2f",bsl) );
  text->SetTextColor(kBlack);
  text->SetTextSize(0.035);
  text->SetTextColor( kRed-3 );
  text->DrawLatex(30, (0.93*(ymax)), "e^{bx} + #Alpha ( f_{1} L_{1}(x) + f_{2} L_{2}(x) + f_{3} L_{3}(x) + f_{4} L_{4}(x))");
  main->SaveAs( Form("%s/SEN%03d/%s.eps",run,key/128,outname.Data()), "eps" );
  return;
}
Exemple #22
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
TF1* fitDstar(TTree* nt, TTree* ntMC, Float_t ptmin, Bool_t plotgenmatch)
{
  TCanvas* c = new TCanvas(Form("c_5p_%.0f",ptmin),"",600,600);
  TH1D* h = new TH1D(Form("h_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSignal = new TH1D(Form("hMCSignal_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSignalplot = new TH1D(Form("hMCSignalplot_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSwapped = new TH1D(Form("hMCSwapped_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSwappedplot = new TH1D(Form("hMCSwappedplot_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);

  TF1* f = new TF1(Form("f_5p_%.0f",ptmin),"[0]*([4]*([6]*([12]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[12])*Gaus(x,[1],[11])/(sqrt(2*3.14159)*[11]))+(1-[6])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5]))+(1-[4])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3]))+[10]*((1-exp((0.13957-x)/[7]))*pow(x/0.13957,[8])+[9]*(x/0.13957-1))",BINMIN,BINMAX);
  nt->Project(Form("h_5p_%.0f",ptmin),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f)",weightdata[isData].Data(),seldata5p[isData].Data(),triggerselectiondata[isData].Data(),ptmin));
  ntMC->Project(Form("hMCSignal_5p_%.0f",ptmin),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f)",weightmc[isData].Data(),selmc5p[isData].Data(),triggerselectionmc[isData].Data(),ptmin));
  ntMC->Project(Form("hMCSwapped_5p_%.0f",ptmin),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f)",weightmc[isData].Data(),selswp5p[isData].Data(),triggerselectionmc[isData].Data(),ptmin));
  for(int ibin=0;ibin<BINNUM;ibin++) hMCSignalplot->SetBinContent(ibin+1,hMCSignal->GetBinContent(ibin+1));
  for(int ibin=0;ibin<BINNUM;ibin++) hMCSwappedplot->SetBinContent(ibin+1,hMCSwapped->GetBinContent(ibin+1));
  f->FixParameter(4,1.);
  f->FixParameter(1,0.145491);
  f->FixParameter(10,0);

  f->SetParLimits(0,0,1.e+5);
  f->SetParLimits(6,0,1.);
  f->SetParLimits(12,0,1.);
  f->SetParLimits(2,3.e-4,1.e-3);
  f->SetParameter(2,5.e-4);
  f->SetParLimits(11,1.6e-4,3.e-4);//1.5e-4 keyong
  f->SetParameter(11,2.e-4);
  f->SetParLimits(5,1.e-3,1.6e-3);
  f->SetParameter(5,1.e-3);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  f->ReleaseParameter(1);
  f->SetParLimits(1,minmass,maxmass);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",minmass,maxmass);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",minmass,maxmass);

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(5,f->GetParameter(5));
  f->FixParameter(11,f->GetParameter(11));
  f->FixParameter(6,f->GetParameter(6));
  f->FixParameter(12,f->GetParameter(12));
  f->FixParameter(4,0);
  f->SetParLimits(3,2.e-4,2.e-3);
  f->SetParameter(3,1.e-3);

  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",BINMIN,BINMAX);
  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",BINMIN,BINMAX);
  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",minmass,maxmass);
  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",minmass,maxmass);

  f->FixParameter(4,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(3,f->GetParameter(3));

  f->SetParLimits(7,5.e-4,1.e-2);
  f->SetParameter(7,1.6e-3);
  f->SetParLimits(8,0.,15.);
  f->SetParameter(8,0.35);
  f->SetParLimits(9,-2.e+1,2.e+1);
  f->SetParameter(9,13.);

  f->ReleaseParameter(10);
  f->SetParLimits(10,0,1.e+6);

  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);

  f->ReleaseParameter(1);
  f->SetParLimits(1,minmass,maxmass);
  f->SetParameter(1,f->GetParameter(1));
  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);

  TF1* background = new TF1(Form("background_5p_%.0f",ptmin),"[3]*((1-exp((0.13957-x)/[0]))*pow(x/0.13957,[1])+[2]*(x/0.13957-1))");
  background->SetParameters(f->GetParameter(7),f->GetParameter(8),f->GetParameter(9),f->GetParameter(10));
  background->SetRange(BINMIN,BINMAX);
  background->SetLineColor(4);
  background->SetLineWidth(3);
  background->SetLineStyle(2);

  TF1* mass = new TF1(Form("fmass_5p_%.0f",ptmin),"[0]*[3]*([5]*([7]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[7])*Gaus(x,[1],[6])/(sqrt(2*3.14159)*[6]))+(1-[5])*Gaus(x,[1],[4])/(sqrt(2*3.14159)*[4]))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(4),f->GetParameter(5),f->GetParameter(6),f->GetParameter(11),f->GetParameter(12));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(4));
  mass->SetParError(4,f->GetParError(5));
  mass->SetParError(5,f->GetParError(6));
  mass->SetRange(BINMIN,BINMAX);
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);

  TF1* massSwap = new TF1(Form("fmassSwap_5p_%.0f",ptmin),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(4),f->GetParameter(3));
  massSwap->SetRange(BINMIN,BINMAX);
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);

  h->SetXTitle("M_{K#pi#pi#pi#pi}-M_{K#pi#pi#pi} (GeV/c^{2})");
  h->SetYTitle("Entries / (0.4 MeV/c^{2})");
  h->SetStats(0);
  h->SetAxisRange(0,h->GetMaximum()*1.3,"Y");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  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");
  mass->Draw("same");
  massSwap->Draw("same");
  background->Draw("same");
  f->Draw("same");

  if(plotgenmatch&&(isData==MC_MB||isData==MC))
    {
      hMCSignalplot->SetMarkerSize(0.8);
      hMCSignalplot->SetMarkerColor(kMagenta+2);
      hMCSignalplot->Draw("psame");
      hMCSwappedplot->SetMarkerSize(0.8);
      hMCSwappedplot->SetMarkerColor(kGray+2);
      hMCSwappedplot->Draw("psame");
    }

  Float_t yield = mass->Integral(BINMIN,BINMAX)/BINWID;
  Float_t yieldErr = mass->Integral(BINMIN,BINMAX)/BINWID*mass->GetParError(0)/mass->GetParameter(0);
  cout<<mass->GetParameter(0)<<" "<<mass->Integral(BINMIN,BINMAX)<<endl;

  TLatex* tex;
  TLegend* leg = new TLegend(0.60,0.57,0.85,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry((TObject*)0,"D* D^{0}(K#pi#pi#pi)#pi",NULL);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D*^{+}+D*^{-} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  tex = new TLatex(0.61,0.52,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  tex = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.65,0.93, "PP #sqrt{s_{NN}} = 5.02 TeV");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.20,0.79,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();
  tex = new TLatex(0.20,0.84,Form("p_{T} > %.1f GeV/c",ptmin));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  c->SaveAs(Form("plots/pp/fitDstar5p/DMass_%s_%.0f.pdf",texData[isData].Data(),ptmin));

  return mass;
}
Exemple #24
0
void fitLOW(const char *run="19020_19035",
	    int arm=0, int lyr=2, int sen=21, int mpd=0,
	    bool draw=true,
	    //int old_xfit_min=12, int old_xfit_max=82,
	    int old_xfit_min=8, int old_xfit_max=62,
	    double xfit_min=2.5, double xfit_max=18.5) {
  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  TString inname = Form("%s/adc/LO_ARM%d_LYR%d_S%d_M%d.root",run,arm,lyr,sen,mpd);
  TString prename = Form("HI_ARM%d_LYR%d_S%d_M%d_%d_%d",arm,lyr,sen,mpd,old_xfit_min,old_xfit_max);
  TString outname = Form("LO_ARM%d_LYR%d_S%d_M%d_%.0f_%.0f",arm,lyr,sen,mpd,xfit_min,xfit_max);
  TFile *file = new TFile( inname.Data() );
  cout << inname.Data() << endl;
  cout << prename.Data() << endl;
  cout << outname.Data() << endl;

  TF1 *fitH = GetFit(run,prename.Data(),outname.Data());
  if(!fitH) return;
  if(lda<1) return;

  // data
  TH1D *out = (TH1D*) file->Get("out");
  double ymax = out->GetMaximum();
  int entries = out->Integral(xfit_min,xfit_max);
  out->Sumw2();
  out->SetLineColor(kBlack);
  out->SetMarkerStyle(20);
  out->SetTitle("");

  // fit
  TCanvas *main = new TCanvas("main","main");
  main->SetLogy(1);
  out->Draw("HE");
  out->GetYaxis()->SetRangeUser(0.5,ymax);
  out->GetXaxis()->SetRangeUser(-4.5,50.5);

  out->Fit(fitH,"QENIML","",xfit_min,xfit_max);
  TF1 *MIPH1 = GetMIP(fitH,1,kCyan-3);
  TF1 *MIPH2 = GetMIP(fitH,2,kGreen-3);
  TF1 *MIPH3 = GetMIP(fitH,3,kOrange-3);
  TF1 *MIPH4 = GetMIP(fitH,4,kMagenta-3);

  double sLDA = fitH->GetParameter(0);
  double eLDA= fitH->GetParError(0);
  double sSGM = fitH->GetParameter(1);
  double eSGM = fitH->GetParError(1);
  double ncs = fitH->GetChisquare()/fitH->GetNDF();

  double ldalow = lda*sLDA;
  double sgmlow = sgm*sSGM;

  double eldalow = TMath::Abs(ldalow)*TMath::Sqrt( elda/lda*elda/lda + eLDA/sLDA*eLDA/sLDA );
  double esgmlow = TMath::Abs(sgmlow)*TMath::Sqrt( esgm/sgm*esgm/sgm + eSGM/sSGM*eSGM/sSGM );

  ofstream outfit;
  outfit.open( Form("%s/fit/%s.dat",run,outname.Data()) );
  outfit << sLDA << " " << eLDA << endl;
  outfit << sSGM << " " << eSGM << endl;
  outfit << ldalow << endl;
  outfit << sgmlow << endl;
  outfit << ncs << endl;
  outfit.close();

  // draw
  if(!draw) return;

  MIPH1->Draw("SAME");
  MIPH2->Draw("SAME");
  MIPH3->Draw("SAME");
  MIPH4->Draw("SAME");
  fitH->SetRange(xfit_min,xfit_max);
  fitH->Draw("SAME");
  TLatex *text = new TLatex();
  text->DrawLatex(1, TMath::Exp(1.03*TMath::Log(ymax)), inname );
  text->DrawLatex(20, TMath::Exp(0.93*TMath::Log(ymax)), Form("Entries  %d",entries) );
  text->SetTextColor(kRed-3);
  text->DrawLatex(44, TMath::Exp(0.83*TMath::Log(ymax)),  Form("#chi^{2} / NDF  %.2f",ncs) );
  text->DrawLatex(20, TMath::Exp(0.83*TMath::Log(ymax)),  Form("S_{#lambda}  %.3f #pm %.3f",sLDA,eLDA) );
  text->DrawLatex(20, TMath::Exp(0.73*TMath::Log(ymax)),  Form("S_{#sigma}  %.3f #pm %.3f",sSGM,eSGM) );
  text->SetTextColor(kBlue-3);
  text->DrawLatex(20, TMath::Exp(0.60*TMath::Log(ymax)),  Form("#lambda^{H}  %.1f #pm %.1f   #rightarrow  #lambda^{L}  %.1f #pm %.1f",lda,elda,ldalow,eldalow) );
  text->DrawLatex(20, TMath::Exp(0.50*TMath::Log(ymax)),  Form("#sigma^{H}  %.1f #pm %.1f   #rightarrow  #sigma^{L}  %.1f #pm %.1f",sgm,esgm,sgmlow,esgmlow) );
  text->SetTextColor(kBlack);
  text->SetTextSize(0.04);
  main->SaveAs( Form("%s/fiteps/%s.png",run,outname.Data()), "png" );
  return;
}
Exemple #25
0
TH2 *
ReturnCorrFromFit(TH2 *hcorr)
{

  gStyle->SetOptStat(kFALSE);
  gStyle->SetOptFit(kTRUE);

  TObjArray *oa = new TObjArray();
  hcorr->FitSlicesX(0, 0, -1, 0, "QNR", oa);

  TCanvas *cFit = new TCanvas("cFit", "cFit");
  cFit->Divide(2, 2);

  TF1 *fMean = new TF1("fMean", "[0] + [1] * TMath::Power(x, [2])", 1., 100.);
  fMean->SetParameter(0, 0.);
  fMean->SetParameter(1, 1.);
  fMean->SetParameter(2, 1.);
  TH1 *hMean = (TH1 *)oa->At(1);
  hMean->Fit(fMean, "0q", "I", 1., 100.);
  cFit->cd(1)->SetLogx();
  cFit->cd(1)->SetLogy();
  hMean->Draw();
  fMean->Draw("same");

  TF1 *fSigma = new TF1("fSigma", "[0] + [1] * TMath::Power(x, [2])", 1., 100.);
  fSigma->SetParameter(0, 0.);
  fSigma->SetParameter(1, 1.);
  fSigma->SetParameter(2, 0.5);
  TH1 *hSigma = (TH1 *)oa->At(2);
  hSigma->Fit(fSigma, "0q", "", 1., 100.);
  cFit->cd(3)->SetLogx();
  cFit->cd(3)->SetLogy();
  hSigma->Draw();
  fSigma->Draw("same");

  cFit->cd(2)->SetLogx();
  cFit->cd(2)->SetLogy();
  cFit->cd(2)->SetLogz();
  hcorr->Draw("colz");

  TH2 *hcorrfit = (TH2 *)hcorr->Clone("hcorrfit");
  //  hcorrfit->Reset();
  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    Float_t cent = hcorr->GetXaxis()->GetBinCenter(i + 1);
    Float_t mean = fMean->Eval(cent);
    Float_t sigma = fSigma->Eval(cent);
    if (cent < 25 || cent > 100) continue;
    for (Int_t j = 0; j < 10000; j++) {
      Float_t val = gRandom->Gaus(mean, sigma);
      if (val <= 0.) continue;
      hcorrfit->Fill(val, cent);
    }
  }

  cFit->cd(4)->SetLogx();
  cFit->cd(4)->SetLogy();
  cFit->cd(4)->SetLogz();
  hcorrfit->Draw("colz");

  return hcorrfit;
}
TF1* fitDstar5prongs(TTree* nt, Double_t ptmin, Double_t ptmax)
{
  static int count5p=0;
  count5p++;
  
  TCanvas* c = new TCanvas(Form("c_5p_%d",count5p),"",600,600);
  TH1D* h = new TH1D(Form("h_5p_%d",count5p),"",60,0.140,0.160);
  TF1* f = new TF1(Form("f_5p_%d",count5p),"[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);
  nt->Project(Form("h_5p_%d",count5p),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f&&Dpt<%f)",weight.Data(),seldata5p.Data(),triggerselection[isData].Data(),ptmin,ptmax));   
    
  f->SetLineColor(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);
  f->SetParLimits(5,0,100000);
  h->Fit(Form("f_5p_%d",count5p),"LL");
  h->Fit(Form("f_5p_%d",count5p),"LL");
  h->Fit(Form("f_5p_%d",count5p),"LL","",minmass3prong,maxmass3prong);
  f->ReleaseParameter(6);
  f->ReleaseParameter(7);
  f->ReleaseParameter(9);
  f->SetParLimits(6,0.144,0.147);
  f->SetParLimits(7,1e-4,9e-4);
  f->SetParLimits(9,1e-4,9e-4);
  h->Fit(Form("f_5p_%d",count5p),"LL","",0.142,0.148);
  h->Fit(Form("f_5p_%d",count5p),"LL","",0.142,0.16);
  h->Fit(Form("f_5p_%d",count5p),"LL","",0.142,0.16);
  h->Fit(Form("f_5p_%d",count5p),"LL","",0.141,0.16);
  h->Fit(Form("f_5p_%d",count5p),"LL","",0.141,0.16);
  h->Fit(Form("f_5p_%d",count5p),"LL","",0.141,0.16);

  TF1* background = new TF1(Form("background_5p_%d",count5p),"[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x");
  background->SetParameter(0,f->GetParameter(0));
  background->SetParameter(1,f->GetParameter(1));
  background->SetParameter(2,f->GetParameter(2));
  background->SetParameter(3,f->GetParameter(3));
  background->SetParameter(4,f->GetParameter(4));
  background->SetLineColor(4);
  background->SetRange(minmass3prong,maxmass3prong);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass_5p_%d",count5p),"[0]*((1-[3])*TMath::Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+[3]*TMath::Gaus(x,[1],[4])/(sqrt(2*3.14159)*[4]))");
  mass->SetParameters(f->GetParameter(5),f->GetParameter(6),f->GetParameter(7),f->GetParameter(8),f->GetParameter(9));
  mass->SetParError(0,f->GetParError(5));
  mass->SetParError(1,f->GetParError(6));
  mass->SetParError(2,f->GetParError(7));
  mass->SetParError(3,f->GetParError(8));
  mass->SetParError(4,f->GetParError(9));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
    
  h->SetXTitle("M_{K#pi#pi#pi#pi}-M_{K#pi#pi#pi} (GeV/c^{2})");
  h->SetYTitle("Entries / (1/3 MeV/c^{2})");
  h->SetStats(0);
  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(0.142,0.152);	
  mass->Draw("same");
  f->Draw("same");
  
  Double_t yield = mass->Integral(minmass5prong,maxmass5prong)/binwidth5prong;
  Double_t yieldErr = mass->Integral(minmass5prong,maxmass5prong)/binwidth5prong*mass->GetParError(0)/mass->GetParameter(0);

  TLatex* tex;
  TLegend* leg = new TLegend(0.60,0.62,0.85,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry((TObject*)0,"D* D^{0}(K#pi#pi#pi)#pi",NULL);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D*^{+}+D*^{-} Signal","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  tex = new TLatex(0.61,0.58,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  tex = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.65,0.93, "PP #sqrt{s_{NN}} = 5.02 TeV");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.20,0.79,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();
  tex = new TLatex(0.20,0.84,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  c->SaveAs(Form("plots/pp/DMass_%s_5prongs-%d.pdf",texData[isData].Data(),count5p));
  
  return mass;
}
Exemple #27
0
void unfoldPt(int mode=0)
{

   // Matched Tracklets
   TFile *inf = new TFile("match-10TeV-12.root");
   TNtuple *nt = (TNtuple*)inf->FindObjectAny("nt");

   // Test sample
   TFile *infTest = new TFile("./TrackletTree-Run123596.root");
   TNtuple *ntTest = (TNtuple*)infTest->FindObjectAny("TrackletTree12");
   
   TFile *pdfFile;
   if (mode==0) pdfFile = new TFile("pdf.root","recreate");
           else pdfFile = new TFile("pdf.root");

   double nPtBin=15;
   double minPt=log(0.05);
   double maxPt=log(10);
   double nDphiBin=600;
   double maxDphi=0.4;
   
   char* mycut = Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f",minPt,maxPt);
   char* mycut1=Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f&&abs(eta-eta1)<0.01&&abs(deta)<0.01",minPt,maxPt);

   TH2F *h;
   TH1F *hdphi = new TH1F("hdphi","",nDphiBin,0,maxDphi);
   TH1F *hdphi2;
   TH1F *hpt;
   TH1F *hptH = new TH1F("hptH","",nPtBin,minPt,maxPt);
   
   TH1F *hptUnfold = new TH1F("hptUnfold","",nPtBin,minPt,maxPt);
   TH1F *hptMC = new TH1F("hptMC","",nPtBin,minPt,maxPt);
   TH1F *hptTemp = new TH1F("hptTemp","",nPtBin,minPt,maxPt);

   // Delta phi as a function of matched genparticle transverse momentum
   TCanvas *c = new TCanvas("c","",600,600);
   
   if (mode == 0) {
      h = new TH2F("h","",nPtBin,minPt,maxPt,nDphiBin,0,maxDphi);
      hdphi2 = new TH1F("hdphiMC","",nDphiBin,0,maxDphi);
      hpt = new TH1F("hpt","",nPtBin,minPt,maxPt);      
      h->SetXTitle("ln(P_{T}) GeV/c");
      h->SetYTitle("|#Delta#phi|");
      nt->Draw("abs(dphi):log(pt)>>h",mycut1,"col");
      // used to generate pdf
      nt->Draw("abs(dphi)>>hdphiMC",mycut,"");
      nt->Draw("log(pt)>>hpt",mycut,"");
      h->Write();      
      hpt->Write();      
      hdphi2->Write();      
   } else {
      h = (TH2F*) pdfFile->FindObjectAny("h");
      hdphi2 = (TH1F*) pdfFile->FindObjectAny("hdphiMC");
      hpt = (TH1F*) pdfFile->FindObjectAny("hpt");
   }
   // Delta phi fit
   TCanvas *c2 = new TCanvas("c2","",600,600);
   c2->SetLogy();
   c2->SetLogx();

 
   // dphi for unfolding and MC truth:  
   ntTest->Draw("abs(dphi)>>hdphi","abs(eta1)<2&&abs(deta)<0.1","",200000);
   ntTest->Draw("log(pt)>>hptH",mycut,"",200000);
   
   histFunction2D *myfun = new histFunction2D(h);
   
   TF1 *test = new TF1("histFun",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);
   TF1 *test2 = new TF1("histFunMC",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);

   for (int i=0;i<nPtBin+1;i++)
   {  
      test->SetParameter(i,1);   
   }


   hdphi2->SetXTitle("|#Delta#phi|");
   hdphi2->SetYTitle("Arbitrary Normalization");
   hdphi2->Fit("histFunMC","M");

   hdphi->SetXTitle("|#Delta#phi|");
   hdphi->SetYTitle("Arbitrary Normalization");
   hdphi->Fit("histFun","M");
   hdphi->SetStats(0);
   hdphi->Draw();

   
   for (int i=0;i<nPtBin+1;i++) {
      TF1 *testPlot = new TF1(Form("histFun%d",i),myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);

      testPlot->SetParameter(i,test->GetParameter(i));
      testPlot->SetLineColor(i+2);
      testPlot->Draw("same");
   }
   
   int total=0,totalMC=0;


   for (int i=0;i<nPtBin;i++){
      if (test->GetParameter(i)==0) continue;
      hptUnfold->SetBinContent(i+1,fabs(test->GetParameter(i)));
      hptUnfold->SetBinError(i+1,test->GetParError(i));

      hptMC->SetBinContent(i+1,fabs(test2->GetParameter(i)));
      hptMC->SetBinError(i+1,test2->GetParError(i));

      total+=fabs(test->GetParameter(i));
      totalMC+=fabs(test2->GetParameter(i));
   }

   hptUnfold->SetEntries(total);
   hptMC->SetEntries(totalMC);
   
   TCanvas *c3 = new TCanvas("c3","",600,600);
   hpt->Sumw2();
   hptH->Sumw2();
   //hptMC->Sumw2();
   
   double normMC=0;
   double norm=0;
   double normTruth=0;
   

   hptUnfold->SetMarkerColor(2);
   hptUnfold->SetMarkerStyle(4);
//   hptUnfold->Scale(1./hptUnfold->GetEntries());
   TH1F *hptCorrected = (TH1F*)hptUnfold->Clone();
   hptCorrected->SetName("hptCorrected");
   hptMC->Divide(hpt);
   hptCorrected->Divide(hptMC);
   
   for (int i=0;i<nPtBin;i++){
      if (hptMC->GetBinContent(i)<=0.001)hptCorrected->SetBinContent(i,0);
   }
   hptCorrected->Scale(1./(hptCorrected->GetSum()));
   hptCorrected->SetMarkerStyle(20);

   hpt->Scale(1./hpt->GetEntries());
   if (hptH->GetEntries())hptH->Scale(1./hptH->GetEntries());

   hptTemp->SetXTitle("ln(P_{T}) GeV/c");
   hptTemp->SetYTitle("Arbitrary Normalization");
   hptTemp->Draw();
   

   hptH->SetXTitle("ln(P_{T}) GeV/c");
   hptH->SetYTitle("Arbitrary Normalization");
   hptH->Draw("hist");
   hptH->SetLineColor(4);
   
   hpt->Draw("hist same ");
   
   hptCorrected->Draw("same");
   
   TH1F *hptUnfoldRatio = (TH1F*)hptUnfold->Clone();
   hptUnfoldRatio->SetName("hptUnfoldRatio");
   hptUnfoldRatio->Scale(1./hptUnfoldRatio->GetSum());
   //hptUnfoldRatio->Divide(hptH);

   TH1F *hptCorrectedRatio = (TH1F*)hptCorrected->Clone();
   hptCorrectedRatio->SetName("hptCorrectedRatio");
   hptCorrectedRatio->SetMarkerColor(2);
   //hptCorrectedRatio->Divide(hptH);

   TCanvas *c4 = new TCanvas("c4","",600,600);
   TLine *l = new TLine(-2.5,1,2.5,1);
   hptUnfoldRatio->Draw();
   hptMC->Draw("same");
   hptCorrectedRatio->Draw("same");
   l->Draw("same");
}
int makeInvMassHistosNoBGKK(){
    //Set global style stuff
    gROOT->Reset();
    gROOT->SetStyle("Plain");
    gStyle->SetPalette(1);
    gStyle->SetCanvasColor(kWhite);
    gStyle->SetCanvasBorderMode(0);
    gStyle->SetPadBorderMode(0);
    gStyle->SetTitleBorderSize(0);
    gStyle->SetOptStat(0);
    gStyle->SetOptFit(1);
    gStyle->SetErrorX(0);
    gStyle->SetTitleW(0.9);
    gStyle->SetTitleSize(0.05, "xyz");
    gStyle->SetTitleSize(0.06, "h");

    int NUM_PT_BINS = 20;
    int NUM_MASS_BINS = 1000;
    double MASS_LOW = 0.0;
    double MASS_HIGH = 2.0;
    string particles [8];
    particles[0] = "K*^{+} + K*^{0}";
    particles[1] = "K*^{-} + #bar{K}*^{0}";
    particles[2] = "K*^{+}";
    particles[3] = "K*^{-}";
    particles[4] = "K*^{0}";
    particles[5] = "#bar{K}*^{0}";
    particles[6] = "K*^{0} + #bar{K}*^{0}";
    particles[7] = "K*^{+} + K*^{-}";
//at decay point
//    string folder = "/Users/jtblair/Downloads/kstar_data/decayed/pt02/";
//reconstructed
    string folder = "/Users/jtblair/Downloads/kstar_data/reconstructed/pt02/";

    string files[20];
    files[0] = "invm_[0.0,0.2].dat";
    files[1] = "invm_[0.2,0.4].dat";
    files[2] = "invm_[0.4,0.6].dat";
    files[3] = "invm_[0.6,0.8].dat";
    files[4] = "invm_[0.8,1.0].dat";
    files[5] = "invm_[1.0,1.2].dat";
    files[6] = "invm_[1.2,1.4].dat";
    files[7] = "invm_[1.4,1.6].dat";   
    files[8] = "invm_[1.6,1.8].dat";
    files[9] = "invm_[1.8,2.0].dat";
    files[10] = "invm_[2.0,2.2].dat";
    files[11] = "invm_[2.2,2.4].dat";
    files[12] = "invm_[2.4,2.6].dat";
    files[13] = "invm_[2.6,2.8].dat";
    files[14] = "invm_[2.8,3.0].dat";
    files[15] = "invm_[3.0,3.2].dat";
    files[16] = "invm_[3.2,3.4].dat";
    files[17] = "invm_[3.4,3.6].dat";
    files[18] = "invm_[3.6,3.8].dat";
    files[19] = "invm_[3.8,4.0].dat";
/*
    string files[8];
    files[0] = "invm_[0.0,0.5].dat";
    files[1] = "invm_[0.5,1.0].dat";
    files[2] = "invm_[1.0,1.5].dat";
    files[3] = "invm_[1.5,2.0].dat";
    files[4] = "invm_[2.0,2.5].dat";
    files[5] = "invm_[2.5,3.0].dat";
    files[6] = "invm_[3.0,3.5].dat";
    files[7] = "invm_[3.5,4.0].dat";
*/

    Int_t PARTICLE_NUM = 5;

    TFile *output = new TFile("20170721_KKbarAdded2_fixedwidth42_recon_pf100_scaled_error05.root", "RECREATE");

    TH1D *kstar0mass = new TH1D("kstar0mass", Form("Fit value of M*_{0} vs. p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS, 0.0, 4.0);
    TH1D *kstar0width = new TH1D("kstar0width", Form("#Gamma_{tot}(M=M*_{0}) vs p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS, 0.0, 4.0);
    TH1D *kstar0collWidth = new TH1D("kstar0collWidth", Form("Fit value of #Gamma_{coll} component vs. p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS,0.0, 4.0);
    TH1D *kstar0decWidth = new TH1D("kstar0decWidth", Form("#Gamma_{dec}(M=M*_{0}) component vs. p_{T} for %s;p_{T} (GeV/c);Width (GeV/c^2)", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS,0.0, 4.0);
   
    kstar0mass->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0mass->GetYaxis()->SetTitle("Mass (GeV/c^{2})");
    kstar0width->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0width->GetYaxis()->SetTitle("Width (GeV/c^2)");
    kstar0collWidth->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0collWidth->GetYaxis()->SetTitle("Width (GeV/c^2)");

    kstar0mass->SetStats(kFALSE);
    kstar0width->SetStats(kFALSE);
    kstar0collWidth->SetStats(kFALSE);
    kstar0decWidth->SetStats(kFALSE);

    TF1 *massline = new TF1("massline", "[0]", 0.0, 4.0);
    massline->SetParameter(0, 0.892);
    massline->SetLineColor(2);
    massline->SetLineStyle(7);

    TF1 *widthline = new TF1("widthline", "[0]", 0.0, 4.0);
    widthline->SetParameter(0, 0.042);

    double mass = 0.0, width = 0.0, collWidth = 0.0, massBG=0.0;
    double massError = 0.0, widthError= 0.0, collWidthError = 0.0, massBGError=0.0;

    TCanvas *canvas[9];
    TCanvas *diffCanvas[9];
    TPaveStats *st;
    TPad *pad;

    //ofstream integrals;
    //integrals.open("kstarbar_integrals.txt");

    for(int nfile = 0; nfile < NUM_PT_BINS; nfile++){
        double meanPT = (double)(nfile*2+1)/10.0;
        string filename = folder+files[nfile];
        string ptLower = filename.substr(filename.find("[")+1, 3);
        string ptHigher = filename.substr(filename.find(",")+1, 3);   
        TH1D* histos[8];
        TH1D* newHistos[8];
        TH1D* diffHistos[8];
        TH1D* bg[8];
        for(int i=0; i<8; i++){
            if(nfile<5){
                histos[i] = new TH1D(Form("ptbin0%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), NUM_MASS_BINS, MASS_LOW, MASS_HIGH);
            newHistos[i] = new TH1D(Form("newptbin0%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), 250, MASS_LOW, MASS_HIGH);

            }else{
                histos[i] = new TH1D(Form("ptbin%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), NUM_MASS_BINS, MASS_LOW, MASS_HIGH);
                newHistos[i] = new TH1D(Form("newptbin%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), 250, MASS_LOW, MASS_HIGH);

            }
            histos[i]->GetXaxis()->SetTitle("Invariant Mass (GeV/c^{2})");
            histos[i]->GetYaxis()->SetTitle("Counts");
        }

        ifstream input;
        input.open(filename.c_str());
        string line = "";
        if(input.good()){
            getline(input, line);
        }

        double massBin=0.0;
        double invMass[8];
        for(int i=0; i<8; i++){
            invMass[i] = 0.0;
        }
        int lineNumber = 1;
        while(1){
            input >> massBin >> invMass[0] >> invMass[1] >> invMass[2] >> invMass[3] >> invMass[4] >> invMass[5] >> invMass[6] >> invMass[7];
            if(!input.good())break;
            for(int i =0; i<8; i++){
                histos[i]->SetBinContent(lineNumber, invMass[i]/500.0);
            }
            if(lineNumber > 440 && lineNumber < 460 && nfile==6){
//               printf("mass: %.12f invMass[6]: %.12f\n", massBin, invMass[6]);
            }
            lineNumber++;
        }
         

        printf("****** Fits for file: %s ******\n", filename.c_str());
        for(int i=PARTICLE_NUM; i<PARTICLE_NUM+1; i++){
           
            //add the K*0 distribution to the K*0bar (K*0 = 4 for decay, K*0 = 3 for reconstructed)
            histos[i]->Add(histos[3]);
            if(nfile==0){
                canvas[i] = new TCanvas(Form("c%i", i),Form("c%i", i), 0,0,900,900);
                canvas[i]->Divide(5,4);
                diffCanvas[i] = new TCanvas(Form("diffC%i", i),Form("diffC%i", i), 0,0,900,900);
                diffCanvas[i]->Divide(5,4);
            }
            //rebin
            //histos[i]->Sumw2();
            histos[i]->Rebin(4);

            //Fixing the errors to a percentage of the signal region:
            for(int ibin=1; ibin < histos[i]->GetNbinsX(); ibin++){
                histos[i]->SetBinError(ibin, histos[i]->GetBinContent((int)(0.892*(250.0/2.0)))*0.05);
                newHistos[i]->SetBinContent(ibin, histos[i]->GetBinContent(ibin));
                newHistos[i]->SetBinError(ibin, histos[i]->GetBinError(ibin));
            }
            
            pad = (TPad*)canvas[i]->cd(nfile+1);
            histos[i]->SetLineColor(1);
            histos[i]->SetLineWidth(1);
            histos[i]->GetXaxis()->SetRangeUser(0.7, 1.2);
            histos[i]->GetYaxis()->SetRangeUser(0, 1.5*histos[i]->GetBinContent(histos[i]->GetMaximumBin()));
            //histos[i]->SetStats(kFALSE);
            
            //histos[i]->Draw("HIST");

            printf("mean PT: %f\n", meanPT);

            TF1 *fit = new TF1(Form("fitPTbin%d00particle%d", nfile*2+1, i), FitFunRelBW, 0.68, 1.05, 5);
            //TF1 *fit = new TF1(Form("fitPTbin%d00particle%d", nfile*2+1, i), "gaus(0)", 0.86, 0.92);


            fit->SetParNames("BW Area", "Mass", "Width", "PT", "Temp");
            fit->SetParameters(TMath::Power(10.0, (float)(nfile)/1.7), 0.89, 0.1, 0.5, 0.130);
            //fit->SetParNames("BW Area", "Mass", "Width");
            //fit->SetParameters(100, 0.89, 0.0474);
            //fit->SetParLimits(0, -10, 1.5e9);
            Float_t max = histos[i]->GetXaxis()->GetBinCenter(histos[i]->GetMaximumBin());
            //if(max < 0.91 && max > 0.892){
            //    fit->SetParLimits(1, max-0.001, max+0.001);
            //}else{
                fit->SetParLimits(1, 0.82, 0.98);
            //}
            //fit->SetParLimits(2, 0.005, 0.15);
            fit->FixParameter(2, 0.042);
            fit->FixParameter(3, meanPT);
            //fit->SetParLimits(4, 0.05, 0.2);
            fit->FixParameter(4, 0.100001);
            fit->SetLineColor(2);

            printf("%s\n", fit->GetName());

            histos[i]->Fit(Form("fitPTbin%d00particle%d", nfile*2+1, i), "BRIM", "SAME");
            TVirtualFitter *fitter = TVirtualFitter::GetFitter();
           
            histos[i]->SetStats(1);
            histos[i]->Draw();
            gPad->Update();
            pad->Update();
            st = (TPaveStats*)histos[i]->FindObject("stats");
            st->SetX1NDC(0.524);
            st->SetY1NDC(0.680);
            st->SetX2NDC(0.884);
            st->SetY2NDC(0.876);
            //fit->Draw("SAME");
            //histos[i]->Draw();
            gPad->Update();
            pad->Update();
            printf("\n");
    
            diffHistos[i] = (TH1D*)histos[i]->Clone(Form("diffPTbin%d00particl%d", nfile*2+1, i));
            diffHistos[i]->Add(fit, -1);
            diffCanvas[i]->cd(nfile+1);
            diffHistos[i]->Draw("HIST E");
            diffHistos[i]->Write();

            //counting bins
            Float_t integral = histos[i]->Integral(1, 500)*500.0;
            //integrals << integral <<" \n";
            histos[i]->Write();
            fit->Write();
            //Do mass and width vs. pT plots just for K*0
            if(i==PARTICLE_NUM){
                mass = fit->GetParameter(1);
                massError = fit->GetParError(1);

                collWidth = fit->GetParameter(2);
                collWidthError = fit->GetParError(2);

                width = Gamma(mass, collWidth);

                kstar0mass->SetBinContent(nfile+1, mass);
                kstar0mass->SetBinError(nfile+1, massError);

                kstar0width->SetBinContent(nfile+1, width);
                Double_t widthError = TMath::Sqrt((GammaDerivative(mass)**2)*fitter->GetCovarianceMatrixElement(1,1) + fitter->GetCovarianceMatrixElement(2,2) + 2.0*GammaDerivative(mass)*fitter->GetCovarianceMatrixElement(1,2));
                kstar0width->SetBinError(nfile+1, widthError);

                kstar0collWidth->SetBinContent(nfile+1, collWidth);
                kstar0collWidth->SetBinError(nfile+1, collWidthError);

                kstar0decWidth->SetBinContent(nfile+1, width - collWidth);
                Double_t decWidthError = TMath::Sqrt((GammaDerivative(mass)**2)*fitter->GetCovarianceMatrixElement(1,1));
                kstar0decWidth->SetBinError(nfile+1, decWidthError);

                if(nfile==4){
                    TCanvas *singlecanvas = new TCanvas("singlecanvas", "singlecanvas", 0,0,600,600);
                    singlecanvas->cd();
                    printf("Got here! \n");
                    histos[i]->Draw("HIST E SAME");

                    fit->SetLineColor(8);
                    fit->SetLineStyle(1);
                    
                    fit->Draw("SAME");
                    if(fitter){
                        printf("sig11: %f, sig12: %f, sig21: %f, sig22: %f GammaDer(0.8): %f GammaDer(0.85): %f GammaDer(0.9): %f\n", TMath::Sqrt(fitter->GetCovarianceMatrixElement(1,1)), fitter->GetCovarianceMatrixElement(2,1), fitter->GetCovarianceMatrixElement(1,2), TMath::Sqrt(fitter->GetCovarianceMatrixElement(2,2)), GammaDerivative(0.8), GammaDerivative(0.85), GammaDerivative(0.9));
                    }
                }
            }
        }
        printf("************************************************************\n");
         
    }
        //integrals.close();
/*
    TH2D *gammaPlot = new TH2D("gammaPlot", "#Gamma_{tot}(M_{0}*);M_{0}*;#Gamma_{coll};#Gamma_{tot}", 100, 0.82, 0.9, 100, 0.0, 0.08);
    for(int im = 0; im<100; im++){
        for(int ig = 0; ig < 100; ig++){
            gammaPlot->SetBinContent(im+1, ig+1, Gamma(((0.9-0.82)/(100.0))*((double)(im)) + 0.82, ((0.08)/100.0)*((double)(ig))));
        }
    }

    TH1D *gammaMassDpnd = gammaPlot->ProjectionX("gammaMassDpnd");
*/
    TCanvas *masscanvas = new TCanvas("masscanvas", "masscanvas", 50,50, 600, 600);
    masscanvas->cd();
    kstar0mass->Draw();
    massline->Draw("SAME");
    masscanvas->Write();

    for(int i=PARTICLE_NUM; i<PARTICLE_NUM+1; i++){
        canvas[i]->Write();
    }
    kstar0mass->Write();
    kstar0collWidth->Write();
    kstar0decWidth->Write();
    kstar0width->Write();
//    gammaPlot->Write();
//    gammaMassDpnd->Write();
}
Exemple #29
0
void FFT()
{

//This tutorial illustrates the Fast Fourier Transforms interface in ROOT.
//FFT transform types provided in ROOT:
// - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) 
//                  in one or more dimensions, -1 in the exponent
// - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) 
//                  in one or more dimensions, +1 in the exponent
// - "R2C"        - a real-input/complex-output discrete Fourier transform (DFT)
//                  in one or more dimensions,
// - "C2R"        - inverse transforms to "R2C", taking complex input 
//                  (storing the non-redundant half of a logically Hermitian array) 
//                  to real output
// - "R2HC"       - a real-input DFT with output in ¡Èhalfcomplex¡É format, 
//                  i.e. real and imaginary parts for a transform of size n stored as
//                  r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1
// - "HC2R"       - computes the reverse of FFTW_R2HC, above
// - "DHT"        - computes a discrete Hartley transform
// Sine/cosine transforms:
//  DCT-I  (REDFT00 in FFTW3 notation)
//  DCT-II (REDFT10 in FFTW3 notation)
//  DCT-III(REDFT01 in FFTW3 notation)
//  DCT-IV (REDFT11 in FFTW3 notation)
//  DST-I  (RODFT00 in FFTW3 notation)
//  DST-II (RODFT10 in FFTW3 notation)
//  DST-III(RODFT01 in FFTW3 notation)
//  DST-IV (RODFT11 in FFTW3 notation)
//First part of the tutorial shows how to transform the histograms
//Second part shows how to transform the data arrays directly
//Authors: Anna Kreshuk and Jens Hoffmann


//********* Histograms ********//


   //prepare the canvas for drawing
   TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600);
   myc->SetFillColor(45);
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99);
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99);
   TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65);
   TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65);
   TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32);
   TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32);
   c1_1->Draw();
   c1_2->Draw();
   c1_3->Draw();
   c1_4->Draw();
   c1_5->Draw();
   c1_6->Draw();
   c1_1->SetFillColor(30);
   c1_1->SetFrameFillColor(42);
   c1_2->SetFillColor(30);
   c1_2->SetFrameFillColor(42);
   c1_3->SetFillColor(30);
   c1_3->SetFrameFillColor(42);
   c1_4->SetFillColor(30);
   c1_4->SetFrameFillColor(42);
   c1_5->SetFillColor(30);
   c1_5->SetFrameFillColor(42);
   c1_6->SetFillColor(30);
   c1_6->SetFrameFillColor(42);
   
   c1_1->cd();
   TH1::AddDirectory(kFALSE);
     
   //A function to sample
   TF1 *fsin = new TF1("fsin", "sin(x)*sin(x)/(x*x)", 0, 4*TMath::Pi());
   fsin->Draw();
   
   Int_t n=25;
   TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 4*TMath::Pi());
   Double_t x;
   
   //Fill the histogram with function values
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      hsin->SetBinContent(i+1, fsin->Eval(x));
   }
   hsin->Draw("same");
   fsin->GetXaxis()->SetLabelSize(0.05);
   fsin->GetYaxis()->SetLabelSize(0.05);
   
   c1_2->cd();
   //Compute the transform and look at the magnitude of the output
   TH1 *hm =0;
   TVirtualFFT::SetTransform(0);
   hm = hsin->FFT(hm, "MAG");
   hm->SetTitle("Magnitude of the 1st transform");
   hm->Draw();
   //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function 
   //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically!
   
   hm->SetStats(kFALSE);
   hm->GetXaxis()->SetLabelSize(0.05);
   hm->GetYaxis()->SetLabelSize(0.05);
   c1_3->cd();   
   //Look at the phase of the output   
   TH1 *hp = 0;
   hp = hsin->FFT(hp, "PH");
   hp->SetTitle("Phase of the 1st transform");
   hp->Draw();
   hp->SetStats(kFALSE);
   hp->GetXaxis()->SetLabelSize(0.05);
   hp->GetYaxis()->SetLabelSize(0.05);
   
   //Look at the DC component and the Nyquist harmonic:
   Double_t re, im;
   //That's the way to get the current transform object:
   TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform();
   c1_4->cd();
   //Use the following method to get just one point of the output
   fft->GetPointComplex(0, re, im);
   printf("1st transform: DC component: %f\n", re);
   fft->GetPointComplex(n/2+1, re, im);
   printf("1st transform: Nyquist harmonic: %f\n", re);

   //Use the following method to get the full output:
   Double_t *re_full = new Double_t[n];
   Double_t *im_full = new Double_t[n];
   fft->GetPointsComplex(re_full,im_full);
  
   //Now let's make a backward transform:
   TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K");
   fft_back->SetPointsComplex(re_full,im_full);
   fft_back->Transform();
   TH1 *hb = 0;
   //Let's look at the output
   hb = TH1::TransformHisto(fft_back,hb,"Re");
   hb->SetTitle("The backward transform result");
   hb->Draw();
   //NOTE: here you get at the x-axes number of bins and not real values
   //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi; 
   //also here the y-axes has to be rescaled (factor 1/bins)
   hb->SetStats(kFALSE);
   hb->GetXaxis()->SetLabelSize(0.05);
   hb->GetYaxis()->SetLabelSize(0.05);
   delete fft_back;
   fft_back=0;

//********* Data array - same transform ********//

   //Allocate an array big enough to hold the transform output
   //Transform output in 1d contains, for a transform of size N, 
   //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers
   //our transform is of size n+1, because the histogram has n+1 bins

   Double_t *in = new Double_t[2*((n+1)/2+1)];
   Double_t re_2,im_2;
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fsin->Eval(x);
   }

   //Make our own TVirtualFFT object (using option "K")
   //Third parameter (option) consists of 3 parts:
   //-transform type:
   // real input/complex output in our case
   //-transform flag: 
   // the amount of time spent in planning
   // the transform (see TVirtualFFT class description)
   //-to create a new TVirtualFFT object (option "K") or use the global (default)
   Int_t n_size = n+1;
   TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K");
   if (!fft_own) return;
   fft_own->SetPoints(in);
   fft_own->Transform();

   //Copy all the output points:
   fft_own->GetPoints(in);
   //Draw the real part of the output
   c1_5->cd();
   TH1 *hr = 0;
   hr = TH1::TransformHisto(fft_own, hr, "RE");
   hr->SetTitle("Real part of the 3rd (array) tranfsorm");
   hr->Draw();
   hr->SetStats(kFALSE);
   hr->GetXaxis()->SetLabelSize(0.05);
   hr->GetYaxis()->SetLabelSize(0.05);
   c1_6->cd();
   TH1 *him = 0;
   him = TH1::TransformHisto(fft_own, him, "IM");
   him->SetTitle("Im. part of the 3rd (array) transform");
   him->Draw();
   him->SetStats(kFALSE);
   him->GetXaxis()->SetLabelSize(0.05);
   him->GetYaxis()->SetLabelSize(0.05);

   myc->cd();
   //Now let's make another transform of the same size
   //The same transform object can be used, as the size and the type of the transform
   //haven't changed
   TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi());
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fcos->Eval(x);
   }
   fft_own->SetPoints(in);
   fft_own->Transform();
   fft_own->GetPointComplex(0, re_2, im_2);
   printf("2nd transform: DC component: %f\n", re_2);
   fft_own->GetPointComplex(n/2+1, re_2, im_2);
   printf("2nd transform: Nyquist harmonic: %f\n", re_2);
   delete fft_own;
   delete [] in;
   delete [] re_full;
   delete [] im_full;
}
TF1* fitDstar3prongs(TTree* nt, TTree* ntMC, Double_t ptmin, Double_t ptmax)
{
  static int count3p=0;
  count3p++;
  
  TCanvas* c = new TCanvas(Form("c_3p_%d",count3p),"",600,600);
  TH1D* h = new TH1D(Form("h_3p_%d",count3p),"",60,0.14,0.16);
  TH1D* hMCSignal = new TH1D(Form("hMCSignal_3p_%d",count3p),"",60,0.14,0.16);
  TH1D* hMCSwapped = new TH1D(Form("hMCSwapped_3p_%d",count3p),"",60,0.14,0.16);

  TF1* f = new TF1(Form("f_3p_%d",count3p),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*([12]*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10])+(1-[12])*Gaus(x,[1],[13])/(sqrt(2*3.14159)*[13])))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]+[4]*x+[5]*x*x+[6]*x*x*x+[11]*x*x*x*x",0.14,0.16);
  f->SetLineColor(kRed);
  nt->Project(Form("h_3p_%d",count3p),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f&&Dpt<%f)",weight.Data(),seldata3p.Data(),triggerselection[isData].Data(),ptmin,ptmax));
  ntMC->Project(Form("hMCSignal_3p_%d",count3p),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f&&Dpt<%f&&(Dgen==23333))",weight.Data(),selmc3p.Data(),triggerselection[isData].Data(),ptmin,ptmax));
  ntMC->Project(Form("hMCSwapped_3p_%d",count3p),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f&&Dpt<%f&&(Dgen==23344))",weight.Data(),selswp3p.Data(),triggerselection[isData].Data(),ptmin,ptmax));

  f->FixParameter(7,1.);
  f->FixParameter(1,0.145491);
  f->FixParameter(2,2.e-3);
  f->FixParameter(10,5.e-4);
  f->FixParameter(13,1.e-4);
  f->FixParameter(3,0.);
  f->FixParameter(4,0.);
  f->FixParameter(5,0.);
  f->FixParameter(6,0.);
  f->FixParameter(11,0.);

  f->SetParLimits(9,0,1);
  f->SetParLimits(12,0,1);
  f->SetParLimits(0,0,1000000);
  hMCSignal->Fit(Form("f_3p_%d",count3p),"LL");
  hMCSignal->Fit(Form("f_3p_%d",count3p),"LL");
  hMCSignal->Fit(Form("f_3p_%d",count3p),"LL","",0.142,0.155);
  f->ReleaseParameter(1);
  f->ReleaseParameter(2);
  f->ReleaseParameter(10);
  f->ReleaseParameter(13);
  f->SetParLimits(1,0.144,0.147);
  if(isData==0||isData==2) f->SetParLimits(2,5.e-4,5.e-3);
  else f->SetParLimits(2,5.e-4,7.e-3);
  f->SetParLimits(10,1.e-4,2.e-3);
  if(isData==0||isData==2) f->SetParLimits(13,5.e-5,3.e-4);
  else if(ptmin>20) f->SetParLimits(13,5.e-5,4.e-4);
  else f->SetParLimits(13,5.e-5,5.e-4);
  hMCSignal->Fit(Form("f_3p_%d",count3p),"LL","",0.143,0.147);
  hMCSignal->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);
  hMCSignal->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(13,f->GetParameter(13));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(12,f->GetParameter(12));
  f->FixParameter(7,0);
  f->SetParLimits(8,2.e-4,2.e-3);

  hMCSwapped->Fit(Form("f_3p_%d",count3p),"L q","",0.14,0.16);
  hMCSwapped->Fit(Form("f_3p_%d",count3p),"L q","",0.14,0.16);

  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->ReleaseParameter(11);
  h->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);
  h->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);
  f->ReleaseParameter(1);
  h->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);
  h->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);
  h->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);
  h->Fit(Form("f_3p_%d",count3p),"LL","",0.14,0.16);

  TF1* background = new TF1(Form("background_3p_%d",count3p),"[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*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->SetParameter(4,f->GetParameter(11));
  background->SetLineColor(4);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass_3p_%d",count3p),"[0]*([3]*([4]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[4])*([6]*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5])+(1-[6])*Gaus(x,[1],[7])/(sqrt(2*3.14159)*[7]))))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10),f->GetParameter(12),f->GetParameter(13));
  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->SetParError(6,f->GetParError(12));
  mass->SetParError(7,f->GetParError(13));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  h->SetXTitle("M_{K#pi#pi}-M_{K#pi} (GeV/c^{2})");
  h->SetYTitle("Entries / (1/3 MeV/c^{2})");
  h->SetStats(0);
  h->SetAxisRange(1,h->GetMaximum()*1.3,"Y");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  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(0.142,0.152);	
  mass->Draw("same");
  f->Draw("same");

  Double_t yield = mass->Integral(0.14,0.16)/binwidth3prong;
  Double_t yieldErr = mass->Integral(0.14,0.16)/binwidth3prong*mass->GetParError(0)/mass->GetParameter(0);

  TLatex* tex;
  TLegend* leg = new TLegend(0.60,0.62,0.85,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry((TObject*)0,"D* D^{0}(K#pi)#pi",NULL);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D*^{+}+D*^{-} Signal","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  tex = new TLatex(0.61,0.58,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  tex = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.65,0.93, "PP #sqrt{s_{NN}} = 5.02 TeV");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.20,0.79,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();
  tex = new TLatex(0.20,0.84,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  c->SaveAs(Form("plots/pp/DMass_%s_3prongs-%d.pdf",texData[isData].Data(),count3p));
  
  return mass;
}