Exemple #1
0
TF1 *GausBF::GetBf(Int_t is1, Int_t is9) const
{
  TF1 *func = new TF1("fbf", FB(), -200, 200);
  for (Int_t i = 0; i < func->GetNpar() && i < Np; i++)
    func->SetParameter(i, GetPar(is1, is9, i));

  return func;
}
Exemple #2
0
TF1* GetFit(const char *address, int lyr, double xinit) {
  const char *bgr = Form("[6]*TMath::Exp([7]*(x-%f))",xinit);
  const char *la1 = "(1-[3]-[4]-[5])*TMath::Landau(x,[1],[2],1)";
  const char *la2 = "[3]*TMath::Landau(x,2*[1]+1.4*[2],2.0*[2],1)";
  const char *la3 = "[4]*TMath::Landau(x,3*[1]+3.3*[2],3.0*[2],1)";
  const char *la4 = "[5]*TMath::Landau(x,4*[1]+5.6*[2],4.0*[2],1)";
  TF1 *ret = new TF1("fit_H1",
                     Form("[0]*(%s+%s+%s+%s)+%s",la1,la2,la3,la4,bgr) );
  ret->SetParName(0,"A");
  ret->SetParName(1,"lambda");
  ret->SetParName(2,"sigma");
  ret->SetParName(3,"f2");
  ret->SetParameter(0,1e4);  ret->SetParLimits(0,1e2,1e7);
  ret->SetParameter(1,21);   ret->SetParLimits(1,13,25.0);
  ret->SetParameter(2,3.0);  ret->SetParLimits(2,1.5,5.0);
  if(lyr>1) {
    ret->SetParameter(1,15);   ret->SetParLimits(1,2,30);
    ret->SetParameter(2,5.0);  ret->SetParLimits(2,0.8,10.0);
  }
  ret->SetParameter(3,0.20); ret->SetParLimits(3,0,0.40);
  ret->SetParameter(4,0.0);
  ret->SetParameter(5,0.0);
  ret->SetParameter(6,500); ret->SetParLimits(6,1e2,1e7);
  ret->SetParameter(7,-1);  ret->SetParLimits(7,-10,-0.1);

  ret->SetLineColor(kRed-3);

  ifstream infit;
  infit.open( address );
  double tmp;
  bool found=false;
  for(int n=0; n!=ret->GetNpar(); ++n) {
    infit >> tmp;
    if(!infit.good()) break;
    ret->SetParameter(n,tmp);
    infit >> tmp;
    found = true;
  }
  infit.close();
  if(found) {
    cout << " Previous fit results found" << endl;
    ret->SetParLimits(4,0,0.40);
    ret->SetParLimits(5,0,0.40);
  } else {
    ret->SetParLimits(4,+1,-1);
    ret->SetParLimits(5,+1,-1);
  }
  return ret;
}
Exemple #3
0
void fit() {
  FILE *ofile;
  ofile = fopen("xsect-integrated-me.txt","w");
  TFile *_file0 = TFile::Open("h3maker-hn.root","update");
  _file0->Delete("*_f;*");
  TH2 *h2xsect = new TH2("hq2wXsect","Q^2:W",32,1.6,3.2,7,1.5,5.1);
  Double_t qbinedges[] = { 1.5, 1.6, 1.8, 2.1, 2.4, 2.76, 3.3, 5.1 };
  h2xsect->GetYaxis()->Set(7,qbinedges);
  TH3 *h3 = (TH3*)_file0->Get("hq2wmmp");
  int qbins = h3->GetZaxis()->GetNbins();
  int wbins = h3->GetYaxis()->GetNbins();
  fprintf(ofile, "W\tQ2\txsect\terror\tpol4p0\tpol4p1\tpol4p2\tpol4p3\tpol4p4\tgN\tgM\tgS\n");
  for (int iq = 0; iq < qbins; iq++) {
    TString hsn = TString::Format("hs%d",iq);
    THStack *hs = (THStack*)_file0->Get(hsn.Data());
    TIter next(hs->GetHists());
    //while (TObject *obj = next()) {
    //TH1 *h = (TH1*)obj;
    while (TH1 *h = (TH1*)next()) {
      float *wq = getwq(h);
      float wval = wq[0];
      float qval = wq[1];
      fitmmp(h);
      TH1 *htmp = (TH1*)h->Clone("hbgsubtracted");
      TF1 *fbg = (TF1*)h->GetListOfFunctions()->FindObject("fbg");
      htmp->Add(fbg,-1);
      double N = htmp->Integral(34,43);
      double qwidth = h3->GetZaxis()->GetBinWidth(iq+1);
      int wbin = h3->GetYaxis()->FindBin(wval);
      double wwidth = h3->GetYaxis()->GetBinWidth(wbin);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
Exemple #4
0
TF1* GetFit(const char *run, const char *inname, const char *outname) {
  ifstream infit;
  infit.open( Form("%s/fit/%s.dat",run,inname) );
  double tmp;
  bool found;
  infit >> alp >> tmp >> lda >> elda >> sgm >> esgm >> f2 >> tmp >> f3 >> tmp >> f4;
  infit.close();
  cout << alp << endl;
  cout << lda << endl;
  cout << sgm << endl;
  cout << f2 << endl;
  cout << f3 << endl;
  cout << f4 << endl;

  double f1 = 1-f2-f3-f4;
  if(1-f2<0.01) return NULL;  
  const char *la1 = Form("%f*TMath::Landau(x,1.00*%f*[0],1.0*%f*[1],1)",f1,lda,sgm);
  const char *la2 = Form("%f*TMath::Landau(x,2.14*%f*[0],2.0*%f*[1],1)",f2,lda,sgm);
  const char *la3 = Form("%f*TMath::Landau(x,3.33*%f*[0],3.0*%f*[1],1)",f3,lda,sgm);
  const char *la4 = Form("%f*TMath::Landau(x,4.55*%f*[0],4.0*%f*[1],1)",f4,lda,sgm);
  TF1 *ret = new TF1("fit_H1", Form("%f*(%s+%s+%s+%s)",alp,la1,la2,la3,la4) );
  ret->SetParName(0,"sLDA");
  ret->SetParName(1,"SSGM");
  ret->SetParameter(0,1.0);  ret->SetParLimits(0,1e-3,2.0);
  ret->SetParameter(1,1.0);  ret->SetParLimits(1,1e-3,2.0);
  ret->SetLineColor(kRed-3);
  infit.open( Form("%s/fit/%s.dat",run,outname) );
  tmp;
  found=false;
  for(int n=0; n!=ret->GetNpar(); ++n) {
    infit >> tmp;
    if(!infit.good()) break;
    ret->SetParameter(n,tmp);
    infit >> tmp;
    found = true;
  }
  infit.close();
  if(found) {
    cout << " Previous fit results found" << endl;
  }
  cout << lda << endl;
  return ret;
}
void GACalibManager::ReadFile(string fname)
{
  try{
    ifstream fin(fname.c_str(), ios::in);
    if(!fin){
      cout << "[GACalibManager-E]: cannot open parameter file: " << fname << endl;
      throw 1; 
    }
    Int_t f_type;
    istringstream iss;
    string line;
    getline(fin, line);
    iss.str(line);
    iss >> f_type;
    Double_t xmin, xmax;
    getline(fin, line);
    iss.str(line);
    iss >> xmin;
    iss >> xmax;
    GACalibFunctions *fGACalibFunction = new GACalibFunctions();
    fGACalibrator = new GACalibrator*[n_hist];
    TF1* Func = fGACalibFunction->CalibFunc((CalFuncType)f_type);
    n_par = Func->GetNpar();
    Double_t **par;
    par = new Double_t*[n_hist];
	getline(fin, line);
    for(int i=0; i<n_hist; i++){
		par[i] = new Double_t[n_par];
		for(int j=0; j<n_par; j++)
			fin >> par[i][j];
		fGACalibrator[i] = new GACalibrator((CalFuncType)f_type, par[i], i);
		fGACalibrator[i]->SetRange(xmin,xmax);
      }
  }
  catch(bad_alloc){
    cout << "[GACalibManager-E]: Exception bad_alloc." << endl;
    throw 1;
  }
}
Exemple #6
0
Double_t sr_fitError(Double_t *xx, Double_t *p) {

  assert(_sr_fitError_func);
  assert(_sr_fitError_emat);
  double x = *xx;
  double k = p[0];
  TF1 *f = _sr_fitError_func;
  int n = f->GetNpar();
  TMatrixD &emat = (*_sr_fitError_emat);
  assert(emat.GetNrows()==n);
  assert(emat.GetNcols()==n);
  
  vector<double> df(n);
  for (int i = 0; i != n; ++i) {

    double p = f->GetParameter(i);
    double dp = 0.1*f->GetParError(i);
    f->SetParameter(i, p+dp);
    double fup = f->Eval(x);
    f->SetParameter(i, p-dp);
    double fdw = f->Eval(x);
    f->SetParameter(i, p);
    df[i] = (dp ? (fup - fdw) / (2.*dp) : 0);
  }

  double sumerr2(0);
  for (int i = 0; i != n; ++i) {
    for (int j = 0; j != n; ++j) {
      sumerr2 += emat[i][j]*df[i]*df[j];
    }
  }

  double err = sqrt(sumerr2);

  return (f->Eval(x) + k*err);
}
Exemple #7
0
void massfitvn_Jpsi()
{
    double fit_range_low = 2.6;
    double fit_range_high = 3.5;
    double JPsi_mass = 3.097;
    int npt = 7;
    TFile* file1 = TFile::Open("HM185_JpsivnHist_etagap1p5_v30_eff_extdeta.root");
    
    TFile ofile("v2vspt_fromfit_jpsi_HM185_250_deta1p5_doubleCB_v30_eff_exp_extdeta.root","RECREATE");
    
    //v12
    double alpha_fit[14] = {4.30986,3.50841,3.03436,2.73741,2.37934,2.10685,2.03615};
    double n_fit[14] = {1.88853,1.9839,2.03198,2.07295,2.11001,2.15234,2.10154};
    
    TF1* fmasssig[9];
    TF1* fmassbkg[9];
    TF1* fmasstotal[9];
    TF1* fvn[9];
    
    double pt[13];
    double KET_ncq[13];
    double v2[13];
    double v2e[13];
    double v2_bkg[13];
    double v2_ncq[13];
    double v2e_ncq[13];
    double ptbin[14] = {0.2, 1.8, 3.0, 4.5, 6.0, 8.0, 10, 20};
    double a[13];
    double b[13];
    double sigfrac[13];
    
    TCanvas* c[10];
    for(int i=0;i<npt;i++)
    {
        c[i] = new TCanvas(Form("c_%d",i),Form("c_%d",i),800,400);
        c[i]->Divide(2,1);
    }
    
    for(int i=0;i<npt;i++)
    {
        c[i]->cd(1)->SetTopMargin(0.06);
        c[i]->cd(1)->SetLeftMargin(0.18);
        c[i]->cd(1)->SetRightMargin(0.043);
        c[i]->cd(1)->SetBottomMargin(0.145);
        c[i]->cd(2)->SetTopMargin(0.06);
        c[i]->cd(2)->SetLeftMargin(0.18);
        c[i]->cd(2)->SetRightMargin(0.043);
        c[i]->cd(2)->SetBottomMargin(0.145);

    }
    
    TCanvas* c2 = new TCanvas("c2","c2",100,100);
    
    TLatex* tex = new TLatex;
    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.045);
    tex->SetLineWidth(2);
 
    TLatex* texCMS = new TLatex;
    texCMS->SetNDC();
    texCMS->SetTextFont(42);
    texCMS->SetTextSize(0.05);
    texCMS->SetTextAlign(12);
    
    TH1D* hist = new TH1D("hist","",10,2.6,3.5);
    hist->SetLineWidth(0);
    //hist->GetYaxis()->SetRangeUser(0,0.3);
    hist->GetXaxis()->SetTitle("#it{m}_{#mu#mu} (GeV)");
    hist->GetYaxis()->SetTitle("v_{2}^{S+B}");
    hist->GetXaxis()->CenterTitle();
    hist->GetYaxis()->CenterTitle();
    hist->GetXaxis()->SetTitleOffset(1.3);
    hist->GetYaxis()->SetTitleOffset(2);
    hist->GetXaxis()->SetLabelOffset(0.007);
    hist->GetYaxis()->SetLabelOffset(0.007);
    hist->GetXaxis()->SetTitleSize(0.045);
    hist->GetYaxis()->SetTitleSize(0.045);
    hist->GetXaxis()->SetTitleFont(42);
    hist->GetYaxis()->SetTitleFont(42);
    hist->GetXaxis()->SetLabelFont(42);
    hist->GetYaxis()->SetLabelFont(42);
    hist->GetXaxis()->SetLabelSize(0.04);
    hist->GetYaxis()->SetLabelSize(0.04);
    hist->SetMinimum(0.01);
    hist->SetMaximum(0.33);
    
    c2->cd();
    hist->Draw();
    
    for(int i=0;i<npt;i++)
    {
        TH1D* h_data = (TH1D*)file1->Get(Form("massjpsi_pt%d",i));
        h_data->SetMinimum(0);
        h_data->SetMarkerSize(0.8);
        h_data->SetMarkerStyle(20);
        h_data->SetLineWidth(1);
        h_data->SetOption("e");
        
        h_data->Rebin(2);

        h_data->GetXaxis()->SetRangeUser(2.6,3.5);
        h_data->GetXaxis()->SetTitle("#it{m}_{#mu#mu} (GeV)");
        h_data->GetYaxis()->SetTitle("Entries / 10 MeV");
        h_data->GetXaxis()->CenterTitle();
        h_data->GetYaxis()->CenterTitle();
        h_data->GetXaxis()->SetTitleOffset(1.3);
        h_data->GetYaxis()->SetTitleOffset(2);
        h_data->GetXaxis()->SetLabelOffset(0.007);
        h_data->GetYaxis()->SetLabelOffset(0.007);
        h_data->GetXaxis()->SetTitleSize(0.045);
        h_data->GetYaxis()->SetTitleSize(0.045);
        h_data->GetXaxis()->SetTitleFont(42);
        h_data->GetYaxis()->SetTitleFont(42);
        h_data->GetXaxis()->SetLabelFont(42);
        h_data->GetYaxis()->SetLabelFont(42);
        h_data->GetXaxis()->SetLabelSize(0.04);
        h_data->GetYaxis()->SetLabelSize(0.04);
        
        h_data->GetXaxis()->SetNoExponent(true);
        ((TGaxis*)h_data->GetXaxis())->SetMaxDigits(7);
        
        h_data->SetMaximum(h_data->GetMaximum()*1.5);
        
        TH1D* h_pt = (TH1D*)file1->Get(Form("Ptjpsi_eff_pt%d",i));
        TH1D* h_KET = (TH1D*)file1->Get(Form("KETjpsi_eff_pt%d",i));
        pt[i] = h_pt->GetMean();
        KET_ncq[i] = h_KET->GetMean()/2.0;

        c[i]->cd(1);
        
        /*p definitions
         [0] CB1 yield;
         [1] Common mean of CB and Gaus;
         [2] CB1 sigma;
         [3] CB n;
         [4] CB alpha;
         [5] CB2 yield;
         [6] CB2 sigma;
         [7-10] poly 3;
         [11] v2 signal;
         [12-13] v2 bkg;
         */
        TF1* f = new TF1(Form("f_%d",i), crystalball_function_total, fit_range_low, fit_range_high, 11);
        f->SetLineColor(2);
        f->SetLineWidth(1);
        f->SetParNames("CB1_Yield","common_mean","CB1_sigma","CB_N","CB_Alpha","CB2_Yield","CB2_Sigma","Pol0","Pol1","Pol2","Pol3");

        //first fit data mass signal + bkg
        
        f->SetParameter(0,10000.);
        f->SetParameter(1,JPsi_mass);
        f->SetParameter(2,0.03);
        f->SetParameter(3,1.0);
        f->SetParameter(4,1.0);
        f->SetParameter(5,10000);
        f->SetParameter(6,0.03);
        
        f->SetParLimits(2,0.01,0.1);
        f->SetParLimits(6,0.01,0.1);
        
        //fix alpha & n from MC
        f->FixParameter(4,alpha_fit[i]);
        f->FixParameter(3,n_fit[i]);
        
        f->FixParameter(1,JPsi_mass); //for first few attempt fix mean of gaussian to get reasonable estimation of other pars; later open it up
        h_data->Fit(Form("f_%d",i),"q","",fit_range_low,fit_range_high);
        h_data->Fit(Form("f_%d",i),"q","",fit_range_low,fit_range_high);
        f->ReleaseParameter(1); //now let gaussian mean float
        h_data->Fit(Form("f_%d",i),"L q","",fit_range_low,fit_range_high);
        h_data->Fit(Form("f_%d",i),"L q","",fit_range_low,fit_range_high);
        h_data->Fit(Form("f_%d",i),"L m","",fit_range_low,fit_range_high);
        
        
        //draw D0 signal separately
        TF1* f1 = new TF1(Form("f_sig_%d",i), crystalball_function_signal, fit_range_low, fit_range_high, 7);
        f1->SetLineColor(kOrange-3);
        f1->SetLineWidth(1);
        f1->SetLineStyle(2);
        f1->SetFillColorAlpha(kOrange-3,0.3);
        f1->SetFillStyle(1001);
        f1->FixParameter(0,f->GetParameter(0));
        f1->FixParameter(1,f->GetParameter(1));
        f1->FixParameter(2,f->GetParameter(2));
        f1->FixParameter(3,f->GetParameter(3));
        f1->FixParameter(4,f->GetParameter(4));
        f1->FixParameter(5,f->GetParameter(5));
        f1->FixParameter(6,f->GetParameter(6));
        
        fmasssig[i] = (TF1*)f1->Clone();
        fmasssig[i]->SetName(Form("masssigfcn_pt%d",i));
        fmasssig[i]->Write();
        
        f1->Draw("LSAME");
        
        //draw poly bkg separately
        TF1* f3 = new TF1(Form("f_bkg_%d",i),"[7] + [8]*x + [9]*x*x + [10]*x*x*x", fit_range_low, fit_range_high);
        f3->SetLineColor(4);
        f3->SetLineWidth(1);
        f3->SetLineStyle(2);
        f3->FixParameter(7,f->GetParameter(7));
        f3->FixParameter(8,f->GetParameter(8));
        f3->FixParameter(9,f->GetParameter(9));
        f3->FixParameter(10,f->GetParameter(10));
        
        fmassbkg[i] = (TF1*)f3->Clone();
        fmassbkg[i]->SetName(Form("massbkgfcn_pt%d",i));
        fmassbkg[i]->Write();
        
        f3->Draw("LSAME");
        
        tex->DrawLatex(0.22,0.86,"185 #leq N_{trk}^{offline} < 250");
        tex->DrawLatex(0.22,0.80,Form("%.1f < p_{T} < %.1f GeV",ptbin[i],ptbin[i+1]));
        tex->DrawLatex(0.22,0.74,"-2.86 < y_{cm} < -1.86 or 0.94 < y_{cm} < 1.94");
        
        texCMS->DrawLatex(.18,.97,"#font[61]{CMS} #it{Preliminary}");
        //texCMS->DrawLatex(.18,.97,"#font[61]{CMS}");
        texCMS->DrawLatex(0.73,0.97, "#scale[0.8]{pPb 8.16 TeV}");
        
        TLegend* leg = new TLegend(0.21,0.4,0.5,0.65,NULL,"brNDC");
        leg->SetBorderSize(0);
        leg->SetTextSize(0.045);
        leg->SetTextFont(42);
        leg->SetFillStyle(0);
        leg->AddEntry(h_data,"data","p");
        leg->AddEntry(f,"Fit","L");
        leg->AddEntry(f1,"J/#psi Signal","f");
        leg->AddEntry(f3,"Combinatorial","l");
        leg->Draw("SAME");
        
        sigfrac[i] = f1->Integral(2.94,3.24)/f->Integral(2.94,3.24);
        
        //c->Print(Form("plots/massfit_pt%d.pdf",i));
        
        //fit vn
        //[9] is vn_sig
        //[10-11] is vn bkg, const + linear vn(pT)
        TGraphErrors* vn_data = (TGraphErrors*)file1->Get(Form("v2_mass_pt%d",i));
        
        c[i]->cd(2);
        
        hist->Draw();
        
        TF1* fmass_combinemassvnfit = new TF1(Form("fmass_combinemassvnfit_%d",i),crystalball_function_total, fit_range_low, fit_range_high, 11);
        
        TF1* fvn_combinemassvnfit = new TF1(Form("fvn_combinemassvnfit_%d",i), crystalball_function_v2, fit_range_low, fit_range_high, 15);
        
        fmass_combinemassvnfit->SetLineColor(2);
        fmass_combinemassvnfit->SetLineWidth(1);
        
        fvn_combinemassvnfit->SetLineColor(2);
        fvn_combinemassvnfit->SetLineWidth(1);

        ROOT::Math::WrappedMultiTF1 wfmass_combinemassvnfit(*fmass_combinemassvnfit,1);
        ROOT::Math::WrappedMultiTF1 wfvn_combinemassvnfit(*fvn_combinemassvnfit,1);
        
        ROOT::Fit::DataOptions opt;
        ROOT::Fit::DataRange range_massfit;

        range_massfit.SetRange(fit_range_low,fit_range_high);
        ROOT::Fit::BinData datamass(opt,range_massfit);
        ROOT::Fit::FillData(datamass, h_data);
        
        ROOT::Fit::DataRange range_vnfit;
        range_vnfit.SetRange(fit_range_low,fit_range_high);
        ROOT::Fit::BinData datavn(opt,range_vnfit);
        ROOT::Fit::FillData(datavn, vn_data);
        
        ROOT::Fit::Chi2Function chi2_B(datamass, wfmass_combinemassvnfit);
        ROOT::Fit::Chi2Function chi2_SB(datavn, wfvn_combinemassvnfit);
        
        GlobalChi2_poly3bkg_floatwidth globalChi2(chi2_B, chi2_SB);

        ROOT::Fit::Fitter fitter;
        
        const int Npar = 15;
        double par0[Npar];
        for( int ipar = 0; ipar < f->GetNpar(); ipar++ ) par0[ipar] = f->GetParameter(ipar);
        par0[11] = 0.01;
        par0[12] = 0.10;
        par0[13] = 0.05;
        par0[14] = 0.01;

        
        fitter.Config().SetParamsSettings(Npar,par0);
        // fix parameter
        fitter.Config().ParSettings(0).Fix();
        fitter.Config().ParSettings(1).Fix();
        fitter.Config().ParSettings(2).Fix();
        fitter.Config().ParSettings(3).Fix();
        fitter.Config().ParSettings(4).Fix();
        fitter.Config().ParSettings(5).Fix();
        fitter.Config().ParSettings(6).Fix();
        fitter.Config().ParSettings(7).Fix();
        fitter.Config().ParSettings(8).Fix();
        fitter.Config().ParSettings(9).Fix();
        fitter.Config().ParSettings(10).Fix();
        
        fitter.Config().MinimizerOptions().SetPrintLevel(0);
        fitter.Config().SetMinimizer("Minuit2","Migrad");

        fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),true);
        ROOT::Fit::FitResult result = fitter.Result();
        result.Print(std::cout);
        
        fmass_combinemassvnfit->SetFitResult( result, iparmassfit_poly3bkg_floatwidth);
        fmass_combinemassvnfit->SetRange(range_massfit().first, range_massfit().second);
        fmass_combinemassvnfit->SetLineColor(kRed);
        h_data->GetListOfFunctions()->Add(fmass_combinemassvnfit);
        //c->cd();
        //h_data->Draw();
        
        fvn_combinemassvnfit->SetFitResult( result, iparvnfit_poly3bkg_floatwidth);
        fvn_combinemassvnfit->SetRange(range_vnfit().first, range_vnfit().second);
        fvn_combinemassvnfit->SetLineColor(2);
        //fvn_combinemassvnfit->SetLineStyle(2);
        vn_data->GetListOfFunctions()->Add(fvn_combinemassvnfit);
        vn_data->SetTitle("");
        vn_data->SetMarkerSize(0.8);
        vn_data->SetLineWidth(1);
        //c1->cd();
        vn_data->Draw("PESAME");
        
        fvn[i] = (TF1*)fvn_combinemassvnfit->Clone();
        fvn[i]->SetName(Form("vnfit_pt%d",i));
        fvn[i]->Write();
        
        fmasstotal[i] = (TF1*)fmass_combinemassvnfit->Clone();
        fmasstotal[i]->SetName(Form("masstotalfcn_pt%d",i));
        fmasstotal[i]->Write();
        
        tex->DrawLatex(0.22,0.86,"185 #leq N_{trk}^{offline} < 250");
        tex->DrawLatex(0.22,0.80,Form("%.1f < p_{T} < %.1f GeV",ptbin[i],ptbin[i+1]));
        //tex->DrawLatex(0.22,0.74,"1.4 < |y_{cm}+0.46| < 2.4");
        tex->DrawLatex(0.22,0.74,"-2.86 < y_{cm} < -1.86 or 0.94 < y_{cm} < 1.94");
        //tex->DrawLatex(0.22,0.68,"|#Delta#eta| > 2");

        
        //texCMS->DrawLatex(.18,.97,"#font[61]{CMS}");
        texCMS->DrawLatex(.18,.97,"#font[61]{CMS} #it{Preliminary}");
        texCMS->DrawLatex(0.73,0.97, "#scale[0.8]{pPb 8.16 TeV}");
        
        v2[i] = fvn_combinemassvnfit->GetParameter(11);
        v2e[i] = fvn_combinemassvnfit->GetParError(11);
        v2_bkg[i] = fvn_combinemassvnfit->GetParameter(12) + fvn_combinemassvnfit->GetParameter(13) * JPsi_mass;
        v2_ncq[i] = v2[i]/2.0;
        v2e_ncq[i] = v2e[i]/2.0;
        a[i] = fvn_combinemassvnfit->GetParameter(12);
        b[i] = fvn_combinemassvnfit->GetParameter(13);
        
        TF1* fvnbkg = new TF1(Form("fvnbkg_%d",1),"( [0] + [1] * x)", fit_range_low, fit_range_high);
        fvnbkg->FixParameter(0,fvn_combinemassvnfit->GetParameter(12));
        fvnbkg->FixParameter(1,fvn_combinemassvnfit->GetParameter(13));
        
        fvnbkg->SetName(Form("fvnbkg_fcn_pt%d",i));
        fvnbkg->Write();
        
        fvnbkg->SetLineStyle(7);
        //fvnbkg->Draw("LSAME");
        
        TF1* fvnsig = new TF1(Form("fvnsig_%d",i),function_v2_sig,fit_range_low,fit_range_high,12);
        for(int k=0;k<12;k++)
        {
            fvnsig->FixParameter(k,fvn_combinemassvnfit->GetParameter(k));
            
        }
        
        fvnsig->SetLineColor(kOrange-3);
        fvnsig->SetLineWidth(1);
        fvnsig->SetLineStyle(2);
        fvnsig->SetFillColorAlpha(kOrange-3,0.3);
        fvnsig->SetFillStyle(1001);
        
        //fvnsig->Draw("LSAME");
        
        TLegend* leg1 = new TLegend(0.72,0.525,0.91,0.65,NULL,"brNDC");
        leg1->SetBorderSize(0);
        leg1->SetTextSize(0.045);
        leg1->SetTextFont(42);
        leg1->SetFillStyle(0);
        leg1->AddEntry(h_data,"data","p");
        leg1->AddEntry(fvn_combinemassvnfit,"Fit","l");
        //leg1->AddEntry(fvnsig,"#alpha(#it{m}_{#mu#mu})v_{2}^{S}","f");
        leg1->Draw("SAME");

        double xmass[200];
        double pullmass[200];
        
        float Chi2=0;
        int ndf = (fit_range_high - fit_range_low)/0.01 - 8;
        
        for(int k=0;k<h_data->GetNbinsX();k++)
        {
            xmass[k] = h_data->GetBinCenter(k);
            pullmass[k] = (h_data->GetBinContent(k) - fmass_combinemassvnfit->Eval(xmass[k]))/h_data->GetBinError(k);
            if(fabs(pullmass[k])<5)
            {
                //cout<<pullmass[k]<<endl;
                Chi2 += pullmass[k]*pullmass[k];
            }
        }

        c[i]->cd(1);
        tex->DrawLatex(0.22,0.67,Form("#chi^{2}/ndf = %.0f/%d",Chi2,ndf));
        
        double xv2[200];
        double pullv2[200];
        double v2y[200];
        
        float Chi2v2=0;
        int ndfv2 = 8 - 4; //Nbin - Npar
        
        for(int k=0;k<vn_data->GetN()-1;k++)
        {
            vn_data->GetPoint(k,xv2[k],v2y[k]);
            //xv2[k] = vn_dara->GetBinCenter(k);
            pullv2[k] = (v2y[k] - fvn_combinemassvnfit->Eval(xv2[k]))/vn_data->GetErrorY(k);
            cout<<k<<": "<<pullv2[k]<<endl;
            if(fabs(pullv2[k])<1000)
            {
                //cout<<pullmass[k]<<endl;
                Chi2v2 += pullv2[k]*pullv2[k];
            }
            cout<<"fcn: "<<fvn_combinemassvnfit->Eval(xv2[k])<<endl;
            cout<<"data: "<<v2y[k]<<endl;
        }

        c[i]->cd(2);
        tex->DrawLatex(0.22,0.67,Form("#chi^{2}/ndf = %.1f/%d",Chi2v2,ndfv2));
        
    }
    
    for(int i=0;i<npt;i++)
    {
        c[i]->Print(Form("plots/v30/eff/exp/JPsi_mass_vnfit_combine_pt%d.pdf",i));
        c[i]->Print(Form("plots/v30/eff/exp/JPsi_mass_vnfit_combine_pt%d.gif",i));
    }
    
    TGraphErrors* v2plot = new TGraphErrors(npt,pt,v2,0,v2e);
    TGraphErrors* v2ncqplot = new TGraphErrors(npt,KET_ncq,v2_ncq,0,v2e_ncq);
    TGraphErrors* v2bkgplot = new TGraphErrors(npt,pt,v2_bkg,0,0);
    
    v2plot->SetName("v2vspt");
    v2ncqplot->SetName("v2vsKET_ncq");
    v2bkgplot->SetName("v2bkgvspt");
    
    v2plot->Write();
    v2ncqplot->Write();
    v2bkgplot->Write();
}
TF1* GeneralCorrectionFunction(
								double ChannelRangeMin, double ChannelRangeMax,double ChannelPeakPos ,
								TH2D *h2DInputForCorrection ,
								int LineIndex,
								TString InputType="T10DeriMaxEnergy",
								TString CorrNumber="1",
								double XRangeMin=0, double XRangeMax=300,
								TString FitFuncCorr="pol2",
								double FitCorrRangeMin=10, double FitCorrRangeMax= 270,
								double TresholdForCorrection=10,
								TString FitFuncSlicesString="gaus(0)+[3]+gaus(4)"
								
								
)
{
	h2DInputForCorrection->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
	char buf[60];
	sprintf(buf, "hMaxCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TH1D *hMaxPosManually=new TH1D(buf,"",h2DInputForCorrection->GetNbinsX(),h2DInputForCorrection->GetXaxis()->GetXmin(),h2DInputForCorrection->GetXaxis()->GetXmax());
	sprintf(buf, "hMaxFitCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TH1D *hMaxPosManuallyFit=new TH1D(buf,"",h2DInputForCorrection->GetNbinsX(),h2DInputForCorrection->GetXaxis()->GetXmin(),h2DInputForCorrection->GetXaxis()->GetXmax());
	sprintf(buf, "hGausSigmaCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TH1D *hGausSigmaManually=new TH1D(buf,"",h2DInputForCorrection->GetNbinsX(),h2DInputForCorrection->GetXaxis()->GetXmin(),h2DInputForCorrection->GetXaxis()->GetXmax());
	for(int binX = h2DInputForCorrection->GetXaxis()->FindBin(XRangeMin);binX <= h2DInputForCorrection->GetXaxis()->FindBin(XRangeMax);binX++)
	//for(int binX = h2DInputForCorrection->GetXaxis()->FindBin(200);binX <= h2DInputForCorrection->GetXaxis()->FindBin(200);binX++)
	{
		TH1D *hProfileY =h2DInputForCorrection->ProjectionY("_py",binX,binX);	
		double MaxValue=hProfileY->GetBinCenter(hProfileY->GetMaximumBin());
		
		//hMaxPosManually->SetBinContent(binX, MaxValue);
		//h2DInputForCorrection
		//cout <<hProfileY->GetEntries()<<endl;
		//TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+[3]",MaxValue-20,MaxValue+20);
		//cout << TMath::Max(MaxValue-20,double(ChannelRangeMin)) << "\t" << TMath::Min(MaxValue+20,double(ChannelRangeMax)) << "\t"<<endl;
		TF1* FitFuncGausSlices = new TF1("FitFuncGausSlices","gaus(0)",TMath::Max(MaxValue-20,double(ChannelRangeMin)),TMath::Min(MaxValue+20,double(ChannelRangeMax)));
		FitFuncGausSlices->SetParameters(hProfileY->GetBinContent(hProfileY->GetMaximumBin()),MaxValue,4);
		
		hProfileY->Fit(FitFuncGausSlices,"RNIQ");
		TF1* FitFuncSlices = new TF1("FitFuncSlices",FitFuncSlicesString.Data(),TMath::Max(MaxValue-3*FitFuncGausSlices->GetParameter(2),double(ChannelRangeMin)),TMath::Min(MaxValue+3*FitFuncGausSlices->GetParameter(2),double(ChannelRangeMax)));
		FitFuncSlices->SetParameters(FitFuncGausSlices->GetParameter(0),FitFuncGausSlices->GetParameter(1),FitFuncGausSlices->GetParameter(2),10,10,FitFuncGausSlices->GetParameter(1)-5,5);
		
		FitFuncSlices->SetParLimits(0,FitFuncGausSlices->GetParameter(0)*0.8,FitFuncGausSlices->GetParameter(0)*1.5);
		FitFuncSlices->SetParLimits(1,TMath::Max(FitFuncGausSlices->GetParameter(1)-10,double(ChannelRangeMin)),TMath::Min(FitFuncGausSlices->GetParameter(1)+10,double(ChannelRangeMax)));
		FitFuncSlices->SetParLimits(2,0,FitFuncGausSlices->GetParameter(2)*2);
		FitFuncSlices->SetParLimits(3,0,500);
		FitFuncSlices->SetParLimits(4,0,FitFuncGausSlices->GetParameter(0)*0.3);
		
		FitFuncSlices->SetParLimits(5,TMath::Max(FitFuncGausSlices->GetParameter(1)-10,double(ChannelRangeMin)),TMath::Min(MaxValue-1,double(ChannelRangeMax)));
		FitFuncSlices->SetParLimits(6,0,10);
		hProfileY->Fit(FitFuncSlices,"RINQ");
		//hProfileY->DrawCopy();
		
		//cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetParError(1) <<endl;
		//cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetMaximumX() <<endl;
		hMaxPosManually->SetBinContent(binX, (FitFuncSlices->GetParameter(1))/ChannelPeakPos);
		hMaxPosManually->SetBinError(binX, FitFuncSlices->GetParError(1)/ChannelPeakPos);
		hGausSigmaManually->SetBinContent(binX, FitFuncSlices->GetParameter(2));
		hGausSigmaManually->SetBinError(binX, FitFuncSlices->GetParError(2));
		if(FitFuncSlices->GetParameter(2)<TresholdForCorrection && FitFuncSlices->GetParError(2)<5)
		{
			hMaxPosManuallyFit->SetBinContent(binX, (FitFuncSlices->GetParameter(1))/ChannelPeakPos);
			hMaxPosManuallyFit->SetBinError(binX, FitFuncSlices->GetParError(1)/ChannelPeakPos);
		}
		//hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->SetBinError(binX, FitFuncSlices->GetParameter(2)/ChannelPeakPos);
		hProfileY->Delete();
		//cin.ignore();
	}
	//write histos to file
		
	//sprintf(buf, "hMaxCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	hMaxPosManually->Write(0,TObject::kOverwrite);
	//sprintf(buf, "hGausSigmaCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	hGausSigmaManually->Write(0,TObject::kOverwrite);
	hMaxPosManuallyFit->Write(0,TObject::kOverwrite);
	sprintf(buf, "funcCorr%s_%sNorm_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	//fit corr function and write it to file
	TF1 *funcCorrNorm = new TF1(buf,FitFuncCorr.Data(),FitCorrRangeMin,FitCorrRangeMax);
	funcCorrNorm->SetParameters(1,0,-0);
	
	funcCorrNorm->SetParLimits(0,0.8,1);
	//funcCorrNorm->SetParLimits(2,-1E5,0);
	//if(LineIndex==2)
	//	hMaxPosManuallyFit->Fit(funcCorrNorm,"RBI");
	//else
		hMaxPosManuallyFit->Fit(funcCorrNorm,"RBQI");
	sprintf(buf, "funcCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	TF1 *funcCorr = new TF1(buf,FitFuncCorr.Data(),FitCorrRangeMin,FitCorrRangeMax);
	for(int i= 0; i<funcCorr->GetNpar();i++)
	{
		funcCorr->SetParameter(i,funcCorrNorm->GetParameter(i)*ChannelPeakPos);
	}
	//sprintf(buf, "funcCorr%s_%sNorm_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	funcCorrNorm->Write(0,TObject::kOverwrite);
	//sprintf(buf, "funcCorr%s_%s_%d",CorrNumber.Data(),InputType.Data(),LineIndex);
	funcCorr->Write(0,TObject::kOverwrite);
	h2DInputForCorrection->GetYaxis()->UnZoom();
	return funcCorr;
}
Exemple #9
0
Double_t GausBF::Gfit(Int_t is1, Int_t is9, Double_t rgt, TGraph *gr,
		                                          TGraph *gb)
{
  if ((is1 == 59 && is9 == 98) || (is1 == 59 && is9 == 109) ||
      (is1 == 73 && is9 == 98) || (is1 == 86 && is9 ==  97) ||
      (is1 == 86 && is9 == 98) || (is1 == 97 && is9 ==  98)) return -1;

  AMSPoint p1 = GetP1(is1);
  AMSPoint p9 = GetP9(is9);

  if (rgt == 0) {
    TGraph grb; if (!gb) gb = &grb;
    TrProp trp(p1, p9-p1, rgt);
    for (Int_t i = 0; i < 200; i++) {
      Double_t z = -200+(i+0.5)*2;
      trp.Propagate(z);
      gb->SetPoint(i, z, trp.GuFld(trp.GetP0()).x());
    }

    TF1 *func = Bfit(gb);

    Double_t *par = GausBF::Head()->GetPar(is1, is9);
    for (Int_t i = 0; i < func->GetNpar() && i < Np; i++)
      par[i] = func->GetParameter(i);

    if (par[0] == 0) cout << "Failed: " << is1 << " " << is9 << endl;

    for (Int_t i = 0; i < Np/3; i++)
      if (par[i*3] != 0) {
	if (par[i*3+2] < 0) par[i*3+2] *= -1;
	if (par[i*3+2] < 1 || TMath::Abs(par[i*3+1]) > 200) {
	  par[i*3] = par[i*3+1] = 0;
	             par[i*3+2] = 1;
	}
      }

    Double_t err = 1e-3;
    Double_t csq = 0;
    for (Int_t i = 0; i < gb->GetN(); i++) {
      Double_t d = gb->GetY()[i]-func->Eval(gb->GetX()[i]);
      csq += d*d/err/err;
    }
    return csq;
  }

  TGraph grp; if (!gr) gr = &grp;
  TrProp trp(p1, p9-p1, rgt);

  AMSPoint pnt;
  AMSDir   dir;
  if (_Zref == 0) _Zref = TkDBc()->GetZlayerAJ(1);

  for (Int_t i = 0; i < 9; i++) {
    Double_t z = TkDBc()->GetZlayerAJ(i+1);
    trp.Propagate(z);
    gr->SetPoint(i, z, trp.GetP0y());
    if (i == 0) { pnt = trp.GetP0(); dir = trp.GetDir(); }
  }

  TF1 *func = GausBF::Head()->GetPr(is1, is9, rgt); 
  gr->Fit(func, "q0");

  for (Int_t i = 0; i < Np; i++)
    GausBF::Head()->SetPar(is1, is9, i, func->GetParameter(i+5));

  Double_t csq = 0;
  for (Int_t i = 0; i < gr->GetN(); i++) {
    Double_t res = (gr->GetY()[i]-func->Eval(gr->GetX()[i]))*1e4;
//  cout << Form("%6.1f %7.3f %7.3f  %6.1f", gr->GetX()[i], gr->GetY()[i],
//		 func->Eval(gr->GetX()[i]), res) << endl;
    gr->GetY()[i] = res;
    csq += res*res;
  }
  delete func;

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

      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      fsig->SetParameter(0,ftmp->GetParameter(5));
      fsig->SetParameter(1,ftmp->GetParameter(6));
      fsig->SetParameter(2,ftmp->GetParameter(7));
      fsig->SetParameter(3,step_x0);
      fsig->SetParameter(4,step_x1);
      fsig->SetLineWidth(2);
      fsig->SetLineColor(kBlue+1);
      h->GetListOfFunctions()->Add((TF1*)fsig->Clone("fsig"));
      //fsig->Print();
      double Nfn = 0;
      for (int b = 1; b < h->GetNbinsX(); b++) {
        double x = h->GetXaxis()->GetBinCenter(b);
        Nfn += fsig->Eval(x);
      }
      //printf("**** %.3e\t\%.3e\n",Nfn,N);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double xsectFn = Nfn/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile,"\t%.3e",xsectFn/(1e6));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
TF1* fit_histo_poly3bkg_floatwidth_poly2bkg_combinemassvnfit( bool isPbPb, int centlow, int centhigh, TH1D * histo, TH1D * h_mc_matched_signal, TH1D * h_mc_matched_kpiswapped, int ipt, TString cfgname, bool get_sig_bkg_ratio = false, TH1D * Ratio_signal_foreground = NULL, TH1D * h_vnvsmass = NULL, TH1D * h_vnvspt = NULL, TString vnorder = "v2", TString EPorSP = "SP", TH1D * h_vnvspt_bkg = NULL)
{
	Double_t setparam0=100.;
	Double_t setparam1=1.8648;
	Double_t setparam2=0.03;
	Double_t setparam3=0.005;
	Double_t setparam4=0.1;
	Double_t setparam7=0.1;
	Double_t fixparam1=1.8648;

	double fit_range_low = generalfitrange_masslow;
	double fit_range_high = generalfitrange_masshigh;
	double histomassbinsize = histo->GetBinWidth(10);

	float ptmin = ptbins[ipt];
	float ptmax = ptbins[ipt+1];

	//remove the fit function from v2 fit when perform v3 fit
	if( histo->GetListOfFunctions()->FindObject(Form("fmass_combinemassvnfit_%s_%d",cfgname.Data(),ipt)) )
		histo->GetListOfFunctions()->Remove( histo->GetListOfFunctions()->FindObject(Form("fmass_combinemassvnfit_%s_%d",cfgname.Data(),ipt)) );

	TH1F* histo_copy_nofitfun = ( TH1F * ) histo->Clone("histo_copy_nofitfun");
	TH1F* histo_massfit = ( TH1F * ) histo->Clone("histo_massfit");

	TCanvas* cfg= new TCanvas(Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_%s_%d",cfgname.Data(),ipt),Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_%s_%d",cfgname.Data(),ipt),600,600);

    gPad->SetRightMargin(0.043);
    gPad->SetLeftMargin(0.18);
    gPad->SetTopMargin(0.1);
    gPad->SetBottomMargin(0.145);

    TF1* f = new TF1(Form("f_%s_%d",cfgname.Data(),ipt),"[0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x", fit_range_low, fit_range_high);

	f->SetParLimits(10,-1000,1000);
	f->SetParLimits(3,0.001,0.05);
	f->SetParLimits(2,0.01,0.1);
	f->SetParLimits(7,0.02,0.2);
	f->SetParLimits(5,0,1);
	f->SetParLimits(4,0,1);

	f->SetParameter(0,setparam0);
	f->SetParameter(1,setparam1);
	f->SetParameter(2,setparam2);
	f->SetParameter(3,setparam3);
	f->SetParameter(4,setparam4);

	f->FixParameter(7,setparam7);
	f->FixParameter(8,setparam1);
	f->FixParameter(5,1);
	f->FixParameter(1,fixparam1);
	f->FixParameter(9,0);
	f->FixParameter(10,0);
	f->FixParameter(11,0);
	f->FixParameter(12,0);
	f->FixParameter(6,0);

	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	f->ReleaseParameter(1);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_signal->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L m","",fit_range_low,fit_range_high);

	f->FixParameter(1,f->GetParameter(1));
	f->FixParameter(2,f->GetParameter(2));
	f->FixParameter(3,f->GetParameter(3));
	f->FixParameter(4,f->GetParameter(4));
	f->FixParameter(5,0);
	f->ReleaseParameter(7);
	f->ReleaseParameter(8);
	f->SetParameter(7,setparam7);
    f->SetParameter(8,setparam1);//mean for swapped candidates
    //if want to fix parameter 8 to parameter 1
    //f->FixParameter(8,f->GetParameter(1));

	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	h_mc_matched_kpiswapped->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L m","",fit_range_low,fit_range_high);

	f->FixParameter(5,h_mc_matched_signal->Integral(0,1000)/(h_mc_matched_kpiswapped->Integral(0,1000)+h_mc_matched_signal->Integral(0,1000)));
	f->FixParameter(7,f->GetParameter(7));
	f->FixParameter(8,f->GetParameter(8));
	f->ReleaseParameter(9);
	f->ReleaseParameter(10);
	f->ReleaseParameter(11);
	f->ReleaseParameter(12);

	f->SetLineColor(kRed);

	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"q","",fit_range_low,fit_range_high);
	f->ReleaseParameter(1);
	////Release Parameter 6 to float signal width
	f->ReleaseParameter(6);
	f->SetParameter(6,0);
	f->SetParLimits(6,-1.0,1.0);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L q","",fit_range_low,fit_range_high);
	histo_massfit->Fit(Form("f_%s_%d",cfgname.Data(),ipt),"L m","",fit_range_low,fit_range_high);

	//begin combine fit
    TF1* fmass_combinemassvnfit = new TF1(Form("fmass_combinemassvnfit_%s_%d",cfgname.Data(),ipt),"[0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x", fit_range_low, fit_range_high);

	TF1* fvn_combinemassvnfit = new TF1(Form("fvn_combinemassvnfit_%s_%d",cfgname.Data(),ipt), "( ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) ) / ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x ) ) * [13] + ( 1.0 - ( ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) ) / ( [0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x ) ) ) * ( [14] + [15] * x + [16] * x * x)", fit_range_low, fit_range_high);

	ROOT::Math::WrappedMultiTF1 wfmass_combinemassvnfit(*fmass_combinemassvnfit,1);
	ROOT::Math::WrappedMultiTF1 wfvn_combinemassvnfit(*fvn_combinemassvnfit,1);

	ROOT::Fit::DataOptions opt;
	ROOT::Fit::DataRange range_massfit;
	// set the data range
	range_massfit.SetRange(fit_range_low,fit_range_high);
	ROOT::Fit::BinData datamass(opt,range_massfit);
	ROOT::Fit::FillData(datamass, histo);

	ROOT::Fit::DataRange range_vnfit;
	range_vnfit.SetRange(fit_range_low,fit_range_high);
	ROOT::Fit::BinData datavn(opt,range_vnfit);
	ROOT::Fit::FillData(datavn, h_vnvsmass);

	ROOT::Fit::Chi2Function chi2_B(datamass, wfmass_combinemassvnfit);
	ROOT::Fit::Chi2Function chi2_SB(datavn, wfvn_combinemassvnfit);

	GlobalChi2_poly3bkg_floatwidth_poly2bkg globalChi2(chi2_B, chi2_SB);

	ROOT::Fit::Fitter fitter;

	const int Npar = 17;
	double par0[Npar];
	for( int ipar = 0; ipar < f->GetNpar(); ipar++ )
		par0[ipar] = f->GetParameter(ipar);
	par0[13] = 0.01;
	par0[14] = 0.10;
	par0[15] = 0.05;
	par0[16] = 0.05;

	// create before the parameter settings in order to fix or set range on them
	fitter.Config().SetParamsSettings(Npar,par0);
	// fix parameter
	fitter.Config().ParSettings(2).Fix();
	fitter.Config().ParSettings(3).Fix();
	fitter.Config().ParSettings(4).Fix();
	fitter.Config().ParSettings(5).Fix();
	fitter.Config().ParSettings(7).Fix();
	fitter.Config().ParSettings(8).Fix();
	// set limits on the third and 4-th parameter
	fitter.Config().ParSettings(1).SetLimits(1.7, 2.0);
	//fitter.Config().ParSettings(12).SetStepSize(0.005);
	//fitter.Config().UseWeightCorrection();

	fitter.Config().MinimizerOptions().SetPrintLevel(0);
	fitter.Config().SetMinimizer("Minuit2","Migrad");

	// fit FCN function directly
	// (specify optionally data size and flag to indicate that is a chi2 fit)
	//fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),false);
	fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),true);
	ROOT::Fit::FitResult result = fitter.Result();
	result.Print(std::cout);

	fmass_combinemassvnfit->SetFitResult( result, iparmassfit_poly3bkg_floatwidth_poly2bkg);
	fmass_combinemassvnfit->SetRange(range_massfit().first, range_massfit().second);
	fmass_combinemassvnfit->SetLineColor(kRed);
	histo->GetListOfFunctions()->Add(fmass_combinemassvnfit);

	fvn_combinemassvnfit->SetFitResult( result, iparvnfit_poly3bkg_floatwidth_poly2bkg);
	fvn_combinemassvnfit->SetRange(range_vnfit().first, range_vnfit().second);
	fvn_combinemassvnfit->SetLineColor(4.0);
	fvn_combinemassvnfit->SetLineStyle(2);
	h_vnvsmass->GetListOfFunctions()->Add(fvn_combinemassvnfit);

	h_vnvspt->SetBinContent( ipt+1, fvn_combinemassvnfit->GetParameter(13));
	h_vnvspt->SetBinError( ipt+1, fvn_combinemassvnfit->GetParError(13));

	//double x[2] = {1.73, 1.864};
	//double error[2];
	//does not work
	//result.GetConfidenceIntervals(2, 1, 1, x, error, 0.683, false);

	//h_vnvspt_bkg->SetBinContent( ipt+1, fvn_combinemassvnfit->GetParameter(13) + fvn_combinemassvnfit->GetParameter(14) * 1.864);
	//h_vnvspt_bkg->SetBinError( ipt+1, error[0]);
	h_vnvspt_bkg->SetBinContent( ipt+1, fvn_combinemassvnfit->GetParameter(14) + fvn_combinemassvnfit->GetParameter(15) * 1.864 + fvn_combinemassvnfit->GetParameter(16) * 1.864 * 1.864);
	h_vnvspt_bkg->SetBinError( ipt+1, 0. );

	TCanvas* cfg_massfit_combinemassvn = new TCanvas(Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_massfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_massfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),600,600);

    gPad->SetRightMargin(0.043);
    gPad->SetLeftMargin(0.18);
//    gPad->SetTopMargin(0.1);
    gPad->SetBottomMargin(0.145);

	histo->SetXTitle("m_{#piK} (GeV/c^{2})");
	histo->SetYTitle("Entries / (5 MeV/c^{2})");
	histo->GetXaxis()->CenterTitle();
	histo->GetYaxis()->CenterTitle();
	//histo->SetAxisRange(0,histo->GetMaximum()*1.4*1.2,"Y");
	histo->GetXaxis()->SetRangeUser(fit_range_low+0.0001,fit_range_high-0.0001);
	histo->GetXaxis()->SetTitleOffset(1.3);
	histo->GetYaxis()->SetTitleOffset(1.8);
	histo->GetXaxis()->SetLabelOffset(0.007);
	histo->GetYaxis()->SetLabelOffset(0.007);
	histo->GetXaxis()->SetTitleSize(0.045);
	histo->GetYaxis()->SetTitleSize(0.045);
	histo->GetXaxis()->SetTitleFont(42);
	histo->GetYaxis()->SetTitleFont(42);
	histo->GetXaxis()->SetLabelFont(42);
	histo->GetYaxis()->SetLabelFont(42);
	histo->GetXaxis()->SetLabelSize(0.04);
	histo->GetYaxis()->SetLabelSize(0.04);
	histo->SetMarkerSize(0.8);
	histo->SetMarkerStyle(20);
	histo->SetStats(0);
	histo->Draw("e");
	
	TF1* background = new TF1(Form("background_%s_%d",cfgname.Data(),ipt),"[0]+[1]*x+[2]*x*x+[3]*x*x*x");
	background->SetParameter(0,fmass_combinemassvnfit->GetParameter(9));
	background->SetParameter(1,fmass_combinemassvnfit->GetParameter(10));
	background->SetParameter(2,fmass_combinemassvnfit->GetParameter(11));
	background->SetParameter(3,fmass_combinemassvnfit->GetParameter(12));
	background->SetLineColor(4);
	background->SetRange(fit_range_low,fit_range_high);
	background->SetLineStyle(2);

    TF1* mass = new TF1(Form("fmass_%s_%d",cfgname.Data(),ipt),"[0]*([5]*([4]*Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6]))))");
    mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(3),f->GetParameter(4),f->GetParameter(5),f->GetParameter(6));
    mass->SetParError(0,f->GetParError(0));
    mass->SetParError(1,f->GetParError(1));
    mass->SetParError(2,f->GetParError(2));
    mass->SetParError(3,f->GetParError(3));
    mass->SetParError(4,f->GetParError(4));
    mass->SetParError(5,f->GetParError(5));
    mass->SetParError(6,f->GetParError(6));
    mass->SetFillColor(kOrange-3);
    mass->SetFillStyle(3002);
    mass->SetLineColor(kOrange-3);
    mass->SetLineWidth(3);
    mass->SetLineStyle(2);

	TF1* massSwap = new TF1(Form("fmassSwap_%s_%d",cfgname.Data(),ipt),"[0]*(1-[2])*Gaus(x,[1],[3]*(1.0 +[4]))/(sqrt(2*3.14159)*[3]*(1.0 +[4]))");
	massSwap->SetParameters(fmass_combinemassvnfit->GetParameter(0),fmass_combinemassvnfit->GetParameter(8),fmass_combinemassvnfit->GetParameter(5),fmass_combinemassvnfit->GetParameter(7),fmass_combinemassvnfit->GetParameter(6));
	massSwap->SetParError(0,fmass_combinemassvnfit->GetParError(0));
	massSwap->SetParError(1,fmass_combinemassvnfit->GetParError(8));
	massSwap->SetParError(2,fmass_combinemassvnfit->GetParError(5));
	massSwap->SetParError(3,fmass_combinemassvnfit->GetParError(7));
	massSwap->SetParError(4,fmass_combinemassvnfit->GetParError(6));
	massSwap->SetFillColor(kGreen+4);
	massSwap->SetFillStyle(3005);
	massSwap->SetLineColor(kGreen+4);
	massSwap->SetLineWidth(3);
	massSwap->SetLineStyle(1);

	background->Draw("same");   
	mass->SetRange(fit_range_low,fit_range_high);	
	mass->Draw("same");
	massSwap->SetRange(fit_range_low,fit_range_high);
	massSwap->Draw("same");

	Double_t yield = mass->Integral(fit_range_low,fit_range_high)/histomassbinsize;
	Double_t yieldErr = mass->Integral(fit_range_low,fit_range_high)/histomassbinsize*mass->GetParError(0)/mass->GetParameter(0);

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

	TLatex Tl;
	Tl.SetNDC();
	Tl.SetTextAlign(12);
	Tl.SetTextSize(0.05);
	Tl.SetTextFont(42);
	Tl.DrawLatex(0.18,0.965, "#font[61]{CMS}");
	if( isPbPb )
		Tl.DrawLatex(0.61,0.965, "#scale[0.8]{PbPb #sqrt{s_{NN}} = 5.02 TeV}");
	else
		Tl.DrawLatex(0.65,0.965, "#scale[0.8]{pp #sqrt{s_{NN}} = 5.02 TeV}");

	TLatex* tex;

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

		tex = new TLatex(0.22,0.78,Form("Cent. %d-%d%%", centlow, centhigh));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

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

		tex = new TLatex(0.22,0.68,Form("N_{sig}: %d #pm %d",int(yield),int(yieldErr)));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();
	}
	else
	{
		tex = new TLatex(0.22,0.83,"|y| < 1.0");
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();

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

		tex = new TLatex(0.22,0.73,Form("N_{sig}: %d #pm %d",int(yield),int(yieldErr)));
		tex->SetNDC();
		tex->SetTextFont(42);
		tex->SetTextSize(0.04);
		tex->SetLineWidth(2);
		tex->Draw();
	}

	histo_copy_nofitfun->Draw("esame");

	if( get_sig_bkg_ratio )
	{
		for(int ibin = 0; ibin < histo->GetNbinsX(); ibin++)
		{
			double foreground = 0.;
			double signal = 0.;
			double ratio = 0.;
			double ratioError = 999.;

			double massbinleftedge = massmin + histomassbinsize * ibin;
			double massbinrightedge = massmin + histomassbinsize * (ibin+1);

			if( massbinleftedge > (fit_range_low - 0.0002) && massbinrightedge < (fit_range_high + 0.0002) )
			{
				foreground = f->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//foregroundErr = f->IntegralError(massbinleftedge, massbinrightedge)/histomassbinsize;
				//foreground =  histo->Integral(ibin+1, ibin+1);
				signal = mass->Integral(massbinleftedge, massbinrightedge)/histomassbinsize + massSwap->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//signal = mass->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//signal = foreground - background->Integral(massbinleftedge, massbinrightedge)/histomassbinsize;
				//signalErr = signal * yieldErr/yield;
				if( foreground > 0 )
				{
					ratio = signal/foreground;
					ratioError = TMath::Sqrt( foreground * ratio * (1.0 - ratio) ) / foreground;
				}
				else
				{
					ratio = 0.5;
					ratioError = 0.5;
				}
			}
			else
			{
				ratio = 0.0;
				ratioError = 1.0;
			}

			Ratio_signal_foreground->SetBinContent(ibin+1, ratio);
			Ratio_signal_foreground->SetBinError(ibin+1, ratioError);
		}

		TF1* Func_Ratio_signal_foreground = new TF1(Form("Func_Ratio_signal_foreground_%s_%d",cfgname.Data(),ipt),"([0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))))/([0]*([5]*([4]*TMath::Gaus(x,[1],[2]*(1.0 +[6]))/(sqrt(2*3.14159)*[2]*(1.0 +[6]))+(1-[4])*TMath::Gaus(x,[1],[3]*(1.0 +[6]))/(sqrt(2*3.14159)*[3]*(1.0 +[6])))+(1-[5])*TMath::Gaus(x,[8],[7]*(1.0 +[6]))/(sqrt(2*3.14159)*[7]*(1.0 +[6]))) + [9] + [10]*x + [11]*x*x + [12]*x*x*x)", generalfitrange_masslow, generalfitrange_masshigh);
        for( int ipar = 0; ipar < 13; ipar++ )
        {
            Func_Ratio_signal_foreground->SetParameter( ipar, f->GetParameter(ipar));
            Func_Ratio_signal_foreground->SetParError(ipar, f->GetParError(ipar));
        }
		Func_Ratio_signal_foreground->SetLineColor(2.0);
		Ratio_signal_foreground->GetListOfFunctions()->Add(Func_Ratio_signal_foreground);
	}

	if(isPbPb)
	{
		cfg_massfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/DMass_combinemassvnfit_isPbPb%d_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.pdf", isPbPb, cfgname.Data(), centlow, centhigh, ipt, vnorder.Data(),EPorSP.Data()));
		cfg_massfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/DMass_combinemassvnfit_isPbPb%d_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.png", isPbPb, cfgname.Data(), centlow, centhigh, ipt, vnorder.Data(),EPorSP.Data()));
	}

	TCanvas* cfg_vnfit_combinemassvn = new TCanvas(Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_vnfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),Form("cfg_poly3bkg_floatwidth_poly2bkg_combinemassvnfit_vnfit_combinemassvn_%s_%d_%s_%s",cfgname.Data(),ipt,vnorder.Data(),EPorSP.Data()),600,600);

	h_vnvsmass->GetYaxis()->SetRangeUser(-0.2, 0.6);
	if( vnorder == "v2") h_vnvsmass->GetYaxis()->SetTitle("v_{2}");
	if( vnorder == "v3") h_vnvsmass->GetYaxis()->SetTitle("v_{3}");
	h_vnvsmass->GetXaxis()->SetTitle("m_{#piK} (GeV/c^{2})");
	h_vnvsmass->GetXaxis()->SetTitleSize(0.05);
	h_vnvsmass->GetYaxis()->SetTitleSize(0.05);

	h_vnvsmass->SetMarkerColor(4.0);
	h_vnvsmass->SetLineColor(4.0);
	h_vnvsmass->SetMarkerStyle(21);
	h_vnvsmass->SetMarkerSize(1.3);
	h_vnvsmass->Draw();

    TLatex Tl2; 
    Tl2.SetNDC();
    Tl2.SetTextAlign(12);
    Tl2.SetTextSize(0.05);
    Tl2.SetTextFont(42);
    Tl2.DrawLatex(0.125,0.965, "#font[61]{CMS}");
    Tl2.DrawLatex(0.57,0.965, "#scale[0.8]{PbPb #sqrt{s_{NN}} = 5.02 TeV}");

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

    tex = new TLatex(0.18,0.78,Form("Cent. %d-%d%%", centlow, centhigh));
    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.04);
    tex->SetLineWidth(2);
    tex->Draw();

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

    if( vnorder == "v2" ) 
        tex = new TLatex(0.55,0.83,Form("v_{2}^{sig} = %.3f #pm %.3f",fvn_combinemassvnfit->GetParameter(13), fvn_combinemassvnfit->GetParError(13)));
    else if( vnorder == "v3" )
        tex = new TLatex(0.55,0.83,Form("v_{3}^{sig} = %.3f #pm %.3f",fvn_combinemassvnfit->GetParameter(13), fvn_combinemassvnfit->GetParError(13)));

    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.04);
    tex->SetLineWidth(2);
    tex->Draw();
	
	if(isPbPb)
	{
		cfg_vnfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/cfg_vnfit_combinemassvn_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.pdf",cfgname.Data(),centlow,centhigh,ipt,vnorder.Data(),EPorSP.Data()));
		cfg_vnfit_combinemassvn->SaveAs(Form("Plots_vn/combinemassvnfit/cfg_vnfit_combinemassvn_%s_cent%dto%d_%d_%s_%s_poly3bkg_floatwidth_poly2bkg_combinemassvnfit.png",cfgname.Data(),centlow,centhigh,ipt,vnorder.Data(),EPorSP.Data()));
	}

	return mass;
}
Exemple #12
0
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

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

  TDirectory *curdir = gDirectory;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	} // for ialpha

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

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

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

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

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

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

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

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

	  g->Draw("SAME Pz");

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

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

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

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

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

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

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

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


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

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

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

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

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

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

	const char *cs = samples[isample];

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

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

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

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

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

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

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


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

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

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

      TMultiGraph *mgk = new TMultiGraph();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  fin->Close();
  curdir->cd();
} // softrad
Exemple #13
0
//***############## main fitting Fxn ################ *****//
void FitPlotAndSave( char *Ifile ){
 
/** Plot Options***/	
//gROOT->Reset();
// gROOT->Clear();
gROOT->SetStyle("Plain") ;
gROOT->SetBatch(kFALSE);
gStyle->SetOptTitle(1);
gStyle->SetOptStat(0);
gStyle->SetOptFit(1);
gStyle->SetStatX(.89);
gStyle->SetStatY(.89) ;
gStyle->SetStatBorderSize(0);
//gStyle->SetOptStat(1111111)
gStyle->SetCanvasColor(kWhite);   // background is no longer mouse-dropping white
gStyle->SetPalette(1);        // blue to red false color palette. Use 9 for b/w
gStyle->SetCanvasBorderMode(0);     // turn off canvas borders
gStyle->SetPadBorderMode(0);
gStyle->SetPaintTextFormat("5.2f");  // What precision to put numbers if plotted with "TEXT"

// For publishing:
gStyle->SetLineWidth(2);
gStyle->SetTextSize(1.1);
gStyle->SetLabelSize(0.06,"xy");
gStyle->SetTitleSize(0.08,"xy");
gStyle->SetTitleOffset(1.2,"x");
gStyle->SetTitleOffset(1.0,"y");
gStyle->SetPadTopMargin(0.1);
gStyle->SetPadRightMargin(0.1);
gStyle->SetPadBottomMargin(0.16);
gStyle->SetPadLeftMargin(0.12);
TGaxis::SetMaxDigits(1); // Set Axis to be of the form 0.11 10^N


       TFile *ifile  = new TFile(Ifile);
        
	TF1 *fitFcn  = new TF1("fitFcn", mygaus, FitLowRange, FitHighRange, 3 );
	fitFcn->SetNpx(500);
	fitFcn->SetLineWidth(4);
	fitFcn->SetLineStyle(5);
	fitFcn->SetLineColor(kBlue);
        cout <<" Calling Fitting Fxntion" << endl;
	TH1F*h_Seed_TimeEBEB = (TH1F*)ifile->Get("EBEB/seed time");
	if(h_Seed_TimeEBEB == 0){ std::cout  <<"!! Histogram Does not exist!!" << std::endl; throw 1;}
        
	h_Seed_TimeEBEB->SetTitle("Seed Time[ns]");   
        h_Seed_TimeEBEB->SetMarkerStyle(20);
        h_Seed_TimeEBEB->SetMarkerSize(0.8);
        h_Seed_TimeEBEB->SetStats(1);
        h_Seed_TimeEBEB->SetTitleSize(0.08, "x");   
        h_Seed_TimeEBEB->SetTitleOffset(1.0, "x");    
        h_Seed_TimeEBEB->SetTitleSize(0.06, "y"); 
        h_Seed_TimeEBEB->SetTitleOffset(0.95, "y");    
        h_Seed_TimeEBEB->SetYTitle("Number of Seeds/0.05ns"); 
        h_Seed_TimeEBEB->SetXTitle("t_{seed}[ns]"); 
        h_Seed_TimeEBEB->GetXaxis()->SetRangeUser(FitLowRange, FitHighRange);   

       /** Set parms as parms of Fit Fxn **/
	fitFcn->SetParameters(500, h_Seed_TimeEBEB->GetMean(), h_Seed_TimeEBEB->GetRMS() );
	fitFcn->SetParNames("CONST", "#mu(ns)", "#sigma(ns)");
	h_Seed_TimeEBEB->Fit("fitFcn", "LL"); /**Fit with improved LL**/
	std::cout << "Printing Fit Parameters for EBEB ......   " << std::endl;
        printf("Integral of function in EBEB = %g\n", fitFcn->Integral( FitLowRange, FitHighRange));

        //*** retrive fit results***//
        int npar = fitFcn->GetNpar();
        TVirtualFitter *fit = TVirtualFitter::GetFitter();
        fit->PrintResults(2,0.);
        TMatrixD *CovMatrix = new TMatrixD ( npar, npar, fit->GetCovarianceMatrix() );
	CovMatrix->Print();
        TCanvas *c1 = new TCanvas("c1","EB-EB",200,10,800,900);
     	c1->SetGridx();
     	c1->SetGridy();
	c1->GetFrame()->SetFillColor(21);
	c1->GetFrame()->SetBorderMode(-1);
	c1->GetFrame()->SetBorderSize(5);
        /* c1->Divide(2,1);  */
	c1->cd();
	h_Seed_TimeEBEB->Draw();
	fitFcn->Draw("sames");
        c1->SetLogy(0);
	//  draw the legend
    	TLegend *leg = new TLegend(0.15,0.72,0.3,0.85);
       	leg->SetTextFont(72);
        leg->SetTextSize(0.04);
        leg->AddEntry(h_Seed_TimeEBEB,"EB","lpe");
        leg->AddEntry(fitFcn,"GAUS","l");
        leg->Draw();
	c1->SaveAs("Seed_Time_DoubleElectron_Run2012A-EB-EB.png");
}       
Exemple #14
0
// Determine sensitivity to tracker dynamic inefficiency
// by studying ratio of jet responses in Runs G and F (and BCD / F, E / F)
void drawAvsB() {

  setTDRStyle();

  string epocha = "BCD";//"BCD";//"H";//"F";//"BCD";//"F";//"E";//"BCD";//"F";
  string epochb = "GH";//"G";//"BCD";//"G";//"E";//"E";//"F";//"G";

  // Add the rest as well
  string epocha2 = "";//"EF";
  string epochb2 = "";//"G";

  string type = "data";

  vector<string> methods;
  methods.push_back("mpfchs1");
  methods.push_back("ptchs");
  bool nozjptb = false;
  bool nogjmpf = false;
  bool nogjptb = true;
  bool mjvsjes = false;
  
  vector<string> samples;
  samples.push_back("zeejet");
  samples.push_back("zmmjet");
  samples.push_back("gamjet");
  //samples.push_back("multijet");

  cout << "draw"<<epocha<<"vs"<<epochb<<endl;
  const char *ct = type.c_str();
  const char *pa = epocha.c_str();
  const char *pb = epochb.c_str();

  const char *pa2 = epocha2.c_str();
  const char *pb2 = epochb2.c_str();

  TFile *fg = new TFile(Form("rootfiles/jecdata%s.root",pb),"READ");
  assert(fg && !fg->IsZombie());

  TFile *ff = new TFile(Form("rootfiles/jecdata%s.root",pa),"READ");
  assert(ff && !ff->IsZombie());

  TFile *fg2(0), *ff2(0);
  if (epochb2!="") fg2 = new TFile(Form("rootfiles/jecdata%s.root",pb2),"READ");
  if (epocha2!="") ff2 = new TFile(Form("rootfiles/jecdata%s.root",pa2),"READ");

  TH1D *h = new TH1D("h",
		     Form(";p_{T,ref} (GeV);%s ratio (%s / %s)",
			  (type=="ratio" ? "Data/MC" :
			   type=="data" ? "Data/data" : "MC/MC"),
			  (epocha + (epocha2!="" ? "+"+epocha2 : "")).c_str(),
			  (epochb + (epochb2!="" ? "+"+epochb2 : "")).c_str()),
		     3470,30,3500);
  h->SetMinimum(0.90);
  h->SetMaximum(1.15);
  h->GetXaxis()->SetMoreLogLabels();
  h->GetXaxis()->SetNoExponent();

  if (epocha=="F" && epochb=="G")
    lumi_13TeV = "Run2016F+G, 3.1+7.1 fb^{-1}";
  if (epocha=="BCD" && epochb=="G")
    lumi_13TeV = "Run2016BCD+H, 12.9+8.8 fb^{-1}";
  if (epocha=="BCD" && epochb=="G")
    lumi_13TeV = "Run2016BCD+FearlyGH, 12.9+16.8 fb^{-1}";
  if (epocha=="BCD" && epochb=="F")
    lumi_13TeV = "Run2016BCD+F, 13+3.1 fb^{-1}";
  if (epocha=="BCD" && epochb=="E")
    lumi_13TeV = "Run2016BCD+E, 13+4.0 fb^{-1}";
  if (epocha=="E" && epochb=="F")
    lumi_13TeV = "Run2016E+F, 4.0+3.1 fb^{-1}";
  if (epocha=="F" && epochb=="E")
    lumi_13TeV = "Run2016E+F, 4.0+3.1 fb^{-1}";

  if ((epocha=="BCDEF" && epochb=="GH") ||
      (epocha=="BCD" && epocha2=="EF" && epochb=="H" && epochb2=="G")) 
    lumi_13TeV = "Run2016BCDEF+GH, 19.7+16.8 fb^{-1}";
  if (epocha=="EF" && epochb=="BCD")
    lumi_13TeV = "Run2016BCD+EF, 12.9+6.8 fb^{-1}";
  if (epocha=="H" && epochb=="G")
    lumi_13TeV = "Run2016G+H, 8.0+8.8 fb^{-1}";

  if ((epocha=="BCD" && epocha2=="EF" && epochb=="G" && epochb2=="H")) 
    lumi_13TeV = "Run2016BCDFearly+FlateGH, 19.7+16.8 fb^{-1}";

  if ((epocha=="BCD" && epocha2=="" && ((epochb=="GH" && epochb2=="") ||
					(epochb=="G" && epochb2=="H"))))
    lumi_13TeV = "Run2016BCD+FlateGH, 12.9+16.8 fb^{-1}";
  if ((epocha=="EF" && epocha2=="" && ((epochb=="GH" && epochb2=="") ||
				       (epochb=="G" && epochb2=="H"))))
    lumi_13TeV = "Run2016EF+FlateGH, 6.8+16.8 fb^{-1}";

  if ((epocha=="EF" && epocha2=="" && epochb=="G" && epochb2=="H")) 
    lumi_13TeV = "Run2016EFearly+FlateGH, 6.8+16.8 fb^{-1}";


  TCanvas *c1 = tdrCanvas("c1",h,4,11,true);
  c1->SetLogx();

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

  TMultiGraph *mg = new TMultiGraph();
  string s = "draw"+epocha+(epocha2!="" ? "p" + epocha2 : "")
    +"vs"+epochb+(epochb2!="" ? "p" + epochb2 : "");

  TGraphErrors *gmjb(0), *gmpf(0);

  for (unsigned int im = 0; im != methods.size(); ++im) {
    const char *cm = methods[im].c_str();

    tex->DrawLatex(0.20,0.75-0.06*im,cm);
    s += "_" + methods[im];

  for (unsigned int is = 0; is != samples.size(); ++is) {

    const char *cs = samples[is].c_str();
    TGraphErrors *gg = (TGraphErrors*)fg->Get(Form("%s/eta00-13/%s_%s_a30",ct,cm,cs));
    cout << cm << " " << cs << endl << flush;
    assert(gg);
    if (fg2) {
      TGraphErrors *gg2 = (TGraphErrors*)fg2->Get(Form("%s/eta00-13/%s_%s_a30",ct,cm,cs));
      assert(gg2);
      gg = addGraph(gg,gg2);
    }
    
    TGraphErrors *gf = (TGraphErrors*)ff->Get(Form("%s/eta00-13/%s_%s_a30",ct,cm,cs));
    assert(gf);
    if (ff2) {
      TGraphErrors *gf2 = (TGraphErrors*)ff2->Get(Form("%s/eta00-13/%s_%s_a30",ct,cm,cs));
      assert(gf2);
      gf = addGraph(gf,gf2);
    }
    
    if (!(gf->GetN()==gg->GetN())) {

      // Remove highest pT point is that is the offender (BCD vs GH)
      if (gg->GetN()>gf->GetN() &&
	  fabs(gg->GetX()[gg->GetN()-1]/gf->GetX()[gf->GetN()-1]-1)>0.1 &&
	  fabs(gg->GetX()[gg->GetN()-2]/gf->GetX()[gf->GetN()-1]-1)<0.1) {
	cout << "Remove point B(N-1)" << endl;
	gg->RemovePoint(gg->GetN()-1);
      }
      else {
	cout << "sample " << samples[is] << " method " << methods[im]
	     << " gf->N: " << gf->GetN() << " gg->N: " << gg->GetN() << endl;
	cout << " x_gf(N-1)=" << gf->GetX()[gf->GetN()-1]
	     << " x_gg(N-1)=" << gg->GetX()[gg->GetN()-1]
	     << " x_gg(N-2)=" << gg->GetX()[gg->GetN()-2] << endl;
      }

      assert(gf->GetN()==gg->GetN());
    }

    TGraphErrors *g = (TGraphErrors*)gg->Clone(Form("ge_%s_%s",cm,cs));
    for (int i = 0; i != g->GetN(); ++i) {
      double yg = gg->GetY()[i];
      double yf = gf->GetY()[i];
      g->SetPoint(i, gg->GetX()[i], yf / yg);
      double ex = gg->GetEX()[i];
      double eg = gg->GetEY()[i];
      double ef = gf->GetEY()[i];
      g->SetPointError(i, ex, yf/yg*sqrt(pow(eg/yg,2)+pow(ef/yf,2)));
    }
    //g->Draw(is==0 ? "AP" : "SAMEP");
    g->SetLineWidth(1+is);
    g->Draw("SAMEPZ");

    if (samples[is]=="gamjet" && methods[im]=="mpfchs1" && nogjmpf) {
      tex->SetTextColor(kBlue);
      tex->DrawLatex(0.20,0.63,"#gamma+jet MPF excl. from fit");
      tex->SetTextColor(kBlack);
    }
    else if (samples[is]=="gamjet" && methods[im]=="ptchs" && nogjptb) {
      tex->SetTextColor(kBlue);
      tex->DrawLatex(0.20,0.63,"#gamma+jet p_{T}^{bal} excl. from fit");
      tex->SetTextColor(kBlack);
    }
    else if ((samples[is]=="zmmjet" || samples[is]=="zeejet") &&
	     methods[im]=="ptchs" && nozjptb) {
      tex->SetTextColor(kRed);
      tex->DrawLatex(0.20,0.63,"Z+jet p_{T}^{bal} excl. from fit");
      tex->SetTextColor(kBlack);
    }
    else if (samples[is]=="multijet") {
      g->SetMarkerColor(kGray+1);
      g->SetLineColor(kGray+1);
      if (methods[im]=="ptchs") gmjb = g;
      if (methods[im]=="mpfchs1") gmpf = g;
    }
    else
      mg->Add(g);
  } // for is
  } // for im
  
  if (nogjmpf) s += "_nogjmpf";
  if (nogjptb) s += "_nogptb";
  if (nozjptb) s += "_nozptb";
  if (mjvsjes) {
    s += "_mjvsjes";
    tex->SetTextColor(kBlack);
    tex->DrawLatex(0.20,0.58,"Multijet vs JES fit");
  }

  TF1 *fjes = new TF1("fjes",jesFit,30,2200,2);
  fjes->SetParameters(0.99,0.05);
  mg->Fit(fjes,"RN");
  fjes->SetLineColor(kBlack);
  fjes->SetLineStyle(kDashed);
  fjes->SetLineWidth(2);
  fjes->SetRange(10.,3500.);
  fjes->Draw("SAME");
  
  //TF1 *ft = new TF1("ft","1-[0]-[1]*pow(x,[2]) + ([3]+[4]*log(x))/x",30,2200);
  //ft->SetParameters(0,0.05,-0.5,1,0.1);
  //ft->FixParameter(3,0);

  // Logarithmic sigmoid
  //TF1 *ft = new TF1("ft","[0]+(1-[0])/(1. + exp(-(log(x)-log(abs([1])))"
  //	       "/(log(abs([2])+abs([1]))-log(abs([1])))))", 30,2200);
  //ft->SetParameters(0.98, 150, 50);
  TF1 *ft = new TF1("ft","[0]+(1-[0])/(1. + exp(-(log(x)-[1])/[2]))",30,2200);
  //ft->SetParameters(0.98,log(145),log(190)-log(145));
  //ft->SetParameters(0.982,4.967,0.271);
  //ft->SetParameters(0.976,5.040,0.370); // ENDCAP
  //ft->SetParameters(0.985,5.0,0.3);
  ft->SetParameters(0.985,5.025,0.3);
  //ft->FixParameter(1,5.03); // semi-weighted average of BCD and EF
  //ft->FixParameter(2,0.395); // combined fit to BCD+EF / G+H 

  // ( 12.9*5.055+6.8*5.000)/(12.9+6.8)
  ft->FixParameter(1,5.036); // semi-weighted average of BCD/GH and EF/GH
  // ( 12.9*0.344 + 6.8*0.455)/(12.9+6.8)
  ft->FixParameter(2,0.391); // combined fit to BCD+EF / GH 

  // Log-sigmoid + powerlaw
  //TF1 *ft = new TF1("ft","[0]+(1-[0])/(1. + exp(-(log(x)-[1])/[2]))"
  //	       "*(1-[3]*pow(x,[4]))",30,2200);
  //ft->SetParameters(0.982,4.967,0.271,0.1,-0.2);
  // Double powerlaw
  //TF1 *ft = new TF1("ft","[4]-[0]*pow(x,[1])-[2]*pow(x,[3])",30,2200);
  //ft->SetParameters(0.05,-0.15,0.01,-0.3,1);
  

  mg->Fit(ft,"RN");
  ft->SetLineColor(kBlue);
  ft->SetLineWidth(2);
  ft->SetRange(10.,3500.);
  ft->Draw("SAME");

  // Map multijet with response ratio
  if (gmpf) { // we have multijet available
    TGraphErrors *gmpf2 = (TGraphErrors*)gmpf->Clone("gmpf2");
    gmpf2->SetMarkerColor(kBlack);//kGray+1);
    gmpf2->SetLineColor(kBlack);//kGray+1);
    for (int i = 0; i != gmpf->GetN(); ++i) {
      if (mjvsjes) {
	gmpf2->SetPoint(i, 0.4*gmpf->GetX()[i],
			fjes->Eval(gmpf->GetX()[i])/gmpf->GetY()[i]);
	gmpf2->SetPointError(i, 0.4*gmpf->GetEX()[i],
			     gmpf->GetEY()[i]);
      }
      else {
	gmpf2->SetPoint(i, 0.4*gmpf->GetX()[i],
			ft->Eval(gmpf->GetX()[i])/gmpf->GetY()[i]);
	gmpf2->SetPointError(i, 0.4*gmpf->GetEX()[i],
			     gmpf->GetEY()[i]);
      }
    }
    gmpf2->Draw("SAMEPz");
  } // multijet

  tex->SetTextColor(kBlue);
  tex->DrawLatex(0.50,0.85,Form("#chi^{2} / NDF = %1.1f / %d",
				ft->GetChisquare(),
				ft->GetNDF()));
  tex->SetTextColor(kBlack);
  tex->SetTextSize(0.040);
  tex->DrawLatex(0.50,0.80,Form("(#chi^{2} / NDF = %1.1f / %d)",
				fjes->GetChisquare(),
				fjes->GetNDF()));


  tex->SetTextColor(kBlue-9);
  tex->SetTextSize(0.030);
  tex->DrawLatex(0.20,0.25,ft->GetExpFormula());
  tex->DrawLatex(0.20,0.20,
		 Form("p_{0}=%1.3f#pm%1.3f"
		      ", p_{1}=%1.3f#pm%1.3f"
		      ", p_{2}=%1.3f#pm%1.3f",
		      ft->GetParameter(0),ft->GetParError(0),
		      ft->GetParameter(1),ft->GetParError(1),
		      ft->GetParameter(2),ft->GetParError(2)));
  if (ft->GetNpar()>3)
    tex->DrawLatex(0.20,0.17,
		   Form("p_{3}=%1.3f#pm%1.3f"
			", p_{4}=%1.3f#pm%1.3f",
			ft->GetParameter(3),ft->GetParError(3),
			ft->GetParameter(4),ft->GetParError(4)));

  c1->SaveAs(Form("pdf/%s.pdf",s.c_str()));

  for (int i = 0; i != ft->GetNpar(); ++i) {
    cout << Form("%s%1.4g",i==0 ? "{" : ", ",ft->GetParameter(i));
  }
  cout << "}" << endl;
    

}