Example #1
0
int main(int argc, char *argv[]) {

  // make sure command line arguments were supplied
  if (argc != 6) { cerr << "Usage: " << argv[0] << " [reference.root] [new-comparison.root] [root dir] [new-release] [old-release] \n"; return 1; }

  // create the comparison class
  PlotCompareUtility *pc = new PlotCompareUtility(argv[1],argv[2],argv[3],"METTask_");
  HistoData *hd;

  if (pc->GetStatus() != 0) { cout << "Final Result: no_data" << endl; return 0; }

  // add histogram information
  //Type = 0 (Do not rebin or zoom) , 1 (Rebin and Zoom, x-axis > 0 ) , 2 (Rebin and Zoom)
  hd = pc->AddHistoData("MET"); hd->SetType(1);
  hd = pc->AddHistoData("METPhi"); hd->SetType(2);
  hd = pc->AddHistoData("METSig"); hd->SetType(1);
  hd = pc->AddHistoData("MEx"); hd->SetType(2);
  hd = pc->AddHistoData("MEy"); hd->SetType(2);
  hd = pc->AddHistoData("SumET"); hd->SetType(2);

  if (pc->GetStatus() != 0) { cerr << "error encountered, exiting.\n"; return pc->GetStatus(); }

  int num_histos = pc->GetNumHistos();
  bool combinedFailed = false;
  float threshold = KS_TEST ?  pc->GetKSThreshold() : pc->GetChi2Threshold(); 

    // get the reference and comparison histograms
  int Nevents_ref = ((TH1F *)pc->GetRefHisto("Nevents"))->GetEntries();
  int Nevents_new = ((TH1F *)pc->GetNewHisto("Nevents"))->GetEntries();
  int Nevents = -1;
  if (Nevents_ref>Nevents_new) Nevents = Nevents_ref;
  else Nevents = Nevents_new;

  // create summary histograms
  TH1F h1dResults_passed("h1dResults_passed","",num_histos, 1, num_histos + 1);
  TH1F h1dResults_failed("h1dResults_failed","",num_histos, 1, num_histos + 1);

  // loop over the supplied list of histograms for comparison
  for (int index = 0; index < pc->GetNumHistos(); index++) {

    int number = index + 1;
    hd = pc->GetHistoData(number);
    //int type = hd->GetType();
    //types[index] = type;
    string name = hd->GetName();
    //string value = hd->GetValueX();
    cout << name << endl;

    // get the reference and comparison histograms
    TH1F *href = (TH1F *)pc->GetRefHisto(name);
    TH1F *hnew = (TH1F *)pc->GetNewHisto(name);


    // ignore if histogram is empty
    if (hnew->GetEntries() <= 1 || href->GetEntries() <= 1) {
      cerr << name << " error: no entries"; combinedFailed = true; continue;
    }

    // calculate and set range and number of bins
    double h1RMS =  hnew->GetRMS();
    double h2RMS =  href->GetRMS();
    double RMS = TMath::Max(h1RMS, h2RMS);
    double h1Mean =  hnew->GetMean();
    double h2Mean =  href->GetMean();
    double Mean = 0.5 * (h1Mean + h2Mean);
    double Nbins = href->GetNbinsX();
    double min = href->GetXaxis()->GetXmin();
    double max = href->GetXaxis()->GetXmax();
    double dX = max - min;
    double dNdX = 1;
    double NewMin = min;
    double NewMax = max;

    int rebinning = Nbins; 

    if (RMS>0 && hd->GetType() ) 
      {
	dNdX = 100. / ( 10 * RMS);
	NewMin = Mean - 10 * RMS;
	NewMax = Mean + 10 * RMS;
      }
    
    if ((dX * dNdX)>0  && hd->GetType() ) 
      rebinning = (int)(double(Nbins) / (dX * dNdX));
    
    if ( rebinning > 1 && hd->GetType() ) 
      {
	href->Rebin(rebinning);
	hnew->Rebin(rebinning);
      }

    if ( hd->GetType() == 1 )
      { 
	href->GetXaxis()->SetRangeUser(0.0, NewMax);
	hnew->GetXaxis()->SetRangeUser(0.0, NewMax);
      }
    else if ( hd->GetType() == 2 )
      {
	href->GetXaxis()->SetRangeUser(NewMin, NewMax);
	hnew->GetXaxis()->SetRangeUser(NewMin, NewMax);
      }

    // perform statistical tests
    double ks_score = hnew->KolmogorovTest(href,"D");
    double chi2_score = hnew->Chi2Test(href, "p");
    //double result = KS_TEST ? ks_score : chi2_score;
    double result = (ks_score>chi2_score) ? ks_score : chi2_score;
    
      href->SetNormFactor(Nevents_new);     	
      hnew->SetNormFactor(Nevents_new);
    //hnew->SetNormFactor(1);

    // ensure that the peaks of both histograms will be shown by making a dummy histogram
    float Nentries_ref = href->GetEntries();
    float Nentries_new = hnew->GetEntries();
    float XaxisMin_ref = 0, XaxisMax_ref = 0, YaxisMin_ref = 0, YaxisMax_ref = 0;
    float XaxisMin_new = 0, XaxisMax_new = 0, YaxisMin_new = 0, YaxisMax_new = 0;
    if (Nentries_ref>0) YaxisMax_ref = (href->GetMaximum()+TMath::Sqrt(href->GetMaximum()))*(Nentries_new/Nentries_ref);
    if (Nentries_new>0) YaxisMax_new = (hnew->GetMaximum()+TMath::Sqrt(hnew->GetMaximum()));

    XaxisMin_ref = href->GetXaxis()->GetXmin()>NewMin  ? href->GetXaxis()->GetXmin() : NewMin;
    XaxisMax_ref = href->GetXaxis()->GetXmax()<=NewMax ? href->GetXaxis()->GetXmax() : NewMax;
    YaxisMax_ref = (YaxisMax_ref>=YaxisMax_new) ? YaxisMax_ref : YaxisMax_new;

    if (TMath::Abs(XaxisMin_ref - XaxisMax_ref)<1E-6)
      {
	XaxisMin_ref = 0;
	XaxisMax_ref = 1;
      }
    
    TH1F *hdumb = new TH1F("hdumb","", rebinning, XaxisMin_ref, XaxisMax_ref);
    hdumb->SetMinimum(1E-1); //--For Rick
    hdumb->SetMaximum(1.05*YaxisMax_ref);
    //    if (href->GetMaximum() < hnew->GetMaximum())
    //  href->SetAxisRange(0, 1.1 * hnew->GetMaximum(), "Y");
        
    // set drawing options on the reference histogram
    href->SetStats(0);
    href->SetLineWidth(2);
    href->SetLineColor(14);
    href->SetMarkerColor(14);
    href->SetFillColor(17);
    //href->SetFillStyle(3004);
    href->GetXaxis()->SetTitle(name.c_str());
    href->GetYaxis()->SetTitle("Entries");
    href->GetYaxis()->SetTitleOffset(1.5);

    // set drawing options on the new histogram
    hnew->SetStats(0);
    hnew->SetLineWidth(2);
    hnew->SetFillStyle(3001);
    // set drawing options on the dummy histogram
    hdumb->SetStats(0);
    hdumb->GetXaxis()->SetTitle(name.c_str());
    hdumb->GetXaxis()->SetLabelSize(0.5 * hdumb->GetXaxis()->GetTitleSize());
    hdumb->GetYaxis()->SetTitle("Entries");
    hdumb->GetYaxis()->SetTitleOffset(1.5);
    hdumb->GetYaxis()->SetLabelSize(0.5 * hdumb->GetXaxis()->GetTitleSize());
    
    stringstream ss_title;
    ss_title.precision(5);
    if (ks_score>chi2_score)
      ss_title << "KS Score = " << ks_score;
    else
      ss_title << "Chi^2 Score = " << chi2_score;
    TText canvas_title(0.1,0.97,ss_title.str().c_str());


    // determine if test is a "pass" or a "fail"
    if (result <= threshold) {

      canvas_title.SetTextColor(kRed);

      // make this histogram red to denote failure
      hnew->SetFillColor(kRed);
      hnew->SetLineColor(206);
      hnew->SetMarkerColor(206);

      // mark the entire sample as being 'not-compatible'
      combinedFailed = true;

      // set the summary bin to failed (only need to set titles for passed h1dResults)
      h1dResults_passed.GetXaxis()->SetBinLabel(number, name.c_str());
      h1dResults_failed.SetBinContent(number, result);

    } else {

      canvas_title.SetTextColor(kGreen);

      // make this histogram green to denote passing score
      hnew->SetFillColor(kGreen);
      hnew->SetLineColor(103);  
      hnew->SetMarkerColor(103);

      // set the summary bin to passed
      h1dResults_passed.GetXaxis()->SetBinLabel(number, name.c_str());
      h1dResults_passed.SetBinContent(number, result);

    }

    // setup canvas for displaying the compared histograms
    TCanvas histo_c("histo_c","histo_c",785,800);
    histo_c.Draw();

    TPad histo_p("histo_p","histo_p",0,0,1,0.99);
    histo_p.Draw();

    histo_c.cd();
    canvas_title.SetTextSize(0.025);
    canvas_title.Draw();

    histo_p.cd();

    histo_p.SetLogy(1); //--This is just for Dr. Rick
    hdumb->Draw();
    href->Draw("SAME");
    hnew->Draw("SAME");
    hnew->Draw("E1SAME");

      stringstream legend_new;
      stringstream legend_ref;
      legend_new << argv[4] << ": " << Nentries_new << " entries, " << Nevents_new << " events";
      legend_ref << argv[5] << ": " << Nentries_ref << " entries, " << Nevents_ref << " events";		
	
      TLegend l1(0.15,0.001,0.33, 0.06);
      l1.SetTextSize(0.02);
      l1.AddEntry(hnew, legend_new.str().c_str(),"lF");
      l1.AddEntry(href, legend_ref.str().c_str(),"lF");
      l1.SetFillColor(kNone);      
      l1.Draw("SAME");


    // print the result to gif
    string histo_name = name + ".gif";
    histo_c.Print(histo_name.c_str(),"gif");
    cout << "Result of comparison for " << name << ": ks score = " << ks_score << " : chi2 score = " << chi2_score << endl << endl;

  }

  // create summary canvas
  int summary_height = int(780 * float(num_histos) / 11); // 780;
  TCanvas main_c("main_c","main_c",799,summary_height);
  main_c.Draw();

  TPad main_p("main_p","main_p",0.01,0.01,0.99,0.94);
  main_p.SetLeftMargin(0.30);
  main_p.SetBottomMargin(0.15);
  main_p.SetLogx(1);
  main_p.SetGrid();
  main_p.SetFrameFillColor(10);
  main_p.Draw();

  main_c.cd();
  TText summary_title(.01, .95, "");
  summary_title.Draw("SAME");

  main_p.cd();

  // setup the passing test bars
  h1dResults_passed.SetStats(0);
  h1dResults_passed.GetXaxis()->SetLabelSize(0.06);
  h1dResults_passed.GetYaxis()->SetLabelSize(0.04);
  h1dResults_passed.GetYaxis()->SetTitle("Compatibility");
  h1dResults_passed.SetBarWidth(0.7);
  h1dResults_passed.SetBarOffset(0.1);
  h1dResults_passed.SetFillColor(kGreen);
  h1dResults_passed.SetLineColor(1);
  h1dResults_passed.GetYaxis()->SetRangeUser(1E-7,2);
  h1dResults_passed.Draw("hbar0");

  // setup the failing test bars
  h1dResults_failed.SetStats(0);
  h1dResults_failed.GetXaxis()->SetLabelSize(0.06);
  h1dResults_failed.GetYaxis()->SetLabelSize(0.04);
  h1dResults_failed.GetYaxis()->SetTitle("Compatibility");
  h1dResults_failed.SetBarWidth(0.7);
  h1dResults_failed.SetBarOffset(0.1);
  h1dResults_failed.SetFillColor(kRed);
  h1dResults_failed.SetLineColor(1);
  h1dResults_failed.GetYaxis()->SetRangeUser(1E-7,2);
  h1dResults_failed.Draw("hbar0SAME");

  // draw the pass/fail threshold line
  TLine l(threshold, 1, threshold, num_histos+1);
  l.SetLineColor(kRed);
  l.SetLineWidth(2);
  l.SetLineStyle(2);
  l.Draw("SAME"); 

  // print the results
  main_c.Update();
  main_c.Print("AllResults-1dHistoCheck.gif","gif");

  if (combinedFailed) cout << "Final Result: fail" << endl;
  else cout << "Final Result: pass" << endl;

  //delete pc;
  return 0;

}
Example #2
0
void plotDistribution( TChain* data , TChain *mc , TCut sel , TCut vtxweight , char* var , int nbins , float xmin , float xmax , char* xtitle , char* plottitle = "" , bool printplot = false , bool residual = false , bool log = false ) {

    //--------------------------------------
    // define histograms and TGraphs
    //--------------------------------------

    TH1F* hdata      = new TH1F(Form("hdata_%i"     , iplot),Form("hdata_%i"    , iplot),nbins,xmin,xmax);
    TH1F* hmc        = new TH1F(Form("hmc_%i"       , iplot),Form("hmc_%i"      , iplot),nbins,xmin,xmax);
    TH1F* hmc_novtx  = new TH1F(Form("hmc_novtx_%i" , iplot),Form("hmc_novtx%i" , iplot),nbins,xmin,xmax);

    hdata->Sumw2();
    hmc->Sumw2();

    TGraphAsymmErrors* grdata = new TGraphAsymmErrors();
    TGraphAsymmErrors* grmc   = new TGraphAsymmErrors();

    TH1F* hdata_denom = new TH1F(Form("hdata_denom_%i",iplot),"",nbins,xmin,xmax);
    TH1F* hmc_denom   = new TH1F(Form("hmc_denom_%i"  ,iplot),"",nbins,xmin,xmax);

    //--------------------------------------
    // set up canvas and pads
    //--------------------------------------

    TCanvas *can = new TCanvas(Form("can_%i",iplot),Form("can_%i",iplot),600,600);
    can->cd();
    if( log ) gPad->SetLogy();

    TPad *mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);

    if( residual ) {
        mainpad->Draw();
        mainpad->cd();
        if( log ) mainpad->SetLogy();
    }

    //--------------------------------------
    // fill histos and TGraphs
    //--------------------------------------

    data->Draw(Form("min(%s,%f)>>hdata_%i"     , var,xmax-0.0001,iplot),sel);
    mc  ->Draw(Form("min(%s,%f)>>hmc_%i"       , var,xmax-0.0001,iplot),sel*vtxweight);
    mc  ->Draw(Form("min(%s,%f)>>hmc_novtx_%i" , var,xmax-0.0001,iplot),sel);

    for( int ibin = 1 ; ibin <= nbins ; ibin++ ) {
        hdata_denom->SetBinContent(ibin,hdata->Integral());
        hmc_denom->SetBinContent(ibin,hmc->Integral());
    }

    grdata->BayesDivide(hdata,hdata_denom);
    grmc->BayesDivide(hmc_novtx,hmc_denom);

    //--------------------------------------
    // get efficiencies and errors
    //--------------------------------------

    /*
    float ndata1     = (float) hdata->GetBinContent(1);
    float ndata      = (float) hdata->Integral();
    float effdata    = 1-ndata1 / ndata;

    // TGraphAsymmErrors* grdata_temp = new TGraphAsymmErrors();
    // TH1F* hdata_num_temp = new TH1F(Form("hdata_num_temp_%i",iplot),"",1,0,1);
    // TH1F* hdata_den_temp = new TH1F(Form("hdata_den_temp_%i",iplot),"",1,0,1);
    // hdata_num_temp->SetBinContent(1,ndata-ndata1);
    // hdata_den_temp->SetBinContent(1,ndata);
    // grdata_temp->BayesDivide(hdata_num_temp,hdata_den_temp);

    //float effdataerr = sqrt(ndata1) / ndata;
    float effdataerr = 0.5 * ( grdata->GetErrorYlow(0) + grdata->GetErrorYhigh(0) );
    //float effdataerr = 0.5 * ( grdata_temp->GetErrorYlow(0) + grdata_temp->GetErrorYhigh(0) );

    float nmc1       = (float) hmc->GetBinContent(1);
    float nmc        = (float) hmc->Integral();
    float effmc      = 1-nmc1 / nmc;
    //float effmcerr   = hmc->GetBinError(1) / nmc;
    float effmcerr   = 0.5 * ( grmc->GetErrorYlow(0) + grmc->GetErrorYhigh(0) );


    float datatot = hdata->Integral();
    float mctot   = hmc->Integral();

    cout << endl;
    cout << plottitle << endl;

    cout << "Data eff  " << Form("%.2f +/- %.3f",effdata,effdataerr) << endl;
    cout << "MC   eff  " << Form("%.2f +/- %.3f",effmc  ,effmcerr)   << endl;
    cout << "Data/MC   " << Form("%.2f +/- %.2f",ratio  ,ratioerr)   << endl;
    */

    float ndata    = hdata->Integral();
    float ndata1   = hdata->Integral(2,20);
    float ndata2   = hdata->Integral(3,20);
    float ndata3   = hdata->Integral(4,20);
    float ndata4   = hdata->Integral(5,20);
    float ndata5   = hdata->Integral(6,20);

    float nmc      = hmc->Integral();
    float nmc1     = hmc->Integral(2,20);
    float nmc2     = hmc->Integral(3,20);
    float nmc3     = hmc->Integral(4,20);
    float nmc4     = hmc->Integral(5,20);
    float nmc5     = hmc->Integral(6,20);

    float effdata1 = ndata1/ndata;
    float effdata2 = ndata2/ndata;
    float effdata3 = ndata3/ndata;
    float effdata4 = ndata4/ndata;
    float effdata5 = ndata5/ndata;

    float effmc1   = nmc1/nmc;
    float effmc2   = nmc2/nmc;
    float effmc3   = nmc3/nmc;
    float effmc4   = nmc4/nmc;
    float effmc5   = nmc5/nmc;

    float effdata1err = getBinomialError(ndata1,ndata);
    float effdata2err = getBinomialError(ndata2,ndata);
    float effdata3err = getBinomialError(ndata3,ndata);
    float effdata4err = getBinomialError(ndata4,ndata);
    float effdata5err = getBinomialError(ndata5,ndata);

    float effmc1err   = getBinomialError(nmc1,nmc);
    float effmc2err   = getBinomialError(nmc2,nmc);
    float effmc3err   = getBinomialError(nmc3,nmc);
    float effmc4err   = getBinomialError(nmc4,nmc);
    float effmc5err   = getBinomialError(nmc5,nmc);

    float ratio1      = effdata1/effmc1;
    float ratio2      = effdata2/effmc2;
    float ratio3      = effdata3/effmc3;
    float ratio4      = effdata4/effmc4;
    float ratio5      = effdata5/effmc5;

    float ratio1err   = ratio1 * sqrt(pow(effdata1err/effdata1,2)+pow(effmc1err/effmc1,2));
    float ratio2err   = ratio2 * sqrt(pow(effdata2err/effdata2,2)+pow(effmc2err/effmc2,2));
    float ratio3err   = ratio3 * sqrt(pow(effdata3err/effdata3,2)+pow(effmc3err/effmc3,2));
    float ratio4err   = ratio4 * sqrt(pow(effdata4err/effdata4,2)+pow(effmc4err/effmc4,2));
    float ratio5err   = ratio5 * sqrt(pow(effdata5err/effdata5,2)+pow(effmc5err/effmc5,2));

    cout << endl << endl << plottitle << endl;

    int left = 20;


    // char* delimstart = "|";
    // char* delim      = "|";
    // char* delimend   = "|";
    // char* pm         = "+/-";

    char* delimstart = "";
    char* delim      = "&";
    char* delimend   = "\\\\";
    char* pm         = "$\\pm$";

    cout << delimstart << setw(10) << "" << setw(4)
         << delim << setw(left) << "$>$ 1 GeV" << setw(4)
         << delim << setw(left) << "$>$ 2 GeV" << setw(4)
         << delim << setw(left) << "$>$ 3 GeV" << setw(4)
         << delim << setw(left) << "$>$ 4 GeV" << setw(4)
         << delim << setw(left) << "$>$ 5 GeV" << setw(4)
         << delimend << endl;

    cout << delimstart << setw(10) << "data" << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effdata1,pm,effdata1err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effdata2,pm,effdata2err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effdata3,pm,effdata3err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effdata4,pm,effdata4err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effdata5,pm,effdata5err) << setw(4)
         << delimend << endl;

    cout << delimstart << setw(10) << "mc" << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effmc1,pm,effmc1err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effmc2,pm,effmc2err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effmc3,pm,effmc3err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effmc4,pm,effmc4err) << setw(4)
         << delim << setw(left) << Form("%.3f %s %.4f",effmc5,pm,effmc5err) << setw(4)
         << delimend << endl;

    cout << delimstart << setw(10) << "data/mc" << setw(4)
         << delim << setw(left) << Form("%.2f %s %.2f",ratio1,pm,ratio1err) << setw(4)
         << delim << setw(left) << Form("%.2f %s %.2f",ratio2,pm,ratio2err) << setw(4)
         << delim << setw(left) << Form("%.2f %s %.2f",ratio3,pm,ratio3err) << setw(4)
         << delim << setw(left) << Form("%.2f %s %.2f",ratio4,pm,ratio4err) << setw(4)
         << delim << setw(left) << Form("%.2f %s %.2f",ratio5,pm,ratio5err) << setw(4)
         << delimend << endl;

    //--------------------------------------
    // draw stuff
    //--------------------------------------

    hdata->Scale(1.0/hdata->Integral());
    hmc->Scale(1.0/hmc->Integral());

    if( log ) hmc->GetYaxis()->SetRangeUser(0.0001,5);
    else      hmc->GetYaxis()->SetRangeUser(0.0,1);

    hmc->GetXaxis()->SetTitle(xtitle);
    hmc->SetLineColor(2);
    hmc->SetMarkerColor(2);
    hmc->DrawNormalized("hist");
    hmc->DrawNormalized("sameE1");
    hdata->SetLineColor(4);
    hdata->SetMarkerColor(4);
    hdata->Draw("sameE1");

    grdata->SetLineColor(6);
    grmc->SetLineColor(7);
    //grdata->Draw("sameP");
    //grmc->Draw("sameP");

    TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
    leg->AddEntry(hdata , "data" , "lp");
    leg->AddEntry(hmc   , "MC"   , "lp");
    leg->SetBorderSize(0);
    leg->SetFillColor(0);
    leg->Draw();

    TLatex *t = new TLatex();
    t->SetNDC();

    if( TString(plottitle).Contains("el") ) t->DrawLatex(0.6,0.6,"electrons");
    if( TString(plottitle).Contains("mu") ) t->DrawLatex(0.6,0.6,"muons");

    if( TString(plottitle).Contains("0j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 0");
    if( TString(plottitle).Contains("1j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 1");
    if( TString(plottitle).Contains("2j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 2");
    if( TString(plottitle).Contains("3j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 3");
    if( TString(plottitle).Contains("4j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 4");

    //--------------------------------------
    // draw residual plots
    //--------------------------------------

    if( residual ) {
        can->cd();

        TPad *respad = new TPad("respad","respad",0.0,0.8,1.0,1.0);
        respad->Draw();
        respad->cd();
        respad->SetGridy();

        TH1F* hratio = (TH1F*) hdata->Clone(Form("hratio_%i",iplot));
        hratio->Divide(hmc);

        hratio->SetMarkerColor(1);
        hratio->SetLineColor(1);
        hratio->Draw();
        hratio->GetYaxis()->SetRangeUser(0.5,1.5);
        hratio->GetYaxis()->SetNdivisions(5);
        hratio->GetYaxis()->SetLabelSize(0.2);
        hratio->GetXaxis()->SetLabelSize(0.0);

        TLine line;
        line.DrawLine(xmin,1.0,xmax,1.0);
    }

    //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel+"tkisonew>20");
    //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel);

    if( printplot ) can->Print(Form("plots/%s.pdf",plottitle));

    iplot++;

    // TCanvas *c2 = new TCanvas();
    // c2->cd();
    // grdata->Draw("AP");

}
Example #3
0
void frac_fit(){
  double Ndata []  = {315239.0, 40524.1, 8625.2};
  double NdataE[]  = {   579.8,   202.8,   95.4};
  double NW []     = {258150.0,    0.38,   14.8};
  double NWE[]     = {   502.8,    0.38,    3.1};
  double NZ []     = { 19473.9, 37494.8,  181.4};
  double NZE[]     = {    61.7,    75.4,    5.2};
  double Ntt []    = { 33156.3,  1637.8, 8214.0};
  double NttE[]    = {    32.9,     8.2,   18.3};
  double Nother [] = { 20934.8,   606.9,  470.8};
  double NotherE[] = {   494.4,     5.3,   10.7};

  TH1F *W     = new TH1F("W"    ,"W"    , 3, 0.5, 3.5);
  TH1F *Z     = new TH1F("Z"    ,"Z"    , 3, 0.5, 3.5);
  TH1F *tt    = new TH1F("tt"   ,"tt"   , 3, 0.5, 3.5);
  TH1F *other = new TH1F("other","other", 3, 0.5, 3.5);
  TH1F *data  = new TH1F("data" ,"data" , 3, 0.5, 3.5);
	
  TH1F *weightW  = new TH1F("W_weight" , "W_weight" , 3, 0.5, 3.5);	
  TH1F *weightZ  = new TH1F("Z_weight" , "Z_weight" , 3, 0.5, 3.5);	
  TH1F *weighttt = new TH1F("tt_weight", "tt_weight", 3, 0.5, 3.5);	

  for(int i=0; i<3; i++){
    double Nw_prime     = TMath::Power(NW[i]/NWE[i]        , 2); 
    double NZ_prime     = TMath::Power(NZ[i]/NZE[i]        , 2); 
    double Ntt_prime    = TMath::Power(Ntt[i]/NttE[i]      , 2); 
    //double Nother_prime = TMath::Power(Nother[i]/NotherE[i], 2); 
    W ->SetBinContent(i+1, Nw_prime );
    Z ->SetBinContent(i+1, NZ_prime );
    tt->SetBinContent(i+1, Ntt_prime);

    weightW -> SetBinContent(i+1, NW[i] /W ->GetBinContent(i+1));   
    weightZ -> SetBinContent(i+1, NZ[i] /Z ->GetBinContent(i+1));   
    weighttt-> SetBinContent(i+1, Ntt[i]/tt->GetBinContent(i+1));   
    //    other   -> SetBinContent(i+1, Nother[i] );
    data    -> SetBinContent(i+1, Ndata[i]);
  }

  W ->SetLineColor(kRed  );
  Z ->SetLineColor(kBlue );
  tt->SetLineColor(kGreen);

	for(int i=1; i<=3; i++){
	//	cout << "data: " << data->GetBinContent(i) << " W " << W->GetBinContent(i) << " Z " << Z->GetBinContent(i) << " tt " << tt->GetBinContent(i) << endl; 	
	//	cout << "data weight=1, W weight "  << weightW->GetBinContent(i) << " Z weight: " << weightZ->GetBinContent(i) << " weight tt " << weighttt->GetBinContent(i) << endl; 
	}
	
  TObjArray *mc= new TObjArray(4);
  mc->Add(W);
  mc->Add(Z);
  mc->Add(tt);
  //  mc->Add(other);
  TFractionFitter *fit = new TFractionFitter(data,mc);
  //fit->GetFitter()->FixParameter(3);
	fit->SetWeight(0,weightW);
	fit->SetWeight(1,weightZ);
	fit->SetWeight(2,weighttt);
	//fit->Constrain(0,0,2);
	//fit->Constrain(1,0,2);
	//fit->Constrain(2,0,2);

  fit->Fit();
  double R[3]; 

  for(int i=0; i<3; i++){
    double x=0;
    double xE=0;
    fit->GetResult(i,x,xE);
    double N=0; 
    if (i==0) N = NW[i] ; 
    if (i==1) N = NZ[i] ;
    if (i==2) N = Ntt[i];
	  cout << "x " << x << endl; 
	  cout << " initial fraction: " << Ndata[i]/N << endl; 
    R[i]=x*(Ndata[i]/N);
    cout << "R: " << R[i] << " +/- " << (xE/x)*R[i] << endl; 

  }
}
Example #4
0
void bbtt_upg_em(std::string var,int nbins, double xmin, double xmax,std::string xtitle, std::string ytitle, double sigscale=1)
{

  TFile *outDC = new TFile("hh_em_inputs.root","RECREATE");

  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);
 
  //std::string dir = "/data/blue/Bacon/029a/Upgrade/merged_talk_jun30/";
  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/ntuples/";
  
  std::stringstream scale; scale << sigscale;
  
  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(tauCat1==3 && tauCat2==2 && ptTau1>20 && ptTau2>20 && tauIso2<0.4 && tauIso1<0.4 && (bTag1==2||bTag1==3||bTag1==6||bTag1==7) && (bTag2==1||bTag2==3||bTag2==6||bTag2==7) && ptB1>20 && ptB2>20 && sqrt( (etaTau1-etaTau2)**2 + (phiTau1-phiTau2)**2 )>0.4)";
  std::string jetcut = objcut+"*(mTT>20 && mTT<90)*(mBB1>70 && mBB1<140)*(mt2pileup>100)*(bdtVal>-0.05)";
  //signal region
  std::string mccut = jetcut+"*eventWeight*"+lumi.str();
  std::string sigcut = jetcut+"*eventWeight*"+lumi.str();
  std::string zjetcut = jetcut+"*eventWeight*(eventType==4)*"+lumi.str();
  std::string wjetcut = jetcut+"*eventWeight*(eventType==3)*"+lumi.str();
  std::string ewkcut = jetcut+"*eventWeight*(eventType!=1)*"+lumi.str();
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *hhtree = load(dir+"HHToTTBB_14TeV.root"); 
  TTree *tttree = load(dir+"tt.root"); 
  //TTree *vbfhtree = load(dir+"VBFToTT_14TeV_phase2.root");
  //TTree *gfhtree = load(dir+"H.root");
  //TTree *vjettree = load(dir+"Vjets.root");
  //TTree *ewktree = load(dir+"diboson.root");
  
  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  /*  TH1F *Ztt = new TH1F("DY","",nbins,xmin,xmax);
  vardraw = var+">>"+"DY";
  vjettree->Draw(vardraw.c_str(),zjetcut.c_str());
  InitHist(Ztt  , xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);*/
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  tttree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  /*  TH1F *wjets = new TH1F("Wjets","",nbins,xmin,xmax);
  vardraw = var+">>"+"Wjets";
  vjettree->Draw(vardraw.c_str(),wjetcut.c_str());
  InitHist(wjets, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001);
  TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ewk";
  ewktree->Draw(vardraw.c_str(),ewkcut.c_str());
  InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *vbfh = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  vbfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(vbfh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *ggh = new TH1F("GGH","",nbins,xmin,xmax);
  vardraw = var+">>"+"GGH";
  gfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ggh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);*/
  TH1F *smhh = new TH1F("SMhh","",nbins,xmin,xmax);
  vardraw = var+">>"+"SMhh";
  hhtree->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(smhh);
  smhh->SetLineColor(kBlack);
  delete canv0;
  //---------------------------------------------------------------------------
  //Print out the yields
  Double_t error=999;
  //ofstream outfile;
  //outfile.open("yields.txt");
  //outfile << "Yields for the signal region." << std::endl;
  cout << "SM hh   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "SM h   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "Ztt    "  << Ztt->IntegralAndError(0,Ztt->GetNbinsX(),error) << "+/-" << error << endl;*/
  cout << "ttbar    "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "wjets    "  << wjets->IntegralAndError(0,wjets->GetNbinsX(),error) << "+/-" << error << endl;*/
  //--------------------------------------------------------------------------
  //outfile.close();
  outDC->cd();
  TDirectory* lTD = outDC->mkdir("emu");
  outDC->cd(lTD->GetPath());
  ttbar->SetName("data_obs");
  ttbar->SetTitle("data_obs");
  ttbar->Write();
  /*Ztt->SetName("ZTT");
  Ztt->SetTitle("ZTT");
  Ztt->Write();*/
  ttbar->SetName("TT");
  ttbar->SetTitle("TT");
  ttbar->Write();
  /*wjets->SetName("W");
  wjets->SetTitle("W");
  wjets->Write();
  ewk->SetName("VV");
  ewk->SetTitle("VV");
  ewk->Write();
  vbfh->SetName("qqH");
  vbfh->SetTitle("qqH");
  vbfh->Write();
  ggh->SetName("ggH");
  ggh->SetTitle("ggH");
  ggh->Write();*/
  smhh->SetName("ggHH");
  smhh->SetTitle("ggHH");
  smhh->Write();
  outDC->Close();
  //stack some  histtograms together
  //vbfh->Add(ggh); 
  //wjets->Add(ewk); 
  //-----------------------------------------------------------------------
  smhh->Scale(sigscale);
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //wjets->Add(ttbar);  //Ztt->Add(wjets); 
  //vbfh->Add(Ztt);
  //Error band stat
  //TH1F* errorBand = (TH1F*)vbfh ->Clone("errorBand");
  TH1F* errorBand = (TH1F*)ttbar ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ttbar->SetMaximum(1.1*std::max(maximum(ttbar, 0), maximum(smhh, 0)));
  //blind(data,75,150);
  //data->Draw("e");
  //vbfh->Draw("hist");
  //Ztt->Draw("histsame");
  //wjets->Draw("histsame");
  //ttbar->Draw("histsame");
  ttbar->SetTitle("");
  ttbar->Draw("hist"); 
  //data->Draw("esame");
  errorBand->Draw("e2same");
  smhh->Draw("histsame");
  canv->RedrawAxis();
  //canv->SetLogy(1);
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(smhh  , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale) , "L" );
  //leg->AddEntry(smhh , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale1) , "L" );
  //leg->AddEntry(data , "Observed"                       , "LP");
  //leg->AddEntry(vbfh  , "SM H#rightarrow#tau#tau"   , "F" );
  //leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  //leg->AddEntry(wjets  , "Electroweak"                    , "F" );
  leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
   
  //CMS preliminary 
  const char* dataset = "CMS Simulation, 3000 fb^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_em.png").c_str());
  
  /*
    Ratio Data over MC
  */
  /*
  TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)vbfh->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    model->SetBinError  (ibin+1, 0);
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ttbar->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)vbfh->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  //stat1->Draw();
  canv1->Print((var+"_ratio.png").c_str());
  */
}
Example #5
0
void doCoinc3(const char *fileIn="SAVO-01-SAVO-02-SAVO-03-2016-01-26.root"){
  Int_t adayMin = (yearRange[0]-2007) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2007) * 1000 + monthRange[1]*50 + dayRange[1];

  // define some histos
  TH1F *hDeltaTheta12 = new TH1F("hDeltaTheta12","#Delta#theta_{12} below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi12 = new TH1F("hDeltaPhi12","#Delta#phi_{12} below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack12 = new TH1F("hDeltaThetaBack12","#Delta#theta_{12} out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack12 = new TH1F("hDeltaPhiBack12","#Delta#phi_{12} out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel12 = new TH1F("hThetaRel12","#theta_{rel}_{12} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack12 = new TH1F("hThetaRelBack12","#theta_{rel}_{12} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH1F *hDeltaTheta13 = new TH1F("hDeltaTheta13","#Delta#theta_{13} below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi13 = new TH1F("hDeltaPhi13","#Delta#phi_{13} below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack13 = new TH1F("hDeltaThetaBack13","#Delta#theta_{13} out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack13 = new TH1F("hDeltaPhiBack13","#Delta#phi_{13} out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel13 = new TH1F("hThetaRel13","#theta_{rel}_{13} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack13 = new TH1F("hThetaRelBack13","#theta_{rel}_{13} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);


  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[3];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");
  tel[2] = (TTree *) f->Get("treeTel3");
  
  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  Bool_t runstatus[3][10][12][31][500]; //#telescope, year-2007, month, day, run
  
  if(tel[0] && tel[1] && tel[2]){
    for(Int_t i=0;i < 3;i++){ // loop on telescopes
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2007) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

	if(aday < adayMin || aday > adayMax) continue;
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]) continue; // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]) continue; // cut on the number of event
	if(tel[i]->GetLeaf("ratePerRun")->GetValue() < rateMin[i] || tel[i]->GetLeaf("ratePerRun")->GetValue() > rateMax[i]) continue; // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499) continue; // run < 500

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]) continue;

	
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2007][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	
      }
    }
  }
  else{
    telC = NULL;
  }
  
  Int_t n = t->GetEntries();

  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499 || telC->GetLeaf("run3")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;

      if(!runstatus[2][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
    }
  }
  
  char title[600];
  TH1F *h;
  TH2F *h2;

  sprintf(title,"correction assuming #Delta#phi_{12} = %4.2f, #DeltaL_{12} = %.1f m, #Delta#phi_{13} = %4.2f, #DeltaL_{13} = %.1f m;#Deltat_{13} (ns) when |#Deltat_{12}| < %i ns;entries",angle12,distance12,angle13,distance13,timeCutOn12);
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  sprintf(title,"correction assuming #Delta#phi_{12} = %4.2f, #DeltaL_{12} = %.1f m, #Delta#phi_{13} = %4.2f, #DeltaL_{13} = %.1f m;#Deltat_{12} (ns);#Deltat_{13} (ns);entries",angle12,distance12,angle13,distance13,timeCutOn12);
  h2 = new TH2F("hCoinc2D",title,nbint,tmin,tmax,nbint,tmin,tmax);
  
  Float_t DeltaT12,DeltaT13;
  Float_t phiAv,thetaAv,corr12,corr13;
  
  Float_t Theta1,Theta2,Theta3;
  Float_t Phi1,Phi2,Phi3;
  
  Float_t v1[3],v2[3],v3[3],vSP12,vSP13; // variable to recompute ThetaRel on the fly
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    // if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499) || t->GetLeaf("RunNumber3")->GetValue() > 499)) continue;
  
    // if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    // if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;
  
    // if(tel[2] && !runstatus[2][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
      }
    }

    Float_t thetarel12 = t->GetLeaf("ThetaRel12")->GetValue();
    Float_t thetarel13 = t->GetLeaf("ThetaRel13")->GetValue();
    Theta1 = t->GetLeaf("Theta1")->GetValue()*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Theta3 = t->GetLeaf("Theta3")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    Phi3 = t->GetLeaf("Phi3")->GetValue()*TMath::DegToRad();
    
    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 -= phi1Corr*TMath::DegToRad();
      Phi2 -= phi2Corr*TMath::DegToRad();
      Phi3 -= phi3Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      if(Phi3 > 2*TMath::Pi()) Phi3 -= 2*TMath::Pi();
      if(Phi3 < 0) Phi3 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      v3[0] = TMath::Sin(Theta3)*TMath::Cos(Phi3);
      v3[1] = TMath::Sin(Theta3)*TMath::Sin(Phi3);
      v3[2] = TMath::Cos(Theta3);
      
      v2[0] *= v1[0];
      v2[1] *= v1[1];
      v2[2] *= v1[2];
      v3[0] *= v1[0];
      v3[1] *= v1[1];
      v3[2] *= v1[2];
      
      vSP12 = v2[0] + v2[1] + v2[2];
      vSP13 = v3[0] + v3[1] + v3[2];
      
      thetarel12 = TMath::ACos(vSP12)*TMath::RadToDeg();
      thetarel13 = TMath::ACos(vSP13)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel12 > maxthetarel) continue;
    if(thetarel13 > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare3")->GetValue() > maxchisquare) continue;
    
    DeltaT12 = t->GetLeaf("DiffTime12")->GetValue();
    DeltaT13 = t->GetLeaf("DiffTime13")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();
    if(TMath::Abs(phiAv-Phi3) < TMath::Pi()) phiAv = (phiAv*2+Phi2)*0.33333333333;
    else if(phiAv > Phi3) phiAv = (phiAv*2+Phi3+2*TMath::Pi())*0.33333333333;
    else phiAv = (phiAv*2+4*TMath::Pi()+Phi3)*0.33333333333;


    thetaAv = (Theta1+Theta2+Theta3)*0.333333333333;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    corr12 = distance12 * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle12)/2.99792458000000039e-01 + deltatCorr12;
    corr13 = distance13 * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle13)/2.99792458000000039e-01 + deltatCorr13;
    
    if(TMath::Abs(DeltaT12-corr12) < timeCutOn12) h->Fill(DeltaT13-corr13);
    h2->Fill(DeltaT12-corr12,DeltaT13-corr13);

    if(TMath::Abs(DeltaT12-corr12) < 500){
      hDeltaTheta12->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi12->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel12->Fill(thetarel12);
    }
    else if(TMath::Abs(DeltaT12-corr12) > 1000 && TMath::Abs(DeltaT12-corr12) < 6000){
      hDeltaThetaBack12->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack12->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack12->Fill(thetarel12);
    }

    if(TMath::Abs(DeltaT13-corr13) < 500){
      hDeltaTheta13->Fill((Theta1-Theta3)*TMath::RadToDeg());
      hDeltaPhi13->Fill((Phi1-Phi3)*TMath::RadToDeg());
      hThetaRel13->Fill(thetarel13);
    }
    else if(TMath::Abs(DeltaT13-corr13) > 1000 && TMath::Abs(DeltaT13-corr13) < 6000){
      hDeltaThetaBack13->Fill((Theta1-Theta3)*TMath::RadToDeg());
      hDeltaPhiBack13->Fill((Phi1-Phi3)*TMath::RadToDeg());
      hThetaRelBack13->Fill(thetarel13);
    }
  }
  
  h->SetStats(0);

  hDeltaThetaBack12->Sumw2();
  hDeltaPhiBack12->Sumw2();
  hThetaRelBack12->Sumw2();
  hDeltaThetaBack12->Scale(0.1);
  hDeltaPhiBack12->Scale(0.1);
  hThetaRelBack12->Scale(0.1);
  hDeltaThetaBack13->Sumw2();
  hDeltaPhiBack13->Sumw2();
  hThetaRelBack13->Sumw2();
  hDeltaThetaBack13->Scale(0.1);
  hDeltaPhiBack13->Scale(0.1);
  hThetaRelBack13->Scale(0.1);

  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,1000);
  ff->SetParameter(2,150); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,20000./nbint); // bin width
  
  ff->SetNpx(1000);
  
  h->Fit(ff);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("output-SAVO-010203.root","RECREATE");
  h->Write();
  h2->Write();
  hDeltaTheta12->Write();
  hDeltaPhi12->Write();
  hThetaRel12->Write();
  hDeltaThetaBack12->Write();
  hDeltaPhiBack12->Write();
  hThetaRelBack12->Write();
  hDeltaTheta13->Write();
  hDeltaPhi13->Write();
  hThetaRel13->Write();
  hDeltaThetaBack13->Write();
  hDeltaPhiBack13->Write();
  hThetaRelBack13->Write();
  fo->Close();
  
}
Example #6
0
//____________________________________
void rs_bernsteinCorrection(){

  // set range of observable
  Double_t lowRange = -1, highRange =5;

  // make a RooRealVar for the observable
  RooRealVar x("x", "x", lowRange, highRange);

  // true model
  RooGaussian narrow("narrow","",x,RooConst(0.), RooConst(.8));
  RooGaussian wide("wide","",x,RooConst(0.), RooConst(2.));
  RooAddPdf reality("reality","",RooArgList(narrow, wide), RooConst(0.8));

  RooDataSet* data = reality.generate(x,1000);

  // nominal model
  RooRealVar sigma("sigma","",1.,0,10);
  RooGaussian nominal("nominal","",x,RooConst(0.), sigma);

  RooWorkspace* wks = new RooWorkspace("myWorksspace");

  wks->import(*data, Rename("data"));
  wks->import(nominal);

  // The tolerance sets the probability to add an unecessary term.
  // lower tolerance will add fewer terms, while higher tolerance
  // will add more terms and provide a more flexible function.
  Double_t tolerance = 0.05; 
  BernsteinCorrection bernsteinCorrection(tolerance);
  Int_t degree = bernsteinCorrection.ImportCorrectedPdf(wks,"nominal","x","data");

  cout << " Correction based on Bernstein Poly of degree " << degree << endl;

  RooPlot* frame = x.frame();
  data->plotOn(frame);
  // plot the best fit nominal model in blue
  nominal.fitTo(*data,PrintLevel(-1));
  nominal.plotOn(frame);

  // plot the best fit corrected model in red
  RooAbsPdf* corrected = wks->pdf("corrected");  
  corrected->fitTo(*data,PrintLevel(-1));
  corrected->plotOn(frame,LineColor(kRed));

  // plot the correction term (* norm constant) in dashed green
  // should make norm constant just be 1, not depend on binning of data
  RooAbsPdf* poly = wks->pdf("poly");  
  poly->plotOn(frame,LineColor(kGreen), LineStyle(kDashed));
  
  // this is a switch to check the sampling distribution
  // of -2 log LR for two comparisons:
  // the first is for n-1 vs. n degree polynomial corrections
  // the second is for n vs. n+1 degree polynomial corrections
  // Here we choose n to be the one chosen by the tolerance
  // critereon above, eg. n = "degree" in the code.
  // Setting this to true is takes about 10 min.
  bool checkSamplingDist = false;

  TCanvas* c1 = new TCanvas();
  if(checkSamplingDist) {
    c1->Divide(1,2);
    c1->cd(1);
  }
  frame->Draw();

  if(checkSamplingDist) {
    // check sampling dist
    TH1F* samplingDist = new TH1F("samplingDist","",20,0,10);
    TH1F* samplingDistExtra = new TH1F("samplingDistExtra","",20,0,10);
    int numToyMC = 1000;
    bernsteinCorrection.CreateQSamplingDist(wks,"nominal","x","data",samplingDist, samplingDistExtra, degree,numToyMC);
    
    c1->cd(2);
    samplingDistExtra->SetLineColor(kRed);
    samplingDistExtra->Draw();
    samplingDist->Draw("same");
  }
}
void 
//HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_mt_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("muTau_0jet_low"             )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("muTau_0jet_medium"          )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("muTau_0jet_high"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("muTau_1jet_medium"          )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("muTau_1jet_high_lowhiggs"   )){ category = "#mu#tau_{h}";                          }
  if(std::string(directory) == std::string("muTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("muTau_1jet_high_mediumhiggs")){ category = "#mu#tau_{h}";                          }
  if(std::string(directory) == std::string("muTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("muTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("muTau_vbf"                  )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("muTau_vbf_loose"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("muTau_vbf_tight"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("muTau_nobtag"               )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag"               )){ category_extra = "no b-tag";                        }
  if(std::string(directory) == std::string("muTau_btag"                 )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_btag"                 )){ category_extra = "b-tag";                           }
  if(std::string(directory) == std::string("muTau_nobtag_low"           )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("muTau_nobtag_low"           )){ category_extra2 = "low"; }
  if(std::string(directory) == std::string("muTau_nobtag_medium"        )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("muTau_nobtag_medium"        )){ category_extra2 = "medium"; }
  if(std::string(directory) == std::string("muTau_nobtag_high"          )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("muTau_nobtag_high"          )){ category_extra2 = "high"; }
  if(std::string(directory) == std::string("muTau_btag_low"             )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("muTau_btag_low"             )){ category_extra2 = "low"; }
  if(std::string(directory) == std::string("muTau_btag_high"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("muTau_btag_high"            )){ category_extra2 = "high"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
 
  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK3 , "", "", TColor::GetColor(222,90,106), 1001);
#else
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
#endif
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK  , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
  TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125"  , directory)), "ggH_SM125"); InitHist(ggH_SM125, "", "", kGreen+2, 1001);
  TH1F* qqH_SM125= refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125"  , directory)), "qqH_SM125"); InitHist(qqH_SM125, "", "", kGreen+2, 1001);
  TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125"   , directory)), "VH_SM125" ); InitHist(VH_SM125, "", "", kGreen+2, 1001);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK3 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK3 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif


  if(scaled){

/*  Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
  EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
  EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
  EWK3 = refill(shape_histos(EWK3, datacard, "ZL"), "ZL");
#else
  //  EWK2 = refill(shape_histos(EWK2, datacard, "ZLL"), "ZLL");
#endif
  EWK = refill(shape_histos(EWK, datacard, "VV"), "VV");
  ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
  Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
#ifdef EXTRA_SAMPLES
    rescale(EWK3 , 5);
#endif 
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK3 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

#ifdef MSSM
  qqH_SM125->Add(ggH_SM125);
  VH_SM125->Add(qqH_SM125);
  Fakes->Add(VH_SM125);
#endif
  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  EWK3 ->Add(EWK2 );
  EWK  ->Add(EWK3 );
#else
  EWK  ->Add(EWK2 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
#ifdef MSSM
    VH_SM125->Draw("histsame");
#endif   
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
#ifdef MSSM
    VH_SM125->Draw("histsame");
#endif   
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{#mu}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{mod+} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "Electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
#ifdef MSSM
  leg->AddEntry(VH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
 
  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
  ggH_SM125->Write("ggH_SM125");
  qqH_SM125->Write("qqH_SM125");
  VH_SM125 ->Write("VH_SM125");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Example #8
0
void t1pfmetPhiwithCorr(double pt1min, double pt2min, double METmin, double DPHImin){
gStyle->SetPadTickY(1);
gStyle->SetPadTickX(1);

int  i = 0;
  TLegend* leg = new TLegend(0.35,0.65,0.87,0.87);
  leg->SetNColumns(2);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);

  TCanvas *canvas = new TCanvas("c1n","",500,600);
  TPad *mainPad = new TPad("mainPad","",0,0.3,1,1);
  TPad *smallPad = new TPad("smallPad","",0,0.05,1,0.3);
  mainPad->SetBottomMargin(0.015);


  smallPad->SetTopMargin(0.05);
  smallPad->SetBottomMargin(0.25);

  canvas->cd();

  mainPad->Draw();
  mainPad->cd();







 
  //  gPad->SetLogy();
  TCut mggmax = "mgg<180";
  TCut mggmin = "mgg>100";
  TCut pt1Cut = Form("pt1/mgg>%lf",pt1min);
  TCut pt2Cut = Form("pt2/mgg>%lf",pt2min);
  //  TCut METCut = Form("t1pfmetCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0)>%lf",METmin);
  TCut METCut = "";
 TCut DPHICut =  Form("Delta(pt1,eta1,phi1,pt2,eta2,phi2,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>%lf",DPHImin);
  TCut eveto1 = "eleveto1 == 1";
  TCut eveto2 = "eleveto2 == 1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  TCut NegWeight = "weight>0.";

  /* 
     TFile *M1 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M1.root","READ");  
     TFile *M10 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M10.root","READ");
     TFile *M100 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M100.root","READ");  
     TFile *M1000 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M1000.root","READ");
  */

  TFile *data = TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");
  
  TFile *sig1 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP600.root","READ");
  TFile *sig2 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP800.root","READ");
  TFile *sig3 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1000.root","READ");
  TFile *sig4 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1200.root","READ");
  TFile *sig5 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1400.root","READ");  
  TFile *sig6 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1700.root","READ");
  TFile *sig7 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP2500.root","READ");
  /*
    TFile *bkg1 =  TFile::Open("./50ns_betaV3/DiPhoton.root","READ");  
    TFile *bkg2 =  TFile::Open("./50ns_betaV3/DYJetsToLL.root","READ");  
    TFile *bkg3 =  TFile::Open("./50ns_betaV3/GJets.root","READ");  
    TFile *bkg4 =  TFile::Open("./50ns_betaV3/GluGluHToGG.root","READ");  
    TFile *bkg5 =  TFile::Open("./50ns_betaV3/QCD.root","READ");  
    TFile *bkg6 =  TFile::Open("./50ns_betaV3/VH.root","READ");  
  */

  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ");  
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");  
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");  
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");  
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");  
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");
  /*
    TTree *tree_M1 = (TTree*) M1->Get("DiPhotonTree");
    TTree *tree_M10 = (TTree*) M10->Get("DiPhotonTree");
    TTree *tree_M100 = (TTree*) M100->Get("DiPhotonTree");
    TTree *tree_M1000 = (TTree*) M1000->Get("DiPhotonTree");
  */

  TTree *tree_data = (TTree*) data->Get("DiPhotonTree");
  
  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree");
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree");
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree");
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree");
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree");
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");
 
  
  
  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");
  
  
  /* 
     tree_M1->Draw("(t1pfmet)>>h1(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
     tree_M10->Draw("(t1pfmet)>>h2(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
     tree_M100->Draw("(t1pfmet)>>h3(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
     tree_M1000->Draw("(t1pfmet)>>h4(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");  
  */
  
  tree_data->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,1))>>hdata(10,-4,4)","(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && eveto && METCut  && metF&& DPHICut ));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");

  tree_sig1->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h1(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h2(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h3(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h4(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h5(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h6(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h7(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");

  





  tree_bkg1->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg1(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg2(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg3(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && genmatch && DPHICut));
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
     
tree_bkg4->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg4(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut)); 
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg5(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && genmatch && DPHICut));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg6(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");  
  tree_bkg7->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg7(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");  
  tree_bkg8->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg8(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");  
  tree_bkg9->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg9(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut)); 
  TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");  
  tree_bkg10->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg10(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");  
 tree_bkg11->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg11(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");  
 tree_bkg12->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg12(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");  



 

  hdata->SetMarkerColor(kBlack);
  hdata->SetLineColor(kBlack);
  hdata->SetMarkerStyle(20);
  
  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4);
 h6->SetLineColor(kPink+7);
 h7->SetLineColor(kMagenta+2);
 h1->SetLineWidth(2);
 h2->SetLineWidth(2);
 h3->SetLineWidth(2);
 h4->SetLineWidth(2);
 h5->SetLineWidth(2);
 h6->SetLineWidth(2);
 h7->SetLineWidth(2);


  
  
  THStack *hs=new THStack("hs","");
  hbkg7->SetFillColor(kGreen+2);
  hbkg6->SetFillColor(kGreen);
  hbkg8->SetFillColor(kYellow);
  hbkg4->SetFillColor(kOrange);
  hbkg9->SetFillColor(kOrange+7);
  hbkg10->SetFillColor(kOrange+4);
  hbkg11->SetFillColor(kCyan);
  hbkg12->SetFillColor(kCyan+1);
  hbkg5->SetFillColor(kBlue+2);
  hbkg2->SetFillColor(kBlue);  
  hbkg3->SetFillColor(kMagenta-2);
  hbkg1->SetFillColor(kViolet);

  hbkg1->SetLineColor(kBlack);
  hbkg2->SetLineColor(kBlack);
  hbkg3->SetLineColor(kBlack);
  hbkg4->SetLineColor(kBlack);
  hbkg5->SetLineColor(kBlack);
  hbkg6->SetLineColor(kBlack);
  hbkg7->SetLineColor(kBlack);
  hbkg8->SetLineColor(kBlack);
  hbkg9->SetLineColor(kBlack);
  hbkg10->SetLineColor(kBlack);
  hbkg11->SetLineColor(kBlack);
  hbkg12->SetLineColor(kBlack);

  hs->Add(hbkg7);
  hs->Add(hbkg6);
  hs->Add(hbkg8);
  hs->Add(hbkg4);
  hs->Add(hbkg9);
  hs->Add(hbkg10);
  hs->Add(hbkg11);
  hs->Add(hbkg12);
  hs->Add(hbkg2);
  hs->Add(hbkg5);
  hs->Add(hbkg3);
  hs->Add(hbkg1);
  
  TH1F *hsum = (TH1F*)hbkg1->Clone("hsum"); 
  hsum->Add(hbkg2);
  hsum->Add(hbkg3);
  hsum->Add(hbkg4);
  hsum->Add(hbkg5);
  hsum->Add(hbkg6);
  hsum->Add(hbkg7);
  hsum->Add(hbkg8);
  hsum->Add(hbkg9);
  hsum->Add(hbkg10);
  hsum->Add(hbkg11);
  hsum->Add(hbkg12);
  


  canvas->SetLeftMargin(0.12);

  // hs->SetMinimum(0.01);
  hs->SetMaximum(5700);

  hs->SetTitle("");
  hs->Draw("HIST"); 
  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3002);
  hsum->Draw("same e2");
  //  h2->Draw("same hist");
  // h3->Draw("same hist"); 
  // h4->Draw("same hist");
  // h1->Draw("same hist");
  //h5->Draw("same hist"); //only for 25ns samples
  //h7->Draw("same hist"); //only for 25ns samples
  // h6->Draw("same hist"); //only for 25ns samples
  hdata->Draw("same E1");
  

  hs->GetXaxis()->SetLabelOffset(999);
  hs->GetYaxis()->SetTitleOffset(1.5);
  hs->GetYaxis()->SetTitle("Events/0.8");  
  //int  iPos = 11;
//  CMS_lumi(canvas,true,iPos,false);
  gPad->Modified();


  leg->AddEntry(hdata,"Data","elp");
  /*leg->AddEntry(h1,"m_{#chi} = 1 GeV","l");
  leg->AddEntry(h2,"m_{#chi} = 10 GeV","l");
  leg->AddEntry(h3,"m_{#chi} = 100 GeV","l");      
  leg->AddEntry(h4,"m_{#chi} = 1000 GeV","l");*/
  //  leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");
  leg->AddEntry(hbkg1,"#gamma #gamma","f");
  // leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");
  leg->AddEntry(hbkg2,"Drell Yann","f");
  // leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");
  leg->AddEntry(hbkg3,"#gamma + Jets","f");
  // leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");
  leg->AddEntry(hbkg5,"QCD","f");
  // leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg4,"ggH","f");
  //leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg6,"VH","f");
  // leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg7,"ttH","f");
  leg->AddEntry(hbkg8,"VBF H","f");
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");
  leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");
  leg->AddEntry(hbkg11,"#gamma+W","f");
  leg->AddEntry(hbkg12,"#gamma+Z","f");
 leg->AddEntry(hsum,"Bkg uncertainty","f");
  leg->Draw("same");




  
  gStyle->SetOptStat(0);  
 

  canvas->cd();
  smallPad->Draw();
  smallPad->cd();

  TGraphErrors *gr = new TGraphErrors(0);
  double integralData=hdata->Integral();
  double integralBKG=hsum->Integral();
  double error, ratio;
  for(int w=1; w<20; w++){
    if((hdata->GetBinContent(w)!=0) && (hsum->GetBinContent(w)!=0)){

      gr->SetPoint(w, hdata->GetBinCenter(w),(hdata->GetBinContent(w))/(hsum->GetBinContent(w)));
      ratio= (hdata->GetBinContent(w))/(hsum->GetBinContent(w));
      error= (hdata->GetBinContent(w)*sqrt(hsum->GetBinContent(w))/(hsum->GetBinContent(w)*hsum->GetBinContent(w)) + sqrt(hdata->GetBinContent(w))/hsum->GetBinContent(w));
      std::cout<<"VALUE: "<<ratio<<" ERROR: "<<error<<std::endl;
      gr->SetPointError(w, hdata->GetBinWidth(w)/2,error);
    }else{
      gr->SetPoint(w, hdata->GetBinCenter(w),10);
    }
  }



  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  gr->GetHistogram()->SetMaximum(2);
  gr->GetHistogram()->SetMinimum(0.1);

  gStyle->SetTextSize(14);
  gROOT->ForceStyle();

  gr->GetXaxis()->SetLabelFont(43);
  gr->GetXaxis()->SetLabelSize(15);
  gr->GetYaxis()->SetLabelFont(43);
  gr->GetYaxis()->SetLabelSize(15);

  gr->GetXaxis()->SetLimits(-4,4);


  gPad->SetGrid();
  gStyle->SetStripDecimals(kTRUE);
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(0.7);


  gr->Draw("AZP");
  gr->GetXaxis()->SetTitle("#phi_{MET}^{corr}");
  gr->GetXaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetNdivisions(505);

  gr->GetXaxis()->SetTitleOffset(1);
  gr->GetYaxis()->SetTitle("Data/MC");
  gr->GetYaxis()->SetTitleOffset(0.4);
  gr->SetTitle("");
  smallPad->Update();
  TF1* line = new TF1("line","1",-4,4);
  line->SetLineColor(kRed);
  line->SetLineWidth(2);
  line->Draw("L same");
  gr->Draw("ZP SAME");


  canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/metphicorr_MET%.0lf.pdf",METmin)); 
  canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/metphicorr_MET%.0lf.png",METmin)); 
    
}
void plotDavid(TH1F* bkgT, TH1F* sigT, TH1F* dataT, std::string name){
  
  gROOT->SetBatch();
  system("mkdir -p plots/ada/david");
  system("mkdir -p plots/grad/david");
  system("mkdir -p plots/ada/diff");
  system("mkdir -p plots/grad/diff");

  std::string bdt;
  TString str = dataT->GetName();
  if (str.Contains("ada")) bdt="ada";
  else if (str.Contains("grad")) bdt="grad";
  else std::cout << "Error find BDT type" << std::endl;
  assert (str.Contains("ada") || str.Contains("grad"));

  if (bkgT->GetNbinsX() != sigT->GetNbinsX() || sigT->GetNbinsX() != dataT->GetNbinsX()) std::cout << "Plot problem: calling plot for histograms with different number of bins" << std::endl;
  assert(bkgT->GetNbinsX() == sigT->GetNbinsX() || sigT->GetNbinsX() == dataT->GetNbinsX());
  
  TH1F *bkg = linearBin(bkgT);
  TH1F *sig2 = linearBin(sigT);
  TH1F *sig5 = (TH1F*)sig2->Clone();
  TH1F *sig10 = (TH1F*)sig2->Clone();
  TH1F *data = linearBin(dataT);
  TH1F *diff = (TH1F*)data->Clone();
  diff->Add(bkg,-1);

  gStyle->SetOptStat(0);
  gROOT->SetStyle("Plain");
  gROOT->ForceStyle();

  TCanvas *canv = new TCanvas();
  bkg->SetLineColor(kBlue);
  bkg->SetFillColor(kBlue-9);
  sig2->SetLineColor(kRed);
  sig2->SetLineStyle(3);
  sig2->Scale(1.);
  sig5->SetLineColor(kRed);
  sig5->SetLineStyle(7);
  sig5->Scale(3.);
  sig10->SetLineColor(kRed);
  sig10->Scale(5.);
  data->SetMarkerStyle(20);
  bkg->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  sig2->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  data->SetTitle(("Background, data and signal distributions for "+bdt+" "+name).c_str());
  bkg->GetXaxis()->SetTitle("");
  sig2->GetXaxis()->SetTitle("");
  data->GetXaxis()->SetTitle("");
  bkg->GetYaxis()->SetTitle("Events");
  sig2->GetYaxis()->SetTitle("Events");
  data->GetYaxis()->SetTitle("Events");

  TLegend *leg = new TLegend(0.45,0.6,0.85,0.85);
  leg->SetLineColor(0);
  leg->SetFillColor(0);
  leg->AddEntry(bkg,"Background","f");
  leg->AddEntry(data,"Data","lep");
  leg->AddEntry(sig10,"Signal (1, 3, 5 #times SM)","l");
  TPaveText *txt = new TPaveText(0.2,0.1,0.4,0.35,"NDC");
  txt->SetFillColor(0);
  txt->SetLineColor(0);
  txt->AddText("#int L = 4.76 fb^{-1}");

  bkg->GetYaxis()->SetRangeUser(1.0,2.*(data->GetMaximum()));

  bkg->Draw("e2");
  sig2->Draw("same hist");
  sig5->Draw("same hist");
  sig10->Draw("same hist");
  data->Draw("same e");
  leg->Draw("same");
  txt->Draw("same");

  canv->SetLogy();
  canv->Print(("plots/"+bdt+"/david/"+name+".png").c_str(),"png");
  canv->SetLogy(false);
  canv->Clear();
  TLegend *leg2 = new TLegend(0.45,0.6,0.85,0.85);
  leg2->SetFillColor(0);
  leg2->SetLineColor(0);
  sig10->GetYaxis()->SetRangeUser((-1*sig10->GetMaximum())+10,sig10->GetMaximum()+20);
  sig10->GetXaxis()->SetTitle("");
  sig10->GetYaxis()->SetTitle("Events");
  sig10->SetTitle(Form("Data, background difference compared to signal %s %s",bdt.c_str(),name.c_str()));
  diff->SetMarkerStyle(20);
  diff->GetXaxis()->SetTitle("");
  diff->GetYaxis()->SetTitle("Events");
  leg2->AddEntry(diff,"Data - background model","lep");
  leg2->AddEntry(sig10,"Signal (1, 3, 5 #times SM)","l");
  TF1 *line = new TF1("line","0.0",0.0,sig10->GetNbinsX()+1);
  line->SetLineColor(kBlue);
  sig10->Draw("hist");
  sig5->Draw("same hist");
  sig2->Draw("same hist");
  line->Draw("same");
  diff->Draw("p same");
  leg2->Draw("same");
  txt->Draw("same");
  canv->Print(("plots/"+bdt+"/diff/"+name+".png").c_str(),"png");

  delete canv;
  delete txt;
  delete leg;
  
  davidCalls++;
}
Example #10
0
void drawFigure4a(TString var="Njets") 
{
  gInterpreter->ExecuteMacro("GoodStyle.C");
  gROOT->LoadMacro("tdrstyle.C");                                                                                                                           
  setTDRStyle();    

  TString variable = "p_{T,max}^{#font[12]{l}}";
  std::ostringstream filename, madname;
  filename<<"rootfiles/all_unfolding_"<<var<<".root";
  TFile* file = new TFile(filename.str().c_str(), "read");
  madname<<"hGenXs"<<var<<"_1";
  std::cout<<madname.str().c_str()<<std::endl;
  TH1F* xsValue          = (TH1F*)(file->Get("hComb_diff")->Clone("xsValue"));
  TH1F* xsValue_Madgraph = (TH1F*)(file->Get(madname.str().c_str())->Clone("xsValue_Madgraph"));
  TH1F* xsValue_MCnlo    = (TH1F*)(file->Get("mcfm_tot")->Clone("xsValue_MCnlo"));

  // Set the data errors- I don't need this because I already have complete error in my plot
  //----------------------------------------------------------------------------
  
  // Data cosmetics
  //----------------------------------------------------------------------------
  xsValue->SetLineWidth(1);
  xsValue->SetMarkerSize(_msize);
  xsValue->SetMarkerStyle(kFullCircle);
  xsValue->SetMarkerColor(kBlack);
  xsValue->SetLineColor(kBlack);
  xsValue->SetFillStyle(1001);
  xsValue->SetFillColor(kWhite);
  // Madgraph cosmetics
  //----------------------------------------------------------------------------
  xsValue_Madgraph->SetFillColor(kOrange);
  //xsValue_Madgraph->SetFillColor(kWhite);
  xsValue_Madgraph->SetFillStyle(1001);
  xsValue_Madgraph->SetLineColor(kOrange+7);
  xsValue_Madgraph->SetLineWidth(1);
  xsValue_Madgraph->SetMarkerColor(kOrange+7);
  xsValue_Madgraph->SetMarkerSize(_msize);
  xsValue_Madgraph->SetMarkerStyle(21);


  // MCNLO cosmetics
  //----------------------------------------------------------------------------
  xsValue_MCnlo->SetFillColor(kAzure-9);
   //xsValue_MCnlo->SetFillColor(kWhite);
  xsValue_MCnlo->SetFillStyle(1001);
  xsValue_MCnlo->SetLineColor(kAzure);
  xsValue_MCnlo->SetLineWidth(1);
  xsValue_MCnlo->SetMarkerColor(kAzure);
  xsValue_MCnlo->SetMarkerSize(_msize);
  //  xsValue_MCnlo->SetMarkerStyle(21);
  xsValue_MCnlo->SetMarkerStyle(24);

  //  TCanvas * c1=new TCanvas("c1", "c1");
  
//xsValue_MCnlo->Draw("pey0");
   

  // Set the canvas and pads
  //----------------------------------------------------------------------------
  TCanvas* canvas = new TCanvas("wwxs", "wwxs", 600, 600);
  //  TCanvas* canvas = new TCanvas("wwxs", "wwxs"); 

  //defalut
  //TCanvas* canvas = new TCanvas("wwxs", "wwxs", 600, 850);
  //  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.55, 1, 1.000);
  //TPad* pad2 = new TPad("pad2", "pad2", 0, 0.39, 1, 0.552);
  //TPad* pad3 = new TPad("pad3", "pad3", 0, 0.23, 1, 0.392);

  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.49, 1, 1.000);
  TPad* pad2 = new TPad("pad2", "pad2", 0, 0.33, 1, 0.492);
  TPad* pad3 = new TPad("pad3", "pad3", 0, 0, 1, 0.332);
  
  pad1->SetTopMargin(0.09);
  pad2->SetTopMargin(0);
  pad3->SetTopMargin(0);

  pad1->SetBottomMargin(0);
  pad2->SetBottomMargin(0);
  //  pad3->SetBottomMargin(0.15);
  pad3->SetBottomMargin(0.45);

  pad1->SetLeftMargin(0.16);
  pad2->SetLeftMargin(0.16);
  pad3->SetLeftMargin(0.16);

  pad1->SetRightMargin(0.06);
  pad2->SetRightMargin(0.06);
  pad3->SetRightMargin(0.06);



  // pad1
  //----------------------------------------------------------------------------
  pad1->Draw();
  pad1->cd();
  pad1->SetLogy();


  // Draw
  //----------------------------------------------------------------------------
  AxisFonts(xsValue->GetXaxis(), variable + " (GeV)");
  if (var=="Zpt")
    AxisFonts(xsValue->GetYaxis(), "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{Z}");
  if (var=="LeadingJetPt")
    AxisFonts(xsValue->GetYaxis(), "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{LeadingJet}");
  
  //TH1F* hpowError = (TH1F*)xsValue_Powheg->Clone();
  //  TH1F* hmadError = (TH1F*)xsValue_Madgraph->Clone();
  //TH1F* hmcError  = (TH1F*)xsValue_MCnlo->Clone();

  xsValue         ->Draw("pe");
  xsValue_Madgraph->Draw("p,same");
  xsValue_MCnlo   ->Draw("p,same");

  xsValue->SetMinimum(1.1e-4);

 
  // Legend
  //----------------------------------------------------------------------------
  DrawLegend(0.718, 0.80, xsValue,   " Data",     "lp");
  DrawLegend(0.718, 0.74, xsValue_Madgraph, " Madgraph", "flp");  
  DrawLegend(0.718, 0.68, xsValue_MCnlo,  " MCFM",   "flp");


  // Draw text 
  //----------------------------------------------------------------------------
  DrawLatex(_cmsTextFont,   0.173, 0.935, 0.065, 11, "CMS");
  DrawLatex(_extraTextFont, 0.268, 0.935, 0.035, 11, "Preliminary");
  DrawLatex(_lumiTextFont,  0.940, 0.935, 0.050, 31, "19.6 fb^{-1} (8 TeV)");


  // Prepare the ratios
  //----------------------------------------------------------------------------
  TH1F* ratio_mad    = xsValue_Madgraph->Clone("ratio");
  TH1F* ratio_mcnlo  = xsValue_Madgraph->Clone("ratio");
  //  TH1F* ratio_mcnlo  = xsValue_MCnlo->Clone("ratio");
  TH1F* hratio_mad   = xsValue_Madgraph->Clone("ratio");
  TH1F* hratio_mcnlo = xsValue_MCnlo->Clone("ratio");
  TH1F* ratioErr     = xsValue->Clone("ratio");


  ratioErr->SetFillColor  (kGray+2);
  ratioErr->SetFillStyle  (   3004);
  ratioErr->SetLineColor  (kGray+2);
  ratioErr->SetMarkerColor(kGray+2);
  ratioErr->SetMarkerSize (      0);


  // Set the bin content
  //----------------------------------------------------------------------------
  for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {
   
    Double_t madValue = xsValue_Madgraph->GetBinContent(ibin);
    //Double_t madError = xsValue_Madgraph->GetBinError  (ibin);
   
    Double_t mcnloValue = xsValue_MCnlo->GetBinContent(ibin);
    //Double_t mcnloError = xsValue_MCnlo->GetBinError  (ibin);
   
    Double_t dataValue = xsValue->GetBinContent(ibin);
    
    Double_t dataError = xsValue->GetBinError(ibin);
   
    Double_t ratioValue_mad = (madValue > 0) ? madValue / dataValue : 0.0;
    //Double_t ratioError_mad = (madValue > 0) ? madError / dataValue : 0.0;
    Double_t ratioError_mad = madValue/pow(dataValue,2)*dataError;
    Double_t ratioValue_mcnlo = (mcnloValue > 0) ? mcnloValue / dataValue : 0.0;
    // Double_t ratioError_mcnlo = (mcnloValue > 0) ? mcnloError / dataValue : 0.0;
    Double_t ratioError_mcnlo = mcnloValue/pow(dataValue,2)*dataError;
   
    Double_t uncertaintyError = (dataValue > 0) ? dataError / dataValue : 0.0;
   
    ratio_mad ->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinError  (ibin, ratioError_mad);
   
    ratio_mcnlo ->SetBinContent(ibin, ratioValue_mcnlo);
    hratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
    hratio_mcnlo->SetBinError  (ibin, ratioError_mcnlo);
   
    ratioErr->SetBinContent(ibin, 1.0);
    ratioErr->SetBinError  (ibin, uncertaintyError);  //??? ovo nije bas jasno sto je
  }


  //  AxisFontsRatio(ratioErr->GetYaxis(), "y", "Theory / Data");
  //AxisFontsRatio(ratioErr->GetXaxis(), "x", variable + " (GeV)");
  AxisFontsRatio(ratio_mad->GetYaxis(), "y", "Theory / Data");
  //AxisFontsRatio(ratio_mad->GetXaxis(), "x", variable + " (GeV)");

  AxisFontsRatio(ratio_mcnlo->GetYaxis(), "y", "Theory / Data");

  if (var=="Zpt")
    AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", "p_{T}^{Z} (GeV)");
  if (var=="LeadingJetPt")
    AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", "p_{T}^{LeadingJet} (GeV)");
  ratio_mcnlo->SetFillColor(kAzure-9);
   //xsValue_MCnlo->SetFillColor(kWhite);
  ratio_mcnlo->SetFillStyle(1001);
  ratio_mcnlo->SetLineColor(kAzure);
  ratio_mcnlo->SetLineWidth(1);
  ratio_mcnlo->SetMarkerColor(kAzure);
  ratio_mcnlo->SetMarkerSize(_msize);
  //  xsValue_MCnlo->SetMarkerStyle(21);
  ratio_mcnlo->SetMarkerStyle(24);

  // Draw pad2
  //----------------------------------------------------------------------------
  canvas->cd();
  pad2->Draw();
  pad2->cd();
  
  //ratioErr  ->Draw("e2");
  
  ratio_mad ->Draw("pz");
  hratio_mad->Draw("e2,same");
  ratio_mad ->Draw("p, same");
  ratio_mad->GetYaxis()->SetRangeUser(0.1, 2.3);  

  pad2->Modified();
  
  DrawLatex(43, 0.2, 0.79, 15.0, 11, "Madgraph+Pythia normalized to #sigma_{NLO}");
  

  // Draw pad3
  //----------------------------------------------------------------------------
  canvas->cd();
  pad3->Draw();
  pad3->cd();
  std::cout<<"Default option: "<<ratio_mcnlo->GetOption()<<std::endl;
  
  //ratioErr    ->Draw("e2");
  ratio_mcnlo->Draw("pz");
  hratio_mcnlo->Draw("e2,same");

  ratio_mcnlo ->Draw("pz, same");
  ratio_mcnlo->GetYaxis()->SetRangeUser(0.1, 2.3);  
  //ratio_mcnlo->GetYaxis()->SetRangeUser(0.0, 0.5);  
  
  pad3->Modified();

  DrawLatex(43, 0.2, 0.89, 15.0, 11, "MCFM");
  
    

  // Save
  //----------------------------------------------------------------------------
  pad1->cd(); pad1->GetFrame()->DrawClone();
  pad2->cd(); pad2->GetFrame()->DrawClone();
  pad3->cd(); pad3->GetFrame()->DrawClone();

  canvas->cd();

  std::ostringstream saveName, saveName2;
  saveName  << "pdf/unfolded_"<<var<<".pdf";
  saveName2 << "png/unfolded_"<<var<<".png";
  canvas->SaveAs(saveName.str().c_str());
  canvas->SaveAs(saveName2.str().c_str());
}
Example #11
0
void v_src_fit(){

/*  int CRunNumberR=20602;
  int endCRunNumberR=20603;
  int HeRunNumberR=999999;
  int endHeRunNumberR=999999;
*/
  int CRunNumberR=20591;
  int endCRunNumberR=22462;
  int CRunNumberL=1699;
  int endCRunNumberL=1829;
  int HeRunNumberR=20579;
  int endHeRunNumberR=20790;
  int HeRunNumberL=1686;
  int endHeRunNumberL=1883;
// NOTE: There is a problem with the BCM values. When fixed, swap below and above lines.
//  int endHeRunNumberR=20879;
//  int endHeRunNumberL=1958;

  TString Q2 = "1.0";
  double bins = 50;
  double plotmin = 0.5;
  double plotmax = 2.0;
  TString title = "12C/3He x with Target cut, Run # ";
  title += CRunNumberR;
  title += " & ";
  title += HeRunNumberR;

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

	TCut cutsR = kinematicsR && targetR && sieveR && goldR && eventtypeR;


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

	TCut cutsL = kinematicsL && targetL && sieveL && goldL && eventtypeL;



  // Makes right and left chains that will contain all the data
  TChain* chainCR = new TChain("T");
  TChain* chainHeR = new TChain("T");
  TChain* chainCL = new TChain("T");
  TChain* chainHeL = new TChain("T");

  gStyle->SetErrorX(.25);
  gStyle->SetEndErrorSize(.25);
  ifstream inp;
  ofstream out;

  TString filenameCR;
  TString filenameHeR;
  TString filenameCL;
  TString filenameHeL;



// Below is the loop for adding chains for the Right Carbon runs
  for (int thisCRunNumberR=CRunNumberR; thisCRunNumberR<(endCRunNumberR+1); thisCRunNumberR++)
  {
 		if(thisCRunNumberR==20592){thisCRunNumberR=20731;}
		if(thisCRunNumberR==20735){thisCRunNumberR=22380;}
		if(thisCRunNumberR==22381){thisCRunNumberR=22389;}
		if(thisCRunNumberR==22390){thisCRunNumberR=22425;}
		if(thisCRunNumberR==22427){thisCRunNumberR=22461;}
		if(thisCRunNumberR==22462){thisCRunNumberR=99999;}

   for (int t=0; t<1000;t++)
    {
      filenameCR = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
      filenameCR += thisCRunNumberR;
      if (t!=0)
      {
        filenameCR += "_";
        filenameCR += t;
      }
      filenameCR += ".root";
      ifstream ifileCR(filenameCR);
      if (ifileCR)
      {
        cout << "Adding file to chainCR: " << filenameCR << endl;
        chainCR->Add(filenameCR);
      }
      else
      {
        cout << "File " << filenameCR << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }
	
// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisCRunNumberR = 99999999;

  }

// Below is the loop for adding chains for the Left Carbon runs
  for (int thisCRunNumberL=CRunNumberL; thisCRunNumberL<(endCRunNumberL+1); thisCRunNumberL++)
  {
 		if(thisCRunNumberL==1700){thisCRunNumberL=1825;}
		if(thisCRunNumberL==1829){thisCRunNumberL=9999;}

   for (int t=0; t<1000;t++)
    {
      filenameCL = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_L_";
      filenameCL += thisCRunNumberL;
      if (t!=0)
      {
        filenameCL += "_";
        filenameCL += t;
      }
      filenameCL += ".root";
      ifstream ifileCL(filenameCL);
      if (ifileCL)
      {
        cout << "Adding file to chainCL: " << filenameCL << endl;
        chainCL->Add(filenameCL);
      }
      else
      {
        cout << "File " << filenameCL << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }
	
// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisCRunNumberL = 99999999;

  }





// Below is the loop for adding chains for the Right 3He runs

  for (int thisHeRunNumberR=HeRunNumberR;thisHeRunNumberR<(endHeRunNumberR+1); thisHeRunNumberR++)
  {
	// Skipping Vertical Carbon Runs
	if(thisHeRunNumberR==20591){thisHeRunNumberR=20596;}
	if(thisHeRunNumberR==20731){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20732){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20733){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20734){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20736){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20737){thisHeRunNumberR=20738;}
	if(thisHeRunNumberR==20791){thisHeRunNumberR=20814;}
	if(thisHeRunNumberR==20792){thisHeRunNumberR=20814;}

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

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

    for (int t=0; t<1000;t++)
    {
      filenameHeR = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_R_";
      filenameHeR += thisHeRunNumberR;
      if (t!=0)
      {
        filenameHeR += "_";
        filenameHeR += t;
      }
      filenameHeR += ".root";
      ifstream ifileHeR(filenameHeR);
      if (ifileHeR)
      {
        cout << "Adding file to chainHeR: " << filenameHeR << endl;
        chainHeR->Add(filenameHeR);
      }
      else
      {
        cout << "File " << filenameHeR << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }

// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisHeRunNumberR = 999999999;

  }

// Below is the loop for adding chains for the Left 3He runs

  for (int thisHeRunNumberL=HeRunNumberL;thisHeRunNumberL<(endHeRunNumberL+1); thisHeRunNumberL++)
  {
	// Skipping Vertical Carbon Runs
	if(thisHeRunNumberL==1699){thisHeRunNumberL=1704;}
	if(thisHeRunNumberL==1825){thisHeRunNumberL=1832;}
	if(thisHeRunNumberL==1826){thisHeRunNumberL=1832;}
	if(thisHeRunNumberL==1827){thisHeRunNumberL=1832;}
	if(thisHeRunNumberL==1828){thisHeRunNumberL=1832;}
	if(thisHeRunNumberL==1830){thisHeRunNumberL=1832;}
	if(thisHeRunNumberL==1831){thisHeRunNumberL=1832;}
	if(thisHeRunNumberL==1884){thisHeRunNumberL=1906;}
	if(thisHeRunNumberL==1885){thisHeRunNumberL=1906;}

    for (int t=0; t<1000;t++)
    {
      filenameHeL = "/home/ellie/physics/e05-102/terabyte/ROOTfiles/e05102_L_";
      filenameHeL += thisHeRunNumberL;
      if (t!=0)
      {
        filenameHeL += "_";
        filenameHeL += t;
      }
      filenameHeL += ".root";
      ifstream ifileHeL(filenameHeL);
      if (ifileHeL)
      {
        cout << "Adding file to chainHeL: " << filenameHeL << endl;
        chainHeL->Add(filenameHeL);
      }
      else
      {
        cout << "File " << filenameHeL << " does not exist. Ending here." << endl;
        t=9999999;
      }

    }

// Uncommenting the line below will let the code only go through one run (Good for debugging purposes)
//	thisHeRunNumberL = 999999999;

  }


	
	gStyle->SetPalette(1);
	gStyle->SetOptFit(0001);

	// Defines Canvas
	TCanvas *c1 = new TCanvas("c1","x of 12C and 3He",1360,800);//x,y
	pad01 = new TPad("pad01","pad01",0.0000,0.8333,0.2000,1.0000,0,0,0);
	pad02 = new TPad("pad02","pad02",0.2000,0.8333,0.4000,1.0000,0,0,0);
	pad03 = new TPad("pad03","pad03",0.4000,0.8333,0.6000,1.0000,0,0,0);
	pad04 = new TPad("pad04","pad04",0.6000,0.8333,0.8000,1.0000,0,0,0);
	pad05 = new TPad("pad05","pad05",0.0000,0.6666,0.2000,0.8333,0,0,0);
	pad06 = new TPad("pad06","pad06",0.2000,0.6666,0.4000,0.8333,0,0,0);
	pad07 = new TPad("pad07","pad07",0.4000,0.6666,0.6000,0.8333,0,0,0);
	pad08 = new TPad("pad08","pad08",0.6000,0.6666,0.8000,0.8333,0,0,0);
	pad09 = new TPad("pad09","pad09",0.0000,0.3333,0.3333,0.6666,0,0,0);
	pad10 = new TPad("pad10","pad10",0.3333,0.3333,0.6666,0.6666,0,0,0);
	pad11 = new TPad("pad11","pad11",0.6666,0.3333,1.0000,0.6666,0,0,0);
	pad12 = new TPad("pad12","pad12",0.0000,0.0000,0.3333,0.3333,0,0,0);
	pad13 = new TPad("pad13","pad13",0.3333,0.0000,0.6666,0.3333,0,0,0);
	pad14 = new TPad("pad14","pad14",0.6666,0.0000,1.0000,0.3333,0,0,0);
	pad15 = new TPad("pad15","pad15",0.8000,0.8333,1.0000,1.0000,0,0,0);
	pad16 = new TPad("pad16","pad16",0.8000,0.6666,1.0000,0.8333,0,0,0);
	pad01->Draw();pad02->Draw();pad03->Draw();pad04->Draw();pad05->Draw();pad06->Draw();pad07->Draw();pad08->Draw();pad09->Draw();pad10->Draw();pad11->Draw();pad12->Draw();pad13->Draw();pad14->Draw();pad15->Draw();pad16->Draw();

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

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

	pad05->cd();
	TString titledpC = "dp Cut from 12C Runs";
	cout << "Drawing " << titledpC << "..." << endl;
	TH1F *CdpNoCut = new TH1F("CdpNoCut",titledpC,400,-0.8,0.8);
	TH1F *CdpCut = new TH1F("CdpCut",titledpC,400,-0.8,0.8);
	chainCR->Draw("ExTgtCor_R.dp>>CdpNoCutR(400,-0.08,0.08)", "", "");
	chainCR->Draw("ExTgtCor_R.dp>>CdpCutR(400,-0.08,0.08)", goldR, "");
	chainCL->Draw("ExTgtCor_L.dp>>CdpNoCutL(400,-0.08,0.08)", "", "");
	chainCL->Draw("ExTgtCor_L.dp>>CdpCutL(400,-0.08,0.08)", goldL, "");
	CdpNoCut->Add(CdpNoCutR,CdpNoCutL);
	CdpNoCut->SetTitle(titledpC);
	CdpNoCut->Draw();
	CdpCut->Add(CdpCutR,CdpCutL);
	CdpCut->SetLineColor(kBlack);
	CdpCut->SetFillColor(kViolet);
	CdpCut->Draw("same");

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

	pad06->cd();
	TString titleTargetC = "Target Cut for 12C Runs";
	cout << "Drawing " << titleTargetC << "..." << endl;
	TH1F *CReactZNoCut = new TH1F("CReactZNoCut",titleTargetC,400,-0.3,0.3);
	TH1F *CReactZCut = new TH1F("CReactZCut",titleTargetC,400,-0.3,0.3);
	chainCR->Draw("ReactPt_R.z>>CReactZNoCutR(400,-0.3,0.3)", "", "");
	chainCR->Draw("ReactPt_R.z>>CReactZCutR(400,-0.3,0.3)", targetR, "");
	chainCL->Draw("ReactPt_L.z>>CReactZNoCutL(400,-0.3,0.3)", "", "");
	chainCL->Draw("ReactPt_L.z>>CReactZCutL(400,-0.3,0.3)", targetL, "");
	CReactZNoCut->Add(CReactZNoCutR,CReactZNoCutL);
	CReactZNoCut->SetTitle(titleTargetC);
	CReactZNoCut->Draw();
	CReactZCut->Add(CReactZCutR,CReactZCutL);
	CReactZCut->SetLineColor(kBlack);
	CReactZCut->SetFillColor(kViolet);
	CReactZCut->Draw("same");

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

	pad07->cd();
	TString titleThetaPhiC = "Theta and Phi, No Cut, for 12C";
	cout << "Drawing " << titleThetaPhiC << "..." << endl;
	TH2F *CThetaPhiNoCut = new TH2F("CThetaPhiNoCut",titleThetaPhiC,100,-0.05,0.05,100,-0.1,0.1);
	chainCR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>CThetaPhiNoCutR(100,-0.05,0.05,100,-0.1,0.1)", targetR, "");
	chainCL->Draw("ExTgtCor_L.th:ExTgtCor_L.ph>>CThetaPhiNoCutL(100,-0.05,0.05,100,-0.1,0.1)", targetL, "");
	CThetaPhiNoCut->Add(CThetaPhiNoCutR,CThetaPhiNoCutL);
	CThetaPhiNoCut->SetTitle(titleThetaPhiC);
	CThetaPhiNoCut->SetStats(kFALSE);
	CThetaPhiNoCut->Draw("COLZ");

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

	pad08->cd();
	TString titleThetaCutC = "Theta and Phi Cut for 12C";
	cout << "Drawing " << titleThetaCutC << "..." << endl;
	TH2F *CThetaPhiCut = new TH2F("CThetaPhiCut",titleThetaCutC,100,-0.05,0.05,100,-0.1,0.1);
	chainCR->Draw("ExTgtCor_R.th:ExTgtCor_R.ph>>CThetaPhiCutR(100,-0.05,0.05,100,-0.1,0.1)", targetR && sieveR, "");
	chainCL->Draw("ExTgtCor_L.th:ExTgtCor_L.ph>>CThetaPhiCutL(100,-0.05,0.05,100,-0.1,0.1)", targetL && sieveL, "");
	CThetaPhiCut->Add(CThetaPhiCutR,CThetaPhiCutL);
	CThetaPhiCut->SetTitle(titleThetaCutC);
	CThetaPhiCut->SetStats(kFALSE);
	CThetaPhiCut->Draw("COLZ");

	pad15->cd();
	TString titleQ2WHe = "Q2 v. Omega for 3He";
	cout << "Drawing " << titleQ2WHe << "..." << endl;
	TH2F *Q2WHe = new TH2F("Q2WHe",titleQ2WHe,100,0.3,0.8,400,0,1.6);
	chainHeR->Draw("PriKineR.Q2:PriKineR.nu>>Q2WHeR(100,0.3,0.8,400,0,1.6)", cutsR, "");
	chainHeL->Draw("PriKineL.Q2:PriKineL.nu>>Q2WHeL(100,0.3,0.8,400,0,1.6)", cutsL, "");
	Q2WHe->Add(Q2WHeR,Q2WHeL);
	Q2WHe->SetTitle(titleQ2WHe);
	Q2WHe->SetStats(kFALSE);
	Q2WHe->Draw("COLZ");

	pad16->cd();
	TString titleQ2WC = "Q2 v. Omega for 12C";
	cout << "Drawing " << titleQ2WC << "..." << endl;
	TH2F *Q2WC = new TH2F("Q2WC",titleQ2WC,100,0.3,0.8,400,0,1.6);
	chainCR->Draw("PriKineR.Q2:PriKineR.nu>>Q2WCR(100,0.3,0.8,400,0,1.6,100)", cutsR, "");
	chainCL->Draw("PriKineL.Q2:PriKineL.nu>>Q2WCL(100,0.3,0.8,400,0,1.6,100)", cutsL, "");
	Q2WC->Add(Q2WCR,Q2WCL);
	Q2WC->SetTitle(titleQ2WC);
	Q2WC->SetStats(kFALSE);
	Q2WC->Draw("COLZ");


	pad09->cd();
	TString titleC = "x for 12C at Q2 of ";
	titleC += Q2;
//	titleC += " and Target Cut of ";
//	titleC += target;
	cout << "Drawing " << titleC << "..." << endl;
	TH1F *histC = new TH1F("histC",titleC,bins,plotmin,plotmax);
	TH1F *histCR = new TH1F("histCR",titleC,bins,plotmin,plotmax);
	TH1F *histCL = new TH1F("histCL",titleC,bins,plotmin,plotmax);
	histC->Sumw2();
	histCR->Sumw2();
	histCL->Sumw2();
	chainCR->Draw("PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315)>>histCR", cutsR, "E");
	chainCL->Draw("PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315)>>histCL", cutsL, "E");
	histCR->Scale(1/0.0161297);
	histCL->Scale(1/0.0063175);
	histC->Add(histCR,histCL);
	histC->Draw();
	TF1 *fitC1 = new TF1("fitC1","[0]*exp(-x*[1])",1.45,1.6);
	fitC1->SetParNames("C Red p1","C Red p2");
	Double_t fitC1const = fitC1->GetParameter(0);
	Double_t fitC1expconst = fitC1->GetParameter(1);
//	Double_t fitC1exp = fitC1->GetParameter(2);
	Double_t fitC1consterror = fitC1->GetParError(0);
	Double_t fitC1expconsterror = fitC1->GetParError(1);
//	Double_t fitC1experror = fitC1->GetParError(2);
	fitC1->SetLineColor(kRed);
	TF1 *fit2 = new TF1("fitC2","[0]*exp(-x*[1])",1.6,1.8);
	fitC2->SetParNames("C Blue p1","C Blue p2");
	Double_t fitC2const = fitC2->GetParameter(0);
	Double_t fitC2expconst = fitC2->GetParameter(1);
//	Double_t fitC2exp = fitC2->GetParameter(2);
	Double_t fitC2consterror = fitC2->GetParError(0);
	Double_t fitC2expconsterror = fitC2->GetParError(1);
//	Double_t fitC2experror = fitC2->GetParError(2);
	fitC2->SetLineColor(kBlue);
//	TF1 *fitC3 = new TF1("fitC3","[0]*exp(-x*[1])",1.35,1.45);
//	fitC3->SetParNames("C Green p1","C Green p2");
//	Double_t fitC3const = fitC3->GetParameter(0);
//	Double_t fitC3expconst = fitC3->GetParameter(1);
//	Double_t fitC3exp = fitC3->GetParameter(2);
//	Double_t fitC3consterror = fitC3->GetParError(0);
//	Double_t fitC3expconsterror = fitC3->GetParError(1);
//	Double_t fitC3experror = fitC3->GetParError(2);
//	fitC3->SetLineColor(kGreen);
//
//	histC.Fit("fitC2","R");
//	histC.Fit("fitC3","R+");
//	histC.Fit("fitC1","R+");
	

	pad12->cd();
	pad12->SetLogy();
	cout << "Drawing " << titleC << " in log scale..." << endl;
	TH1F *histC = new TH1F("histC",titleC,bins,plotmin,plotmax);
	TH1F *histCR = new TH1F("histCR",titleC,bins,plotmin,plotmax);
	TH1F *histCL = new TH1F("histCL",titleC,bins,plotmin,plotmax);
	histC->Sumw2();
	histCR->Sumw2();
	histCL->Sumw2();
	chainCR->Draw("PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315)>>histCR", cutsR, "E");
	chainCL->Draw("PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315)>>histCL", cutsL, "E");
	histC->Add(histCR,histCL);
	histC->Draw();
//	histC.Fit("fitC1","R");
//	histC.Fit("fitC3","R+");
//	histC.Fit("fitC2","R+");

	pad10->cd();
	TString titleHe = "x for 3He at Q2 of ";
	titleHe += Q2;
//	titleHe += " and Target Cut of ";
//	titleHe += target;
	cout << "Drawing " << titleHe << "..." << endl;
	TH1F *histHe = new TH1F("histHe",titleHe,bins,plotmin,plotmax);
	TH1F *histHeR = new TH1F("histHeR",titleHe,bins,plotmin,plotmax);
	TH1F *histHeL = new TH1F("histHeL",titleHe,bins,plotmin,plotmax);
	histHe->Sumw2();
	histHeR->Sumw2();
	histHeL->Sumw2();
	chainHeR->Draw("PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315)>>histHeR", cutsR, "E");
	chainHeL->Draw("PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315)>>histHeL", cutsL, "E");
	histHeR->Scale(1/2.409416);
	histHeL->Scale(1/2.407866);
	histHe->Add(histHeR,histHeL);
	histHe->Draw();
	TF1 *fitHe1 = new TF1("fitHe1","[0]*exp(-x*[1])",1.45,1.6);
	fitHe1->SetParNames("He Red p1", "He Red p2");
	Double_t fitHe1const = fitHe1->GetParameter(0);
	Double_t fitHe1expconst = fitHe1->GetParameter(1);
//	Double_t fitHe1exp = fitHe1->GetParameter(2);
	Double_t fitHe1consterror = fitHe1->GetParError(0);
	Double_t fitHe1expconsterror = fitHe1->GetParError(1);
//	Double_t fitHe1experror = fitHe1->GetParError(2);
	fitHe1->SetLineColor(kRed);
	TF1 *fitHe2 = new TF1("fitHe2","[0]*exp(-x*[1])",1.6,1.8);
	fitHe2->SetParNames("He Blue p1","He Blue p2");
	Double_t fitHe2const = fitHe2->GetParameter(0);
	Double_t fitHe2expconst = fitHe2->GetParameter(1);
//	Double_t fitHe2exp = fitHe2->GetParameter(2);
	Double_t fitHe2consterror = fitHe2->GetParError(0);
	Double_t fitHe2expconsterror = fitHe2->GetParError(1);
//	Double_t fitHe2experror = fitHe2->GetParError(2);
	fitHe2->SetLineColor(kBlue);
//	TF1 *fitHe3 = new TF1("fitHe3","[0]*exp(-x*[1])",1.35,1.45);
//	fitHe3->SetParNames("He Green p1","He Green p2");
//	Double_t fitHe3const = fitHe3->GetParameter(0);
//	Double_t fitHe3expconst = fitHe3->GetParameter(1);
//	Double_t fitHe3exp = fitHe3->GetParameter(2);
//	Double_t fitHe3consterror = fitHe3->GetParError(0);
//	Double_t fitHe3expconsterror = fitHe3->GetParError(1);
//	Double_t fitHe3experror = fitHe3->GetParError(2);
//	fitHe3->SetLineColor(kGreen);



//	histHe.Fit("fitHe2","R");
//	histHe.Fit("fitHe3","R+");
//	histHe.Fit("fitHe1","R+");

	pad13->cd();
	pad13->SetLogy();
	cout << "Drawing " << titleHe << " in log scale..." << endl;
	TH1F *histHe = new TH1F("histHe",titleHe,bins,plotmin,plotmax);
	TH1F *histHeR = new TH1F("histHeR",titleHe,bins,plotmin,plotmax);
	TH1F *histHeL = new TH1F("histHeL",titleHe,bins,plotmin,plotmax);
	histHe->Sumw2();
	histHeR->Sumw2();
	histHeL->Sumw2();
	chainHeR->Draw("PriKineR.Q2 / (PriKineR.nu * 2 * 0.9315)>>histHeR", cutsR, "E");
	chainHeL->Draw("PriKineL.Q2 / (PriKineL.nu * 2 * 0.9315)>>histHeL", cutsR, "E");
	histHe->Add(histHeR,histHeL);
	histHe->Draw();
//	histHe.Fit("fitHe1","R");
//	histHe.Fit("fitHe3","R+");
//	histHe.Fit("fitHe2","R+");

	pad11->cd();
	TString titleCoverHe = "12C/3He for Q2 of ";
	titleCoverHe += Q2;
//	titleCoverHe += " and Target Cut of ";
//	titleCoverHe += target;
	cout << "Drawing " << titleCoverHe << "..." << endl;
	TH1F *histCoverHe = new TH1F("histCoverHe",titleCoverHe,bins,plotmin,plotmax);
	histCoverHe->Sumw2();
	histCoverHe->Divide(histC,histHe,1,0.0918143);
	histCoverHe->Draw("E");

	pad14->cd();
	pad14->SetLogy();
	cout << "Drawing " << titleCoverHe << " in log scale..." << endl;
	TH1F *histCoverHe = new TH1F("histCoverHe",titleCoverHe,bins,plotmin,plotmax);
	histCoverHe->Sumw2();
	histCoverHe->Divide(histC,histHe,1,0.0918143);
	histCoverHe->Draw("E");

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

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


}
Example #12
0
void meson_pi0_normalization(){
  gROOT->Reset();
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  c1 = new TCanvas("c1","A Simple Graph with error bars",200,10,700,500);

  c1->SetFillColor(10);
  c1->SetGrid();
  c1->SetLogy();
  c1->SetTicks();

  float pt, mtpion, mtother;
  float weight = 1.0;
  int   nbins  = 5000;
  float ptmin  = 0.0;
  float ptmax  = 5.0;
  float binwidth = (ptmax-ptmin)/(double)nbins;
  TH1F * ptpion = new TH1F("ptpion","ptpion",nbins,ptmin,ptmax);
  TH1F * ptother = new TH1F("ptother","ptother",nbins,ptmin,ptmax);
  TH1F * ptothermt = new TH1F("ptothermt","ptothermt",nbins,ptmin,ptmax);
  TH1F * ratio = new TH1F("ratio","ratio",nbins,ptmin,ptmax);
  TH1F * ratiomt = new TH1F("ratiomt","ratiomt",nbins,ptmin,ptmax);

  TMath math1;

  double pi     = acos(-1.0);
  double pimass = 0.1349766;
  double omass  = 0.54730;
  double expected = 0.45;
  // double omass  = 0.7711;
  // double expected = 1.0;
  // double omass  = 0.78257;
  // double expected = 1.0;
  // double omass  = 0.95778;
  // double expected = 0.25;
  // double omass  = 1.019456;
  // double expected = 0.4;

  double t_fo = 0.122;
  double beta = 0.70;
  double norm = 1.0;
 
  double intpion    = 0.0;
  double intother   = 0.0;
  double intothermt = 0.0;

  for (int ibin=1; ibin<=nbins; ibin++ )
  {
    pt = ptmin+(double)(ibin-1)*binwidth+binwidth/2.0;
    mtpion  = sqrt(pt*pt+pimass*pimass);
    mtother = sqrt(pt*pt+omass*omass);

    // minimum bias:
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 3.53e+07/pow(2.28+pt,13.7);
    // double pipower    = 33.9/pow(pt,8.16);
    // double otherhagedorn = 3.53e+07 / 
    //   pow(2.28+sqrt(mtother*mtother-pimass*pimass),13.7);
    // double otherpower = 33.9/pow(sqrt(mtother*mtother-pimass*pimass),8.16);
    // 0 - 10 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 1.41e+13/pow(3.48+pt,18.7);
    // double pipower    = 137.3/pow(pt,8.44);
    // double otherhagedorn = 1.41e+13 / 
    //   pow(3.48+sqrt(mtother*mtother-pimass*pimass),18.7);
    // double otherpower = 137.3/pow(sqrt(mtother*mtother-pimass*pimass),8.44);
    // 10 - 20 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 2.176e+09/pow(2.651+pt,15.170);
    // double pipower    = 92.46/pow(pt,8.326);
    // double otherhagedorn = 2.176e+09 / 
    //   pow(2.651+sqrt(mtother*mtother-pimass*pimass),15.170);
    // double otherpower = 92.46/pow(sqrt(mtother*mtother-pimass*pimass),8.326);    // 20 - 40 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 2.99e+06/pow(2.00+pt,12.45);
    // double pipower    = 51.28/pow(pt,8.21);
    // double otherhagedorn = 2.99e+06 / 
    //   pow(2.00+sqrt(mtother*mtother-pimass*pimass),12.45);
    // double otherpower = 51.28/pow(sqrt(mtother*mtother-pimass*pimass),8.21);
    // 40 - 60 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 3.00e+04/pow(1.56+pt,10.76);
    // double pipower    = 15.75/pow(pt,7.97);
    // double otherhagedorn = 3.00e+04 / 
    //   pow(1.56+sqrt(mtother*mtother-pimass*pimass),10.76);
    // double otherpower = 15.75/pow(sqrt(mtother*mtother-pimass*pimass),7.97);
    // 60 - 92 % central
    // double trans      = 1./(1.+exp(5.*pt-17.5));
    // double pihagedorn = 8.73e+02/pow(1.29+pt,9.94);
    // double pipower    = 5.28/pow(pt,8.28);
    // double otherhagedorn = 8.73e+02 / 
    //   pow(1.29+sqrt(mtother*mtother-pimass*pimass),9.94);
    // double otherpower = 5.28/pow(sqrt(mtother*mtother-pimass*pimass),8.28);
    // if ( pt<1.5 ) weight = 2.0 * pi * pt * pihagedorn;
    // if ( pt>=1.5 && pt<=5.5 ) 
    //   weight = 2.0 * pi * pt * (trans*pihagedorn + (1.-trans)*pipower);
    // if ( pt>5.5 ) weight = 2.0*pi*pt*pipower;

    // pp (Xinhua's Run-2 parameterization)
    // weight = 2.0*pi*pt * (485.0/42.) / pow(exp(-0.5187*pt) + pt/0.6631,8.163);
    // pp (Run-2 hard parameterization)
    weight = 2.0*pi*pt * (450.8/42.) / pow(exp(-0.5553*pt) + pt/0.6467,8.046);
    // pp (Run-3 parameterization)
    // weight = 2.0*pi*pt * (413.5/42.2) / pow(exp(-0.2614*pt) + pt/0.8144,8.807);
    // pp (average Run-2/3 parameterization)
    // weight = 2.0*pi*pt * (546.2/42.2) / pow(exp(-0.2664*pt) + pt/0.7703,8.718);
    //    weight = weight*(1+0.6362/exp(7.736*pt));

    ptpion->AddBinContent(ibin,weight);
    intpion = intpion + weight*binwidth;

    // if ( pt<1.5 ) weight = 2.0 * pi * pt * otherhagedorn;
    // if ( pt>=1.5 && pt<=5.5 ) 
    //   weight = 2.0 * pi * pt * (trans*otherhagedorn + (1.-trans)*otherpower);
    // if ( pt>5.5 ) weight = 2.0*pi*pt*otherpower;

    weight = 2.0*pi*pt * (450.8/42.2) / 
      pow(exp(-0.5553*sqrt(mtother*mtother-pimass*pimass)) + 
	  sqrt(mtother*mtother-pimass*pimass)/0.6467,8.046);

    ptothermt->AddBinContent(ibin,weight);
    intothermt = intothermt + weight*binwidth;

    weight = norm*InitializePtHydro(omass,t_fo,beta,pt);
    ptother->AddBinContent(ibin,weight);
    intother = intother + weight*binwidth;
  }

  cout << "Integral pion    (dN/dy): " << intpion << endl;
  cout << "Integral other   (dN/dy): " << intother << endl;
  cout << "Integral othermt (dN/dy): " << intothermt << endl;

  norm = intpion/intothermt;
  ptothermt->Scale(norm);
 
  for (int ibin=1; ibin<=nbins; ibin++ )
  {
    weight = ptothermt->GetBinContent(ibin)/ptpion->GetBinContent(ibin);
    ratiomt->AddBinContent(ibin,weight);
  }

  norm = expected/ratiomt->GetMaximum();
  ratiomt->Scale(norm);
  ptothermt->Scale(norm);
  cout << "meson/pion ratio should be set to: " << norm << endl;

  norm = expected*intothermt/intother;
  ptother->Scale(norm);
 
  for (int ibin=1; ibin<=nbins; ibin++ )
  {
    weight = ptother->GetBinContent(ibin)/ptpion->GetBinContent(ibin);
    ratio->AddBinContent(ibin,weight);
  }

  ptpion->SetXTitle("p_{t} [GeV/c]");
  ptpion->SetYTitle("(1/2#pi p_{t})dN/dp_{t}dy [(c/GeV)^{2}]");
  ptpion->SetLineWidth(5);
  ptpion->SetLineColor(1);
  ptother->SetLineWidth(5);
  ptother->SetLineColor(2);
  ptothermt->SetLineWidth(5);
  ptothermt->SetLineColor(4);
  ptpion->Draw("");
  ptothermt->Draw("same");
  ptother->Draw("same");

  TLatex *text_pion0 = new TLatex(3.2,1.5,"#pi^{0}");
  text_pion0->SetTextColor(1);
  text_pion0->Draw();
  TLatex *text_pionm = new TLatex(3.2,1.1,"#eta m_{t} scaled");
  text_pionm->SetTextColor(4);
  text_pionm->Draw();
  TLatex *text_pionp = new TLatex(3.2,0.7,"#eta hydro");
  text_pionp->SetTextColor(2);
  text_pionp->Draw();

   c2 = new TCanvas("c2","A Simple Graph with error bars",200,10,700,500);

   c2->SetFillColor(10);
   c2->SetGrid();
   c2->SetLogy(0);
   c2->SetTicks();
 
   c2->cd();

  ratiomt->SetXTitle("p_{t} [GeV/c]");
  ratiomt->SetYTitle("#eta / #pi^{0}");
  ratio->SetLineWidth(5);
  ratio->SetLineColor(2);
  ratiomt->SetLineWidth(5);
  ratiomt->SetLineColor(4);
  ratiomt->Draw();
  ratio->Draw("same");

  TLatex *text_pionm = new TLatex(3.2,0.42,"#eta m_{t} scaled");
  text_pionm->SetTextColor(4);
  text_pionm->Draw();
  TLatex *text_pionp = new TLatex(3.2,0.35,"#eta hydro");
  text_pionp->SetTextColor(2);
  text_pionp->Draw();

  return;
}
void BkgDemo_Diplot(TCanvas* c, TH1F** h, TLegend* l1, TLegend* l2){
		//Make a split canvas, comparison of methods and tag above, bkg subtracted tag below
//	printf("\nDo BkgDemo_Diplot for canvas %s\n",c->GetName());
//	printf("integrals stage1: tag %f usb %f lsb %f\n",h[1]->Integral(),h[5]->Integral(),h[6]->Integral());

	
	TLatex * TEX_CMSPrelim;
	if(preliminary) TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS Preliminary"); 
	else TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS"); 
	PrettyLatex(TEX_CMSPrelim,0.03);
	TLatex * TEX_E_TeV = new TLatex(0.800251,0.953368,"#sqrt{s} = 8 TeV");
	PrettyLatex(TEX_E_TeV,0.03);
	TLatex * TEX_lumi_fb = new TLatex(0.621859,0.953368,Form("#intL dt = %.1f fb^{-1}",Integrated_Luminosity_Data));
	PrettyLatex(TEX_lumi_fb,0.03);
	string sp1 = string(c->GetName())+"_p1";
	string sp2 = string(c->GetName())+"_p2";
    TPad *p1 = new TPad((char*)sp1.c_str(),"",0.,0.3,1.,1.);
    p1->SetBottomMargin(0);
    p1->cd();
//	c->Divide(1,2);
//	c->cd(1);
	PrettyHist(h[3],kRed);
	PrettyHist(h[5],kBlue);
	PrettyHist(h[1]);
	PrettyHist(h[6],kGreen);
	//PrettyHist(h[3],kRed);
	PrettyHist(h[7],kTeal);
PrettyBlock2(h[5],kBlue,3354,2);
	//PrettyBlock(h[5],kBlue,string("//thatch"));//PrettyMarker(h[5],kBlue,4);
	PrettyMarker(h[1]);
PrettyBlock2(h[6],kGreen,3345,2);
	//PrettyBlock(h[6],kGreen,string("\\thatch"));//PrettyMarker(h[6],kGreen,4);
	//PrettyMarker(h[3],kRed);
	PrettyMarker(h[7],kTeal);
//	h[5]->Scale(mHwidth/sidebandwidth);//lsb scaled
//	h[6]->Scale(mHwidth/sidebandwidth);//usb scaled
//	printf("integrals stage2: tag %f usb %f lsb %f\n",h[1]->Integral(),h[5]->Integral(),h[6]->Integral());
//	printf("ranges maximi before setrange tag %f lsb %f, usb %f\n",h[1]->GetMaximum(),h[5]->GetMaximum(),h[6]->GetMaximum());
//	printf("integrals stage3: tag %f usb %f lsb %f\n",h[1]->Integral(),h[5]->Integral(),h[6]->Integral());
//	printf("ranges maximi before after tag %f lsb %f usb %f\n",h[1]->GetMaximum(),h[5]->GetMaximum(),h[6]->GetMaximum());
	h[3]->SetFillStyle(0);//open rectangle
	h[3]->SetLineColor(kRed);
	h[3]->SetLineWidth(4);

	h[6]->SetMinimum(0.0);
	//float linmax = h[6]->GetMaximum();
	//float linmin = h[6]->GetMinimum();
	playNiceWithLegend(h[6],0.30,0.0);
	playNiceWithLegend(h[3],0.30,0.0);
	playNiceWithLegend(h[5],0.30,0.0);
	playNiceWithLegend(h[1],0.30,0.0);
	SameRange(h[3],h[1]);
	SameRange(h[3],h[5],h[6]);
	SameRange(h[3],h[1]);
	h[3]->Draw("e2p");
	h[5]->Draw("e2psame");
	h[6]->Draw("e2psame");
	h[3]->Draw("e2psame");
	//if(showTag) h[1]->Draw("e1psame");//tag
	TPad *p2 = new TPad((char*)sp2.c_str(),"",0.,0.125,1.,0.3);
    p2->SetTopMargin(0);
    p2->cd();
//	c->cd(2);
	TAxis * x = h[7]->GetXaxis();
	TAxis * y = h[7]->GetYaxis();
	float fontsize = 0.25;
	float fontsizeY = 0.10;
	x->SetTitleSize(fontsize);
	y->SetTitleSize(fontsizeY);
	x->SetLabelSize(fontsize);
	y->SetLabelSize(fontsizeY);

	h[7]->GetYaxis()->SetRangeUser(0.,2.);
	h[7]->Draw("e1p");
	TLine *OneLine = new TLine(x->GetXmin(),1.0,x->GetXmax(),1.0);
	OneLine->SetLineColor(kBlack);
	OneLine->SetLineWidth(2);
	OneLine->SetLineStyle(7);//dashed.
	OneLine->Draw("same");
	h[7]->Draw("e1psame");
	
	p1->cd();
//  c->cd(1);
	if(showTag) l1->AddEntry(h[1],"Higgs Mass Region");
        TH1F * box = new TH1F("box","asdf",1,0,1);
        box->SetMarkerColor(kRed);
        box->SetMarkerStyle(25);
        box->SetMarkerSize(2);
        box->SetLineColor(0);
	l1->AddEntry(box,"Data Driven Background");
	l1->AddEntry(h[5],"Lower Mass Sideband");
	l1->AddEntry(h[6], "Upper Mass Sideband");
	l1->Draw("same");
        TEX_CMSPrelim->Draw("same");
        TEX_E_TeV->Draw("same");
        TEX_lumi_fb->Draw("same");
	p2->cd();
		//c->cd(2);
	l2->SetTextSize(fontsize*0.8);
	l2->AddEntry(h[7],"Lower/Upper Sideband Ratio");
	l2->Draw("same");
    c->cd();
	p1->Draw();
	p2->Draw();
}
void format_plots_data(){
	cout<<"hello world"<<endl;
	CMSStyle();
	
		///////////////////////////// Switcehs //////////////////////////////////////

        int nKinemVars = nKinemVars_all;
	string *s_KinemVars = s_KinemVars_all;


	int printlevel = 1;
	bool saveImages = true;
	
	bool makediphoMassPlot = 1;
	bool makeBkgDemo = 1;
	bool makeBkg1 = 0;
	bool makeBkgRat = 0;	
		///////////////////////////// File Work ///////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Start File work" << endl;

		///INPUT FILES
	const int nDataAndMcFiles = 1;
	string Data = "Data";
	string s_DataAndMcFiles[nDataAndMcFiles]    = {Data};//** FOR INEDEXING
	string s_DataAndMcFiles_v4[nDataAndMcFiles] = {Data};

		///Output File
	TFile* fplots = new TFile(formatedplotsroot_data.c_str(),"RECREATE");

	TFileMap PostAnaAnaFiles;
	TFileMap MainAnaFiles;
	cout<<endl<<"Reading in data file "<<plotsAndBackground_data<<endl<<endl;
	PostAnaAnaFiles[Data] = new TFile(plotsAndBackground_data.c_str());
	MainAnaFiles[Data]    = new TFile(plotsroot_data.c_str());
	
//	PostAnaAnaFiles["st350ho200"] = new TFile(plotsAndBackground_mc.c_str());
//	MainAnaFiles["st350ho200"]    = new TFile(plotsroot_mc.c_str());

	cout<<endl<<"Writing finished plots to file "<<plotsroot_data<<endl<<endl;

                ///////////////////////////// STANDARD MARKINGS ///////////////////////////////////////
        TLatex * TEX_CMSPrelim;
        if(preliminary) TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS Preliminary");
        else TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS");
        PrettyLatex(TEX_CMSPrelim,0.03);
        TLatex * TEX_E_TeV = new TLatex(0.800251,0.953368,"#sqrt{s} = 8 TeV");
        PrettyLatex(TEX_E_TeV,0.03);
        TLatex * TEX_lumi_fb = new TLatex(0.621859,0.953368,Form("#intL dt = %.1f fb^{-1}",Integrated_Luminosity_Data));
        PrettyLatex(TEX_lumi_fb,0.03);


		///////////////////////////// Other Lists ///////////////////////////////////////	
	/*Debug*/ if(printlevel > 0) cout << "Make Other Lists" << endl;


	
		/////////////// FOR INDEXING, USE THESE /////////////////////////
		///	string s_MassBkgDists[nPhoMassAndBkgDists]={lowSB,tag,upperSB,bkg,tag_subbkg,lowSB_scaled,upperSB_scaled};
		/// string s_EventTopology[nEventTopologies]={"","1Jb","3J","3Jb","metCut"};
		/// string s_KinemVars[nKinemVars]={"MET","ST","PtGG","HT","MHT"};
		/// string s_DataAndMcFiles[nDataAndMcFiles]={Data,"MC_st350ho200"...}
		/////////////////////////////////////////////////////////////////



		//	const int nEventTopologies = 5; // the number of types of cuts selected, like 1JB...
		//string s_EventTopology[nEventTopologies] = {"","1Jb","3J","3Jb","metCut"};//** FOR INEDEXING
	string s_EventTopology_v2[nEventTopologies];//{"","_1Jb","_3J","_3Jb","_metCut"};
	string s_EventTopology_v3[nEventTopologies];//{"","_1Jb_","_3J_","_3Jb_","_metCut_"};
	//s_EventTopology_v2[0]=s_EventTopology[0];
	//s_EventTopology_v3[0]=s_EventTopology[0];
	for (int i=0; i<nEventTopologies; i++) {
		s_EventTopology_v2[i] = string("_")+s_EventTopology[i];
		s_EventTopology_v3[i] = string("_")+s_EventTopology[i]+"_";
	}

	//const int nPhoMassAndBkgDists //lsb, tag, usb...
	//	string s_MassBkgDists[] = {"lowSB","tag","upperSB","bkg","tag_subbkg","lowSB_scaled","upperSB_scaled"};
	//	string s_MassBkgDists_v2[] = {"_lowSB","_tag","_upperSB","_bkg","_tag_subbkg","_lowSB_scaled","_upperSB_scaled"};
	string s_MassBkgDists_v2[nPhoMassAndBkgDists];
	for (int i=0; i<nPhoMassAndBkgDists; i++) {s_MassBkgDists_v2[i]=string("_")+s_MassBkgDists[i];}

	string s_DataAndMcFiles_v2[nDataAndMcFiles];
	string s_DataAndMcFiles_v3[nDataAndMcFiles];
	s_DataAndMcFiles_v2[0]=Data;//{Data,"MC_st350ho200"...}
	s_DataAndMcFiles_v3[0]=Data;//{Data,"MC","MC","MC"...}
	for (int i=1; i<nDataAndMcFiles; i++) {s_DataAndMcFiles_v3[i]=string("MC_")+s_DataAndMcFiles[i];}
	for (int i=1; i<nDataAndMcFiles; i++) {s_DataAndMcFiles_v3[i]=string("MC");}

		///////////////////////////// LUMI SCALES ///////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Set Lumi Scales" << endl;
	Labledflaot lumiscalemap;
	lumiscalemap[Data] = 1.;
	const float Integrated_Luminosity_Data = 5.725; /*fb^-1*/
	lumiscalemap["st350ho200"] = (Integrated_Luminosity_Data * 447.4 /*fb*/)/((float) 1000000 /*events*/);


		//////////////////////////////////////////////////////////////////////////////
		///////////////////////////////Load h_mGG/////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Load h_mGG" << endl;
		//load mGG_unsliced histograms from all files. 
	Lable2Hist h_mGG_unsliced;
	for (int jFile=0; jFile<nDataAndMcFiles; jFile++) { //loop over all files
		LableHist tmp; // this is the collection of histograms, indexed by topology name
		/*Debug*/ if(printlevel > 2) cout << "first loop, jFile = "<<jFile << endl;
		for (int iTop = 0; iTop<nEventTopologies; iTop++) {
			/*Debug*/ if(printlevel > 4) cout << "second loop, iTop = "<<iTop <<endl;
			string instring = string("h_mGG") +s_EventTopology[iTop] + "_unsliced";
			/*Debug*/ if(printlevel > 4) cout << "loading "<<instring<< " from file " << s_DataAndMcFiles[jFile] << " for topology "<<s_EventTopology[iTop] <<endl;
			tmp[s_EventTopology[iTop]] = (TH1F*)PostAnaAnaFiles[s_DataAndMcFiles[jFile]]->Get(instring.c_str());
			/*Debug*/ if(printlevel > 4) cout << "succeeded"<<endl;
			
				//fix the root names
			string newname = instring+"_"+s_DataAndMcFiles[jFile];
			/*Debug*/ if(printlevel > 4) cout << "resetting name to "<<newname<<" for topology "<<s_EventTopology[iTop]<<endl;
//			/*Debug*/ if(printlevel > 6) cout << tmp[s_EventTopology[iTop]]->Integral()<<endl;
			
			tmp[s_EventTopology[iTop]]->SetName((newname).c_str());
			/*Debug*/ if(printlevel > 4) cout << "succeeded"<<endl;
		}
		/*Debug*/ if(printlevel > 2) cout << "Attempting to write tmp to h_mGG_unsliced with tag "<<s_DataAndMcFiles[jFile] << endl;
		h_mGG_unsliced[s_DataAndMcFiles[jFile]] = tmp;
		/*Debug*/ if(printlevel > 2) cout << "succeeded"<<endl;
	}
//	TH1F* h_mGG_unsliced = (TH1F*)fin.Get("h_mGG_unsliced");
//	TH1F* h_mGG_1Jb_unsliced = (TH1F*)fin.Get("h_mGG_1Jb_unsliced");
	
		////////////////////////////// Load Kin Var Plots //////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Load Kin Var Plots" << endl;
	Lable3HistArr KinVarHistMap;
	for (int jFile=0; jFile<nDataAndMcFiles; jFile++) {
		
		/*Debug*/ if(printlevel >2) cout << "first loop, jFile = "<<jFile <<endl;	
		Lable2HistArr tmpMapTopo;
		for (int iTop = 0; iTop<nEventTopologies; iTop++) {
			/*Debug*/ if(printlevel >4) cout << "second loop, iTop = "<<iTop <<endl;
			
			LableHistArr tmpMapKinVar;
			for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
				/*Debug*/ if(printlevel >6) cout << "third loop, kKinVar = "<<kKinVar <<endl;
				
					//there is no MET dist for metCut, so don't try to load it. 
				if (s_EventTopology[iTop].compare("metCut") == 0 && s_KinemVars[kKinVar].compare("MET") == 0) continue;
				if (iTop == 2 && kKinVar==0) {cout << endl<<endl<<" ***** ERROR!! your attempt to skip metCut|MET failed"<<endl<<endl; 	}
				
				TH1F** tmpHistArray = new TH1F*[nPhoMassAndBkgDists];
					//LoadHistSet(hMET, &fin, "MET");
				for (int lMassDist=0; lMassDist < nPhoMassAndBkgDists; lMassDist++){
					/*Debug*/ if(printlevel >8) cout << "forth loop, lMassDist = "<<lMassDist <<" out of "<<nPhoMassAndBkgDists<<endl;
					string instring = string("h")+s_KinemVars[kKinVar]+s_EventTopology[iTop]+"_"+s_MassBkgDists[lMassDist];
					/*Debug*/ if(printlevel >8) cout << "Load hist "<<instring<< " from file "<< s_DataAndMcFiles[jFile] << " into tmpHistArray["<<lMassDist<<"]"<<endl;

					tmpHistArray[lMassDist] = (TH1F*) PostAnaAnaFiles[s_DataAndMcFiles[jFile]]->Get( instring.c_str() );
						//fix the root name
					string newname = instring+"_"+s_DataAndMcFiles[jFile];
					/*Debug*/ if(printlevel >8) cout << "rename hist "<<newname <<endl;
					tmpHistArray[lMassDist]->SetName((newname).c_str());
					/*Debug*/ if(printlevel >8) cout << "success" <<endl;
					string newtitle = string(";")+s_KinemVars[kKinVar]+" (GeV)";
					tmpHistArray[lMassDist]->SetTitle((char*)newtitle.c_str());
				}//end for every Mass Dist
				/*Debug*/ if(printlevel >6) cout << "load hist array into tmpMapKinVar for "<< s_KinemVars[kKinVar] <<endl;
				tmpMapKinVar[s_KinemVars[kKinVar]] = tmpHistArray;
								
			}//End for each kinematic varraible
			/*Debug*/ if(printlevel >4) cout << "load hist array into tmpMapTopo for "<< s_EventTopology[iTop] <<endl;
			tmpMapTopo[s_EventTopology[iTop]] = tmpMapKinVar;
			
		}//end for each topology
		/*Debug*/ if(printlevel >2) cout << "load hist array into KinVarHistMap for "<< s_DataAndMcFiles[jFile] <<endl;
		KinVarHistMap[s_DataAndMcFiles[jFile]] = tmpMapTopo;
	}//end for each file

	/*Debug*/ if(printlevel >2){
		cout << "***KinVarHistMap should now be loaded, but did it work?***"<<endl;
		//cout << "Data 1Jb MHT tag name:" <<KinVarHistMap["Data"]["1Jb"]["MHT"][1]->GetName()<<endl;
		//cout << "Data 3Jb MHT tag name:" <<KinVarHistMap["Data"]["3Jb"]["MHT"][1]->GetName()<<endl;
		//cout << "Data 1Jb ST tag name:" <<KinVarHistMap["Data"]["1Jb"]["ST"][1]->GetName()<<endl;
		//cout << "Data 1Jb MHT sb name:" <<KinVarHistMap["Data"]["1Jb"]["MHT"][5]->GetName()<<endl;
		cout << "Data MHT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["MHT"][7]->GetBinContent(1)<<endl;
		cout << "Data HT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["HT"][7]->GetBinContent(1)<<endl;
		cout << "Data ST L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["ST"][7]->GetBinContent(1)<<endl;
		cout << "***If this is printing, then the answer is probably Yes ***"<<endl;
	}

	
//	h_mGG_unsliced->SetName("h_mGG_unsliced");
/*	TH1F * hMET[nPhoMassAndBkgDists];
	LoadHistSet(hMET, &fin, "MET");

	TH1F * hST_1Jb[nPhoMassAndBkgDists];
	LoadHistSet(hST_1Jb,&fin,"ST_1Jb");
	*/
	
		////////////////////////////////////////////////////////////////////
		/*Debug*/ if(printlevel > 0) cout << "Load the Fit Curves" << endl;
		//load the fit curves for the data. 
	TF1* mgg_fit_curve[nEventTopologies];
	for (int iTop=0; iTop<nEventTopologies; iTop++) {
		/*Debug*/ if(printlevel > 1) cout << "first loop, iTop = "<<iTop <<endl;
		string instring = string("mgg") + s_EventTopology_v3[iTop] + "fit";
		/*Debug*/ if(printlevel > 1) cout << "instring = "<<instring <<endl;//mggNULLfit, am I naming it wrong? 
		mgg_fit_curve[iTop] = (TF1*)PostAnaAnaFiles[Data]->Get(instring.c_str());
		/*Debug*/ if(printlevel > 1) cout << "supposidly loaded it, try it "<<endl;
		/*Debug*/ if(printlevel > 1) cout << mgg_fit_curve[iTop]->GetProb() <<endl;//seg faults the first time it's exectuted. 
		
/*	mgg_fit_curve[0] = (TF1*)fin.Get("mggfit");
	mgg_fit_curve[1] = (TF1*)fin.Get("mgg_1Jb_fit");
	mgg_fit_curve[2] = (TF1*)fin.Get("mgg_3J_fit");
	mgg_fit_curve[3] = (TF1*)fin.Get("mgg_3Jb_fit");
	mgg_fit_curve[4] = (TF1*)fin.Get("mgg_metCut_fit");*/
	}
	
	
		// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//     ___              __       ____           ___  __     __    
//    / _ \___ ___ ____/ /_ __  / __/__  ____  / _ \/ /__  / /____
//   / , _/ -_) _ `/ _  / // / / _// _ \/ __/ / ___/ / _ \/ __(_-<
//  /_/|_|\__/\_,_/\_,_/\_, / /_/  \___/_/   /_/  /_/\___/\__/___/
//                     /___/                                      
		/*Debug*/ if(printlevel > 0) cout << "Start Building Plots" << endl;

	fplots->cd();

		//if there is not a plots folder, make it. 
	
//     __  ___            ___  __     __ 
//    /  |/  /__ ____ _  / _ \/ /__  / /_
//   / /|_/ / _ `/ _ `/ / ___/ / _ \/ __/
//  /_/  /_/\_, /\_, / /_/  /_/\___/\__/ 
//         /___//___/ 


		/*Debug*/ if(printlevel > 0) cout << "Build mass plots" << endl;
	
		//diphoton mass plots, one for each data plot, for each topology. 
	if(makediphoMassPlot){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		/*Debug*/ if(printlevel > 1) cout << "first loop, iTop = "<<iTop <<endl;
		string canvName = string("c_mgg")+s_EventTopology_v2[iTop]+"_unsliced";
		/*Debug*/ if(printlevel > 1) cout << "made tempCanv with name "<<canvName  <<endl;
		TCanvas* tempCanv = newTCanvas((char*)canvName.c_str()); //char*error
		/*Debug*/ if(printlevel > 1) cout << "Enter the merky deptsh of diphoMassPlot"<<endl;
		diphoMassPlot(h_mGG_unsliced[Data][s_EventTopology[iTop]],tempCanv,mgg_fit_curve[iTop]);
		/*Debug*/ if(printlevel > 1) cout << "fin dinphoMass plot, try to write to fplots" <<endl;
		tempCanv->Write();
		if(saveImages) SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfjpgepspng");//save as all types
		//if(saveImages) SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
	}
	}
	

		// %%%%%%%%%%%%%%%%%%%%%%%% Kinematics and backgrounds %%%%%%%%%%%%%%%%%
//     ___  __        ___                   ___  __     __    
//    / _ )/ /_____ _/ _ \___ __ _  ___    / _ \/ /__  / /____
//   / _  /  '_/ _ `/ // / -_)  ' \/ _ \  / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, /____/\__/_/_/_/\___/ /_/  /_/\___/\__/___/
//            /___/                                           

	/*Debug*/ if(printlevel > 0) cout << "Build Kin Var plots type 1" << endl;
		//Arrangement 1
        TH1F * box = new TH1F("box","asdf",1,0,1);
        box->SetMarkerColor(kRed);
        box->SetMarkerStyle(25);
        box->SetMarkerSize(2);
        box->SetLineColor(0);
		///Demonstrate background. Plot two side bands with their ratio as a sub-plot. include a switchable Tag.


	if(makeBkgDemo){
	for (int iTop = 0; iTop<nEventTopologies; iTop++){
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++){
			/*Debug*/ if(printlevel >2) cout << "iTop="<<iTop<<" kKinVar="<<kKinVar<<endl;
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ){
				/*Debug*/ if(printlevel >2) cout << "skipping met plot for met cut"<<endl;
				continue;
			}
			string canvName = string("BkgFull_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			/*Debug*/ if(printlevel >6) {TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			/*Debug*/ if(printlevel >6) printf("Scan1 Ratio bin1 for %s %s  = %f\n",s_EventTopology[iTop].c_str(),s_KinemVars[kKinVar].c_str(),h[7]->GetBinContent(1));}
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			BkgDemo_Diplot(tempCanv,
					 KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]],
						   makeL1(0.2072864,0.7203704,0.4070352,0.9203704),
						   makeL2(0.51005,0.706436,0.708543,0.902669));
			//tempCanv->Write();
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
		}//edn for each kinematic varriable
	}//end for each topology
	}

//     ___  __       ___  ___  __     __    
//    / _ )/ /_____ <  / / _ \/ /__  / /____
//   / _  /  '_/ _ `/ / / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, /_/ /_/  /_/\___/\__/___/
//            /___/                         

		///Demostrate background-upper. Plot the two side bands together, but ignore the ratio. (Arr2)
	if(makeBkg1){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ) continue;
			string canvName = string("Bkg1_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			string canvNamelog = string("Bkg1Log_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			TCanvas* tempCanvlog = newTCanvas((char*)canvNamelog.c_str());
			tempCanvlog->SetTopMargin(0.06);
                        tempCanvlog->SetBottomMargin(0.15);

			TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			tempCanv->cd();
			//RaiseRangeRoof(h[5],1.25);
			//RaiseRangeRoof(h[1],1.25);
			//RaiseRangeRoof(h[6],1.25);
			PrettyHist(h[5],kBlue);
			PrettyHist(h[1],1);
			PrettyHist(h[6],kGreen);
			PrettyHist(h[3],kRed);

//			string cname = tempCanv->GetName();
//			if(cname.find("_HT")!=string::npos)//if found "_HT" in the name
//				h[5]->GetXaxis()->SetLabelSize(0.04);
				//SPECIAL
			if (s_KinemVars[kKinVar].compare("HT") == 0) {
				h[5]->GetXaxis()->SetLabelSize(0.04);}

			PrettyBlock2(h[5],kBlue,3354,2);//PrettyMarker(h[5],kBlue,4);
			//PrettyBlock(h[5],kBlue,string("//thatch"));//PrettyMarker(h[5],kBlue,4);
			PrettyMarker(h[1]);
			PrettyBlock2(h[6],kGreen,3345,2);//PrettyMarker(h[6],kGreen,4);
			h[3]->SetFillStyle(0);//open rectangle
                        h[3]->SetLineColor(kRed);
                        h[3]->SetLineWidth(4);
			//PrettyBlock(h[6],kGreen,string("\\thatch"));//PrettyMarker(h[6],kGreen,4);
			playNiceWithLegend(h[3],0.30,0.0);
                        playNiceWithLegend(h[6],0.30,0.0);
                        playNiceWithLegend(h[5],0.30,0.0);
                        playNiceWithLegend(h[1],0.30,0.0);
			h[6]->SetMinimum(0.0);
			SameRange(h[1],h[3]);
			SameRange(h[5],h[6],h[1]);
			SameRange(h[1],h[3]);
			h[5]->Draw("e2p");
			h[6]->Draw("e2psame");
			h[3]->Draw("e2psame");
			//if(showTag) h[1]->Draw("e1psame");//tag
			TLegend* l1 = makeL1_v2(0.443467,0.720207,0.643216,0.919689);
			if(showTag) l1->AddEntry(h[1],"Higgs Mass Region");
			l1->AddEntry(h[5],"Lower Mass Sideband");
			l1->AddEntry(h[6],"Upper Mass Sideband");
			l1->AddEntry(box,"Data Driven Background");//h[3
			l1->Draw("same");
		        TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");
			tempCanv->Write();
			if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types

			tempCanvlog->cd();
			h[5]->SetMinimum(0.05);
                        tempCanvlog->SetLogy();
			h[5]->Draw("e2p");
			h[6]->Draw("e2psame");
			h[3]->Draw("e2psame");
			l1->Draw("same");
			TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");
			if(saveImages)SaveCanvas(tempCanvlog,plotsdir+tempCanvlog->GetName(),"ggif");//save as all types
			
		}//edn for each kinematic varriable
	}//end for each topology
	}//end if


//     ___  __          ___       __  _        ___  __     __    
//    / _ )/ /_____ _  / _ \___ _/ /_(_)__    / _ \/ /__  / /____
//   / _  /  '_/ _ `/ / , _/ _ `/ __/ / _ \  / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, / /_/|_|\_,_/\__/_/\___/ /_/  /_/\___/\__/___/
//            /___/                                              

		///Demostrate background--Ratio. Plot the ratio of the two side bands, and nothing else. 
	if(makeBkgRat){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
			/*Debug*/ if(printlevel >6) cout << "Data MHT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["MHT"][7]->GetBinContent(1)<<endl;
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ) continue;
			string canvName = string("BkgRat_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			/*Debug*/ if(printlevel >6)	printf("Scan2 Ratio bin1 for %s %s  = %f\n",s_EventTopology[iTop].c_str(),s_KinemVars[kKinVar].c_str(),h[7]->GetBinContent(1));
			tempCanv->cd();
			PrettyHist(h[7],kTeal);
			h[7]->GetYaxis()->SetRangeUser(0.,2.);
			if (s_KinemVars[kKinVar].compare("HT") == 0) {
				h[7]->GetXaxis()->SetLabelSize(0.04);}

			PrettyMarker(h[7],kTeal);
			h[7]->Draw("e1p");
			TAxis* xaxis = h[7]->GetXaxis();
			TLine *OneLine = new TLine(xaxis->GetXmin(),1.0,xaxis->GetXmax(),1.0);
			OneLine->SetLineColor(kBlack);
			OneLine->SetLineWidth(2);
			OneLine->SetLineStyle(7);//dashed.
			OneLine->Draw("same");
			h[7]->Draw("e1psame");
			TLegend* l1 = makeL1_v2(0.330402,0.836788,0.530151,0.919689);
			l1->AddEntry(h[7],"Lower/Upper Sideband Ratio");
			l1->Draw("same");
			TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");

			tempCanv->Write();
			if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
		}//edn for each kinematic varriable
	}//end for each topology
	}//end if makeBkgRat

		///END MAKE PLOTS
	/*Debug*/ if(printlevel > 0) cout << "Close Files" << endl;
	fplots->Close(); 
		//itterate over the map. close everything. 
	for( TFileMap::iterator i=PostAnaAnaFiles.begin(); i!=PostAnaAnaFiles.end(); ++i){
		(*i).second->Close();
	}
	for( TFileMap::iterator i=MainAnaFiles.begin(); i!=MainAnaFiles.end(); ++i){
		(*i).second->Close();
	}


}//end format plots
void MB_errorEnvelope_PMTbyPMT(Int_t calLow, Int_t calHigh, Int_t pmt, bool postReplayPass4)
{
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(12);

  // Style options
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(11);
  //gStyle->SetOptStat(0);
  //gStyle->SetStatFontSize(0.020);
  gStyle->SetOptFit(1011); // 1111
  gStyle->SetOptTitle(1);
  gStyle->SetTitleFontSize(0.05);
  //gStyle->SetTitleX(0.17);
  //gStyle->SetTitleAlign(13);
  gStyle->SetTitleOffset(1.20, "x");
  gStyle->SetTitleOffset(1.10, "y");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetNdivisions(510,"X");
  gStyle->SetNdivisions(510,"Y");
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetPadRightMargin(0.05);
  gStyle->SetPadBottomMargin(0.12);

  Int_t PMT = pmt; //0->Average over PMTs; 1,2,3,4 -> single PMT

  Int_t calPeriodLow = calLow;
  Int_t calPeriodHigh = calHigh;

  // Setup output file for error Envelope
  ofstream errEnv;
  Char_t tempfile[200];
  if (postReplayPass4) {
    sprintf(tempfile,"../error_envelope/error_envelope_PostReplayPass4_PMTbyPMT_calPeriods_%i-%i.dat",calPeriodLow,calPeriodHigh);}
  else if (calPeriodLow!=calPeriodHigh && !PMT) {
    sprintf(tempfile,"../error_envelope/error_envelope_calPeriods_%i-%i.dat",calPeriodLow,calPeriodHigh);}
  else if (calPeriodLow!=calPeriodHigh && PMT) {
    sprintf(tempfile,"../error_envelope/error_envelope_calPeriods_%i-%i_PMT%i.dat",calPeriodLow,calPeriodHigh,PMT);}
  else if (calPeriodLow==calPeriodHigh && !PMT) {
    sprintf(tempfile,"../error_envelope/error_envelope_calPeriod_%i.dat",calPeriodHigh);}
  else if (calPeriodLow==calPeriodHigh && PMT) {
    sprintf(tempfile,"../error_envelope/error_envelope_calPeriod_%i_PMT%i.dat",calPeriodLow,PMT);}

  errEnv.open(tempfile);

  // Read East data file
  char tempEast[500];
  if (postReplayPass4) sprintf(tempEast, "../residuals/residuals_global_EvisPMTbyPMT_East_periods_%i-%i.dat", calPeriodLow, calPeriodHigh);
  else if (calPeriodLow!=calPeriodHigh && !PMT) sprintf(tempEast, "../residuals/residuals_global_East_periods_%i-%i.dat", calPeriodLow, calPeriodHigh);
  else if (calPeriodLow==calPeriodHigh && !PMT) sprintf(tempEast, "../residuals/residuals_East_runPeriod_%i.dat", calPeriodLow);
  else if (calPeriodLow!=calPeriodHigh && PMT) sprintf(tempEast,"../residuals/residuals_global_East_periods_%i-%i_PMTE%i.dat", calPeriodLow, calPeriodHigh, PMT);
  else if (calPeriodLow==calPeriodHigh && PMT) sprintf(tempEast,"../residuals/residuals_East_runPeriod_%i_PMTE%i.dat", calPeriodLow,PMT);
  ifstream fileEast(tempEast);

  const size_t N = 1000;
  TString sourceEast[N];
  Int_t runEast[N];
  Double_t resEast[N];
  Double_t resCeEast[N], resInEast[N], resSnEast[N], resBi1East[N], resBi2East[N];

  Int_t i = 0;
  Int_t nCeEast = 0;
  Int_t nInEast = 0;
  Int_t nSnEast = 0;
  Int_t nBi1East = 0;
  Int_t nBi2East = 0;
  cout << "East \"bad\" runs: \n";
  while (!fileEast.eof()) {
    fileEast >> sourceEast[i] >> runEast[i] >> resEast[i];
    if (sourceEast[i] == "Ce_East") {
      resCeEast[nCeEast] = resEast[i];
      nCeEast++;
      if (sqrt(resEast[i]*resEast[i])>0.05*peakCe_EQ) cout << runEast[i] << " " << sourceEast[i] << " " << resEast[i] << endl; 
    }
    if (sourceEast[i] == "In_East") {
      resInEast[nInEast] = resEast[i];
      nInEast++;
      if (sqrt(resEast[i]*resEast[i])>0.05*peakIn_EQ) cout << runEast[i] << " " << sourceEast[i] << " " << resEast[i] << endl; 
    }
    if (sourceEast[i] == "Sn_East") {
      resSnEast[nSnEast] = resEast[i];
      nSnEast++;
      if (sqrt(resEast[i]*resEast[i])>0.05*peakSn_EQ) cout << runEast[i] << " " << sourceEast[i] << " " << resEast[i] << endl; 
    }
    if (sourceEast[i] == "Bi1_East") {
      resBi1East[nBi1East] = resEast[i];
      nBi1East++;
      if (sqrt(resEast[i]*resEast[i])>0.05*peakBiHigh_EQ) cout << runEast[i] << " " << sourceEast[i] << " " << resEast[i] << endl; 
    }
    if (sourceEast[i] == "Bi2_East") {
      resBi2East[nBi2East] = resEast[i];
      nBi2East++;
      if (sqrt(resEast[i]*resEast[i])>0.05*peakBiLow_EQ) cout << runEast[i] << " " << sourceEast[i] << " " << resEast[i] << endl; 
    }
    if (fileEast.fail()) break;
    i++;
  }
  cout << nCeEast << " " << nInEast << " " << nSnEast << " " << nBi1East << " " << nBi2East << endl;

  // Read West data file
  char tempWest[500];
  if (postReplayPass4) sprintf(tempWest, "../residuals/residuals_global_EvisPMTbyPMT_West_periods_%i-%i.dat", calPeriodLow, calPeriodHigh);
  else if (calPeriodLow!=calPeriodHigh && !PMT) sprintf(tempWest, "../residuals/residuals_global_West_periods_%i-%i.dat", calPeriodLow, calPeriodHigh);
  else if (calPeriodLow==calPeriodHigh && !PMT) sprintf(tempWest, "../residuals/residuals_West_runPeriod_%i.dat", calPeriodLow);
  else if (calPeriodLow!=calPeriodHigh && PMT) sprintf(tempWest,"../residuals/residuals_global_West_periods_%i-%i_PMTW%i.dat", calPeriodLow, calPeriodHigh, PMT);
  else if (calPeriodLow==calPeriodHigh && PMT) sprintf(tempWest,"../residuals/residuals_West_runPeriod_%i_PMTW%i.dat", calPeriodLow,PMT);
  ifstream fileWest(tempWest);

  TString sourceWest[N];
  Int_t runWest[N];
  Double_t resWest[N];
  Double_t resCeWest[N], resInWest[N], resSnWest[N], resBi1West[N], resBi2West[N];

  Int_t i = 0;
  Int_t nCeWest = 0;
  Int_t nInWest = 0;
  Int_t nSnWest = 0;
  Int_t nBi1West = 0;
  Int_t nBi2West = 0;
  
  cout << "West \"bad\" runs: \n";
  while (!fileWest.eof()) {
    fileWest >> sourceWest[i] >> runWest[i] >> resWest[i];
    if (sourceWest[i] == "Ce_West") {
      resCeWest[nCeWest] = resWest[i];
      nCeWest++;
      if (sqrt(resWest[i]*resWest[i])>0.05*peakCe_EQ) cout << runWest[i] << " " << sourceWest[i] << " " << resWest[i] << endl; 
    }
    if (sourceWest[i] == "In_West") {
      resInWest[nInWest] = resWest[i];
      nInWest++;
      if (sqrt(resWest[i]*resWest[i])>0.05*peakIn_EQ) cout << runWest[i] << " " << sourceWest[i] << " " << resWest[i] << endl; 
    }
    if (sourceWest[i] == "Sn_West") {
      resSnWest[nSnWest] = resWest[i];
      nSnWest++;
      if (sqrt(resWest[i]*resWest[i])>0.05*peakSn_EQ) cout << runWest[i] << " " << sourceWest[i] << " " << resWest[i] << endl; 
    }    
    if (sourceWest[i] == "Bi1_West") {
      resBi1West[nBi1West] = resWest[i];
      nBi1West++;
      if (sqrt(resWest[i]*resWest[i])>0.05*peakBiHigh_EQ) cout << runWest[i] << " " << sourceWest[i] << " " << resWest[i] << endl; 
    }
    if (sourceWest[i] == "Bi2_West") {
      resBi2West[nBi2West] = resWest[i];
      nBi2West++;
      if (sqrt(resWest[i]*resWest[i])>0.05*peakBiLow_EQ) cout << runWest[i] << " " << sourceWest[i] << " " << resWest[i] << endl; 
    }
    if (fileWest.fail()) break;
    i++;
  }
  cout << nCeWest << " " << nInWest << " " << nSnWest << " " << nBi1West << " " << nBi2West << endl;

  // Histograms
  TH1F *hisCeEast = new TH1F("hisCeEast", "", 60, -30.0, 30.0);
  TH1F *hisInEast = new TH1F("hisInEast", "", 40, -30.0, 30.0);
  TH1F *hisSnEast = new TH1F("hisSnEast", "", 30, -30.0, 30.0);
  TH1F *hisBi1East = new TH1F("hisBi1East", "", 30, -60.0, 60.0);
  TH1F *hisBi2East = new TH1F("hisBi2East", "", 30, -60.0, 60.0);
  TH1F *hisCeWest = new TH1F("hisCeWest", "", 60, -30.0, 30.0);
  TH1F *hisInWest = new TH1F("hisInWest", "", 60, -30.0, 30.0);
  TH1F *hisSnWest = new TH1F("hisSnWest", "", 30, -30.0, 30.0);
  TH1F *hisBi1West = new TH1F("hisBi1West", "", 30, -60.0, 60.0);
  TH1F *hisBi2West = new TH1F("hisBi2West", "", 30, -60.0, 60.0);
  TH1F *hisCe = new TH1F("hisCe", "", 60, -30.0, 30.0);
  TH1F *hisIn = new TH1F("hisIn", "", 60, -30.0, 30.0);
  TH1F *hisSn = new TH1F("hisSn", "", 30, -30.0, 30.0);
  TH1F *hisBi1 = new TH1F("hisBi1", "", 30, -60.0, 60.0);
  TH1F *hisBi2 = new TH1F("hisBi2", "", 30, -60.0, 60.0);

  // Fill histograms
  for (int j=0; j<nCeEast; j++) {
    hisCeEast->Fill(resCeEast[j]);
    hisCe->Fill(resCeEast[j]);
  }
  for (int j=0; j<nInEast; j++) {
    hisInEast->Fill(resInEast[j]);
    hisIn->Fill(resInEast[j]);
  }
  for (int j=0; j<nSnEast; j++) {
    hisSnEast->Fill(resSnEast[j]);
    hisSn->Fill(resSnEast[j]);
  }
  for (int j=0; j<nBi1East; j++) {
    hisBi1East->Fill(resBi1East[j]);
    hisBi1->Fill(resBi1East[j]);
  }
  for (int j=0; j<nBi2East; j++) {
    hisBi2East->Fill(resBi2East[j]);
    hisBi2->Fill(resBi2East[j]);
  }
  for (int j=0; j<nCeWest; j++) {
    hisCeWest->Fill(resCeWest[j]);
    hisCe->Fill(resCeWest[j]);
  }
  for (int j=0; j<nInWest; j++) {
    hisInWest->Fill(resInWest[j]);
    hisIn->Fill(resInWest[j]);
  }
  for (int j=0; j<nSnWest; j++) {
    hisSnWest->Fill(resSnWest[j]);
    hisSn->Fill(resSnWest[j]);
  }
  for (int j=0; j<nBi1West; j++) {
    hisBi1West->Fill(resBi1West[j]);
    hisBi1->Fill(resBi1West[j]);
  }
 for (int j=0; j<nBi2West; j++) {
    hisBi2West->Fill(resBi2West[j]);
    hisBi2->Fill(resBi2West[j]);
  }
  // Calculate mean and standard deviation
  double meanCeEast = 0.;
  for (int j=0; j<nCeEast; j++) {
    meanCeEast += resCeEast[j];
  }
  meanCeEast = meanCeEast / (double) nCeEast;

  double sigmaCeEast = 0.;
  for (int j=0; j<nCeEast; j++) {
    sigmaCeEast += (resCeEast[j] - meanCeEast)*(resCeEast[j] - meanCeEast);
  }
  sigmaCeEast = sigmaCeEast / (double) nCeEast;
  sigmaCeEast = sqrt( sigmaCeEast );

  cout << "meanCeEast = " << meanCeEast << endl;
  cout << "     sigma = " << sigmaCeEast << endl;
  errEnv << "meanCeEast = " << meanCeEast << endl;
  errEnv << "sigma = " << sigmaCeEast << endl;

  double meanInEast = 0.;
  for (int j=0; j<nInEast; j++) {
    meanInEast += resInEast[j];
  }
  meanInEast = meanInEast / (double) nInEast;

  double sigmaInEast = 0.;
  for (int j=0; j<nInEast; j++) {
    sigmaInEast += (resInEast[j] - meanInEast)*(resInEast[j] - meanInEast);
  }
  sigmaInEast = sigmaInEast / (double) nInEast;
  sigmaInEast = sqrt( sigmaInEast );

  cout << "meanInEast = " << meanInEast << endl;
  cout << "     sigma = " << sigmaInEast << endl;
  errEnv << "meanInEast = " << meanInEast << endl;
  errEnv << "sigma = " << sigmaInEast << endl;

  double meanSnEast = 0.;
  for (int j=0; j<nSnEast; j++) {
    meanSnEast += resSnEast[j];
  }
  meanSnEast = meanSnEast / (double) nSnEast;

  double sigmaSnEast = 0.;
  for (int j=0; j<nSnEast; j++) {
    sigmaSnEast += (resSnEast[j] - meanSnEast)*(resSnEast[j] - meanSnEast);
  }
  sigmaSnEast = sigmaSnEast / (double) nSnEast;
  sigmaSnEast = sqrt( sigmaSnEast );

  cout << "meanSnEast = " << meanSnEast << endl;
  cout << "     sigma = " << sigmaSnEast << endl;
  errEnv << "meanSnEast = " << meanSnEast << endl;
  errEnv << "sigma = " << sigmaSnEast << endl;

  double meanBi1East = 0.;
  for (int j=0; j<nBi1East; j++) {
    meanBi1East += resBi1East[j];
  }
  meanBi1East = meanBi1East / (double) nBi1East;

  double sigmaBi1East = 0.;
  for (int j=0; j<nBi1East; j++) {
    sigmaBi1East += (resBi1East[j] - meanBi1East)*(resBi1East[j] - meanBi1East);
  }
  sigmaBi1East = sigmaBi1East / (double) nBi1East;
  sigmaBi1East = sqrt( sigmaBi1East );

  cout << "meanBi1East = " << meanBi1East << endl;
  cout << "     sigma = " << sigmaBi1East << endl;
  errEnv << "meanBi1East = " << meanBi1East << endl;
  errEnv << "sigma = " << sigmaBi1East << endl;

  if (postReplayPass4) {
    double meanBi2East = 0.;
    for (int j=0; j<nBi2East; j++) {
      meanBi2East += resBi2East[j];
    }
    meanBi2East = meanBi2East / (double) nBi2East;
    
    double sigmaBi2East = 0.;
    for (int j=0; j<nBi2East; j++) {
      sigmaBi2East += (resBi2East[j] - meanBi2East)*(resBi2East[j] - meanBi2East);
    }
    sigmaBi2East = sigmaBi2East / (double) nBi2East;
    sigmaBi2East = sqrt( sigmaBi2East );
    
    cout << "meanBi2East = " << meanBi2East << endl;
    cout << "     sigma = " << sigmaBi2East << endl;
    errEnv << "meanBi2East = " << meanBi2East << endl;
    errEnv << "sigma = " << sigmaBi2East << endl;
  }
  // Calculate mean and standard deviation
  double meanCeWest = 0.;
  for (int j=0; j<nCeWest; j++) {
    meanCeWest += resCeWest[j];
  }
  meanCeWest = meanCeWest / (double) nCeWest;

  double sigmaCeWest = 0.;
  for (int j=0; j<nCeWest; j++) {
    sigmaCeWest += (resCeWest[j] - meanCeWest)*(resCeWest[j] - meanCeWest);
  }
  sigmaCeWest = sigmaCeWest / (double) nCeWest;
  sigmaCeWest = sqrt( sigmaCeWest );

  cout << "meanCeWest = " << meanCeWest << endl;
  cout << "     sigma = " << sigmaCeWest << endl;
  errEnv << "meanCeWest = " << meanCeWest << endl;
  errEnv << "sigma = " << sigmaCeWest << endl;

  double meanInWest = 0.;
  for (int j=0; j<nInWest; j++) {
    meanInWest += resInWest[j];
  }
  meanInWest = meanInWest / (double) nInWest;

  double sigmaInWest = 0.;
  for (int j=0; j<nInWest; j++) {
    sigmaInWest += (resInWest[j] - meanInWest)*(resInWest[j] - meanInWest);
  }
  sigmaInWest = sigmaInWest / (double) nInWest;
  sigmaInWest = sqrt( sigmaInWest );

  cout << "meanInWest = " << meanInWest << endl;
  cout << "     sigma = " << sigmaInWest << endl;
  errEnv << "meanInWest = " << meanInWest << endl;
  errEnv << "sigma = " << sigmaInWest << endl;

  double meanSnWest = 0.;
  for (int j=0; j<nSnWest; j++) {
    meanSnWest += resSnWest[j];
  }
  meanSnWest = meanSnWest / (double) nSnWest;

  double sigmaSnWest = 0.;
  for (int j=0; j<nSnWest; j++) {
    sigmaSnWest += (resSnWest[j] - meanSnWest)*(resSnWest[j] - meanSnWest);
  }
  sigmaSnWest = sigmaSnWest / (double) nSnWest;
  sigmaSnWest = sqrt( sigmaSnWest );

  cout << "meanSnWest = " << meanSnWest << endl;
  cout << "     sigma = " << sigmaSnWest << endl;
  errEnv << "meanSnWest = " << meanSnWest << endl;
  errEnv << "sigma = " << sigmaSnWest << endl;

  double meanBi1West = 0.;
  for (int j=0; j<nBi1West; j++) {
    meanBi1West += resBi1West[j];
  }
  meanBi1West = meanBi1West / (double) nBi1West;

  double sigmaBi1West = 0.;
  for (int j=0; j<nBi1West; j++) {
    sigmaBi1West += (resBi1West[j] - meanBi1West)*(resBi1West[j] - meanBi1West);
  }
  sigmaBi1West = sigmaBi1West / (double) nBi1West;
  sigmaBi1West = sqrt( sigmaBi1West );

  cout << "meanBi1West = " << meanBi1West << endl;
  cout << "     sigma = " << sigmaBi1West << endl;
  errEnv << "meanBi1West = " << meanBi1West << endl;
  errEnv << "sigma = " << sigmaBi1West << endl;

  if (postReplayPass4) {
    double meanBi2West = 0.;
    for (int j=0; j<nBi2West; j++) {
      meanBi2West += resBi2West[j];
    }
    meanBi2West = meanBi2West / (double) nBi2West;
    
    double sigmaBi2West = 0.;
    for (int j=0; j<nBi2West; j++) {
      sigmaBi2West += (resBi2West[j] - meanBi2West)*(resBi2West[j] - meanBi2West);
    }
    sigmaBi2West = sigmaBi2West / (double) nBi2West;
    sigmaBi2West = sqrt( sigmaBi2West );
    
    cout << "meanBi2West = " << meanBi2West << endl;
    cout << "     sigma = " << sigmaBi2West << endl;
    errEnv << "meanBi2West = " << meanBi2West << endl;
    errEnv << "sigma = " << sigmaBi2West << endl;
  }
  //Calculate total mean and rms
  double meanCe = 0.;
  for (int j=0; j<nCeEast; j++) {
    meanCe += resCeEast[j];
  }
  for (int j=0; j<nCeWest; j++) {
    meanCe += resCeWest[j];
  }
  meanCe = meanCe / (double) (nCeEast+nCeWest);

  double sigmaCe = 0.;
  for (int j=0; j<nCeEast; j++) {
    sigmaCe += (resCeEast[j] - meanCe)*(resCeEast[j] - meanCe);
  }
  for (int j=0; j<nCeWest; j++) {
    sigmaCe += (resCeWest[j] - meanCe)*(resCeWest[j] - meanCe);
  }
  sigmaCe = sigmaCe / (double) (nCeEast+nCeWest);
  sigmaCe = sqrt( sigmaCe );

  cout << "meanCe = " << meanCe << endl;
  cout << "     sigma = " << sigmaCe << endl;
  errEnv << "meanCe = " << meanCe << endl;
  errEnv << "sigma = " << sigmaCe << endl;

  double meanIn = 0.;
  for (int j=0; j<nInEast; j++) {
    meanIn += resInEast[j];
  }
  for (int j=0; j<nInWest; j++) {
    meanIn += resInWest[j];
  }
  meanIn = meanIn / (double) (nInEast+nInWest);

  double sigmaIn = 0.;
  for (int j=0; j<nInEast; j++) {
    sigmaIn += (resInEast[j] - meanIn)*(resInEast[j] - meanIn);
  }
  for (int j=0; j<nInWest; j++) {
    sigmaIn += (resInWest[j] - meanIn)*(resInWest[j] - meanIn);
  }
  sigmaIn = sigmaIn / (double) (nInEast+nInWest);
  sigmaIn = sqrt( sigmaIn );

  cout << "meanIn = " << meanIn << endl;
  cout << "     sigma = " << sigmaIn << endl;
  errEnv << "meanIn = " << meanIn << endl;
  errEnv << "sigma = " << sigmaIn << endl;


  double meanSn = 0.;
  for (int j=0; j<nSnEast; j++) {
    meanSn += resSnEast[j];
  }
  for (int j=0; j<nSnWest; j++) {
    meanSn += resSnWest[j];
  }
  meanSn = meanSn / (double) (nSnEast+nSnWest);

  double sigmaSn = 0.;
  for (int j=0; j<nSnEast; j++) {
    sigmaSn += (resSnEast[j] - meanSn)*(resSnEast[j] - meanSn);
  }
  for (int j=0; j<nSnWest; j++) {
    sigmaSn += (resSnWest[j] - meanSn)*(resSnWest[j] - meanSn);
  }
  sigmaSn = sigmaSn / (double) (nSnEast+nSnWest);
  sigmaSn = sqrt( sigmaSn );

  cout << "meanSn = " << meanSn << endl;
  cout << "     sigma = " << sigmaSn << endl;
  errEnv << "meanSn = " << meanSn << endl;
  errEnv << "sigma = " << sigmaSn << endl;


  double meanBi1 = 0.;
  for (int j=0; j<nBi1East; j++) {
    meanBi1 += resBi1East[j];
  }
  for (int j=0; j<nBi1West; j++) {
    meanBi1 += resBi1West[j];
  }
  meanBi1 = meanBi1 / (double) (nBi1East+nBi1West);

  double sigmaBi1 = 0.;
  for (int j=0; j<nBi1East; j++) {
    sigmaBi1 += (resBi1East[j] - meanBi1)*(resBi1East[j] - meanBi1);
  }
  for (int j=0; j<nBi1West; j++) {
    sigmaBi1 += (resBi1West[j] - meanBi1)*(resBi1West[j] - meanBi1);
  }
  sigmaBi1 = sigmaBi1 / (double) (nBi1East+nBi1West);
  sigmaBi1 = sqrt( sigmaBi1 );

  cout << "meanBi1 = " << meanBi1 << endl;
  cout << "     sigma = " << sigmaBi1 << endl;
  errEnv << "meanBi1 = " << meanBi1 << endl;
  errEnv << "sigma = " << sigmaBi1 << endl;

  if (postReplayPass4) {
    double meanBi2 = 0.;
    for (int j=0; j<nBi2East; j++) {
      meanBi2 += resBi2East[j];
    }
    for (int j=0; j<nBi2West; j++) {
      meanBi2 += resBi2West[j];
    }
    meanBi2 = meanBi2 / (double) (nBi2East+nBi2West);
    
    double sigmaBi2 = 0.;
    for (int j=0; j<nBi2East; j++) {
      sigmaBi2 += (resBi2East[j] - meanBi2)*(resBi2East[j] - meanBi2);
    }
    for (int j=0; j<nBi2West; j++) {
      sigmaBi2 += (resBi2West[j] - meanBi2)*(resBi2West[j] - meanBi2);
    }
    sigmaBi2 = sigmaBi2 / (double) (nBi2East+nBi2West);
    sigmaBi2 = sqrt( sigmaBi2 );
    
    cout << "meanBi2 = " << meanBi2 << endl;
    cout << "     sigma = " << sigmaBi2 << endl;
    errEnv << "meanBi2 = " << meanBi2 << endl;
    errEnv << "sigma = " << sigmaBi2 << endl;
  }

  cout << endl << "Results of Gaussian Fits:\n";
  errEnv << endl << "Results of Gaussian Fits:\n";

  // Ce East
  c1 = new TCanvas("c1", "c1");
  c1->SetLogy(0);

  hisCeEast->SetXTitle("East Ce E_{Q} Error [keV]");
  hisCeEast->GetXaxis()->CenterTitle();
  hisCeEast->SetLineColor(1);
  hisCeEast->Draw();
  hisCeEast->Fit("gaus", "", "", -8.0, 8.0);
  cout << "meanCeEast = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanCeEast = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  //In East
  c2 = new TCanvas("c2", "c2");
  c2->SetLogy(0);

  hisInEast->SetXTitle("East In E_{Q} Error [keV]");
  hisInEast->GetXaxis()->CenterTitle();
  hisInEast->SetLineColor(1);
  hisInEast->Draw();
  hisInEast->Fit("gaus", "", "", -8.0, 8.0);
  cout << "meanInEast = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanInEast = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Sn East
  c3 = new TCanvas("c3", "c3");
  c3->SetLogy(0);

  hisSnEast->SetXTitle("East Sn E_{Q} Error [keV]");
  hisSnEast->GetXaxis()->CenterTitle();
  hisSnEast->SetLineColor(1);
  hisSnEast->Draw();
  hisSnEast->Fit("gaus", "", "", -25.0, 25.0);
  cout << "meanSnEast = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanSnEast = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Bi1 East
  c4 = new TCanvas("c4", "c4");
  c4->SetLogy(0);

  hisBi1East->SetXTitle("East Bi1 E_{Q} Error [keV]");
  hisBi1East->GetXaxis()->CenterTitle();
  hisBi1East->SetLineColor(1);
  hisBi1East->Draw();
  hisBi1East->Fit("gaus", "","", -46., 46.);
  cout << "meanBi1East = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanBi1East = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Bi2 East
  c5 = new TCanvas("c5", "c5");
  c5->SetLogy(0);

  hisBi2East->SetXTitle("East Bi2 E_{Q} Error [keV]");
  hisBi2East->GetXaxis()->CenterTitle();
  hisBi2East->SetLineColor(1);
  hisBi2East->Draw();
  hisBi2East->Fit("gaus", "","", -46., 46.);
  if (postReplayPass4) {
    cout << "meanBi2East = " << gaus->GetParameter(1) << endl;
    cout << "     sigma = " << gaus->GetParameter(2)  << endl;
    errEnv << "meanBi2East = " << gaus->GetParameter(1) << endl;
    errEnv << "sigma = " << gaus->GetParameter(2) << endl;
  }

  // Ce West
  c6 = new TCanvas("c6", "c6");
  c6->SetLogy(0);

  hisCeWest->SetXTitle("West Ce E_{Q} Error [keV]");
  hisCeWest->GetXaxis()->CenterTitle();
  hisCeWest->SetLineColor(1);
  hisCeWest->Draw();
  hisCeWest->Fit("gaus", "", "", -8., 8.);
  cout << "meanCeWest = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanCeWest = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // In West
  c7 = new TCanvas("c7", "c7");
  c7->SetLogy(0);

  hisInWest->SetXTitle("West In E_{Q} Error [keV]");
  hisInWest->GetXaxis()->CenterTitle();
  hisInWest->SetLineColor(1);
  hisInWest->Draw();
  hisInWest->Fit("gaus", "", "", -8., 8.);
  cout << "meanInWest = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanInWest = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;


  // Sn West
  c8 = new TCanvas("c8", "c8");
  c8->SetLogy(0);

  hisSnWest->SetXTitle("West Sn E_{Q} Error [keV]");
  hisSnWest->GetXaxis()->CenterTitle();
  hisSnWest->SetLineColor(1);
  hisSnWest->Draw();
  hisSnWest->Fit("gaus", "", "", -25., 25.);
  cout << "meanCeWest = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanCeWest = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Bi1 West
  c9 = new TCanvas("c9", "c9");
  c9->SetLogy(0);

  hisBi1West->SetXTitle("West Bi1 E_{Q} Error [keV]");
  hisBi1West->GetXaxis()->CenterTitle();
  hisBi1West->SetLineColor(1);
  hisBi1West->Draw();
  hisBi1West->Fit("gaus", "", "", -46., 46.);
  cout << "meanBi1West = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanBi1West = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Bi2 West
  c10 = new TCanvas("c10", "c10");
  c10->SetLogy(0);

  hisBi2West->SetXTitle("West Bi2 E_{Q} Error [keV]");
  hisBi2West->GetXaxis()->CenterTitle();
  hisBi2West->SetLineColor(1);
  hisBi2West->Draw();
  hisBi2West->Fit("gaus", "", "", -46., 46.);
  if (postReplayPass4) {
    cout << "meanBi2West = " << gaus->GetParameter(1) << endl;
    cout << "     sigma = " << gaus->GetParameter(2)  << endl;
    errEnv << "meanBi2West = " << gaus->GetParameter(1) << endl;
    errEnv << "sigma = " << gaus->GetParameter(2) << endl;
  }

  // Ce 
  c11= new TCanvas("c11", "c11");
  c11->SetLogy(0);

  hisCe->SetXTitle("Total Ce E_{Q} Error [keV]");
  hisCe->GetXaxis()->CenterTitle();
  hisCe->SetLineColor(1);
  hisCe->Draw();
  hisCe->Fit("gaus", "", "", -8.0, 8.0);
  cout << "meanCe = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanCe = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // In 
  c12= new TCanvas("c12", "c12");
  c12->SetLogy(0);

  hisIn->SetXTitle("Total In E_{Q} Error [keV]");
  hisIn->GetXaxis()->CenterTitle();
  hisIn->SetLineColor(1);
  hisIn->Draw();
  hisIn->Fit("gaus", "", "", -10.0, 10.0);
  cout << "meanIn = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanIn = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Sn 
  c13 = new TCanvas("c13", "c13");
  c13->SetLogy(0);

  hisSn->SetXTitle("Total Sn E_{Q} Error [keV]");
  hisSn->GetXaxis()->CenterTitle();
  hisSn->SetLineColor(1);
  hisSn->Draw();
  hisSn->Fit("gaus", "", "", -25.0, 25.0);
  cout << "meanSn = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanSn = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Bi1 
  c14 = new TCanvas("c14", "c14");
  c14->SetLogy(0);

  hisBi1->SetXTitle("Total Bi1 E_{Q} Error [keV]");
  hisBi1->GetXaxis()->CenterTitle();
  hisBi1->SetLineColor(1);
  hisBi1->Draw();
  hisBi1->Fit("gaus", "", "", -46., 46.);
  cout << "meanBi1 = " << gaus->GetParameter(1) << endl;
  cout << "     sigma = " << gaus->GetParameter(2)  << endl;
  errEnv << "meanBi1 = " << gaus->GetParameter(1) << endl;
  errEnv << "sigma = " << gaus->GetParameter(2) << endl;

  // Bi2 
  c15 = new TCanvas("c15", "c15");
  c15->SetLogy(0);

  hisBi2->SetXTitle("Total Bi2 E_{Q} Error [keV]");
  hisBi2->GetXaxis()->CenterTitle();
  hisBi2->SetLineColor(1);
  hisBi2->Draw();
  hisBi2->Fit("gaus", "", "", -46., 46.);
  if (postReplayPass4) {
    cout << "meanBi2 = " << gaus->GetParameter(1) << endl;
    cout << "     sigma = " << gaus->GetParameter(2)  << endl;
    errEnv << "meanBi2 = " << gaus->GetParameter(1) << endl;
    errEnv << "sigma = " << gaus->GetParameter(2) << endl;
  }

  errEnv.close();
}
void plotFrac(TList* HistList, TH1F* compT, std::string name, bool fracAll){

  gROOT->SetBatch();
  system("mkdir -p plots/ada/fracs");
  system("mkdir -p plots/grad/fracs");

  std::string bdt;
  TString str = compT->GetName();
  if (str.Contains("ada")) bdt="ada";
  if (str.Contains("grad")) bdt="grad";

  int nHists=HistList->GetEntries();
  TH1F *comp = linearBin(compT);
  TH1F *uandd[nHists];
  
  gROOT->SetStyle("Plain");
  gROOT->ForceStyle();
  gStyle->SetOptStat(0);
  TCanvas *canv = new TCanvas("","",700,700);
  
  canv->Divide(1,2,0.1,0.1);
  canv->cd(1);
  gPad->SetPad(0.01,0.3,0.99,0.99);
  gPad->SetBottomMargin(0.0);
  gPad->SetLeftMargin(0.1);
  comp->SetLineColor(1);
  comp->SetFillColor(kGray);
  comp->Draw("hist");
  comp->SetTitle(("Up, down and interpolated templates for "+bdt+" "+name).c_str());
  comp->GetYaxis()->SetRangeUser(0.0,((TH1F*)HistList->At(0))->GetMaximum()+0.5);
  comp->GetYaxis()->SetTitle("Events / bin");
  comp->GetXaxis()->SetTitle("Category");
  int mass;
  if (name=="syst120") mass=120;
  if (name=="syst135") mass=135;
  TLegend *leg = new TLegend(0.6,0.5,0.88,0.88);
  leg->SetLineColor(0);
  leg->SetFillColor(0);
  if (name=="syst120" || name=="syst135"){
    leg->AddEntry(comp,Form("True %d signal binned at %d",mass,mass),"f");
  }
  
  canv->cd(2);
  gPad->SetPad(0.01,0.01,0.99,0.3);
  gPad->SetTopMargin(0.0);
  gPad->SetBottomMargin(0.2);
  gPad->SetLeftMargin(0.1);
  TF1 *line = new TF1("line","0.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line->SetLineColor(kBlack);
  
  for (int i=0; i<nHists; i++){
    TH1F *temp = linearBin((TH1F*)HistList->At(i));
    temp->SetLineColor((i+1)*2);
    if (!fracAll && i==nHists-1) temp->SetLineColor(kBlack); 
    canv->cd(1);
    temp->DrawCopy("same e");
    uandd[i]= (TH1F*)temp->Clone();
    uandd[i]->Add(comp,-1);
    uandd[i]->Divide(temp);
    uandd[i]->Scale(-100.);
    //uandd[i]->Divide(comp);
    if (name=="syst120" || name=="syst135") {
      if (i==0) leg->AddEntry(uandd[i],Form("True %d signal binned at %d",mass+5,mass),"lep");
      if (i==1) leg->AddEntry(uandd[i],Form("True %d signal binned at %d",mass-5,mass),"lep");
      if (i==nHists-1) leg->AddEntry(uandd[i],Form("Interpolated %d signal",mass),"lep");
    }
    //uandd[i]->Scale(100.0);
    canv->cd(2);
    if (fracAll){
      if (i==0) uandd[i]->Draw("e");
      else {
        uandd[i]->Draw("same e");
        line->Draw("same");
      }
    }
    else {
      if (i==nHists-1) {
        uandd[i]->Draw("e");
        line->Draw("same");
      }
    }
    uandd[i]->SetTitle("");
    uandd[i]->GetYaxis()->SetLabelSize(0.08);
    uandd[i]->GetYaxis()->SetRangeUser(-50.,50.);
    uandd[i]->GetYaxis()->SetTitle("#frac{#Delta_{int}}{int} %");
    uandd[i]->GetYaxis()->SetTitleOffset(0.4);
    uandd[i]->GetYaxis()->SetTitleSize(0.08);
    uandd[i]->GetXaxis()->SetLabelSize(0.08);
    uandd[i]->GetXaxis()->SetTitle("BDT output");
    uandd[i]->GetXaxis()->SetTitleSize(0.08);
    canv->cd(1);
    if (name=="syst120" || name=="syst135") leg->Draw("same");
  }
  

  canv->Print(("plots/"+bdt+"/fracs/"+name+".png").c_str(),"png");
  delete canv;
  
  fracCalls++;
  
}
Example #17
0
void th2polyEurope(Int_t npoints=500000)
{
   Int_t i,j;
   Double_t lon1 = -25;
   Double_t lon2 =  35;
   Double_t lat1 =  34;
   Double_t lat2 =  72;
   Double_t R = (lat2-lat1)/(lon2-lon1);
   Int_t W    = 800;
   Int_t H    = (Int_t)(R*800);
   gStyle->SetTitleX(0.2);
   gStyle->SetStatX(0.28);
   gStyle->SetStatY(0.45);
   gStyle->SetStatW(0.15);

   // Canvas used to draw TH2Poly (the map)
   TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
   ce->ToggleEventStatus();
   ce->SetGridx();
   ce->SetGridy();

   // Real surfaces taken from Wikipedia.
   const Int_t nx = 36;
   // see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
   const char *countries[nx] = { "france",     "spain",  "sweden",  "germany",       "finland",
      "norway",     "poland", "italy",   "yugoslavia",    "united_kingdom",
      "romania",    "belarus","greece",  "czechoslovakia","bulgaria",
      "iceland",    "hungary","portugal","austria",       "ireland",
      "lithuania",  "latvia", "estonia", "denmark",       "netherlands",
      "switzerland","moldova","belgium", "albania",       "cyprus",
      "luxembourg", "andorra","malta",   "liechtenstein", "san_marino",
      "monaco" };
   Float_t surfaces[nx] = { 547030,        505580,   449964,      357021,        338145,
      324220,        312685,   301230,      255438,        244820,
      237500,        207600,   131940,      127711,        110910,
      103000,         93030,    89242,       83870,         70280,
      65200,         64589,    45226,       43094,         41526,
      41290,         33843,    30528,       28748,          9250,
      2586,           468,      316,         160,            61,
      2};

   TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
   for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
   h->LabelsDeflate();

   TFile::SetCacheFileDir(".");
   TFile *f;
   f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");

   if (!f) {
      printf("Cannot access europe.root. Is internet working ?\n");
      return;
   }

   TH2Poly *p = new TH2Poly(
             "Europe",
             "Europe (bin contents are normalized to the surfaces in km^{2})",
             lon1,lon2,lat1,lat2);
   p->GetXaxis()->SetNdivisions(520);
   p->GetXaxis()->SetTitle("longitude");
   p->GetYaxis()->SetTitle("latitude");

   p->SetContour(100);

   TMultiGraph *mg;
   TKey *key;
   TIter nextkey(gDirectory->GetListOfKeys());
   while ((key = (TKey*)nextkey())) {
      TObject *obj = key->ReadObj();
      if (obj->InheritsFrom("TMultiGraph")) {
         mg = (TMultiGraph*)obj;
         p->AddBin(mg);
      }
   }

   TRandom r;
   Double_t longitude, latitude;
   Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;

   gBenchmark->Start("Partitioning");
   p->ChangePartition(100, 100);
   gBenchmark->Show("Partitioning");

   // Fill TH2Poly according to a Mercator projection.
   gBenchmark->Start("Filling");
   for (i=0; i<npoints; i++) {
      longitude = r.Uniform(lon1,lon2);
      latitude  = r.Uniform(lat1,lat2);
      x         = longitude;
      y         = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
      p->Fill(x,y);
   }
   gBenchmark->Show("Filling");

   Int_t nbins = p->GetNumberOfBins();
   Double_t maximum = p->GetMaximum();


   // h2 contains the surfaces computed from TH2Poly.
   TH1F *h2 = (TH1F *)h->Clone("h2");
   h2->Reset();
   for (j=0; j<nx; j++) {
      for (i=0; i<nbins; i++) {
         if (strstr(countries[j],p->GetBinName(i+1))) {
            h2->Fill(countries[j],p->GetBinContent(i+1));
            h2->SetBinError(j, p->GetBinError(i+1));
         }
      }
   }

   // Normalize the TH2Poly bin contents to the real surfaces.
   Double_t scale = surfaces[0]/maximum;
   for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));

   gStyle->SetOptStat(1111);
   p->Draw("COLZ");

   TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
   c1->SetRightMargin(0.047);

   scale = h->GetMaximum()/h2->GetMaximum();

   h->SetStats(0);
   h->SetLineColor(kRed-3);
   h->SetLineWidth(2);
   h->SetMarkerStyle(20);
   h->SetMarkerColor(kBlue);
   h->SetMarkerSize(0.8);
   h->Draw("LP");
   h->GetXaxis()->SetLabelFont(42);
   h->GetXaxis()->SetLabelSize(0.03);
   h->GetYaxis()->SetLabelFont(42);

   h2->Scale(scale);
   Double_t scale2=TMath::Sqrt(scale);
   for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
   h2->Draw("E SAME");
   h2->SetMarkerStyle(20);
   h2->SetMarkerSize(0.8);

   TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
   leg->SetTextFont(42);
   leg->SetTextSize(0.025);
   leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
   leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
   leg->Draw();
   leg->Draw();

   Double_t wikiSum = h->Integral();
   Double_t polySum = h2->Integral();
   Double_t error = TMath::Abs(wikiSum-polySum)/wikiSum;
   printf("THPoly Europe surface estimation error wrt wikipedia = %f per cent when using %d points\n",100*error,npoints);
}
void plotSystFracs(TList* HistList, TH1F* compT, std::string name){

  gROOT->SetBatch();
  system("mkdir -p plots/ada/systs");
  system("mkdir -p plots/grad/systs");

  std::string bdt;
  TString str = compT->GetName();
  if (str.Contains("ada")) bdt="ada";
  if (str.Contains("grad")) bdt="grad";

  int nHists=HistList->GetEntries();
  TH1F *comp = linearBin(compT);
  
  gROOT->SetStyle("Plain");
  gROOT->ForceStyle();
  gStyle->SetOptStat(0);
  TCanvas *canv = new TCanvas("","",700,700);
  
  TLegend *leg = new TLegend(0.6,0.6,0.88,0.88);
  leg->SetLineColor(0);
  leg->SetFillColor(0);
  
  TF1 *line = new TF1("line","0.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line->SetLineColor(kBlack);
  TF1 *line1 = new TF1("line","10.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line1->SetLineColor(kGray+2);
  line1->SetLineStyle(2);
  TF1 *line2 = new TF1("line","-10.0",0.,comp->GetBinLowEdge(comp->GetNbinsX()+1));
  line2->SetLineColor(kGray+2);
  line2->SetLineStyle(2);
  
  int colors[10] = {kBlue,kMagenta,kGreen,kCyan,kRed,kBlue+3,kOrange+1,kSpring-1,kMagenta+3,kGreen+3};
  int color=0;
  for (int i=0; i<nHists; i++){
    TH1F *systHist = linearBin((TH1F*)HistList->At(i));
    systHist->Add(comp,-1);
    systHist->Divide(comp);
    systHist->Scale(100.);
    std::string systStr = systHist->GetName();
    int ind = systStr.rfind("cat0");
    std::string systName = systStr.substr(ind+5,systStr.size());
    systHist->SetLineColor(colors[color]);
    systHist->SetTitle(Form("%s",name.c_str()));
    systHist->GetYaxis()->SetTitle("Difference over nominal %");
    systHist->GetYaxis()->SetTitleOffset(1.4);
    systHist->GetXaxis()->SetTitle("BDT output");
    systHist->GetYaxis()->SetRangeUser(-100.,250);
    if (int(systName.find("Up"))>0){
      systHist->SetLineStyle(1);
      systName = systName.substr(0,systName.rfind("Up"));
      leg->AddEntry(systHist,systName.c_str(),"l");
      color++;
    }
    else if (int(systName.find("Down"))>0){
      systHist->SetLineStyle(2);
      systName = systName.substr(0,systName.rfind("Down"));
    }
    if (i==0) systHist->DrawCopy("hist");
    else systHist->DrawCopy("same hist");
  }
  leg->Draw("same");
  line->Draw("same");
  line1->Draw("same");
  line2->Draw("same");
  canv->Print(("plots/"+bdt+"/systs/"+name+".png").c_str(),"png");
  
  delete canv;
  
  systCalls++;
  
}
void plotSuperMelaProjections(TString drawString="(p0plus_VAJHU*p0plus_m4l)/((p0plus_VAJHU*p0plus_m4l)+(bkg_VAMCFMNorm*bkg_m4l))",
			      TString cutString="ZZMass>106.&&ZZMass<141."){

  gROOT->ProcessLine(".L ~/tdrstyle.C");
  setTDRStyle();

  TCanvas* can = new TCanvas("can","can",500,500);

  gStyle->SetOptStat(0);

  TChain* qqZZ_8 = new TChain("SelectedTree");
  qqZZ_8->Add(inputDir+"PRODFSR_8TeV/4mu/HZZ4lTree_ZZTo*.root");
  qqZZ_8->Add(inputDir+"PRODFSR_8TeV/4e/HZZ4lTree_ZZTo*.root");
  qqZZ_8->Add(inputDir+"PRODFSR_8TeV/2mu2e/HZZ4lTree_ZZTo*.root");
  TChain* qqZZ_7 = new TChain("SelectedTree");
  qqZZ_7->Add(inputDir+"PRODFSR/4mu/HZZ4lTree_ZZTo*.root");
  qqZZ_7->Add(inputDir+"PRODFSR/4e/HZZ4lTree_ZZTo*.root");
  qqZZ_7->Add(inputDir+"PRODFSR/2mu2e/HZZ4lTree_ZZTo*.root");

  TChain* SM_8 = new TChain("SelectedTree");
  SM_8->Add(inputDir+"PRODFSR_8TeV/4mu/HZZ4lTree_H126.root");
  SM_8->Add(inputDir+"PRODFSR_8TeV/4e/HZZ4lTree_H126.root");
  SM_8->Add(inputDir+"PRODFSR_8TeV/2mu2e/HZZ4lTree_H126.root");
  TChain* SM_7 = new TChain("SelectedTree");
  SM_7->Add(inputDir+"PRODFSR/4mu/HZZ4lTree_H126.root");
  SM_7->Add(inputDir+"PRODFSR/4e/HZZ4lTree_H126.root");
  SM_7->Add(inputDir+"PRODFSR/2mu2e/HZZ4lTree_H126.root");

  //TChain* ZX = new TChain("SelectedTree");

  TChain* data = new TChain("SelectedTree");
  data->Add(inputDir+"PRODFSR_8TeV/data/HZZ4lTree_DoubleEle.root");
  data->Add(inputDir+"PRODFSR_8TeV/data/HZZ4lTree_DoubleMu.root");
  data->Add(inputDir+"PRODFSR_8TeV/data/HZZ4lTree_DoubleOr.root");
  data->Add(inputDir+"PRODFSR/data/HZZ4lTree_DoubleEle.root");
  data->Add(inputDir+"PRODFSR/data/HZZ4lTree_DoubleMu.root");
  data->Add(inputDir+"PRODFSR/data/HZZ4lTree_DoubleOr.root");

  data->Draw(drawString+">>datahisto(30,0,1)",cutString);
  TH1F* datahisto = (TH1F*) gDirectory->Get("datahisto");

  TChain* PS_8 = new TChain("SelectedTree");
  PS_8->Add(JHUinputDir+"JHU_8TeV/4mu/HZZ4lTree_jhuGenV2PseH126.root");
  PS_8->Add(JHUinputDir+"JHU_8TeV/4e/HZZ4lTree_jhuGenV2PseH126.root");
  PS_8->Add(JHUinputDir+"JHU_8TeV/2mu2e/HZZ4lTree_jhuGenV2PseH126.root");
  TChain* PS_7 = new TChain("SelectedTree");
  PS_7->Add(JHUinputDir+"JHU/4mu/HZZ4lTree_jhuGenV2PseH126.root");
  PS_7->Add(JHUinputDir+"JHU/4e/HZZ4lTree_jhuGenV2PseH126.root");
  PS_7->Add(JHUinputDir+"JHU/2mu2e/HZZ4lTree_jhuGenV2PseH126.root");
  
  qqZZ_7->Draw(drawString+">>qqZZ_7histo(30,0,1)","5.051*MC_weight*("+cutString+")");
  TH1F* qqZZ_7histo = (TH1F*) gDirectory->Get("qqZZ_7histo");

  qqZZ_8->Draw(drawString+">>qqZZ_8histo(30,0,1)","19.6*MC_weight*("+cutString+")");
  TH1F* qqZZ_8histo = (TH1F*) gDirectory->Get("qqZZ_8histo");

  SM_7->Draw(drawString+">>SM_7histo(30,0,1)","5.051*MC_weight*("+cutString+")");
  TH1F* SM_7histo = (TH1F*) gDirectory->Get("SM_7histo");

  SM_8->Draw(drawString+">>SM_8histo(30,0,1)","19.6*MC_weight*("+cutString+")");
  TH1F* SM_8histo = (TH1F*) gDirectory->Get("SM_8histo");

  PS_8->Draw(drawString+">>PS_8histo(30,0,1)","19.6*MC_weight*("+cutString+")");
  TH1F* PS_8histo = (TH1F*) gDirectory->Get("PS_8histo");

  PS_7->Draw(drawString+">>PS_7histo(30,0,1)","5.051*MC_weight*("+cutString+")");
  TH1F* PS_7histo = (TH1F*) gDirectory->Get("PS_7histo");
 
  //=========================
	
  //datahisto->SetBinErrorOption(TH1::kPoisson);
  datahisto->SetMarkerStyle(20);
  datahisto->SetMarkerSize(1.1);
	
  TH1F* qqZZhisto = new TH1F(*qqZZ_7histo);
  qqZZhisto->Add(qqZZ_8histo);
  cout<<qqZZhisto->Integral()<<endl;
  qqZZhisto->SetLineColor(1);
  qqZZhisto->SetLineWidth(2);
  qqZZhisto->SetFillColor(kAzure-9);

  TH1F* ZXhisto = new TH1F(*qqZZhisto);
  ZXhisto->Scale(ZXnorm/ZXhisto->Integral());
  ZXhisto->SetLineColor(1);
  ZXhisto->SetLineWidth(2);
  ZXhisto->SetFillColor(kGreen-5);

  TH1F* SMhisto = new TH1F(*SM_7histo);
  SMhisto->Add(SM_8histo);
  SMhisto->SetLineColor(kOrange+10);
  SMhisto->SetLineWidth(2);
  SMhisto->SetFillColor(0);

  TH1F* PShisto = new TH1F(*PS_7histo);
  PShisto->Add(PS_8histo);
  PShisto->SetLineColor(kRed+1);
  PShisto->SetLineWidth(2);
  PShisto->SetFillColor(0);
  //==========================

  datahisto->GetXaxis()->SetTitle("#it{D}_{bkg}");
  datahisto->GetYaxis()->SetTitle("Events");

  THStack* stack = new THStack("stack","stack");
  stack->Add(ZXhisto);
  stack->Add(qqZZhisto);
  stack->Add(SMhisto);
  stack->Draw("");
  stack->GetXaxis()->SetTitle("#it{D}_{bkg}");
  stack->GetYaxis()->SetTitle("Events");  

  if(plotData){
    datahisto->SetMaximum(20);
    datahisto->Draw("E1");
    stack->Draw("SAME");
    datahisto->Draw("E1same");
    datahisto->Draw("SAMEp");
  }else{
    stack->Draw();
  }

  // --------------- legend ----------------

  TLegend* leg = new TLegend(.3,.65,.65,.9);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);

  if(plotData) leg->AddEntry(datahisto,"data","p");
  leg->AddEntry(SMhisto,"0^{+}, m_{H}=126 GeV","l");
  leg->AddEntry(qqZZhisto,"ZZ/Z#gamma^{*}","f");
  leg->AddEntry(ZXhisto,"Z+X","f");

  leg->Draw();

  if(plotData) datahisto->Draw("E1same");
  gPad->RedrawAxis();

  // -------- plot header --------------

  TPaveText *pt = new TPaveText(0.1577181,0.9562937,0.9580537,0.9947552,"brNDC");
  pt->SetBorderSize(0);
  pt->SetTextAlign(12);
  pt->SetFillStyle(0);
  pt->SetTextFont(42);
  pt->SetTextSize(0.03);
  TText *text = pt->AddText(0.01,0.5,"CMS preliminary");
  text = pt->AddText(0.3,0.6,"#sqrt{s} = 7 TeV, L = 5.1 fb^{-1}  #sqrt{s} = 8 TeV, L = 19.6 fb^{-1}");
  pt->Draw();   

  // ---------- save ----------
  
  can->SaveAs("superMELAproj.png");
  can->SaveAs("superMELAproj.eps");
  can->SaveAs("superMELAproj.root");
  
}
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;
}
Example #21
0
void alicePlots(){
    
    TFile* alice = new TFile("~/Downloads/HEPData-ins1288320-v1-root.root");
    alice->cd("Table 16");
    TGraph* aliceData = Graph1D_y1;
    TH1F* hist = Hist1D_y1;
    TH1F* stat = Hist1D_y1_e1;
    TH1F* syst = Hist1D_y1_e2;
    TGraphAsymmErrors* graph2 = (TGraphAsymmErrors*)aliceData->Clone("graph2");

    Int_t numPts = aliceData->GetN();
    Double_t x, y;
    for(int i = 0; i<numPts; i++){
        aliceData->GetPoint(i, x, y);
        aliceData->SetPoint(i, x, (y - 0.89581));
        graph2->SetPoint(i, x, (y- 0.89581));
        hist->SetBinContent(i+1, hist->GetBinContent(i+1) - 0.89581);
        hist->SetBinError(i+1, stat->GetBinContent(i+1));
        graph2->SetPointEXhigh(i, 0.1);
        graph2->SetPointEXlow(i, 0.1);
    }

    graph2->SetLineColor(kBlue-10);
    graph2->SetLineWidth(2);
    graph2->SetMarkerColor(kBlue-10);
    graph2->SetFillColor(kBlue-10);
    hist->SetLineColor(kBlue-2);
    hist->SetLineWidth(2);

    aliceData->SetTitle("");
    aliceData->GetYaxis()->SetTitle("Mass - Vacuum Mass (GeV/c^{2})");
    aliceData->GetYaxis()->SetTitleSize(0.06);
    aliceData->GetYaxis()->SetLabelSize(0.04);
    aliceData->GetYaxis()->SetTitleOffset(1.65);
    aliceData->GetYaxis()->SetTitleFont(42);
    aliceData->GetYaxis()->SetLabelFont(42);
    aliceData->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    aliceData->GetXaxis()->SetTitleSize(0.06);
    aliceData->GetXaxis()->SetLabelSize(0.05);
    aliceData->GetXaxis()->SetTitleFont(42);
    aliceData->GetXaxis()->SetLabelFont(42);
    aliceData->SetMarkerStyle(29);
    aliceData->SetMarkerSize(2.5);
    aliceData->SetMarkerColor(kBlue-2);
    aliceData->SetLineColor(kBlue-2);

    aliceData->GetYaxis()->SetRangeUser(-0.02, 0.015);
    aliceData->GetXaxis()->SetRangeUser(0, 5);

    TFile* phsd = new TFile("~/utaustin/resonancefits/finalplotting/20170721_KKbarAdded2_fixedwidth42_recon_pf100_scaled_error05.root");
    TH1D* mass = phsd->Get("kstar0mass");
    mass->SetName("mass");
    mass->SetMarkerStyle(26);
    mass->SetMarkerSize(2.5);
    mass->SetMarkerColor(2);
    mass->SetLineColor(2);

    TF1* line = new TF1("line", "[0]", 0.0, 5.0);
    line->SetParameter(0, 0.0);
    line->SetLineColor(1);
    line->SetLineStyle(7);
    line->SetLineWidth(3);

    for(int j = 0; j<mass->GetNbinsX(); j++){
        mass->SetBinContent(j+1, (mass->GetBinContent(j+1) - 0.892));
    }


    TFile* phsd2 = new TFile("~/utaustin/resonancefits/finalplotting/20170616_KKbarAdded2_fixedwidth_recon_pf100_scaled_error05.root");
    TH1D* mass2 = phsd2->Get("kstar0mass");
    mass2->SetName("mass2");
    mass2->SetMarkerStyle(22);
    mass2->SetMarkerSize(2.5);
    mass2->SetMarkerColor(2);
    mass2->SetLineColor(2);
    for(int j = 0; j<mass2->GetNbinsX(); j++){
        mass2->SetBinContent(j+1, (mass2->GetBinContent(j+1) - 0.892));
    }



    TExec *exec1 = new TExec("exec1", "gStyle->SetErrorX(0.1)");
    TExec *exec2 = new TExec("exec2", "gStyle->SetErrorX(0.5)");
    
    TCanvas *c = new TCanvas ("c", "c", 50, 50, 650, 600);
    c->cd()->SetMargin(0.1997, 0.0369, 0.1396, 0.0681);
    aliceData->Draw("APX");
    //exec1->Draw();
    graph2->Draw("SAME P2");
    //exec2->Draw();
    hist->Draw("SAME E1");
    line->Draw("SAME");
    mass2->Draw("SAME P E1");
    mass->Draw("SAME P E1");
    aliceData->Draw("SAME PX");
    

    TLegend* legend = new TLegend(0.5836, 0.1815, 0.9489, 0.3438);
    legend->SetMargin(0.2);
    legend->SetTextSizePixels(20);
    legend->AddEntry(aliceData, "ALICE data, 0-20%", "p");
    legend->AddEntry(mass2, "Fit IV to PHSD: w in-med", "p");
    legend->AddEntry(mass, "Fit IV to PHSD: w/o in-med", "p");
    legend->Draw("SAME"); 
  
    TPaveText* text = new TPaveText(0.2554, 0.7243, 0.6006, 0.9162, "NDC");
    text->AddText("(K*^{0} + #bar{K}*^{0})");
    text->AddText("Pb-Pb #sqrt{s_{NN}} = 2.76 TeV");
    text->GetLine(0)->SetTextSizePixels(36);
    text->GetLine(1)->SetTextSizePixels(24);
    text->SetTextFont(42);
    text->SetBorderSize(0);
    text->SetFillStyle(0);
    text->Draw();
}
Example #22
0
void draw_TEM_MEC(int selection = 1, int choice = 0, bool poster = false, double normalised = false) {
  
  // choice = 0    Track Range
  // choice = 1    CosTheta
  // choice = 2    Phi
  
  
  const double BASELINE_POT = 2.300468e+20;
  const double MEC_POT      = 2.075599e+20;
  const double TEM_POT      = 2.317981e+20;
  
  const double NOMINAL_POT = 2.2e20;
  
  
  const Color_t kTotalMCColor = kRed;
  const Color_t kTotalMCErrorBandColor = kRed-10;
  const Color_t kNueSignalColor = kViolet-6;
  const Color_t kNCBackgroundColor = kBlue;
  const Color_t kBeamNueBackgroundColor = kMagenta;
  const Color_t kNumuBackgroundColor = kGreen+2;
  const Color_t kNormalHierarchyColor = kBlue;
  const Color_t kInvertedHierarchyColor = kRed;
  const Style_t k90PercentConfidenceStyle = kSolid;
  const Style_t k68PercentConfidenceStyle = 7; ///< Dashed
  
  // for Selection I
  TFile* file = new TFile("./histograms_TEM_MEC_trkrange_costheta_phi.root");
  
  // for Selection II
  TFile* fileOriginal = new TFile("./MCOriginalnew.root");
  TFile* fileTEM = new TFile("./MCTEMnew.root");
  TFile* fileMEC = new TFile("./MCMECnew.root");
  
  TH1F *histoPmu, *histoPmu_TEM, *histoPmu_MEC;
  
  if (selection == 1) {
  if (choice == 0) {
    file->GetObject("Track RangeMC Prodgenie BNB Nu Cosmic",     histoPmu);
    file->GetObject("Track RangeMC Prodgenie BNB Nu Cosmic TEM", histoPmu_TEM);
    file->GetObject("Track RangeMC Prodgenie BNB Nu Cosmic MEC", histoPmu_MEC);
  } else if (choice == 1) {
    file->GetObject("cos#theta-AngleMC Prodgenie BNB Nu Cosmic",     histoPmu);
    file->GetObject("cos#theta-AngleMC Prodgenie BNB Nu Cosmic TEM", histoPmu_TEM);
    file->GetObject("cos#theta-AngleMC Prodgenie BNB Nu Cosmic MEC", histoPmu_MEC);
  } else if (choice == 2) {
    file->GetObject("#phi-AngleMC Prodgenie BNB Nu Cosmic",     histoPmu);
    file->GetObject("#phi-AngleMC Prodgenie BNB Nu Cosmic TEM", histoPmu_TEM);
    file->GetObject("#phi-AngleMC Prodgenie BNB Nu Cosmic MEC", histoPmu_MEC);
  } else
    cout << "Not a valid choice." << endl;
  } else if (selection == 2) {
    if (choice == 0) {
      fileOriginal->GetObject("SelectedFinalTrackLengthAll",     histoPmu);
      fileTEM->GetObject("SelectedFinalTrackLengthAll", histoPmu_TEM);
      fileMEC->GetObject("SelectedFinalTrackLengthAll", histoPmu_MEC);
    } else if (choice == 1) {
      fileOriginal->GetObject("SelectedFinalTrackCorrectedCosZAll",     histoPmu);
      fileTEM->GetObject("SelectedFinalTrackCorrectedCosZAll", histoPmu_TEM);
      fileMEC->GetObject("SelectedFinalTrackCorrectedCosZAll", histoPmu_MEC);
    } else if (choice == 2) {
      fileOriginal->GetObject("SelectedFinalTrackCorrectedPhiAll",     histoPmu);
      fileTEM->GetObject("SelectedFinalTrackCorrectedPhiAll", histoPmu_TEM);
      fileMEC->GetObject("SelectedFinalTrackCorrectedPhiAll", histoPmu_MEC);
    } else
      cout << "Not a valid choice." << endl;
  } else
    cout << "Not a valid choice." << endl;

    
    
  
  histoPmu->Sumw2();
  histoPmu_TEM->Sumw2();
  histoPmu_MEC->Sumw2();
  
  histoPmu->Scale(NOMINAL_POT/BASELINE_POT);
  histoPmu_TEM->Scale(NOMINAL_POT/TEM_POT);
  histoPmu_MEC->Scale(NOMINAL_POT/MEC_POT);
  
  
  
  
  
   
   double histoPmu_Int = histoPmu->Integral();
   double histoPmu_TEM_Int = histoPmu_TEM->Integral();
   double histoPmu_MEC_Int = histoPmu_MEC->Integral();
   
   
   if (normalised) {
   histoPmu->Scale(1./histoPmu_Int);
   histoPmu_TEM->Scale(1./histoPmu_TEM_Int);
   histoPmu_MEC->Scale(1./histoPmu_MEC_Int);
   }
   
   // Calculate integrals
   cout << "Integral histoPmu:    " << histoPmu->Integral() << endl;
   cout << "Integral histoPmu_TEM: " << histoPmu_TEM->Integral() << endl;
   cout << "Integral histoPmu_MEC: " << histoPmu_MEC->Integral() << endl;
   
   cout << "Difference w.r.t. histoPmu (%):" << endl;
   cout << "histoPmu_TEM: " << (histoPmu_TEM->Integral()-histoPmu->Integral())/(histoPmu->Integral())*100. << endl;
   cout << "histoPmu_MEC: " << (histoPmu_MEC->Integral()-histoPmu->Integral())/(histoPmu->Integral())*100. << endl;
  
  cout << endl << endl << "Difference w.r.t. histoPmu (%) -- bin by bin -- TEM" << endl;
  for (int i = 0; i < histoPmu->GetNbinsX(); i++) {
    cout << "Bin: " << i << "   " << (histoPmu_TEM->GetBinContent(i)-histoPmu->GetBinContent(i))/(histoPmu->GetBinContent(i))*100. << endl;
  }
  
  cout << endl << endl << "Difference w.r.t. histoPmu (%) -- bin by bin -- MEC" << endl;
  for (int i = 0; i < histoPmu->GetNbinsX(); i++) {
    cout << "Bin: " << i << "   " << (histoPmu_MEC->GetBinContent(i)-histoPmu->GetBinContent(i))/(histoPmu->GetBinContent(i))*100. << endl;
  }
  
  
  
  
  // Define the Canvas
  TCanvas *c;
  if (!poster) c = new TCanvas("c", "canvas", 800, 800);
  if (poster)  c = new TCanvas("c", "canvas", 0,45,1164,907);//("c", "canvas", 0,45,1200,690); the commented one was used for Neutrino2016, the non-commented one for the STFC Summer School
  //c->SetFillStyle(4000);      // Transparent
  //c->SetFrameFillStyle(4000); // Transparent
  
  
  
  // Upper plot will be in pad1
  TPad *pad1 = new TPad("pad1", "pad1", 0, 0.25, 1, 1.0);
  pad1->SetRightMargin(0.05);
  //pad1->SetFillStyle(4000);       // Transparent
  //pad1->SetFrameFillStyle(4000);  // Transparent
  pad1->SetBottomMargin(0);         // Upper and lower plot are joined
  pad1->SetGridx();                 // Vertical grid
  pad1->Draw();                     // Draw the upper pad: pad1
  pad1->cd();                       // pad1 becomes the current pad
  histoPmu_TEM->SetMinimum(0.0001); // Otherwise 0 label overlaps
  histoPmu_MEC->SetMinimum(0.0001); // Otherwise 0 label overlaps
  histoPmu->SetMinimum(0.0001);     // Otherwise 0 label overlaps
  histoPmu_TEM->SetStats(0);        // No statistics on upper plot
  histoPmu_MEC->SetStats(0);        // No statistics on upper plot
  histoPmu->SetStats(0);            // No statistics on upper plot
  if (choice == 0) histoPmu_TEM->GetXaxis()->SetRangeUser(0., 700.);
  if (choice == 0 && selection == 2) histoPmu_TEM->GetYaxis()->SetRangeUser(0.0001, 5500);
  if (choice == 1) histoPmu_TEM->GetXaxis()->SetRangeUser(0., 1.);
  //if (choice == 1 && selection == 2) histoPmu_TEM->GetXaxis()->SetRangeUser(-1., 1.);
  if (choice == 1 && selection == 1) histoPmu_TEM->GetYaxis()->SetRangeUser(0.0001, 4500.);
  if (choice == 1 && selection == 2) histoPmu_TEM->GetYaxis()->SetRangeUser(0.0001, 5500.);
  if (choice == 2 && selection == 1) histoPmu_TEM->GetXaxis()->SetRangeUser(-TMath::Pi(), TMath::Pi());
  if (choice == 2 && selection == 2) histoPmu_TEM->GetXaxis()->SetRangeUser(-3., 3.);
  if (choice == 2 && selection == 1) histoPmu_TEM->GetYaxis()->SetRangeUser(240, 650.);
  if (choice == 2 && selection == 2) histoPmu_TEM->GetYaxis()->SetRangeUser(300, 1500.);

  
  histoPmu_TEM->Draw("E2");         // Draw h1
  
  TH1F * test2 = (TH1F*)histoPmu_TEM->Clone("test2");
  test2->Draw("same histo");
  test2->SetLineColor(kBlue);

  histoPmu_MEC->Draw("same E2");    // Draw h2 on top of h1
  
  TH1F * test3 = (TH1F*)histoPmu_MEC->Clone("test3");
  test3->Draw("same histo");
  test3->SetLineColor(kGreen+2);

  histoPmu->Draw("same E2");        // Draw h3 on top of h1
  
  TH1F * test = (TH1F*)histoPmu->Clone("test");
  test->Draw("same histo");
  test->SetLineColor(kTotalMCColor);
  

  
  histoPmu_TEM->GetYaxis()->SetTitle("Selected Events");
  histoPmu_TEM->SetTitle("");
  
  if (choice == 1 && selection == 1) histoPmu_TEM->GetXaxis()->SetTitle("cos#theta");
  
  if (choice == 0 && selection == 2) histoPmu_TEM->GetXaxis()->SetTitle("Track Length [cm]");
  if (choice == 1 && selection == 2) histoPmu_TEM->GetXaxis()->SetTitle("cos#theta");
  if (choice == 2 && selection == 2) histoPmu_TEM->GetXaxis()->SetTitle("#phi angle [rad]");
  
  uBooNESimulation_2();
  
  // TLatex
  double x = 0.89;//0.839599,0.52
  double y = 0.47;
  double size = 25;
  int color = 1;
  int font = 43;
  int align = 32;
  TLatex *latex;
  if(selection == 1) latex = new TLatex(x, y, "#splitline{All events passing}{Selection I}");
  if(selection == 2) latex = new TLatex(x, y, "#splitline{All events passing}{Selection II}");
  latex->SetNDC();
  latex->SetTextSize(size);
  latex->SetTextColor(color);
  latex->SetTextFont(font);
  latex->SetTextAlign(align);
  latex->Draw();

  
  // Do not draw the Y axis label on the upper plot and redraw a small
  // axis instead, in order to avoid the first label (0) to be clipped.
  //histoPmu->GetYaxis()->SetLabelSize(0.);
  //TGaxis *axis = new TGaxis( -5, 20, -5, 220, 20,220,510,"");
  //axis->SetLabelFont(43); // Absolute font size in pixel (precision 3)
  //axis->SetLabelSize(15);
  //axis->Draw();
  
  // Legend for the upper plot
  leg = new TLegend(0.6541353,0.5750538,0.9135338,0.8451613,NULL,"brNDC");//0.65,0.6,.85,0.87);
  leg->SetTextFont(42);
  leg->SetBorderSize(0);
  //leg->SetFillStyle(0);  // Transparent
  //leg->SetHeader("");
  //leg->SetTextFont(42);
  leg->AddEntry(histoPmu, "Baseline");
  leg->AddEntry(histoPmu_TEM, "ESF+TEM");
  leg->AddEntry(histoPmu_MEC, "MEC");
  leg->Draw();
  
  
  
  /*
  TPad *padImage = new TPad("padImage", "padImage", 0.8, 0.9, 0.9, 1.0);
  padImage->Draw();                     // Draw the upper pad: pad1
  padImage->cd();
  
  TImage *img = TImage::Open("logo.png");
  
  img->SetConstRatio(0);
  img->SetImageQuality(TAttImage::kImgBest);
  
  img->Draw("xxx");
  img->SetEditable(kTRUE);
   */
  
  
  
  
  // lower plot will be in pad
  c->cd();          // Go back to the main canvas before defining pad2
  TPad *pad2 = new TPad("pad2", "pad2", 0, 0.005, 1, 0.25);
  //pad2->SetFrameFillStyle(4000); // Transparent
  //pad2->SetFillStyle(4000); // Transparent
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(0.3);
  if (poster)   pad2->SetBottomMargin(0.4);         // Leave some space for the X axis title
  pad2->SetRightMargin(0.05);
  pad2->SetGridx(); // vertical grid
  //pad2->SetGridy(); // orizontal grid
  pad2->Draw();
  pad2->cd();       // pad2 becomes the current pad
  
  // Define the first ratio plot
  TH1F *ratio_TEM = (TH1F*)histoPmu_TEM->Clone("ratio_TEM");
  ratio_TEM->SetMinimum(0.4);  // Define Y ..
  ratio_TEM->SetMaximum(2.1); // .. range
  ratio_TEM->Sumw2();
  ratio_TEM->SetStats(0);      // No statistics on lower plot
  ratio_TEM->Divide(histoPmu);
  ratio_TEM->SetLineWidth(2);
  ratio_TEM->SetLineColor(kBlue);
  if (choice == 0) ratio_TEM->GetXaxis()->SetRangeUser(0., 700.);
  if (choice == 1) ratio_TEM->GetXaxis()->SetRangeUser(0., 1.);
  //if (choice == 1 && selection == 2) ratio_TEM->GetXaxis()->SetRangeUser(-1., 1.);
  if (choice == 2 && selection == 1) ratio_TEM->GetXaxis()->SetRangeUser(-TMath::Pi(), TMath::Pi());
  if (choice == 2 && selection == 2) ratio_TEM->GetXaxis()->SetRangeUser(-3., 3.);

  ratio_TEM->Draw("E2");       // Draw the ratio plot
  
  TH1F * test4 = (TH1F*)ratio_TEM->Clone("test4");
  test4->Draw("same histo");
  test4->SetLineColor(kBlue);
  
  ratio_TEM->SetFillColor(38);
  
  
  // Define the second ratio plot
  TH1F *ratio_MEC = (TH1F*)histoPmu_MEC->Clone("ratio_MEC");
  //ratio_MEC->SetMinimum(0.8);  // Define Y ..
  //ratio_MEC->SetMaximum(1.2); // .. range
  ratio_MEC->Sumw2();
  ratio_MEC->SetStats(0);      // No statistics on lower plot
  ratio_MEC->Divide(histoPmu);
  ratio_MEC->SetLineWidth(2);
  ratio_MEC->SetLineColor(kGreen+2);
  ratio_MEC->Draw("E2 same");       // Draw the ratio plot
  
  TH1F * test5 = (TH1F*)ratio_MEC->Clone("test5");
  test5->Draw("same histo");
  test5->SetLineColor(kGreen+2);
  
  ratio_MEC->SetFillColor(29);
  
  
  
  
  
  
  //**********************
  //
  // Settings
  //
  //**********************
  
  // h1 settings
  histoPmu->SetLineColor(kRed);
  histoPmu->SetLineWidth(2);
  histoPmu->SetFillColor(kTotalMCErrorBandColor);
  if(choice == 2) histoPmu->SetFillColorAlpha(kTotalMCErrorBandColor, 0.35);//histoPmu->SetFillStyle(3001);
  
  // Y axis h1 plot settings
  histoPmu_MEC->GetYaxis()->CenterTitle();
  histoPmu_MEC->GetYaxis()->SetTitleSize(35);
  histoPmu_MEC->GetYaxis()->SetTitleFont(43);
  histoPmu_MEC->GetYaxis()->SetTitleOffset(1.14);
  
  // h2 settings
  histoPmu_TEM->SetLineColor(kBlue);
  histoPmu_TEM->SetLineWidth(2);
  histoPmu_TEM->SetFillColor(38);
  histoPmu_TEM->GetYaxis()->CenterTitle();
  histoPmu_TEM->GetYaxis()->SetTitleSize(35);
  histoPmu_TEM->GetYaxis()->SetTitleFont(43);
  histoPmu_TEM->GetYaxis()->SetTitleOffset(1.14);
  //histoPmu_TEM->SetFillStyle(3001);
  
  
  // h3 settings
  histoPmu_MEC->SetLineColor(kGreen+2);
  histoPmu_MEC->SetLineWidth(2);
  //histoPmu_MEC->SetFillColor(29);
  //histoPmu_MEC->SetFillStyle(3001);
  histoPmu_MEC->SetFillColorAlpha(29, 0.60);
  
  // Ratio plot (ratio_TEM) settings
  ratio_TEM->SetTitle(""); // Remove the ratio title
  
  // Y axis ratio plot settings
  ratio_TEM->GetYaxis()->SetTitle("Ratio");
  ratio_TEM->GetYaxis()->CenterTitle();
  ratio_TEM->GetYaxis()->SetNdivisions(505);
  ratio_TEM->GetYaxis()->SetTitleSize(35);
  ratio_TEM->GetYaxis()->SetTitleFont(43);
  ratio_TEM->GetYaxis()->SetTitleOffset(.75);
  ratio_TEM->GetYaxis()->SetLabelFont(43); // Absolute font size in pixel (precision 3)
  ratio_TEM->GetYaxis()->SetLabelSize(15);
  
  // X axis ratio plot settings
  ratio_TEM->GetXaxis()->CenterTitle();
  ratio_TEM->GetXaxis()->SetTitleSize(35);
  ratio_TEM->GetXaxis()->SetTitleFont(43);
  ratio_TEM->GetXaxis()->SetTitleOffset(3.0);
  ratio_TEM->GetXaxis()->SetLabelFont(43); // Absolute font size in pixel (precision 3)
  ratio_TEM->GetXaxis()->SetLabelSize(20);
  
  //ratio_MEC->SetFillStyle(3001);
  ratio_MEC->SetFillColorAlpha(29, 0.60);
  
  // Draw linea at 1 in ratio plot
  TLine *line;
  if (choice == 0 && selection == 1) line = new TLine(0,1,726,1);
  if (choice == 0 && selection == 2) line = new TLine(0,1,700,1);
  if (choice == 1) line = new TLine(0,1,1,1);
  if (choice == 2) line = new TLine(-TMath::Pi(),1,TMath::Pi(),1);
  if (choice == 2 && selection == 2) line = new TLine(-TMath::Pi(),1,TMath::Pi(),1);
  line->SetLineColor(kBlack);
  line->SetLineStyle(9); // dashed
  line->Draw();
  
  
  
  
  //**********************
  //
  // Area Normalised plot
  //
  //**********************
  /*
   TH1F *histoPmu_copy = (TH1F*)histoPmu->Clone("histoPmu_copy");
   TH1F *histoPmu_TEM_copy = (TH1F*)histoPmu_TEM->Clone("histoPmu_TEM_copy");
   TH1F *histoPmu_MEC_copy = (TH1F*)histoPmu_MEC->Clone("histoPmu_MEC_copy");
   
   // Area Norm
   histoPmu_copy->Scale(1./histoPmu_copy->Integral());
   histoPmu_TEM_copy->Scale(1./histoPmu_TEM_copy->Integral());
   histoPmu_MEC_copy->Scale(1./histoPmu_MEC_copy->Integral());
   
   // Draw them in a new canvas
   TCanvas *c1 = new TCanvas("c1", "canvas", 800, 800);
   histoPmu_TEM_copy->Draw();
   histoPmu_copy->Draw("same");
   histoPmu_MEC_copy->Draw("same");
   
   //Settings
   histoPmu_TEM_copy->GetXaxis()->CenterTitle();
   histoPmu_TEM_copy->GetYaxis()->CenterTitle();
   //histoPmu_TEM_copy->GetYaxis()->SetTitleOffset(1.0);
   
   leg->Draw();
   
   // TLatex
   double x = 0.87;
   double y = 0.52;
   double size = 28;
   int color = 1;
   int font = 43;
   int align = 32;
   
   TLatex *latex = new TLatex( x, y, "Area Normalised" );
   latex->SetNDC();
   latex->SetTextSize(size);
   latex->SetTextColor(color);
   latex->SetTextFont(font);
   latex->SetTextAlign(align);
   
   latex->Draw();
   */
  
  
}
Example #23
0
void plotDist(char* drawVar="sumJetMass_pt50",char* binning="(20,0,2000)"){

  gROOT->ProcessLine(".L ~/tdrstyle.C");
  setTDRStyle();

  // fill signal tree and draw
  ///////////////////////////////////////
  TChain* sigTree = new TChain("TreeFiller/AnalysisTree");
  cout << sampleNames[ kT1tttt ] << " " << sigTree->Add( fileNames[ kT1tttt ] ) << endl;

  char drawString[150];
  sprintf(drawString,"%s>>sig%s",drawVar,binning);

  sigTree->Draw(drawString,"nJets_pt50>3");

  TH1F* sig = (TH1F*) gDirectory->Get("sig");
  sig->SetLineWidth(2);
  sig->SetLineColor(colorCodes[kT1tttt]);
  
  TLegend* leg = new TLegend(.9,.9,.7,.7);
  leg->SetFillColor(0);
  
  leg->AddEntry(sig,sampleNames[ kT1tttt ],"l");

  // Fill background tree and draw
  //////////////////////////////////////
  const int numBkg = 4;

  TChain* bkgTree[numBkg];
  TH1F* bkg[numBkg];
			
  for( unsigned int iBkg = 0 ; iBkg < numBkg ; iBkg++){

    //if( iBkg == 1 || iBkg==2 || iBkg==3 ) continue;
    
    bkgTree[iBkg] = new TChain("TreeFiller/AnalysisTree");
    cout << sampleNames[ iBkg ] << " " << bkgTree[iBkg]->Add( fileNames[ iBkg ] ) << endl;

    sprintf(drawString,"%s>>bkg%i%s",drawVar,iBkg,binning);

    bkgTree[iBkg]->Draw(drawString,"nJets_pt50>3");

    char histoName[150];
    sprintf(histoName,"bkg%i",iBkg);

    bkg[iBkg] = (TH1F*) gDirectory->Get(histoName);
    bkg[iBkg]->SetLineWidth(2);
    bkg[iBkg]->SetLineColor(colorCodes[iBkg]);

    leg->AddEntry(bkg[iBkg],sampleNames[ iBkg ],"l");

  }

  // hacking normalizations...
  //sig->Scale(1000*4.e-2/50000.);
  //bkg[kQCD]->Scale(1000*2.99e10/100000.);


  sig->DrawNormalized("");
  
  for( unsigned int iBkg = 0 ; iBkg < numBkg ; iBkg++){
    //if( iBkg == 1 || iBkg==2 || iBkg==3 ) continue;
    bkg[iBkg]->DrawNormalized("SAME");
  }

  leg->Draw();

}
Example #24
0
TH1F* refhist(TString name, TFile *f, EColor c)
{
  TH1F *h = (TH1F *) f->Get(name);
  h->SetLineColor(c);
  return h;
}
Example #25
0
void ootpu_comparison(TString files, TString var, TString title, int nbins, float low, float high, TString comments="") {

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

  TH1::SetDefaultSumw2();

  TH1F* hA = new TH1F("hA",title, nbins, low, high);
  TH1F* hB = new TH1F("hB",title, nbins, low, high);
  TH1F* hC = new TH1F("hC",title, nbins, low, high);
  TH1F* hD = new TH1F("hD",title, nbins, low, high);

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

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

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


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

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

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

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

  float avg1_l(hA_l->GetMean());
  float avg2_l(hB_l->GetMean());
  float avg3_l(hC_l->GetMean());
  float avg4_l(hD_l->GetMean());

  hA_l->Scale(1/hA_l->Integral());
  hB_l->Scale(1/hB_l->Integral());
  hC_l->Scale(1/hC_l->Integral());
  hD_l->Scale(1/hD_l->Integral());

  hA_l->SetLineColor(12);
  hB_l->SetLineColor(46);
  hC_l->SetLineColor(8);
  hD_l->SetLineColor(7);

  hA_l->SetLineWidth(2);
  hB_l->SetLineWidth(2);
  hC_l->SetLineWidth(2);
  hD_l->SetLineWidth(2);

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

  hA->SetMaximum(max*1.1);
  hA->Draw("hist");
  hB->Draw("hist,same");
  hC->Draw("hist,same");
  hD->Draw("hist,same");
  hA_l->Draw("hist,same");
  hB_l->Draw("hist,same");
  hC_l->Draw("hist,same");
  hD_l->Draw("hist,same");

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

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

  cout << "Rejection rates" << endl;
  Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  left = hA->IntegralAndError(1,12,lerror);
  right = hA->IntegralAndError(13,31,rerror);
  float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hB->IntegralAndError(1,12,lerror);
  right = hB->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hC->IntegralAndError(1,12,lerror);
  right = hC->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hD->IntegralAndError(1,12,lerror);
  right = hD->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

  // Print settings
  printf("SETTINGS\nAnalyze output from new Analyzer\n");
  printf("Input file = %s\n",fileIn);
  printf("School distance = %f m, angle = %f deg\n",distance,angle);
  printf("School orientation: tel1=%f deg, tel2=%f deg\n",phi1Corr,phi2Corr);
  printf("Max Chi2 = %f\n",maxchisquare);
  printf("Theta Rel Range = %f - %f deg\n",minthetarel,maxthetarel);
  printf("Range for N sattellite in each run = (tel1) %f - %f, (tel2) %f - %f \n",minAvSat[0],maxAvSat[0],minAvSat[1],maxAvSat[1]);
  printf("Min N satellite in a single event = %i\n",satEventThr);

  Int_t adayMin = (yearRange[0]-2014) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2014) * 1000 + monthRange[1]*50 + dayRange[1];

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

  // define some histos
  TH1F *hDeltaTheta = new TH1F("hDeltaTheta","#Delta#theta below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi = new TH1F("hDeltaPhi","#Delta#phi below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack = new TH1F("hDeltaThetaBack","#Delta#theta out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack = new TH1F("hDeltaPhiBack","#Delta#phi out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel = new TH1F("hThetaRel","#theta_{rel} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack = new TH1F("hThetaRelBack","#theta_{rel} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH2F *hAngle = new TH2F("hAngle",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);
  TH2F *hAngleBack = new TH2F("hAngleBack",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);

  TProfile *hModulation = new  TProfile("hModulation","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulation2 = new  TProfile("hModulation2","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAv = new  TProfile("hModulationAv","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAvCorr = new  TProfile("hModulationAvCorr","#theta^{rel} < 10#circ;#phi - #alpha;diff (ns)",50,0,360);

  TH1F *hnsigpeak = new TH1F("hnsigpeak","",50,0,360);
  TH1F *hnbackpeak = new TH1F("hnbackpeak","",50,0,360);

  TProfile *hSinTheta = new  TProfile("hSinTheta",";#phi - #alpha;sin(#theta)",50,0,360);
  TProfile *hSinTheta2 = new  TProfile("hSinTheta2",";#phi - #alpha;sin(#theta)",50,0,360);

  TH1F *hRunCut[2];
  hRunCut[0] = new TH1F("hRunCut1","Reason for Run Rejection Tel-1;Reason;runs rejected",11,0,11);
  hRunCut[1] = new TH1F("hRunCut2","Reason for Run Rejection Tel-2;Reason;runs rejected",11,0,11);

  for(Int_t i=0;i<2;i++){
    hRunCut[i]->Fill("DateRange",0);
    hRunCut[i]->Fill("LowFractionGT",0);
    hRunCut[i]->Fill("TimeDuration",0);
    hRunCut[i]->Fill("rateGT",0);
    hRunCut[i]->Fill("RunNumber",0);
    hRunCut[i]->Fill("MissingHitFrac",0);
    hRunCut[i]->Fill("DeadStripBot",0);
    hRunCut[i]->Fill("DeadStripMid",0);
    hRunCut[i]->Fill("DeadStripTop",0);
    hRunCut[i]->Fill("NSatellites",0);
    hRunCut[i]->Fill("NoGoodWeather",0);  
  }

  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[2];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");

  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  const Int_t nyearmax = 5;
  Bool_t runstatus[2][nyearmax][12][31][500]; //#telescope, year-2014, month, day, run
  Float_t effTel[2][nyearmax][12][31][500];
  Int_t nStripDeadBot[2][nyearmax][12][31][500];
  Int_t nStripDeadMid[2][nyearmax][12][31][500];
  Int_t nStripDeadTop[2][nyearmax][12][31][500];

  Float_t nstripDeadB[2]={0,0},nstripDeadM[2]={0,0},nstripDeadT[2]={0,0};

  // sat info
  Float_t NsatAv[2][nyearmax][12][31][500];

  // weather info
  Float_t pressureTel[2][nyearmax][12][31][500];
  Float_t TempInTel[2][nyearmax][12][31][500];
  Float_t TempOutTel[2][nyearmax][12][31][500];
  Float_t timeWeath[2][nyearmax][12][31][500];

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

  if(tel[0] && tel[1]){
    for(Int_t i=0;i < 2;i++){ // loop on telescopes
      printf("Tel-%i\n",i+1);
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	rateGT = tel[i]->GetLeaf("FractionGoodTrack")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue();

	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2014) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

        if(i==1) printf("%f %f\n",rateGT , rateMin[i]);

	if(aday < adayMin || aday > adayMax){
	  hRunCut[i]->Fill("DateRange",1); continue;}
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]){
	  hRunCut[i]->Fill("LowFractionGT",1); continue;} // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]){
	  hRunCut[i]->Fill("TimeDuration",1); continue;} // cut on the number of event
	if(rateGT < rateMin[i] || rateGT > rateMax[i]){
	  hRunCut[i]->Fill("rateGT",1); continue;} // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499){
	  hRunCut[i]->Fill("RunNumber",1); continue;} // run < 500

        if(i==1) printf("GR\n");

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]){
	  hRunCut[i]->Fill("MissingHitFrac",1); continue;}
		
	// active strip maps
	if(tel[i]->GetLeaf("maskB")) nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskB")->GetValue()));
	if(tel[i]->GetLeaf("maskM")) nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskM")->GetValue()));
	if(tel[i]->GetLeaf("maskT")) nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskT")->GetValue()));

	if(nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadBotMax[i] || nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadBotMin[i]) {
	  hRunCut[i]->Fill("DeadStripBot",1); continue;}
	if(nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadMidMax[i] || nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadMidMin[i]){
	  hRunCut[i]->Fill("DeadStripMid",1); continue;}
	if(nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadTopMax[i] || nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadTopMin[i]){
	  hRunCut[i]->Fill("DeadStripTop",1); continue;}
     
	// nsat averaged  per run
	if(tel[i]->GetLeaf("nSat")) NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("nSat")->GetValue();


	if(NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minAvSat[i] || NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxAvSat[i]){
	 hRunCut[i]->Fill("NSatellites",1); continue;}

	// weather info
	if(tel[i]->GetLeaf("Pressure")) pressureTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("Pressure")->GetValue();
	if(tel[i]->GetLeaf("IndoorTemperature")) TempInTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("IndoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("OutdoorTemperature")) TempOutTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("OutdoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("TimeWeatherUpdate")) timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("TimeWeatherUpdate")->GetValue();

	if(timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minWeathTimeDelay[i] ||  timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxWeathTimeDelay[i]){ hRunCut[i]->Fill("NoGoodWeather",1); continue;	}

	// Set good runs
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	effTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = 1;//rateGT/refRate[i];

      }
    }
  }
  else{
    telC = NULL;
  }

  printf("Start to process correlations\n");
  Int_t n = t->GetEntries();
  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
      nstripDeadB[0] += countBits(nStripDeadBot[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[0] += countBits(nStripDeadMid[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[0] += countBits(nStripDeadTop[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();

      nstripDeadB[1] += countBits(nStripDeadBot[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[1] += countBits(nStripDeadMid[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[1] += countBits(nStripDeadTop[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
    }
    nstripDeadB[0] /= nsecGR;
    nstripDeadM[0] /= nsecGR;
    nstripDeadT[0] /= nsecGR;

    nstripDeadB[1] /= nsecGR;
    nstripDeadM[1] /= nsecGR;
    nstripDeadT[1] /= nsecGR;

    printf("Dead channel tel1 = %f - %f - %f\n",nstripDeadB[0],nstripDeadM[0],nstripDeadT[0]);
    printf("Dead channel tel2 = %f - %f - %f\n",nstripDeadB[1],nstripDeadM[1],nstripDeadT[1]);
  }
  
  char title[300];
  TH1F *h;
  
  sprintf(title,"correction assuming #Delta#phi = %4.2f, #DeltaL = %.1f m;#Deltat (ns);entries",angle,distance);
  
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  
  Float_t DeltaT;
  Float_t phiAv,thetaAv,corr;
  
  Float_t Theta1,Theta2;
  Float_t Phi1,Phi2;
  Int_t nsatel1cur,nsatel2cur,ntrack1,ntrack2;

  Float_t v1[3],v2[3],vSP; // variable to recompute ThetaRel on the fly
  Float_t eff = 1; 
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499)) continue;
  
    if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;


    eff = effTel[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())];
    eff *= effTel[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())];
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
    }
    }

    Float_t thetarel = t->GetLeaf("ThetaRel")->GetValue();
    Theta1 = (t->GetLeaf("Theta1")->GetValue())*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    
    nsatel1cur = t->GetLeaf("Nsatellite1")->GetValue();
    nsatel2cur = t->GetLeaf("Nsatellite2")->GetValue();
    ntrack1 = t->GetLeaf("Ntracks1")->GetValue();
    ntrack2 = t->GetLeaf("Ntracks2")->GetValue();

    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 += phi1Corr*TMath::DegToRad();
      Phi2 += phi2Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      
      v1[0] *= v2[0];
      v1[1] *= v2[1];
      v1[2] *= v2[2];
      
      vSP = v1[0] + v1[1] + v1[2];
      
      thetarel = TMath::ACos(vSP)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel < minthetarel) continue;
    if(thetarel > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    

    neventsGR++;

    // reject events with not enough satellites
    if(nsatel1cur < satEventThr || nsatel1cur < satEventThr) continue;

    neventsGRandSat++;
    
    DeltaT = t->GetLeaf("DiffTime")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();

    thetaAv = (Theta1+Theta2)*0.5;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    Float_t resFactor = 1;
    if(thetarel > 10 ) resFactor *= 0.5;
    if(thetarel > 20 ) resFactor *= 0.5;
    if(thetarel > 30 ) resFactor *= 0.5;

    corr = distance * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle)/2.99792458000000039e-01 + deltatCorr;

    phirelative = (Phi1-angle)*TMath::RadToDeg();
    if(phirelative < 0) phirelative += 360;
    if(phirelative < 0) phirelative += 360;
    if(phirelative > 360) phirelative -= 360;
    if(phirelative > 360) phirelative -= 360;

    phirelative2 = (Phi2-angle)*TMath::RadToDeg();
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 > 360) phirelative2 -= 360;
    if(phirelative2 > 360) phirelative2 -= 360;

    phirelativeAv = (phiAv-angle)*TMath::RadToDeg();
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;


    // if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
      
    // }

    if(thetarel < 10){//cos(thetarel*TMath::DegToRad())>0.98 && sin(thetaAv)>0.1){
      if(TMath::Abs(DeltaT- corr) < windowAlignment)
	hModulationAvCorr->Fill(phirelativeAv,DeltaT-corr);
      if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
	hModulation->Fill(phirelative,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulation2->Fill(phirelative2,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulationAv->Fill(phirelativeAv,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hSinTheta->Fill(phirelative,sin(thetaAv));
	hSinTheta2->Fill(phirelative2,sin(thetaAv));
	nsigPeak++;
	hnsigpeak->Fill(phirelativeAv);
      }
      else if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment*10){
	nbackPeak++;
	hnbackpeak->Fill(phirelativeAv);
      }
    }

    h->Fill(DeltaT-corr,1./eff);
    if(TMath::Abs(DeltaT-corr) < windowAlignment){
      hDeltaTheta->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel->Fill(thetarel);
      hAngle->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
    else if(TMath::Abs(DeltaT-corr) > windowAlignment*2 && TMath::Abs(DeltaT-corr) < windowAlignment*12){
      hDeltaThetaBack->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack->Fill(thetarel);
      hAngleBack->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
  }
  
  // compute (S+B)/S
  for(Int_t i=1;i<=50;i++){
    Float_t corrfactorPeak = 1;
    if(nsigPeak-nbackPeak*0.1 > 0)
      corrfactorPeak = hnsigpeak->GetBinContent(i)/(hnsigpeak->GetBinContent(i)-hnbackpeak->GetBinContent(i)*0.1);
    else
      printf("bin %i) not enough statistics\n",i);
    hnsigpeak->SetBinContent(i,corrfactorPeak);
  }

  TF1 *fpol0 = new TF1("fpol0","pol0");
  hnsigpeak->Fit(fpol0);

  hModulation->Scale(fpol0->GetParameter(0));
  hModulation2->Scale(fpol0->GetParameter(0));
  hModulationAv->Scale(fpol0->GetParameter(0));
  hModulationAvCorr->Scale(fpol0->GetParameter(0));
  
  TF1 *fmod = new TF1("fmod","[0] + [1]*cos((x-[2])*TMath::DegToRad())"); 
  hModulationAv->Fit(fmod); 

  printf("Estimates from time delay: Distance = %f +/- %f m -- Angle = %f +/- %f deg\n",fmod->GetParameter(1),fmod->GetParError(1),fmod->GetParameter(2),fmod->GetParError(2));

  h->SetStats(0);

  hDeltaThetaBack->Sumw2();
  hDeltaPhiBack->Sumw2();
  hThetaRelBack->Sumw2();
  hDeltaThetaBack->Scale(0.1);
  hDeltaPhiBack->Scale(0.1);
  hThetaRelBack->Scale(0.1);
  hAngleBack->Scale(0.1);
  hAngle->Add(hAngleBack,-1);

  printf("bin counting: SIGNAL = %f +/- %f\n",hDeltaPhi->Integral()-hDeltaPhiBack->Integral(),sqrt(hDeltaPhi->Integral()));
  rate = (hDeltaPhi->Integral()-hDeltaPhiBack->Integral())/nsecGR*86400;
  rateErr = sqrt(hDeltaPhi->Integral())/nsecGR*86400;


  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,maxwidth);
  ff->SetParameter(2,350); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,(tmax-tmin)/nbint); // bin width

  ff->SetNpx(1000);
  
  if(cout) cout->cd();
  h->Fit(ff,"EI","",-10000,10000);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  new TCanvas;

  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  // correct nsecGR for the event rejected because of the number of satellites (event by event cut)
  nsecGR *= neventsGRandSat/neventsGR;

  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("outputCERN-01-02.root","RECREATE");
  h->Write();
  hDeltaTheta->Write();
  hDeltaPhi->Write();
  hThetaRel->Write();
  hDeltaThetaBack->Write();
  hDeltaPhiBack->Write();
  hThetaRelBack->Write();
  hAngle->Write();
  hModulation->Write();
  hModulation2->Write();
  hModulationAv->Write();
  hModulationAvCorr->Write();
  hSinTheta->Write();
  hSinTheta2->Write();
  hnsigpeak->Write();
  hRunCut[0]->Write();
  hRunCut[1]->Write();
  fo->Close();

  return nsecGR*1./86400;
  
}
Example #27
0
void DeltaPhiPhoMETMax(double pt1_cutIN,double pt2_cutIN,double MET_cutIN, double DPHI_cutIN){
  cout<<"#### Max[DeltaPhi(MET,pho1),DeltaPhi(MET,pho2)] #####"<<endl;


 

  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  TLegend* leg = new TLegend(0.13,0.55,0.68,0.87);
  leg->SetNColumns(2);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  TLegend* leg_norm = new TLegend(0.13,0.5,0.7,0.87);
  leg_norm->SetNColumns(2);
  leg_norm->SetBorderSize(0);
  leg_norm->SetFillStyle(0);


  TCanvas *canvas = new TCanvas("c1n","",1100,500);
  canvas->Divide(2,1);
  canvas->cd(1);

  TCut mggmax = "mgg<180";
  TCut mggmin = "mgg>100";
  TCut mggblind = "((mgg<115)||(mgg>135))";
  TCut eveto1 = "eleveto1 == 1";
  TCut eveto2 = "eleveto2 == 1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  TCut pt1cut = Form("pt1/mgg>%lf",pt1_cutIN);
  TCut pt2cut = Form("pt2/mgg>%lf",pt2_cutIN);  
  TCut METcut = Form("t1pfmet>%lf",MET_cutIN);  
  TCut DPHIcut = Form("FDelta(pt1,eta1,phi1,0.,pt2,eta2,phi2,0.,t1pfmetPhi)>%lf",DPHI_cutIN);  
  TCut NegWeight = "weight>0.";
  
 

  TFile *data = TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");  
  TFile *sig1 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP600.root","READ");
  TFile *sig2 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP800.root","READ");
  TFile *sig3 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1000.root","READ");
  TFile *sig4 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1200.root","READ");
  TFile *sig5 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1400.root","READ");  
  TFile *sig6 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1700.root","READ");  
  TFile *sig7 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP2500.root","READ");  

 
  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ");  
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");  
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");  
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");  
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");  
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");
  
  
  TTree *tree_data = (TTree*) data->Get("DiPhotonTree");
  
  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree");
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree");
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree");
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree");
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree");
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");
  
  
  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");

  
  tree_data->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hdata(25,0,3.5)",(mggblind && mggmax && mggmin && metF && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");
  hdata->SetMarkerColor(kBlack);
  hdata->SetMarkerStyle(20);
  hdata->SetLineColor(kBlack);
    
 
 
  
  tree_sig1->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h1(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h2(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h3(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h4(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h5(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h6(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h7(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");
 
  tree_bkg1->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg1(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg2(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg3(25,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
  tree_bkg4->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg4(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut)); //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg5(25,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg6(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));   //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");
  tree_bkg7->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg7(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples   
   TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");
    tree_bkg8->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg8(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");

    tree_bkg9->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg9(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut && NegWeight));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");
    tree_bkg10->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg10(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");
    tree_bkg11->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg11(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");
    tree_bkg12->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg12(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");

 
 


  /*  h1->Scale(0.00009338);
  h2->Scale(0.00010348);
  h3->Scale(0.00008394);
  h4->Scale(0.00006352);
  h5->Scale(0.00004712);
  h6->Scale(0.00003020);
  h7->Scale(0.00000972);
  */


  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4); //only for 25ns samples
  h6->SetLineColor(kPink+7); //only for 25ns samples
  h7->SetLineColor(kMagenta+2); //only for 25ns samples
  h1->SetLineWidth(2);
  h2->SetLineWidth(2);
  h3->SetLineWidth(2);
  h4->SetLineWidth(2);
  h5->SetLineWidth(2); //only for 25ns samples
  h6->SetLineWidth(2); //only for 25ns samples
  h7->SetLineWidth(2); //only for 25ns samples
  
  





  
  
   THStack *hs=new THStack("hs","");
 
   hbkg7->SetFillColor(kGreen+2);
   hbkg6->SetFillColor(kGreen);
   hbkg8->SetFillColor(kYellow);
   hbkg4->SetFillColor(kOrange);
   hbkg9->SetFillColor(kOrange+7);
   hbkg10->SetFillColor(kOrange+4);
   hbkg11->SetFillColor(kCyan);
   hbkg12->SetFillColor(kCyan+1);
   hbkg5->SetFillColor(kBlue+3);
   hbkg2->SetFillColor(kBlue);
   hbkg3->SetFillColor(kMagenta-2);
   hbkg1->SetFillColor(kViolet);





  hbkg1->SetLineColor(kBlack);
  hbkg2->SetLineColor(kBlack);
  hbkg3->SetLineColor(kBlack);
  hbkg4->SetLineColor(kBlack);
  hbkg5->SetLineColor(kBlack);
  hbkg6->SetLineColor(kBlack);
  hbkg7->SetLineColor(kBlack);
  hbkg8->SetLineColor(kBlack);
  hbkg9->SetLineColor(kBlack);
  hbkg10->SetLineColor(kBlack);
  hbkg11->SetLineColor(kBlack);
  hbkg12->SetLineColor(kBlack);
 
  hs->Add(hbkg7);
  hs->Add(hbkg6);
  hs->Add(hbkg8);
  hs->Add(hbkg4);
  hs->Add(hbkg9);
  hs->Add(hbkg10);
  hs->Add(hbkg11);
  hs->Add(hbkg12);
  hs->Add(hbkg2);
  hs->Add(hbkg5);
  hs->Add(hbkg3);
  hs->Add(hbkg1);
  
  
  
  
  TH1F *hsum = (TH1F*)hbkg1->Clone("hsum"); 
  hsum->Add(hbkg2);
  hsum->Add(hbkg3);
  hsum->Add(hbkg4);
  hsum->Add(hbkg5);
  hsum->Add(hbkg6);
  hsum->Add(hbkg7);
  hsum->Add(hbkg8);
  hsum->Add(hbkg9);
  hsum->Add(hbkg10);
  hsum->Add(hbkg11);
  hsum->Add(hbkg12);  
//  hs->SetMaximum(700);
  // hs->SetMinimum(0.0001);
  hdata->SetTitle("");
  hdata->Draw("e1"); 

  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3001);
  
  hs->Draw("same hist");
  hsum->Draw("same e2");
  h2->Draw("same hist");
  h3->Draw("same hist"); 
  h4->Draw("same hist");
  h1->Draw("same hist");
  h5->Draw("same hist"); //only for 25ns samples
  h6->Draw("same hist"); //only for 25ns samples
  h7->Draw("same hist"); //only for 25ns samples
  hdata->Draw("same e1");  
  
  hdata->GetXaxis()->SetTitle("max[|#Delta#phi(#gamma_{1},MET)|,|#Delta#phi(#gamma_{2},MET)|]");
  hdata->GetYaxis()->SetTitleOffset(1.2);
  hdata->GetYaxis()->SetTitle("Events/0.1 GeV");  
  gPad->Modified();
  
  

  /*leg->AddEntry(h1,"m_{#chi} = 1 GeV","l");
    leg->AddEntry(h2,"m_{#chi} = 10 GeV","l");
    leg->AddEntry(h3,"m_{#chi} = 100 GeV","l");      
    leg->AddEntry(h4,"m_{#chi} = 1000 GeV","l");*/
  leg->AddEntry(hdata,"Data","elp"); 
  leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");
  leg->AddEntry(hbkg1,"#gamma #gamma","f");         
  leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");
  leg->AddEntry(hbkg2,"Drell Yann","f");       
  leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");      
  leg->AddEntry(hbkg3,"#gamma + Jets","f");      
  leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");     
  leg->AddEntry(hbkg5,"QCD","f");    
  leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l"); //only for 25ns samples    
  leg->AddEntry(hbkg4,"ggH","f");      
  leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l"); //only for 25ns samples    
  leg->AddEntry(hbkg6,"VH","f");  
  leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples      
  leg->AddEntry(hbkg7,"ttH","f");  
  leg->AddEntry(hbkg8,"VBF H","f");
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");
  leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");
  leg->AddEntry(hbkg11,"#gamma+W","f");
  leg->AddEntry(hbkg12,"#gamma+Z","f");
  leg->AddEntry(hsum,"Bkg uncertainty","f");
  leg->Draw("same");
  
  gStyle->SetOptStat(0);  
  

  tree_data->Scan("event:lumi:run:t1pfmet",(mggblind && METcut && metF && pt1cut && pt2cut)*"max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>2.5");


  canvas->cd(2);
  
  

  tree_sig1->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h1_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h1_norm =(TH1F*)gPad->GetPrimitive("h1_norm");
  tree_sig2->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h2_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h2_norm =(TH1F*)gPad->GetPrimitive("h2_norm");
  tree_sig3->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h3_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h3_norm =(TH1F*)gPad->GetPrimitive("h3_norm");
  tree_sig4->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h4_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h4_norm =(TH1F*)gPad->GetPrimitive("h4_norm");
  tree_sig5->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h5_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h5_norm =(TH1F*)gPad->GetPrimitive("h5_norm");
  tree_sig6->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h6_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h6_norm =(TH1F*)gPad->GetPrimitive("h6_norm");
  tree_sig7->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>h7_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *h7_norm =(TH1F*)gPad->GetPrimitive("h7_norm");
  




  tree_bkg1->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg1_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg1_norm =(TH1F*)gPad->GetPrimitive("hbkg1_norm");
  tree_bkg2->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg2_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg2_norm =(TH1F*)gPad->GetPrimitive("hbkg2_norm");
  tree_bkg3->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg3_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));  
  TH1F *hbkg3_norm =(TH1F*)gPad->GetPrimitive("hbkg3_norm");
  tree_bkg4->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg4_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut)); //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg4_norm =(TH1F*)gPad->GetPrimitive("hbkg4_norm");
  tree_bkg5->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg5_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && genmatch && pt1cut && pt2cut && METcut&& DPHIcut));
  TH1F *hbkg5_norm =(TH1F*)gPad->GetPrimitive("hbkg5_norm");
  tree_bkg6->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg6_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));   //weight also on BR = 0.002 if using 50ns samples
  TH1F *hbkg6_norm =(TH1F*)gPad->GetPrimitive("hbkg6_norm");
  tree_bkg7->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg7_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples   
   TH1F *hbkg7_norm =(TH1F*)gPad->GetPrimitive("hbkg7_norm");
    tree_bkg8->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg8_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg8_norm =(TH1F*)gPad->GetPrimitive("hbkg8_norm");
    tree_bkg9->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg9_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut && NegWeight));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg9_norm =(TH1F*)gPad->GetPrimitive("hbkg9_norm");
    tree_bkg10->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg10_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg10_norm =(TH1F*)gPad->GetPrimitive("hbkg10_norm");
    tree_bkg11->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg11_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg11_norm =(TH1F*)gPad->GetPrimitive("hbkg11_norm");
    tree_bkg12->Draw("max(FDelta(pt1,eta1,phi1,0.,0.,0.,0.,0.,t1pfmetPhi),FDelta(0.,0.,0.,0.,pt2,eta2,phi2,0.,t1pfmetPhi))>>hbkg12_norm(25,0,3.5)","weight"*(mggmax && mggmin && eveto && pt1cut && pt2cut && METcut&& DPHIcut));  //weight also on BR = 0.002 if using 50ns samples  
   TH1F *hbkg12_norm =(TH1F*)gPad->GetPrimitive("hbkg12_norm");



  double norm = 1./h1_norm->Integral();
  h1_norm->Scale(norm);
  norm = 1./h2_norm->Integral();
  h2_norm->Scale(norm);
  norm = 1./h3_norm->Integral();
  h3_norm->Scale(norm);
  norm = 1./h4_norm->Integral();
  h4_norm->Scale(norm);  
  norm = 1./h5_norm->Integral(); //only for 50ns samples
  h5_norm->Scale(norm);  //only for 50ns samples
  norm = 1./h6_norm->Integral(); //only for 50ns samples
  h6_norm->Scale(norm);  //only for 50ns samples
  norm = 1./h7_norm->Integral(); //only for 50ns samples
  h7_norm->Scale(norm);  //only for 50ns samples
  


  norm = 1./hbkg1_norm->Integral();
  hbkg1_norm->Scale(norm);  
  norm = 1./hbkg2_norm->Integral();
  hbkg2_norm->Scale(norm);  
  norm = 1./hbkg3_norm->Integral();
  hbkg3_norm->Scale(norm);  
  norm = 1./hbkg4_norm->Integral();
  hbkg4_norm->Scale(norm);  
  norm = 1./hbkg5_norm->Integral();
  hbkg5_norm->Scale(norm);  
  norm = 1./hbkg6_norm->Integral();
  hbkg6_norm->Scale(norm);  
   norm = 1./hbkg7_norm->Integral();
  hbkg7_norm->Scale(norm);  
    norm = 1./hbkg8_norm->Integral();
  hbkg8_norm->Scale(norm);  
  norm = 1./hbkg9_norm->Integral();
  hbkg9_norm->Scale(norm);
  norm = 1./hbkg10_norm->Integral();
  hbkg10_norm->Scale(norm);
  norm = 1./hbkg11_norm->Integral();
  hbkg11_norm->Scale(norm);
  norm = 1./hbkg12_norm->Integral();
  hbkg12_norm->Scale(norm);
  
  h1_norm->SetLineColor(kRed+3);
  h2_norm->SetLineColor(kRed+1);
  h3_norm->SetLineColor(kRed);
  h4_norm->SetLineColor(kPink+2);
  h5_norm->SetLineColor(kPink+4); //only for 25ns samples
  h6_norm->SetLineColor(kPink+7); //only for 25ns samples
  h7_norm->SetLineColor(kMagenta+2); //only for 25ns samples
  h1_norm->SetLineWidth(2);
  h2_norm->SetLineWidth(2);
  h3_norm->SetLineWidth(2);
  h4_norm->SetLineWidth(2);
  h5_norm->SetLineWidth(2); //only for 25ns samples
  h6_norm->SetLineWidth(2); //only for 25ns samples
  h7_norm->SetLineWidth(2); //only for 25ns samples

 


  hbkg7_norm->SetLineColor(kGreen+2);
  hbkg6_norm->SetLineColor(kGreen);
  hbkg8_norm->SetLineColor(kYellow);
  hbkg4_norm->SetLineColor(kOrange);
  hbkg9_norm->SetLineColor(kOrange+7);
  hbkg10_norm->SetLineColor(kOrange+4);
  hbkg11_norm->SetLineColor(kCyan);
  hbkg12_norm->SetLineColor(kCyan+1);
  hbkg5_norm->SetLineColor(kBlue+3);
  hbkg2_norm->SetLineColor(kBlue);
  hbkg3_norm->SetLineColor(kMagenta-2);
  hbkg1_norm->SetLineColor(kViolet);
  
  hbkg1_norm->SetFillStyle(0);
  hbkg2_norm->SetFillStyle(0);
  hbkg3_norm->SetFillStyle(0);
  hbkg4_norm->SetFillStyle(0);
  hbkg5_norm->SetFillStyle(0);
  hbkg6_norm->SetFillStyle(0);
   hbkg7_norm->SetFillStyle(0); 
  hbkg8_norm->SetFillStyle(0);
  hbkg9_norm->SetFillStyle(0);
  hbkg10_norm->SetFillStyle(0);
  hbkg11_norm->SetFillStyle(0);
  hbkg12_norm->SetFillStyle(0); 
 
  
  h1_norm->SetTitle("");

  h1_norm->SetMaximum(1);  
  h1_norm->SetMinimum(0.001);  
  h1_norm->Draw("HIST"); 
  
  hbkg1_norm->Draw("same HIST");  
  hbkg2_norm->Draw("same HIST"); 
  hbkg3_norm->Draw("same HIST"); 
  hbkg5_norm->Draw("same HIST"); 
  hbkg4_norm->Draw("same HIST"); 
  hbkg6_norm->Draw("same HIST"); 
  hbkg7_norm->Draw("same HIST"); 
  hbkg8_norm->Draw("same HIST"); 
  hbkg9_norm->Draw("same HIST");
  hbkg10_norm->Draw("same HIST");
  hbkg11_norm->Draw("same HIST");
  hbkg12_norm->Draw("same HIST"); 
  h1_norm->Draw("same hist"); 
  h2_norm->Draw("same hist");
  h3_norm->Draw("same hist"); 
  h4_norm->Draw("same hist");
  h5_norm->Draw("same hist");
  h6_norm->Draw("same hist");
  h7_norm->Draw("same hist");

  h1_norm->GetXaxis()->SetTitle("max[|#Delta#phi(#gamma_{1},MET)|,|#Delta#phi(#gamma_{2},MET)|]");
  h1_norm->GetYaxis()->SetTitle("Normalized events");  
  h1_norm->GetYaxis()->SetTitleOffset(1.2);  
  gPad->Modified();
  gStyle->SetOptStat(0);
  
  
  
  
  leg_norm->AddEntry(h1_norm,"m_{Z'} = 600 GeV","l");
  leg_norm->AddEntry(hbkg1_norm,"#gamma #gamma","l");      
  leg_norm->AddEntry(h2_norm,"m_{Z'} = 800 GeV","l");
  leg_norm->AddEntry(hbkg2_norm,"Drell Yann","l");      
  leg_norm->AddEntry(h3_norm,"m_{Z'} = 1000 GeV","l");      
  leg_norm->AddEntry(hbkg3_norm,"#gamma + Jets","l");      
  leg_norm->AddEntry(h4_norm,"m_{Z'} = 1200 GeV","l");    
  leg_norm->AddEntry(hbkg5_norm,"QCD","l");     
  leg_norm->AddEntry(h5_norm,"m_{Z'} = 1400 GeV","l"); //only for 25ns samples    
  leg_norm->AddEntry(hbkg4_norm,"ggH","l");      
  leg_norm->AddEntry(h6_norm,"m_{Z'} = 1700 GeV","l"); //only for 25ns samples    
  leg_norm->AddEntry(hbkg6_norm,"VH","l");   
  leg_norm->AddEntry(h7_norm,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples      
    leg_norm->AddEntry(hbkg7_norm,"ttH","l");  
    leg_norm->AddEntry(hbkg8_norm,"VBF H","l");   
    leg_norm->AddEntry(hbkg9_norm,"t + #gamma + Jets","l");
    leg_norm->AddEntry(hbkg10_norm,"tt + #gamma +Jets","l");
    leg_norm->AddEntry(hbkg11_norm,"#gamma+W","l");
    leg_norm->AddEntry(hbkg12_norm,"#gamma+Z","l");
  leg_norm->Draw("same");
  
  TPad *p1 = ((TPad*)(canvas->GetPad(1)));
  TPad *p2 = ((TPad*)(canvas->GetPad(2)));

  // int iPos =0;
  // CMS_lumi(p1,true,iPos,true);
  //CMS_lumi(p2,true,iPos,true);

  if(pt1_cutIN==0 && pt2_cutIN == 0 && MET_cutIN == 0){
    canvas->SaveAs("./25ns_2246inv_v3/plots/kinematics/DeltaPhiMax_Pho_MET.png");
    canvas->SaveAs("./25ns_2246inv_v3/plots/kinematics/DeltaPhiMax_Pho_MET.pdf");
  }
  if(pt1_cutIN==0.65 && pt2_cutIN == 0.25){
    canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/DeltaPhiMax_Pho_MET_optcuts_MET%.0lf.png",MET_cutIN));
    canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/DeltaPhiMax_Pho_MET_optcuts_MET%.0lf.pdf",MET_cutIN));
  }
  


 
}
Example #28
0
void runEffRej() {	
	
	gROOT->LoadMacro("AtlasStyle.C");
	gROOT->LoadMacro("AtlasUtils.C");
	gROOT->LoadMacro("AtlasLabels.C");
	
	TString input("effrej_su4");

	TFile* r17 = new TFile(TString("input/btagval.su4.susy1049.root"),"READ");
	TFile* r16 = new TFile(TString("input/btagval.su4.susy1004.root"),"READ");
	
	TString prefix("btagwgt/");
	
	bool doLogY = true;
	//bool doLogY = false;
	
	vector<TString> cuts;

//	cuts.push_back("2jet_metmeff0.25");
	cuts.push_back("2jet_deltaphi0.4");
//	cuts.push_back("2jet_deltaphi0.4cr");
//	cuts.push_back("2jet_nbtag1");
//	cuts.push_back("2jet_qcdcontrol");
//	cuts.push_back("2jet_nbtag2");
//	cuts.push_back("2jet_metphi");
//	cuts.push_back("2jet_mct100");
//	cuts.push_back("2jet_mct100cr");
//	cuts.push_back("2jet_mct150"); 
//	cuts.push_back("2jet_mct200"); 
	
//	cuts.push_back("2jetX_metmeff0.25");
//	cuts.push_back("2jetX_deltaphi0.4");
//	cuts.push_back("2jetX_deltaphi0.4cr");
//	cuts.push_back("2jetX_nbtag1");
//	cuts.push_back("2jetX_qcdcontrol"); 
//	cuts.push_back("2jetX_nbtag2");
//	cuts.push_back("2jetX_metphi");
//	cuts.push_back("2jetX_mct100");
//	cuts.push_back("2jetX_mct100cr");
//	cuts.push_back("2jetX_mct150"); 
//	cuts.push_back("2jetX_mct200"); 
	
//	cuts.push_back("3jet_metmeff0.25");
	cuts.push_back("3jet_deltaphi0.4");
//	cuts.push_back("3jet_nbtag1");
//	cuts.push_back("3jet_ewcontrol");
//	cuts.push_back("3jet_topcontrol");
//	cuts.push_back("3jet_topcontrol_2");
/*	cuts.push_back("3jet_meff500_qcdcontrol");
	cuts.push_back("3jet_meff500_2_qcdcontrol");
	cuts.push_back("3jet_meff700_qcdcontrol");
	cuts.push_back("3jet_meff700_2_qcdcontrol");
	cuts.push_back("3jet_meff900_qcdcontrol");
	cuts.push_back("3jet_meff900_2_qcdcontrol"); */
/*	cuts.push_back("3jet_meff500");
	cuts.push_back("3jet_meff500_2");
	cuts.push_back("3jet_meff700");
	cuts.push_back("3jet_meff700_2");
	cuts.push_back("3jet_meff900");
	cuts.push_back("3jet_meff900_2");
*/	
	vector<TString> plottype;
	plottype.push_back("jjfitNN0jfitNN");
	plottype.push_back("jjfitNN1jfitNN");
	plottype.push_back("jjfitNN2jfitNN");
	plottype.push_back("jsv00sv0");		
	plottype.push_back("jsv01sv0");		
	plottype.push_back("jsv02sv0");	

	TString logstring = "";
	if(doLogY) logstring = "_logy";
	
	TCanvas* canvas = new TCanvas();
	canvas->Print(TString::Format("output/%s_2jet%s.ps[",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_2jetX%s.ps[",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_3jet%s.ps[",input.Data(),logstring.Data()),"Portrait");
	
	gStyle->SetPaperSize(100,20);
	
	vector<TString>::iterator cut = cuts.begin();
	for(; cut!=cuts.end(); cut++) {
	
		vector<TString>::iterator type = plottype.begin();
		for(; type!=plottype.end(); type++) {
		
			canvas->Clear();
			canvas->SetLogy(doLogY);

			TString histo_l = TString::Format("%s%s_%s_l",prefix.Data(),cut->Data(),type->Data());
			TString histo_c = TString::Format("%s%s_%s_c",prefix.Data(),cut->Data(),type->Data());
			TString histo_b = TString::Format("%s%s_%s_b",prefix.Data(),cut->Data(),type->Data());
			
			TH1F* R17_l = (TH1F*)r17->Get(histo_l);
			TH1F* R17_c = (TH1F*)r17->Get(histo_c);
			TH1F* R17_b = (TH1F*)r17->Get(histo_b);
			
			TH1F* R16_l = (TH1F*)r16->Get(histo_l);
			TH1F* R16_c = (TH1F*)r16->Get(histo_c);
			TH1F* R16_b = (TH1F*)r16->Get(histo_b);
			
			map<TString, float> op; //op, eff
			map<TString, float> r17op; //op, eff
			map<TString, float> newop; //oldop, newop			
			//Find current efficiency operating points
			if(histo_b.Contains("sv0")) {
				op["5.85"] = R16_b->Integral(R16_b->FindBin(5.85),-1)/R16_b->Integral(0,-1);
				r17op["5.85"] = R17_b->Integral(R17_b->FindBin(5.85),-1)/R17_b->Integral(0,-1);
				
				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["5.85"] << endl;
					if(eff>op["5.85"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["5.85"] = R17_b->GetBinCenter(i-1)+slope*(op["5.85"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["5.85"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "5.85: "<< op["5.85"] << ", " << newop["5.85"] << ": " << R17_b->Integral(R17_b->FindBin(newop["5.85"]),-1)/R17_b->Integral(0,-1) << endl;
			}
			else {
				op["2.00"] = R16_b->Integral(R16_b->FindBin(2.00),-1)/R16_b->Integral(0,-1);
				op["0.35"] = R16_b->Integral(R16_b->FindBin(0.35),-1)/R16_b->Integral(0,-1);
				op["-1.25"] = R16_b->Integral(R16_b->FindBin(-1.25),-1)/R16_b->Integral(0,-1);	
				
				r17op["2.00"] = R17_b->Integral(R16_b->FindBin(2.00),-1)/R17_b->Integral(0,-1);
				r17op["0.35"] = R17_b->Integral(R16_b->FindBin(0.35),-1)/R17_b->Integral(0,-1);
				r17op["-1.25"] = R17_b->Integral(R16_b->FindBin(-1.25),-1)/R17_b->Integral(0,-1);	
				
				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["2.00"] << endl;
					if(eff>op["2.00"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["2.00"] = R17_b->GetBinCenter(i-1)+slope*(op["2.00"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["2.00"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "2.00: "<< op["2.00"] << ", " << newop["2.00"] << ": " << R17_b->Integral(R17_b->FindBin(newop["2.00"]),-1)/R17_b->Integral(0,-1) << endl;

				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["0.35"] << endl;
					if(eff>op["0.35"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["0.35"] = R17_b->GetBinCenter(i-1)+slope*(op["0.35"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["0.35"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "0.35: "<< op["0.35"] << ", " << newop["0.35"] << ": " << R17_b->Integral(R17_b->FindBin(newop["0.35"]),-1)/R17_b->Integral(0,-1) << endl;

				for(int i = 0; i<100; i++) {
					float eff = R17_b->Integral(i,-1)/R17_b->Integral(0,-1);
					//cout << eff << " " << op["0.35"] << endl;
					if(eff>op["-1.25"]) continue;
					else {
						//float slope = (R17_b->GetBinCenter(i)-R17_b->GetBinCenter(i-1))/(eff-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						//newop["-1.25"] = R17_b->GetBinCenter(i-1)+slope*(op["-1.25"]-R17_b->Integral(i-1,-1)/R17_b->Integral(0,-1));
						newop["-1.25"] = (R17_b->GetBinCenter(i-1)+R17_b->GetBinCenter(i))/2.;
						break;
					}
				}
				cout << "-1.25: "<< op["-1.25"] << ", " << newop["-1.25"] << ": " << R17_b->Integral(R17_b->FindBin(newop["-1.25"]),-1)/R17_b->Integral(0,-1) << endl;

			}

			R17_l->Rebin(5);
			R17_c->Rebin(5);
			R17_b->Rebin(5);
			
			R16_l->Rebin(5);
			R16_c->Rebin(5);
			R16_b->Rebin(5);
			
			TH2F* grid = new TH2F("grid","grid",2,0.,1.,2,1.,1000.);
			TString num;
			if(histo_b.Contains("2")) num = "3 tags";
			else if(histo_b.Contains("1")) num = "2 tags";
			else if(histo_b.Contains("0")) num = "1 tag";
			
			grid->SetXTitle(TString("Efficiency ("+num+")"));
			grid->SetYTitle("l-jet Rejection");
			//grid->Reset();
			//grid->SetMinimum(0.);
			//grid->SetMaximum(1.);
			
			grid->Draw();
			
			TGraph* r16graph = MakeEffRej(R16_l,R16_c,R16_b);
			TGraph* r17graph = MakeEffRej(R17_l,R17_c,R17_b);
			
			r16graph->SetMarkerColor(kBlack);
			r16graph->SetLineColor(kBlack);
			r16graph->Draw("elp same");
			
			r17graph->SetMarkerColor(kRed);
			r17graph->SetLineColor(kRed);
			//r17graph->SetMarkerSize();
			r17graph->Draw("elp same");
			

			//stacked->SetATLASLabel("Preliminary");
			//if(input.Contains("JetTauEtmiss")) stacked->SetLumi("95.6 pb^{-1}");
			//else stacked->SetLumi("2.052 fb^{-1}");
			
			TString label(TString("#splitline{"+input+"}{"));
			label.Append(*cut);
			label.Append("}");
			TLatex n2;
			n2.SetNDC();
			n2.SetTextFont(42);
			n2.SetTextColor(kBlack);
			n2.DrawLatex(0.20,0.25,label.Data());
			
			float leg_ylower = 0.90-((float)(2+op.size()))*0.06;
			TLegend* legend = new TLegend(0.75,leg_ylower,0.95,0.95);
			legend->SetFillStyle(0);
			legend->SetBorderSize(0);
			TLegendEntry* entry = 0;
			
			entry = legend->AddEntry(r17graph,"Release 17","elp");
			entry->SetTextAlign(12);
			entry->SetTextColor(1);
			
			entry = legend->AddEntry(r16graph,"Release 16","elp");
			entry->SetTextAlign(12);
			entry->SetTextColor(1);
			
			map<TString, float>::iterator iter = op.begin();
			int color = 3;
			for(; iter!=op.end(); iter++) {
				TLine* line = new TLine(iter->second,0.,iter->second,1000.);
				line->SetLineColor(color);
				line->Draw("same");
			
				TH1F* histo = new TH1F();
				histo->SetLineColor(color);
				entry = legend->AddEntry(histo,TString("Release 16, "+iter->first+ " ("+TString::Format("R17 %0.2f",newop[iter->first])+")"),"l");
				entry->SetTextAlign(12);
				entry->SetTextColor(1);
				color++;
			}
			
			iter = r17op.begin();
			for(; iter!=r17op.end(); iter++) {
				TLine* line = new TLine(iter->second,0.,iter->second,1000.);
				line->SetLineColor(color);
				line->Draw("same");
			
				TH1F* histo = new TH1F();
				histo->SetLineColor(color);
				entry = legend->AddEntry(histo,TString("Release 17, "+iter->first),"l");
				entry->SetTextAlign(12);
				entry->SetTextColor(1);
				color++;
			}
			
			legend->Draw();
			canvas->Update();
			
			if(cut->Contains("2jet_")) canvas->Print(TString::Format("output/%s_2jet%s.ps",input.Data(),logstring.Data()));
			else if(cut->Contains("2jetX_")) canvas->Print(TString::Format("output/%s_2jetX%s.ps",input.Data(),logstring.Data()));
			else if(cut->Contains("3jet_")) canvas->Print(TString::Format("output/%s_3jet%s.ps",input.Data(),logstring.Data()));
			canvas->Print(TString::Format("output/%s_%s_%s%s.eps",input.Data(),cut->Data(),type->Data(),logstring.Data()));
			
			delete r16graph;
			delete r17graph;
			delete grid;
		}
	}
	
	canvas->Print(TString::Format("output/%s_2jet%s.ps]",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_2jetX%s.ps]",input.Data(),logstring.Data()),"Portrait");
	canvas->Print(TString::Format("output/%s_3jet%s.ps]",input.Data(),logstring.Data()),"Portrait");
}
Example #29
0
int main(int argc, char* argv[]){
    UImanager uimanager(argc, argv, "dndt_fit");
//work directory    
    TString workdir(getenv("WORKDIR"));
//***************************set constant ****************************************
    Double_t acdntl_corr = 1., respf_corr = 1.;
	Double_t eff_corr = uimanager.get_adcerr() * uimanager.get_br_corr() * uimanager.get_ta_corr() * acdntl_corr * respf_corr;//	adcerr x tdiff_cut_eff x veto_eff x pi0 decay products abs. (set to 1, since included in current rmat) x bkg_in_fit (not in current rmat)
    if(uimanager.best_tdiff()) eff_corr *= uimanager.get_bit_corr();
    if(uimanager.ismc()) eff_corr = uimanager.get_ta_corr(); 

    cout << eff_corr << " " << uimanager.flux() << " " << uimanager.get_tgt_lumi() << endl;
	Double_t f_l = uimanager.flux() * uimanager.get_tgt_lumi() * eff_corr;

//************ start reading files *******************************
//read tables/eflux.dat [tables/effcor.dat] tables/dfp1_xx.dat or current_foler/dfp1_xx.dat
//get echn flux
	Double_t flw[180];
	ifstream eflux(workdir+"tables/eflux.dat");
	if (!eflux.is_open()) {
		cout << "eflux doesn't exist" << endl;
		exit(1);
 	}
	for(int i=0;i<180;i++)eflux>>flw[i];
//get efficiency table
    TString dfp;
    if (!uimanager.target()) dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_si.dat";
    else dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_c12.dat";

	ifstream profile;
    profile.open(dfp);
    if (profile.is_open()) {
        cout << "use local efficiency table: " << dfp << endl;
    } else {
        //profile.open(workdir+"efficiency2/tables/"+dfp);
        profile.open(workdir+"/tables/"+dfp);
        if(!profile.is_open()) cout << " can't open table " << dfp << endl;
        cout << " use efficiency table in tables: " << dfp << endl;
    }
	
    const int phy = 5;
	const int ech = 180;
	Double_t dfprob[phy][nangle][ech];
	Double_t coulm[nangle], ncohe[nangle], cosfiint[nangle], sinfiint[nangle], ninco[nangle];
	for(int i=0;i<nangle;i++){
		coulm[i]=0;
        ncohe[i]=0;
		cosfiint[i]=0;
		sinfiint[i]=0;
		ninco[i]=0;
	}

	for(int i = 0;i < 180;i++)
		for(int j = 0;j < nangle;j++)
			for(int k = 0;k < 5;k++){
				Double_t f_l_j=f_l;
				int ic = 0;
				int jc = 0;
				int kc = 0;
				profile>>ic>>jc>>kc>>dfprob[k][j][i];
                if(ic!=i+1||jc!=j+1||kc!=k+1){
					cout << i << " " << j << " " << k << endl;
					cout << ic << " " << jc << " " << kc << " " << dfprob[k][j][i] << endl;
					cout<<"Bad data given for dfprob"<<endl;
					exit(1);
				}
				if(kc==1)coulm[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==2)cosfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==3)ncohe[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==4)ninco[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else sinfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
            }

	for(int i=1;i<=nangle;i++){
		hcoulm->SetBinContent(i,coulm[i-1]);
		hcosfiint->SetBinContent(i,cosfiint[i-1]);
		hncohe->SetBinContent(i,ncohe[i-1]);
		hninco->SetBinContent(i,ninco[i-1]);
		hsinfiint->SetBinContent(i,sinfiint[i-1]);
    }
//read yield
    TString inrootname("pi0alt" + uimanager.input_filename("fit") + ".root");

	TFile *yield = new TFile(inrootname);
    if (!yield->IsOpen()) exit(open_err(inrootname));
	TH1F *yieldhist = (TH1F*)yield->Get("hyield");
	//TH1F *yieldhist = (TH1F*)yield->Get("hyield_mc_nocut");
	yieldhist->SetDirectory(0);
	if (!uimanager.target() && !uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/o tran.)");
    else if (!uimanager.target()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/ tran.)");
    else if (!uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/o tran.)");
    else yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/ tran.)");
    
    double nyield = 0, nyield_err = 0;
    for(int i = 1; i<=125; i++) {
        nyield += yieldhist->GetBinContent(i);
        nyield_err += yieldhist->GetBinError(i)*yieldhist->GetBinError(i);
    }
    nyield_err = sqrt(nyield_err);
//***************** end reading files **************************************
    
	gStyle->SetOptFit(1);
	gStyle->SetOptStat(0);
	gStyle->SetPaperSize(12,24);
	//Double_t parameter[4] = {7.9, 1.0, 1.0, 0.8};
	Double_t parameter[4] = {7.7, 1.0, 0.8, 0.5};

	TF1 *ftot = new TF1("ftot", dndt, 0., dndt_fit_range, 4);
	ftot->SetParNames("#Gamma","C1","#phi","C2");

	ftot->SetParameter(0,parameter[0]);
	ftot->SetParameter(1,parameter[1]);
	ftot->SetParameter(2,parameter[2]);
	ftot->SetParameter(3,parameter[3]);
/*
	ftot->FixParameter(0,parameter[0]);
	ftot->FixParameter(1,parameter[1]);
	ftot->FixParameter(2,parameter[2]);
	ftot->FixParameter(3,parameter[3]);
*/
    ftot->SetParLimits(0, 3, 10);
    ftot->SetParLimits(1, 0.3, 1.5);
    ftot->SetParLimits(2, 0, 3.1415936/2);
    ftot->SetParLimits(3, 0., 10.0);

	yieldhist->Fit("ftot", "RMBE0");

	Double_t chi2 = ftot->GetChisquare()/ftot->GetNDF();
	parameter[0]=ftot->GetParameter(0);
	parameter[1]=ftot->GetParameter(1);
	parameter[2]=ftot->GetParameter(2);
	parameter[3]=ftot->GetParameter(3);
	
    Double_t e1 = ftot->GetParError(0);
    Double_t e2 = ftot->GetParError(1);
    Double_t e3 = ftot->GetParError(2);
    Double_t e4 = ftot->GetParError(3);

	//cout<<chi2<<" "<<parameter[0]<<" "<<parameter[1]<<" "<<parameter[2]<<" "<<parameter[3]<<endl;
    TString fname = "fitresult" + uimanager.input_filename("fit") + ".dat";
    ofstream output(fname);
    output<<nyield<<" "<<nyield_err<<" "<<chi2<<" "<<parameter[0]<<" "<<e1<<" "<<parameter[1]<<" "<<e2<<" "<<parameter[2]<<" "<<e3<<" "<<parameter[3]<<" "<<e4<<endl;

	TH1F *fithist = new TH1F("fithist", "fithist", fit_nangle, 0, dndt_fit_range);
	TH1F *fitcoulm = new TH1F("fitcolum", "fitcolum", fit_nangle, 0, dndt_fit_range);
	TH1F *fitncohe = new TH1F("fitncohe", "fitncohe", fit_nangle, 0, dndt_fit_range);
	TH1F *fitit = new TH1F("fitit", "fitit", fit_nangle, 0, dndt_fit_range);
	TH1F *fitninco = new TH1F("fitninco", "fitninco", fit_nangle, 0, dndt_fit_range);

	yieldhist->SetLineWidth(2);
	fithist->SetLineWidth(2);
	fitcoulm->SetLineWidth(2);
	fitncohe->SetLineWidth(2);
	fitit->SetLineWidth(2);
	fitninco->SetLineWidth(2);

	float accfit[fit_nangle], acchist[fit_nangle], acchisterr[fit_nangle], diff[fit_nangle];

	for(int i=1;i<=fit_nangle;i++){
		fithist->SetBinContent(i,ftot->Eval(max_angle/nangle*(i-0.5)));
		fitcoulm->SetBinContent(i,parameter[0]*hcoulm->GetBinContent(i));
		fitncohe->SetBinContent(i,parameter[1]*hncohe->GetBinContent(i));
		fitit->SetBinContent(i,TMath::Sqrt(parameter[0]*parameter[1])*(TMath::Cos(parameter[2])*hcosfiint->GetBinContent(i)+TMath::Sin(parameter[2])*hsinfiint->GetBinContent(i)));
		fitninco->SetBinContent(i,parameter[3]*hninco->GetBinContent(i));
		if (i == 1) {
			accfit[0] = fithist->GetBinContent(1);
			acchist[0] = yieldhist->GetBinContent(1);
			acchisterr[0] = yieldhist->GetBinError(1) * yieldhist->GetBinError(1);
		}
		if (i != fit_nangle) {
			acchist[i] = yieldhist->GetBinContent(i) + acchist[i - 1];
			accfit[i] = fithist->GetBinContent(i) + accfit[i - 1];
			acchisterr[i] = acchisterr[i - 1] + yieldhist->GetBinError(i) * yieldhist->GetBinError(i);
		}
	}

	for(int i = 0; i < fit_nangle; ++i) {
		
		diff[i] = acchist[i] - accfit[i];
		acchisterr[i] = sqrt(acchisterr[i]);
	}

	TString outfilename("fyield" + uimanager.input_filename("fit"));

	float angles[fit_nangle], ex[fit_nangle];
	for(int i=0;i<fit_nangle;i++) {
		angles[i] = 0.02*(i+0.5);
        ex[i] = 0;
    }

	TGraphErrors ge(fit_nangle, angles, diff, ex, acchisterr);
	TGraphErrors ge1(fit_nangle, angles, acchist, ex, acchisterr);
	TGraph ge2(fit_nangle, angles, accfit);

	TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
	c1->SaveAs(outfilename+".pdf[");
	yieldhist->SetMinimum(0);
	yieldhist->SetMaximum(yieldhist->GetMaximum()*1.05);
	yieldhist->Draw("e1");
	fitcoulm->SetLineColor(kBlue);
	fitcoulm->Draw("sameC");
	fitncohe->SetLineColor(32);
	fitncohe->Draw("sameC");
	fitit->SetLineColor(kBlack);
	fitit->Draw("sameC");
	fitninco->SetLineColor(kYellow);
	fitninco->Draw("sameC");
	fithist->SetLineColor(kRed);
	fithist->Draw("sameC");

	TLegend *leg = new TLegend(0.1,0.7,0.45,0.9);
	leg->SetFillColor(0);
	leg->SetTextSize(0.03);
	leg->AddEntry(fitcoulm,"Primakoff","L");
	leg->AddEntry(fitncohe,"Nuclear Coherent","L");
	leg->AddEntry(fitit,"Interference","L");
	leg->AddEntry(fitninco,"Nuclear Incoherent","L");
	//leg->Draw();

	c1->SaveAs(outfilename+".pdf");

	ge.SetMarkerStyle(20);
	ge.SetMarkerColor(kBlue);
	ge.SetTitle("accumulated yield - fit vs. #theta");
	ge.Draw("ap");
	c1->SaveAs(outfilename + ".pdf");

	ge1.SetMarkerStyle(20);
	ge1.SetMarkerColor(kBlue);
	ge1.SetTitle("accumulated yield and fitting vs. #theta");
	ge1.Draw("ap");
	ge2.SetLineColor(kRed);
	ge2.Draw("sameC");
	c1->SaveAs(outfilename + ".pdf");

	c1->SaveAs(outfilename+".pdf]");

	TFile *ftyd = new TFile(outfilename+".root", "RECREATE");
	yieldhist->Write();
	fithist->Write();
	fitcoulm->Write();
	fitncohe->Write();
	fitit->Write();
	fitninco->Write();
    hcoulm->Write();
    hncohe->Write();
    hninco->Write();
	hcosfiint->Write();
    hsinfiint->Write();
    ftyd->Close();
    
	return 0;
}
Example #30
0
Bool_t CheckESD(const char* gAliceFileName = "galice.root", 
		const char* esdFileName = "AliESDs.root")
{
// check the content of the ESD
 
  // check values
  Int_t    checkNGenLow = 1;

  Double_t checkEffLow = 0.5;
  Double_t checkEffSigma = 3;
  Double_t checkFakeHigh = 0.5;
  Double_t checkFakeSigma = 3;

  Double_t checkResPtInvHigh = 5;
  Double_t checkResPtInvSigma = 3;
  Double_t checkResPhiHigh = 10;
  Double_t checkResPhiSigma = 3;
  Double_t checkResThetaHigh = 10;
  Double_t checkResThetaSigma = 3;

  Double_t checkPIDEffLow = 0.5;
  Double_t checkPIDEffSigma = 3;
  Double_t checkResTOFHigh = 500;
  Double_t checkResTOFSigma = 3;

  Double_t checkPHOSNLow = 5;
  Double_t checkPHOSEnergyLow = 0.3;
  Double_t checkPHOSEnergyHigh = 1.0;
  Double_t checkEMCALNLow = 50;
  Double_t checkEMCALEnergyLow = 0.05;
  Double_t checkEMCALEnergyHigh = 1.0;

  Double_t checkMUONNLow = 1;
  Double_t checkMUONPtLow = 0.5;
  Double_t checkMUONPtHigh = 10.;

  Double_t cutPtV0 = 0.3;
  Double_t checkV0EffLow = 0.02;
  Double_t checkV0EffSigma = 3;
  Double_t cutPtCascade = 0.5;
  Double_t checkCascadeEffLow = 0.01;
  Double_t checkCascadeEffSigma = 3;

  // open run loader and load gAlice, kinematics and header
  AliRunLoader* runLoader = AliRunLoader::Open(gAliceFileName);
  if (!runLoader) {
    Error("CheckESD", "getting run loader from file %s failed", 
	    gAliceFileName);
    return kFALSE;
  }
  runLoader->LoadgAlice();
  gAlice = runLoader->GetAliRun();
  if (!gAlice) {
    Error("CheckESD", "no galice object found");
    return kFALSE;
  }
  runLoader->LoadKinematics();
  runLoader->LoadHeader();

  // open the ESD file
  TFile* esdFile = TFile::Open(esdFileName);
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", esdFileName);
    return kFALSE;
  }
  AliESDEvent * esd = new AliESDEvent;
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return kFALSE;
  }
  esd->ReadFromTree(tree);

  // efficiency and resolution histograms
  Int_t nBinsPt = 15;
  Float_t minPt = 0.1;
  Float_t maxPt = 3.1;
  TH1F* hGen = CreateHisto("hGen", "generated tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  TH1F* hRec = CreateHisto("hRec", "reconstructed tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  Int_t nGen = 0;
  Int_t nRec = 0;
  Int_t nFake = 0;

  TH1F* hResPtInv = CreateHisto("hResPtInv", "", 100, -10, 10, 
           "(p_{t,rec}^{-1}-p_{t,sim}^{-1}) / p_{t,sim}^{-1} [%]", "N");
  TH1F* hResPhi = CreateHisto("hResPhi", "", 100, -20, 20, 
			      "#phi_{rec}-#phi_{sim} [mrad]", "N");
  TH1F* hResTheta = CreateHisto("hResTheta", "", 100, -20, 20, 
				"#theta_{rec}-#theta_{sim} [mrad]", "N");

  // PID
  Int_t partCode[AliPID::kSPECIES] = 
    {kElectron, kMuonMinus, kPiPlus, kKPlus, kProton};
  const char* partName[AliPID::kSPECIES+1] = 
    {"electron", "muon", "pion", "kaon", "proton", "other"};
  Double_t partFrac[AliPID::kSPECIES] = 
    {0.01, 0.01, 0.85, 0.10, 0.05};
  Int_t identified[AliPID::kSPECIES+1][AliPID::kSPECIES];
  for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      identified[iGen][iRec] = 0;
    }
  }
  Int_t nIdentified = 0;

  // dE/dx and TOF
  TH2F* hDEdxRight = new TH2F("hDEdxRight", "", 300, 0, 3, 100, 0, 400);
  hDEdxRight->SetStats(kFALSE);
  hDEdxRight->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxRight->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxRight->SetMarkerStyle(kFullCircle);
  hDEdxRight->SetMarkerSize(0.4);
  TH2F* hDEdxWrong = new TH2F("hDEdxWrong", "", 300, 0, 3, 100, 0, 400);
  hDEdxWrong->SetStats(kFALSE);
  hDEdxWrong->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxWrong->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxWrong->SetMarkerStyle(kFullCircle);
  hDEdxWrong->SetMarkerSize(0.4);
  hDEdxWrong->SetMarkerColor(kRed);
  TH1F* hResTOFRight = CreateHisto("hResTOFRight", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  TH1F* hResTOFWrong = CreateHisto("hResTOFWrong", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  hResTOFWrong->SetLineColor(kRed);

  // calorimeters
  TH1F* hEPHOS = CreateHisto("hEPHOS", "PHOS", 100, 0, 50, "E [GeV]", "N");
  TH1F* hEEMCAL = CreateHisto("hEEMCAL", "EMCAL", 100, 0, 50, "E [GeV]", "N");

  // muons
  TH1F* hPtMUON = CreateHisto("hPtMUON", "MUON", 100, 0, 20, 
			      "p_{t} [GeV/c]", "N");

  // V0s and cascades
  TH1F* hMassK0 = CreateHisto("hMassK0", "K^{0}", 100, 0.4, 0.6, 
			      "M(#pi^{+}#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambda = CreateHisto("hMassLambda", "#Lambda", 100, 1.0, 1.2, 
				  "M(p#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambdaBar = CreateHisto("hMassLambdaBar", "#bar{#Lambda}", 
				     100, 1.0, 1.2, 
				     "M(#bar{p}#pi^{+}) [GeV/c^{2}]", "N");
  Int_t nGenV0s = 0;
  Int_t nRecV0s = 0;
  TH1F* hMassXi = CreateHisto("hMassXi", "#Xi", 100, 1.2, 1.5, 
			      "M(#Lambda#pi) [GeV/c^{2}]", "N");
  TH1F* hMassOmega = CreateHisto("hMassOmega", "#Omega", 100, 1.5, 1.8, 
				 "M(#LambdaK) [GeV/c^{2}]", "N");
  Int_t nGenCascades = 0;
  Int_t nRecCascades = 0;

  // loop over events
  for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
    runLoader->GetEvent(iEvent);

    // select simulated primary particles, V0s and cascades
    AliStack* stack = runLoader->Stack();
    Int_t nParticles = stack->GetNtrack();
    TArrayF vertex(3);
    runLoader->GetHeader()->GenEventHeader()->PrimaryVertex(vertex);
    TObjArray selParticles;
    TObjArray selV0s;
    TObjArray selCascades;
    for (Int_t iParticle = 0; iParticle < nParticles; iParticle++) {
      TParticle* particle = stack->Particle(iParticle);
      if (!particle) continue;
      if (particle->Pt() < 0.001) continue;
      if (TMath::Abs(particle->Eta()) > 0.9) continue;
      TVector3 dVertex(particle->Vx() - vertex[0], 
		       particle->Vy() - vertex[1],
		       particle->Vz() - vertex[2]);
      if (dVertex.Mag() > 0.0001) continue;

      switch (TMath::Abs(particle->GetPdgCode())) {
      case kElectron:
      case kMuonMinus:
      case kPiPlus:
      case kKPlus:
      case kProton: {
	if (particle->Pt() > minPt) {
	  selParticles.Add(particle);
	  nGen++;
	  hGen->Fill(particle->Pt());
	}
	break;
      }
      case kK0Short:
      case kLambda0: {
	if (particle->Pt() > cutPtV0) {
	  nGenV0s++;
	  selV0s.Add(particle);
	}
	break;
      }
      case kXiMinus:
      case kOmegaMinus: {
	if (particle->Pt() > cutPtCascade) {
	  nGenCascades++;
	  selCascades.Add(particle);
	}
	break;
      }
      default: break;
      }
    }

    // get the event summary data
    tree->GetEvent(iEvent);
    if (!esd) {
      Error("CheckESD", "no ESD object found for event %d", iEvent);
      return kFALSE;
    }

    // loop over tracks
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfTracks(); iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);

      // select tracks of selected particles
      Int_t label = TMath::Abs(track->GetLabel());
      if (label > stack->GetNtrack()) continue;     // background
      TParticle* particle = stack->Particle(label);
      if (!selParticles.Contains(particle)) continue;
      if ((track->GetStatus() & AliESDtrack::kITSrefit) == 0) continue;
      if (track->GetConstrainedChi2() > 1e9) continue;
      selParticles.Remove(particle);   // don't count multiple tracks

      nRec++;
      hRec->Fill(particle->Pt());
      if (track->GetLabel() < 0) nFake++;

      // resolutions
      hResPtInv->Fill(100. * (TMath::Abs(track->GetSigned1Pt()) - 1./particle->Pt()) * 
		      particle->Pt());
      hResPhi->Fill(1000. * (track->Phi() - particle->Phi()));
      hResTheta->Fill(1000. * (track->Theta() - particle->Theta()));

      // PID
      if ((track->GetStatus() & AliESDtrack::kESDpid) == 0) continue;
      Int_t iGen = 5;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	if (TMath::Abs(particle->GetPdgCode()) == partCode[i]) iGen = i;
      }
      Double_t probability[AliPID::kSPECIES];
      track->GetESDpid(probability);
      Double_t pMax = 0;
      Int_t iRec = 0;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	probability[i] *= partFrac[i];
	if (probability[i] > pMax) {
	  pMax = probability[i];
	  iRec = i;
	}
      }
      identified[iGen][iRec]++;
      if (iGen == iRec) nIdentified++;

      // dE/dx and TOF
      Double_t time[AliPID::kSPECIES];
      track->GetIntegratedTimes(time);
      if (iGen == iRec) {
	hDEdxRight->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFRight->Fill(track->GetTOFsignal() - time[iRec]);
	}
      } else {
	hDEdxWrong->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFWrong->Fill(track->GetTOFsignal() - time[iRec]);
	}
      }
    }

    // loop over muon tracks
    {
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfMuonTracks(); iTrack++) {
      AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack);
      Double_t ptInv = TMath::Abs(muonTrack->GetInverseBendingMomentum());
      if (ptInv > 0.001) {
	hPtMUON->Fill(1./ptInv);
      }
    }
    }

    // loop over V0s
    for (Int_t iV0 = 0; iV0 < esd->GetNumberOfV0s(); iV0++) {
      AliESDv0* v0 = esd->GetV0(iV0);
      if (v0->GetOnFlyStatus()) continue;
      v0->ChangeMassHypothesis(kK0Short);
      hMassK0->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0);
      hMassLambda->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0Bar);
      hMassLambdaBar->Fill(v0->GetEffMass());

      Int_t negLabel = TMath::Abs(esd->GetTrack(v0->GetNindex())->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background
      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(v0->GetPindex())->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background
      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      TParticle* particle = stack->Particle(negMother);
      if (!selV0s.Contains(particle)) continue;
      selV0s.Remove(particle);
      nRecV0s++;
    }

    // loop over Cascades
    for (Int_t iCascade = 0; iCascade < esd->GetNumberOfCascades(); 
	 iCascade++) {
      AliESDcascade* cascade = esd->GetCascade(iCascade);
      Double_t v0q;
      cascade->ChangeMassHypothesis(v0q,kXiMinus);
      hMassXi->Fill(cascade->GetEffMassXi());
      cascade->ChangeMassHypothesis(v0q,kOmegaMinus);
      hMassOmega->Fill(cascade->GetEffMassXi());

      Int_t negLabel = TMath::Abs(esd->GetTrack(cascade->GetNindex())
				  ->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background
      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(cascade->GetPindex())
				  ->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background
      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      Int_t v0Mother = stack->Particle(negMother)->GetMother(0);
      if (v0Mother < 0) continue;
      Int_t bacLabel = TMath::Abs(esd->GetTrack(cascade->GetBindex())
				  ->GetLabel());
      if (bacLabel > stack->GetNtrack()) continue;     // background
      Int_t bacMother = stack->Particle(bacLabel)->GetMother(0);
      if (v0Mother != bacMother) continue;
      TParticle* particle = stack->Particle(v0Mother);
      if (!selCascades.Contains(particle)) continue;
      selCascades.Remove(particle);
      nRecCascades++;
    }

    // loop over the clusters
    {
      for (Int_t iCluster=0; iCluster<esd->GetNumberOfCaloClusters(); iCluster++) {
	AliESDCaloCluster * clust = esd->GetCaloCluster(iCluster);
	if (clust->IsPHOS()) hEPHOS->Fill(clust->E());
	if (clust->IsEMCAL()) hEEMCAL->Fill(clust->E());
      }
    }

  }

  // perform checks
  if (nGen < checkNGenLow) {
    Warning("CheckESD", "low number of generated particles: %d", Int_t(nGen));
  }

  TH1F* hEff = CreateEffHisto(hGen, hRec);

  Info("CheckESD", "%d out of %d tracks reconstructed including %d "
	 "fake tracks", nRec, nGen, nFake);
  if (nGen > 0) {
    // efficiency
    Double_t eff = nRec*1./nGen;
    Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGen);
    Double_t fake = nFake*1./nGen;
    Double_t fakeError = TMath::Sqrt(fake*(1.-fake) / nGen);
    Info("CheckESD", "eff = (%.1f +- %.1f) %%  fake = (%.1f +- %.1f) %%",
	 100.*eff, 100.*effError, 100.*fake, 100.*fakeError);

    if (eff < checkEffLow - checkEffSigma*effError) {
      Warning("CheckESD", "low efficiency: (%.1f +- %.1f) %%", 
	      100.*eff, 100.*effError);
    }
    if (fake > checkFakeHigh + checkFakeSigma*fakeError) {
      Warning("CheckESD", "high fake: (%.1f +- %.1f) %%", 
	      100.*fake, 100.*fakeError);
    }

    // resolutions
    Double_t res, resError;
    if (FitHisto(hResPtInv, res, resError)) {
      Info("CheckESD", "relative inverse pt resolution = (%.1f +- %.1f) %%",
	   res, resError);
      if (res > checkResPtInvHigh + checkResPtInvSigma*resError) {
	Warning("CheckESD", "bad pt resolution: (%.1f +- %.1f) %%", 
		res, resError);
      }
    }

    if (FitHisto(hResPhi, res, resError)) {
      Info("CheckESD", "phi resolution = (%.1f +- %.1f) mrad", res, resError);
      if (res > checkResPhiHigh + checkResPhiSigma*resError) {
	Warning("CheckESD", "bad phi resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    if (FitHisto(hResTheta, res, resError)) {
      Info("CheckESD", "theta resolution = (%.1f +- %.1f) mrad", 
	   res, resError);
      if (res > checkResThetaHigh + checkResThetaSigma*resError) {
	Warning("CheckESD", "bad theta resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    // PID
    if (nRec > 0) {
      Double_t eff = nIdentified*1./nRec;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nRec);
      Info("CheckESD", "PID eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkPIDEffLow - checkPIDEffSigma*effError) {
	Warning("CheckESD", "low PID efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }

    printf("%9s:", "gen\\rec");
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      printf("%9s", partName[iRec]);
    }
    printf("\n");
    for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
      printf("%9s:", partName[iGen]);
      for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
	printf("%9d", identified[iGen][iRec]);
      }
      printf("\n");
    }

    if (FitHisto(hResTOFRight, res, resError)) {
      Info("CheckESD", "TOF resolution = (%.1f +- %.1f) ps", res, resError);
      if (res > checkResTOFHigh + checkResTOFSigma*resError) {
	Warning("CheckESD", "bad TOF resolution: (%.1f +- %.1f) ps", 
		res, resError);
      }
    }

    // calorimeters
    if (hEPHOS->Integral() < checkPHOSNLow) {
      Warning("CheckESD", "low number of PHOS particles: %d", 
	      Int_t(hEPHOS->Integral()));
    } else {
      Double_t mean = hEPHOS->GetMean();
      if (mean < checkPHOSEnergyLow) {
	Warning("CheckESD", "low mean PHOS energy: %.1f GeV", mean);
      } else if (mean > checkPHOSEnergyHigh) {
	Warning("CheckESD", "high mean PHOS energy: %.1f GeV", mean);
      }
    }

    if (hEEMCAL->Integral() < checkEMCALNLow) {
      Warning("CheckESD", "low number of EMCAL particles: %d", 
	      Int_t(hEEMCAL->Integral()));
    } else {
      Double_t mean = hEEMCAL->GetMean();
      if (mean < checkEMCALEnergyLow) {
	Warning("CheckESD", "low mean EMCAL energy: %.1f GeV", mean);
      } else if (mean > checkEMCALEnergyHigh) {
	Warning("CheckESD", "high mean EMCAL energy: %.1f GeV", mean);
      }
    }

    // muons
    if (hPtMUON->Integral() < checkMUONNLow) {
      Warning("CheckESD", "low number of MUON particles: %d", 
	      Int_t(hPtMUON->Integral()));
    } else {
      Double_t mean = hPtMUON->GetMean();
      if (mean < checkMUONPtLow) {
	Warning("CheckESD", "low mean MUON pt: %.1f GeV/c", mean);
      } else if (mean > checkMUONPtHigh) {
	Warning("CheckESD", "high mean MUON pt: %.1f GeV/c", mean);
      }
    }

    // V0s
    if (nGenV0s > 0) {
      Double_t eff = nRecV0s*1./nGenV0s;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGenV0s);
      if (effError == 0) effError = checkV0EffLow / TMath::Sqrt(1.*nGenV0s);
      Info("CheckESD", "V0 eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkV0EffLow - checkV0EffSigma*effError) {
	Warning("CheckESD", "low V0 efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }

    // Cascades
    if (nGenCascades > 0) {
      Double_t eff = nRecCascades*1./nGenCascades;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGenCascades);
      if (effError == 0) effError = checkV0EffLow / 
			   TMath::Sqrt(1.*nGenCascades);
      Info("CheckESD", "Cascade eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkCascadeEffLow - checkCascadeEffSigma*effError) {
	Warning("CheckESD", "low Cascade efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }
  }

  // draw the histograms if not in batch mode
  if (!gROOT->IsBatch()) {
    new TCanvas;
    hEff->DrawCopy();
    new TCanvas;
    hResPtInv->DrawCopy("E");
    new TCanvas;
    hResPhi->DrawCopy("E");
    new TCanvas;
    hResTheta->DrawCopy("E");
    new TCanvas;
    hDEdxRight->DrawCopy();
    hDEdxWrong->DrawCopy("SAME");
    new TCanvas;
    hResTOFRight->DrawCopy("E");
    hResTOFWrong->DrawCopy("SAME");
    new TCanvas;
    hEPHOS->DrawCopy("E");
    new TCanvas;
    hEEMCAL->DrawCopy("E");
    new TCanvas;
    hPtMUON->DrawCopy("E");
    new TCanvas;
    hMassK0->DrawCopy("E");
    new TCanvas;
    hMassLambda->DrawCopy("E");
    new TCanvas;
    hMassLambdaBar->DrawCopy("E");
    new TCanvas;
    hMassXi->DrawCopy("E");
    new TCanvas;
    hMassOmega->DrawCopy("E");
  }

  // write the output histograms to a file
  TFile* outputFile = TFile::Open("check.root", "recreate");
  if (!outputFile || !outputFile->IsOpen()) {
    Error("CheckESD", "opening output file check.root failed");
    return kFALSE;
  }
  hEff->Write();
  hResPtInv->Write();
  hResPhi->Write();
  hResTheta->Write();
  hDEdxRight->Write();
  hDEdxWrong->Write();
  hResTOFRight->Write();
  hResTOFWrong->Write();
  hEPHOS->Write();
  hEEMCAL->Write();
  hPtMUON->Write();
  hMassK0->Write();
  hMassLambda->Write();
  hMassLambdaBar->Write();
  hMassXi->Write();
  hMassOmega->Write();
  outputFile->Close();
  delete outputFile;

  // clean up
  delete hGen;
  delete hRec;
  delete hEff;
  delete hResPtInv;
  delete hResPhi;
  delete hResTheta;
  delete hDEdxRight;
  delete hDEdxWrong;
  delete hResTOFRight;
  delete hResTOFWrong;
  delete hEPHOS;
  delete hEEMCAL;
  delete hPtMUON;
  delete hMassK0;
  delete hMassLambda;
  delete hMassLambdaBar;
  delete hMassXi;
  delete hMassOmega;

  delete esd;
  esdFile->Close();
  delete esdFile;

  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

  // result of check
  Info("CheckESD", "check of ESD was successfull");
  return kTRUE;
}