Example #1
0
void anaFragShape(TString infile="dj_HCPR-GoodTrkAndPixel_CleanEvt1130.root")
{
  TChain * djcalo = new TChain("djcalo/djTree");
  djcalo->Add(infile);
  aliases_dijet(djcalo);
  TChain * djcalopix = new TChain("djcalo_pxl/djTree");
  djcalopix->Add(infile);
  aliases_dijet(djcalopix);
  TString evtSel("(cent<10 && nljet>120 && abs(nljeta)<2 && aljet>50 && abs(aljeta)<2 && jdphi>2.5 && Aj>0.24)");
  TH1::SetDefaultSumw2();

  TCanvas * c0 = new TCanvas("c0","c0",500,500);
  djcalo->Draw("Aj>>hAj(20,0,1)",evtSel);
  djcalopix->Draw("Aj",evtSel,"Esame");

  TCanvas * c2 = new TCanvas("c2","c2",500,500);
  TH1D * hJDPhi = new TH1D("hJDPhi","hJDPhi",50,0,3.1416);
  TH1D * hJDPhi2 = new TH1D("hJDPhi2","hJDPhi",50,0,3.1416);
  Float_t numDJ = djcalo->Draw("jdphi>>hJDPhi",evtSel);
  Float_t numDJ2 = djcalopix->Draw("jdphi>>hJDPhi2",evtSel);
  cout << "num djs: " << numDJ << "  djs(pix)" << numDJ2 << endl;

  TH1D * hPNDRTrk = new TH1D("hPNDRTrk",";R(trk,jet);1/(N_{DJ} 2#piR) dp_{T}^{Trk}/dR",10,0,TMath::PiOver2());
  TH1D * hPNDRPix = new TH1D("hPNDRPix",";R(trk,jet);1/(N_{DJ} 2#piR) dp_{T}^{Trk}/dR",10,0,TMath::PiOver2());
  TH1D * hPADRTrk = new TH1D("hPADRTrk",";R(trk,jet);1/(N_{DJ} 2#piR) dp_{T}^{Trk}/dR",10,0,TMath::PiOver2());
  TH1D * hPADRPix = new TH1D("hPADRPix",";R(trk,jet);1/(N_{DJ} 2#piR) dp_{T}^{Trk}/dR",10,0,TMath::PiOver2());
  djcalo->Draw("pndr>>hPNDRTrk",Form("(%s&&ppt>=1.2)*(ppt/(TMath::TwoPi()*pndr))",evtSel.Data()));
  djcalopix->Draw("pndr>>hPNDRPix",Form("(%s&&ppt>=0.3&&ppt<1.2)*(ppt/(TMath::TwoPi()*pndr))",evtSel.Data()));
  djcalo->Draw("padr>>hPADRTrk",Form("(%s&&ppt>=1.2)*(ppt/(TMath::TwoPi()*padr))",evtSel.Data()));
  djcalopix->Draw("padr>>hPADRPix",Form("(%s&&ppt>=0.3&&ppt<1.2)*(ppt/(TMath::TwoPi()*padr))",evtSel.Data()));
  hPNDRTrk->Scale(1./(numDJ*hPNDRTrk->GetBinWidth(1)));
  hPNDRPix->Scale(1./(numDJ*hPNDRPix->GetBinWidth(1)));
  hPADRTrk->Scale(1./(numDJ*hPADRTrk->GetBinWidth(1)));
  hPADRPix->Scale(1./(numDJ*hPADRPix->GetBinWidth(1)));
  hPNDRPix->SetMinimum(50);
  hPNDRPix->SetMaximum(100);
  hPNDRTrk->SetMinimum(10);
  hPNDRTrk->SetMaximum(2000);
  hPNDRPix->SetMarkerStyle(kFullCircle);
  hPNDRTrk->SetMarkerStyle(kFullSquare);
  hPNDRPix->SetMarkerColor(kRed);
  hPNDRTrk->SetMarkerColor(kRed);
  hPADRPix->SetMarkerStyle(kOpenCircle);
  hPADRTrk->SetMarkerStyle(kOpenSquare);
  hPADRPix->SetMarkerColor(kBlue);
  hPADRTrk->SetMarkerColor(kBlue);
  TCanvas * c3 = new TCanvas("c3","c3",500,500);
  hPNDRPix->Draw("E");
  hPADRPix->Draw("Esame");
  TCanvas * c3_2 = new TCanvas("c3_2","c3_2",500,500);
  c3_2->SetLogy();
  hPNDRTrk->Draw("E");
  hPADRTrk->Draw("Esame");
}
Example #2
0
TH1D *
GetITSsaSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent, Bool_t cutSpectrum = kTRUE, Bool_t addSystematicError = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin[AliPID::kSPECIES] = {0., 0., 0.1, 0.2, 0.3};
  Double_t ptMax[AliPID::kSPECIES] = {0., 0., 0.6, 0.5, 0.6};

  TList *list = (TList *)file->Get("output");
  TH1D *hin = (TH1D *)list->FindObject(Form("h_%s_%s_cen_%d", ITSsaPartName[part], ITSsaChargeName[charge], cent));
  if (!hin) return NULL;  

  /* get systematics */
  TFile *fsys = TFile::Open("SPECTRASYS_ITSsa.root");
  TH1 *hsys = fsys->Get(Form("hSystTot%s%s", ITSsaChargeName[charge], ITSsaPartName[part]));
			
  TH1D *h = new TH1D(Form("hITSsa_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "ITSsa", NptBins, ptBin);
  Double_t pt, width, value, error, sys;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin[part] || pt > ptMax[part])) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    /*** TEMP ADD SYS ***/
    if (addSystematicError) {
      sys = hsys->GetBinContent(bin) * value;
      error = TMath::Sqrt(error * error + sys * sys);
    }
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }

  h->SetTitle("ITSsa");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(20);
  h->SetMarkerColor(1);
  h->SetFillStyle(0);
  h->SetFillColor(0);

  return h;
}
Example #3
0
TH1D *
GetITSTPCSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent)
{
  TList *list = (TList *)file->Get("output");
  TH1D *hin = (TH1D *)list->FindObject(Form("h_%s_%s_cen_%d", ITSTPCPartName[part], ITSTPCChargeName[charge], cent + 1));
  if (!hin) return NULL;

  TH1D *h = new TH1D(Form("hITSTPC_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "ITSTPC", NptBins, ptBin);
  Double_t pt, width, value, error;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
#if 0
  /* add systematic error */
  Double_t sys;
  if (part == 2) sys = 0.5;
  else sys = 0.1;
  Double_t cont, conte;
  for (Int_t ipt = 0; ipt < h->GetNbinsX(); ipt++) {
    cont = h->GetBinContent(ipt + 1);
    conte = h->GetBinError(ipt + 1);
    conte = TMath::Sqrt(conte * conte + sys * sys * cont * cont);
    h->SetBinError(ipt + 1, conte);
  }
#endif
  
  h->SetTitle("ITSTPC");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(21);
  h->SetMarkerColor(2);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  return h;
}
Example #4
0
// Rebin first histogram to match the second
TH1D *tools::Rebin(const TH1D *h, const TH1D* href) {

  //assert(href->GetNbinsX()<=h->GetNbinsX());
  if (!(href->GetNbinsX()<=h->GetNbinsX())) {
    cout << "Histo has less bins than ref: "
	 << h->GetNbinsX() << " vs " << href->GetNbinsX()
	 << " for " << h->GetName() << endl;
  }
  
  // First, we need to rebin inclusive jets to match b-tagged jets
  TH1D *hre = (TH1D*)href->Clone(Form("%s_rebin",h->GetName()));
  hre->Reset();

  for (int i = 1; i != h->GetNbinsX()+1; ++i) {

    double x = h->GetBinLowEdge(i);
    int j = hre->FindBin(x);
    // Check that h is fully contained within href bin
    if (h->GetBinContent(i)!=0) {

      if (!(h->GetBinLowEdge(i)>=hre->GetBinLowEdge(j) - 1e-5 &&
	    h->GetBinLowEdge(i+1)<=hre->GetBinLowEdge(j+1) + 1e-5)) {
	cerr << Form("Warning, bin edges overlapping: h=[%1.0f,%1.0f],"
		     " hre=[%1.0f,%1.0f] (%s)",
		     h->GetBinLowEdge(i), h->GetBinLowEdge(i+1),
		     hre->GetBinLowEdge(j), hre->GetBinLowEdge(j+1),
		     h->GetName()) << endl;
      }

      double y = ( hre->GetBinContent(j)*hre->GetBinWidth(j)
		   + h->GetBinContent(i)*h->GetBinWidth(i) )
	/ hre->GetBinWidth(j);
      //double ey = ( hre->GetBinError(j)*hre->GetBinWidth(j)
      //	    + h->GetBinError(i)*h->GetBinWidth(i) )
      // / hre->GetBinWidth(j);
      double ey = sqrt( pow(hre->GetBinError(j)*hre->GetBinWidth(j),2)
			+ pow(h->GetBinError(i)*h->GetBinWidth(i),2) )
	/ hre->GetBinWidth(j);
      hre->SetBinContent(j, y);
      hre->SetBinError(j, ey);
    }
  } // for i

  return hre;
} // Rebin
Example #5
0
TH1D *
GetTPCTOFSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent, Bool_t cutSpectrum = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin[AliPID::kSPECIES] = {0., 0., 0., 0., 0.};
  Double_t ptMax[AliPID::kSPECIES] = {0., 0., 1.2, 1.2, 1.8};

  TH1D *hin = (TH1D *)file->Get(Form("%sFinal%s%d", TPCTOFPartName[part], TPCTOFChargeName[charge], cent));
  if (!hin) return NULL;

  TH1D *h = new TH1D(Form("hTPCTOF_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "TPCTOF", NptBins, ptBin);
  Double_t pt, width, value, error;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin[part] || pt > ptMax[part])) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
  h->SetTitle("TPCTOF");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(22);
  h->SetMarkerColor(8);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  
  return h;
}
Example #6
0
void XS1S_Rap(){
  
  TFile *f = new TFile("XSection.root");
  TH1D *H;
  H = (TH1D*)gFile->Get("S1YieldEta");
  double tot(0.); double totE(0.); 
  
  ofstream OUT("XS_1S_rap.tex");
  OUT << "% ----------------------------------------------------------------------" << endl;
  OUT << "% -- Yields" << endl;
  for ( int x = 1; x <= H->GetNbinsX(); ++x ){
    OUT << Form("\\vdef{XS_rap%iS_bin%iContent} {\\ensuremath{ {%.3f } } }",1, x, H->GetBinContent(x)*H->GetBinWidth(x) ) << endl;
    OUT << Form("\\vdef{XS_rap%iS_bin%iError} {\\ensuremath{ {%.3f } } }",1, x, H->GetBinError(x)*H->GetBinWidth(x) ) << endl;
    tot += H->GetBinContent(x)*H->GetBinWidth(x);
    totE += (H->GetBinError(x)*H->GetBinWidth(x)*H->GetBinWidth(x)*H->GetBinError(x));
  }
		
  OUT << Form("\\vdef{sum%iS} {\\ensuremath{ {%.4f } } }",1, tot) << endl;
  OUT << Form("\\vdef{sum%iSError} {\\ensuremath{ {%.4f } } }",1 , TMath::Sqrt(totE) ) << endl;
  OUT.close();
  
}
void RRootHistRead_v1(){
	
	TFile *inputFile = new TFile("pPb_MBSpectra_Combine_-1_1.root");
	cout << "Is the file Open " << inputFile->IsOpen() << endl;

	//Copy the histogram
	TString hName = "Spectra_NtrkOffline0_inf";
	TH1D *h = (TH1D*)inputFile->Get(hName);

	cout << "Number of bins in the histogram: " << h->GetSize() << "\n";
	h->Draw();

	double nhBins = h->GetSize();
	for (int i=0; i < nhBins; i++) cout << h->GetBinWidth(i) << ", ";
	cout << endl;

	// Fit function
	double nParam = 2, maxValue = 5, minValue = 0;

	TF1 *fitFn = new TF1("fitFn", fitFunction, minValue, maxValue, nParam);

	// Set parameters for Fit
	fitFn->SetParameter(0, 0.008);

	// Get parameters from Fit
	double paramFromFit[2];
	fitFn->GetParameters(paramFromFit);

	// Generate data from fit
	double nBins = 27, pT[27], spectraFromFit[27]; // From the Xi 
	for (int i=0; i < nBins; i++){

		spectraFromFit[i] = paramFromFit[0]*exp(-i) + paramFromFit[1];
		cout << spectraFromFit[i] << ", ";
		pT[i] = i;
			
	}

	// Using Integral for the Fit
	h->Fit(fitFn, "I");

	TGraph *g = new TGraph(nBins, pT, spectraFromFit);
	g->SetMarkerStyle(7);
	g->SetMarkerSize(1.5);
	g->SetMarkerColor(kGreen);
	g->Draw("ALP");
	h->Draw("same");
	
}
Example #8
0
TH1F* getTruthCrossSection(TFile *file, double x, TString name){

  TTree* genTree = (TTree*)file->Get("ttbarGenAna/tree");
  TH1D* h = new TH1D(Form("h_%s",name.Data()),"h",nGen, genBins);
  genTree->Project(Form("h_%s",name.Data()), "mTT");
  TH1F* hSigma = new TH1F(Form("hSigma_%s",name.Data()),"hSigma", nGen, genBins);

  for(int i=1; i <= nGen; i++){
    double dsigma = x * h->GetBinContent(i) / ( h->GetBinWidth(i) * h->Integral() );
    hSigma->SetBinContent(i,dsigma);
  }

  return hSigma;

}
Example #9
0
TH1D* getFF_pp(double jetPt_low, double jetPt_high, const char* histTitle, int mode)
{
  TH1D * FF = new TH1D(histTitle,";p_{T trk};#frac{1}{N_{jet}} #frac{dN_{trk}}{dp_{t trk}}",trkBins ,yAxis);

  getSpectra(mode);

  //looping over bins in Trk pt
    for(int t = 1; t < trkBins+1; t++)
    {
      double sum   = 0;
      double error = 0;
      double norm  = 0;        

      //looping over jet pt
      for(int j = jet->FindBin(jetPt_low); j < jet->FindBin(jetPt_high); j++)
      {
        //reweighting factor to 5 TeV pPb
        //for (mode 2) 5TeV pPb jet_pPb = jet so this is by definition one
        double w = jet_pPb->GetBinContent(j)/jet->GetBinContent(j);

        //adding up contributions to the FF from each track and jet bin
        sum   += w*(trk->GetBinContent(j,t) - trkUE->GetBinContent(j,t));
        error += w*w*(TMath::Power(trk->GetBinError(j,t),2) + TMath::Power(trkUE->GetBinError(j,t),2));
        norm  += jet_pPb->GetBinContent(j);
      }

      if(norm!=0)
      {   
        sum   = sum/(norm*FF->GetBinWidth(t));
        error = TMath::Power(error,0.5)/(norm*FF->GetBinWidth(t));
        FF->SetBinContent(t,sum);
        FF->SetBinError(t,error);
      }
    }
  return FF;
}
Example #10
0
void AdjustDensityForBinWidth(TH1D &h) {
    double entries = h.GetEntries();
    int nbins = h.GetNbinsX();
    double low = h.GetBinLowEdge(1);
    double high = h.GetBinLowEdge(nbins+1);
    double width = (high-low)/nbins;
    for(int bin = 1; bin <= nbins; ++bin) {
        double content = h.GetBinContent(bin);
        double error = h.GetBinError(bin);
        double this_width = h.GetBinWidth(bin);
        double scale = width/this_width;
        h.SetBinContent(bin, content*scale);
        h.SetBinError(bin, error*scale);
    }
    h.SetEntries(entries);
}
void writeDataBackgroundHistosForModel(const std::map<TString,TGraph*>& m_bkgds,
				       const std::vector<TH1D *>& vchans,
				       TFile  *allHistFile)
{
  for (std::map<TString,TGraph*>::const_iterator it = m_bkgds.begin();
       it != m_bkgds.end();
       it++) {
    const TString& name = it->first;

    // determine binning from the signal histogram for this channel
    // - (sigh) have to find it first...
    //
    TString channame = name.Copy().Remove(0,strlen("Bckgrndtot_"));
    TH1D *sigh=(TH1D*)0;
    for (int ichan=0; ichan<NUMCHAN; ichan++) {
      sigh = vchans.at(ichan);
      if (strstr(sigh->GetName(),channame.Data()))
	break;
    }
    assert (sigh);


    // for variable binning - all histos must have the same binning per channel
    TAxis *xax = sigh->GetXaxis();

    TVectorD xbins   = TVectorD(sigh->GetNbinsX(),xax->GetXbins()->GetArray());

    int lobin = xax->FindFixBin(sumwinmin);
    int hibin = xax->FindFixBin(sumwinmax)-1;
    int nbins = hibin-lobin+1;

    TVectorD xwindow = xbins.GetSub(lobin-1,hibin);
    
    printf("Booking TH1D(%s,%s,%d,xwindowarray)\n",
	   name.Data(),name.Data(),nbins);
    TH1D *h = new TH1D(name.Data(),name.Data(),nbins,xwindow.GetMatrixArray());

    for (int ibin=1; ibin <= nbins; ibin++)
      h->SetBinContent(ibin,
		       it->second->Eval(h->GetBinCenter(ibin))
		       * h->GetBinWidth(ibin)
		       );

    allHistFile->WriteTObject(h);
  }

}                                            //  writeDataBackgroundHistosForModel
Example #12
0
void vn_spectra_trackHF()
{
   TString filename = Form("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/outputs_312/HIData_Minbias_2760GeV/merged/HIData_Minbias_2760GeV_UCC2011_INCLv1HF_nmin-1_nmax-1_etatrg-5.0--3.0_etaass3.0-5.0_centmin110_centmax1000.root");
   TFile* fdiff = new TFile(filename.Data());

  TH1D* hpt_ref;
  TH2D* hsignal_ref;
  TH2D* hbackground_ref;
  TH1D* hsignal_ref_1D;
  TH1D* hbackground_ref_1D;
  TH1D* hcorr_ref_1D;

  TH1D* hpt[20];
  TH2D* hsignal[20];
  TH2D* hbackground[20];
  TH1D* hsignal_1D[20];
  TH1D* hbackground_1D[20];
  TH1D* hcorr_1D[20];

  TGraphErrors* gr[20];
  TGraphErrors* gr_corr[20];
  for(int i=0;i<20;i++)
  {
    if(i>=5)
    {
      gr[i] = new TGraphErrors(11);
      gr_corr[i] = new TGraphErrors(11);
    }
    else
    {
      gr[i] = new TGraphErrors(13);
      gr_corr[i] = new TGraphErrors(13);
    }
    gr[i]->SetName(Form("vnpt_%d",i));
    gr_corr[i]->SetName(Form("vnpt_corr_%d",i));
  }

  double factor[20]={1.,1.3,1.0,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8};
  double factor_err[20]={0.,0.1,0.4,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6};
  double VnArray[20][20],Vn0[20],vn0[20],vn0err[20],vn01[20],vn01err[20],vn0_corr[20],vn0_corr_up[20],vn0_corr_down[20],vn0_corr_sys[28],vn0err_corr[20],vn0_ratio[20],vn0err_ratio[20];
  hsignal_ref = (TH2D*)fdiff->Get("signalcosn_trg0_ass0");
  hbackground_ref = (TH2D*)fdiff->Get("backgroundcosn_trg0_ass0");
  hsignal_ref_1D = (TH1D*)hsignal_ref->ProfileY("signal_1D_trg0_ass0_ref",1,-1,"e");
  hbackground_ref_1D = (TH1D*)hbackground_ref->ProfileY("background_1D_trg0_ass0_ref",1,-1,"e");
  hcorr_ref_1D = new TH1D("Vn_1D_trg0_ass0_ref",";n;V_{n#Delta}",15,0.5,15.5);
  for(int n=1;n<=hcorr_ref_1D->GetNbinsX();n++)
  {
    double Vn=hsignal_ref_1D->GetBinContent(n)-hbackground_ref_1D->GetBinContent(n);
    double VnError=sqrt(hsignal_ref_1D->GetBinError(n)*hsignal_ref_1D->GetBinError(n)+hbackground_ref_1D->GetBinError(n)*hbackground_ref_1D->GetBinError(n));
    hcorr_ref_1D->SetBinContent(n,Vn);
    hcorr_ref_1D->SetBinError(n,VnError);
    Vn0[n] = Vn;
    vn0[n] = sqrt(fabs(Vn));
    vn0err[n] = fabs(VnError/Vn)*vn0[n];
  }

  TFile* fpt = new TFile(Form("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/outputs_312/HIData_Minbias_2760GeV/merged/HIData_Minbias_2760GeV_UCC2011_INCLv1TrackHF_nmin-1_nmax-1_etatrg-2.4-0.0_etaass3.0-5.0_centmin110_centmax1000.root"));
  TH1D* hptcorr = (TH1D*)fpt->Get("ptcorrall_trg");

  double merit[20]={0};
  double merit_err[20]={0};
  double total[20]={0};
  double merit_corr[20]={0};
  double merit_corr_up[20]={0};
  double merit_corr_down[20]={0};
  double merit_corr_err[20]={0};
  double total_corr[20]={0};
  for(int i=13;i>=0;i--)
  {
    hpt[i] = (TH1D*)fdiff1->Get(Form("ptcorr_trg_%d",i+1));
    if(i>2)
    {
      hsignal[i] = (TH2D*)fdiff->Get(Form("signalcosn_trg%d_ass0",i+1));
      hbackground[i] = (TH2D*)fdiff->Get(Form("backgroundcosn_trg%d_ass0",i+1));
    }
    else
    {
      hsignal[i] = (TH2D*)fdiff1->Get(Form("signalcosn_trg%d_ass0",i+1));
      hbackground[i] = (TH2D*)fdiff1->Get(Form("backgroundcosn_trg%d_ass0",i+1));
    }
    hsignal_1D[i] = (TH1D*)hsignal[i]->ProfileY(Form("signal_1D_trg%d_ass0",i+1),1,-1,"e");
    hbackground_1D[i] = (TH1D*)hbackground[i]->ProfileY(Form("background_1D_trg%d_ass0",i+1),1,-1,"e");
    hcorr_1D[i] = new TH1D(Form("Vn_1D_trg%d_ass0",i+1),";n;V_{n#Delta}",15,0.5,15.5);

    for(int n=1;n<=hcorr_1D[i]->GetNbinsX();n++)
    {
      if(n>=6 && hpt[i]->GetMean()>5.0) continue;
      if(n==5 && hpt[i]->GetMean()>8.0) continue;
      if(n==4 && hpt[i]->GetMean()>10.0) continue;

      double Vn=hsignal_1D[i]->GetBinContent(n)-hbackground_1D[i]->GetBinContent(n);
      double VnError=sqrt(hsignal_1D[i]->GetBinError(n)*hsignal_1D[i]->GetBinError(n)+hbackground_1D[i]->GetBinError(n)*hbackground_1D[i]->GetBinError(n));

      VnArray[n][i] = Vn;
      hcorr_1D[i]->SetBinContent(n,Vn);
      hcorr_1D[i]->SetBinError(n,VnError);
      
      double vn=Vn/vn0[n];
      if(i<=2) vn=Vn/vn01[n];
      double vnerr=vn*sqrt((VnError/Vn)*(VnError/Vn)+vn0err[n]*vn0err[n]);
      if(i<=2) vnerr=vn*sqrt((VnError/Vn)*(VnError/Vn)+vn01err[n]*vn01err[n]);
      gr[n-1]->SetPoint(i,hpt[i]->GetMean(),vn);
      gr[n-1]->SetPointError(i,0,vnerr);

/*
      double integral = hpt[i]->Integral();
      if(i==0) integral = hpt[1]->Integral();
      if(hpt[i]->GetMean()>3.0) continue;
      merit[n-1] =  merit[n-1] + integral/1000.*vn;
      merit_err[n-1] =  merit_err[n-1] + integral/1000.*vnerr;
      total[n-1] =  total[n-1] + integral/1000.;
      gr_merit[n-1]->SetPoint(i,hpt[i]->GetMean(),merit[n-1]/sqrt(total[n-1]));
if(n==2) cout<<"n="<<n<<" i="<<i<<" "<<merit[n-1]/sqrt(total[n-1])<<endl;
*/
      double integral = hptcorr->GetBinContent(hptcorr->FindBin(hpt[i]->GetMean()))*hptcorr->GetBinWidth(hptcorr->FindBin(hpt[i]->GetMean()));
      if(hpt[i]->GetMean()>3.0) continue;
      merit[n-1] =  merit[n-1] + integral/1000.*vn;
      merit_err[n-1] =  merit_err[n-1] + integral/1000.*vnerr;
      total[n-1] =  total[n-1] + integral/1000.;
      gr_merit[n-1]->SetPoint(i,hpt[i]->GetMean(),merit[n-1]/sqrt(total[n-1]));
if(n==2) cout<<"n="<<n<<" i="<<i<<" "<<merit[n-1]/sqrt(total[n-1])<<endl;
    }
  }

  TH1D* h1corr = (TH1D*)Get1DCFdPhiv3(filename.Data(),0,0,1.9,4.0);
  TH1D* h2corr = (TH1D*)Get1DCFdPhiv3(filename.Data(),11,0,1.9,4.0);
  TCanvas* ccorr = new TCanvas("ccorr","ccorr",900,400);
  ccorr->Divide(2,1);
  ccorr->cd(1);
  ccorr->GetPad(1)->SetLeftMargin(0.23);
  h1corr->SetAxisRange(50.9,52.,"Y");
  h1corr->GetYaxis()->SetTitleOffset(1.2);
  h1corr->GetXaxis()->SetLabelSize(h1corr->GetXaxis()->GetLabelSize()*0.98);
  h1corr->GetYaxis()->SetLabelSize(h1corr->GetXaxis()->GetLabelSize()*0.98);
  h1corr->GetXaxis()->SetTitleSize(h1corr->GetXaxis()->GetTitleSize()*0.98);
  h1corr->GetYaxis()->SetTitleSize(h1corr->GetXaxis()->GetTitleSize()*0.98);
  h1corr->GetYaxis()->SetTitleOffset(h1corr->GetYaxis()->GetTitleOffset()*1.4);
  h1corr->GetXaxis()->CenterTitle();
  h1corr->GetYaxis()->CenterTitle();
  h1corr->Draw("PE");
  ccorr->cd(2);
  ccorr->GetPad(2)->SetLeftMargin(0.23);
  h2corr->SetAxisRange(50.8,52.4,"Y");
  h2corr->GetYaxis()->SetTitleOffset(1.2);
  h2corr->GetXaxis()->SetLabelSize(h2corr->GetXaxis()->GetLabelSize()*0.98);
  h2corr->GetYaxis()->SetLabelSize(h2corr->GetXaxis()->GetLabelSize()*0.98);
  h2corr->GetXaxis()->SetTitleSize(h2corr->GetXaxis()->GetTitleSize()*0.98);
  h2corr->GetYaxis()->SetTitleSize(h2corr->GetXaxis()->GetTitleSize()*0.98);
  h2corr->GetYaxis()->SetTitleOffset(h2corr->GetYaxis()->GetTitleOffset()*1.4);
  h2corr->GetXaxis()->CenterTitle();
  h2corr->GetYaxis()->CenterTitle();
  h2corr->Draw("PE");  

  TF1* fitfunc1 = FitVnFunc(h1corr);
  TF1* fitfunc2 = FitVnFunc(h2corr);
  fitfunc1->SetLineStyle(4);
  fitfunc2->SetLineStyle(4);
  fitfunc1->SetParameters(fitfunc1->GetParameter(0),Vn0[1],Vn0[2],Vn0[3],Vn0[4],Vn0[5],Vn0[6],Vn0[7],Vn0[8],Vn0[9],Vn0[10]);
  fitfunc2->SetParameters(fitfunc2->GetParameter(0),VnArray[1][10],VnArray[2][10],VnArray[3][10],VnArray[4][10],VnArray[5][10],VnArray[6][10],VnArray[7][10],VnArray[8][10],VnArray[9][10],VnArray[10][10]);
  ccorr->cd(1);
  fitfunc1->Draw("Lsame");
  ccorr->cd(2);
  fitfunc2->Draw("Lsame");
  TF1* fitfuns1[6];
  TF1* fitfuns2[6];
  for(int i=0;i<6;i++)
  {
    fitfuns1[i] = (TF1*)fitfunc1->Clone(Form("fitfuncs1_%d",i));
    fitfuns2[i] = (TF1*)fitfunc2->Clone(Form("fitfuncs2_%d",i));
    fitfuns1[i]->SetLineColor(i+1);
    fitfuns2[i]->SetLineColor(i+1);
    fitfuns1[i]->SetLineWidth(1);
    fitfuns2[i]->SetLineWidth(1);
    fitfuns1[i]->SetLineStyle(1);
    fitfuns2[i]->SetLineStyle(1);
  }
  fitfuns1[0]->SetLineColor(1);
  fitfuns1[1]->SetLineColor(2);
  fitfuns1[2]->SetLineColor(9);
  fitfuns1[3]->SetLineColor(4);
  fitfuns1[4]->SetLineColor(8);
  fitfuns1[5]->SetLineColor(6);
  fitfuns2[0]->SetLineColor(1);
  fitfuns2[1]->SetLineColor(2);
  fitfuns2[2]->SetLineColor(9);
  fitfuns2[3]->SetLineColor(4);
  fitfuns2[4]->SetLineColor(8);
  fitfuns2[5]->SetLineColor(6);

  fitfuns1[0]->SetParameters(fitfuns1[0]->GetParameter(0),fitfuns1[0]->GetParameter(1),0,0,0,0,0,0,0,0,0);
  fitfuns1[1]->SetParameters(fitfuns1[1]->GetParameter(0),0,fitfuns1[1]->GetParameter(2),0,0,0,0,0,0,0,0);
  fitfuns1[2]->SetParameters(fitfuns1[2]->GetParameter(0),0,0,fitfuns1[2]->GetParameter(3),0,0,0,0,0,0,0);
  fitfuns1[3]->SetParameters(fitfuns1[3]->GetParameter(0),0,0,0,fitfuns1[3]->GetParameter(4),0,0,0,0,0,0);
  fitfuns1[4]->SetParameters(fitfuns1[4]->GetParameter(0),0,0,0,0,fitfuns1[4]->GetParameter(5),0,0,0,0,0);
  fitfuns1[5]->SetParameters(fitfuns1[5]->GetParameter(0),0,0,0,0,0,fitfuns1[5]->GetParameter(6),0,0,0,0);
  fitfuns2[0]->SetParameters(fitfuns2[0]->GetParameter(0),fitfuns2[0]->GetParameter(1),0,0,0,0,0,0,0,0,0);
  fitfuns2[1]->SetParameters(fitfuns2[1]->GetParameter(0),0,fitfuns2[1]->GetParameter(2),0,0,0,0,0,0,0,0);
  fitfuns2[2]->SetParameters(fitfuns2[2]->GetParameter(0),0,0,fitfuns2[2]->GetParameter(3),0,0,0,0,0,0,0);
  fitfuns2[3]->SetParameters(fitfuns2[3]->GetParameter(0),0,0,0,fitfuns2[3]->GetParameter(4),0,0,0,0,0,0);
  fitfuns2[4]->SetParameters(fitfuns2[4]->GetParameter(0),0,0,0,0,fitfuns2[4]->GetParameter(5),0,0,0,0,0);
  fitfuns2[5]->SetParameters(fitfuns2[5]->GetParameter(0),0,0,0,0,0,fitfuns2[5]->GetParameter(6),0,0,0,0);
  
  ccorr->cd(1);
  fitfuns1[0]->Draw("Lsame");
  fitfuns1[1]->Draw("Lsame");
  fitfuns1[2]->Draw("Lsame");
  fitfuns1[3]->Draw("Lsame");
  fitfuns1[4]->Draw("Lsame");
  fitfuns1[5]->Draw("Lsame");
  ccorr->cd(2);
  fitfuns2[0]->Draw("Lsame");
  fitfuns2[1]->Draw("Lsame");
  fitfuns2[2]->Draw("Lsame");
  fitfuns2[3]->Draw("Lsame");
  fitfuns2[4]->Draw("Lsame");
  fitfuns2[5]->Draw("Lsame");

  TLegend* legend_corr = new TLegend(0.28,0.63,0.7,0.92);
  legend_corr->SetFillStyle(0);
  legend_corr->SetTextFont(42);
  legend_corr->AddEntry(fitfunc1,"Sum","L");
  legend_corr->AddEntry(fitfuns1[0],"n = 1","L");
  legend_corr->AddEntry(fitfuns1[1],"n = 2","L");
  legend_corr->AddEntry(fitfuns1[2],"n = 3","L");
  legend_corr->AddEntry(fitfuns1[3],"n = 4","L");
  legend_corr->AddEntry(fitfuns1[4],"n = 5","L");  
  legend_corr->AddEntry(fitfuns1[5],"n = 6","L");
  ccorr->cd(1);
  legend_corr->Draw("same");
  ccorr->cd(2);
  legend_corr->Draw("same");

  ccorr->cd(1);
  TLatex* latex_corr = new TLatex();
  latex_corr->SetNDC(1);
  latex_corr->SetTextSize(latex_corr->GetTextSize()*0.8);
  latex_corr->DrawLatex(0.47,0.88,"CMS PbPb  #sqrt{s_{NN}} = 2.76 TeV");
  latex_corr->DrawLatex(0.63,0.82,centtag.Data());
  latex_corr->DrawLatex(0.76,0.76,"|#Delta#eta| > 2");
  ccorr->cd(2);
  TLatex* latex1_corr = new TLatex();
  latex1_corr->SetNDC(1);
  latex1_corr->SetTextSize(latex1_corr->GetTextSize()*0.8);
  latex1_corr->DrawLatex(0.47,0.88,"CMS PbPb  #sqrt{s_{NN}} = 2.76 TeV");
  latex1_corr->DrawLatex(0.63,0.82,centtag.Data());
  latex1_corr->DrawLatex(0.76,0.76,"|#Delta#eta| > 2");  
  ccorr->cd(1);
  TLatex* latex_trg1 = new TLatex();
  latex_trg1->SetNDC(1);
  latex_trg1->SetTextSize(latex_trg1->GetTextSize()*0.8);
  latex_trg1->DrawLatex(0.59,0.635,"1 < p_{T}^{trig} < 3 GeV/c");
  latex_trg1->DrawLatex(0.59,0.57,"1 < p_{T}^{assoc} < 3 GeV/c");
  ccorr->cd(2);
  TLatex* latex_trg2 = new TLatex();
  latex_trg2->SetNDC(1);
  latex_trg2->SetTextSize(latex_trg2->GetTextSize()*0.8);
  latex_trg2->DrawLatex(0.59,0.635,"4 < p_{T}^{trig} < 5 GeV/c");
  latex_trg2->DrawLatex(0.59,0.57,"1 < p_{T}^{assoc} < 3 GeV/c");

  SaveCanvas(ccorr,"HI/UCC",Form("corr1Dfit_%s_centmin%d_centmax%d",tag.Data(),centmin,centmax));
/*
  TCanvas* ccc = new TCanvas("ccc","ccc",900,400);
  ccc->Divide(2,1);
  ccc->cd(1);
  ccc->GetPad(1)->SetLeftMargin(0.3);
  hsignal_ref_1D->GetYaxis()->SetTitleOffset(2.0);
  hsignal_ref_1D->GetYaxis()->CenterTitle();
  hsignal_ref_1D->SetAxisRange(1.5,10.5,"X");
  hsignal_ref_1D->SetAxisRange(-0.00025,0.0019,"Y");
  hsignal_ref_1D->SetYTitle("<cos(n#Delta#phi)>");
  hsignal_ref_1D->Draw("PE");
  hbackground_ref_1D->SetMarkerStyle(24);
  hbackground_ref_1D->Draw("PESAME");
  TLegend* legend = new TLegend(0.5,0.75,0.9,0.9);
  legend->SetFillStyle(0);
  legend->SetTextFont(42);
  legend->AddEntry(hsignal_ref_1D,"Signal","P");
  legend->AddEntry(hbackground_ref_1D,"Background","P");
  legend->Draw("same");
  ccc->cd(2);
  ccc->GetPad(2)->SetLeftMargin(0.3);
  hcorr_ref_1D->GetYaxis()->SetTitleOffset(2.0);
  hcorr_ref_1D->GetYaxis()->CenterTitle();
  hcorr_ref_1D->SetAxisRange(1.5,10.5,"X");
  hcorr_ref_1D->Draw("PE");

  SaveCanvas(ccc,"HI/UCC",Form("sigbak_%s_centmin%d_centmax%d",tag.Data(),centmin,centmax));
*/
  for(int n=1;n<=hcorr_ref_1D->GetNbinsX();n++)
  {  
    vn0[n] = merit[n-1]/total[n-1];
    vn0err[n] = merit_err[n-1]/total[n-1];
  }    

  TFile* ffake = new TFile("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/efficiency/fake_hiGoodTightMerged_ucc_new.root");
  TH1D* hfake = (TH1D*)ffake->Get("hFake");

//  TFile* ffake1 = new TFile("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/efficiency/fake_hiGoodTight_ucc_new.root");
//  TH1D* hfake1 = (TH1D*)ffake1->Get("hFake");

  TFile* ffake1 = new TFile("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/efficiency/fake_hiGoodTightMerged_ucc_new.root");
  TH1D* hfake1 = (TH1D*)ffake1->Get("hFake");

  for(int n=1;n<=hcorr_ref_1D->GetNbinsX();n++)
  {
cout<<"n="<<n<<endl;
    for(i=0;i<13;i++) 
    {
      double x,y,xerr,yerr;
      gr[n-1]->GetPoint(i,x,y);
      xerr=gr[n-1]->GetErrorX(i);
      yerr=gr[n-1]->GetErrorY(i);

      if(n>=6 && i>10) continue;

      double fake = 0;
      if(x>1.0) fake = hfake1->GetBinContent(hfake1->FindBin(x));
      if(x<1.0) fake = hfake->GetBinContent(hfake->FindBin(x));
      double vn_corr = (y-fake*factor[n-1]*vn0[n])/(1-fake);
      gr_corr[n-1]->SetPoint(i,x,vn_corr);
      gr_corr[n-1]->SetPointError(i,0,yerr);
cout<<x<<" "<<vn_corr<<" "<<yerr<<endl;
      double vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.02;
      double vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.02;
// temporarily add additional systematics due to EP comparison
/*
      if(n==2 && i==8)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.08;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.08;
      }
      if(n==2 && i==9)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.10;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.10;
      }
      if(n==2 && i==10)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.17;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.17;
      }
      if(n==2 && i>10)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.17;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.17;
      }

      if(n==3 && i>=8)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.04;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.04;
      }
      if(n==5)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.04;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.04;
      }
      if(n>5)
      {
        vn_corr_up = (y-fake*(factor[n-1]-factor_err[n-1])*vn0[n])/(1-fake)+y*0.08;
        vn_corr_down = (y-fake*(factor[n-1]+factor_err[n-1])*vn0[n])/(1-fake)-y*0.08;
      }
*/
      if(n>=6)
      {
        gr_syst[n-1]->SetPoint(i,x,vn_corr_up);
        gr_syst[n-1]->SetPoint(21-i,x,vn_corr_down);
      }
      else 
      {
        gr_syst[n-1]->SetPoint(i,x,vn_corr_up);
        gr_syst[n-1]->SetPoint(25-i,x,vn_corr_down);
      }

      gr_ratio[n-1]->SetPoint(i,x,vn_corr/y);
      gr_ratio[n-1]->SetPointError(i,0,0);

//      double integral = hpt[i]->Integral();
//      if(i==0) integral = hpt[1]->Integral();
      double integral = hptcorr->GetBinContent(hptcorr->FindBin(hpt[i]->GetMean()))*hptcorr->GetBinWidth(hptcorr->FindBin(hpt[i]->GetMean()));
      merit_corr[n-1] =  merit_corr[n-1] + integral/1000.*vn_corr;
      merit_corr_up[n-1] =  merit_corr_up[n-1] + integral/1000.*vn_corr_up;
      merit_corr_down[n-1] =  merit_corr_down[n-1] + integral/1000.*vn_corr_down;
      merit_corr_err[n-1] =  merit_corr_err[n-1] + integral/1000.*yerr;
      total_corr[n-1] =  total_corr[n-1] + integral/1000.;
    }
  }

  for(int n=2;n<=15;n++)
  {
    vn0_corr[n] = merit_corr[n-1]/total_corr[n-1];
cout<<n<<" "<<vn0_corr[n]<<endl;
    vn0_corr_up[n] = merit_corr_up[n-1]/total_corr[n-1];
    vn0_corr_down[n] = merit_corr_down[n-1]/total_corr[n-1];
    vn0_corr_sys[n-2] = vn0_corr_up[n];
    vn0_corr_sys[29-n] = vn0_corr_down[n];
    if(n>=5)
    {
      vn0_corr_sys[n-2] = vn0_corr[n]+0.0004;
      vn0_corr_sys[29-n] = vn0_corr[n]-0.0004;
    }
    vn0err_corr[n] = merit_corr_err[n-1]/total_corr[n-1];
    vn0_ratio[n] = vn0_corr[n]/vn0[n];
    vn0err_ratio[n] = 0;
  }

  double vn_hydro_ideal[4] = {0.21,0.1875,0.1,0.0375};
  double vn_hydro_004[4] = {0.195,0.167,0.08,0.025};
  double vn_hydro_008[4] = {0.18,0.15,0.0625,0.0167};
  double vn_hydro_012[4] = {0.167,0.14,0.05,0.0084};
  double vn_hydro_016[4] = {0.15,0.128,0.04,0.001};
  double etas[4] = {2,3,4,5};

  for(int i=3;i>=0;i--)
  {
    vn_hydro_ideal[i] = vn_hydro_ideal[i]/vn_hydro_ideal[0]*vn0[2];
    vn_hydro_004[i] = vn_hydro_004[i]/vn_hydro_004[0]*vn0[2];
    vn_hydro_008[i] = vn_hydro_008[i]/vn_hydro_008[0]*vn0[2];
    vn_hydro_012[i] = vn_hydro_012[i]/vn_hydro_012[0]*vn0[2];
    vn_hydro_016[i] = vn_hydro_016[i]/vn_hydro_016[0]*vn0[2];
  }

  TGraph* gr_ideal = new TGraph(4,etas,vn_hydro_ideal);
  TGraph* gr_004 = new TGraph(4,etas,vn_hydro_004);
  TGraph* gr_008 = new TGraph(4,etas,vn_hydro_008);
  TGraph* gr_012 = new TGraph(4,etas,vn_hydro_012);
  TGraph* gr_016 = new TGraph(4,etas,vn_hydro_016);
  gr_004->SetLineColor(kRed);
  gr_008->SetLineColor(kBlue);
  gr_012->SetLineColor(kGreen);
  gr_016->SetLineColor(6);
  gr_ideal->SetLineStyle(9);
  gr_ideal->SetLineWidth(2);
  gr_004->SetLineWidth(2);
  gr_008->SetLineWidth(2);
  gr_012->SetLineWidth(2);
  gr_016->SetLineWidth(2);

  double narray[15] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14};
  double narray2[28] = {2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,14,13,12,11,10,9,8,7,6,5,4,3,2};

  double narrayerr[15] = {0};
  TGraphErrors* gr_vn0 = new TGraphErrors(15,narray,vn0,narrayerr,vn0err);
  gr_vn0->SetName("vnn");
  TCanvas* c1 = new TCanvas("c1","",580,500);
  c1->SetLeftMargin(0.16);
  TH2D* htmp1 = new TH2D("htmp1",";n;v_{n}",100,0.5,7.9+5,100,0.00003-0.01,0.04);
  htmp1->GetXaxis()->CenterTitle();
  htmp1->GetYaxis()->CenterTitle();
  htmp1->GetXaxis()->SetLabelSize(0.8*htmp1->GetXaxis()->GetLabelSize());
  htmp1->GetYaxis()->SetLabelSize(0.8*htmp1->GetYaxis()->GetLabelSize());
  htmp1->GetYaxis()->SetTitleOffset(0.96*htmp1->GetYaxis()->GetTitleOffset());
  htmp1->GetXaxis()->SetTitleOffset(1.02*htmp1->GetXaxis()->GetTitleOffset());
  htmp1->GetYaxis()->SetTitleSize(1.1*htmp1->GetYaxis()->GetTitleSize());
  htmp1->GetXaxis()->SetTitleSize(0.9*htmp1->GetXaxis()->GetTitleSize());
//  c1->SetLogy();
  htmp1->Draw("");
  gr_vn0->Draw("PESAME");

  gr_ideal->Draw("LSAME");
  gr_004->Draw("LSAME");
  gr_008->Draw("LSAME");
  gr_012->Draw("LSAME");
  gr_016->Draw("LSAME");

  TLine* line1 = new TLine(0.5,0.0,7.9+5,0.0);
  line1->SetLineStyle(9);
  line1->Draw("lsame");

  TLatex* latex1 = new TLatex();
  latex1->SetNDC(1);
  latex1->SetTextSize(latex1->GetTextSize()*1.0);
  latex1->DrawLatex(0.65,0.87,"CMS Preliminary");
  latex1->DrawLatex(0.65,0.80,"PbPb  #sqrt{s_{NN}} = 2.76 TeV");
  latex1->DrawLatex(0.65,0.74,centtag.Data());
  latex1->DrawLatex(0.25,0.34,"0.3<p_{T}<3 GeV/c");

  TLegend* legend = new TLegend(0.2,0.45,0.45,0.7);
  legend->SetFillStyle(0);
  legend->SetTextFont(42);
  legend->AddEntry(gr_ideal,"Ideal Hydro","L");
  legend->AddEntry(gr_004,"#eta/s=0.04","L");
  legend->AddEntry(gr_008,"#eta/s=0.08","L");
  legend->AddEntry(gr_012,"#eta/s=0.12","L");
  legend->AddEntry(gr_016,"#eta/s=0.16","L");
//  legend->Draw("same");

  SaveCanvas(c1,"HI/UCC",Form("vnn_%s_centmin%d_centmax%d",tag.Data(),centmin,centmax));

  TGraphErrors* gr_corr_vn0 = new TGraphErrors(15,narray,vn0_corr,narrayerr,vn0err_corr);
  gr_corr_vn0->SetName("vnn_corr");
  TGraph* gr_corr_vn0_sys = new TGraph(28,narray2,vn0_corr_sys);
  gr_corr_vn0_sys->SetName("vnn_corr_sys");

  TCanvas* c1_corr = new TCanvas("c1_corr","",580,500);
  c1_corr->SetLeftMargin(0.16);
  htmp1->Draw("");
  gr_corr_vn0_sys->SetFillColor(17);
  gr_corr_vn0_sys->Draw("Fsame");
  gr_corr_vn0->Draw("PESAME");

  gr_ideal->Draw("LSAME");
  gr_004->Draw("LSAME");
  gr_008->Draw("LSAME");
  gr_012->Draw("LSAME");
  gr_016->Draw("LSAME");

  line1->Draw("lsame");
  latex1->Draw("same");
//  legend->Draw("same");

  SaveCanvas(c1_corr,"HI/UCC",Form("vnn_%s_centmin%d_centmax%d_corr",tag.Data(),centmin,centmax));

  TGraphErrors* gr_ratio_vn0 = new TGraphErrors(15,narray,vn0_ratio,narrayerr,vn0err_ratio);
  gr_ratio_vn0->SetName("vnn_ratio");
  TCanvas* c1_ratio = new TCanvas("c1_ratio","",580,500);
  c1_ratio->SetLeftMargin(0.16);
  TH2D* htmp1_ratio = new TH2D("htmp1_ratio",";n;v_{n}",100,0.5,7.9+5,100,0.5,1.5);
  htmp1_ratio->GetXaxis()->CenterTitle();
  htmp1_ratio->GetYaxis()->CenterTitle();
  htmp1_ratio->GetXaxis()->SetLabelSize(0.8*htmp1_ratio->GetXaxis()->GetLabelSize());
  htmp1_ratio->GetYaxis()->SetLabelSize(0.8*htmp1_ratio->GetYaxis()->GetLabelSize());
  htmp1_ratio->GetYaxis()->SetTitleOffset(0.96*htmp1_ratio->GetYaxis()->GetTitleOffset());
  htmp1_ratio->GetXaxis()->SetTitleOffset(1.02*htmp1_ratio->GetXaxis()->GetTitleOffset());
  htmp1_ratio->GetYaxis()->SetTitleSize(1.1*htmp1_ratio->GetYaxis()->GetTitleSize());
  htmp1_ratio->GetXaxis()->SetTitleSize(0.9*htmp1_ratio->GetXaxis()->GetTitleSize());
//  c1->SetLogy();
  htmp1_ratio->Draw("");
  gr_ratio_vn0->Draw("PESAME");
  latex1->Draw("same");
  TLine* line1_ratio = new TLine(0.5,1.0,7.9+5,1.0);
  line1_ratio->SetLineStyle(9);
  line1_ratio->Draw("lsame");

  SaveCanvas(c1_ratio,"HI/UCC",Form("vnn_%s_centmin%d_centmax%d_ratio",tag.Data(),centmin,centmax));

  TCanvas* c2 = new TCanvas("c2","",580,500);
  c2->SetLeftMargin(0.18);
  TH2D* htmp = new TH2D("htmp",";p_{T}(GeV/c);v_{n}{2part, |#Delta#eta| > 2}",100,-0.001,7.3,100,-0.005,0.099);  
  htmp->GetXaxis()->CenterTitle();
  htmp->GetYaxis()->CenterTitle();
  htmp->GetXaxis()->SetLabelSize(htmp->GetXaxis()->GetLabelSize());
  htmp->GetYaxis()->SetLabelSize(htmp->GetYaxis()->GetLabelSize());
  htmp->GetYaxis()->SetTitleOffset(0.8*htmp->GetYaxis()->GetTitleOffset());
  htmp->GetXaxis()->SetTitleOffset(0.7*htmp->GetXaxis()->GetTitleOffset());
  htmp->GetYaxis()->SetTitleSize(1.5*htmp->GetYaxis()->GetTitleSize());
  htmp->GetXaxis()->SetTitleSize(1.4*htmp->GetXaxis()->GetTitleSize());
  htmp->Draw();
  TLine* line = new TLine(0.001,0,7.3,0.0);
  line->SetLineStyle(9);
  line->Draw("lsame");
//  gr[0]->SetMarkerColor(6);
  gr[1]->SetMarkerColor(1);
  gr[2]->SetMarkerColor(2);
  gr[3]->SetMarkerColor(3);
  gr[4]->SetMarkerColor(4);
  gr[5]->SetMarkerColor(6);
  gr[1]->SetMarkerStyle(20);
  gr[2]->SetMarkerStyle(22);
  gr[3]->SetMarkerStyle(21);
  gr[4]->SetMarkerStyle(29);
  gr[5]->SetMarkerStyle(3);
  gr[2]->SetMarkerSize(1.1*gr[2]->GetMarkerSize());
  gr[3]->SetMarkerSize(0.8*gr[3]->GetMarkerSize());
  gr[4]->SetMarkerSize(1.3*gr[4]->GetMarkerSize());
  gr[5]->SetMarkerSize(1.3*gr[5]->GetMarkerSize());
  gr[1]->Draw("PESAME");
  gr[2]->Draw("PESAME");
  gr[3]->Draw("PESAME");
  gr[4]->Draw("PESAME");
  gr[5]->Draw("PESAME");

  TLegend* legend = new TLegend(0.18,0.6,0.47,0.9);
  legend->SetFillStyle(0);
  legend->SetTextFont(42);
  legend->AddEntry(gr[1],"n = 2","P");
  legend->AddEntry(gr[2],"n = 3","P");
  legend->AddEntry(gr[3],"n = 4","P");
  legend->AddEntry(gr[4],"n = 5","P");
  legend->AddEntry(gr[5],"n = 6","P");
  legend->Draw("same");

  TLatex* latex = new TLatex();
  latex->SetNDC(1);
  latex->SetTextSize(latex->GetTextSize()*1.0);
  latex->DrawLatex(0.66,0.86,"CMS Preliminary");
  latex->DrawLatex(0.64,0.80,"PbPb  #sqrt{s_{NN}} = 2.76 TeV");
  latex->DrawLatex(0.66,0.74,centtag.Data());

  SaveCanvas(c2,"HI/UCC",Form("vn_pt_%s_centmin%d_centmax%d",tag.Data(),centmin,centmax));

  TCanvas* c2_corr = new TCanvas("c2corr","",600,500);
  c2_corr->SetBottomMargin(0.12);
  c2_corr->SetLeftMargin(0.15);
  htmp->Draw();
  line->Draw("lsame");
  gr_corr[1]->SetMarkerColor(1);
  gr_corr[2]->SetMarkerColor(2);
  gr_corr[3]->SetMarkerColor(3);
  gr_corr[4]->SetMarkerColor(4);
  gr_corr[5]->SetMarkerColor(6);
  gr_corr[1]->SetMarkerStyle(20);
  gr_corr[2]->SetMarkerStyle(22);
  gr_corr[3]->SetMarkerStyle(21);
  gr_corr[4]->SetMarkerStyle(29);
  gr_corr[5]->SetMarkerStyle(3);
  gr_corr[2]->SetMarkerSize(1.3*gr_corr[2]->GetMarkerSize());
  gr_corr[3]->SetMarkerSize(1.0*gr_corr[3]->GetMarkerSize());
  gr_corr[4]->SetMarkerSize(1.5*gr_corr[4]->GetMarkerSize());
  gr_corr[5]->SetMarkerSize(1.3*gr_corr[5]->GetMarkerSize());

  gr_syst[1]->Draw("FSAME");
  gr_syst[2]->Draw("FSAME");
  gr_syst[3]->Draw("FSAME");
  gr_syst[4]->Draw("FSAME");
  gr_syst[5]->Draw("FSAME");

  gr_corr[1]->Draw("PESAME");
  gr_corr[2]->Draw("PESAME");
  gr_corr[3]->Draw("PESAME");
  gr_corr[4]->Draw("PESAME");
  gr_corr[5]->Draw("PESAME");
  legend->Draw("same");

  TLatex* latex_corr = new TLatex();
  latex_corr->SetNDC(1);
  latex_corr->SetTextSize(latex_corr->GetTextSize()*0.8);
//  latex_corr->DrawLatex(0.63,0.88,"CMS Preliminary");
  latex_corr->DrawLatex(0.54,0.875,"CMS PbPb  #sqrt{s_{NN}} = 2.76 TeV");
  latex_corr->DrawLatex(0.68,0.815,centtag.Data());
  latex_corr->DrawLatex(0.68,0.755,"1 < p_{T}^{ref} < 3 GeV/c");

  SaveCanvas(c2_corr,"HI/UCC",Form("vn_pt_%s_centmin%d_centmax%d_corr",tag.Data(),centmin,centmax));

  TCanvas* c2_ratio = new TCanvas("c2_ratio","",580,500);
  c2_ratio->SetLeftMargin(0.16);
  TH2D* htmp_ratio = new TH2D("htmp_ratio",";p_{T}(GeV/c);v^{corr}_{n}/v^{raw}_{n}",100,0.001,7.3,100,0.5,1.5);
  htmp_ratio->GetXaxis()->CenterTitle();
  htmp_ratio->GetYaxis()->CenterTitle();
  htmp_ratio->GetXaxis()->SetLabelSize(0.8*htmp_ratio->GetXaxis()->GetLabelSize());
  htmp_ratio->GetYaxis()->SetLabelSize(0.8*htmp_ratio->GetYaxis()->GetLabelSize());
  htmp_ratio->GetYaxis()->SetTitleOffset(0.98*htmp_ratio->GetYaxis()->GetTitleOffset());
  htmp_ratio->GetXaxis()->SetTitleOffset(1.02*htmp_ratio->GetXaxis()->GetTitleOffset());
  htmp_ratio->GetYaxis()->SetTitleSize(1.1*htmp_ratio->GetYaxis()->GetTitleSize());
  htmp_ratio->GetXaxis()->SetTitleSize(0.9*htmp_ratio->GetXaxis()->GetTitleSize());
  htmp_ratio->Draw();
  TLine* line_ratio = new TLine(0.001,1.0,7.3,1.0);
  line_ratio->SetLineStyle(9);
  line_ratio->Draw("lsame");
  gr_ratio[1]->SetMarkerColor(1);
  gr_ratio[2]->SetMarkerColor(2);
  gr_ratio[3]->SetMarkerColor(3);
  gr_ratio[4]->SetMarkerColor(4);
  gr_ratio[5]->SetMarkerColor(6);
  gr_ratio[1]->SetMarkerStyle(20);
  gr_ratio[2]->SetMarkerStyle(22);
  gr_ratio[3]->SetMarkerStyle(21);
  gr_ratio[4]->SetMarkerStyle(29);
  gr_ratio[5]->SetMarkerStyle(3);
  gr_ratio[2]->SetMarkerSize(1.1*gr_ratio[2]->GetMarkerSize());
  gr_ratio[3]->SetMarkerSize(0.8*gr_ratio[3]->GetMarkerSize());
  gr_ratio[4]->SetMarkerSize(1.3*gr_ratio[4]->GetMarkerSize());
  gr_ratio[5]->SetMarkerSize(1.3*gr_ratio[5]->GetMarkerSize());
  gr_ratio[1]->Draw("PESAME");
  gr_ratio[2]->Draw("PESAME");
  gr_ratio[3]->Draw("PESAME");
  gr_ratio[4]->Draw("PESAME");
  gr_ratio[5]->Draw("PESAME");
  legend->Draw("same");

  TLatex* latex_ratio = new TLatex();
  latex_ratio->SetNDC(1);
  latex_ratio->SetTextSize(latex_ratio->GetTextSize()*1.0);
  latex_ratio->DrawLatex(0.65,0.87,"CMS Preliminary");
  latex_ratio->DrawLatex(0.65,0.80,"PbPb  #sqrt{s_{NN}} = 2.76 TeV");
  latex_ratio->DrawLatex(0.65,0.74,centtag.Data());

  SaveCanvas(c2_ratio,"HI/UCC",Form("vn_pt_%s_centmin%d_centmax%d_ratio",tag.Data(),centmin,centmax));

//  gr[0]->Draw("PESAME");
/*
  c2->Print("/net/hisrv0001/home/davidlw/scratch1/UCCPileUp/pics/vnpt_data_UCC020.gif");
  c2->Print("/net/hisrv0001/home/davidlw/scratch1/UCCPileUp/pics/vnpt_data_UCC020.pdf");
  c2->Print("/net/hisrv0001/home/davidlw/scratch1/UCCPileUp/pics/vnpt_data_UCC020.eps");
  c2->Print("/net/hisrv0001/home/davidlw/scratch1/UCCPileUp/pics/vnpt_data_UCC020.C");
*/
/*
  TCanvas* c0 = new TCanvas("c0","",500,500);
  hsignal_1D[3]->Draw("PE");
  hbackground_1D[3]->SetMarkerStyle(24);
  hbackground_1D[3]->Draw("PESAME");

  TCanvas* c = new TCanvas("c","",500,500);
  hcorr_1D[3]->SetAxisRange(-0.001,0.006,"Y");
  hcorr_1D[3]->SetMarkerColor(1);
  hcorr_1D[3]->Draw("PE");
*/
return;
  TFile* fout = new TFile(Form("gr_%s_centmin%d_centmax%d.root",tag.Data(),centmin,centmax),"recreate");
  gr_vn0->SetName("vnn");
  gr_vn0->Write();
  gr_corr_vn0->SetName("vnn_corr");
  gr_corr_vn0->Write();
  gr_corr_vn0_sys->SetName("vnn_corr_sys");
  gr_corr_vn0_sys->Write();
  gr_ratio_vn0->SetName("vnn_ratio");
  gr_ratio_vn0->Write();
  for(int i=0;i<6;i++) 
  {
    gr[i]->SetName(Form("v%dpt",i+1));
    gr[i]->Write();
    gr_corr[i]->SetName(Form("v%dpt_corr",i+1));
    gr_corr[i]->Write();
    gr_ratio[i]->SetName(Form("v%dpt_ratio",i+1));
    gr_ratio[i]->Write();
    gr_syst[i]->SetName(Form("v%dpt_syst",i+1));
    gr_syst[i]->Write();
  }
}
Example #13
0
void Smooth (TString sel, double frac_true_err ) {

    // -C8 : maximum quality factor 1.1314+-0.00503415 at LR > 0.4
    // -M8 : maximum quality factor 1.03056+-0.00499927 at LR > 1.4
    // -C6 : maximum quality factor 1.18157+-0.00673922 at LR > 0.8
    // -M6 : maximum quality factor 1.01414+-0.00240137 at LR > 1.2
    // MEt : maximum quality factor 1.00301+-0.00088719 at LR > 0.8
    // -MEtSig : maximum quality factor 1.01873+-0.00367832 at LR > 1.4
    // -CorrSumEt : maximum quality factor 1.02956+-0.00487776 at LR > 1.4
    // GoodHt : maximum quality factor 1.05092+-0.00244139 at LR > 0.4
    // M45bestall : maximum quality factor 1.03104+-0.00370672 at LR > 1
    // -Chi2mass : maximum quality factor 1.13193+-0.00467282 at LR > 0.4
    // Chi2extall : maximum quality factor 1.07473+-0.00716133 at LR > 1.4
    // Mbbnoh : maximum quality factor 2.17059+-0.0321631 at LR > 0.8
    // DPbbnoh : maximum quality factor 1.30261+-0.0105512 at LR > 0.8
    // SumHED4 : maximum quality factor 1.08131+-0.00809236 at LR > 1.4
    // SumHED6 : maximum quality factor 1.09023+-0.0160105 at LR > 1.8
    // DP12 : maximum quality factor 2.29376+-0.0270215 at LR > 0.4
    // MEtDPM : maximum quality factor 1+-0.1 at LR > 0
    // -MEtDP1 : maximum quality factor 1.06697+-0.00357291 at LR > 0.4
    // MEtDP2 : maximum quality factor 1+-0.1 at LR > 0
    // -M45best : maximum quality factor 1.02626+-0.00341181 at LR > 1.2
    // -M_others : maximum quality factor 1.11418+-0.00859052 at LR > 1.4
    // -Et6 : maximum quality factor 1.02596+-0.00268856 at LR > 1

    const int nbins = 50;

    const int nvars=25;
    TString var[nvars] = { "C8", "M8", "C6", "M6", "MEt", "MEtSig", "CorrSumEt", "GoodHt",
                           "Hbestcomb", "Chi2mass", "Mbbnoh", "DPbbnoh",
                           "SumHED4", "SumHED6", "MEtDPM", "MEtDP1", "MEtDP2",
                           "M_others", "Et6", "Scprod", "Thdeta", "M5", "M3best", "Mwbest",
                           "TTMS1"
                         }

                         TString pippo[nvars];
    TString pippotot[nvars];
    TString pippotth[nvars];
    TString pippototS[nvars];
    TString pippotthS[nvars];
    for ( int i=0; i<nvars; i++ ) {
        pippo[i] = var[i]+sel;
        pippotot[i]=var[i]+sel+"_bgr";
        pippotth[i]=var[i]+sel+"_sig";
        pippototS[i]=var[i]+sel+"_bgrS";
        pippotthS[i]=var[i]+sel+"_sigS";
    }

    const int nqcdsamples=8;
    TFile * QCD[nqcdsamples];
    QCD[0] = new TFile("./root/TDAna_QCD30-50_tk3.root");
    QCD[1] = new TFile("./root/TDAna_QCD50-80_tk3.root");
    QCD[2] = new TFile("./root/TDAna_QCD80-120_tk3.root");
    QCD[3] = new TFile("./root/TDAna_QCD120-170_tk3.root");
    QCD[4] = new TFile("./root/TDAna_QCD170-230_tk3.root");
    QCD[5] = new TFile("./root/TDAna_QCD230-300_tk3.root");
    QCD[6] = new TFile("./root/TDAna_QCD300-380_tk3.root");
    QCD[7] = new TFile("./root/TDAna_QCD380incl_tk3.root");
    double QCDxs[nqcdsamples] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
    double NQCD[nqcdsamples] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};


    const int nwsamples=11;
    TFile * W[nwsamples];
    W[0] = new TFile ("./root/TDAna_W0w_tk3.root");
    W[1] = new TFile ("./root/TDAna_W10w_tk3.root");
    W[2] = new TFile ("./root/TDAna_W11w_tk3.root");
    W[3] = new TFile ("./root/TDAna_W20w_tk3.root");
    W[4] = new TFile ("./root/TDAna_W21w_tk3.root");
    W[5] = new TFile ("./root/TDAna_W30w_tk3.root");
    W[6] = new TFile ("./root/TDAna_W31w_tk3.root");
    W[7] = new TFile ("./root/TDAna_W40w_tk3.root");
    W[8] = new TFile ("./root/TDAna_W41w_tk3.root");
    W[9] = new TFile ("./root/TDAna_W50w_tk3.root");
    W[10] = new TFile ("./root/TDAna_W51w_tk3.root");
    double Wxs[nwsamples] = { 45000., 9200., 250., 2500., 225., 590., 100., 125., 40., 85., 40. };
    double NW[nwsamples] = { 88000., 40000., 100530., 99523., 105255., 79000.,
                             88258., 83038., 30796., 59022., 41865.
                           };

    TFile * TTH = new TFile("./root/TDAna_ttH_120_tk3.root");
    double TTHxs = 0.667 ;
    double NTTH = 1000000.; // 62000.; // 1652000.; // 62000.;

    const int nttsamples=5;
    TFile * TT[nttsamples];
    TT[0] = new TFile("./root/TDAna_TT0_tk3.root");
    TT[1] = new TFile("./root/TDAna_TT1_tk3.root");
    TT[2] = new TFile("./root/TDAna_TT2_tk3.root");
    TT[3] = new TFile("./root/TDAna_TT3_tk3.root");
    TT[4] = new TFile("./root/TDAna_TT4_tk3.root");
    // double TTxs[5] = { 619., 176., 34.,  6., 1.5 };  // from web
    double TTxs[nttsamples] = { 434., 162., 43., 10., 1.9 };     // from note
    double NTT[nttsamples] = { 57900., 66000., 98159., 14768., 5304. };

    double Lumfactor = 100000; // 100/fb of luminosity assumed in histograms

    TH1D * Histo_TOT[nvars];
    TH1D * Histo_TTH[nvars];
    TH1D * Histo_TOTS[nvars];
    TH1D * Histo_TTHS[nvars];
    for ( int i=0; i<nvars; i++ ) {
        cout << i << endl;
        TH1D * H = dynamic_cast<TH1D*>(TTH->Get(pippo[i]));
        double minx=H->GetBinLowEdge(1);
        double maxx=nbins*H->GetBinWidth(1);
        Histo_TOT[i] = new TH1D ( pippotot[i],pippotot[i], nbins, minx, maxx );
        Histo_TTH[i] = new TH1D ( pippotth[i],pippotth[i], nbins, minx, maxx );
        Histo_TOTS[i] = new TH1D ( pippototS[i],pippototS[i], nbins, minx, maxx );
        Histo_TTHS[i] = new TH1D ( pippotthS[i],pippotthS[i], nbins, minx, maxx );
    }

    cout << "Starting loop on variables needing smoothing" << endl;

    // Loop on variables
    // -----------------
    for ( int ivar=0; ivar<nvars; ivar++ ) {

        // Extract sum histograms with the right normalization and errors
        // --------------------------------------------------------------
        double totWW[nwsamples][nbins]= {0.};
        double totW[nbins]= {0.};
        double s2_totW[nbins]= {0.};
        double totNW[nwsamples][nbins]= {0.};
        for ( int i=0; i<nwsamples; i++ ) {
            //cout << "Processing W file #" << i << " ..." << endl;
            TH1D * Histo = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]));
            TH1D * HistoW = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"W"));
            // For W, we need also total entries in histograms to add a
            // Poisson fluke contribution to total errors from matrix:
            // ----------------------------------------------------------
            TH1D * HistoN = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"N"));
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                double t=Histo->GetBinContent(ibin);
                double s2t=HistoW->GetBinContent(ibin);
                double n=HistoN->GetBinContent(ibin);
                totWW[i][ibin-1]+=t*Wxs[i]/NW[i]*Lumfactor;
                s2_totW[ibin-1]+=s2t*pow(Wxs[i]/NW[i]*Lumfactor,2);
                totNW[i][ibin-1]+=n;
            }
        }
        // Once grandtotals of weights are computed for each bin, we can
        // add to the total s2 the Poisson contribution 1/sqrt(N) * T
        // -------------------------------------------------------------
        for ( int i=0; i<nwsamples; i++ ) {
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                totW[ibin-1]+=totWW[i][ibin-1];
                if ( totNW[i][ibin-1]>0 ) {
                    s2_totW[ibin-1]+=pow(totWW[i][ibin-1],2)/totNW[i][ibin-1];
                }
            }
        }

        double totWQCD[nqcdsamples][nbins]= {0.};
        double totQCD[nbins]= {0.};
        double s2_totQCD[nbins]= {0.};
        double totNQCD[nqcdsamples][nbins]= {0.};
        for ( int i=0; i<nqcdsamples; i++ ) {
            //cout << "Processing QCD file #" << i << " ..." << endl;
            TH1D * Histo = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]));
            TH1D * HistoW = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"W"));
            // For QCD, we need also total entries in histograms to add a
            // Poisson fluke contribution to total errors from matrix:
            // ----------------------------------------------------------
            TH1D * HistoN = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"N"));
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                double t=Histo->GetBinContent(ibin);
                double s2t=HistoW->GetBinContent(ibin);
                double n=HistoN->GetBinContent(ibin);
                totWQCD[i][ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
                s2_totQCD[ibin-1]+=s2t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
                totNQCD[i][ibin-1]+=n;
            }
        }
        // Once grandtotals of weights are computed for each bin, we can
        // add to the total s2 the Poisson contribution 1/sqrt(N) * T
        // -------------------------------------------------------------
        for ( int i=0; i<nqcdsamples; i++ ) {
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                totQCD[ibin-1]+=totWQCD[i][ibin-1];
                if ( totNQCD[i][ibin-1]>0 ) {
                    s2_totQCD[ibin-1]+=pow(totWQCD[i][ibin-1],2)/totNQCD[i][ibin-1];
                }
            }
        }

        double totTT[nbins]= {0.};
        double s2_totTT[nbins]= {0.};
        for ( int i=0; i<nttsamples; i++ ) {
            //cout << "Processing TT file #" << i << " ..." << endl;
            TH1D * Histo = dynamic_cast<TH1D*>(TT[i]->Get(pippo[ivar]));
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                double t=Histo->GetBinContent(ibin);
                totTT[ibin-1]+=t*TTxs[i]/NTT[i]*Lumfactor;
                s2_totTT[ibin-1]+=t*pow(TTxs[i]/NTT[i]*Lumfactor,2);
            }
        }
        double totTTH[nbins]= {0.};
        double s2_totTTH[nbins]= {0.};
        //cout << "Processing TTH file " << " ..." << endl;
        TH1D * Histo = dynamic_cast<TH1D*>(TTH->Get(pippo[ivar]));
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            double t=Histo->GetBinContent(ibin);
            totTTH[ibin-1]+=t*TTHxs/NTTH*Lumfactor;
            s2_totTTH[ibin-1]+=t*pow(TTHxs/NTTH*Lumfactor,2);
        }

        // OK now fill total histograms
        // ----------------------------
        double total_sig=0.;
        double total_bgr=0.;
        double grandtot[nbins]= {0.};
        double grandtote[nbins]= {0.};
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            Histo_TTH[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
            Histo_TTH[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
            Histo_TTHS[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
            Histo_TTHS[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
            grandtot[ibin-1] = totQCD[ibin-1]+totTT[ibin-1]+totW[ibin-1];
            grandtote[ibin-1]= sqrt(s2_totQCD[ibin-1]+s2_totTT[ibin-1]+s2_totW[ibin-1]);
            Histo_TOT[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
            Histo_TOT[ivar]->SetBinError(ibin,grandtote[ibin-1]);
            Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
            Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]);
            total_sig+=totTTH[ibin-1];
            total_bgr+=grandtot[ibin-1];
        }

        // Preliminary: we set to zero bins with less than 0.01% of the integral
        // ---------------------------------------------------------------------
        for ( int ibin=0; ibin<nbins; ibin++ ) {
            if ( grandtot[ibin]/total_bgr<0.0001 ) grandtot[ibin]=0.;
        }
        // Pre-pre-smoothing: kill bins with abnormally large errors,
        // replace with average of neighbors
        // ----------------------------------------------------------
        double averror=0.;
        double nav=0.;
        for ( int ibin=0; ibin<nbins; ibin++ ) {
            if ( grandtot[ibin]>0 && grandtote[ibin]>0 ) {
                averror+=grandtote[ibin]/grandtot[ibin];
                nav++;
            }
        }
        if ( nav>0 ) {
            averror=averror/nav;
            double err;
            double nlterr[100]= {0.};
            double max67pc;
            int i67=-1;
            for ( int i=0; i<100 && i67==-1; i++ ) {
                err=2*averror/100.*(double)i;
                for ( int ibin=0; ibin<nbins; ibin++ ) {
                    if ( grandtot[ibin]>0 && grandtote[ibin]>0 ) {
                        if ( grandtote[ibin]/grandtot[ibin]<err ) nlterr[i]++;
                    }
                }
                nlterr[i]=nlterr[i]/nav;
                if ( nlterr[i]>frac_true_err ) {
                    max67pc=err;
                    i67=i;
                }
            }
            cout << "var#" << ivar<< " averror=" << averror << " nav=" <<nav << " max67pc=" << max67pc << endl;

            // Ok now we know which bins to disregard. Let us correct them:
            // ------------------------------------------------------------
            int inext;
            int iprev;
            for ( int ibin=0; ibin<nbins; ibin++ ) {
                if ( grandtot[ibin]>0. && grandtote[ibin]>0. ) {
                    if ( grandtote[ibin]/grandtot[ibin]>2*max67pc ) { // consider this bin for smoothing
                        if ( ibin==0 ) {
                            inext=0;
                            // look at the three next ones
                            // ---------------------------
                            for ( int jbin=ibin+1; jbin<ibin+4 && inext==0; jbin++ ) {
                                if ( grandtot[jbin]>0. && grandtote[jbin]>0. ) {
                                    if ( grandtote[jbin]/grandtot[jbin]<2*max67pc ) inext=jbin;
                                }
                            }
                            if ( inext==0 ) inext=1;
                            iprev=inext;
                        } else if ( ibin<nbins-1 && ibin>0 ) {
                            iprev=ibin-1;
                            inext=0;
                            // look at the three next ones
                            // ---------------------------
                            for ( int jbin=ibin+1; jbin<ibin+4 && jbin<nbins && inext==0; jbin++ ) {
                                if ( grandtot[jbin]>0. && grandtote[jbin]>0. ) {
                                    if ( grandtote[jbin]/grandtot[jbin]<2*max67pc ) inext=jbin;
                                }
                            }
                            if ( inext==0 ) inext=iprev;
                        } else if ( ibin==nbins-1 ) {
                            iprev=ibin-1;
                            inext=ibin-1;
                        }
                        // Compute new value of bin, taking into account the prescription that
                        // when averaging, an average of x and zero is given value zero.
                        // Also, do not replace bins which are consistent with their neighbors
                        // within the errors in the average of the latter
                        // ------------------------------------------------------------------
                        if ( grandtot[iprev]>0. && grandtot[inext]>0. ) {
                            double av = (grandtot[iprev]+grandtot[inext])/2;
                            double s_av = sqrt((pow(grandtote[iprev],2)+pow(grandtote[inext],2))/4.);
                            if ( fabs(grandtot[ibin]-av)>s_av ) {
                                grandtot[ibin]=av;
                                grandtote[ibin]=s_av;
                            }
                        } else {
                            grandtot[ibin]=0.;
                            grandtote[ibin]=sqrt((pow(grandtote[iprev],2)+pow(grandtote[inext],2))/4.);
                        }
                    }
                }
            }
        }
        double total_bgr_s=0.;
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            total_bgr_s+=grandtot[ibin-1];
            Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
            Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]);
        }

        // Now do the regular smoothing
        // ----------------------------
        //Histo_TOTS[ivar]->Smooth(1);
        //Histo_TTHS[ivar]->Smooth(1);
        double sumtot=0.;
        double sumtth=0.;
        double sumtotS=0.;
        double sumtthS=0.;
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            sumtotS+=Histo_TOTS[ivar]->GetBinContent(ibin);
            sumtthS+=Histo_TTHS[ivar]->GetBinContent(ibin);
            sumtot+=Histo_TOT[ivar]->GetBinContent(ibin);
            sumtth+=Histo_TTH[ivar]->GetBinContent(ibin);
        }
        if ( sumtotS>0 ) Histo_TOTS[ivar]->Scale(1./sumtotS);
        if ( sumtthS>0 ) Histo_TTHS[ivar]->Scale(1./sumtthS);
        if ( sumtot>0 ) Histo_TOT[ivar]->Scale(1./sumtot);
        if ( sumtth>0 ) Histo_TTH[ivar]->Scale(1./sumtth);

    } // end of ivar loop

    cout << "Done, now plotting and writing histos." << endl;

// File where smoothed histos are stored
// -------------------------------------
    TString fname;
    fname="functionfile" + sel + ".root";
    TFile * Smoothed = new TFile(fname,"RECREATE");
    Smoothed->cd();

    TCanvas * b1 = new TCanvas ("b1", "Kinematics comparison", 600, 600 );
    b1->Divide(2,4);
    for ( int ivar=0; ivar<8; ivar++ ) {
        b1->cd(ivar+1);
        Histo_TOTS[ivar]->SetMinimum(0.);
        Histo_TOTS[ivar]->Draw();
        Histo_TTHS[ivar]->SetLineColor(kBlue);
        Histo_TTHS[ivar]->Draw("PESAME");
    }
    b1->Print("./ps/Smooth_svsb_1.ps");
    TCanvas * b2 = new TCanvas ("b2", "Kinematics comparison", 600, 600 );
    b2->Divide(2,4);
    for ( int ivar=8; ivar<16; ivar++ ) {
        b2->cd(ivar-7);
        Histo_TOTS[ivar]->SetMinimum(0.);
        Histo_TOTS[ivar]->Draw();
        Histo_TTHS[ivar]->SetLineColor(kBlue);
        Histo_TTHS[ivar]->Draw("PESAME");
    }
    b2->Print("./ps/Smooth_svsb_2.ps");
    TCanvas * b3 = new TCanvas ("b3", "Kinematics comparison", 600, 600 );
    b3->Divide(2,4);
    for ( int ivar=16; ivar<nvars; ivar++ ) {
        b3->cd(ivar-15);
        Histo_TOTS[ivar]->SetMinimum(0.);
        Histo_TOTS[ivar]->Draw();
        Histo_TTHS[ivar]->SetLineColor(kBlue);
        Histo_TTHS[ivar]->Draw("PESAME");
    }
    b3->Print("./ps/Smooth_svsb_3.ps");

    TCanvas * c1 = new TCanvas ("c1", "Kinematics comparison", 600, 600 );
    c1->Divide(2,4);
    for ( int ivar=0; ivar<8; ivar++ ) {
        c1->cd(ivar+1);
        Histo_TOT[ivar]->SetMinimum(0.);
        Histo_TOT[ivar]->SetLineColor(kRed);
        Histo_TOT[ivar]->Draw("PE");
        Histo_TOTS[ivar]->Draw("PESAME");
        Histo_TOT[ivar]->Write();
        Histo_TTH[ivar]->Write();
        Histo_TOTS[ivar]->Write();
        Histo_TTHS[ivar]->Write();
    }
    c1->Print("./ps/Smooth_check_1.ps");
    TCanvas * c2 = new TCanvas ("c2", "Kinematics comparison", 600, 600 );
    c2->Divide(2,4);
    for ( int ivar=8; ivar<16; ivar++ ) {
        c2->cd(ivar-7);
        Histo_TOT[ivar]->SetMinimum(0.);
        Histo_TOT[ivar]->SetLineColor(kRed);
        Histo_TOT[ivar]->Draw("PE");
        Histo_TOTS[ivar]->Draw("PESAME");
        Histo_TOT[ivar]->Write();
        Histo_TTH[ivar]->Write();
        Histo_TOTS[ivar]->Write();
        Histo_TTHS[ivar]->Write();
    }
    c2->Print("./ps/Smooth_check_2.ps");
    TCanvas * c3 = new TCanvas ("c3", "Kinematics comparison", 600, 600 );
    c3->Divide(2,4);
    for ( int ivar=16; ivar<nvars; ivar++ ) {
        c3->cd(ivar-15);
        Histo_TOT[ivar]->SetMinimum(0.);
        Histo_TOT[ivar]->SetLineColor(kRed);
        Histo_TOT[ivar]->Draw("PE");
        Histo_TOTS[ivar]->Draw("PESAME");
        Histo_TOT[ivar]->Write();
        Histo_TTH[ivar]->Write();
        Histo_TOTS[ivar]->Write();
        Histo_TTHS[ivar]->Write();
    }
    c3->Print("./ps/Smooth_check_3.ps");

    Smoothed->Close();

}
Example #14
0
void Z0AccEff(int isData = 2, int yieldInt = 1, int iSpec = 3, int Weight =1)
{
  ////////  definitions of Switches   ///////////
  //  isData = 1 for Data
  //  isData = 2 for Simulation
  
    
  // iSpec = 1  pT spectra
  // iSpec = 2  Y spectra
  // iSpec = 3  Centrality Spectra
  
  //Weight = 1 for weighted histo
  //weight = 0  for non weighted histo



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

  // Fit ranges
  float mass_low, mass_high, mlow, mhigh;
  int nrebin;
  bool isLog, isFit;
  double MassZ0, WidthZ0;

  // High Mass range
  MassZ0 = 91.1876; WidthZ0 = 2.4952;
  mass_low = 60; mass_high = 120;  // Fit ranges Glb Glb
  //mass_low = 40; mass_high = 140;  // Fit ranges STA
  mlow = 0.0; mhigh = 200.0; nrebin = 80; isLog =0; isFit = 0; // draw ranges
  
  int whis = 1; // 1 for full all eta, 2 for barrel  //4 for trigger matched PAT
  
  //file one is good file

  TFile *fil1, *fil2;

  if (isData == 2) fil2 = new TFile("Z0_DataMixPt50_PatDiMuonPlots_All11Dec.root");
  //if (isData == 2) fil2 = new TFile("ReReco_DM_DiMuonPlot_All16Dec.root");
  if (isData == 2)  fil1 = new TFile("Z0HydPt50_PatDiMuonPlots_AllWOSel12Dec.root");

  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  
  if(iSpec == 1) { 
    Nptbin = 3;
    pt_bound[0] = 0.0; pt_bound[1] = 6.0;
    pt_bound[2] = 12.0; pt_bound[3] = 100.0;
    
    if(isData == 2) {
      Nptbin = 25;
      // pt_bound[100] = {0.0,100.0,12.0,100.0};
      pt_bound[0] = 0;
      pt_bound[1] = 2;
      pt_bound[2] = 4;
      pt_bound[3] = 6;
      pt_bound[4] = 8;
      pt_bound[5] = 10;
      pt_bound[6] = 12;
      pt_bound[7] = 14;
      pt_bound[8] = 16;
      pt_bound[9] = 18;
      pt_bound[10] = 20;
      pt_bound[11] = 22;
      pt_bound[12] = 24;
      pt_bound[13] = 26;
      pt_bound[14] = 28;
      pt_bound[15] = 30;
      pt_bound[16] = 32;
      pt_bound[17] = 34;
      pt_bound[18] = 36;
      pt_bound[19] = 38;
      pt_bound[20] = 40;
      pt_bound[21] = 42;
      pt_bound[22] = 44;
      pt_bound[23] = 46;
      pt_bound[24] = 48;
      pt_bound[25] = 50;
    }
  }
  
  // Y bin sizes
  if(iSpec == 2) {
    Nptbin = 10;
    // pt_bound[100] = {-2.4,-1.0,-0.5,0.5,1.0,2.4}; 
    // pt_bound[100] = {-2.4,-1.0,-0.5,0.5,1.0,2.4}; 
    // pt_bound[100] = {-2.4,-2.1,-1.6,-1.1,-0.6,0,0.6,1.1,1.6,2.1,2.4}; 
    pt_bound[0] = -2.4; 
    pt_bound[1] = -2.1; 
    pt_bound[2] = -1.6; 
    pt_bound[3] = -1.1; 
    pt_bound[4] = -0.6; 
    pt_bound[5] =  0.0; 
    pt_bound[6] = 0.6; 
    pt_bound[7] = 1.1; 
    pt_bound[8] = 1.6; 
    pt_bound[9] = 2.1; 
    pt_bound[10] = 2.4; 

  }
  
  if(iSpec == 3) {
    if(isData == 2) { 
      Nptbin = 9;
      pt_bound[0] = 0.0;
      pt_bound[1] = 4.0;
      pt_bound[2] = 8.0;
      pt_bound[3] = 12.0;
      pt_bound[4] = 16.0;
      pt_bound[5] = 20.0;
      pt_bound[6] = 24.0;
      pt_bound[7] = 28.0;
      pt_bound[8] = 32.0;
      pt_bound[9] = 40.0;
    }
  }
  
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  float gen_pt[100], gen_ptError[100];
  float gen_ptS[100], gen_ptErrorS[100];
  
  if(isData==2){

    TH2D *genMass_1, *genMassS_1;

    if (iSpec == 1 &&  Weight==1 ) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsPtW");
    if (iSpec == 2 &&  Weight==1) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsYW");
    if (iSpec == 3 &&  Weight==1) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsCenW");
    
    if (iSpec == 1 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsPtW");
    if (iSpec == 2 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsYW");
    if (iSpec == 3 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsCenW");
    
    if (iSpec == 1 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsPt");
    if (iSpec == 2 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsY");
    if (iSpec == 3 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsCen");


    if (iSpec == 1 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsPt");
    if (iSpec == 2 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsY");
    if (iSpec == 3 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsCen");

    TH1D *ptaxis = (TH1D*)genMass_1->ProjectionY("ptaxis");
    
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      cout<<pt_bound[ih]<<"  "<<pt_bound[ih+1]<<endl;
      int pt_bin1 = ptaxis->FindBin(pt_bound[ih]+0.0000001);
      int pt_bin2 = ptaxis->FindBin(pt_bound[ih+1]+0.0000001);
      
      cout<< pt_bin1<<"  "<< pt_bin2<<endl; 
      TH1D * genMassVsPt = (TH1D*)genMass_1->ProjectionX("genMassVsPt", pt_bin1, pt_bin2-1);
      TH1D * genMassVsPtS = (TH1D*)genMassS_1->ProjectionX("genMassVsPtS", pt_bin1, pt_bin2-1);
      
      //does not work with weight
      //gen_pt[ih] = genMassVsPt->GetEntries();
      
      double genError,genErrorS;
      gen_pt[ih] = genMassVsPt->IntegralAndError(1,8000,genError);
      gen_ptError[ih]= genError;
      
      gen_ptS[ih] = genMassVsPtS->IntegralAndError(1,8000,genErrorS);
      gen_ptErrorS[ih]= genErrorS;
      
      cout<<" gen entries : "<< gen_pt[ih]<<endl;
      cout<<"genErro "<<genError<<"  "<< gen_ptError[ih]<<endl<<endl;
    }
  }
  
  // Efficiency
  float Eff_cat_1[100]; 
  float Eff_catS_1[100]; 
  
  float errEff_cat_1[100];
  float errEff_catS_1[100];
  
  float errEff_cat_S1[100], errEff_cat_S2[100];
  float errEff_catS_S1[100], errEff_catS_S2[100];
  
  char *Xname[100] = {" ", "p_{T}^{Dimuon} (GeV/c)", "rapidity", "centrality"};
  
  double yld_cat_1[100];
  double yld_catS_1[100];
  double cyld_cat_1[100];
  double cyld_catS_1[100];
  double eyld_cat_1[100];
  double eyld_catS_1[100];
  double ceyld_cat_1[100], ceyld_catS_1[100];

  char namePt_1[500];
  char namePt_1S[500];
  //char namePt_1B[500];
  char text[100];
  
  ///// Write the spectra 
  char fspectra[500];
  sprintf(fspectra,"fileSpecta%d.root", yieldInt);
  TFile *fileSpectra = new TFile(fspectra, "recreate");

  ///////////////////////////////////////////////////////////////////////
  // Category _1 
  TLegend *lcat_1;
  lcat_1 = new TLegend(.1, .82, .50, .93);
  lcat_1->SetName("lcat_1");
  lcat_1->SetBorderSize(0);
  lcat_1->SetFillStyle(0);
  lcat_1->SetFillColor(0);
  lcat_1->SetTextSize(0.032);
  //lcat_1->AddEntry(RBWPOL," CMS Preliminary", " ");
  //lcat_1->AddEntry(RBWPOL," PbPb #sqrt{s_{NN}} = 2.76 TeV ", " ");
  
  TLegend *legend_1[100];
  for(int i=0; i<100; i++) { 
    if(isFit) legend_1[i] = new TLegend(.62, .52, .91, 0.93 );
    if(!isFit) legend_1[i] = new TLegend(.62, .68, .91, 0.93 );
    legend_1[i]->SetBorderSize(0);
    legend_1[i]->SetFillStyle(0);
    legend_1[i]->SetFillColor(0);
    legend_1[i]->SetTextSize(0.032);
  }
  
  //for no cut
  //if(whis == 1 && iSpec == 1 ) TH2D *Z0Mass_1 = (TH2D*)fil1->Get("dimu");
  //if(whis == 2 && iSpec == 1) TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPtBRL");
  //if(whis == 4 && iSpec == 1 ) {
    //TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsPATInvMassVsPt");
    //TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsPATSTAInvMassVsPt");
  //}



  TH2D *Z0Mass_1, *Z0Mass_1S;

  //with weight

  if(iSpec == 1 &&  Weight==1 ) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPtW");
  if(iSpec == 2 &&  Weight==1) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsYW");
  if(iSpec == 3 &&  Weight==1) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsCenW");


  //without weight
  if(iSpec == 1  &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPt");
  if(iSpec == 2 &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsY");
  if(iSpec == 3 &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsCen");
      
  //with weight fil2
  if(iSpec == 1  &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsPtW");
  if(iSpec == 2 &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsYW");
  if(iSpec == 3 &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsCenW");

  //without weight fil2
  if(iSpec == 1 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsPt");
  if(iSpec == 2 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsY");
  if(iSpec == 3 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsCen");
  
  TH1D *service = (TH1D*)Z0Mass_1->ProjectionY("service");
  int pt_bin_bound[100];
  TH1D *dimuonsGlobalInvMassVsPt[100],  *dimuonsGlobalInvMassVsPtS[100];
  
  TCanvas *CanvPt_1 = new TCanvas("CanvPt_1"," Z0 Yield Vs. Pt ", 40,40,1000,700);
  if (Nptbin == 2)  CanvPt_1->Divide(2,1);
  if (Nptbin == 3 || Nptbin == 4)  CanvPt_1->Divide(2,2);
  if (Nptbin == 5 || Nptbin == 6)  CanvPt_1->Divide(3,2);
  if (Nptbin == 9 || Nptbin == 10)  CanvPt_1->Divide(5,2);
  cout << endl << Xname[iSpec] << "    Yield      Mass (GeV)    Width (GeV)    GauWidth    chi2/ndf " << endl << endl; 
  //ih loop
  for (Int_t ih = 0; ih < Nptbin; ih++) 
    {
      CanvPt_1->cd(ih+1);
      gPad->SetTickx();
      gPad->SetTicky();
      
      // Project 1 D 
      pt_bin_bound[ih] = Z0Mass_1->GetYaxis()->FindBin(pt_bound[ih]+0.0000001);
      pt_bin_bound[ih+1] = Z0Mass_1->GetYaxis()->FindBin(pt_bound[ih+1]-0.0000001);
      sprintf(namePt_1,"Z0_1_pt_%d",ih);
      sprintf(namePt_1S,"Z0_1S_pt_%d",ih);
      
      //printf(namePt_1,"Z0_1_pt_%d",ih);
      //cout<<endl<<endl;
      //continue;
      
      dimuonsGlobalInvMassVsPt[ih] = (TH1D*)Z0Mass_1->ProjectionX(namePt_1, pt_bin_bound[ih], pt_bin_bound[ih+1]-1+1, "e");
      dimuonsGlobalInvMassVsPtS[ih] = (TH1D*)Z0Mass_1S->ProjectionX(namePt_1S, pt_bin_bound[ih], pt_bin_bound[ih+1]-1+1,"e");
      if(iSpec == 1 || iSpec == 2) {sprintf(text," %s [%.1f, %.1f]", Xname[iSpec], service->GetBinLowEdge(pt_bin_bound[ih]), 
					    service->GetBinLowEdge(pt_bin_bound[ih+1])+service->GetBinWidth(pt_bin_bound[ih+1]));}
      if(iSpec == 3) {sprintf(text," %s [%.1f, %.1f] %s", Xname[iSpec], 2.5*service->GetBinLowEdge(pt_bin_bound[ih]), 
			      2.5*(service->GetBinLowEdge(pt_bin_bound[ih+1])+service->GetBinWidth(pt_bin_bound[ih+1])), "%");}
      
      dimuonsGlobalInvMassVsPt[ih]->Rebin(nrebin);
      dimuonsGlobalInvMassVsPtS[ih]->Rebin(nrebin);
      
      float m_low = 60.0;
      float m_high = 120.0;
      
      TAxis *axs   = dimuonsGlobalInvMassVsPt[ih]->GetXaxis();
      int binlow = axs->FindBin(m_low);
      int binhi  = axs->FindBin(m_high);
      //      Double_t bin_size = (1.0*dimuonsGlobalInvMassVsPt[ih]->GetNbinsX())/(axs->GetXmax() - axs->GetXmin());
      //    Float_t int_sig = 0.0;
      //for(Int_t bin = binlow; bin<=binhi;bin++) {
      //int_sig+ = dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);
      //}   
      double recerror,recerrorS;
      //double yld;
      double yld_1 = dimuonsGlobalInvMassVsPt[ih]->IntegralAndError(binlow, binhi, recerror);
      double yldS_1 = dimuonsGlobalInvMassVsPtS[ih]->IntegralAndError(binlow, binhi, recerrorS); 
      eyld_cat_1[ih] =recerror;
      eyld_catS_1[ih] =recerrorS;
      cout<< "yld " << yld_1 <<"  eyld_cat_1[ih]  "<< eyld_cat_1[ih]<<" rec error "<<recerror<<endl;
      
      yld_cat_1[ih] = yld_1;
      yld_catS_1[ih] = yldS_1;
      
      if(isLog) gPad->SetLogy(1);
      TColor *pal = new TColor();
      Int_t kblue = pal->GetColor(9,0,200);
      //      Int_t korange  = pal->GetColor(101, 42,  0);
      
      dimuonsGlobalInvMassVsPt[ih]->SetMarkerStyle(21);
      dimuonsGlobalInvMassVsPt[ih]->SetMarkerColor(kblue);
      dimuonsGlobalInvMassVsPt[ih]->SetLineColor(kblue);
      dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetTitle("Dimuon mass (GeV/c^{2})");
      dimuonsGlobalInvMassVsPt[ih]->GetYaxis()->SetTitle("Events/(2 GeV/c^{2})");
      dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetRangeUser(mlow,mhigh);
      dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPL");
      // fil2
      dimuonsGlobalInvMassVsPtS[ih]->SetMarkerStyle(8);
      dimuonsGlobalInvMassVsPtS[ih]->SetMarkerColor(46);
      dimuonsGlobalInvMassVsPtS[ih]->SetLineColor(46);
      //****** dimuonsGlobalInvMassVsPtS[ih]->DrawCopy("EPsame");
      //RBWPOL->SetLineColor(kblue);
      //backfun_1->SetLineColor(46);
      //backfun_1->SetLineWidth(1);
      //if(isFit) backfun_1->Draw("same");
      lcat_1->Draw("same"); 
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih],"Global-Global", " ");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," |y| < 2.4 ", "");  
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], text, "");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Opposite Charge ", "LP");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPtS[ih]," Same Charge ", "LP");
      char label_1[512];
      //      char label_2[512], label_3[512], label_4[512];
      sprintf(label_1, "N=%1.2f #pm %1.2f ", yld_cat_1[ih], eyld_cat_1[ih]);
      //    sprintf(label_1, "N_{Z^{0}} = 27");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], label_1, "");
    }//ih loop
  cout << endl << endl;
  CanvPt_1->Print("Pt_Z0MassCat_1.png");
  
  TGraphErrors *Z0pt_cat_1 = new TGraphErrors(Nptbin, PT, yld_cat_1, mom_err, eyld_cat_1);
  Z0pt_cat_1->SetMarkerStyle(20);
  Z0pt_cat_1->SetMarkerColor(2);
  Z0pt_cat_1->GetXaxis()->SetTitle(Xname[iSpec]);
  Z0pt_cat_1->GetYaxis()->SetTitle("counts");

  new TCanvas;
  Z0pt_cat_1->SetMinimum(0.0);
  Z0pt_cat_1->SetName("Z0pt_cat_1");
  Z0pt_cat_1->Draw("AP");
  lcat_1->Draw("same"); 
  gPad->Print("Pt_Z0YieldCat_1.png");
  cout << endl << endl;
  Z0pt_cat_1->Write();
  lcat_1->Write();
  
  // Efficiency correction
  if(isData==2) 
    {
       ofstream fileout("correction.txt");
       cout << Xname[iSpec] << "   Eff_cat_1  " << endl;
       
       for (Int_t ih = 0; ih < Nptbin; ih++) {
      	//cout<<"gen_pt[ih];  "<<gen_pt[ih]<<endl;
	 Eff_cat_1[ih] = yld_cat_1[ih]/gen_pt[ih]; 
	 Eff_catS_1[ih] = yld_catS_1[ih]/gen_ptS[ih]; 
	 //eyld_cat_1[ih];
	 //gen_ptError[ih];
	 //cout<<endl<<endl<<endl;
	//cout<<"Eff_cat_1[ih] "<<Eff_cat_1[ih]<<endl;
	//cout<<"yld_cat_1[ih] "<< yld_cat_1[ih] <<endl;
	//cout<<"eyld_cat_1[ih] "<<eyld_cat_1[ih] <<endl;
	//cout<<"gen_pt[ih]    "<< gen_pt[ih] <<endl;
	//cout<<"gen_ptError[ih] "<< gen_ptError[ih]<<endl;
	 //Error for first graph
	 double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
	 double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
	 errEff_cat_S1_1[ih]= ( (Eff_cat_1[ih] * Eff_cat_1[ih]) /(gen_pt[ih] * gen_pt[ih]) );
	 errEff_cat_S1_2[ih]= (gen_ptError[ih] * gen_ptError[ih] ) - ( eyld_cat_1[ih] * eyld_cat_1[ih] );
	 errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
	 //cout<<" errEff_cat_S1_1[ih] "<<	errEff_cat_S1_1[ih]<< " errEff_cat_S1_2[ih] "<<errEff_cat_S1_2[ih]<<endl;
	 errEff_cat_S2_1[ih]= ( (1 - Eff_cat_1[ih])* (1 - Eff_cat_1[ih]) ) / ( gen_pt[ih] * gen_pt[ih]);
	 errEff_cat_S2_2[ih]= (eyld_cat_1[ih] * eyld_cat_1[ih]);
	 errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
	 //cout<<" errEff_cat_S2_1[ih] "<<	errEff_cat_S2_1[ih]<< " errEff_cat_S2_2[ih] "<<errEff_cat_S2_2[ih]<<endl;
	 //cout<<"errEff_cat_S1[ih]    "<<errEff_cat_S1[ih]<< " errEff_cat_S2[ih]   "<< errEff_cat_S2[ih]<<endl;	
	 errEff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
	 
	 //Error for second graph
	 double errEff_catS_S1_1[100]={0},errEff_catS_S1_2[100]={0};
	 double errEff_catS_S2_1[100]={0},errEff_catS_S2_2[100]={0};
	 errEff_catS_S1_1[ih]= ( (Eff_catS_1[ih] * Eff_catS_1[ih]) /(gen_ptS[ih] * gen_ptS[ih]) );
	 errEff_catS_S1_2[ih]= (gen_ptErrorS[ih] * gen_ptErrorS[ih] ) - (eyld_catS_1[ih] * eyld_catS_1[ih] );
	 errEff_catS_S1[ih]= (errEff_catS_S1_1[ih] * errEff_catS_S1_2[ih]);
	 errEff_catS_S2_1[ih]= ( (1 - Eff_catS_1[ih])* (1 - Eff_catS_1[ih]) ) / ( gen_ptS[ih] * gen_ptS[ih]);
	 errEff_catS_S2_2[ih]= (eyld_catS_1[ih] * eyld_catS_1[ih]);
	 errEff_catS_S2[ih]= errEff_catS_S2_1[ih]*errEff_catS_S2_2[ih];
	 errEff_catS_1[ih]=sqrt(errEff_catS_S1[ih] + errEff_catS_S2[ih]);
	 //Error for no weight
	 //errEff_cat_1[ih] =((Eff_cat_1[ih]*(1- Eff_cat_1[ih]))/gen_pt[ih]);
	 //Prashant error
	 //errEff_cat_1[ih] = eyld_cat_1[ih]/gen_pt[ih]; 
	 fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << errEff_cat_1[ih] << endl; 
	 cout <<"    " << PT[ih] <<"    "<< Eff_cat_1[ih] << " +- " << errEff_cat_1[ih] << endl;
	 cyld_cat_1[ih] = Eff_cat_1[ih];
	 ceyld_cat_1[ih] = errEff_cat_1[ih];
	 cyld_catS_1[ih] = Eff_catS_1[ih];
	 ceyld_catS_1[ih] = errEff_catS_1[ih];
       }
    }
  
  TGraphErrors *Z0ptC_cat_1 = new TGraphErrors(Nptbin, PT, cyld_cat_1, mom_err, ceyld_cat_1);
  Z0ptC_cat_1->SetMarkerStyle(20);
  Z0ptC_cat_1->SetMarkerColor(2);
  Z0ptC_cat_1->GetXaxis()->SetTitle(Xname[iSpec]);
  Z0ptC_cat_1->GetYaxis()->SetTitle("Acc #times Eff");
  Z0ptC_cat_1->GetYaxis()->SetRangeUser(0,1.0);

  TGraphErrors *Z0ptC_catS_1 = new TGraphErrors(Nptbin, PT, cyld_catS_1, mom_err, ceyld_catS_1);
  Z0ptC_catS_1->SetMarkerStyle(8);
  Z0ptC_catS_1->SetMarkerColor(1);
  Z0ptC_catS_1->GetYaxis()->SetRangeUser(0,0.8);
  
  TLegend *legend_GP = new TLegend( 0.59,0.79,0.88,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  //legend_GP->AddEntry(Z0ptC_catS_1,"Pythia Gun in MB HI Data ", "");
  legend_GP->AddEntry(Z0ptC_catS_1,"Pythia Gun in MB Hydjet ", "");
  new TCanvas;
  Z0ptC_cat_1->SetMinimum(0.0);
  Z0ptC_cat_1->Draw("AP");
  //Z0ptC_catS_1->Draw("sameP");
  lcat_1->Draw("same"); 
  legend_GP->Draw("same");
  cout << endl << endl;
  Z0ptC_cat_1->Write();
}
TH1D * getNiceHistogram(int nbins, std::vector<Double_t> binning, TFile * file, TString hist) {
  TH1D *sample = (TH1D*)(file->Get(hist)->Clone());
  TH1D *binned = dynamic_cast<TH1D*>(sample->Rebin(nbins,"madgraph",&binning.front()));
  for (Int_t bin=0; bin < nbins; bin++) {
    // Divide rebinned histogram's bin content by bin width factor (new/old):
    binned->SetBinError(bin+1,sqrt(binned->GetBinContent(bin+1))/((binning.at(bin+1)-binning.at(bin))/sample->GetBinWidth(1)));
    binned->SetBinContent(bin+1,binned->GetBinContent(bin+1)/((binning.at(bin+1)-binning.at(bin))/sample->GetBinWidth(1)));
  }
  binned->Scale(1/binned->Integral("width"));
  return binned;
}
Example #16
0
void Smooth (TString sel) 
{

  const int nbins = 50;

  const int nvars=17;
  TString var[nvars] = { "C8", "M8", "C6", "M6", "MEt", "MEtSig", "CorrSumEt", "GoodHt", 
		      "M45bestall", "Chi2mass", "Chi2extall", "Mbbnoh", "DPbbnoh", 
		      "SumHED4", "SumHED6", "DP12", "MEtDP2" };
  TString pippo[nvars];
  TString pippotot[nvars];
  TString pippotth[nvars];
  TString pippototS[nvars];
  TString pippotthS[nvars];
  for ( int i=0; i<nvars; i++ ) { 
    pippo[i] = var[i]+sel; 
    pippotot[i]=var[i]+sel+"_bgr";
    pippotth[i]=var[i]+sel+"_sig";
    pippototS[i]=var[i]+sel+"_bgrS";
    pippotthS[i]=var[i]+sel+"_sigS";
  }
  
  const int nqcdsamples=8;
  TFile * QCD[nqcdsamples];     
  QCD[0] = new TFile("./root/et30_eta2.5/TDAna_QCD30-50_tk3.root");
  QCD[1] = new TFile("./root/et30_eta2.5/TDAna_QCD50-80_tk3.root");
  QCD[2] = new TFile("./root/et30_eta2.5/TDAna_QCD80-120_tk3.root");
  QCD[3] = new TFile("./root/et30_eta2.5/TDAna_QCD120-170_tk3.root");
  QCD[4] = new TFile("./root/et30_eta2.5/TDAna_QCD170-230_tk3.root");
  QCD[5] = new TFile("./root/et30_eta2.5/TDAna_QCD230-300_tk3.root");
  QCD[6] = new TFile("./root/et30_eta2.5/TDAna_QCD300-380_tk3.root");
  QCD[7] = new TFile("./root/et30_eta2.5/TDAna_QCD380incl_tk3.root");
  double QCDxs[nqcdsamples] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
  double NQCD[nqcdsamples] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};


  const int nwsamples=11;
  TFile * W[nwsamples];
  W[0] = new TFile ("./root/et30_eta2.5/TDAna_W0w_tk3.root");
  W[1] = new TFile ("./root/et30_eta2.5/TDAna_W10w_tk3.root");
  W[2] = new TFile ("./root/et30_eta2.5/TDAna_W11w_tk3.root");
  W[3] = new TFile ("./root/et30_eta2.5/TDAna_W20w_tk3.root");
  W[4] = new TFile ("./root/et30_eta2.5/TDAna_W21w_tk3.root");
  W[5] = new TFile ("./root/et30_eta2.5/TDAna_W30w_tk3.root");
  W[6] = new TFile ("./root/et30_eta2.5/TDAna_W31w_tk3.root");
  W[7] = new TFile ("./root/et30_eta2.5/TDAna_W40w_tk3.root");
  W[8] = new TFile ("./root/et30_eta2.5/TDAna_W41w_tk3.root");
  W[9] = new TFile ("./root/et30_eta2.5/TDAna_W50w_tk3.root");
  W[10] = new TFile ("./root/et30_eta2.5/TDAna_W51w_tk3.root");
  double Wxs[nwsamples] = { 45000., 9200., 250., 2500., 225., 590., 100., 125., 40., 85., 40. };
  double NW[nwsamples] = { 88000., 40000., 100530., 99523., 105255., 79000., 
			   88258., 83038., 30796., 59022., 41865. };

  TFile * TTH = new TFile("./root/et30_eta2.5/TDAna_ttH_120_tk3.root");
  double TTHxs = 0.667 ;
  double NTTH = 62000.; // 1652000.; // 62000.;

  const int nttsamples=5;
  TFile * TT[nttsamples];
  TT[0] = new TFile("./root/et30_eta2.5/TDAna_TT0_tk3.root");
  TT[1] = new TFile("./root/et30_eta2.5/TDAna_TT1_tk3.root");
  TT[2] = new TFile("./root/et30_eta2.5/TDAna_TT2_tk3.root");
  TT[3] = new TFile("./root/et30_eta2.5/TDAna_TT3_tk3.root");
  TT[4] = new TFile("./root/et30_eta2.5/TDAna_TT4_tk3.root");
  // double TTxs[5] = { 619., 176., 34.,  6., 1.5 };  // from web
  double TTxs[nttsamples] = { 434., 162., 43., 10., 1.9 };     // from note
  double NTT[nttsamples] = { 57900., 66000., 98159., 14768., 5304. };

  double Lumfactor = 100000; // 100/fb of luminosity assumed in histograms

  TH1D * Histo_TOT[nvars];
  TH1D * Histo_TTH[nvars];
  TH1D * Histo_TOTS[nvars];
  TH1D * Histo_TTHS[nvars];
  for ( int i=0; i<nvars; i++ ) {
    cout << i << endl;
    TH1D * H = dynamic_cast<TH1D*>(TTH->Get(pippo[i]));
    double minx=H->GetBinLowEdge(1);
    double maxx=nbins*H->GetBinWidth(1);
    Histo_TOT[i] = new TH1D ( pippotot[i]," ", nbins, minx, maxx );
    Histo_TTH[i] = new TH1D ( pippotth[i]," ", nbins, minx, maxx );
    Histo_TOTS[i] = new TH1D ( pippototS[i]," ", nbins, minx, maxx );
    Histo_TTHS[i] = new TH1D ( pippotthS[i]," ", nbins, minx, maxx );
  }

  cout << "Starting loop on variables needing smoothing" << endl;

  // Loop on variables 
  // -----------------
  for ( int ivar=0; ivar<nvars; ivar++ ) {

    // Extract sum histograms with the right normalization and errors
    // --------------------------------------------------------------
    double totWW[nwsamples][nbins]={0.};
    double totW[nbins]={0.};
    double s2_totW[nbins]={0.};
    double totNW[nwsamples][nbins]={0.};
    for ( int i=0; i<nwsamples; i++ ) {
      cout << "Processing W file #" << i << " ..." << endl;
      TH1D * Histo = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]));
      TH1D * HistoW = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"W"));
      // For W, we need also total entries in histograms to add a
      // Poisson fluke contribution to total errors from matrix:
      // ----------------------------------------------------------
      TH1D * HistoN = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"N"));    
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t=Histo->GetBinContent(ibin);
	double s2t=HistoW->GetBinContent(ibin);
	double n=HistoN->GetBinContent(ibin);
	totWW[i][ibin-1]+=t*Wxs[i]/NW[i]*Lumfactor;
	s2_totW[ibin-1]+=s2t*pow(Wxs[i]/NW[i]*Lumfactor,2);
	totNW[i][ibin-1]+=n;
      }
    }
    // Once grandtotals of weights are computed for each bin, we can
    // add to the total s2 the Poisson contribution 1/sqrt(N) * T
    // -------------------------------------------------------------
    for ( int i=0; i<nwsamples; i++ ) {
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	totW[ibin-1]+=totWW[i][ibin-1];
	if ( totNW[i][ibin-1]>0 ) {
	  s2_totW[ibin-1]+=pow(totWW[i][ibin-1],2)/totNW[i][ibin-1];
	}
      }
    }
    
    double totWQCD[nqcdsamples][nbins]={0.};
    double totQCD[nbins]={0.};
    double s2_totQCD[nbins]={0.};
    double totNQCD[nqcdsamples][nbins]={0.};
    for ( int i=0; i<nqcdsamples; i++ ) {
      cout << "Processing QCD file #" << i << " ..." << endl;
      TH1D * Histo = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]));
      TH1D * HistoW = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"W"));
      // For QCD, we need also total entries in histograms to add a
      // Poisson fluke contribution to total errors from matrix:
      // ----------------------------------------------------------
      TH1D * HistoN = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"N"));    
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t=Histo->GetBinContent(ibin);
	double s2t=HistoW->GetBinContent(ibin);
	double n=HistoN->GetBinContent(ibin);
	totWQCD[i][ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
	s2_totQCD[ibin-1]+=s2t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
	totNQCD[i][ibin-1]+=n;
      }
    }
    // Once grandtotals of weights are computed for each bin, we can
    // add to the total s2 the Poisson contribution 1/sqrt(N) * T
    // -------------------------------------------------------------
    for ( int i=0; i<nqcdsamples; i++ ) {
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	totQCD[ibin-1]+=totWQCD[i][ibin-1];
	if ( totNQCD[i][ibin-1]>0 ) {
	  s2_totQCD[ibin-1]+=pow(totWQCD[i][ibin-1],2)/totNQCD[i][ibin-1];
	}
      }
    }
    
    double totTT[nbins]={0.};
    double s2_totTT[nbins]={0.};
    for ( int i=0; i<nttsamples; i++ ) {
      cout << "Processing TT file #" << i << " ..." << endl;
      TH1D * Histo = dynamic_cast<TH1D*>(TT[i]->Get(pippo[ivar]));
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t=Histo->GetBinContent(ibin);
	totTT[ibin-1]+=t*TTxs[i]/NTT[i]*Lumfactor;
	s2_totTT[ibin-1]+=t*pow(TTxs[i]/NTT[i]*Lumfactor,2);
      }
    }
    double totTTH[nbins]={0.};
    double s2_totTTH[nbins]={0.};
    cout << "Processing TTH file " << " ..." << endl;
    TH1D * Histo = dynamic_cast<TH1D*>(TTH->Get(pippo[ivar]));
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      double t=Histo->GetBinContent(ibin);
      totTTH[ibin-1]+=t*TTHxs/NTTH*Lumfactor;
      s2_totTTH[ibin-1]+=t*pow(TTHxs/NTTH*Lumfactor,2);
    }
    
    // OK now fill total histograms
    // ----------------------------
    double total_sig=0.;
    double total_bgr=0.;
    double grandtot[nbins]={0.};
    double grandtote[nbins]={0.};
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      Histo_TTH[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
      Histo_TTH[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
      Histo_TTHS[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
      Histo_TTHS[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
      grandtot[ibin-1] = totQCD[ibin-1]+totTT[ibin-1]+totW[ibin-1];
      grandtote[ibin-1]= sqrt(s2_totQCD[ibin-1]+s2_totTT[ibin-1]+s2_totW[ibin-1]);
      Histo_TOT[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
      Histo_TOT[ivar]->SetBinError(ibin,grandtote[ibin-1]);
      Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
      Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]);
      total_sig+=totTTH[ibin-1];
      total_bgr+=grandtot[ibin-1];
    }

    // Pre-smoothing algorithm that levels down spikes
    // -----------------------------------------------
    double mean;
    double errmean;
    double delta_bgr=0.;
    for ( int ibin=0; ibin<nbins-2; ibin++ ) {
      double delta=fabs(grandtot[ibin]-grandtot[ibin+1]);
      if ( delta>3*grandtote[ibin] && grandtot[ibin]>0 ) {  // the signal is a bin way off from the previous
	// Avoid averaging with bins with large error
	if ( delta>3*grandtote[ibin+2] ) {
	  mean=(grandtot[ibin]+grandtot[ibin+2])/2.;
	  errmean=sqrt(pow(grandtote[ibin],2)+pow(grandtote[ibin+2],2))/2.;
	  cout << ivar << " " << ibin << " " << mean <<"+-" << errmean << " " << grandtot[ibin+1];
	  if ( mean>0 && fabs(grandtot[ibin+1]-mean)>3.*errmean ) {
	    delta_bgr += grandtot[ibin+1]-mean;
	    grandtot[ibin+1]=mean;
	    grandtote[ibin+1]=errmean;
	    cout << ": doing it " << mean << " " << errmean << " " << delta_bgr << endl;
	    cout << grandtot[ibin] << " " << grandtot[ibin+1] << " " << grandtot[ibin+2] << endl;
	  } else cout << ": not doing it." << endl;
	}
      }
    }
    // fix bin 0 if needed
    // -------------------
    mean=(grandtot[1]+grandtot[2])/2;
    errmean=sqrt(pow(grandtote[1],2)+pow(grandtote[2],2))/2.;
    if ( mean>0 & fabs(grandtot[0]-mean)>3.*errmean ) {
      delta_bgr += grandtot[0]-mean;
      grandtot[0]=mean;
      grandtote[0]=errmean;
    } 
    // fix last bin if needed
    // ----------------------
    mean=(grandtot[nbins-3]+grandtot[nbins-2])/2;
    errmean=sqrt(pow(grandtote[nbins-3],2)+pow(grandtote[nbins-2],2))/2;
    if ( mean>0 & fabs(grandtot[nbins-1]-mean)>3.*errmean ) {
      delta_bgr += grandtot[nbins-1]-mean;
      grandtot[nbins-1]=mean;
      grandtote[nbins-1]=errmean;
    } 
    // Renormalize bgr histogram
    // -------------------------
    cout << ivar << " " << ": delta=" << delta_bgr << endl;
    if ( delta_bgr>0 && total_bgr>delta_bgr ) {
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]*total_bgr/(total_bgr-delta_bgr));
	Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]*total_bgr/(total_bgr-delta_bgr));
      } 
    } 
    
    Histo_TOTS[ivar]->Smooth(1);
    Histo_TTHS[ivar]->Smooth(1);
    double sumtot=0.;
    double sumtth=0.;
    double sumtotS=0.;
    double sumtthS=0.;
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      sumtotS+=Histo_TOTS[ivar]->GetBinContent(ibin);
      sumtthS+=Histo_TTHS[ivar]->GetBinContent(ibin);
      sumtot+=Histo_TOT[ivar]->GetBinContent(ibin);
      sumtth+=Histo_TTH[ivar]->GetBinContent(ibin);
    }
    if ( sumtotS>0 ) Histo_TOTS[ivar]->Scale(1./sumtotS);
    if ( sumtthS>0 ) Histo_TTHS[ivar]->Scale(1./sumtthS);
    if ( sumtot>0 ) Histo_TOT[ivar]->Scale(1./sumtot);
    if ( sumtth>0 ) Histo_TTH[ivar]->Scale(1./sumtth);

  } // end of ivar loop

  cout << "Done, now plotting and writing histos." << endl;

  TString fname;
  fname="functionfile"+sel+".root";

  TFile * Smoothed = new TFile(fname,"RECREATE");
  Smoothed->cd();

  TCanvas * b1 = new TCanvas ("b1", "Kinematics comparison", 600, 600 );
  b1->Divide(3,3);
  for ( int ivar=0; ivar<9; ivar++ ) {
    b1->cd(ivar+1);
    Histo_TOTS[ivar]->SetMinimum(0.);
    Histo_TOTS[ivar]->Draw();
    Histo_TTHS[ivar]->SetLineColor(kBlue);
    Histo_TTHS[ivar]->Draw("PESAME");
  }
  b1->Print("./ps/Smooth_svsb_1.ps");
  TCanvas * b2 = new TCanvas ("b2", "Kinematics comparison", 600, 600 );
  b2->Divide(3,3);
  for ( int ivar=9; ivar<nvars; ivar++ ) {
    b2->cd(ivar-8);
    Histo_TOTS[ivar]->SetMinimum(0.);
    Histo_TOTS[ivar]->Draw();
    Histo_TTHS[ivar]->SetLineColor(kBlue);
    Histo_TTHS[ivar]->Draw("PESAME");
  }
  b2->Print("./ps/Smooth_svsb_2.ps");

  TCanvas * b3 = new TCanvas ("b3", "Kinematics comparison", 600, 600 );
  b3->Divide(3,3);
  for ( int ivar=0; ivar<9; ivar++ ) {
    b3->cd(ivar+1);
    Histo_TOT[ivar]->SetMinimum(0.);
    Histo_TOT[ivar]->SetLineColor(kRed);
    Histo_TOT[ivar]->Draw("PE");    
    Histo_TOTS[ivar]->Draw("PESAME");
    Histo_TOT[ivar]->Write();
    Histo_TTH[ivar]->Write();
    Histo_TOTS[ivar]->Write();
    Histo_TTHS[ivar]->Write();
  }
  b3->Print("./ps/Smooth_check_1.ps");
  TCanvas * b4 = new TCanvas ("b4", "Kinematics comparison", 600, 600 );
  b4->Divide(3,3);
  for ( int ivar=9; ivar<nvars; ivar++ ) {
    b4->cd(ivar-8);
    Histo_TOT[ivar]->SetMinimum(0.);
    Histo_TOT[ivar]->SetLineColor(kRed);
    Histo_TOT[ivar]->Draw("PE");    
    Histo_TOTS[ivar]->Draw("PESAME");
    Histo_TOT[ivar]->Write();
    Histo_TTH[ivar]->Write();
    Histo_TOTS[ivar]->Write();
    Histo_TTHS[ivar]->Write();
  }
  b4->Print("./ps/Smooth_check_2.ps");

  Smoothed->Close();

}
Example #17
0
void DetermineAnchorsPP(const Char_t* inputDir, TString lPeriodName = "LHC18f", Int_t runNo, const Char_t* chunkName = "", Bool_t automaticMode=kFALSE) {
   //
   // In automatic mode the function does not request any standard input and creates anchor points if the fit was ok
   // using the anchor value determined automatically.
   // One must check the QA plots for individual run to make sure the automatic values are fine and eventually run this 
   // function again in manual mode.
   //
   
    Bool_t lUseDefaultAnchorPercentile = kFALSE;
    Double_t  lDefaultAnchorPercentile = 0.10;
    Double_t  lMinimumAnchorPercentile = 0.05;

    // open minimum bias OADB file
    TString lOADBfile = Form("OADB-%s-MB.root", lPeriodName.Data());

    cout << "Opening minimum bias info ... " << endl;
    TFile *foadb = new TFile( lOADBfile.Data(), "READ" );
    AliOADBContainer *lOADBcontainer = (AliOADBContainer*)foadb->Get("MultSel");

    // set percentile boundaries for the estimator histos
    // (based on what is implemented in the calibration)
    Double_t lDesiredBoundaries[1000];
    Long_t   lNDesiredBoundaries=0;
    lDesiredBoundaries[0] = 0.0;
    //From High To Low Multiplicity
    for( Int_t ib = 1; ib < 101; ib++) { // 100 bins  ] 0.0 , 0.1 ]
      lNDesiredBoundaries++;
      lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 0.01;
    }
    for( Int_t ib = 1; ib < 91; ib++) { // 90 bins ] 1.0 , 10. ]
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 0.1;
    }
    for( Int_t ib = 1; ib < 91; ib++) { // 90 bins ] 10.0 , 100.0 ]
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 1.0;
    }
    
    FILE *fap = 0x0;

    // auxiliary objects
    TLegend *legEstimator = 0x0;
    //
    TLine *anchorLine = new TLine();
    anchorLine->SetLineStyle(2);
    //
    TLatex *latex = new TLatex();
    latex->SetTextFont(42);
    latex->SetTextSize(0.025);

    // constant function for the scaling factor determination
    TF1 *fpol0 = new TF1("fpol0", "[0]", 0.005, lMinimumAnchorPercentile);
    fpol0->SetLineStyle(3);
    fpol0->SetLineWidth(1);
    fpol0->SetLineColor(kBlack);
    TF1 *fpol0_hi = (TF1*)fpol0->Clone("fpol0_hi");
    TF1 *fpol0_lo = (TF1*)fpol0->Clone("fpol0_lo");
    //
    Int_t npar = 3;
    TF1 *fturnon = new TF1("fturnon", func_turnon, 0., 1., npar);
    fturnon->SetParameters(1., 0.1, -1.);
    fturnon->SetParLimits(1, lMinimumAnchorPercentile, 1.0);
    fturnon->SetParLimits(2, -1.e15, 0.);
    fturnon->SetLineColor(1);

    // open input AnalysisResults.root file for the VHM sample
    TString fileIdentifier = Form("%d", runNo);
    if(chunkName[0]!='\0') fileIdentifier = chunkName;
    TFile *fin = TFile::Open(Form("%s/AnalysisResults_%s.root", inputDir, fileIdentifier.Data()), "READ");
    TTree *treeEvent = (TTree*)fin->Get("MultSelection/fTreeEvent");

    cout << "   - run number....................: " << runNo << endl;

    // define estimator histo for this run
    TH1D* hEstimator = new TH1D(Form("hEstimator_%d", runNo), "", lNDesiredBoundaries, lDesiredBoundaries);
    hEstimator->Sumw2();
    hEstimator->GetXaxis()->SetTitle("V0M Percentile");
    hEstimator->GetYaxis()->SetTitle("Counts");
    hEstimator->SetStats(0);
    hEstimator->SetLineColor(kRed);

    // get corresponding calibration histogram from OADB
    AliOADBMultSelection* lOADB = (AliOADBMultSelection*)lOADBcontainer->GetObject( runNo, "Default" );
    if( (Int_t)lOADBcontainer->GetIndexForRun( runNo )<0 ) {
      cout << "   ---> Warning: no calibration histo found for this run - skipping..." << endl;
      return;
    }

    // set the pointer to the calib histo for this run
    hCalib = (TH1D*)lOADB->GetCalibHisto( "hCalib_V0M" );;
    //
    Double_t nall = treeEvent->Draw(Form("get_percentile(fAmplitude_V0A+fAmplitude_V0C)>>hEstimator_%d", runNo), 
                                        Form("fRunNumber==%d && fEvSel_Triggered && fEvSel_IsNotPileupInMultBins && fEvSel_PassesTrackletVsCluster && fEvSel_INELgtZERO && fEvSel_HasNoInconsistentVertices && TMath::Abs(fEvSel_VtxZ)<=10.0 && isSelectedHM(fEvSel_TriggerMask)", runNo),
                                        "goff"); 

    hEstimator->Scale(1., "width");
    Double_t nevents = (Double_t)hEstimator->GetEntries();
    cout << "   - number of events (selected)...: " << nevents << endl;

    // draw histogram
    TCanvas *cEstimator = new TCanvas(Form("cEstimator_%d", runNo), "Estimator Distribution", 10, 10, 1000, 750);
    cEstimator->SetRightMargin(0.05);
    cEstimator->SetTopMargin(0.11);

    hEstimator->GetXaxis()->SetRangeUser(0., 0.2);
    hEstimator->Draw("hist e0");
    latex->SetNDC();
    latex->SetTextSize(0.06);
    latex->DrawLatex(0.1, 0.93, Form("Run: %d", runNo));

    // first, fit a pol0 in the flat region (usually up to 0.05)
    hEstimator->Fit(fpol0, "RQ0");
    Double_t flat_top = fpol0->GetParameter(0);

    // get standard deviantion of bin contents in the flat region
    Double_t flat_top_stdev = 0.;
    for(Int_t ibin=1; ibin<=hEstimator->FindBin(lMinimumAnchorPercentile); ++ibin) {
      Double_t content = hEstimator->GetBinContent(ibin);
      Double_t   width = hEstimator->GetBinWidth(ibin);
      flat_top_stdev += TMath::Power((content-flat_top), 2.)*width;
    }
    flat_top_stdev = TMath::Sqrt(flat_top_stdev/lMinimumAnchorPercentile) / 2.;
    fpol0_hi->SetParameter(0, flat_top+flat_top_stdev);
    fpol0_lo->SetParameter(0, flat_top-flat_top_stdev);
        
    // now, fix the constant parameter in the turnon function
    fturnon->SetParameters(1., 0.1, -1.);
    fturnon->FixParameter(0, flat_top);
        
    // get the maximum range to perform the fit
    Double_t range_max = (hEstimator->GetBinLowEdge(hEstimator->FindLastBinAbove())) / 1.8;
    fturnon->SetRange(0.005, (range_max>0.1) ? range_max : 0.1);

    // get anchor percentile
    Double_t anchor_percentile = -1.;
    TString fitstatus = "";
    if(nevents>0) {
      TFitResultPtr fitr = hEstimator->Fit(fturnon, "RQM");
      fturnon->Draw("lsame");
      fitstatus = gMinuit->fCstatu;
    }
    cEstimator->Flush();
    cEstimator->Update();
    cout << "   - fit status....................: " << fitstatus << endl;
    if( !fitstatus.Contains("OK") ) {
      if(gROOT->IsBatch()) {
         cout << "   ---> Warning: fit failed! -- skipping this run..." << endl;
         if(!automaticMode) {
            fap = fopen(Form("temp/anchors/Anchor_%s_%d_VHM.txt", lPeriodName.Data(), runNo), "w");
            fprintf(fap, "%d %d %.2lf %lf\n", runNo, runNo, -1., -1.);
         }
         return;
      }
      
      if(!automaticMode) {
         cout << "   - Please, provide an anchor percentile to continue: " << endl;
         cout << "     (entering a negative value will skip this run)" << endl;
         cout << "     >>>> anchor percentile: "; 
         cin >> anchor_percentile;
         if(anchor_percentile<0.) {
            cout << "   ---> Warning: percentile provided is negative -- skipping this run..." << endl;
            fap = fopen(Form("temp/anchors/Anchor_%s_%d_VHM.txt", lPeriodName.Data(), runNo), "w");
            fprintf(fap, "%d %d %.2lf %lf\n", runNo, runNo, -1., -1.);
            return;
         }
      }
      else return;      // in automatic mode we do not create an anchor file
Example #18
0
Compare_QCD ( TString pippo ) 
{

  TFile * QCD[8];     
  QCD[0] = new TFile("./root/TDAna_QCD30-50_tk3.root");
  QCD[1] = new TFile("./root/TDAna_QCD50-80_tk3.root");
  QCD[2] = new TFile("./root/TDAna_QCD80-120_tk3.root");
  QCD[3] = new TFile("./root/TDAna_QCD120-170_tk3.root");
  QCD[4] = new TFile("./root/TDAna_QCD170-230_tk3.root");
  QCD[5] = new TFile("./root/TDAna_QCD230-300_tk3.root");
  QCD[6] = new TFile("./root/TDAna_QCD300-380_tk3.root");
  QCD[7] = new TFile("./root/TDAna_QCD380incl_tk3.root");
  double QCDxs[8] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
  double NQCD[8] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};

  TFile * QCDOLD[8];     
  QCDOLD[0] = new TFile("./rootold/TDAna_QCD30-50_tk3.root");
  QCDOLD[1] = new TFile("./rootold/TDAna_QCD50-80_tk3.root");
  QCDOLD[2] = new TFile("./rootold/TDAna_QCD80-120_tk3.root");
  QCDOLD[3] = new TFile("./rootold/TDAna_QCD120-170_tk3.root");
  QCDOLD[4] = new TFile("./rootold/TDAna_QCD170-230_tk3.root");
  QCDOLD[5] = new TFile("./rootold/TDAna_QCD230-300_tk3.root");
  QCDOLD[6] = new TFile("./rootold/TDAna_QCD300-380_tk3.root");
  QCDOLD[7] = new TFile("./rootold/TDAna_QCD380incl_tk3.root");

  double Lumfactor = 100000.;

  TH1D * H = dynamic_cast<TH1D*>(QCD[0]->Get(pippo));
  double minx=H->GetBinLowEdge(1);
  double maxx=50.*H->GetBinWidth(1);
  TH1D * Histo_QCD = new TH1D ( pippo+"_QCD", "", 50, minx, maxx );
  TH1D * R_QCD = new TH1D ( pippo+"_QCD", "", 50, minx, maxx );
  TH1F * Histo_QCDOLD = new TH1F ( pippo+"_QCDOLD", "", 50, minx,maxx );

  // Extract sum histograms with the right normalization and errors
  // --------------------------------------------------------------
  double totQCD[50]={0.};
  double s2_totQCD[50]={0.};
  for ( int i=0; i<8; i++ ) {
    cout << "Processing QCD file #" << i << " ..." << endl;
    TH1D * Histo = dynamic_cast<TH1D*>(QCD[i]->Get(pippo));
    TH1D * HistoW = dynamic_cast<TH1D*>(QCD[i]->Get(pippo+"W"));
    for ( int ibin=1; ibin<=50; ibin++ ) {
      double t=Histo->GetBinContent(ibin);
      double s2t=HistoW->GetBinContent(ibin);
      totQCD[ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
      s2_totQCD[ibin-1]+=s2t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
    }
  }
  double totQCDOLD[50]={0.};
  double totNQCDOLD[50]={0.};
  double s2_totQCDOLD[50]={0.};
  for ( int i=0; i<8; i++ ) {
    cout << "Processing QCD OLD file #" << i << " ..." << endl;
    TH1D * Histo = dynamic_cast<TH1D*>(QCDOLD[i]->Get(pippo));
    for ( int ibin=1; ibin<=50; ibin++ ) {
      double t=Histo->GetBinContent(ibin);
      totQCDOLD[ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
      totNQCDOLD[ibin-1]+=t;
      s2_totQCDOLD[ibin-1]+=t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
    }
  }
  // Once grandtotals of weights are computed for each bin, we can
  // add to the total s2 the Poisson contribution 1/sqrt(N) * T
  // -------------------------------------------------------------
  for ( int ibin=1; ibin<=50; ibin++ ) {
    if ( totNQCDOLD[ibin-1]==0 ) totNQCDOLD[ibin-1]=1;
    s2_totQCD[ibin-1]+=pow(totQCD[ibin-1],2)/totNQCDOLD[ibin-1];
  }

  // OK now fill total histograms
  // ----------------------------
  double nQCD=0.;
  double s2_NQCD=0.;
  double nQCDOLD=0.;
  double s2_NQCDOLD=0.;
  for ( int ibin=1; ibin<=50; ibin++ ) {
    nQCD+=totQCD[ibin-1];
    s2_NQCD+=s2_totQCD[ibin-1];
    nQCDOLD+=totQCDOLD[ibin-1];
    s2_NQCDOLD+=s2_totQCDOLD[ibin-1];
    Histo_QCD->SetBinContent(ibin,totQCD[ibin-1]);
    Histo_QCDOLD->SetBinContent(ibin,totQCDOLD[ibin-1]);
    Histo_QCD->SetBinError(ibin,sqrt(s2_totQCD[ibin-1]));
    Histo_QCDOLD->SetBinError(ibin,sqrt(s2_totQCDOLD[ibin-1]));
    double R=1.;
    double s_R;
    if ( totQCDOLD[ibin-1]>0 && totQCD[ibin-1] ) {
      R = totQCDOLD[ibin-1]/totQCD[ibin-1];
      s_R = R*sqrt(s2_totQCD[ibin-1]/pow(totQCD[ibin-1],2)+
		   s2_totQCDOLD[ibin-1]/pow(totQCDOLD[ibin-1],2));
      cout << ibin-1 << " " << totQCD[ibin-1] << "+-" << sqrt(s2_totQCD[ibin-1])/totQCD[ibin-1] 
	   << " / " <<  totQCDOLD[ibin-1] <<  "+-" <<sqrt(s2_totQCDOLD[ibin-1])/totQCDOLD[ibin-1]  
	   << " = " << R << "+-" << s_R << endl;
    }
    R_QCD->SetBinContent(ibin,R);
    R_QCD->SetBinError(ibin,s_R);
  }
  cout << "Totals: N(seen) = " << nQCDOLD << "+-" << sqrt(s2_NQCDOLD) << endl;
  cout << "        N(pred) = " << nQCD    << "+-" << sqrt(s2_NQCD) << endl;

  TCanvas * b = new TCanvas ("b", "Kinematics comparison", 700, 700 );
  b->Divide(1,2);

  b->cd(1);
  //b->GetPad(1)->SetLogy();
  Histo_QCD->SetLineColor(kRed);
  Histo_QCD->Draw("PE");
  Histo_QCDOLD->SetLineColor(kBlue);
  Histo_QCDOLD->Draw("PESAME");
  b->cd(2);
  R_QCD->SetMinimum(0.);
  R_QCD->SetMaximum(4.);
  R_QCD->Draw("PE");

  b->Print(pippo+".ps");

}
Example #19
0
void calculateTriggerRates(
			   TString inFile0Name = "root://eoscms//eos/cms/store/caf/user/velicanu/PA2013_merged_HiForest/pPb_hiForest2_pilotRun_200kHz_v3.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"
    }; */
  //trigger list for singleMu rate plot
  const int ntrigs = 4 ;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAMu3_v1",
    "HLT_PAMu7_v1",
    "HLT_PAMu12_v1"
  };
  /*
  //trigger list for DoubleMu rate plot
  const int ntrigs = 4 ;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAL1DoubleMuOpen_v1",
    "HLT_PAL1DoubleMu0_HighQ_v1",
    "HLT_PAL2DoubleMu3_v1"
  };
  
  //trigger list fo bJet+Mu rate plot
  const int ntrigs =5;
  const char* triggerPath[ntrigs] = {
    "",
    "HLT_PAMu3PFJet20_v1",
    "HLT_PAMu3PFJet40_v1",
    "HLT_PAMu7PFJet20_v1",
    "HLT_PABTagMu_Jet20_Mu4_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",";Lumi Section; Counts ",1100,0,1100);
    HltTree->Draw("LumiBlock>>ph",str.Format("%s",triggerPath[it]));
    TLegend *lTemp= new TLegend(0.2,0.8,0.8,0.9);
    lTemp->SetHeader(str.Format("Run : %d",runNum));
    lTemp->SetMargin(0.05);
    lTemp->SetFillStyle(0);
    lTemp->SetLineColor(0);
    lTemp->SetLineWidth(5.0);
    lTemp->SetTextSize(0.03); 
    lTemp->AddEntry(ph,str.Format("%s",triggerPath[it],"l")); 
    lTemp->Draw("same");
    c1->SaveAs(str.Format("%d_%s.pdf",runNum,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.7,0.8,0.9);
  l0->SetHeader(str.Format("Run : %d",runNum));
  l0->SetMargin(0.03);
  l0->SetFillStyle(0);
  l0->SetLineColor(0);
  l0->SetLineWidth(1.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 Hz",triggerPath[it],ahTempRate[it]),"l");
      pcLumi->Update();
     
    }
  l0->Draw("same");
  pcLumi->SaveAs(str.Format("%d_ratedMu.png",runNum));
}
Example #20
0
int main(int argc, char *argv[]){	
// int argcb;
// char **argvb;	
TApplication *app = new TApplication("app", &argc, argv);
TH1::AddDirectory(kFALSE);//avoid name overwrites but could cause other memory histogram issues
//        h->SetDirectory(0);          for the current histogram h
	
	double worldsize=80;
	exp_core experiment(worldsize);
	
	//
	// Set the option you wish to run
	//
	int control =0;
	// 0 = EVERYTHING
	// 1 = geometry
	// 2 = Rutherford
	// 3 = Decay position
	// 4 = Distribution hits
	// 5 = Draw events for real time viewing
	
	bool save_text=true;//saves terminal output but no terminal output until completion
	
	//
	// Set the target
	//
	double density_targ=1.55;
	double density_back=19.32;
	target tharget(20,40,1000,180.0,0,10000,79,197);
	experiment.set_targ(tharget);
	
	//
	// Set the beam
	//
	double ebeam=120; //MeV
	experiment.set_beam(18,36,ebeam);	
		
	//
	// Input your physics
	//
	double excited_Z=34;
	double excited_A=70;
	double initial_state_MeV = 1.4;
	double transition_keV = 200;
	bool excited_beam_like=false;
	double halflife=0.003;//in ns
	string dist="";// leave blank for a uniform distribution

	//
	// Setup Detectors
	//	
	
	int config=0; // 0 normal, 1 stopper, 2 old
	int S3=1; // 0 off, 1 S3 simple, 2 S3 rings , 3 pin
	double overr=0; // mm >0 non-default S3 / pin position
	

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// END OF USER INPUT ////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	double t_d=0.2,t_u=0.35*pi;

	///////// First we sort output files ////////
	
	// Create the names 
	stringstream ss;
	ss<<"outputs/SPICE_"<<experiment.channelnames(experiment.get_BZ(),experiment.get_BA());
	ss<<"_"<<experiment.channelnames(experiment.get_TZ(),experiment.get_TA());
	if(tharget.backing_thickness>0)
		ss<<"_"<<experiment.channelnames(tharget.backing_Z,tharget.backing_A)<<"_backed";
	ss<<"_"<<ebeam<<"MeV";
	string file_title=ss.str();
	
	// Check if the root file exists already 
	bool exist=false;
	TFile* outfile= new TFile((file_title+".root").c_str(),"READ");
	if(outfile->IsOpen()){exist=true;outfile->Close();delete outfile;}
	
	// Open the file root file to right, whether or not it exists
	outfile= new TFile((file_title+".root").c_str(),"UPDATE");//Open an existing file for writing. If no file exists, it is created.
	gROOT->cd();// 

// This code is for capturing the terminal output
std::streambuf *psbuf, *backup;
std::ofstream filestr;	
if(save_text){
	// Append if the root file is being
	if(exist){filestr.open(file_title+".txt",std::ofstream::app);filestr<<endl<<"/////// APPEND //////"<<endl;} //appended
	else filestr.open(file_title+".txt");
	backup = std::cout.rdbuf();     // back up cout's streambuf
	psbuf = filestr.rdbuf();        // get file's streambuf
	std::cout.rdbuf(psbuf);         // assign streambuf to cout
}

	// Create the canvas that is used as an inbetween for the whole program
	TCanvas * can_view = new TCanvas("can_view", "can_view", 1200, 600);
	gStyle->SetOptStat(0);
	can_view->cd();
	
	/////////////////////////////////////////////////////
	////////////////// Draw Geometry ////////////////////
	/////////////////////////////////////////////////////
	
	// This loop outputs graphics of the chosen detector geography
	if(control==0||control==1){spice_auto_setup(experiment,config,S3,overr);

		if(!outfile->GetDirectory("Geometry"))outfile->mkdir("Geometry");
		gROOT->cd();
		
		can_view->cd();can_view->Clear();
		experiment.draw_exp();
		outfile->cd("Geometry");
		can_view->SetName("3Dview");can_view->Write("3Dview",TObject::kOverwrite);
		gROOT->cd();
		
		can_view->cd();can_view->Clear();
		experiment.draw_exp(2);
		outfile->cd("Geometry");
		can_view->SetName("side_view");can_view->Write("side_view",TObject::kOverwrite);
		gROOT->cd();
		
		can_view->cd();can_view->Clear();
		experiment.draw_exp(3);
		outfile->cd("Geometry");
		can_view->SetName("beam_view");can_view->Write("beam_view",TObject::kOverwrite);
		gROOT->cd();
		
		can_view->cd();can_view->Clear();
		experiment.draw_phi();
		outfile->cd("Geometry");
		can_view->SetName("theta_view");can_view->Write("theta_view",TObject::kOverwrite);
		gROOT->cd();
	}
	
	/////////////////////////////////////////////////////	
	//////// Calculate Rutherford and Kinematics ////////
	/////////////////////////////////////////////////////

	// This loop calculates the basic beam target kinematics and Rutherford scattering rates
	if(control==0||control==2){spice_auto_setup(experiment,config,S3,overr);
		//experiment.set_rutherford();//sets reaction
		experiment.set_elastic();
		
		can_view->Clear();
		can_view->Divide(2);
		can_view->cd(1);
		experiment.set_ruthmask(t_d,t_u,true,false);// Cut down on wasted simulations by only focusing on the region of interest
		experiment.draw_hit_pattern_2D(1,1000000,1,1,0);
		((TH2D*)gPad->GetPrimitive("Hit_Map_copy"))->SetTitle("Target");
		can_view->cd(2);
		experiment.set_ruthmask(t_d,t_u,false,true);
		experiment.draw_hit_pattern_2D(1,1000000,1,0,1);
		((TH2D*)gPad->GetPrimitive("Hit_Map_copy"))->SetTitle("Beam");
		outfile->cd();
		can_view->SetName("Hit_map_rutherford");can_view->Write("Hit_map_rutherford",TObject::kOverwrite);
		gROOT->cd();
		
		can_view->Clear();can_view->cd();
		experiment.draw_primary_kinematics();
		outfile->cd();
		can_view->SetName("Kinematics");can_view->Write("Kinematics",TObject::kOverwrite);
		gROOT->cd();
		
		experiment.auto_rutherford_OTT(100000,true);
		if(S3==2){spice_auto_setup(experiment,config,1,overr);experiment.auto_rutherford_OTT(100000,true);}
	}
	

	
	/////////////////////////////////////////////////////	
	////// Experimental Interaction and Detection ///////
	/////////////////////////////////////////////////////

	// This loop calculates data for the reaction of interest
	// 
	if(control==0||control==3||control==4||control==5){
		if(excited_Z<0||excited_A<0){
			if(excited_beam_like){
				experiment.set_reco(experiment.get_BZ(),experiment.get_BA());
			}else{
				experiment.set_elastic();
			}			
		}else{
			experiment.set_reco(excited_Z,excited_A);
		}
		
		// Now we set the target interaction and decay information		
		experiment.set_target_interaction(2);//E^2 is a reasonably approximation for most of our stuff
		
		experiment.set_E_star(initial_state_MeV);
		
		experiment.set_ICE(transition_keV);
		// experiment.density_targ=density_targ;// experiment.density_back=density_back;
		if(halflife>0) experiment.set_halflife_ns(halflife,density_targ,density_back); // Can set the densities directly as well

		//set some distribution
		if(dist.size()>0){
			experiment.set_primary_dist(dist);
		}else{
			//experiment.set_uniform(t_d,t_u);
			TFormula fot("fot","sin(x)");
			experiment.set_primary_dist(&fot);//using this one so we can use the same masking for both
		}
		
		if(excited_beam_like)experiment.reverse_primary_dist();//because distribution defined for beam like by default but RECOIL is excited
		
		experiment.set_implant_escape(-1); //SET THIS so things dont escape when they go wack into things
		
		int z=2;// Detector number of the first heavy ion detector
		if(S3==2)z++;// If S3, skip the PCB. PCBs left out for the diodes in spice_auto_setup
		
		//////////////////////////////
		////// FINISHED SET UP ///////
		//////////////////////////////
		
		experiment.print_reaction();
		experiment.print_target();
		experiment.print_decay();
// 		experiment.print_detectables();
		
		outfile->cd();
			experiment.dist_target_KE_beam.Write("KE_though_target",TObject::kOverwrite);
		gROOT->cd();	
		
		if(control==0||control==3){spice_auto_setup(experiment,config,S3,overr);
			experiment.basic_decay_check(100000);

			// Draw the target and decay things
			// quite important to check things are set and working right
			can_view->Clear();can_view->Divide(2);
			can_view->cd(1);
			experiment.draw_decay_Z(0,true,10);
			can_view->cd(2);
			experiment.draw_target_interaction(0,true);
			outfile->cd();
			can_view->SetName("Ungated_Decay_Position");can_view->Write("Ungated_Decay_Position",TObject::kOverwrite);
			gROOT->cd();
			
			for(int i=z;i<experiment.detN();i++){ //set only the daughter recoil as valid in the S3 or pins
				experiment.set_valid_part(i,0,0,1,0);
			}
			string n=experiment.channelnames(experiment.get_D1Z(),experiment.get_D1A())+"_Gated_Decay_Position";
			experiment.mask_manual(t_d,t_u,true,false);//saves on wasted computation

			can_view->Clear();can_view->Divide(2);
			can_view->cd(1);
			experiment.draw_decay_Z(1,true,10);
			can_view->cd(2);
			experiment.draw_target_interaction(1,true);
			outfile->cd();
			can_view->SetName(n.c_str());can_view->Write(n.c_str(),TObject::kOverwrite);
			gROOT->cd();		
			
			
			for(int i=z;i<experiment.detN();i++){ //set only the ejectile as valid in the S3 or pins
				experiment.set_valid_part(i,0,1,0,0);
			}		
			string N=experiment.channelnames(experiment.get_EZ(),experiment.get_EA())+"_Gated_Decay_Position";
			experiment.mask_manual(t_d,t_u,false,true);//saves on wasted computation

			
			can_view->Clear();can_view->Divide(2);
			can_view->cd(1);
			experiment.draw_decay_Z(1,true,10);
			can_view->cd(2);
			experiment.draw_target_interaction(1,true);
			outfile->cd();
			can_view->SetName(N.c_str());can_view->Write(N.c_str(),TObject::kOverwrite);
			gROOT->cd();
		}
		
		// Distribution hit loops
		if(control==0||control==4){spice_auto_setup(experiment,config,S3,overr);
			can_view->Clear();
			can_view->cd();
			
			experiment.mask_manual(t_d,t_u,true,true);
			double ra=experiment.manual_primary_dist_hist.Integral();//Ask what fraction we have masked too, as unmask integral = 1	
			// Print a basic output of fractions of hits
			cout<<endl<<endl<<"Multiply by fraction "<<ra;
			experiment.basic_hit_count(100000,true,1,1,0,0);
						
			string r=experiment.channelnames(experiment.get_RZ(),experiment.get_RA());
			string e=experiment.channelnames(experiment.get_EZ(),experiment.get_EA());
			experiment.manual_primary_dist_hist.SetLineWidth(2);			
			
			TH1D full;
			// Get theta CM for different hit conditions					
			// Fetch the manual CM distribution histogram and the speed masked one
			// We want to show the mask so we know we havent cut it too small			
			can_view->Clear();
			can_view->Divide(2);
			can_view->cd(1);
				experiment.mask_manual(t_d,t_u,true,false);//saves on wasted computation
				full=experiment.manual_primary_dist_store;
				ra=experiment.manual_primary_dist_hist.Integral();//Ask what fraction we have masked too, as unmask integral = 1			
				full.SetTitle(("CM_theta_dist_"+r+"_gated").c_str());
				
				//Get theta CM for different hit condition	
				TH1D recoh=experiment.theta_hist(500000,true,1,0,0,0);
				recoh.SetLineColor(2);		
				recoh.Scale(ra*(full.GetBinWidth(1)/recoh.GetBinWidth(1)));//Some basic scaling to match distribution histogram	

				full.DrawCopy();
				experiment.manual_primary_dist_hist.DrawCopy("same");
				recoh.DrawCopy("same");
			can_view->cd(2);
				experiment.mask_manual(t_d,t_u,false,true);//saves on wasted computation
				full=experiment.manual_primary_dist_store;
				ra=experiment.manual_primary_dist_hist.Integral();
				full.SetTitle(("CM_theta_dist_"+e+"_gated").c_str());
				
				TH1D ejech=experiment.theta_hist(500000,true,0,1,0,0);
				ejech.SetLineColor(2);				
				ejech.Scale(ra*(full.GetBinWidth(1)/ejech.GetBinWidth(1)));
				
				full.DrawCopy();
				experiment.manual_primary_dist_hist.DrawCopy("same");
				ejech.DrawCopy("same");
			outfile->cd();
			can_view->SetName("CM_angles");can_view->Write("CM_angles",TObject::kOverwrite);
			gROOT->cd(); 			
			
			can_view->Clear();
			can_view->Divide(2);
			can_view->cd(1);
			experiment.mask_manual(t_d,t_u,true,false);//saves on wasted computation
				experiment.draw_hit_pattern_2D(1,500000,1,1,0);
				((TH2D*)gPad->GetPrimitive("Hit_Map_copy"))->SetTitle(r.c_str());
			can_view->cd(2);
				experiment.mask_manual(t_d,t_u,false,true);//saves on wasted computation
				experiment.draw_hit_pattern_2D(1,500000,1,0,1);
				((TH2D*)gPad->GetPrimitive("Hit_Map_copy"))->SetTitle(e.c_str());
			outfile->cd();
			can_view->SetName("Hit_map_ditribution");can_view->Write("Hit_map_ditribution",TObject::kOverwrite);
			gROOT->cd(); 		
			
			
			can_view->Clear();
			can_view->cd();
				experiment.mask_manual(t_d,t_u,true,true);//saves on wasted computation
				experiment.auto_E_theta(500000,1,1,1);
			outfile->cd();
			can_view->SetName("Theta_E");can_view->Write("Theta_E",TObject::kOverwrite);
			gROOT->cd(); 

		}
		
		if(control==5){spice_auto_setup(experiment,config,S3,overr);
			can_view->Clear();
			can_view->cd();
			experiment.draw_hits_3D(2);
		}
	}
	
	
	

	
	
	
	
	
	
// 
// 	// Next we spend 20 seconds drawing events so that if something is very wrong it can be corrected
// 	// We set multiplicity=1 so it will only show us S3 good events
// 	experiment.draw_hits_3D(2,1,true,0.5,1,true,20);
// 	//draw_hits_3D(projection,hit_multiplicity,obstructions,display_time,refresh_rate,draw_misses,run_time)
// 
// 	
// 	


	
	
	
	
if(save_text){
	std::cout.rdbuf(backup);        // restore cout's original streambuf
	filestr.close();
		
	string x;
	ifstream inFile(file_title+".txt");
	while (getline(inFile,x)){
	cout << x << endl ;
	}
	inFile.close();

	outfile->cd();
	TMacro mac((file_title+".txt").c_str()); 
	mac.Write("terminal.txt",TObject::kOverwrite);
}	


	outfile->Close();
	cout<<endl<<"/////////////////////////////////////////////////////////////////////////"<<endl;	
	app->Run();
	return 0;
}	
void BayesUnfoldingExample641()
{

#ifdef __CINT__ // Avoid CINT badness
  Printf("Please compile this script (root BayesUnfoldingExample641.C+) "
         "or use ROOT 6.");
  gSystem->Exit(0);
#endif

  if (!gROOT->IsBatch())
  {
    Printf("Several canvases coming...adding -b flag.");
    gROOT->SetBatch();
  }

  gStyle->SetOptStat(0);
  gStyle->SetPaintTextFormat(".2f");

  if (gSystem->Getenv("TMPDIR"))
    gSystem->SetBuildDir(gSystem->Getenv("TMPDIR"));

  TRandom3 ran;
  TStopwatch watch; // Watch starts here. A call to Start() would reset it.

  TObjArray *cList = new TObjArray(); // List of drawn canvases --> PDF file

  // Set up the problem
  double bins[Nt+1] = {0};
  for (int j=0; j<=Nt; j++)
    bins[j] = 500*TMath::Exp(0.15*j);

  TestProblem testprob = AtlasDiJetMass(Nt, Nr, bins, bins,
                                        apar, bpar, nevts, evtWeight);
  TH2D *hM   = testprob.Response;
  TH1D *hT   = testprob.xTruth;
  TH1D *hTmc = testprob.xTruthEst;
  TH1D *hMt  = testprob.xIni;
  TH1D *hD   = testprob.bNoisy;
  TH1D *heff = testprob.eff;
  SetHistProps(hT,kRed+2,kNone,kRed+2);
  SetHistProps(hTmc,kRed,kNone,kRed);
  SetHistProps(hD,kBlack,kNone,kBlack,kFullCircle,1.5);

  TMatrixD M   = MatrixUtils::Hist2Matrix(hM);
  TVectorD T   = MatrixUtils::Hist2Vec(hT);   // \hat{T}
  TVectorD Tmc = MatrixUtils::Hist2Vec(hTmc); // \tilde{T}
  TVectorD D   = MatrixUtils::Hist2Vec(hD);
  TVectorD eff = MatrixUtils::Hist2Vec(heff);
  TVectorD Pt  = MatrixUtils::ElemDiv(MatrixUtils::Hist2Vec(hMt), eff); // P(t)
  TMatrixD Prt = MatrixUtils::DivRowsByVector(M, Pt);  // P(r|t)

  // Compute initial sampling volume and do MCMC sampling
  TGraphAsymmErrors *box = HyperBox(hTmc);
  SetGraphProps(box, kGreen+2, kNone, kSpring, kFullSquare, 1.0);

  // Likelihood functor
  LogPoissonLikeFn llfunc(Prt, D);

  // Curvature regularization.
  // Note that this is not directly penalizing curvature of the solution.
  // Instead it smooths the solution divided by the trial spectrum.
  std::vector<double> regpars;
  regpars.push_back(alpha);  // Regularization strength
  for (int i=0; i<box->GetN(); i++)
    regpars.push_back(box->GetY()[i]);

  CurvatureRegFn regfunc(regpars);

  TTree *tmcmc = SampleMH(nMcmcSamples, 1e4, 0.01, box, llfunc, regfunc);

  // Create marginal prob. distributions from MCMC
  std::cout << Form("Marginalizing parameters from Markov chain...")
            << std::flush;

  TH1D *hMCMC[Nt];
  for (int t=0; t<Nt; t++)
  {
    double tlo = box->GetY()[t] - box->GetEYlow()[t];
    double thi = box->GetY()[t] + box->GetEYhigh()[t];
    hMCMC[t] = new TH1D(Form("hMCMC%d",t),"",nMcmcBins, tlo, thi);
    hMCMC[t]->SetTitle(Form("MCMC - point %d;"
                            "entries;"
                            "Marginal posterior probability",t));

    // Marginalize with unit weight when using MCMC, weight by
    // likelihood if sampling was uniform.
    tmcmc->Draw(Form("T%d >> hMCMC%d",t,t), "", "goff");
    hMCMC[t]->Scale(1./hMCMC[t]->Integral(1, nMcmcBins));
    SetHistProps(hMCMC[t], kBlack, kYellow, kBlack, kFullCircle, 1.0);
    hMCMC[t]->GetYaxis()->SetTitleOffset(1.5);
  }
  Printf("Done marginalizing MCMC.");

  // Now compute reduced sampling volume, and do uniform sampling
  TGraphAsymmErrors *rbox = ReducedSamplingVolume(hMCMC, box);
  SetGraphProps(rbox, kBlack, kNone, kNone, kFullSquare, 1.0);
  TH1D *hFlat[Nt];
  if (doUniformSampling)
  {
    TTree *tflat = SampleUniform(nFlatSamples, D, Prt, rbox);
    std::cout << Form("Marginalizing parameters from uniform volume...")
              << std::flush;

    for (int t=0; t<Nt; t++)
    {
      double tlo = rbox->GetY()[t] - rbox->GetEYlow()[t];
      double thi = rbox->GetY()[t] + rbox->GetEYhigh()[t];
      hFlat[t] = new TH1D(Form("hFlat%d",t),"",nFlatBins, tlo, thi);
      hFlat[t]->SetTitle(Form("Uniform sampling - point %d;"
                              "dijet mass (GeV/c^{2});"
                              "Marginal posterior probability",t));

      tflat->Draw(Form("T%d >> hFlat%d",t,t), "L", "goff");
      hFlat[t]->Scale(1./hFlat[t]->Integral(1,nFlatBins));
      SetHistProps(hFlat[t], kBlack, kOrange, kBlack, kFullCircle, 1.0);
    }
    Printf("Done marginalizing uniform volume.");
  }

  // Unfolded spectrum from MCMC
  TGraphErrors *unf1 = new TGraphErrors();
  SetGraphProps(unf1, kBlue, kNone, kBlue, kOpenSquare, 1.5);
  unf1->SetLineWidth(2);
  for (int t=0; t<Nt; t++)
  {
    MaxDensityInterval mdi = GetMDI(hMCMC[t], 0.68);
    unf1->SetPoint(t, hD->GetBinCenter(t+1), mdi.u);
    unf1->SetPointError(t, 0.48*hD->GetBinWidth(t+1), mdi.du);
  }

  // Unfolded spectrum from uniform sampling after volume reduction
  TGraphErrors *unf2 = 0;
  if (doUniformSampling)
  {
    unf2 = new TGraphErrors();
    SetGraphProps(unf2, kRed, kNone, kRed, kOpenSquare, 1.5);
    unf2->SetLineWidth(2);

    for (int t=0; t<Nt; t++)
    {
      MaxDensityInterval mdi = GetMDI(hFlat[t], 0.68);
      unf2->SetPoint(t, hD->GetBinCenter(t+1), mdi.u);
      unf2->SetPointError(t, 0.47*hD->GetBinWidth(t+1), mdi.du);
    }
  }

  Printf("Drawing results...");
  DrawObject(hM, "colz", "matrix", cList, 550, 500);
  gPad->SetLogx();  gPad->SetLogy();  gPad->SetLogz();
  gPad->SetRightMargin(0.15);

  DrawObject(heff, "", "efficiency", cList);

  // Draw marginal dists. from MCMC
  for (int t=0; t<Nt; t++)
  {
    DrawObject(hMCMC[t], "", Form("post_%d", t), cList);
    gPad->SetLeftMargin(0.15);

    if (doUniformSampling)
    {
      hFlat[t]->Scale(1./hFlat[t]->Integral(1, nFlatBins,"width"));
      hFlat[t]->Draw("same");
    }

    double ymin = hMCMC[t]->GetMinimum();
    double ymax = hMCMC[t]->GetMaximum();
    double yDraw = 0.25*(ymax-ymin);
    DataPoint(hD, hMCMC[t], t, 0.75*yDraw)->Draw("ep same");
    TruePoint(hT, hMCMC[t], t, yDraw)->Draw("p same");
    MD68Point(hMCMC[t], yDraw)->Draw("ep same");
  }

  // Result!
  hT->GetYaxis()->SetRangeUser(0.002, 101*nevts*evtWeight);
  DrawObject(hT, "ep", "result", cList);
  gPad->SetLogy();
  box->Draw("e5 same");
  if (doUniformSampling || drawReducedVolume)
    rbox->Draw("e5 same");
  hT->Draw("same");
  hD->Draw("ep same");
  unf1->Draw("ep same");
  if (unf2)
    unf2->Draw("ep same");

  if (printPDFs)
  {
    PrintPDFs(cList, "pdfs"); // Print individuals into ./pdfs dir
    PrintPDF(cList, "pdfs/mcmc_unfold_example"); // Multipage PDF
  }

  Printf("All done.");
  watch.Stop();
  watch.Print();

  return;
}
Example #22
0
TH1D *
GetITSsaRatio(TFile *file, Int_t num, Int_t den, Int_t cent, Bool_t cutSpectrum = kTRUE, Bool_t addSystematicError = kTRUE)
{
  /* pt limits for combined spectra */
  //  Double_t ptMin[AliPID::kSPECIES] = {0., 0., 0.1, 0.2, 0.3};
  //  Double_t ptMax[AliPID::kSPECIES] = {0., 0., 0.6, 0.5, 0.6};

  TH1 *hnum, *hden;
  Double_t ptMin = 0., ptMax = 10.;
  switch (num) {
  case kPiMinus:
    ptMin = TMath::Min(ptMin, 0.1);
    ptMax = TMath::Min(ptMax, 0.6);
    hnum = GetITSsaSpectrum(file, AliPID::kPion, 1, cent, kFALSE, kFALSE);
    break;
  case kPiPlus:
    ptMin = TMath::Min(ptMin, 0.1);
    ptMax = TMath::Min(ptMax, 0.6);
    hnum = GetITSsaSpectrum(file, AliPID::kPion, 0, cent, kFALSE, kFALSE);
    break;
  case kPi:
    ptMin = TMath::Min(ptMin, 0.1);
    ptMax = TMath::Min(ptMax, 0.6);
    hnum = GetITSsaSpectrum(file, AliPID::kPion, 1, cent, kFALSE, kFALSE);
    hnum->Add(GetITSsaSpectrum(file, AliPID::kPion, 0, cent, kFALSE, kFALSE));
    break;
  case kKaMinus:
    ptMin = TMath::Min(ptMin, 0.2);
    ptMax = TMath::Min(ptMax, 0.5);
    hnum = GetITSsaSpectrum(file, AliPID::kKaon, 1, cent, kFALSE, kFALSE);
    break;
  case kKaPlus:
    ptMin = TMath::Min(ptMin, 0.2);
    ptMax = TMath::Min(ptMax, 0.5);
    hnum = GetITSsaSpectrum(file, AliPID::kKaon, 0, cent, kFALSE, kFALSE);
    break;
  case kKa:
    ptMin = TMath::Min(ptMin, 0.2);
    ptMax = TMath::Min(ptMax, 0.5);
    hnum = GetITSsaSpectrum(file, AliPID::kKaon, 1, cent, kFALSE, kFALSE);
    hnum->Add(GetITSsaSpectrum(file, AliPID::kKaon, 0, cent, kFALSE, kFALSE));
    break;
  case kPrMinus:
    ptMin = TMath::Min(ptMin, 0.3);
    ptMax = TMath::Min(ptMax, 0.6);
    hnum = GetITSsaSpectrum(file, AliPID::kProton, 1, cent, kFALSE, kFALSE);
    break;
  case kPrPlus:
    ptMin = TMath::Min(ptMin, 0.3);
    ptMax = TMath::Min(ptMax, 0.6);
    hnum = GetITSsaSpectrum(file, AliPID::kProton, 0, cent, kFALSE, kFALSE);
    break;
  case kPr:
    ptMin = TMath::Min(ptMin, 0.3);
    ptMax = TMath::Min(ptMax, 0.6);
    hnum = GetITSsaSpectrum(file, AliPID::kProton, 1, cent, kFALSE, kFALSE);
    hnum->Add(GetITSsaSpectrum(file, AliPID::kProton, 0, cent, kFALSE, kFALSE));
    break;
  }
  switch (den) {
  case kPiMinus:
    ptMin = TMath::Max(ptMin, 0.1);
    ptMax = TMath::Min(ptMax, 0.6);
    hden = GetITSsaSpectrum(file, AliPID::kPion, 1, cent, kFALSE, kFALSE);
    break;
  case kPiPlus:
    ptMin = TMath::Max(ptMin, 0.1);
    ptMax = TMath::Min(ptMax, 0.6);
    hden = GetITSsaSpectrum(file, AliPID::kPion, 0, cent, kFALSE, kFALSE);
    break;
  case kPi:
    ptMin = TMath::Max(ptMin, 0.1);
    ptMax = TMath::Min(ptMax, 0.6);
    hden = GetITSsaSpectrum(file, AliPID::kPion, 1, cent, kFALSE, kFALSE);
    hden->Add(GetITSsaSpectrum(file, AliPID::kPion, 0, cent, kFALSE, kFALSE));
    break;
  case kKaMinus:
    ptMin = TMath::Max(ptMin, 0.2);
    ptMax = TMath::Min(ptMax, 0.5);
    hden = GetITSsaSpectrum(file, AliPID::kKaon, 1, cent, kFALSE, kFALSE);
    break;
  case kKaPlus:
    ptMin = TMath::Max(ptMin, 0.2);
    ptMax = TMath::Min(ptMax, 0.5);
    hden = GetITSsaSpectrum(file, AliPID::kKaon, 0, cent, kFALSE, kFALSE);
    break;
  case kKa:
    ptMin = TMath::Max(ptMin, 0.2);
    ptMax = TMath::Min(ptMax, 0.5);
    hden = GetITSsaSpectrum(file, AliPID::kKaon, 1, cent, kFALSE, kFALSE);
    hden->Add(GetITSsaSpectrum(file, AliPID::kKaon, 0, cent, kFALSE, kFALSE));
    break;
  case kPrMinus:
    ptMin = TMath::Max(ptMin, 0.3);
    ptMax = TMath::Min(ptMax, 0.6);
    hden = GetITSsaSpectrum(file, AliPID::kProton, 1, cent, kFALSE, kFALSE);
    break;
  case kPrPlus:
    ptMin = TMath::Max(ptMin, 0.3);
    ptMax = TMath::Min(ptMax, 0.6);
    hden = GetITSsaSpectrum(file, AliPID::kProton, 0, cent, kFALSE, kFALSE);
    break;
  case kPr:
    ptMin = TMath::Max(ptMin, 0.3);
    ptMax = TMath::Min(ptMax, 0.6);
    hden = GetITSsaSpectrum(file, AliPID::kProton, 1, cent, kFALSE, kFALSE);
    hden->Add(GetITSsaSpectrum(file, AliPID::kProton, 0, cent, kFALSE, kFALSE));
    break;
  }

  if (!hnum || !hden) return NULL;  

  Char_t sysname[1024];
  if (num == kPiMinus && den == kPiPlus)
    sprintf(sysname, "Pi_Pos2Neg");
  else if (num == kKaMinus && den == kKaPlus)
    sprintf(sysname, "K_Pos2Neg");
  else if (num == kPrMinus && den == kPrPlus)
    sprintf(sysname, "P_Pos2Neg");
  else if ((num == kKa || num == kKaPlus || num == kKaMinus)
	   && (den == kPi || den == kPiPlus || den == kPiMinus))
    sprintf(sysname, "K2Pi");
  else if ((num == kPr || num == kPrPlus || num == kPrMinus)
	   && (den == kPi || den == kPiPlus || den == kPiMinus))
    sprintf(sysname, "P2Pi");

  TH1D *hin = (TH1D *)hnum->Clone("hin");
  hin->Divide(hden);

  /* get systematics */
  TFile *fsys = TFile::Open("RATIOSYS_ITSsa.root");
  TH1 *hsys = fsys->Get(Form("hSystTot%s", sysname));
			
  TH1D *h = new TH1D(Form("hITSsa_cent%d_%s_%s", cent, ratioName[num], ratioName[den]), "ITSsa", NptBins, ptBin);
  Double_t pt, width, value, error, sys;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001) {
      //      printf("skipping %f because of sanity checks\n", pt);
      continue;
    }
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin || pt > ptMax)) {
      //      printf("skipping %f because of limits\n", pt);
      continue;
    }
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    /*** TEMP ADD SYS ***/
    if (addSystematicError) {
      sys = hsys->GetBinContent(bin) * value;
      error = TMath::Sqrt(error * error + sys * sys);
    }
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }

  h->SetTitle("ITSsa");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(20);
  h->SetMarkerColor(1);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  return h;
}
Example #23
0
void bToDRawYield()
{
	gStyle->SetTextSize(0.05);
	gStyle->SetTextFont(42);
	gStyle->SetPadRightMargin(0.04);
	gStyle->SetPadLeftMargin(0.14);
	gStyle->SetPadTopMargin(0.1);
	gStyle->SetPadBottomMargin(0.14);
	gStyle->SetTitleX(.0f);
	gStyle->SetOptFit(1111);
	gStyle->SetOptStat(0);
	gStyle->SetOptTitle(0);

	TCanvas* c4 = new TCanvas("c4","",800,600);
	c4->Divide(2,2);

	TCanvas* c2 = new TCanvas("c2","",400,600);
	c2->Divide(1,2);

	TCanvas* c1 = new TCanvas();

	TCanvas* c15 = new TCanvas("c15","",810,1000);
	c15->Divide(3,5);

	TFile* fPbPb = new TFile("bFeedDownPbPb.hist.root");
	TFile* fPbPbMB = new TFile("bFeedDownPbPbMB.hist.root");
	TFile* fPbPbMC = new TFile("bFeedDownPbPbMC.hist.root");
	TFile* fPbPbMBMC = new TFile("bFeedDownPbPbMBMC.hist.root");

	TH3D* hDataPbPb = (TH3D*)fPbPb->Get("hData");
	TH3D* hSidebandPbPb = (TH3D*)fPbPb->Get("hSideband");
	TH3D* hDataPbPbMB = (TH3D*)fPbPbMB->Get("hData");
	TH3D* hSidebandPbPbMB = (TH3D*)fPbPbMB->Get("hSideband");
	TH3D* hPtMD0DcaPbPb = (TH3D*)fPbPb->Get("hPtMD0Dca");
	TH3D* hPtMD0DcaPbPbMB = (TH3D*)fPbPbMB->Get("hPtMD0Dca");

	TH3D* hMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCNPSignal");
	TH3D* hMCPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCNPSignal");
	TH3D* hPtMD0DcaMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSwapped");
	TH3D* hPtMD0DcaMCPSignalPbPbMB =(TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPbMB = (TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSwapped");

	TH3D* hData = (TH3D*)hDataPbPb->Clone("hData");
	hData->Sumw2();
	hData->Add(hDataPbPbMB);

	TH3D* hSideband = (TH3D*)hSidebandPbPb->Clone("hSideband");
	hSideband->Sumw2();
	hSideband->Add(hSidebandPbPbMB);

	TH3D* hPtMD0Dca = (TH3D*)hPtMD0DcaPbPb->Clone("hPtMD0Dca");
	hPtMD0Dca->Sumw2();
	hPtMD0Dca->Add(hPtMD0DcaPbPbMB);

	TH3D* hMCPSignal = (TH3D*)hMCPSignalPbPb->Clone("hMCPSignal");
	hMCPSignal->Sumw2();
	hMCPSignal->Add(hMCPSignalPbPbMB);

	TH3D* hMCNPSignal = (TH3D*)hMCNPSignalPbPb->Clone("hMCNPSignal");
	hMCNPSignal->Sumw2();
	hMCNPSignal->Add(hMCNPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSignal = (TH3D*)hPtMD0DcaMCPSignalPbPb->Clone("hPtMD0DcaMCPSignal");
	hPtMD0DcaMCPSignal->Sumw2();
	hPtMD0DcaMCPSignal->Add(hPtMD0DcaMCPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSwapped =(TH3D*)hPtMD0DcaMCPSwappedPbPb->Clone("hPtMD0DcaMCPSwapped");
	hPtMD0DcaMCPSwapped->Sumw2();
	hPtMD0DcaMCPSwapped->Add(hPtMD0DcaMCPSwappedPbPbMB);

	TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
	texCms->SetNDC();
	texCms->SetTextAlign(12);
	texCms->SetTextSize(0.06);
	texCms->SetTextFont(42);

	TLatex* texCol = new TLatex(0.96,0.93, "PbPb #sqrt{s_{NN}} = 5.02 TeV");
	texCol->SetNDC();
	texCol->SetTextAlign(32);
	texCol->SetTextSize(0.06);
	texCol->SetTextFont(42);

	const int nPtBins = 14;
	float ptBins[nPtBins+1] = {2.,3.,4.,5.,6.,8.,10.,12.5,15.0,20.,25.,30.,40.,60.,100};

	float pts[nPtBins];
	float ptErrors[nPtBins];
	float promptFraction[nPtBins];
	float totalYield[nPtBins];
	float totalYieldInvMassFit[nPtBins];
	float totalYieldInvMassFitError[nPtBins];
	float bToDYield[nPtBins];
	float bToDYieldError[nPtBins];
	float bToDYieldErrorDataOnly[nPtBins];
	float promptDYield[nPtBins];
	float promptDYieldError[nPtBins];
	float promptDYieldErrorDataOnly[nPtBins];

	const int nBinY = 14;
	Float_t binsY[nBinY+1];
	float firstBinYWidth = 0.001;
	float binYWidthRatio = 1.27;
	binsY[0]=0;
	for(int i=1; i<=nBinY; i++)
		binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1);
	cout<<"last y bin: "<<binsY[nBinY]<<endl;

	//  for(int i=1; i<=nPtBins; i++)
	for(int i =7; i<=7; i++)
	{
		pts[i-1] = 0.5*(ptBins[i-1]+ptBins[i]);
		ptErrors[i-1] = 0.5*(ptBins[i]-ptBins[i-1]);
		float ptLow = ptBins[i-1];
		float ptHigh = ptBins[i];
		cout<<endl<<"======================================="<<endl;
		cout<<"pT range: "<<ptLow<<" "<<ptHigh<<endl;

		TLatex* texPtY = new TLatex(0.32,0.82,Form("%.1f < p_{T} < %.1f GeV/c      |y| < 1.0",ptLow,ptHigh));
		texPtY->SetNDC();
		texPtY->SetTextFont(42);
		texPtY->SetTextSize(0.06);
		texPtY->SetLineWidth(2);

		TLatex* texPt = new TLatex(0.18,0.82,Form("%.1f < p_{T} < %.1f GeV/c",ptLow,ptHigh));
		texPt->SetNDC();
		texPt->SetTextFont(42);
		texPt->SetTextSize(0.06);
		texPt->SetLineWidth(2);

		TLatex* texY = new TLatex(0.18,0.74,Form("|y| < 1.0"));
		texY->SetNDC();
		texY->SetTextFont(42);
		texY->SetTextSize(0.06);
		texY->SetLineWidth(2);

		c2->cd(1);

		hPtMD0Dca->GetZaxis()->SetRange(1,100);
		hPtMD0Dca->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSwapped->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		TH1D* hMData = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_%1.1f_%1.1f", ptLow, ptHigh));
		TH1D* hMMCSignal = (TH1D*)hPtMD0DcaMCPSignal->Project3D("y");
		TH1D* hMMCSwapped = (TH1D*)hPtMD0DcaMCPSwapped->Project3D("y");

		setColorTitleLabel(hMData);
		setColorTitleLabel(hMMCSignal);
		setColorTitleLabel(hMMCSwapped);

		TF1* fMass = fitMass(hMData, hMMCSignal, hMMCSwapped);

		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		TF1* fSignalAndSwapped = new TF1("fSignalAndSwapped","[0]*([3]*([5]*Gaus(x,[1],[2]*(1+[7]))/(sqrt(2*3.1415927)*[2]*(1+[7]))+(1-[5])*Gaus(x,[1],[6]*(1+[7]))/(sqrt(2*3.1415927)*[6]*(1+[7])))+(1-[3])*Gaus(x,[1],[4]*(1+[7]))/(sqrt(2*3.1415927)*[4]*(1+[7])))", 1.7, 2.0);      
		fSignalAndSwapped->SetParameter(0,fMass->GetParameter(0));
		fSignalAndSwapped->SetParameter(1,fMass->GetParameter(1));
		fSignalAndSwapped->SetParameter(2,fMass->GetParameter(2));
		fSignalAndSwapped->SetParameter(3,fMass->GetParameter(7));
		fSignalAndSwapped->SetParameter(4,fMass->GetParameter(8));
		fSignalAndSwapped->SetParameter(5,fMass->GetParameter(9));
		fSignalAndSwapped->SetParameter(6,fMass->GetParameter(10));
		fSignalAndSwapped->SetParameter(7,fMass->GetParameter(11));

		TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
		background->SetParameter(0,fMass->GetParameter(3));
		background->SetParameter(1,fMass->GetParameter(4));
		background->SetParameter(2,fMass->GetParameter(5));
		background->SetParameter(3,fMass->GetParameter(6));

		cout<<"MC signal width: "<<fMass->GetParameter(2)<<"   "<<fMass->GetParameter(10)<<endl;
		cout<<"MC swapped width: "<<fMass->GetParameter(8)<<endl;

		float massD = 1.8649;
		float massSignal1 = massD-0.025;
		float massSignal2 = massD+0.025;
		float massSideBand1 = massD-0.1;
		float massSideBand2 = massD-0.075;
		float massSideBand3 = massD+0.075;
		float massSideBand4 = massD+0.1;

		float scaleSideBandBackground = background->Integral(massSignal1, massSignal2)/(background->Integral(massSideBand1, massSideBand2)+background->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandBackground: "<<scaleSideBandBackground<<endl;
		totalYieldInvMassFit[i-1] = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		totalYieldInvMassFitError[i-1] = fMass->GetParError(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		cout<<"totalYieldInvMassFit: "<<totalYieldInvMassFit[i-1]<<" +- "<<totalYieldInvMassFitError[i-1]<<endl;
		float scaleSideBandMethodSignal = fSignalAndSwapped->GetParameter(0)*fSignalAndSwapped->GetParameter(3) / (fSignalAndSwapped->Integral(massSignal1, massSignal2)-fSignalAndSwapped->Integral(massSideBand1, massSideBand2)-fSignalAndSwapped->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandMethodSignal: "<<scaleSideBandMethodSignal<<endl;

		TLatex* texScale = new TLatex(0.18,0.66,Form("side band bg scale: %1.3f", scaleSideBandBackground));
		texScale->SetNDC();
		texScale->SetTextFont(42);
		texScale->SetTextSize(0.06);
		texScale->SetLineWidth(2);
		texScale->Draw();

		TLine* lineSignal1 = new TLine(massSignal1, 0, massSignal1, hMData->GetMaximum()*0.5);
		TLine* lineSignal2 = new TLine(massSignal2, 0, massSignal2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand1 = new TLine(massSideBand1, 0, massSideBand1, hMData->GetMaximum()*0.5);
		TLine* lineSideBand2 = new TLine(massSideBand2, 0, massSideBand2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand3 = new TLine(massSideBand3, 0, massSideBand3, hMData->GetMaximum()*0.5);
		TLine* lineSideBand4 = new TLine(massSideBand4, 0, massSideBand4, hMData->GetMaximum()*0.5);
		lineSignal1->Draw();
		lineSignal2->Draw();
		lineSideBand1->Draw();
		lineSideBand2->Draw();
		lineSideBand3->Draw();
		lineSideBand4->Draw();

		c2->cd(2);
		gPad->SetLogy();

		hData->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hSideband->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCNPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);

		TH1D* hD0DcaData0 = (TH1D*)hData->Project3D("y")->Clone("hD0DcaData0");
		TH1D* hD0DcaSideband = (TH1D*)hSideband->Project3D("y")->Clone("hD0DcaSideband");
		TH1D* hD0DcaMCPSignal0 = (TH1D*)hMCPSignal->Project3D("y")->Clone("hD0DcaMCPSignal0");
		TH1D* hD0DcaMCNPSignal0 = (TH1D*)hMCNPSignal->Project3D("y")->Clone("hD0DcaMCNPSignal0");

		float integralRawYieldMCP = hD0DcaMCPSignal0->Integral();
		float integralRawYieldMCNP = hD0DcaMCNPSignal0->Integral();
		cout<<"integralRawYieldMCP: "<<integralRawYieldMCP<<endl;
		cout<<"integralRawYieldMCNP: "<<integralRawYieldMCNP<<endl;

		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;

		divideBinWidth(hD0DcaData0);
		divideBinWidth(hD0DcaSideband);
		setColorTitleLabel(hD0DcaData0, 1);
		hD0DcaData0->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData0->GetYaxis()->SetTitle("counts per cm");

		TH1D* hD0DcaSideband0 = (TH1D*)hD0DcaSideband->Clone("hD0DcaSideband0");
		hD0DcaSideband->Scale(scaleSideBandBackground);

		TH1D* hD0DcaDataSubSideBand = (TH1D*)hD0DcaData0->Clone("hD0DcaDataSubSideBand");
		hD0DcaDataSubSideBand->Add(hD0DcaSideband,-1);
		hD0DcaDataSubSideBand->Scale(scaleSideBandMethodSignal);

		hD0DcaData0->SetMarkerSize(0.6);
		hD0DcaData0->Draw();
		hD0DcaSideband->Draw("hsame");
		hD0DcaSideband0->SetLineStyle(2);
		hD0DcaSideband0->Draw("hsame");

		TLegend* leg1 = new TLegend(0.44,0.6,0.90,0.76,NULL,"brNDC");
		leg1->SetBorderSize(0);
		leg1->SetTextSize(0.06);
		leg1->SetTextFont(42);
		leg1->SetFillStyle(0);
		leg1->AddEntry(hD0DcaData0,"D^{0} candidate","pl");
		leg1->AddEntry(hD0DcaSideband,"side band","l");
		leg1->AddEntry(hD0DcaSideband0,"side band unscaled","l");
		leg1->Draw("same");

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_sideBand.pdf",ptLow,ptHigh));

		c2->cd(1);
		hMMCSignal->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->cd(2);
		gPad->SetLogy(0);
		hMMCSwapped->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_McInvMassFit.pdf",ptLow,ptHigh));

		c15->cd(1);

		fitMass(hMData, hMMCSignal, hMMCSwapped);

		texPt->Draw();
		texY->Draw();

		TH1D* hD0DcaDataFit = new TH1D("hD0DcaDataFit", ";D^{0} DCA (cm);dN / d(D^{0} DCA) (cm^{-1})", nBinY, binsY);

		for(int j=1; j<=14; j++)
		{
			c15->cd(j+1);
			hPtMD0Dca->GetZaxis()->SetRange(j,j);
			float D0DcaLow = hPtMD0Dca->GetZaxis()->GetBinLowEdge(j);
			float D0DcaHigh = hPtMD0Dca->GetZaxis()->GetBinUpEdge(j);
			TH1D* hMData_D0Dca = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_pt_%1.1f_%1.1f_D0Dca_%1.4f_%1.4f", ptLow, ptHigh, D0DcaLow, D0DcaHigh));
			setColorTitleLabel(hMData_D0Dca);
			fMass = fitMass(hMData_D0Dca, hMMCSignal, hMMCSwapped);

			float yield = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);
			float yieldError = fMass->GetParError(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);

			hD0DcaDataFit->SetBinContent(j, yield);
			hD0DcaDataFit->SetBinError(j, yieldError);

			TLatex* texD0Dca = new TLatex(0.18,0.82,Form("D^{0} DCA: %1.4f - %1.4f",D0DcaLow,D0DcaHigh));
			texD0Dca->SetNDC();
			texD0Dca->SetTextFont(42);
			texD0Dca->SetTextSize(0.06);
			texD0Dca->SetLineWidth(2);
			texD0Dca->Draw();

			TLatex* texYield = new TLatex(0.18,0.74,Form("D^{0} yield: %1.0f #pm %1.0f",yield,yieldError));
			texYield->SetNDC();
			texYield->SetTextFont(42);
			texYield->SetTextSize(0.06);
			texYield->SetLineWidth(2);
			texYield->Draw();
		}

		c15->SaveAs(Form("plots/PbPb_%.0f_%.0f_invMassFit.pdf",ptLow,ptHigh));

		divideBinWidth(hD0DcaDataFit);

		c4->cd(1);
		gPad->SetLogy();

		normalize(hD0DcaMCPSignal);
		setColorTitleLabel(hD0DcaMCPSignal, 2);
		hD0DcaMCPSignal->GetXaxis()->SetRangeUser(0,0.07);

		normalize(hD0DcaMCNPSignal);
		setColorTitleLabel(hD0DcaMCNPSignal, 4);
		hD0DcaMCNPSignal->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaMCNPSignal->GetYaxis()->SetTitle("dN / d(D^{0} DCA) (cm^{-1})");
		hD0DcaMCNPSignal->GetXaxis()->SetTitle("D^{0} DCA (cm)");
		hD0DcaMCNPSignal->SetMaximum(hD0DcaMCPSignal->GetMaximum()*3.);

		hD0DcaMCNPSignal->Draw("");
		hD0DcaMCPSignal->Draw("same");

		TLegend* leg2 = new TLegend(0.54,0.72,0.90,0.88,NULL,"brNDC");
		leg2->SetBorderSize(0);
		leg2->SetTextSize(0.06);
		leg2->SetTextFont(42);
		leg2->SetFillStyle(0);
		leg2->AddEntry(hD0DcaMCPSignal,"MC Prompt D^{0}","pl");
		leg2->AddEntry(hD0DcaMCNPSignal,"MC Non-prompt D^{0}","pl");
		leg2->Draw("same");

		c4->cd(2);
		gPad->SetLogy();

		TH1D* hD0DcaData = hD0DcaDataFit;
		if(pts[i-1]>20) hD0DcaData = hD0DcaDataSubSideBand;

		setColorTitleLabel(hD0DcaData, 1);

		double integralTotalYield = hD0DcaData->Integral(1,hD0DcaData->GetXaxis()->GetNbins(),"width");
		cout<<"integralTotalYield: "<<integralTotalYield<<endl;

		TF1* fMix = new TF1("fMix",&funMix, 0., 0.5, 2);
		fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
		fMix->SetParLimits(0,0,2*integralTotalYield);
		fMix->SetParLimits(1,0,2*integralTotalYield);

		fMix->SetLineColor(2);
		fMix->SetFillColor(kRed-9);
		fMix->SetFillStyle(1001);

		float fitRangeL = 0;
		float fitRangeH = 0.08;

		hD0DcaData->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData->Draw();
		int fitStatus = 1;
		TFitResultPtr fitResult;
		double fitPrecision = 1.e-6;
		while(fitStatus)
		{
			TFitter::SetPrecision(fitPrecision);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);
			fitResult = hD0DcaData->Fit("fMix","E SNQ0", "", fitRangeL, fitRangeH);
			fitStatus = fitResult->Status();
			cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;
			if(fitStatus)
				fitPrecision *= 10;
		}
		cout<<"============== do main fit ============"<<endl;
		fMix->SetParameters(integralTotalYield,0.9);
		fMix->SetParError(0,0.1*integralTotalYield);
		fMix->SetParError(1,0.1);
		fMix->SetNpx(10000);
		fitResult = hD0DcaData->Fit("fMix","E S0", "", fitRangeL, fitRangeH);
		hD0DcaData->GetFunction("fMix")->Draw("flsame");
		fitStatus = fitResult->Status();
		cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;

		TF1* fNP = new TF1("fNP",&funNonPrompt, 0., 0.5, 2);
		fNP->SetParameters(fMix->GetParameter(0),fMix->GetParameter(1));
		fNP->SetRange(fitRangeL,fitRangeH);
		fNP->SetLineColor(4);
		fNP->SetFillStyle(1001);
		fNP->SetFillColor(kBlue-9);
		fNP->SetNpx(10000);
		fNP->Draw("same");  

		hD0DcaData->Draw("same");

		promptDYield[i-1] = fMix->GetParameter(0);
		promptDYieldErrorDataOnly[i-1] = fMix->GetParError(0);
		bToDYield[i-1] = fMix->GetParameter(1);
		bToDYieldErrorDataOnly[i-1] = fMix->GetParError(1);
		totalYield[i-1] = promptDYield[i-1]+bToDYield[i-1];
		promptFraction[i-1] = promptDYield[i-1]/totalYield[i-1];

		cout<<"chi2 / NDF: "<<fitResult->Chi2()<<" / "<<fitResult->Ndf()<<endl;

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		TLatex* texPrompt = new TLatex(0.4,0.73,Form("Prompt D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(0),fMix->GetParError(0)));
		texPrompt->SetNDC();
		texPrompt->SetTextFont(42);
		texPrompt->SetTextSize(0.06);
		texPrompt->SetLineWidth(2);
		texPrompt->Draw();

		TLatex* texNonPrompt = new TLatex(0.4,0.65,Form("B to D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(1),fMix->GetParError(1)));
		texNonPrompt->SetNDC();
		texNonPrompt->SetTextFont(42);
		texNonPrompt->SetTextSize(0.06);
		texNonPrompt->SetLineWidth(2);
		texNonPrompt->Draw();

		TLegend* leg4 = new TLegend(0.56,0.38,0.90,0.62);
		leg4->SetBorderSize(0);
		leg4->SetTextSize(0.06);
		leg4->SetTextFont(42);
		leg4->SetFillStyle(0);
		leg4->AddEntry(hD0DcaData,"Data","pl");
		leg4->AddEntry(fMix,"Prompt D^{0}","f");
		leg4->AddEntry(fNP,"B to D^{0}","f");
		leg4->Draw("same");

		//smear MC smaple with the error, to simulate the MC statistic error effect.
		c4->cd(3);

		hD0DcaMCPSignal = (TH1D*)hD0DcaMCPSignal0->Clone("hMCPSignal");
		hD0DcaMCNPSignal = (TH1D*)hD0DcaMCNPSignal0->Clone("hMCNPSignal");

		TH1D* hNPYield = new TH1D("hNPYield", ";hNPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		TH1D* hPYield = new TH1D("hPYield", ";hPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		setColorTitleLabel(hNPYield, 1);
		setColorTitleLabel(hPYield, 1);

		int nSmear = 1000;

		for(int j=0; j<nSmear; j++)
		{
			RandomSmear(hD0DcaMCPSignal0, hD0DcaMCPSignal);
			RandomSmear(hD0DcaMCNPSignal0, hD0DcaMCNPSignal);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);

			hD0DcaData->Fit("fMix","E QN0");

			hPYield->Fill(fMix->GetParameter(0));
			hNPYield->Fill(fMix->GetParameter(1));
		}

		hPYield->GetXaxis()->SetTitle("prompt D^{0} yield");
		hPYield->GetYaxis()->SetTitle("counts");
		hPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hPYield->GetMaximum());
		hPYield->SetMarkerStyle(20);
		hPYield->SetStats(0);
		hPYield->Draw("e");
		hPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hPYield->GetFunction("gaus")->GetParameter(1),hPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaP->SetNDC();
		texGaussMeanSigmaP->SetTextFont(42);
		texGaussMeanSigmaP->SetTextSize(0.06);
		texGaussMeanSigmaP->SetLineWidth(2);
		texGaussMeanSigmaP->Draw();

		float promptYieldErrorMc = hPYield->GetFunction("gaus")->GetParameter(2);
		promptDYieldError[i-1] = sqrt(pow(promptDYieldErrorDataOnly[i-1],2)+pow(promptYieldErrorMc,2));

		c4->cd(4);

		hNPYield->GetXaxis()->SetTitle("B to D^{0} yield");
		hNPYield->GetYaxis()->SetTitle("counts");
		hNPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hNPYield->GetMaximum());
		hNPYield->SetMarkerStyle(20);
		hNPYield->SetStats(0);
		hNPYield->Draw("e");
		hNPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaNP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hNPYield->GetFunction("gaus")->GetParameter(1),hNPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaNP->SetNDC();
		texGaussMeanSigmaNP->SetTextFont(42);
		texGaussMeanSigmaNP->SetTextSize(0.06);
		texGaussMeanSigmaNP->SetLineWidth(2);
		texGaussMeanSigmaNP->Draw();

		float bToDYieldErrorMc = hNPYield->GetFunction("gaus")->GetParameter(2);
		bToDYieldError[i-1] = sqrt(pow(bToDYieldErrorDataOnly[i-1],2)+pow(bToDYieldErrorMc,2));

		cout<<"prompt D yield: "<<promptDYield[i-1]<<" +- "<<promptDYieldError[i-1]<<" (+- "<<promptDYieldErrorDataOnly[i-1]<<" +- "<<promptYieldErrorMc<<" )"<<endl;
		cout<<"B to D yield: "<<bToDYield[i-1]<<" +- "<<bToDYieldError[i-1]<<" (+- "<<bToDYieldErrorDataOnly[i-1]<<" +- "<<bToDYieldErrorMc<<" )"<<endl;
		cout<<"total yield: "<<totalYield[i-1]<<endl;
		cout<<"prompt fraction: "<<promptFraction[i-1]<<endl;

		float promptMCScale = promptDYield[i-1]/integralRawYieldMCP;
		float nonPromptMCScale = bToDYield[i-1]/integralRawYieldMCNP;

		cout<<"promptMCScale: "<<promptMCScale<<endl;
		cout<<"nonPromptMCScale: "<<nonPromptMCScale<<endl;

		//restore original unsmeared histograms before saving plots
		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;
		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;
		hD0DcaData->Fit("fMix","E QN0");

		c4->SaveAs(Form("plots/PbPb_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		c1->cd();

		TH1D* hD0DcaDataOverFit = (TH1D*)hD0DcaData->Clone("hD0DcaDataOverFit");
		hD0DcaDataOverFit->Divide(fMix);
		hD0DcaDataOverFit->GetYaxis()->SetTitle("data / fit");
		hD0DcaDataOverFit->GetYaxis()->SetRangeUser(0,5);
		hD0DcaDataOverFit->GetXaxis()->SetRangeUser(0,0.07);
		setColorTitleLabel(hD0DcaDataOverFit, 1);
		hD0DcaDataOverFit->Draw("e");

		TF1* fLine1 = new TF1("fLine1", "1", 0,1);
		fLine1->Draw("same");
		hD0DcaDataOverFit->Draw("esame");

		c1->SaveAs(Form("plots/dataOverFit_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;

	} // end for i ptbins
	c1->cd();

	TH1D* hStupidJie = new TH1D("hStupidJie", "", 100, 0, 100);
	hStupidJie->GetYaxis()->SetRangeUser(0,1);
	hStupidJie->GetXaxis()->SetTitle("p_{T} (GeV/c)");
	hStupidJie->GetYaxis()->SetTitle("prompt fraction");
	hStupidJie->SetStats(0);
	hStupidJie->Draw();
	TGraph* grFraction = new TGraph(nPtBins, pts, promptFraction);
	grFraction->SetName("grPromptFraction");
	grFraction->SetMarkerStyle(20);
	grFraction->Draw("psame");

	c1->SaveAs("promptFraction.pdf");

	c1->SetLogy();

	TH1D* hBtoDRawYield = new TH1D("hBtoDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(bToDYield[i-1] <= 0) continue;
		hBtoDRawYield->SetBinContent(i, bToDYield[i-1]);
		hBtoDRawYield->SetBinError(i, bToDYieldError[i-1]);
	}
	divideBinWidth(hBtoDRawYield);
	setColorTitleLabel(hBtoDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hBtoDRawYield->Draw("p");
	c1->SaveAs("BtoD.pdf");

	TH1D* hPromptDRawYield = new TH1D("hPromptDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(promptDYield[i-1] <= 0) continue;
		hPromptDRawYield->SetBinContent(i, promptDYield[i-1]);
		hPromptDRawYield->SetBinError(i, promptDYieldError[i-1]);
	}
	divideBinWidth(hPromptDRawYield);
	setColorTitleLabel(hPromptDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hPromptDRawYield->Draw("p");
	c1->SaveAs("promptD.pdf");

	TH1D* hTotalDYieldInvMassFit = new TH1D("hTotalDYieldInvMassFit", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(totalYieldInvMassFit[i-1] <= 0) continue;
		hTotalDYieldInvMassFit->SetBinContent(i, totalYieldInvMassFit[i-1]);
		hTotalDYieldInvMassFit->SetBinError(i, totalYieldInvMassFitError[i-1]);
	}
	divideBinWidth(hTotalDYieldInvMassFit);
	setColorTitleLabel(hTotalDYieldInvMassFit, 1);
	hTotalDYieldInvMassFit->Draw("p");
	c1->SaveAs("totalDInvMassFit.pdf");

	TFile* fOut = new TFile("bFeedDownResult.root", "recreate");
	fOut->WriteTObject(grFraction);
	fOut->WriteTObject(hBtoDRawYield);
	fOut->WriteTObject(hPromptDRawYield);
	fOut->WriteTObject(hTotalDYieldInvMassFit);
	fOut->Write();
	fOut->Close();
}
Example #24
0
void Find_Bpt()
{
  
  double BpT[100]={0},BpTEr[100]={0},JpT[100]={0};
  double BpTPlus[100]={0},BpTMinus[100]={0};
  
  //double a0 = 0.604865,a0Er = 0.00790439,a1 = 1.03837, a1Er = 0.00381658;
  //double a0 = 0.680535 ,a0Er =0.00465789 ,a1 =0.978251 , a1Er =0.0010945 ; //pol1
  //double a0 =0.767454,a0Er =0.00637919 ,a1 =0.926482, a1Er =0.00281732; // pol2

  // Acceptance
  //double a0 =0.627337,a0Er =0.0049568,a1 =1.02592, a1Er =0.0010564; // pol1
  //double a0 =0.742605,a0Er =0.00714768 ,a1 =0.957962, a1Er =0.00321474; // pol2

  //New Acceptance
  //double a0 = 0.718407,a0Er =0.0106664 ,a1 =1.1037, a1Er =0.00138381; //pol1
  double a0 =0.491983 ,a0Er =0.0178676 ,a1 =1.1242, a1Er =0.00296712; //pol1
  
  char OutTextFile[100]; 
  sprintf(OutTextFile,"Find_BpT.txt");
  ofstream dataFile(Form(OutTextFile),ios::app);

  for(int i=1;i<=30;i++)
    {
      BpT[i] = a0 + a1*i; 
      BpTPlus[i] = a0 + a0Er + (a1+a1Er)*i; 
      BpTMinus[i] = a0 - a0Er + (a1-a1Er)*i; 
      BpTEr[i] = (BpTPlus[i]-BpTMinus[i])/2.0;
      
      //dataFile<<setprecision(4);
      //if(i==1)dataFile<<" J/#psi pT  "<<" B pT   "<<endl;
      //dataFile<<i<<"    &"<<BpT[i]<<" /pm "<<BpTEr[i]<<endl;
      
      //cout<<i<<"    &"<<BpT[i]<<" /pm "<<BpTEr[i]<<endl;
      //cout<<"==============================================="<<endl;
    }
  
  // Pt bin sizes

  double pt_bound[100] = {0.0};
  double PT[100], DelPT[100];
  double YPT[100], DelYPT[100];

  int Nptbin = 20;
  double step =0.5;

  for (Int_t ih = 0; ih < Nptbin; ih++) {
    pt_bound[ih] = 1 + step*ih;
    pt_bound[ih+1] = 1 + step*(ih+1);
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = (pt_bound[ih+1] - pt_bound[ih])/2.0;
  }

  char namePt[500];
  char text[100],text1[100],text2[100];

  TFile *fpT = new TFile("hist1.root");
  //  TH2D *JPt_BPt = (TH2D*)fpT->Get("JpTBpTAccpt");
  TH2D *JPt_BPt = (TH2D*)fpT->Get("JpTBpT");
  
  new TCanvas;
  JPt_BPt->Draw("colz");

  TH1D *service = (TH1D*)JPt_BPt->ProjectionX("service");
  
  //service->Draw();
  //cout<<" service  "<<service<<endl;

  int pt_bin_bound[100];

  TH1D *ProfY_BPt[100];

  cout<<"  J/psi pT  " << "  B pT Mean  "<< "  BpT RMS  " <<endl;
  dataFile<<"  J/psi pT  " << "  B pT Mean  "<< "  BpT RMS  " <<endl;

  for (Int_t ih = 0; ih < Nptbin; ih++) {
  
    
    pt_bin_bound[ih] = service->FindBin(pt_bound[ih]);
    //cout<<" pt_bin_bound[ih]  "<<pt_bin_bound[ih]<<endl;
    
    pt_bin_bound[ih+1] = service->FindBin(pt_bound[ih+1]);
    //cout<<" pt_bin_bound[ih+1]  "<<pt_bin_bound[ih+1] -1<<endl;
    
    sprintf(namePt,"BPt_%d",ih);
    
    ProfY_BPt[ih] = (TH1D*)JPt_BPt->ProjectionY(namePt, pt_bin_bound[ih], pt_bin_bound[ih+1]-1);
    sprintf(text," %.1f-%.1f ",  service->GetBinLowEdge(pt_bin_bound[ih]), 
	      service->GetBinLowEdge(pt_bin_bound[ih+1]-1)+service->GetBinWidth(pt_bin_bound[ih+1]));
    
    dataFile<<setprecision(2);

    cout<< text <<"  "<< ProfY_BPt[ih]->GetMean()<<" /pm "<< ProfY_BPt[ih]->GetRMS()<< endl<<endl;

    YPT[ih] = ProfY_BPt[ih]->GetMean();
    DelYPT[ih] = ProfY_BPt[ih]->GetRMS();

    cout<< text <<"  "<< YPT[ih] <<" /pm "<<  DelYPT[ih]<< endl<<endl;

    sprintf(text1," %.1f ", YPT[ih]);
    sprintf(text2," %.1f ", DelYPT[ih]);
    dataFile<< text <<"  &"<< text1<<" /pm   "<< text2<< endl<<endl;

    /*
    if(ih ==1 || ih ==4 ||ih ==5 ||ih == 9 ||ih ==14 ||ih ==19 || ih ==29)
      {
	new TCanvas;
	ProfY_BPt[ih]->Draw();
      }
    */
  }
  
  dataFile.close();


  /* TGraphErrors *gr_BpTvsJpT = new TGraphErrors(Nptbin, PT, YPT, DelPT, DelYPT);
  TF1 *func_BpTvsJpT = new TF1("pol1", pol1, 0, 24, 2); 
  func_BpTvsJpT->SetLineColor(2);
  gr_BpTvsJpT->Fit("pol1","","",0,24);
  gr_BpTvsJpT->GetXaxis()->SetRangeUser(0,25);
  // gr_BpTvsJpT->GetYaxis()->SetRangeUser(0,25);
  gr_BpTvsJpT->Draw("ap");
  func_BpTvsJpT->Draw("same");
  */

  TGraphErrors *gr_BpTvsJpT = new TGraphErrors(Nptbin, PT, YPT, DelPT, DelYPT);
  TF1 *func_BpTvsJpT = new TF1("pol1", pol1, 0, 10, 2); 
  func_BpTvsJpT->SetLineColor(2);
  gr_BpTvsJpT->Fit("pol1","","",0,6);
  gr_BpTvsJpT->GetXaxis()->SetRangeUser(0,10);
  gr_BpTvsJpT->Draw("ap");
  func_BpTvsJpT->Draw("same");
}
Example #25
0
void plotZee(const TString  outputDir,   // output directory
             const Double_t lumi         // integrated luminosity (/fb)
) {
  gBenchmark->Start("plotZee");
  gStyle->SetTitleOffset(1.100,"Y");
  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  //
  // input ntuple file names
  //
  enum { eData, eZee, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/zee_select.root");  typev.push_back(eZee);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/top_select.root");  typev.push_back(eEWK);

  //
  // Fit options
  //
  const Int_t    NBINS     = 60;
  const Double_t MASS_LOW  = 60;
  const Double_t MASS_HIGH = 120;  
  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.5;
  
  // plot output file format
  const TString format("png");
 
   
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  // event category enumeration
  enum { eEleEle2HLT=1, eEleEle1HLT, eEleEleNoSel, eEleSC };
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
    

  // histograms for full selection (EleEle2HLT + EleEle1HLT)
  TH1D *hData = new TH1D("hData","",NBINS,MASS_LOW,MASS_HIGH); hData->Sumw2();
  TH1D *hZee  = new TH1D("hZee", "",NBINS,MASS_LOW,MASS_HIGH); hZee->Sumw2();
  TH1D *hEWK  = new TH1D("hEWK", "",NBINS,MASS_LOW,MASS_HIGH); hEWK->Sumw2();
  TH1D *hMC   = new TH1D("hMC",  "",NBINS,MASS_LOW,MASS_HIGH); hMC->Sumw2();
    
  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  matchGen;
  UInt_t  category;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, u1, u2;
  Int_t   q1, q2;
  LorentzVector *dilep=0, *lep1=0, *lep2=0;
  LorentzVector *sc1=0, *sc2=0;

  TFile *infile=0;
  TTree *intree=0;

  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
  
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	    assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);     // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);    // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);     // event number
    intree->SetBranchAddress("matchGen", &matchGen);   // event has both leptons matched to MC Z->ll
    intree->SetBranchAddress("category", &category);   // dilepton category
    intree->SetBranchAddress("npv",      &npv);	       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);	       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);     // GEN Z boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);    // GEN Z boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);   // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);	       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);     // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);      // Sum ET
    intree->SetBranchAddress("u1",       &u1);	       // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);	       // perpendicular component of recoil
    intree->SetBranchAddress("q1",       &q1);	       // charge of tag lepton
    intree->SetBranchAddress("q2",       &q2);	       // charge of probe lepton
    intree->SetBranchAddress("dilep",    &dilep);      // dilepton 4-vector
    intree->SetBranchAddress("lep1",     &lep1);       // tag lepton 4-vector
    intree->SetBranchAddress("lep2",     &lep2);       // probe lepton 4-vector
    intree->SetBranchAddress("sc1",      &sc1);        // tag Supercluster 4-vector
    intree->SetBranchAddress("sc2",      &sc2);        // probe Supercluster 4-vector 
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);

      if(dilep->M()       < MASS_LOW)  continue;
      if(dilep->M()       > MASS_HIGH) continue;
      if(sc1->Pt()        < PT_CUT)    continue;
      if(sc2->Pt()        < PT_CUT)    continue;
      if(fabs(sc1->Eta()) > ETA_CUT)   continue;      
      if(fabs(sc2->Eta()) > ETA_CUT)   continue;
   
      Float_t mass = dilep->M();
      
      Double_t weight=1;
      if(typev[ifile]!=eData) {
	weight *= scale1fb*lumi;
      }
      
      // fill Z events passing selection (EleEle2HLT + EleEle1HLT)
      if((category==eEleEle2HLT) || (category==eEleEle1HLT)) {
        if(typev[ifile]==eData) { 
	  hData->Fill(mass); 
	
	} else {
          
	  LorentzVector slep1 = (*lep1);
	  slep1 *= gRandom->Gaus(slep1.E(), getResCorr(sc1->Eta()))/slep1.E();
	  
	  LorentzVector slep2 = (*lep2);
	  slep2 *= gRandom->Gaus(slep2.E(), getResCorr(sc2->Eta()))/slep2.E();
	  
	  mass = (slep1+slep2).M();	  
	  
	  hMC->Fill(mass,weight);
	  if(typev[ifile]==eZee) { hZee->Fill(mass,weight); }
	  if(typev[ifile]==eEWK) { hEWK->Fill(mass,weight); }
	}
      }
    }
    
    delete infile;
    infile=0, intree=0;
  }

  TH1D *hZeeDiff = makeDiffHist(hData,hMC,"hZeeDiff");
  hZeeDiff->SetMarkerStyle(kFullCircle); 
  hZeeDiff->SetMarkerSize(0.9);
  

  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  

  char ylabel[100];     // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);  
  
  // plot colors
  Int_t linecolorZ   = kOrange-3;
  Int_t fillcolorZ   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t ratioColor   = kGray+2;
    
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  TGaxis::SetMaxDigits(3);
  
  //
  // EleEle2HLT + EleEle1HLT categories
  //   
  sprintf(ylabel,"Events / %.1f GeV/c^{2}",hData->GetBinWidth(1));
  CPlot plotZee("zee","","",ylabel);
  plotZee.AddHist1D(hData,"data","E");
  plotZee.AddToStack(hZee,"Z#rightarrowee",fillcolorZ,linecolorZ);
  plotZee.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotZee.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotZee.SetYRange(0.01,1.2*(hData->GetMaximum() + sqrt(hData->GetMaximum())));
  plotZee.TransLegend(-0.35,-0.15);
  plotZee.Draw(c,kFALSE,format,1);

  CPlot plotZeeDiff("zee","","M(e^{+}e^{-}) [GeV/c^{2}]","#chi");
  plotZeeDiff.AddHist1D(hZeeDiff,"EX0",ratioColor);
  plotZeeDiff.SetYRange(-8,8);
  plotZeeDiff.AddLine(MASS_LOW, 0,MASS_HIGH, 0,kBlack,1);
  plotZeeDiff.AddLine(MASS_LOW, 5,MASS_HIGH, 5,kBlack,3);
  plotZeeDiff.AddLine(MASS_LOW,-5,MASS_HIGH,-5,kBlack,3);
  plotZeeDiff.Draw(c,kTRUE,format,2);
  
  CPlot plotZee2("zeelog","","",ylabel);
  plotZee2.AddHist1D(hData,"data","E");
  plotZee2.AddToStack(hEWK,"EWK",fillcolorEWK,linecolorEWK);
  plotZee2.AddToStack(hZee,"Z#rightarrowee",fillcolorZ,linecolorZ);
  plotZee2.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);plotZee2.SetName("zeelog");
  plotZee2.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotZee2.SetLogy();
  plotZee2.SetYRange(1e-4*(hData->GetMaximum()),10*(hData->GetMaximum()));
  plotZee2.TransLegend(-0.35,-0.15);
  plotZee2.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("plotZee");
}
Example #26
0
void AnalysisBase::findCutoutRegion(TH2F* h){

  cout << "===============================================================" << endl;
  cout << "findCutoutRegion(): Looking for cutout region in D type sensor " << endl;
  cout << "===============================================================" << endl;


  int ilx = h->GetXaxis()->FindBin(xMin) + 1;
  int ihx = h->GetXaxis()->FindBin(xMax) - 1;
  int ily = 1;//h->GetYaxis()->GetBinFindBin(yMin) - 10;
  int ihy = h->GetYaxis()->FindBin(yMax) + 10;
  if(ily < 0) ily = 0;
  if(ihy > h->GetYaxis()->GetNbins()) ihy = h->GetYaxis()->GetNbins();  
  int nb = h->GetXaxis()->GetNbins(); 

  double xlow = h->GetXaxis()->GetBinLowEdge(1);
  double xhi = h->GetXaxis()->GetBinLowEdge(nb)+h->GetXaxis()->GetBinWidth(1);

  TH1F *hpr = new TH1F("hpr","Y vs X, edge",nb,xlow,xhi);

  TH1D *hpy;
  int ipeak = 0;
  for(int i=ilx; i<ihx-1; i++){
    hpy = h->ProjectionY("hpy",i,i);
    double maxcon  = 0.0;
    double maxbin  = 0.0;
    for(int j=ily;j<ihy;j++){
      maxcon = maxcon + hpy->GetBinContent(j);
      if(hpy->GetBinContent(j) > maxbin) {
        maxbin = hpy->GetBinContent(j) ;
        ipeak = j;
      }
    }
    // Find the lower "edge"
    for(int j=ipeak; j>=ily; j--){
      double r0 = (hpy->GetBinContent(j-1)+hpy->GetBinContent(j-2))/2.0;
      double r1 = hpy->GetBinContent(j);
      double r2 = (hpy->GetBinContent(j+3)+hpy->GetBinContent(j+4))/2.0;
      if(r1<=2 && r0<=1.5 && r2>5*r1 && r2>8){
        hpr->SetBinContent(i,hpy->GetBinCenter(j)+2*hpy->GetBinWidth(j));
        hpr->SetBinError(i,hpy->GetBinWidth(1)/2.0);
        //cout << "found: " << i << " " << hpy->GetEntries() << " " << hpy->GetBinCenter(j) << " " 
        //     << hpy->GetBinContent(j) << " " << r0 << " " << r1 << " " << r2 << " " << endl;
        break;
      }
    }
    
  }

  TF1* poly2 = new TF1("poly2","[0]+[1]*x+[2]*x*x",xMin,xMax);
  poly2->SetParameters(-1.5,-0.17,-0.15);
  hpr->Fit(poly2,"R0");
  hpr->SetLineColor(kRed);

  holeQuadPar[0] = poly2->GetParameter(0);
  holeQuadPar[1] = poly2->GetParameter(1);
  holeQuadPar[2] = poly2->GetParameter(2);

  //return;
  

  delete poly2;
  delete hpr;
  delete hpy;
  
  return;
}
Example #27
0
void fitWm(const TString  outputDir,   // output directory
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
) {
  gBenchmark->Start("fitWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS   = 50;
  const Double_t METMAX  = 100;
  
  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.1;

  // file format for output plots
  const TString format("png"); 

    
  // recoil correction
  RecoilCorrector recoilCorr("../Recoil/ZmmData/fits.root");//, (!) uncomment to perform corrections to recoil from W-MC/Z-MC
                             //"../Recoil/WmpMC/fits.root",
			     //"../Recoil/WmmMC/fits.root",
			     //"../Recoil/ZmmMC/fits.root");
   
  // NNLO boson pT k-factors
  TFile nnloCorrFile("/data/blue/ksung/EWKAna/8TeV/Utils/Ratio.root");
  TH1D *hNNLOCorr = (TH1D*)nnloCorrFile.Get("RpT_B");
  
  //
  // input ntuple file names
  //
  enum { eData, eWmunu, eEWK, eAntiData, eAntiWmunu, eAntiEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/wm_select.root");   typev.push_back(eWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/top_select.root");  typev.push_back(eEWK);
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/data_select.root"); typev.push_back(eAntiData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/wm_select.root");   typev.push_back(eAntiWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/ewk_select.root");  typev.push_back(eAntiEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/top_select.root");  typev.push_back(eAntiEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet   = new TH1D("hDataMet","",  NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm  = new TH1D("hDataMetm","", NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp  = new TH1D("hDataMetp","", NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWmunuMet  = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2();
  TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2();
  TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->Sumw2();
  TH1D *hEWKMet    = new TH1D("hEWKMet", "",  NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp   = new TH1D("hEWKMetp", "", NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm   = new TH1D("hEWKMetm", "", NBINS,0,METMAX); hEWKMetm->Sumw2();

  TH1D *hAntiDataMet   = new TH1D("hAntiDataMet","",  NBINS,0,METMAX); hAntiDataMet->Sumw2();
  TH1D *hAntiDataMetm  = new TH1D("hAntiDataMetm","", NBINS,0,METMAX); hAntiDataMetm->Sumw2();  
  TH1D *hAntiDataMetp  = new TH1D("hAntiDataMetp","", NBINS,0,METMAX); hAntiDataMetp->Sumw2();
  TH1D *hAntiWmunuMet  = new TH1D("hAntiWmunuMet","", NBINS,0,METMAX); hAntiWmunuMet->Sumw2();
  TH1D *hAntiWmunuMetp = new TH1D("hAntiWmunuMetp","",NBINS,0,METMAX); hAntiWmunuMetp->Sumw2();
  TH1D *hAntiWmunuMetm = new TH1D("hAntiWmunuMetm","",NBINS,0,METMAX); hAntiWmunuMetm->Sumw2();
  TH1D *hAntiEWKMet    = new TH1D("hAntiEWKMet", "",  NBINS,0,METMAX); hAntiEWKMet->Sumw2();
  TH1D *hAntiEWKMetp   = new TH1D("hAntiEWKMetp", "", NBINS,0,METMAX); hAntiEWKMetp->Sumw2();
  TH1D *hAntiEWKMetm   = new TH1D("hAntiEWKMetm", "", NBINS,0,METMAX); hAntiEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  Float_t pfChIso, pfGamIso, pfNeuIso;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);   // GEN W boson phi (signal MC)   
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);	      // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("pfChIso",  &pfChIso);
    intree->SetBranchAddress("pfGamIso", &pfGamIso);
    intree->SetBranchAddress("pfNeuIso", &pfNeuIso);
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(lep->Pt()        < PT_CUT)  continue;	
      if(fabs(lep->Eta()) > ETA_CUT) continue;
      
      if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) &&
          (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) 
	  continue;
      
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else if(typev[ifile]==eAntiData) {
        hAntiDataMet->Fill(met);
	if(q>0) { hAntiDataMetp->Fill(met); } 
	else    { hAntiDataMetm->Fill(met); }      
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
	
	if(typev[ifile]==eWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
	
          Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
	  
          hWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hWmunuMetp->Fill(corrMet,weight); } 
	  else    { hWmunuMetm->Fill(corrMet,weight); }
        }
	if(typev[ifile]==eAntiWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5);
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
          
	  Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
          
	  hAntiWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } 
	  else    { hAntiWmunuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
        if(typev[ifile]==eAntiEWK) {
          hAntiEWKMet->Fill(met,weight);
	  if(q>0) { hAntiEWKMetp->Fill(met,weight); }
	  else    { hAntiEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWmunuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral());
  RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar dewk("dewk","dewk",0.1,0,5) ;
  dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral());
  dewk.setConstant(kTRUE);
  RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWmunuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ;
  dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral());
  dewkp.setConstant(kTRUE);
  RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWmunuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ;
  dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral());
  dewkm.setConstant(kTRUE);
  RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm));

  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wmunuMet ("wmunuMET", "wmunuMET", RooArgSet(pfmet),hWmunuMet);  RooHistPdf pdfWm ("wm", "wm", pfmet,wmunuMet, 1);
  RooDataHist wmunuMetp("wmunuMETp","wmunuMETp",RooArgSet(pfmet),hWmunuMetp); RooHistPdf pdfWmp("wmp","wmp",pfmet,wmunuMetp,1);
  RooDataHist wmunuMetm("wmunuMETm","wmunuMETm",RooArgSet(pfmet),hWmunuMetm); RooHistPdf pdfWmm("wmm","wmm",pfmet,wmunuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWm,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWmp,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWmm,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  
  // Anti-Signal PDFs
  RooDataHist awmunuMet ("awmunuMET", "awmunuMET", RooArgSet(pfmet),hAntiWmunuMet);  RooHistPdf apdfWm ("awm", "awm", pfmet,awmunuMet, 1);
  RooDataHist awmunuMetp("awmunuMETp","awmunuMETp",RooArgSet(pfmet),hAntiWmunuMetp); RooHistPdf apdfWmp("awmp","awmp",pfmet,awmunuMetp,1);
  RooDataHist awmunuMetm("awmunuMETm","awmunuMETm",RooArgSet(pfmet),hAntiWmunuMetm); RooHistPdf apdfWmm("awmm","awmm",pfmet,awmunuMetm,1); 
  
  // Anti-EWK+top PDFs
  RooDataHist aewkMet ("aewkMET", "aewkMET", RooArgSet(pfmet),hAntiEWKMet);  RooHistPdf apdfEWK ("aewk", "aewk", pfmet,aewkMet, 1);
  RooDataHist aewkMetp("aewkMETp","aewkMETp",RooArgSet(pfmet),hAntiEWKMetp); RooHistPdf apdfEWKp("aewkp","aewkp",pfmet,aewkMetp,1); 
  RooDataHist aewkMetm("aewkMETm","aewkMETm",RooArgSet(pfmet),hAntiEWKMetm); RooHistPdf apdfEWKm("aewkm","aewkm",pfmet,aewkMetm,1); 
  
  // Anti-QCD Pdfs
  CPepeModel1 aqcd("aqcd",pfmet,qcd.a1);
  CPepeModel1 aqcdp("aqcdp",pfmet,qcdp.a1);
  CPepeModel1 aqcdm("aqcdm",pfmet,qcdm.a1);
  
  // Anti-selection PDFs
  RooAddPdf apdfMet ("apdfMet", "apdfMet", RooArgList(apdfWm,apdfEWK,*(aqcd.model)),   RooArgList(nAntiSig,nAntiEWK,nAntiQCD));  
  RooAddPdf apdfMetp("apdfMetp","apdfMetp",RooArgList(apdfWmp,apdfEWKp,*(aqcdp.model)),RooArgList(nAntiSigp,nAntiEWKp,nAntiQCDp));
  RooAddPdf apdfMetm("apdfMetm","apdfMetm",RooArgList(apdfWmm,apdfEWKm,*(aqcdm.model)),RooArgList(nAntiSigm,nAntiEWKm,nAntiQCDm));
  
  // PDF for simultaneous fit
  RooCategory rooCat("rooCat","rooCat");
  rooCat.defineType("Select");
  rooCat.defineType("Anti");
  
  RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat);
  pdfTotal.addPdf(pdfMet, "Select");
  pdfTotal.addPdf(apdfMet,"Anti");
  
  RooSimultaneous pdfTotalp("pdfTotalp","pdfTotalp",rooCat);
  pdfTotalp.addPdf(pdfMetp, "Select");
  pdfTotalp.addPdf(apdfMetp,"Anti");
  
  RooSimultaneous pdfTotalm("pdfTotalm","pdfTotalm",rooCat);
  pdfTotalm.addPdf(pdfMetm, "Select");
  pdfTotalm.addPdf(apdfMetm,"Anti");
  
  //
  // Perform fits
  //

  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet);
  RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet);
  RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat),
                        Import("Select", dataMet),
                        Import("Anti",   antiMet));
  RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp);
  RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp);
  RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetp),
                         Import("Anti",   antiMetp));
  RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm);
  RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm);
  RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetm),
                         Import("Anti",   antiMetm));
  RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet));
  hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
  TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff");
  hAntiMetDiff->SetMarkerStyle(kFullCircle);
  hAntiMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet));
  hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral());
  TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff");
  hAntiMetpDiff->SetMarkerStyle(kFullCircle);
  hAntiMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet));
  hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral());
  TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff");
  hAntiMetmDiff->SetMarkerStyle(kFullCircle); 
  hAntiMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  TGaxis::SetMaxDigits(3);
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *wmframe = pfmet.frame(Bins(NBINS)); 
  wmframe->GetYaxis()->SetNdivisions(505);
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(wmframe,LineColor(linecolorW));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",wmframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kFALSE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  RooPlot *awmframe = pfmet.frame(Bins(NBINS));    
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMet.plotOn(awmframe,LineColor(linecolorW));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2));
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1));
  CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel);
  plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); 
  plotAntiMet.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetDiff("fitantimet","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotAntiMetDiff.SetYRange(-8,8);
  plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMet.SetName("fitantimetlog");
  plotAntiMet.SetLogy();
  plotAntiMet.SetYRange(1e-3*(hAntiDataMet->GetMaximum()),10*(hAntiDataMet->GetMaximum()));
  plotAntiMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wmpframe = pfmet.frame(Bins(NBINS));
  wmpframe->GetYaxis()->SetNdivisions(505);
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wmpframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,LineColor(linecolorW));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfWmp)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wmpframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
plotMetp.SetYRange(0.1,4100);
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);

  RooPlot *awmpframe = pfmet.frame(Bins(NBINS));    
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetp.plotOn(awmpframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,LineColor(linecolorW));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),LineColor(linecolorEWK));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),LineColor(linecolorQCD));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfWmp)),LineColor(linecolorW),LineStyle(2));
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMetp->GetBinWidth(1));
  CPlot plotAntiMetp("fitantimetp",awmpframe,"","",ylabel);
  plotAntiMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetp.SetYRange(0.1,1.1*(hAntiDataMetp->GetMaximum()));
plotAntiMetp.SetYRange(0.1,1500);
  plotAntiMetp.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetpDiff("fitantimetp","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetpDiff.AddHist1D(hAntiMetpDiff,"EX0",ratioColor);
  plotAntiMetpDiff.SetYRange(-8,8);
  plotAntiMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetpDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetp.SetName("fitantimetplog");
  plotAntiMetp.SetLogy();
  plotAntiMetp.SetYRange(1e-3*(hAntiDataMetp->GetMaximum()),10*(hAntiDataMetp->GetMaximum()));
  plotAntiMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wmmframe = pfmet.frame(Bins(NBINS)); 
  wmmframe->GetYaxis()->SetNdivisions(505);
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wmmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,LineColor(linecolorW));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfWmm)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wmmframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
plotMetm.SetYRange(0.1,4100);
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

  RooPlot *awmmframe = pfmet.frame(Bins(NBINS)); 
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetm.plotOn(awmmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,LineColor(linecolorW));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),LineColor(linecolorEWK));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),LineColor(linecolorQCD));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfWmm)),LineColor(linecolorW),LineStyle(2));
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotAntiMetm("fitantimetm",awmmframe,"","",ylabel);
  plotAntiMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetm.SetYRange(0.1,1.1*(hAntiDataMetm->GetMaximum()));
plotAntiMetm.SetYRange(0.1,1500);
  plotAntiMetm.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor);
  plotAntiMetmDiff.SetYRange(-8,8);
  plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetmDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetm.SetName("fitantimetmlog");
  plotAntiMetm.SetLogy();
  plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum()));
  plotAntiMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWmp.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWmm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWm");
}
Example #28
0
TH1D *
GetTPCTOFRatio(TFile *file, Int_t num, Int_t den, Int_t cent, Bool_t cutSpectrum = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin_[9] = {
    0.0, 0.0, 0.0, 
    0., 0., 0., 
    0.5, 0.5, 0.5
  };
  Double_t ptMax_[9] = {
    1.2, 1.2, 1.2, 
    1.2, 1.2, 1.2, 
    1.8, 1.8, 1.8
  };

  Double_t ptMin = TMath::Max(ptMin_[num], ptMin_[den]);
  Double_t ptMax = TMath::Min(ptMax_[num], ptMax_[den]);

  Int_t part = 0, charge = 0;
  if (num == kPiMinus && den == kPiPlus) {
    part = AliPID::kPion;
    charge = 1;
  }
  else if (num == kKaMinus && den == kKaPlus) {
    part = AliPID::kKaon;
    charge = 1;
  }
  else if (num == kPrMinus && den == kPrPlus) {
    part = AliPID::kProton;
    charge = 1;
  }
  else if (num == kKaMinus && den == kPiMinus) {
    part = AliPID::kKaon;
    charge = 1;
  }
  else if (num == kKaPlus && den == kPiPlus) {
    part = AliPID::kKaon;
    charge = 0;
  }
  else if (num == kPrMinus && den == kPiMinus) {
    part = AliPID::kProton;
    charge = 1;
  }
  else if (num == kPrPlus && den == kPiPlus) {
    part = AliPID::kProton;
    charge = 0;
  }

  TH1D *hin = (TH1D *)file->Get(Form("%sFinal%s%d", TPCTOFPartName[part], TPCTOFChargeName[charge], cent));
  if (!hin) return NULL;

  TH1D *h = new TH1D(Form("hTPCTOF_cent%d_%s_%s", cent, ratioName[num], ratioName[den]), "TPCTOF", NptBins, ptBin);
  Double_t pt, width, value, error;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin || pt > ptMax)) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
  h->SetTitle("TPCTOF");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(22);
  h->SetMarkerColor(8);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  
  return h;
}
Example #29
0
void DrawPhi(Int_t step=1,Float_t ptmin=0,Float_t ptmax=10){
  TFile *fcur = TFile::Open(Form("step%i.root",step));
  TFile *fpre = TFile::Open(Form("step%i.root",step-1));

  TH2D *hcurT = (TH2D *) fcur->Get("truePidPhiKaKa");
  TH2D *hcurP = (TH2D *) fcur->Get("priorsPhiKaKa");

  TH2D *hpreT = (TH2D *) fpre->Get("truePidPhiLaKa");
  TH2D *hpreP = (TH2D *) fpre->Get("priorsPhiKaKa");

  TH2D *hPion = (TH2D *) fcur->Get("priorsPhiPiPi");
//   hPion->Add((TH2D *) fcur->Get("priorsPhiPiKa"));
//   hPion->Add((TH2D *) fcur->Get("priorsPhiPiPr"));
//   hPion->Add((TH2D *) fcur->Get("priorsPhiKaPi"));
//   hPion->Add((TH2D *) fcur->Get("priorsPhiPrPi"));


  TH1D *hprior = hcurP->ProjectionX("meas",hcurP->GetYaxis()->FindBin(ptmin+0.001),hcurP->GetYaxis()->FindBin(ptmax-0.001));
  TH1D *htrue = hcurT->ProjectionX("true",hcurT->GetYaxis()->FindBin(ptmin+0.001),hcurT->GetYaxis()->FindBin(ptmax-0.001));

  TH1D *hpriorOld = hpreP->ProjectionX("measOld",hpreP->GetYaxis()->FindBin(ptmin+0.001),hpreP->GetYaxis()->FindBin(ptmax-0.001));

  TH1D *hnorm = hPion->ProjectionX("norm",hPion->GetYaxis()->FindBin(ptmin+0.001),hPion->GetYaxis()->FindBin(ptmax-0.001));


  for(Int_t i=1;i <= hprior->GetNbinsX();i++){
    Float_t err = TMath::Abs(hprior->GetBinContent(i)-hpriorOld->GetBinContent(i));
    if(hprior->GetBinContent(i)){
      err *= hnorm->GetBinContent(i);
      err /= hprior->GetBinContent(i);
    }
    hprior->SetBinError(i,err);
    //htrue->SetBinError(i,0);

  }

  TF1 *bw = new TF1("bw","[0]/((x-[1])*(x-[1]) +([2]*[2]*0.25)) + pol1(3)",1,1.05);
  TF1 *bwsig = new TF1("bw","[0]/((x-[1])*(x-[1]) +([2]*[2]*0.25))",1,1.05);

  bw->SetLineColor(2);
  bw->SetParameter(0,100);
  bw->FixParameter(1,1.02);
  bw->FixParameter(2,0.00426);
  bw->SetParameter(3,0);
  bw->SetParameter(4,0);
  bw->SetParameter(5,0);


  TCanvas *c = new TCanvas();
  c->Divide(1,2);
  c->cd(1);

  hprior->Draw("ERR3");
  htrue->SetLineColor(2);
  htrue->Draw("SAME");
  htrue->Fit(bw,"W","",1,1.05);

  for(Int_t i=0;i < 3;i++) bwsig->SetParameter(i,bw->GetParameter(i));
  
  Float_t truesig = bwsig->Integral(1,1.05) / htrue->GetBinWidth(1);

  hprior->Fit(bw,"W","",1,1.05);

  for(Int_t i=0;i < 3;i++) bwsig->SetParameter(i,bw->GetParameter(i));
  
  Float_t meassig = bwsig->Integral(1,1.05) / htrue->GetBinWidth(1);

  c->cd(2);
  bw->SetParameter(0,100);
  bw->SetParameter(3,0);
  bw->SetParameter(4,0);
  bw->SetParameter(5,0);
  TH1D *hr=new TH1D(*hprior);
  hr->Add(htrue,-1);
  hr->GetYaxis()->SetTitle("(meas-true)/true");
  hr->Divide(htrue);
  hr->Draw();
  hr->GetYaxis()->UnZoom();
  hr->Fit("pol0");
  hr->Fit(bw,"W","",1,1.05);

  for(Int_t i=0;i < 3;i++) bwsig->SetParameter(i,bw->GetParameter(i));

  Float_t deltasig = bwsig->Integral(1,1.05) / hr->GetBinWidth(1);

  printf("signal = %f -- delta = %f (%f) --> Precision = %f(%f)%c\n",truesig,meassig-truesig,deltasig,(meassig-truesig)/truesig,deltasig/truesig*100,'%');

}
Example #30
0
TH1D *
GetTOFRatio(TFile *file, Int_t num, Int_t den, Int_t cent, Bool_t cutSpectrum = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin_[9] = {
    0.5, 0.5, 0.5, 
    0.45, 0.45, 0.45, 
    0.5, 0.5, 0.5
  };
  Double_t ptMax_[9] = {
    3.0, 3.0, 3.0, 
    3.0, 3.0, 3.0, 
    4.5, 4.5, 4.5
  };

  Double_t ptMin = TMath::Max(ptMin_[num], ptMin_[den]);
  Double_t ptMax = TMath::Min(ptMax_[num], ptMax_[den]);
  
  TH1D *hin = (TH1D *)file->Get(Form("hRatio_cent%d_%s_%s", cent, ratioName[num], ratioName[den]));
  if (!hin) return NULL;


#if 0
  /* get matching systematics */
  TFile *fsys = TFile::Open(Form("MATCHSYS_TOF_%s.root", TOFChargeName[charge]));
  TH1 *hsys = fsys->Get(Form("hErr%sMatch", ITSsaPartName[part]));
  TF1 *ffsys = new TF1("fsys", "[0] + [1] * x + [2] * TMath::Exp(-[3] * x)");
  ffsys->SetParameter(0, 0.02);
  ffsys->FixParameter(1, 0.);
  ffsys->SetParameter(2, 0.5);
  ffsys->SetParameter(3, 10.);
  hsys->Fit(ffsys, "W");
  ffsys->ReleaseParameter(1);
  hsys->Fit(ffsys, "W");
  hsys->Fit(ffsys, "W");
  hsys->Fit(ffsys, "W");
  hsys->Draw();
#endif
			
  TH1D *h = new TH1D(Form("hTOF_cent%d_%s_%s", cent, ratioName[num], ratioName[den]), "TOF", NptBins, ptBin);
  Double_t pt, width, value, error, sys;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin || pt > ptMax)) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    /*** TEMP ADD SYS ***/
    //    sys = ffsys->Eval(pt) * value;
    //    error = TMath::Sqrt(error * error + sys * sys);
    //    h->SetBinContent(ipt + 1, value);
    //    h->SetBinError(ipt + 1, error);

    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
  h->SetTitle("TOF");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(23);
  h->SetMarkerColor(4);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  return h;
}