Esempio n. 1
0
void mathBeta() {
  TCanvas *c1=new TCanvas("c1", "TMath::BetaDist",600,800);
  c1->Divide(1, 2);
  TVirtualPad *pad1 = c1->cd(1);
  pad1->SetGrid();
  TF1 *fbeta = new TF1("fbeta", "TMath::BetaDist(x, [0], [1])", 0, 1);
  fbeta->SetParameters(0.5, 0.5);
  TF1 *f1 = fbeta->DrawCopy();
  f1->SetLineColor(kRed);
  f1->SetLineWidth(1);
  fbeta->SetParameters(0.5, 2);
  TF1 *f2 = fbeta->DrawCopy("same");
  f2->SetLineColor(kGreen);
  f2->SetLineWidth(1);
  fbeta->SetParameters(2, 0.5);
  TF1 *f3 = fbeta->DrawCopy("same");
  f3->SetLineColor(kBlue);
  f3->SetLineWidth(1);
  fbeta->SetParameters(2, 2);
  TF1 *f4 = fbeta->DrawCopy("same");
  f4->SetLineColor(kMagenta);
  f4->SetLineWidth(1);
  TLegend *legend1 = new TLegend(.5,.7,.8,.9);
  legend1->AddEntry(f1,"p=0.5  q=0.5","l");
  legend1->AddEntry(f2,"p=0.5  q=2","l");
  legend1->AddEntry(f3,"p=2    q=0.5","l");
  legend1->AddEntry(f4,"p=2    q=2","l");
  legend1->Draw();

  TVirtualPad *pad2 = c1->cd(2);
  pad2->SetGrid();
  TF1 *fbetai=new TF1("fbetai", "TMath::BetaDistI(x, [0], [1])", 0, 1);
  fbetai->SetParameters(0.5, 0.5);
  TF1 *g1=fbetai->DrawCopy();
  g1->SetLineColor(kRed);
  g1->SetLineWidth(1);
  fbetai->SetParameters(0.5, 2);
  TF1 *g2=fbetai->DrawCopy("same");
  g2->SetLineColor(kGreen);
  g2->SetLineWidth(1);
  fbetai->SetParameters(2, 0.5);
  TF1 *g3=fbetai->DrawCopy("same");
  g3->SetLineColor(kBlue);
  g3->SetLineWidth(1);
  fbetai->SetParameters(2, 2);
  TF1 *g4=fbetai->DrawCopy("same");
  g4->SetLineColor(kMagenta);
  g4->SetLineWidth(1);

  TLegend *legend2 = new TLegend(.7,.15,0.9,.35);
  legend2->AddEntry(f1,"p=0.5  q=0.5","l");
  legend2->AddEntry(f2,"p=0.5  q=2","l");
  legend2->AddEntry(f3,"p=2    q=0.5","l");
  legend2->AddEntry(f4,"p=2    q=2","l");
  legend2->Draw();
  c1->cd();
}
Esempio n. 2
0
void mathLaplace(){
   TCanvas *c1=new TCanvas("c1", "TMath::LaplaceDist",600,800);
   c1->Divide(1, 2);
   TVirtualPad *pad1 = c1->cd(1);
   pad1->SetGrid();
   TF1 *flaplace = new TF1("flaplace", "TMath::LaplaceDist(x, [0], [1])", -10, 10);
   flaplace->SetParameters(0, 1);
   TF1 *f1 = flaplace->DrawCopy();
   f1->SetLineColor(kRed);
   f1->SetLineWidth(1);
   flaplace->SetParameters(0, 2);
   TF1 *f2 = flaplace->DrawCopy("same");
   f2->SetLineColor(kGreen);
   f2->SetLineWidth(1);
   flaplace->SetParameters(2, 1);
   TF1 *f3 = flaplace->DrawCopy("same");
   f3->SetLineColor(kBlue);
   f3->SetLineWidth(1);
   flaplace->SetParameters(2, 2);
   TF1 *f4 = flaplace->DrawCopy("same");
   f4->SetLineColor(kMagenta);
   f4->SetLineWidth(1);
   TLegend *legend1 = new TLegend(.7,.7,.9,.9);
   legend1->AddEntry(f1,"alpha=0 beta=1","l");
   legend1->AddEntry(f2,"alpha=0 beta=2","l");
   legend1->AddEntry(f3,"alpha=2 beta=1","l");
   legend1->AddEntry(f4,"alpha=2 beta=2","l");
   legend1->Draw();

   TVirtualPad *pad2 = c1->cd(2);
   pad2->SetGrid();
   TF1 *flaplacei=new TF1("flaplacei", "TMath::LaplaceDistI(x, [0], [1])", -10, 10);
   flaplacei->SetParameters(0, 1);
   TF1 *g1=flaplacei->DrawCopy();
   g1->SetLineColor(kRed);
   g1->SetLineWidth(1);
   flaplacei->SetParameters(0, 2);
   TF1 *g2=flaplacei->DrawCopy("same");
   g2->SetLineColor(kGreen);
   g2->SetLineWidth(1);
   flaplacei->SetParameters(2, 1);
   TF1 *g3=flaplacei->DrawCopy("same");
   g3->SetLineColor(kBlue);
   g3->SetLineWidth(1);
   flaplacei->SetParameters(2, 2);
   TF1 *g4=flaplacei->DrawCopy("same");
   g4->SetLineColor(kMagenta);
   g4->SetLineWidth(1);

   TLegend *legend2 = new TLegend(.7,.15,0.9,.35);
   legend2->AddEntry(f1,"alpha=0 beta=1","l");
   legend2->AddEntry(f2,"alpha=0 beta=2","l");
   legend2->AddEntry(f3,"alpha=2 beta=1","l");
   legend2->AddEntry(f4,"alpha=2 beta=2","l");
   legend2->Draw();
   c1->cd();
}
Esempio n. 3
0
// tutorial illustrating the use of TMath::GammaDist and TMath::LogNormal
void mathGammaNormal(){
  TCanvas *myc = new TCanvas("c1","gamma and lognormal",10,10,600,800);
  myc->Divide(1,2);
  TPad *pad1 = myc->cd(1);
  pad1->SetLogy();
  pad1->SetGrid();

  //TMath::GammaDist
  TF1 *fgamma = new TF1("fgamma", "TMath::GammaDist(x, [0], [1], [2])", 0, 10);
  fgamma->SetParameters(0.5, 0, 1);
  TF1 *f1 = fgamma->DrawCopy();
  f1->SetMinimum(1e-5);
  f1->SetLineColor(kRed);
  fgamma->SetParameters(1, 0, 1);
  TF1 *f2 = fgamma->DrawCopy("same");
  f2->SetLineColor(kGreen);
  fgamma->SetParameters(2, 0, 1);
  TF1 *f3 = fgamma->DrawCopy("same");
  f3->SetLineColor(kBlue);
  fgamma->SetParameters(5, 0, 1);
  TF1 *f4 = fgamma->DrawCopy("same");
  f4->SetLineColor(kMagenta);
  TLegend *legend1 = new TLegend(.2,.15,.5,.4);
  legend1->AddEntry(f1,"gamma = 0.5 mu = 0  beta = 1","l");
  legend1->AddEntry(f2,"gamma = 1   mu = 0  beta = 1","l");
  legend1->AddEntry(f3,"gamma = 2   mu = 0  beta = 1","l");
  legend1->AddEntry(f4,"gamma = 5   mu = 0  beta = 1","l");
  legend1->Draw();

  //TMath::LogNormal
  TPad *pad2 = myc->cd(2);
  pad2->SetLogy();
  pad2->SetGrid();
  TF1 *flog = new TF1("flog", "TMath::LogNormal(x, [0], [1], [2])", 0, 5);
  flog->SetParameters(0.5, 0, 1);
  TF1 *g1 = flog->DrawCopy();
  g1->SetLineColor(kRed);
  flog->SetParameters(1, 0, 1);
  TF1 *g2 = flog->DrawCopy("same");
  g2->SetLineColor(kGreen);
  flog->SetParameters(2, 0, 1);
  TF1 *g3 = flog->DrawCopy("same");
  g3->SetLineColor(kBlue);
  flog->SetParameters(5, 0, 1);
  TF1 *g4 = flog->DrawCopy("same");
  g4->SetLineColor(kMagenta);
  TLegend *legend2 = new TLegend(.2,.15,.5,.4);
  legend2->AddEntry(g1,"sigma = 0.5 theta = 0  m = 1","l");
  legend2->AddEntry(g2,"sigma = 1   theta = 0  m = 1","l");
  legend2->AddEntry(g3,"sigma = 2   theta = 0  m = 1","l");
  legend2->AddEntry(g4,"sigma = 5   theta = 0  m = 1","l");
  legend2->Draw();
}
Esempio n. 4
0
void tStudent()
{

   //gSystem->Load("libMathMore");
   // this is the way to force load of MathMore in Cling
   ROOT::Math::MathMoreLibrary::Load();

   int n=100;
   double a=-5.;
   double b=5.;
   //double r  = 3;
   TF1* pdf = new TF1("pdf", "ROOT::Math::tdistribution_pdf(x,3.0)", a,b);
   TF1* cum = new TF1("cum", "ROOT::Math::tdistribution_cdf(x,3.0)", a,b);

   TH1D* quant = new TH1D("quant", "", 9, 0, 0.9);

   for(int i=1; i < 10; i++)
      quant->Fill((i-0.5)/10.0, ROOT::Math::tdistribution_quantile((1.0*i)/10, 3.0 ) );

   double xx[10];
   xx[0] = -1.5;
   for(int i=1; i<9; i++)
      xx[i]= quant->GetBinContent(i);
   xx[9] = 1.5;
   TH1D* pdfq[10];
   //int nbin = n/10.0;
   for(int i=0; i < 9; i++) {
      int nbin = n * (xx[i+1]-xx[i])/3.0 + 1.0;
      TString name = "pdf";
      name += i;
      pdfq[i]= new TH1D(name, "", nbin,xx[i],xx[i+1] );
      for(int j=1; j<nbin; j++) {
         double x= j*(xx[i+1]-xx[i])/nbin + xx[i];
         pdfq[i]->SetBinContent(j, ROOT::Math::tdistribution_pdf(x,3));
      }
   }

   TCanvas *Canvas = new TCanvas("DistCanvas", "Student Distribution graphs", 10, 10, 800, 700);
   pdf->SetTitle("Student t distribution function");
   cum->SetTitle("Cumulative for Student t");
   quant->SetTitle("10-quantiles  for Student t");
   Canvas->Divide(2, 2);
   Canvas->cd(1);
   pdf->SetLineWidth(2);
   pdf->DrawCopy();
   Canvas->cd(2);
   cum->SetLineWidth(2);
   cum->SetLineColor(kRed);
   cum->Draw();
   Canvas->cd(3);
   quant->Draw();
   quant->SetLineWidth(2);
   quant->SetLineColor(kBlue);
   quant->SetStats(0);
   Canvas->cd(4);
   pdfq[0]->SetTitle("Student t & its quantiles");
   pdf->SetTitle("");
   pdf->Draw();
   //pdfq[0]->SetAxisRange(-1.5, 0, 1.5,1.0);
   pdfq[0]->SetTitle("Student t & its quantiles");
   for(int i=0; i < 9; i++) {
      pdfq[i]->SetStats(0);
      pdfq[i]->SetFillColor(i+1);
      pdfq[i]->Draw("same");
   }
   Canvas->Modified();
   Canvas->cd();
}
int BDTInterpolation(std::string inFileName,bool Diagnose=false, bool doNorm=true, bool doSidebands=false){

  std::cout << getTime() << std::endl;

  system("rm -r plots");
  system("mkdir plots");

  //gROOT->SetBatch();
  gStyle->SetOptStat(0);

  // input flags
  bool all=0;
 
  if (Diagnose) {
    std::cout << "Diagnostics turned on \n Output plots available in \"plots\" directory \n Diagnostic log available in \"plots/BDTInterpolationDiagnostics.txt\"" << std::endl;
    all = true;
  }
  else std::cout << "Diagnostics turned off" << std::endl;
  if (doNorm) std::cout << "Normalization turned on" << std::endl;
  else std::cout << "Normalization turned off" << std::endl;
  if (doSidebands) std::cout << "Background model from sidebands turned on" << std::endl;
  else std::cout << "Background model from sidebands turned off" << std::endl;

  TFile *inFile = new TFile(inFileName.c_str());
  //TFile *inFile = new TFile("/vols/cms02/nw709/hgg/src_cvs/oct13/CMSSW_4_2_8/src/HiggsAnalysis/HiggsTo2photons/h2gglobe/Macros/CMS-HGG_1658pb_mva.root");
  //TFile *inFile = new TFile("RefWorkspaces/CMS-HGG_1658pb_mva.root");
  TFile *outFile = new TFile(Form("%s_interpolated.root",inFileName.c_str()),"RECREATE");
  TFile *systTestF = new TFile("systTest.root","RECREATE");
  ofstream diagFile("plots/BDTInterpolationDiagnostics.txt");

  const int nBDTs=2;
  const int nMasses=8;
  const int nProds=4;
  std::string BDTtype[nBDTs] = {"ada","grad"};
  std::string BDTmasses[nMasses] = {"110.0","115.0","120.0","125.0","130.0","135.0","140.0","150.0"};
  std::string productionTypes[nProds] = {"ggh","vbf","wzh","tth"};
// ----- else can just get rebinned histograms straight out of workspace

  std::cout << "Extracting histograms from workspace........." << std::endl;

  diagFile << "Diagnostics for Signal Interpolation run at " << getTime() << std::endl;
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Following orginal histograms rewritten into new workspace: " << std::endl;
  
  // ------ stuff for interpolation systematic -------
  TH1F *systHists120[2][3];
  TH1F *systHists135[2][3];

  std::string syst120mass[3] = {"120.0","115.0","125.0"};
  std::string syst135mass[3] = {"135.0","130.0","140.0"};
  // ---------------------------------------------------
  
  // make plots of background model from sidebands
  if (doSidebands){
    for (int bdt=0; bdt<nBDTs; bdt++){
      for (double mass=110.; mass<=150.0; mass+=0.5){
        TList *bkgModelList = new TList();
        TH1F *bkgModel[7];
        bkgModel[0] = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[1] = (TH1F*)inFile->Get(Form("th1f_bkg_3low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[2] = (TH1F*)inFile->Get(Form("th1f_bkg_2low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[3] = (TH1F*)inFile->Get(Form("th1f_bkg_1low_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[4] = (TH1F*)inFile->Get(Form("th1f_bkg_1high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[5] = (TH1F*)inFile->Get(Form("th1f_bkg_2high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        bkgModel[6] = (TH1F*)inFile->Get(Form("th1f_bkg_3high_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        for (int i=0; i<7; i++) {
          bkgModelList->Add(bkgModel[i]);
        }
        std::string name(Form("%3.1f",mass));
        plotBkgModel(bkgModelList,name);
      }
    }
  }
  
  // write original histograms in out file
  TList *HistList = inFile->GetListOfKeys();
  for (int j=0; j<HistList->GetSize(); j++){
    TH1F *temp = (TH1F*)inFile->Get(HistList->At(j)->GetName());
    TString name = temp->GetName();

    // store stuff for interpolation systematic
    for (int bdt=0; bdt<nBDTs; bdt++){
      for (int syst=0; syst<3; syst++){
        if (name.Contains(("th1f_sig_"+BDTtype[bdt]+"_"+productionTypes[0]+"_"+syst120mass[0]+"_"+syst120mass[syst]).c_str()) && !name.Contains("sigma")){
          systHists120[bdt][syst] = (TH1F*)inFile->Get(name.Data());
          systHists120[bdt][syst]->SetLineColor(syst+2);
        }
        if (name.Contains(("th1f_sig_"+BDTtype[bdt]+"_"+productionTypes[0]+"_"+syst135mass[0]+"_"+syst135mass[syst]).c_str()) && !name.Contains("sigma")){
          systHists135[bdt][syst] = (TH1F*)inFile->Get(name.Data());
          systHists135[bdt][syst]->SetLineColor(syst+2);
        }
      }
    }
    // ---------------------------------------------
    std::string tName = temp->GetName();
    for (int i=0; i<nMasses; i++){
      int ind = tName.find(BDTmasses[i]+"_"+BDTmasses[i]);
      if (ind>0) tName.replace(ind,11,BDTmasses[i]);
    }
    temp->SetName(tName.c_str());
      
    outFile->cd();
    temp->Write();
    diagFile << "Histo written: " << temp->GetName() << std::endl;
  }

  // ----------- Do stuff for interpolation systematic ------------
  std::cout << "Creating interpolation systematic templates......." << std::endl;

  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Writing following interpolation systematic templates: " << std::endl;
  
  for (int bdt=0; bdt<nBDTs; bdt++){
    double norm120 = GetNorm(115.0,systHists120[bdt][1],125.0,systHists120[bdt][2],120.0);
    double norm135 = GetNorm(130.0,systHists135[bdt][1],140.0,systHists135[bdt][2],135.0);
    if (doNorm) {
      systHists120[bdt][1]->Scale(1./(GetXsection(115.0)*GetBR(115.0)));
      systHists120[bdt][2]->Scale(1./(GetXsection(125.0)*GetBR(125.0)));
      systHists135[bdt][1]->Scale(1./(GetXsection(130.0)*GetBR(130.0)));
      systHists135[bdt][2]->Scale(1./(GetXsection(140.0)*GetBR(140.0)));
    }
    TH1F *int120 = Interpolate(115.0,systHists120[bdt][1],125.0,systHists120[bdt][2],120.0);
    TH1F *int135 = Interpolate(130.0,systHists135[bdt][1],140.0,systHists135[bdt][2],135.0);
    if (doNorm) {
      systHists120[bdt][1]->Scale(GetXsection(115.0)*GetBR(115.0));
      systHists120[bdt][2]->Scale(GetXsection(125.0)*GetBR(125.0));
      systHists135[bdt][1]->Scale(GetXsection(130.0)*GetBR(130.0));
      systHists135[bdt][2]->Scale(GetXsection(140.0)*GetBR(140.0));
    }
    if (doNorm) {
      int120->Scale(norm120/int120->Integral());
      int135->Scale(norm135/int135->Integral());
    }
    
    TList *int120list = new TList();
    int120list->Add(systHists120[bdt][1]);
    int120list->Add(systHists120[bdt][2]);
    int120list->Add(int120);
    plotFrac(int120list,systHists120[bdt][0],"syst120",false);
    
    TList *int135list = new TList();
    int135list->Add(systHists135[bdt][1]);
    int135list->Add(systHists135[bdt][2]);
    int135list->Add(int135);
    plotFrac(int135list,systHists135[bdt][0],"syst135",false);
    TH1F *frac=(TH1F*)systHists135[bdt][0]->Clone();
    frac->Add(int135,-1);
    frac->Divide(int135);
    TH1F *linFrac = (TH1F*)linearBin(frac);
    linFrac->GetYaxis()->SetRangeUser(-0.4,0.4);
    TCanvas *c = new TCanvas();
    systTestF->cd();
    linFrac->Write();
    linFrac->Draw();
    TF1 *fit = new TF1("fit","[0]*(x-36.)^2",0.,36.);
    linFrac->Fit(fit,"q");
    fit->DrawCopy("same");
    fit->SetLineColor(kGray);
    fit->SetLineStyle(2);
    double var = fit->GetParameter(0);
    double err = fit->GetParError(0);
    fit->SetParameter(0,var+err);
    fit->DrawCopy("same");
    fit->SetParameter(0,var-err);
    fit->DrawCopy("same");

    c->Print(Form("plots/%s/fracs/systTest135.png",BDTtype[bdt].c_str()),"png");

    // get plus and minus templates
    std::pair<TH1F*,TH1F*> result135 = GetPMSyst(systHists135[bdt][0],int135,"th1f_sig_"+BDTtype[bdt]+"_ggh_135.0_cat0_sigInt");
    TH1F* sigIntDown = (TH1F*)linearBin(result135.first);
    TH1F* sigIntUp = (TH1F*)linearBin(result135.second);
    TH1F* sigIntCent = (TH1F*)linearBin(int135);
    diagFile << (result135.first)->GetName() << std::endl;
    diagFile << (result135.second)->GetName() << std::endl;
    
    TCanvas *test = new TCanvas();
    sigIntDown->SetLineColor(2);
    sigIntUp->SetLineColor(4);
    sigIntDown->Draw();
    sigIntUp->Draw("same");
    sigIntCent->Draw("same'");
    test->Print(("plots/"+BDTtype[bdt]+"/fracs/PMsysts135.png").c_str(),"png");
   
    outFile->cd();
    (result135.first)->Write();
    (result135.second)->Write();
   
  }

    // -------------------- systematic stuff done ----------------------

  // get lists of middle, upper and lower templates for each mass
  TList *orgHistList[nBDTs][nProds][nMasses];
  TList *orgHistListBelow[nBDTs][nProds][nMasses];
  TList *orgHistListAbove[nBDTs][nProds][nMasses];
  for (int i=0; i<nBDTs; i++) {
   for (int pT=0;pT<nProds;pT++){
    for (int j=0; j<nMasses; j++) {
      orgHistList[i][pT][j]=new TList();
      orgHistListBelow[i][pT][j]=new TList();
      orgHistListAbove[i][pT][j]=new TList();
    }
   }
  }

  for (int j=0; j<HistList->GetSize(); j++){
    TString HistName(HistList->At(j)->GetName());
    for (int bdt=0; bdt<nBDTs; bdt++){
     for (int pT=0;pT<nProds;pT++){
      for (int bdtmass=0; bdtmass<nMasses; bdtmass++){
        for (int k=-1; k<2; k++){
          if ((bdtmass==0 && k==-1) || (bdtmass==nMasses-1 && k==1)) continue;
          if (HistName.Contains(("sig_"+BDTtype[bdt]+"_"+productionTypes[pT]+"_"+BDTmasses[bdtmass]+"_"+BDTmasses[bdtmass+k]).c_str())){
            TH1F *temp = (TH1F*)inFile->Get(HistName.Data());
            cout << temp->GetName() << " " << temp->GetEntries() << endl;
            if (k==-1) orgHistListBelow[bdt][pT][bdtmass]->Add(temp);
            if (k==0) orgHistList[bdt][pT][bdtmass]->Add(temp);
            if (k==1) orgHistListAbove[bdt][pT][bdtmass]->Add(temp);
          }
        }
       }
      }
    }
  }
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Following histo's being used for interpolation: " << std::endl;
  for (int bdt=0; bdt<nBDTs; bdt++){
   for (int pT=0;pT<nProds;pT++){
    for (int mass=0; mass<nMasses; mass++){
      diagFile << "BDT: " << BDTtype[bdt] << std::endl;
      diagFile << "Production : " << productionTypes[pT] << std::endl;
      diagFile << "Mass: " << BDTmasses[mass] << std::endl;
      for (int syst=0; syst<orgHistList[bdt][pT][mass]->GetSize(); syst++){
        diagFile << "   Central: " << orgHistList[bdt][pT][mass]->At(syst)->GetName() << std::endl;
        if (mass!=0) diagFile << "   Lower:   " << orgHistListBelow[bdt][pT][mass]->At(syst)->GetName() << std::endl;
        if (mass!=nMasses-1) diagFile << "   Upper:   " << orgHistListAbove[bdt][pT][mass]->At(syst)->GetName() << std::endl;
      }
    }
   }
  }

  // now have orgHistList for each BDT and above and below signals.
  // the contain 17 histos - 1 for actual sig and 8 up and down for each systematic

  // ---------- at this points have signal hists for each mass points as well as +- models all rebinned at mass points --------

  std::cout << "Calculating interpolated signal templates........" << std::endl;
  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Interpolating intermediate signals from following lower and upper templates" << std::endl;

  const int nGlobalMs=81; // no of mass points between lowMass and highMass with 0.5 GeV steps
  TList *orgHistListInt[nBDTs][nProds][nGlobalMs];
  for (int i=0; i<nBDTs; i++) for (int pT=0; pT<nProds; pT++) for (int j=0; j<nGlobalMs; j++) orgHistListInt[i][pT][j] = new TList();
  TH1F *systUp, *systDown, *systTrue;
  TH1F *background, *data, *signal, *sig_ggh, *sig_vbf, *sig_wzh, *sig_tth;

  int i=0;
  // loop over mass points etc.
  for (double mass=110.; mass<=150.; mass+=0.5){
    if (int(mass)%2==0) std::cout << Form("%3.0f",((mass-110.)/40.)*100.) << "% done" << std::endl;
    //points we have signal for
    if (int(mass*2)%10==0 && mass!=145.0) {
     for (int pT=0;pT<nProds;pT++){
      for (int bdt=0; bdt<nBDTs; bdt++){  
        background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",BDTtype[bdt].c_str(),mass));
      //  background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        data = (TH1F*)inFile->Get(Form("th1f_data_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
        sig_ggh = (TH1F*)inFile->Get(Form("th1f_sig_%s_ggh_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_vbf = (TH1F*)inFile->Get(Form("th1f_sig_%s_vbf_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_wzh = (TH1F*)inFile->Get(Form("th1f_sig_%s_wzh_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
        sig_tth = (TH1F*)inFile->Get(Form("th1f_sig_%s_tth_%3.1f_%3.1f_cat0",BDTtype[bdt].c_str(),mass,mass));
	
        signal = (TH1F*)sig_ggh->Clone();
        signal->Add(sig_vbf);
        signal->Add(sig_wzh);
        signal->Add(sig_tth);

        std::string name = Form("%3.1f",mass);
        if (Diagnose) {
          plotDavid(background,signal,data,name);
          TList *systList = new TList();
          TH1F *central;
          int bdtmass = getIndex((findNearest(mass).first));
          for (int syst=0; syst<orgHistList[bdt][pT][bdtmass]->GetSize(); syst++){
            if (syst==0) central = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
            else {
              TH1F *tempSig = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
              systList->Add(tempSig);
            }
          }
          plotSystFracs(systList,central,Form("%3.1f_systFracs",mass));
        }
        // store some systematic histograms
        if (int(mass)>110 && int(mass)<150){
          int bdtmass = getIndex(int(mass));
          systTrue = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(0)->Clone();
          systUp = (TH1F*)orgHistListAbove[bdt][pT][bdtmass]->At(0)->Clone();
          systDown = (TH1F*)orgHistListBelow[bdt][pT][bdtmass]->At(0)->Clone();

          double trueNorm = systTrue->Integral();
          systUp->Scale(trueNorm/systUp->Integral());
          systDown->Scale(trueNorm/systDown->Integral());
          systUp->SetName(Form("th1f_sig_%s_%s_%3.1f_cat0_sigIntNewUp01_sigma",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass));
          systDown->SetName(Form("th1f_sig_%s_%s_%3.1f_cat0_sigIntNewDown01_sigma",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass));
          
          outFile->cd();
          systUp->Write();
          systDown->Write();
          TCanvas *lil = new TCanvas();
          systUp->SetLineColor(kRed);
          systDown->SetLineColor(kBlue);
          systDown->Draw("e");
          systUp->Draw("same e");
          systTrue->Draw("same e");
          lil->Print(Form("plots/%s/systNew_%s_%3.1f.png",BDTtype[bdt].c_str(),productionTypes[pT].c_str(),mass),"png");
          delete lil;
        }
      }
     }
      continue;
    }
    std::pair<int,int> nearestPair = findNearest(mass);
    bool above;
    int nearest = nearestPair.first;
    int nextNear =nearestPair.second;
    if (nearest-nextNear < 0) above = true;
    else above = false;
    
    //std::cout << mass << " bracketed by: " << nearestPair.first << " " << nearestPair.second << " " << above << std::endl;

    int bdtmass = getIndex(nearest); // gives index of bdt to use

    // loop bdt type
    for (int bdt=0; bdt<nBDTs; bdt++){
     TH1F *combSignal;
     for (int pT=0;pT<nProds;pT++){
      diagFile << "Mass: " << mass << std::endl;
      diagFile << "BDT: " << BDTtype[bdt] << std::endl;
      // loop different histos in list (signal and systematics)
      background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",BDTtype[bdt].c_str(),mass));
     // background = (TH1F*)inFile->Get(Form("th1f_bkg_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
      data = (TH1F*)inFile->Get(Form("th1f_data_%s_%3.1f_cat0",BDTtype[bdt].c_str(),mass));
      TList *systList = new TList();
      TH1F *central;
      for (int syst=0; syst<orgHistList[bdt][pT][bdtmass]->GetSize(); syst++){
        TH1F *tempSig = (TH1F*)orgHistList[bdt][pT][bdtmass]->At(syst);
        central = (TH1F*)tempSig->Clone();
        TH1F *tempAbove = (TH1F*)orgHistListAbove[bdt][pT][bdtmass]->At(syst);
        TH1F *tempBelow = (TH1F*)orgHistListBelow[bdt][pT][bdtmass]->At(syst);
        TH1F* tempInt;
        TList* plotList = new TList();
        if (above){
          if (doNorm) tempSig->Scale(1./(GetXsection(double(nearest))*GetBR(double(nearest))));
          if (doNorm) tempAbove->Scale(1./(GetXsection(double(nextNear))*GetBR(double(nextNear))));
          tempInt = Interpolate(double(nearest),tempSig,double(nextNear),tempAbove,mass);
          if (doNorm) tempSig->Scale(GetXsection(double(nearest))*GetBR(double(nearest)));
          if (doNorm) tempAbove->Scale(GetXsection(double(nextNear))*GetBR(double(nextNear)));
          double norm = GetNorm(double(nearest),tempSig,double(nextNear),tempAbove,mass);
          if (doNorm) tempInt->Scale(norm/tempInt->Integral());
          // diagnostic stuff
          diagFile << "   Interpolated:     " << tempInt->GetName() << std::endl;
          diagFile << "   from:             " << tempSig->GetName() << std::endl;
          diagFile << "   and:              " << tempAbove->GetName() << std::endl;
          std::string histName = tempSig->GetName();
          std::string systName = histName.substr(histName.rfind("cat0"),histName.size());
          plotList->Add(tempSig);
          plotList->Add(tempAbove);
          if (Diagnose){
            if (syst==0) plotFrac(plotList,tempInt,Form("%3.1f_%s",mass,systName.c_str()),true);
            else systList->Add(tempInt);
          }
        }
        else{
          if (doNorm) tempSig->Scale(1./(GetXsection(double(nearest))*GetBR(double(nearest))));
          if (doNorm) tempBelow->Scale(1./(GetXsection(double(nextNear))*GetBR(double(nextNear))));
          tempInt = Interpolate(double(nextNear),tempBelow,double(nearest),tempSig,mass);
          if (doNorm) tempSig->Scale(GetXsection(double(nearest))*GetBR(double(nearest)));
          if (doNorm) tempBelow->Scale(GetXsection(double(nextNear))*GetBR(double(nextNear)));
          double norm = GetNorm(double(nextNear),tempBelow,double(nearest),tempSig,mass);
          if (doNorm) tempInt->Scale(norm/tempInt->Integral());
          // diagnostic stuff
          diagFile << "   Interpolated:     " << tempInt->GetName() << std::endl;
          diagFile << "   from:             " << tempBelow->GetName() << std::endl;
          diagFile << "   and:              " << tempSig->GetName() << std::endl;
          std::string histName = tempSig->GetName();
          std::string systName = histName.substr(histName.rfind("cat0"),histName.size());
          plotList->Add(tempBelow);
          plotList->Add(tempSig);
          if (Diagnose){
            if (syst==0) plotFrac(plotList,tempInt,Form("%3.1f_%s",mass,systName.c_str()),true);
            else systList->Add(tempInt);
          }
        }
        orgHistListInt[bdt][pT][i]->Add(tempInt);
        if (syst==0 && Diagnose){
          if (pT==0) combSignal = (TH1F*)tempInt->Clone();
          else combSignal->Add(tempInt,1.);
          std::string name = Form("%3.1f",mass);
          if (pT==3) plotDavid(background,combSignal,data,name);
        }
        delete plotList;
      }
      if (Diagnose) plotSystFracs(systList,central,Form("%3.1f_systFracs",mass));
     }
    }
    i++;
  }
 
  outFile->cd();

  diagFile << "---------------------------------------------------------------------" << std::endl;
  diagFile << "Writing following interpolated histograms to file: " << std::endl;
  for (int l=0; l<nBDTs; l++) for (int pT=0; pT<nProds; pT++)for (int j=0; j<nGlobalMs; j++) for (int k=0; k<orgHistListInt[l][pT][j]->GetSize(); k++) {
    orgHistListInt[l][pT][j]->At(k)->Write();
    diagFile << orgHistListInt[l][pT][j]->At(k)->GetName() << std::endl;
  }
  
  TList* endList = outFile->GetListOfKeys();
  for (double mass=110.0; mass<=150.; mass+=0.5){
    diagFile << mass << std::endl;
    std::pair<int,int> nearestPair = findNearest(mass);
    double nearest = nearestPair.first;
    double nextNear = nearestPair.second;
    for (int k=0; k<endList->GetSize(); k++){
      TString hName = endList->At(k)->GetName();
      if (hName.Contains("sigma") || !hName.Contains("sig")) continue;
      if (hName.Contains(Form("a_%3.1f_cat0",nearest)) || hName.Contains(Form("d_%3.1f_cat0",nearest)) || hName.Contains(Form("%3.1f_%3.1f_cat0",nearest,nextNear)) || hName.Contains(Form("%3.1f_cat0",mass))) {
        TH1F *temp = (TH1F*)outFile->Get(hName);
        diagFile << "    " << setw(30) << temp->GetName();
        diagFile << "    " << setw(8) << temp->GetEntries();
        diagFile << "    " << setw(8) << temp->Integral() << std::endl;
      }
    }
  }
    
  outFile->Close();

  std::cout << "Diagnostics log written to \"BDTInterpolationDiagnostics.txt\"" << std::endl;
  if (davidCalls>0) std::cout << davidCalls << " plots written to: plots/ada/david/ \n                    plots/grad/david/ " << std::endl;
  if (davidCalls>0) std::cout << davidCalls << " plots written to: plots/ada/diff/ \n                    plots/grad/diff/ " << std::endl;
  if (fracCalls>0) std::cout << fracCalls << " plots written to: plots/ada/frac/ \n                      plots/grad/frac/" << std::endl;
  if (systCalls>0) std::cout << systCalls << " plots written to: plots/ada/syst/ \n                    plots/grad/syst/ " << std::endl;
  if (bkgCalls>0) std::cout << bkgCalls << " plots written to: plots/ada/bkgMod/ \n                    plots/grad/bkgMod/ " << std::endl;

  std::string TIME_DATE = getTime();
  if (Diagnose){
    /*
    system("whoami > temp.txt");
    std::ifstream temp("temp.txt");
    std::string result;
    temp >> result;
    temp.close();
    system("rm temp.txt");
    system(("python make_html.py "+result+" "+TIME_DATE+" "+inFileName).c_str());
    system(("mkdir -p ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str());
    system(("cp -r plots ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str());
    system(("rm ~/public_html/h2g/MVA/SigInt/Diagnostics/Current"));
    system(("ln -s ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+" ~/public_html/h2g/MVA/SigInt/Diagnostics/Current").c_str());
    std::cout << ("Plots avaiable to view in ~/public_html/h2g/MVA/SigInt/Diagnostics/"+TIME_DATE+"/").c_str() << std::endl;
    std::cout << "If working on /vols/ at IC plots avaliable to view at www.hep.ph.ic.ac.uk/~"+result+"/h2g/MVA/SigInt/Diagnostics/Current/plots/plots.html" << std::endl;
    */
  }
  std::cout << "Checking all relevant histograms have been written to workspace......" << std::endl;
  //system(("python checkOK.py "+string(outFile->GetName())).c_str());
  std::cout << "New workspace written to " << outFile->GetName() << std::endl;
  return 0;
}
Esempio n. 6
0
void updateHIN11010(int etPho = 60, int etJet = 30, bool scaleByR=true, bool drawMC=true, int prodDate=20131021) {
  bool mcOnly=false;

  int percentBin[5] = {0,10,30,50,100};
  TH1D* hxgj[5][10];   //[data kind] [ centrality] 
  TH1D* hxgjpp[20];
  TFile *fSum1 = new TFile(Form("histOutputFiles60GeVInclusive/HisOutput_Photonv7_v29_akPu3PF_InclPtRatio_gamma%djet%ddphiSig2749_Isol0_Norm1.root",etPho,etJet));
  for ( int icent=0; icent<=3 ; icent++) { 
    hxgj[khimc][icent] =  (TH1D*)fSum1->Get(Form("dataSrc%d_reco1_cent%dSubtractedExtrapExtrapNorm",khimc,icent));
    hxgj[khidata][icent] =  (TH1D*)fSum1->Get(Form("dataSrc%d_reco1_cent%dSubtractedExtrapExtrapNorm",khidata,icent));
  }
  hxgjpp[kppdata] = (TH1D*)fSum1->Get("dataSrc2_reco1_cent0SubtractedExtrapExtrapNorm");

  TFile *fSum2 = new TFile(Form("histOutputFiles60GeVInclusive/HisOutput_Photonv7_v29_akPu3PF_InclPtRatio_gamma%djet%ddphiSig2749_Isol0_Norm2.root",etPho,etJet));
  TGraphAsymmErrors* mxhimc = (TGraphAsymmErrors*)fSum2->Get("dataSrc0_reco1_x_Summary_0");
  TGraphAsymmErrors* mxhidata = (TGraphAsymmErrors*)fSum2->Get("dataSrc1_reco1_x_Summary_0");
  //  TGraphAsymmErrors* mxppdata = (TGraphAsymmErrors*)fSum2->Get("dataSrc2_reco1_x_Summary_0");
  TGraphAsymmErrors* mxppdata;
  TGraphAsymmErrors* mxppmc = (TGraphAsymmErrors*)fSum2->Get("dataSrc10_reco1_x_Summary_0");

  TGraphAsymmErrors* rxhimc = (TGraphAsymmErrors*)fSum2->Get("dataSrc0_reco1_R_Summary_0");
  TGraphAsymmErrors* rxhidata = (TGraphAsymmErrors*)fSum2->Get("dataSrc1_reco1_R_Summary_0");
  TGraphAsymmErrors* rxppdata = (TGraphAsymmErrors*)fSum2->Get("dataSrc2_reco1_R_Summary_0");
  TGraphAsymmErrors* rxppmc = (TGraphAsymmErrors*)fSum2->Get("dataSrc10_reco1_R_Summary_0");

  TFile *fSum3 = new TFile(Form("histOutputFiles60GeVInclusive/HisOutput_Photonv7_v29_akPu3PF_InclDeltaPhi_gamma%djet%ddphiSig628_subJ1SS1_Isol0_Norm1.root",etPho,etJet));

  TFile *fSum4 = new TFile("histOutputFiles60GeVInclusive/HisSummary_Photonv7_v29_akPu3PF_InclDeltaPhi_gamma60jet30dphiSig628_subJ1SS1_Isol0_Norm1.root");
  TGraphAsymmErrors* dphihimc = (TGraphAsymmErrors*)fSum4->Get("dataSrc0_reco1_dphi_Summary");
  TGraphAsymmErrors* dphihidata = (TGraphAsymmErrors*)fSum4->Get("dataSrc1_reco1_dphi_Summary");
  TGraphAsymmErrors* dphippdata = (TGraphAsymmErrors*)fSum4->Get("dataSrc2_reco1_dphi_Summary");
  TGraphAsymmErrors* dphippmc = (TGraphAsymmErrors*)fSum4->Get("dataSrc10_reco1_dphi_Summary");

  // new dphihidata points
  //


  double sysDphi[4] = {0.032,0.03,0.045,0.077};
  //0.109940, 0.046998, 0.034206,0.142664};
  double sysDphipp[1] = {sysDphi[3]};
  
  double sysR[4] = {0.045,0.039,0.041,0.037};
  //0.017232,0.012847,0.011691,0.012724};
  double sysRpp[1] = {sysR[3]};
  
  double sysMx[4] = { 0.053,0.048,0.051,0.032};
  double sysMxpp[1] = {0.009};
  double corrSysMx =  0.028;

  TH1D* hdphi[5][5];   //[data kind] [ centrality]                                                                                     
  TH1D* hdphipp[20];
  for ( int icent=0; icent<=3 ; icent++) {
    hdphi[khimc][icent] =  (TH1D*)fSum3->Get(Form("dataSrc%d_reco1_cent%dSubtractedExtrapExtrapNorm",khimc,icent));
    hdphi[khidata][icent] =  (TH1D*)fSum3->Get(Form("dataSrc%d_reco1_cent%dSubtractedExtrapExtrapNorm",khidata,icent));
  }
  hdphipp[kppdata] = (TH1D*)fSum3->Get("dataSrc2_reco1_cent0SubtractedExtrapExtrapNorm");
  
  // 2013 pp data!!!!!!
  TFile* pp13 = new TFile(Form("ffFilesPP60GeVInclusive/photonTrackCorr_ppDATA_output_photonPtThr60_to_9999_jetPtThr30_%d.root", prodDate));
  // TFile* pp13 = new TFile("ffFilesPP60GeVInclusive/oldSmearing.root");

  hdphi[kppdata13][1] =  (TH1D*)pp13->Get("jetDphi_icent10010_final");
  hxgj[kppdata13][1] = (TH1D*)pp13->Get("xjg_icent10010_final");
  hdphi[kppdata13][2] =  (TH1D*)pp13->Get("jetDphi_icent11030_final");
  hxgj[kppdata13][2] = (TH1D*)pp13->Get("xjg_icent11030_final");
  hdphi[kppdata13][3] =  (TH1D*)pp13->Get("jetDphi_icent13050_final");
  hxgj[kppdata13][3] = (TH1D*)pp13->Get("xjg_icent13050_final");
  hdphi[kppdata13][4] =  (TH1D*)pp13->Get("jetDphi_icent15099_final");
  hxgj[kppdata13][4] = (TH1D*)pp13->Get("xjg_icent15099_final");
  hdphi[kppdata13][5] =  (TH1D*)pp13->Get("jetDphi_icent7_final");
  hxgj[kppdata13][5] = (TH1D*)pp13->Get("xjg_icent7_final");
  

  for ( int icent  = 1 ; icent<=5 ; icent++) {
    hdphi[kppdata13][icent]->Scale(1./hdphi[kppdata13][icent]->Integral());
    for ( int i = 1 ; i<=5 ; i++) {
      hdphi[kppdata13][icent]->SetBinContent(i,-1e4);
    }
    //    hxgj[kppdata13][icent]->Rebin(10);  // Now the bins are already rebined from photonTrackCorr_ppDATA_output_photonPtThr60_to_9999_jetPtThr30_20131021.root
    hxgj[kppdata13][icent]->Scale(1./hxgj[kppdata13][icent]->Integral("width"));
  }
  
  TH1D* hPtPP2013[10];  
  hPtPP2013[1] = (TH1D*)pp13->Get("jetPt_icent10010_final");
  hPtPP2013[2] = (TH1D*)pp13->Get("jetPt_icent11030_final");
  hPtPP2013[3] = (TH1D*)pp13->Get("jetPt_icent13050_final");
  hPtPP2013[4] = (TH1D*)pp13->Get("jetPt_icent15099_final");
  hPtPP2013[5] = (TH1D*)pp13->Get("jetPt_icent7_final");
  
  TH1D* hRpp2013[10]; 
  hRpp2013[1] = new TH1D("hrpp2013_icent1","",1, 359.1-10, 359.1+10);
  hRpp2013[2] = new TH1D("hrpp2013_icent2","",1, 235.6-10, 235.6+10);
  hRpp2013[3] = new TH1D("hrpp2013_icent3","",1, 116.4-10, 116.4+10);
  hRpp2013[4] = new TH1D("hrpp2013_icent4","",1, 43.6-10,  43.6 +10);
  hRpp2013[5] = new TH1D("hrpp2013_icent5","",1, -8,  18 );

  for ( int icent=1 ;  icent<=5; icent++) { 
    double temprPP13err;
    double temprPP13 = hPtPP2013[icent]->IntegralAndError(1,hPtPP2013[icent]->GetNbinsX(),temprPP13err,"width");
    hRpp2013[icent]->SetBinContent(1,temprPP13);
    hRpp2013[icent]->SetBinError(1,temprPP13err);
    handsomeTH1(hRpp2013[icent],1);
    hRpp2013[icent]->SetMarkerStyle(21);
  }
  
  TH1D* hMXpp2013[10];
  hMXpp2013[1] = new TH1D("hmxpp2013_icent1","",1, 359.1-10, 359.1+10);
  hMXpp2013[2] = new TH1D("hmxpp2013_icent2","",1, 235.6-10, 235.6+10);
  hMXpp2013[3] = new TH1D("hmxpp2013_icent3","",1, 116.4-10, 116.4+10);
  hMXpp2013[4] = new TH1D("hmxpp2013_icent4","",1, 43.6-10,  43.6 +10);
  hMXpp2013[5] = new TH1D("hmxpp2013_icent5","",1, -8, 18);
  for ( int icent=1 ;  icent<=5; icent++) {
    hMXpp2013[icent]->SetBinContent(1,hxgj[kppdata13][icent]->GetMean());
    hMXpp2013[icent]->SetBinError(1,hxgj[kppdata13][icent]->GetMeanError());
    handsomeTH1(hMXpp2013[icent],1);
    hMXpp2013[icent]->SetMarkerStyle(21);
  }


  TFile* fPPsys = new TFile("ffFilesPP60GeVInclusive/relativeSys_merged_pp60GeV.root");

  TH1D* hdphiWidth  = (TH1D*)fPPsys->Get("dphiWidth_uncertainty_merged");
  
  TH1D* hDphiPPUnc = new TH1D("hdphippunc","",1,0,1);
  hDphiPPUnc->SetBinContent(1, hdphiWidth->GetBinContent(1) );

  TH1D* ppSysX[4];
  ppSysX[0] = (TH1D*)fPPsys->Get("dNdXjg_uncertainty_merged");
  ppSysX[1] = (TH1D*)ppSysX[0]->Clone("ppSysx1");
  ppSysX[2] = (TH1D*)ppSysX[0]->Clone("ppSysx2");
  ppSysX[3] = (TH1D*)ppSysX[0]->Clone("ppSysx3");

  TH1D* meanXpp13Sys = (TH1D*)fPPsys->Get("meanXjg_uncertainty_merged");

  float ppSysMx60 = meanXpp13Sys->GetBinContent(1);    // UPDATED on Oct 22nd
  TH1D* ppSysMx = new TH1D("ppSysMx","",1,0,1);
  ppSysMx->SetBinContent(1,ppSysMx60);

  TH1D* meanRpp13Sys = (TH1D*)fPPsys->Get("meanRjg_uncertainty_merged");
  float ppSysR60 = meanRpp13Sys->GetBinContent(1); // UPDATED on Oct 22nd
  TH1D* ppSysR = new TH1D("ppSysR","",1,0,1);
  ppSysR->SetBinContent(1,ppSysR60);

  
  
  // xjg distributions
  TCanvas *c1 = new TCanvas("c1","",1100,330);
  makeMultiPanelCanvas(c1,4,1,0.0,0.0,0.24,0.15,0.075);
  c1->cd(0);
  drawCMSppPbPb(0.1,0.95);
  //c1->Divide(4,1,0.0,0.0);
  for ( int icent=0; icent<=3 ; icent++) {
    c1->cd( 4 - icent);
    //hxgj[khimc][icent]->SetAxisRange(-.2,2.5,"Y");
    hxgj[khimc][icent]->SetAxisRange(0,2.5,"Y");
    hxgj[khimc][icent]->SetNdivisions(505);
    //    hxgj[khimc][icent]->SetTitle(";x_{J#gamma} = p^{Jet}_{T}/p^{#gamma}_{T}; #frac{1}{N_{J#gamma}} #frac{dN_{J#gamma}}{dx_{J#gamma}}");
    hxgj[khimc][icent]->SetTitle(";x_{J#gamma}; #frac{1}{N_{J#gamma}} #frac{dN_{J#gamma}}{dx_{J#gamma}}");
    handsomeTH1(hxgj[khimc][icent]);
    fixedFontHist(hxgj[khimc][icent],1,1.35);
    mcStyle2(hxgj[khimc][icent]);
    handsomeTH1(hxgj[khidata][icent],2);
    
    hxgj[khimc][icent]->GetYaxis()->SetTitleOffset(1.5);
    TH1D * htemp41 = (TH1D*)hxgj[khimc][icent]->Clone(Form("htemp41_%d",icent));
    for ( int i=0 ; i<=20 ; i++) {
      htemp41->SetBinContent(i,0);
      htemp41->SetBinError(i,0);
    }
    if (scaleByR) {
      htemp41->SetAxisRange(0,2,"Y");
      htemp41->SetYTitle("#frac{1}{N_{#gamma}} #frac{dN_{J#gamma}}{dx_{J#gamma}}");
    }
    htemp41->DrawCopy("hist");

    if (scaleByR)    {
      hxgj[kppdata13][icent+1]->Scale(hRpp2013[icent+1]->GetBinContent(1));
      std::cout <<"  Scaled by pp R :" << hRpp2013[icent+1]->GetBinContent(1) << std::endl;
      
      double x,y;
      rxhidata->GetPoint(icent, x,y);
      hxgj[khidata][icent]->Scale(y);
      std::cout << " scaled by PbPb R: " << y << std::endl;

      rxhimc->GetPoint(icent, x,y);
      hxgj[khimc][icent]->Scale(y);
      std::cout << " scaled by PbPb R: " << y << std::endl;
    }
    if(drawMC) hxgj[khimc][icent]->DrawCopy("hist same");

    if ( !mcOnly )    drawXSys(icent,hxgj[khidata][icent]);
    //   if ( icent==3){ }
    
    handsomeTH1(hxgj[kppdata13][icent+1]);
    hxgj[kppdata13][icent+1]->SetMarkerStyle(21);

    drawSys(hxgj[kppdata13][icent+1],ppSysX[icent],kGreen,3001);

    hxgj[kppdata13][icent+1]->Draw("same ");
    
    if ( !mcOnly )   hxgj[khidata][icent]->Draw("same");
    //onSun(0,0,2,0);
 
    // if ( icent == 2) {
    //   TLegend *leg0  = new TLegend(0.2796373,0.7545885,0.9742202,0.9937661,NULL,"brNDC");
    //     easyLeg(leg0,"");
    //   //      if ( !mcOnly )       leg0->AddEntry(hxgj[khidata][icent],"PbPb Data","p");
    //   leg0->AddEntry(hxgj[khimc][icent],"PYTHIA + HYDJET","f");
    //   leg0->AddEntry(hxgjpp[kppdata],"","");

    //   leg0->Draw();
    // }
    
    if ( icent == 3) {
      TLegend *leg0 = new TLegend(0.2916647,0.7045885,0.9862476,0.9869226,NULL,"brNDC");
      easyLeg(leg0);
      leg0->AddEntry(hxgj[khidata][icent],"PbPb Data","p");
      if ( !mcOnly )       leg0->AddEntry(hxgj[kppdata13][icent+1],"Smeared pp reference","p");
      //    leg0->AddEntry(hxgj[khidata][icent],"","");
      if(drawMC) leg0->AddEntry(hxgj[khimc][icent],"PbPb PYTHIA + HYDJET","f");
      leg0->Draw();
      //drawText("#sqrt{s_{NN}}=2.76 TeV ",0.65,0.74,0,15);
    }
        
    if ( icent == 2) {
      drawText(Form("p^{#gamma}_{T} > %d GeV/c     |#eta^{#gamma}| < 1.44",etPho),0.2,0.85,0,15);
      drawText(Form("p^{Jet}_{T} > %d GeV/c    |#eta^{Jet}| < 1.6",etJet),0.2,0.77,0,15);
      drawText("#Delta#phi_{J#gamma} > #frac{7}{8}#pi",0.2,0.69,0,15);
    }
    if ( icent == 0 ) {
      //      drawText("CMS",0.8,0.9,1);
      //      drawText("pp       #int L dt = 231 nb^{-1}",0.4,0.68,1,15);
    }
    
    if ( icent == 3) 
      drawText(Form("%d%% - %d%%",percentBin[icent],percentBin[icent+1]),0.72,0.5,0,15);
    else 
      drawText(Form("%d%% - %d%%",percentBin[icent],percentBin[icent+1]),0.67,0.5,0,15);
    
    /*    if ( icent == 3)
      drawText("(a)",0.275,0.8,1);
    if ( icent == 2)
      drawText("(b)",0.05,0.8,1);  
    if ( icent == 1)
      drawText("(c)",0.05,0.8,1);   
    if ( icent == 0)
      drawText("(d)",0.05,0.8,1);
    */
    gPad->RedrawAxis();
  }

  c1->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_distribution.pdf");
  //c1->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_distribution.png");
  //c1->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_distribution.gif");
  //c1->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_distribution.C");

  
  
  // TCanvas *c1all = new TCanvas("c1all","",500,500);

  // for ( int icent=0;icent<4;icent++){
  //   hxgj[khimc][icent]->SetFillStyle(0);
  //   hxgj[khimc][icent]->SetMarkerSize(1.5);
  // }
  // hxgj[khimc][0]->SetMarkerStyle(22);
  // hxgj[khimc][1]->SetMarkerStyle(26);
  // hxgj[khimc][2]->SetMarkerStyle(23);
  // hxgj[khimc][3]->SetMarkerStyle(32);
  // hxgj[khimc][0]->DrawCopy("");
  // hxgj[khimc][1]->DrawCopy(" same");
  // hxgj[khimc][2]->DrawCopy(" same");
  // hxgj[khimc][3]->DrawCopy(" same");
  // jumSun(0,0,2,0);

  // drawText("PYTHIA+HYDJET",0.2,0.80,0,25);
  // TLegend *legc1all = new TLegend(0.6149194,0.6716102,0.9435484,0.9555085,NULL,"brNDC");
  // easyLeg(legc1all,"");
  // legc1all->AddEntry(hxgj[khimc][3],"50-100%","p");
  // legc1all->AddEntry(hxgj[khimc][2],"30-50%","p");
  // legc1all->AddEntry(hxgj[khimc][1],"10-30%","p");
  // legc1all->AddEntry(hxgj[khimc][0],"0-10%","p");
  // legc1all->Draw();
  
  // dphi distributions
  TCanvas *c1ppDphi = new TCanvas("c1ppDphi","",500,500);
  TString fitFunc = "(TMath::Pi()/20.0)*exp(-(TMath::Pi()-x)/[0])/([0]*(1-exp(-TMath::Pi()/[0])))";
  float fitxmin=3.1415926*2./3;
  TF1 *fdphiPP[10];
  TH1D* hDphiPP2013[10];
  hDphiPP2013[1] = new TH1D("hDphiPP2013_icent1","",1, 359.1-10, 359.1+10);
  hDphiPP2013[2] = new TH1D("hDphiPP2013_icent2","",1, 235.6-10, 235.6+10);
  hDphiPP2013[3] = new TH1D("hDphiPP2013_icent3","",1, 116.4-10, 116.4+10);
  hDphiPP2013[4] = new TH1D("hDphiPP2013_icent4","",1, 43.6-10,  43.6 +10);
  hDphiPP2013[5] = new TH1D("hDphiPP2013_icent5","",1, -8, 18);
  
  for ( int icent=1; icent<=5 ; icent++) {
    fdphiPP[icent] = new TF1(Form("fdphiPP_icent%d",icent),fitFunc.Data(),2.0*TMath::Pi()/3.0,TMath::Pi());
    fdphiPP[icent]->SetParName(0,"width");
    fdphiPP[icent]->SetParameter("width",0.3);
    hdphi[kppdata13][icent]->Fit(Form("fdphiPP_icent%d",icent),"0","",fitxmin,3.1415926);
    fdphiPP[icent]->SetLineWidth(1);
    fdphiPP[icent]->SetLineStyle(2);
    fdphiPP[icent]->SetLineColor(1);
    hdphi[kppdata13][icent]->SetAxisRange(1.00001e-3,1,"Y");
    hdphi[kppdata13][icent]->SetStats(0);
    hdphi[kppdata13][icent]->Draw("");
    hdphi[kppdata13][icent]->SetAxisRange(1.00001e-3,1,"Y");
    hdphi[kppdata13][icent]->SetStats(0);
    fdphiPP[icent]->SetLineWidth(2);
    fdphiPP[icent]->SetLineStyle(7); 
    fdphiPP[icent]->DrawCopy("same");
    gPad->SetLogy();
  
    float dphiWidth13 = fdphiPP[icent]->GetParameter(0) ; 
    float dphiWidth13err = fdphiPP[icent]->GetParError(0);
    hDphiPP2013[icent]->SetBinContent(1,dphiWidth13);
    hDphiPP2013[icent]->SetBinError(  1,dphiWidth13err);
    handsomeTH1(hDphiPP2013[icent],1);
    hDphiPP2013[icent]->SetMarkerStyle(21);
  }

  TCanvas *c1dphi = new TCanvas("c1dphi","",1100,330);
  makeMultiPanelCanvas(c1dphi,4,1,0.0,0.0,0.24,0.18,0.075);
  c1dphi->cd(0);
  drawCMSppPbPb(0.1,0.95);

  for ( int icent=0; icent<=3 ; icent++) {
    c1dphi->cd( 4 - icent);
    hdphi[khimc][icent]->SetAxisRange(1.e-3,1,"Y");
    //   hdphi[khimc][icent]->SetNdivisions(505);
    hdphi[khimc][icent]->GetXaxis()->SetNdivisions(3,5,0,kFALSE);
    
    hdphi[khimc][icent]->SetTitle(";#Delta#phi_{J#gamma};Pair Fraction");

    handsomeTH1(hdphi[khimc][icent]);
    fixedFontHist(hdphi[khimc][icent],1,1.35);
    mcStyle2(hdphi[khimc][icent]);
    handsomeTH1(hdphi[khidata][icent],2);

    TF1 *fdphi = new TF1("fdphi",fitFunc.Data(),2.0*TMath::Pi()/3.0,TMath::Pi());
    fdphi->SetParName(0,"width");
    fdphi->SetParameter("width",0.3);
    
    hdphi[khimc][icent]->Fit("fdphi","0llm","",fitxmin,3.1415926);

    fdphi->SetLineWidth(1);
    fdphi->SetLineStyle(2);
    fdphi->SetLineColor(kBlue); 
    // float dphiWidth = fdphi->GetParameter("width");
    // float dphiWidthErr = fdphi->GetParError(0);
    // std::cout << " dphiWidth,dphiWidthErr = " << dphiWidth <<"   "<< dphiWidthErr << std::endl;
    hdphi[khimc][icent]->SetAxisRange(1.00001e-3,1,"Y");
    hdphi[khimc][icent]->SetStats(0);
    TH1D* hdphitemp = (TH1D*)hdphi[khimc][icent]->Clone(Form("hdphitemp55_%d",icent));
    if(!drawMC)
    {
      for ( int i=0;i<=30;i++) { 
	hdphitemp->SetBinContent(i,0);
	hdphitemp->SetBinError(i,0);
      }
    }
    hdphitemp->Draw("hist");
    hdphi[khidata][icent]->SetAxisRange(1.00001e-3,1,"Y");
    if (!mcOnly) hdphi[khidata][icent]->Draw("same ");
    hdphi[khidata][icent]->SetStats(0);
    fdphi->SetLineWidth(2);
    fdphi->SetLineStyle(7);
    if ( mcOnly )    fdphi->DrawCopy("same");


    gPad->SetLogy();
    handsomeTH1(hdphi[kppdata13][icent+1]);
    
    hdphi[kppdata13][icent+1]->SetMarkerStyle(21);
    hdphi[kppdata13][icent+1]->Draw("same");

    
    if ( icent == 3) {
      TLegend *leg0  = new TLegend(0.32,0.7,0.9,0.89,NULL,"brNDC");
      easyLeg(leg0);
      if ( !mcOnly )   leg0->AddEntry(hdphi[kppdata13][icent+1],"Smeared pp reference","p");
      if ( !mcOnly )      leg0->AddEntry(hdphi[khidata][icent],"PbPb Data","p");
      if(drawMC) leg0->AddEntry(hdphi[khimc][icent],"PYTHIA + HYDJET","f");
      leg0->Draw();
    }

    if (( !mcOnly ) && ( icent == 2)) {
      //drawText("#sqrt{s_{NN}}=2.76 TeV ",0.4,0.88,0,15);
      //drawText("#int L dt = 150 #mub^{-1}",0.4,0.75,0,15);
    }

    if ( icent == 1) {
      drawText(Form("p^{#gamma}_{T} > %d GeV/c     |#eta^{#gamma}| < 1.44",etPho),0.15,0.8,0,15);
      drawText(Form("p^{Jet}_{T} > %d GeV/c    |#eta^{Jet}| < 1.6",etJet),0.15,0.7,0,15);
    }

    if ( icent == 0 ) {
      //      drawText("CMS",0.8,0.9,1);
      //      drawText("pp       #int L dt = 231 nb^{-1}",0.4,0.68,1,15);                                                                     
    }


    if ( icent == 3)
      drawText(Form("%d%% - %d%%",percentBin[icent],percentBin[icent+1]),0.313,0.6,0,15);
    else
      drawText(Form("%d%% - %d%%",percentBin[icent],percentBin[icent+1]),0.1,0.6,0,15);

    if ( icent == 3)
      drawText("(a)",0.275,0.8,1);
    if ( icent == 2)
      drawText("(b)",0.05,0.8,1);
    if ( icent == 1)
      drawText("(c)",0.05,0.8,1);
    if ( icent == 0)
      drawText("(d)",0.05,0.8,1);
    
    double bottomY = 0.0009;
    double pi = TMath::Pi();

    drawPatch(-0.5,bottomY/100,pi+0.5,bottomY);

    bottomY = 0.0005;
    drawText("0",0.05,bottomY,0,18,false);
    drawText("#frac{1}{3}#pi",pi/3-0.05,bottomY,0,18,0);
    drawText("#frac{2}{3}#pi",2*pi/3-0.05,bottomY,0,18,0);
    if ( icent==0) 
      drawText("#pi",pi-0.1,bottomY,0,18,0);
    drawText("#Delta#phi_{J#gamma}",pi/2.-0.1,bottomY-0.0002,0,18,0);
    
  }
  


  gPad->RedrawAxis();
  c1dphi->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dPhi_dist.pdf");
  //c1dphi->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dPhi_dist.png");
  //c1dphi->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dPhi_dist.gif");
  //c1dphi->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dPhi_dist.C");
  
  ////////////////////////////// summary plots
  TCanvas *c2 = new TCanvas("c2","",350,350);
  TH1D* hTemp2 = new TH1D("htemp2",";N_{part};<x_{J#gamma}>",100,-20,400);
  hTemp2->SetNdivisions(505);
  handsomeTH1(hTemp2,1);
  handsomeTGraph(mxhidata,2);
  mxhidata->SetMarkerStyle(20);
  handsomeTGraph(mxhimc,1);
  mxhimc->SetMarkerStyle(24);
  //  handsomeTGraph(mxppdata,1);
  //  mxppdata->SetMarkerStyle(21);
  handsomeTGraph(mxppmc,1);
  mxppmc->SetMarkerStyle(25);
  
    
  hTemp2->SetAxisRange(0.6,1.1,"Y");
  hTemp2->DrawCopy();
  //  TH1D* hMXpp2013_2 = new TH1D("hmxpp2013_2","",1,-10,370);
  //  hMXpp2013_2->SetBinContent(1,hMXpp2013->GetBinContent(1));
  //  if ( !mcOnly )   drawSys(hMXpp2013_2,sysMxpp,kGreen,3001);
  if ( !mcOnly )   drawSys(mxhidata,sysMx,10);
  
  // mxppmc->Draw("p");
  //  if ( !mcOnly )   mxppdata->Draw("p");
  if ( !mcOnly )  {
    hMXpp2013[5]->SetMarkerStyle(20);
    for ( int icent = 1 ; icent<=5 ; icent++) {
      drawSys(hMXpp2013[icent],ppSysMx,kGreen,3001);
      hMXpp2013[icent]->DrawCopy("p same");
    }
  }
  if(drawMC) mxhimc->Draw("p same");
  if ( !mcOnly )  mxhidata->Draw("p same");

  hMXpp2013[5]->SetFillStyle(3001);
  hMXpp2013[5]->SetFillColor(kGreen);
  hMXpp2013[5]->SetLineColor(0);
  hDphiPP2013[2]->SetFillStyle(3001);
  hDphiPP2013[2]->SetFillColor(kGreen);
  hDphiPP2013[2]->SetLineColor(0);
  TH1D *dummyHist = new TH1D("dummyHist","",10,0,1);
  dummyHist->SetFillStyle(1001);
  dummyHist->SetMarkerColor(kRed);
  dummyHist->SetFillColor(90);
  dummyHist->SetLineColor(0);
  
  //// sys bar by energy scale
  /*
  TBox *b1 = new TBox(400-20,0.85 - corrSysMx ,400,  0.85 + corrSysMx);
  b1->SetFillColor(1);
  b1->SetFillStyle(1001);
  if ( !mcOnly )   b1->Draw();
  TBox *b2 = new TBox(400-20+3,0.85 - corrSysMx+ 0.002 ,400-3,  0.85 + corrSysMx- 0.002);
  b2->SetFillColor(0);
  b2->SetFillStyle(1001);
  if ( !mcOnly )   b2->Draw();
  */
  //  drawText("Common uncertainty due to jet ",0.35,0.25,0,15);
  //  drawText("energy scale & photon purity",0.35,0.2,0,15);
  //  drawText("#sqrt{s_{NN}}=2.76 TeV ",0.5,0.85,0,15);
  //  drawText("#int L dt = 150 #mub^{-1}",0.5,0.72,0,15);
  //  drawText("(a)",0.22,0.87,1);
  drawText("#Delta#phi_{J#gamma} > #frac{7}{8}#pi",0.7,0.75,0);
  drawCMSppPbPb(0.1,0.95,12);
  //  drawText("#Delta#phi_{J#gamma} > #frac{7}{8}#pi",0.5,0.38,0);
  // drawText("CMS",0.78,0.88,1);

  TLegend *leg4 =  new TLegend(0.1630303,0.6054839,0.7590909,0.8931183,NULL,"brNDC");
  easyLeg(leg4,"");
  //  if ( !mcOnly )  leg4->AddEntry(mxppdata,"pp Data 231nb^{-1}","p");
  if ( !mcOnly ) leg4->AddEntry(dummyHist,"PbPb Data","fp");
  if ( !mcOnly )  leg4->AddEntry(hMXpp2013[5],"pp Data","fp");
  if ( !mcOnly )  leg4->AddEntry(hDphiPP2013[2],"Smeared pp reference","fp");
  if(drawMC) leg4->AddEntry(mxhimc,"PYTHIA + HYDJET","p");
  //  leg4->AddEntry(mxppmc,"PYTHIA","p");




  //  leg4->AddEntry(hSysTemp,"Sys. Uncertainty","f");                                                                                         
  leg4->Draw();


  gPad->RedrawAxis();
  
  c2->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_npart.pdf");
  //c2->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_npart.png");
  //c2->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_npart.gif");
  //c2->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_xjg_npart.C");
  
  ////////////////////////////// rx 
  TCanvas *c3 = new TCanvas("c3","",350,350);

  TH1D* hTemp3 = new TH1D("htemp2",";N_{part};R_{J#gamma}",100,-20,400);
  hTemp3->SetNdivisions(505);
  handsomeTH1(hTemp3,1);
  handsomeTGraph(rxhidata,2);
  rxhidata->SetMarkerStyle(20);
  handsomeTGraph(rxhimc,1);
  rxhimc->SetMarkerStyle(24);
  handsomeTGraph(rxppdata,1);
  rxppdata->SetMarkerStyle(21);
  handsomeTGraph(rxppmc,1);
  rxppmc->SetMarkerStyle(25);

  hTemp3->SetAxisRange(0.41,1.,"Y");
  hTemp3->Draw();


  // Ratio
  // DivideTG(rxppdata,rxppmc);
  // DivideTG(rxhidata,rxhimc);
  //////////////////////////////////////////////
  //  TH1D* hdphi2013_2 = new TH1D("hdphi2013_2","",1,-10,370);
  //  hdphi2013_2->SetBinContent(1,hRpp2013->GetBinContent(1));
  //  if ( !mcOnly )   drawSys(hdphi2013_2,sysRpp,kGreen,3001);
  if ( !mcOnly )   drawSys(rxhidata,sysR,10);
  //  if ( !mcOnly )   drawSys(rxppdata,sysRpp,10);
  // jumSun(-10,1,400,1);
  if(drawMC) rxhimc->Draw("p");
  //  rxppmc->Draw("p");
  //  if ( !mcOnly )   rxppdata->Draw("p");
  if ( !mcOnly )   {
    hRpp2013[5]->SetMarkerStyle(20);
    for ( int icent =1 ; icent<=5 ; icent++) { 
      drawSys(hRpp2013[icent],ppSysR,kGreen,3001);
      hRpp2013[icent]->Draw("same");
    }
  }
  if ( !mcOnly )   rxhidata->Draw("p same");
  //  drawText(Form("p^{#gamma}_{T} > %d GeV/c",etPho),0.6,0.75,0,15);
  //  drawText(Form("p^{Jet}_{T} > %d GeV/c",etJet),0.6,0.67,0,15);
  //  drawText("CMS",0.78,0.88,1);
  //  drawText("(b)",0.22,0.87,1);
  drawText("#Delta#phi_{J#gamma} > #frac{7}{8}#pi",0.7,0.75,0);
  drawCMSppPbPb(0.1,0.95,12);

  leg4->Draw();
  gPad->RedrawAxis();

  c3->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_r_npart.pdf");
  //c3->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_r_npart.png");
  //c3->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_r_npart.gif");
  //c3->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_r_npart.C");
  
  TCanvas *c4 = new TCanvas("c4","",350,350);

  TH1D* hTemp4 = new TH1D("htemp2",";N_{part};#sigma(#Delta#phi_{J#gamma})",100,-20,400);
  hTemp4->SetNdivisions(505);
  handsomeTH1(hTemp4,1);
  handsomeTGraph(dphihidata,2);
  dphihidata->SetMarkerStyle(20);
  handsomeTGraph(dphihimc,1);
  dphihimc->SetMarkerStyle(24);
  handsomeTGraph(dphippdata,1);
  dphippdata->SetMarkerStyle(21);
  handsomeTGraph(dphippmc,1);
  dphippmc->SetMarkerStyle(25);

  hTemp4->SetAxisRange(0,.5,"Y");
  hTemp4->Draw();
  
                                                                                 
  // TH1D* h2013_3 = new TH1D("hdphi2013_3","",1,-10,370);
  //  h2013_3->SetBinContent(1,hDphiPP2013->GetBinContent(1));

  //  if ( !mcOnly )  drawSys(h2013_3,sysDphipp,kGreen,3001);
  if ( !mcOnly )  drawSys(dphihidata,sysDphi,10);
  if(drawMC) dphihimc->Draw("p same");
  // dphippmc->Draw("p");
  //  if ( !mcOnly )  dphippdata->Draw("p");
  for ( int icent=1 ; icent<=5 ; icent++){
    drawSys(hDphiPP2013[icent], hDphiPPUnc, kGreen,3001);
  }
  
  TH1D* hDphiPP2013Temp = new TH1D("hDphiPP2013Temp","",1,380,400);
  hDphiPP2013Temp->SetBinContent(1,0.27);
  hDphiPP2013[5]->SetMarkerStyle(20);
  for ( int icent=1 ; icent<=5 ; icent++){ 
    hDphiPP2013[icent]->Draw("same");
  }
  if ( !mcOnly )  dphihidata->Draw("p");

  // TLegend *legDphi =  new TLegend(0.32,0.18,0.93,0.7,NULL,"brNDC");
  // easyLeg(legDphi,"");
  // legDphi->SetTextSize(17);
  // //  drawText("|#Delta#phi_{J#gamma}| > #frac{2}{3}#pi",0.5,0.38,0);
  // //  drawText("Fit : #frac{e^{#frac{|#Delta#phi_{J#gamma}|-#pi}{#sigma}}}{#sigma(1-e^{-#pi/#sigma})}",0.5,0.23,0);
  // legDphi->Draw();
  // //  drawText("(a)",0.22,0.87,1);
  // //  drawText("CMS",0.78,0.88,1);


  TH1D* hSysTemp = new TH1D("hSystemp","",1,0,1);
  hSysTemp->SetFillColor(newYellow);
  hSysTemp->SetLineColor(newYellow);

  leg4->Draw();

  drawText(Form("p^{#gamma}_{T} > %d GeV/c     |#eta^{#gamma}| < 1.44",etPho),0.25,0.3,0,15);
  drawText(Form("p^{Jet}_{T} > %d GeV/c    |#eta^{Jet}| < 1.6",etJet),0.25,0.2,0,15);
  drawCMSppPbPb(0.1,0.95,12);

  gPad->RedrawAxis();
  c4->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dphi_npart.pdf");
  //c4->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dphi_npart.png");
  //c4->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dphi_npart.gif");
  //c4->SaveAs("plotPPPbPb/inclusivePt_ppPbPb_dphi_npart.C");

   // // print numbers
   // std::cout << " Summary of Points for PbPb " << std::endl;
   // PrintGraphAndSys(dphihidata,sysDphi);
   // PrintGraphAndSys(mxhidata,sysMx);
   // PrintGraphAndSys(rxhidata,sysR);

   // std::cout << " Summary of Points for PYTHIA + HYDJET " << std::endl;
   // PrintGraph(dphihimc);
   // PrintGraph(mxhimc);
   // PrintGraph(rxhimc);

   //   std::cout << " Summary of Points for pp " << std::endl;
   //  PrintGraphAndSys(dphippdata[5],sysDphipp);
   //  PrintGraphAndSys(mxppdata[5],sysMxpp);
   // PrintGraphAndSys(rxppdata[5],sysRpp);


   
   /*
   TCanvas *c5 = new TCanvas("c5","",500,500);
   hxgj[khidata][0]->SetAxisRange(-.2,2.5,"Y");
   hxgj[khidata][0]->SetNdivisions(505);
   fixedFontHist(hxgj[khidata][0],1,1.35);
   handsomeTH1(hxgj[khidata][0],2);
   hxgj[khidata][0]->GetYaxis()->SetTitleOffset(1.5);
   hxgj[khidata][0]->DrawCopy("");
   handsomeTH1(hxgj[kppdata13][5],4);
   hxgj[kppdata13][5]->Draw("same hist");
   onSun(0,0,2,0);
   */
}
Esempio n. 7
0
CompareSpectra(Int_t part, Int_t charge, Int_t cent = -1, Int_t ratio = kFALSE, Int_t fitfunc = -1, Bool_t cutSpectra = kTRUE) 
{

  gROOT->LoadMacro("HistoUtils.C");

  gStyle->SetOptStat(0);
  gStyle->SetOptFit();

  LoadLibraries();
  AliBWFunc bwf;
  bwf.SetVarType(AliBWFunc::kdNdpt);
  TF1 *fFitFunc = NULL;

  switch (fitfunc) {
  case 0:
    gROOT->LoadMacro("SpectraAnalysis.C");
    fFitFunc = STAR_BlastWave("fBW", AliPID::ParticleMass(part), 0.9, 0.1, 1.);
    fBW->SetParLimits(3, 0.5, 1.5);
    //    fBW->FixParameter(3, 1.);
    break;
  case 1:
    fFitFunc = bwf.GetLevi(AliPID::ParticleMass(part), AliPID::ParticleMass(part), 5., 1000.);
    break;
  case 2:
    fFitFunc = bwf.GetBoltzmann(AliPID::ParticleMass(part), AliPID::ParticleMass(part), 100.);
    break;
  case 3:
    fFitFunc = bwf.GetMTExp(AliPID::ParticleMass(part),AliPID::ParticleMass(part) , 100.);
    break;
  case 4:
    fFitFunc = bwf.GetPTExp(AliPID::ParticleMass(part), 100.);
    break;
  case 5:
    fFitFunc = bwf.GetBGBW(AliPID::ParticleMass(part), 0.5, 0.1, 1.e6);
    break;
  case 6:
    fFitFunc = new TF1("fpol9", "pol9", 0., 5.0);
    break;
  }
  if (fFitFunc) fFitFunc->SetLineWidth(2);

  TFile *itssafile = TFile::Open(ratio ? itssaratiofilename : itssafilename);
  //  TFile *itstpcfile = TFile::Open(itstpcfilename);
  if (part / 3 == charge / 3)
    Char_t *tpctofratiofilename = tpctofratiofilenameA;
  else
    Char_t *tpctofratiofilename = tpctofratiofilenameB;
  TFile *tpctoffile = TFile::Open(ratio ? tpctofratiofilename : tpctoffilename);
  TFile *toffile = TFile::Open(ratio ? tofratiofilename : toffilename);
  //  TFile *hydrofile = TFile::Open(hydrofilename);

  TCanvas *cCanvas = new TCanvas("cCanvas");
  if (cent == -1) cCanvas->Divide(5, 2);
  TCanvas *cCanvasCombined = new TCanvas("cCanvasCombined");
  TCanvas *cCanvasRatio = new TCanvas("cCanvasRatio");
  if (cent == -1) cCanvasRatio->Divide(5, 2);
  TCanvas *cCanvasRatioComb = new TCanvas("cCanvasRatioComb");
  if (cent == -1) cCanvasRatioComb->Divide(5, 2);
  TCanvas *cCanvasRatioFit = new TCanvas("cCanvasRatioFit");
  if (cent == -1) cCanvasRatioFit->Divide(5, 2);
  TPad *curpad = NULL;
  TH1D *hITSsa, *hITSTPC, *hTPCTOF, *hTOF;
  TGraph *hHydro;
  TGraphErrors *gCombined[10];
  TProfile *pCombined[10];
  TH1D *hCombined[10];
  TH1D *hRatio_ITSsa_ITSTPC[10];
  TH1D *hRatio_ITSsa_TPCTOF[10];
  TH1D *hRatio_ITSTPC_TPCTOF[10];
  TH1D *hRatio_ITSTPC_TOF[10];
  TH1D *hRatio_TPCTOF_TOF[10];
  TH1D *hRatio_ITSsa_TOF[10];
  for (Int_t icent = 0; icent < 10; icent++) {
    if (cent != -1 && icent != cent) continue;
    gCombined[icent] = new TGraphErrors();
    pCombined[icent] = new TProfile(Form("pCombined_cent%d", icent), "", NptBins, ptBin);
    hCombined[icent] = new TH1D(Form("hCombined_cent%d", icent), "", NptBins, ptBin);
    TObjArray spectraArray;
    hITSsa = ratio ? GetITSsaRatio(itssafile, part, charge, icent, cutSpectra): GetITSsaSpectrum(itssafile, part, charge, icent, cutSpectra);
    //    hITSTPC = GetITSTPCSpectrum(itstpcfile, part, charge, icent, cutSpectra);
    hTPCTOF = ratio ? GetTPCTOFRatio(tpctoffile, part, charge, icent, cutSpectra) : GetTPCTOFSpectrum(tpctoffile, part, charge, icent, cutSpectra);
    hTOF = ratio ? GetTOFRatio(toffile, part, charge, icent, cutSpectra) : GetTOFSpectrum(toffile, part, charge, icent, cutSpectra);
    //    hHydro = GetHydroSpectrum(hydrofile, part, charge, icent);
    if (cent == -1)
      curpad = (TPad *)cCanvas->cd(icent + 1);
    else
      curpad = (TPad *)cCanvas->cd();
    if (!ratio)
      TH1D *hArea = new TH1D(Form("hArea_%d", icent), Form("%s (%s);p_{T} (GeV/c);#frac{d^{2}N}{dy dp_{t}};", partChargeName[part][charge], centName[icent]), 100, 0., 5.);
    else
      TH1D *hArea = new TH1D(Form("hArea_%d", icent), Form("%s (%s);p_{T} (GeV/c);#frac{d^{2}N}{dy dp_{t}};", "generic ratio", centName[icent]), 100, 0., 5.);
    hArea->Draw();
    Double_t minimum = 0.001;
    Double_t maximum = 1000.;
    if (hITSsa) {
      AddPointsToGraph(hITSsa, gCombined[icent]);
      AddPointsToProfile(hITSsa, pCombined[icent]);
      spectraArray.Add(hITSsa);
      hITSsa->DrawCopy("same");
      if (hITSsa->GetMaximum() > maximum) maximum = hITSsa->GetMaximum();
      if (hITSsa->GetMinimum() < minimum) minimum = hITSsa->GetMinimum();
    }
    if (hITSTPC) {
      AddPointsToGraph(hITSTPC, gCombined[icent]);
      AddPointsToProfile(hITSTPC, pCombined[icent]);
      spectraArray.Add(hITSTPC);
      hITSTPC->DrawCopy("same");
      if (hITSTPC->GetMaximum() > maximum) maximum = hITSTPC->GetMaximum();
      if (hITSTPC->GetMinimum() < minimum) minimum = hITSTPC->GetMinimum();
    }
    if (hTPCTOF) {
      AddPointsToGraph(hTPCTOF, gCombined[icent]);
      AddPointsToProfile(hTPCTOF, pCombined[icent]);
      spectraArray.Add(hTPCTOF);
      hTPCTOF->DrawCopy("same");
      if (hTPCTOF->GetMaximum() > maximum) maximum = hTPCTOF->GetMaximum();
      if (hTPCTOF->GetMinimum() < minimum) minimum = hTPCTOF->GetMinimum();
    }
    if (hTOF) {
      AddPointsToGraph(hTOF, gCombined[icent]);
      AddPointsToProfile(hTOF, pCombined[icent]);
      spectraArray.Add(hTOF);
      hTOF->DrawCopy("same");
      if (hTOF->GetMaximum() > maximum) maximum = hTOF->GetMaximum();
      if (hTOF->GetMinimum() < minimum) minimum = hTOF->GetMinimum();
    }
    if (hHydro) {
      ;//hHydro->Draw("c,same");
    }
    TLegend *legend = curpad->BuildLegend();
    legend->SetFillStyle(0);
    legend->SetFillColor(0);
    legend->DeleteEntry();

    hArea->SetMaximum(maximum * 1.1);
    hArea->SetMinimum(0.01);
    //    gPad->SetLogy();

    /*** RATIOS ***/

    /* switch canvas */
    if (cent == -1)
      curpad = (TPad *)cCanvasRatio->cd(icent + 1);
    else
      curpad = (TPad *)cCanvasRatio->cd();

   
    /* area histo */
    if (!ratio)
      TH1D *hAreaRatio = new TH1D(Form("hAreaRatio_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio;", partChargeName[part][charge], centName[icent]), 100, 0., 5.);
    else
      TH1D *hAreaRatio = new TH1D(Form("hAreaRatio_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio;", "generic ratio", centName[icent]), 100, 0., 5.);

    hAreaRatio->SetMaximum(1.5);
    hAreaRatio->SetMinimum(0.5);
    hAreaRatio->Draw();

    /* do ratios */
    if (hITSsa && hITSTPC) {
      hRatio_ITSsa_ITSTPC[icent] = new TH1D(*hITSsa);
      hRatio_ITSsa_ITSTPC[icent]->Divide(hITSTPC);
      hRatio_ITSsa_ITSTPC[icent]->SetNameTitle(Form("hRatio_ITSsa_ITSTPC_cent%d", icent), "ITSsa / ITSTPC");
      hRatio_ITSsa_ITSTPC[icent]->Draw("same");
    }
    if (hITSsa && hTPCTOF) {
      hRatio_ITSsa_TPCTOF[icent] = new TH1D(*hITSsa);
      hRatio_ITSsa_TPCTOF[icent]->Divide(hTPCTOF);
      hRatio_ITSsa_TPCTOF[icent]->SetNameTitle(Form("hRatio_ITSsa_TPCTOF_cent%d", icent), "ITSsa / TPCTOF");
      hRatio_ITSsa_TPCTOF[icent]->SetMarkerStyle(23);
      hRatio_ITSsa_TPCTOF[icent]->SetMarkerColor(4);
      hRatio_ITSsa_TPCTOF[icent]->Draw("same");
    }
    if (hITSTPC && hTPCTOF) {
      hRatio_ITSTPC_TPCTOF[icent] = new TH1D(*hITSTPC);
      hRatio_ITSTPC_TPCTOF[icent]->Divide(hTPCTOF);
      hRatio_ITSTPC_TPCTOF[icent]->SetNameTitle(Form("hRatio_ITSTPC_TPCTOF_cent%d", icent), "ITSTPC / TPCTOF");
      hRatio_ITSTPC_TPCTOF[icent]->Draw("same");
    }
    if (hTPCTOF && hTOF) {
      hRatio_TPCTOF_TOF[icent] = new TH1D(*hTPCTOF);
      hRatio_TPCTOF_TOF[icent]->Divide(hTOF);
      hRatio_TPCTOF_TOF[icent]->SetNameTitle(Form("hRatio_TPCTOF_TOF_cent%d", icent), "TPCTOF / TOF");
      hRatio_TPCTOF_TOF[icent]->Draw("same");
    }
    if (hITSsa && hTOF) {
      hRatio_ITSsa_TOF[icent] = new TH1D(*hITSsa);
      hRatio_ITSsa_TOF[icent]->Divide(hTOF);
      hRatio_ITSsa_TOF[icent]->SetNameTitle(Form("hRatio_ITSsa_TOF_cent%d", icent), "ITSsa / TOF");
      //      hRatio_ITSsa_TOF[icent]->SetMarkerStyle(25);
      //      hRatio_ITSsa_TOF[icent]->SetMarkerColor(2);
      hRatio_ITSsa_TOF[icent]->Draw("same");
    }

    /* legend */
    TLegend *legendRatio = curpad->BuildLegend();
    legendRatio->SetFillStyle(0);
    legendRatio->SetFillColor(0);
    legendRatio->DeleteEntry();

    CombineSpectra(hCombined[icent], &spectraArray);
    hCombined[icent]->SetFillStyle(0);
    hCombined[icent]->SetFillColor(kOrange + 1);
    hCombined[icent]->SetMarkerColor(kOrange+1);
    hCombined[icent]->SetMarkerStyle(24);
    hCombined[icent]->SetLineColor(kOrange+1);
    hCombined[icent]->SetLineWidth(2);
    hCombined[icent]->SetMarkerSize(0);
    
    //    hCombined[icent]->DrawCopy("same,E2");
    //    pCombined[icent]->DrawCopy("same");

    if (cent == -1)
      cCanvas->cd(icent + 1);
    else
      cCanvas->cd();
    //    hCombined[icent]->Draw("same, E2");

    cCanvasCombined->cd();
    if (cent == -1 && icent != 0)
      hCombined[icent]->Draw("E2,same");
    else
      hCombined[icent]->Draw("E2");

    //    cCanvasCombined->DrawClonePad();
    if (hITSsa) {
      hITSsa->DrawCopy("same");
    }
    if (hITSTPC) {
      hITSTPC->DrawCopy("same");
    }
    if (hTPCTOF) {
      hTPCTOF->DrawCopy("same");
    }
    if (hTOF) {
      hTOF->DrawCopy("same");
    }
    if (hHydro) {
      ;//hHydro->Draw("c,same");
    }

    if (cent == -1)
      cCanvasRatioComb->cd(icent + 1);
    else
      cCanvasRatioComb->cd();
    //    hCombined[icent]->Draw("same, E2");

    TH1 *hhr = HistoUtils_smartratio(hCombined[icent], hCombined[icent]);
    hhr->SetMaximum(1.25);
    hhr->SetMinimum(0.75);
    hhr->SetFillStyle(3001);
    hhr->SetTitle("combined error;p_{T} (GeV/c);ratio wrt. combined");
    hhr->Draw("e2");
    if (hITSsa) {
      hhr = HistoUtils_smartratio(hITSsa, hCombined[icent]);
      hhr->SetLineColor(1);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hITSTPC) {
      hhr = HistoUtils_smartratio(hITSTPC, hCombined[icent]);
      hhr->SetLineColor(1);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hTPCTOF) {
      hhr = HistoUtils_smartratio(hTPCTOF, hCombined[icent]);
      hhr->SetLineColor(8);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hTOF) {
      hhr = HistoUtils_smartratio(hTOF, hCombined[icent]);
      hhr->SetLineColor(4);
      hhr->SetLineWidth(2);
      hhr->Draw("e2,same");
    }
    if (hHydro) {
      ;//hHydro->Draw("c,same");
    }


    if (!fFitFunc)
      continue;
    
    //    gCombined[icent]->Draw("p*");
    //    gCombined[icent]->Fit(fFitFunc, "0q", "", 0.5, 1.0);
    //    gCombined[icent]->Fit(fFitFunc, "0q", "", 0.2, 1.5);
    hCombined[icent]->Fit(fFitFunc, "0q", "", 0., 5.);
    fFitFunc->DrawCopy("same");
    printf("cent = %d, dNdy = %f +- %f\n", icent, fFitFunc->GetParameter(0), fFitFunc->GetParError(0));

    if (cent == -1)
      cCanvas->cd(icent + 1);
    else
      cCanvas->cd();
    fFitFunc->DrawCopy("same");

    if (cent == -1)
      cCanvasRatioFit->cd(icent + 1);
    else
      cCanvasRatioFit->cd();
    if (!ratio)
      TH1D *hAreaRatioFit = new TH1D(Form("hAreaRatioFit_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio wrt. fit;", partChargeName[part][charge], centName[icent]), 100, 0., 5.);
    else
      TH1D *hAreaRatioFit = new TH1D(Form("hAreaRatioFit_%d", icent), Form("%s (%s);p_{T} (GeV/c);ratio wrt. fit;", "generic ratio", centName[icent]), 100, 0., 5.);
    hAreaRatioFit->SetMaximum(1.5);
    hAreaRatioFit->SetMinimum(0.5);
    hAreaRatioFit->Draw();
    legend->Draw("same");

    if (hITSsa) {
      hITSsa->Divide(fFitFunc);
      hITSsa->DrawCopy("same");
    }
    if (hITSTPC) {
      hITSTPC->Divide(fFitFunc);
      hITSTPC->DrawCopy("same");
    }
    if (hTPCTOF) {
      hTPCTOF->Divide(fFitFunc);
      hTPCTOF->DrawCopy("same");
    }
    if (hTOF) {
      hTOF->Divide(fFitFunc);
      hTOF->DrawCopy("same");
    }

  }

}
void drawDphi() { 
  
  TH1D* hdphi[5][5]; // [species][centrality] 
  TH1D* hxjg[5][5]; // [species][centrality] 
  TH1D* hxjgNorm[5][5];
  TFile* fff[5];
  
  fff[kHIDATA] = new TFile("ffFiles/photonTrackCorr_pbpbDATA_output_photonPtThr60_jetPtThr30_20130210_genLevel0.root");
  for ( int iSpecies =0 ; iSpecies<=5 ; iSpecies++) {
    if (iSpecies != kHIDATA)       continue;
    for ( int icent = 1 ; icent<=4 ; icent++) {
      hdphi[iSpecies][icent] = (TH1D*)fff[iSpecies]->Get(Form("jetDphi_icent%d_final",icent));
      hxjg[iSpecies][icent] = (TH1D*)fff[iSpecies]->Get(Form("jetXjg_icent%d_final",icent));
      hxjgNorm[iSpecies][icent] = (TH1D*)hxjg[iSpecies][icent]->Clone(Form("norm_%s",hxjg[iSpecies][icent]->GetName()));
      scaleInt(hxjgNorm[iSpecies][icent]);    
    }}
  
  fff[kHIMC]   = new TFile("ffFiles/photonTrackCorr_pbpbMC_output_photonPtThr60_jetPtThr30_20130210_genLevel0.root"); 
  for ( int iSpecies =0 ; iSpecies<=5 ; iSpecies++) {
    if (iSpecies != kHIMC)         continue;
    for ( int icent = 1 ; icent<=4 ; icent++) {
      hdphi[iSpecies][icent] = (TH1D*)fff[iSpecies]->Get(Form("jetDphi_icent%d_final",icent));
      hxjg[iSpecies][icent] = (TH1D*)fff[iSpecies]->Get(Form("jetXjg_icent%d_final",icent));
      hxjgNorm[iSpecies][icent] = (TH1D*)hxjg[iSpecies][icent]->Clone(Form("norm_%s",hxjg[iSpecies][icent]->GetName()));
      scaleInt(hxjgNorm[iSpecies][icent]);
    }}
  
  
  
  TCanvas* c1 = new TCanvas("c1","",1400,450);
  makeMultiPanelCanvas(c1,4,1,0.0,0.0,0.2,0.15,0.02);
  for ( int icent = 1 ; icent<=4 ; icent++) {
    c1->cd(5-icent);
    handsomeTH1(hdphi[kHIMC][icent],1);
    handsomeTH1(hdphi[kHIDATA][icent],2);
    hdphi[kHIMC][icent]->Scale(1./hdphi[kHIMC][icent]->Integral("width"));
    hdphi[kHIDATA][icent]->Scale(1./hdphi[kHIDATA][icent]->Integral("width"));
    hdphi[kHIMC][icent]->SetAxisRange(3.141592/3.,3.141592,"X");
    hdphi[kHIMC][icent]->SetAxisRange(0.01,5,"Y");
    hdphi[kHIMC][icent]->DrawCopy("hist");
    //  hdphi[kHIDATA][icent]->Draw("same");
    //    gPad->SetLogy();
    
    TF1 *fdphi = new TF1("fdphi","exp(-(TMath::Pi()-x)/[0]) / ([0]*(1-exp(-TMath::Pi()/[0]))) ",2.0*TMath::Pi()/3.0,TMath::Pi());
    fdphi->SetParName(0,"width");
    fdphi->SetParameter("width",0.22);
        
    float fitxmin=3.1415926*2./3;
    //    float fitxmin=2.5;
    hdphi[kHIMC][icent]->Fit("fdphi","0llm","",fitxmin,3.1415926);
    fdphi->SetLineWidth(1);
    fdphi->SetLineStyle(2);
    fdphi->SetLineColor(kBlue);
    float dphiWidth = fdphi->GetParameter("width");
    float dphiWidthErr = fdphi->GetParError(0);
    cout << " dphiWidth,dphiWidthErr = " << dphiWidth <<"   "<< dphiWidthErr << endl;
    fdphi->DrawCopy("same");
  }
  c1->SaveAs("pdfFiles/dPhi_MC_only.pdf");


  TCanvas* c2 = new TCanvas("c2","",1400,450);
  makeMultiPanelCanvas(c2,4,1,0.0,0.0,0.2,0.15,0.02);
  for ( int icent = 1 ; icent<=4 ; icent++) {
    c2->cd(5-icent);
    handsomeTH1(hxjgNorm[kHIMC][icent],1);
    handsomeTH1(hxjgNorm[kHIDATA][icent],2);
    hxjgNorm[kHIMC][icent]->SetAxisRange(-0.01,0.35,"Y");
    hxjgNorm[kHIMC][icent]->DrawCopy("");
    //    hxjgNorm[kHIDATA][5-icent]->Draw("same");
    int lowCent = centBin1[icent-1];    int highCent = centBin1[icent]-1;
    drawText(Form("%.0f%% - %.0f%%", float((float)lowCent*2.5), float((float)(highCent+1)*2.5)), 0.67,0.7,1);
  }
  TLegend *l12 = new TLegend(0.304355,0.755085,.8,0.9552542,NULL,"brNDC");
  easyLeg(l12,"p_{T}^{Jet}/p_{T}^{#gamma}");
  l12->AddEntry(hxjgNorm[kHIMC][1],"PYTHIA+HYDJET","pl");
  c2->cd(1);   l12->Draw();

  c2->SaveAs("pdfFiles/xgj_MC_only.pdf");

  TCanvas* c2MCover = new TCanvas("c2MCover","",500,500);
  bool drawn=false;
  for ( int icent = 1 ; icent<=4 ; icent++) {
    c2MCover->cd(icent);
    handsomeTH1(hxjgNorm[kHIMC][icent],ycolor[icent]);
    hxjgNorm[kHIMC][5-icent]->SetAxisRange(-0.01,0.38,"Y");
    if (drawn)  
      hxjgNorm[kHIMC][5-icent]->Draw("same");
    else       hxjgNorm[kHIMC][5-icent]->Draw("");
    
    
    drawn = true;
  }
  TLegend *l11 = new TLegend(0.1794355,0.7055085,1,0.9152542,NULL,"brNDC");
  easyLeg(l11,"p_{T}^{Jet}/p_{T}^{#gamma} of PYTHIA embedded in"); 
  l11->AddEntry(hxjgNorm[kHIMC][4],"HYDJET 50-100%","p");
  l11->AddEntry(hxjgNorm[kHIMC][3],"HYDJET 30-50%","p");
  l11->AddEntry(hxjgNorm[kHIMC][2],"HYDJET 10-30%","p");
  l11->AddEntry(hxjgNorm[kHIMC][1],"HYDJET 0 -10%","p");
  l11->Draw();
  c2MCover->SaveAs("pdfFiles/xgj_MC_OnePannel.pdf");


  
  TCanvas* c3 = new TCanvas("c3","",500,500);
  TH1D* npartTempHist = new TH1D("meanR",";N_{part}; R",100,0,400);
  
  double npart4[8] = { 43.6661-10, 43.6661+10, 116.36-10, 116.36+10, 235.769-10, 235.769+10, 359.22-10,359.22+10};
  double npart4_2[4] = { 43.6661, 116.36, 235.769, 359.22};
  TGraphAsymmErrors* gR[5];

  for ( int iSpec = 0 ; iSpec<5 ; iSpec++) {
    
    if ( (iSpec != kHIDATA) && (iSpec != kHIMC) )       continue;
    gR[iSpec] = new TGraphAsymmErrors();
    gR[iSpec]->SetName(Form("gR_%d",iSpec));
    for ( int icent =4 ; icent>=1 ; icent--) {
      double theRerror;
      double theR = hxjg[iSpec][icent]->IntegralAndError(1, hxjg[iSpec][5-icent]->GetNbinsX(), theRerror, "width");
      gR[iSpec]->SetPoint(icent, npart4_2[4 - icent], theR );
      gR[iSpec]->SetPointError(icent, 0.001,0.001, theRerror, theRerror);    
    }
  }
  handsomeTH1(npartTempHist,1);
  npartTempHist->SetAxisRange(0.3,1.0,"Y");
  npartTempHist->DrawCopy();
  gR[kHIDATA]->SetMarkerColor(2);
  gR[kHIDATA]->SetLineColor(2);
  gR[kHIMC]->Draw("same p");
  //  gR[kHIDATA]->Draw("same p");

  c3->SaveAs("pdfFiles/r_MC_only.pdf");

  TCanvas* c3a = new TCanvas("c3a","",500,500);
  npartTempHist->DrawCopy();
  gR[kHIMC]->Draw("same p");
  gR[kHIDATA]->Draw("same p");
  TLegend *l13 = new TLegend(0.1794355,0.7055085,1,0.9152542,NULL,"brNDC");
  easyLeg(l13,"R_{J,#gamma}");
  l13->AddEntry(gR[kHIDATA],"PbPb data","pl");
  l13->AddEntry(gR[kHIMC],"PYTHIA+HYDJET","pl");
  l13->Draw();
  c3a->SaveAs("pdfFiles/r_MC_Data.pdf");


  TCanvas* c4 = new TCanvas("c4","",500,500);
  
  TGraphAsymmErrors* gX[5];

  for ( int iSpec = 0 ; iSpec<5 ; iSpec++) {
    
    if ( (iSpec != kHIDATA) && (iSpec != kHIMC) )       continue;
    gX[iSpec] = new TGraphAsymmErrors();
    gX[iSpec]->SetName(Form("gX_%d",iSpec));
    for ( int icent =4 ; icent>=1 ; icent--) {
      double theX      = hxjg[iSpec][icent]->GetMean();
      double theXerror = hxjg[iSpec][icent]->GetMeanError();
      gX[iSpec]->SetPoint(icent, npart4_2[4 - icent], theX );
      gX[iSpec]->SetPointError(icent, 0.001,0.001, theXerror, theXerror);    
    }
  }
  handsomeTH1(npartTempHist,1);
  npartTempHist->SetYTitle("<X_{J,#gamma}>");
  npartTempHist->SetAxisRange(0.6,1.1,"Y");
  npartTempHist->DrawCopy();
  gX[kHIDATA]->SetMarkerColor(2);
  gX[kHIDATA]->SetLineColor(2);
  gX[kHIMC]->Draw("same p");
  //  gX[kHIDATA]->Draw("same p");

  c4->SaveAs("pdfFiles/meanX_MC_only.pdf");


 TCanvas* c4a = new TCanvas("c4a","",500,500);
  
 npartTempHist->DrawCopy();
 gX[kHIMC]->Draw("same p");
 gX[kHIDATA]->Draw("same p");
 TLegend *l14 = new TLegend(0.1794355,0.7055085,1,0.9152542,NULL,"brNDC");
 easyLeg(l14,"<X_{J,#gamma}>");
 l14->AddEntry(gX[kHIDATA],"PbPb data","pl");
 l14->AddEntry(gX[kHIMC],"PYTHIA+HYDJET","pl");
 l14->Draw();
 c4a->SaveAs("pdfFiles/meanX_MC_Data.pdf");




    
}
Esempio n. 9
0
int FitSPE(TH1* spe, int ntriggers) 
{
  double fitmin, fitmax;
  double params[NPAR];
  //find the likely place for the single p.e. peak
  params[MEAN] = spe->GetMean();
  params[SIGMA] = spe->GetRMS();
  int bin = spe->FindBin(params[MEAN]);
  if(spe->GetMaximumBin() == 1){
    spe->Fit("gaus","Q0","",spe->GetBinCenter(bin), 
	     spe->GetBinCenter(bin+20));
  }
  else{
    spe->Fit("gaus","Q0","",spe->GetBinCenter(bin-10), 
	     spe->GetBinCenter(bin+10));
  }
  TF1* gaus = spe->GetFunction("gaus");
  if(gaus->GetParameter(1) > 0)
    params[MEAN] = gaus->GetParameter(1);
  if(gaus->GetParameter(2) > 0 && gaus->GetParameter(2) < params[SIGMA])
    params[SIGMA] = gaus->GetParameter(2);
  
  params[LAMBDA] = 0.5;
  //find the maximum fit range
  bin = spe->GetNbinsX();
  while(spe->GetBinContent(--bin) < 2) {}
  fitmax = spe->GetBinCenter(bin);
  
  spe->Fit("expo","Q0","",spe->GetBinCenter(bin), spe->GetBinCenter(bin-10));
  
  //find the best estimate for the exponentials
  //the first is from the first few bins
  bin = spe->FindBin(params[MEAN]) - 5;
  double compval = spe->GetBinContent(bin--);
  while(spe->GetBinContent(bin) < compval && spe->GetBinContent(bin) != 0){
    compval = spe->GetBinContent(bin--);
  }
  if(spe->GetBinContent(bin) == 0){
    fitmin = spe->GetBinCenter(bin+1);
  }
  else{
    ++bin;
    //now find the max of the turnover
    int minbin = bin;
    compval = spe->GetBinContent(bin--);
    while(spe->GetBinContent(bin) > compval && bin > 0 ){
      compval = spe->GetBinContent(bin--);
    }
    ++bin;
    spe->Fit("expo","Q0","",spe->GetBinCenter(bin), spe->GetBinCenter(minbin));
    params[AMP1] = spe->GetFunction("expo")->GetParameter(0);
    params[L1] = spe->GetFunction("expo")->GetParameter(1);
    fitmin = spe->GetBinCenter(bin+1);
  }
  
  //estimate the peak heights
  
  params[CONSTANT] = ntriggers * spe->GetBinWidth(1);
  fitmin = spe->GetBinCenter(4);
  
  TF1* spefunc = new TF1("spefunc", SPEFunc, fitmin, fitmax, NPAR);
  
  
  spefunc->SetParameters(params);
  for(int i=0; i<NPAR; i++)
    spefunc->SetParName(i, names[i]);
  spefunc->SetParLimits(CONSTANT, 0 , params[CONSTANT]*100.);
  spefunc->SetParLimits(LAMBDA, 0, 2);
  spefunc->SetParLimits(MEAN, std::max(params[MEAN]-params[SIGMA],0.), 
			params[MEAN]+params[SIGMA]);
  spefunc->SetParLimits(SIGMA, 0, spe->GetRMS());
    
  spefunc->SetParLimits(L1, -30, 0);
  spefunc->SetParLimits(AMP1, -30, 30);
  spefunc->SetParLimits(L2, -30, 0);
  spefunc->SetParLimits(AMP2, -30, 30);
    
  //spefunc->FixParameter(CONSTANT, ntriggers * spe->GetBinWidth(1));
  
  //return 0;
  spefunc->SetLineStyle(1);
  spefunc->SetLineColor(kBlue);
  int result = spe->Fit(spefunc,"MRNI");
  spefunc->DrawCopy("same");
  std::cout<<"Fit results: \n"<<
    "\t Chi2/NDF = "<<spefunc->GetChisquare()<<"/"<<spefunc->GetNDF()
	   <<"\n\t Prob = "<<spefunc->GetProb()<<std::endl;
  for(int i=0; i<NPAR; i++)
    params[i] = spefunc->GetParameter(i);
  TF1* background = new TF1("background",background_func,fitmin,fitmax,NPAR);
  background->SetLineColor(kRed);
  background->SetParameters(spefunc->GetParameters());
  background->DrawCopy("same");
  
  TF1* signal = new TF1("signal",signal_func,fitmin,fitmax,NPAR);
  signal->SetLineColor(kGreen); 
  signal->SetParameters(spefunc->GetParameters());
  signal->DrawCopy("same");
  
  TF1* apeak = new TF1("apeak","[0]*TMath::Gaus(x,[1],[2],1)",fitmin, fitmax);
  apeak->SetLineColor(kMagenta);
  apeak->SetLineStyle(2);
  for(int i=1; i<=NPEAKS; i++){
    apeak->SetParameters(params[CONSTANT]*TMath::Poisson(i,params[LAMBDA]),
			 i*params[MEAN], sqrt(i)*params[SIGMA]);
    apeak->DrawCopy("same");
  }
  cout<<"Entries in Events tree: "<<ntriggers<<"; Poisson trials: "
      <<params[CONSTANT] / spe->GetBinWidth(1)<<std::endl;
  
  return result;
}
Esempio n. 10
0
//-------------------------------------------------------------------
void Alignment_1(int cluster_length_leftCut = 2,int cluster_length_rightCut = 7,float TotSignal_Cut = 5){
  gStyle->SetOptStat(11111111);
  gStyle->SetOptFit(111111111);
  //gAnaCombine->LinkBranches();
  ofstream outputlog("./AMS/AMSAlignment_1.txt",ios::out | ios::app);
  outputlog<<"\nfile: "<<gRootIOSvc->GetInputFileName()<<".\tCluster length: "<<cluster_length_leftCut<<"~"<<cluster_length_rightCut<<".\tTotal signale cut "<<TotSignal_Cut<<endl;

  TH1D *h_ladder_stripID[5][2];
  TH1D *h_Refer[5][2];
  char name[80];
  for(short lid =0;lid<5;++lid){
    for(short sid=0;sid<2;++sid){
      snprintf(name,80,"ladder_%d-side_%d",lid,sid);
      h_ladder_stripID[lid][sid] = new TH1D(name,name,500,0,1100);
      snprintf(name,80,"ladder_%d-side_%d VS ladder 0",lid,sid);
      h_Refer[lid][sid] = new TH1D(name,name,200,-200,200);
    }
    snprintf(name,80,"ladder_%d",lid);
    h_ladder_stripID[lid][0]->SetTitle(name);
    snprintf(name,80,"Seed Address ladder_%d",lid);
    h_Refer[lid][0]->SetTitle(name);
  }

  TChain *tree = gAnaCombine->GetTree();
  long nEvt = tree->GetEntries();
  std::vector<Cluster*> clusterIndex[5][2];
  for(long ievt=0;ievt<nEvt;++ievt){
    tree->GetEntry(ievt);
    short nCluster = gAnaCombine->fEvtAMS->GetEntriesFast();
    for(int iclu=0;iclu<nCluster;++iclu){
      Cluster *acluster = (Cluster*)gAnaCombine->fEvtAMS->At(iclu);
      if(acluster->GetTotSig()>TotSignal_Cut && cluster_length_leftCut<=acluster->length && acluster->length <= cluster_length_rightCut){
        int ladder = acluster->ladder;
        if(ladder==5){
          ladder = 2;
        }else if(ladder == 4){
          ladder = 3;
        }else if(ladder == 3){
          ladder = 4;
        }
        clusterIndex[ladder][acluster->side].push_back(acluster);
      }
    }
    if(clusterIndex[0][0].size() == 1 && clusterIndex[0][1].size() == 1){
      for(short il=0;il<5;++il){
        for(short is=0;is<2;++is){
          if(clusterIndex[il][is].size() == 1){
            h_ladder_stripID[il][is]->Fill(clusterIndex[il][is][0]->GetSeedAdd());
            h_Refer[il][is]->Fill(clusterIndex[il][is][0]->GetSeedAdd() - clusterIndex[0][is][0]->GetSeedAdd());
          }
          clusterIndex[il][is].clear();
        }
      }
    }
  }
  snprintf(name,80,"AMS Alignment_1_a: cluster length %d~%d, total signal cut %f",cluster_length_leftCut,cluster_length_rightCut,TotSignal_Cut);
  TCanvas *c1 = new TCanvas(name,name);
  c1->Divide(2,3);
  snprintf(name,80,"AMS Alignment_1_b: cluster length %d~%d, totalt signal cut %f",cluster_length_leftCut,cluster_length_rightCut,TotSignal_Cut);

  TF1 *gausFit = new TF1("GausFit","gaus",0,150);
  TCanvas *c2 = new TCanvas(name,name);
  c2->Divide(2,3);
  double mean=0.,sigma =0.;
  for(short lid=0;lid<5;++lid){
    c1->cd(lid+1);
    h_ladder_stripID[lid][0]->Draw();
    h_ladder_stripID[lid][1]->SetLineColor(6);
    h_ladder_stripID[lid][1]->Draw("same");

    c2->cd(lid+1);
    h_Refer[lid][0]->Draw();
    mean = h_Refer[lid][0]->GetMean(); sigma = h_Refer[lid][0]->GetRMS();
    gausFit->SetRange(mean-2.5*sigma,mean+2.5*sigma);
    h_Refer[lid][0]->Fit(gausFit,"R0Q");
    gausFit->DrawCopy("lsame");
    outputlog<<lid<<"  "<<gausFit->GetParameter(1)<<"  "<<gausFit->GetParameter(2)<<"    ";

    h_Refer[lid][1]->SetLineColor(6);
    h_Refer[lid][1]->Draw("same");
    mean = h_Refer[lid][1]->GetMean(); sigma = h_Refer[lid][1]->GetRMS();
    gausFit->SetRange(mean-2.5*sigma,mean+2.5*sigma);
    h_Refer[lid][1]->Fit(gausFit,"R0Q");
    gausFit->DrawCopy("lsame");
    outputlog<<gausFit->GetParameter(1)<<"  "<<gausFit->GetParameter(2)<<endl;
  }
}
void DoTDeriMax1090Correction(TString SpectrumFileInput = "/lustre/miifs05/scratch/him-specf/hyp/steinen/COSYBeamtestAna/COSYnewMogon/June2014/COSYJune2014Dataset11_200,100,0,5339_SR1.root", TString FitFileInput = "/lustre/miifs05/scratch/him-specf/hyp/steinen/COSYBeamtestAna/COSYnewMogon/Fit/FitCOSYJune2014Dataset11_200,100,0,5339_SR1.root")
{
	TH2D *hSpectrumTDeriMax1090_EnergyChannel;
	TH2D *hSpectrumTDeriMax1090Rel_EnergyChannel;
	
	TH2D *hSpectrumT1090_EnergyChannelCorr1;
	TNtuple *DataNTuple;
	TFile *SpectrumInput = new TFile(SpectrumFileInput.Data());
	
	hSpectrumTDeriMax1090_EnergyChannel = (TH2D*) SpectrumInput->Get("Histograms/Energy_DeriMaxT90/Energy_DeriMaxT90_01");
	hSpectrumTDeriMax1090_EnergyChannel->SetDirectory(0);
	hSpectrumTDeriMax1090Rel_EnergyChannel = (TH2D*) SpectrumInput->Get("Histograms/Energy_DeriMaxT90Rel/Energy_DeriMaxT90Rel_01");
	hSpectrumTDeriMax1090Rel_EnergyChannel->SetDirectory(0);
	hSpectrumT1090_EnergyChannelCorr1 = (TH2D*) SpectrumInput->Get("Histograms/EnergyRt1090/EnergyRt1090CorrectionRt_01");
	hSpectrumT1090_EnergyChannelCorr1->SetDirectory(0);
	SpectrumInput->Close();
	//hSpectrumTDeriMax1090_EnergyChannel->Draw("colz");
	
	
	TFile *FitInput = new TFile(FitFileInput.Data(),"Update");
	DataNTuple = (TNtuple*)FitInput->Get("DataNTuple");
	DataNTuple->Scan();
	
	Int_t entries = (Int_t)DataNTuple->GetEntries();
	cout<<"Number of Entries: "<<entries<< endl;
	const int entriesArrayValue =entries;
	TF1 *FitFunc[entriesArrayValue];
	float Energy=0;
	float ChannelPeakPos=0;
	float ChannelRangeMin=0;
	float ChannelRangeMax=0;
	DataNTuple->SetBranchAddress("Energy",&Energy);
	DataNTuple->SetBranchAddress("ChannelPeakPos",&ChannelPeakPos);
	DataNTuple->SetBranchAddress("ChannelRangeMin",&ChannelRangeMin);
	DataNTuple->SetBranchAddress("ChannelRangeMax",&ChannelRangeMax);
	
	TCanvas* can=new TCanvas();
	gPad->SetLogz();
	hSpectrumTDeriMax1090_EnergyChannel->GetXaxis()->SetRangeUser(-30,250);
	hSpectrumTDeriMax1090Rel_EnergyChannel->GetXaxis()->SetRangeUser(-0.1,0.95);
	
	for (Int_t ki=0;ki<entries;ki++)
	{
		DataNTuple->GetEntry(ki);
		//if (int(Energy) == 1332)
		//if (int(Energy) == 510)
		//if (ki == entries-1)
		{
			cout << ChannelRangeMin << " " << ChannelRangeMax << endl;
			
			
			//first correction via TDeriMaxT90Rel
			hSpectrumTDeriMax1090_EnergyChannel->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
			hSpectrumTDeriMax1090Rel_EnergyChannel->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
			//TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+pol0(3)",ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParameters(1000,ChannelPeakPos-10,4,10);
			//FitFuncSlices->SetParLimits(1,ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParLimits(2,0,10);
			//FitFuncSlices->SetParLimits(3,0,100);
	
			//gDirectory->ls();
			
			TH1D *hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually=new TH1D("hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually","",hSpectrumTDeriMax1090Rel_EnergyChannel->GetNbinsX(),-0.3,1.3);
			//cout <<hSpectrumTDeriMax1090_EnergyChannel_MaxPos->GetEntries()<< endl;
			for(int binX = hSpectrumTDeriMax1090Rel_EnergyChannel->GetXaxis()->FindBin(-0.1);binX <= hSpectrumTDeriMax1090Rel_EnergyChannel->GetXaxis()->FindBin(0.90);binX++)
			{
				cout << "binx " << binX << endl;
				TH1D *hProfileY =hSpectrumTDeriMax1090Rel_EnergyChannel->ProjectionY("_py",binX,binX);	
				double MaxValue=hProfileY->GetBinCenter(hProfileY->GetMaximumBin());
				TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+[3]",MaxValue-20,MaxValue+20);
				TF1* FitFuncGausSlices = new TF1("FitFuncGausSlices","gaus(0)",MaxValue-20,MaxValue+20);
				FitFuncGausSlices->SetParameters(hProfileY->GetBinContent(hProfileY->GetMaximumBin()),MaxValue,4);
				
				hProfileY->Fit(FitFuncGausSlices,"RNQ");
				
				FitFuncSlices->SetParameters(FitFuncGausSlices->GetParameter(0),FitFuncGausSlices->GetParameter(1),FitFuncGausSlices->GetParameter(2),10);
				
				FitFuncSlices->SetParLimits(0,0,10000);
				FitFuncSlices->SetParLimits(1,MaxValue-10,MaxValue+10);
				FitFuncSlices->SetParLimits(2,0,10);
				FitFuncSlices->SetParLimits(3,0,100);
				hProfileY->Fit(FitFuncSlices,"RNQ");
				
				cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetParError(1) <<endl;
				hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->SetBinContent(binX, FitFuncSlices->GetParameter(1));
				hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->SetBinError(binX, FitFuncSlices->GetParError(1));
				
				
			}
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->GetYaxis()->SetRangeUser(ChannelPeakPos-100,ChannelPeakPos+50);
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->GetXaxis()->SetRangeUser(-0.05,0.9);
			TF1 * funcCorrConst = new TF1("funcCorrConst","pol0",-0.03,0.03);
			funcCorrConst->SetLineColor(kRed);
			TF1 * funcCorrPol = new TF1("funcCorrPol",PolPiecewise,-0.05,0.9,6);
			
			funcCorrPol->SetLineColor(kBlue);
			funcCorrPol->SetParameter(0,0.04);
			funcCorrPol->SetParameter(1,ChannelPeakPos);
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->Fit(funcCorrConst,"R");
			hSpectrumTDeriMax1090Rel_EnergyChannel_MaxPosManually->Fit(funcCorrPol,"R+");
			TCanvas* can2=new TCanvas();
			gPad->SetLogz();
			
			hSpectrumTDeriMax1090Rel_EnergyChannel->Draw("colz");
			funcCorrPol->DrawCopy("same");
			for(int i = 7;i>0;i--)
				funcCorrPol->SetParameter(i,funcCorrPol->GetParameter(i)/funcCorrPol->GetParameter(1));
			funcCorrPol->Print();
			char buf[20];
			sprintf(buf, "funcCorrNorm_%d",ki);
			funcCorrPol->Write(buf,TObject::kOverwrite);
			
			funcCorrConst->Delete();
			funcCorrPol->Delete();
			
			
			//second correction via T1090 (after first)
			
			hSpectrumT1090_EnergyChannelCorr1->GetYaxis()->SetRangeUser(ChannelRangeMin,ChannelRangeMax);
			
			//TF1* FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+pol0(3)",ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParameters(1000,ChannelPeakPos-10,4,10);
			//FitFuncSlices->SetParLimits(1,ChannelRangeMin,ChannelRangeMax);
			//FitFuncSlices->SetParLimits(2,0,10);
			//FitFuncSlices->SetParLimits(3,0,100);
	
			//gDirectory->ls();
			
			TH1D *hSpectrumT1090_EnergyChannelCorr1_MaxPosManually=new TH1D("hSpectrumT1090_EnergyChannelCorr1_MaxPosManually","",hSpectrumT1090_EnergyChannelCorr1->GetNbinsX(),0,1000);
			//cout <<hSpectrumTDeriMax1090_EnergyChannel_MaxPos->GetEntries()<< endl;
			for(int binX = hSpectrumT1090_EnergyChannelCorr1->GetXaxis()->FindBin(30);binX <= hSpectrumT1090_EnergyChannelCorr1->GetXaxis()->FindBin(500);binX++)
			{
				cout << "binx " << binX << endl;
				TH1D *hProfileY =hSpectrumT1090_EnergyChannelCorr1->ProjectionY("_py",binX,binX);
				//hProfileY->Draw();
				//return 0;
				double MaxValue=hProfileY->GetBinCenter(hProfileY->GetMaximumBin());
				FitFuncSlices = new TF1("FitFuncSlices","gaus(0)+[3]",MaxValue-20,MaxValue+20);
				FitFuncGausSlices = new TF1("FitFuncGausSlices","gaus(0)",MaxValue-20,MaxValue+20);
				FitFuncGausSlices->SetParameters(hProfileY->GetBinContent(hProfileY->GetMaximumBin()),MaxValue,4);
				
				hProfileY->Fit(FitFuncGausSlices,"RNQ");
				
				FitFuncSlices->SetParameters(FitFuncGausSlices->GetParameter(0),FitFuncGausSlices->GetParameter(1),FitFuncGausSlices->GetParameter(2),10);
				
				FitFuncSlices->SetParLimits(0,0,10000);
				FitFuncSlices->SetParLimits(1,MaxValue-10,MaxValue+10);
				FitFuncSlices->SetParLimits(2,0,10);
				FitFuncSlices->SetParLimits(3,0,100);
				hProfileY->Fit(FitFuncSlices,"RNQ");
				
				cout <<MaxValue<<"  " << FitFuncSlices->GetParameter(1) << "   " << FitFuncSlices->GetParError(1) <<endl;
				hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->SetBinContent(binX, FitFuncSlices->GetParameter(1));
				hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->SetBinError(binX, FitFuncSlices->GetParError(1));
				
			}
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->GetYaxis()->SetRangeUser(ChannelPeakPos-100,ChannelPeakPos+50);
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->GetXaxis()->SetRangeUser(30,500);
			new TCanvas();
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->Draw();
			
			TF1 * funcCorrConst = new TF1("funcCorrConst","pol0",50,350);
			funcCorrConst->SetLineColor(kRed);
			TF1 * funcCorrPol = new TF1("funcCorrPol","pol6",50,300);
			
			funcCorrPol->SetLineColor(kBlue);
			funcCorrPol->SetParameter(0,0.04);
			funcCorrPol->SetParameter(1,ChannelPeakPos);
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->Fit(funcCorrConst,"R");
			hSpectrumT1090_EnergyChannelCorr1_MaxPosManually->Fit(funcCorrPol,"R+");
			
			TCanvas* can2=new TCanvas();
			gPad->SetLogz();
			
			hSpectrumT1090_EnergyChannelCorr1->Draw("colz");
			funcCorrPol->DrawCopy("same");
			for(int i = 7;i>=0;i--)
				funcCorrPol->SetParameter(i,funcCorrPol->GetParameter(i)/funcCorrConst->GetParameter(0));
			funcCorrPol->Print();
			char buf[20];
			sprintf(buf, "funcCorr2Norm_%d",ki);
			funcCorrPol->Write(buf,TObject::kOverwrite);
			
			funcCorrConst->Delete();
			funcCorrPol->Delete();
			//return 0;
			
		}
	}
	//can->ls();
	gDirectory->Delete("ncCorrPol;1");
	
	FitInput->ls();
	//TCanvas* can3=new TCanvas();
	//hSpectrumTDeriMax1090_EnergyChannel->ProfileX()->Draw();
	//hSpectrumTDeriMax1090Rel_EnergyChannel->ProfileX()->Draw();
	//hSpectrumTDeriMax1090Rel_EnergyChannel->Fit("pol3");
	FitInput->Close();
	
	
}
void GradeCorrelation(double prob = 0.10, int nCut = 50) {
	
	std::cout << "Starting Grade Correlation..." << std::endl;
	TBenchmark* myBenchmark = new TBenchmark();
	
	myBenchmark->Start("NormMap");
	// Get the student TTree prepared in another macro.
	if (MyFunctions::gradeNormMap.size() == 0)
		MyFunctions::BuildGradeNormMap();
	myBenchmark->Stop("NormMap");
	
	std::cout << "Made GradeNormMap..." << std::endl;
	
	// Just a quick look at the data in the Students TTree
	TFile* f = new TFile("Students.root");
	TTree* studentTree = (TTree*)f->Get("Students");
	Student* student = 0;
	studentTree->SetBranchAddress("student", &student);
	
	Long64_t nentries = studentTree->GetEntriesFast();
	
	std::cout << "Entries in Students TTree = " << nentries << std::endl;
	
	// We want to loop over students and look at pairs of courses taken in different semesters to see if there is
	// any correlation between graede performance.
	
	std::map<std::pair<TString, TString>, CorrelationCalculator> corrMap;
	
//	nentries = 1000;
	
	myBenchmark->Start("Main Loop");
	int nPairAll = 0;
	for (Long64_t jentry = 0; jentry < nentries; ++jentry) {
		studentTree->GetEntry(jentry);
		if (jentry % 1000 == 0)
			std::cout << "At student " << jentry << std::endl;
//		std::cout << "Looking at student " << student->Id() << std::endl;
		student->Finalize();  // Regenerates non-persisted references
		int nTerms = student->Enrollments().size();
//		std::cout << "nTerms = " << nTerms << std::endl;
		
		for (int iTerm = 0; iTerm < nTerms - 1; ++iTerm) {
			const Student::Enrollment iEnrollment = student->Enrollments()[iTerm];
			if (!MyFunctions::regularSemester(iEnrollment.term)) continue;
			for (Student::Grade iGrade : iEnrollment.grades) {
				if (!MyFunctions::ValidGrade(iGrade.grade)) continue;
				// Get a prediction for this grade using norm-corrected grades
//				std::cout << "1" << std::endl;
				double prediction_i = student->CourseGradePrediction(iGrade, Student::DISTRIBUTION);
//				std::cout << "2" << std::endl;
				double delta_i = iGrade.quality - prediction_i;
			
				// Find next regular term only
				bool foundRegTerm = false;
				for (int jTerm = iTerm + 1; jTerm < nTerms && !foundRegTerm; ++jTerm) {
					const Student::Enrollment jEnrollment = student->Enrollments()[jTerm];
					if (!MyFunctions::regularSemester(jEnrollment.term)) continue;
					foundRegTerm = true;
					for (Student::Grade jGrade : jEnrollment.grades) {
						if (jGrade.course == iGrade.course) continue;
						if (!MyFunctions::ValidGrade(jGrade.grade)) continue;
						
						double prediction_j = student->CourseGradePrediction(jGrade, Student::DISTRIBUTION);
						double delta_j = jGrade.quality - prediction_j;
						
						corrMap[std::make_pair(iGrade.course, jGrade.course)].Add(delta_i, delta_j);
						++nPairAll;
						
					}
				}
			} 
		}
		
	}
	myBenchmark->Stop("Main Loop");
	
	std::cout << "nPairAll     = " << nPairAll << std::endl;
	std::cout << "Unique Pairs = " << corrMap.size() << std::endl;
	
	TH1D* rHist = new TH1D("rHist", "Correlation Coefficient, #rho", 120, -1.2, 1.2);
	TH1D* pHist = new TH1D("pHist", "Probablity Distribution", 100, 0., 1.);
	TH1D* nHist = new TH1D("nHist", "Number of entries", 100, 0., 2000.);
	TH2D* pVrHist = new TH2D("pVrHist", "Prob vs. #rho", 100, -1., 1., 100, 0., 1.);
	
	myBenchmark->Start("Prune");
	for (auto iter = corrMap.begin(); iter != corrMap.end();) {
		if (iter->second.n() < nCut) {
			corrMap.erase(iter++);
			continue;
		}
		double p = iter->second.p();
		double r = iter->second.r();

		// Test for nan?
		if (p != p) {
			std::cout << "Found p = nan: n = " << iter->second.n() << std::endl;
			corrMap.erase(iter++);
			continue;
		}
		if (p < 0.) {
			corrMap.erase(iter++);
			continue;
		}
		rHist->Fill(r);
		pHist->Fill(p);
		nHist->Fill(iter->second.n());
		pVrHist->Fill(r, p);
		if (p < 1. - prob && p > prob) {
			corrMap.erase(iter++);
		}
		else {
			std::cout << "r = " << iter->second.r() << ", p = " << p << std::endl;
			++iter;
		}
	}
	myBenchmark->Stop("Prune");
	std::cout << "Post Cut     = " << corrMap.size() << std::endl;
	
	myBenchmark->Start("Sort");
	std::vector<std::pair<std::pair<TString, TString>, CorrelationCalculator>> corrVec(corrMap.begin(), corrMap.end());
	std::sort(corrVec.begin(), corrVec.end(), &sortFunc);
	myBenchmark->Stop("Sort");
	
	int printTop = 50;
	int printed = 0;
	for (auto const& entry : corrVec) {
		std::cout << entry.first.first << " : " << entry.first.second << "\t, n = " << entry.second.n() << "\t, r = " << entry.second.r() 
			<< "\t, p = " << entry.second.p() << std::endl;
		++printed;
		if (printed >= printTop) break;
	}

	TCanvas* c1 = new TCanvas("c1", "Grade Correlation", 1600, 1200);
	c1->Divide(2,2);
	c1->cd(1);
	TF1* myGaus = new TF1("myGaus", "gaus", -1., 1.);
	myGaus->SetParameters(600., 0., 0.2);
	myGaus->FixParameter(1, 0.);
	rHist->Fit(myGaus, "0B", "", -1., 0.);
	rHist->DrawCopy();
	myGaus->DrawCopy("SAME");
	c1->cd(2);
	pHist->DrawCopy();
	c1->cd(3);
	nHist->DrawCopy();
	c1->cd(4);
	pVrHist->DrawCopy();
	
	float rt, cp;
	myBenchmark->Summary(rt, cp);
	
}