Exemplo n.º 1
0
void binary( string inFile = "allSim.root", int cSpecies = 1, bool cutDedx = false ){

	TCanvas * c = new TCanvas( "c", "c", 800, 800 );
	string outName = "rpBinaryPid.pdf";
	c->Print( (outName+"[").c_str() );

	TFile * f = new TFile( inFile.c_str(), "READ" );

	string rOutName = "rootBinaryPid.root";
	TFile * fOut = new TFile( rOutName.c_str(), "RECREATE" );

	vector<double>effVsP;
	vector<double>pureVsP;

	c->Divide( 2, 2 );
	for ( int i = 0; i < 70; i++ ){

		stringstream sstr;
		sstr << "h_dedx_tof_p3_b" << i;
		TH2* sum = (TH2*)f->Get( sstr.str().c_str() );
		
		sstr.str("");
		sstr << "h_dedx_tof_p0_b" << i;

		TH2* p0 = (TH2*)f->Get( sstr.str().c_str() );
		sstr.str("");
		sstr << "h_dedx_tof_p1_b" << i;
		TH2* p1 = (TH2*)f->Get( sstr.str().c_str() );
		sstr.str("");
		sstr << "h_dedx_tof_p2_b" << i;
		TH2* p2 = (TH2*)f->Get( sstr.str().c_str() );

		pidBinary * pid = new pidBinary( sum, cSpecies, p0, p1, p2 );
		pid->cutDedx( cutDedx );

		c->cd( 3 );
		gPad->SetLogz(1);
		sum->Draw("colz");
		

		c->cd( 4 );
		gPad->SetLogx(1);
		TH1* pX = sum->ProjectionX();
		TH1* pY = sum->ProjectionY();
		pY->SetFillColor( kBlue );
		pY->SetLineColor( kBlue );
		pY->Draw("hbar");


		c->cd(1);
		gPad->SetLogy(1);
		pX->SetFillColor( kBlue );
		pX->SetLineColor( kBlue );
		pX->Draw("h");
		c->cd(2);
		
		sstr.str("");
		sstr << "eff_" << i;
		TH1D* eff = pid->efficiency( sstr.str(), 0.0, 5.0, 0.1 );
		sstr.str("");
		sstr << "pure_" << i;
		TH1D* pure = pid->purity( sstr.str(), 0.0, 5.0, 0.1 );

		gStyle->SetOptStat( 0 );
		eff->SetTitle( "Efficiecy (Blue), Purity (Red)" );
		eff->GetYaxis()->SetRangeUser(0, 1.05);
		eff->SetLineWidth( 2 );
		eff->Draw();
		pure->SetLineColor( kRed );
		pure->SetLineWidth( 2 );
		pure->Draw("same");

		effVsP.push_back( pid->efficiency() );
		pureVsP.push_back( pid->purity( ) );

		c->Print( outName.c_str());
	}

	int nBins = (3.7 - 0.2) / 0.05;
	TH1D * hEffVsP = new TH1D( "hEffVsP", "Efficiency Vs. P; P [GeV]", nBins, 0.2, 3.7 );
	for ( int i = 0; i < effVsP.size(); i++ ){
		hEffVsP->SetBinContent( i, effVsP[ i ] );
	}
	TH1D * hPureVsP = new TH1D( "hPureVsP", "Purity Vs. P; P [GeV]", nBins, 0.2, 3.7 );
	for ( int i = 0; i < pureVsP.size(); i++ ){
		hPureVsP->SetBinContent( i, pureVsP[ i ] );
	}

	c->Divide( 1 );
	c->cd( 0 );
	hEffVsP->GetYaxis()->SetRangeUser( 0.0, 1.05);
	hEffVsP->SetLineWidth( 2 );
	hEffVsP->SetTitle( "Efficiency (Blue), Purity (Red)" );
	hEffVsP->Draw( "");
	hPureVsP->SetLineColor( kRed );
	hPureVsP->SetLineWidth( 2 );
	hPureVsP->Draw( "same" );

	c->Print( outName.c_str());



	c->Print( (outName+"]").c_str() );

	fOut->Write();

}
void EMCDistribution_PeakSample_Fast(bool full_gain = false)
{
  const TString gain = "RAW";

  TString hname = "EMCDistribution_" + gain + TString(full_gain ? "_FullGain" : "") + cuts;

  TH2 *h2 = NULL;
  {
    if (full_gain)
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 100,
                    .05 * 100, 25 * 100, 64, -.5, 63.5);
      QAHistManagerDef::useLogBins(h2->GetXaxis());
    }
    else
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 260,
                    -.2 * 100, 5 * 100, 64, -.5, 63.5);
    }
    T->Draw(
        "TOWER_" + gain + "_CEMC[].get_bineta() + 8* TOWER_" + gain + "_CEMC[].get_binphi():(TOWER_RAW_CEMC[].signal_samples[10] - TOWER_RAW_CEMC[].signal_samples[0])*(-1)>>" + hname, "", "goff");
  }

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts,
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts, 1800, 950);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      if (full_gain)
      {
        p->SetLogx();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(full_gain ? "_FullGain" : "");

      TH1 *h = h2->ProjectionX(hname, ieta + 8 * iphi + 1,
                               ieta + 8 * iphi + 1);  // axis bin number is encoded as ieta+8*iphi+1

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);

      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      h->Draw();

      if (full_gain)
        h->Fit("x*gaus", "M");
      else
        h->Fit("landau", "M");

      double peak = -1;

      TF1 *fit = ((TF1 *) (h->GetListOfFunctions()->At(0)));
      if (fit)
      {
        fit->SetLineColor(kRed);
        peak = fit->GetParameter(1);
      }

      cout << Form("Finished <Col%d Row%d> = %.1f", ieta, iphi, peak)
           << endl;

      TText *t = new TText(.9, .9,
                           Form("<Col%d Row%d> = %.1f", ieta, iphi, peak));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype4EMCalTower_") + TString(c1->GetName()), false);
}
void plot_efficiencies( TFile* file, Int_t type = 2, TDirectory* BinDir=0)
{
   // input:   - Input file (result from TMVA),
   //          - type = 1 --> plot efficiency(B) versus eff(S)
   //                 = 2 --> plot rejection (B) versus efficiency (S)
   //                 = 3 --> plot 1/eff(B) versus efficiency (S)

   Bool_t __PLOT_LOGO__  = kTRUE;
   Bool_t __SAVE_IMAGE__ = kTRUE;

   // the coordinates
   Float_t x1 = 0;
   Float_t x2 = 1;
   Float_t y1 = 0;
   Float_t y2 = 0.8;

   // reverse order if "rejection"
   if (type == 2) {
      Float_t z = y1;
      y1 = 1 - y2;
      y2 = 1 - z;
      //      cout << "--- type==2: plot background rejection versus signal efficiency" << endl;
   } else if (type == 3) {
      y1 = 0;
      y2 = -1; // will be set to the max found in the histograms

   } else {
      //  cout << "--- type==1: plot background efficiency versus signal efficiency" << endl;
   }
   // create canvas
   TCanvas* c = new TCanvas( "c", "the canvas", 200, 0, 650, 500 );

   // global style settings
   c->SetGrid();
   c->SetTicks();

   // legend
   Float_t x0L = 0.107,     y0H = 0.899;
   Float_t dxL = 0.457-x0L, dyH = 0.22;
   if (type == 2) {
      x0L = 0.15;
      y0H = 1 - y0H + dyH + 0.07;
   }
   TLegend *legend = new TLegend( x0L, y0H-dyH, x0L+dxL, y0H );
   //legend->SetTextSize( 0.05 );
   legend->SetHeader( "MVA Method:" );
   legend->SetMargin( 0.4 );

   TString xtit = "Signal efficiency";
   TString ytit = "Background efficiency";
   if (type == 2) ytit = "Background rejection";
   if (type == 3) ytit = "1/(Background eff.)";
   TString ftit = ytit + " versus " + xtit;

   TString hNameRef = "effBvsS";
   if (type == 2) hNameRef = "rejBvsS";
   if (type == 3) hNameRef = "invBeffvsSeff";


   if (TString(BinDir->GetName()).Contains("multicut")){
      ftit += "  Bin: ";
      ftit += (BinDir->GetTitle());
   }

   TList xhists;
   TList xmethods;
   UInt_t xnm = TMVAGlob::GetListOfMethods( xmethods );
   TIter xnext(&xmethods);
   // loop over all methods
   TKey *xkey;
   while ((xkey = (TKey*)xnext())) {
      TDirectory * mDir = (TDirectory*)xkey->ReadObj();
      TList titles;
      UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles);
      TIter nextTitle(&titles);
      TKey *titkey;
      TDirectory *titDir;
      while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) {
         titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);
         TIter nextKey( titDir->GetListOfKeys() );
         TKey *hkey2;
         while ((hkey2 = TMVAGlob::NextKey(nextKey,"TH1"))) {
            TH1 *h = (TH1*)hkey2->ReadObj();
            TString hname = h->GetName();
            if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) {
               if (type==3 && h->GetMaximum() > y2) y2 = h->GetMaximum()*1.1;
            }
         }
      }
   }


   // draw empty frame
   if(gROOT->FindObject("frame")!=0) gROOT->FindObject("frame")->Delete();
   TH2F* frame = new TH2F( "frame", ftit, 500, x1, x2, 500, y1, y2 );
   frame->GetXaxis()->SetTitle( xtit );
   frame->GetYaxis()->SetTitle( ytit );
   TMVAGlob::SetFrameStyle( frame, 1.0 );

   frame->Draw();

   Int_t color = 1;
   Int_t nmva  = 0;
   TKey *key;

   TList hists;
   TList methods;
   UInt_t nm = TMVAGlob::GetListOfMethods( methods );
   //   TIter next(file->GetListOfKeys());
   TIter next(&methods);

   // loop over all methods
   while ((key = (TKey*)next())) {
      TDirectory * mDir = (TDirectory*)key->ReadObj();
      TList titles;
      UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles);
      TIter nextTitle(&titles);
      TKey *titkey;
      TDirectory *titDir;
      while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) {
         titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);
         TIter nextKey( titDir->GetListOfKeys() );
         TKey *hkey2;
         while ((hkey2 = TMVAGlob::NextKey(nextKey,"TH1"))) {
            TH1 *h = (TH1*)hkey2->ReadObj();
            TString hname = h->GetName();
            if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) {
               h->SetLineWidth(3);
               h->SetLineColor(color);
               color++; if (color == 5 || color == 10 || color == 11) color++;
               h->Draw("csame");
               hists.Add(h);
               nmva++;
            }
         }
      }
   }

   while (hists.GetSize()) {
      TListIter hIt(&hists);
      TH1* hist(0);
      Double_t largestInt=-1;
      TH1* histWithLargestInt(0);
      while ((hist = (TH1*)hIt())!=0) {
         Double_t integral = hist->Integral(1,hist->FindBin(0.9999));
         if (integral>largestInt) {
            largestInt = integral;
            histWithLargestInt = hist;
         }
      }
      if (histWithLargestInt == 0) {
         cout << "ERROR - unknown hist \"histWithLargestInt\" --> serious problem in ROOT file" << endl;
         break;
      }
      legend->AddEntry(histWithLargestInt,TString(histWithLargestInt->GetTitle()).ReplaceAll("MVA_",""),"l");
      hists.Remove(histWithLargestInt);
   }

   // rescale legend box size
   // current box size has been tuned for 3 MVAs + 1 title
   if (type == 1) {
      dyH *= (1.0 + Float_t(nmva - 3.0)/4.0);
      legend->SetY1( y0H - dyH );
   }
   else {
      dyH *= (Float_t(TMath::Min(10,nmva) - 3.0)/4.0);
      legend->SetY2( y0H + dyH);
   }

   // redraw axes
   frame->Draw("sameaxis");
   legend->Draw("same");

   // ============================================================

   if (__PLOT_LOGO__) TMVAGlob::plot_logo();

   // ============================================================

   c->Update();

   TString fname = "plots/" + hNameRef;
   if (TString(BinDir->GetName()).Contains("multicut")){
      TString fprepend(BinDir->GetName());
      fprepend.ReplaceAll("multicutMVA_","");
      fname = "plots/" + fprepend + "_" + hNameRef;
   }
   if (__SAVE_IMAGE__) TMVAGlob::imgconv( c, fname );

   return;
}
Exemplo n.º 4
0
RooHistN::RooHistN(const TH1 &data1, const TH1 &data2, Double_t nominalBinWidth, Double_t nSigma, Double_t xErrorFrac) :
  TGraphAsymmErrors(), _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
{
  // Create a histogram from the asymmetry between the specified TH1 objects
  // which may have fixed or variable bin widths, but which must both have
  // the same binning. The asymmetry is calculated as (1-2)/(1+2). Error bars are
  // calculated using Binomial statistics. Prints a warning and rounds
  // any bins with non-integer contents. Use the optional parameter to
  // specify the confidence level in units of sigma to use for
  // calculating error bars. The nominal bin width specifies the
  // default used by addAsymmetryBin(), and is used to set the relative
  // normalization of bins with different widths. If not set, the
  // nominal bin width is calculated as range/nbins.

  initialize();
  // copy the first input histogram's name and title
  SetName(data1.GetName());
  SetTitle(data1.GetTitle());
  // calculate our nominal bin width if necessary
  if(_nominalBinWidth == 0) {
    const TAxis *axis= ((TH1&)data1).GetXaxis();
    if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins();
  }
  setYAxisLabel(Form("Asymmetry (%s - %s)/(%s + %s)",
		     data1.GetName(),data2.GetName(),data1.GetName(),data2.GetName()));
  // initialize our contents from the input histogram contents
  Int_t nbin= data1.GetNbinsX();
  if(data2.GetNbinsX() != nbin) {
    coutE(InputArguments) << "RooHistN::RooHistN: histograms have different number of bins" << endl;
    return;
  }
  for(Int_t bin= 1; bin <= nbin; bin++) {
    Axis_t x= data1.GetBinCenter(bin);
    if(fabs(data2.GetBinCenter(bin)-x)>1e-10) {
      coutW(InputArguments) << "RooHistN::RooHistN: histograms have different centers for bin " << bin << endl;
    }
    Stat_t y1= data1.GetBinContent(bin);
    Stat_t y2= data2.GetBinContent(bin);
    addAsymmetryBin(x,roundBin(y1),roundBin(y2),data1.GetBinWidth(bin),xErrorFrac);
  }
  // we do not have a meaningful number of entries
  _entries= -1;
}
void EMCDistribution_ADC(bool log_scale = true)
{
  TString gain = "RAW";

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_ADC_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      "EMCDistribution_ADC_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      1800, 1000);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      if (log_scale)
      {
        p->SetLogz();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(log_scale ? "_Log" : "");

      TH1 *h = NULL;

      if (log_scale)
        h = new TH2F(hname,
                     Form(";Sample ID;ADC"), 31, -.5,
                     30.5,
                     //                128+64, 0, 3096);
                     1 << 10, 0, 1 << 14);
      //          else
      //            h = new TH2F(hname,
      //                Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 100,
      //                -.050, .5,128,0,2048);

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);
      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);
      //          h->GetYaxis()->SetRangeUser(2000,3000);

      //          if (log_scale)
      //            QAHistManagerDef::useLogBins(h->GetYaxis());

      TString sdraw = "TOWER_" + gain + "_CEMC[].signal_samples[]:fmod(Iteration$,31)>>" + hname;
      TString scut =
          Form(
              "TOWER_%s_CEMC[].get_bineta()==%d && TOWER_%s_CEMC[].get_binphi()==%d",
              gain.Data(), ieta, gain.Data(), iphi);

      cout << "T->Draw(\"" << sdraw << "\",\"" << scut << "\");" << endl;

      T->Draw(sdraw, scut, "colz");

      TText *t = new TText(.9, .9, Form("Col%d Row%d", ieta, iphi));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();

      //          return;
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype4EMCalTower_") + TString(c1->GetName()), false);
}
Exemplo n.º 6
0
void SetStyle(TH1& h, double size, int color, int style, int fillstyle=0, int linestyle=1){
	h.SetMarkerSize(size);
	h.SetMarkerColor(color);
	h.SetLineColor(color);
	h.SetMarkerStyle(style);
	h.SetFillStyle(fillstyle);
	h.SetLineStyle(linestyle);
	h.GetXaxis()->SetTitleFont(42);
	h.GetYaxis()->SetTitleFont(42);
	h.GetXaxis()->SetTitleSize(0.048);
	h.GetYaxis()->SetTitleSize(0.048);
	h.GetXaxis()->CenterTitle();
	h.GetYaxis()->CenterTitle();
}
Exemplo n.º 7
0
void SetXRange(TH1 &h, double xmin, double xmax){
	h.GetXaxis()->SetRangeUser(xmin,xmax);
}
Exemplo n.º 8
0
/*============================================================================*/
void gaus2peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[8],epar[8],x[2],y[2];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

  //--**-- Linear background estimation --**--//
  x[0] = x1;
  x[1] = x4;
  Int_t bin1 = hist->FindBin(x1);
  y[0] = hist->GetBinContent(bin1);
  Int_t bin2 = hist->FindBin(x4);
  y[1] = hist->GetBinContent(bin2);
  TGraph *g = new TGraph(2,x,y);
  TF1 *fpol1 = new TF1("POL1","pol1",x1,x4);
  g->Fit(fpol1,"RQN");
  par[6]=fpol1->GetParameter(0);
  par[7]=fpol1->GetParameter(1);

  //--**-- Two Gaussian Peak estimation without background --**--//
  fgaus1 = new TF1("m1","gaus",x1,x2);
  fgaus2 = new TF1("m2","gaus",x3,x4);
  hist->Fit(fgaus1,"R+QN");
  hist->Fit(fgaus2,"R+QN");
  fgaus1->GetParameters(&par[0]);
  fgaus2->GetParameters(&par[3]);

  //--**-- Final Peak Fit with Background --**--//
  func = new TF1("m","gaus(0)+gaus(3)+pol1(6)",x1,x4);
  func->SetParameters(par);

  
  hist->Fit(func,"R+QN");
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  epar[3]=func->GetParError(3);
  epar[4]=func->GetParError(4);
  epar[5]=func->GetParError(5);
 
  Double_t fwhm1 = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm1 = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N10 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r10 = epar[0]/par[0];
  Double_t r12 = epar[2]/par[2];
  Double_t eN10= N10*TMath::Sqrt(r10*r10+r12*r12);

  Double_t fwhm2 = par[5]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm2 = epar[5]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N20 = par[3]*(TMath::Sqrt(TMath::TwoPi())*par[5]);
  Double_t r20 = epar[3]/par[3];
  Double_t r22 = epar[5]/par[5];
  Double_t eN20= N20*TMath::Sqrt(r20*r20+r22*r22);

  //printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
  //        par[1],epar[1],fwhm1,efwhm1,N10,eN10);
  //printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
  //        par[4],epar[4],fwhm2,efwhm2,N20,eN20);
  printf("%11.4f %11.4f %11.0f %11.0f\n",
          par[1],epar[1],N10,eN10);
  printf("%11.4f %11.4f %11.0f %11.0f\n",
          par[4],epar[4],N20,eN20);
}
Exemplo n.º 9
0
void CombinePreScale()
{

    double jetptbin[] = {27, 33, 39, 47, 55, 64,74, 84, 97, 114, 133, 153, 174, 196, 220, 245, 272, 300, 429, 692, 1000};   
    int nbins = sizeof(jetptbin)/sizeof(double)-1; 

    TString kDir="/scratch/xuq7/RpA/TreeAna";
    TString algo ="akPu3PF"; //"AkPu3PF" ;
    TString residual = "NoResidual"; //"NoResidual" ;
    TString coll = "PPbNoGplus" ; // or "PbP" ;
    TString class = "HFsumEta4Bin1" ; // "" for inclusive ;
    TString effTab = "TrkEffHIN12017v5TrkCorr2DCut" ;  //"HistIterTrkCorrtestFilterCut"; //  "Trk" ; "HistIterTrkCorrtest" ;
    const int Nfile = 5 ;
    TFile * f ;
    TString name[]={"jetptEta","jetptphi","jetEtaphi","jetptchMax","jetptchSum","jetptneuMax","jetptneuSum","jetptphoMax","jetptphoSum","jetptchMaxpt","jetptchSumpt","jetptneuMaxpt","jetptneuSumpt","jetptphoMaxpt","jetptphoSumpt","jetptSumSumpt","jetptSumSumrawpt","jetptneuMaxr","jetptchN","jetptneuN","jetptphoN"};
    TString etaname[]={"jetpt","rawptJES","jetptchMaxpt","jetptneuMaxr","jetptSumSumpt"};
    int nname=sizeof(name)/sizeof(TString);
    int netaname=sizeof(etaname)/sizeof(TString);
    f = TFile::Open(Form("%s/AllTrigLumiDATAPPb%sDiJetMass.root",kDir.Data(),algo.Data()),"readonly");
    TString outname ;
    outname ="Datacombined.root";
    TFile * outf = new TFile(Form("%s/%s", kDir.Data(), outname.Data()), "RECREATE");
//    f =  TFile::Open("AllTrigLumiDATAPPbakPu3PFDiJetMass.root", "readonly");
for(int m=0;m<nname;m++){
    TH1 *hCombined;
    TH1 *hTrkPt[5];
  
                hTrkPt[0] = (TH1*)f->Get(Form("Jet20%s_0-100%%",name[m].Data()));
                hTrkPt[1] = (TH1*)f->Get(Form("Jet40%s_0-100%%",name[m].Data()));
                hTrkPt[2] = (TH1*)f->Get(Form("Jet60%s_0-100%%",name[m].Data()));
                hTrkPt[3] = (TH1*)f->Get(Form("Jet80%s_0-100%%",name[m].Data()));
                hTrkPt[4] = (TH1*)f->Get(Form("Jet100%s_0-100%%",name[m].Data()));
    for( int i = 0; i<5; i++)
    {
        if(i==0){ 
	hCombined = (TH1*)hTrkPt[i]->Clone(Form("%sCombinedSpectra",name[m].Data()));
	hCombined->SetTitle("");
	}
        else hCombined->Add(hTrkPt[i]);
    }
    hCombined->Write();
}
     double etaMin[8] = {-1.,-2.2,-1.2,-0.7,-0.3,0.3,0.7,1.2};
    double etaMax[8] = { 1.,-1.2,-0.7,-0.3, 0.3,0.7,1.2,2.2};
TH1* hTrk[8][5];
TH1* hCombinedEtaBin[8];
for(int m=0;m<netaname;m++){
	    for(int ieta=0; ieta<8; ieta++){
            if(ieta==0){
                hTrk[ieta][0] = (TH1*)f->Get(Form("Jet20%s_0-100%%",etaname[m].Data()));
                hTrk[ieta][1] = (TH1*)f->Get(Form("Jet40%s_0-100%%",etaname[m].Data()));
                hTrk[ieta][2] = (TH1*)f->Get(Form("Jet60%s_0-100%%",etaname[m].Data()));
                hTrk[ieta][3] = (TH1*)f->Get(Form("Jet80%s_0-100%%",etaname[m].Data()));
                hTrk[ieta][4] = (TH1*)f->Get(Form("Jet100%s_0-100%%",etaname[m].Data()));
            }
            else {
                hTrk[ieta][0] = (TH1*)f->Get(Form("Jet20%sEtaBin%.f_%.f_Cen0-100%%",etaname[m].Data(), etaMin[ieta]*10, etaMax[ieta]*10));
                hTrk[ieta][1] = (TH1*)f->Get(Form("Jet40%sEtaBin%.f_%.f_Cen0-100%%",etaname[m].Data(), etaMin[ieta]*10, etaMax[ieta]*10));
                hTrk[ieta][2] = (TH1*)f->Get(Form("Jet60%sEtaBin%.f_%.f_Cen0-100%%",etaname[m].Data(), etaMin[ieta]*10, etaMax[ieta]*10));
                hTrk[ieta][3] = (TH1*)f->Get(Form("Jet80%sEtaBin%.f_%.f_Cen0-100%%",etaname[m].Data(), etaMin[ieta]*10, etaMax[ieta]*10));
                hTrk[ieta][4] = (TH1*)f->Get(Form("Jet100%sEtaBin%.f_%.f_Cen0-100%%",etaname[m].Data(), etaMin[ieta]*10, etaMax[ieta]*10));
                }

 for(int i = 0; i<5; i++)
    {
        if(i==0) {
	hCombinedEtaBin[ieta] = (TH1*)hTrk[ieta][i]->Clone(Form("%sCombinedSpectraInEtaBin%.f_%.f",etaname[m].Data(), etaMin[ieta]*10, etaMax[ieta]*10));
	hCombinedEtaBin[ieta]->SetTitle("");
	}
        else hCombinedEtaBin[ieta]->Add(hTrk[ieta][i]);
    }
    hCombinedEtaBin[ieta]->Write();
}
}

    outf->Close();//write into a root file
    
}
Exemplo n.º 10
0
void plot_fitter_validation()
{
  TFile* fin = new TFile("fitter_validation_cafana.root");

  const int dcpCols[] = {kBlack, kRed, kGreen+2, kBlue};
  const std::string dcpStrs[] = {"0", "#pi/2", "#pi", "3#pi/2"};

  for(std::string hcStr: {"fhc", "rhc"}){
    const std::string HCStr = (hcStr == "fhc") ? "FHC" : "RHC";

    for(std::string chanStr: {"numu", "nue"}){
      const std::string CHANStr = (chanStr == "numu") ? "#nu_{#mu}" : "#nu_{e}";

      for(std::string hieStr: {"nh", "ih"}){
        const std::string HIEStr = (hieStr == "nh") ? "NH" : "IH";

        new TCanvas;

        for(int deltaIdx2 = 0; deltaIdx2 < 4; ++deltaIdx2){
          // For neutrinos 3pi/2 is the tallest histogram, draw it first, for
          // antineutrinos we need pi/2 first.
          const int deltaIdx = (hcStr == "fhc") ? 3-deltaIdx2 : (deltaIdx2+1)%4;

          const std::string dcpStr = TString::Format("%gpi", deltaIdx/2.).Data();

          TH1* h = (TH1*)fin->Get((chanStr+"_"+hcStr+"_"+hieStr+"_"+dcpStr).c_str());
          h->SetLineColor(dcpCols[deltaIdx]);
          h->Draw("same");

          h->SetTitle(("5 yrs "+HCStr+" "+CHANStr+" "+HIEStr).c_str());
        } // end for deltaIdx

        TLegend* leg = new TLegend(.6, .6, .85, .85);
        leg->SetFillStyle(0);
        for(int deltaIdx = 0; deltaIdx < 4; ++deltaIdx){
          TH1* dummy = new TH1F("", "", 1, 0, 1);
          dummy->SetLineColor(dcpCols[deltaIdx]);
          leg->AddEntry(dummy, ("#delta_{CP}="+dcpStrs[deltaIdx]).c_str(), "l");
        }
        leg->Draw("same");

        gPad->Print((hcStr+"_"+chanStr+"_"+hieStr+".pdf").c_str());
      } // end for hieStr
    } // end for chanStr
  } // end for hcStr


  TGraph* gNH = (TGraph*)fin->Get("sens_nh");
  TGraph* gIH = (TGraph*)fin->Get("sens_ih");
  TGraph* gNHOscErr = (TGraph*)fin->Get("sens_nh_oscerr");
  TGraph* gIHOscErr = (TGraph*)fin->Get("sens_ih_oscerr");

  TGraph* gNHFlux[10];
  TGraph* gIHFlux[10];
  for(int i = 0; i < 10; ++i){
    gNHFlux[i] = (TGraph*)fin->Get(TString::Format("sens_nh_flux%d", i).Data());
    gIHFlux[i] = (TGraph*)fin->Get(TString::Format("sens_ih_flux%d", i).Data());
  }

  TGraph* gNHXSec[10];
  TGraph* gIHXSec[10];
  for(int i = 0; i < 10; ++i){
    gNHXSec[i] = (TGraph*)fin->Get(TString::Format("sens_nh_xsec%d", i).Data());
    gIHXSec[i] = (TGraph*)fin->Get(TString::Format("sens_ih_xsec%d", i).Data());
  }

  TH2* axes = new TH2F("", ";#delta_{CP} / #pi;#sigma = #sqrt{#Delta#chi^{2}}", 100, 0, 2, 100, 0, 8);
  axes->GetXaxis()->CenterTitle();
  axes->GetYaxis()->SetTitleOffset(.75);
  axes->GetYaxis()->CenterTitle();
  axes->Draw();

  gNH->Draw("l same");
  gIH->Draw("l same");
  gNHOscErr->Draw("l same");
  gIHOscErr->Draw("l same");

  TLegend* leg = new TLegend(.4, .65, .6, .875);
  leg->SetFillStyle(0);
  leg->AddEntry(gNH, "NH", "l");
  leg->AddEntry(gIH, "IH", "l");
  leg->AddEntry(gNHOscErr, "NH osc err", "l");
  leg->AddEntry(gIHOscErr, "IH osc err", "l");
  leg->Draw();

  gPad->Print("mcd.pdf");


  new TCanvas;
  axes->Draw();
  for(int i = 0; i < 10; ++i){
    gNHFlux[i]->Draw("l same");
    gIHFlux[i]->Draw("l same");
  }
  gNH->Draw("l same");
  gIH->Draw("l same");

  leg = new TLegend(.4, .65, .6, .875);
  leg->SetFillStyle(0);
  leg->AddEntry(gNH, "NH", "l");
  leg->AddEntry(gIH, "IH", "l");
  leg->AddEntry(gNHFlux[0], "NH flux err", "l");
  leg->AddEntry(gIHFlux[0], "IH flux err", "l");
  leg->Draw();

  gPad->Print("mcd_flux.pdf");


  new TCanvas;
  axes->Draw();
  for(int i = 0; i < 10; ++i){
    gNHXSec[i]->Draw("l same");
    gIHXSec[i]->Draw("l same");
  }
  gNH->Draw("l same");
  gIH->Draw("l same");

  leg = new TLegend(.4, .65, .6, .875);
  leg->SetFillStyle(0);
  leg->AddEntry(gNH, "NH", "l");
  leg->AddEntry(gIH, "IH", "l");
  leg->AddEntry(gNHXSec[0], "NH xsec err", "l");
  leg->AddEntry(gIHXSec[0], "IH xsec err", "l");
  leg->Draw();

  gPad->Print("mcd_xsec.pdf");
}
Exemplo n.º 11
0
/*============================================================================*/
void gaus1peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[5],epar[5],x[4],y[4];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  setcanvas(1);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

  //--**-- Linear background estimation --**--//
  x[0] = x1;
  x[1] = x2;
  x[2] = x3;
  x[3] = x4;
  Int_t bin1 = hist->FindBin(x1);
  y[0] = hist->GetBinContent(bin1);
  Int_t bin2 = hist->FindBin(x2);
  y[1] = hist->GetBinContent(bin2);
  Int_t bin3 = hist->FindBin(x3);
  y[2] = hist->GetBinContent(bin3);
  Int_t bin4 = hist->FindBin(x4);
  y[3] = hist->GetBinContent(bin4);
  TGraph *g = new TGraph(4,x,y);
  TF1 *fpol1 = new TF1("POL1","pol1",x1,x4);
  g->Fit(fpol1,"RQN");
  par[3]=fpol1->GetParameter(0);
  par[4]=fpol1->GetParameter(1);

  //--**-- Gaussian Peak estimation without background --**--//
  TF1 *fgaus = new TF1("GAUS","gaus",x2,x3);
  hist->Fit(fgaus,"RQN");
  fgaus->GetParameters(&par[0]);

  //--**-- Final Peak Fit with Background --**--//
  TF1 *func = new TF1("FGAUS","gaus(0)+pol1(3)",x1,x4);
  func->SetParameters(par);
  hist->Fit(func,"R+QN");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  Double_t fwhm = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N0 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r0 = epar[0]/par[0];
  Double_t r2 = epar[2]/par[2];
  Double_t eN0= N0*TMath::Sqrt(r0*r0+r2*r2);
  printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
          par[1],epar[1],fwhm,efwhm,N0,eN0);
  //printf("%11.4f %11.4f %11.0f %11.0f\n",
  //        par[1],epar[1],N0,eN0);
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
}
Exemplo n.º 12
0
void gluinoMass(double lumi=-1., double maxInstLumi=-1.) {
	
  if (lumi<0)
    lumi=877.;
  if (maxInstLumi<0)
    maxInstLumi=1300.;
  LimitPlots plots(lumi);
  
  //mchamp index 0 is used, corresponds to 0th mass point = 100 GeV
  plots.calculateCrossSections(7,4,0,39,9);
	
  // expected limit (1 and 2 sigma bands)
  TGraph* g_exp = plots.getExpMassLimitGluino();
  TGraphAsymmErrors* g_exp1 = plots.getExpMassLimitGluino1Sig();
  TGraphAsymmErrors* g_exp2 = plots.getExpMassLimitGluino2Sig();
  
  // three points on counting expt curve
  TGraph* g_gluino = plots.getMassLimitGluino();
  TGraph* g_stop = plots.getMassLimitStop();
  
  // one point from lifetime fit
  TGraph* g_tp = plots.getMassLimitGluinoTP();
  
  // theory prediction
  TGraph* g_thGluino = plots.getGluinoTheory();
  TGraph* g_thStop = plots.getStopTheory();
  
  TCanvas* canvas = new TCanvas("canvas");
  
  //canvas->SetGrid();
  canvas->SetLogy();
  
  TH1 * h;
  h = canvas->DrawFrame(300., .02, 1000., 1e2);
  //h->SetTitle("Beamgap Expt;m_{#tilde{g}} [GeV/c^{2}]; Stopped HSCP Cross Section #times BR [pb]");
  h->SetTitle("Beamgap Expt;m_{#tilde{g}} [GeV/c^{2}]; #sigma(pp #rightarrow #tilde{g}#tilde{g}) #times BR(#tilde{g} #rightarrow g#tilde{#chi}^{0}) [pb]");
  
  // not covered region
  TBox* nc = new TBox(100., .1, 150., 5e2);
  nc->SetFillStyle(3354);
  nc->SetFillColor(kRed-4);
  //nc->Draw();
  
  // details
  TPaveText* blurb = new TPaveText(300., 2, 550., 1e2);
  blurb->AddText("CMS Preliminary 2012");

  std::stringstream label;
  label<<"#int L dt = "<<lumi<<" fb^{-1}";
  blurb->AddText(label.str().c_str());
  label.str("");
  double peakInstLumi=maxInstLumi;
  int exponent=30;
  while (peakInstLumi>10) {
    peakInstLumi/=10.;
    ++exponent;
  }
  label<<"L^{max}_{inst} = "<<peakInstLumi<<" x 10^{"<<exponent<<"} cm^{-2}s^{-1}";
  blurb->AddText(label.str().c_str());
  label.str("");
  label << "#sqrt{s} = " << ENERGY << " TeV";
  blurb->AddText(label.str().c_str());
  blurb->AddText("m_{#tilde{g}} - m_{#tilde{#chi}^{0}} = 100 GeV/c^{2}");
  //blurb->AddText("m_{#tilde{t}} - m_{#tilde{#chi}^{0}} = 200 GeV/c^{2}");	
  blurb->SetTextFont(42);
  blurb->SetBorderSize(0);
  blurb->SetFillColor(0);
  blurb->SetShadowColor(0);
  blurb->SetTextAlign(12);
  blurb->SetTextSize(0.032);

  
  // legend
  TBox *legbg = new TBox(600., 2., 900., 1e2);
  legbg->Draw();
  TLegend *leg = new TLegend(600., 2., 900., 1e2,"95% C.L. Limits","");
  leg->SetTextSize(0.028);
  leg->SetBorderSize(0);
  leg->SetTextFont(42);
  leg->SetFillColor(0);
  leg->AddEntry(g_exp, "Expected: 10 #mus - 1000 s Counting Exp. ", "l");
  leg->AddEntry(g_exp1, "Expected #pm1#sigma: 10 #mus - 1000 s Counting Exp. ", "f");
  leg->AddEntry(g_exp2, "Expected #pm2#sigma: 10 #mus - 1000 s Counting Exp. ", "f");
  //	  leg->AddEntry(graph3, "Obs.: 10^{6} s Counting Exp.", "l");
  leg->AddEntry(g_gluino, "Obs.: 10 #mus - 1000 s Counting Exp. ", "l");
  leg->AddEntry(g_tp, "Obs.: 10 #mus Timing Profile ", "l");
  //leg->AddEntry(g_stop, "Obs.: 10 #mus - 1000 s Counting Exp. (#tilde{t})", "l");
  //leg->AddEntry(graph_em, "Obs.: 10 #mus - 1000 s Counting Exp. (EM only)", "l");
  //  leg->AddEntry(graph1, "Obs.: 570 ns Counting Exp.", "l");
  leg->Draw();
  
  
  
  // 2 sigma expected band
  g_exp2->SetLineColor(0);
  g_exp2->SetLineStyle(0);
  g_exp2->SetLineWidth(0);
  g_exp2->SetFillColor(5);
  g_exp2->SetFillStyle(1001);
  g_exp2->Draw("3");
  
  // 1 sigma expected band
  g_exp1->SetLineColor(0);
  g_exp1->SetLineStyle(0);
  g_exp1->SetLineWidth(0);
  g_exp1->SetFillColor(3);
  g_exp1->SetFillStyle(1001);
  g_exp1->Draw("3");  
  
  // expected line
  g_exp->SetLineStyle(2);
  g_exp->SetLineWidth(1);
  g_exp->Draw("l");
  
 
  // plateau limit - 1 ms
  g_gluino->SetLineColor(1);
  g_gluino->SetLineStyle(1);
  g_gluino->SetLineWidth(2);
  g_gluino->Draw("l");
  
  // stop curve
  g_stop->SetLineColor(1);
  g_stop->SetLineStyle(5);
  g_stop->SetLineWidth(2);
  //g_stop->Draw("l");
 

  // 1 mus lifetime fit limit
  g_tp->SetLineColor(kRed);
  g_tp->SetLineStyle(1);
  g_tp->SetLineWidth(2);
  g_tp->Draw("l");
  
  // theory line
  g_thGluino->SetLineColor(kBlue);
  g_thGluino->SetLineStyle(1);
  g_thGluino->SetLineWidth(2);
  g_thGluino->SetFillStyle(3001);
  g_thGluino->SetFillColor(kBlue-4);
  g_thGluino->Draw("l3");
  
  g_thStop->SetLineColor(kRed);
  g_thStop->SetLineStyle(1);
  g_thStop->SetLineWidth(2);
  g_thStop->SetFillStyle(3001);
  g_thStop->SetFillColor(kRed-4);
  //g_thStop->Draw("l3");


  // theory line label
  TLatex* th = new TLatex(600., .3, "NLO+NLL #tilde{g}");
  th->SetTextColor(kBlue);
  th->SetTextFont(42);
  th->SetTextSize(0.035);
  th->Draw();

  TLatex* ths = new TLatex(330., 2., "NLO+NLL #tilde{t}");
  ths->SetTextColor(kRed);
  ths->SetTextFont(42);
  ths->SetTextSize(0.035);
  //ths->Draw();

  // not explored label
  TText* ne = new TText(125., .2, "Not Sensitive");
  ne->SetTextColor(kRed+1);
  ne->SetTextFont(42);
  ne->SetTextAngle(90);
  ne->SetTextSize(0.035);
  //ne->Draw();

  blurb->Draw();

  canvas->RedrawAxis();

  canvas->Print("gluinoMassLimit.pdf");
  canvas->Print("gluinoMassLimit.C");

  plots.calculateIntercepts();
  
}
void makeSplitQCDhist_PythiaBinned(vector<string> folders, const string histname, 
											const string htrange, const string htbinlabel,
											const hist_t histinfo)
{
	const float scaleTo = fDATA_LUMI; // pb

	TLegend *leg  = new TLegend(0.6,0.65,0.9,0.9);
	leg->SetTextFont(42);
	vector<TH1*> hists;
	new TCanvas();
	gPad->SetLogy();
	gPad->SetTickx();
	gPad->SetTicky();

		stringstream title;
		title << htrange << " [" << histinfo.name << "];" << histinfo.title;
		cout << title.str() << endl;
		TH1* Hist = GetHist(histname);

		Hist->SetTitle(title.str().c_str());
		Hist->SetMarkerStyle(20);
		Hist->SetStats(0);
		Hist->Rebin(histinfo.rebin);
		Hist->Draw("P");


/*
	for (unsigned i = 0; i < folders.size(); ++i)
	{	
		string njet("");
		if (i==0) njet += "[2-3]";
		else if (i==1) njet += "[4-5]";
		else if (i==2) njet += "[6-7]";
		else if (i==3) njet += "#geq 8";
*/		/*if (i==0) njet += "3";
		else if (i==1) njet += "4";
		else if (i==2) njet += "5";
		else if (i==3) njet += "6";
		else if (i==4) njet += "7";
		else if (i==5) njet += "8";*/

/*		stringstream title, histName;
		title << htrange << ";" << histinfo.title;
		cout << title.str() << endl;
		histName << folders.at(i) << "/" << histname;;
		hists.push_back(GetHist(histName.str()));
		hists.at(i)->SetTitle(title.str().c_str());
		hists.at(i)->SetMarkerStyle(20+i);
		hists.at(i)->SetMarkerColor(1+i*2);
		hists.at(i)->SetStats(0);
		hists.at(i)->Rebin(histinfo.rebin);
		if (histinfo.normalizeByBinWidth) NormByBinWidth(hists.at(i));

		stringstream legname;
		legname << "Njets " << njet;
		leg->AddEntry(hists.at(i), legname.str().c_str());
		if (i==0) hists.at(i)->Draw("P");
		else hists.at(i)->Draw("same P");
	}
	leg->Draw();
*/
}
Exemplo n.º 14
0
Double_t TTimeHists::Check(EHist hist)
{
   // Check bin content of all bins
   Double_t check = 0.;
   Int_t* x = new Int_t[fDim];
   memset(x, 0, sizeof(Int_t) * fDim);

   if (hist == kHist) {
      Long_t idx = 0;
      Long_t size = 1;
      for (Int_t d = 0; d < fDim; ++d)
         size *= (fBins + 2);
      while (x[0] <= fBins + 1) {
         Double_t v = -1.;
         if (fDim < 4) {
            Long_t histidx = x[0];
            if (fDim == 2) histidx = fHist->GetBin(x[0], x[1]);
            else if (fDim == 3) histidx = fHist->GetBin(x[0], x[1], x[2]);
            v = fHist->GetBinContent(histidx);
         }
         else v = fHn->GetBinContent(x);
         Double_t checkx = 0.;
         if (v)
            for (Int_t d = 0; d < fDim; ++d)
               checkx += x[d];
         check += checkx * v;

         if (fgDebug > 2 || (fgDebug > 1 && v)) {
            printf("%s%d", fDim < 4 ? "hist" : "arr", fDim);
            for (Int_t d = 0; d < fDim; ++d)
               printf("[%d]", x[d]);
            printf(" = %g\n", v);
         }

         ++x[fDim - 1];
         // Adjust the bin idx
         // no wrapping for dim 0 - it's what we break on!
         for (Int_t d = fDim - 1; d > 0; --d) {
            if (x[d] > fBins + 1) {
               x[d] = 0;
               ++x[d - 1];
            }
         }
         ++idx;
      } // while next bin
   } else {
      for (Long64_t i = 0; i < fSparse->GetNbins(); ++i) {
         Double_t v = fSparse->GetBinContent(i, x);
         Double_t checkx = 0.;
         for (Int_t d = 0; d < fDim; ++d)
            checkx += x[d];
         check += checkx * v;

         if (fgDebug > 1) {
            printf("sparse%d", fDim);
            for (Int_t d = 0; d < fDim; ++d)
               printf("[%d]", x[d]);
            printf(" = %g\n", v);
         }
      }
   }
   check /= fNum;
   if (fgDebug > 0)
      printf("check %s%d = %g\n", hist == kHist ? (fDim < 4 ? "hist" : "arr") : "sparse", fDim, check);
   return check;
}
Exemplo n.º 15
0
void BasePlotter::writeStacked(string filename, const HistogramContainer& histContainer, string extension) const
{
    // Check histContainer consistency
    if( ! histContainer.check() ) 
        throw 1;

    if( extension[0] == '.' )
        extension.erase(0,1);
    
    if( filename.find(".root") == string::npos )
    filename.append( ".root" );
    
    system(("mkdir -p " + configContainer.outputDir).c_str()); 
    TFile* f = new TFile((configContainer.outputDir + filename).c_str(), "UPDATE");
    
    unsigned int nSamples = histContainer.reducedNames.size();
    TCanvas *c = new TCanvas(("Canv_stacked_" + histContainer.containerName).c_str(), "", 600, 600 + (120 * configContainer.plotRatio));
    TPad *histPad=nullptr, *ratioPad=nullptr;
    if( configContainer.plotRatio || configContainer.plotSignificance )
    {
        histPad = new TPad("pad1", "pad1", 0, 0.25, 1, 1);
        histPad->Draw();     
        ratioPad = new TPad("pad2", "pad2", 0, 0, 1, 0.3); 
        ratioPad->Draw();
        histPad->cd();
    }    
    
    TLegend* leg = nullptr;
    vector<TLatex*> latexVector;
    setCanvasAttributes( nSamples, leg, latexVector);
    
    vector<TH1F*> hStack;
    TH1* hData = nullptr, *hSignal = nullptr;
    // Add backgrounds to stack
    for( int iSample = nSamples-1; iSample > -1; --iSample )
    {
        if( histContainer.sampleType[iSample] == SampleType::MC || histContainer.sampleType[iSample] == SampleType::FAKELEPTON || histContainer.sampleType[iSample] == SampleType::MCFAKELEPTON )
        {
            TH1F *temp = (TH1F*) histContainer.histograms[iSample]->Clone(("stack_hist_"+histContainer.reducedNames[iSample]).c_str());
            if( hStack.size() > 0 ) temp->Add(hStack[hStack.size()-1]);
            temp->SetLineColor(histContainer.color[iSample]);
            temp->SetFillColor(histContainer.color[iSample]);
            temp->SetFillStyle(1001);
            hStack.push_back(temp);
            string legendEntry = histContainer.reducedNames[iSample];
            replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            leg->AddEntry(temp,legendEntry.c_str(),"f");
        }
    }
    
    // Add signal to stack
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
        if( histContainer.sampleType[iSample] == SampleType::SIGNAL )
        {
            hSignal = histContainer.histograms[iSample];
            hSignal->SetLineColor(histContainer.color[iSample]);
            string legendEntry = histContainer.reducedNames[iSample];
            replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            if( configContainer.signalStacked )
            {
                TH1F *temp = (TH1F*) histContainer.histograms[iSample]->Clone(("stack_hist_"+histContainer.reducedNames[iSample]).c_str());
                if( hStack.size() > 0 ) temp->Add(hStack[hStack.size()-1]);
                temp->SetFillColor(histContainer.color[iSample]);
                temp->SetFillStyle(1001);
                hStack.push_back(temp);
                leg->AddEntry(temp,legendEntry.c_str(),"f");
            }
            else
            {
                hSignal->SetLineWidth(2);
                leg->AddEntry(hSignal,legendEntry.c_str(),"l");
            }
        }
    }
    
    // Add data
    for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
    {
        if( histContainer.sampleType[iSample] == SampleType::DATA && configContainer.unblind )
        {
            histContainer.histograms[iSample]->SetLineColor(histContainer.color[iSample]);
            histContainer.histograms[iSample]->SetMarkerColor(histContainer.color[iSample]);
            histContainer.histograms[iSample]->SetMarkerSize(1);
            histContainer.histograms[iSample]->SetMarkerStyle(20);
            histContainer.histograms[iSample]->SetLineWidth(2);
            string legendEntry = histContainer.reducedNames[iSample];
            replace(legendEntry.begin(), legendEntry.end(), '_', ' ');
            leg->AddEntry(histContainer.histograms[iSample],legendEntry.c_str(),"lp");
            hData = histContainer.histograms[iSample];
        }
    }

    // Set y-range
    float hMax = 0.;
    float hMin = 0.;
    bool maxMakesSense = true;
    if( configContainer.drawNormalized )
        hMax = 1;
    else
    {
        if ( hStack.size() > 0 ) 
            hMax = getMaximumIncludingErrors(hStack[hStack.size()-1]);
        if ( hData ) 
            hMax = max( getMaximumIncludingErrors(hData) , hMax ); 
        if ( hSignal ) 
            hMax = max( getMaximumIncludingErrors(hSignal) , hMax ); 
    }
    
    // Check consistency (for efficiency plot with fixed axis)
    if( histContainer.axisRanges.size() > 0 && hMax > histContainer.axisRanges[1] )
        maxMakesSense = false;
    
    if( configContainer.logY ) 
    {
        c->SetLogy(1);
        hMin = 0.05;
        hMax *= 500;
    }
    else
        hMax *= 1.55;
    if( histContainer.axisRanges.size() > 0 )
    {
        if( maxMakesSense && (!configContainer.drawNormalized) )
        {
            hMin = histContainer.axisRanges[0];
            hMax = histContainer.axisRanges[1];
        }
        else 
        {
            cout << "Maximum range is too small for: " << histContainer.containerName << ". Set to default.\n";
        }
    }
    
        
    // Draw stack
    for( int iHist = hStack.size()-1; iHist > -1; --iHist )
    {
        if( configContainer.drawNormalized )
        {
            hStack[iHist]->Scale(1./hStack[iHist]->Integral());
            hStack[iHist]->GetYaxis()->SetRangeUser(hMin, getMaximumIncludingErrors(hStack[iHist])*1.5);
        }
        else
            hStack[iHist]->GetYaxis()->SetRangeUser(hMin, hMax);
        hStack[iHist]->Draw("hist same");
    }
    
    // Draw uncertainty
    TH1F* hErr;
    if( configContainer.drawUncertainty && hStack.size() > 0 )
    {
        hErr = (TH1F*) hStack[hStack.size()-1]->Clone("uncertainty") ;
        hErr->SetFillColor(15);
        hErr->SetLineColor( 0);
        hErr->SetFillStyle(3445);
        hErr->SetMarkerSize(0);
//         hErr->SetMarkerColor(kBlack);
        hErr->Draw("e2 same");
//         leg->AddEntry( hErr , TString(" stat.#oplussyst.") , "f");
        leg->AddEntry( hErr , TString("stat. error") , "f");
    }
    
    // Draw signal
    if( hSignal && !configContainer.signalStacked ) 
    {
        if( configContainer.drawNormalized )
        {
            hSignal->Scale(1./hSignal->Integral());
            hSignal->GetYaxis()->SetRangeUser(hMin, getMaximumIncludingErrors(hSignal)*1.5);
        }
        else
            hSignal->GetYaxis()->SetRangeUser(hMin, hMax);
        hSignal->Draw("e same");
    }
    
    // Draw data
    if( hData ) 
    {
        if( configContainer.drawNormalized )
        {
            hData->Scale(1./hData->Integral());
            hData->GetYaxis()->SetRangeUser(hMin, getMaximumIncludingErrors(hData)*1.5);
        }
        else
            hData->GetYaxis()->SetRangeUser(hMin, hMax);
        hData->Draw("e same");
    }
   
    // Draw legend
    leg->Draw(); 
    for( auto* text : latexVector )
    {
        text->Draw("same");
    }
    
    // Redraw axis
    gPad->RedrawAxis();
    
    // Draw Ratio plot
    if( configContainer.plotRatio && hStack.size() > 0 && (hData || (hSignal && !configContainer.signalStacked)) ) {
        ratioPad->cd();

        TH1F* hRatio;
        if( hData ) 
        {
           hRatio = (TH1F*) hData->Clone("ratio");
           hRatio->GetYaxis()->SetTitle("Data / MC"); 
        }
        else
        {
            hRatio = (TH1F*) hSignal->Clone("ratio");
            hRatio->GetYaxis()->SetTitle("Signal / Background"); 
        }
        
//         if( configContainer.signalStacked || !hData )
//             hRatio->Divide(hStack[hStack.size()-1]);
//         else
//         {
            TH1F* hAllMC = (TH1F*) hStack[hStack.size()-1]->Clone("allMC");
//             hAllMC->Add( hSignal );
            hRatio->Divide(hAllMC);
//         }

        hRatio->GetYaxis()->SetRangeUser(0, 2); 
        hRatio->Draw("ep");
        hRatio->GetXaxis()->SetTitle(""); 
                        
        TLine *line = new TLine(hRatio->GetXaxis()->GetXmin(),1,hRatio->GetXaxis()->GetXmax(),1);
        line->SetLineStyle(3);
        line->Draw();
        
        // Print global ratio
        if( hData )
            cout << "Data / MC: " << hData->Integral()/hStack[hStack.size()-1]->Integral() << endl;
        else
            cout << "Signal / Background: " << hSignal->Integral()/hStack[hStack.size()-1]->Integral() << endl;
    }
    
    //Draw significance plot
    if( configContainer.plotSignificance && !configContainer.plotRatio && hStack.size() > 0 && hSignal && !configContainer.signalStacked ) {
        ratioPad->cd();
        TH1F* hRatio = (TH1F*) hSignal->Clone("ratio");
        hRatio->GetYaxis()->UnZoom();
        unsigned int nBins = hRatio->GetNbinsX();
        for( unsigned int iBin = 1; iBin <= nBins; ++iBin ) 
        {
            float denom = sqrt(hRatio->GetBinContent(iBin)+hStack[hStack.size()-1]->GetBinContent(iBin));
            if( denom > 0 ) 
            {
                hRatio->SetBinContent(iBin, hRatio->GetBinContent(iBin)/denom);
                float S = hSignal->GetBinContent(iBin), B = hStack[hStack.size()-1]->GetBinContent(iBin);
                hRatio->SetBinError(iBin, sqrt( pow(S/2./pow(B+S,1.5),2) * pow(hSignal->GetBinError(iBin),2) + pow((B+S/2.)/pow(B+S,1.5),2) * pow(hStack[hStack.size()-1]->GetBinError(iBin),2)) );
            }
            else
            {
                hRatio->SetBinContent(iBin, 0);
                hRatio->SetBinError(iBin, 0);
            }
        }

//         hRatio->GetYaxis()->SetRangeUser(0, 2); 
        hRatio->Draw("ep");
        hRatio->GetYaxis()->SetTitle("S / #sqrt{S+B}"); 
        hRatio->GetXaxis()->SetTitle(""); 
    }
    
    // Redraw axis
    gPad->RedrawAxis();
    
    c->Print((configContainer.outputDir + histContainer.containerName + "." + extension).c_str(), extension.c_str());
    cout << "Wrote plot " << (histContainer.containerName + "." + extension) << endl;
    c->Write();
    f->Close();
}
Exemplo n.º 16
0
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void deviations( TString fin = "TMVAReg.root", 
                 HistType htype = MVAType, Bool_t showTarget, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );
   gStyle->SetNumberContours(999);

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 650;   // size of canvas

   // this defines how many canvases we need
   TCanvas* c[100];

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   //    TList* methods = new TMap();

   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if (!gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory")) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);
      cout << "--- Plotting deviation for method: " << methodName << endl;

      TObjString *mN  = new TObjString( methodName );
      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TList* jobNames = new TList();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {

         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();

         TObjString *jN = new TObjString( titDir->GetName() );
         if (!jobNames->Contains( jN )) jobNames->Add( jN );
         else delete jN;
	    
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         TString hname = "MVA_" + methodTitle;
         TIter   dirKeyIt( titDir->GetListOfKeys() );
         TKey*   dirKey;

         Int_t countPlots = 0;
         while ((dirKey = (TKey*)dirKeyIt())){
            if (dirKey->ReadObj()->InheritsFrom("TH2F")) {
               TString s(dirKey->ReadObj()->GetName());
               if (s.Contains("_reg_") && 
                   ( (showTarget && s.Contains("_tgt")) || (!showTarget && !s.Contains("_tgt")) ) && 
                   s.Contains( (htype == CompareType ? "train" : "test" ))) {
                  c[countCanvas] = new TCanvas( Form("canvas%d", countCanvas+1), 
                                                Form( "Regression output deviation versus %s for method: %s",
                                                      (showTarget ? "target" : "input variables"), methodName.Data() ),
                                                countCanvas*50+100, (countCanvas+1)*20, width, (Int_t)width*0.72 ); 
                  c[countCanvas]->SetRightMargin(0.10); // leave space for border
                  TH1* h = (TH1*)dirKey->ReadObj();
                  h->SetTitle( Form("Output deviation for method: %s (%s sample)", 
                                    hname.Data(), (htype == CompareType ? "training" : "test" )) );
                  //                                    methodName.Data(), (htype == CompareType ? "training" : "test" )) );
                  h->Draw("colz");
                  TLine* l = new TLine( h->GetXaxis()->GetXmin(), 0, h->GetXaxis()->GetXmax(), 0 );
                  l->SetLineStyle(2);
                  l->Draw();

                  // update and print
                  cout << "plotting logo" << endl;
                  TMVAGlob::plot_logo(1.058);
                  c[countCanvas]->Update();

                  TString fname = Form( "plots/deviation_%s_%s_%s_c%i", 
                                        methodName.Data(), 
                                        (showTarget ? "target" : "vars"),
                                        (htype == CompareType ? "training" : "test" ), countPlots );
                  TMVAGlob::imgconv( c[countCanvas], fname );

                  countPlots++;
                  countCanvas++;
               }
            }
         }         
      }
   }
}
Exemplo n.º 17
0
// Main function to create the pdf's
int main(int argc, char**argv){
  TString version = "80X";

  // Define binning for pdfs (details and more options in binningConfigurations.h)
  binClass bins;
  if(version.Contains("v2")) 		bins = getV2Binning();
  if(version.Contains("80X")) 		bins = get76XBinning();
  else return 1;

  // For different jet types (if _antib is added bTag is applied)
  for(TString jetType : {"AK4chs","AK4chs_antib"}){ //,"AK4","AK4_antib"}){
    std::cout << "Building pdf's for " << jetType << "..." << std::endl;

    treeLooper t("QCD_AllPtBins", jetType);										// Init tree (third argument is the directory path, if other than default in treeLooper.h)
    bins.setReference("pt",  &t.pt);											// Give the binning class a pointer to the variables used to bin in
    bins.setReference("eta", &t.eta);
    bins.setReference("rho", &t.rho);

    // Creation of the pdfs
    std::map<TString, TH1D*> pdfs;
    for(TString binName : bins.getAllBinNames()){
      for(TString type : {"quark","gluon"}){
        TString histName = "_" + type + "_" + binName;
        pdfs["axis2" + histName] = new TH1D("axis2" + histName, "axis2" + histName, 100, 0, 8);				// Has been 200 bins before, but seemed to have a bit too much fluctuations still
        pdfs["mult"  + histName] = new TH1D("mult"  + histName, "mult"  + histName, 140, 2.5, 142.5);
        pdfs["ptD"   + histName] = new TH1D("ptD"   + histName, "ptD"   + histName, 100, 0, 1);				// Also 200 before
      }
    }


    // Fill pdfs
    TString binName;
    while(t.next()){
      if(!bins.getBinName(binName)) 								continue;		// Find bin and return false if outside ranges
      if(t.jetIdLevel < 3) 									continue;		// Select tight jets
      if(!t.matchedJet) 								 	continue; 		// Only matched jets
      if(t.nGenJetsInCone != 1 || t.nJetsForGenParticle != 1 || t.nGenJetsForGenParticle != 1) 	continue;		// Use only jets matched to exactly one gen jet and gen particle, and no other jet candidates
      if((fabs(t.partonId) > 3 && t.partonId != 21)) 						continue; 		// Keep only udsg
      if(t.bTag) 										continue;		// Anti-b tagging (always false if jetType does not contain "antib")
      if(!t.balanced) 										continue;		// Take only two leading jets with pt3 < 0.15*(pt1+pt2)  (surpresses small radiated jets with pt <<< pthat)
      if(t.mult < 3)										continue;		// Avoid jets with less than 3 particles (otherwise axis2=0)
      TString type = (t.partonId == 21? "gluon" : "quark");								// Define q/g
      TString histName = "_" + type + "_" + binName;

      pdfs["axis2" + histName]->Fill(t.axis2, t.weight);								// "axis2" already contains the log
      pdfs["mult"  + histName]->Fill(t.mult,  t.weight);
      pdfs["ptD"   + histName]->Fill(t.ptD,   t.weight);
    }

    // Try to add statistics from neighbours (first make copy, so you don't get an iterative effect)
    std::map<TString, TH1D*> pdfsCopy;
    for(auto& pdf : pdfs) pdfsCopy[pdf.first] = (TH1D*) pdf.second->Clone(pdf.first + "clone");
    for(TString binName : bins.getAllBinNames()){
      for(TString var : {"axis2","mult","ptD"}){
        for(TString neighbour : bins.getNeighbourBins(binName, var)){							// If neighbours are defined: add their statistics
          for(TString type : {"quark","gluon"}){
            pdfs[var + "_" + type + "_" + binName]->Add(pdfsCopy[var + "_" + type + "_" + neighbour]);
          }
        }
      }
    }
    for(auto& copy : pdfsCopy) delete copy.second;

    // Store the mean and RMS of the original histogram (because they could be changed by rebinning operations)
    std::map<TString, float> mean;
    std::map<TString, float> rms;
    for(auto& pdf : pdfs){
      if(pdf.second->GetEntries() == 0){ std::cout << "Error: no entries in " << pdf.first << std::endl; exit(1);}	// Force to exit when no entries in pdfs: the binning configuration should be altered to avoid this
      mean[pdf.first] = pdf.second->GetMean();
      rms[pdf.first]  = pdf.second->GetRMS();
    }


    // Check "smoothness" of the pdf: if fluctuations seem really big, we do a rebinning
    std::map<TString, int> rebinFactor;
    for(auto& pdf : pdfs){
      bool isBelow      = (mean[pdf.first] < mean[switchQG(pdf.first)]);						// Define region between low(meanQ, meanG) - RMS <--> high(meanQ, meanG) + RMS
      TString low	= isBelow? pdf.first : switchQG(pdf.first);							// Most events will be within those borders, so we should not allow empty bins here
      TString high	= isBelow? switchQG(pdf.first) : pdf.first;							// (an empty bin for 1 of the three variables already results in L = 0 or 1)
      int leftBin	= pdf.second->FindBin(mean[low] - rms[low]) - 1;
      int rightBin	= pdf.second->FindBin(mean[high] + rms[high]) + 1;
     
      int leftBin2      = 0;												// Define region of the peak: most extreme bins which exceed 80% of the maximum
      int rightBin2     = 0;												// We will check for bins within this region which go below 70%
      for(int bin = 1; bin < pdf.second->GetNbinsX(); ++bin){								// In such cases the fluctuations are really high and a larger bin width is preferred
        if(pdf.second->GetBinContent(bin) > pdf.second->GetMaximum()*0.8){						// (Maybe the thresholds could still be optimized a bit more though)
          if(!leftBin2) leftBin2  = bin;
          else          rightBin2 = bin;
        }
      }


      int leftBin3      = 0;												// Define region of the peak: most extreme bins which exceed 90% of the maximum
      int rightBin3     = 0;												// We will check for bins within this region which go below 80%
      for(int bin = 1; bin < pdf.second->GetNbinsX(); ++bin){								// In such cases the fluctuations are really high and a larger bin width is preferred
        if(pdf.second->GetBinContent(bin) > pdf.second->GetMaximum()*0.9){						// (Maybe the thresholds could still be optimized a bit more though)
          if(!leftBin3) leftBin3  = bin;
          else          rightBin3 = bin;
        }
      }

      int emptyBins     = 0;
      int maxEmptyBins  = 0;
      for(int bin = 1; bin < pdf.second->GetNbinsX(); ++bin){
        if(     bin >= leftBin  && bin <= rightBin  && pdf.second->GetBinContent(bin) <= 0)                            ++emptyBins;
        else if(bin >= leftBin2 && bin <= rightBin2 && pdf.second->GetBinContent(bin) <= pdf.second->GetMaximum()*0.7) ++emptyBins;
        else if(bin >= leftBin3 && bin <= rightBin3 && pdf.second->GetBinContent(bin) <= pdf.second->GetMaximum()*0.8) ++emptyBins;
        else {
          if(emptyBins > maxEmptyBins) maxEmptyBins = emptyBins;
          emptyBins = 0;
        }
      }
      rebinFactor[pdf.first] = std::max(maxEmptyBins, emptyBins);
    }

    for(auto& pdf : pdfs) rebinFactor[pdf.first] = std::max(rebinFactor[pdf.first], rebinFactor[switchQG(pdf.first)]);	// Use same rebin factor in quark and gluon pdf (otherwise bias if second derivate of pdf is non-zero)
    
    for(auto& pdf : pdfs){
      if(rebinFactor[pdf.first] > 19)     std::cout << "This pdf has a lot of emtpy bins and fluctuations:" << std::endl;
      if(rebinFactor[pdf.first] > 9)      rebin(pdf.second, 20);
      else if(rebinFactor[pdf.first] > 4) rebin(pdf.second, 10);
      else if(rebinFactor[pdf.first] > 3) rebin(pdf.second, 5);
      else if(rebinFactor[pdf.first] > 1) rebin(pdf.second, 4);
      else if(rebinFactor[pdf.first] > 0) rebin(pdf.second, 2);
    }


    // Normalization of the pdf's
    for(auto& pdf : pdfs) pdf.second->Scale(1./pdf.second->Integral(0, pdf.second->GetNbinsX() + 1));			// Scale to integral=1 (also include underflow/overflow)


    // Try to average out leftover fluctuations and empty bins
    for(auto& pdf : pdfs){
      if(pdf.first.Contains("gluon")) continue;

      TH1* tempQ = (TH1*) pdf.second->Clone();
      TH1* tempG = (TH1*) pdfs[switchQG(pdf.first)]->Clone();
      for(int i = 1; i < pdf.second->GetNbinsX() + 1; ++i){								// Do not consider underflow/overflow
        float contentQ = tempQ->GetBinContent(i);
        float contentG = tempG->GetBinContent(i);
        float width    = tempQ->GetBinWidth(i);

        if((1.5*contentQ < tempQ->GetBinContent(i-1) && 1.5*contentQ < tempQ->GetBinContent(i+1)) ||			// Try to average out some extreme fluctuations (i.e. only allow a difference of max 50% between two neighbouring bins)
           (1.5*contentG < tempG->GetBinContent(i-1) && 1.5*contentG < tempG->GetBinContent(i+1)) ||
           (contentQ < 1.5*tempQ->GetBinContent(i-1) && contentQ < 1.5*tempQ->GetBinContent(i+1)) ||
           (contentG < 1.5*tempG->GetBinContent(i-1) && contentG < 1.5*tempG->GetBinContent(i+1))){
          if(i-1 > 0 && i+1 < pdf.second->GetNbinsX() + 1){
            contentQ += tempQ->GetBinContent(i-1) + tempQ->GetBinContent(i+1);
            contentG += tempG->GetBinContent(i-1) + tempG->GetBinContent(i+1);
            width    += tempQ->GetBinWidth(i-1)   + tempQ->GetBinWidth(i+1);
          }
        }

        int j = 1;
        while(contentQ <= 0 || contentG <= 0){										// Average empty bins
          if(tempQ->Integral(0, i-j) <= 0) break;									// but not when surpassing the extreme edges of the pdf (see next part)
          if(tempG->Integral(0, i-j) <= 0) break;
          if(tempQ->Integral(i+j, tempQ->GetNbinsX()+1) <= 0) break;
          if(tempG->Integral(i+j, tempG->GetNbinsX()+1) <= 0) break;
          if(i-j == 0) break;
          if(i+j == pdf.second->GetNbinsX()) break;
          contentQ += tempQ->GetBinContent(i-j) + tempQ->GetBinContent(i+j);
          contentG += tempG->GetBinContent(i-j) + tempG->GetBinContent(i+j);
          width    += tempQ->GetBinWidth(i-j)   + tempQ->GetBinWidth(i+j);
          ++j;
        }

        pdf.second->SetBinContent(i, contentQ/width);
        pdfs[switchQG(pdf.first)]->SetBinContent(i, contentG/width);
      }
      delete tempQ;
      delete tempG;
    }


    // Now there are still empty bins left on the edges of the pdf, for which we assign extreme values to avoid a 0
    // (relative though, so it does not dominate the pdf's when we want to inspect them in the ROOT file; 0.000001/0.000999 has the same effect as 0.001/0.999)
    for(auto& pdf : pdfs){
      if(pdf.first.Contains("gluon")) continue;
      for(int i = 0; i <= pdf.second->GetNbinsX() + 1; ++i){
        if(pdf.second->GetBinContent(i) <= 0 || pdfs[switchQG(pdf.first)]->GetBinContent(i) <= 0){
          bool isBelow = (mean[pdf.first] < mean[switchQG(pdf.first)]);
          if(isBelow == pdf.second->GetBinCenter(i) < mean[pdf.first]){
            pdf.second->SetBinContent(i, 0.000999);
            pdfs[switchQG(pdf.first)]->SetBinContent(i, 0.000001);
          } else {
            pdf.second->SetBinContent(i, 0.000001);
            pdfs[switchQG(pdf.first)]->SetBinContent(i, 0.000999);
          }
        }
      }
    }


    // Apply the likelihood weight
    for(auto& pdf : pdfs){
      TString thisBin = pdf.first(pdf.first.Index(TRegexp("eta")), pdf.first.Length());
      TString thisVar = pdf.first(0, pdf.first.Index(TRegexp("_")));
      for(int i = 0; i < pdf.second->GetNbinsX() + 1; ++i){
        pdf.second->SetBinContent(i, std::pow(pdf.second->GetBinContent(i), bins.getWeight(thisBin, (thisVar == "mult"? 0 : (thisVar == "ptD" ? 1 : 2 )))));
      }
    }


    // Make file and write binnings
    TFile *pdfFile = new TFile("pdfQG_"+jetType + "_13TeV_" + version + ".root","RECREATE");
    pdfFile->cd();
    bins.writeBinsToFile();

    // Write to file
    for(TString var : {"axis2","ptD","mult"}) pdfFile->mkdir(var);
    for(auto& pdf : pdfs){
      for(TString var: {"axis2","ptD","mult"}) if(pdf.first.Contains(var)) pdfFile->cd(var);
      pdf.second->SetTitle(pdf.first);
      pdf.second->Write();

      TString thisBin = pdf.first(pdf.first.Index(TRegexp("eta")), pdf.first.Length());
      for(auto i : bins.getLinkedBins(thisBin)){									// Store copies for merged bins
        TString copyBin = pdf.first;
        copyBin.ReplaceAll(thisBin, i);
        pdf.second->Write(copyBin);
      }
    }

    for(auto& pdf : pdfs) delete pdf.second;
    for(auto& file : {pdfFile}){ file->Close(); delete file;}
  }
  return 0;
}
Exemplo n.º 18
0
void glauberCut(int from=0, int to=100){

    char name[200];

    TChain* t = new TChain("t");
    char dfilelist[100];
    sprintf(dfilelist,"filelist.txt");
    ifstream lis(dfilelist);
    int cnt=0;
    int dnt=0;
    while(!lis.eof())
    {
        string filename;
        lis >> filename;
        if(cnt>=from&&cnt<to)
        {
            cout << filename << endl;
            if(!filename.empty()) t->Add(filename.c_str());
            dnt++;
        }
        cnt++;
    }

    double b;
    int ncoll;
    int npart,npartproj,nparttarg;
    int nHitBbc_n, nHitBbc_s, BBCTrig;
    int Centbin;
    double qBBC_n, qBBC_s, pTrigBBC;
    double vertex, ecc_std,ecc_rp, ecc_part,ecc_partr,r_ollitra,r_geo,r_arith,r_ollitrar,r_geor,r_arithr,e4;

    double e_gl[ETOT],ang_gl[ETOT];
    double re_gl[ETOT],rang_gl[ETOT];

    double pe_gl[ETOT],pang_gl[ETOT];
    double pre_gl[ETOT],prang_gl[ETOT];

    t->SetBranchAddress("b",            &b   );
    t->SetBranchAddress("Centbin",      &Centbin);
    t->SetBranchAddress("ncoll",        &ncoll);
    t->SetBranchAddress("npart",        &npart);
    t->SetBranchAddress("npartproj",    &npartproj);
    t->SetBranchAddress("nparttarg",    &nparttarg);
/*    t->SetBranchAddress("ecc_std",      &ecc_std  );
    t->SetBranchAddress("ecc_rp",       &ecc_rp );
    t->SetBranchAddress("ecc_part",     &ecc_part );

    t->SetBranchAddress("e_gl",         e_gl );   //r2
    t->SetBranchAddress("ang_gl",       ang_gl );
    t->SetBranchAddress("pe_gl",         pe_gl ); //no only Conside Npart
    t->SetBranchAddress("pang_gl",       pang_gl);
*/
  //  t->SetBranchAddress("re_gl",        re_gl );  //r3,2,3,4,5,6
  //  t->SetBranchAddress("rang_gl",      rang_gl);
    t->SetBranchAddress("pre_gl",        pre_gl);
   // t->SetBranchAddress("prang_gl",      prang_gl);

    //t->SetBranchAddress("nux",  &nux);
    //t->SetBranchAddress("nuy",  &nuy);
    //t->SetBranchAddress("st_part",  &st_part);

    int nevents = t->GetEntries();
    cout<<"will run "<<nevents/1000000<<"M  events"<<endl;


    TH1D* hecc [NCENT][NHAR];
    TH1D* hcent[NCENT];
    for(int icent=0; icent<NCENT; icent++){
        sprintf(name,"hcent_%.2d", icent);
        hcent[icent] = new TH1D(name, name ,NCENT, 0-0.5, NCENT-0.5);
    }
    for(int icent=0; icent<NCENT; icent++){
        for(int ihar=0; ihar<NHAR; ihar++){
            sprintf(name, "hecc_ic%.2d_ih%d", icent, ihar);
            hecc[icent][ihar] = new TH1D(name, name, 100000, 0, 1);
        }
    }

    for(int iev=0; iev<nevents; iev++){
        t->GetEntry(iev);
        if(iev%1000000==0) cout<<iev<<endl;
        if(Centbin!=0) continue;
        hcent[Centbin] ->Fill(Centbin);
        for(int ihar=0; ihar<NHAR; ihar++){
            hecc[Centbin][ihar] ->Fill(pre_gl[ihar]);
        }
    } //end of events

    float steps[NSTEP] = {0};
    float Ecut[NCENT][NHAR][NSTEP];

    for(int is=0; is<NSTEP-1; is++){
        steps[is] = (is+1)*1.0/NSTEP;
    }
    steps[NSTEP-1] = 1.01;

    for(int icent=0; icent<NCENT; icent++){
        for(int ihar=0; ihar<NHAR; ihar++){
            TH1* htmp;
            sprintf(name,"scale_%d_%d", icent, ihar);
            htmp = (TH1*)hecc[icent][ihar] ->Clone(name);
            htmp-> Scale(1.0/htmp->GetEntries());
            double sum = 0;
            int cnt = 0;
            for(int ib=1; ib<=htmp->GetNbinsX(); ib++){
                sum+= htmp->GetBinContent(ib);
                if(sum>steps[cnt]) { Ecut[icent][ihar][cnt] = htmp->GetBinCenter(ib); cnt++;}
            }
            Ecut[icent][ihar][NSTEP-1] = 1.01;
            cout<<icent<<"  "<<ihar<<"  "<<cnt<<"   "<<sum<<endl;
        }
    }

    ofstream tout;
    sprintf(name,"ECut_cent0.txt");
    tout.open(name);
    for(int cent=0; cent<NCENT; cent++){

    tout<<"centb "<<cent<<endl;
    for(int ihar=0; ihar<NHAR; ihar++){
        for(int iq=0; iq<NSTEP; iq++){
            if(iq==0) tout<<"{"<<Ecut[cent][ihar][iq]<<", ";
            else if(iq<NSTEP-1) tout<<Ecut[cent][ihar][iq]<<", ";
            else if(iq ==NSTEP-1) tout<<Ecut[cent][ihar][iq]<<"}, "<<endl;
        }
    }
    }


    tout.close();

    TFile* fout = new TFile("glauber_cut_cent0.root","recreate");
    for(int icent=0; icent<NCENT; icent++){
        for(int ihar=0; ihar<NHAR; ihar++){
            hecc[icent][ihar] ->Write();
        }
    }
    for(int icent=0; icent<NCENT; icent++){
        hcent[icent] ->Write();
    }
    fout->Close();
}
Exemplo n.º 19
0
void SetRange(TH1 &h, double xmin, double ymin, double xmax, double ymax){
	h.GetXaxis()->SetRangeUser(xmin,xmax);
	h.GetYaxis()->SetRangeUser(ymin,ymax);
}
Exemplo n.º 20
0
void
GetEccenNpart_new(char* xname = "ile")
{
  gStyle->SetOptStat(0);
  gStyle->SetTitle(0);

  char name[100];

  TChain* ch = new TChain("t");
  int n;

  //you need a file list of root ntuple: fxxxx.lis
  //
  sprintf(name,"f%s.lis",xname);
  cout << "open the filelist : " << name << endl;
  ifstream fin(name);

  string filename;
  while(!fin.eof()){
    fin >> filename;
    if(filename.empty()) continue;
    cout << filename << endl;

    ch->AddFile(filename.c_str());
  }
  fin.close();

  double b;
  int ncoll;
  int npart;
  int nHitBbc_n, nHitBbc_s;
  double qBBC_n, qBBC_s;
  double vertex, ecc_std, ecc_rp, ecc_part,e4;
  double r_oll,r_geo,r_arith;
  ch->SetBranchAddress("b",            &b        );
  ch->SetBranchAddress("vertex",       &vertex   );
  ch->SetBranchAddress("ncoll",        &ncoll    );
  ch->SetBranchAddress("npart",        &npart    );
  ch->SetBranchAddress("ecc_std",      &ecc_std  );
  ch->SetBranchAddress("ecc_rp",       &ecc_rp  );
  ch->SetBranchAddress("ecc_part",     &ecc_part );
  ch->SetBranchAddress("r_ollitra",    &r_oll );
  ch->SetBranchAddress("r_geo",        &r_geo );
  ch->SetBranchAddress("r_arith",      &r_arith );
  ch->SetBranchAddress("e4",           &e4       );
  ch->SetBranchAddress("qBBC_n",       &qBBC_n   );
  ch->SetBranchAddress("qBBC_s",       &qBBC_s   );
  ch->SetBranchAddress("nHitBbc_n",    &nHitBbc_n);
  ch->SetBranchAddress("nHitBbc_s",    &nHitBbc_s);

  char fname[100];
  sprintf(fname,"rootfile/g%s_cent.root",xname);
  TFile* fout = new TFile(fname,"recreate");//rootfile to save distributions

  TH1* hbbcq    = new TH1D("hbbcq","hbbcq",12000,-0.5,2999.5);      hbbcq->Sumw2();
  TH1* hbbcqall = new TH1D("hbbcqall","hbbcqall",12000,-0.5,2999.5);hbbcqall->Sumw2();
  TH1* hbbcqeff = new TH1D("hbbcqeff","hbbcqeff",12000,-0.5,2999.5);hbbcqeff->Sumw2();

  n = ch->GetEntries();
  cout << "events: "<< n << endl;

  //First loop determines the BBC trigger efficiency
  //as function of bbcq;
  for(int i=0; i<n; i++){
    ch->GetEntry(i);

    if(nHitBbc_n>=2&&nHitBbc_s>=2){
      hbbcq->Fill( (qBBC_n+qBBC_s)/100. );//divide by 100 to fit in 0-3000 range
    }

    hbbcqall->Fill( (qBBC_n+qBBC_s)/100. );
  }
  hbbcqeff->Divide(hbbcq,hbbcqall);

  efficiency = hbbcq->Integral()/hbbcqall->Integral();
  cout << "efficiency : " << efficiency << endl;

  //hbin contains the integrated fraction starting from 0 bbc charge, including the BBC trigger efficiency
  TH1* hbin = new TH1D("hbin","hbin",hbbcq->GetNbinsX(),-0.5,2999.5);
  TH1* hbbcqscale = (TH1*)hbbcq->Clone("hbbcqscale");
  hbbcqscale->Scale(1.0/hbbcq->Integral());
  for(int i=1; i<=hbbcqscale->GetNbinsX(); i++){
    hbin->SetBinContent(i,hbbcqscale->Integral(1,i));
  }
  //Following two lines defines the array of cuts and average bbc charge
  //for centrality percentitle in 5%, 10% and 20% steps
  double bbcq5[21],bbcq10[11],bbcq20[6];
  double abbcq5[20],abbcq10[10],abbcq20[5];

  //calculate the various variables for 5% step
  GetCentrality(hbin,20,bbcq5,hbbcq,abbcq5);
  cout << endl << endl;

  //calculate the various variables for 10% step
  GetCentrality(hbin,10,bbcq10,hbbcq,abbcq10);
  cout << endl << endl;

  //calculate the various variables for 20% step
  GetCentrality(hbin,5,bbcq20,hbbcq,abbcq20);
  cout << endl << endl;

  cout << " Find cuts for all the centralities " << endl << endl;

  const int nval=9;//number of variables to fill
  char* centname[3] = {"5pStep","10pStep","20pStep"};
  char* varname[nval] = {"npart","ncoll","b","standard_ecc","reactionplane_ecc","participant_ecc","R_Ollitraut","R_Geo", "R_arith"};
  double vup[nval] = {499.5,2999.5,19.995,1,1,1,4,4,4};
  double vlo[nval] = {-0.5,-0.5,-0.005,-1,-1,-1,0,0,0};
  int vNb[nval] = {500,3000,2000,200,200,200,400,400,400};

  //initialize the histograms which are used to fill the distribution of variables for each centrality
  TH1* hvar[3][nval][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int ivar=0; ivar<nval; ivar++){
      for(int icen=0; icen<NC; icen++){
	sprintf(name,"hvar_%s_%s_cent%d",centname[i],varname[ivar],icen);
	hvar[i][ivar][icen] = new TH1D(name,name,vNb[ivar],vlo[ivar],vup[ivar]);
      }
    }
  }

  double qbbcsum;
  for(int i=0; i<n; i++){
    if(i%1000000==0) cout << i << endl;
    ch->GetEntry(i);

    if(!(nHitBbc_n>=2&&nHitBbc_s>=2)) continue;//BBC trigger condition

    qbbcsum = (qBBC_n+qBBC_s)/100.;

    int centbin5  = FindBin(20,bbcq5,qbbcsum);
    int centbin10 = FindBin(10,bbcq10,qbbcsum);
    int centbin20 = FindBin(5,bbcq20,qbbcsum);

    if(centbin5==-1) continue;
    if(centbin10==-1) continue;
    if(centbin20==-1) continue;

    //find the weight according to the corresponding average efficiency.
    double weight = hbbcqeff->GetBinContent(hbbcqeff->FindBin(qbbcsum));
    //5 percent step
    //
    hvar[0][0][centbin5]->Fill(npart,weight);
    hvar[0][1][centbin5]->Fill(ncoll,weight);
    hvar[0][2][centbin5]->Fill(b,weight);
    hvar[0][3][centbin5]->Fill(ecc_std,weight);
    hvar[0][4][centbin5]->Fill(ecc_rp,weight);
    hvar[0][5][centbin5]->Fill(ecc_part,weight);
    hvar[0][6][centbin5]->Fill(r_oll,weight);
    hvar[0][7][centbin5]->Fill(r_geo,weight);
    hvar[0][8][centbin5]->Fill(r_arith,weight);

    //10 percent step
    //
    hvar[1][0][centbin10]->Fill(npart,weight);
    hvar[1][1][centbin10]->Fill(ncoll,weight);
    hvar[1][2][centbin10]->Fill(b,weight);
    hvar[1][3][centbin10]->Fill(ecc_std,weight);
    hvar[1][4][centbin10]->Fill(ecc_rp,weight);
    hvar[1][5][centbin10]->Fill(ecc_part,weight);
    hvar[1][6][centbin10]->Fill(r_oll,weight);
    hvar[1][7][centbin10]->Fill(r_geo,weight);
    hvar[1][8][centbin10]->Fill(r_arith,weight);


    //20 percent step
    //
    hvar[2][0][centbin20]->Fill(npart,weight);
    hvar[2][1][centbin20]->Fill(ncoll,weight);
    hvar[2][2][centbin20]->Fill(b,weight);
    hvar[2][3][centbin20]->Fill(ecc_std,weight);
    hvar[2][4][centbin20]->Fill(ecc_rp,weight);
    hvar[2][5][centbin20]->Fill(ecc_part,weight);
    hvar[2][6][centbin20]->Fill(r_oll,weight);
    hvar[2][7][centbin20]->Fill(r_geo,weight);
    hvar[2][8][centbin20]->Fill(r_arith,weight);
  }

  //get mean and RMS values for the variables
  float var[3][nval+1][20];
  float rms[3][nval+1][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int icen=0; icen<NC; icen++){
      for(int ivar=0; ivar<nval; ivar++){
	var[i][ivar][icen] = hvar[i][ivar][icen]->GetMean();
	rms[i][ivar][icen] = hvar[i][ivar][icen]->GetRMS();
      }
      var[i][nval][icen] = var[i][1][icen]/sigmann;
      rms[i][nval][icen] = rms[i][1][icen]/sigmann;
    }
  }
  //save to file
  for(int ivar=0; ivar<4; ivar++){
    for(int icen=0; icen<16; icen++){
      cout<<var[0][ivar][icen]<<",";
    }
    cout<<var[2][ivar][4]<<",";
    cout<<endl;
  }

  cout.precision(4);

  sprintf(name,"5pstepresults/t%s.txt",xname);
  ofstream f5(name);
  cout << " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<19; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f5 << var[0][ivar][icen] << " ";
    }
    f5 << var[0][nval][icen] << " ";
    f5 <<endl<<  " (";
    /* for(int ivar=0; ivar<7; ivar++){
      f5 << rms[0][ivar][icen] << " ";
    }
    f5 << rms[0][nval][icen] << " ";
    f5 <<  ")"<< endl;
    */
    cout << icen*5 << "-" << icen*5+5;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[0][ivar][icen] ;
    }
    cout <<" & " <<var[0][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[0][ivar][icen];
      else cout <<" & "<<rms[0][ivar][icen];
    }
    cout <<" & "<<rms[0][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    // printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //	   var[0][0][icen],var[0][1][icen],var[0][2][icen],var[0][3][icen],var[0][4][icen],var[0][5][icen],var[0][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[0][0][icen],rms[0][1][icen],rms[0][2][icen],rms[0][3][icen],rms[0][4][icen],rms[0][5][icen],rms[0][6][icen]);
  }
  f5.close();

  cout << endl << endl;
  sprintf(name,"10pstepresults/t%s.txt",xname);
  ofstream f10(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<10; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f10 << var[1][ivar][icen] << " ";
    }
    f10 << var[1][nval][icen] << " ";
    f10 <<endl<<" (";
    /*for(int ivar=0; ivar<7; ivar++){
      f10 << rms[1][ivar][icen] << " ";
    }
    f10 << rms[1][nval][icen] << " ";
    f10 <<  ")" << endl;
    */
    cout << icen*10 << "-" << icen*10+10;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[1][ivar][icen] ;
    }
    cout <<" & " <<var[1][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[1][ivar][icen];
      else cout <<" & "<<rms[1][ivar][icen];
    }
    cout <<" & "<<rms[1][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[1][0][icen],var[1][1][icen],var[1][2][icen],var[1][3][icen],var[1][4][icen],var[1][5][icen],var[1][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[1][0][icen],rms[1][1][icen],rms[1][2][icen],rms[1][3][icen],rms[1][4][icen],rms[1][5][icen],rms[1][6][icen]);

  }
  f10.close();

  cout << endl << endl;
  sprintf(name,"20pstepresults/t%s.txt",xname);
  ofstream f20(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<5; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f20 << var[2][ivar][icen] << " ";
    }
    f20 << var[2][nval][icen] << " ";
    f20 << endl<<  " (";

    /*for(int ivar=0; ivar<7; ivar++){
      f20 << rms[2][ivar][icen] << " ";
    }
    f20 << rms[2][nval][icen] << " ";
    f20 <<  ")"<< endl;
    */
    cout << icen*20 << "-" << icen*20+20;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[2][ivar][icen] ;
    }
    cout <<" & " <<var[2][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[2][ivar][icen];
      else cout <<" & "<<rms[2][ivar][icen];
    }
    cout <<" & "<<rms[2][nval][icen];
    cout <<  ")\\\\\\hline" << endl;
    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[2][0][icen],var[2][1][icen],var[2][2][icen],var[2][3][icen],var[2][4][icen],var[2][5][icen],var[2][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[2][0][icen],rms[2][1][icen],rms[2][2][icen],rms[2][3][icen],rms[2][4][icen],rms[2][5][icen],rms[2][6][icen]);

  }
  f20.close();

  fout->Write();
  fout->Close();

  return;
}
Exemplo n.º 21
0
void SetYRange(TH1 &h, double ymin, double ymax){
	h.GetYaxis()->SetRangeUser(ymin,ymax);
}
///////////////////////
// Begin Main function:
void mkROOTaqgcMuLT0_Para(){


  //////////////////////////////////////
  // Set MC normalization scale factors:
  const double intLUMI = 19297;

  const double WWA_scale     =  2.1*0.01362 * intLUMI/198777;
  const double WWA2_scale    =  2.1*0.01409 * intLUMI/199183;

  const double LT0_p8m5_scale     =  2.1*0.0809985 * intLUMI/184603 ;
  const double LT0_p5m5_scale     =  2.1*0.0443325 * intLUMI/149975;
  const double LT0_p3m5_scale     =  2.1*0.029308 * intLUMI/97015;
  const double LT0_m3m5_scale     =  2.1*0.0290669 * intLUMI/154634;
  const double LT0_m5m5_scale     =  2.1*0.0440545 * intLUMI/199930;
  const double LT0_m8m5_scale     =  2.1*0.0806445 * intLUMI/196613;


  ///////////////////////////////////////////////////////////////////////////////////
  // Specify what kinematical distribution to observe, as well as histogram settings:
  // 
  plotVar_t pv = {"Photon_Et[iPhoton12]",30,450,10,3,"Photon ET (GeV)"};
  if ( !strlen(pv.plotvar) ) break;
  std::cout << TString(pv.plotvar) << "\t"<<pv.MINRange<<"\t" << pv.MAXRange<<"\t" << pv.NBINS<<"\tTHE CUT " << endl;


  ////////////////////////////////
  // Specify event selection cuts:
  TCut the_cutKfac("effwt*puwt*(iPhoton12>-1&&Photon_Et[iPhoton12]>30.&&Photon_dRlep[iPhoton12]>0.5&&i12Jet2>-1&&i12Jet1>-1&&JetPFCor_dRpho12[i12Jet1]>0.5&&JetPFCor_dRpho12[i12Jet2]>0.5&&abs(W_muon_eta)<2.1&&abs(JetPFCor_dphiMET[i12Jet1])>0.4&& abs(JetPFCor_dphiMET[i12Jet2])>0.4&&JetPFCor_bDiscriminatorCSV[i12Jet1]<0.679&&JetPFCor_bDiscriminatorCSV[i12Jet2]<0.679&&abs(JetPFCor_Eta[i12Jet1]-JetPFCor_Eta[i12Jet2])<1.4&&abs(Photon_Eta[iPhoton12])<1.44421&&W_muon_pt>25&&event_met_pfmet>35.&&c2jMass12>70.&&c2jMass12<100.&&W_mt>30.&&abs(W_muon_dz000)<0.02&&abs(W_muon_dzPV)<0.5&&((i12Jet3>-1)? JetPFCor_dRpho12[i12Jet3]>0.5: 1 )&&((i12Jet4>-1)? JetPFCor_dRpho12[i12Jet4]>0.5: 1 ))");
//mva2jWWAmuA1>0.32

  ///////////////////////////
  // Create output ROOT file:
  TFile f("para_mu_LT0_WWA_PhotonEt.root", "RECREATE");


  //////////////////////////////////////////////////
  // Create file pointers for each sample ROOT file:
  TFile *wwaShape_file,*wwa2Shape_file;

  TFile *LT0_m8m5_file,*LT0_m5m5_file,*LT0_m3m5_file,*LT0_p3m5_file,*LT0_p5m5_file,*LT0_p8m5_file;


  //////////////////////////////
  // Open each sample ROOT file:
  wwaShape_file = new TFile("InData_New/RD_mu_qq_wpwma_wp_qq_wm_lvl.root");
  wwa2Shape_file = new TFile("InData_New/RD_mu_qq_wpwma_wp_lvl_wm_qq.root");

  LT0_m8m5_file = new TFile("InData_New/RD_mu_LT0_m8m11MG_CMSSW532.root");
  LT0_m5m5_file = new TFile("InData_New/RD_mu_LT0_m5m11MG_CMSSW532.root");
  LT0_m3m5_file = new TFile("InData_New/RD_mu_LT0_m3m11MG_CMSSW532.root");
  LT0_p3m5_file = new TFile("InData_New/RD_mu_LT0_p3m11MG_CMSSW532.root");
  LT0_p5m5_file = new TFile("InData_New/RD_mu_LT0_p5m11MG_CMSSW532.root");
  LT0_p8m5_file = new TFile("InData_New/RD_mu_LT0_p8m11MG_CMSSW532.root");


  ///////////////////////////////////////////////////
  // Retrieve ROOT tree with kinematic distributions:
  TTree* treewwa    = (TTree*)    wwaShape_file->Get("WJet");
  TTree* treewwa2    = (TTree*)    wwa2Shape_file->Get("WJet");

  TTree* treeLT0_m8m5 = (TTree*) LT0_m8m5_file->Get("WJet");
  TTree* treeLT0_m5m5 = (TTree*) LT0_m5m5_file->Get("WJet");
  TTree* treeLT0_m3m5 = (TTree*) LT0_m3m5_file->Get("WJet");
  TTree* treeLT0_p3m5 = (TTree*) LT0_p3m5_file->Get("WJet");
  TTree* treeLT0_p5m5 = (TTree*) LT0_p5m5_file->Get("WJet");
  TTree* treeLT0_p8m5 = (TTree*) LT0_p8m5_file->Get("WJet");


  ////////////////////////////////////////////////////////////
  // Create kinematic-distribution histograms for each sample:
  TH1* th1wwa = new TH1D("th1wwa", "th1wwa", pv.NBINS, pv.MINRange, pv.MAXRange);
  TH1* th1wwa2 = new TH1D("th1wwa2", "th1wwa2", pv.NBINS, pv.MINRange, pv.MAXRange);

  TH1* signal_lt0_80 = new TH1D("signal_lt0_80","signal_lt0_80",pv.NBINS, pv.MINRange, pv.MAXRange);
  TH1* signal_lt0_50 = new TH1D("signal_lt0_50","signal_lt0_50",pv.NBINS, pv.MINRange, pv.MAXRange);
  TH1* signal_lt0_30 = new TH1D("signal_lt0_30","signal_lt0_30",pv.NBINS, pv.MINRange, pv.MAXRange);
  TH1* signal_lt0_m30 = new TH1D("signal_lt0_m30","signal_lt0_-30",pv.NBINS, pv.MINRange, pv.MAXRange);
  TH1* signal_lt0_m50 = new TH1D("signal_lt0_m50","signal_lt0_-50",pv.NBINS, pv.MINRange, pv.MAXRange);
  TH1* signal_lt0_m80 = new TH1D("signal_lt0_m80","signal_lt0_-80",pv.NBINS, pv.MINRange, pv.MAXRange);


  /////////////////////////////////////////////////////////////////////////
  // Specify histograms to store Sum of Squares of Weights for each sample:
  th1wwa->Sumw2();
  th1wwa2->Sumw2();

  ///////////////////////////////////////////////////////////////////////////////////
  // Fill kinematical distribution for each sample according to event selection cuts:
  std::cout<<"Fill SM WWA Histogram..."<<std::endl;
  treewwa->Draw(TString(pv.plotvar)+TString(">>th1wwa"), the_cutKfac, "goff");
  th1wwa->AddBinContent(pv.NBINS,th1wwa->GetBinContent(pv.NBINS+1));th1wwa->SetBinContent(pv.NBINS+1,0.);
  treewwa2->Draw(TString(pv.plotvar)+TString(">>th1wwa2"), the_cutKfac, "goff");
  th1wwa2->AddBinContent(pv.NBINS,th1wwa2->GetBinContent(pv.NBINS+1));th1wwa2->SetBinContent(pv.NBINS+1,0.);


  std::cout<<"Fill aQGC_1 WWA Histogram..."<<std::endl;
  treeLT0_m8m5->Draw(TString(pv.plotvar)+TString(">>signal_lt0_m80"), the_cutKfac, "goff");

  std::cout<<"Fill aQGC_2 WWA Histogram..."<<std::endl;
  treeLT0_m5m5->Draw(TString(pv.plotvar)+TString(">>signal_lt0_m50"), the_cutKfac, "goff");

  std::cout<<"Fill aQGC_3 WWA Histogram..."<<std::endl;
  treeLT0_m3m5->Draw(TString(pv.plotvar)+TString(">>signal_lt0_m30"), the_cutKfac, "goff");

  std::cout<<"Fill aQGC_4 WWA Histogram..."<<std::endl;
  treeLT0_p3m5->Draw(TString(pv.plotvar)+TString(">>signal_lt0_30"), the_cutKfac, "goff");

  std::cout<<"Fill aQGC_5 WWA Histogram..."<<std::endl;
  treeLT0_p5m5->Draw(TString(pv.plotvar)+TString(">>signal_lt0_50"), the_cutKfac, "goff");

  std::cout<<"Fill aQGC_6 WWA Histogram..."<<std::endl;
  treeLT0_p8m5->Draw(TString(pv.plotvar)+TString(">>signal_lt0_80"), the_cutKfac, "goff");

  signal_lt0_80->AddBinContent(pv.NBINS,signal_lt0_80->GetBinContent(pv.NBINS+1));signal_lt0_80->SetBinContent(pv.NBINS+1,0.);
  signal_lt0_50->AddBinContent(pv.NBINS,signal_lt0_50->GetBinContent(pv.NBINS+1));signal_lt0_50->SetBinContent(pv.NBINS+1,0.);
  signal_lt0_30->AddBinContent(pv.NBINS,signal_lt0_30->GetBinContent(pv.NBINS+1));signal_lt0_30->SetBinContent(pv.NBINS+1,0.);
  signal_lt0_m30->AddBinContent(pv.NBINS,signal_lt0_m30->GetBinContent(pv.NBINS+1));signal_lt0_m30->SetBinContent(pv.NBINS+1,0.);
  signal_lt0_m50->AddBinContent(pv.NBINS,signal_lt0_m50->GetBinContent(pv.NBINS+1));signal_lt0_m50->SetBinContent(pv.NBINS+1,0.);
  signal_lt0_m80->AddBinContent(pv.NBINS,signal_lt0_m80->GetBinContent(pv.NBINS+1));signal_lt0_m80->SetBinContent(pv.NBINS+1,0.);


  /////////////////////////
  // Normalize each sample:
  std::cout<<"\nScale Histograms..."<<std::endl;
  th1wwa->Scale(WWA_scale);
  th1wwa2->Scale(WWA2_scale);

  signal_lt0_m80->Scale(LT0_m8m5_scale);
  signal_lt0_m50->Scale(LT0_m5m5_scale);
  signal_lt0_m30->Scale(LT0_m3m5_scale);
  signal_lt0_30->Scale(LT0_p3m5_scale);
  signal_lt0_50->Scale(LT0_p5m5_scale);
  signal_lt0_80->Scale(LT0_p8m5_scale);


  ///////////////////////////
  // Combine certain samples:
  th1wwa->Add(th1wwa2,1);

  signal_lt0_80->Divide(th1wwa);
  signal_lt0_50->Divide(th1wwa);
  signal_lt0_30->Divide(th1wwa);
  signal_lt0_m30->Divide(th1wwa);
  signal_lt0_m50->Divide(th1wwa);
  signal_lt0_m80->Divide(th1wwa);

  ///////////////////////////
  //Fill Parabolic Histogram:
  TH1* bin_1 = new TH1D("bin_1","bin_1",17, -8.5E-11, 8.5E-11);
  TH1* bin_2 = new TH1D("bin_2","bin_2",17, -8.5E-11, 8.5E-11);
  TH1* bin_3 = new TH1D("bin_3","bin_3",17, -8.5E-11, 8.5E-11);
  TH1* bin_4 = new TH1D("bin_4","bin_4",17, -8.5E-11, 8.5E-11);
  TH1* bin_5 = new TH1D("bin_5","bin_5",17, -8.5E-11, 8.5E-11);
  TH1* bin_6 = new TH1D("bin_6","bin_6",17, -8.5E-11, 8.5E-11);
  TH1* bin_7 = new TH1D("bin_7","bin_7",17, -8.5E-11, 8.5E-11);
  TH1* bin_8 = new TH1D("bin_8","bin_8",17, -8.5E-11, 8.5E-11);
  TH1* bin_9 = new TH1D("bin_9","bin_9",17, -8.5E-11, 8.5E-11);
  TH1* bin_10 = new TH1D("bin_10","bin_10",17, -8.5E-11, 8.5E-11);


  bin_1->SetBinContent(1,signal_lt0_m80->GetBinContent(1));
  bin_1->SetBinContent(4,signal_lt0_m50->GetBinContent(1));
  bin_1->SetBinContent(6,signal_lt0_m30->GetBinContent(1));
  bin_1->SetBinContent(9,1);
  bin_1->SetBinContent(12,signal_lt0_30->GetBinContent(1));
  bin_1->SetBinContent(14,signal_lt0_50->GetBinContent(1));
  bin_1->SetBinContent(17,signal_lt0_80->GetBinContent(1));

  bin_2->SetBinContent(1,signal_lt0_m80->GetBinContent(2));
  bin_2->SetBinContent(4,signal_lt0_m50->GetBinContent(2));
  bin_2->SetBinContent(6,signal_lt0_m30->GetBinContent(2));
  bin_2->SetBinContent(9,1);
  bin_2->SetBinContent(12,signal_lt0_30->GetBinContent(2));
  bin_2->SetBinContent(14,signal_lt0_50->GetBinContent(2));
  bin_2->SetBinContent(17,signal_lt0_80->GetBinContent(2));

  bin_3->SetBinContent(1,signal_lt0_m80->GetBinContent(3));
  bin_3->SetBinContent(4,signal_lt0_m50->GetBinContent(3));
  bin_3->SetBinContent(6,signal_lt0_m30->GetBinContent(3));
  bin_3->SetBinContent(9,1);
  bin_3->SetBinContent(12,signal_lt0_30->GetBinContent(3));
  bin_3->SetBinContent(14,signal_lt0_50->GetBinContent(3));
  bin_3->SetBinContent(17,signal_lt0_80->GetBinContent(3));

  bin_4->SetBinContent(1,signal_lt0_m80->GetBinContent(4));
  bin_4->SetBinContent(4,signal_lt0_m50->GetBinContent(4));
  bin_4->SetBinContent(6,signal_lt0_m30->GetBinContent(4));
  bin_4->SetBinContent(9,1);
  bin_4->SetBinContent(12,signal_lt0_30->GetBinContent(4));
  bin_4->SetBinContent(14,signal_lt0_50->GetBinContent(4));
  bin_4->SetBinContent(17,signal_lt0_80->GetBinContent(4));

  bin_5->SetBinContent(1,signal_lt0_m80->GetBinContent(5));
  bin_5->SetBinContent(4,signal_lt0_m50->GetBinContent(5));
  bin_5->SetBinContent(6,signal_lt0_m30->GetBinContent(5));
  bin_5->SetBinContent(9,1);
  bin_5->SetBinContent(12,signal_lt0_30->GetBinContent(5));
  bin_5->SetBinContent(14,signal_lt0_50->GetBinContent(5));
  bin_5->SetBinContent(17,signal_lt0_80->GetBinContent(5));

  bin_6->SetBinContent(1,signal_lt0_m80->GetBinContent(6));
  bin_6->SetBinContent(4,signal_lt0_m50->GetBinContent(6));
  bin_6->SetBinContent(6,signal_lt0_m30->GetBinContent(6));
  bin_6->SetBinContent(9,1);
  bin_6->SetBinContent(12,signal_lt0_30->GetBinContent(6));
  bin_6->SetBinContent(14,signal_lt0_50->GetBinContent(6));
  bin_6->SetBinContent(17,signal_lt0_80->GetBinContent(6));

  bin_7->SetBinContent(1,signal_lt0_m80->GetBinContent(7));
  bin_7->SetBinContent(4,signal_lt0_m50->GetBinContent(7));
  bin_7->SetBinContent(6,signal_lt0_m30->GetBinContent(7));
  bin_7->SetBinContent(9,1);
  bin_7->SetBinContent(12,signal_lt0_30->GetBinContent(7));
  bin_7->SetBinContent(14,signal_lt0_50->GetBinContent(7));
  bin_7->SetBinContent(17,signal_lt0_80->GetBinContent(7));

  bin_8->SetBinContent(1,signal_lt0_m80->GetBinContent(8));
  bin_8->SetBinContent(4,signal_lt0_m50->GetBinContent(8));
  bin_8->SetBinContent(6,signal_lt0_m30->GetBinContent(8));
  bin_8->SetBinContent(9,1);
  bin_8->SetBinContent(12,signal_lt0_30->GetBinContent(8));
  bin_8->SetBinContent(14,signal_lt0_50->GetBinContent(8));
  bin_8->SetBinContent(17,signal_lt0_80->GetBinContent(8));

  bin_9->SetBinContent(1,signal_lt0_m80->GetBinContent(9));
  bin_9->SetBinContent(4,signal_lt0_m50->GetBinContent(9));
  bin_9->SetBinContent(6,signal_lt0_m30->GetBinContent(9));
  bin_9->SetBinContent(9,1);
  bin_9->SetBinContent(12,signal_lt0_30->GetBinContent(9));
  bin_9->SetBinContent(14,signal_lt0_50->GetBinContent(9));
  bin_9->SetBinContent(17,signal_lt0_80->GetBinContent(9));

  bin_10->SetBinContent(1,signal_lt0_m80->GetBinContent(10));
  bin_10->SetBinContent(4,signal_lt0_m50->GetBinContent(10));
  bin_10->SetBinContent(6,signal_lt0_m30->GetBinContent(10));
  bin_10->SetBinContent(9,1);
  bin_10->SetBinContent(12,signal_lt0_30->GetBinContent(10));
  bin_10->SetBinContent(14,signal_lt0_50->GetBinContent(10));
  bin_10->SetBinContent(17,signal_lt0_80->GetBinContent(10));


  ////////////////
  // Fit function:
  Char_t para_fit[] = "[0]+[1]*x+[2]*x^2";
  Char_t fitopt[] = "QMR";
  Double_t xmin = -8E-5;
  Double_t xmax = 8E-5;
  Double_t p[3][10];
  TF1 *pfit = new TF1("pfit",para_fit,xmin,xmax);
//  pfit->SetParLimits(1,0.0,1E15);
//  pfit->FixParameter(0,0.0);


  /////////////////
  // Fit histogram:
  bin_1->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][0] = pfit->GetParameter(0);
  p[1][0] = pfit->GetParameter(1);
  p[2][0] = pfit->GetParameter(2);

  bin_2->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][1] = pfit->GetParameter(0);
  p[1][1] = pfit->GetParameter(1);
  p[2][1] = pfit->GetParameter(2);

  bin_3->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][2] = pfit->GetParameter(0);
  p[1][2] = pfit->GetParameter(1);
  p[2][2] = pfit->GetParameter(2);

  bin_4->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][3] = pfit->GetParameter(0);
  p[1][3] = pfit->GetParameter(1);
  p[2][3] = pfit->GetParameter(2);

  bin_5->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][4] = pfit->GetParameter(0);
  p[1][4] = pfit->GetParameter(1);
  p[2][4] = pfit->GetParameter(2);

  bin_6->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][5] = pfit->GetParameter(0);
  p[1][5] = pfit->GetParameter(1);
  p[2][5] = pfit->GetParameter(2);

  bin_7->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][6] = pfit->GetParameter(0);
  p[1][6] = pfit->GetParameter(1);
  p[2][6] = pfit->GetParameter(2);

  bin_8->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][7] = pfit->GetParameter(0);
  p[1][7] = pfit->GetParameter(1);
  p[2][7] = pfit->GetParameter(2);

  bin_9->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][8] = pfit->GetParameter(0);
  p[1][8] = pfit->GetParameter(1);
  p[2][8] = pfit->GetParameter(2);

  bin_10->Fit(pfit,fitopt,"sames",xmin,xmax);
  p[0][9] = pfit->GetParameter(0);
  p[1][9] = pfit->GetParameter(1);
  p[2][9] = pfit->GetParameter(2);


  /////////////////////////////
  // Fill parameter histograms:
  TH1* p0 = new TH1D("p0","Parameter 0",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* p1 = new TH1D("p1","Parameter 1",pv.NBINS,pv.MINRange,pv.MAXRange);

  for(Int_t i=1;i<=pv.NBINS;i++){
     p0->SetBinContent(i,p[0][i-1]);
     p1->SetBinContent(i,p[1][i-1]);
  }

/*
  ///////////////////
  // Fit pT-function:
  Char_t pt_fit[] = "[0]+[1]*x+[2]*x^2";
  Char_t fitopt[] = "QMR";
  Double_t xmin = 150;//45;
  Double_t xmax = 1050;//275;
  Double_t pt[2][3];
  TF1 *ptfit = new TF1("ptfit",pt_fit,xmin,xmax);

  p0->Fit(ptfit,fitopt,"sames",xmin,xmax);
  pt[0][0] = ptfit->GetParameter(0);
  pt[0][1] = ptfit->GetParameter(1);
  pt[0][2] = ptfit->GetParameter(2);

  p1->Fit(ptfit,fitopt,"sames",xmin,xmax);
  pt[1][0] = ptfit->GetParameter(0);
  pt[1][1] = ptfit->GetParameter(1);
  pt[1][2] = ptfit->GetParameter(2);
*/

  ////////////////
  // Closure test:
  // ratio = 1 + (pt[0][0]+pt[0][1]*pt+pt[0][2]*pt^2)*KOW + (pt[1][0]+pt[1][1]*pt+[1][2]*pt^2)*KOW^2
  TH1* test = new TH1D("test","Test aQGC Photon ET",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* test2 = new TH1D("test2","Test aQGC Photon ET",pv.NBINS,pv.MINRange,pv.MAXRange);

  for(Int_t j=1;j<=pv.NBINS;j++){

     Double_t value,bincent;
     TAxis* xaxis = test->GetXaxis();
     bincent = xaxis->GetBinCenter(j);

     value = p[0][j-1]+p[1][j-1]*(8E-11)+p[2][j-1]*pow(8E-11,2);
     test->SetBinContent(j,value);

     test2->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-8E-11)+p[2][j-1]*pow(-8E-11,2));

  }

//  test->SetBinContent(8,1+p[0][7]*(8E-11)+p[1][7]*pow(8E-11,2));
//  test2->SetBinContent(8,1+p[0][7]*(-8E-11)+p[1][7]*pow(-8E-11,2));

  TH1D* test_r = (TH1D*)test->Clone("test_r");
  TH1D* test2_r = (TH1D*)test2->Clone("test2_r");

  test_r->Divide(signal_lt0_80);
  test2_r->Divide(signal_lt0_m80);

  test->Multiply(th1wwa);
  test2->Multiply(th1wwa);
  test->Add(th1wwa,-1);
  test2->Add(th1wwa,-1);


  /////////////////////
  // Simulate new aQGC:
  TH1* signal_lt0_18 = new TH1D("signal_lt0_18","signal_lt0_1p8",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_20 = new TH1D("signal_lt0_20","signal_lt0_2p0",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_22 = new TH1D("signal_lt0_22","signal_lt0_2p2",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_24 = new TH1D("signal_lt0_24","signal_lt0_2p4",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_26 = new TH1D("signal_lt0_26","signal_lt0_2p6",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_28 = new TH1D("signal_lt0_28","signal_lt0_2p8",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_32 = new TH1D("signal_lt0_32","signal_lt0_3p2",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_34 = new TH1D("signal_lt0_34","signal_lt0_3p4",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_36 = new TH1D("signal_lt0_36","signal_lt0_3p6",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_38 = new TH1D("signal_lt0_38","signal_lt0_3p8",pv.NBINS,pv.MINRange,pv.MAXRange);

  TH1* signal_lt0_m18 = new TH1D("signal_lt0_m18","signal_lt0_-1p8",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m20 = new TH1D("signal_lt0_m20","signal_lt0_-2p0",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m22 = new TH1D("signal_lt0_m22","signal_lt0_-2p2",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m24 = new TH1D("signal_lt0_m24","signal_lt0_-2p4",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m26 = new TH1D("signal_lt0_m26","signal_lt0_-2p6",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m28 = new TH1D("signal_lt0_m28","signal_lt0_-2p8",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m32 = new TH1D("signal_lt0_m32","signal_lt0_-3p2",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m34 = new TH1D("signal_lt0_m34","signal_lt0_-3p4",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m36 = new TH1D("signal_lt0_m36","signal_lt0_-3p6",pv.NBINS,pv.MINRange,pv.MAXRange);
  TH1* signal_lt0_m38 = new TH1D("signal_lt0_m38","signal_lt0_-3p8",pv.NBINS,pv.MINRange,pv.MAXRange);


  signal_lt0_18->Sumw2();
  signal_lt0_20->Sumw2();
  signal_lt0_22->Sumw2();
  signal_lt0_24->Sumw2();
  signal_lt0_26->Sumw2();
  signal_lt0_28->Sumw2();
  signal_lt0_32->Sumw2();
  signal_lt0_34->Sumw2();
  signal_lt0_36->Sumw2();
  signal_lt0_38->Sumw2();
  signal_lt0_m18->Sumw2();
  signal_lt0_m20->Sumw2();
  signal_lt0_m22->Sumw2();
  signal_lt0_m24->Sumw2();
  signal_lt0_m26->Sumw2();
  signal_lt0_m28->Sumw2();
  signal_lt0_m32->Sumw2();
  signal_lt0_m34->Sumw2();
  signal_lt0_m36->Sumw2();
  signal_lt0_m38->Sumw2();

  for(Int_t j=1;j<=pv.NBINS;j++){

     Double_t bincent;
     TAxis* xaxis = test->GetXaxis();
     bincent = xaxis->GetBinCenter(j);

     signal_lt0_m50->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-5.E-11)+p[2][j-1]*pow(-5.E-11,2));
     signal_lt0_m30->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-3.E-11)+p[2][j-1]*pow(-3.E-11,2));
     signal_lt0_m80->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-8.E-11)+p[2][j-1]*pow(-8.E-11,2));

     signal_lt0_m28->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-2.8E-11)+p[2][j-1]*pow(-2.8E-11,2));
     signal_lt0_m26->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-2.6E-11)+p[2][j-1]*pow(-2.6E-11,2));
     signal_lt0_m24->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-2.4E-11)+p[2][j-1]*pow(-2.4E-11,2));
     signal_lt0_m22->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-2.2E-11)+p[2][j-1]*pow(-2.2E-11,2));
     signal_lt0_m20->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-2.E-11)+p[2][j-1]*pow(-2.E-11,2));
     signal_lt0_m18->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-1.8E-11)+p[2][j-1]*pow(-1.8E-11,2));
     signal_lt0_m32->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-3.2E-11)+p[2][j-1]*pow(-3.2E-11,2));
     signal_lt0_m34->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-3.4E-11)+p[2][j-1]*pow(-3.4E-11,2));
     signal_lt0_m36->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-3.6E-11)+p[2][j-1]*pow(-3.6E-11,2));
     signal_lt0_m38->SetBinContent(j,p[0][j-1]+p[1][j-1]*(-3.8E-11)+p[2][j-1]*pow(-3.8E-11,2));

     signal_lt0_50->SetBinContent(j,p[0][j-1]+p[1][j-1]*(5.E-11)+p[2][j-1]*pow(5.E-11,2));
     signal_lt0_30->SetBinContent(j,p[0][j-1]+p[1][j-1]*(3.E-11)+p[2][j-1]*pow(3.E-11,2));
     signal_lt0_80->SetBinContent(j,p[0][j-1]+p[1][j-1]*(8.E-11)+p[2][j-1]*pow(8.E-11,2));

     signal_lt0_28->SetBinContent(j,p[0][j-1]+p[1][j-1]*(2.8E-11)+p[2][j-1]*pow(2.8E-11,2));
     signal_lt0_26->SetBinContent(j,p[0][j-1]+p[1][j-1]*(2.6E-11)+p[2][j-1]*pow(2.6E-11,2));
     signal_lt0_24->SetBinContent(j,p[0][j-1]+p[1][j-1]*(2.4E-11)+p[2][j-1]*pow(2.4E-11,2));
     signal_lt0_22->SetBinContent(j,p[0][j-1]+p[1][j-1]*(2.2E-11)+p[2][j-1]*pow(2.2E-11,2));
     signal_lt0_20->SetBinContent(j,p[0][j-1]+p[1][j-1]*(2.E-11)+p[2][j-1]*pow(2.E-11,2));
     signal_lt0_18->SetBinContent(j,p[0][j-1]+p[1][j-1]*(1.8E-11)+p[2][j-1]*pow(1.8E-11,2));
     signal_lt0_32->SetBinContent(j,p[0][j-1]+p[1][j-1]*(3.2E-11)+p[2][j-1]*pow(3.2E-11,2));
     signal_lt0_34->SetBinContent(j,p[0][j-1]+p[1][j-1]*(3.4E-11)+p[2][j-1]*pow(3.4E-11,2));
     signal_lt0_36->SetBinContent(j,p[0][j-1]+p[1][j-1]*(3.6E-11)+p[2][j-1]*pow(3.6E-11,2));
     signal_lt0_38->SetBinContent(j,p[0][j-1]+p[1][j-1]*(3.8E-11)+p[2][j-1]*pow(3.8E-11,2));

  }
/*
  signal_lt0_m50->SetBinContent(8,1+p[0][7]*(-5.E-11)+p[1][7]*pow(-5.E-11,2));
  signal_lt0_m30->SetBinContent(8,1+p[0][7]*(-3.E-11)+p[1][7]*pow(-3.E-11,2));
  signal_lt0_m80->SetBinContent(8,1+p[0][7]*(-8.E-11)+p[1][7]*pow(-8.E-11,2));

  signal_lt0_m28->SetBinContent(8,1+p[0][7]*(-2.8E-11)+p[1][7]*pow(-2.8E-11,2));
  signal_lt0_m26->SetBinContent(8,1+p[0][7]*(-2.6E-11)+p[1][7]*pow(-2.6E-11,2));
  signal_lt0_m24->SetBinContent(8,1+p[0][7]*(-2.4E-11)+p[1][7]*pow(-2.4E-11,2));
  signal_lt0_m22->SetBinContent(8,1+p[0][7]*(-2.2E-11)+p[1][7]*pow(-2.2E-11,2));
  signal_lt0_m20->SetBinContent(8,1+p[0][7]*(-2.E-11)+p[1][7]*pow(-2.E-11,2));
  signal_lt0_m18->SetBinContent(8,1+p[0][7]*(-1.8E-11)+p[1][7]*pow(-1.8E-11,2));
  signal_lt0_m32->SetBinContent(8,1+p[0][7]*(-3.2E-11)+p[1][7]*pow(-3.2E-11,2));
  signal_lt0_m34->SetBinContent(8,1+p[0][7]*(-3.4E-11)+p[1][7]*pow(-3.4E-11,2));
  signal_lt0_m36->SetBinContent(8,1+p[0][7]*(-3.6E-11)+p[1][7]*pow(-3.6E-11,2));
  signal_lt0_m38->SetBinContent(8,1+p[0][7]*(-3.8E-11)+p[1][7]*pow(-3.8E-11,2));

  signal_lt0_50->SetBinContent(8,1+p[0][7]*(5.E-11)+p[1][7]*pow(5.E-11,2));
  signal_lt0_30->SetBinContent(8,1+p[0][7]*(3.E-11)+p[1][7]*pow(3.E-11,2));
  signal_lt0_80->SetBinContent(8,1+p[0][7]*(8.E-11)+p[1][7]*pow(8.E-11,2));

  signal_lt0_28->SetBinContent(8,1+p[0][7]*(2.8E-11)+p[1][7]*pow(2.8E-11,2));
  signal_lt0_26->SetBinContent(8,1+p[0][7]*(2.6E-11)+p[1][7]*pow(2.6E-11,2));
  signal_lt0_24->SetBinContent(8,1+p[0][7]*(2.4E-11)+p[1][7]*pow(2.4E-11,2));
  signal_lt0_22->SetBinContent(8,1+p[0][7]*(2.2E-11)+p[1][7]*pow(2.2E-11,2));
  signal_lt0_20->SetBinContent(8,1+p[0][7]*(2.E-11)+p[1][7]*pow(2.E-11,2));
  signal_lt0_18->SetBinContent(8,1+p[0][7]*(1.8E-11)+p[1][7]*pow(1.8E-11,2));
  signal_lt0_32->SetBinContent(8,1+p[0][7]*(3.2E-11)+p[1][7]*pow(3.2E-11,2));
  signal_lt0_34->SetBinContent(8,1+p[0][7]*(3.4E-11)+p[1][7]*pow(3.4E-11,2));
  signal_lt0_36->SetBinContent(8,1+p[0][7]*(3.6E-11)+p[1][7]*pow(3.6E-11,2));
  signal_lt0_38->SetBinContent(8,1+p[0][7]*(3.8E-11)+p[1][7]*pow(3.8E-11,2));
*/
  signal_lt0_m50->Multiply(th1wwa);
  signal_lt0_m30->Multiply(th1wwa);
  signal_lt0_m80->Multiply(th1wwa);

  signal_lt0_m28->Multiply(th1wwa);
  signal_lt0_m26->Multiply(th1wwa);
  signal_lt0_m24->Multiply(th1wwa);
  signal_lt0_m22->Multiply(th1wwa);
  signal_lt0_m20->Multiply(th1wwa);
  signal_lt0_m18->Multiply(th1wwa);
  signal_lt0_m32->Multiply(th1wwa);
  signal_lt0_m34->Multiply(th1wwa);
  signal_lt0_m36->Multiply(th1wwa);
  signal_lt0_m38->Multiply(th1wwa);

  signal_lt0_50->Multiply(th1wwa);
  signal_lt0_30->Multiply(th1wwa);
  signal_lt0_80->Multiply(th1wwa);

  signal_lt0_28->Multiply(th1wwa);
  signal_lt0_26->Multiply(th1wwa);
  signal_lt0_24->Multiply(th1wwa);
  signal_lt0_22->Multiply(th1wwa);
  signal_lt0_20->Multiply(th1wwa);
  signal_lt0_18->Multiply(th1wwa);
  signal_lt0_32->Multiply(th1wwa);
  signal_lt0_34->Multiply(th1wwa);
  signal_lt0_36->Multiply(th1wwa);
  signal_lt0_38->Multiply(th1wwa);

  signal_lt0_m50->Add(th1wwa,-1);
  signal_lt0_m30->Add(th1wwa,-1);
  signal_lt0_m80->Add(th1wwa,-1);

  signal_lt0_m28->Add(th1wwa,-1);
  signal_lt0_m26->Add(th1wwa,-1);
  signal_lt0_m24->Add(th1wwa,-1);
  signal_lt0_m22->Add(th1wwa,-1);
  signal_lt0_m20->Add(th1wwa,-1);
  signal_lt0_m18->Add(th1wwa,-1);
  signal_lt0_m32->Add(th1wwa,-1);
  signal_lt0_m34->Add(th1wwa,-1);
  signal_lt0_m36->Add(th1wwa,-1);
  signal_lt0_m38->Add(th1wwa,-1);

  signal_lt0_50->Add(th1wwa,-1);
  signal_lt0_30->Add(th1wwa,-1);
  signal_lt0_80->Add(th1wwa,-1);

  signal_lt0_28->Add(th1wwa,-1);
  signal_lt0_26->Add(th1wwa,-1);
  signal_lt0_24->Add(th1wwa,-1);
  signal_lt0_22->Add(th1wwa,-1);
  signal_lt0_20->Add(th1wwa,-1);
  signal_lt0_18->Add(th1wwa,-1);
  signal_lt0_32->Add(th1wwa,-1);
  signal_lt0_34->Add(th1wwa,-1);
  signal_lt0_36->Add(th1wwa,-1);
  signal_lt0_38->Add(th1wwa,-1);


  signal_lt0_m50->Scale(1.185/2.1);
  signal_lt0_m30->Scale(1.185/2.1);
  signal_lt0_m80->Scale(1.185/2.1);

  signal_lt0_m28->Scale(1.185/2.1);
  signal_lt0_m26->Scale(1.185/2.1);
  signal_lt0_m24->Scale(1.185/2.1);
  signal_lt0_m22->Scale(1.185/2.1);
  signal_lt0_m20->Scale(1.185/2.1);
  signal_lt0_m18->Scale(1.185/2.1);
  signal_lt0_m32->Scale(1.185/2.1);
  signal_lt0_m34->Scale(1.185/2.1);
  signal_lt0_m36->Scale(1.185/2.1);
  signal_lt0_m38->Scale(1.185/2.1);

  signal_lt0_50->Scale(1.185/2.1);
  signal_lt0_30->Scale(1.185/2.1);
  signal_lt0_80->Scale(1.185/2.1);

  signal_lt0_28->Scale(1.185/2.1);
  signal_lt0_26->Scale(1.185/2.1);
  signal_lt0_24->Scale(1.185/2.1);
  signal_lt0_22->Scale(1.185/2.1);
  signal_lt0_20->Scale(1.185/2.1);
  signal_lt0_18->Scale(1.185/2.1);
  signal_lt0_32->Scale(1.185/2.1);
  signal_lt0_34->Scale(1.185/2.1);
  signal_lt0_36->Scale(1.185/2.1);
  signal_lt0_38->Scale(1.185/2.1);

/*
  signal_lt0_18->Sumw2();
  signal_lt0_20->Sumw2();
  signal_lt0_22->Sumw2();
  signal_lt0_24->Sumw2();
  signal_lt0_26->Sumw2();
  signal_lt0_28->Sumw2();
  signal_lt0_30->Sumw2();
  signal_lt0_32->Sumw2();
  signal_lt0_34->Sumw2();
  signal_lt0_36->Sumw2();
  signal_lt0_38->Sumw2();
  signal_lt0_50->Sumw2();
  signal_lt0_80->Sumw2();

  signal_lt0_m18->Sumw2();
  signal_lt0_m20->Sumw2();
  signal_lt0_m22->Sumw2();
  signal_lt0_m24->Sumw2();
  signal_lt0_m26->Sumw2();
  signal_lt0_m28->Sumw2();
  signal_lt0_m30->Sumw2();
  signal_lt0_m32->Sumw2();
  signal_lt0_m34->Sumw2();
  signal_lt0_m36->Sumw2();
  signal_lt0_m38->Sumw2();
  signal_lt0_m50->Sumw2();
  signal_lt0_m80->Sumw2();
*/

/*  // Adding 35% Signal K-factor Systematic uncertainty
  for(int hi=1;hi<=pv.NBINS;hi++){

     fperr = pow(signal_lt0_m18->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m18->GetBinContent(hi),2);
     signal_lt0_m18->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m20->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m20->GetBinContent(hi),2);
     signal_lt0_m20->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m22->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m22->GetBinContent(hi),2);
     signal_lt0_m22->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m24->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m24->GetBinContent(hi),2);
     signal_lt0_m24->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m26->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m26->GetBinContent(hi),2);
     signal_lt0_m26->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m28->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m28->GetBinContent(hi),2);
     signal_lt0_m28->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m30->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m30->GetBinContent(hi),2);
     signal_lt0_m30->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m32->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m32->GetBinContent(hi),2);
     signal_lt0_m32->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m34->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m34->GetBinContent(hi),2);
     signal_lt0_m34->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m36->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m36->GetBinContent(hi),2);
     signal_lt0_m36->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m38->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m38->GetBinContent(hi),2);
     signal_lt0_m38->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m50->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m50->GetBinContent(hi),2);
     signal_lt0_m50->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_m80->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_m80->GetBinContent(hi),2);
     signal_lt0_m80->SetBinError(hi,sqrt(fperr));


     fperr = pow(signal_lt0_18->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_18->GetBinContent(hi),2);
     signal_lt0_18->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_20->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_20->GetBinContent(hi),2);
     signal_lt0_20->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_22->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_22->GetBinContent(hi),2);
     signal_lt0_22->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_24->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_24->GetBinContent(hi),2);
     signal_lt0_24->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_26->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_26->GetBinContent(hi),2);
     signal_lt0_26->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_28->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_28->GetBinContent(hi),2);
     signal_lt0_28->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_30->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_30->GetBinContent(hi),2);
     signal_lt0_30->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_32->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_32->GetBinContent(hi),2);
     signal_lt0_32->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_34->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_34->GetBinContent(hi),2);
     signal_lt0_34->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_36->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_36->GetBinContent(hi),2);
     signal_lt0_36->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_38->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_38->GetBinContent(hi),2);
     signal_lt0_38->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_50->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_50->GetBinContent(hi),2);
     signal_lt0_50->SetBinError(hi,sqrt(fperr));

     fperr = pow(signal_lt0_80->GetBinError(hi),2);
     fperr += pow(0.28,2)*pow(signal_lt0_80->GetBinContent(hi),2);
     signal_lt0_80->SetBinError(hi,sqrt(fperr));

  }
*/

  ////////////////////////
  // Set histogram labels:
  const double BINWIDTH = ((pv.MAXRange-pv.MINRange)/pv.NBINS);
  char tmpc[100];    sprintf(tmpc,"Events / %.1f GeV",BINWIDTH);
  if (pv.slog==1)    sprintf(tmpc,"Events / %.1f",BINWIDTH);
  if (pv.slog==2)    sprintf(tmpc,"Events / %.2f",BINWIDTH);
  if (pv.slog==3)    sprintf(tmpc,"Events / %.0f GeV",BINWIDTH);
  if (pv.slog==6)    sprintf(tmpc,"Events / %.2f rad",BINWIDTH);

  signal_lt0_80->SetYTitle(tmpc);
  signal_lt0_80->GetXaxis()->SetTitle(pv.xlabel);
  signal_lt0_80->GetYaxis()->CenterTitle(true);

  signal_lt0_50->SetYTitle(tmpc);
  signal_lt0_50->GetXaxis()->SetTitle(pv.xlabel);
  signal_lt0_50->GetYaxis()->CenterTitle(true);

  signal_lt0_30->SetYTitle(tmpc);
  signal_lt0_30->GetXaxis()->SetTitle(pv.xlabel);
  signal_lt0_30->GetYaxis()->CenterTitle(true);

  signal_lt0_m30->SetYTitle(tmpc);
  signal_lt0_m30->GetXaxis()->SetTitle(pv.xlabel);
  signal_lt0_m30->GetYaxis()->CenterTitle(true);

  signal_lt0_m50->SetYTitle(tmpc);
  signal_lt0_m50->GetXaxis()->SetTitle(pv.xlabel);
  signal_lt0_m50->GetYaxis()->CenterTitle(true);

  signal_lt0_m80->SetYTitle(tmpc);
  signal_lt0_m80->GetXaxis()->SetTitle(pv.xlabel);
  signal_lt0_m80->GetYaxis()->CenterTitle(true);


  //////////////////////////////////////////////////////////
  // Save Observed Data, Background (+ SM WWA), Background +
  // Uncertainty, Background - Uncertainty, Anomalous Signal
  // histograms to output ROOT file:
  std::cout<<"Save Histograms..."<<std::endl;
  f.cd();
  signal_lt0_80->Write();
  signal_lt0_50->Write();
  signal_lt0_30->Write();
  signal_lt0_m30->Write();
  signal_lt0_m50->Write();
  signal_lt0_m80->Write();

  bin_1->Write();
  bin_2->Write();
  bin_3->Write();
  bin_4->Write();
  bin_5->Write();
  bin_6->Write();
  bin_7->Write();
  bin_8->Write();
  bin_9->Write();
  bin_10->Write();

  p0->Write();
  p1->Write();
  test->Write();
  test2->Write();
  test_r->Write();
  test2_r->Write();

  signal_lt0_m28->Write();
  signal_lt0_m26->Write();
  signal_lt0_m24->Write();
  signal_lt0_m22->Write();
  signal_lt0_m20->Write();
  signal_lt0_m18->Write();
  signal_lt0_m32->Write();
  signal_lt0_m34->Write();
  signal_lt0_m36->Write();
  signal_lt0_m38->Write();

  signal_lt0_28->Write();
  signal_lt0_26->Write();
  signal_lt0_24->Write();
  signal_lt0_22->Write();
  signal_lt0_20->Write();
  signal_lt0_18->Write();
  signal_lt0_32->Write();
  signal_lt0_34->Write();
  signal_lt0_36->Write();
  signal_lt0_38->Write();

  //For conveners
//  th1wwa->Write();

  //
}// End Main function
void EMCDistribution(TString gain = "CALIB", bool log_scale = false)
{
  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      "EMCDistribution_" + gain + TString(log_scale ? "_Log" : "") + cuts, 1800,
      1000);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(log_scale ? "_Log" : "");

      TH1 *h = NULL;

      if (log_scale)
        h = new TH1F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 300,
                     5e-3, 3096);
      else
        //            h = new TH1F(hname,
        //                Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 196,
        //                1900, 2096);
        h = new TH1F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 596,
                     -96, 500);

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);
      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      if (log_scale)
        QAHistManagerDef::useLogBins(h->GetXaxis());

      T->Draw(
          "TOWER_" + gain + "_CEMC[].get_energy_power_law_exp()>>" + hname,
          Form(
              "TOWER_%s_CEMC[].get_bineta()==%d && TOWER_%s_CEMC[].get_binphi()==%d",
              gain.Data(), ieta, gain.Data(), iphi),
          "");

      TText *t = new TText(.9, .9, Form("Col%d Row%d", ieta, iphi));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();

      //          return;
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype4EMCalTower_") + TString(c1->GetName()), false);
}
Exemplo n.º 24
0
void calculateTriggerRates(
         TString inFile0Name = "root://eoscms//eos/cms/store/caf/user/velicanu/PA2013_merged_HiForest/pPb_hiForest2_1_15_test.root",
//         TString inFile0Name = "/castor/cern.ch/user/m/miheejo/openHLT/cms442/r181530_reco_v1_2/HIExpressPhysics_hiexp-hirun2011-r181530-reco-v1_2.root",
//         "/castor/cern.ch/user/k/kimy/openHLT//openhlt_run181531.root",
//         "/castor/cern.ch/user/v/velicanu/HIHLT_Validation_Test_GRIF_v10.root",
			   Int_t runNum        = 202792,
 			   TString outdir      = "output",
			   char *projectTitle  = "HIpARun2013",
			   string source       = "data"
			   )
{
  char szBuf[256];
  int scale = 23;


  // event selectoin
  //Form("&&Run==%d&&LumiBlock>%d",runNum,goodLumiStart)
  // trigger under investigation
 //  const int ntrigs = 8;
//   const char* triggerPath[ntrigs] = {"","HLT_HIMinBiasHfOrBSC",
// 				     "L1_SingleMu3_BptxAND","HLT_HIL1SingleMu3","HLT_HIL2Mu3",
// 				     "L1_DoubleMuOpen_BptxAND","HLT_HIL1DoubleMuOpen","HLT_HIL2DoubleMu3"};

  const int ntrigs = 9;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAL1SingleMuOpen_v1",
    "HLT_PAL1SingleMu3_v1",
    "HLT_PAL1SingleMu7_v1",
    "HLT_PAL1SingleMu12_v1",
    "HLT_PAL1DoubleMu0_v1",
    "HLT_PADimuon0_NoVertexing_v1",
    "HLT_PAMu5_v1",
    "HLT_PAMu8_v1"
  };
  
  TString str;
  TH1D *ahTemp[ntrigs];
  double ahTempRate[ntrigs];  //Rates (Integrated over lumisections)
  // Load input
  TChain * HltTree = new TChain("hltanalysis/HltTree","HI OpenHLT Tree");
  HltTree->Add(inFile0Name);
  cout << inFile0Name << endl;
  cout << " # entries: " << HltTree->GetEntries() << endl;
  int nEvents = HltTree->GetEntries();
  for(int it=1; it<ntrigs; it++)
  {
    
    TH1D *ph  = new TH1D("ph","",1100,0,1100);
    HltTree->Draw("LumiBlock>>ph",str.Format("%s",triggerPath[it]));

    TH1D *phLumi = (TH1D*)gDirectory->Get("ph");
    phLumi->SetDirectory(0);
    phLumi->Scale(1./(phLumi->GetBinWidth(1)*23));// 1lumi unit=23 sec
    ahTempRate[it] = phLumi->Integral()/phLumi->GetNbinsX();
    ahTemp[it] = phLumi;

    cout<< triggerPath[it]<<"\t"<<phLumi->GetEntries()<< "\t" << ahTempRate[it] << endl;
   
  }
     
  //----------------------------
  // drawing part
  // axis
  //  TH1D * phLumiAxis = new TH1D("phLumiAxis",";Lumi Section;dEvt/dLumiSec",1100,0,1100);
  TH1D * phLumiAxis = new TH1D("phLumiAxis",";Lumi Section;Rate [Hz]",1,0,1200);
  phLumiAxis->SetMinimum(0.01);
  phLumiAxis->SetMaximum(1e+3);
  gStyle->SetOptStat(kFALSE);

  // legend
  TLegend *l0= new TLegend(0.2,0.4,0.8,0.9);
  l0->SetHeader(str.Format("HICorePhysics_L1DoubleMuOpen: %d",nEvents));
  l0->SetMargin(0.1);
  l0->SetFillStyle(0);
  l0->SetLineColor(0);
  l0->SetLineWidth(5.0);
  l0->SetTextSize(0.03); 

  // canvas
  TCanvas *pcLumi = new TCanvas("pcLumi","pcLumi");
  pcLumi->cd();
  phLumiAxis->Draw();
  pcLumi->SetLogy();
 
  for(int it=1; it<ntrigs; it++)
    {
      TH1 *phLocal = (TH1 *)(ahTemp[it]->Clone("phLocal"));
      phLocal->SetDirectory(0); 
      phLocal->SetLineColor(it);
      if (it >= 10) phLocal->SetLineColor(it+20);
      if(it==5)	phLocal->SetLineColor(kOrange+2);
      phLocal->Draw("same");

      l0->AddEntry(phLocal,str.Format("%s: %.2f%, %.2f Hz",triggerPath[it],100*phLocal->GetEntries()/nEvents,ahTempRate[it]),"l");;
     
      pcLumi->Update();
     
    }
  l0->Draw("same");
  pcLumi->SaveAs("TrigRate.pdf");
}
void EMCDistribution_SUM_RawADC(TString sTOWER = "Energy_Sum_col1_row2_5x5",
                                TString CherenkovSignal = "C2_Inner")
{
  TH1 *EnergySum_LG_full = new TH1F("EnergySum_LG_full",
                                    ";Tower Energy Sum (ADC);Count / bin", 210, -1000, 20000);
  TH1 *EnergySum_LG = new TH1F("EnergySum_LG",
                               ";Tower Energy Sum (ADC);Count / bin", 210, -1000, 20000);
  //  TH1 * EnergySum_HG = new TH1F("EnergySum_HG",
  //      ";Low range Tower Energy Sum (ADC);Count / bin", 50, 0, 500);

  TH1 *C2_Inner_full = new TH1F("C2_Inner_full",
                                CherenkovSignal + ";Cherenkov Signal (ADC);Count / bin", 180, -1000, 17000);
  TH1 *C2_Inner = new TH1F("C2_Inner",
                           CherenkovSignal + ";Cherenkov Inner Signal (ADC);Count / bin", 180, -1000,
                           17000);

  EnergySum_LG_full->SetLineColor(kBlue + 3);
  EnergySum_LG_full->SetLineWidth(2);

  EnergySum_LG->SetLineColor(kGreen + 3);
  EnergySum_LG->SetLineWidth(3);
  EnergySum_LG->SetMarkerColor(kGreen + 3);

  C2_Inner_full->SetLineColor(kBlue + 3);
  C2_Inner_full->SetLineWidth(2);

  C2_Inner->SetLineColor(kGreen + 3);
  C2_Inner->SetLineWidth(3);
  C2_Inner->SetMarkerColor(kGreen + 3);

  TCut c2 = CherenkovSignal + ">2000";

  T->Draw(sTOWER + ">>EnergySum_LG_full", "", "goff");
  T->Draw(sTOWER + ">>EnergySum_LG", c2, "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner_full", "", "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner", c2, "goff");

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts,
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts, 1800,
      600);
  c1->Divide(3, 1);
  int idx = 1;
  TPad *p;

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  C2_Inner_full->DrawClone();
  C2_Inner->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h = (TH1 *) EnergySum_LG_full->DrawClone();
  //  h->GetXaxis()->SetRangeUser(-1, h->GetMean() + 5 * h->GetRMS());
  (TH1 *) EnergySum_LG->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h_full = (TH1 *) EnergySum_LG_full->DrawClone();
  //  h_full->GetXaxis()->SetRangeUser(0.5,32);
  TH1 *h = (TH1 *) EnergySum_LG->DrawClone("same");

  TF1 *fgaus_g = new TF1("fgaus_LG_g", "gaus", h->GetMean() - 1 * h->GetRMS(),
                         h->GetMean() + 4 * h->GetRMS());
  fgaus_g->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
                         h->GetMean() + 2 * h->GetRMS());
  h->Fit(fgaus_g, "MR0N");

  TF1 *fgaus = new TF1("fgaus_LG", "gaus",
                       fgaus_g->GetParameter(1) - 1 * fgaus_g->GetParameter(2),
                       fgaus_g->GetParameter(1) + 4 * fgaus_g->GetParameter(2));
  fgaus->SetParameters(fgaus_g->GetParameter(0), fgaus_g->GetParameter(1),
                       fgaus_g->GetParameter(2));
  h->Fit(fgaus, "MR");

  h->Sumw2();
  h_full->Sumw2();
  h_full->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
                                   h->GetMean() + 4 * h->GetRMS());
  h_full->GetYaxis()->SetRangeUser(0,
                                   fgaus_g->GetParameter(0) * 4);

  h->SetLineWidth(2);
  h->SetMarkerStyle(kFullCircle);

  h_full->SetTitle(
      Form("#DeltaE/<E> = %.1f%%",
           100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //  h->SetLineWidth(2);
  //  h->SetLineColor(kBlue + 3);
  ////  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  //
  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  ////  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //
  //  TF1 * fgaus = new TF1("fgaus_HG", "gaus", 0, 100);
  //  fgaus->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
  //      h->GetMean() + 2 * h->GetRMS());
  //  h->Fit(fgaus, "M");
  //
  //  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
  //      h->GetMean() + 4 * h->GetRMS());
  //
  //  h->SetLineWidth(2);
  //  h->SetMarkerStyle(kFullCircle);
  //
  //  h->SetTitle(
  //      Form("#DeltaE/<E> = %.1f%%",
  //          100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype4EMCalTower_") + TString(c1->GetName()), false);
}
Exemplo n.º 26
0
static PyObject *
fill_hist_with_ndarray(PyObject *self, PyObject *args, PyObject* keywords) {

    using namespace std;
    PyObject *hist_ = NULL;
    PyObject *array_ = NULL;
    PyObject *weights_ = NULL;
    PyArrayObject *array = NULL;
    PyArrayObject *weights = NULL;
    TH1* hist = NULL;
    TH2* hist2d = NULL;
    TH3* hist3d = NULL;
    unsigned int dim = 1;
    unsigned int array_depth = 1;
    unsigned int i, n, k;
    char *array_data;
    char *weights_data = NULL;
    npy_intp array_stride_n;
    npy_intp array_stride_k = 1;
    npy_intp weights_stride = 1;
    static const char* keywordslist[] = {
        "hist",
        "array",
        "weights",
        NULL};

    if(!PyArg_ParseTupleAndKeywords(
                args, keywords, "OO|O",
                const_cast<char **>(keywordslist),
                &hist_, &array_, &weights_)) {
        return NULL;
    }

    if(!PyCObject_Check(hist_)) {
        PyErr_SetString(PyExc_TypeError,"Unable to convert hist to PyCObject");
        return NULL;
    }
    //this is not safe so be sure to know what you are doing type check in python first
    //this is a c++ limitation because void* have no vtable so dynamic cast doesn't work
    hist = static_cast<TH1*>(PyCObject_AsVoidPtr(hist_));
    if (hist == NULL) {
        PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH1*");
        return NULL;
    }
    dim = hist->GetDimension();

    if (dim == 2) {
        hist2d = static_cast<TH2*>(PyCObject_AsVoidPtr(hist_));
        if (hist2d == NULL) {
            PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH2*");
            return NULL;
        }
    } else if (dim == 3) {
        hist3d = static_cast<TH3*>(PyCObject_AsVoidPtr(hist_));
        if (hist3d == NULL) {
            PyErr_SetString(PyExc_TypeError,"Unable to convert hist to TH3*");
            return NULL;
        }
    } else if (dim > 3) {
        PyErr_SetString(PyExc_ValueError,"dim must not be greater than 3");
        return NULL;
    }

    if (dim > 1)
        array_depth = 2;

    array = (PyArrayObject *) PyArray_ContiguousFromAny(
            array_, PyArray_DOUBLE, array_depth, array_depth);
    if (array == NULL) {
        PyErr_SetString(PyExc_TypeError,
                "Unable to convert object to array");
        return NULL;
    }

    if (dim > 1) {
        k = array->dimensions[1];
        if (k != dim) {
            PyErr_SetString(PyExc_ValueError,
                "length of the second dimension must equal the dimension of the histogram");
            Py_DECREF(array);
            return NULL;
        }
        array_stride_k = array->strides[1];
    }

    n = array->dimensions[0];
    array_stride_n = array->strides[0];
    array_data = array->data;

    if (weights_) {
        weights = (PyArrayObject *) PyArray_ContiguousFromAny(
                weights_, PyArray_DOUBLE, 1, 1);
        if (weights == NULL) {
            PyErr_SetString(PyExc_TypeError,
                    "Unable to convert object to array");
            Py_DECREF(array);
            return NULL;
        }
        if (n != weights->dimensions[0]) {
            PyErr_SetString(PyExc_ValueError,
                    "array and weights must have the same length");
            Py_DECREF(weights);
            Py_DECREF(array);
            return NULL;
        }
        weights_data = weights->data;
        weights_stride = weights->strides[0];
    }

    if (dim == 1) {
        // weighted fill
        if (weights) {
            for (i = 0; i < n; ++i) {
                hist->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(weights_data + i * weights_stride));
            }
        } else {
            // unweighted fill
            for (i = 0; i < n; ++i) {
                hist->Fill(*(double *)(array_data + i * array_stride_n));
            }
        }
    } else if (dim == 2) {
        // weighted fill
        if (weights) {
            for (i = 0; i < n; ++i) {
                hist2d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k),
                        *(double *)(weights_data + i * weights_stride));
            }
        } else {
            // unweighted fill
            for (i = 0; i < n; ++i) {
                hist2d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k));
            }
        }
    } else if (dim == 3) {
        // weighted fill
        if (weights) {
            for (i = 0; i < n; ++i) {
                hist3d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k),
                        *(double *)(array_data + i * array_stride_n + 2 * array_stride_k),
                        *(double *)(weights_data + i * weights_stride));
            }
        } else {
            // unweighted fill
            for (i = 0; i < n; ++i) {
                hist3d->Fill(
                        *(double *)(array_data + i * array_stride_n),
                        *(double *)(array_data + i * array_stride_n + array_stride_k),
                        *(double *)(array_data + i * array_stride_n + 2 * array_stride_k));
            }
        }
    }
    if (weights)
        Py_DECREF(weights);
    Py_DECREF(array);
    Py_RETURN_NONE;
}
Exemplo n.º 27
0
void Opt_ntuple_midmass_200(){

  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetHistLineWidth(2);
  gStyle->SetPalette(1);
  gStyle->SetOptStat(1111);

  TChain * f_chain = new TChain("MyTree");
  f_chain->Add("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_SKnonprompt_dilep_5_3_14.root");
  f_chain->LoadTree(0) ;
  
  TChain * f_chainmc = new TChain("MyTree");
  f_chainmc->Add("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_mc_5_3_14.root");
  f_chainmc->LoadTree(0) ;

  TChain * f_chainsig = new TChain("MyTree");
  f_chainsig->Add("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_SKHNee200_nocut_5_3_14.root");
  TFile * file = new TFile("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_SKHNee200_nocut_5_3_14.root");
  cout << file << endl;
  float  k_met=0., k_eemass=0., k_eejjmass=0., k_e1jjmass=0., k_e2jjmass=0.,  k_st=0., k_ht;
  float k_weight=0.;
  int k_njet;
  float k_el1pt=0., k_el2pt=0., k_j1pt=0., k_jjmass=0.;
  
  f_chain->SetBranchAddress("met", &k_met);
  f_chain->SetBranchAddress("ee_mass", &k_eemass);
  f_chain->SetBranchAddress("eejj_mass", &k_eejjmass);
  f_chain->SetBranchAddress("e1jj_mass", &k_e1jjmass);
  f_chain->SetBranchAddress("e2jj_mass", &k_e2jjmass);
  f_chain->SetBranchAddress("jj_mass", &k_jjmass);
  f_chain->SetBranchAddress("st", &k_st);
  f_chain->SetBranchAddress("ht", &k_ht);
  f_chain->SetBranchAddress("njet", &k_njet);
  f_chain->SetBranchAddress("el1_pt", &k_el1pt);
  f_chain->SetBranchAddress("el2_pt", &k_el2pt);
  f_chain->SetBranchAddress("jet1_pt", &k_j1pt);
  f_chain->SetBranchAddress("weight", &k_weight);
  
  f_chainmc->SetBranchAddress("met", &k_met);
  f_chainmc->SetBranchAddress("ee_mass", &k_eemass);
  f_chainmc->SetBranchAddress("eejj_mass", &k_eejjmass);
  f_chainmc->SetBranchAddress("e1jj_mass", &k_e1jjmass);
  f_chainmc->SetBranchAddress("e2jj_mass", &k_e2jjmass);
  f_chainmc->SetBranchAddress("jj_mass", &k_jjmass);
  f_chainmc->SetBranchAddress("st", &k_st);
  f_chainmc->SetBranchAddress("ht", &k_ht);
  f_chainmc->SetBranchAddress("njet", &k_njet);
  f_chainmc->SetBranchAddress("el1_pt", &k_el1pt);
  f_chainmc->SetBranchAddress("el2_pt", &k_el2pt);
  f_chainmc->SetBranchAddress("jet1_pt", &k_j1pt);
  f_chainmc->SetBranchAddress("weight", &k_weight);

  f_chainsig->SetBranchAddress("met", &k_met);
  f_chainsig->SetBranchAddress("ee_mass", &k_eemass);
  f_chainsig->SetBranchAddress("eejj_mass", &k_eejjmass);
  f_chainsig->SetBranchAddress("e1jj_mass", &k_e1jjmass);
  f_chainsig->SetBranchAddress("e2jj_mass", &k_e2jjmass);
  f_chainsig->SetBranchAddress("jj_mass", &k_jjmass);
  f_chainsig->SetBranchAddress("st", &k_st);
  f_chainsig->SetBranchAddress("ht", &k_ht);
  f_chainsig->SetBranchAddress("njet", &k_njet);
  f_chainsig->SetBranchAddress("el1_pt", &k_el1pt);
  f_chainsig->SetBranchAddress("el2_pt", &k_el2pt);
  f_chainsig->SetBranchAddress("jet1_pt", &k_j1pt);
  f_chainsig->SetBranchAddress("weight", &k_weight);



  float sum_event =0.;
  for(Int_t i = 0; i < f_chain->GetEntries(); i++){
    f_chain->GetEntry(i) ;
    
    if( (i % 100000) == 0) cout << "Bkg: N processing = " << i << endl;
    sum_event+= k_weight;
  }
  
  for(Int_t i = 0; i < f_chainmc->GetEntries(); i++){
    f_chainmc->GetEntry(i) ;

    if( (i % 100000) == 0) cout << "Bkg: N processing = " << i << endl;
    sum_event+= k_weight;
  }

  
  float sum_sigevent =0.;
  for(Int_t i = 0; i < f_chainsig->GetEntries(); i++){
    f_chainsig->GetEntry(i) ;

    if( (i % 100000) == 0) cout << "Sig: N processing = " << i << endl;
    sum_sigevent+=k_weight;
  }

  cout << "Total bkg = " << sum_event  << endl;
  cout << "Total sig = " <<  sum_sigevent << endl;
  

  std::vector<float> METcut;
  METcut.push_back(35.);
  
  int imet_opt=0;
  float imeejjmin_opt=0.;
  float imeejjmax_opt=0.;
  float ipt1_opt=0.;
  float ipt2_opt=0.;
  float sig_eff_opt=0.;
  float sig_eff_opt_presel=0.;
  float cut_sum_opt=0.;
  float opt_cut_sb=0.;
  float ieemin_opt=0.;
  float ieemax_opt=0.;
  float ie2jjmin_opt=0.;
  float ie2jjmax_opt=0.;
  float ie1jjmin_opt=0.;
  float ie1jjmax_opt=0.;
  float istmin_opt=0.;
  float istmax_opt=0.;
  float ihtmin_opt=0.;
  float ihtmax_opt=0.;
  float ijetpt_opt=0.;
  int injet_opt=0.;

  TH1* hnsig =   (TH1F*)file->Get(("eventcutflow"));

  float nsig = float(hnsig->GetBinContent(2));
  cout << "Number of signal events before any cut = " << nsig << endl; 

  for(unsigned int imet=0; imet < METcut.size(); imet++){
    float met_cut = METcut.at(imet);
    cout << "MET : "<< met_cut << endl;
    for(int imeejjmin= 20; imeejjmin < 27. ; imeejjmin++){
      float meejjmin_cut = float(imeejjmin) * 10.;
      for(int imeejjmax= 0; imeejjmax <1. ; imeejjmax++){
	float meejjmax_cut = 10000.+ float(imeejjmax)*20.;
	cout << meejjmin_cut <<   "  < M(eejj) < "<< meejjmax_cut << endl;
	for(int ipt1= 9; ipt1 < 10. ; ipt1++){
	  float pt1_cut =  20. + float(ipt1)*5.;
	  for(int ipt2= 0; ipt2 < 1. ; ipt2++){
	    float pt2_cut =  15. + float(ipt2)*5.;
	    if(pt2_cut > pt1_cut) continue;
	    cout << "pt1_cut = " << pt1_cut << " pt2_cut = " << pt2_cut << endl;
	    for(int ieemin =0 ; ieemin < 6 ; ieemin++){
	      float eemin_cut =  10. + float(ieemin)* 5.;
	      if(ieemin == 5) eemin_cut = 100.;
	      
	      for(int ieemax =0 ; ieemax <1 ; ieemax++){
		float eemax_cut =  100000.;
		for(int ie1jjmin =8 ; ie1jjmin < 9 ; ie1jjmin++){
                  float e1jjmin_cut = 0. + float(ie1jjmin)* 10.;

                  for(int ie1jjmax =0 ; ie1jjmax < 1 ; ie1jjmax++){
                    float e1jjmax_cut =  10000. + float(ie1jjmax)* 20.;

		    for(int ie2jjmin =0 ; ie2jjmin < 2 ; ie2jjmin++){
		      float e2jjmin_cut = 120. + float(ie2jjmin)* 10.;
		      
		      for(int ie2jjmax =0 ; ie2jjmax < 15 ; ie2jjmax++){
			float e2jjmax_cut =  200. + float(ie2jjmax)* 10.;
			if(ie2jjmax == 9) e2jjmax_cut = 10000.;
			
			for(int ihtmin =0 ; ihtmin < 1 ; ihtmin++){
			  float htmin_cut = 50. + float(ihtmin)*5.;
			  for(int ihtmax =16 ; ihtmax < 17 ; ihtmax++){
			    float htmax_cut =10000. + float(ihtmax)*25.;
			    for(int istmin =0 ; istmin < 1 ; istmin++){
			      float stmin_cut = float(istmin)*10.;  
			      for(int istmax =45 ; istmax < 46 ; istmax++){
				float stmax_cut = 10000. + float(istmax) *10.;
				
				for(int ijpt =2 ; ijpt <3 ; ijpt++){
				  float jetpt_cut = 20. + float(ijpt)*5.;
				  
				  for(int injet = 14 ; injet< 15 ; injet ++){
				    
				    /// Optmise cuts:
				    float cut_sum=0.;
				    float np_sum=0.;
				    for(Int_t i = 0; i < f_chain->GetEntries(); i++){
				      f_chain->GetEntry(i) ;
				      if(k_eemass > 80. && k_eemass < 100) continue;
				      if(k_jjmass > 110.) continue;
				      if(k_jjmass < 50.) continue;
				      if(k_e1jjmass < e1jjmin_cut) continue;
				      if(k_e1jjmass > e1jjmax_cut) continue;
				      if(k_e2jjmass < e2jjmin_cut) continue;
                                      if(k_e2jjmass > e2jjmax_cut) continue;
				      if(k_eemass < eemin_cut) continue;
				      if(k_eemass > eemax_cut) continue;
				      if(k_met > met_cut) continue;
				      if(k_eejjmass < meejjmin_cut) continue;
				      if(k_eejjmass > meejjmax_cut) continue;
				      if(k_st <  stmin_cut) continue;
				      if(k_st >  stmax_cut) continue;
				      if(k_ht <  htmin_cut) continue;
                                      if(k_ht >  htmax_cut) continue;
				      if(k_j1pt < jetpt_cut) continue;
				      if(k_el1pt < pt1_cut) continue;
				      if(k_el2pt < pt2_cut) continue;
				      if(k_njet> injet) continue;
				      cut_sum+=k_weight;
				      np_sum+=k_weight;
				    }
				    
				    for(Int_t i = 0; i < f_chainmc->GetEntries(); i++){
				      f_chainmc->GetEntry(i) ;
				      if(k_jjmass > 110.) continue;
				      if(k_jjmass < 50.) continue;
				      if(k_eemass > 80. && k_eemass < 100) continue;
				      if(k_eemass < eemin_cut) continue;
				      if(k_eemass > eemax_cut) continue;
				      if(k_e1jjmass < e1jjmin_cut) continue;
                                      if(k_e1jjmass > e1jjmax_cut) continue;
				      if(k_e2jjmass < e2jjmin_cut) continue;
				      if(k_e2jjmass > e2jjmax_cut) continue;
				      if(k_met > met_cut) continue;
				      if(k_eejjmass < meejjmin_cut) continue;
				      if(k_eejjmass > meejjmax_cut) continue;
				      if(k_st <  stmin_cut) continue;
				      if(k_st >  stmax_cut) continue;
				      if(k_ht <  htmin_cut) continue;
                                      if(k_ht >  htmax_cut) continue;
				      if(k_j1pt < jetpt_cut) continue;
				      if(k_el1pt < pt1_cut) continue;
				      if(k_el2pt < pt2_cut) continue;
				      if(k_njet> injet) continue;
				      cut_sum+=k_weight;
				    }
				    
				    float cut_sum_sig=0.;
				    for(Int_t i = 0; i < f_chainsig->GetEntries(); i++){
				      f_chainsig->GetEntry(i) ;
				      if(k_eemass > 80. && k_eemass < 100) continue;
				      if(k_jjmass > 110.) continue;
				      if(k_jjmass < 50.) continue;
				      if(k_e1jjmass < e1jjmin_cut) continue;
				      if(k_e1jjmass > e1jjmax_cut) continue;
				      if(k_e2jjmass < e2jjmin_cut) continue;
                                      if(k_e2jjmass > e2jjmax_cut) continue;
				      if(k_eemass < eemin_cut) continue;
				      if(k_eemass > eemax_cut) continue;
				      if(k_met > met_cut)continue;
				      if(k_eejjmass < meejjmin_cut) continue;
				      if(k_eejjmass > meejjmax_cut) continue;
				      if(k_st <  stmin_cut) continue;
				      if(k_st >  stmax_cut) continue;
				      if(k_ht <  htmin_cut) continue;
                                      if(k_ht >  htmax_cut) continue;
				      if(k_j1pt < jetpt_cut) continue;
				      if(k_el1pt < pt1_cut) continue;
				      if(k_el2pt < pt2_cut) continue;
				      if(k_njet> injet) continue;
				      cut_sum_sig+=k_weight;
				    }
				    
				    float sig_eff = cut_sum_sig /nsig ;
				    float total_bkg = cut_sum;
				    float bkgtmp = total_bkg + (0.28* np_sum)* (0.28* np_sum);
				    float denom = 1. + sqrt(bkgtmp);
				    float punzi = sig_eff / denom;
				    if( (punzi) > opt_cut_sb){
				      opt_cut_sb = punzi;
				      imet_opt = imet;
				      injet_opt = injet;
				      imeejjmin_opt = meejjmin_cut;
				      imeejjmax_opt = meejjmax_cut;
				      ipt1_opt=  pt1_cut;
				      ipt2_opt=  pt2_cut;
				      ieemin_opt =  eemin_cut;
				      ieemax_opt =  eemax_cut;
				      ie1jjmin_opt = e1jjmin_cut;
				      ie1jjmax_opt = e1jjmax_cut;
				      ie2jjmin_opt = e2jjmin_cut;
                                      ie2jjmax_opt = e2jjmax_cut;
				      istmin_opt = stmin_cut;
				      istmax_opt = stmax_cut;
				      ihtmin_opt = htmin_cut;
                                      ihtmax_opt = htmax_cut;
				      ijetpt_opt = jetpt_cut;
				      sig_eff_opt = sig_eff;
				      
				      sig_eff_opt_presel = cut_sum_sig / sum_sigevent;
				      cut_sum_opt= cut_sum;
				      cout << "Max punzi = " << punzi << " : nbkg = " << total_bkg <<  " : %sig = " << sig_eff_opt_presel*100. << endl;
				      
				    }
				  }
				  
				}//jetpt
			      }
			    }
			  }
			}
		      }//stmax
		    }//stmin
		  }//e2jjmax
		}//eemax
	      }//eemin
	    }//pt2
	  }//pt1
	}// meejjmax
      }/// meejjmin
    }/// MET 
  }
  //Opt cut
  cout << "Opt punzi = " << opt_cut_sb << endl;
  cout << "Opt cut : MET <  " << METcut.at(imet_opt) << endl;
  cout << "Opt cut : njet <  " << injet_opt<< endl;
  cout << "Opt cut : " << imeejjmin_opt << " < M(eejj) <  " << imeejjmax_opt << endl;
  cout << "Opt cut : " << ie1jjmin_opt << " < M(e1jj) <  " << ie1jjmax_opt << endl;
  cout << "Opt cut : " << ie2jjmin_opt << " < M(e2jj) <  " << ie2jjmax_opt << endl;
  cout << "Opt cut : " << ieemin_opt << " < M(ee) < " << ieemax_opt<< endl;
  cout << "Opt cut : " << istmin_opt << " < ST < " << istmax_opt<< endl;
  cout << "Opt cut : " << ihtmin_opt << " < HT < " << ihtmax_opt<< endl;
  

  cout << "Opt pt1 = " << ipt1_opt << endl;
  cout << "Opt pt2 = " << ipt2_opt << endl;
  cout << "Opt jet1pt = " << ijetpt_opt << endl;
  cout << "Cut (opt) eff. bkg = " << cut_sum_opt/sum_event  <<  " nbkg = " << cut_sum_opt << endl;
  cout << "Cut eff .sig = " <<  sig_eff_opt << " : wrt preselection "<< sig_eff_opt_presel*100 <<  endl;
  
  
}
Exemplo n.º 28
0
int main(int argc, char* argv[]) {

  TFile* dataFile=TFile::Open("pu_truth_data2015_50bins.root"); 
  TFile* mcFile = TFile::Open("computed_mc_GJET_plus_QCD_pu_truth_50bins.root");

  TH1* dataHisto = static_cast<TH1*>(dataFile->Get("pileup"));
  TH1* mcHisto = static_cast<TH1*>(mcFile->Get("pileup"));

  TFile f1("/cmshome/fpreiato/GammaJet/CMSSW_7_4_14/src/JetMETCorrections/GammaJetFilter/analysis/tuples/GJET_MC/PhotonJet_2ndLevel_GJet_Pt-15To6000_TuneCUETP8M1-Flat_13TeV_pythia8_25ns_ReReco.root");                                       
  TTree* AnalysisTree_mc = (TTree*) f1.Get("gammaJet/analysis");                                                        
  uint64_t totalEvents_mc = AnalysisTree_mc->GetEntries();  

  
    ///////////////////////////////////////////////////////////////////

    // Normalize
    dataHisto->Scale(1.0 / dataHisto->Integral());
    mcHisto->Scale(1.0 / mcHisto->Integral());
    
    TCanvas *c1 = new TCanvas("c1","c1",800,800);
    dataHisto-> SetLineColor(kBlue);
    mcHisto -> SetLineColor(kRed);
    dataHisto -> Draw();
    mcHisto -> Draw("same");
    c1-> SaveAs("Plot/pileup_truth.png");
    //   c1-> SaveAs("pileup_truth.root");
        
    // MC * data / MC = data, so the weights are data/MC:
    TH1* ratioHisto = static_cast<TH1*>(dataHisto->Clone());
    ratioHisto->Divide(mcHisto);

    int NBins = ratioHisto->GetNbinsX();

    for (int ibin = 1; ibin < NBins + 1; ++ibin) {
      std::cout << "   " << ibin - 1 << " " << ratioHisto->GetBinContent(ibin) << std::endl;
    }
        
    TCanvas *c2 = new TCanvas("c2","c2",800,800);
    ratioHisto -> Draw();
    c2-> SaveAs("Plot/ratioHisto.png");
    //    c2-> SaveAs("ratioHisto.root");
    
    TH1D* mcHisto_reweighted = new TH1D("mcHisto_reweighted", "mc Reweighted", 50, 0, 50);
    
    for (uint64_t i = 0; i < totalEvents_mc; i++) {      
      if(i == 0 || i % 5000 == 0) cout<< "Events processed "<< i <<endl;
      AnalysisTree_mc->GetEntry(i);
      Float_t interaction;
      AnalysisTree_mc->SetBranchAddress("ntrue_interactions", &interaction);
      //cout<< ptPhot << endl;
      
	int bin = ratioHisto ->GetXaxis()-> FindBin(interaction);
	float PUweight = ratioHisto -> GetBinContent(bin);
	
	double generator_weight;
	AnalysisTree_mc->SetBranchAddress("generator_weight", &generator_weight);   
	if(generator_weight == 0) generator_weight = 1;
	float event_weight;
	AnalysisTree_mc->SetBranchAddress("evtWeightTot", &event_weight);   
	
	double Weight = PUweight* generator_weight * event_weight;
	
	//      cout<< "nvertex "<< nvertex_mc<<endl;
	//      cout<< "PUWeight "<< PUweight<<endl;	
	mcHisto_reweighted -> Fill(interaction, Weight);     
    }
    
    mcHisto_reweighted ->Scale(1.0 / mcHisto_reweighted->Integral());
    
    TCanvas *c3 = new TCanvas("c3","c3",800,800);
    dataHisto -> SetLineColor(kBlue);
    mcHisto_reweighted -> SetLineColor(kRed);
    dataHisto -> Draw();
    mcHisto_reweighted -> Draw("same");
    c3-> SaveAs("Plot/Histo_reweighted.png");
    //    c3-> SaveAs("Histo_reweighted.root");


        
}//main
Exemplo n.º 29
0
TCanvas *trackSplitPlot(Int_t nFiles,TString *files,TString *names,TString xvar,TString yvar,
                     Bool_t relative = kFALSE,Bool_t logscale = kFALSE,Bool_t resolution = kFALSE,Bool_t pull = kFALSE,
                     TString saveas = "")
{
    cout << xvar << " " << yvar << endl;
    if (xvar == "" && yvar == "")
        return 0;

    PlotType type;
    if (xvar == "")      type = Histogram;
    else if (yvar == "") type = OrgHistogram;
    else if (resolution) type = Resolution;
    else if (nFiles < 1) type = ScatterPlot;
    else                 type = Profile;
    if (nFiles < 1) nFiles = 1;

    const Int_t n = nFiles;
    
    TStyle *tdrStyle = setTDRStyle();
    tdrStyle->SetOptStat(0);
    if ((type == Histogram || type == OrgHistogram) && nFiles == 1)
        tdrStyle->SetOptStat(1110);
    if (type == ScatterPlot || (type == Histogram && !pull) || xvar == "runNumber")
    {
        tdrStyle->SetCanvasDefW(678);
        tdrStyle->SetPadRightMargin(0.115);
    }

    Bool_t nHits = (xvar[0] == 'n' && xvar[1] == 'H' && xvar[2] == 'i'
                                   && xvar[3] == 't' && xvar[4] == 's');

    Int_t nBinsScatterPlotx = binsScatterPlotx;
    Int_t nBinsScatterPloty = binsScatterPloty;
    Int_t nBinsHistogram = binsHistogram;
    Int_t nBinsProfileResolution = binsProfileResolution;
    if (xvar == "runNumber")
    {
        nBinsProfileResolution = runNumberBins;
        nBinsHistogram = runNumberBins;
    }
    if (nHits)
    {
        nBinsHistogram = (int)(findMax(nFiles,files,xvar,'x') - findMin(nFiles,files,xvar,'x') + 1.1);     //in case it's .99999
        nBinsScatterPlotx = nBinsHistogram;
        nBinsProfileResolution = nBinsHistogram;
    }

    TH1 **p = new TH1*[n];
    Int_t lengths[n];

    stringstream sx,sy,srel,ssigma1,ssigma2,ssigmaorg;

    sx << xvar << "_org";
    TString xvariable = sx.str();
    TString xvariable2 = "";
    if (xvar == "runNumber") xvariable = "runNumber";
    if (nHits)
    {
        xvariable  = xvar;
        xvariable2 = xvar;
        xvariable.Append("1_spl");
        xvariable2.Append("2_spl");
    }

    sy << "Delta_" << yvar;
    TString yvariable = sy.str();

    TString relvariable = "1";
    if (relative)
    {
        srel << yvar << "_org";
        relvariable = srel.str();
    }

    TString sigma1variable = "",sigma2variable = "";
    if (pull)
    {
        ssigma1 << yvar << "1Err_spl";
        ssigma2 << yvar << "2Err_spl";
    }
    sigma1variable = ssigma1.str();
    sigma2variable = ssigma2.str();

    TString sigmaorgvariable = "";
    if (pull && relative)
        ssigmaorg << yvar << "Err_org";
    sigmaorgvariable = ssigmaorg.str();


    Double_t xmin = -1,xmax = 1,ymin = -1,ymax = 1;
    if (type == Profile || type == ScatterPlot || type == OrgHistogram || type == Resolution)
        axislimits(nFiles,files,xvar,'x',relative,pull,xmin,xmax);
    if (type == Profile || type == ScatterPlot || type == Histogram || type == Resolution)
        axislimits(nFiles,files,yvar,'y',relative,pull,ymin,ymax);

    TString meansrmss[n];

    for (Int_t i = 0; i < n; i++)
    {
        TFile *f = TFile::Open(files[i]);
        TTree *tree = (TTree*)f->Get("splitterTree");

        stringstream sid;
        sid << "p" << i;
        TString id = sid.str();

        TH1F **q = new TH1F*[nBinsProfileResolution];
        if (type == ScatterPlot)
            p[i] = new TH2F(id,"",nBinsScatterPlotx,xmin,xmax,nBinsScatterPloty,ymin,ymax);
        if (type == Histogram)
            p[i] = new TH1F(id,"",nBinsHistogram,ymin,ymax);
        if (type == OrgHistogram)
            p[i] = new TH1F(id,"",nBinsHistogram,xmin,xmax);
        if (type == Resolution || type == Profile)
        {
            p[i] = new TH1F(id,"",nBinsProfileResolution,xmin,xmax);
            for (Int_t j = 0; j < nBinsProfileResolution; j++)
            {
                stringstream sid2;
                sid2 << "q" << j;
                TString id2 = sid2.str();
                q[j] = new TH1F(id2,"",nBinsHistogram,ymin,ymax);
            }
        }
        p[i]->SetDirectory(0);

        lengths[i] = tree->GetEntries();

        if (files[i].Contains("MC") && xvar == "runNumber")
        {
            p[i]->SetLineColor(kWhite);
            p[i]->SetMarkerColor(kWhite);
            f->Close();
            continue;
        }

        Double_t x = 0, y = 0, rel = 1, sigma1 = 1, sigma2 = 1,           //if !pull, we want to divide by sqrt(2) because we want the error from 1 track
                                                  sigmaorg = 0;
        Int_t xint = 0, xint2 = 0;
        Int_t runNumber = 0;

        if (!relative && !pull && (yvar == "dz" || yvar == "dxy"))
            rel = 1e-4;                                     //it's in cm but we want it in um, so divide by 1e-4

        tree->SetBranchAddress("runNumber",&runNumber);
        if (type == Profile || type == ScatterPlot || type == Resolution || type == OrgHistogram)
        {
            if (xvar == "runNumber")
                tree->SetBranchAddress(xvariable,&xint);
            else if (nHits)
            {
                tree->SetBranchAddress(xvariable,&xint);
                tree->SetBranchAddress(xvariable2,&xint2);
            }
            else
                tree->SetBranchAddress(xvariable,&x);
        }
        if (type == Profile || type == ScatterPlot || type == Resolution || type == Histogram)
            tree->SetBranchAddress(yvariable,&y);
        if (relative && xvar != yvar)                       //if xvar == yvar, setting the branch here will undo setting it to x 2 lines earlier
            tree->SetBranchAddress(relvariable,&rel);
        if (pull)
        {
            tree->SetBranchAddress(sigma1variable,&sigma1);
            tree->SetBranchAddress(sigma2variable,&sigma2);
        }
        if (relative && pull)
            tree->SetBranchAddress(sigmaorgvariable,&sigmaorg);
   
        Int_t notincluded = 0;

        for (Int_t j = 0; j<lengths[i]; j++)
        {
            tree->GetEntry(j);
            if (xvar == "runNumber" || nHits)
                x = xint;
            if (xvar == "runNumber")
                runNumber = x;
            if (runNumber < minrun || (runNumber > maxrun && maxrun > 0)) 
            {
                notincluded++;
                continue;
            }
            if (relative && xvar == yvar)
            {
                rel = x;
            }
            Double_t error = 0;
            if (relative && pull)
                error = sqrt((sigma1/rel)*(sigma1/rel) + (sigma2/rel)*(sigma2/rel) + (sigmaorg*y/(rel*rel))*(sigmaorg*x/(rel*rel)));
            else
                error = sqrt(sigma1 * sigma1 + sigma2 * sigma2);   // = sqrt(2) if !pull, to get the error in 1 track
            y /= (rel * error);

            if (logscale)
                y = fabs(y);
            if (ymin <= y && y < ymax && xmin <= x && x < xmax)
            {
                if (type == Histogram)
                    p[i]->Fill(y);
                if (type == ScatterPlot)
                    p[i]->Fill(x,y);
                if (type == Resolution || type == Profile)
                {
                    int which = (p[i]->Fill(x,0)) - 1;
                    if (which >= 0) q[which]->Fill(y);         //get which q[j] by filling p[i] (with nothing), which returns the bin number
                }
                if (type == OrgHistogram)
                    p[i]->Fill(x);
            }

            if (nHits)
            {
                x = xint2;
                if (ymin <= y && y < ymax && xmin <= x && x < xmax)
                {
                    if (type == Histogram)
                        p[i]->Fill(y);
                    if (type == ScatterPlot)
                        p[i]->Fill(x,y);
                    if (type == Resolution || type == Profile)
                    {
                        int which = (p[i]->Fill(x,0)) - 1;
                        if (which >= 0) q[which]->Fill(y);         //get which q[j] by filling p[i] (with nothing), which returns the bin number
                    }
                    if (type == OrgHistogram)
                        p[i]->Fill(x);
                }
            }

            if (((j+1)/(int)(pow(10,(int)(log10(lengths[i]))-1)))*(int)(pow(10,(int)(log10(lengths[i]))-1)) == j + 1 || j + 1 == lengths[i])
            {
                cout << j + 1 << "/" << lengths[i] << ": "; 
                if (type == Profile || type == ScatterPlot || type == Resolution)
                    cout << x << ", " << y << endl;
                if (type == OrgHistogram)
                    cout << x << endl;
                if (type == Histogram)
                    cout << y << endl;
            }
        }
        lengths[i] -= notincluded;

        meansrmss[i] = "";
        if (type == Histogram || type == OrgHistogram)
        {
            cout << "Average = " << p[i]->GetMean() << endl;
            cout << "RMS     = " << p[i]->GetRMS()  << endl;
            stringstream meanrms;
            meanrms.precision(3);
            meanrms << "#mu=" << p[i]->GetMean() << ", #sigma=" << p[i]->GetRMS();
            meansrmss[i] = meanrms.str();
        }

        if (type == Resolution)
        {
            for (Int_t j = 0; j < nBinsProfileResolution; j++)
            {
                p[i]->SetBinContent(j+1,q[j]->GetRMS());
                p[i]->SetBinError  (j+1,q[j]->GetRMSError());
                delete q[j];
            }
        }

        if (type == Profile)
        {
            for (Int_t j = 0; j < nBinsProfileResolution; j++)
            {
                p[i]->SetBinContent(j+1,q[j]->GetMean());
                p[i]->SetBinError  (j+1,q[j]->GetMeanError());
                delete q[j];
            }
        }
        delete[] q;

        setAxisLabels(p[i],type,xvar,yvar,relative,pull);

        p[i]->SetLineColor(colors[i]);
        if (type == Resolution || type == Profile)
        {
            p[i]->SetMarkerColor(colors[i]);
            p[i]->SetMarkerStyle(20+i);
        }
        else
        {
            p[i]->SetMarkerStyle(1);
        }
        f->Close();
    }

    TCanvas *c1 = TCanvas::MakeDefCanvas();
    if (type == ScatterPlot || type == Profile || type == Resolution || type == OrgHistogram)
        c1->SetLogy((Bool_t)(logscale));
    if (type == Histogram)
        c1->SetLogx((Bool_t)(logscale));

    TH1 *maxp = p[0];
    TGraphErrors *g[n];
    TMultiGraph *list = new TMultiGraph();
    if (type == ScatterPlot)
        p[0]->Draw("COLZ");
    else if (type == Resolution || type == Profile)
    {
        for (Int_t i = 0; i < n; i++)
        {
            if (files[i].Contains("MC") && xvar == "runNumber")
                continue;
            g[i] = new TGraphErrors(p[i]);
            for (Int_t j = 0; j < g[i]->GetN(); j++)
            {
                if (g[i]->GetY()[j] == 0 && g[i]->GetEY()[j] == 0)
                {
                    g[i]->RemovePoint(j);
                    j--;
                }
            }
            list->Add(g[i]);
        }
        list->Draw("AP");
        Double_t yaxismax = list->GetYaxis()->GetXmax();
        Double_t yaxismin = list->GetYaxis()->GetXmin();
        if (yaxismin > 0)
        {
            yaxismax += yaxismin;
            yaxismin = 0;
        }
        p[0]->GetYaxis()->SetRangeUser(yaxismin,yaxismax);
        p[0]->Draw("P");
    }
    else if (type == Histogram || type == OrgHistogram)
    {
        Bool_t allthesame = true;
        for (Int_t i = 1; i < n && allthesame; i++)
        {
            if (lengths[i] != lengths[0])
                allthesame = false;
        }
        if (!allthesame && xvar != "runNumber")
            for (Int_t i = 0; i < n; i++)
            {
                p[i]->Scale(1.0/lengths[i]);
            }
        maxp = (TH1F*)p[0]->Clone("maxp");
        maxp->SetLineColor(kWhite);
        for (Int_t i = 1; i <= maxp->GetNbinsX(); i++)
        {
            for (Int_t j = 0; j < n; j++)
            {
                if (files[j].Contains("MC") && xvar == "runNumber")
                    continue;
                maxp->SetBinContent(i,TMath::Max(maxp->GetBinContent(i),p[j]->GetBinContent(i)));
            }
        }
        maxp->Draw();
        p[0]->Draw("same");
    }
    TLegend *legend = new TLegend(.6,.7,.9,.9,"","br");
    if (n == 1 && files[0].Contains("MC") && xvar == "runNumber")
    {
        placeholder(saveas,yvar == "");
        return 0;
    }
    if (n>=2)
    {
        if (!(files[0].Contains("MC") && xvar == "runNumber") && files[0] != "")
        {
            if (type == Resolution || type == Profile)
                legend->AddEntry(p[0],names[0],"pl");
            else if (type == Histogram || type == OrgHistogram)
            {
                legend->AddEntry(p[0],names[0],"l");
                legend->AddEntry((TObject*)0,meansrmss[0],"");
            }
        }
        for (Int_t i = 1; i < n; i++)
        {
            if (files[i].Contains("MC") && xvar == "runNumber")
                continue;
            if (type == Resolution || type == Profile)
            {
                p[i]->Draw("same P");
                legend->AddEntry(p[i],names[i],"pl");
            }
            else if (type == Histogram || type == OrgHistogram)
            {
                p[i]->Draw("same");
                legend->AddEntry(p[i],names[i],"l");
                legend->AddEntry((TObject*)0,meansrmss[i],"");
            }
        }

        if (legend->GetListOfPrimitives()->At(0) == 0)
        {
            delete legend;
            placeholder(saveas,yvar == "");
            return 0;
        }

        
        c1->Update();
        Double_t x1min  = .98*gPad->GetUxmin() + .02*gPad->GetUxmax();
        Double_t x2max  = .02*gPad->GetUxmin() + .98*gPad->GetUxmax();
        Double_t y1min  = .98*gPad->GetUymin() + .02*gPad->GetUymax();
        Double_t y2max  = .02*gPad->GetUymin() + .98*gPad->GetUymax();
        Double_t width  = .4*(x2max-x1min);
        Double_t height = (1./20)*legend->GetListOfPrimitives()->GetEntries()*(y2max-y1min);
        if (type == Histogram || type == OrgHistogram)
        {
            width *= 2;
            height /= 2;
            legend->SetNColumns(2);
        }
        Double_t newy2max = placeLegend(legend,width,height,x1min,y1min,x2max,y2max);
        maxp->GetYaxis()->SetRangeUser(gPad->GetUymin(),(newy2max-.02*gPad->GetUymin())/.98);
                
        legend->SetFillStyle(0);
        legend->Draw();
    }
    if (saveas != "")
    {
        saveplot(c1,saveas);
        for (int i = 0; i < n; i++)
        {
            //delete p[i];
            //delete g[i];
        }
        //delete list;
        //delete maxp;
        //delete legend;
    }
    return c1;
}
void makePlot(double canvasSizeX, double canvasSizeY,
	      TH1* histogramTTH, 
	      TH1* histogramData, 
	      TH1* histogramTT,
	      TH1* histogramTTV,
	      TH1* histogramEWK,
	      TH1* histogramRares,
	      TH1* histogramBgrSum,
	      TH1* histogramBgrUncertainty,		
	      const std::string& xAxisTitle, double xAxisOffset,
	      bool useLogScale, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset,
	      const std::string& outputFileName)
{
  TH1* histogramTTH_density = 0;
  if ( histogramTTH ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTH, histogramData);
    histogramTTH_density = divideHistogramByBinWidth(histogramTTH);
  }
  TH1* histogramData_density = 0;
  if ( histogramData ) {
    histogramData_density = divideHistogramByBinWidth(histogramData);      
  }
  TH1* histogramTT_density = 0;
  if ( histogramTT ) {
    if ( histogramData ) checkCompatibleBinning(histogramTT, histogramData);
    histogramTT_density = divideHistogramByBinWidth(histogramTT);
  } 
  TH1* histogramTTV_density = 0;
  if ( histogramTTV ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTV, histogramData);
    histogramTTV_density = divideHistogramByBinWidth(histogramTTV);
  }    
  TH1* histogramEWK_density = 0;
  if ( histogramEWK ) {
    if ( histogramData ) checkCompatibleBinning(histogramEWK, histogramData);
    histogramEWK_density = divideHistogramByBinWidth(histogramEWK);
  }
  TH1* histogramRares_density = 0;
  if ( histogramRares ) {
    if ( histogramData ) checkCompatibleBinning(histogramRares, histogramData);
    histogramRares_density = divideHistogramByBinWidth(histogramRares);
  }    
  TH1* histogramBgrSum_density = 0;
  if ( histogramBgrSum ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrSum, histogramData);
    histogramBgrSum_density = divideHistogramByBinWidth(histogramBgrSum); 
  }
  TH1* histogramBgrUncertainty_density = 0;
  if ( histogramBgrUncertainty ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrUncertainty, histogramData);
    histogramBgrUncertainty_density = divideHistogramByBinWidth(histogramBgrUncertainty);
  }
  
  TCanvas* canvas = new TCanvas("canvas", "", canvasSizeX, canvasSizeY);
  canvas->SetFillColor(10);
  canvas->SetFillStyle(4000);
  canvas->SetFillColor(10);
  canvas->SetTicky();
  canvas->SetBorderSize(2);  
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);
  
  TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.065);
  topPad->SetLeftMargin(0.15);
  topPad->SetBottomMargin(0.03);
  topPad->SetRightMargin(0.05);
  topPad->SetLogy(useLogScale);
  
  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.02);
  bottomPad->SetLeftMargin(0.15);
  bottomPad->SetBottomMargin(0.31);
  bottomPad->SetRightMargin(0.05);
  bottomPad->SetLogy(false);
  
  canvas->cd();
  topPad->Draw();
  topPad->cd();
  
  TAxis* xAxis_top = histogramData_density->GetXaxis();
  xAxis_top->SetTitle(xAxisTitle.data());
  xAxis_top->SetTitleOffset(xAxisOffset);
  xAxis_top->SetLabelColor(10);
  xAxis_top->SetTitleColor(10);
    
  TAxis* yAxis_top = histogramData_density->GetYaxis();
  yAxis_top->SetTitle(yAxisTitle.data());
  yAxis_top->SetTitleOffset(yAxisOffset);
  yAxis_top->SetTitleSize(0.085);
  yAxis_top->SetLabelSize(0.05);
  yAxis_top->SetTickLength(0.04);  
  
  TLegend* legend = new TLegend(0.66, 0.45, 0.94, 0.92, NULL, "brNDC");
  legend->SetFillStyle(0);
  legend->SetBorderSize(0);
  legend->SetFillColor(10);
  legend->SetTextSize(0.055);
  
  histogramData_density->SetTitle("");
  histogramData_density->SetStats(false);
  histogramData_density->SetMaximum(yMax);
  histogramData_density->SetMinimum(yMin);
  histogramData_density->SetMarkerStyle(20);
  histogramData_density->SetMarkerSize(2);
  histogramData_density->SetMarkerColor(kBlack);
  histogramData_density->SetLineColor(kBlack);
  legend->AddEntry(histogramData_density, "Observed", "p");    
  
  histogramData_density->Draw("ep");
  
  legend->AddEntry(histogramTTH_density, "t#bar{t}H", "l");

  histogramTT_density->SetTitle("");
  histogramTT_density->SetStats(false);
  histogramTT_density->SetMaximum(yMax);
  histogramTT_density->SetMinimum(yMin);
  histogramTT_density->SetFillColor(kMagenta - 10); 
  legend->AddEntry(histogramTT_density, "t#bar{t}+jets", "f");

  histogramTTV_density->SetFillColor(kOrange - 4);
  legend->AddEntry(histogramTTV_density, "t#bar{t}+V", "f");

  histogramEWK_density->SetFillColor(kRed + 2); 
  legend->AddEntry(histogramEWK_density, "EWK", "f");

  histogramRares_density->SetFillColor(kBlue - 8); 
  legend->AddEntry(histogramRares_density, "Rares", "f");

  THStack* histogramStack_density = new THStack("stack", "");
  histogramStack_density->Add(histogramRares_density);
  histogramStack_density->Add(histogramEWK_density);
  histogramStack_density->Add(histogramTTV_density);
  histogramStack_density->Add(histogramTT_density);
  histogramStack_density->Draw("histsame");
  
  histogramBgrUncertainty_density->SetFillColor(kBlack);
  histogramBgrUncertainty_density->SetFillStyle(3344);    
  histogramBgrUncertainty_density->Draw("e2same");
  legend->AddEntry(histogramBgrUncertainty_density, "Uncertainty", "f");

  histogramTTH_density->SetLineWidth(2);
  histogramTTH_density->SetLineStyle(1);
  histogramTTH_density->SetLineColor(kBlue);
  histogramTTH_density->Draw("histsame");
  
  histogramData_density->Draw("epsame");
  histogramData_density->Draw("axissame");
  
  legend->Draw();
  
  addLabel_CMS_luminosity(0.2050, 0.9225, 0.6850);
  
  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();
  
  TH1* histogramRatio = (TH1*)histogramData->Clone("histogramRatio");
  histogramRatio->Reset();
  if ( !histogramRatio->GetSumw2N() ) histogramRatio->Sumw2();
  checkCompatibleBinning(histogramRatio, histogramBgrSum);
  histogramRatio->Divide(histogramData, histogramBgrSum);
  int numBins_bottom = histogramRatio->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins_bottom; ++iBin ) {
    double binContent = histogramRatio->GetBinContent(iBin);
    if ( histogramData && histogramData->GetBinContent(iBin) >= 0. ) histogramRatio->SetBinContent(iBin, binContent - 1.0);
    else histogramRatio->SetBinContent(iBin, -10.);
  }
  histogramRatio->SetTitle("");
  histogramRatio->SetStats(false);
  histogramRatio->SetMinimum(-0.50);
  histogramRatio->SetMaximum(+0.50);
  histogramRatio->SetMarkerStyle(histogramData_density->GetMarkerStyle());
  histogramRatio->SetMarkerSize(histogramData_density->GetMarkerSize());
  histogramRatio->SetMarkerColor(histogramData_density->GetMarkerColor());
  histogramRatio->SetLineColor(histogramData_density->GetLineColor());
  histogramRatio->Draw("ep");
  
  TAxis* xAxis_bottom = histogramRatio->GetXaxis();
  xAxis_bottom->SetTitle(xAxis_top->GetTitle());
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleOffset(1.20);
  xAxis_bottom->SetTitleSize(0.13);
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.10);
  xAxis_bottom->SetTickLength(0.055);
  
  TAxis* yAxis_bottom = histogramRatio->GetYaxis();
  yAxis_bottom->SetTitle("#frac{Data - Simulation}{Simulation}");
  yAxis_bottom->SetTitleOffset(0.80);
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.09);
  yAxis_bottom->SetLabelSize(0.10);
  yAxis_bottom->SetTickLength(0.04);  
  
  TH1* histogramRatioUncertainty = (TH1*)histogramBgrUncertainty->Clone("histogramRatioUncertainty");
  if ( !histogramRatioUncertainty->GetSumw2N() ) histogramRatioUncertainty->Sumw2();
  checkCompatibleBinning(histogramRatioUncertainty, histogramBgrUncertainty);
  histogramRatioUncertainty->Divide(histogramBgrSum);
  int numBins = histogramRatioUncertainty->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    double binContent = histogramRatioUncertainty->GetBinContent(iBin);
    histogramRatioUncertainty->SetBinContent(iBin, binContent - 1.0);
  }
  histogramRatioUncertainty->SetFillColor(histogramBgrUncertainty_density->GetFillColor());
  //histogramRatioUncertainty->SetFillStyle(histogramBgrUncertainty_density->GetFillStyle());    
  histogramRatioUncertainty->SetFillStyle(3644);    
  
  TF1* line = new TF1("line","0", xAxis_bottom->GetXmin(), xAxis_bottom->GetXmax());
  line->SetLineStyle(3);
  line->SetLineWidth(1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  
  histogramRatioUncertainty->Draw("e2same");
  
  histogramRatio->Draw("epsame");
  
  canvas->Update();
  size_t idx = outputFileName.find(".");
  std::string outputFileName_plot(outputFileName, 0, idx);
  if ( useLogScale ) outputFileName_plot.append("_log");
  else outputFileName_plot.append("_linear");
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());
  
  delete histogramTTH_density;
  delete histogramData_density;
  delete histogramTT_density;
  delete histogramTTV_density;
  delete histogramEWK_density;
  delete histogramRares_density;
  delete histogramBgrSum_density;
  //delete histogramBgrUncertainty_density;
  delete histogramStack_density;
  delete legend;
  delete topPad;
  delete histogramRatio;
  delete histogramRatioUncertainty;
  delete line;
  delete bottomPad;    
  delete canvas;
}