void decon_ind(Int_t chan = 221){
  TFile *file = new TFile("Run_00009188.root");
  TH2* h1 = (TH2*)file->Get(Form("Ind_%d",chan));
  TH2* h3 = (TH2*)h1->Clone("h3");
  TH2* h4 = (TH2*)h1->Clone("h4");
  
  h3->Reset();
  h4->Reset();

  gStyle->SetOptStat(0);

  TCanvas *c1 = new TCanvas("c1","c1",800,800);
  c1->Divide(2,2);
  c1->cd(1);
  h1->Draw("COLZ");
  h1->GetZaxis()->SetRangeUser(-80,80);
  h1->GetXaxis()->SetRangeUser(0,3000);

  h1->SetTitle("Original Induction");
  h3->SetTitle("Noise Removed Induction");
  
  Int_t max_bin = h1->GetMaximumBin();
  Float_t max = h1->GetBinContent(max_bin);
  Int_t min_bin = h1->GetMinimumBin();
  Float_t min = h1->GetBinContent(min_bin);
  
  TH1F *h2 = new TH1F("h2","h2",Int_t(max - min+2), min-1, max+1);
  
  //cout << h1->GetXaxis()->GetNbins() << " " << h1->GetYaxis()->GetNbins() << endl;
  for (Int_t i=0;i!=h1->GetXaxis()->GetNbins();i++){
    h2->Reset();
    for (Int_t j=0;j!=h1->GetYaxis()->GetNbins();j++){
      h2->Fill(h1->GetBinContent(i,j));
    }
    Double_t xq = 0.5;
    Double_t par[10];
    h2->GetQuantiles(1,&par[0],&xq);
    
    for (Int_t j=0;j!=h1->GetYaxis()->GetNbins();j++){
      h3->SetBinContent(i,j,h1->GetBinContent(i,j)-par[0]);
    }
    //cout << par[0] << endl;
    
  }
  c1->cd(2);
  h3->Draw("COLZ");
  h3->GetXaxis()->SetRangeUser(0,3000);
  

  // do deconvolution for every channel ...
  c1->cd(3);
  TFile *file1 = new TFile("ave_res.root");
  TH1F *hva = (TH1F*)file1->Get("hu");
  TGraph *gva = new TGraph();
  for (Int_t i=0;i!=hva->GetNbinsX();i++){
    Double_t x = hva->GetBinCenter(i+1);
    Double_t y = hva->GetBinContent(i+1) * (-1);
    gva->SetPoint(i,x,y);
  }
  TH1F *h2t = new TH1F("h2t","h2t",h1->GetXaxis()->GetNbins(),0,h1->GetXaxis()->GetNbins());
  TH1F *h2r = (TH1F*)h2t->Clone("h2r");
  h2r->Reset();
  for (Int_t i=0;i!=h2r->GetNbinsX();i++){
     Double_t x = h2r->GetBinCenter(i+1)/2.-50;
     h2r->SetBinContent(i+1,gva->Eval(x));
  }
  TF1 *filter_v = new TF1("filter_v","(x>0.0)*gaus*exp(-0.5*pow(x/[3],[4]))");
  double par1[5]={1.74/0.941034, 1.46, 1.33, 0.23, 4.89};
  filter_v->SetParameters(par1);

  TVirtualFFT::SetTransform(0);
  TH1 *hmr = 0;
  TH1 *hpr = 0;
  Int_t n = 8192;
  TVirtualFFT *ifft = TVirtualFFT::FFT(1,&n,"C2R M K");
  Double_t value_re[8192];
  Double_t value_im[8192];
  TH1 *fb = 0;
  TH1 *hmv = 0;
  TH1 *hpv = 0;

  for (Int_t k=0;k!=h1->GetYaxis()->GetNbins();k++){
  // for (Int_t k=33;k!=33+1;k++){
    h2t->Reset();
    for (Int_t i=0;i!=8192;i++){
      float content = h3->GetBinContent(i+1,k+1);
      h2t->SetBinContent(i+1,content);
    }
    h2t->Draw();

    cout << h2t->Integral(500,1500) << endl;
    //cout << max << " " << min << endl;
    hmr = 0;
    hpr = 0;
    hmr = h2r->FFT(hmr,"MAG");
    hpr = h2r->FFT(hpr,"PH");
    
    hmv = 0;
    hpv = 0;
    hmv = h2t->FFT(hmv,"MAG");
    hpv = h2t->FFT(hpv,"PH");
    
    for (Int_t j=0;j!=8192;j++){
      Double_t freq;
      if ( j < 8192/2.){
	freq = j/8192.*2.;
      }else{
	freq = (8192-j)/8192.*2.;
      }
      Double_t rho;
      if (hmr->GetBinContent(j+1)!=0){
	rho = hmv->GetBinContent(j+1) / hmr->GetBinContent(j+1)*filter_v->Eval(freq);
      }else{
	rho = 0;
      }
      Double_t phi = hpv->GetBinContent(j+1) - hpr->GetBinContent(j+1);
      value_re[j] = rho*cos(phi)/8192.;
      value_im[j] = rho*sin(phi)/8192.;
    }
    
    ifft->SetPointsComplex(value_re,value_im);
    ifft->Transform();
    fb = 0;
    fb = TH1::TransformHisto(ifft,fb,"Re");
    
    Double_t sum = 0;
    Double_t sum1 = 0;
    for (Int_t i=5000;i!=8000;i++){
      sum += fb->GetBinContent(i+1);
      sum1 += 1;
    }
    

    for (Int_t i=0;i!=8192;i++){
      Int_t binnum = i+1+104;
      if (binnum > 8192) binnum -=8192;
      h4->SetBinContent(binnum,k+1,fb->GetBinContent(i+1)-sum/sum1);
    }
  }


  h3->GetZaxis()->SetRangeUser(0,100);

  c1->cd(3);
  h4->RebinX(4);
  for (Int_t i=0;i!=h4->GetXaxis()->GetNbins();i++){
    for (Int_t j=0;j!=h4->GetYaxis()->GetNbins();j++){
      Double_t content1 = h4->GetBinContent(i+1,j+1);
      // if (content1 <1)
  	//	h4->SetBinContent(i+1,j+1,1);
    }
  }
  h4->Draw("COLZ");
  h4->GetZaxis()->SetRangeUser(0,30);
  h4->GetXaxis()->SetRangeUser(0,3000);
  c1->cd(4);
  TH2 *h5 = (TH2*)file->Get(Form("Col_%d",chan));
  h5->Draw("COLZ");
  h5->GetZaxis()->SetRangeUser(0,300);
  h5->GetXaxis()->SetRangeUser(0,3000);
  c1->cd(2);
  for (Int_t i=0;i!=h3->GetXaxis()->GetNbins();i++){
    for (Int_t j=0;j!=h3->GetYaxis()->GetNbins();j++){
      Double_t content1 = h3->GetBinContent(i+1,j+1);
      content1 = fabs(content1);
      h3->SetBinContent(i+1,j+1,content1);
    }
  }
  h3->Draw("COLZ");

  h4->SetTitle("Deconvoluted Induction");
  h5->SetTitle("Collection Raw");
  
  // c1->cd(1);
  // h2r->Draw();

  // c1->cd(4);
  // Double_t sum = 0;
  // Double_t sum1 = 0;
  // for (Int_t i=4000;i!=7000;i++){
  //   sum += fb->GetBinContent(i+1);
  //   sum1 += 1;
  // }
  // TH1F *h2k = (TH1F*)h2t->Clone("h2k");
  // for (Int_t j=0;j!=8192;j++){
  //   h2k->SetBinContent(j+1,fb->GetBinContent(j+1)-sum/sum1);
  // }
  // h2k->Rebin(4);
  // h2k->Draw();
  

}
Example #2
0
int ntuAnalyzer(std::string fileName)
{
  setGlobalStyle();
  
  //###############################
  //## run274200 ##
  unsigned int HT250Calo  = 9; //index of DST_HT250_CaloScouting_v   old:1 ref:9
  float HT250Calo_rate = 1928;

  unsigned int HT410PF = 7; //index of DST_HT410_PFScouting_v   old:3 ref:7
  float HT410PF_rate = 294;

  unsigned int MJJ200Calo = 12; //index of DST_DiCaloWideJetMass200_CaloScouting_v
  
  unsigned int HTT200 = 0; //index if L1_HTT200
  unsigned int HTT240 = 1; //index if L1_HTT240
  unsigned int HTT270 = 2; //index if L1_HTT270
  unsigned int HTT280 = 3; //index if L1_HTT280
  unsigned int DoubleJetC100 = 7; //index if L1_DoubleJetC100
  unsigned int DoubleJetC112 = 8; //index if L1_DoubleJetC112
  unsigned int DoubleIsoTau28er = 11; //index if L1_DoubleJetC112

  float instLumi = 0.4; //E34
  float targetLumi = 1; //E34
  float lumiScaleFactor = targetLumi/instLumi;

  float PDRate = 59300; //unprescaled rate of HLTPhysics accordingly to: https://cmswbm2.web.cern.ch/cmswbm2/cmsdb/servlet/DatasetSummary?RUN=274200 and prescale of 9000
  

  unsigned int L1scenario = HTT240;
  //###############################

  TChain* tt = new TChain("MyAnalysis/HLTree");
  tt->Add(fileName.c_str());

  //set branches
  TBranch* b_lumi;
  
  TBranch* b_caloMjj;
  TBranch* b_PFMjj;

  TBranch* b_hltAccept;
  TBranch* b_l1Accept;
  TBranch* b_l1Names;

  TBranch* b_caloJet1Pt;
  TBranch* b_caloJet2Pt;
  TBranch* b_caloJet1Eta;
  TBranch* b_caloJet2Eta;
  TBranch* b_caloDeltaEta;

  TBranch* b_PFJet1Pt;
  TBranch* b_PFJet2Pt;
  TBranch* b_PFJet1Eta;
  TBranch* b_PFJet2Eta;
  TBranch* b_PFDeltaEta;

  int lumi = 0;
  float caloMjj = 0;
  float PFMjj = 0;

  float caloJet1Pt_ = 0;
  float caloJet2Pt_ = 0;
  float caloJet1Eta_ = -999;
  float caloJet2Eta_ = -999;
  float caloDeltaEta_ = -999;

  float PFJet1Pt_ = 0;
  float PFJet2Pt_ = 0;
  float PFJet1Eta_ = -999;
  float PFJet2Eta_ = -999;
  float PFDeltaEta_ = -999;

  
  std::vector<int>* hltAccept = 0;
  std::vector<int>* l1Accept = 0;
  std::vector<string>* l1Names = 0;

  tt->SetBranchAddress("lumi", &lumi, &b_lumi);

  tt->SetBranchAddress("caloMjj", &caloMjj, &b_caloMjj);
  tt->SetBranchAddress("PFMjj", &PFMjj, &b_PFMjj);

  tt->SetBranchAddress("caloJet1Pt", &caloJet1Pt_, &b_caloJet1Pt);
  tt->SetBranchAddress("caloJet2Pt", &caloJet2Pt_, &b_caloJet2Pt);
  tt->SetBranchAddress("caloJet1Eta", &caloJet1Eta_, &b_caloJet1Eta);
  tt->SetBranchAddress("caloJet2Eta", &caloJet2Eta_, &b_caloJet2Eta);
  tt->SetBranchAddress("caloDeltaEta", &caloDeltaEta_, &b_caloDeltaEta);

  tt->SetBranchAddress("PFJet1Pt", &PFJet1Pt_, &b_PFJet1Pt);
  tt->SetBranchAddress("PFJet2Pt", &PFJet2Pt_, &b_PFJet2Pt);
  tt->SetBranchAddress("PFJet1Eta", &PFJet1Eta_, &b_PFJet1Eta);
  tt->SetBranchAddress("PFJet2Eta", &PFJet2Eta_, &b_PFJet2Eta);
  tt->SetBranchAddress("PFDeltaEta", &PFDeltaEta_, &b_PFDeltaEta);

  tt->SetBranchAddress("hltAccept", &hltAccept, &b_hltAccept);
  tt->SetBranchAddress("l1Accept", &l1Accept, &b_l1Accept);
  tt->SetBranchAddress("l1Names", &l1Names, &b_l1Names);

  int nentries = tt->GetEntries();
  std::cout << "Number of entries: " << nentries << std::endl;

  //book graphs and plots
  float min = 0.;
  float max = 1000.;
  int nBins = 20;

  TF1* f1 = new TF1("f1","[0]*TMath::Erf((x-[1])/[2])-[0]*TMath::Erf((-x-[1])/[2])",min,max);
  f1->SetParameters(0.5,350,40);  
  f1->FixParameter(0,0.5);
  f1->SetLineWidth(2.);
  f1->SetLineColor(kRed);

  TF1* f2 = (TF1*)f1->Clone("f2");
  f2->SetParameters(0.5,150,10);
  f2->SetLineColor(kBlack);

  TH1F* caloMjjSpectrum = new TH1F("caloMjjSpectrum","caloMjjSpectrum",nBins,min,max);
  TH1F* PFMjjSpectrum = new TH1F("PFMjjSpectrum","PFMjjSpectrum",nBins,min,max);
  
  TEfficiency* mjj450_eff = new TEfficiency("mjj450_eff","mjj450_eff",nBins,min,max);
  mjj450_eff->SetMarkerColor(kRed);
  mjj450_eff->SetLineColor(kRed);
  mjj450_eff->SetLineWidth(2);
  mjj450_eff->SetTitle("turnOn;Mjj [GeV]");
  TEfficiency* mjj200_eff = new TEfficiency("mjj200_eff","mjj200_eff",nBins,min,max);
  mjj200_eff->SetLineWidth(2);
  mjj200_eff->SetTitle("turnOn;Mjj [GeV]");
  TEfficiency* pf410_eff = new TEfficiency("pf410_eff","pf410_eff",nBins,min,max);
  pf410_eff->SetMarkerColor(kOrange+1);
  pf410_eff->SetLineColor(kOrange+1);
  TEfficiency* calo250_eff = new TEfficiency("calo250_eff","calo250_eff",nBins,min,max);
  calo250_eff->SetMarkerColor(kBlue);
  calo250_eff->SetLineColor(kBlue);
  TEfficiency* HTT240_eff = new TEfficiency("HTT240_eff","HTT240_eff",nBins,min,max);
  HTT240_eff->SetMarkerColor(kGreen+2);
  HTT240_eff->SetLineColor(kGreen+2);

  TH1F* l1 = new TH1F("l1","l1",14,0.,14.);
  TH1F* l2 = new TH1F("l2","l2",14,0.,14.);
  
  //loop
  for (Long64_t jentry=0; jentry<nentries;++jentry)
    {
      tt->GetEntry(jentry);

      //remove low rate lumis.
      //see: https://cmswbm2.web.cern.ch/cmswbm2/cmsdb/servlet/ChartHLTTriggerRates?RUNID=274200&PATHID=2043408&LSLENGTH=23.31040958&TRIGGER_PATH=DST_HT250_CaloScouting_v2
      //if(lumi > 539 && lumi < 553) continue;

      //l1 and hlt rates
      for(unsigned int ii=0; ii<l1Names->size(); ++ii)
	if (l1Accept->at(ii)==1)
	  l1->Fill(ii);
      
      
      //analysis cuts needed to compare to the analysis
      //calo analysis
      if (caloJet1Pt_ > 60. &&
	  caloJet2Pt_ > 30. &&
	  fabs(caloJet1Eta_) < 2.5 &&
	  fabs(caloJet2Eta_) < 2.5 &&
	  caloDeltaEta_ < 1.3)
	{
	  caloMjjSpectrum->Fill(caloMjj);
	  mjj200_eff->Fill((caloMjj>200 && l1Accept->at(L1scenario)==1) || hltAccept->at(HT250Calo)==1, caloMjj);
	  calo250_eff->Fill((hltAccept->at(HT250Calo)==1 && l1Accept->at(L1scenario)==1), caloMjj);

	  //references
	  HTT240_eff->Fill(l1Accept->at(HTT240)==1, caloMjj);
	  //l1 and hlt rates
	  for(unsigned int ii=0; ii<l1Names->size(); ++ii)
	    if (l1Accept->at(ii)==1)
	      l2->Fill(ii);
	}

      //PF analysis
      if (PFJet1Pt_ > 60. &&
	  PFJet2Pt_ > 30. &&
	  fabs(PFJet1Eta_) < 2.5 &&
	  fabs(PFJet2Eta_) < 2.5 &&
	  PFDeltaEta_ < 1.3)
	{
	  PFMjjSpectrum->Fill(PFMjj);
	  mjj450_eff->Fill((caloMjj>450 && l1Accept->at(L1scenario)==1) || hltAccept->at(HT410PF)==1, PFMjj);
	  pf410_eff->Fill((hltAccept->at(HT410PF)==1 && l1Accept->at(L1scenario)==1), PFMjj);
	}
    }

  mjj450_eff->Fit(f1,"r");
  mjj200_eff->Fit(f2,"r");


  caloMjjSpectrum->Scale(1./caloMjjSpectrum->GetBinContent(caloMjjSpectrum->GetMaximumBin()));
  PFMjjSpectrum->Scale(1./PFMjjSpectrum->GetBinContent(PFMjjSpectrum->GetMaximumBin()));

			      
  
  TLegend* leg0 = new TLegend(0.62, 0.78, 0.83, 0.89);
  leg0->AddEntry(mjj200_eff,"MJJ200Calo || HT250Calo","L");
  leg0->AddEntry(calo250_eff,"HT250_Calo","P");
  leg0->AddEntry(HTT240_eff,"HTT240","P");

  TLegend* leg1 = new TLegend(0.62, 0.78, 0.83, 0.89);
  leg1->AddEntry(mjj450_eff,"MJJ450PF || HT410PF","L");
  leg1->AddEntry(pf410_eff,"HT410_PF","P");

  TCanvas* c1 = new TCanvas();
  mjj200_eff->Draw();
  calo250_eff->Draw("sames");
  HTT240_eff->Draw("sames");
  caloMjjSpectrum->Draw("L,sames");
  leg0->Draw("sames");

  TCanvas* c2 = new TCanvas();
  mjj450_eff->Draw();
  pf410_eff->Draw("sames");
  PFMjjSpectrum->Draw("L,sames");
  leg1->Draw("sames");

  TCanvas* c3 = new TCanvas();
  //l1->Scale(PDRate/nentries);

  for(unsigned int ii=0; ii<l1Names->size(); ++ii)
    l1->GetXaxis()->SetBinLabel(ii+1,l1Names->at(ii).c_str());
  //l1->GetYaxis()->SetTitle("L1 Rate @4E33 [Hz]");
  l1->SetMaximum(l1->GetMaximum()+200);
  l2->SetLineColor(kRed);
  
  l1->Draw();
  l2->Draw("same");
  c3->Update();

  // TGaxis *l1axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(), gPad->GetUymax(),
  // 			      l1->GetMinimum()*lumiScaleFactor,
  // 			      l1->GetMaximum()*lumiScaleFactor,510,"+L");

  // c2->SetTicky(0);
  // l1axis->SetLineColor(kRed);
  // l1axis->SetLabelColor(kRed);
  // l1axis->SetTextColor(kRed);
  // l1axis->SetTitleOffset(1.3);
  // l1axis->SetLabelSize(0.03);
  // l1axis->SetTitle("L1 Rate @1E34 [Hz]");
  // l1axis->Draw();
  
  
  //return 0;

  //##############################################
  //##############################################

  //book graphs and plots
  TGraphErrors* totRateVsCut = new TGraphErrors();
  totRateVsCut->SetMinimum(0);
  TGraphErrors* pureRateVsCut450 = new TGraphErrors();
  TGraphErrors* pureRateVsCut280 = new TGraphErrors();

  //loops
  int bin = 0;
  for (int cut = 350; cut < 500; cut=cut+10)
    {
      int mjjPassed = 0;
      int HT250Calo_Passed = 0;
      int excl410_passed = 0;
      int excl250_passed = 0;
      for (Long64_t jentry=0; jentry<nentries;++jentry) 
	{
	  tt->GetEntry(jentry);

	  if (hltAccept->at(HT250Calo) == 1)
	    ++HT250Calo_Passed;

	  //if (caloMjj > cut && !hltAccept->at(HT410PF))
	  if (caloMjj > cut && l1Accept->at(L1scenario) == 1 && hltAccept->at(HT410PF)==0)
	    ++excl410_passed;
	  if (caloMjj > cut && l1Accept->at(L1scenario)==1 && hltAccept->at(HT250Calo)==0)
	    ++excl250_passed;
	  if (caloMjj > cut && l1Accept->at(L1scenario)==1)
	    ++mjjPassed;

	  // if (hltAccept->at(HT250Calo) == 0 && mjj > cut)
	  //   std::cout << "ref trigger doesn't completely cover cut at " << cut << std::endl;
	}
      // float mjjTotalRate = (float)mjjPassed/(float)HT250Calo_Passed*HT250Calo_rate;
      // float mjjPureRate = (float)exclPassed/(float)HT250Calo_Passed*HT250Calo_rate;

      float sigmaMjjPassed = sqrt((float)mjjPassed);
      float sigmaNentries = sqrt((float)nentries);
      float sigmaExcl410_passed = sqrt((float)excl410_passed);
      float sigmaExcl250_passed = sqrt((float)excl250_passed);

      float mjjTotalRate = (float)mjjPassed/(float)nentries*PDRate;
      float mjjTotalRateE = PDRate*sqrt(pow((sigmaMjjPassed/nentries),2)+pow((sigmaNentries*mjjPassed/nentries/nentries),2));

      float mjj450_PureRate = (float)excl410_passed/(float)nentries*PDRate;
      float mjj450_PureRateE = PDRate*sqrt(pow((sigmaExcl410_passed/nentries),2)+pow((sigmaNentries*excl410_passed/nentries/nentries),2));
      
      float mjj280_PureRate = (float)excl250_passed/(float)nentries*PDRate;
      float mjj280_PureRateE = PDRate*sqrt(pow((sigmaExcl250_passed/nentries),2)+pow((sigmaNentries*excl250_passed/nentries/nentries),2));

      totRateVsCut->SetPoint(bin,cut,mjjTotalRate);
      totRateVsCut->SetPointError(bin,0.,mjjTotalRateE);

      pureRateVsCut450->SetPoint(bin,cut,mjj450_PureRate);
      pureRateVsCut450->SetPointError(bin,0.,mjj450_PureRateE);

      pureRateVsCut280->SetPoint(bin,cut,mjj280_PureRate);
      pureRateVsCut280->SetPointError(bin,0.,mjj280_PureRateE);

      ++bin;
    }

  //plotting and styling
  TLegend* leg = new TLegend(0.62, 0.78, 0.83, 0.89);
  leg->AddEntry(totRateVsCut,"total rate","P");
  leg->AddEntry(pureRateVsCut450,"pure rate wrt HT410PF","P");
  leg->AddEntry(pureRateVsCut280,"pure rate wrt HT250Calo","P");

  totRateVsCut->SetTitle("Rate Ref");

  totRateVsCut->GetXaxis()->SetTitle("Mjj cut threshold [GeV]");
  totRateVsCut->GetYaxis()->SetTitle("Rate @4E33 [Hz]");
  pureRateVsCut450->SetMarkerColor(kRed);
  pureRateVsCut450->SetLineColor(kRed);
  pureRateVsCut280->SetMarkerColor(kOrange+1);
  pureRateVsCut280->SetLineColor(kOrange+1);

  TCanvas* c4 = new TCanvas();
  c4->cd();
  totRateVsCut->Draw("AP");
  pureRateVsCut450->Draw("P,sames");
  pureRateVsCut280->Draw("P,sames");
  leg->Draw("sames");
  c4->Update();

  TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(), gPad->GetUymax(),
    			    (totRateVsCut->GetYaxis()->GetBinLowEdge(1))*lumiScaleFactor,
			    (totRateVsCut->GetYaxis()->GetBinLowEdge(totRateVsCut->GetYaxis()->GetNbins())+totRateVsCut->GetYaxis()->GetBinWidth(1))*lumiScaleFactor,510,"+L");

  c4->SetTicky(0);
  axis->SetLineColor(kRed);
  axis->SetLabelColor(kRed);
  axis->SetTextColor(kRed);
  axis->SetTitleOffset(1.3);
  axis->SetLabelSize(0.03);
  axis->SetTitle("Rate @1E34 [Hz]");
  axis->Draw();


  return 0;
}
Example #3
0
void analysis() {
    Int_t nbins = 800;
    Int_t j;
    char name[20];
    char title[100];
    TH1F *HistoEvent[2214];
    for (Int_t z=0;z<2214;z++) {
        sprintf(name,"HistoEvent%d",z-1);
        sprintf(title,"Event%d Histo", z-1);
        HistoEvent[z] = new TH1F(name,title,nbins, -0.1, 159.9);
    }
    TH1F *NewHistoEvent[2214];
    for (Int_t z=0;z<2214;z++) {
        sprintf(name,"NewHistoEvent%d",z-1);
        sprintf(title,"Event%d Histo", z-1);
        NewHistoEvent[z] = new TH1F(name,title,nbins, -0.1, 159.9);
    }
    TH1F *NewHistoEventFFT[2214];
    for (Int_t z=0;z<2214;z++) {
        sprintf(name,"NewHistoEventFFT%d",z-1);
        sprintf(title,"Event%d Histo", z-1);
        NewHistoEventFFT[z] = new TH1F(name,title,nbins, 0, 5);
    }
    Double_t mean;
    Double_t rms;
    Double_t meansum = 0;
    Double_t count = 0;
    Double_t meanrms = 0;
	TFile f("/home/marko/H4Analysis/ntuples/analysis_4443.root"); //ntuple generated by H4Analysis tool
	TFile f1("/home/marko/H4Analysis/ntuples/analysis_3905.root");
    TFile f2("/home/marko/Desktop/TB Timing Res/NormalizedSignalNoise.root", "read");
    TH1F* BestSignal = (TH1F*) f2.Get("BetterSignal");
    TFile outputfile("myoutput.root", "recreate");
    TCanvas* TimeandFreq = new TCanvas("TimeandFreq","Time and Frequency",1500,900);
    TCanvas* Freq = new TCanvas("Freq","Frequency",800,1200);
    TCanvas* TimeSignal = new TCanvas("TimeSignal","Pure Signal",800,1200);
	TimeandFreq->Divide(2,2);
	TTree* h4 = (TTree*) f.Get("h4");
    TTree* h4_2 = (TTree*) f1.Get("h4");
    TString plot;
    TString cut;
	TH2F* WavePulse = new TH2F ("WavePulse", "Wave Pulse", nbins, -0.1, 159.9, 850, -50, 800);
    TH2F* NoisePulse = new TH2F ("NoisePulse", "Noise", nbins, -0.1, 159.9, 100, -50, 50);
    TH1F* PulseTime = new TH1F ("PulseTime", "Original Wave Pulse", nbins, -0.1, 159.9); //nanoseconds
    TH2F* TempHisto = new TH2F ("TempHisto", "Temp Histo", nbins, -0.1, 159.9, 1000, -15, 15); //nanoseconds
	h4->Draw("WF_val:WF_time>>WavePulse", "WF_ch==2 && event==1 && spill==1");
    h4_2->Draw("WF_val:WF_time>>NoisePulse","WF_ch==APD1 && amp_max[APD3]<25 && b_rms[APD3]<5. && charge_tot[APD3]<20000 &&  amp_max[APD5]<25 && b_rms[APD5]<5. &&  amp_max[APD6]<25 && b_rms[APD6]<5. &&  amp_max[APD4]<25 && b_rms[APD4]<5. && amp_max[SiPM1]<20 && amp_max[SiPM2]<20 && amp_max[APD1]<40 && amp_max[APD2]<40 && b_rms[APD1]<5. && b_rms[APD2]<5. && WF_time<160");
    for (Int_t i=0; i<nbins; i++) {
		for (Int_t k=0; k<4096; k++) {
			if (WavePulse->GetBinContent(i+1, k) != 0) {
				PulseTime->SetBinContent(i+1,k-50);
			}
		}
	}
    TH1F *NoiseTime = new TH1F ("NoiseTime", "Noise", nbins, -0.1, 159.9);
    for (Int_t i=0; i<nbins; i++) {
        for (Int_t k=0; k<4096; k++) {
            if (NoisePulse->GetBinContent(i+1, k) != 0) {
                NoiseTime->SetBinContent(i+1,k-62.9087);
            }
        }
    }
    //TH1F* NormNoiseFFT = new TH1F ("NormNoiseFFT", "Normalized Noise FFT", nbins, 0, 5);
    //TStopwatch t;
    //t.Start(); //1 hour runtime
    //for (j=10;j<20;j++) {
    //    plot = "WF_val:WF_time>>TempHisto";
    //    cut = "WF_ch==APD1 && amp_max[APD3]<25 && b_rms[APD3]<5. && charge_tot[APD3]<20000 &&  amp_max[APD5]<25 && b_rms[APD5]<5. &&  amp_max[APD6]<25 && b_rms[APD6]<5. &&  amp_max[APD4]<25 && b_rms[APD4]<5. && amp_max[SiPM1]<20 && amp_max[SiPM2]<20 && amp_max[APD1]<40 && amp_max[APD2]<40 && b_rms[APD1]<5. && b_rms[APD2]<5. && WF_time<160 && event==";
    //    cut += j;
    //    h4_2->Draw(plot, cut, "goff");
    //    if (TempHisto->GetMaximum() == 0) {
    //        delete HistoEvent[j+1];
    //        continue;
    //    }
    //    for (Int_t i=0; i<nbins; i++) {
    //        for (Int_t k=0; k<1000; k++) {
    //            if (TempHisto->GetBinContent(i+1, k) != 0) {
    //                HistoEvent[j+1]->SetBinContent(i+1,k*0.03-15);
    //            }
    //        }
    //    }
    //    mean = TempHisto->GetMean(2);
    //    rms = TempHisto->GetRMS(2);
    //    for (Int_t q=0;q<nbins;q++) {
    //        NewHistoEvent[j+1]->SetBinContent(q+1, HistoEvent[j+1]->GetBinContent(q+1)-mean);
    //    }
    //    NewHistoEvent[j+1]->Scale(1/rms);
    //    NewHistoEvent[j+1]->FFT(NewHistoEventFFT[j+1], "MAG");
    //    NormNoiseFFT->Add(NormNoiseFFT, NewHistoEventFFT[j+1]);
    //    TempHisto->Write();
    //    NewHistoEvent[j+1]->Write();
    //    NewHistoEventFFT[j+1]->Write();
    //    cout << "Event " << j << ", Mean = " << mean << ", RMS = " << rms << endl;
    //    count += 1;
    //}
    //NormNoiseFFT->Scale(1/count);
    //NormNoiseFFT->Write();
    //t.Stop();
    //t.Print();
	new TFile("/home/marko/H4Analysis/ntuples/analysis_4443.root"); // ignore this reloading of the same file, it is required or else the plots do not show up (when I tried)
    TimeandFreq->cd(1);
    PulseTime->GetXaxis()->SetTitle("Time (ns)");
    PulseTime->GetYaxis()->SetTitle("Amplitude");
    PulseTime->DrawClone(); //Wave Pulse in Time domain
    TimeandFreq->cd(2);
    TH1F* PulseFreq = new TH1F ("PulseFreq", "Pulse FFT", nbins, 0, 5);
    TH1F* PulsePhase = new TH1F ("PulsePhase", "Pulse Phase", nbins, -0.1, 799.9);
    PulseTime->FFT(PulseFreq, "MAG");
    PulseTime->FFT(PulsePhase, "PH");
    PulseFreq->SetLineColor(kRed);
    PulseFreq->GetXaxis()->SetTitle("Frequency (GHz)");
    PulseFreq->GetYaxis()->SetTitle("Amplitude");
    PulseFreq->DrawClone(); //Wave Pulse in Frequency domain
    gPad->SetLogy();
    TimeandFreq->cd(3);
    NoiseTime->GetXaxis()->SetTitle("Time (ns)");
    NoiseTime->GetYaxis()->SetTitle("Amplitude");
    NoiseTime->DrawClone(); // Noise from pedestal in Time domain
    TimeandFreq->cd(4);
    TH1F* NoiseFreq = new TH1F ("NoiseFreq", "Noise FFT", nbins, 0, 5);
    NoiseTime->FFT(NoiseFreq, "MAG");
    NoiseFreq->GetXaxis()->SetTitle("Frequency (GHz)");
    NoiseFreq->GetYaxis()->SetTitle("Amplitude");
    NoiseFreq->Draw(); // Noise from pedestal in Frequency domain
    gPad->SetLogy();
    Freq->Divide(1,3);
    Freq->cd(1);
    PulseFreq->DrawClone();
    gPad->SetLogy();
    Freq->cd(2);
    NoiseFreq->DrawClone();
    gPad->SetLogy();
    Freq->cd(3);
    PulseFreq->SetTitle("Pulse and Noise FFT Comparison");
    PulseFreq->Draw();
    NoiseFreq->Draw("same");
    gPad->SetLogy();
    TH1F* UnscaledSignalFreq = new TH1F ("UnscaledSignalFreq", "Unscaled Signal Frequency", nbins, -0.1, 799.9);
    for (Int_t l=0; l<nbins; l++) {
        UnscaledSignalFreq->SetBinContent(l+1, (PulseFreq->GetBinContent(l+1)-NoiseFreq->GetBinContent(l+1))/PulseFreq->GetBinContent(l+1));
    }
    TH1F* SignalFreq = new TH1F ("SignalFreq", "Signal Frequency", nbins, 0, 799.9);
    for (Int_t m=0; m<nbins; m++) {
        SignalFreq->SetBinContent(m+1, UnscaledSignalFreq->GetBinContent(m+1)*PulseFreq->GetBinContent(m+1));
    }
    Double_t *re_full = new Double_t[nbins];
    Double_t *im_full = new Double_t[nbins];
    for (Int_t n=0; n<nbins; n++) {
        (re_full)[n]=(SignalFreq->GetBinContent(n+1)*cos(PulsePhase->GetBinContent(n+1)));
        (im_full)[n]=(SignalFreq->GetBinContent(n+1)*sin(PulsePhase->GetBinContent(n+1)));
    }
    TVirtualFFT *invFFT = TVirtualFFT::FFT(1, &nbins, "C2R M K");
    invFFT->SetPointsComplex(re_full, im_full);
    invFFT->Transform();
    TH1 *Signal = 0;
    Signal = TH1::TransformHisto(invFFT,Signal,"Re");
    Signal->SetTitle("Recovered Signal 'S'");
    TH1F* BetterSignal = new TH1F ("BetterSignal", "Recovered Signal", nbins, -0.1, 159.9);
    for (Int_t p=0; p<nbins; p++) {
        BetterSignal->SetBinContent(p+1, Signal->GetBinContent(p+1)/nbins);
    }
    TimeSignal->Divide(1,2);
    TimeSignal->cd(1);
    PulseTime->DrawClone(); //Original Wave Pulse
    TimeSignal->cd(2);
    BetterSignal->GetXaxis()->SetTitle("Time (ns)");
    BetterSignal->GetYaxis()->SetTitle("Amplitude");
    BetterSignal->SetLineColor(kRed);
    //BetterSignal->Draw(); // Recovered Wave Pulse with decreased contribution from background noise
    BestSignal->SetLineColor(kGreen);
    BestSignal->DrawClone("same");
    PulseTime->DrawClone("same");
}
void makeTable(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, TString inFileName,
               bool isBlind, bool isLog, 
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();

  // prepare the necessary for the scale factor estimation
  float defScaleFactor = 1.3;
  float newScaleFactor = 1.;
  float varScaleFactor = 1.;
  float nBkg = 0;
  float nBkgErrSq = 0;
  float nSig = 0;
  float nSigErrSq = 0;
    
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  //variable bin histo
  if (xlowVec != 0) hdata = new TH1F("hdata","",nBins,xlowVec);
  //fixed bin histo
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  
  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    
    if ( iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
       cout << *listOfSamples.at(iSample)->Legend() << " ";
    }

    //fill the histogram
    
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "hlt_weight*evt_weight*kf_weight*pu_weight" + myCut,"goff");
        
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       cout << hist[theHistCounter] -> GetBinContent(1) << " +/- " <<  hist[theHistCounter] -> GetBinError(1) << endl;
       if ( listOfSamples.at(iSample)->Name()->Contains("wgptg130") ) {
         nSig +=  hist[theHistCounter] -> GetBinContent(1) ;
         nSigErrSq +=  pow(hist[theHistCounter] -> GetBinError(1),2) ;
       }
       else {
         nBkg +=  hist[theHistCounter] -> GetBinContent(1) ;
         nBkgErrSq +=  pow(hist[theHistCounter] -> GetBinError(1),2) ;
       }
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  cout << "total MC " << theMCSum -> GetBinContent(1) << " +/- " << theMCSum -> GetBinError(1) << endl;
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
    
  if (isBlind) cout << "total DATA " << hdata -> GetBinContent(1) << " +/- " <<  hdata -> GetBinError(1) << endl;

  //compute the scale factor
  float nData =  hdata -> GetBinContent(1);
  float nDataErr =  hdata -> GetBinError(1);
  newScaleFactor = (nData - nBkg)/(nSig/defScaleFactor);
  float newScaleFactorErr = sqrt( (pow(nDataErr,2) + nBkgErrSq)/(nData - nBkg)/(nData - nBkg) + nSigErrSq/nSig/nSig ) * newScaleFactor;
  cout << "\n The scale factor is " << newScaleFactor << " +/- " << newScaleFactorErr << endl;
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  infile -> Close();
  delete infile;
  
  return;
}
Example #5
0
int main(int argc, char **argv){


  vector <string> inputs;
  for (int i=1;i<argc;++i){
    inputs.push_back(string(argv[i]));
  }
  if (inputs.size() == 0 ){ // no argumnets display helpful message
    cout<<"Usage: ./LendaAnalysis runNumber [options:value]"<<endl;
    return 0;
  }  
  
  InputManager theInputManager;
  if ( !  theInputManager.loadInputs2(inputs) ){
    return 0;
  }
  

  BuildBins();  
  ////////////////////////////////////////////////////////////////////////////////////

  //load settings

  Int_t runNum=theInputManager.runNum;
  Int_t numFiles=theInputManager.numFiles;

  Long64_t maxentry=theInputManager.maxEntry;

  

  

  //prepare files
  ////////////////////////////////////////////////////////////////////////////////////
  TFile *outFile=0;
  
  FileManager * fileMan = new FileManager();
  fileMan->fileNotes = theInputManager.notes;
  
  ///The input trees are put into a TChain
  TChain * inT;
  if (theInputManager.specificFileName !=""){
    inT= new TChain("flt");
    for (int i=theInputManager.StartFile;i<theInputManager.StartFile+numFiles;i++){
      TString s =fileMan->LoadFile(runNum,i,theInputManager.specificFileName);
      inT->Add(s);
      cout<<"Adding file "<<s<<endl;
    }
  }


  Long64_t nentry=(Long64_t) (inT->GetEntries());
  cout <<"The number of entires is : "<< nentry << endl ;
  
  // Openning output Tree and output file

  stringstream temp;
  if ( theInputManager.StartFile !=0 )
    temp<<"~/analysis/run"<<runNum<<"/Run"<<runNum<<"LA"<<theInputManager.StartFile<<".root";
  else 
    temp<<"~/analysis/run"<<runNum<<"/Run"<<runNum<<"LA0"<<".root";
  outFile = new TFile(temp.str().c_str(),"recreate");


  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////
  //Declare A Bunch Of histograms
  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////
  Int_t NumOfChannelsInModule=16;

  vector <TH1F*> EnergiesRaw(NumOfChannelsInModule);
  vector <TH1F*> EnergiesNoOFs(NumOfChannelsInModule);  
  vector <TH1F*> EnergiesCorrected(NumOfChannelsInModule);  
  
  vector< vector <TH1F*> > ReferenceEnergiesScaled(100);

  vector < vector <TH1F*> > EnergiesRawForN; //outer vector for various Multiplicities
  vector < vector <TH1F*> > EnergiesNoOFsForN; //outer vector for various Multiplicities
  vector < vector <TH1F*> > EnergiesCorrectedForN;
  //Defualt Binning For Energy Histograms
  Double_t ERawBinning[3];
  ERawBinning[0]=1000;
  ERawBinning[1]=0;
  ERawBinning[2]=40000;
  
  //Raw Channels Histogram
  TH1F * ChannelsRaw = new TH1F("ChannelsRaw","ChannelsRaw",16,0,15);

  //Channels Histogram for different multiplicities
  vector <TH1F*> ChannelsForN;

  //Energy Cut settings for Channel histograms
  Double_t NumOfChannelECuts = 20;
  Double_t MaxEnergy = 7000;
  vector <TH1F *> ChannelsECut(NumOfChannelECuts);

  TH1F * Multiplicity = new TH1F("Multiplicity","Multiplicity",16,0,15);


  stringstream nameStream;
  for (int i=0;i<NumOfChannelsInModule;i++){
    
    nameStream.str("");
    nameStream<<"ERaw"<<i;
    EnergiesRaw[i]= new TH1F(nameStream.str().c_str(),nameStream.str().c_str(),
				 ERawBinning[0],ERawBinning[1],ERawBinning[2]);
    nameStream.str("");
    nameStream<<"ENoOverFlows"<<i;
    EnergiesNoOFs[i]= new TH1F(nameStream.str().c_str(),nameStream.str().c_str(), // use same binning as raw histos
			       ERawBinning[0],ERawBinning[1],ERawBinning[2]);

    nameStream.str("");
    nameStream<<"ECor"<<i;
    EnergiesCorrected[i]= new TH1F(nameStream.str().c_str(),nameStream.str().c_str(), // use same binning as raw histos
			       ERawBinning[0],ERawBinning[1],ERawBinning[2]);

  }
  for (int i=0;i<ReferenceEnergiesScaled.size();i++){
    ReferenceEnergiesScaled[i].resize(100);
    for (int j=0;j<ReferenceEnergiesScaled[i].size();j++){
      nameStream.str("");
      nameStream<<"RefScaledE"<<i<<"_"<<j;
      ReferenceEnergiesScaled[i][j] = new TH1F(nameStream.str().c_str(),nameStream.str().c_str(), 
					    500,ERawBinning[1],ERawBinning[2]);
    }
  }
  

  Int_t MaxMultiplicity=6;
  EnergiesRawForN.resize(MaxMultiplicity);
  EnergiesNoOFsForN.resize(MaxMultiplicity);
  EnergiesCorrectedForN.resize(MaxMultiplicity);
  ChannelsForN.resize(MaxMultiplicity);


  TH2F* test = new TH2F("test","",1000,0,20000,1000,0,20000);
  
  TH2F* PulseShapeTrig = new TH2F("PulseShapeTrig","",1000,0,20000,1000,0,5);
  TH2F* LongVShortTrig = new TH2F("LongVShortTrig","",1000,0,20000,1000,0,20000);
  vector <TH2F*> LongVShortTrigForN(MaxMultiplicity);
  vector <TH2F*> PulseShapeTrigForN(MaxMultiplicity);


  TH2F* PulseShapeRef = new TH2F("PulseShapeRef","",1000,0,20000,1000,0,5);
  TH2F* LongVShortRef = new TH2F("LongVShortRef","",1000,0,20000,1000,0,20000);
  vector <TH2F*> LongVShortRefForN(MaxMultiplicity);
  vector <TH2F*> PulseShapeRefForN(MaxMultiplicity);




  //Declare things histograms for particular multiplicities
  for (int j=0;j<MaxMultiplicity;j++){
    for (int i=0;i<NumOfChannelsInModule;i++){
      nameStream.str("");
      nameStream<<"ERaw"<<i<<"N"<<j+1;
      EnergiesRawForN[j].push_back( new TH1F(nameStream.str().c_str(),nameStream.str().c_str(),
					 ERawBinning[0],ERawBinning[1],ERawBinning[2]));
      nameStream.str("");
      nameStream<<"ENoOverFlows"<<i<<"N"<<j+1;
      EnergiesNoOFsForN[j].push_back( new TH1F(nameStream.str().c_str(),nameStream.str().c_str(), // use same binning as raw histos
					   ERawBinning[0],ERawBinning[1],ERawBinning[2]));

      nameStream.str("");
      nameStream<<"ECor"<<i<<"N"<<j+1;
      EnergiesCorrectedForN[j].push_back( new TH1F(nameStream.str().c_str(),nameStream.str().c_str(), // use same binning as raw histos
					   ERawBinning[0],ERawBinning[1],ERawBinning[2]));

    }
    nameStream.str("");
    nameStream<<"ChannelsN"<<j+1;
    ChannelsForN[j] = new TH1F(nameStream.str().c_str(),nameStream.str().c_str(),16,0,15);
    //Trigger Scint for N
    nameStream.str("");
    nameStream<<"LongVShortTrigN"<<j+1;
    LongVShortTrigForN[j] = new TH2F(nameStream.str().c_str(),"",1000,0,20000,1000,0,20000);

    nameStream.str("");
    nameStream<<"PulseShapeTrigN"<<j+1;
    PulseShapeTrigForN[j] = new TH2F(nameStream.str().c_str(),"",1000,0,20000,1000,0,5);
    //Reference Scint for N
    nameStream.str("");
    nameStream<<"LongVShortRefN"<<j+1;
    LongVShortRefForN[j] = new TH2F(nameStream.str().c_str(),"",1000,0,20000,1000,0,20000);

    nameStream.str("");
    nameStream<<"PulseShapeRefN"<<j+1;
    PulseShapeRefForN[j] = new TH2F(nameStream.str().c_str(),"",1000,0,20000,1000,0,5);

  }
  

  for (int i=0;i<NumOfChannelECuts;i++){
    nameStream.str("");
    nameStream<<"ChannelsECut_"<<floor((i/NumOfChannelECuts)*MaxEnergy);

    ChannelsECut[i] = new  TH1F(nameStream.str().c_str(),nameStream.str().c_str(),16,0,15);
  }

  int nBinsForTOF=16000;
  int nBinsForLLEnergy=200;
  int nBinsForEnergy=1000;
  ///Time of Flight spectra for lenda bar in coincidence with trigger
  TH1F * TOF = new TH1F("TOF","",nBinsForTOF,-150,150);// Time of flight in clock tics raw
  TH1F * TOFPS = new TH1F("TOFPS","",nBinsForTOF,-150,150);// Time of flight in clock tics with PS
  TH1F * ShiftTOF = new TH1F("ShiftTOF","",nBinsForTOF,-150,150);// Time of flight in clock tics After GammaPeak Shift
  TH1F * TOFWithPS = new TH1F("TOFWithPS","",nBinsForTOF,-150,150);// Time of Flight with only Gammas on trig
  TH1F * TOFEnergy = new TH1F("TOFEnergy","",nBinsForTOF,0,150); // the Energy from TOF Raw
  TH1F * TOFEnergyNeutrons = new TH1F("TOFEnergyNeutrons","",nBinsForEnergy,0,20); // TOF energy with gammas cut and PS
  TH1F* TOFEnergyRandomBkg = new TH1F("TOFEnergyRandomBkg","",nBinsForEnergy,0,20);// TOF energy for negative time Of Flights
  TH1F* TOFEnergyRBkgSubtracted = new TH1F("TOFEnergyRBkgSubtracted","",nBinsForEnergy,0,20);// TOFEnergyNeutrons-TOFEnergyRandomBkg 

  TH1F* TOFEnergyCFBins = new TH1F("TOFEnergyCFBins","",NumOfCFBins,CFBins);  
  TH1F* TOFEnergyBkgCFBins = new TH1F("TOFEnergyBkgCFBins","",NumOfCFBins,CFBins);  
  TH1F* TOFEnergySubCFBins = new TH1F("TOFEnergySubCFBins","",NumOfCFBins,CFBins);  
  
  TH2F* EvsTOFEnergy = new TH2F("EvsTOFEnergy","",nBinsForEnergy,0,20,1000,0,20000);
  TH2F* EvsTOFEnergyBkg = new TH2F("EvsTOFEnergyBkg","",nBinsForEnergy,0,20,1000,0,20000);
  
  

  ////Time of Flight spectra for reference scintillator in coincidence with trigger
  TH1F * TOFL_L = new TH1F("TOFL_L","",nBinsForTOF,-150,150);// Time of flight in clock tics raw
  TH1F * TOFPSL_L = new TH1F("TOFPSL_L","",nBinsForTOF,-150,150);// Time of flight in clock tics with PS
  TH1F * ShiftTOFL_L = new TH1F("ShiftTOFL_L","",nBinsForTOF,-150,150);// Time of flight in clock tics After GammaPeak Shift
  TH1F * TOFWithPSL_L = new TH1F("TOFWithPSL_L","",nBinsForTOF,-150,150);// Time of Flight with only Gammas on trig
  TH1F * TOFWith2PSL_L = new TH1F("TOFWith2PSL_L","",nBinsForTOF,-150,150);// Time of Flight with only Gammas on trig
  TH1F * TOFEnergyL_L = new TH1F("TOFEnergyL_L","",nBinsForTOF,0,150); // the Energy from TOF Raw
  TH1F * TOFEnergyNeutronsL_L = new TH1F("TOFEnergyNeutronsL_L","",nBinsForLLEnergy,0,20); // TOF energy with gammas cut and PS
  TH1F * TOFEnergyRandomBkgL_L = new TH1F("TOFEnergyRandomBkgL_L","",nBinsForLLEnergy,0,20);// TOF energy for negative time Of Flights
  TH1F * TOFEnergyNeutrons1PSL_L = new TH1F("TOFEnergyNeutrons1PSL_L","",nBinsForLLEnergy,0,20); // TOF energy with gammas cut and PS
  TH1F * TOFEnergyRandomBkg1PSL_L = new TH1F("TOFEnergyRandomBkg1PSL_L","",nBinsForLLEnergy,0,20);// TOF energy for negative time Of Flights
  TH1F * TOFEnergyRBkgSubtracted1PSL_L = new TH1F("TOFEnergyRBkgSubtracted1PSL_L","",nBinsForLLEnergy,0,20);//
  TH1F* TOFEnergyCFBinsL_L = new TH1F("TOFEnergyCFBinsL_L","",NumOfCFBins,CFBins);  
  TH1F* TOFEnergyBkgCFBinsL_L = new TH1F("TOFEnergyBkgCFBinsL_L","",NumOfCFBins,CFBins);  
  TH1F* TOFEnergySubCFBinsL_L = new TH1F("TOFEnergySubCFBinsL_L","",NumOfCFBins,CFBins);  

  TH2F* EvsTOFEnergyL_L = new TH2F("EvsTOFEnergyL_L","",nBinsForLLEnergy,0,20,1000,0,20000);
  TH2F* EvsTOFEnergyBkgL_L = new TH2F("EvsTOFEnergyBkgL_L","",nBinsForLLEnergy,0,20,1000,0,20000);

  double RefScintThresh=313.619;
  
  vector<double> threshVals(2);
  threshVals[0]=43.9740;
  threshVals[1]=153.647;//{ Americum 26.3, americium 59.5}
  vector <TH1F*> LendaThreshs(threshVals.size());
  vector <TH1F*> LendaThreshsBkg(threshVals.size());
  vector <TH1F*> LendaThreshsResult(threshVals.size());

  for (int i=0;i<threshVals.size();i++){
    nameStream.str("");
    nameStream<<"LendaThresh_"<<TMath::Floor(threshVals[i]);
    LendaThreshs[i] = new TH1F(nameStream.str().c_str(),"",NumOfCFBins,CFBins);

    nameStream.str("");
    nameStream<<"LendaThreshBkg_"<<TMath::Floor(threshVals[i]);
    LendaThreshsBkg[i] = new TH1F(nameStream.str().c_str(),"",NumOfCFBins,CFBins);
    
    nameStream.str("");
    nameStream<<"LendaThreshSub_"<<TMath::Floor(threshVals[i]);
    LendaThreshsResult[i] = new TH1F(nameStream.str().c_str(),"",NumOfCFBins,CFBins);
  }


  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////
  //Main Analysis Loop
  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////  //////////////////////////////////////////////

  LendaEvent * theEvent = new LendaEvent();
  inT->SetBranchAddress("Event",&theEvent);
  for (Long64_t jentry=0;jentry<nentry;jentry++){ // LOOP OVER ALL EVENTS
    inT->GetEntry(jentry);//Get the Event From The TREE

    for (int i=0;i<theEvent->N;i++){ //Loop Over all Channel Firings in the Event
      //Fill Raw energy Histogram
      EnergiesRaw[theEvent->channels[i]]->Fill(theEvent->energies[i]);

      
      ///Fill Raw Energy Histograms for particlar Multiplicities
      EnergiesRawForN[theEvent->N-1][theEvent->channels[i]]->Fill(theEvent->energies[i]);
      
      if (theEvent->OverFlows[i] == false){
	//Fill Energies no OFs for particular Multiplicities
	EnergiesNoOFsForN[theEvent->N-1][theEvent->channels[i]]->Fill(theEvent->energies[i]);
	//Fill Raw No overflow histogram
	EnergiesNoOFs[theEvent->channels[i]]->Fill(theEvent->energies[i]);
	//Fill Corrected Energies 
	EnergiesCorrected[theEvent->channels[i]]->Fill(theEvent->energiesCor[i]);
	EnergiesCorrectedForN[theEvent->N-1][theEvent->channels[i]]->Fill(theEvent->energiesCor[i]);
	
	if (theEvent->channels[i] == 9 && theEvent->longGates[i]>0){ //Pulse Shape discrimination for the trigger
	  PulseShapeTrig->Fill(theEvent->longGates[i],theEvent->longGates[i]/theEvent->shortGates[i]);
	  LongVShortTrig->Fill(theEvent->shortGates[i],theEvent->longGates[i]);
	  
	  LongVShortTrigForN[theEvent->N-1]->Fill(theEvent->shortGates[i],theEvent->longGates[i]);
	  PulseShapeTrigForN[theEvent->N-1]->Fill(theEvent->longGates[i],theEvent->longGates[i]/theEvent->shortGates[i]);
	}
	if (theEvent->channels[i] == 8 && theEvent->longGates[i]>0){ //Pulse Shape discrimination for the reference
	  PulseShapeRef->Fill(theEvent->longGates[i],theEvent->longGates[i]/theEvent->shortGates[i]);
	  LongVShortRef->Fill(theEvent->shortGates[i],theEvent->longGates[i]);
	  
	  LongVShortRefForN[theEvent->N-1]->Fill(theEvent->shortGates[i],theEvent->longGates[i]);
	  PulseShapeRefForN[theEvent->N-1]->Fill(theEvent->longGates[i],theEvent->longGates[i]/theEvent->shortGates[i]);
	}
	if (theEvent->N == 2 && theEvent->channels[0]==8 && theEvent->channels[1]==9&&theEvent->channels[i]==8){
	  if (TMath::Abs(theEvent->times[0]-theEvent->times[1]) < 35 ){
	    test->Fill(theEvent->shortGates[i],theEvent->longGates[i]);
	  }
	}
      }
      ///Fill Raw Channels Histogram
      ChannelsRaw->Fill(theEvent->channels[i]);
      
      //Fill Channels Histogram with energy cut and remove OFs
      for (int a=0;a<ChannelsECut.size();a++){
	if (theEvent->energies[i]>(double(a)/ChannelsECut.size())*MaxEnergy && theEvent->OverFlows[i]==false){
	  ChannelsECut[a]->Fill(theEvent->channels[i]);
	}
      }
      //Fill channels for different multiplicities 
	ChannelsForN[theEvent->N-1]->Fill(theEvent->channels[i]);

    }//End Loop over Channels In Event
    
    //Fill total event histograms like TOF
    //For the Lenda bar in coincidence with the trigger
    if (theEvent->N==3 && theEvent->channels[0]==0 && theEvent->channels[1]==1 &&theEvent->channels[2]==9){
      TOF->Fill(theEvent->TOF);
      ShiftTOF->Fill(theEvent->ShiftTOF);
      TOFEnergy->Fill(theEvent->TOFEnergy);
      if (theEvent->longGates[2]>1200 && theEvent->longGates[2]/theEvent->shortGates[2]<1.14){
	TOFWithPS->Fill(theEvent->ShiftTOF);
	TOFPS->Fill(theEvent->TOF); // just ps no shift
	if (theEvent->ShiftTOF > 2.5 && theEvent->ShiftTOF<100){
	  TOFEnergyNeutrons->Fill(theEvent->TOFEnergy);
	  TOFEnergyCFBins->Fill(theEvent->TOFEnergy);
	  EvsTOFEnergy->Fill(theEvent->TOFEnergy,sqrt(theEvent->energies[0]*theEvent->energies[1]));
	  //loop over the different threshold options for lenda spectra
	  for (int a=0;a<LendaThreshs.size();a++){
	    if (TMath::Sqrt(theEvent->energies[0]*theEvent->energies[1])>threshVals[a]){
	      LendaThreshs[a]->Fill(theEvent->TOFEnergy);
	    }
	  }
	}
	if (theEvent->ShiftTOF < -2.5 && theEvent->ShiftTOF>-100){
	  TOFEnergyRandomBkg->Fill(theEvent->TOFEnergy);
	  TOFEnergyBkgCFBins->Fill(theEvent->TOFEnergy);
	  EvsTOFEnergyBkg->Fill(theEvent->TOFEnergy,sqrt(theEvent->energies[0]*theEvent->energies[1]));
	  //Loop over the different threshold option for lenda background spectra
	  for (int a=0;a<LendaThreshsBkg.size();a++){
	    if (TMath::Sqrt(theEvent->energies[0]*theEvent->energies[1])>threshVals[a]){
	      LendaThreshsBkg[a]->Fill(theEvent->TOFEnergy);
	    }
	  }
	}
      }
    }
    //for the reference in coincidence with the trigger
    if (theEvent->N==2 && theEvent->channels[0]==8 && theEvent->channels[1]==9){
      TOFL_L->Fill(theEvent->TOF);
      ShiftTOFL_L->Fill(theEvent->ShiftTOF);
      TOFEnergyL_L->Fill(theEvent->TOFEnergy);
      if (theEvent->longGates[1]>1200 && theEvent->longGates[1]/theEvent->shortGates[1]<1.14){
	TOFWithPSL_L->Fill(theEvent->ShiftTOF);
	TOFPSL_L->Fill(theEvent->TOF);
	
	
	if (theEvent->longGates[0]>2000 && theEvent->longGates[0]/theEvent->shortGates[0]>1.06){	
	  TOFWith2PSL_L->Fill(theEvent->ShiftTOF);
	  
	  if (theEvent->ShiftTOF > 2 && theEvent->ShiftTOF<35){
	    TOFEnergyNeutronsL_L->Fill(theEvent->TOFEnergy);

	  }
	  if (theEvent->ShiftTOF < -2 && theEvent->ShiftTOF>-35){
	    TOFEnergyRandomBkgL_L->Fill(theEvent->TOFEnergy);
	  }
	} //end if over second pusle shape discrimination	
	
	//Fill the histograms that have the specifed threhold cut in them
	if (theEvent->ShiftTOF > 2 && theEvent->ShiftTOF<35){
	  if ( theEvent->energies[0]>RefScintThresh){
	    TOFEnergyNeutrons1PSL_L->Fill(theEvent->TOFEnergy);
	    TOFEnergyCFBinsL_L->Fill(theEvent->TOFEnergy);
	    EvsTOFEnergyL_L->Fill(theEvent->TOFEnergy,theEvent->energies[0]);
	  }
	}
	  

      
	if (theEvent->ShiftTOF < -2 && theEvent->ShiftTOF>-35){
	  if ( theEvent->energies[0]>RefScintThresh){
	    TOFEnergyRandomBkg1PSL_L->Fill(theEvent->TOFEnergy);
	    TOFEnergyBkgCFBinsL_L->Fill(theEvent->TOFEnergy);
	    EvsTOFEnergyBkgL_L->Fill(theEvent->TOFEnergy,theEvent->energies[0]);
	  }
	}
      }
    }



    Multiplicity->Fill(theEvent->N);


    if ( jentry % 100000 == 0){
      cout<<"ON "<<jentry<<endl;
    }

  }//End Main Loop over Everything

  ///Do analysis on whole historgrams 
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  for (int i=1;i<=TOFEnergyNeutrons->GetXaxis()->GetNbins();i++){
    Float_t N = TOFEnergyNeutrons->GetBinContent(i);
    Float_t NRandom = TOFEnergyRandomBkg->GetBinContent(i);
    TOFEnergyRBkgSubtracted->SetBinContent(i,N-NRandom);
    TOFEnergyRBkgSubtracted->SetBinError(i,TMath::Sqrt(N+NRandom));


    Float_t NL_L =TOFEnergyNeutrons1PSL_L->GetBinContent(i);
    Float_t NRandomL_L=TOFEnergyRandomBkg1PSL_L->GetBinContent(i);
    TOFEnergyRBkgSubtracted1PSL_L->SetBinContent(i,NL_L-NRandomL_L);
    TOFEnergyRBkgSubtracted1PSL_L->SetBinError(i,TMath::Sqrt(NL_L+NRandomL_L));
  }
  
  //Spectra that have the CF BINNING
  for (int i=1;i<=TOFEnergySubCFBins->GetXaxis()->GetNbins();i++){
    Float_t N =TOFEnergyCFBins->GetBinContent(i);
    Float_t NRandom=TOFEnergyBkgCFBins->GetBinContent(i);
    TOFEnergySubCFBins->SetBinContent(i,N-NRandom);
    TOFEnergySubCFBins->SetBinError(i,TMath::Sqrt(N+NRandom));
    
    Float_t NL_L = TOFEnergyCFBinsL_L->GetBinContent(i);
    Float_t NRandomL_L=TOFEnergyBkgCFBinsL_L->GetBinContent(i);
    TOFEnergySubCFBinsL_L->SetBinContent(i,NL_L-NRandomL_L);
    TOFEnergySubCFBinsL_L->SetBinError(i,TMath::Sqrt(NL_L+NRandomL_L));
    
    for (int a=0;a<LendaThreshs.size();a++){
      Float_t thisN=LendaThreshs[a]->GetBinContent(i);
      Float_t thisNRandom=LendaThreshsBkg[a]->GetBinContent(i);
      LendaThreshsResult[a]->SetBinContent(i,thisN-thisNRandom);
      LendaThreshsResult[a]->SetBinError(i,sqrt(thisN+thisNRandom));
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Write all the histograms to file
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  for (int i=0;i<EnergiesNoOFsForN.size();i++){
    for (int j=0;j<EnergiesNoOFsForN[i].size();j++){
	EnergiesNoOFsForN[i][j]->Write();	
	EnergiesRawForN[i][j]->Write();
	EnergiesCorrectedForN[i][j]->Write();  
    }
  }

  for (int i=0;i<ChannelsForN.size();i++){
    ChannelsForN[i]->Write();
  }
  
  for (int i=0;i<EnergiesRaw.size();i++){
    EnergiesRaw[i]->Write();
    EnergiesNoOFs[i]->Write();
    EnergiesCorrected[i]->Write();
  }

  for (int i=0;i<ChannelsECut.size();i++){
    ChannelsECut[i]->Write();
  }

  for (int i=0;i<LongVShortTrigForN.size();i++){
    LongVShortTrigForN[i]->Write();
    PulseShapeTrigForN[i]->Write();
    LongVShortRefForN[i]->Write();
    PulseShapeRefForN[i]->Write();
  }

  ChannelsRaw->Write();

  Multiplicity->Write();
  test->Write();

  PulseShapeTrig->Write();
  LongVShortTrig->Write();
  PulseShapeRef->Write();
  LongVShortRef->Write();


  TOFEnergy->Write();
  TOFEnergyNeutrons->Write();
  ShiftTOF->Write();
  TOF->Write();
  TOFWithPS->Write();
  TOFEnergyRandomBkg->Write();
  TOFEnergyRBkgSubtracted->Write();
  TOFEnergyCFBins->Write();
  TOFEnergyBkgCFBins->Write();
  TOFEnergySubCFBins->Write();
  EvsTOFEnergy->Write();
  TOFPSL_L->Write();
  TOFPS->Write();
  EvsTOFEnergyBkg->Write();
  

  TOFEnergyL_L->Write();
  TOFEnergyNeutronsL_L->Write();
  ShiftTOFL_L->Write();
  TOFL_L->Write();
  TOFWithPSL_L->Write();
  TOFWith2PSL_L->Write();
  TOFEnergyRandomBkgL_L->Write();
  TOFEnergyRBkgSubtracted1PSL_L->Write();
  TOFEnergyCFBinsL_L->Write();
  TOFEnergyBkgCFBinsL_L->Write();
  TOFEnergySubCFBinsL_L->Write();
  TOFEnergyNeutrons1PSL_L->Write();
  TOFEnergyRandomBkg1PSL_L->Write();
  EvsTOFEnergyL_L->Write();
  EvsTOFEnergyBkgL_L->Write();


  for (int i=0;i<LendaThreshs.size();i++){
    LendaThreshs[i]->Write();
    LendaThreshsBkg[i]->Write();
    LendaThreshsResult[i]->Write();
    
  }
  
  /*  for (int i=0;i<ReferenceEnergiesScaled.size();i++){
    for (int j=0;j<ReferenceEnergiesScaled[i].size();j++){
      ReferenceEnergiesScaled[i][j]->Scale(20);
      //	ReferenceEnergiesScaled[i][j]->Write();
    }
  }
  for (int i=0;i<ThreshHoldVaryL_L.size();i++){
    // ThreshHoldVaryL_L[i]->Write();
    // ThreshHoldVaryBkgL_L[i]->Write();
    // ThreshHoldVaryResultL_L[i]->Write();

    }*/


  outFile->Close();
  
  cout<<"\n\n*****Finished******"<<endl;

  return 0;
}
Example #6
0
///
/// Make a plot out of a 1D histogram holding a 1-CL curve.
/// The strategy is to always convert the 1-CL histogram (hCL) into
/// a TGraph. This way we can add known points (solutions, points
/// at end of scan range) and also have a filled area without line
/// smoothing. This is not possible with histograms due to a Root bug.
///
/// The function draws the TGraphs, and returns a pointer to the
/// TGraph object that can be used in the TLegend.
///
/// Markers are plotted if the method name of the scanner is "Plugin" or "BergerBoos" or "DatasetsPlugin".
/// One can plot a line instead of points even for the Plugin method by
/// using setPluginMarkers().
///
/// For the angle variables, a new axis is painted that is in Deg.
///
/// \param s The scanner to plot.
/// \param first
/// \param last
/// \param filled
///
TGraph* OneMinusClPlot::scan1dPlot(MethodAbsScan* s, bool first, bool last, bool filled, int CLsType)
{
	if ( arg->debug ){
		cout << "OneMinusClPlot::scan1dPlot() : plotting ";
		cout << s->getName() << " (" << s->getMethodName() << ")" << endl;
	}
	if ( m_mainCanvas==0 ){
		m_mainCanvas = newNoWarnTCanvas(name+getUniqueRootName(), title, 800, 600);
	}
	m_mainCanvas->cd();
	bool plotPoints = ( s->getMethodName()=="Plugin" || s->getMethodName()=="BergerBoos" || s->getMethodName()=="DatasetsPlugin" ) && plotPluginMarkers;
	TH1F *hCL = (TH1F*)s->getHCL()->Clone(getUniqueRootName());
	if (CLsType==1) hCL = (TH1F*)s->getHCLs()->Clone(getUniqueRootName());
  else if (CLsType==2) hCL = (TH1F*)s->getHCLsFreq()->Clone(getUniqueRootName());
	// fix inf and nan entries
	for ( int i=1; i<=s->getHCL()->GetNbinsX(); i++ ){
		if ( s->getHCL()->GetBinContent(i)!=s->getHCL()->GetBinContent(i)
				|| std::isinf(s->getHCL()->GetBinContent(i)) ) s->getHCL()->SetBinContent(i, 0.0);
	}

	// remove errors the hard way, else root ALWAYS plots them
	if ( !plotPoints ) hCL = histHardCopy(hCL, true, true);

	// disable any statistics box
	hCL->SetStats(0);

	// Convert the histogram into a TGraph so we can add the solution.
	// Also, the lf2 drawing option is broken in latest root versions.
	TGraph *g;
	if ( plotPoints ) g = new TGraphErrors(hCL->GetNbinsX());
	else              g = new TGraph(hCL->GetNbinsX());
	g->SetName(getUniqueRootName());
	for ( int i=0; i<hCL->GetNbinsX(); i++ ){
		g->SetPoint(i, hCL->GetBinCenter(i+1), hCL->GetBinContent(i+1));
		if ( plotPoints ) ((TGraphErrors*)g)->SetPointError(i, 0.0, hCL->GetBinError(i+1));
	}

	// add solution
	if ( ! s->getSolutions().empty() ){
		TGraphTools t;
		TGraph *gNew = t.addPointToGraphAtFirstMatchingX(g, s->getScanVar1Solution(0), 1.0);
		delete g;
		g = gNew;
	}

	// // set last point to the same p-value as first point by hand
	// // some angle plots sometimes don't manage to do it by themselves...
	// if ( arg->isQuickhack(XX) )
	// {
	//   Double_t pointx0, pointy0, err0;
	//   Double_t pointx1, pointy1, err1;
	//   g->GetPoint(0, pointx0, pointy0);
	//   g->GetPoint(g->GetN()-1, pointx1, pointy1);
	//   g->SetPoint(g->GetN()-1, pointx1, pointy0);
	//   if ( plotPoints ) err0 = ((TGraphErrors*)g)->GetErrorY(0);
	//   if ( plotPoints ) ((TGraphErrors*)g)->SetPointError(g->GetN()-1, 0.0, err0);
	// }

	// add end points of scan range
	if ( !plotPoints )
	{
		Double_t pointx0, pointy0;
		TGraph *gNew = new TGraph(g->GetN()+4);
		gNew->SetName(getUniqueRootName());
		for ( int i=0; i<g->GetN(); i++)
		{
			g->GetPoint(i, pointx0, pointy0);
			gNew->SetPoint(i+2, pointx0, pointy0);
		}

		// add origin
		gNew->SetPoint(0, hCL->GetXaxis()->GetXmin(), 0);

		// add a point at first y height but at x=origin.
		g->GetPoint(0, pointx0, pointy0);
		gNew->SetPoint(1, hCL->GetXaxis()->GetXmin(), pointy0);

		// add a point at last y height but at x=xmax.
		g->GetPoint(g->GetN()-1, pointx0, pointy0);
		gNew->SetPoint(gNew->GetN()-2, hCL->GetXaxis()->GetXmax(), pointy0);

		// add a point at xmax, 0
		gNew->SetPoint(gNew->GetN()-1, hCL->GetXaxis()->GetXmax(), 0);
		g = gNew;
	}

	int color = s->getLineColor();
	if(CLsType>0 && s->getMethodName().Contains("Plugin") && !arg->plotpluginonly) {
    if (CLsType==1) color = kBlue-7;
    else if (CLsType==2) color = kBlue+2;
  }
	else if(CLsType>0) {
    if (CLsType==1) color = s->getLineColor() - 5;
    if (CLsType==2) color = s->getLineColor() - 4;
  }
	g->SetLineColor(color);

	if ( filled ){
		g->SetLineWidth(2);
    double alpha = arg->isQuickhack(12) ? 0.4 : 1.;
    if ( arg->isQuickhack(24) ) alpha = 0.;
		g->SetFillColorAlpha(color,alpha);
		g->SetLineStyle(1);
    g->SetFillStyle( s->getFillStyle() );
	}
	else{
		g->SetLineWidth(2);
		g->SetLineStyle(s->getLineStyle());
    if ( last && arg->isQuickhack(25) ) g->SetLineWidth(3);
	}

	if ( plotPoints ){
		g->SetLineWidth(1);
		g->SetMarkerColor(color);
		g->SetMarkerStyle(8);
		g->SetMarkerSize(0.6);
		if(CLsType==1) {
			g->SetMarkerStyle(33);
			g->SetMarkerSize(1);
		}
		if(CLsType==2) {
			g->SetMarkerStyle(21);
		}
	}

	// build a histogram which holds the axes
	float min = arg->scanrangeMin == arg->scanrangeMax ? hCL->GetXaxis()->GetXmin() : arg->scanrangeMin;
	float max = arg->scanrangeMin == arg->scanrangeMax ? hCL->GetXaxis()->GetXmax() : arg->scanrangeMax;
	TH1F *haxes = new TH1F("haxes"+getUniqueRootName(), "", 100, min, max);
	haxes->SetStats(0);
	haxes->GetXaxis()->SetTitle(s->getScanVar1()->GetTitle());
	haxes->GetYaxis()->SetTitle("1-CL");
	haxes->GetXaxis()->SetLabelFont(font);
	haxes->GetYaxis()->SetLabelFont(font);
	haxes->GetXaxis()->SetTitleFont(font);
	haxes->GetYaxis()->SetTitleFont(font);
	haxes->GetXaxis()->SetTitleOffset(0.9);
	haxes->GetYaxis()->SetTitleOffset(0.85);
	haxes->GetXaxis()->SetLabelSize(labelsize);
	haxes->GetYaxis()->SetLabelSize(labelsize);
	haxes->GetXaxis()->SetTitleSize(titlesize);
	haxes->GetYaxis()->SetTitleSize(titlesize);
	int xndiv = arg->ndiv==-1 ? 407 : abs(arg->ndiv);
	bool optimizeNdiv = arg->ndiv<0 ? true : false;
	haxes->GetXaxis()->SetNdivisions(xndiv, optimizeNdiv);
	haxes->GetYaxis()->SetNdivisions(407, true);

  // plot y range
  float plotYMax;
  float plotYMin;
  if ( plotLegend && !arg->isQuickhack(22) ) {
    if ( arg->plotlog ) { plotYMin = 1.e-3; plotYMax = 10.; }
    else                { plotYMin = 0.0  ; plotYMax = 1.3; }
  }
  else {
    if ( arg->plotlog ) { plotYMin = 1.e-3; plotYMax = 1.0; }
    else                { plotYMin = 0.0  ; plotYMax = 1.0; }
  }
  // change if passed as option
	plotYMin = arg->plotymin > 0. ? arg->plotymin : plotYMin;
  plotYMax = arg->plotymax > 0. ? arg->plotymax : plotYMax;

  haxes->GetYaxis()->SetRangeUser( plotYMin, plotYMax );
	haxes->Draw("axissame");
	g->SetHistogram(haxes);

	TString drawOption = "";
	if ( plotPoints )   drawOption += " pe";
	else if ( filled )  drawOption += " F";
	else                drawOption += " L";
	if ( first )        drawOption += " A";
	g->Draw(drawOption);
  //if ( drawOption.Contains("F") ) ((TGraph*)g->Clone())->Draw("L");

	gPad->Update();
	float ymin = gPad->GetUymin();
	float ymax = gPad->GetUymax();
	float xmin = gPad->GetUxmin();
	float xmax = gPad->GetUxmax();

	// for the angles, draw a new axis in units of degrees
	if ( isAngle(s->getScanVar1()) ){
		haxes->GetXaxis()->SetTitle(s->getScanVar1()->GetTitle() + TString(" [#circ]"));
		haxes->GetXaxis()->SetNdivisions(0);  // disable old axis
		if ( last ){
			// new top axis
			TString chopt = "-U"; // - = downward ticks, U = unlabeled, http://root.cern.ch/root/html534/TGaxis.html
			if ( !optimizeNdiv ) chopt += "N"; // n = no bin optimization
			TGaxis *axist = new TGaxis(xmin, 1, xmax, 1, RadToDeg(xmin), RadToDeg(xmax), xndiv, chopt);
			axist->SetName("axist");
			axist->Draw();

			// new bottom axis
			float axisbMin = RadToDeg(xmin);
			float axisbMax = RadToDeg(xmax);
			if ( arg->isQuickhack(3) ){ ///< see documentation of --qh option in OptParser.cpp
				axisbMin += 180.;
				axisbMax += 180.;
			}
			chopt = ""; // - = downward ticks, U = unlabeled, http://root.cern.ch/root/html534/TGaxis.html
			if ( !optimizeNdiv ) chopt += "N"; // n = no bin optimization
			TGaxis *axisb = new TGaxis(xmin, ymin, xmax, ymin, axisbMin, axisbMax, xndiv, chopt);
			axisb->SetName("axisb");
			axisb->SetLabelFont(font);
			axisb->SetLabelSize(labelsize);
			axisb->Draw();
		}
	}
	else
	{
		if ( last ){
			// add top axis
			TString chopt = "-U"; // - = downward ticks, U = unlabeled, http://root.cern.ch/root/html534/TGaxis.html
			if ( !optimizeNdiv ) chopt += "N"; // n = no bin optimization
			TGaxis *axist = new TGaxis(xmin, 1.0, xmax, 1.0, xmin, xmax, xndiv, chopt);
			axist->SetName("axist");
			axist->SetLineWidth(1);
			axist->Draw();
		}
	}

	if ( last )
	{
		// add right axis
		TGaxis *axisr = 0;
		if ( arg->plotlog ){
			float f3min = 1e-3;
			float f3max = (plotLegend && !arg->isQuickhack(22)) ? 10. : 1.;
			TF1 *f3 = new TF1("f3","log10(x)",f3min,f3max);
			axisr = new TGaxis(xmax, f3min, xmax, f3max, "f3", 510, "G+");
		}
		else{
			axisr = new TGaxis(xmax, ymin, xmax, ymax, 0, (plotLegend && !arg->isQuickhack(22)) ? 1.3 : 1.0, 407, "+");
		}
		axisr->SetLabelSize(0);
		axisr->SetLineWidth(1);
		axisr->SetName("axisr");
		axisr->SetLabelColor(kWhite);
		axisr->SetTitleColor(kWhite);
		axisr->Draw();

		// redraw right axis as well because the 1-CL graph can cover the old one
		haxes->Draw("axissame");
	}

	return g;
}
void GenerateInputFile_ge4b( double mgl=-1., double mlsp=-1., double target_susy_all0lep=-1. ) {

  TChain* dyTree = new TChain("treeZ") ;
  int nAdded = dyTree->Add("files15fb_8TeV_old1/DY.root") ;
  if ( nAdded <= 0 ) {
     printf("\n\n\n *** No treeZ in files15fb_8TeV_old1/DY.root\n\n\n") ;
     return ;
  }

  double t1bbbbWeight(0.) ;
  TChain chainT1bbbb("tree") ;
  char susycutstring[1000] ;
  sprintf( susycutstring, "&&mgluino==%.0f&&mlsp==%.0f", mgl, mlsp ) ;
  TString susycut( susycutstring ) ;
  if ( mgl>0. && mlsp>0. ) {
     nAdded = chainT1bbbb.Add("files5fb_MT/T1bbbb.root") ;
     if ( nAdded <= 0 ) {
        printf("\n\n\n *** No tree in files5fb_MT/T1bbbb.root\n\n\n") ;
        return ;
     }
     TFile f("referenceXSecs.root") ;
     TH1F* xsechist = (TH1F*) f.Get("gluino8TeV_NLONLL") ;
     if ( xsechist==0x0 ) { printf("\n\n *** can't find reference Xsec histogram in referenceXSecs.root.\n\n") ; return ; }
     int theBin = xsechist->FindBin( mgl ) ;
     if ( theBin <=0 || theBin > xsechist->GetNbinsX() ) {
        printf("\n\n *** can't find bin for mgl=%g.  Returned %d\n\n", mgl, theBin ) ;
        return ;
     }
     double xsec = xsechist->GetBinContent( theBin ) ;
     printf("\n\n T1bbbb xsec for mgl=%g is %g\n\n", mgl, xsec ) ;
     t1bbbbWeight = 1.5*xsec ;  //in pb. scan has 10k events, so nScan*1.5*xsec = events in 15fb-1
     //////  t1bbbbWeight = 0.1*xsec ;  //in pb. T1tttt scan has 50k events, so nScan*0.1*xsec = events in 5fb-1
     printf("\n\n Susy ttree cut: %s\n\n", susycutstring ) ;
  }


  TChain chainQCD("tree") ;
   //--- these have high weight
//chainQCD.Add("files15fb_8TeV/QCD-50to80.root");
//chainQCD.Add("files15fb_8TeV/QCD-80to120.root");
  chainQCD.Add("files15fb_8TeV/QCD-120to170.root");
  chainQCD.Add("files15fb_8TeV/QCD-170to300.root");
   //--- below here, these have weight less than one.
  chainQCD.Add("files15fb_8TeV/QCD-300to470.root");
  chainQCD.Add("files15fb_8TeV/QCD-470to600.root");
  chainQCD.Add("files15fb_8TeV/QCD-600to800.root");
  chainQCD.Add("files15fb_8TeV/QCD-800to1000.root");
  chainQCD.Add("files15fb_8TeV/QCD-1000to1400.root");
  chainQCD.Add("files15fb_8TeV/QCD-1400to1800.root");
  chainQCD.Add("files15fb_8TeV/QCD-1800.root");

  TChain chainTT("tree") ;
  chainTT.Add("files15fb_8TeV/TT.root") ;

  TChain chainZnn("tree") ;
  chainZnn.Add("files15fb_8TeV/Zinv-100to200.root") ;
  chainZnn.Add("files15fb_8TeV/Zinv-200to400.root") ;
  chainZnn.Add("files15fb_8TeV/Zinv-400.root") ;

  TChain chainWJets("tree") ;
  chainWJets.Add("files15fb_8TeV/WJets-250to300.root") ;
  chainWJets.Add("files15fb_8TeV/WJets-300to400.root") ;
  chainWJets.Add("files15fb_8TeV/WJets-400.root") ;
  chainWJets.Add("files15fb_8TeV/T-s.root") ;
  chainWJets.Add("files15fb_8TeV/T-t.root") ;
  chainWJets.Add("files15fb_8TeV/T-tW.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-s.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-t.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-tW.root") ;



      char qcdinputfile[9][1000] = {
        "files15fb_8TeV/QCD-120to170.root"
       ,"files15fb_8TeV/QCD-170to300.root"
       ,"files15fb_8TeV/QCD-300to470.root"
       ,"files15fb_8TeV/QCD-470to600.root"
       ,"files15fb_8TeV/QCD-600to800.root"
       ,"files15fb_8TeV/QCD-800to1000.root"
       ,"files15fb_8TeV/QCD-1000to1400.root"
       ,"files15fb_8TeV/QCD-1400to1800.root"
       ,"files15fb_8TeV/QCD-1800.root"
      } ;

      char qcdsamplename[9][100] = {
        "qcd_0120_to_0170"
       ,"qcd_0170_to_0300"
       ,"qcd_0300_to_0470"
       ,"qcd_0470_to_0600"
       ,"qcd_0600_to_0800"
       ,"qcd_0800_to_1000"
       ,"qcd_1000_to_1400"
       ,"qcd_1400_to_1800"
       ,"qcd_1800_to_9999"
      } ;



  gROOT->Reset();

  const int nBinsBjets = 4 ;
  const int nJetsCut = 3 ;     // #jets >= nJetsCut

//be careful because this is hard coded now in SmallTree::Loop
  double minLeadJetPt = 70. ;
  double min3rdJetPt = 50. ;
  
  bool doPUreweighting = false;

  //-- met2-ht1-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 1 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,99999.};

//-- met2-ht2-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};

////-- met2-ht8-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

  //-- met3-ht2-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,800.,99999.};

////-- met3-ht3-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met3-ht3-v5
//    const int nBinsMET = 3 ;
//    const int nBinsHT  = 3 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = { 125, 200,  350, 99999. } ;
//    float Hbins[nBinsHT+1]  = { 400, 600, 1000, 99999. } ;

////-- met3-ht3-v2
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

////-- met3-ht4-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

////-- met3-ht5-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met4-ht3-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met4-ht3-v2
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

  //-- met5-ht4-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

////-- met4-ht4-v1
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 1;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v2
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 2;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v3
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 3;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v4
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 4;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v5
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = {150.,175.,200.,400.,99999.};
//    float Hbins[nBinsHT+1] = {400.,450.,550.,850.,99999.};

  //-- met4-ht4-v6
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 6;
//    float Mbins[nBinsMET+1] = {150.,200.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,550.,800.,950.,99999.};

////-- met4-ht4-v7
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 4 ;
//    const int version = 7;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

  //-- met4-ht4-v15
      const int nBinsMET   = 4 ;
      const int nBinsHT    = 4 ;
      const int version = 15;
      float Mbins[nBinsMET+1] = {125.,150.,250.,350.,99999.};
      float Hbins[nBinsHT+1] = {400.,500.,800.,1000.,99999.};

////-- met4-ht5-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,300.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,1200.,99999.};

////-- met5-ht5-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met5-ht3-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met5-ht3-v2
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,175.,200.,350.,450.,99999.};
//float Hbins[nBinsHT+1] = {400.,550.,800.,99999.};

  //-- met6-ht6-v1
//const int nBinsMET   = 6 ;
//const int nBinsHT    = 6 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,99999.};

  //-- met7-ht7-v1
//const int nBinsMET   = 7 ;
//const int nBinsHT    = 7 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,99999.};

////-- met8-ht8-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

////-- met8-ht2-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};



  TString sMbins[nBinsMET];
  TString sHbins[nBinsHT];
  TString sBbins[nBinsBjets] = {"_1b","_2b","_3b","_4b"};

  TString cMbins[nBinsMET];
  TString cHbins[nBinsHT];

  for (int i = 0 ; i < nBinsMET ; i++) {
    TString base = "_M";
    stringstream sbin;
    sbin << i+1;
    base += sbin.str();
    sMbins[i] = base;
    base = "&&MET>";
    stringstream cbin;
    cbin << Mbins[i] << "&&MET<" << Mbins[i+1];
    base += cbin.str();
    cMbins[i] = base;
  }

  for (int j = 0 ; j < nBinsHT ; j++) {
    TString base = "_H";
    stringstream sbin;
    sbin << j+1;
    base += sbin.str();
    sHbins[j] = base;
    base = "&&HT>";
    stringstream cbin;
    cbin << Hbins[j] << "&&HT<" << Hbins[j+1];
    base += cbin.str();
    cHbins[j] = base;
  }

  TString leadJetPtCutString ;
  {
     leadJetPtCutString = "(pt_1st_leadJet>" ;
     stringstream number ;
     number << minLeadJetPt ;
     stringstream number2 ;
     number2 << min3rdJetPt ;
     leadJetPtCutString += number.str() ;
     leadJetPtCutString += "&&pt_2nd_leadJet>" ;
     leadJetPtCutString += number.str() ;
     leadJetPtCutString += "&&pt_3rd_leadJet>" ;
     leadJetPtCutString += number2.str() ;
     leadJetPtCutString += ")" ;
  }

//int dummyInt = 99;
//float dummyFloat = 9.999;
  float dummyZero = 0.;
  float dummyOne = 1.0;
  float dummyPoint999 = 0.999 ;
  float dummyErr = 0.1;

  float sl_frac2b_val[nBinsMET][nBinsHT];
  float sl_frac2b_err[nBinsMET][nBinsHT];
  float sl_frac3b_val[nBinsMET][nBinsHT];
  float sl_frac3b_err[nBinsMET][nBinsHT];
  float sl_frac4b_val[nBinsMET][nBinsHT];
  float sl_frac4b_err[nBinsMET][nBinsHT];


  ofstream inFile;
  char outfile[10000] ;
  if ( mgl > 0. && mlsp > 0. ) {
     if ( target_susy_all0lep > 0. ) {
        sprintf( outfile, "InputWT1bbbb-nb4-mgl%.0f-mlsp%.0f-%.0fevts-met%d-ht%d-v%d.dat", mgl, mlsp, target_susy_all0lep, nBinsMET, nBinsHT, version  ) ;
     } else {
        sprintf( outfile, "InputWT1bbbb-nb4-mgl%.0f-mlsp%.0f-met%d-ht%d-v%d.dat", mgl, mlsp, nBinsMET, nBinsHT, version  ) ;
     }
  } else {
     sprintf( outfile, "Input-nb4-met%d-ht%d-v%d.dat", nBinsMET, nBinsHT, version  ) ;
  }
  inFile.open( outfile );

  // print out header line:

  inFile << "Using HT bins:  " ;
  for (int j = 0 ; j <= nBinsHT ; j++ ) {
    inFile << Hbins[j] ;
    if ( j < nBinsHT ) inFile << "-" ;
  }

  inFile << "\t Using MET bins: " ;
  for (int i = 0 ; i <= nBinsMET ; i++ ) {
    inFile << Mbins[i] ;
    if ( i < nBinsMET ) inFile << "-" ;
  }
  
  inFile << endl ;


   int nSel(3) ;
   char selname[3][100] = { "0lep", "1lep", "ldp" } ;

   char selcuts[3][10000] = {
        "minDelPhiN>4&&nMu==0&&nEl==0&&",
        "minDelPhiN>4&&( (nMu==1&&nEl==0) || (nMu==0&&nEl==1) )&&",
        "minDelPhiN<4&&nMu==0&&nEl==0&&" } ;


  //--- Output histograms.

   TH1F* hmctruth_susy [3][4] ;
   TH1F* hmctruth_ttwj [3][4] ;
   TH1F* hmctruth_ttbar[3][4] ;
   TH1F* hmctruth_wjets[3][4] ;
   TH1F* hmctruth_qcd  [3][4] ;
   TH1F* hmctruth_znn  [3][4] ;
   TH1F* hmctruth_allsm[3][4] ;
   TH1F* hmctruth_all  [3][4] ;

   for ( int si=0; si<nSel; si++ ) {
      for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

         char hname[1000] ;
         char htitle[1000] ;
         sprintf( htitle, "%s, %d btag", selname[si], bbi+1 ) ;

         sprintf( hname, "hmctruth_susy_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_susy[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_ttwj_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_ttwj[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_ttbar_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_ttbar[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_wjets_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_wjets[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_qcd_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_qcd[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_znn_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_znn[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_allsm_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_allsm[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_all_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_all[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;


      } // bbi.
   } // si.




     TH1F* hmctruth_fit_zee_1b  = bookHist("hmctruth_fit_zee_1b" , "Zee" , "Zee", 1, nBinsMET, nBinsHT ) ;
     TH1F* hmctruth_fit_zmm_1b  = bookHist("hmctruth_fit_zmm_1b" , "Zmm" , "Zmm", 1, nBinsMET, nBinsHT ) ;






  //--- histograms used in getting the observables.

    TH2F* h_tt[10] ;
    TH2F* h_wjets[10] ;
    TH2F* h_qcd[10] ;
    TH2F* h_znn[10] ;
    TH2F* h_susy[10] ;
    TH2F* h_mc[10] ;

    for ( int bi=0; bi<nBinsBjets; bi++ ) {

       char hname[100] ;

       sprintf( hname, "h_tt_%db", bi+1 ) ;
       h_tt[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_tt[bi] -> Sumw2() ;

       sprintf( hname, "h_wjets_%db", bi+1 ) ;
       h_wjets[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_wjets[bi] -> Sumw2() ;

       sprintf( hname, "h_qcd_%db", bi+1 ) ;
       h_qcd[bi]  = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_qcd[bi] -> Sumw2() ;

       sprintf( hname, "h_znn_%db", bi+1 ) ;
       h_znn[bi]  = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_znn[bi] -> Sumw2() ;

       sprintf( hname, "h_susy_%db", bi+1 ) ;
       h_susy[bi] = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_susy[bi] -> Sumw2() ;

       sprintf( hname, "h_mc_%db", bi+1 ) ;
       h_mc[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_mc[bi] -> Sumw2() ;

    }

  float nSusyTotal = 0;

  for ( int si=0 ; si<nSel ; si++ ) {


  printf("\n\n-----------------------------------------------------------------\n\n") ;

      for (int k = 0 ; k < nBinsBjets ; k++) {

        char allcuts[10000] ;
        char allsusycuts[10000] ;

        if ( k < (nBinsBjets-1) ) {
          sprintf( allcuts, "%snB==%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
          sprintf( allsusycuts, "%snB==%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)%s", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt, susycut.Data() ) ;
        } else {
          sprintf( allcuts, "%snB>=%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
          sprintf( allsusycuts, "%snB>=%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)%s", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt, susycut.Data() ) ;
        }


        printf("\n\n N_%s -- nbjet bin (%d): cuts=%s\n\n", selname[si], k, allcuts) ; cout << flush ;

        char hname[100] ;
        sprintf( hname, "h_tt_%db", k+1 ) ;
        if(doPUreweighting) FillHTMET(&chainTT, h_tt[k], si, k);
	else chainTT.Project (hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_tt[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_wjets_%db", k+1 ) ;
        if(doPUreweighting) FillHTMET(&chainWJets, h_wjets[k], si, k);
	else chainWJets.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_wjets[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_qcd_%db", k+1 ) ;
        if (doPUreweighting) FillHTMET(&chainQCD, h_qcd[k], si, k);
	else chainQCD.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_qcd[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_znn_%db", k+1 ) ;
        if (doPUreweighting) FillHTMET(&chainZnn, h_znn[k], si, k);
	else chainZnn.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_znn[k]->Integral() ) ; cout << flush ;
        if ( mgl > 0. ) {
           sprintf( hname, "h_susy_%db", k+1 ) ;
           chainT1bbbb.Project(hname,"HT:MET",allsusycuts);
           h_susy[k]->Scale( t1bbbbWeight ) ;
           printf("    %12s %9.1f events\n", hname, h_susy[k]->Integral() ) ; cout << flush ;
	   if (si==0) nSusyTotal += h_susy[k]->Integral();
        }
      } // k
      if (si==0) printf("N_Susy_Total = %9.1f events", nSusyTotal); cout << flush;
      printf("\n\n") ;


      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {


             char obsname[1000] ;
             sprintf( obsname, "N_%s_M%d_H%d_%db", selname[si], i+1, j+1, k+1 ) ;


             double ttval = h_tt[k] -> GetBinContent( i+1, j+1 ) ;
             double tterr = h_tt[k] -> GetBinError(   i+1, j+1 ) ;

             double wjetsval = h_wjets[k] -> GetBinContent( i+1, j+1 ) ;
             double wjetserr = h_wjets[k] -> GetBinError(   i+1, j+1 ) ;

             double qcdval = h_qcd[k] -> GetBinContent( i+1, j+1 ) ;
             double qcderr = h_qcd[k] -> GetBinError(   i+1, j+1 ) ;

             double znnval = h_znn[k] -> GetBinContent( i+1, j+1 ) ;
             double znnerr = h_znn[k] -> GetBinError(   i+1, j+1 ) ;

             double susyval = h_susy[k] -> GetBinContent( i+1, j+1 ) ;
             double susyerr = h_susy[k] -> GetBinError(   i+1, j+1 ) ;

             printf(" N_%s, tt     met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, ttval,tterr) ; cout << flush ;
             printf(" N_%s, wjets  met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, wjetsval,wjetserr) ; cout << flush ;
             printf(" N_%s, qcd    met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, qcdval,qcderr) ; cout << flush ;
             printf(" N_%s, znn    met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, znnval,znnerr) ; cout << flush ;
             if ( mgl>0. ) {
                if ( target_susy_all0lep > 0. ) {
                   susyval = susyval * (target_susy_all0lep/nSusyTotal);
                   susyerr = susyerr * (target_susy_all0lep/nSusyTotal);
                }
                printf(" N_%s, susy   met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, susyval,susyerr) ; cout << flush ;
             }
             printf("\n") ;

             double allval = ttval + wjetsval + qcdval + znnval + susyval ;

             //// inFile << obsname << "  \t" << (int)allval << endl;
             inFile << obsname << "  \t" << allval << endl;

             int histbin = 1 + (nBinsHT+1)*i + j + 1 ;

             hmctruth_ttwj[si][k]  -> SetBinContent( histbin, ttval + wjetsval  ) ;
             hmctruth_ttwj[si][k]  -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) )  ) ;
             hmctruth_ttbar[si][k] -> SetBinContent( histbin, ttval ) ;
             hmctruth_ttbar[si][k] -> SetBinError(   histbin, tterr ) ;
             hmctruth_wjets[si][k] -> SetBinContent( histbin, wjetsval  ) ;
             hmctruth_wjets[si][k] -> SetBinError(   histbin, wjetserr  ) ;
             hmctruth_qcd[si][k]   -> SetBinContent( histbin, qcdval ) ;
             hmctruth_qcd[si][k]   -> SetBinError(   histbin, qcderr ) ;
             hmctruth_znn[si][k]   -> SetBinContent( histbin, znnval ) ;
             hmctruth_znn[si][k]   -> SetBinError(   histbin, znnerr ) ;
             hmctruth_susy[si][k]  -> SetBinContent( histbin, susyval  ) ;
             hmctruth_susy[si][k]  -> SetBinError(   histbin, susyerr  ) ;
             hmctruth_allsm[si][k] -> SetBinContent( histbin, ttval+wjetsval+qcdval+znnval ) ;
             hmctruth_allsm[si][k] -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) + pow(qcderr,2) + pow(znnerr,2) ) ) ;
             hmctruth_all[si][k]   -> SetBinContent( histbin, ttval+wjetsval+qcdval+znnval+susyval ) ;
             hmctruth_all[si][k]   -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) + pow(qcderr,2) + pow(znnerr,2) + pow(susyerr,2) ) ) ;


	     // compute fractions of SL 2b/1b and 3b/1b

	     if ( si == 1 && k > 0 ) {

	       double ttval_1b = h_tt[0] -> GetBinContent( i+1, j+1 ) ;
	       double wjetsval_1b = h_wjets[0] -> GetBinContent( i+1, j+1 ) ;

	       double ttwjval = ttval + wjetsval ;
	       double ttwjval_1b = ttval_1b + wjetsval_1b ;

	       if ( k == 1 ) {
		 sl_frac2b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac2b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	       if ( k == 2 ) {
		 sl_frac3b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac3b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	       if ( k == 3 ) {
		 sl_frac4b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac4b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	     }

            } // k
          } // j
        } // i



          for (int k = 0 ; k < nBinsBjets ; k++) {
             h_tt[k] -> Reset() ;
             h_wjets[k] -> Reset() ;
             h_qcd[k] -> Reset() ;
             h_znn[k] -> Reset() ;
             h_susy[k] -> Reset() ;
          }


     } // si.




     //--- Insert dummy R_lsb lines for backwards compatibility.
     for ( int hbi=0; hbi<nBinsHT; hbi++ ) {
        for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {
           char dummyline[1000] ;
           sprintf( dummyline, "R_lsb_H%d_%db       0.1", hbi+1, bbi+1 ) ;
           inFile << dummyline << endl ;
           sprintf( dummyline, "R_lsb_H%d_%db_err   0.01", hbi+1, bbi+1 ) ;
           inFile << dummyline << endl ;
        } // bbi.
     } // hbi.





    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;

    { //--- scoping bracket for QCD chunk.

    //--- Fill histograms to be used in QCD analysis (done in mcclosure4.c).

      const int nQcdSamples(9) ;

      TCanvas* cqcd = new TCanvas("cqcd","QCD") ;

      TH2F*   h0lep[nQcdSamples][nBinsBjets] ;
      TH2F*   hldp [nQcdSamples][nBinsBjets] ;

      TChain* qcdch[nQcdSamples] ;

      char hname[1000] ;
      char htitle[1000] ;

      TH2F* hdummy = new TH2F("hdummy","",2, Mbins[0], 1500., 2, Hbins[0], 1500. ) ;

         printf("\n\n") ;
         for ( int si=0; si<nQcdSamples; si++ ) {

            qcdch[si] = new TChain("tree") ;
            printf(" %2d : connecting to %s\n", si, qcdinputfile[si] ) ;
            qcdch[si] -> Add( qcdinputfile[si] ) ;

            for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

               sprintf( hname, "h_0lep_%db_%s", bbi+1, qcdsamplename[si] ) ;
               sprintf( htitle, "QCD 0lep yield, nb=%d, %s", bbi+1, qcdsamplename[si] ) ;
               printf("         booking hist %s : %s\n", hname, htitle ) ;
               h0lep[si][bbi] = new TH2F( hname, htitle, nBinsMET, Mbins, nBinsHT, Hbins ) ;
               h0lep[si][bbi] -> Sumw2() ;
               sprintf( hname, "h_ldp_%db_%s", bbi+1, qcdsamplename[si] ) ;
               sprintf( htitle, "QCD  LDP yield, nb=%d, %s", bbi+1, qcdsamplename[si] ) ;
               printf("         booking hist %s  : %s\n", hname, htitle ) ;
               hldp [si][bbi] = new TH2F( hname, htitle, nBinsMET, Mbins, nBinsHT, Hbins ) ;
               hldp [si][bbi] -> Sumw2() ;

            } // bbi.

         } // si.
         printf("\n\n") ;


         char bcut[4][100] = { "nB==1", "nB==2", "nB==3", "nB>=4" } ;

         for ( int si=0; si<nQcdSamples; si++ ) {

            printf(" %2d : %s : 0lep\n", si, qcdsamplename[si] ) ; cout << flush ;
            for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

               char arg1[1000] ;

               char cuts0lep[10000] ;
               sprintf( cuts0lep, "%s(%s)&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[0], bcut[bbi], nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
               printf("     %db, 0lep cuts : %s\n", bbi+1, cuts0lep ) ;
               sprintf( arg1, "HT:MET>>h_0lep_%db_%s", bbi+1, qcdsamplename[si] ) ;
               qcdch[si] -> Draw( arg1, cuts0lep ) ;
               hdummy->Draw() ;
               h0lep[si][bbi]->Draw("samecolz") ;
               cqcd->Update() ; cqcd->Draw() ;


               char cutsldp[10000] ;
               sprintf( cutsldp, "%s(%s)&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[2], bcut[bbi], nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
               printf("     %db, ldp  cuts : %s\n", bbi+1, cutsldp  ) ;
               sprintf( arg1, "HT:MET>>h_ldp_%db_%s", bbi+1, qcdsamplename[si] ) ;
               qcdch[si] -> Draw( arg1, cutsldp, "colz" ) ;
               hdummy->Draw() ;
               hldp[si][bbi]->Draw("samecolz") ;
               cqcd->Update() ; cqcd->Draw() ;

            } // bbi.

         } // si.

    } //--- scoping bracket for QCD chunk.

    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // Z -> ee observables 
  
    TH1F* ht = new TH1F("ht","ht",10,0,10000);
  
    ht -> Sumw2() ;

    TString cutszee = "cat==2&&minDelPhiNee>4&&nVLB>=1&&nJets>=";
    stringstream njcut ; njcut << nJetsCut ;
    cutszee += njcut.str();
    cutszee += "&&";

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
  
        TString obs_Zee = "N_Zee" ;
        obs_Zee = obs_Zee+sMbins[i]+sHbins[j] ;
        
        TString cut = "HT>";  
        cut += Hbins[j];
        cut += "&&HT<";
        cut += Hbins[j+1];
        cut += "&&METee>";
        cut += Mbins[i];
        cut += "&&METee<";
        cut += Mbins[i+1];
  
        TString allcutsZ = cutszee+cut ;
        allcutsZ += "&&" ;
        allcutsZ += leadJetPtCutString ;
  
        dyTree->Project("ht","HT",allcutsZ);
        double allerr(0.) ;
        double allval = ht->IntegralAndError(1,10,allerr) ;
        printf(" N_Zee -- HT,MET bins (%d,%d): events=%7.1f +/- %6.1f, cuts=%s\n", j,i,allval,allerr,allcutsZ.Data() ) ; cout << flush ;
          ht->Reset() ;
  
        ////// inFile << obs_Zee << "  \t" << (int)allval << endl;
        inFile << obs_Zee << "  \t" << allval << endl;

        //Z->ee counts, with 1 VLb and sig selection, so so MET>250, HT>400, mindelphi>4, 2e, 0mu, nJets >= 3
  
        int histbin = 1 + (nBinsHT+1)*i + j + 1 ;
  
        hmctruth_fit_zee_1b -> SetBinContent( histbin, allval ) ;
        hmctruth_fit_zee_1b -> SetBinError(   histbin, allerr ) ;
  
      }
    }
  
    
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // Z -> mm observables
  
    TString cutszmm = "cat==1&&minDelPhiNmm>4&&nVLB>=1&&nJets>=";
    cutszmm += njcut.str();
    cutszmm += "&&";

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
  
        TString obs_Zmm = "N_Zmm" ;
        obs_Zmm = obs_Zmm+sMbins[i]+sHbins[j] ;
        
        TString cut = "HT>";  
        cut += Hbins[j];
        cut += "&&HT<";
        cut += Hbins[j+1];
        cut += "&&METmm>";
        cut += Mbins[i];
        cut += "&&METmm<";
        cut += Mbins[i+1];
        
        TString allcutsZ = cutszmm+cut ;
        allcutsZ += "&&" ;
        allcutsZ += leadJetPtCutString ;
  
        dyTree->Project("ht","HT",allcutsZ);
        double allerr(0.) ;
        double allval = ht->IntegralAndError(1,10,allerr) ;
        printf(" N_Zmm -- HT,MET bins (%d,%d): events=%7.1f +/- %6.1f, cuts=%s\n", j,i,allval,allerr,allcutsZ.Data() ) ; cout << flush ;
          ht->Reset() ;
  
        ////// inFile << obs_Zmm << "  \t" << (int)allval << endl;
        inFile << obs_Zmm << "  \t" << allval << endl;

        //Z->mm counts, with 1 VLb and sig selection, so so MET>250, HT>400, mindelphi>4, 2mu, 0e, nJets >= 3
  
        int histbin = 1 + (nBinsHT+1)*i + j + 1 ;
  
        hmctruth_fit_zmm_1b -> SetBinContent( histbin, allval ) ;
        hmctruth_fit_zmm_1b -> SetBinError(   histbin, allerr ) ;
  
  
      }
    }
  
    //inFile << "Why are all three of these MC categories separate? I've just put them together (only QCD, Zinv, tt)" << endl;
    // Nttbarsingletopzjetsmc_ldp
  
  
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;

    //--- Owen : these MC inputs are no longer used.  Insert dummy values for backwards compatibility in format.

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {

           char obsname[1000] ;
           sprintf( obsname, "N_ttbarsingletopzjetsmc_ldp_M%d_H%d_%db", i+1, j+1, k+1 ) ;

           double val, err ;
           val = 0. ;
           err = 0. ;

           printf(" %s : %7.1f +/- %7.1f\n", obsname, val, err ) ;

           inFile << obsname << "  \t" << val << endl ;

        }
        printf("\n") ;
      }
      printf("\n") ;
    }

    // NWJmc_ldp
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString obs_WJmc_ldp = "N_WJmc_ldp" ;
  	obs_WJmc_ldp = obs_WJmc_ldp+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << obs_WJmc_ldp << "  \t" << dummyZero << endl;
  // signal selection, but ldp, so MET>250, HT>400, >=1 b, mindelphi<4, 0L, nJets >= 3
        }
      }
    }
  
  
    // NZnnmc_ldp
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString obs_Znnmc_ldp = "N_Znnmc_ldp" ;
  	obs_Znnmc_ldp = obs_Znnmc_ldp+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << obs_Znnmc_ldp << "  \t" << dummyZero << endl;
  // signal selection, but ldp, so MET>250, HT>400, >=1 b, mindelphi<4, 0L, nJets >= 3
        }
      }
    }
  
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // various parameters needed for Z -> invis.
  
    // Z -> ee acceptance
  
    for (int i = 0 ; i < nBinsMET ; i++) {
  
      TString Zee_acc = "acc_Zee";
      Zee_acc = Zee_acc+sMbins[i];
  
      inFile << Zee_acc << "  \t" << dummyPoint999 << endl;
  
      Zee_acc = Zee_acc+"_err";
      inFile << Zee_acc << "  \t" << dummyErr << endl;
  
    }
  
  
    // Z -> mm acceptance
  
    for (int i = 0 ; i < nBinsMET ; i++) {
  
      TString Zmm_acc = "acc_Zmm";
      Zmm_acc = Zmm_acc+sMbins[i];
  
      inFile << Zmm_acc << "  \t" << dummyPoint999 << endl;
  
      Zmm_acc = Zmm_acc+"_err";
      inFile << Zmm_acc << "  \t" << dummyErr << endl;
  
    }
  
  
    // Z -> ll efficiencies
  
  // use 2011 values for now.
    inFile << "Z_ee_eff  \t" << 0.6774 << endl;
    inFile << "Z_ee_eff_err  \t" << 0.0580 << endl;
    inFile << "Z_mm_eff  \t" << 0.7217 << endl;
    inFile << "Z_mm_eff_err  \t" << 0.0506 << endl;
  
  
    // Z -> ee VL to nominal scale factors
  // would it make more sense to count events in only the loosest HT and/or MET bin and
  // use the scale factors to translate between the different HT and MET bins?

   //    for (int k = 0 ; k < nBinsBjets ; k++) {
   //    TString knn_ee = "knn_ee" ;
   //    knn_ee = knn_ee+sBbins[k] ;
   //    inFile << knn_ee << "  \t" << dummyOne << endl;
   //    knn_ee = knn_ee+"_err" ;
   //    inFile << knn_ee << "  \t" << dummyErr << endl;
   //  }
   //
   //
   //  // use 2011 values for now.
   //  inFile << "knn_1b     \t" << 0.401 << endl;
   //  inFile << "knn_1b_err \t" << 0.018 << endl;
   //  inFile << "knn_2b     \t" << 0.067 << endl;
   //  inFile << "knn_2b_err \t" << 0.009 << endl;
   //  inFile << "knn_3b     \t" << 0.009 << endl;
   //  inFile << "knn_3b_err \t" << 0.003 << endl;
   //

    // updated SF's to improve MC closure (the errors are the same as before)
    inFile << "knn_1b     \t" << 0.394  << endl;
    inFile << "knn_1b_err \t" << 0.018  << endl;
    inFile << "knn_2b     \t" << 0.0626 << endl;
    inFile << "knn_2b_err \t" << 0.009  << endl;
    inFile << "knn_3b     \t" << 0.0036 << endl;
    inFile << "knn_3b_err \t" << 0.003  << endl;
    inFile << "knn_4b     \t" << 0.00011 << endl;
    inFile << "knn_4b_err \t" << 0.00011  << endl;

    // Z -> ll purity
  
    // use 2011 values for now.
    inFile << "Z_ee_pur  \t" << 0.911 << endl;
    inFile << "Z_ee_pur_err  \t" << 0.079 << endl;
    inFile << "Z_mm_pur  \t" << 0.866 << endl;
    inFile << "Z_mm_pur_err  \t" << 0.079 << endl;
  
  
    // scale factors:
  
    inFile << "sf_mc  \t" << dummyOne << endl ; 
    inFile << "sf_mc_err  \t" << dummyErr << endl; 
  
  
    // sf_qcd
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString sf_qcd = "sf_qcd" ;
  	sf_qcd = sf_qcd+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << sf_qcd << "  \t" << dummyOne << endl;	
  
  	sf_qcd = sf_qcd+"_err" ;
  	inFile << sf_qcd << "  \t" << dummyErr << endl;	
  
        }
      }
    }
  
  
    // sf_ttwj
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString sf_ttwj = "sf_ttwj" ;
  	sf_ttwj = sf_ttwj+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << sf_ttwj << "  \t" << dummyOne << endl;	
  
  	sf_ttwj = sf_ttwj+"_err" ;
  	inFile << sf_ttwj << "  \t" << dummyErr << endl;	
  
        }
      }
    }
  
  
    // sf_ee
  
    for (int k = 0 ; k < nBinsBjets ; k++) {
  
      TString sf_ee = "sf_ee" ;
      sf_ee = sf_ee+sBbins[k] ;
  
      inFile << sf_ee << "  \t" << dummyOne << endl;
      
      sf_ee = sf_ee+"_err" ;
      inFile << sf_ee << "  \t" << dummyErr << endl;
  
    }
  
  
    // sf_mm
  
    for (int k = 0 ; k < nBinsBjets ; k++) {
  
      TString sf_mm = "sf_mm" ;
      sf_mm = sf_mm+sBbins[k] ;
  
      inFile << sf_mm << "  \t" << dummyOne << endl;
      
      sf_mm = sf_mm+"_err" ;
      inFile << sf_mm << "  \t" << dummyErr << endl;
  
    }


    // btag eff err (Note: this was missing until Aug 3, 2012, but it's apparently not used.)
    inFile << "btageff_err" << " \t" << dummyErr << endl ;



    //--- Addding ttwj and znn LDP/ZL MC values

    //--- ttwj MC LDP/ZL

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {
        int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;
        for (int bbi = 0 ; bbi < nBinsBjets ; bbi++) {

            float ldpval = hmctruth_ttwj[2][bbi] -> GetBinContent( hbin ) ;
            float ldperr = hmctruth_ttwj[2][bbi] -> GetBinError(   hbin ) ;
            float zlval  = hmctruth_ttwj[0][bbi] -> GetBinContent( hbin ) ;
            float zlerr  = hmctruth_ttwj[0][bbi] -> GetBinError(   hbin ) ;

            float ldpoverzl = 0. ;
            float ldpoverzlerr = 0. ;

            if ( zlval > 0. && ldpval > 0. ) {
               ldpoverzl = ldpval / zlval ;
               ldpoverzlerr = ldpoverzl * sqrt( pow((zlerr/zlval),2) + pow((ldperr/ldpval),2) ) ;
            }

            char parname[1000] ;

            sprintf( parname, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_%db", mbi+1, hbi+1, bbi+1 ) ;
            printf(" %s  :  %6.3f +/- %5.3f\n", parname, ldpoverzl, ldpoverzlerr ) ;
            inFile << parname << "  \t" << ldpoverzl << endl;

            sprintf( parname, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_%db_err", mbi+1, hbi+1, bbi+1 ) ;
            inFile << parname << "  \t" << ldpoverzlerr << endl;

        } // bbi
      } // hbi
    } // mbi


    //--- Znn MC LDP/ZL
    //--- Note: the 2b and >=3b MC stats are too low.  Use 1b values for all 3.

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {
        int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

        float ldpval = hmctruth_znn[2][0] -> GetBinContent( hbin ) ;
        float ldperr = hmctruth_znn[2][0] -> GetBinError(   hbin ) ;
        float zlval  = hmctruth_znn[0][0] -> GetBinContent( hbin ) ;
        float zlerr  = hmctruth_znn[0][0] -> GetBinError(   hbin ) ;

        float ldpoverzl = 0. ;
        float ldpoverzlerr = 0. ;

        if ( zlval > 0. && ldpval > 0. ) {
           ldpoverzl = ldpval / zlval ;
           ldpoverzlerr = ldpoverzl * sqrt( pow((zlerr/zlval),2) + pow((ldperr/ldpval),2) ) ;
        }

        char parname[1000] ;

        for (int bbi = 0 ; bbi < nBinsBjets ; bbi++) {
            sprintf( parname, "znn_mc_ldpover0lep_ratio_M%d_H%d_%db", mbi+1, hbi+1, bbi+1 ) ;
            printf(" %s  :  %6.3f +/- %5.3f\n", parname, ldpoverzl, ldpoverzlerr ) ;
            inFile << parname << "  \t" << ldpoverzl << endl;

            sprintf( parname, "znn_mc_ldpover0lep_ratio_M%d_H%d_%db_err", mbi+1, hbi+1, bbi+1 ) ;
            inFile << parname << "  \t" << ldpoverzlerr << endl;
        } // bbi
      } // hbi
    } // mbi


    // add here the fractions (bin by bin) of 2b/1b and 3b/1b SL events (just for the MC for now)

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {

	TString Sl2bstring     = "sl_frac_2b_val";
	TString Sl2bstring_err = "sl_frac_2b_err";
	TString Sl3bstring     = "sl_frac_3b_val";
	TString Sl3bstring_err = "sl_frac_3b_err";
	TString Sl4bstring     = "sl_frac_4b_val";
	TString Sl4bstring_err = "sl_frac_4b_err";

	Sl2bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl2bstring_err += sMbins[mbi]+sHbins[hbi] ;
	Sl3bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl3bstring_err += sMbins[mbi]+sHbins[hbi] ;
	Sl4bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl4bstring_err += sMbins[mbi]+sHbins[hbi] ;

	inFile << Sl2bstring     << "   \t" << sl_frac2b_val[mbi][hbi] << endl ;
	inFile << Sl2bstring_err << "   \t" << sl_frac2b_err[mbi][hbi] << endl ;
	inFile << Sl3bstring     << "   \t" << sl_frac3b_val[mbi][hbi] << endl ;
	inFile << Sl3bstring_err << "   \t" << sl_frac3b_err[mbi][hbi] << endl ;
	inFile << Sl4bstring     << "   \t" << sl_frac4b_val[mbi][hbi] << endl ;
	inFile << Sl4bstring_err << "   \t" << sl_frac4b_err[mbi][hbi] << endl ;

      }
    }




    gSystem->Exec("mkdir -p rootfiles") ;
    char outHistName[1000] ;
    if ( mgl>0. && mlsp>0. ) {
       if ( target_susy_all0lep > 0 ) {
          sprintf( outHistName, "rootfiles/gi-plots-nb4-wsusy-mgl%.0f-mlsp%.0f-%.0fevts-met%d-ht%d-v%d.root", mgl, mlsp, target_susy_all0lep, nBinsMET, nBinsHT, version ) ;
       } else {
          sprintf( outHistName, "rootfiles/gi-plots-nb4-wsusy-mgl%.0f-mlsp%.0f-met%d-ht%d-v%d.root", mgl, mlsp, nBinsMET, nBinsHT, version ) ;
       }
    } else {
       sprintf( outHistName, "rootfiles/gi-plots-nb4-met%d-ht%d-v%d.root", nBinsMET, nBinsHT, version ) ;
    }
    saveHist( outHistName, "h*" ) ;


    inFile.close();
    return;
  
  }
int Plot_tauPt_Stage1_DD() {

  double totalMC =0.0;
  double lumi= 35.865; //20.011 ;  // B->5.882  // C->2.646   D->4.353 ;  // E->4.049 ; F->3.16 ;  G->7.554;  H->5.942  //--inv fb--//

  unsigned long long evt_DYJetsToLL_M50=1;
  unsigned long long evt_DYJetsToLL_M5to50=1;
  unsigned long long evt_TT=1;
 
  TFile *file_DYJetsToLL_M50  = new TFile("../python/crab_projects_March3/crab_DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");             
  double xs_DYJetsToLL_M50=4895000;  //--fb--//                                                                                                                    

  TFile *file_DYJetsToLL_M5to50  = new TFile("../python/crab_projects_March3/crab_DYJetsToLL_M-10to50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");    
  double xs_DYJetsToLL_M5to50=7160000;  //--fb--//                                                                                                                    

  TFile *file_TT              = new TFile("../python/crab_projects_March3/crab_TT_TuneCUETP8M2T4_13TeV-powheg-pythia8/results/hist.root");
  double xs_TT=730000; //--fb--//
  double kfact_TT= 1.139;

  TFile *file_TT_Mtt_700to1000      = new TFile("../python/crab_projects_March3/crab_TT_Mtt-700to1000_TuneCUETP8M1_13TeV-powheg-pythia8/results/hist.root");
  double xs_TT_Mtt_700to1000=730000; //--fb--//
  double kfact_TT_Mtt_700to1000= 0.0921;

  TFile *file_TT_Mtt_1000toInf              = new TFile("../python/crab_projects_March3/crab_TT_Mtt-1000toInf_TuneCUETP8M1_13TeV-powheg-pythia8/results/hist.root");
  double xs_TT_Mtt_1000toInf=730000; //--fb--//
  double kfact_TT_Mtt_1000toInf= 0.02474;


  //TFile *file_WJetsToLNu      = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/results/hist.root");
  //double xs_WJetsToLNu=60290000; //--fb--//

  TFile *file_WJetsToLNu      = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu= 50690000; //--fb--//
  //
  TFile *file_WToTauNu_M100  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-100_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M100 = 165000; //--fb--//
  double kfact_WToTauNu_M100 = 1.0 ; 
  //
  TFile *file_WToTauNu_M200  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-200_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M200 = 6370; //--fb--//
  double kfact_WToTauNu_M200 = 1.0 ; 
  //
  TFile *file_WToTauNu_M500  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-500_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M500 = 224.0; //--fb--//
  double kfact_WToTauNu_M500 = 1.0 ; 
  //
  TFile *file_WToTauNu_M1000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-1000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M1000 = 13.7; //--fb--//
  double kfact_WToTauNu_M1000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M2000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-2000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M2000 = 0.437; //--fb--//
  double kfact_WToTauNu_M2000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M3000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-3000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M3000 = 0.0342; //--fb--//
  double kfact_WToTauNu_M3000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M4000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-4000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M4000 = 0.00292; //--fb--//
  double kfact_WToTauNu_M4000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M5000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-5000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M5000 = 0.000233; //--fb--//
  double kfact_WToTauNu_M5000 = 1.0 ; 
  //
  TFile *file_WToTauNu_M6000  = new TFile("../python/crab_projects_March3/crab_WToTauNu_M-6000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_WToTauNu_M6000 = 0.000015; //--fb--//
  double kfact_WToTauNu_M6000 = 1.0 ; 
  //
  TFile *file_WJetsToLNu_HT100To200  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-100To200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT100To200 = 1345000 ; //--fb--//
  double kfact_WJetsToLNu_HT100To200 = 1.0 ; 

  TFile *file_WJetsToLNu_HT200To400  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-200To400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT200To400 = 359700 ; //--fb--//
  double kfact_WJetsToLNu_HT200To400 = 1.0 ;

  TFile *file_WJetsToLNu_HT400To600  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT400To600 = 48910 ; //--fb--//
  double kfact_WJetsToLNu_HT400To600 = 1.0 ;

  TFile *file_WJetsToLNu_HT600To800  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-600To800_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT600To800 = 12050 ; //--fb--//
  double kfact_WJetsToLNu_HT600To800 = 1.0 ;

  TFile *file_WJetsToLNu_HT800To1200  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT800To1200 = 5501 ; //--fb--//
  double kfact_WJetsToLNu_HT800To1200 = 1.0 ;

  TFile *file_WJetsToLNu_HT1200To2500  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-1200To2500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT1200To2500 = 1329 ; //--fb--//
  double kfact_WJetsToLNu_HT1200To2500 = 1.0 ;

  TFile *file_WJetsToLNu_HT2500ToInf  = new TFile("../python/crab_projects_March3/crab_WJetsToLNu_HT-2500ToInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/results/hist.root");
  double xs_WJetsToLNu_HT2500ToInf = 32.16  ; //--fb--//
  double kfact_WJetsToLNu_HT2500ToInf = 1.0 ;

  TFile *file_ST_tchannel_antitop=new TFile("../python/crab_projects_March3/crab_ST_t-channel_antitop_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV-powhegV2-madspin/results/hist.root");
  double xs_ST_tchannel_antitop = 80950; //--fb--//
  double kfact_ST_tchannel_antitop = 1.0; //0.326;
  //
  TFile *file_ST_tchannel_top=new TFile("../python/crab_projects_March3/crab_ST_t-channel_top_4f_inclusiveDecays_TuneCUETP8M2T4_13TeV-powhegV2-madspin/results/hist.root");
  double xs_ST_tchannel_top =136020; //103200; //--fb--//
  double kfact_ST_tchannel_top = 1.0; //0.43;
  //
  TFile *file_ST_tW_antitop=new TFile("../python/crab_projects_March3/crab_ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M2T4/results/hist.root");
  double xs_ST_tW_antitop = 38090; //--fb--//
  double kfact_ST_tW_antitop =1.0; // 0.94;
  //
  TFile *file_ST_tW_top=new TFile("../python/crab_projects_March3/crab_ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M2T4/results/hist.root");
  double xs_ST_tW_top = 38090; //--fb--//
  double kfact_ST_tW_top = 1.0; //0.94;
  //
  TFile *file_WW=new TFile("../python/crab_projects_March3/crab_WW_TuneCUETP8M1_13TeV-pythia8/results/hist.root");
  double xs_WW = 63210; //--fb--//
  //
  TFile *file_WZ=new TFile("../python/crab_projects_March3/crab_WZ_TuneCUETP8M1_13TeV-pythia8/results/hist.root");
  double xs_WZ = 22820; //--fb--//
  double kfact_WZ = 2.06; // 47.13/22.82
  //
  TFile *file_ZZ=new TFile("../python/crab_projects_March3/crab_ZZ_TuneCUETP8M1_13TeV-pythia8/results/hist.root");
  double xs_ZZ = 10320; //--fb--//
  double kfact_ZZ = 1.60 ; //16523/10320
  //
  std::cout << "get datadriven root file" << std::endl;
  TFile *file_Datadriven  = new TFile("/net/scratch_cms3a/materok/wprime/qcd/dataDrivenTree15_pt_base_Mar7_fromData.root");


  /// DATA ///
  TFile *file_Tau_Run2016B = new TFile("../python/crab_projects_March3/crab_Tau_Run2016B/results/hist.root");
  TFile *file_Tau_Run2016C = new TFile("../python/crab_projects_March3/crab_Tau_Run2016C/results/hist.root");
  TFile *file_Tau_Run2016D = new TFile("../python/crab_projects_March3/crab_Tau_Run2016D/results/hist.root");
  TFile *file_Tau_Run2016E = new TFile("../python/crab_projects_March3/crab_Tau_Run2016E/results/hist.root");
  TFile *file_Tau_Run2016F = new TFile("../python/crab_projects_March3/crab_Tau_Run2016F/results/hist.root");
  TFile *file_Tau_Run2016G = new TFile("../python/crab_projects_March3/crab_Tau_Run2016G/results/hist.root");
  TFile *file_Tau_Run2016H_v2 = new TFile("../python/crab_projects_March3/crab_Tau_Run2016H_1/results/hist.root");
  TFile *file_Tau_Run2016H_v3 = new TFile("../python/crab_projects_March3/crab_Tau_Run2016H_2/results/hist.root");


  /// Signal ///
  TFile *file_Wprime_M4000 = new TFile("../python/crab_projects_March3/crab_WprimeToTauNu_M-4000_TuneCUETP8M1_13TeV-pythia8-tauola/results/hist.root");
  double xs_Wprime_M4000= 2.04; // --fb-- //

  //--//
  TH1D* h1_evt_DYJetsToLL_M50 = (TH1D*)file_DYJetsToLL_M50->Get("demo/histoDir/eventCount");
  evt_DYJetsToLL_M50 = h1_evt_DYJetsToLL_M50->GetEntries(); // Integral();
  double wt_DYJetsToLL_M50 = (xs_DYJetsToLL_M50*lumi)/evt_DYJetsToLL_M50 ;
  TH1D* tauPt_Stage1_DYJetsToLL_M50 = (TH1D*)file_DYJetsToLL_M50->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_DYJetsToLL_M50->Scale(wt_DYJetsToLL_M50);
  std::cout << "DYJetsToLL_M50 weighted nevt=" << tauPt_Stage1_DYJetsToLL_M50->Integral() << std::endl;
  totalMC += tauPt_Stage1_DYJetsToLL_M50->Integral();

  TH1D* h1_evt_DYJetsToLL_M5to50 = (TH1D*)file_DYJetsToLL_M5to50->Get("demo/histoDir/eventCount");
  evt_DYJetsToLL_M5to50 = h1_evt_DYJetsToLL_M5to50->GetEntries(); // Integral();
  double wt_DYJetsToLL_M5to50 = (xs_DYJetsToLL_M5to50*lumi)/evt_DYJetsToLL_M5to50 ;
  TH1D* tauPt_Stage1_DYJetsToLL_M5to50 = (TH1D*)file_DYJetsToLL_M5to50->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_DYJetsToLL_M5to50->Scale(wt_DYJetsToLL_M5to50);
  std::cout << "DYJetsToLL_M5to50 weighted nevt=" << tauPt_Stage1_DYJetsToLL_M5to50->Integral() << std::endl;
  totalMC += tauPt_Stage1_DYJetsToLL_M5to50->Integral() ;
  //
  TH1D* total_DY = (TH1D*)tauPt_Stage1_DYJetsToLL_M50->Clone(); 
  total_DY->Add(tauPt_Stage1_DYJetsToLL_M5to50);
  total_DY->SetFillColorAlpha(kRed,0.5);
  total_DY->SetLineColor(kBlack);
  total_DY->Rebin(10);
  //

  TH1D* h1_evt_TT = (TH1D*)file_TT->Get("demo/histoDir/eventCount");
  evt_TT = h1_evt_TT->GetEntries(); // Integral();
  double wt_TT = (xs_TT*lumi)/evt_TT ;
  TH1D* tauPt_Stage1_TT  = (TH1D*)file_TT->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_TT->Scale(wt_TT);
  tauPt_Stage1_TT->Scale(kfact_TT);
  std::cout << "TTbar weighted nevt=" << tauPt_Stage1_TT->Integral() << std::endl;
  totalMC += tauPt_Stage1_TT->Integral();

  //file_TT_Mtt_700to1000
  TH1D* h1_evt_TT_Mtt_700to1000 = (TH1D*)file_TT_Mtt_700to1000->Get("demo/histoDir/eventCount");
  evt_TT_Mtt_700to1000 = h1_evt_TT_Mtt_700to1000->GetEntries(); // Integral();
  double wt_TT_Mtt_700to1000 = (xs_TT_Mtt_700to1000*lumi)/evt_TT_Mtt_700to1000 ;
  TH1D* tauPt_Stage1_TT_Mtt_700to1000  = (TH1D*)file_TT_Mtt_700to1000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_TT_Mtt_700to1000->Scale(wt_TT_Mtt_700to1000);
  tauPt_Stage1_TT_Mtt_700to1000->Scale(kfact_TT_Mtt_700to1000);
  std::cout << "TT_Mtt_700to1000bar weighted nevt=" << tauPt_Stage1_TT_Mtt_700to1000->Integral() << std::endl;
  totalMC += tauPt_Stage1_TT_Mtt_700to1000->Integral() ;

  //file_TT_Mtt_1000toInf
  TH1D* h1_evt_TT_Mtt_1000toInf = (TH1D*)file_TT_Mtt_1000toInf->Get("demo/histoDir/eventCount");
  evt_TT_Mtt_1000toInf = h1_evt_TT_Mtt_1000toInf->GetEntries(); // Integral();
  double wt_TT_Mtt_1000toInf = (xs_TT_Mtt_1000toInf*lumi)/evt_TT_Mtt_1000toInf ;
  TH1D* tauPt_Stage1_TT_Mtt_1000toInf  = (TH1D*)file_TT_Mtt_1000toInf->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_TT_Mtt_1000toInf->Scale(wt_TT_Mtt_1000toInf);
  tauPt_Stage1_TT_Mtt_1000toInf->Scale(kfact_TT_Mtt_1000toInf);
  std::cout << "TT_Mtt_1000toInfbar weighted nevt=" << tauPt_Stage1_TT_Mtt_1000toInf->Integral() << std::endl;
  totalMC += tauPt_Stage1_TT_Mtt_1000toInf->Integral() ;

  TH1D* total_TT = (TH1D*)tauPt_Stage1_TT->Clone(); 
  total_TT->Add(tauPt_Stage1_TT_Mtt_700to1000);
  total_TT->Add(tauPt_Stage1_TT_Mtt_1000toInf);
  total_TT->SetFillColor(kBlue-7);
  total_TT->SetLineColor(kBlack);
  total_TT->Rebin(10);


  /*
  TH1D* h1_evt_WJetsToLNu = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/eventCount");
  evt_WJetsToLNu = h1_evt_WJetsToLNu->GetEntries(); //Integral();
  std::cout << "evt_WJetsToLNu = " << evt_WJetsToLNu << std::endl;
  double wt_WJetsToLNu = (xs_WJetsToLNu*lumi)/evt_WJetsToLNu ;
  TH1D* tauPt_Stage1_WJetsToLNu  = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  tauPt_Stage1_WJetsToLNu->Sumw2(kFALSE);
  tauPt_Stage1_WJetsToLNu->SetBinErrorOption(TH1::kPoisson);
  std::cout << "**WJets** unweighted nevt=" << tauPt_Stage1_WJetsToLNu->Integral() << std::endl;
  std::cout << "wt_WJetsToLNu = " << wt_WJetsToLNu << std::endl;
  tauPt_Stage1_WJetsToLNu->Scale(wt_WJetsToLNu);
  tauPt_Stage1_WJetsToLNu->SetFillColorAlpha(kGreen-7,0.5);
  tauPt_Stage1_WJetsToLNu->SetLineColor(kGreen-7);
  tauPt_Stage1_WJetsToLNu->Rebin(40);
  std::cout << "**WJets** weighted nevt=" << tauPt_Stage1_WJetsToLNu->Integral() << std::endl;
  */

  //file_ST_tchannel_antitop
  TH1D* h1_evt_ST_tchannel_antitop = (TH1D*)file_ST_tchannel_antitop->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tchannel_antitop = h1_evt_ST_tchannel_antitop->GetEntries(); //Integral();
  double wt_ST_tchannel_antitop = (xs_ST_tchannel_antitop*lumi)/evt_ST_tchannel_antitop ;
  TH1D* tauPt_Stage1_ST_tchannel_antitop  = (TH1D*)file_ST_tchannel_antitop->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tchannel_antitop->Scale(wt_ST_tchannel_antitop);
  tauPt_Stage1_ST_tchannel_antitop->Scale(kfact_ST_tchannel_antitop);
  std::cout << "ST_tchannel_antitop weighted nevt=" << tauPt_Stage1_ST_tchannel_antitop->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tchannel_antitop->Integral();

  //file_ST_tchannel_top
  TH1D* h1_evt_ST_tchannel_top = (TH1D*)file_ST_tchannel_top->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tchannel_top = h1_evt_ST_tchannel_top->GetEntries(); //Integral();
  double wt_ST_tchannel_top = (xs_ST_tchannel_top*lumi)/evt_ST_tchannel_top ;
  TH1D* tauPt_Stage1_ST_tchannel_top  = (TH1D*)file_ST_tchannel_top->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tchannel_top->Scale(wt_ST_tchannel_top);
  tauPt_Stage1_ST_tchannel_top->Scale(kfact_ST_tchannel_top);
  std::cout << "ST_tchannel_top weighted nevt=" << tauPt_Stage1_ST_tchannel_top->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tchannel_top->Integral() ;

  //file_ST_tW_antitop
  TH1D* h1_evt_ST_tW_antitop = (TH1D*)file_ST_tW_antitop->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tW_antitop = h1_evt_ST_tW_antitop->GetEntries(); //Integral();
  double wt_ST_tW_antitop = (xs_ST_tW_antitop*lumi)/evt_ST_tW_antitop ;
  TH1D* tauPt_Stage1_ST_tW_antitop  = (TH1D*)file_ST_tW_antitop->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tW_antitop->Scale(wt_ST_tW_antitop);
  tauPt_Stage1_ST_tW_antitop->Scale(kfact_ST_tW_antitop);
  std::cout << "ST_tW_antitop weighted nevt=" << tauPt_Stage1_ST_tW_antitop->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tW_antitop->Integral();

  //file_ST_tW_top
  TH1D* h1_evt_ST_tW_top = (TH1D*)file_ST_tW_top->Get("demo/histoDir/eventCount");
  unsigned long long evt_ST_tW_top = h1_evt_ST_tW_top->GetEntries(); //Integral();
  double wt_ST_tW_top = (xs_ST_tW_top*lumi)/evt_ST_tW_top ;
  TH1D* tauPt_Stage1_ST_tW_top  = (TH1D*)file_ST_tW_top->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_ST_tW_top->Scale(wt_ST_tW_top);
  tauPt_Stage1_ST_tW_top->Scale(kfact_ST_tW_top);
  std::cout << "ST_tW_top weighted nevt=" << tauPt_Stage1_ST_tW_top->Integral() << std::endl;
  totalMC += tauPt_Stage1_ST_tW_top->Integral() ;

  TH1D* total_ST = (TH1D*)tauPt_Stage1_ST_tchannel_antitop->Clone(); 
  total_ST->Add(tauPt_Stage1_ST_tchannel_top);
  total_ST->Add(tauPt_Stage1_ST_tW_antitop);
  total_ST->Add(tauPt_Stage1_ST_tW_top);
  total_ST->SetFillColorAlpha(kCyan,0.5);
  total_ST->SetLineColor(kBlack);
  total_ST->Rebin(10);

  //file_WJetsToLNu_HT100To200
  TH1D* h1_evt_WJetsToLNu_HT100To200 = (TH1D*)file_WJetsToLNu_HT100To200->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT100To200 = h1_evt_WJetsToLNu_HT100To200->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT100To200 = (xs_WJetsToLNu_HT100To200*lumi)/evt_WJetsToLNu_HT100To200 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT100To200  = (TH1D*)file_WJetsToLNu_HT100To200->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                           
  //  tauPt_Stage1_WJetsToLNu_HT100To200->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT100To200->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT100To200->Scale(wt_WJetsToLNu_HT100To200);
  std::cout << "WJetsToLNu_HT100To200 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT100To200->Integral() << std::endl;
  totalMC += tauPt_Stage1_WJetsToLNu_HT100To200->Integral();
  //tauPt_Stage1_WJetsToLNu_HT100To200->Scale(kfact_WJetsToLNu_HT100To200);
  //  std::cout << tauPt_Stage1_WJetsToLNu_HT100To200->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT200To400
  TH1D* h1_evt_WJetsToLNu_HT200To400 = (TH1D*)file_WJetsToLNu_HT200To400->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT200To400 = h1_evt_WJetsToLNu_HT200To400->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT200To400 = (xs_WJetsToLNu_HT200To400*lumi)/evt_WJetsToLNu_HT200To400 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT200To400  = (TH1D*)file_WJetsToLNu_HT200To400->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT200To400->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT200To400->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT200To400->Scale(wt_WJetsToLNu_HT200To400);
 std::cout << "WJetsToLNu_HT200To400 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT200To400->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT200To400->Integral();
  //tauPt_Stage1_WJetsToLNu_HT200To400->Scale(kfact_WJetsToLNu_HT200To400);
  //std::cout << tauPt_Stage1_WJetsToLNu_HT200To400->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT400To600
  TH1D* h1_evt_WJetsToLNu_HT400To600 = (TH1D*)file_WJetsToLNu_HT400To600->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT400To600 = h1_evt_WJetsToLNu_HT400To600->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT400To600 = (xs_WJetsToLNu_HT400To600*lumi)/evt_WJetsToLNu_HT400To600 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT400To600  = (TH1D*)file_WJetsToLNu_HT400To600->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT400To600->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT400To600->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT400To600->Scale(wt_WJetsToLNu_HT400To600);
  std::cout << "WJetsToLNu_HT400To600 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT400To600->Integral() << std::endl;
  totalMC += tauPt_Stage1_WJetsToLNu_HT400To600->Integral();
  // tauPt_Stage1_WJetsToLNu_HT400To600->Scale(kfact_WJetsToLNu_HT400To600);
  // std::cout << tauPt_Stage1_WJetsToLNu_HT400To600->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT600To800
  TH1D* h1_evt_WJetsToLNu_HT600To800 = (TH1D*)file_WJetsToLNu_HT600To800->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT600To800 = h1_evt_WJetsToLNu_HT600To800->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT600To800 = (xs_WJetsToLNu_HT600To800*lumi)/evt_WJetsToLNu_HT600To800 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT600To800  = (TH1D*)file_WJetsToLNu_HT600To800->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  //  tauPt_Stage1_WJetsToLNu_HT600To800->Sumw2(kFALSE);
  // tauPt_Stage1_WJetsToLNu_HT600To800->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT600To800->Scale(wt_WJetsToLNu_HT600To800);
  std::cout << "WJetsToLNu_HT600To800 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT600To800->Integral() << std::endl;
  totalMC +=  tauPt_Stage1_WJetsToLNu_HT600To800->Integral();
  // tauPt_Stage1_WJetsToLNu_HT600To800->Scale(kfact_WJetsToLNu_HT600To800);
  // std::cout << tauPt_Stage1_WJetsToLNu_HT600To800->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT800To1200
  TH1D* h1_evt_WJetsToLNu_HT800To1200 = (TH1D*)file_WJetsToLNu_HT800To1200->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT800To1200 = h1_evt_WJetsToLNu_HT800To1200->GetEntries(); //Integral();                                                                 
  double wt_WJetsToLNu_HT800To1200 = (xs_WJetsToLNu_HT800To1200*lumi)/evt_WJetsToLNu_HT800To1200 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT800To1200  = (TH1D*)file_WJetsToLNu_HT800To1200->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT800To1200->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT800To1200->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT800To1200->Scale(wt_WJetsToLNu_HT800To1200);
 std::cout << "WJetsToLNu_HT800To1200 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT800To1200->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT800To1200->Integral();
  //tauPt_Stage1_WJetsToLNu_HT800To1200->Scale(kfact_WJetsToLNu_HT800To1200);
  // std::cout << tauPt_Stage1_WJetsToLNu_HT800To1200->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT1200To2500
  TH1D* h1_evt_WJetsToLNu_HT1200To2500 = (TH1D*)file_WJetsToLNu_HT1200To2500->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT1200To2500 = h1_evt_WJetsToLNu_HT1200To2500->GetEntries(); //Integral();                                                             
  double wt_WJetsToLNu_HT1200To2500 = (xs_WJetsToLNu_HT1200To2500*lumi)/evt_WJetsToLNu_HT1200To2500 ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT1200To2500  = (TH1D*)file_WJetsToLNu_HT1200To2500->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  // tauPt_Stage1_WJetsToLNu_HT1200To2500->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT1200To2500->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT1200To2500->Scale(wt_WJetsToLNu_HT1200To2500);
 std::cout << "WJetsToLNu_HT1200To2500 weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT1200To2500->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT1200To2500->Integral();
  // tauPt_Stage1_WJetsToLNu_HT1200To2500->Scale(kfact_WJetsToLNu_HT1200To2500);
  //std::cout << tauPt_Stage1_WJetsToLNu_HT1200To2500->GetBinError(300) << std::endl;

  //file_WJetsToLNu_HT2500ToInf
  TH1D* h1_evt_WJetsToLNu_HT2500ToInf = (TH1D*)file_WJetsToLNu_HT2500ToInf->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu_HT2500ToInf = h1_evt_WJetsToLNu_HT2500ToInf->GetEntries(); //Integral();                                                             
  double wt_WJetsToLNu_HT2500ToInf = (xs_WJetsToLNu_HT2500ToInf*lumi)/evt_WJetsToLNu_HT2500ToInf ;
  TH1D* tauPt_Stage1_WJetsToLNu_HT2500ToInf  = (TH1D*)file_WJetsToLNu_HT2500ToInf->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //                                                                                                                                                      
  //tauPt_Stage1_WJetsToLNu_HT2500ToInf->Sumw2(kFALSE);
  //tauPt_Stage1_WJetsToLNu_HT2500ToInf->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WJetsToLNu_HT2500ToInf->Scale(wt_WJetsToLNu_HT2500ToInf);
 std::cout << "WJetsToLNu_HT2500ToInf weighted nevt=" << tauPt_Stage1_WJetsToLNu_HT2500ToInf->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu_HT2500ToInf->Integral();
  //tauPt_Stage1_WJetsToLNu_HT2500ToInf->Scale(kfact_WJetsToLNu_HT2500ToInf);
  ///std::cout << tauPt_Stage1_WJetsToLNu_HT2500ToInf->GetBinError(300) << std::endl;

  //file_WToTauNu_M100
  TH1D* h1_evt_WToTauNu_M100 = (TH1D*)file_WToTauNu_M100->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M100 = h1_evt_WToTauNu_M100->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M100 = (xs_WToTauNu_M100*lumi)/evt_WToTauNu_M100 ;
  TH1D* tauPt_Stage1_WToTauNu_M100  = (TH1D*)file_WToTauNu_M100->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M100->Scale(wt_WToTauNu_M100);
 std::cout << "WToTauNu_M100 weighted nevt=" << tauPt_Stage1_WToTauNu_M100->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M100->Integral() ;

  //file_WToTauNu_M200
  TH1D* h1_evt_WToTauNu_M200 = (TH1D*)file_WToTauNu_M200->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M200 = h1_evt_WToTauNu_M200->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M200 = (xs_WToTauNu_M200*lumi)/evt_WToTauNu_M200 ;
  TH1D* tauPt_Stage1_WToTauNu_M200  = (TH1D*)file_WToTauNu_M200->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M200->Scale(wt_WToTauNu_M200);
 std::cout << "WToTauNu_M200 weighted nevt=" << tauPt_Stage1_WToTauNu_M200->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M200->Integral();

  //file_WToTauNu_M500
  TH1D* h1_evt_WToTauNu_M500 = (TH1D*)file_WToTauNu_M500->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M500 = h1_evt_WToTauNu_M500->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M500 = (xs_WToTauNu_M500*lumi)/evt_WToTauNu_M500 ;
  TH1D* tauPt_Stage1_WToTauNu_M500  = (TH1D*)file_WToTauNu_M500->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M500->Scale(wt_WToTauNu_M500);
 std::cout << "WToTauNu_M500 weighted nevt=" << tauPt_Stage1_WToTauNu_M500->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M500->Integral() ;

  //file_WToTauNu_M1000
  TH1D* h1_evt_WToTauNu_M1000 = (TH1D*)file_WToTauNu_M1000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M1000 = h1_evt_WToTauNu_M1000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M1000 = (xs_WToTauNu_M1000*lumi)/evt_WToTauNu_M1000 ;
  TH1D* tauPt_Stage1_WToTauNu_M1000  = (TH1D*)file_WToTauNu_M1000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M1000->Scale(wt_WToTauNu_M1000);
 std::cout << "WToTauNu_M1000 weighted nevt=" << tauPt_Stage1_WToTauNu_M1000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M1000->Integral();

  //file_WToTauNu_M2000
  TH1D* h1_evt_WToTauNu_M2000 = (TH1D*)file_WToTauNu_M2000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M2000 = h1_evt_WToTauNu_M2000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M2000 = (xs_WToTauNu_M2000*lumi)/evt_WToTauNu_M2000 ;
  TH1D* tauPt_Stage1_WToTauNu_M2000  = (TH1D*)file_WToTauNu_M2000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M2000->Scale(wt_WToTauNu_M2000);
 std::cout << "WToTauNu_M2000 weighted nevt=" << tauPt_Stage1_WToTauNu_M2000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M2000->Integral();

  //file_WToTauNu_M3000
  TH1D* h1_evt_WToTauNu_M3000 = (TH1D*)file_WToTauNu_M3000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M3000 = h1_evt_WToTauNu_M3000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M3000 = (xs_WToTauNu_M3000*lumi)/evt_WToTauNu_M3000 ;
  TH1D* tauPt_Stage1_WToTauNu_M3000  = (TH1D*)file_WToTauNu_M3000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M3000->Scale(wt_WToTauNu_M3000);
 std::cout << "WToTauNu_M3000 weighted nevt=" << tauPt_Stage1_WToTauNu_M3000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M3000->Integral();

  //file_WToTauNu_M4000
  TH1D* h1_evt_WToTauNu_M4000 = (TH1D*)file_WToTauNu_M4000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M4000 = h1_evt_WToTauNu_M4000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M4000 = (xs_WToTauNu_M4000*lumi)/evt_WToTauNu_M4000 ;
  TH1D* tauPt_Stage1_WToTauNu_M4000  = (TH1D*)file_WToTauNu_M4000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M4000->Scale(wt_WToTauNu_M4000);
 std::cout << "WToTauNu_M4000 weighted nevt=" << tauPt_Stage1_WToTauNu_M4000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M4000->Integral();

  //file_WToTauNu_M5000
  TH1D* h1_evt_WToTauNu_M5000 = (TH1D*)file_WToTauNu_M5000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M5000 = h1_evt_WToTauNu_M5000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M5000 = (xs_WToTauNu_M5000*lumi)/evt_WToTauNu_M5000 ;
  TH1D* tauPt_Stage1_WToTauNu_M5000  = (TH1D*)file_WToTauNu_M5000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M5000->Scale(wt_WToTauNu_M5000);
 std::cout << "WToTauNu_M5000 weighted nevt=" << tauPt_Stage1_WToTauNu_M5000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M5000->Integral();

  //file_WToTauNu_M6000
  TH1D* h1_evt_WToTauNu_M6000 = (TH1D*)file_WToTauNu_M6000->Get("demo/histoDir/eventCount");
  unsigned long long evt_WToTauNu_M6000 = h1_evt_WToTauNu_M6000->GetEntries(); //Integral();                                                             
  double wt_WToTauNu_M6000 = (xs_WToTauNu_M6000*lumi)/evt_WToTauNu_M6000 ;
  TH1D* tauPt_Stage1_WToTauNu_M6000  = (TH1D*)file_WToTauNu_M6000->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WToTauNu_M6000->Scale(wt_WToTauNu_M6000);
 std::cout << "WToTauNu_M6000 weighted nevt=" << tauPt_Stage1_WToTauNu_M6000->Integral() << std::endl;
 totalMC += tauPt_Stage1_WToTauNu_M6000->Integral();

  //file_WJetsToLNu
  TH1D* h1_evt_WJetsToLNu = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/eventCount");
  unsigned long long evt_WJetsToLNu = h1_evt_WJetsToLNu->GetEntries(); //Integral();                                                             
  double wt_WJetsToLNu = (xs_WJetsToLNu*lumi)/evt_WJetsToLNu ;
  TH1D* tauPt_Stage1_WJetsToLNu  = (TH1D*)file_WJetsToLNu->Get("demo/histoDir/tauPt_Stage1");
  tauPt_Stage1_WJetsToLNu->Scale(wt_WJetsToLNu);
 std::cout << "WJetsToLNu weighted nevt=" << tauPt_Stage1_WJetsToLNu->Integral() << std::endl;
 totalMC += tauPt_Stage1_WJetsToLNu->Integral();

  TH1D* total_WJets = (TH1D*)tauPt_Stage1_WJetsToLNu_HT100To200->Clone();
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT200To400);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT400To600);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT600To800);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT800To1200);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT1200To2500);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu_HT2500ToInf);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M100);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M200);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M500);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M1000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M2000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M3000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M4000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M5000);
  total_WJets->Add(tauPt_Stage1_WToTauNu_M6000);
  total_WJets->Add(tauPt_Stage1_WJetsToLNu);
  total_WJets->SetFillColorAlpha(kGreen-8,0.5);
  total_WJets->SetLineColor(kBlack);
  //std::cout << "Wjets " << total_WJets->GetBinError(300) << std::endl;

  total_WJets->Rebin(10);


  //file_WW
  TH1D* h1_evt_WW = (TH1D*)file_WW->Get("demo/histoDir/eventCount");
  unsigned long long evt_WW = h1_evt_WW->GetEntries(); //Integral();                                                                         
  double wt_WW = (xs_WW*lumi)/evt_WW ;
  TH1D* tauPt_Stage1_WW  = (TH1D*)file_WW->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  //tauPt_Stage1_WW->Sumw2(kFALSE);
  //tauPt_Stage1_WW->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WW->Scale(wt_WW);
 std::cout << "WW weighted nevt=" << tauPt_Stage1_WW->Integral() << std::endl;
 totalMC +=tauPt_Stage1_WW->Integral() ;

  //file_WZ
  TH1D* h1_evt_WZ = (TH1D*)file_WZ->Get("demo/histoDir/eventCount");
  unsigned long long evt_WZ = h1_evt_WZ->GetEntries(); //Integral();                                                                         
  double wt_WZ = (xs_WZ*lumi)/evt_WZ ;
  TH1D* tauPt_Stage1_WZ  = (TH1D*)file_WZ->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  //tauPt_Stage1_WZ->Sumw2(kFALSE);
  // tauPt_Stage1_WZ->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_WZ->Scale(wt_WZ);
  tauPt_Stage1_WZ->Scale(kfact_WZ);
 std::cout << "WZ weighted nevt=" << tauPt_Stage1_WZ->Integral() << std::endl;
 totalMC +=  tauPt_Stage1_WZ->Integral();

  //file_ZZ
  TH1D* h1_evt_ZZ = (TH1D*)file_ZZ->Get("demo/histoDir/eventCount");
  unsigned long long evt_ZZ = h1_evt_ZZ->GetEntries(); //Integral();                                                                         
  double wt_ZZ = (xs_ZZ*lumi)/evt_ZZ ;
  TH1D* tauPt_Stage1_ZZ  = (TH1D*)file_ZZ->Get("demo/histoDir/tauPt_Stage1");
  // Poisson error //
  //tauPt_Stage1_ZZ->Sumw2(kFALSE);
  //tauPt_Stage1_ZZ->SetBinErrorOption(TH1::kPoisson);
  tauPt_Stage1_ZZ->Scale(wt_ZZ);
  tauPt_Stage1_ZZ->Scale(kfact_ZZ);
 std::cout << "ZZ weighted nevt=" << tauPt_Stage1_ZZ->Integral() << std::endl;
 totalMC += tauPt_Stage1_ZZ->Integral();

  TH1D* total_diboson = (TH1D*)tauPt_Stage1_WW->Clone();
  total_diboson->Add(tauPt_Stage1_WZ);
  total_diboson->Add(tauPt_Stage1_ZZ);
  total_diboson->SetFillColorAlpha(kOrange+2,0.5);
  total_diboson->SetLineColor(kBlack);
  total_diboson->Rebin(10);


  //datadriven                                                                                                                                                                                                           
  //  double wt_Datadriven = (lumi/33.507) ;                                                                                                                                                                             
  TH1D* total_QCD = (TH1D*)file_Datadriven->Get("demo/histoDir/tauPt_Stage1");
  total_QCD->SetFillStyle(3001);
  total_QCD->SetFillColor(kPink+1);
  total_QCD->SetLineColor(kBlack);
  total_QCD->Rebin(10);  //datadriven                                                                                                                                                                                  

  std::cout << "totalMC(w/o DD) =" << totalMC << std::endl;

   std::cout << "will do data" << std::endl;
  
  //--Data--//
   TH1D* tauPt_Stage1_Run2016F  =  (TH1D*)file_Tau_Run2016F->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016E  =  (TH1D*)file_Tau_Run2016E->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016D  =  (TH1D*)file_Tau_Run2016D->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016C  =  (TH1D*)file_Tau_Run2016C->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016B  =  (TH1D*)file_Tau_Run2016B->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016G  =  (TH1D*)file_Tau_Run2016G->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016H_v2  = (TH1D*)file_Tau_Run2016H_v2->Get("demo/histoDir/tauPt_Stage1");
   TH1D* tauPt_Stage1_Run2016H_v3  = (TH1D*)file_Tau_Run2016H_v3->Get("demo/histoDir/tauPt_Stage1");
   
   /*
  std::cout << "Will Clone B" << std::endl;
  TH1D* tauPt_Stage1_Run2016BCD = (TH1D*)tauPt_Stage1_Run2016B->Clone();
 
  std::cout << "Will add C" << std::endl;
  tauPt_Stage1_Run2016BCD->Add(tauPt_Stage1_Run2016C);

  std::cout << "Will add D" << std::endl;
  tauPt_Stage1_Run2016BCD->Add(tauPt_Stage1_Run2016D);

  //  std::cout << "Will add E" << std::endl;
  // tauPt_Stage1_Run2016BCDEF->Add(tauPt_Stage1_Run2016E);

  // std::cout << "Will add F" << std::endl;
  //  tauPt_Stage1_Run2016BCDEF->Add(tauPt_Stage1_Run2016F);
  */

  TH1D* tauPt_Stage1_Run2016all = (TH1D*)tauPt_Stage1_Run2016B->Clone();
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016C);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016D);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016E);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016F);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016G);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016H_v2);
  tauPt_Stage1_Run2016all->Add(tauPt_Stage1_Run2016H_v3);
                                                                                                                                    
  tauPt_Stage1_Run2016all->SetMarkerStyle(20);
  tauPt_Stage1_Run2016all->SetMarkerColor(kBlack);
  tauPt_Stage1_Run2016all->SetLineColor(kBlack);
  tauPt_Stage1_Run2016all->Rebin(10);
  
  std::cout << "will do signal " << std::endl;
  //--Signal--//
  TH1D* h1_evt_Wprime_M4000 = (TH1D*)file_Wprime_M4000->Get("demo/histoDir/eventCount");
  unsigned long long evt_Wprime_M4000 = h1_evt_Wprime_M4000->GetEntries(); //Integral();                                                                          
  // std::cout << "evt_Wprime_M4000 = " << evt_Wprime_M4000 << std::endl;
  double wt_Wprime_M4000 = (xs_Wprime_M4000*lumi)/evt_Wprime_M4000 ;
  TH1D* tauPt_Stage1_Wprime_M4000  = (TH1D*)file_Wprime_M4000->Get("demo/histoDir/tauPt_Stage1");
  std::cout << "Sig Eff W' M4000 : " << ( tauPt_Stage1_Wprime_M4000->GetEntries() / evt_Wprime_M4000 ) << std::endl;
  tauPt_Stage1_Wprime_M4000->Scale(wt_Wprime_M4000);
  //  tauPt_Stage1_Wprime_M4000->SetFillColorAlpha(kGreen-7,0.5);
  tauPt_Stage1_Wprime_M4000->SetLineColor(kMagenta);
  tauPt_Stage1_Wprime_M4000->SetLineWidth(2);
  tauPt_Stage1_Wprime_M4000->SetLineStyle(5);
  tauPt_Stage1_Wprime_M4000->Rebin(10) ;
 
  //--Plotting Styles//
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.05);
  gStyle->SetPadBottomMargin(0.12);  
  gStyle->SetPadTopMargin(0.05);   
  gStyle->SetTitleXSize(0.05);
  gStyle->SetTitleXOffset(1.05);
  gStyle->SetTitleYSize(0.05);
  gStyle->SetTitleYOffset(1.05);

  //////// Output File /////////
  TFile* outputFile = new TFile("Out_tauPt_Stage1.root","RECREATE");
  outputFile->cd();

  //--//
  THStack *hs = new THStack("hs","");
  // hs->Add(tauPt_Stage1_WJetsToLNu);
  hs->Add(total_diboson);
  hs->Add(total_DY);
  hs->Add(total_ST);
  hs->Add(total_TT);
  //  hs->Add(tauPt_Stage1_DYJetsToLL_M50);
  hs->Add(total_QCD);
  //  hs->Add(total_ZJets);
  hs->Add(total_WJets);
  //tauPt_Stage1_->SetTitle("");
    /*
  eff1->GetYaxis()->SetTitle("Events");
  //eff1->SetMarkerStyle(0);
  //eff1->SetMarkerColor(kBlack);
  eff1->SetLineColor(kBlack);
  eff1->SetLineWidth(2);
  */
  TCanvas* my_canvas = new TCanvas("canvas","canvas",800,600);
  my_canvas->cd();
  //  hs->Draw();
  gPad->SetLogy();
  hs->Draw("HIST");                                                                                                                                        
  hs->SetMaximum(100000);
  hs->SetMinimum(0.1);
  hs->GetXaxis()->SetRangeUser(0, 1000);
  //  hs->GetXaxis()->SetLimits(40, 3200);
  hs->GetXaxis()->SetTitle("#tau pT [GeV]");
  hs->GetYaxis()->SetTitle("Events");

  TH1F* total =  (TH1F*)hs->GetStack()->Last()->Clone();
  // total->SetFillStyle(3004);                                                                                                                                      
  // total->SetFillColor(kGray+1); 
  //  total->SetMarkerColor(0);
  // total->Draw("SAME E2");
  //hs->GetStack()->Last()->Draw("same E");
  // hs->Draw("SAME HIST");

  //  tauPt_Stage1_Run2016E->Draw("SAME E0");
  tauPt_Stage1_Run2016all->Draw("SAME E0");
  TH1F* mydata =  (TH1F*)tauPt_Stage1_Run2016all->Clone();

  //tauPt_Stage1_Run2016C->Draw("SAME E0");
  //tauPt_Stage1_Run2016CDE->Draw("SAME E0");
  //
  tauPt_Stage1_Wprime_M4000->Draw("SAME HIST");
  //  hs->SetOption("HIST L");
  
  TLatex* CMS_text = new TLatex(0.20,0.90,"CMS");
  CMS_text->SetNDC();
  CMS_text->SetTextSize(0.05);
  CMS_text->SetTextAngle(0);
  CMS_text->Draw("same");
  TLatex* CMS_text_2 = new TLatex(0.20,0.85,"Preliminary");
  CMS_text_2->SetNDC();
  CMS_text_2->SetTextFont(42);
  CMS_text_2->SetTextSize(0.05);
  CMS_text_2->SetTextAngle(0);
  CMS_text_2->Draw("same");    

  TLatex* lumiText = new TLatex(0.92,0.975,"35.9 fb^{-1} (13 TeV)");
  lumiText->SetNDC();
  lumiText->SetTextFont(42);
  lumiText->SetTextSize(0.04);
  lumiText->SetTextAlign(32);
  lumiText->Draw("same");     

  TLegend *leg_example = new TLegend(0.75,0.50,0.94,0.94);
  leg_example->SetFillColor(0);
  leg_example->SetTextFont(42);
  leg_example->SetBorderSize(0);
  leg_example->AddEntry(total_WJets, "Wjets","f");
  leg_example->AddEntry(total_DY, "DY","f");
  leg_example->AddEntry(total_TT, "TT","f");
  //leg_example->AddEntry(tauPt_Stage1_WJetsToLNu, "Wjets","f");
  leg_example->AddEntry(total_ST, "Single Top", "f");
  leg_example->AddEntry(total_diboson, "Diboson", "f");
  leg_example->AddEntry(total_QCD, "QCD datadriven", "f");
  // leg_example->AddEntry(total_ZJets, "Z", "f");
  leg_example->AddEntry(tauPt_Stage1_Wprime_M4000, "SSM W' 4 TeV", "l");
  leg_example->AddEntry(tauPt_Stage1_Run2016all, "Data", "pl" );
  // leg_example->AddEntry(tauPt_Stage1_Run2016E, "Data", "pl" );
  // leg_example->AddEntry(tauPt_Stage1_Run2016D, "Data", "pl" );
  leg_example->Draw("same");
  
  my_canvas->Write();
  my_canvas->Print("tauPt_Stage1_DD.pdf");


  /*

  TCanvas* my_canvas2 = new TCanvas("canvas2","canvas2");
  my_canvas2->cd();
  gPad->SetLogy();
  total->SetMaximum(1000);
  total->SetMarkerStyle(20);
  total->Draw("E");
  my_canvas2->Write();
  */
  TCanvas* ratio_c = new TCanvas("ratio","ratio_canvas",800,700);
  ratio_c->SetTopMargin(0.); 
  ratio_c->SetBottomMargin(0.); 
  ratio_c->Update();
  ratio_c->Divide(1, 2);
  ratio_c->cd(1);

  gPad->SetPad(.005, .30, .995, .995);
  TPad* pad1 = (TPad*)ratio_c->GetPad(1); 
  pad1->SetTopMargin(0.05);
  pad1->SetBottomMargin(0.05); 
  
  ratio_c->Update();
  gPad->SetLogy();
  
  hs->Draw("HIST");                                                                                                                                        
  hs->SetMaximum(100000);
  hs->SetMinimum(0.01);
  //  hs->GetXaxis()->SetLimits(40, 3200);
  hs->GetXaxis()->SetRangeUser(0, 1000);
  hs->GetXaxis()->SetTitle("");
  // total->Draw("SAME E2");
  mydata->Draw("SAME E1");
  tauPt_Stage1_Wprime_M4000->Draw("SAME HIST");
  CMS_text->Draw("same");
  CMS_text_2->Draw("same");
  lumiText->Draw("same");
  leg_example->Draw("same");
  ratio_c->cd(2);

  gPad->SetPad(.005, .08, .995, .28); 
  gStyle->SetOptStat(false);
  ratio_c->Update();
  TPad* pad2 = (TPad*)ratio_c->GetPad(2);
  pad2->SetTopMargin(0.04); 
  pad2->SetBottomMargin(0.30); 
  pad2->SetGridx();
  pad2->SetGridy();

  std::cout << "data bins = " << mydata->GetNbinsX() << " width=" << mydata->GetBinWidth(2);
  std::cout << " MC bins = " << total->GetNbinsX() << " width=" << total->GetBinWidth(2) << std::endl;

  int nbin=mydata->GetNbinsX() ;
  float width=mydata->GetBinWidth(2);
  TH1F *data_by_MC = new TH1F("h1", "ratio", nbin, 0, 4000);
  std::cout << "before D/MC bins=" << data_by_MC->GetNbinsX() << " width=" << data_by_MC->GetBinWidth(2) << std::endl;

  for (int i=0; i<nbin; i++) {
    float data = mydata->GetBinContent(i);
    float MC = total->GetBinContent(i);
    float ratio=0;
    if (MC>0) ratio=data/MC ;
    data_by_MC->SetBinContent(i,ratio);
    if (data>0) {
      float stat_err = sqrt(data)/data ;  
      data_by_MC->SetBinError(i,stat_err);
    }

    // data_by_MC->SetBinWidth(i,width);  
  }

  //  TH1F* data_by_MC = (TH1F*)mydata->Clone();
  // data_by_MC->Divide(total);
  data_by_MC->SetMarkerStyle(20);
  data_by_MC->Draw("E");
  data_by_MC->GetXaxis()->SetTitle("#tau pT [GeV]");
  data_by_MC->GetYaxis()->SetTitle("#frac{DATA}{MC}");
  data_by_MC->GetYaxis()->SetLabelSize(0.12);
  data_by_MC->GetXaxis()->SetLabelSize(0.12);
  data_by_MC->GetYaxis()->SetTitleSize(0.18);
  data_by_MC->GetXaxis()->SetTitleSize(0.18);
  data_by_MC->GetYaxis()->SetTitleOffset(0.20);
  data_by_MC->GetXaxis()->SetTitleOffset(0.75);
  data_by_MC->SetTitle("");
  data_by_MC->GetXaxis()->SetRangeUser(0, 1000);
  data_by_MC->SetMaximum(4);
  data_by_MC->SetMinimum(0);
  data_by_MC->GetYaxis()->SetNdivisions(4);



  TLine *l=new TLine(0,1,1000,1);
  l->SetLineColor(kRed);
  l->Draw("same");

  std::cout << "D/MC bins=" << data_by_MC->GetNbinsX() << " width=" << data_by_MC->GetBinWidth(2) << std::endl;
  ratio_c->Write();
  ratio_c->Print("tauPt_Stage1_ratio_DD.pdf");

 
  return 0;

}
Example #9
0
void Skim(TString fname="ZnnH125", TString outputname = "")
{
    gROOT->LoadMacro("HelperFunctions.h" );  // make functions visible to TTreeFormula
    gROOT->SetBatch(1);

    TChain * chain  = new TChain("tree");
    TString dijet   = "";
    TString outdir  = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Phys14_PU20bx25/skimV11_v2/";
    TString prefix  = "skim_";
    TString suffix  = "tree*.root";
    


    TCut selection = baseline.c_str();
    // Different baseline for dimuons
    // MET filters
    selection += metfilter.c_str();

    // JSON & trigger
    if (fname.Contains("Data")) {
        TCut trigger = mettrigger.c_str();
        selection += trigger;
        //selection.Print();
      }
      /*
    } else if (process == "Data_METBTag_R" || process == "Data_METBTag_P") {
        TCut trigger = metbtagtrigger.c_str();
        selection += trigger;
        //selection.Print();
    } else if (process == "Data_SingleMu_R" || process == "Data_SingleMu_P") {
        TCut trigger = singlemutrigger.c_str();
        selection += trigger;
        //selection.Print();
    } else if (process == "Data_SingleEl_R" || process == "Data_SingleEl_P") {
        TCut trigger = singleeltrigger.c_str();
        selection += trigger;
        //selection.Print();
    }
      */


    chain->Add(fname);

    // Sum Count, CountWithPU, CountWithPUP, CountWithPUM
    TObjArray * files = chain->GetListOfFiles();
    TIter next(files);
    TChainElement * chainElem = 0;
    TFile * f2 = 0;
    TH1D * h1 = new TH1D("Count", ";Counts", 16, 0, 16);
    TH1F * htemp = 0;

    while ((chainElem = (TChainElement*) next())) {
      //#ifndef XROOTD
      //      f2 = TFile::Open("dcache:" + TString(chainElem->GetTitle()));
      //#else
      std::cout << "chainElem->GetTitle() " << chainElem->GetTitle() << std::endl; 
        f2 = TFile::Open( TString(chainElem->GetTitle()));
	//#endif
        htemp = (TH1F*) f2->Get("Count");
        h1->SetBinContent(1, h1->GetBinContent(1)+htemp->GetBinContent(1));
	/*
        htemp = (TH1F*) f2->Get("CountWithPU");
        h1->SetBinContent(2, h1->GetBinContent(2)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithPUP");
        h1->SetBinContent(3, h1->GetBinContent(3)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithPUM");
        h1->SetBinContent(4, h1->GetBinContent(4)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithMCProd");
        h1->SetBinContent(5, h1->GetBinContent(5)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithPUMCProd");
        h1->SetBinContent(6, h1->GetBinContent(6)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("countWithSignalQCDcorrections");
        h1->SetBinContent(7, h1->GetBinContent(7)+htemp->GetBinContent(1));
        */
        std::clog << fname << ": skimmed from " << chainElem->GetTitle() << std::endl;
    }
    
    // LHE Count
    
    TH1D * h2 = new TH1D("LHECount", ";LHE Counts", 16, 0, 16);
    TString process_lhe = fname;
    if (process_lhe.BeginsWith("WJets"))
        process_lhe = "WJets";
    else if (process_lhe.BeginsWith("ZJets"))
        process_lhe = "ZJets";
    else 
        process_lhe = "";
    const std::vector<std::string>& lhecuts = GetLHECuts(process_lhe.Data());
    for (unsigned int i=0; i < lhecuts.size(); i++) {
        TCut cut2 = lhecuts.at(i).c_str();
        h2->SetBinContent(i+1, chain->GetEntries(cut2));
    }
    
    

    // Make output directory if it doesn't exist
    if (gSystem->AccessPathName(outdir))
        gSystem->mkdir(outdir);
    TString outname = outdir + prefix + Form("%s.root", outputname.Data());
    std::cout << "outname is " << outname << std::endl;

    TFile* f1 = TFile::Open(outname, "RECREATE");
    TTree* t1 = (TTree*) chain->CopyTree(selection);
    std::clog << fname << ": skimmed from " << chain->GetEntriesFast() << " to " << t1->GetEntriesFast() << " entries." << std::endl;
    
    t1->Write();
    h1->Write();
     h2->Write();
    f1->Close();

    return;
}
void 
//HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_et_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category_extra = "no b-tag";     }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category_extra = "b-tag";  }        
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra2 = "medium p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }

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

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

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

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK0 = refill(shape_histos(EWK0, datacard, "VV"), "VV"); 
    EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
    EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK = refill(shape_histos(EWK, datacard, "ZL"), "ZL");
#else
    //    EWK = refill(shape_histos(EWK, datacard, "ZLL"), "ZLL");
#endif
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
    Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/

    rescale(Fakes, 7); 
    rescale(EWK0 , 6); 
    rescale(EWK1 , 3); 
#ifdef EXTRA_SAMPLES
    rescale(EWK2 , 4); 
    rescale(EWK  , 5);
#else
    rescale(EWK  , 4);
#endif 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);
#endif  
#endif
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("Zee"     );
  EWK1 ->Write("EWK"    );
  //EWK  ->Write("EWK"     );
  EWK1 ->Write("EWK1"    );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
  ggH_SM125->Write("ggH_SM125");
  qqH_SM125->Write("qqH_SM125");
  VH_SM125 ->Write("VH_SM125");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
void compareSherpaMadgraph(std::string sherpafile, std::string madgraphfile,
                           std::string var,
                           float xmin=-9999.0, float xmax=-9999.0,
                           bool logScale=false,
                           std::string output="test")
{

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

    TH1F* hsherpa;
    TH1F* hmadgraph;

    char tempName[300];


    // first get the histogram files
    TFile *fsherpa = TFile::Open(sherpafile.data());
    TFile *fmadgraph   = TFile::Open(madgraphfile.data());

    hsherpa  = (TH1F*)(fsherpa->Get(var.data()));
    hmadgraph    = (TH1F*)(fmadgraph->Get(var.data()));

    TH1D* hscale =(TH1D*) hsherpa->Clone("hscale");
    hscale->SetYTitle("SHERPA/MADGRAPH");

    int nREBIN=2;
    if(var.find("pt")!= std::string::npos)
        nREBIN=4;

    hsherpa->GetXaxis()->SetNdivisions(5);
    hsherpa->GetYaxis()->SetDecimals();
    hsherpa->Rebin(nREBIN);

    hmadgraph->GetXaxis()->SetNdivisions(5);
    hmadgraph->GetYaxis()->SetDecimals();
    hmadgraph->Rebin(nREBIN);

    hscale->GetXaxis()->SetNdivisions(5);
    hscale->GetYaxis()->SetDecimals();
    hscale->Rebin(nREBIN);

    hsherpa->SetLineColor(2);
    hsherpa->SetMarkerColor(2);
    hsherpa->SetMarkerSize(1);
    hsherpa->SetMarkerStyle(24);


    hmadgraph->SetLineColor(4);
    hmadgraph->SetMarkerColor(4);
    hmadgraph->SetMarkerSize(1);
    hmadgraph->SetMarkerStyle(21);

    // if normalizing to the same area, set the scale

    int binLo = -1;
    int binHi = -1;
    int nbins = hsherpa->GetNbinsX();
    if(xmin>-9999.0 && xmax>-9999.0)
    {

        binLo = hsherpa->FindBin(xmin);
        binHi = hsherpa->FindBin(xmax)-1;

    }

    else
    {
        binLo = 1;
        binHi = nbins;
        xmin = hsherpa->GetBinLowEdge(1);
        xmax = hsherpa->GetBinLowEdge(nbins+1);
    }


    //   float scale_mc = (float)hsherpa->Integral(binLo,binHi)/(float)hmadgraph->Integral(binLo,binHi);
    //   cout << "binLo = " << binLo << ", binHi = " << binHi << endl;
    //   cout << "xmin = " << xmin << "xmax = " << xmax << endl;

    //   hmadgraph->Sumw2();
    //   hmadgraph->Scale(scale_mc);

    float scale_sherpa   = 1000.0*4.890*3048.0/4.71644910071102437e+06;

    float scale_madgraph = 1000.0*4.890*3048.0/3.59644320000000000e+07;

    hsherpa->Sumw2();
    hsherpa->Scale(scale_sherpa);

    hmadgraph->Sumw2();
    hmadgraph->Scale(scale_madgraph);

    cout << "hmadgraph integral = " << hmadgraph->Integral() << endl;
    cout << "hsherpa integral = "   << hsherpa->Integral() << endl;;

    // get the ratio
    double chi2 = 0;
    int realbin = 0;
    for(int i=1; i<= nbins; i++) {

        double nmc=hmadgraph->GetBinContent(i);
        double ndata=hsherpa->GetBinContent(i);
        double nmcerr=hmadgraph->GetBinError(i);
        double ndataerr=hsherpa->GetBinError(i);

        if(nmc<0 || ndata<0)continue;

        if(nmcerr==0 && ndataerr==0)continue;

        if(nmc==0 && ndata==0)continue;

        double chi2ndef = (nmc-ndata)*(nmc-ndata)/
                          ( nmcerr*nmcerr+ ndataerr*ndataerr);
        chi2 += chi2ndef;
        realbin++;

        cout << "Bin " << i << " : " << ndata << ", " << nmc;
        cout << " " << chi2ndef << endl;


        // now calculate the ratio
        if(nmc==0 || nmcerr==0 || ndata==0 || ndataerr==0)continue;
        cout << "Bin " << i << " ratio = " << ndata/nmc << endl;
        hscale->SetBinContent(i,ndata/nmc);
        double err = 0;
        err=
            (ndata/nmc)*sqrt(pow(nmcerr/nmc,2)+pow(ndataerr/ndata,2));
        hscale->SetBinError(i,err);

    }


    hsherpa->GetXaxis()->SetRangeUser(xmin,xmax);
    hmadgraph->GetXaxis()->SetRangeUser(xmin,xmax);
    hscale->GetXaxis()->SetRangeUser(xmin,xmax);


    TCanvas* c1 = new TCanvas("c1","",700,1000);
    c1->Divide(1,2,0.01,0);
    c1->cd(1);
    if(logScale)
        gPad->SetLogy(1);
    gPad->SetTopMargin(0.01);
    gPad->SetBottomMargin(0);
    gPad->SetRightMargin(0.04);


    float max_data  = hsherpa->GetBinError(hsherpa->GetMaximumBin()) + hsherpa->GetMaximum();
    float max_mc    = hmadgraph->GetBinError(hmadgraph->GetMaximumBin()) + hmadgraph->GetMaximum();

    if(max_data > max_mc)
    {
        hsherpa->Draw("e");
        hmadgraph->Draw("hesame");
    }
    else
    {   hmadgraph->Draw("he");
        hsherpa->Draw("esame");
    }


    float x1NDC = 0.691;
    float y1NDC = 0.757;
    float x2NDC = 0.894;
    float y2NDC = 0.973;

    TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);

    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    leg->SetTextSize(0.04);
    leg->SetBorderSize(0);
    leg->AddEntry(hsherpa, "SHERPA");
    leg->AddEntry(hmadgraph, "MADGRAPH");
    leg->Draw("same");



    c1->cd(2);
    gStyle->SetStatW       (0.3);
    gStyle->SetStatH       (0.3);
    gStyle->SetStatX       (0.879447);
    gStyle->SetStatY       (0.939033);
    gStyle->SetStatFontSize(0.05);
    gStyle->SetStatBorderSize(0);
    gPad->SetRightMargin(0.04);
    gPad->SetTopMargin(0);
    gPad->SetBottomMargin(0.2);
    gPad->SetTickx();
    gStyle->SetOptFit(1);
    hscale->SetTitle("");
    hscale->SetMaximum(3.0);
    hscale->SetMinimum(-0.5);
    hscale->SetTitleOffset(1.2,"Y");
    hscale->Draw("e1");
    TF1* fline = new TF1("fline","pol1");
    TLine* l2 = new TLine(xmin,1.,xmax,1.);
    l2->SetLineColor(4);
    l2->SetLineStyle(3);
    fline->SetLineWidth(3);
    fline->SetLineColor(6);
    fline->SetNpx(2500);
    hscale->Fit("fline","","");
    l2->Draw("same");


    string dirName = "compareSherpaMadgraph";
    gSystem->mkdir(dirName.data());

    std::string filename;
    std::string psname = dirName + "/" + var;
    if(output !="test")
        psname = dirName+ "/" + output;
    else
        psname = dirName+ "/" + var;
    filename = psname + ".eps";
    c1->Print(filename.data());
    filename = psname + ".gif";
    c1->Print(filename.data());
    filename = psname + ".pdf";
    c1->Print(filename.data());
    //   c1->Close();
}
void plotRatioDoubleratio(TString varname_="", TString vartex_="")
{
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.05);
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptStat(0);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(0.8);

  varname=varname_;
  vartex=vartex_;
  
  TFile* infPP = new TFile(Form("outfDoubleratio/fPP_%s_DoubleRatio.root",varname.Data()));
  TH1D* hPP = (TH1D*)infPP->Get("hDoubleRatio");
  hPP->SetName(Form("hPP_%.0f",varname.Data()));
  TFile* infPbPb = new TFile(Form("outfDoubleratio/fPbPb_%s_DoubleRatio.root",varname.Data()));
  TH1D* hPbPb = (TH1D*)infPbPb->Get("hDoubleRatio");
  hPbPb->SetName(Form("hPbPb_%.0f",varname.Data()));
  TFile* infPPMB = new TFile(Form("outfDoubleratio/fPPMB_%s_DoubleRatio.root",varname.Data()));
  TH1D* hPPMB = (TH1D*)infPPMB->Get("hDoubleRatio");
  hPPMB->SetName(Form("hPPMB_%.0f",varname.Data()));
  TFile* infPbPbMB = new TFile(Form("outfDoubleratio/fPbPbMB_%s_DoubleRatio.root",varname.Data()));
  TH1D* hPbPbMB = (TH1D*)infPbPbMB->Get("hDoubleRatio");
  hPbPbMB->SetName(Form("hPbPbMB_%.0f",varname.Data()));

  TH1F* hRatio = (TH1F*)hPbPb->Clone("hRatio");
  hRatio->Divide(hPP);
  TH1F* hRatioMB = (TH1F*)hPbPbMB->Clone("hRatioMB");
  hRatioMB->Divide(hPPMB);

  Int_t varbins = hRatio->GetNbinsX();
  Float_t varstep = hRatio->GetBinWidth(1);
  Float_t varmin = hRatio->GetBinCenter(1)-0.5*varstep;
  Float_t varmax = hRatio->GetBinCenter(varbins)-0.5*varstep;
  Float_t aRatio[varbins],aRatioErr[varbins];
  Float_t aRatioMB[varbins],aRatioMBErr[varbins];
  Float_t aX[varbins],aZero[varbins];
  for(int i=0;i<varbins;i++)
    {
      aX[i] = hRatio->GetBinCenter(i+1)-0.5*varstep;
      aZero[i] = 0;
      aRatio[i] = hRatio->GetBinContent(i+1);
      aRatioErr[i] = hRatio->GetBinError(i+1);
      aRatioMB[i] = hRatioMB->GetBinContent(i+1);
      aRatioMBErr[i] = hRatioMB->GetBinError(i+1);
    }

  TGraphErrors* gRatio = new TGraphErrors(varbins,aX,aRatio,aZero,aRatioErr);
  TH2F* hemptyRatio = new TH2F("hemptyRatio","",20,varmin-0.5*varstep,varmax+0.5*varstep,10.,0.7,1.3);
  hemptyRatio->GetXaxis()->SetTitle(Form("%s",vartex.Data()));
  hemptyRatio->GetYaxis()->SetTitle("DoubleRatio^{PbPb} / DoubleRatio^{PP}");
  hemptyRatio->GetXaxis()->SetTitleOffset(1.);
  hemptyRatio->GetYaxis()->SetTitleOffset(.9);
  hemptyRatio->GetXaxis()->SetTitleSize(0.045);
  hemptyRatio->GetYaxis()->SetTitleSize(0.045);
  hemptyRatio->GetXaxis()->SetTitleFont(42);
  hemptyRatio->GetYaxis()->SetTitleFont(42);
  hemptyRatio->GetXaxis()->SetLabelFont(42);
  hemptyRatio->GetYaxis()->SetLabelFont(42);
  hemptyRatio->GetXaxis()->SetLabelSize(0.04);
  hemptyRatio->GetYaxis()->SetLabelSize(0.04);
  TCanvas* cRatio = new TCanvas("cRatio","",600,600);
  hemptyRatio->Draw();
  gRatio->Draw("psame");
  cRatio->SaveAs(Form("plotRatios/cRatio_%s.pdf",varname.Data()));

  TGraphErrors* gRatioMB = new TGraphErrors(varbins,aX,aRatioMB,aZero,aRatioMBErr);
  TH2F* hemptyRatioMB = new TH2F("hemptyRatioMB","",20,varmin-0.5*varstep,varmax+0.5*varstep,10.,0.7,1.3);
  hemptyRatioMB->GetXaxis()->SetTitle(Form("%s",vartex.Data()));
  hemptyRatioMB->GetYaxis()->SetTitle("DoubleRatio^{PbPb} / DoubleRatio^{PP}");
  hemptyRatioMB->GetXaxis()->SetTitleOffset(1.);
  hemptyRatioMB->GetYaxis()->SetTitleOffset(.9);
  hemptyRatioMB->GetXaxis()->SetTitleSize(0.045);
  hemptyRatioMB->GetYaxis()->SetTitleSize(0.045);
  hemptyRatioMB->GetXaxis()->SetTitleFont(42);
  hemptyRatioMB->GetYaxis()->SetTitleFont(42);
  hemptyRatioMB->GetXaxis()->SetLabelFont(42);
  hemptyRatioMB->GetYaxis()->SetLabelFont(42);
  hemptyRatioMB->GetXaxis()->SetLabelSize(0.04);
  hemptyRatioMB->GetYaxis()->SetLabelSize(0.04);
  TCanvas* cRatioMB = new TCanvas("cRatioMB","",600,600);
  hemptyRatioMB->Draw();
  gRatioMB->Draw("psame");
  cRatioMB->SaveAs(Form("plotRatios/cRatioMB_%s.pdf",varname.Data()));

}
Example #13
0
//Compare the btag histo files histograms bin-by-bin
void CompareBtagEffFiles( TString ind = "" , TString inf = "" ) {

  const int ngraph = 9;       // # plots to compare
  const int nbins = 19;       // # bins to compare in each plot
  const int taggedgraphs = 6; // # plots which are simple counts only

  TFile myFiled(ind);
  TFile myFilef(inf);
  if ( myFiled.IsZombie() || myFilef.IsZombie() ) { cout << "Files are zombies!" << endl; return; }
 
  string names_d[ngraph] = {"h_bjet","h_cjet","h_ljet","h_btag","h_ctag","h_ltag","h_btageff","h_ctageff","h_ltageff"};
  string names_f[ngraph] = {"h_bjet","h_cjet","h_ljet","h_btag","h_ctag","h_ltag","h_btageff","h_ctageff","h_ltageff"};
  double ptbins[18] = {20, 30, 40, 50, 60, 70, 80, 100, 120, 160, 210, 260, 320, 400, 500, 600, 800, 99999}; 
 
  TH1D * histd;
  TH1F * histf;

  cout << endl << "Comparing histograms in the btag eff histo files bin-by-bin (inc under/over-flow). " << endl;
  cout << "-------------------------------------------------------------" << endl;
  for( int i = 0; i < ngraph; i++ ) {
    //This 'hack' absolutely needed. Don't ask...
    char  hist_named[200], hist_namef[200]; 
    sprintf(hist_named,"%s",names_d[i].c_str());
    sprintf(hist_namef,"%s",names_f[i].c_str());

    cout << endl << "Now processing " << names_d[i] << " and " << names_f[i] << " ... "  << endl << endl;
    myFiled.cd("");
    histd = (TH1D*) gDirectory->Get(hist_named); 
    myFilef.cd("");
    histf = (TH1F*) gDirectory->Get(hist_namef); 
    if (histd->IsZombie() ) { cout << "There is something wrong with " << names_d[i] << "d. Please fix: now exiting." << endl; return; } 
    if (histf->IsZombie() ) { cout << "There is something wrong with " << names_f[i] << "f. Please fix: now exiting." << endl; return; }
 
    if ( i < taggedgraphs )
      cout << "  | TH1D       : TH1F       : D/F " << endl;
    else
      cout << "  | TH1D              : TH1F              : D/F " << endl;

    double totd = 0, totf = 0;
    for( int j = 0; j < nbins; j++ ) {
      if ( i < taggedgraphs ) { 
        printf("%2i| %10.0f : %-10.0f : %5.4f\n",j,histd->GetBinContent(j),histf->GetBinContent(j),histd->GetBinContent(j)/histf->GetBinContent(j));
        totd +=  histd->GetBinContent(j); 
        totf +=  histf->GetBinContent(j); 
      }
      else
        printf("%2i| %15.15f : %15.15f : %5.4f\n",j,histd->GetBinContent(j),histf->GetBinContent(j),histd->GetBinContent(j)/histf->GetBinContent(j));
    }//go through the bins..

    if ( i < taggedgraphs ) {
      cout << "  " << endl;
      printf("SUM %10.0f : %-10.0f : %5.4f\n",totd, totf, totd/totf);
    }
    cout << "-------------------------------------------------------------" << endl;

  }//end for  

  myFiled.Close();
  myFilef.Close();
 
  cout << endl << " .. Done " << endl;
} // end of function
Example #14
0
void finalPlot(bool drawRatio = 1, int differential = 0, int nsel = 0, int ReBin = 1, TString XTitle = "p_{T,max}^{l} (GeV)", TString units = "", TString plotName = "XSLeadingPt_AN.root", TString outputName = "WW_LeadingPt_final", bool isLogY = false,  double lumi = 19.5) {

  gInterpreter->ExecuteMacro("GoodStyle.C");

  TFile* file = new TFile(plotName.Data(), "read");
 
  TH1F* xsValue = (TH1F*) xsValue->Clone();
  TH1F* xsValue_Powheg =  (TH1F*) xsValue_Powheg->Clone();
  TH1F* xsValue_Madgraph = (TH1F*) xsValue_Madgraph->Clone();
  TH1F* xsValue_MCnlo = (TH1F*) xsValue_MCnlo->Clone();
  TH1F* systHisto = (TH1F*) systHisto->Clone();

 
  TCanvas* canvas ;
  TPad *pad1, *pad2;
 
   if (drawRatio) {
    canvas = new TCanvas("wwxs", "wwxs", 550, 1.2*600);
    
    pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1);
    pad1->SetTopMargin   (0.05);
    pad1->SetBottomMargin(0.02);
    pad1->Draw();
    
    pad2 = new TPad("pad2", "pad2", 0, 0, 1, 0.31); 
    pad2->SetTopMargin   (0.08);
    pad2->SetBottomMargin(0.35);
    pad2->Draw();
  
  }       else { 
    canvas = new TCanvas("wwxs", "wwxs", 550, 550);
    }

   if (drawRatio) pad1->cd();


   //Plot Data
   xsValue->SetLineWidth(1);
   xsValue->SetMarkerSize(1.0);

   int NBins = xsValue->GetNbinsX();

   for(int i=1; i <NBins; i++) {

     float err_stat = xsValue->GetBinError(i);
     float err_syst = systHisto->GetBinError(i);
     float err_total = sqrt(err_stat*err_stat + err_syst*err_syst);

     xsValue->SetBinError(i, err_total);
   }


  //-- Plot Powheg

   TH1F *hpowError  = (TH1F*) xsValue_Powheg->Clone();

   xsValue_Powheg->SetMarkerColor(kAzure-3);
   xsValue_Powheg->SetLineWidth(1);
   xsValue_Powheg->SetLineColor(kBlue+2);
   xsValue_Powheg->SetMarkerStyle(22);
   xsValue_Powheg->SetMarkerSize(1.2);
  

   hpowError->SetLineWidth(0);
   hpowError->SetMarkerSize (      0);  
   hpowError->SetFillColor  (kAzure-9);


  //-- Plot Madgraph

  TH1F *hmadError  = (TH1F*) xsValue_Madgraph->Clone();

  xsValue_Madgraph->SetMarkerColor(kPink-9);
  xsValue_Madgraph->SetLineWidth(1);
  xsValue_Madgraph->SetLineStyle(1);
  xsValue_Madgraph->SetMarkerStyle(21);
  xsValue_Madgraph->SetMarkerSize(1.0);

  hmadError->SetLineWidth(0);
  hmadError->SetMarkerSize (      0); 
  hmadError->SetFillColor  (kPink+1);


  //-- Plot MCNLO

  TH1F *hmcError  = (TH1F*) xsValue_MCnlo->Clone();

  xsValue_MCnlo->SetMarkerColor(kRed);
  xsValue_MCnlo->SetLineColor(kRed);
  xsValue_MCnlo->SetLineWidth(1);
  xsValue_MCnlo->SetLineStyle(1);
  xsValue_MCnlo->SetMarkerStyle(24);
  xsValue_MCnlo->SetMarkerSize(1.0);

  hmcError->SetLineWidth(0);
  hmcError->SetMarkerSize (      0); 
  hmcError->SetFillColor  (kOrange);
 



  //-- Plot Data

  xsValue->SetMarkerStyle(kFullCircle);
      
  if (differential == 0) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{dp_{T,max}^{l}}");
  if (differential == 1) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{dp_{T}(ll)}");
  if (differential == 2) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{dm_{#font[12]{ll}}}");
  if (differential == 3) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{d#Delta#phi_{ll}}");

  AxisFonts (xsValue->GetXaxis(), XTitle);
 



  xsValue->Draw("p");
  hmadError->Draw("e2,same"); 
  xsValue_Madgraph->Draw("pe1,same");
  hmcError->Draw("e2,same");
  xsValue_MCnlo->Draw("pe1,same");
  hpowError->Draw("e2,same");
  xsValue_Powheg->Draw("pe1,same");
  //systHisto->Draw("e2, same");
  xsValue->Draw("pe1,same");
      
  // Legend
  //----------------------------------------------------------------------------
  
  DrawLegend (0.65, 0.85, xsValue, "Data", "P");
  DrawLegend (0.65, 0.80, hpowError,   "", "F");
  DrawLegend (0.65, 0.80, xsValue_Powheg,   "Powheg", "PL");
  DrawLegend (0.65, 0.75, hmadError,   "", "F");
  DrawLegend (0.65, 0.75, xsValue_Madgraph,   "Madgraph", "PL");  
  DrawLegend (0.65, 0.70, hmcError,   "", "F");
  DrawLegend (0.65, 0.70, xsValue_MCnlo,   "MCNLO", "LP");

  canvas->GetFrame()->DrawClone();



  // Draw text 
  //----------------------------------------------------------------------------
  TLatex * CMSLabel = new TLatex (0.18, 0.96, "#bf{CMS}");
  CMSLabel->SetNDC ();
  CMSLabel->SetTextAlign (10);
  CMSLabel->SetTextFont (42);
  CMSLabel->SetTextSize (_tsize);
  CMSLabel->Draw ("same") ;


  TLatex * _lumiLabel = new TLatex (0.95, 0.96, "19.4fb#lower[0.3]{^{-1}} (8 TeV)");
  _lumiLabel->SetNDC ();
  _lumiLabel->SetTextAlign (30);
  _lumiLabel->SetTextFont (42);
  _lumiLabel->SetTextSize (_tsize);
  _lumiLabel->Draw ("same") ;


  // Draw also ratio
  //----------------------------------------------------------------------------
  if (drawRatio) {

     pad2->cd();
	
    TH1F* ratio_pow       = xsValue_Powheg->Clone("ratio");
    TH1F* ratio_mad       = xsValue_Madgraph->Clone("ratio");
    TH1F* ratio_mcnlo     = xsValue_MCnlo->Clone("ratio");
    TH1F* hratio_pow       = xsValue_Powheg->Clone("ratio");
    TH1F* hratio_mad       = xsValue_Madgraph->Clone("ratio");
    TH1F* hratio_mcnlo     = xsValue_MCnlo->Clone("ratio");
    TH1F* ratioErr        = xsValue->Clone("ratio");
    

    for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {

      Double_t powValue = xsValue_Powheg->GetBinContent(ibin);
      Double_t powError = xsValue_Powheg->GetBinError  (ibin);
      
      Double_t madValue = xsValue_Madgraph->GetBinContent(ibin);
      Double_t madError = xsValue_Madgraph->GetBinError  (ibin);
      
      Double_t mcnloValue = xsValue_MCnlo->GetBinContent(ibin);
      Double_t mcnloError = xsValue_MCnlo->GetBinError  (ibin);
      
      Double_t dataValue = xsValue->GetBinContent(ibin);
      Double_t statError = xsValue->GetBinError  (ibin);
      Double_t systError = systHisto->GetBinError(ibin);
      
      Double_t dataError = systError;
      
      Double_t ratioValue_pow           = (powValue > 0) ? powValue/dataValue : 0.0;
      Double_t ratioError_pow           = (powValue > 0) ? powError / dataValue : 0.0;
      
      Double_t ratioValue_mad           = (madValue > 0) ? madValue/dataValue : 0.0;
      Double_t ratioError_mad           = (madValue > 0) ? madError/dataValue : 0.0;
      
      Double_t ratioValue_mcnlo         = (mcnloValue > 0) ? mcnloValue/dataValue : 0.0;
      Double_t ratioError_mcnlo         = (mcnloValue > 0) ? mcnloError/dataValue : 0.0;
      
      Double_t uncertaintyError         = (dataValue > 0) ? dataError/dataValue : 0.0;
      

      //dataError/dataValue 
      ratio_pow->SetBinContent(ibin, ratioValue_pow);
      hratio_pow->SetBinContent(ibin, ratioValue_pow);
      hratio_pow->SetBinError  (ibin, ratioError_pow);
      
      ratio_mad->SetBinContent(ibin, ratioValue_mad);
      hratio_mad->SetBinContent(ibin, ratioValue_mad);
      hratio_mad->SetBinError  (ibin, ratioError_mad);
      
      ratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
      hratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
      hratio_mcnlo->SetBinError  (ibin, ratioError_mcnlo);
      
      ratioErr->SetBinContent(ibin, 1.0);
      ratioErr->SetBinError  (ibin, uncertaintyError);
    }

    ratioErr->SetTitle("");
    ratioErr  ->Draw("e2");
    
   
    
    ratio_mad      ->SetLineColor(kPink-9);
    ratio_mad      ->SetMarkerSize(1.0);
    ratio_mad      ->SetLineWidth(1);
    ratio_mad      ->SetMarkerStyle(21);
    hratio_mad     ->SetLineWidth(0);
    hratio_mad     ->SetMarkerSize (      0);  
    hratio_mad     ->SetFillColor  (kPink+1);
    hratio_mad     ->SetFillStyle  (1001);
    hratio_mad     ->Draw("e2,same");
    ratio_mad      ->Draw("e1p,same");
    
    
    ratio_mcnlo     ->SetLineColor(kRed);
    ratio_mcnlo     ->SetMarkerSize(1.0);
    ratio_mcnlo      ->SetLineWidth(1);
    ratio_mcnlo     ->SetMarkerStyle(24);
    hratio_mcnlo    ->SetLineWidth(0);
    hratio_mcnlo    ->SetMarkerSize (      0);  
    hratio_mcnlo    ->SetFillColor  (kOrange);
    hratio_mcnlo     ->SetFillStyle  (1001);
    hratio_mcnlo    ->Draw("e2,same");
    ratio_mcnlo     ->Draw("ep,same");

    ratio_pow      ->SetLineColor(kAzure-3);
    ratio_pow      ->SetMarkerSize(1.2);
    ratio_pow      ->SetLineWidth(1);
    ratio_pow      ->SetMarkerStyle(22);
    hratio_pow     ->SetLineWidth(0);
    hratio_pow     ->SetMarkerSize (      0);  
    hratio_pow     ->SetFillColor  (kAzure-9);
    hratio_pow     ->SetFillStyle  (1001);
    hratio_pow     ->Draw("e2,same");
    ratio_pow      ->Draw("e1p,same");
    
  
    
    ratioErr->SetFillColor  (kGray+2);
    ratioErr->SetFillStyle  (   3345);
    ratioErr->SetLineColor  (kGray+2);
    ratioErr->SetMarkerColor(kGray+2);
    ratioErr->SetMarkerSize (      0);

    ratioErr->Draw("sameaxis");

    ratioErr->GetYaxis()->SetRangeUser(0.4, 1.6);

   
    AxisFontsRatio (ratioErr->GetYaxis(), "y", "MC/data");
    AxisFontsRatio (ratioErr->GetXaxis(), "x", XTitle);

  }
      

}
Example #15
0
void cetaflatHFM12(int nIterN=1, double Ethr1=10, double Ethr2=150) { // for HFM, L and S separately
  // nIterN - number of iterations
  // Ethr1 and Ethr2 - E thresholds within which E is estimated
  
  gStyle->SetOptLogz(0);
  gStyle->SetMarkerSize(0.7);
  gStyle->SetMarkerStyle(20);
  gStyle->SetPadGridX(0);
  gStyle->SetPadGridY(0);
  gStyle->SetTitleOffset(1.7,"Y");
  gStyle->SetTitleOffset(0.9,"X");
  //gStyle->SetPadRightMargin(0.12);
  gStyle->SetPadRightMargin(0.03);
  gStyle->SetPadLeftMargin(0.18);
  //gStyle->SetNdivisions(516);
  gStyle->SetStatH(0.025);
  gStyle->SetStatW(0.3);
  gStyle->SetTitleW(0.4);
  gStyle->SetTitleX(0.28);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();

  char ctit[245],ftit[245];
  float etaBounds[14] = {2.853,2.964,3.139,3.314,3.489,3.664,3.839,4.013,4.191,4.363,4.538,4.716,4.889,5.205};

  // ------Histos input: spectra of all channels-----------------------------------

  //sprintf(ftit,"%s","phi43val2012A");
  //sprintf(ftit,"%s","phi2012A_May");
  //sprintf(ftit,"%s","phiSym524_2012AB");
  //sprintf(ftit,"%s","phiSym524newGain_2012AB");
  //sprintf(ftit,"%s","phiSym524newGain_2012ABC");
  //sprintf(ftit,"%s","phisymNewCond2012Cval");
  //sprintf(ftit,"%s","phisymOldCond2012Cval");
  //sprintf(ftit,"%s","phiSym533Gain507_2012D");
  //  sprintf(ftit,"%s","phiSym533Corr45Gain507_2012D");  //  histo root file processed

  //sprintf(ctit,"/home/vodib/beam12/intercal/%s.root",ftit);
  sprintf(ctit,"hcal.root",ftit);    
TFile *fila = new TFile (ctit);
  cout<<"File= "<<ctit<<endl;

  TH1F *hcounter =   new TH1F(*((TH1F*)fila->Get("phaseHF/hcounter")));
  cout<<"Stat= "<<hcounter->GetBinContent(2)<<endl;
  cout<<"E within: "<<Ethr1<<" - "<<Ethr2<<endl;

  TH2F* hLmapP = new TH2F("hLmapP","E L HFM;i#eta;i#phi",13,-41.5,-28.5,36,0,72);
  TH2F* hSmapP = new TH2F("hSmapP","E S HFM;i#eta;i#phi",13,-41.5,-28.5,36,0,72);
  TH2F* hLmapM0 = new TH2F("hLmapM0","E0 L HFM;i#eta;i#phi",13,-41.5,-28.5,36,0,72);
  TH2F* hSmapM0 = new TH2F("hSmapM0","E0 S HFM;i#eta;i#phi",13,-41.5,-28.5,36,0,72);
  TH2F* hLmapPc = new TH2F("hLmapPc","corr L HFM;i#eta;i#phi",13,-41.5,-28.5,36,0,72);
  TH2F* hSmapPc = new TH2F("hSmapPc","corr S HFM;i#eta;i#phi",13,-41.5,-28.5,36,0,72);
  hLmapPc->Sumw2(); hSmapPc->Sumw2();
  //TH1F *hLcorr1D = new TH1F("hLcorr1D","Corr L",300,0.5,2);
  //TH1F *hScorr1D = new TH1F("hScorr1D","Corr S",300,0.5,2);
  TH1F *hLcorr1D = new TH1F("hLcorr1D","Corr L",180,0.7,1.5);
  TH1F *hScorr1D = new TH1F("hScorr1D","Corr S",180,0.7,1.5);
  TH1F *hLdatP[13][36], *hSdatP[13][36], *hLdatPx[13][36], *hSdatPx[13][36];
  for (int ii=0;ii<13;ii++) for (int jj=0;jj<36;jj++) {
    sprintf(ctit,"hL%d_%d",-29-ii,2*jj+1);
    hLdatP[ii][jj] = new TH1F(ctit,ctit,8000,0,250);
    sprintf(ctit,"hS%d_%d",-29-ii,2*jj+1);
    hSdatP[ii][jj] = new TH1F(ctit,ctit,8000,0,250);
  }
  TH1F *htL = new TH1F("htL","htL",20000,0,7e8/3.);
  TH1F *htS = new TH1F("htS","htS",20000,0,5e8/3.);
  //TH1F *htL = new TH1F("htL","htL",20000,0,4e8/40);
  //TH1F *htS = new TH1F("htS","htS",20000,0,2e8/40);
  TH1F *hLdatPx[13][36], *hSdatPx[13][36];

  TCanvas *cLx[200],*cSx[200];
  TSpline5 *ttL,*ttS;

  Double_t x,y,rPL,rPS,drPL,drPS,mLE,mSE,ermean,rms;
  Double_t xxL[1000],yyL[1000];
  Double_t xxS[1000],yyS[1000];
  Int_t nELP, nESP, nIter=0;
  Double_t mcorrL,scorrL,mcorrS,scorrS,erLP,erSP,rLP,drLP,rSP,drSP,corrL,corrS,dcorrL,dcorrS;
  double mLEphi[13],mSEphi[13],dmLEphi[13],dmSEphi[13];

  TCanvas *ccxx = new TCanvas("ccxx","ccxx",100,300,900,500);
  ccxx->Divide(2,1);

  // loop over channels, 
  for (int ii=0;ii<13;ii++) {  // loop over HFM ieta (rings)
  //for (int ii=1;ii<2;ii++) {
    int ieta=-ii-29;

    mLE=mSE=0;   // ------------------for initial condition
    int nmLE=0, nmSE=0;
    htL->Reset(); htS->Reset();
    for (int ll=1;ll<=72;ll+=2) { // loop over channels within HFM ieta (ring) to get data
      int iphi=ll;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      //if (ieta==29 && iphi==67) continue;
      hSmapPc->SetBinContent(13-ii,ll/2+1,1);  //  initial correction set to 1
      hLmapPc->SetBinContent(13-ii,ll/2+1,1);
      hSmapPc->SetBinError(13-ii,ll/2+1,1.e-6);  //  non-zero err required
      hLmapPc->SetBinError(13-ii,ll/2+1,1.e-6);
      sprintf(ctit,"phaseHF/espec/E_%d_%d_1",ieta,iphi);
      hLdatPx[ii][ll/2]  =   new TH1F(*((TH1F*)fila->Get(ctit)));  // read spectrum from root file
      hLdatPx[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
      rLP = hLdatPx[ii][ll/2]->Integral()*hLdatPx[ii][ll/2]->GetMean();  // channel's total E between thresholds
      if (rLP>0) {
	htL->Fill(rLP);
	mLE += rLP;  // ring's total E between thresholds
	nmLE++;
      }
      sprintf(ctit,"phaseHF/espec/E_%d_%d_2",ieta,iphi);
      hSdatPx[ii][ll/2]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
      hSdatPx[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
      rSP = hSdatPx[ii][ll/2]->Integral()*hSdatPx[ii][ll/2]->GetMean();
      if (rSP>0) {
	htS->Fill(rSP);
	mSE += rSP;
	nmSE++;
      }
      hLmapM0->SetBinContent(13-ii,ll/2+1,rLP);
      hSmapM0->SetBinContent(13-ii,ll/2+1,rSP);
      hSdatP[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
    }
    if (nmLE>0) mLE /= nmLE; // ring's <E> 
    else continue;
    if (nmSE>0) mSE /= nmSE; 
    else continue;
    ccxx->cd(1); htL->Draw("hist");
    ccxx->cd(2); htS->Draw("hist");
    ccxx->Update();
    //histspec(htL,mLE,ermean,rms,4,3);
    //histspec(htS,mSE,ermean,rms,4,3);
    mLEphi[ii]=mLE;
    mSEphi[ii]=mSE;
    dmLEphi[ii]=htL->GetRMS();
    dmSEphi[ii]=htS->GetRMS();
    printf("ieta %2d :  <E>L= %8.1f (%6.1f) x %d    <E>S= %8.1f (%6.1f) x %d \n",
	   ieta,mLE,dmLEphi[ii],nmLE,mSE,dmSEphi[ii],nmSE);
    
    for (int jj=1;jj<=72;jj+=2) { // loop over channels within HFM ieta (ring) to get correction
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;

      for (nIter=1;nIter<nIterN;nIter++) { // loop over iterations, L channels
	corrL=hLmapPc->GetBinContent(13-ii,jj/2+1);  // correction factor
	hLdatP[ii][jj/2]->Reset();

	for (int kk=1;kk<=hLdatPx[ii][jj/2]->GetNbinsX();kk++) {
	  xxL[kk-1]=hLdatPx[ii][jj/2]->GetBinCenter(kk);
	  yyL[kk-1]=hLdatPx[ii][jj/2]->GetBinContent(kk);
	}
	ttL = new TSpline5("tt",xxL,yyL,1000,"",10,20);  // spline function over spectrum to get
	// smoother image of spectrum to improve convergence 

	for (int kk=1;kk<=hLdatP[ii][jj/2]->GetNbinsX();kk++) {
	  x=hLdatP[ii][jj/2]->GetBinCenter(kk);
	  y=hLdatP[ii][jj/2]->GetBinContent(kk);
	  hLdatP[ii][jj/2]->Fill(x*corrL,ttL->Eval(x)/8.0);  // smoother image of spectrum,
	  // with E shifted (corrected) by correction factor;
	  // factor 8 due to difference in bin size of spectrum and smoother image of spectrum.
	}
	ttL->Delete();

	hLdatP[ii][jj/2]->SetAxisRange(Ethr1,Ethr2);
	rLP = hLdatP[ii][jj/2]->Integral()*hLdatP[ii][jj/2]->GetMean(); // E of corrected spectrum 
	dcorrL=(rLP-mLE)/mLE;  // estimator of difference between <E> and E of corrected spectrum
	if (rLP>0) drLP=
	      sqrt(pow(hLdatP[ii][jj/2]->GetMeanError()/hLdatP[ii][jj/2]->GetMean(),2)+
		   1.f/hLdatP[ii][jj/2]->Integral()+
		   pow(dcorrL/(1.0+sqrt((float) nIter)),2));
	else drLP=1.e-6;
	if (fabs(dcorrL)>0.001) { 
	  corrL*=1-dcorrL/(1.0+sqrt((float) nIter));  // new correction factor
	  //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrL,corrL);
	  hLmapPc->SetBinContent(13-ii,jj/2+1,corrL);
	  hLmapPc->SetBinError(13-ii,jj/2+1,corrL*drLP);
	  hLmapP->SetBinContent(13-ii,jj/2+1,rLP);
	}
	else {
	  printf("%2d : %2d / %2d / 1 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
	  hLmapP->SetBinContent(13-ii,jj/2+1,rLP);
	  hLmapPc->SetBinError(13-ii,jj/2+1,corrL*drLP);
	  break;
	}
	if (nIter==nIterN-1) {
	  printf("%2d : %2d / %2d / 1 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
	}
      }

      for (nIter=1;nIter<nIterN;nIter++) { 
	corrS=hSmapPc->GetBinContent(13-ii,jj/2+1);
	hSdatP[ii][jj/2]->Reset();

	for (int kk=1;kk<=hSdatPx[ii][jj/2]->GetNbinsX();kk++) {
	  xxS[kk-1]=hSdatPx[ii][jj/2]->GetBinCenter(kk);
	  yyS[kk-1]=hSdatPx[ii][jj/2]->GetBinContent(kk);
	}
	ttS = new TSpline5("tt",xxS,yyS,1000,"",10,20);

	for (int kk=1;kk<=hSdatP[ii][jj/2]->GetNbinsX();kk++) {
	  x=hSdatP[ii][jj/2]->GetBinCenter(kk);
	  y=hSdatP[ii][jj/2]->GetBinContent(kk);
	  hSdatP[ii][jj/2]->Fill(x*corrS,ttS->Eval(x)/8.0);
	}
	ttS->Delete();

	hSdatP[ii][jj/2]->SetAxisRange(Ethr1,Ethr2);
	rSP = hSdatP[ii][jj/2]->Integral()*hSdatP[ii][jj/2]->GetMean();
	dcorrS=(rSP-mSE)/mSE;
	if (rSP>0) drSP=sqrt(pow(hSdatP[ii][jj/2]->GetMeanError()/hSdatP[ii][jj/2]->GetMean(),2)+
			     1.f/hSdatP[ii][jj/2]->Integral()+
			     pow(dcorrS/(1.0+sqrt((float) nIter)),2));
	else drSP=1.e-6;
	if (fabs(dcorrS)>0.001) { 
	  corrS*=1-dcorrS/(1.0+sqrt((float) nIter));
	  //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrS,corrS);
	  hSmapPc->SetBinContent(13-ii,jj/2+1,corrS);
	  hSmapPc->SetBinError(13-ii,jj/2+1,corrS*drSP);
	  hSmapP->SetBinContent(13-ii,jj/2+1,rSP);
	}
	else {
	  printf("%2d : %2d / %2d / 2 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrS,corrS,corrS*drSP);
	  hSmapP->SetBinContent(13-ii,jj/2+1,rSP);
	  hSmapPc->SetBinError(13-ii,jj/2+1,corrS*drSP);
	  break;
	}
	if (nIter==nIterN-1) {
	  printf("%2d : %2d / %2d / 2 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrS,corrS,corrS*drSP);
	}
      }
    }
  }
  //fila->Close();

  cout<<endl<<"Rings :  "<<endl;
  cout<<"       E L        "<<"E S        "<<"eta     "<<"delta eta"<<endl;
  double xeta[13], weta[13], reta[13];
  for (int i=0;i<13;i++) {
    xeta[i]=-(etaBounds[i+1]+etaBounds[i])/2;
    weta[i]=(etaBounds[i+1]-etaBounds[i]);
    mLEphi[i]=mLEphi[i]*36/weta[i];
    mSEphi[i]=mSEphi[i]*36/weta[i];
    dmLEphi[i]=dmLEphi[i]*36/weta[i];
    dmSEphi[i]=dmSEphi[i]*36/weta[i];
    if (i>10) {  mLEphi[i]/=2; mSEphi[i]/=2; dmLEphi[i]/=2; dmSEphi[i]/=2; }
    reta[i] = mSEphi[i]/mLEphi[i];
    cout<<i<<" :  "<<mLEphi[i]<<"    "<<mSEphi[i]<<"    "<<xeta[i]<<"   "<<weta[i]<<endl;
  }
  TCanvas *cgL = new TCanvas("cgL","cgL",300,300,600,600);
  TGraphErrors *grL = new TGraphErrors(13,xeta,mLEphi,0,dmLEphi);
  grL->SetName("grL");
  grL->SetTitle("HFM L;#eta;E_{Ring} / #Delta#eta_{Ring} ,  GeV");
  grL->SetMinimum(0);
  grL->SetMarkerStyle(20);
  grL->Draw("1+PAl");
  cgL->Print("pictHFplot/etaProfHFML.gif");
  //cgL->Print("pictHFmc/etaProfHFML.gif");
  mSEphi[12]/=2; mSEphi[11]/=2;
  TCanvas *cgS = new TCanvas("cgS","cgS",300,300,600,600);
  TGraphErrors *grS = new TGraphErrors(13,xeta,mSEphi,0,dmSEphi);
  grS->SetName("grS");
  grS->SetTitle("HFM S;#eta;E_{Ring} / #Delta#eta_{Ring} ,  GeV");
  grS->SetMinimum(0);
  grS->SetMarkerStyle(20);
  grS->Draw("1+PAl");
  cgS->Print("pictHFplot/etaProfHFMS.gif");
  //cgS->Print("pictHFmc/etaProfHFMS.gif");
  TCanvas *crg = new TCanvas("crg","crg",300,300,600,600);
  TGraphErrors *rg = new TGraphErrors(13,xeta,reta,0,0);
  rg->SetTitle("HFM;#eta;E(S) / E(L)");
  rg->SetMinimum(0);
  rg->Draw("1+PAl");
  crg->Print("pictHFplot/SoverLetaHFM.gif");
  //crg->Print("pictHFmc/SoverLetaHFM.gif");

  TCanvas *cL0 = new TCanvas("cL0","cL0",0,0,650,600);
  hLmapM0->Draw("colz");
  cL0->Update();
  TCanvas *cS = new TCanvas("cS0","cS0",1000,0,650,600);
  hSmapM0->Draw("colz");
  cS0->Update();

  //TFile *histf = new TFile("HFMmc.root","RECREATE");

  FILE *ft1;
  //sprintf(ctit,"corrHFMmc_%d_%d.txt",((int) Ethr1),((int) Ethr2));
  sprintf(ctit,"corrHFM_%s_%d_%d.txt",ftit,((int) Ethr1),((int) Ethr2));
  if ((ft1 = fopen(ctit,"w"))==NULL){               // Open new file
    printf("\nNo file %s open => EXIT\n\n",file);
    return;
  }
  printf("\n\n File '%s' open \n\n",ctit);

  TH1D *hprL[13],*hprS[13],*hprL0[13],*hprS0[13];
  TH1D *hprcL[13],*hprcS[13];
  TCanvas *cpr[13],*ccc[13];
  TLine *lin1 = new TLine(0,1,71,1); lin1->SetLineWidth(1);

  int noff=0;
  for (int ii=0;ii<13;ii++) {
    int ieta=-ii-29;

    sprintf(ctit,"HFMcorr_%d_L",-ii-29);  // draw corrections
    hprcL[ii] = hLmapPc->ProjectionY(ctit,13-ii,13-ii);
    hprcL[ii]->SetTitle(ctit);
    sprintf(ctit,"HFMcorr_%d_S",-ii-29);
    hprcS[ii] = hSmapPc->ProjectionY(ctit,13-ii,13-ii);
    hprcS[ii]->SetTitle(ctit);
    ccc[ii] = new TCanvas(ctit,ctit,800,100,500,900);
    ccc[ii]->Divide(1,2);
    ccc[ii]->cd(1);
    if (abs(ieta)>39) {
      hprcL[ii]->Rebin(2);
      hprcS[ii]->Rebin(2);
    }
    hprcL[ii]->SetMinimum(0);
    hprcL[ii]->SetTitleOffset(0.9,"X");
    hprcL[ii]->Draw("e");
    lin1->Draw();
    ccc[ii]->cd(2);
    hprcS[ii]->SetMinimum(0);
    hprcS[ii]->SetTitleOffset(0.9,"X");
    hprcS[ii]->Draw("e");
    lin1->Draw();
    sprintf(ctit,"pictHFplot/HFMcorr_%d.gif",ii+29);
    //sprintf(ctit,"pictHFmc/HFMcorr_%d.gif",ii+29);
    ccc[ii]->Update();
    ccc[ii]->Print(ctit);
    //hprcL[ii]->Write();
    //hprcS[ii]->Write();

    sprintf(ctit,"HFM_%d_L",-29-ii);  //  draw E depositions
    hprL0[ii] = hLmapM0->ProjectionY(ctit,13-ii,13-ii);
    sprintf(ctit,"HFM_%d_L;i#phi;GeV;",-29-ii);  //  draw E depositions
    hprL0[ii]->SetTitle(ctit);
    sprintf(ctit,"HFM_L_%d",-29-ii);
    hprL[ii] = hLmapP->ProjectionY(ctit,13-ii,13-ii);
    sprintf(ctit,"HFM_%d_S",-29-ii);
    hprS0[ii] = hSmapM0->ProjectionY(ctit,13-ii,13-ii);
    sprintf(ctit,"HFM_%d_S;i#phi;GeV;",-29-ii);  //  draw E depositions
    hprS0[ii]->SetTitle(ctit);
    sprintf(ctit,"HFM_S_%d",-29-ii);
    hprS[ii] = hSmapP->ProjectionY(ctit,13-ii,13-ii);

    cpr[ii] = new TCanvas(ctit,ctit,800,100,500,900);
    cpr[ii]->Divide(1,2);
    cpr[ii]->cd(1);
    if (abs(ieta)>39) {
      hprL0[ii]->Rebin(2);
      hprL[ii]->Rebin(2);
      hprS0[ii]->Rebin(2);
      hprS[ii]->Rebin(2);
    }
    hprL0[ii]->SetFillColor(3);hprL0[ii]->SetLineColor(3);hprL0[ii]->SetLineWidth(3);
    hprL0[ii]->SetMinimum(0);
    hprL0[ii]->SetTitleOffset(0.9,"X");
    hprL0[ii]->Draw("hist");
    hprL[ii]->Draw("samehist");
    cpr[ii]->cd(2);
    hprS0[ii]->SetMinimum(0);
    hprS0[ii]->SetTitleOffset(0.9,"X");
    hprS0[ii]->SetFillColor(3);hprS0[ii]->SetLineColor(3);hprS0[ii]->SetLineWidth(3);
    hprS0[ii]->Draw("hist");
    hprS[ii]->Draw("samehist");
    sprintf(ctit,"pictHFplot/HFM_%d.gif",ii+29);
    //sprintf(ctit,"pictHFmc/HFM_10_100G_%d.gif",ii+29);
    cpr[ii]->Update();
    cpr[ii]->Print(ctit);
    //hprS0[ii]->Write();
    //hprL0[ii]->Write();

    cout<<"Results : "<<endl;
    for (int jj=1;jj<=72;jj+=2) {
      int ieta=-ii-29;
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      //if (ieta==29 && iphi==67) continue;
      corrL=hLmapPc->GetBinContent(13-ii,jj/2+1);
      corrS=hSmapPc->GetBinContent(13-ii,jj/2+1);
      dcorrL=hLmapPc->GetBinError(13-ii,jj/2+1);
      dcorrS=hSmapPc->GetBinError(13-ii,jj/2+1);
      // -------------------------------------------------------------- !!!
      //if (abs(ieta)>29 && abs(ieta)<41) 
      hLcorr1D->Fill(corrL); 
      hScorr1D->Fill(corrS);
      noff++;
      //printf("%2d : %2d / %2d / 1 %9.4f %9.4f\n",noff,ieta,iphi,corrL,dcorrL);
      fprintf(ft1,"%2d   %2d   1 %9.4f %9.4f\n",ieta,iphi,corrL,dcorrL);
      noff++;
      //printf("%2d : %2d / %2d / 2 %9.4f %9.4f\n",noff,ieta,iphi,corrS,dcorrS);
      fprintf(ft1,"%2d   %2d   2 %9.4f %9.4f\n",ieta,iphi,corrS,dcorrS);
    }
  }
  fclose(ft1);

  for (int ii=0;ii<13;ii++) for (int jj=1;jj<=72;jj+=2) {
      int ieta=-ii-29;
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      //if (ieta==29 && iphi==67) continue;
      corrL=hLmapPc->GetBinContent(13-ii,jj/2+1);
      if (fabs(corrL-1)>0.16) printf("%2d / %2d / 1 %9.4f %9.4f\n",ieta,iphi,corrL,dcorrL);
      corrS=hSmapPc->GetBinContent(13-ii,jj/2+1);
      if (fabs(corrS-1)>0.16) printf("%2d / %2d / 2 %9.4f %9.4f\n",ieta,iphi,corrS,dcorrS);
  }

  TCanvas *cLcorr =new TCanvas("cLcorr","cLcorr",30,30,600,600);
  cLcorr->SetRightMargin(0.12);
  hLmapPc->SetAxisRange(0.6,1.6,"Z");
  hLmapPc->Draw("colz");
  TCanvas *cScorr =new TCanvas("cScorr","cScorr",30,300,600,600);
  cScorr->SetRightMargin(0.12);
  hSmapPc->SetAxisRange(0.6,1.6,"Z");
  hSmapPc->Draw("colz");

  TCanvas *cL = new TCanvas("cL","cL",0,0,650,600);
  hLmapP->Draw("colz");
  cL->Update();
  TCanvas *cS = new TCanvas("cS","cS",1000,0,650,600);
  hSmapP->Draw("colz");
  cS->Update();
  
  TCanvas *c1corr =new TCanvas("c1corr","c1corr",30,30,900,500);
  c1corr->Divide(2,1);
  c1corr->cd(1);  hLcorr1D->Draw("hist");  histStat(hLcorr1D,1);
  c1corr->cd(2);  hScorr1D->Draw("hist");  histStat(hScorr1D,1);
  c1corr->Print("pictHFplot/corrHFM.gif");
  //c1corr->Print("pictHFmc/corrM.gif");
  c1corr->Update();
  
  //fila->Close();
  //histf->Close();

  sprintf(ctit,"HFMo_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
  TFile *histf = new TFile(ctit,"RECREATE");
  hLcorr1D->Write(); 
  hScorr1D->Write();  
  hLmapP->Write(); 
  hLmapM0->Write(); 
  hLmapPc->Write(); 
  hSmapP->Write(); 
  hSmapM0->Write(); 
  hSmapPc->Write(); 
  grL->Write();
  grS->Write();
  histf->Close();
}
void hand_target_asymmetry(){

	bool includeVetos;
// 	If includeVetos = false, then only good bars will be displayed. If 
//	includeVetos = true, then veto bars will be shown along with the good bars.
	includeVetos = true;
//	includeVetos = false;

	bool includeAntivetos;
// 	If includeAntivetos = false, then only good bars will be displayed. If 
//	includeAntivetos = true, then antiveto bars will be shown along with the good bars.
//	includeAntivetos = true;
	includeAntivetos = false;

	bool antivetosAsVetos;
//	If antivetosAsVetos = false, then the antivetos will not be included in the veto cut
//	If antivetosAsVetos = true, then the antivetos will be included in the veto cut
//	Discusses elsewhere, antivetos are the bars immediately following a goodBar
	antivetosAsVetos = false;
//	antivetosAsVetos = true;

	bool drawCuts = true;
//	bool drawCuts = false;

// 	The SinglePlane and SingleBar booleans skip the loop that goes over
// 	ever bar into just a single plane and/or a single bar.
	bool SinglePlane;
	bool SingleBar;
	int singleplane;
	int singlebar;
//	SinglePlane = true;
	SinglePlane = false;
	singleplane = 2;
//	SingleBar = true;
	SingleBar = false;
	singlebar = 10;
/*
	int HeRunNumber = 22441;
	int endHeRunNumber = 22441;
	TString Q2 = "1.0";
	double q2min = 0.75;
	double q2max = 1.2;
	double numin = 0.3;
	double numax = 0.7;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 100;
	double TDCmin = 700;
	double TDCmax = 800;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 752;
	double goodTDCleftcutmax = 775;
	double goodTDCrightcutmin = 752;
	double goodTDCrightcutmax = 775;
	double vetoTDCcutmin = 750;
	double vetoTDCcutmax = 785;
*/
/*
// ********* Vertical, Q2=1.0 *******************
	int HeRunNumber = 20596;
	int endHeRunNumber = 20683;
	TString Q2 = "1.0";
	double q2min = 0.75;
	double q2max = 1.2;
	double numin = 0.3;
	double numax = 0.7;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 200;
	double TDCmin = 1300;
	double TDCmax = 1700;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 1385;
	double goodTDCleftcutmax = 1415;
	double goodTDCrightcutmin = 1385;
	double goodTDCrightcutmax = 1415;
	double vetoTDCcutmin = 1385;
	double vetoTDCcutmax = 1415;
*/
/*
// ********* Vertical, Q2=0.5 *******************
	int HeRunNumber = 20890;
	int endHeRunNumber = 20890;
	TString Q2 = "0.5";
	double q2min = 0.3;
	double q2max = 0.6;
	double numin = 0.1;
	double numax = 0.35;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 75;
	double TDCmin = 1300;
	double TDCmax = 1500;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 1385;
	double goodTDCleftcutmax = 1415;
	double goodTDCrightcutmin = 1385;
	double goodTDCrightcutmax = 1415;
	double vetoTDCcutmin = 1385;
	double vetoTDCcutmax = 1415;
*/

/*
// ********* Vertical, Q2=0.42 *******************
	int HeRunNumber = 21383;
	int endHeRunNumber = 21387;
	TString Q2 = "0.42";
	double q2min = 0.33;
	double q2max = 0.51;
	double numin = 0.17;
	double numax = 0.3;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 50;
	double TDCmin = 700;
	double TDCmax = 800;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 730;
	double goodTDCleftcutmax = 770;
	double goodTDCrightcutmin = 740;
	double goodTDCrightcutmax = 780;
	double vetoTDCcutmin = 730;
	double vetoTDCcutmax = 770;
*/
/*
	int HeRunNumber = 21714;
	int endHeRunNumber = 22248;
	TString Q2 = "0.52";
	double q2min = 0.33;
	double q2max = 0.62;
	double numin = 0.17;
	double numax = 0.35;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 50;
	double TDCmin = 700;
	double TDCmax = 800;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 730;
	double goodTDCleftcutmax = 770;
	double goodTDCrightcutmin = 740;
	double goodTDCrightcutmax = 780;
	double vetoTDCcutmin = 730;
	double vetoTDCcutmax = 770;
*/

// ********* Transverse, Q2=1.0 *******************
	int HeRunNumber = 22447;
	int endHeRunNumber = 22447;
	TString Q2 = "1.0";
	double q2min = 0.75;
	double q2max = 1.2;
	double numin = 0.3;
	double numax = 0.7;
	int Positionbins = 30;
	double Positionmin = -30;
	double Positionmax = 30;
	int TDCbins = 100;
	double TDCmin = 650;
	double TDCmax = 850;
	int ADCbins = 700;
	double ADCmin = -100;
	double ADCmax = 11100;
	double goodTDCleftcutmin = 745;
	double goodTDCleftcutmax = 775;
	double goodTDCrightcutmin = 750;
	double goodTDCrightcutmax = 780;
	double vetoTDCcutmin = 745;
	double vetoTDCcutmax = 780;



	const int xBjbins = 50;
	double xBjmin = 0.6;
	double xBjmax = 1.6;

	double xmin = 0.6;
	double xmax = 3.0;

	int bins = 50;

	TString outputPlotsHere = "/home/ellie/physics/e05-102/images/plots_for_hand/hand_target_asymmetry/";

	TString asymOutFileName = outputPlotsHere;
	asymOutFileName += "target_asymmetry_for_runs_";
	asymOutFileName += HeRunNumber;
	asymOutFileName += "-";
	asymOutFileName += endHeRunNumber;
	asymOutFileName += ".txt";
	ofstream asymOutFile;
	asymOutFile.open(asymOutFileName);

	// Although declared here, the goodTDCcut is actually made down below where  it can be included
	// in the loop so that it is easy to have it change for each good bar when done one at a time.
	// However, the left and right min and max TDC values are defined here
	TCut goodTDCcut = "";

	TChain* chainHe = new TChain("T");
	TString filenameHe;

	for (int thisHeRunNumber=HeRunNumber; thisHeRunNumber<(endHeRunNumber+1); thisHeRunNumber++)
	{
		// Skipping Vertical Non-Production Runs
		if(thisHeRunNumber==20591){thisHeRunNumber=20596;}
		if(thisHeRunNumber==20731){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20732){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20733){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20734){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20736){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20737){thisHeRunNumber=20738;}
		if(thisHeRunNumber==20762){thisHeRunNumber=20789;}
		if(thisHeRunNumber==20763){thisHeRunNumber=20789;}
		if(thisHeRunNumber==20764){thisHeRunNumber=20789;}
		if(thisHeRunNumber==20791){thisHeRunNumber=20814;}
		if(thisHeRunNumber==20792){thisHeRunNumber=20814;}

		// Skipping Longitudinal Non-Production Runs
		if(thisHeRunNumber==22380){thisHeRunNumber=22393;}
		if(thisHeRunNumber==22389){thisHeRunNumber=22393;}
		if(thisHeRunNumber==22425){thisHeRunNumber=22436;}
		if(thisHeRunNumber==22426){thisHeRunNumber=22436;}

		// Skipping Transverse Non-Production Runs
		if(thisHeRunNumber==22461){thisHeRunNumber=22465;}


		for (int t=0; t<1000; t++)
		{
			filenameHe = "/home/ellie/physics/e05-102/ellana/ROOTfiles/e05102_R_";
			filenameHe += thisHeRunNumber;
			if (t != 0)
			{
				filenameHe += "_";
				filenameHe += t;
			}
			filenameHe += ".root";
			ifstream ifileHe(filenameHe);
			if (ifileHe)
			{
				cout << "Adding file to chainHe: " << filenameHe << endl;
				chainHe->Add(filenameHe);
			}
			else
			{
				cout << "File " << filenameHe << " does not exist. Ending here." << endl;
				t=999999999;
			}
			TFile fileHe(filenameHe);
		}
	}

	gStyle->SetPalette(1);

	TCut cut = ""; TCut kinematics = ""; TCut eventtype = ""; TCut dp = ""; TCut target = "";
	TCut tracks = ""; TCut thph = ""; TCut xbj = ""; TCut pssh = ""; TCut cerenkov = "";
	TCut q2nu = ""; TCut basic = ""; TCut cuts = "";

	TString imageCutsTitle = outputPlotsHere;
	imageCutsTitle += "HAND_plots_Run_Num_";
	imageCutsTitle += HeRunNumber;
	imageCutsTitle += "-";
	imageCutsTitle += endHeRunNumber;
	imageCutsTitle += "_basic_cuts";
	if (includeVetos) imageCutsTitle += "_with_vetos";
	if (includeAntivetos) {imageCutsTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {imageCutsTitle += "_as_vetos";}
	imageCutsTitle += ".png";

	hand_basic_cuts(cut, kinematics, eventtype, dp, target, tracks, thph, xbj, pssh, cerenkov, q2nu, basic, cuts, imageCutsTitle, HeRunNumber, endHeRunNumber, chainHe, numin, numax, q2min, q2max, bins, xmin, xmax, drawCuts, Q2);
	TString cutstring = TString(cuts);
	cout << "Cuts: " << cutstring << endl;
// **********************************************************************************************
	gStyle->SetOptFit(1111);
        TString veto1plane = "";
        TString veto1bar = "";
        TString veto2plane = "";
        TString veto2bar = "";
        TString veto3plane = "";
        TString veto3bar = "";
        TString veto4plane = "";
        TString veto4bar = "";
        TString veto5plane = "";
        TString veto5bar = "";
        TString veto6plane = "";
        TString veto6bar = "";
        TString antiveto1plane = "";
        TString antiveto1bar = "";
        TString antiveto2plane = "";
        TString antiveto2bar = "";
        TString antiveto3plane = "";
        TString antiveto3bar = "";
        TString allVetos = "";
        TString allAntivetos = "";
        TString vetoTDCslSt = "";
        TString vetoTDCsrSt = "";
        TCut vetoTDCsl = "";
        TCut vetoTDCsr = "";
        TCut vetoTDCs = "";
        TString antivetosTDCslSt = "";
        TString antivetosTDCsrSt = "";
	int maxbars = 0;
	int vetoplane = 0;
	int padBins = 0;
	double padMin = 0;
	double padMax = 0;

// **********************************************************************************************
// This bit of code should set the charge and livetime scaling factors
	double HeChargeScale = 0; double Helivetime = 0;
	double HeChargeScaleUp = 0; double HelivetimeUp = 0;
	double HeChargeScaleDown = 0; double HelivetimeDown = 0;
	hand_scaling_factors(HeRunNumber, endHeRunNumber, HeChargeScale, Helivetime, HeChargeScaleUp, HelivetimeUp, HeChargeScaleDown, HelivetimeDown);
	HeChargeScale = 0.00001 * int(HeChargeScale * 100000.0 + 0.5);
	HeChargeScaleUp = 0.00001 * int(HeChargeScaleUp * 100000.0 + 0.5);
	HeChargeScaleDown = 0.00001 * int(HeChargeScaleDown * 100000.0 + 0.5);
	Helivetime = 0.0001 * int(Helivetime * 10000.0 + 0.5);
	HelivetimeUp = 0.0001 * int(HelivetimeUp * 10000.0 + 0.5);
	HelivetimeDown = 0.0001 * int(HelivetimeDown * 10000.0 + 0.5);
	cout << "HeChargeScale: " << HeChargeScale << "C, Helivetime: " << Helivetime << endl;
	cout << "HeChargeScaleUp: " << HeChargeScaleUp << "C, HelivetimeUp: " << HelivetimeUp << endl;
	cout << "HeChargeScaleDown: " << HeChargeScaleDown << "C, HelivetimeDown: " << HelivetimeDown << endl;
// **********************************************************************************************

// The section below plots the HAND data
// **********************************************************************************************
//	int whichplane = 0;
	int whichplane = 1;
	int endplane = 5;
	if (SinglePlane) {whichplane = singleplane; endplane = singleplane+1;}
	int whichbar=0;
//	int whichbar=11;
	TString titleTotalSpinUpx = "Total Spin Up vs. xBj";
	if (includeVetos) {titleTotalSpinUpx += " with vetos";}
	else {titleTotalSpinUpx += " without vetos";}
	titleTotalSpinUpx += " with goodTDC cuts";
	cout << "Drawing " << titleTotalSpinUpx << "..." << endl;
	TString plotTotalSpinUpx = "HANDTotalSpinUpx";
	TH1F *HANDTotalSpinUpx = new TH1F(plotTotalSpinUpx,titleTotalSpinUpx,xBjbins,xBjmin,xBjmax);
	TString titleTotalSpinDownx = "Total Spin Down vs. xBj";
	if (includeVetos) {titleTotalSpinDownx += " with vetos";}
	else {titleTotalSpinDownx += " without vetos";}
	titleTotalSpinDownx += " with goodTDC cuts";
	cout << "Drawing " << titleTotalSpinDownx << "..." << endl;
	TString plotTotalSpinDownx = "HANDTotalSpinDownx";
	TH1F *HANDTotalSpinDownx = new TH1F(plotTotalSpinDownx,titleTotalSpinDownx,xBjbins,xBjmin,xBjmax);

	for (int nplane=whichplane; nplane<endplane; nplane++)
	{
		if (nplane==0) maxbars=32;
		if (nplane==1) maxbars=30;
		if (nplane==2) maxbars=24;
		if (nplane==3) maxbars=22;
		if (nplane==4) maxbars=12;
		if (SingleBar) {whichbar = singlebar; maxbars = singlebar + 1;}
		for (int thisbar=whichbar; thisbar<maxbars; thisbar++)
		{

			TString goodPlane = nplane;
			TString goodPMT = thisbar;
			hand_define_vetos(includeVetos, includeAntivetos, antivetosAsVetos, nplane, thisbar, veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane, veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, antiveto1plane, antiveto2plane, antiveto3plane, antiveto1bar, antiveto2bar, antiveto3bar, allVetos, allAntivetos, vetoTDCslSt, vetoTDCsrSt, vetoTDCsl, vetoTDCsr, vetoTDCs, vetoTDCcutmin, vetoTDCcutmax, antivetosTDCslSt, antivetosTDCsrSt);

			TString goodBar = "nd.p";
			goodBar += nplane;
			goodBar += ".";
			goodBar += thisbar;
			goodBar += " ";
			cout << "Good Bar: " << goodBar << endl;

			TString goodTDCl = "NA.nd.p";
			goodTDCl += nplane;
			if (nplane == 0) goodTDCl = "NA.veto";
			goodTDCl += ".lt_c[";
			goodTDCl += thisbar;
			goodTDCl += "]";
			TString goodTDCr = "NA.nd.p";
			goodTDCr += nplane;
			if (nplane == 0) goodTDCr = "NA.veto";
			goodTDCr += ".rt_c[";
			goodTDCr += thisbar;
			goodTDCr += "]";
			TString goodTDCs = goodTDCl;
			goodTDCs += ":";
			goodTDCs += goodTDCr;
		
                        TString goodADCl = "NA.nd.p";
                        goodADCl += nplane;
                        if (nplane == 0) goodADCl = "NA.veto";
                        goodADCl += ".la_c[";
                        goodADCl += thisbar;
                        goodADCl += "]";
                        TString goodADCr = "NA.nd.p";
                        goodADCr += nplane;
                        if (nplane == 0) goodADCr = "NA.veto";
                        goodADCr += ".ra_c[";
                        goodADCr += thisbar;
                        goodADCr += "]";
                        TString goodADCs = goodADCl;
                        goodADCs += ":";
                        goodADCs += goodADCr;
	
			TString canvasName = "handp";
			canvasName += nplane;
			canvasName += "b";
			canvasName += thisbar;
			TString canvasTitle = "HAND - Plane ";
			canvasTitle += nplane;
			canvasTitle += ", Bar ";
			canvasTitle += thisbar;
			TCanvas *handCanvas = new TCanvas(canvasName,canvasTitle,1400,770); //x,y
			handpad01 =  new TPad("handpad01","handpad01",0.0000,0.0000,0.1000,1.0000,0,0,0);
			handpad02 =  new TPad("handpad02","handpad02",0.1000,0.6666,0.5500,1.0000,0,0,0);
			handpad03 =  new TPad("handpad03","handpad03",0.5500,0.6666,1.0000,1.0000,0,0,0);
			handpad04 =  new TPad("handpad04","handpad04",0.1000,0.3333,0.5500,0.6666,0,0,0);
			handpad05 =  new TPad("handpad05","handpad05",0.5500,0.3333,1.0000,0.6666,0,0,0);
			handpad06 =  new TPad("handpad06","handpad06",0.1000,0.0000,0.5500,0.3333,0,0,0);
			handpad07 =  new TPad("handpad07","handpad07",0.5500,0.0000,1.0000,0.3333,0,0,0);
			handpad01->Draw(); handpad02->Draw(); handpad03->Draw(); handpad04->Draw(); handpad05->Draw();
			handpad06->Draw(); handpad07->Draw();

			// This section will run hand_draw.h which will draw the HAND in handpad01.
			handpad01->cd();
			hand_draw(HeRunNumber, endHeRunNumber, antivetosAsVetos, allVetos, goodBar, allAntivetos);
			handpad01->Update();

			TString goodTDCleftcutString = "(NA.nd.p";
			goodTDCleftcutString += nplane;
			if (nplane == 0) {goodTDCleftcutString = "(NA.veto";}
			goodTDCleftcutString += ".lt_c[";
			goodTDCleftcutString += thisbar;
			goodTDCleftcutString += "]>";
			goodTDCleftcutString += goodTDCleftcutmin;
			if (nplane > 0)
			{
				goodTDCleftcutString += " && NA.nd.p";
				goodTDCleftcutString += nplane;
			}
			if (nplane == 0) {goodTDCleftcutString += " && NA.veto";}
			goodTDCleftcutString += ".lt_c[";
			goodTDCleftcutString += thisbar;
			goodTDCleftcutString += "]<";
			goodTDCleftcutString += goodTDCleftcutmax;
			goodTDCleftcutString += ")";
			cout << "goodTDCleftcutString = " << goodTDCleftcutString << endl;
			TCut goodTDCleftcut = goodTDCleftcutString;
	
			TString goodTDCrightcutString = "(NA.nd.p";
			goodTDCrightcutString += nplane;
			if (nplane == 0) {goodTDCrightcutString = "(NA.veto";}
			goodTDCrightcutString += ".rt_c[";
			goodTDCrightcutString += thisbar;
			goodTDCrightcutString += "]>";
			goodTDCrightcutString += goodTDCrightcutmin;
			if (nplane > 0)
			{
				goodTDCrightcutString += " && NA.nd.p";
				goodTDCrightcutString += nplane;
			}
			if (nplane == 0) {goodTDCrightcutString += " && NA.veto";}
			goodTDCrightcutString += ".rt_c[";
			goodTDCrightcutString += thisbar;
			goodTDCrightcutString += "]<";
			goodTDCrightcutString += goodTDCrightcutmax;
			goodTDCrightcutString += ")";
			cout << "goodTDCrightcutString = " << goodTDCrightcutString << endl;
			TCut goodTDCrightcut = goodTDCrightcutString;
		
			TString firstTrackString = "NA.tr.firstplane==";
			firstTrackString += (nplane - 1);
			firstTrackString += " && NA.tr.firstpad==";
			firstTrackString += thisbar;
			TCut firstTrack = firstTrackString;

	
			goodTDCcut = (goodTDCleftcut || goodTDCrightcut);

//			cout << "Cuts: " << cutstring << endl;
			TString vetoCutString = TString(vetoTDCs);
//			cout << "Veto Cuts: " << vetoCutString << endl; 

			handpad02->cd();
			TString titleHANDleft = "Left TDC for Plane #";
			titleHANDleft += nplane;
			titleHANDleft += ", PMT # ";
			titleHANDleft += thisbar;
			if (includeVetos) {titleHANDleft += " with vetos";}
			else {titleHANDleft += " without vetos";}
			cout << "Drawing " << titleHANDleft << "..." << endl;
			TString plotHANDleft = "HANDleft_p";
			plotHANDleft += nplane;
			plotHANDleft += "_b";
			plotHANDleft += thisbar;
			TString plotHANDleftcut = plotHANDleft;
			plotHANDleftcut += "_cut";
//			cout << "plotHANDleft: " << plotHANDleft << ", plotHANDleftcut: " << plotHANDleftcut << endl;
			cout << "goodTDCl: " << goodTDCl << endl;
			TH1F *HANDleft = new TH1F(plotHANDleft,titleHANDleft,TDCbins,TDCmin,TDCmax);
			HANDleft->SetMinimum(0);
			TH1F *HANDleftcut = new TH1F(plotHANDleftcut,titleHANDleft,TDCbins,TDCmin,TDCmax);
			HANDleftcut->SetMinimum(0);
			TString HANDleftTDC = goodTDCl;
			HANDleftTDC += ">>";
			HANDleftTDC += plotHANDleft;
			TString HANDleftTDCcut = goodTDCl;
			HANDleftTDCcut += ">>";
			HANDleftTDCcut += plotHANDleftcut;
			chainHe->Draw(HANDleftTDC, cuts && vetoTDCs,"");
//			chainHe->Draw(HANDleftTDC, vetoTDCs,"");
//			HANDleft->Scale(1/(HeChargeScale*Helivetime));
			HANDleft->Draw();
			chainHe->Draw(HANDleftTDCcut, cuts && vetoTDCs && goodTDCleftcut && firstTrack,"same");
			HANDleftcut->SetFillColor(kViolet);
//			HANDleftcut->Scale(1/(HeChargeScale*Helivetime));
			HANDleftcut->Draw("same");
			// ********************************************************************************
			// This section below gathers and prints some statistics on the plot
			double numHANDleftcutEvents = 0;
			for (int i=0; i<TDCbins; i++){ numHANDleftcutEvents = numHANDleftcutEvents + HANDleftcut->GetBinContent(i);}
			TString HANDleftFactorsString = "Total Charge for Runs: ";
			HANDleftFactorsString += HeChargeScale;
			HANDleftFactorsString += " C";
			TString HANDleftFactorsString1 = "Total Livetime for Runs: ";
			HANDleftFactorsString1 += Helivetime;
			TString HANDleftFactorsString2 = "# of Cut (Purple) Events: ";
			HANDleftFactorsString2 += numHANDleftcutEvents;
			HANDleftFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
			TText *t1 = HANDleftFactors->AddText(HANDleftFactorsString);
			TText *t2 = HANDleftFactors->AddText(HANDleftFactorsString1);
			TText *t2 = HANDleftFactors->AddText(HANDleftFactorsString2);
			HANDleftFactors->Draw("same");
			// ********************************************************************************
			handpad02->Update();

			handpad03->cd();
			TString titleHANDright = "Right TDC for Plane #";
			titleHANDright += nplane;
			titleHANDright += ", PMT # ";
			titleHANDright += thisbar;
			if (includeVetos) {titleHANDright += " with vetos";}
			else {titleHANDright += " without vetos";}
			TString plotHANDright = "HANDright_p";
			plotHANDright += nplane;
			plotHANDright += "_b";
			plotHANDright += thisbar;
			TString plotHANDrightcut = plotHANDright;
			plotHANDrightcut += "_cut";
			cout << "Drawing " << titleHANDright << "..." << endl;
			TH1F *HANDright = new TH1F(plotHANDright,titleHANDright,TDCbins,TDCmin,TDCmax);
			HANDright->SetMinimum(0);
			TH1F *HANDrightcut = new TH1F(plotHANDrightcut,titleHANDright,TDCbins,TDCmin,TDCmax);
			HANDrightcut->SetMinimum(0);
			TString HANDrightTDC = goodTDCr;
			HANDrightTDC += ">>";
			HANDrightTDC += plotHANDright;
			TString HANDrightTDCcut = goodTDCr;
			HANDrightTDCcut += ">>";
			HANDrightTDCcut += plotHANDrightcut;
			chainHe->Draw(HANDrightTDC, cuts && vetoTDCs,"");
//			HANDright->Scale(1/(HeChargeScale*Helivetime));
			HANDright->Draw();
			chainHe->Draw(HANDrightTDCcut, cuts && vetoTDCs && goodTDCrightcut && firstTrack,"same");
			HANDrightcut->SetFillColor(kViolet);
//			HANDrightcut->Scale(1/(HeChargeScale*Helivetime));
			HANDrightcut->Draw("same");
			// ********************************************************************************
			// This section below gathers and prints some statistics on the plot
			double numHANDrightcutEvents = 0;
			for (int j=0; j<TDCbins; j++){ numHANDrightcutEvents = numHANDrightcutEvents + HANDrightcut->GetBinContent(j);}
			TString HANDrightFactorsString = "Total Charge for Runs: ";
			HANDrightFactorsString += HeChargeScale;
			HANDrightFactorsString += " C";
			TString HANDrightFactorsString1 = "Total Livetime for Runs: ";
			HANDrightFactorsString1 += Helivetime;
			TString HANDrightFactorsString2 = "# of Cut (Purple) Events: ";
			HANDrightFactorsString2 += numHANDrightcutEvents;
			HANDrightFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
			TText *t1 = HANDrightFactors->AddText(HANDrightFactorsString);
			TText *t2 = HANDrightFactors->AddText(HANDrightFactorsString1);
			TText *t2 = HANDrightFactors->AddText(HANDrightFactorsString2);
			HANDrightFactors->Draw("same");
			// ********************************************************************************
			handpad03->Update();

			handpad04->cd();
			cout << "Drawing Spin Up vs. xBj..." << endl;
			TString titleSpinUpx = "Spin Up vs. xBj for Plane #";
			titleSpinUpx += nplane;
			titleSpinUpx += ", PMT # ";
			titleSpinUpx += thisbar;
			if (includeVetos) {titleSpinUpx += " with vetos";}
			else {titleSpinUpx += " without vetos";}
			TString titleSpinUpxcut = titleSpinUpx;
			titleSpinUpxcut += " with goodTDC cuts";
			cout << "Drawing " << titleSpinUpx << "..." << endl;
			TString plotSpinUpx = "HANDSpinUpx_p";
			plotSpinUpx += nplane;
			plotSpinUpx += "_b";
			plotSpinUpx += thisbar;
			TH1F *HANDSpinUpx = new TH1F(plotSpinUpx,titleSpinUpxcut,xBjbins,xBjmin,xBjmax);
			TString HANDSpinUpxString = "PriKineR.x_bj";
			HANDSpinUpxString += ">>";
			HANDSpinUpxString += plotSpinUpx;
			chainHe->Draw(HANDSpinUpxString, cuts && vetoTDCs && goodTDCcut && firstTrack && "he3R.Spin==1","");
			HANDSpinUpx->SetMinimum(0);
			HANDSpinUpx->Draw();
			handpad04->Update();

			handpad05->cd();
			cout << "Drawing Spin Down vs. xBj..." << endl;
			TString titleSpinDownx = "Spin Down vs. xBj for Plane #";
			titleSpinDownx += nplane;
			titleSpinDownx += ", PMT # ";
			titleSpinDownx += thisbar;
			if (includeVetos) {titleSpinDownx += " with vetos";}
			else {titleSpinDownx += " without vetos";}
			TString titleSpinDownxcut = titleSpinDownx;
			titleSpinDownxcut += " with goodTDC cuts";
			cout << "Drawing " << titleSpinDownx << "..." << endl;
			TString plotSpinDownx = "HANDSpinDownx_p";
			plotSpinDownx += nplane;
			plotSpinDownx += "_b";
			plotSpinDownx += thisbar;
			TH1F *HANDSpinDownx = new TH1F(plotSpinDownx,titleSpinDownxcut,xBjbins,xBjmin,xBjmax);
			TString HANDSpinDownxString = "PriKineR.x_bj";
			HANDSpinDownxString += ">>";
			HANDSpinDownxString += plotSpinDownx;
			chainHe->Draw(HANDSpinDownxString, cuts && vetoTDCs && goodTDCcut && firstTrack && "he3R.Spin==-1","");
			HANDSpinDownx->SetMinimum(0);
			HANDSpinDownx->Draw();
			handpad05->Update();

			handpad06->cd();
			cout << "Drawing Total Spin Up vs. xBj..." << endl;
//			TString titleTotalSpinUpx = "Total Spin Up vs. xBj";
//			if (includeVetos) {titleTotalSpinUpx += " with vetos";}
//			else {titleTotalSpinUpx += " without vetos";}
//			titleTotalSpinUpx += " with goodTDC cuts";
//			cout << "Drawing " << titleTotalSpinUpx << "..." << endl;
//			TString plotTotalSpinUpx = "HANDTotalSpinUpx";
//			TH1F *HANDTotalSpinUpx = new TH1F(plotTotalSpinUpx,titleTotalSpinUpx,xBjbins,xBjmin,xBjmax);
			HANDTotalSpinUpx->Add(HANDSpinUpx);
			HANDTotalSpinUpx->SetMinimum(0);
			HANDTotalSpinUpx->Draw();
			handpad06->Update();

			handpad07->cd();
			cout << "Drawing Total Spin Down vs. xBj..." << endl;
//			TString titleTotalSpinDownx = "Total Spin Down vs. xBj";
//			if (includeVetos) {titleTotalSpinDownx += " with vetos";}
//			else {titleTotalSpinDownx += " without vetos";}
//			titleTotalSpinDownx += " with goodTDC cuts";
//			cout << "Drawing " << titleTotalSpinDownx << "..." << endl;
//			TString plotTotalSpinDownx = "HANDTotalSpinDownx";
//			TH1F *HANDTotalSpinDownx = new TH1F(plotTotalSpinDownx,titleTotalSpinDownx,xBjbins,xBjmin,xBjmax);
			HANDTotalSpinDownx->Add(HANDSpinDownx);
			HANDTotalSpinDownx->SetMinimum(0);
			HANDTotalSpinDownx->Draw();
			handpad07->Update();




			TString imageTitle = outputPlotsHere;
			imageTitle += "TDC_plots_Run_Num_";
			imageTitle += HeRunNumber;
			imageTitle += "-";
			imageTitle += endHeRunNumber;
			imageTitle += "_p";
			imageTitle += nplane;
			imageTitle += "_b";
			if (thisbar < 10) {imageTitle += "0";}
			imageTitle += thisbar;
			if (includeVetos) {imageTitle += "_with_vetos";}
			if (includeAntivetos) {imageTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageTitle += "_as_vetos";}
			imageTitle+= ".png";
			handCanvas->Print(imageTitle);

			TString imageAntivetosTitle = outputPlotsHere;
			imageAntivetosTitle += "antivetos_for_Run_Num_";
			imageAntivetosTitle += HeRunNumber;
			imageAntivetosTitle += "-";
			imageAntivetosTitle += endHeRunNumber;
			imageAntivetosTitle += "_p";
			imageAntivetosTitle += nplane;
			imageAntivetosTitle += "_b";
			imageAntivetosTitle += thisbar;
			if (includeVetos) {imageAntivetosTitle += "_with_vetos";}
			if (includeAntivetos) {imageAntivetosTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageAntivetosTitle += "_as_vetos";}
			imageAntivetosTitle += ".png";

			if (includeAntivetos) {hand_draw_antivetos(antiveto1plane, antiveto1bar, antiveto2plane, antiveto2bar, antiveto3plane, antiveto3bar, HeRunNumber, endHeRunNumber, chainHe, TDCbins, TDCmin, TDCmax, cuts, goodTDCcut, vetoTDCs, imageAntivetosTitle, nplane, thisbar, includeVetos, includeAntivetos, antivetosAsVetos, veto1plane, veto1bar, veto2plane, veto2bar, veto3plane, veto3bar, veto4plane, veto4bar, veto5plane, veto5bar, veto6plane, veto6bar, allVetos, allAntivetos);}

// *********************************************************************************************************
// The section below will plot the bars used for vetos for the previous canvas. It will consist of two
// canvases, one without the veto cuts made and one with to show the different.
			TString imageVetosWithoutVetosTitle = outputPlotsHere;
			imageVetosWithoutVetosTitle += "vetos_without_veto_cut_for_Run_Num_";
			imageVetosWithoutVetosTitle += HeRunNumber;
			imageVetosWithoutVetosTitle += "-";
			imageVetosWithoutVetosTitle += endHeRunNumber;
			imageVetosWithoutVetosTitle += "_p";
			imageVetosWithoutVetosTitle += nplane;
			imageVetosWithoutVetosTitle += "_b";
			imageVetosWithoutVetosTitle += thisbar;
			if (includeVetos) {imageVetosWithoutVetosTitle += "_with_vetos";}
			if (includeAntivetos) {imageVetosWithoutVetosTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageVetosWithoutVetosTitle += "_as_vetos";}
			imageVetosWithoutVetosTitle+= ".png";

			TString imageVetosWithVetosTitle = outputPlotsHere;
			imageVetosWithVetosTitle += "vetos_with_veto_cut_for_Run_Num_";
			imageVetosWithVetosTitle += HeRunNumber;
			imageVetosWithVetosTitle += "-";
			imageVetosWithVetosTitle += endHeRunNumber;
			imageVetosWithVetosTitle += "_p";
			imageVetosWithVetosTitle += nplane;
			imageVetosWithVetosTitle += "_b";
			imageVetosWithVetosTitle += thisbar;
			if (includeVetos) {imageVetosWithVetosTitle += "_with_vetos";}
			if (includeAntivetos) {imageVetosWithVetosTitle += "_with_antivetos";}
			if (antivetosAsVetos && includeAntivetos) {imageVetosWithVetosTitle += "_as_vetos";}
			imageVetosWithVetosTitle+= ".png";

//			if (includeVetos) {hand_draw_vetos(veto1plane, veto2plane, veto3plane, veto4plane, veto5plane, veto6plane,veto1bar, veto2bar, veto3bar, veto4bar, veto5bar, veto6bar, imageVetosWithoutVetosTitle, imageVetosWithVetosTitle, HeRunNumber, endHeRunNumber, chainHe, nplane, thisbar, TDCbins, TDCmin, TDCmax, cuts, vetoTDCs, antivetosAsVetos, allVetos, allAntivetos);}

/*		if ((nplane==1) && (thisbar==15)) { nplane = 2; thisbar = 7;}
		if ((nplane==2) && (thisbar==12)) { nplane = 3; thisbar = 6;}
		if ((nplane==3) && (thisbar==11)) { nplane = 4; thisbar = 3;}
		if ((nplane==4) && (thisbar==7))  { nplane = 4; thisbar = 99;}
*/

		}
	}

	TString canvasTotalSpinTest = "TotalSpinTest";
	TString canvasTitleTotalSpinTest = "HAND - Total Spin (Not Scaled)";
	TCanvas *totalSpinTestCanvas = new TCanvas(canvasTotalSpinTest,canvasTitleTotalSpinTest,1400,770); //x,y
	totalspintestpad01 =  new TPad("totalspintestpad01","totalspintestpad01",0.0000,0.5000,0.5000,1.0000,0,0,0);
	totalspintestpad02 =  new TPad("totalspintestpad02","totalspintestpad02",0.5000,0.5000,1.0000,1.0000,0,0,0);
	totalspintestpad03 =  new TPad("totalspintestpad03","totalspintestpad03",0.0000,0.0000,1.0000,0.5000,0,0,0);
	totalspintestpad01->Draw(); totalspintestpad02->Draw(); totalspintestpad03->Draw();

	totalspintestpad01->cd();
	HANDTotalSpinUpx->SetTitle("Total Spin Up (Not Scaled)");
	HANDTotalSpinUpx->Draw();
	totalspintestpad01->Update();

	totalspintestpad02->cd();
	HANDTotalSpinDownx->SetTitle("Total Spin Down (Not Scaled)");
	HANDTotalSpinDownx->Draw();
	totalspintestpad02->Update();

	totalspintestpad03->cd();
        TF1 *fitasymtest = new TF1("fitasymtest","[0]",xBjmin,xBjmax);
	HANDAsymTest = HANDTotalSpinUpx->GetAsymmetry(HANDTotalSpinDownx);
	TString AsymTestTitle = "Target Asymmerty with Neutron Cuts vs. xBj for runs ";
	AsymTestTitle += HeRunNumber;
	AsymTestTitle += "-";
	AsymTestTitle += endHeRunNumber;
	HANDAsymTest->SetTitle(AsymTestTitle);
	HANDAsymTest->Draw();
        fitasymtest->SetLineColor(kBlue);
        HANDAsymTest->Fit("fitasymtest","R");
	totalspintestpad03->Update();


	TString asymTitle = "Target Asymmetry for Runs ";
	asymTitle += HeRunNumber;
	asymTitle += "-";
	asymTitle += endHeRunNumber;
	TCanvas *asymCanvas = new TCanvas("asymCanvas",asymTitle,1400,770); //x,y
	asymCanvas->cd();
	asymCanvas->SetGrid();
	Double_t x[xBjbins], y[xBjbins], errorx[xBjbins], errory[xBjbins];
	double minError;
	double maxError;
	double posStuff;
	double negStuff;
	double UpEvents;
	double DownEvents;
	asymOutFile << "Runs " << HeRunNumber << "-" << endHeRunNumber << endl;
	cout << "Runs " << HeRunNumber << "-" << endHeRunNumber << endl;
	asymOutFile << "xBj	Asymmetry	Stat. Error	# Pos Events	Pos Charge	Pos LT	# Neg Events	Neg Charge	Neg LT" << endl;
	cout << "xBj	Asymmetry	Stat. Error	# Pos Events	Pos Charge	Pos LT	# Neg Events	Neg Charge	Neg LT" << endl;
	for (int i=0; i<xBjbins; i++)
	{	
		UpEvents = HANDTotalSpinUpx->GetBinContent(i);
		DownEvents = HANDTotalSpinDownx->GetBinContent(i);
		x[i] = HANDTotalSpinUpx->GetBinCenter(i);
		if (x[i] != (HANDTotalSpinDownx->GetBinCenter(i))) { cout << endl << endl << "!!!!!!!!!!!!!!!!!!!!!!!!!! STOP! THERE'S A PROBLEM!!!!!!!!!!!!!!!!!!!!!!" << endl << endl << endl;}
		posStuff = UpEvents/(HeChargeScaleUp * HelivetimeUp + 1e-15);
		negStuff = DownEvents/(HeChargeScaleDown * HelivetimeDown + 1e-15);
		y[i] = ((posStuff - negStuff)/(posStuff + negStuff + 1e-15));
		errory[i] = 2*(DownEvents*sqrt(UpEvents) + UpEvents*sqrt(DownEvents))/((HeChargeScaleUp*HelivetimeUp)*(HeChargeScaleDown*HelivetimeDown)*pow((UpEvents/(HeChargeScaleUp*HelivetimeUp)) + (DownEvents/(HeChargeScaleDown*HelivetimeDown)),2) + 1e-15);
		if ((UpEvents == 0) || (DownEvents == 0)) { errory[i] = 1;}
		if ((UpEvents == 0) || (DownEvents == 0)) { y[i] = NULL;}
		if (i==0)
		{
			minError = y[i] - 2*errory[i];
			maxError = y[i] + 2*errory[i];
		}
		if ((y[i] - 2*errory[i]) < minError) { minError = y[i] - 2*errory[i];}
		if ((y[i] + 2*errory[i]) > maxError) { maxError = y[i] + 2*errory[i];}
		errorx[i] = ((xBjmax - xBjmin)/xBjbins)/2;
		asymOutFile << x[i] << "	" << y[i] << "	" << errory[i] << "	" << UpEvents << "	" << HeChargeScaleUp << "	" << HelivetimeUp << "	" << DownEvents << "	" << HeChargeScaleDown << "	" << HelivetimeDown << endl;
		cout << x[i] << "	" << y[i] << "	" << errory[i] << "	" << UpEvents << "	" << HeChargeScaleUp << "	" << HelivetimeUp << "	" << DownEvents << "	" << HeChargeScaleDown << "	" << HelivetimeDown << endl;
	}
	asymGraph = new TGraphErrors(xBjbins, x, y, errorx, errory);
	asymGraph->SetMarkerStyle(21);
	asymGraph->SetMarkerColor(4);
	asymGraph->SetTitle(asymTitle);
	asymTestHist = new TH2F("asymTestHist",asymTitle,xBjbins,xBjmin,xBjmax,100,minError,maxError);
	asymTestHist->SetStats(kFALSE);
	asymTestHist->Draw();
	cout << "Fit min = " << xBjmin << "; Fit max = " << xBjmax << endl;
	TF1 *fitAsymGraph = new TF1("fitAsymGraph", "[0]", xBjmin, xBjmax);
	asymGraph->Draw("P");
	fitAsymGraph->SetLineColor(kBlue);
	asymGraph->Fit("fitAsymGraph","R");
	asymCanvas->Update();

	TString TotalAsymOutTitle = outputPlotsHere;
	TotalAsymOutTitle += "target_asymmetry_good_for_Run_Num_";
	TotalAsymOutTitle += HeRunNumber;
	TotalAsymOutTitle += "-";
	TotalAsymOutTitle += endHeRunNumber;
	if (includeVetos) {TotalAsymOutTitle += "_with_vetos";}
	if (includeAntivetos) {TotalAsymOutTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {TotalAsymOutTitle += "_as_vetos";}
	TotalAsymOutTitle += ".png";
	asymCanvas->Print(TotalAsymOutTitle);



	TString canvasTotalSpin = "TotalSpin";
	TString canvasTitleTotalSpin = "HAND - Total Spin";
	TCanvas *totalSpinCanvas = new TCanvas(canvasTotalSpin,canvasTitleTotalSpin,1400,770); //x,y
	totalspinpad01 =  new TPad("totalspinpad01","totalspinpad01",0.0000,0.5000,0.5000,1.0000,0,0,0);
	totalspinpad02 =  new TPad("totalspinpad02","totalspinpad02",0.5000,0.5000,1.0000,1.0000,0,0,0);
	totalspinpad03 =  new TPad("totalspinpad03","totalspinpad03",0.0000,0.0000,1.0000,0.5000,0,0,0);
	totalspinpad01->Draw(); totalspinpad02->Draw(); totalspinpad03->Draw();

	totalspinpad01->cd();
	cout << "HeChargeScaleUp: " << HeChargeScaleUp << "   HelivetimeUp: " << HelivetimeUp << endl;
	HANDTotalSpinUpx->Scale(1/(HeChargeScaleUp * HelivetimeUp));
	HANDTotalSpinUpx->SetTitle("Total Spin Up (Scaled by Charge, LT)");
	HANDTotalSpinUpx->Draw();
	// ********************************************************************************
	// This section below gathers and prints some statistics on the plot
	TString HANDUpFactorsString = "Total Positive Charge for Runs: ";
	HANDUpFactorsString += HeChargeScaleUp;
	HANDUpFactorsString += " C";
	TString HANDUpFactorsString1 = "Total Positive Livetime for Runs: ";
	HANDUpFactorsString1 += HelivetimeUp;
	HANDUpFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
	TText *t1 = HANDUpFactors->AddText(HANDUpFactorsString);
	TText *t2 = HANDUpFactors->AddText(HANDUpFactorsString1);
	HANDUpFactors->Draw("same");
	// ********************************************************************************
	totalspinpad01->Update();

	totalspinpad02->cd();
	cout << "HeChargeScaleDown: " << HeChargeScaleDown << "   HelivetimeDown: " << HelivetimeDown << endl;
	HANDTotalSpinDownx->Scale(1/(HeChargeScaleDown * HelivetimeDown));
	HANDTotalSpinDownx->SetTitle("Total Spin Down (Scaled by Charge, LT)");
	HANDTotalSpinDownx->Draw();
	// ********************************************************************************
	// This section below gathers and prints some statistics on the plot
	TString HANDDownFactorsString = "Total Negative Charge for Runs: ";
	HANDDownFactorsString += HeChargeScaleDown;
	HANDDownFactorsString += " C";
	TString HANDDownFactorsString1 = "Total Negative Livetime for Runs: ";
	HANDDownFactorsString1 += HelivetimeDown;
	HANDDownFactors = new TPaveText(0.11,0.69,0.4,0.89,"NDC");
	TText *t1 = HANDDownFactors->AddText(HANDDownFactorsString);
	TText *t2 = HANDDownFactors->AddText(HANDDownFactorsString1);
	HANDDownFactors->Draw("same");
	// ********************************************************************************
	totalspinpad02->Update();

	totalspinpad03->cd();
        TF1 *fitasym = new TF1("fitasym","[0]",xBjmin,xBjmax);
	HANDAsym = HANDTotalSpinUpx->GetAsymmetry(HANDTotalSpinDownx);
	TString AsymTitle = "Target Asymmerty with Neutron Cuts vs. xBj for runs ";
	AsymTitle += HeRunNumber;
	AsymTitle += "-";
	AsymTitle += endHeRunNumber;
	HANDAsym->SetTitle(AsymTitle);
	HANDAsym->Draw();
        fitasym->SetLineColor(kBlue);
        HANDAsym->Fit("fitasym","R");
	totalspinpad03->Update();

	TString TotalSpinOutTitle = outputPlotsHere;
	TotalSpinOutTitle += "target_asymmetry_for_Run_Num_";
	TotalSpinOutTitle += HeRunNumber;
	TotalSpinOutTitle += "-";
	TotalSpinOutTitle += endHeRunNumber;
	if (includeVetos) {TotalSpinOutTitle += "_with_vetos";}
	if (includeAntivetos) {TotalSpinOutTitle += "_with_antivetos";}
	if (antivetosAsVetos && includeAntivetos) {TotalSpinOutTitle += "_as_vetos";}
	TotalSpinOutTitle += ".png";
	totalSpinCanvas->Print(TotalSpinOutTitle);


	asymOutFile.close();

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



}
Example #17
0
int main(int argc, char** argv)
{ 
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>>>> VertexStudiesAnalysis::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  // Parse the config file
  parseConfigFile (argv[1]) ;

  std::string inputFileList = gConfigParser -> readStringOption("Input::inputFileList");

  std::string treeName  = gConfigParser -> readStringOption("Input::treeName");

  std::string outputRootFilePath = gConfigParser -> readStringOption("Output::outputRootFilePath");
  std::string outputRootFileName = gConfigParser -> readStringOption("Output::outputRootFileName");  
 
  std::string tmvaMethod    = gConfigParser -> readStringOption("Input::tmvaMethod");
  std::string tmvaWeights   = gConfigParser -> readStringOption("Input::tmvaWeights");
 
  int entryMIN = gConfigParser -> readIntOption("Options::entryMIN");
  int entryMAX = gConfigParser -> readIntOption("Options::entryMAX");
 
  int isZee    = gConfigParser -> readIntOption("Options::isZee");
  int isZmumu  = gConfigParser -> readIntOption("Options::isZmumu");
  int isHiggs  = gConfigParser -> readIntOption("Options::isHiggs");

  int isData   = gConfigParser -> readIntOption("Options::isData");

  double trackThr = gConfigParser -> readDoubleOption("Options::trackThr");

  int useWeights      = gConfigParser -> readIntOption("Options::useWeights");
  int poissonWeights  = gConfigParser -> readIntOption("Options::poissonWeights");
  int nAvePU          = gConfigParser -> readIntOption("Options::nAvePU");
  
  std::string puweightsFileName = gConfigParser -> readStringOption("Options::puweightsFileName");  

  int useJSON      = gConfigParser -> readIntOption("Options::useJSON");
  std::string jsonFileName = gConfigParser -> readStringOption("Options::jsonFileName");  

  //******* Get run/LS map from JSON file *******
  std::map<int, std::vector<std::pair<int, int> > > jsonMap;
  if ( isData && useJSON ) {
    std::cout << ">>> Getting GOOD  run/LS from JSON file" << std::endl;
    jsonMap = readJSONFile(jsonFileName);
    std::cout << std::endl;
    std::cout << std::endl;
  }

  
  //****** Get weights for MC ****** 
  float nmax;
  float w[50];
  TRandom *gRandom = new TRandom();
  
  if (useWeights){
    
    TFile weightsFile(puweightsFileName.c_str(),"READ");  
    TH1F* hweights;
     
    if ( poissonWeights ){
      std::cout << "N ave PU for Poisson PU reweighting : " << nAvePU << std::endl;
      char hname[100];
      sprintf(hname,"hwpoisson_%d",nAvePU);
      hweights = (TH1F*)weightsFile.Get(hname);
    }
    else {
      hweights = (TH1F*)weightsFile.Get("hweights");
    }
    nmax = hweights ->GetMaximum();
    std::cout << " Max weight " << nmax << std::endl;
    
    for (int ibin = 1; ibin < hweights->GetNbinsX()+1; ibin++){
      w[ibin-1] = hweights->GetBinContent(ibin);  // bin 1 --> nvtx = 0 
    }
    weightsFile.Close();
  }
  
  //****** open TH1 with tracks pt for kolmogorov test
  TH1F *hTrackPt;
  TFile ptFile("hTracksPt_PU25_upTo10GeV.root","READ"); 
  hTrackPt = (TH1F*)ptFile.Get("hTracksPt")->Clone("hTrackPt");
  hTrackPt->SetDirectory(0);
  ptFile.Close();
  std::cout << hTrackPt->GetEntries() << std::endl;

  TH1F *htemp = (TH1F*)hTrackPt->Clone("htemp");
  htemp->Reset();
 

  //****** Parameters for vertex finding algo ****** 
  VertexAlgoParameters vtxAlgoParams_;
  vtxAlgoParams_.rescaleTkPtByError = false;
  vtxAlgoParams_.trackCountThr      = 1.;
  vtxAlgoParams_.highPurityOnly     = false;
  vtxAlgoParams_.maxD0Signif        = 9999999.;
  vtxAlgoParams_.maxDzSignif        = 9999999.;
  vtxAlgoParams_.removeTracksInCone = 1;
  vtxAlgoParams_.coneSize           = 0.05;
  
  //--- sumpt2 ordering
  vector<string> ranksumpt2_;
  ranksumpt2_.push_back("logsumpt2");  

  //--- ranking product variables
  vector<string> rankVariables_;
  // variables order matters to resolve ties
  rankVariables_.push_back("ptbal"), rankVariables_.push_back("ptasym"),rankVariables_.push_back("logsumpt2");  
  
  //--- book TMVA 
  int isSig, evtNumber, nVertices;
  float diphopt; 
  float logsumpt2;
  float ptbal, ptasym, ptmax, ptmax3, sumpt, nchthr, nch, sumtwd;
  float dk;
  TMVA::Reader *tmvaReader_ = new TMVA::Reader( "!Color:!Silent" );
  
  tmvaReader_->AddVariable( "logsumpt2",&logsumpt2 );
  tmvaReader_->AddVariable( "ptbal" , &ptbal);
  tmvaReader_->AddVariable( "ptasym", &ptasym );
  tmvaReader_->AddVariable( "nch",&nch );
  tmvaReader_->AddVariable( "nchthr",&nchthr );
  tmvaReader_->AddVariable( "ptmax" ,&ptmax  );
  tmvaReader_->AddVariable( "ptmax3",&ptmax3 );
  tmvaReader_->AddVariable( "sumtwd",&sumtwd );
  tmvaReader_->AddVariable( "dk",&dk );
  tmvaReader_->BookMVA( tmvaMethod.c_str(), tmvaWeights.c_str() );

 

  //****** BOOK OUTPUT HISTOGRAMS ******

  TH1F PtAll("PtAll","Pt of boson all",80,0,400);
  TH1F PtGood("PtGood","Pt of boson good",80,0,400);
  TH1F PtGood_BDT("PtGood_BDT","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK("PtGood_RANK","Pt of boson good (RANKING)",80,0,400);

  TH1F PtAll_EBEB("PtAll_EBEB","Pt of boson all",80,0,400);
  TH1F PtGood_EBEB("PtGood_EBEB","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_EBEB("PtGood_BDT_EBEB","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_EBEB("PtGood_RANK_EBEB","Pt of boson good (RANKING)",80,0,400);

  TH1F PtAll_EBEE("PtAll_EBEE","Pt of boson all",80,0,400);
  TH1F PtGood_EBEE("PtGood_EBEE","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_EBEE("PtGood_BDT_EBEE","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_EBEE("PtGood_RANK_EBEE","Pt of boson good (RANKING)",80,0,400);

  TH1F PtAll_EEEE("PtAll_EEEE","Pt of boson all",80,0,400);
  TH1F PtGood_EEEE("PtGood_EEEE","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_EEEE("PtGood_BDT_EEEE","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_EEEE("PtGood_RANK_EEEE","Pt of boson good (RANKING)",80,0,400);

  TH1F EtaAll("EtaAll","Eta of max SC",50,-5,5);
  TH1F EtaGood("EtaGood","Eta of max SC good",50,-5,5);
  TH1F EtaGood_BDT("EtaGood_BDT","Eta of max SC good (BDT)",50,-5,5);
  TH1F EtaGood_RANK("EtaGood_RANK","Eta of max SC good (RANKING)",50,-5,5);
  
  TH1F NvtAll("NvtAll","number of PV all",50,0,50);
  TH1F NvtGood("NvtGood","number of PV good",50,0,50);
  TH1F NvtGood_BDT("NvtGood_BDT","number of PV good (BDT)",50,0,50);
  TH1F NvtGood_RANK("NvtGood_RANK","number of PV good (RANKING)",50,0,50);

  TH1F NpuAll("NpuAll","number of PV all",50,0,50);
  TH1F NpuGood("NpuGood","number of PV good",50,0,50);
  TH1F NpuGood_BDT("NpuGood_BDT","number of PV good (BDT)",50,0,50);
  TH1F NpuGood_RANK("NpuGood_RANK","number of PV good (RANKING)",50,0,50);

  TH1F PtGood_matchedClosest("PtGood_matchedClosest","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_matchedClosest("PtGood_BDT_matchedClosest","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_matchedClosest("PtGood_RANK_matchedClosest","Pt of boson good (RANKING)",80,0,400);

  TH1F EtaGood_matchedClosest("EtaGood_matchedClosest","Eta of max SC good",50,-5,5);
  TH1F EtaGood_BDT_matchedClosest("EtaGood_BDT_matchedClosest","Eta of max SC good (BDT)",50,-5,5);
  TH1F EtaGood_RANK_matchedClosest("EtaGood_RANK_matchedClosest","Eta of max SC good (RANKING)",50,-5,5);
  
  TH1F NvtGood_matchedClosest("NvtGood_matchedClosest","number of PV good",50,0,50);
  TH1F NvtGood_BDT_matchedClosest("NvtGood_BDT_matchedClosest","number of PV good (BDT)",50,0,50);
  TH1F NvtGood_RANK_matchedClosest("NvtGood_RANK_matchedClosest","number of PV good (RANKING)",50,0,50);

  TH1F NpuGood_matchedClosest("NpuGood_matchedClosest","number of PV good",50,0,50);
  TH1F NpuGood_BDT_matchedClosest("NpuGood_BDT_matchedClosest","number of PV good (BDT)",50,0,50);
  TH1F NpuGood_RANK_matchedClosest("NpuGood_RANK_matchedClosest","number of PV good (RANKING)",50,0,50);

  TH2F hdist("hdist"," hdist",80,0,200,400,-10,10);
  TH2F hdiff_dZ_muons("hdiff_dZ_muons","hdiff_dZ_muons",80,0,200,400,-10,10);
  TH2F hdiff_dZ_electrons("hdiff_dZ_electrons","hdiff_dZ_electrons",80,0,200,400,-10,10);

  TH1F BDToutput("BDToutput","BDT output",500,-1,1);
  TH1F BDToutput_sig("BDToutput_sig","BDT output - signal vertices",500,-1,1);
  TH1F BDToutput_bkg("BDToutput_bkg","BDT output - background",500,-1,1);
  

  TH1F pt2h("pt2h","pt2 H",500,0,500);
  TH1F pt2bkg("pt2bkg","pt2 bkg",500,0,500);


  TH2F * hAcceptedLumis = new TH2F("hAcceptedLumis","hAcceptedLumis",20000, 160000, 180000, 10000, 0, 10000);


  float ww = 1;
  float r9cut = 0.93;
  
  //****** LOAD TREE ******
  TChain* chain = new TChain(treeName.c_str());
  FillChain(*chain, inputFileList.c_str());
  treeReader reader((TTree*)(chain));
  std::cout<<"found "<< reader.GetEntries() <<" entries"<<std::endl;

  //****** Start loop over entries ******
  int runId, lumiId;

  for (int u = 0; u < reader.GetEntries(); u++ )
    {
      if(u == entryMAX) break;
      if(u < entryMIN)  continue;
      if(u%10000 == 0) std::cout<<"reading event "<< u <<std::endl;
      reader.GetEntry(u);
      
      //*** filter bad runs/lumis
      runId = reader.GetInt("runId")->at(0);
      lumiId = reader.GetInt("lumiId")->at(0);
      
      bool skipEvent = false;
      if( isData && useJSON ){
	if(AcceptEventByRunAndLumiSection(runId,lumiId,jsonMap) == false)
	  skipEvent = true;
      }
      if( skipEvent == true ) continue;
      hAcceptedLumis -> Fill(runId, lumiId);

      //*** pu weights
      std::vector<float>*PU_z ;
      std::vector<int>* mc_PUit_NumInteractions; 
      int npu ;

      if ( !isData ){
      	mc_PUit_NumInteractions  = reader.GetInt("mc_PUit_NumInteractions");
	npu = mc_PUit_NumInteractions->at(0);
      
	//--- use weights 
	if (useWeights){
	  float myrnd = gRandom->Uniform(0,nmax);
	  if (myrnd > w[npu]) continue;
	}
      }

     
      //*** setup common branches ***
      std::vector<int>* PV_nTracks;
      std::vector<float>* PV_z;
      std::vector<float>* PV_d0;
      std::vector<ROOT::Math::XYZVector>* PVtracks;
      std::vector<int>* PVtracks_PVindex;
      std::vector<int>* tracks_PVindex;
      std::vector<float>* tracks_dz ; //?
      std::vector<float>* tracks_dz_PV ; //?
      std::vector<float>* tracks_dxy_PV ; //?
      std::vector<ROOT::Math::XYZTVector>* sc; // supercluster
      
      int accept = 0;
      int indpho1 = -100;
      int indpho2 = -100;
	
      ROOT::Math::XYZTVector sum2pho;
      float etaMaxSC ;
      float TrueVertex_Z;

      //*** selections for Hgg ***
      if (isHiggs){
	std::vector<ROOT::Math::XYZVector>* mc_H_vertex = reader.Get3V("mc_H_vertex");
	std::vector<ROOT::Math::XYZTVector>* mcV1 = reader.Get4V("mcV1");
	std::vector<ROOT::Math::XYZTVector>* mcV2 = reader.Get4V("mcV2");
	std::vector<ROOT::Math::XYZTVector>* photons = reader.Get4V("photons");
	std::vector<float>* photons_r9 = reader.GetFloat("photons_r9");
	
	if (mc_H_vertex->size() != 1) continue;
	
	PV_nTracks       = reader.GetInt("PV_nTracks");
	PV_z             = reader.GetFloat("PV_z");
	PV_d0            = reader.GetFloat("PV_d0");
	PVtracks         = reader.Get3V("PVtracks");
	PVtracks_PVindex = reader.GetInt("PVtracks_PVindex");
	tracks_PVindex   = reader.GetInt("tracks_PVindex");
	tracks_dxy_PV    = reader.GetFloat("tracks_dxy_PV");
	tracks_dz_PV     = reader.GetFloat("tracks_dz_PV");
	tracks_dz        = reader.GetFloat("tracks_dz");
	sc               = reader.Get4V("photons_SC");

	hggSelection(mcV1, mcV2, photons, sc, photons_r9, accept, indpho1, indpho2);
	if (!accept) continue;

	if ( photons_r9->at(indpho1) < r9cut ) continue;
	if ( photons_r9->at(indpho2) < r9cut ) continue;
	
	etaMaxSC = sc->at(indpho1).eta();
	sum2pho  = photons->at(indpho1)+ photons->at(indpho2);
	TrueVertex_Z = mc_H_vertex->at(0).Z();
      }// end Hgg selection


      //*** selections for Zee ***
      if (isZee){
	std::vector<ROOT::Math::XYZTVector>* electrons = reader.Get4V("electrons");
	// std::vector<float>* eleid = reader.GetFloat("simpleEleId95cIso");
	// no eleID95 available for data 2011 --> compute it by hand
	std::vector<float>* eleid = new std::vector<float>;
	eleid->clear();
	if ( electrons->size() < 2) continue; 
	
	for (unsigned int iele = 0; iele < electrons->size(); iele++){
	  
	  float pt = electrons->at(iele).pt();
	  float tkIso   = reader.GetFloat("electrons_tkIsoR03")->at(iele);
	  float emIso   = reader.GetFloat("electrons_emIsoR03")->at(iele);
	  float hadIso  = reader.GetFloat("electrons_hadIsoR03_depth1")->at(iele) + reader.GetFloat("electrons_hadIsoR03_depth2")->at(iele);
	  float combIso = tkIso + emIso + hadIso;
	
	  int isEB = reader.GetInt("electrons_isEB")->at(iele);
	  float sigmaIetaIeta = reader.GetFloat("electrons_sigmaIetaIeta")->at(iele);
	  float DetaIn        = reader.GetFloat("electrons_deltaEtaIn")->at(iele);
	  float DphiIn        = reader.GetFloat("electrons_deltaPhiIn")->at(iele);
	  float HOverE        = reader.GetFloat("electrons_hOverE")->at(iele);
	  int mishits         = reader.GetInt("electrons_mishits")->at(iele);

	  float id = eleId95 ( pt, tkIso, emIso, hadIso, combIso, isEB, sigmaIetaIeta, DetaIn, DphiIn, HOverE, mishits);	
	  id *= 7.; // to emulate simpleEleId95cIso

	  eleid->push_back( id );
	}

	std::vector<float>* electrons_dz_PV_noEle = reader.GetFloat("electrons_dz_PV_noEle");

	PV_nTracks       = reader.GetInt("PV_noEle_nTracks");
	PV_z             = reader.GetFloat("PV_noEle_z");
	PV_d0            = reader.GetFloat("PV_noEle_d0");
	PVtracks         = reader.Get3V("PVEleLessTracks");
	PVtracks_PVindex = reader.GetInt("PVEleLessTracks_PVindex");
	tracks_PVindex   = reader.GetInt("tracks_PVindex");
	tracks_dxy_PV    = reader.GetFloat("tracks_dxy_PV");
	tracks_dz_PV     = reader.GetFloat("tracks_dz_PV");
	tracks_dz        = reader.GetFloat("tracks_dz");
	//sc               = reader.Get4V("electrons_SC");
	sc               = reader.Get4V("electrons");
	
	zeeSelection(electrons, eleid, accept, indpho1, indpho2);
	if (!accept) continue;

	etaMaxSC = sc->at(indpho1).eta();
	sum2pho  = electrons->at(indpho1)+ electrons->at(indpho2);
	TrueVertex_Z = PV_z->at(0) + (electrons_dz_PV_noEle->at(indpho1) + electrons_dz_PV_noEle->at(indpho2))/2.;

	hdiff_dZ_electrons.Fill( sum2pho.pt(), electrons_dz_PV_noEle->at(indpho1) - electrons_dz_PV_noEle->at(indpho2) );
      }

      //*** selections for Zmumu
      if ( isZmumu ){
	std::vector<ROOT::Math::XYZTVector>* muons = reader.Get4V("muons");
	std::vector<int>* muons_global = reader.GetInt("muons_global");
	std::vector<int>* muons_tracker = reader.GetInt("muons_tracker");
	std::vector<float>* muons_tkIsoR03 = reader.GetFloat("muons_tkIsoR03");
	std::vector<float>* muons_normalizedChi2 = reader.GetFloat("muons_normalizedChi2");
	std::vector<int>* muons_numberOfValidMuonHits = reader.GetInt("muons_numberOfValidMuonHits");
	std::vector<int>* muons_numberOfValidPixelHits = reader.GetInt("muons_numberOfValidPixelHits");
	std::vector<float>* muons_dxy_PV = reader.GetFloat("muons_dxy_PV");
	std::vector<float>* muons_dz_PV = reader.GetFloat("muons_dz_PV");
	std::vector<float>* muons_dz_PV_noMuon = reader.GetFloat("muons_dz_PV_noMuon");
	
	PV_nTracks       = reader.GetInt("PV_noMuon_nTracks");
	PV_z             = reader.GetFloat("PV_noMuon_z");
	PV_d0            = reader.GetFloat("PV_noMuon_d0");
	PVtracks         = reader.Get3V("PVMuonLessTracks");
	PVtracks_PVindex = reader.GetInt("PVMuonLessTracks_PVindex");
	tracks_PVindex   = reader.GetInt("tracks_PVindex");
	tracks_dxy_PV    = reader.GetFloat("tracks_dxy_PV");
	tracks_dz_PV     = reader.GetFloat("tracks_dz_PV");
	tracks_dz        = reader.GetFloat("tracks_dz");
	sc               = reader.Get4V("muons");  // use muon info for SC
	
	
	zmumuSelection(muons,muons_global,muons_tracker, muons_tkIsoR03, 
		       muons_normalizedChi2 , 
		       muons_numberOfValidMuonHits,
		       muons_numberOfValidPixelHits,
		       muons_dxy_PV,
		       muons_dz_PV,
		       accept, indpho1, indpho2);
	

	if (!accept) continue;
	
	etaMaxSC = muons->at(indpho1).eta();
	sum2pho  = muons->at(indpho1)+ muons->at(indpho2);
	TrueVertex_Z = PV_z->at(0) + (muons_dz_PV_noMuon->at(indpho1) + muons_dz_PV_noMuon->at(indpho2))/2.;
	
	hdiff_dZ_muons.Fill( sum2pho.pt(), muons_dz_PV_noMuon->at(indpho1) - muons_dz_PV_noMuon->at(indpho2) );
	
	if ( fabs(muons_dz_PV_noMuon->at(indpho1) - muons_dz_PV_noMuon->at(indpho2))> 0.5) continue;
      }//Zmumu end
      
      // branches buffers
      int nvtx_;
      float  vtxx_[1000], vtxy_[1000], vtxz_[1000];
      int ntracks_;
      float tkpx_[1000], tkpy_[1000], tkpz_[1000], tkPtErr_[1000], tkWeight_[1000], 
	tkd0_[1000], tkd0Err_[1000], tkdz_[1000], tkdzErr_[1000];
      int tkVtxId_[1000];
      bool tkIsHighPurity_[1000];
      
      float phocalox_[100], phocaloy_[100], phocaloz_[100], phoen_[100];
      
      // set variables
      
      // vertices 
      nvtx_    = (int) PV_z->size();
      for ( int iv = 0; iv < nvtx_; iv++){
	vtxx_[iv] =  0;
	vtxy_[iv] =  0;
	vtxz_[iv] =  PV_z->at(iv) ;
      }
      
      // tracks
      ntracks_ = PVtracks->size();
      for (int itrk = 0; itrk <ntracks_; itrk++ ){
	tkpx_[itrk]    = PVtracks->at(itrk).X();
	tkpy_[itrk]    = PVtracks->at(itrk).Y();
	tkpz_[itrk]    = PVtracks->at(itrk).Z();
	tkPtErr_[itrk] = 0;
	tkVtxId_[itrk] = PVtracks_PVindex->at(itrk);
	
	tkWeight_[itrk]= 1.;
	tkd0_[itrk]    = 0;
	tkd0Err_[itrk] = 0;
	tkdz_[itrk]    = 0;
	tkdzErr_[itrk] = 0;
	tkIsHighPurity_[itrk]= 1.;
      }
      
      // photons
      for (int ipho = 0 ; ipho < sc->size(); ipho++){
	float px = sc->at(ipho).X();
	float py = sc->at(ipho).Y();
	float pz = sc->at(ipho).Z();
	float pt = sqrt ( px*px+py*py ); 
	float theta = 2*atan(exp(-sc->at(ipho).eta()) );
	float tantheta = tan(theta);

	if ( fabs(sc->at(ipho).eta()) < etaEB ) {
	  phocalox_[ipho] = R_ECAL*px/pt;
	  phocaloy_[ipho] = R_ECAL*py/pt;
	  phocaloz_[ipho] = R_ECAL/tantheta;
	} 

	if ( fabs(sc->at(ipho).eta()) > etaEE ) {
	  float r_endcap  = fabs(Z_ENDCAP * tantheta);
	  phocalox_[ipho] = r_endcap * px/pt;
	  phocaloy_[ipho] = r_endcap * py/pt;
	  if (pz > 0) phocaloz_[ipho] = Z_ENDCAP;
	  else phocaloz_[ipho] = -Z_ENDCAP;
	} 
	
	phoen_[ipho] = sc->at(ipho).E();
	
      }


      float eta1 = sc->at(indpho1).eta();
      float eta2 = sc->at(indpho2).eta();

      if ( (fabs(eta1) > etaEB && fabs(eta1) < etaEE) || fabs(eta1) > 2.5) continue;
      if ( (fabs(eta2) > etaEB && fabs(eta2) < etaEE) || fabs(eta2) > 2.5) continue;
   
      //*** set vertex info
      TupleVertexInfo vinfo( nvtx_, vtxx_ , vtxy_, vtxz_, ntracks_, tkpx_, tkpy_, tkpz_, tkPtErr_, tkVtxId_, tkWeight_, tkd0_, tkd0Err_,tkdz_, tkdzErr_ , tkIsHighPurity_);
           
      //*** set photon info
      PhotonInfo pho1(indpho1, TVector3(phocalox_[indpho1],phocaloy_[indpho1],phocaloz_[indpho1]),phoen_[indpho1]); 
      PhotonInfo pho2(indpho2, TVector3(phocalox_[indpho2],phocaloy_[indpho2],phocaloz_[indpho2]),phoen_[indpho2]); 
     
      //*** vertex analyzer
      HggVertexAnalyzer vAna(vtxAlgoParams_,nvtx_);
      vAna.analyze(vinfo,pho1,pho2);
            
      // if Zmumu : setNconv to zero
      if (isZmumu) vAna.setNConv(0);

      //*** preselect vertices 
      std::vector<int> presel;
      for(int i=0; i<nvtx_; i++) {
	presel.push_back(i); 
      }
      vAna.preselection(presel);
      
      
      //*** Look if the H vertex matches one of the PV vertices
      float dmin = 10000;
      int iClosest = -1;
      for ( int uu = 0; uu < nvtx_; uu++){
	float distt = fabs( PV_z->at(uu) - TrueVertex_Z );
	if ( distt < dmin)   { dmin = distt; iClosest = uu; }
      }

      //*** NOW FILL HISTOGRAMS
      
      PtAll.Fill( sum2pho.pt(),ww );
      if (fabs(eta1) < etaEB && fabs(eta2) < etaEB)  PtAll_EBEB.Fill( sum2pho.pt(),ww );
      if (fabs(eta1) > etaEE && fabs(eta2) > etaEE)  PtAll_EEEE.Fill( sum2pho.pt(),ww );
      if ( (fabs(eta1) < etaEB && fabs(eta2) > etaEE) || (fabs(eta2) < etaEB && fabs(eta1) > etaEE))  PtAll_EBEE.Fill( sum2pho.pt(),ww );

      EtaAll.Fill( etaMaxSC ,ww);
      NvtAll.Fill( nvtx_,ww );
      if (!isData) NpuAll.Fill(npu,ww);

      
      //*** SUMPT2 CRITERION
      vector<int> ranksumpt2 = vAna.rankprod(ranksumpt2_);
      //-- matching 1cm
      if ( fabs( TrueVertex_Z - PV_z->at(ranksumpt2[0]) ) < 1.) {
	PtGood.Fill( sum2pho.pt(),ww );
	EtaGood.Fill( etaMaxSC ,ww);
	NvtGood.Fill( nvtx_ ,ww);
	if (!isData) NpuGood.Fill(npu,ww);
      }
      //-- matching closest vtx
      if ( iClosest == ranksumpt2[0]){
	PtGood_matchedClosest.Fill( sum2pho.pt(),ww );
	EtaGood_matchedClosest.Fill( etaMaxSC ,ww);
	NvtGood_matchedClosest.Fill( nvtx_ ,ww);
	if (!isData) NpuGood_matchedClosest.Fill(npu,ww);
	} 

   
      //*** RANKING PRODUCT
      vector<int> rankprod = vAna.rankprod(rankVariables_);
      //-- matching 1cm
      if ( fabs( TrueVertex_Z - PV_z->at(rankprod[0]) ) < 1.) {
	PtGood_RANK.Fill( sum2pho.pt(),ww );
	EtaGood_RANK.Fill( etaMaxSC ,ww);
	NvtGood_RANK.Fill( nvtx_,ww );
	if (!isData) NpuGood_RANK.Fill(npu,ww);
      }
      //-- matching closest vtx
      if ( iClosest == rankprod[0]){
	PtGood_RANK_matchedClosest.Fill( sum2pho.pt(),ww );
	EtaGood_RANK_matchedClosest.Fill( etaMaxSC ,ww);
	NvtGood_RANK_matchedClosest.Fill( nvtx_,ww );
	if (!isData) NpuGood_RANK_matchedClosest.Fill(npu,ww);
      }
      


      //*** BDT
      int TMVAind = -1;
      float TMVAmax = -1000.;

      for ( int uu = 0; uu < nvtx_; uu++){
			
	diphopt   = vAna.diphopt(uu);
	logsumpt2 = vAna.logsumpt2(uu);
	nch       = vAna.nch(uu);
	nchthr    = vAna.nchthr(uu);
	ptbal     = vAna.ptbal(uu);
	ptasym    = vAna.ptasym(uu);
	ptmax     = vAna.ptmax(uu);
	ptmax3    = vAna.ptmax3(uu);
	sumtwd    = vAna.sumtwd(uu);

	htemp->Reset();
	for (unsigned int kk = 0; kk < PVtracks->size(); ++kk){
	  if (PVtracks_PVindex->at(kk) == uu){
	    float tkpt = sqrt(PVtracks->at(kk).perp2()) ;
	    htemp ->Fill( (tkpt < 10. ? tkpt : 10.) );
	  }
	}

	if ( htemp->GetEntries()!=0 ) 
	  dk = htemp->KolmogorovTest(hTrackPt);

	//--- Evaluate TMVA
	Double_t mva = tmvaReader_->EvaluateMVA( "BDTG" ); 
	
	BDToutput.Fill( mva );
	if ( fabs( TrueVertex_Z - PV_z->at(uu) ) < 1.)  
	  BDToutput_sig.Fill( mva );
	else 
	  BDToutput_bkg.Fill( mva );

	// take the highest score
	if ( mva > TMVAmax) {
	  TMVAmax = mva;
	  TMVAind = uu;
	}
	
      } // end loop over vertices


      //-- matching 1cm
      if ( fabs( TrueVertex_Z - PV_z->at(TMVAind) ) < 1.) {
	PtGood_BDT.Fill( sum2pho.pt(),ww );
	EtaGood_BDT.Fill( etaMaxSC ,ww);
	NvtGood_BDT.Fill( nvtx_ ,ww);
	if (!isData) NpuGood_BDT.Fill(npu,ww);
      }
      //-- matching closest vtx
      if ( iClosest == TMVAind){
	PtGood_BDT_matchedClosest.Fill( sum2pho.pt(),ww );
	EtaGood_BDT_matchedClosest.Fill( etaMaxSC ,ww);
	NvtGood_BDT_matchedClosest.Fill( nvtx_,ww );
	if (!isData) NpuGood_BDT_matchedClosest.Fill(npu,ww);
      }
      
      
      
    }// end loop over entries

  std::cout << "END LOOP OVER ENTRIES" << std::endl;
  std::cout << "Saving histos on file ..." << std::endl;
  
  TFile ff( (outputRootFilePath+outputRootFileName).c_str(),"recreate");

  hAcceptedLumis -> Write();
  
  PtAll.Write();
  PtGood.Write();
  PtGood_BDT.Write();
  PtGood_RANK.Write();
  
  EtaAll.Write();
  EtaGood.Write();
  EtaGood_BDT.Write();
  EtaGood_RANK.Write();
  
  NvtAll.Write();
  NvtGood.Write();
  NvtGood_BDT.Write(); 
  NvtGood_RANK.Write();

  NpuAll.Write();
  NpuGood.Write();
  NpuGood_BDT.Write(); 
  NpuGood_RANK.Write();
    
  PtGood_matchedClosest.Write();
  PtGood_BDT_matchedClosest.Write();
  PtGood_RANK_matchedClosest.Write();
  
  EtaGood_matchedClosest.Write();
  EtaGood_BDT_matchedClosest.Write();
  EtaGood_RANK_matchedClosest.Write();
  
  NvtGood_matchedClosest.Write();
  NvtGood_BDT_matchedClosest.Write(); 
  NvtGood_RANK_matchedClosest.Write();

  NpuGood_matchedClosest.Write();
  NpuGood_BDT_matchedClosest.Write(); 
  NpuGood_RANK_matchedClosest.Write();

  hdist.Write();
  hdiff_dZ_muons.Write();
  hdiff_dZ_electrons.Write();
  
  BDToutput.Write();
  BDToutput_sig.Write();
  BDToutput_bkg.Write();
   
  ff.Close();
  
  std::cout << "BYE BYE !!!! " << std::endl;

  return 0; 
  

}
Example #18
0
int main() {
   float lumi = 2260.;
   TString dir = "/Users/dygyun/Top/HET_v763";
   //TString dir = "/xrootd/store/user/tjkim/ntuples/hep/V6";
   TFile * fA = TFile::Open(dir+"/hep_TT_powheg.root");
   TFile * fB = TFile::Open(dir+"/hep_TT_powheg.root");
   TFile * fC = TFile::Open(dir+"/hep_WJets.root");
   TFile * fD = TFile::Open(dir+"/hep_DYJets.root");
   TFile * fE = TFile::Open(dir+"/hep_DYJets_10to50.root");
   TFile * fI = TFile::Open(dir+"/hep_SingleTop_t.root");
   TFile * fJ = TFile::Open(dir+"/hep_SingleTbar_t.root");
   TFile * fK = TFile::Open(dir+"/hep_SingleTop_tW.root");
   TFile * fL = TFile::Open(dir+"/hep_SingleTbar_tW.root");
   TFile * fN = TFile::Open(dir+"/hep_WW.root");
   TFile * fO = TFile::Open(dir+"/hep_WZ.root");
   TFile * fM = TFile::Open(dir+"/hep_ZZ.root");
//   TFile * fP = TFile::Open(dir+"/hep_qcd.root");
   
   TH1F * hBsemi = (TH1F*) fA->Get("TopTree/EventSummary");
   TH1F * hB = (TH1F*) fB->Get("TopTree/EventSummary");
   TH1F * hC = (TH1F*) fC->Get("TopTree/EventSummary");
   TH1F * hD = (TH1F*) fD->Get("TopTree/EventSummary");
   TH1F * hE = (TH1F*) fE->Get("TopTree/EventSummary");
   TH1F * hI = (TH1F*) fI->Get("TopTree/EventSummary");
   TH1F * hJ = (TH1F*) fJ->Get("TopTree/EventSummary");
   TH1F * hK = (TH1F*) fK->Get("TopTree/EventSummary");
   TH1F * hL = (TH1F*) fL->Get("TopTree/EventSummary");
   TH1F * hN = (TH1F*) fN->Get("TopTree/EventSummary");
   TH1F * hO = (TH1F*) fO->Get("TopTree/EventSummary");
   TH1F * hM = (TH1F*) fM->Get("TopTree/EventSummary");
 //  TH1F * hP = (TH1F*) fP->Get("");
   int nevt = -1;

   MyAnalysis *A = new MyAnalysis();
   TChain* ch = new TChain("TopTree/events");
   ch->Add(Form("%s/hep_data_json.root",dir.Data()), nevt);
   ch->Process(A);
   
   MyAnalysis_others *B = new MyAnalysis_others(1,1,831.8,lumi,hB->GetBinContent(1));
   TChain* ch2 = new TChain("TopTree/events");
   ch2->Add(Form("%s/hep_TT_powheg.root",dir.Data()), nevt);
   ch2->Process(B);
   //////
   MyAnalysis_Sig *Bsemi = new MyAnalysis_Sig(1,1,831.8,lumi,hBsemi->GetBinContent(1));
   TChain* ch2semi = new TChain("TopTree/events");
   ch2semi->Add(Form("%s/hep_TT_powheg.root",dir.Data()), nevt);
ch2semi->Process(Bsemi);
///////// 
   MyAnalysis *C = new MyAnalysis(1,1,61524,lumi,hC->GetBinContent(2));
   TChain* ch3 = new TChain("TopTree/events");
   ch3->Add(Form("%s/hep_WJets.root",dir.Data()),nevt);
   ch3->Process(C);
   
   MyAnalysis *D = new MyAnalysis(1,1,6025.2,lumi,hD->GetBinContent(1));
   TChain* ch4 = new TChain("TopTree/events");
   ch4->Add(Form("%s/hep_DYJets.root",dir.Data()),nevt);
   ch4->Process(D);
  
   MyAnalysis *E = new MyAnalysis(1,1,18610.0,lumi,hE->GetBinContent(1));
   TChain* ch5 = new TChain("TopTree/events");
   ch5->Add(Form("%s/hep_DYJets_10to50.root",dir.Data()),nevt);
   ch5->Process(E);
 
   MyAnalysis *I = new MyAnalysis(1,1,44.33,lumi,hI->GetBinContent(1));
   TChain* ch6 = new TChain("TopTree/events");
   ch6->Add(Form("%s/hep_SingleTop_t.root",dir.Data()),nevt);
   ch6->Process(I);
  
   MyAnalysis *J = new MyAnalysis(1,1,26.38,lumi,hJ->GetBinContent(1));
   TChain* ch7 = new TChain("TopTree/events");
   ch7->Add(Form("%s/hep_SingleTbar_t.root",dir.Data()),nevt);
   ch7->Process(J);

   MyAnalysis *K = new MyAnalysis(1,1,35.6,lumi,hK->GetBinContent(1));
   TChain* ch8 = new TChain("TopTree/events");
   ch8->Add(Form("%s/hep_SingleTop_tW.root",dir.Data()),nevt);
   ch8->Process(K);

   MyAnalysis *L = new MyAnalysis(1,1,35.6,lumi,hL->GetBinContent(1));
   TChain* ch9 = new TChain("TopTree/events");
   ch9->Add(Form("%s/hep_SingleTbar_tW.root",dir.Data()),nevt);
   ch9->Process(L);
   
   MyAnalysis *N = new MyAnalysis(1,1,118.7,lumi,hN->GetBinContent(1));
   TChain* ch10 = new TChain("TopTree/events");
   ch10->Add(Form("%s/hep_WW.root",dir.Data()),nevt);
   ch10->Process(N);

   MyAnalysis *O = new MyAnalysis(1,1,47.13,lumi,hO->GetBinContent(1));
   TChain* ch11 = new TChain("TopTree/events");
   ch11->Add(Form("%s/hep_WZ.root",dir.Data()),nevt);
   ch11->Process(O);
   
   MyAnalysis *M = new MyAnalysis(1,1,16.523,lumi,hM->GetBinContent(1));
   TChain* ch12 = new TChain("TopTree/events");
   ch12->Add(Form("%s/hep_ZZ.root",dir.Data()),nevt);
   ch12->Process(M);
 
Plotter P;

   for (int i=0; i < 6 ;i++) {
   //for (int i=0; i < D->histograms.size() ;i++) {
     //merge for DY
     D->histograms[i]->Add(E->histograms[i]);
     //merge for SingleTop
     I->histograms[i]->Add(J->histograms[i]);
     I->histograms[i]->Add(K->histograms[i]);
     I->histograms[i]->Add(L->histograms[i]);
    //////merge for VV 
     N->histograms[i]->Add(O->histograms[i]);
     N->histograms[i]->Add(M->histograms[i]);
////tt bkg     
  //   B->histograms[i]->Add(Bhad->histograms[i]);

} 
   P.SetData(A->histograms, std::string("Data"));
   P.AddBg(Bsemi->histograms, std::string("TTbar"));
   P.AddBg(C->histograms, std::string("Wjets"));
   P.AddBg(D->histograms, std::string("DY"));
   P.AddBg(I->histograms, std::string("Single Top"));
   P.AddBg(N->histograms, std::string("VV"));
   
  P.AddBg(B->histograms, std::string("TTOthers"));

   P.Plot(string("results_ABCD.pdf"));

   TFile * outA = TFile::Open("hist_data.root","RECREATE");
   for(int i=0; i < A->histograms.size(); i++){
     TH1F * tmp = (TH1F *) A->histograms[i];
     tmp->Write();
   }
   for(int i=0; i < A->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) A->histograms_2D[i];
     tmp->Write();
   }
   outA->Write();
   outA->Close();

   TFile * outB = TFile::Open("hist_TT_others.root","RECREATE");
   for(int i=0; i < B->histograms.size(); i++){
     TH1F * tmp = (TH1F *) B->histograms[i];
     tmp->Write();
   }
   for(int i=0; i < B->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) B->histograms_2D[i];
     tmp->Write();
   }
   outB->Write();
   outB->Close();

   TFile * outBsemi = TFile::Open("hist_TT_SemiLeptonic.root","RECREATE");
   for(int i=0; i < Bsemi->histograms.size(); i++){
     TH1F * tmp = (TH1F *) Bsemi->histograms[i];
     tmp->Write();
   }
   for(int i=0; i < Bsemi->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) Bsemi->histograms_2D[i];
     tmp->Write();
   }
   outBsemi->Write();
   outBsemi->Close();
   
  TFile * outC = TFile::Open("hist_WJets.root","RECREATE");
   for(int i=0; i < C->histograms.size(); i++){
     TH1F * tmp = (TH1F *) C->histograms[i];
     tmp->Write();
   }
   for(int i=0; i < C->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) C->histograms_2D[i];
     tmp->Write();
   }
   outC->Write();
   outC->Close();

   TFile * outD = TFile::Open("hist_DY.root","RECREATE");
   for(int i=0; i < D->histograms.size(); i++){
     TH1F * tmp = (TH1F *) D->histograms[i];
     tmp->Write();
    }
   for(int i=0; i < D->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) D->histograms_2D[i];
     tmp->Write();
   }
   outD->Write();
   outD->Close();
   
    TFile * outI = TFile::Open("hist_SingleTop.root","RECREATE");
    for(int i=0; i < I->histograms.size(); i++){
      TH1F * tmp = (TH1F *) I->histograms[i];
      tmp->Write();
    }
   for(int i=0; i < I->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) I->histograms_2D[i];
     tmp->Write();
   }
    outI->Write();
    outI->Close();

  TFile * outN = TFile::Open("hist_VV.root","RECREATE");
   for(int i=0; i < N->histograms.size(); i++){
     TH1F * tmp = (TH1F *) N->histograms[i];
     tmp->Write();
   }
   for(int i=0; i < N->histograms_2D.size(); i++){
     TH2D * tmp = (TH2D *) N->histograms_2D[i];
     tmp->Write();
   }
   outN->Write();
   outN->Close();
}
void TP_eff_mu(TString fileName = "SingleMuon_Run2016_TP", // RooT file with TP otree for data 

 	  TString what = "IdIso", //what do you want to evaluated
 	  float iso = 0.1, //isolation cut to be used
	  float norm = 1 // luminosity normalization factor (1 for data) 
	  ) 
{

	gErrorIgnoreLevel = kFatal;

  // output inizialization 
  TString lepton = "Muon";
	TString OutFileName = fileName + "_" + lepton + "_" + what + "_IsoLt" + Form("%.2f", iso) + "_eff_Spring16";
	TFile * outputFile = new TFile(OutFileName+".root","recreate");

	// Title of axis in plots  
	TString yTitle = "Efficiency";
	TString xTitle = lepton+"  p_{T}[GeV]";
	TString xtit; 
	xtit = "m_{#mu#mu}[GeV]"; 

	//names of final graphs - suffix
	bool isData=false;
	if (fileName.Contains("SingleMuon")) isData = true;
  TString SampleName("_MC");
  if (isData) SampleName = "_Data";

  //open input file
	TFile * file = new TFile(fileName+".root");
  file->cd();
  TTree *t = (TTree*)(file->Get("TagProbe"));


  //binning inizialization

  int nEtaBins = 3;
	float etaBins[4] = {0,0.9,1.2,2.1};

	TString EtaBins[3] = {"EtaLt0p9",
				"Eta0p9to1p2",
				"EtaGt1p2"};

	float ptBins_def[8] = {10,15,20,25,30,40,60,1000};

	TString PtBins_def[7] = {"Pt10to15",
       "Pt15to20",
       "Pt20to25",
       "Pt25to30",
       "Pt30to40",
       "Pt40to60",
       "PtGt60"};

  float ptBinsTrig_def[17] = {10,
			  13,
			  16,
			  19,
			  22,
			  25,
			  28,
			  31,
			  34,
			  37,
			  40,
			  45,
			  50,
			  60,
			  70,
			  100,
				1000};

	TString PtBinsTrig_def[16] = {"Pt10to13",
		    "Pt13to16",
		    "Pt16to19",
		    "Pt19to22",
		    "Pt22to25",
		    "Pt25to28",
		    "Pt28to31",
		    "Pt31to34",
		    "Pt34to37",
		    "Pt37to40",
		    "Pt40to45",
		    "Pt45to50",
		    "Pt50to60",
		    "Pt60to70",
		    "Pt70to100",
		    "PtGt100"};

	int nPtBins = 16; if(what == "IdIso") nPtBins = 7;
	float * ptBins = new float[nPtBins+1];
	TString * PtBins = new TString[nPtBins];

	if(what == "IdIso"){
		for(int i=0; i<nPtBins; ++i){
			ptBins[i] = ptBins_def[i];
			PtBins[i] = PtBins_def [i];
		}
		ptBins[nPtBins] = ptBins_def[nPtBins];
	} else {
		for(int i=0; i<nPtBins; ++i){
			ptBins[i] = ptBinsTrig_def[i];
			PtBins[i] = PtBinsTrig_def[i];
		}
		ptBins[nPtBins] = ptBinsTrig_def[nPtBins];
	}


  //	create eta histogram with eta ranges associated to their names (eg. endcap, barrel)   ***** //

	TH1D * etaBinsH = new TH1D("etaBinsH", "etaBinsH", nEtaBins, etaBins);
  etaBinsH->Draw();
  etaBinsH->GetXaxis()->Set(nEtaBins, etaBins);
  for (int i=0; i<nEtaBins; i++){ etaBinsH->GetXaxis()->SetBinLabel(i+1, EtaBins[i]);}
  etaBinsH->Draw();


	//	create pt histogram_s with pt ranges associated to their names (eg. Pt10to13, ..)   ***** //

	TH1D * ptBinsH =  new TH1D("ptBinsH", "ptBinsH", nPtBins, ptBins);
  ptBinsH->Draw();
  ptBinsH->GetXaxis()->Set(nPtBins, ptBins);
  for (int i=0; i<nPtBins; i++){ ptBinsH->GetXaxis()->SetBinLabel(i+1, PtBins[i]);}
  ptBinsH->Draw();

  float ptBins_edges[nPtBins+1];

	for (int i=0; i<nPtBins; i++) { ptBins_edges[i]=ptBinsH->GetBinLowEdge(i+1); }
	ptBins_edges[nPtBins]= ptBinsH->GetBinLowEdge(nPtBins+1); 

  
	// define if in the fit of failing probes
  // the FSR component will be used in the 
  // signal function 
  bool fitWithFSR[nPtBins];

  for (int i=0; i<nPtBins; i++)  fitWithFSR[i] = true;

  if(what == "IdIso"){
   	fitWithFSR[0]=false;
    fitWithFSR[1]=false;
    fitWithFSR[5]=false;
    fitWithFSR[6]=false;
  } else{ for (int i=0; i<nPtBins; i++)  fitWithFSR[i] = false; }

	// building the histogram base name
  TString prefix = "ZMass";
  TString which = what; 
  if (what == "IdIso") which = "";
  which = "";
  TString histBaseName; 

  //definition of the passing and failing criterias

  TCut cut_flag_idiso_pass, cut_flag_hlt_pass, cut_flag_hlt_fail, cut_pt, cut_eta;

  if (what == "IdIso") {
  	cut_flag_idiso_pass = Form("id_probe == 1 && iso_probe < %f", iso);
  } else{
  		if(what == "hlt_1") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_1_probe == 0"; }
  		if(what == "hlt_2") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_2_probe == 0"; }
  		if(what == "hlt_3") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_3_probe == 0"; }
  		if(what == "hlt_4") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_4_probe == 0"; }
  		if(what == "hlt_5") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_5_probe == 0"; }
  		if(what == "hlt_6") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_6_probe == 0"; }
  		if(what == "hlt_7") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_7_probe == 0"; }
  		if(what == "hlt_8") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_8_probe == 0"; }
  		if(what == "hlt_9") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_9_probe == 0"; }
  		if(what == "hlt_10") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_10_probe == 0"; }
  		if(what == "hlt_11") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_11_probe == 0"; }
  		if(what == "hlt_12") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_12_probe == 0"; }
  		if(what == "hlt_13") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_13_probe == 0"; }
  		if(what == "hlt_14") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_14_probe == 0"; }
  		if(what == "hlt_15") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_15_probe == 0"; }
  		if(what == "hlt_16") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_16_probe == 0"; }
  		if(what == "hlt_17") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_17_probe == 0"; }
  		if(what == "hlt_18") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_18_probe == 0"; }
  		if(what == "hlt_19") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_19_probe == 0"; }
  		if(what == "hlt_20") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_20_probe == 0"; }
  	}

  //Definition of the output directory names and creation of it
	TString dir_name = "Muon_";
	dir_name += what;
	dir_name += Form("_IsoLt%.2f", iso);
	if (!isData) dir_name += "_MC";
	dir_name += "_eff";
	gSystem->mkdir(dir_name, kTRUE);

	for (int iEta = 0; iEta < nEtaBins; iEta++) { //loop on eta bins

		histBaseName = prefix+which+EtaBins[iEta];

		//eta cuts
		cut_eta = Form("abs(eta_probe)>= %f && abs(eta_probe)< %f", etaBins[iEta], etaBins[iEta+1]);

		TH1F * numeratorH   = new TH1F("numeratorH","",nPtBins,ptBins_edges);
		TH1F * denominatorH = new TH1F("denominatorH","",nPtBins,ptBins_edges);
	
	  for (int iPt=0; iPt<nPtBins; ++iPt) { //loop on pt bins

	  	//pt cuts
	  	cut_pt = Form("pt_probe > %f && pt_probe < %f", ptBins[iPt], ptBins[iPt+1]);

	  	TH1F * histPassOld = new TH1F("histPassOld","",250,50,300);
	  	TH1F * histFailOld = new TH1F("histFailOld","",250,50,300);
	  	
	  	//Drawing histogram of passing and failing probes
	  	if (what == "IdIso") {
		  	t->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_idiso_pass));
		  	t->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && !cut_flag_idiso_pass));
		  }else{
		  	t->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_pass && cut_flag_idiso_pass));
		  	t->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_fail && cut_flag_idiso_pass));
		  }

	  	int nBinsX = histPassOld->GetNbinsX();

	  	//lumi renormalization
	    for (int iB=1;iB<=nBinsX;++iB) {
	      histPassOld->SetBinContent(iB,norm*histPassOld->GetBinContent(iB));
	      histPassOld->SetBinError(iB,norm*histPassOld->GetBinError(iB));
	      histFailOld->SetBinContent(iB,norm*histFailOld->GetBinContent(iB));
	      histFailOld->SetBinError(iB,norm*histFailOld->GetBinError(iB));
	    }

	    float output[2];
	    TCanvas * c1 = new TCanvas("c1","",700,600);
	    TCanvas * c2 = new TCanvas("c2","",700,600);


	    //defining fit options
	    bool fitPass = true; 
	    bool fitFail = true;
	    bool rebinPass = false;
	    bool rebinFail = false;
	    if(what != "IdIso") {fitPass= false; fitFail = false;}

	    //fitting
	    FitPassAndFail(fileName,
	    	histBaseName+PtBins[iPt],
	    	xtit,
	    	histPassOld,
	    	histFailOld,
	    	fitPass,
	    	fitFail,
	    	fitWithFSR[iPt],
	    	rebinPass,
	    	rebinFail,
	    	c1,
	    	c2,
	    	output,
	    	dir_name);


	    c1->cd();
	    c1->Update();
	    c2->cd();
	    c2->Update();
	    numeratorH->SetBinContent(iPt+1,output[0]);
	    denominatorH->SetBinContent(iPt+1,output[0]+output[1]);

	  }

	  outputFile->cd();

	  //produce efficiencies plot
	  TGraphAsymmErrors * eff = new TGraphAsymmErrors();
	  eff->Divide(numeratorH,denominatorH);

	  eff->GetXaxis()->SetTitle(xTitle);
	  //  eff->GetXaxis()->SetRangeUser(10.01,59.99);
	  eff->GetYaxis()->SetRangeUser(0,1.0);
	  eff->GetXaxis()->SetRangeUser(0,99.99);
	  eff->GetYaxis()->SetTitle(yTitle);
	  eff->GetXaxis()->SetTitleOffset(1.1);
	  eff->GetXaxis()->SetNdivisions(510);
	  eff->GetYaxis()->SetTitleOffset(1.1);
	  eff->SetMarkerStyle(21);
	  eff->SetMarkerSize(1);
	  eff->SetMarkerColor(kBlue);
	  eff->SetLineWidth(2);
	  eff->SetLineColor(kBlue);
	  if(!isData){
	  	eff->SetMarkerColor(kRed);
	  	eff->SetLineColor(kRed);
	  }


	  TCanvas * canv = new TCanvas("canv","",700,600);
	  eff->Draw("APE");
	  canv->SetGridx();
	  canv->SetGridy();
	  canv->Update();

	  canv->SaveAs(dir_name + "/" + fileName+"_" + histBaseName + ".png");
	  eff->Write(histBaseName+SampleName);

/*	  for(int ip=0; ip<nPtBins; ++ip){
		cout<<"PtBins "<<ip<<" content: "<<numeratorH->GetBinContent(ip)/ denominatorH->GetBinContent(ip)<<endl;
	}*/

	}

	//closing
	outputFile->cd(); 
	etaBinsH->Write();
	outputFile->Close();

}
Example #20
0
File: calccorr.C Project: XuQiao/HI
void calccorr(int i=1,string t="ptfiner"){
float const PI = acos(-1.0);
if(i==0){
const int ncent = 6;
const int npt = 25;
TString dire="north";
}
else if(i==1){
const int ncent = 6;
const int npt = 25;
TString dire="south";
}
else if(i==2){
const int ncent = 6;
const int npt = 1;
TString dire="sn";
}

TFile *f=TFile::Open("../../../work/20GeV/output_3corrF.root");
TH1F* kforebbcw[ncent][npt];
TH1F* hforebbcw[ncent][npt];
TH1F* kbackbbcw2[ncent][npt];
TH1F* kforebbcw_In;
TH1F* hforebbcw_In;
TH1F* kbackbbcw2_In;
double ptbin[26] = {0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
double centbin[7] = {0,0.05,0.1,0.2,0.4,0.6,1.0};
//double centbin[ncent+1] = {0,1,2};
TString type = t.c_str();
if(type=="ptIn25_4"){
double selptbin[] = {2.5,4.0};
double selcentbin[ncent+1] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptIn"){
    if(i==2){
double selptbin[] = {0.0,0.2};
    }
    else{
double selptbin[] = {0.4,3.0};
    }
double selcentbin[] = {0,0.05,0.1,0.2,0.4,0.6,1.0};
}
else if(type=="ptcoarser"){
double selptbin[] = {0.2,1.0,2.0,3.0,5.0};
double selcentbin[] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptfiner"){
double selptbin[] = {0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
double selcentbin[] = {0,0.05,0.1,0.2,0.4,0.6,1.0};
//double selcentbin[ncent+1] = {0,1,2};
}
else if(type=="centIn"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {0,1.0};
}
else if(type=="ptccentc"){
double selptbin[] = {0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.4,4.6,4.8,5.0};
double selcentbin[] = {0,0.1};
}
else{exit(0);};

/*double ptmin = 1.0; double ptmax = 3.0;//has to be boundary
for(int ipt=0; ipt<npt; ipt++){
if(ptmin >= ptbin[ipt] && ptmin < ptbin[ipt+1]){int xptmin = ipt; continue;}
if(ptmax >= ptbin[ipt] && ptmax < ptbin[ipt+1]){int xptmax = ipt; continue;}
}*/
  ofstream fout(Form("c1_c2_central_%s_%s.dat",type.Data(),dire.Data()));
for(int icent=0; icent<ncent; icent++){
for(int ipt=0; ipt<npt; ipt++){
kforebbcw[icent][ipt] = (TH1F*)f->Get(Form("kfore%sbbcw_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("kforenorthbbcw_%d_%d",icent,ipt));
//kforebbcw[icent][ipt]->Add(htemp,-1);
hforebbcw[icent][ipt] = (TH1F*)f->Get(Form("hfore%sbbcw_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("hforenorthbbcw_%d_%d",icent,ipt));
//hforebbcw[icent][ipt]->Add(htemp,-1);
kbackbbcw2[icent][ipt] = (TH1F*)f->Get(Form("kback%sbbcw2_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("kbacknorthbbcw2_%d_%d",icent,ipt));
//kbackbbcw2[icent][ipt]->Add(htemp,-1);
}
}
int ncent_a = sizeof(selcentbin)/sizeof(double)-1;
int npt_a = sizeof(selptbin)/sizeof(double)-1;
for(int icent_a=0;icent_a<ncent+1;icent_a++){
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a] == centbin[icent_b]) break;
int xcentmin = icent_b;
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a+1] == centbin[icent_b]) break;
int xcentmax = icent_b;
if((xcentmin == ncent+1) || (xcentmax == ncent+1)) exit(0);
for(int ipt_a=0;ipt_a<npt_a;ipt_a++){
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a] == ptbin[ipt_b]) break;
int xptmin = ipt_b;
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a+1] == ptbin[ipt_b]) break;
int xptmax = ipt_b;
if((xptmin == npt+1) || (xptmax == npt+1)) exit(0);
cout<<xcentmin<<"\t"<<xcentmax<<"\t"<<endl;
cout<<xptmin<<"\t"<<xptmax<<"\t"<<endl;
kforebbcw_In = (TH1F*)kforebbcw[xcentmin][xptmin]->Clone();
hforebbcw_In = (TH1F*)hforebbcw[xcentmin][xptmin]->Clone();
kbackbbcw2_In = (TH1F*)kbackbbcw2[xcentmin][xptmin]->Clone();
kforebbcw_In->Reset();
hforebbcw_In->Reset();
kbackbbcw2_In->Reset();
for(int icent=xcentmin; icent<xcentmax; icent++){
for(int ipt=xptmin; ipt<xptmax; ipt++){
kforebbcw_In->Add(kforebbcw[icent][ipt]);
hforebbcw_In->Add(hforebbcw[icent][ipt]);
kbackbbcw2_In->Add(kbackbbcw2[icent][ipt]);
}
}
kforebbcw_In->Rebin(2);
hforebbcw_In->Rebin(2);
kbackbbcw2_In->Rebin(2);


TH1F* hpp;
TH1F* hbackpp;
  hpp = (TH1F*)kforebbcw_In->Clone();
  hbackpp = (TH1F*)kbackbbcw2_In->Clone();
  float nbackpp = hbackpp->Integral()/2.0/PI;
  float nforepp = hpp->Integral()/2.0/PI;
  //float ntrig0 = ptforedis_0->Integral(11,30);
   for(int i=0; i<20; i++){
     float pp_cont = 1.0*hpp->GetBinContent(i+1);
     //float pp0_err = 1.0*hpp->GetBinError(i+1);
     float weight2 = sqrt(1.0*hforebbcw_In->GetBinContent(i+1));

     float backpp_cont = 1.0*hbackpp->GetBinContent(i+1);
    
     float con = pp_cont/backpp_cont*nbackpp/nforepp;
     float err = weight2/backpp_cont*nbackpp/nforepp;

     hpp->SetBinContent(i+1, con);
     hpp->SetBinError(i+1, err);

   }
  TF1 *fun0 = new TF1("fun0","[0]*(1+2*[1]*cos(x)+2*[2]*cos(2*x)+2*[3]*cos(3*x)+2*[4]*cos(4*x))", -0.5*PI, 1.5*PI);

  fun0->SetLineColor(1);
  hpp->Fit("fun0","NORQ");

  TF1 *fun1 = new TF1("fun1","[0]*(1+2*[1]*cos(x))",   -0.5*PI, 1.5*PI);
  TF1 *fun2 = new TF1("fun2","[0]*(1+2*[1]*cos(2*x))", -0.5*PI, 1.5*PI);
  TF1 *fun3 = new TF1("fun3","[0]*(1+2*[1]*cos(3*x))", -0.5*PI, 1.5*PI);
  TF1 *fun4 = new TF1("fun4","[0]*(1+2*[1]*cos(4*x))", -0.5*PI, 1.5*PI);

//const double ptmean[npt] = {0.360943, 0.691833, 1.1911, 1.69654, 2.20117, 2.70571, 3.2097, 3.71372, 4.21814, 4.72014};
  fout<<fun0->GetParameter(1)<<" "<<fun0->GetParError(1)<<" "
      <<fun0->GetParameter(2)<<" "<<fun0->GetParError(2)<<" "//<<0.05*fun0->GetParameter(2)<<" "<<endl;
      <<fun0->GetParameter(3)<<" "<<fun0->GetParError(3)<<endl;
}
}
  fout.close();

/*  
  cout<<"*************** v2 ***********"<<endl;
  float v2_0 = funvn0->GetParameter(1)/(zym_pp0 + funvn0->GetParameter(0));
  float v2_1 = funvn1->GetParameter(1)/(zym_pp1 + funvn1->GetParameter(0));
  float v2_2 = funvn2->GetParameter(1)/(zym_pp2 + funvn2->GetParameter(0));
  float v2_3 = funvn3->GetParameter(1)/(zym_pp3 + funvn3->GetParameter(0));
  

  cout<<v2_0<<" "<<v2_1<<" "<<v2_2<<" "<<v2_3<<endl;
 
  
  cout<<funvn0->GetParameter(0)*funvn0->GetParameter(1)<<" "
      <<funvn1->GetParameter(0)*funvn1->GetParameter(1)<<" "
      <<funvn2->GetParameter(0)*funvn2->GetParameter(1)<<" "
      <<funvn3->GetParameter(0)*funvn3->GetParameter(1)<<endl;
  

  cout<<"*************** v2 ***********"<<endl;
  cout<<funvn0->GetParameter(2)<<" "<<funvn1->GetParameter(2)<<" "<<funvn2->GetParameter(2)<<" "<<funvn3->GetParameter(2)<<endl;

  cout<<"*************** v3 ***********"<<endl;
  cout<<funvn0->GetParameter(3)<<" "<<funvn1->GetParameter(3)<<" "<<funvn2->GetParameter(3)<<" "<<funvn3->GetParameter(3)<<endl;
*/
}
void cutFlowStudyMu( TString weightFile = "TMVAClassificationPtOrd_qqH115vsWZttQCD_Cuts.weights.xml",
		     Double_t effS_ = 0.3) 
{
  
  ofstream out("cutFlow-MuTauStream.txt");
  out.precision(4);

  TMVA::Tools::Instance();
  TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );   

  Float_t pt1, pt2;
  Float_t Deta, Mjj;
  Float_t eta1,eta2;

  reader->AddVariable( "pt1", &pt1);
  reader->AddVariable( "pt2", &pt2);
  reader->AddVariable( "Deta",&Deta);
  reader->AddVariable( "Mjj", &Mjj);
  reader->AddSpectator("eta1",&eta1);
  reader->AddSpectator("eta2",&eta2);
  reader->BookMVA( "Cuts", TString("/home/llr/cms/lbianchini/CMSSW_3_9_9/src/Bianchi/TauTauStudies/test/Macro/weights/")+weightFile ); 
 
  TFile *fFullSignalVBF           = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_VBFH115-Mu-powheg-PUS1.root","READ"); 
  TFile *fFullSignalGGH           = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_GGFH115-Mu-powheg-PUS1.root","READ");  
  TFile *fFullBackgroundDYTauTau  = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_DYToTauTau-Mu-20-PUS1.root","READ"); 
  TFile *fFullBackgroundDYMuMu    = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_DYToMuMu-20-PUS1.root","READ"); 
  TFile *fFullBackgroundWJets     = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_WJets-Mu-madgraph-PUS1.root","READ"); 
  TFile *fFullBackgroundQCD       = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_QCDmu.root","READ"); 
  TFile *fFullBackgroundTTbar     = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_TTJets-Mu-madgraph-PUS1.root","READ"); 
  TFile *fFullBackgroundDiBoson   = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_DiBoson-Mu.root","READ"); 

  // OpenNTuples
  TString fSignalNameVBF           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleVBFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fSignalNameGGH           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleGGFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYTauTau  = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleDYToTauTau-Mu-20-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYMuMu  = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleDYToMuMu-20-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameWJets     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleWJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameQCD       = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleQCDmu_Open_MuTauStream.root";
  TString fBackgroundNameTTbar     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleTTJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDiBoson   = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleDiBoson-Mu_Open_MuTauStream.root";

  TFile *fSignalVBF(0); 
  TFile *fSignalGGH(0); 
  TFile *fBackgroundDYTauTau(0);
  TFile *fBackgroundDYMuMu(0);
  TFile *fBackgroundWJets(0);
  TFile *fBackgroundQCD(0);
  TFile *fBackgroundTTbar(0);
  TFile *fBackgroundDiBoson(0);
 
  fSignalVBF          = TFile::Open( fSignalNameVBF ); 
  fSignalGGH          = TFile::Open( fSignalNameGGH ); 
  fBackgroundDYTauTau = TFile::Open( fBackgroundNameDYTauTau ); 
  fBackgroundDYMuMu   = TFile::Open( fBackgroundNameDYMuMu ); 
  fBackgroundWJets    = TFile::Open( fBackgroundNameWJets ); 
  fBackgroundQCD      = TFile::Open( fBackgroundNameQCD ); 
  fBackgroundTTbar    = TFile::Open( fBackgroundNameTTbar ); 
  fBackgroundDiBoson  = TFile::Open( fBackgroundNameDiBoson ); 

  if(!fSignalVBF || !fBackgroundDYTauTau || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar ||
     !fSignalGGH || !fBackgroundDYMuMu || !fBackgroundDiBoson ){
    std::cout << "ERROR: could not open files" << std::endl;
    exit(1);
  }

  TString tree = "outTreePtOrd";

  TTree *signalVBF           = (TTree*)fSignalVBF->Get(tree);
  TTree *signalGGH           = (TTree*)fSignalGGH->Get(tree);
  TTree *backgroundDYTauTau  = (TTree*)fBackgroundDYTauTau->Get(tree);
  TTree *backgroundDYMuMu    = (TTree*)fBackgroundDYMuMu->Get(tree);
  TTree *backgroundWJets     = (TTree*)fBackgroundWJets->Get(tree);
  TTree *backgroundQCD       = (TTree*)fBackgroundQCD->Get(tree);
  TTree *backgroundTTbar     = (TTree*)fBackgroundTTbar->Get(tree);
  TTree *backgroundDiBoson   = (TTree*)fBackgroundDiBoson->Get(tree);

  // here I define the map between a sample name and its tree
  std::map<std::string,TTree*> tMap;
  tMap["ggH115"]=signalGGH;
  tMap["qqH115"]=signalVBF;
  tMap["Ztautau"]=backgroundDYTauTau;
  tMap["Zmumu"]=backgroundDYMuMu;
  tMap["Wjets"]=backgroundWJets;
  tMap["QCD"]=backgroundQCD;
  tMap["TTbar"]=backgroundTTbar;
  tMap["DiBoson"]=backgroundDiBoson;

  std::map<std::string,TTree*>::iterator jt;

  Float_t pt1_, pt2_;
  Float_t Deta_, Mjj_;
  Float_t Dphi,diTauSVFitPt,diTauSVFitEta,diTauVisMass,diTauSVFitMass,ptL1,ptL2,etaL1,etaL2,diTauCharge,MtLeg1,numPV,combRelIsoLeg1,sampleWeight,ptVeto,HLT;
  Int_t tightestHPSWP;

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



  // here I choose the order in the stack
  std::vector<string> samples;
  samples.push_back("ggH115");
  samples.push_back("qqH115");
  samples.push_back("DiBoson");
  samples.push_back("TTbar");
  samples.push_back("Wjets");
  samples.push_back("Zmumu");
  samples.push_back("Ztautau");
  samples.push_back("QCD");

  std::map<std::string,float> crossSec;
  crossSec["ggH115"]=( 7.65e-02 * 18.13 );
  crossSec["qqH115"]=( 0.1012);
  crossSec["DiBoson"]=( -1  );
  crossSec["TTbar"]=( 157.5 );
  crossSec["Wjets"]=( 31314.0);
  crossSec["Zmumu"]=( 1666  );
  crossSec["Ztautau"]=( 1666  );
  crossSec["QCD"]=( 296600000*0.0002855 );

  float Lumi = 1000;


  // here I choose the order in the stack
  std::vector<string> filters;
  filters.push_back("total");
  filters.push_back("vertex");
  filters.push_back("1-mu");
  filters.push_back("0-e");
  filters.push_back("mu-ID");
  filters.push_back("tau-ID");
  filters.push_back("Delta R mu-tau");
  filters.push_back("mu-iso");
  filters.push_back("tau-iso");
  filters.push_back("Mt");
  filters.push_back("OS");
  filters.push_back("2-jets");
  filters.push_back("VBF cuts");
  filters.push_back("jet-veto");
  filters.push_back("HLT");

  // here I define the map between a sample name and its file ptr
  std::map<std::string,TFile*> fullMap;
  fullMap["ggH115"]   = fFullSignalGGH;
  fullMap["qqH115"]   = fFullSignalVBF;
  fullMap["Ztautau"]  = fFullBackgroundDYTauTau;
  fullMap["Zmumu"]    = fFullBackgroundDYMuMu;
  fullMap["Wjets"]    = fFullBackgroundWJets;
  fullMap["QCD"]      = fFullBackgroundQCD;
  fullMap["TTbar"]    = fFullBackgroundTTbar;
  fullMap["DiBoson"]  = fFullBackgroundDiBoson;

  std::map<std::string,TFile*>::iterator it;

  std::map<std::string,float> cutMap_allEventsFilter;
  std::map<std::string,float> cutMap_allEventsFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    float tot = totalEvents;
    if(crossSec[it->first]>0) tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    cutMap_allEventsFilter[it->first] = tot;
    cutMap_allEventsFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_vertexScrapingFilter;
  std::map<std::string,float> cutMap_vertexScrapingFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("vertexScrapingFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_vertexScrapingFilter[it->first] = tot;
    cutMap_vertexScrapingFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_oneElectronFilter;
  std::map<std::string,float> cutMap_oneElectronFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("oneMuonFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_oneElectronFilter[it->first] = tot;
    cutMap_oneElectronFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_noMuonFilter;
  std::map<std::string,float> cutMap_noMuonFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("noElecFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_noMuonFilter[it->first] = tot;
    cutMap_noMuonFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_electronLegFilter;
  std::map<std::string,float> cutMap_electronLegFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("muonLegFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_electronLegFilter[it->first] = tot;
    cutMap_electronLegFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_tauLegFilter;
  std::map<std::string,float> cutMap_tauLegFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("tauLegFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_tauLegFilter[it->first] = tot;
    cutMap_tauLegFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_atLeastOneDiTauFilter;
  std::map<std::string,float> cutMap_atLeastOneDiTauFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("atLeastOneDiTauFilter/totalEvents");
    float tot = allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_atLeastOneDiTauFilter[it->first] = tot;
    cutMap_atLeastOneDiTauFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_ElecIso;
  std::map<std::string,float> cutMap_ElecIsoE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_ElecIso[it->first] = tot;
    cutMap_ElecIsoE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_TauIso;
  std::map<std::string,float> cutMap_TauIsoE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_TauIso[it->first] = tot;
    cutMap_TauIsoE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_Mt;
  std::map<std::string,float> cutMap_MtE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && MtLeg1<40"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && MtLeg1<40)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_Mt[it->first] = tot;
    cutMap_MtE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_OS;
  std::map<std::string,float> cutMap_OSE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_OS[it->first] = tot;
    cutMap_OSE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_VBFPre;
  std::map<std::string,float> cutMap_VBFPreE;
  for(jt = tMap.begin(); jt != tMap.end(); jt++){
    cout<<jt->first<<endl;
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  "sampleWeight*(pt1>0 && combRelIsoLeg1<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40)"; 
    jt->second->Draw("etaL1>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    cutMap_VBFPre[jt->first] = tot;
    cutMap_VBFPreE[jt->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_VBF;
  std::map<std::string,float> cutMap_VBFE;
  std::map<std::string,float> cutMap_JetVeto;
  std::map<std::string,float> cutMap_JetVetoE;
  std::map<std::string,float> cutMap_HLT;
  std::map<std::string,float> cutMap_HLTE;
  for(jt = tMap.begin(); jt != tMap.end(); jt++){
    cout<<jt->first<<endl;
    TCut cut =  "(pt1>0 && combRelIsoLeg1<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40)"; 

    TFile* dummy = new TFile("dummy.root","RECREATE");  
    TTree* currentTree = (TTree*)(jt->second)->CopyTree(cut);
    float tot = 0;
    int counter = 0;
    float tot2 = 0;
    int counter2 = 0;
    float tot3 = 0;
    int counter3 = 0;

    currentTree->SetBranchAddress( "pt1", &pt1_ );
    currentTree->SetBranchAddress( "pt2", &pt2_ );
    currentTree->SetBranchAddress( "Deta",&Deta_ );
    currentTree->SetBranchAddress( "Mjj", &Mjj_ );
    currentTree->SetBranchAddress( "diTauSVFitPt",&diTauSVFitPt);
    //currentTree->SetBranchAddress( "diTauSVFitEta",&diTauSVFitEta);
    currentTree->SetBranchAddress( "diTauSVFitMass",&diTauSVFitMass);
    currentTree->SetBranchAddress( "diTauVisMass",&diTauVisMass);
    currentTree->SetBranchAddress( "ptL1", &ptL1 );
    currentTree->SetBranchAddress( "ptL2",  &ptL2 );
    currentTree->SetBranchAddress( "etaL1", &etaL1 );
    currentTree->SetBranchAddress( "etaL2", &etaL2 );
    currentTree->SetBranchAddress( "combRelIsoLeg1",&combRelIsoLeg1);
    currentTree->SetBranchAddress( "tightestHPSWP",&tightestHPSWP);
    currentTree->SetBranchAddress( "diTauCharge",&diTauCharge);
    currentTree->SetBranchAddress( "MtLeg1",&MtLeg1);
    currentTree->SetBranchAddress( "numPV",&numPV);
    currentTree->SetBranchAddress( "sampleWeight",&sampleWeight);
    currentTree->SetBranchAddress( "ptVeto",&ptVeto);
    currentTree->SetBranchAddress( "HLT",&HLT);

    for (Long64_t ievt=0; ievt<currentTree->GetEntries();ievt++) {

      currentTree->GetEntry(ievt);

      if (ievt%10000 == 0){
	std::cout << (jt->first) << " ---> processing event: " << ievt << " ..." <<std::endl;
      }

      pt1  = pt1_;
      pt2  = pt2_;
      Deta = Deta_;
      Mjj  = Mjj_;

      bool pass = effS_>0 ? reader->EvaluateMVA( "Cuts", effS_ ) : (pt1>0);

      if(pass){
	tot+=sampleWeight;
	counter++;
	if(ptVeto<20){
	  tot2+=sampleWeight;
	  counter2++;
	  if(HLT>0.5 && HLT<1.5){
	    tot3+=sampleWeight;
	    counter3++;
	  }
	}
      }
    
    }// end loop   

    cutMap_VBF[jt->first] = tot;
    cutMap_VBFE[jt->first] = counter>0 ? sqrt(counter)*tot/counter : 0;
    cutMap_JetVeto[jt->first] = tot2;
    cutMap_JetVetoE[jt->first] = counter2>0 ? sqrt(counter2)*tot2/counter2 : 0;
    cutMap_HLT[jt->first] = tot3;
    cutMap_HLTE[jt->first] = counter3>0 ? sqrt(counter3)*tot3/counter3 : 0;
  }


  
 

  std::vector< std::map<std::string,float> > allFilters;
  allFilters.push_back(cutMap_allEventsFilter);
  allFilters.push_back(cutMap_vertexScrapingFilter);
  allFilters.push_back(cutMap_oneElectronFilter);
  allFilters.push_back(cutMap_noMuonFilter);
  allFilters.push_back(cutMap_electronLegFilter);
  allFilters.push_back(cutMap_tauLegFilter);
  allFilters.push_back(cutMap_atLeastOneDiTauFilter);
  allFilters.push_back(cutMap_ElecIso);
  allFilters.push_back(cutMap_TauIso);
  allFilters.push_back(cutMap_Mt);
  allFilters.push_back(cutMap_OS);
  allFilters.push_back(cutMap_VBFPre);
  allFilters.push_back(cutMap_VBF);
  allFilters.push_back(cutMap_JetVeto);
  allFilters.push_back(cutMap_HLT);

  std::vector< std::map<std::string,float> > allFiltersE;
  allFiltersE.push_back(cutMap_allEventsFilterE);
  allFiltersE.push_back(cutMap_vertexScrapingFilterE);
  allFiltersE.push_back(cutMap_oneElectronFilterE);
  allFiltersE.push_back(cutMap_noMuonFilterE);
  allFiltersE.push_back(cutMap_electronLegFilterE);
  allFiltersE.push_back(cutMap_tauLegFilterE);
  allFiltersE.push_back(cutMap_atLeastOneDiTauFilterE);
  allFiltersE.push_back(cutMap_ElecIsoE);
  allFiltersE.push_back(cutMap_TauIsoE);
  allFiltersE.push_back(cutMap_MtE);
  allFiltersE.push_back(cutMap_OSE);
  allFiltersE.push_back(cutMap_VBFPreE);
  allFiltersE.push_back(cutMap_VBFE);
  allFiltersE.push_back(cutMap_JetVetoE);
  allFiltersE.push_back(cutMap_HLTE);

  //out<<"\\begin{center}"<<endl;
  out<<"\\begin{tabular}[!htbp]{|c";
  for(int k = 0 ; k < samples.size(); k++) out<<"|c";
  out<<"|} \\hline"<<endl;
  out<< "Cut & ";
  for(int k = 0 ; k < samples.size(); k++){
    out << (fullMap.find(samples[k]))->first;
    if(k!=samples.size()-1) out <<" & " ;
    else out << " \\\\ " << endl;
  }
  out <<  " \\hline" << endl;

  
  for(int i = 0; i < allFilters.size(); i++){
    out << filters[i] << " & ";
    for(int k = 0 ; k < samples.size(); k++){
      out << (allFilters[i].find(samples[k]))->second << " $\\pm$ " << (allFiltersE[i].find(samples[k]))->second;
      if(k!=samples.size()-1) out <<" & " ;
      else out << " \\\\ " << endl;
    }
    out <<  " \\hline" << endl;

  }
  
  out<<"\\end{tabular}"<<endl;
  //out<<"\\end{center}"<<endl;
 

  return;

}
int main(int argc, char* argv[]){
  TH1::AddDirectory(0);
  ModTDRStyle();
  string cfg;                                   // The configuration file

  bool do_ratio = false;
  bool do_logy = true;

  vector<string> datacards;
  string fitresult_file = "";
  string parse_rule = "";

  string output           = "";
  string text1            = "";
  string text2            = "";
  bool blinded            = true;
  bool postfit            = true;

  po::variables_map vm;
  po::options_description config("configuration");
  config.add_options()
    ("help,h",  "print the help message")
    ("datacards,d",
      po::value<vector<string>> (&datacards)->multitoken()->required())
    ("fitresult,f",
      po::value<string> (&fitresult_file))
    ("parse_rule,p",
      po::value<string> (&parse_rule)
      ->default_value("$MASS/$ANALYSIS_$CHANNEL_$BINID_$ERA.txt"))
    ("output",
      po::value<string>(&output)->required(),
      "[REQUIRED] output name (no extension)")
    ("text1",
      po::value<string>(&text1)->default_value(""),
      "[REQUIRED] output name (no extension)")
    ("text2",
      po::value<string>(&text2)->default_value(""),
      "[REQUIRED] output name (no extension)")
    ("blinded",
     po::value<bool>(&blinded)->default_value("true"),
     "[REQUIRED] blinded")
    ("postfit",
      po::value<bool>(&postfit)->required(),
      "[REQUIRED] use the pulls file to make a post-fit plot");
  po::store(po::command_line_parser(argc, argv)
    .options(config).allow_unregistered().run(), vm);
  po::notify(vm);

  ch::CombineHarvester cmb;
  // cmb.SetVerbosity(2);
  for (auto const& d : datacards) {
    cmb.ParseDatacard(d, parse_rule);
  }
  ch::SetStandardBinNames(cmb);

  RooFitResult* fitresult = nullptr;
  if (fitresult_file.length() && postfit) {
    fitresult =
        new RooFitResult(ch::OpenFromTFile<RooFitResult>(fitresult_file));
    auto fitparams = ch::ExtractFitParameters(*fitresult);
    cmb.UpdateParameters(fitparams);
  }

  auto bins = cmb.bin_set();



  TH1F proto("proto", "proto", 17, -3, 0.4);

  for (auto const& bin : bins) {
    ch::CombineHarvester cmb_bin = std::move(cmb.cp().bin({bin}));
    TH1F bkg = cmb_bin.cp().backgrounds().GetShape();
    TH1F sig = cmb_bin.cp().signals().GetShape();
    std::map<int, int> bin_mapping;
    for (int b = 1; b <= bkg.GetNbinsX(); ++b) {
      float i_sig = sig.GetBinContent(b);
      float i_bkg = bkg.GetBinContent(b);
      int bin_result = 1;
      if (i_sig > 0.) {
        float s_sb = i_sig / (i_sig + i_bkg);
        bin_result = proto.FindFixBin(std::log10(s_sb));
        if (bin_result == 0) {
          bin_result = 1;
        } else if (bin_result == 16) {
          std::cout << "Bin " << bin << " has an s/s+b == 1\n";
        } else if (bin_result == 18) {
          std::cout << "Bin " << bin << " has an s/s+b: " << s_sb << "\n";
          std::cout << "Bin " << bin << " has s: " << i_sig << "\n";
          std::cout << "Bin " << bin << " has b: " << i_bkg << "\n";
        }
      }
      bin_mapping[b] = bin_result;
    }
    cmb_bin.ForEachObs([&](ch::Observation *e) {
      TH1 const* old_h = e->shape();
      std::unique_ptr<TH1> new_h = ch::make_unique<TH1F>(TH1F(proto));
      for (int b = 1; b <= old_h->GetNbinsX(); ++b) {
        int new_bin = (bin_mapping.find(b))->second;
        new_h->SetBinContent(
            new_bin,
            new_h->GetBinContent(new_bin) + old_h->GetBinContent(b));
      }
      e->set_shape(std::move(new_h), false);
    });

    cmb_bin.ForEachProc([&](ch::Process *e) {
      TH1 const* old_h = e->shape();
      std::unique_ptr<TH1> new_h = ch::make_unique<TH1F>(TH1F(proto));
      for (int b = 1; b <= old_h->GetNbinsX(); ++b) {
        int new_bin = (bin_mapping.find(b))->second;
        new_h->SetBinContent(
            new_bin,
            new_h->GetBinContent(new_bin) + old_h->GetBinContent(b));
      }
      e->set_shape(std::move(new_h), false);
    });
    cmb_bin.ForEachSyst([&](ch::Systematic *e) {
      if (e->type() != "shape") return;
      TH1 const* old_hd = e->shape_d();
      TH1 const* old_hu = e->shape_u();
      std::unique_ptr<TH1> new_hd = ch::make_unique<TH1F>(TH1F(proto));
      std::unique_ptr<TH1> new_hu = ch::make_unique<TH1F>(TH1F(proto));
      for (int b = 1; b <= old_hd->GetNbinsX(); ++b) {
        int new_bin = (bin_mapping.find(b))->second;
        new_hd->SetBinContent(
            new_bin,
            new_hd->GetBinContent(new_bin) + old_hd->GetBinContent(b));
        new_hu->SetBinContent(
            new_bin,
            new_hu->GetBinContent(new_bin) + old_hu->GetBinContent(b));
      }
      e->set_shapes(std::move(new_hu), std::move(new_hd), nullptr);
    });
  }

  std::vector<TH1F *> by_chn;

  auto channels = cmb.channel_set();

  THStack stack_bkg;

  for (auto chn : channels) {
    by_chn.push_back(
        new TH1F(cmb.cp().channel({chn}).backgrounds().GetShape()));
    if (chn == "et") by_chn.back()->SetFillColorAlpha(TColor::GetColor(200, 2, 285),.85);
    if (chn == "mt") by_chn.back()->SetFillColorAlpha(TColor::GetColor(408, 106, 154),.85);
    if (chn == "em") by_chn.back()->SetFillColorAlpha(TColor::GetColor(200, 222, 285),.85);
    if (chn == "tt") by_chn.back()->SetFillColorAlpha(TColor::GetColor(208, 376, 124),.85);
    if (chn == "ee") by_chn.back()->SetFillColor(TColor::GetColor(247, 186, 254));
    if (chn == "mm") by_chn.back()->SetFillColor(TColor::GetColor(112, 142, 122));
    if (chn == "vhtt") by_chn.back()->SetFillColor(TColor::GetColor(137, 132, 192));
    if (chn == "et") by_chn.back()->SetTitle("e_{}#tau_{h}");
    if (chn == "mt") by_chn.back()->SetTitle("#mu_{}#tau_{h}");
    if (chn == "em") by_chn.back()->SetTitle("e#mu");
    if (chn == "ee") by_chn.back()->SetTitle("ee");
    if (chn == "mm") by_chn.back()->SetTitle("#mu#mu");
    if (chn == "tt") by_chn.back()->SetTitle("#tau_{h}#tau_{h}");
    if (chn == "vhtt") by_chn.back()->SetTitle("VH");
    by_chn.back()->SetBinContent(17, 0.);
    stack_bkg.Add(by_chn.back());

  }

  TH1F sb_sig = cmb.cp().signals().GetShape();
  TH1F sb_bkg = cmb.cp().backgrounds().GetShapeWithUncertainty();
  TH1F sb_err = sb_bkg;
  TH1F sb_obs = cmb.cp().GetObservedShape();

  sb_sig.SetBinContent(17, 0.);
  sb_bkg.SetBinContent(17, 0.);
  sb_obs.SetBinContent(17, 0.);

  sb_bkg.SetFillColor(18);
  sb_sig.SetFillColor(kRed);
  sb_sig.SetFillStyle(3004);
  sb_sig.SetLineColor(kRed);

  int new_idx = CreateTransparentColor(12, 0.4);
  sb_err.SetFillColor(new_idx);
  sb_err.SetMarkerSize(0);

  THStack *stack = new THStack("stack", "stack");
  stack->Add((TH1F*)sb_bkg.Clone(), "hist");
  stack->Add((TH1F*)sb_sig.Clone(), "hist");


  TCanvas* canv = new TCanvas(output.c_str(), output.c_str());
  canv->cd();

  std::vector<TPad*> pads =
      do_ratio ? TwoPadSplit(0.29, 0.005, 0.005) : OnePad();

  pads[0]->SetLogy(do_logy);
  std::vector<TH1*> h = CreateAxisHists(2, &sb_obs);
  if (do_ratio) {
    SetupTwoPadSplitAsRatio(pads, h[0], h[1], "Obs - Bkg", true, -10., 10.);
    h[1]->GetXaxis()->SetTitle("log(S/S+B)");
    h[0]->GetYaxis()->SetTitle("Events");
  } else {
    h[0]->GetXaxis()->SetTitle("log(S/S+B)");
    h[0]->GetYaxis()->SetTitle("Events");
  }

  h[0]->Draw("");

  if (pads[0]->GetLogy()) h[0]->SetMinimum(0.1);

    if (blinded){
    for (int ibin=0; ibin < sb_obs.GetNbinsX() ; ibin++ ){
        if (ibin > 7)
            sb_obs.SetBinContent(ibin,0);
    }
  }
    
    
  stack->Draw("histsame");
  stack_bkg.Draw("histsame");
  sb_err.Draw("e2same");

  sb_obs.Draw("esamex0");

  FixTopRange(pads[0], GetPadYMax(pads[0]), 0.15);

  TLegend *legend = PositionedLegend(0.30, 0.30, 3, 0.03);
  legend->AddEntry(&sb_obs, "Observed", "pe");
  // legend->AddEntry(&sb_bkg, "Background", "f");
  for (auto chn: by_chn) {
    legend->AddEntry(chn, chn->GetTitle(), "f");
  }
  legend->AddEntry(&sb_sig, "Signal", "f");
  // legend->AddEntry(&sb_err, "Bkg. Uncertainty", "f");
  legend->Draw();

  for (auto pad : pads) {
    pad->cd();
    FixOverlay();
  }

  DrawTitle(pads[0], "CMS Preliminary                       35.9 fb^{-1} (13 TeV)", 1);

//
//    float lowX=0.65;
//    float lowY=0.85;
//    TPaveText * lumi  = new TPaveText(lowX, lowY+0.06, lowX+0.30, lowY+0.16, "NDC");
//    lumi->SetBorderSize(   0 );
//    lumi->SetFillStyle(    0 );
//    lumi->SetTextAlign(   12 );
//    lumi->SetTextColor(    1 );
//    lumi->SetTextSize(0.04);
//    lumi->SetTextFont (   42 );
//    lumi->AddText("35.9 fb^{-1} (13 TeV)");
//    lumi->Draw();
//    
//    lowX=0.15;
//    lowY=0.75;
//    TPaveText * lumi1  = new TPaveText(lowX, lowY+0.06, lowX+0.15, lowY+0.16, "NDC");
//    lumi1->SetTextFont(61);
//    lumi1->SetTextSize(0.05);
//    lumi1->SetBorderSize(   0 );
//    lumi1->SetFillStyle(    0 );
//    lumi1->SetTextAlign(   12 );
//    lumi1->SetTextColor(    1 );
//    lumi1->AddText("CMS Preliminary");
//    lumi1->Draw();
    
    

  canv->Print(".pdf");



  // TFile outfile((output+".root").c_str(), "RECREATE");
  // outfile.cd();
  // ch::WriteToTFile(&sb_sig, &outfile, "TotalSig");
  // ch::WriteToTFile(&sb_bkg, &outfile, "TotalBkg");
  // ch::WriteToTFile(&sb_obs, &outfile, "TotalObs");
  // outfile.Close();



  return 0;
}
Example #23
0
void fitM3()
{

	// LOAD HISTOGRAMS FROM FILES
	/////////////////////////////////
	TH1F *hTTjets;
	TH1F *hWjets;
	TH1F *hM3;
	TH1F *hZjets;
	TH1F *hQCD;
	TH1F *hST_s;
	TH1F *hST_t;
	TH1F *hST_tW;

	// histograms from nonimal sample
	///////////
	
	TFile *infile0 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_TTJets-madgraph_Fall08_all_all.root");
	//TFile *infile0 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_TauolaTTbar.root");
	hTTjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	TFile *infile1 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_WJets_madgraph_Fall08_all.root");
	hWjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	TFile *infile1Fast = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Wjets_madgraph_Winter09_v2_all.root");
	hWjetsFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZ = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ZJets_madgraph_Fall08_all.root");
	hZjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	TFile *infileZFast = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Zjets_madgraph_Winter09_v2_all.root");
	hZjetsFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_s = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_s.root");
	hST_s = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_t = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_t.root");
	hST_t = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tW = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_tW.root");
	hST_tW = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileQCD = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_InclusiveMuPt15_Summer08_all.root");
	hQCD = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	// histograms from systematic samples
	//////////
	TFile *infile0S = TFile::Open("nominal_JESUp/TopAnalysis_TTJets-madgraph_Fall08_all_all.root");
	hTTjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
		
	TFile *infile1S = TFile::Open("nominal_JESUp/TopAnalysis_WJets_madgraph_Fall08_all.root");// from FullSim
	hWjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	//TFile *infile1SF = TFile::Open("nominal_JESUp_Fast/TopAnalysis_WJets_madgraph_Fall08_all.root");// from FastSim
	//TFile *infile1SF = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Wjets_ScaleUp_madgraph_Winter09_all.root");
	TFile *infile1SF = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_WJets_Threshold20GeV_madgraph_Winter09_all.root");
	hWjetsSFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZS = TFile::Open("nominal_JESUp/TopAnalysis_ZJets_madgraph_Fall08_all.root");// from FullSim
	hZjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZSF = TFile::Open("nominal_JESUp_Fast/TopAnalysis_ZJets_madgraph_Fall08_all.root");// from FullSim
	hZjetsSFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_sS = TFile::Open("nominal_JESUp/TopAnalysis_ST_s.root");
	hST_sS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tS = TFile::Open("nominal_JESUp/TopAnalysis_ST_t.root");
	hST_tS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tWS = TFile::Open("nominal_JESUp/TopAnalysis_ST_tW.root");
	hST_tWS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileQCDS = TFile::Open("nominal_JESUp/TopAnalysis_InclusiveMuPt15_Summer08_all.root");//
	hQCDS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	//TFile *infileQCD_CS = TFile::Open("nominal_antiMuon/TopAnalysis_InclusiveMuPt15_Summer08_all.root");
	//hQCD_CS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	// write templates to file
	//TFile *outfile = TFile::Open("templates.root","RECREATE");
	//hTTjets->Write("ttbar");
	//hWjets->Write("Wjets");
	//outfile->Close();

	// Add over/underflow bins if requested
	bool UseOverflow = true;
	bool UseUnderflow = true;
	
	if (UseOverflow) {
		int maxbin=hTTjets->GetNbinsX();
	
		hTTjets->SetBinContent(maxbin,    hTTjets->GetBinContent(maxbin+1)+hTTjets->GetBinContent(maxbin) );
		hWjets->SetBinContent(maxbin,     hWjets->GetBinContent(maxbin+1)+hWjets->GetBinContent(maxbin) );
		hWjetsFast->SetBinContent(maxbin, hWjetsFast->GetBinContent(maxbin+1)+hWjetsFast->GetBinContent(maxbin) );
		hZjets->SetBinContent(maxbin,     hZjets->GetBinContent(maxbin+1)+hZjets->GetBinContent(maxbin) );
		hZjetsFast->SetBinContent(maxbin, hZjetsFast->GetBinContent(maxbin+1)+hZjetsFast->GetBinContent(maxbin) );
		hQCD->SetBinContent(maxbin,       hQCD->GetBinContent(maxbin+1)+hQCD->GetBinContent(maxbin) );
		//hQCD_CS->SetBinContent(maxbin, hQCD_CS->GetBinContent(maxbin+1)+hQCD_CS->GetBinContent(maxbin) );
		hST_s->SetBinContent(maxbin,      hST_s->GetBinContent(maxbin+1)+hST_s->GetBinContent(maxbin) );
		hST_t->SetBinContent(maxbin,      hST_t->GetBinContent(maxbin+1)+hST_t->GetBinContent(maxbin) );
		hST_tW->SetBinContent(maxbin,     hST_tW->GetBinContent(maxbin+1)+hST_tW->GetBinContent(maxbin) );
	}
	//underflow bin
	if (UseUnderflow) {
		int maxbin=1;
		hTTjets->SetBinContent(maxbin,    hTTjets->GetBinContent(maxbin-1)+hTTjets->GetBinContent(maxbin) );
		hWjets->SetBinContent(maxbin,     hWjets->GetBinContent(maxbin-1)+hWjets->GetBinContent(maxbin) );
		hWjetsFast->SetBinContent(maxbin, hWjetsFast->GetBinContent(maxbin-1)+hWjetsFast->GetBinContent(maxbin) );
		hZjets->SetBinContent(maxbin,     hZjets->GetBinContent(maxbin-1)+hZjets->GetBinContent(maxbin) );
		hZjetsFast->SetBinContent(maxbin, hZjetsFast->GetBinContent(maxbin-1)+hZjetsFast->GetBinContent(maxbin) );
		hQCD->SetBinContent(maxbin,       hQCD->GetBinContent(maxbin-1)+hQCD->GetBinContent(maxbin) );
		//hQCD_CS->SetBinContent(maxbin, hQCD_CS->GetBinContent(maxbin-1)+hQCD_CS->GetBinContent(maxbin) );
		hST_s->SetBinContent(maxbin,      hST_s->GetBinContent(maxbin-1)+hST_s->GetBinContent(maxbin) );
		hST_t->SetBinContent(maxbin,      hST_t->GetBinContent(maxbin-1)+hST_t->GetBinContent(maxbin) );
		hST_tW->SetBinContent(maxbin,     hST_tW->GetBinContent(maxbin-1)+hST_tW->GetBinContent(maxbin) );
	}
	//syst.
	if (UseOverflow) {
		int maxbin=hTTjetsS->GetNbinsX();
		hTTjetsS->SetBinContent(maxbin,    hTTjetsS->GetBinContent(maxbin+1)+hTTjetsS->GetBinContent(maxbin) );
		hWjetsS->SetBinContent(maxbin,     hWjetsS->GetBinContent(maxbin+1)+hWjetsS->GetBinContent(maxbin) );
		hWjetsSFast->SetBinContent(maxbin, hWjetsSFast->GetBinContent(maxbin+1)+hWjetsSFast->GetBinContent(maxbin) );
		hZjetsS->SetBinContent(maxbin,     hZjetsS->GetBinContent(maxbin+1)+hZjetsS->GetBinContent(maxbin) );
		hZjetsSFast->SetBinContent(maxbin, hZjetsSFast->GetBinContent(maxbin+1)+hZjetsSFast->GetBinContent(maxbin) );
		hQCDS->SetBinContent(maxbin,       hQCDS->GetBinContent(maxbin+1)+hQCDS->GetBinContent(maxbin) );
		hST_sS->SetBinContent(maxbin,      hST_sS->GetBinContent(maxbin+1)+hST_sS->GetBinContent(maxbin) );
		hST_tS->SetBinContent(maxbin,      hST_tS->GetBinContent(maxbin+1)+hST_tS->GetBinContent(maxbin) );
		hST_tWS->SetBinContent(maxbin,     hST_tWS->GetBinContent(maxbin+1)+hST_tWS->GetBinContent(maxbin) );
	}
	if (UseUnderflow) {
		//underflow bin
		int maxbin=1;
		hTTjetsS->SetBinContent(maxbin,    hTTjetsS->GetBinContent(maxbin-1)+hTTjetsS->GetBinContent(maxbin) );
		hWjetsS->SetBinContent(maxbin,     hWjetsS->GetBinContent(maxbin-1)+hWjetsS->GetBinContent(maxbin) );
		hWjetsSFast->SetBinContent(maxbin, hWjetsSFast->GetBinContent(maxbin-1)+hWjetsSFast->GetBinContent(maxbin) );
		hZjetsS->SetBinContent(maxbin,     hZjetsS->GetBinContent(maxbin-1)+hZjetsS->GetBinContent(maxbin) );
		hZjetsSFast->SetBinContent(maxbin,     hZjetsSFast->GetBinContent(maxbin-1)+hZjetsSFast->GetBinContent(maxbin) );
		hQCDS->SetBinContent(maxbin,       hQCDS->GetBinContent(maxbin-1)+hQCDS->GetBinContent(maxbin) );
		hST_sS->SetBinContent(maxbin,      hST_sS->GetBinContent(maxbin-1)+hST_sS->GetBinContent(maxbin) );
		hST_tS->SetBinContent(maxbin,      hST_tS->GetBinContent(maxbin-1)+hST_tS->GetBinContent(maxbin) );
		hST_tWS->SetBinContent(maxbin,     hST_tWS->GetBinContent(maxbin-1)+hST_tWS->GetBinContent(maxbin) );
	}
	
	// scale histograms to 20/pb

	hTTjets->Scale(0.0081); // madgraph
	//hTTjets->Scale(0.0777);//Tauola
	hWjets->Scale(0.0883);
	//hWjetsFast->Scale(0.0091); //fastsim
	hWjetsFast->Scale(hWjets->Integral() / hWjetsFast->Integral()); // scale to FullSim
		
	hZjets->Scale(0.0731);
	hZjetsFast->Scale(hZjets->Integral()/hZjetsFast->Integral()); //scale to FullSim
	hQCD->Scale(0.4003);
	hQCD_WFast = (TH1F*) hWjetsFast->Clone("hQCD_WFast"); //take shape from Wjets
	hQCD_WFast->Scale(hQCD->Integral()/hQCD_WFast->Integral()); //scale to FullSim
	hST_t->Scale(0.003);
	hST_s->Scale(0.0027);
	hST_tW->Scale(0.0034);

	hTTjetsS->Scale(0.0081); // 
	//hTTjetsS->Scale(0.0008); // for fastsim
	hWjetsS->Scale(0.0883);
	//hWjetsS->Scale(0.0091);// from fastsim
	//hWjetsSFast->Scale(hWjetsS->Integral() / hWjetsSFast->Integral()); // scale to FullSim
	//hWjetsSFast->Scale(0.6642); // scaleUP
	//hWjetsSFast->Scale(0.8041); // scaleDown
	//hWjetsSFast->Scale(0.0605); // threshold 5gev
	hWjetsSFast->Scale(0.042); // threshold 20gev
	
	hZjetsS->Scale(0.0731);
	//hZjetsS->Scale(0.0085);// from fastsim
	hZjetsSFast->Scale(hZjetsS->Integral() / hZjetsSFast->Integral()); // scale to FullSim
	hQCDS->Scale(0.4003);
	//hQCDS_WFast = (TH1F*) hWjetsS->Clone("hQCDS_WFast");
	//hQCDS_WFast->Scale(hQCDS->Integral()/hQCDS_WFast->Integral());
	hST_tS->Scale(0.003);
	hST_sS->Scale(0.0027);
	hST_tWS->Scale(0.0034);
	
	cout << " N expected ttbar+jets events = " << hTTjets->Integral() << endl;
	cout << " N expected W+jets     events = " << hWjets->Integral()  << endl;
	cout << " N expected Z+jets     events = " << hZjets->Integral()  << endl;
	cout << " N expected ST s       events = " << hST_s->Integral()  << endl;
	cout << " N expected ST t       events = " << hST_t->Integral()  << endl;
	cout << " N expected ST tW      events = " << hST_tW->Integral()  << endl;
	cout << " N expected qcd        events = " << hQCD->Integral()  << endl;

	cout << endl;
	cout << " N expected W+jets fast = " << hWjetsFast->Integral() << endl;
	cout << " N expected z+jets fast = " << hZjetsFast->Integral() << endl;
	cout << " N expected qcd Wfast = " << hQCD_WFast->Integral() << endl;

	cout << "\n systematics: " << endl;
	cout << " N expected W+jets fast = " << hWjetsSFast->Integral() << endl;
	cout << " N expected z+jets fast = " << hZjetsS->Integral() << endl;
	cout << " N expected qcd Wfast = " << hQCDS->Integral() << endl;

	// add all three single top samples

	// for systematics
	//hST_t->Scale(2.);
	
	hST_t->Add(hST_s);
	hST_t->Add(hST_tW);
	cout << " number of ST = " << hST_t->Integral() << endl;
	// syst. uncertainty in single top
	//double tmpST = 0.6* hST_t->Integral();
	//hST_t->Scale(0.6);
	//cout << tmpST << endl;
	cout << " New number of ST = " << hST_t->Integral() << endl;
	
	hST_tS->Add(hST_sS);
	hST_tS->Add(hST_tWS);

	// dump scaled histograms in root file
	//TFile *output = TFile::Open("fitM3.root","RECREATE");
	//hTTjets->SetName("ttbar");hTTjets->Write();
	//hWjetsFast->SetName("WjetsFast");hWjetsFast->Write();
	//hST_t->SetName("ST");hST_t->Write();
	//output->Close();
	
		
	hM3 = (TH1F*) hTTjets->Clone("hM3");
	hM3->Add(hWjets);
	hM3->Add(hZjets);
	hM3->Add(hQCD);
	hM3->Add(hST_t);
	
	int Nbins = hM3->GetNbinsX();
	
	// --- Observable ---
        
	RooRealVar mass("mass","M3'(#chi^{2})",100,500,"GeV/c^{2}") ; 
	RooRealVar Ntt("Ntt","number of t#bar{t} events", hTTjets->Integral(), -100 , 1000);
    RooRealVar NW("NW","number of W+jets events", hWjetsFast->Integral(), -500 , 1000);
	RooRealVar NST("NST","number of single top events", hST_t->Integral(), -500,100);
	RooRealVar NZjets("NZjets","number of Z+jets events", hZjetsS->Integral(), -500,500);
	RooRealVar Nqcd("Nqcd","number of QCD events", hQCD_WFast->Integral(), -500,100);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral()+hST_t->Integral()+hZjetsFast->Integral()+hQCD_WFast->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of W+jets events", hWjets->Integral(), -500 , 1000); // 2 templates

	RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral()+hZjets->Integral()+hQCD_WFast->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral(), -500 , 1000);
	
	// for systematics
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsSFast->Integral()+hZjetsS->Integral()+hQCDS->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsSFast->Integral(), -500 , 1000);
	
	mass.setBins(Nbins);

	// RooFit datasets
	RooDataHist hdata_ttbar("hdata_ttbar","ttbar", mass, hTTjets);       
	//RooDataHist hdata_wjets("hdata_wjets","wjets", mass, hWjets);
	RooDataHist hdata_wjetsFast("hdata_wjetsFast","wjets_Fast", mass, hWjetsFast);
	RooDataHist hdata_ST("hdata_ST","ST", mass, hST_t);
	RooDataHist hdata_zjets("hdata_zjets","zjets", mass, hZjets);
	//RooDataHist hdata_qcd("hdata_qcd","qcd", mass, hQCD);
	RooDataHist hdata_zjetsFast("hdata_zjetsFast","zjets_Fast", mass, hZjetsFast);
	RooDataHist hdata_qcdWFast("hdata_qcdWFast","qcd WFast", mass, hQCD_WFast);
	
	RooHistPdf hpdf_ttbar("hpdf_ttbar","signal pdf", mass, hdata_ttbar, 0 );
	//RooHistPdf hpdf_wjets("hpdf_wjets","W+jets pdf", mass, hdata_wjets, 0 );
	RooHistPdf hpdf_wjetsFast("hpdf_wjetsFast","W+jets pdf", mass, hdata_wjetsFast, 0 );
	RooHistPdf hpdf_ST("hpdf_ST","ST pdf", mass, hdata_ST, 0 );
	//RooHistPdf hpdf_zjets("hpdf_zjets","Z+jets pdf", mass, hdata_zjets, 0 );
	//RooHistPdf hpdf_qcd("hpdf_qcd","qcd pdf", mass, hdata_qcd, 0 );
	RooHistPdf hpdf_zjetsFast("hpdf_zjetsFast","Z+jets pdf", mass, hdata_zjetsFast, 0 );
	RooHistPdf hpdf_qcdWFast("hpdf_qcdWFast","qcd WFast pdf", mass, hdata_qcdWFast, 0 );
	
	// for systematics
	RooDataHist hdata_ttbarS("hdata_ttbarS","ttbar", mass, hTTjetsS);       
	RooDataHist hdata_wjetsS("hdata_wjetsS","wjets", mass, hWjetsSFast);
	RooDataHist hdata_STS("hdata_STS","ST", mass, hST_tS);
	RooDataHist hdata_zjetsS("hdata_zjetsS","zjets", mass, hZjetsSFast);
	RooDataHist hdata_qcdS("hdata_qcdS","qcd", mass, hQCDS);
	//RooDataHist hdata_qcdSWFast("hdata_qcdSWFast","qcd WFast", mass, hQCDS_WFast);
		
	RooHistPdf hpdf_ttbarS("hpdf_ttbarS","signal pdf", mass, hdata_ttbarS, 0 );
	RooHistPdf hpdf_wjetsS("hpdf_wjetsS","W+jets pdf", mass, hdata_wjetsS, 0 );
	RooHistPdf hpdf_STS("hpdf_STS","ST pdf", mass, hdata_STS, 0 );
	RooHistPdf hpdf_zjetsS("hpdf_zjetsS","Z+jets pdf", mass, hdata_zjetsS, 0 );
	RooHistPdf hpdf_qcdS("hpdf_qcdS","qcd pdf", mass, hdata_qcdS, 0 );
	//RooHistPdf hpdf_qcdSWFast("hpdf_qcdSWFast","qcd WFast pdf", mass, hdata_qcdSWFast, 0 );

	//RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsFast,hpdf_ST,hpdf_qcdWFast),
	//				   RooArgList(NW,NST,Nqcd) );
					   
	//RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsFast,hpdf_ST,hpdf_zjetsFast,hpdf_qcdWFast),
					   //RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsS,hpdf_STS,hpdf_zjetsS,hpdf_qcdSWFast),
					   //RooArgList(NW,NST,NZjets,Nqcd) );
// only two pdfs: ttbar + Wjets
//RooHistPdf hpdf_bkg = hpdf_wjetsFast;
	
	//RooAddPdf model_M3("modelM3","all", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST,hpdf_zjetsFast,hpdf_qcdWFast),
	//			   RooArgList(Ntt,Nbkg,NST,NZjets,Nqcd));
	// for systematics
	RooAddPdf model_M3("modelM3","all", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),//RooArgList(hpdf_ttbar,hpdf_wjetsS,hpdf_ST),
					   RooArgList(Ntt,Nbkg,NST) );
	
	//RooAddPdf model_M3("modelM3","all",RooArgList(hpdf_ttbar,hpdf_bkg),
	//		   RooArgList(Ntt,Nbkg) );
	//RooArgList(Ntt,Nbkg,NST,Nqcd) );
	
	RooAddPdf model_histpdf("model", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),
							RooArgList(Ntt, Nbkg, NST) ) ;

	// Construct another Gaussian constraint p.d.f on parameter f at n with resolution of sqrt(n)
	RooGaussian STgaussConstraint("STgaussConstraint","STgaussConstraint",NST,RooConst(hST_t->Integral()),RooConst(sqrt(hST_t->Integral() + (0.3*hST_t->Integral())*(0.3*hST_t->Integral()))) );
	//RooGaussian fconstext2("fconstext2","fconstext2",NZjets,RooConst(hZjets->Integral()),RooConst(sqrt(hZjets->Integral())) );
	
	// --- Generate a toyMC sample 
	//RooMCStudy *mcstudyM3 = new RooMCStudy(model_M3, mass, Binned(kTRUE),Silence(),Extended(),
	//								   FitOptions(Save(kTRUE),Minos(kTRUE),Extended(), ExternalConstraints(fconstext)) );

	// generate PEs
	int Nsamples = 1000;
	// PEs for ttbar
/*
	RooExtendPdf ext_hpdf_ttbar("ext_hpdf_ttbar","ext_hpdf_ttbar",hpdf_ttbar,Ntt);
	RooExtendPdf ext_hpdf_wjets("ext_hpdf_wjets","ext_hpdf_wjets",hpdf_wjetsFast,NW);
	RooExtendPdf ext_hpdf_zjets("ext_hpdf_zjets","ext_hpdf_zjets",hpdf_zjetsFast,NZjets);
	RooExtendPdf ext_hpdf_qcd("ext_hpdf_qcd","ext_hpdf_qcd",hpdf_qcdWFast,Nqcd);
	RooExtendPdf ext_hpdf_ST("ext_hpdf_ST","ext_hpdf_ST",hpdf_ST,NST);
	
	RooMCStudy *mc_ttbar = new RooMCStudy(ext_hpdf_ttbar,mass,Binned(kTRUE),Silence(kTRUE));
	mc_ttbar->generate(Nsamples,0,kFALSE,"data/toymc_ttbar_%04d.dat");
	RooMCStudy *mc_wjets = new RooMCStudy(ext_hpdf_wjets,mass,Binned(kTRUE),Silence(kTRUE));
	mc_wjets->generate(Nsamples,0,kFALSE,"data/toymc_wjets_%04d.dat");
	RooMCStudy *mc_zjets = new RooMCStudy(ext_hpdf_zjets,mass,Binned(kTRUE),Silence(kTRUE));
	mc_zjets->generate(Nsamples,0,kFALSE,"data/toymc_zjets_%04d.dat");
	RooMCStudy *mc_qcd = new RooMCStudy(ext_hpdf_qcd,mass,Binned(kTRUE),Silence(kTRUE));
	mc_qcd->generate(Nsamples,0,kFALSE,"data/toymc_qcd_%04d.dat");
	RooMCStudy *mc_ST = new RooMCStudy(ext_hpdf_ST,mass,Binned(kTRUE),Silence(kTRUE),FitOptions(ExternalConstraints(STgaussConstraint)));
	mc_ST->generate(Nsamples,0,kFALSE,"data/toymc_ST_%04d.dat");

	return;
*/	
	RooMCStudy *mcstudy = new RooMCStudy(model_M3, mass, FitModel(model_histpdf),Binned(kTRUE),Silence(kTRUE), Extended() , 
										 //FitOptions(Save(kTRUE),Minos(kTRUE),Extended()) );
										 FitOptions(Save(kTRUE),Minos(kTRUE),Extended(),ExternalConstraints(STgaussConstraint)));//RooArgList(fconstext,fconstext2)) )); //gaussian constraint
	
		
	//mcstudyM3->generate(Nsamples,0,kFALSE,"toymc.dat");
	//mcstudyM3->generateAndFit(Nsamples,0,kFALSE,"toymc.dat");
	
	//TList dataList;
	//for (int isample=0; isample<Nsamples; ++isample) dataList.Add( mcstudyM3->genData(isample));

	
	// Fit
	mcstudy->generateAndFit(Nsamples,0,kTRUE);
	//mcstudy->fit(Nsamples, "data/toymc_%04d.dat");

		
	gDirectory->Add(mcstudy) ;	
	// E x p l o r e   r e s u l t s   o f   s t u d y 
	// ------------------------------------------------

	// Make plots of the distributions of mean, the error on mean and the pull of mean
	RooPlot* frame1 = mcstudy->plotParam(Ntt,Bins(40));
	RooPlot* frame2 = mcstudy->plotError(Ntt,Bins(40)) ;
	RooPlot* frame3 = mcstudy->plotPull(Ntt,Bins(40),FitGauss(kTRUE)) ;
	RooPlot* frame1w = mcstudy->plotParam(Nbkg,Bins(40)) ;
	RooPlot* frame2w = mcstudy->plotError(Nbkg,Bins(40)) ;
	RooPlot* frame3w = mcstudy->plotPull(Nbkg,Bins(40),FitGauss(kTRUE)) ;
	RooPlot* frame1st = mcstudy->plotParam(NST,Bins(40)) ;
	RooPlot* frame2st = mcstudy->plotError(NST,Bins(40)) ;
	//RooPlot* frame3st = mcstudy->plotPull(NST,Bins(40),FitGauss(kTRUE)) ;
	
	// Plot distribution of minimized likelihood
	RooPlot* frame4 = mcstudy->plotNLL(Bins(40)) ;

	// Make some histograms from the parameter dataset
	TH1* hh_cor_ttbar_w = mcstudy->fitParDataSet().createHistogram("hh",Ntt,YVar(Nbkg)) ;

	// Access some of the saved fit results from individual toys
	//TH2* corrHist000 = mcstudy->fitResult(0)->correlationHist("c000") ;
	//TH2* corrHist127 = mcstudy->fitResult(127)->correlationHist("c127") ;
	//TH2* corrHist953 = mcstudy->fitResult(953)->correlationHist("c953") ;

	
	// Draw all plots on a canvas
	gStyle->SetPalette(1) ;
	gStyle->SetOptStat(0) ;

	TCanvas* cv = new TCanvas("cv","cv",600,600) ;
	hM3->SetFillColor(kRed);
	hWjets->SetFillColor(kGreen);
	hM3->Draw();
	hWjets->Draw("same");
	gPad->RedrawAxis();
	
	TCanvas* cva = new TCanvas("cva","cva",1800,600) ;
	cva->Divide(3);
	cva->cd(1) ;
	RooPlot *initialframe = mass.frame();
	//initial->SetMaximum(10);
	hpdf_ttbar.plotOn(initialframe,LineColor(kRed));
	hpdf_wjetsFast.plotOn(initialframe,LineColor(kGreen));
	hpdf_ST.plotOn(initialframe,LineColor(kYellow));
	initialframe->Draw();
	//initialframe->SetTitle();
	cva->cd(2);
	//retrieve data for only one PE
	
	int Npe = 10;
	RooPlot *genframe = mass.frame(Nbins);
	RooDataSet *gendata = mcstudy->genData(Npe);
	cout << " N events = " << gendata->numEntries() << endl;
	gendata->plotOn(genframe);
	//mcstudy->fitResult(Npe)->plotOn(genframe, model_histpdf);
	genframe->Draw();
	cva->cd(3);
	RooPlot *genframe2 = mass.frame(Nbins);
	mcstudy->fitResult(Npe)->Print("v");
	gendata->plotOn(genframe2);
	RooArgList arglist = mcstudy->fitResult(Npe)->floatParsFinal();

	
	//cout << "name of argument:" << arglist[2].GetName() << endl;
	//cout << "name of argument:" << arglist[1].GetName() << endl;
	//cout << "name of argument:" << arglist[0].GetName() << endl;
	
	RooAddPdf model_histpdf_fitted("modelfitted", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),
							   RooArgList(arglist[2],arglist[1],arglist[0]) ) ;
	
	model_histpdf_fitted.plotOn(genframe2,LineColor(kRed));
	model_histpdf_fitted.plotOn(genframe2,Components(hpdf_wjetsFast),LineColor(kGreen));
	model_histpdf_fitted.plotOn(genframe2,Components(hpdf_ST),LineColor(kYellow));
	genframe2->Draw();

	TCanvas* cvb = new TCanvas("cvb","cvb",1800,600) ;
	cvb->Divide(3);
	cvb->cd(1) ; frame1->Draw();
	cvb->cd(2) ; frame2->Draw();
	cvb->cd(3) ; frame3->Draw();
	TCanvas* cvbb = new TCanvas("cvbb","cvbb",1800,600) ;
	cvbb->Divide(3);
	cvbb->cd(1) ; frame1w->Draw();
	cvbb->cd(2) ; frame2w->Draw();
	cvbb->cd(3) ; frame3w->Draw();

	TCanvas* cvbbb = new TCanvas("cvbbb","cvbbb",1200,600) ;
	cvbbb->Divide(2);
	cvbbb->cd(1) ; frame1st->Draw();
	cvbbb->cd(2) ; frame2st->Draw();
	//cvbbb->cd(3) ; frame3st->Draw();
	
	TCanvas* cvbc = new TCanvas("cvbc","cvbc",600,600) ;
	TH2 *h2 = Ntt.createHistogram("Nttbar vs NWjets",Nbkg);
	mcstudy->fitParDataSet().fillHistogram(h2,RooArgList(Ntt,Nbkg));
	h2->Draw("box");

	
	TCanvas* cvc = new TCanvas("cvc","cvc",600,600) ;	
	// Plot distribution of minimized likelihood
	RooPlot* frame4 = mcstudy->plotNLL(Bins(40)) ;
	frame4->Draw();

	//return;//debuging

	
	TCanvas* cvd = new TCanvas("cvd","cvd",600,600) ;
	TCanvas* cve = new TCanvas("cve","cve",1200,600) ;
	TCanvas* cvf = new TCanvas("cvf","cvf",600,600) ;

	TH1F *hNgen = new TH1F("hNgen","Number of observed events",30,350,650);
	hNgen->SetXTitle("Number of observed events");

	TH1F *hNttresults = new TH1F("hNttresults","number of ttbar events",50,20,600);
	TH1F *hNWresults = new TH1F("hNWresults","number of W events",50,-150,400);
	TH1F *hNSTresults = new TH1F("hNSTresults","number of ttbar events",50,5,25);
									 
	bool gotone = false;
	int Nfailed = 0;
	for ( int i=0; i< Nsamples; i++)
	{
		
		RooFitResult *r = mcstudy->fitResult(i);
		RooArgList list = r->floatParsFinal();
		RooRealVar *rrv_nt = (RooRealVar*)list.at(2);
		double nt = rrv_nt->getVal();
		//double nte= rrv_nt->getError();
		RooRealVar *rrv_nw = (RooRealVar*)list.at(1);
		double nw = rrv_nw->getVal();
		//double nwe= rrv_nw->getError();
		RooRealVar *rrv_nst = (RooRealVar*)list.at(0);
		double nst = rrv_nst->getVal();

				
		hNttresults->Fill(nt);
		hNWresults->Fill(nw);
		hNSTresults->Fill(nst);
		
		
		RooDataSet *adata = mcstudy->genData(i);
		hNgen->Fill(adata->numEntries());
		
		if ( r->numInvalidNLL() > 0 ) Nfailed++;
		
		
		/*
		if ( false ) {
			cout << " sample # " << i << endl;
			gotone = true;
			r->Print("v");
			cout << " invalidNLL = "<< r->numInvalidNLL() << endl;
			cout << " N events = " << adata->numEntries() << endl;

			
			RooAddPdf amodel("amodel", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjets,hpdf_ST),
							 RooArgList(list[2],list[1],list[0])) ;
			RooPlot *d2 = new RooPlot(Ntt,NW,0,500,-200,200);
			r->plotOn(d2,Ntt,NW,"ME12ABHV");
			cvd->cd();
			d2->Draw();
			
			RooNLLVar nll("nll","nll", amodel, *adata, Extended() );//, Extended(), PrintEvalErrors(-1) );
			RooMinuit myminuit(nll)
			myminuit.migrad();
			myminuit.hesse();
			myminuit.minos();
			//myminuit.Save()->Print("v");

			cve->Divide(2);
			RooPlot *nllframett = Ntt.frame(Bins(50),Range(100,600));//,Range(10,2000));
			nll.plotOn(nllframett);//,ShiftToZero());
						
			RooProfileLL pll_ntt("pll_ntt","pll_ntt",nll,Ntt);
			pll_ntt.plotOn(nllframett,LineColor(kRed));

			RooPlot *nllframeW = NW.frame(Bins(50),Range(0,250));//,Range(10,2000));
			nll.plotOn(nllframeW);//,ShiftToZero());
						
			RooProfileLL pll_nW("pll_nW","pll_nW",nll,NW);
			pll_nW.plotOn(nllframeW,LineColor(kRed));

			cve->cd(1);
			nllframett->SetMaximum(2);
			nllframett->Draw();
			cve->cd(2);
			nllframeW->SetMaximum(2);
			nllframeW->Draw();
			
		}
		*/
	}

	TCanvas *tmpcv = new TCanvas("tmpcv","tmpcv",700,700);
	cout << "\n ==================================" << endl;
	cout << "gaussian fit of Nttbar fitted values: " << endl;
	//hNttresults->Print("all");
	hNttresults->Fit("gaus");

	cout << "\n ==================================" << endl;
	cout << "gaussian fit of NW fitted values: " << endl;
	//hNWresults->Print("all");
	hNWresults->Fit("gaus");

	cout << "\n ==================================" << endl;
	cout << "gaussian fit of NST fitted values: " << endl;
	//hNSTresults->Print("all");
	hNSTresults->Fit("gaus");

	
	cout << "N failed fits = " << Nfailed << endl;
	
	cvf->cd();
	hNgen->Draw();
	
	// Make RooMCStudy object available on command line after
	// macro finishes
	//gDirectory->Add(mcstudy) ;
}
Example #24
0
void phi2(double pt1min, double pt2min, double METmin){


  TLegend* leg = new TLegend(0.13,0.6,0.87,0.87);
  leg->SetNColumns(3);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);

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


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

  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree"); 
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree"); 
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree"); 
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree"); 
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree"); 
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");  


  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");

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

  c1->cd();
  
  mainPad->Draw();
  mainPad->cd(); 
 
  
  
  
  
  
  
  gPad->SetLogy();  
  
  TCut mggmax = "mgg<180";
  TCut mggmin = "mgg>100";
  TCut pt1Cut = Form("pt1/mgg>%lf",pt1min);
  TCut pt2Cut = Form("pt2/mgg>%lf",pt2min);
  TCut METCut = Form("t1pfmet>%lf",METmin);
  TCut eveto1 = "eleveto1 == 1";
  TCut eveto2 = "eleveto2 == 1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  
  tree_data->Draw("(phi2)>>hdata(20,-4,4)",(mggmax && mggmin && metF&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");
  
  
  tree_sig1->Draw("(phi2)>>h1(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("(phi2)>>h2(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("(phi2)>>h3(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("(phi2)>>h4(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("(phi2)>>h5(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("(phi2)>>h6(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("(phi2)>>h7(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");
  
  
  tree_bkg1->Draw("(phi2)>>hbkg1(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("(phi2)>>hbkg2(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));  
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("(phi2)>>hbkg3(20,-4,4)","weight"*(mggmin && mggmax && genmatch&& METCut &&pt1Cut && pt2Cut&& eveto));  
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
  tree_bkg4->Draw("(phi2)>>hbkg4(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto)); //weight also on BR = 0.002 if using the 50ns samples
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("(phi2)>>hbkg5(20,-4,4)","weight"*(mggmin && mggmax && genmatch&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("(phi2)>>hbkg6(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");
  tree_bkg7->Draw("(phi2)>>hbkg7(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");
  tree_bkg8->Draw("(phi2)>>hbkg8(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");
  tree_bkg9->Draw("(phi2)>>hbkg9(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");
  tree_bkg10->Draw("(phi2)>>hbkg10(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");
  tree_bkg11->Draw("(phi2)>>hbkg11(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");
  tree_bkg12->Draw("(phi2)>>hbkg12(20,-4,4)","weight"*(mggmin && mggmax&& METCut &&pt1Cut && pt2Cut&& eveto));
  TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");
  
  hdata->SetMarkerColor(kBlack);
  hdata->SetMarkerStyle(20);
  hdata->SetLineColor(kBlack);
  
  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4);
  h6->SetLineColor(kPink+7);
  h7->SetLineColor(kMagenta+2);
 
  h1->SetLineWidth(2);
  h2->SetLineWidth(2);  
  h3->SetLineWidth(2);
  h4->SetLineWidth(2);
  h5->SetLineWidth(2);
 h6->SetLineWidth(2);
 h7->SetLineWidth(2);
  




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

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

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






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

  hs->SetMaximum(1000000);
  hs->SetMinimum(0.1);
  hs->SetTitle("");
  hs->Draw("HIST"); 

  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3002);
  hsum->Draw("same e2");
  h2->Draw("same hist");
  h3->Draw("same hist"); 
  h4->Draw("same hist");
  h1->Draw("same hist");
  h5->Draw("same hist"); 
 h6->Draw("same hist"); 
 h7->Draw("same hist"); 

  hdata->Draw("same E1");
  
  hs->GetXaxis()->SetLabelOffset(999);
  hs->GetYaxis()->SetTitle("Events/0.4");  
  hs->GetYaxis()->SetTitleOffset(1.2);  
  gPad->Modified();
  
  leg->AddEntry(hdata,"Data","lep");
     
  
  
  leg->AddEntry(hbkg1,"#gamma #gamma","f");
leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");                                                                               

  leg->AddEntry(hbkg2,"Drell Yann","f");
 
  leg->AddEntry(hbkg3,"#gamma + Jets","f");
leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");                                                                               

  leg->AddEntry(hbkg5,"QCD","f");
  
  leg->AddEntry(hbkg4,"ggH","f");
 leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");                                                                    
 
  leg->AddEntry(hbkg6,"VH","f");
 
  leg->AddEntry(hbkg7,"ttH","f");

 leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");                                                                    
  leg->AddEntry(hbkg8,"VBF H","f");
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");
leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l");                                                            
leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");
  leg->AddEntry(hbkg11,"#gamma+W","f");
leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l");     
  leg->AddEntry(hbkg12,"#gamma+Z","f");
  leg->AddEntry(hsum,"Bkg uncertainty","f");

 leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l");                            
 leg->Draw("same");
  
  c1->cd(); 
  smallPad->Draw(); 
  smallPad->cd();

  TGraphErrors *gr = new TGraphErrors(0);
  double integralData=hdata->Integral();
  double integralBKG=hsum->Integral();
  double error, ratio;
  for(int w=1; w<20; w++){
    if((hdata->GetBinContent(w)!=0) && (hsum->GetBinContent(w)!=0)){
      
      gr->SetPoint(w, hdata->GetBinCenter(w),(hdata->GetBinContent(w))/(hsum->GetBinContent(w)));
      ratio= (hdata->GetBinContent(w))/(hsum->GetBinContent(w));
      error= (hdata->GetBinContent(w)*sqrt(hsum->GetBinContent(w))/(hsum->GetBinContent(w)*hsum->GetBinContent(w)) + sqrt(hdata->GetBinContent(w))/hsum->GetBinContent(w));
      std::cout<<"VALUE: "<<ratio<<" ERROR: "<<error<<std::endl;
      gr->SetPointError(w, hdata->GetBinWidth(w)/2,error);
    }else{
      gr->SetPoint(w, hdata->GetBinCenter(w),10);
    } 
  }

  
  
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  gr->GetHistogram()->SetMaximum(2);
  gr->GetHistogram()->SetMinimum(0.1);
  
  gStyle->SetTextSize(14);
  gROOT->ForceStyle();
  
  gr->GetXaxis()->SetLabelFont(43);
  gr->GetXaxis()->SetLabelSize(15);
  gr->GetYaxis()->SetLabelFont(43);
  gr->GetYaxis()->SetLabelSize(15);
  
  gr->GetXaxis()->SetLimits(-4,4);
  
  
  gPad->SetGrid();
  gStyle->SetStripDecimals(kTRUE);
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(0.7);
  
  
  gr->Draw("AZP");
  gr->GetXaxis()->SetTitle("#phi_{2}");
  gr->GetXaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetNdivisions(505);
 
  gr->GetXaxis()->SetTitleOffset(1);
  gr->GetYaxis()->SetTitle("Data/MC"); 
  gr->GetYaxis()->SetTitleOffset(0.4);
  gr->SetTitle(""); 
  smallPad->Update();
  TF1* line = new TF1("line","1",-4,4);
  line->SetLineColor(kRed);
  line->SetLineWidth(2);
  line->Draw("L same");
  gr->Draw("ZP SAME");
  

  if(pt1min==0 && pt2min == 0 && METmin == 0){
    c1->SaveAs("./25ns_2246inv_v3/plots/kinematics/phi2.png");
    c1->SaveAs("./25ns_2246inv_v3/plots/kinematics/phi2.pdf");
  }
  if(pt1min==0.65 && pt2min == 0.25){
    c1->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/phi2_optcuts_MET%.0lf.png",METmin));
    c1->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/phi2_optcuts_MET%.0lf.pdf",METmin));
  }
  


}
Example #25
0
int main(int argc, char **argv)
{
	TString xvar = "TMath::Power(J_psi_1S_MM/1000,2)";
	TString xvarname = "q2";
	TString type = "All";
	TCut extCut = "";
	
	string drawopt = "";
	TString outFileName = "";
	bool rel = false, doSys = false, percent = false, jpsi = false, pythia6 = false;
	
	int xnbins = 12;
	double def_xbins[] = {0.1, 2.0, 4.0, 6.0, 8.0, 9.1, 10.1, 11.0, 12.5, 15.0, 16.0, 18.0, 20.0};
	//double def_xbins[] = {1.1, 6.0, 15.0, 20.0};
	double * xbins = &def_xbins[0];
	
	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);
			
			if(arg.find("-t") != string::npos) type = (TString)str;
			if(arg == "-r") rel = true;
			if(arg.find("-b") != string::npos ) xbins = decodeBinning(str,&xnbins);
			if(arg.find("-c") != string::npos ) xbins = decodeBinning(str,&xnbins,"custom");
			if(arg.find("-C") != string::npos ) extCut = (TCut)((TString)str);
			if(arg == "-highq2Cut") extCut = (TCut)"( TMath::Power(J_psi_1S_MM/1000,2) > 15. && TMath::Power(J_psi_1S_MM/1000,2) < 20. )";
			if(arg == "-Pythia6") pythia6 = true;
			if(arg.find("-X") != string::npos) { xvar = str; xvarname = xvar; }
			if(arg.find("-D") != string::npos) drawopt = str;
			if(arg.find("-sys") != string::npos) doSys = true;
			if(arg.find("-percent") != string::npos) percent = true;
			if(arg.find("-o") != string::npos) outFileName = str;
			if(arg.find("-jpsi") != string::npos) jpsi = true;
		}
	}
	
	if(jpsi) { if(xvarname=="q2") xbins = decodeBinning("[1,0,25]",&xnbins); rel = false; doSys = false; }

	// Set trees of cancdidates previously created

	TString mctype = "MC_Pythia8_NBweighted";
	if(pythia6) mctype = "MC_Pythia6_NBweighted"; 
	TString weight = "MCnorm*(lifeTimeW > 0)*(physRate_pol0_noDecay > 0)";
	cout << "Using: " << mctype << endl;
	cout << "Plotting: " << xvar << endl;
	cout << "Binning: [";
	for(int i = 0; i < xnbins; i++) cout << xbins[i] << ",";
	cout << xbins[xnbins] << "]" << endl;	

	TString namefileMCgeom = "/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_geom"+mctype+".root";
	TString namefileMC = "/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_"+mctype+".root";
	TString namefileMCjpsi = "/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2JpsiL_"+mctype+".root";
	TString namefileMCjpsiGeom = "/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2JpsiL_geom"+mctype+".root";
	TString namefileDataJpsi = "/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_CL_NBweighted.root";

	TString nameGeomTree = "MCtree";
	if(xvar=="cosThetaB") nameGeomTree = "MCtreeDecay";
	TFile * MCfile = TFile::Open(namefileMCgeom);
	TTree * treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
	MCfile = TFile::Open(namefileMC);
	TTree * treeMC = (TTree *)MCfile->Get("tree");
	TTree * treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
	TTree * treeMCAllGen = (TTree *)MCfile->Get("MCtree");
	MCfile = TFile::Open("/afs/cern.ch/work/p/pluca/Lmumu/weighted/trainingSamples.root");
	TTree * treeMCmva = (TTree *)MCfile->Get("sigTestSample");

	TTree * treeMCjpsi = NULL, * treeMCjpsi_Gen = NULL, * treeMCjpsi_AllGen = NULL, * treeMCjpsi_geom = NULL;
	if(rel || jpsi)
	{
		
		MCfile = TFile::Open(namefileMCjpsi);
		if(jpsi) {
		treeMC = (TTree *)MCfile->Get("tree");
		treeMCmva = (TTree *)MCfile->Get("tree");
		treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCAllGen = (TTree *)MCfile->Get("MCtree");	}
		else {
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	}
		
		MCfile = TFile::Open(namefileMCjpsiGeom);		
		if(jpsi) treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
		else treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);
	}
	
	TCut geomCut = CutsDef::geomCut;
	TCut baseCut = extCut + CutsDef::baseCutMuMu;
	if(jpsi) baseCut = extCut + CutsDef::baseCutJpsi;
	TCut baseJpsiCut = extCut + CutsDef::baseCutJpsi;
	TCut binCut = "TMath::Power(J_psi_1S_MM/1000,2) > 9.1 && TMath::Power(J_psi_1S_MM/1000,2) < 10.1";
	if(type == "DD") { baseCut += CutsDef::DDcut; baseJpsiCut += CutsDef::DDcut; }
	else if(type == "LL") { baseCut += CutsDef::LLcut; baseJpsiCut += CutsDef::LLcut; }
	cout << "Analysisng " << type << " events" << endl;

	TString myName = "Lbeff";
	if(rel) myName = "Lbreleff";
	if(doSys) myName += "AndSys";
	if(jpsi) myName += "_Jpsi"; 
	myName += ("vs"+xvarname+"_"+type+".root");
	if(outFileName!="") myName = outFileName;
	TFile * histFile = new TFile(myName,"recreate");

	/**      Calc efficiencies and systematics        */

	gROOT->ProcessLine(".x ~/work/lhcbStyle.C");

	vector <TString> effnames;
	effnames.push_back("geom");
	effnames.push_back("det");
	effnames.push_back("reco");
	effnames.push_back("mva");
	effnames.push_back("trig");

	vector <TString> complnames;
	complnames.push_back("Geometric");
	complnames.push_back("Detection");
	complnames.push_back("Reconstruction");
	complnames.push_back("MVA");
	complnames.push_back("Trigger");

	vector <TH1F * >  hdefault, hsys, hPIDsys;
	vector <TH1F * >  lfsys_plus, lfsys_minus;
	vector <TH1F * >  decaysys, DDsys;
	vector <TH1F * >  polsys_minus, polsys_plus;
	vector <TH1F * >  poljpsi1, poljpsi2, poljpsi3, poljpsi4, poljpsi5, poljpsi6, poljpsi7, poljpsi8;
	vector <TH1F * >  hwilson1, hwilson2, hwilson3;
	
	cout << "Analysing GEO sys" << endl;
	getAllEffSys("GEO", xvar, xnbins, xbins, weight,
			treeMCgeom, geomCut+extCut, treeMCgeom, extCut,
			treeMCjpsi_geom, geomCut+extCut+binCut, treeMCjpsi_geom, extCut+binCut,
			&hdefault, &hsys, NULL, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8,
			&hwilson1, &hwilson2, &hwilson3,
			&DDsys, doSys, "-f0.5", jpsi);

	cout << "Analysing DET sys" << endl;
	if(xvar=="cosThetaB")
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCgeom, geomCut+extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, geomCut+extCut+binCut,
			&hdefault, &hsys, NULL, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8,
			&hwilson1, &hwilson2, &hwilson3,
			&DDsys, doSys, "", jpsi );	
	else
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCAllGen, extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, extCut+binCut,
			&hdefault, &hsys, NULL, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8,
			&hwilson1, &hwilson2, &hwilson3,
			&DDsys, doSys, "", jpsi );
	
	cout << "Analysing RECO sys" << endl;
	getAllEffSys("RECO", xvar, xnbins, xbins, weight,
			treeMC, baseCut, treeMCGen, extCut,
			treeMCjpsi, baseJpsiCut+binCut, treeMCjpsi_Gen, extCut+binCut,
			&hdefault, &hsys, NULL, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8,
			&hwilson1, &hwilson2, &hwilson3,
			&DDsys, doSys, "", jpsi );
	
	cout << "Analysing MVA sys" << endl;
	getAllEffSys("MVA", xvar, xnbins, xbins, weight,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut, treeMCjpsi, baseJpsiCut+binCut,
			&hdefault, &hsys, &hPIDsys, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8,
			&hwilson1, &hwilson2, &hwilson3,
			&DDsys, doSys, "", jpsi );

	cout << "Analysing TRIG sys" << endl;
	getAllEffSys("TRIG", xvar, xnbins, xbins, weight,
			treeMC, baseCut+CutsDef::MVAcut+CutsDef::TrigPassed, treeMC, baseCut+CutsDef::MVAcut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+CutsDef::TrigPassed+binCut, treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut,
			&hdefault, &hsys, &hPIDsys, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8,
			&hwilson1, &hwilson2, &hwilson3,
			&DDsys, doSys, "", jpsi );
	
	TH1F * toteff_lowSel = NULL;
	if(rel || jpsi)
	{
		TString polweight = "physRate_polp006";
		if(jpsi) polweight = "physRate_pol0";
		TH1F * mva_lowSel = getEff("UPPER", xvar, xnbins, xbins,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			weight+"*lifeTimeW*Lb_weight*"+polweight,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut_lowSel+binCut, treeMCjpsi, baseJpsiCut+binCut,
			weight+"*lifeTimeW*physRate_pol0*pt_weight" );
		mva_lowSel->Write("hmvaeff_lowSel");
		TH1F * uppereff_lowSel = (TH1F *)hdefault[2]->Clone("huppereff_lowSel");
		uppereff_lowSel->Multiply(hdefault[3]);
		uppereff_lowSel->Multiply(mva_lowSel);
		toteff_lowSel = (TH1F *)hdefault[0]->Clone("htoteff_lowSel");
		toteff_lowSel->Multiply(hdefault[1]);
		toteff_lowSel->Multiply(uppereff_lowSel);
		uppereff_lowSel->Write("huppereff_lowSel");
		toteff_lowSel->Write("htoteff_lowSel");

		if(jpsi)
		{
			TH1F * pid = getEff("MCPID", xvar, xnbins, xbins,
			treeMC, baseCut+"pplus_PIDp > -5", treeMC, baseCut,
			weight+"*lifeTimeW*Lb_weight*"+polweight);
			cout << pid->GetBinCenter(1) << "   " << pid->GetBinContent(1) << " +/- " << pid->GetBinError(1) << endl;
		}
	}

			
	TCanvas * c = new TCanvas();
	gStyle->SetOptStat(0);
	gStyle->SetOptFit();
	TH1F * uppereff = (TH1F *)hdefault[2]->Clone("huppereff");
	uppereff->Multiply(hdefault[3]);
	uppereff->Multiply(hdefault[4]);
	TH1F * toteff = (TH1F *)hdefault[0]->Clone("htoteff");
	if(xvar=="cosThetaB") hdefault[1]->Scale(1./hdefault[1]->Integral());
	toteff->Multiply(hdefault[1]);
	toteff->Multiply(uppereff);
	toteff->SetTitle("Total eff");
	toteff->Draw();
	//toteff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_tot.pdf");
	toteff->Write("htoteff");
	//uppereff->Fit("pol2");
	uppereff->Draw();
	c->Print("effvs"+xvarname+"_"+type+"_upper.pdf");
	uppereff->Write("huppereff");
	TH1F * tot_nodet_eff = (TH1F *)hdefault[0]->Clone("htot_nodet_eff");
	tot_nodet_eff->Multiply(uppereff);
	tot_nodet_eff->Write("htot_nodet_eff");

	TH1F * syseff = (TH1F *)hsys[0]->Clone("hsyseff");
	syseff->Multiply(hsys[1]);
	syseff->Multiply(hsys[2]);
	syseff->Multiply(hsys[3]);
	syseff->Multiply(hsys[4]);
	syseff->Write("sys_eff");

	/*
	TH1F * Kinsys = (TH1F *)syseff->Clone("Kinsys");
	Kinsys->Add(toteff,-1);
	Kinsys->GetXaxis()->SetTitle("q^{2} (GeV^{2})");
	Kinsys->GetYaxis()->SetTitle("(eff^{now} - eff^{w})");// / eff^{w}");
	Kinsys->Draw();
	c->Print("Kin_sys.pdf");
	
	TH1F * PIDsyseff = (TH1F *)hPIDsys[0]->Clone("hPIDsyseff");
	PIDsyseff->Multiply(hPIDsys[1]);

	TH1F * PIDdefeff = (TH1F *)hdefault[3]->Clone("hdefPID");
	PIDdefeff->Multiply(hdefault[4]);
	
	TH1F * PIDsys = (TH1F *)PIDsyseff->Clone("PIDsys");
	PIDsys->Add(PIDdefeff,-1);
	//PIDsys->Divide(toteff,1,"B");
	PIDsys->Write("PIDmuSys");
	PIDsys->GetXaxis()->SetTitle("q^{2} (GeV^{2})");
	PIDsys->GetYaxis()->SetTitle("(eff^{now} - eff^{w})");// / eff^{w}");
	PIDsys->Draw();
	c->Print("PIDmu_sys.pdf");
*/

	for(unsigned i = 0; i < effnames.size(); i++)
	{
		//hdefault[i]->Fit("pol2");
		if(!jpsi)
		for(int b = 0; b < hdefault[i]->GetNbinsX(); b++)
		{
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(10.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(10.5),0);
		}
		if(rel) hdefault[i]->SetMinimum(0.5);
		if(rel) hdefault[i]->SetMaximum(1.5);
		hdefault[i]->GetXaxis()->SetTitle("q^{2} [GeV^{2}/#it{c}^{4}]");
		hdefault[i]->GetYaxis()->SetTitle("Efficiency");
		hdefault[i]->SetTitle(complnames[i]);
		hdefault[i]->Draw();
		c->Print("effvs"+xvarname+"_"+type+"_"+effnames[i]+".pdf");
		hdefault[i]->Write("h"+effnames[i]+"eff");
	}

	gStyle->SetOptFit(0);



	/** Printing out efficiencies and systematics **/

	vector <TString> sysnames;
	sysnames.push_back("Lifetime");
	sysnames.push_back("Decay Model");
	sysnames.push_back("Polarization");
	if(type=="DD") sysnames.push_back("DD vtx");
	
	/** Print efficiencies */ 

	cout << "\n\n" << xvarname << " bin " << " \t\t\t& ";
	for(unsigned s = 0; s < effnames.size(); s++) cout << effnames[s] << " \t\t\t\t& ";
	cout << "Upper \t\t\t\t& Total  \\\\" << endl;

	TGraphErrors * grtoteff = new TGraphErrors();
	TGraphErrors * grtoteff_lowSel = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << fixed << setprecision(1) << "eff " << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";

		for(unsigned i = 0; i < hdefault.size(); i++)	
			cout << "$" << hdefault[i]->GetBinContent(j) << " \\pm " << hdefault[i]->GetBinError(j) << "$ \t & ";

		cout << "$" << uppereff->GetBinContent(j) << " \\pm " << uppereff->GetBinError(j) << "$ \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << toteff->GetBinError(j) << "$ \\\\ " << endl;

		grtoteff->SetPoint(j,toteff->GetBinCenter(j),toteff->GetBinContent(j));
		grtoteff->SetPointError(j,toteff->GetBinWidth(j)/2.,toteff->GetBinError(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPoint(j,toteff_lowSel->GetBinCenter(j),toteff_lowSel->GetBinContent(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPointError(j,toteff_lowSel->GetBinWidth(j)/2.,toteff_lowSel->GetBinError(j));
	}

	grtoteff->Write("toteff");
	if(toteff_lowSel) grtoteff_lowSel->Write("toteff_lowSel");
	if(!doSys) { delete MCfile; delete histFile; return 0; }


	/** Print sys separate in efficiency */
	
	vector < TH1F * > tmp;
	vector < vector < TH1F * > > sys_eff(4,tmp);
	vector < TH1F * > tot_sys_eff;
	vector < TH1F * > wilson1_sys_eff, wilson2_sys_eff, wilson3_sys_eff;

	cout << endl << endl << endl;
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << "\t& " << sysnames[s];
	cout << " \\\\" << endl;

	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==10.1 && !rel) || xbins[j]==15 || xbins[j]==9.1 || xbins[j]==11) continue;

		cout << "-----------------------------------------------------------------------------------------" << endl;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << endl;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		if(!percent) cout << fixed << setprecision(5);

		for(unsigned i = 0; i < effnames.size(); i++)
		{
			if(j==1)
			{
				sys_eff[0].push_back((TH1F*)toteff->Clone("sys_lf_"+effnames[i]));
				sys_eff[1].push_back((TH1F*)toteff->Clone("sys_decay_"+effnames[i]));
				sys_eff[2].push_back((TH1F*)toteff->Clone("sys_pol_"+effnames[i]));
				sys_eff[3].push_back((TH1F*)toteff->Clone("sys_DD_"+effnames[i]));
				tot_sys_eff.push_back((TH1F*)toteff->Clone("tot_sys_eff"));
				wilson1_sys_eff.push_back((TH1F*)toteff->Clone("wilson1_sys"));
				wilson2_sys_eff.push_back((TH1F*)toteff->Clone("wilson2_sys"));
				wilson3_sys_eff.push_back((TH1F*)toteff->Clone("wilson3_sys"));
				sys_eff[0][i]->Reset();
				sys_eff[1][i]->Reset();
				sys_eff[2][i]->Reset();
				sys_eff[3][i]->Reset();
				tot_sys_eff[i]->Reset();
				wilson1_sys_eff[i]->Reset();
				wilson2_sys_eff[i]->Reset();
				wilson3_sys_eff[i]->Reset();
			}

			double lf_sys = createSys(j,hdefault[i], lfsys_minus[i], lfsys_plus[i]);
			double decay_sys = createSys(j,hdefault[i], decaysys[i], decaysys[i]);
			double DD_sys = 0;
			double pol_sys = createSys(j, hdefault[i], polsys_minus[i], polsys_plus[i]);
			pol_sys = createSys(j, hdefault[i], poljpsi1[i], poljpsi2[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi3[i], poljpsi4[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi5[i], poljpsi6[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi7[i], poljpsi8[i], pol_sys);
			double cureff = hdefault[i]->GetBinContent(j);
			double curerr = hdefault[i]->GetBinError(j);
			double tot_eff_sys = TMath::Sqrt( TMath::Power(lf_sys,2) + TMath::Power(pol_sys,2) + TMath::Power(decay_sys,2) );

			double wilson_sys1 = createSys(j, hdefault[i], hwilson1[i], hwilson1[i]);
			double wilson_sys2 = createSys(j, hdefault[i], hwilson2[i], hwilson2[i]);
			double wilson_sys3 = createSys(j, hdefault[i], hwilson3[i], hwilson3[i]);
			
			if(type=="DD")
			{
				DD_sys = createSys(j, hdefault[i], DDsys[i], DDsys[i]);
				tot_eff_sys = TMath::Sqrt( TMath::Power(tot_eff_sys,2) + TMath::Power(DD_sys,2) );
				sys_eff[3][i]->SetBinContent(j,DD_sys);
			}

			cout << effnames[i] << " \t  & ";
			if(percent)
			{
				cout << lf_sys*100 << "\\% \t & " << decay_sys*100 << "\\% \t & " << pol_sys*100 << "\\% \t";
				if(type=="DD") cout << " & " << DD_sys*100 << " \t ";	
			}	
			else
			{
				cout << cureff << " \t & " << curerr << " \t & ";
				cout << lf_sys*cureff << " \t & " << decay_sys*cureff << " \t & " << pol_sys*cureff << " \t";
				if(type=="DD") cout << " & " << DD_sys*cureff << " \t";	
			}	
			cout << " \\\\ " << endl;
			sys_eff[0][i]->SetBinContent(j,lf_sys);
			sys_eff[1][i]->SetBinContent(j,decay_sys);
			sys_eff[2][i]->SetBinContent(j,pol_sys);
			tot_sys_eff[i]->SetBinContent(j,tot_eff_sys);
			wilson1_sys_eff[i]->SetBinContent(j,wilson_sys1);
			wilson2_sys_eff[i]->SetBinContent(j,wilson_sys2);
			wilson3_sys_eff[i]->SetBinContent(j,wilson_sys3);
		}
	}


		/** Print total sys */

	vector< TH1F * > sys;
	TH1F * tot_sys = getErrHist(toteff);
	
	for(unsigned s = 0; s < sysnames.size(); s++)
	{
		TH1F * tmp_sys = NULL;
				
		for(unsigned i = 0; i < effnames.size(); i++)
			tmp_sys = sqSum(tmp_sys,sys_eff[s][i]); 
	
		sys.push_back( tmp_sys );
		tmp_sys->Write("sys_"+sysnames[s]);
		tot_sys = sqSum(tot_sys,tmp_sys);
	}
	tot_sys->Write("sys_tot");

	TH1F * wilson_sys1 = NULL, * wilson_sys2 = NULL, * wilson_sys3 = NULL;
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		wilson_sys1 = sqSum(wilson_sys1,wilson1_sys_eff[i]); 
		wilson_sys2 = sqSum(wilson_sys2,wilson2_sys_eff[i]);
		wilson_sys3 = sqSum(wilson_sys3,wilson3_sys_eff[i]);
	}

	wilson_sys1->SetBinContent(wilson_sys1->GetXaxis()->FindBin(8.5),0);
	wilson_sys1->SetBinError(wilson_sys1->GetXaxis()->FindBin(8.5),0);
	wilson_sys1->SetBinContent(wilson_sys1->GetXaxis()->FindBin(10.5),0);
	wilson_sys1->SetBinError(wilson_sys1->GetXaxis()->FindBin(10.5),0);
	wilson_sys1->SetBinContent(wilson_sys1->GetXaxis()->FindBin(13.),0);
	wilson_sys1->SetBinError(wilson_sys1->GetXaxis()->FindBin(13.),0);

	wilson_sys1->Write("rel_wilson_sys1");
	wilson_sys1->SetTitle("Relative Wilson Coeff variation sys (CNP[7]=-0.05, CNP[9]=-1.3)");
	wilson_sys1->Draw();
	c->Print("rel_wilson1_sys"+type+".pdf");

	wilson_sys2->SetBinContent(wilson_sys2->GetXaxis()->FindBin(8.5),0);
	wilson_sys2->SetBinError(wilson_sys2->GetXaxis()->FindBin(8.5),0);
	wilson_sys2->SetBinContent(wilson_sys2->GetXaxis()->FindBin(10.5),0);
	wilson_sys2->SetBinError(wilson_sys2->GetXaxis()->FindBin(10.5),0);
	wilson_sys2->SetBinContent(wilson_sys2->GetXaxis()->FindBin(13.),0);
	wilson_sys2->SetBinError(wilson_sys2->GetXaxis()->FindBin(13.),0);

	wilson_sys2->Write("rel_wilson_sys2");
	wilson_sys2->SetTitle("Relative Wilson Coeff variation sys (CNP[7]=-0.03, CNP[9]=-1.7)");
	wilson_sys2->Draw();
	c->Print("rel_wilson2_sys"+type+".pdf");

	wilson_sys3->SetBinContent(wilson_sys3->GetXaxis()->FindBin(8.5),0);
	wilson_sys3->SetBinError(wilson_sys3->GetXaxis()->FindBin(8.5),0);
	wilson_sys3->SetBinContent(wilson_sys3->GetXaxis()->FindBin(10.5),0);
	wilson_sys3->SetBinError(wilson_sys3->GetXaxis()->FindBin(10.5),0);
	wilson_sys3->SetBinContent(wilson_sys3->GetXaxis()->FindBin(13.),0);
	wilson_sys3->SetBinError(wilson_sys3->GetXaxis()->FindBin(13.),0);

	wilson_sys3->Write("rel_wilson_sys3");
	wilson_sys3->SetTitle("Relative Wilson Coeff variation sys (CNP[7]= 0.01, CNP[9]=-2.1)");
	wilson_sys3->Draw();
	c->Print("rel_wilson3_sys"+type+".pdf");

	cout << endl << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t & " << sysnames[s];
	cout << " \t & Total \\\\" << endl;


	for(unsigned i = 0; i < effnames.size(); i++)
	{
		TGraphErrors * grtot_eff = new TGraphErrors();
		cout << endl << effnames[i] << endl;

		for(int j = 1; j <= toteff->GetNbinsX(); j++)
		{
			if((xbins[j]==10.1 && !rel) || xbins[j]==15 || xbins[j] == 9.1 || xbins[j]==11) continue;
			cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << "  \t & ";
		
			double cureff = hdefault[i]->GetBinContent(j);
			if(!percent) cout << fixed << setprecision(5) << cureff << " \t & " << hdefault[i]->GetBinError(j) << "   \t & ";
		
			for(unsigned s = 0; s < sysnames.size(); s++)
				if(percent) cout << sys_eff[s][i]->GetBinContent(j)*100 << "\\% \t & ";
				else cout << sys_eff[s][i]->GetBinContent(j)*cureff << " \t & ";
			
			if(percent) cout << tot_sys_eff[i]->GetBinContent(j)*100 << "\\% ";
			else cout << tot_sys_eff[i]->GetBinContent(j)*cureff;

			//if(percent) cout << wilson_sys_eff[i]->GetBinContent(j)*100 << "\\%";
			//else cout << wilson_sys_eff[i]->GetBinContent(j)*cureff;
			cout << " \\\\ " << endl;

			grtot_eff->SetPoint(j,tot_sys_eff[i]->GetBinCenter(j),tot_sys_eff[i]->GetBinContent(j));
			grtot_eff->SetPointError(j,tot_sys_eff[i]->GetBinWidth(j)/2.,0.);
		}

		grtot_eff->Write(effnames[i]+"sys");
	}

	cout << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t\t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t\t & " << sysnames[s];
	cout << " \t\t & Wilson Coeff sys";
	cout << " \\\\" << endl;

	TGraphErrors * grtot = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3);
		double cureff = toteff->GetBinContent(j);
		if(!percent) cout << fixed << setprecision(5) << cureff << " \t\t & " << toteff->GetBinError(j);
		
		for(unsigned s = 0; s < sysnames.size(); s++)
			if(percent) cout << "  \t\t & " << sys[s]->GetBinContent(j)*100 << "\\% ";
			else cout << " \t\t & " << sys[s]->GetBinContent(j)*cureff;
			
		//if(percent) cout << " \t\t & " << wilson_sys->GetBinContent(j)*100 << "\\% ";
		//else cout << " \t\t & " << wilson_sys->GetBinContent(j)*cureff;

		cout << " \\\\ " << endl;

		grtot->SetPoint(j,tot_sys->GetBinCenter(j),tot_sys->GetBinContent(j));
		grtot->SetPointError(j,tot_sys->GetBinWidth(j)/2.,0.);
	}
	
	grtot->Write("totsys");

/*
	cout << "\n\n" << xvarname << " bin\t\t& Value \\\\" << endl;
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << tot_sys->GetBinContent(j)*toteff->GetBinContent(j) << "$ \\\\ " << endl;
	}
*/
	delete MCfile;
	delete histFile;
	return 0;
}
Example #26
0
void PlotPubHisto(TObjArray histograms,TEnv *params){
    // This is a modification of the AddHistos macro
    
    // Number of histos to plot:
    Int_t ntot = histograms.GetEntries();
    
    // Check we have what we expect (the order should be: data, qcd, wjets, etc...)
    for(Int_t i = 0; i<ntot; i++){
	if(histograms[i]==0) {
	    cout<<"Error in AddHistos: histogram "<<i<<" is a NULL pointer!"<<endl;
	    return;
	}
	TH1F * hthis = (TH1F*) histograms[i];
	// include the overflow/underflow bins:
	int numbins = hthis->GetNbinsX(); //this is the last bin plotted
	double hicontent = hthis->GetBinContent(numbins);
	double overflow  = hthis->GetBinContent(numbins+1);// this bin contains the overflow
	double locontent = hthis->GetBinContent(1);// this is the first bin plotted
	double underflow = hthis->GetBinContent(0);// this bin contains the underflow
	if (underflow>0 || overflow>0){
	    //printf("%-20s numbins=%4i hicontent=%4.2f over=%4.2f locontent=%4.2f underflow=%4.2f \n",
	    //	 title.Data(),numbins,hicontent,overflow,locontent,underflow);
	}
	hthis->SetBinContent(numbins,hicontent+overflow);
	hthis->SetBinContent(1,locontent+underflow);
    }
    
    // define a few additional line styles:
    gStyle->SetLineStyleString(5,"20 12 4 12");
    gStyle->SetLineStyleString(6,"20 12 4 12 4 12 4 12");
    gStyle->SetLineStyleString(7,"20 20");
    gStyle->SetLineStyleString(8,"20 12 4 12 4 12");
    gStyle->SetLineStyleString(9,"80 25");
    gStyle->SetLineStyleString(10,"50 10 10 10");
    gStyle->SetLineStyleString(17,"30 25");
    gStyle->SetLineStyleString(20,"60 20");
    gStyle->SetLineStyleString(21,"60 20 20 20");
    int lineStyle[20];
    for(int i=0;i<20;i++) {
	lineStyle[i]=i;
    }

    // the first histogram in the list:
    TH1F *h0=((TH1F*) histograms[0])->Clone();
    
    // histogram output filename
    TString oFileName=params->GetValue("Histo.Output.Filename","bogus.eps");
    
    // figure out the number of signals
    Int_t nsig=1;
    if(params->Defined("Histo.Signal.Title.1")) nsig=1;
    if(params->Defined("Histo.Signal.Title.2")) nsig=2;
    if(params->Defined("Histo.Signal.Title.3")) nsig=3;
    
    cout << " I will use nsig = " << nsig << " signal sources" << endl;
    
    // Do the cumulative summing, except for the data
    TObjArray addedhistos; addedhistos.Clear();
    TObjArray signalhistos; signalhistos.Clear();
    TString sampletitles[20];
    Int_t nbkg=0;
    for(Int_t i = 1; i<ntot; i++){// i runs over histograms[i], so data is for i=0
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+1 << ".";// Counting starts at 1: Files.1.Name: Data
	TString bSrcName(baseSrcName.str().c_str());
	// skip some if we want to show them as lines
	TString htitle=params->GetValue(bSrcName+"Title","");
	sampletitles[i-1]=htitle;
	if(params->GetValue("Histo.ShowSignalSeparately",0)==1 &&
	   // skip the last two if the signal title is not defined:
	   ( ( !(params->Defined("Histo.Signal.Title")||params->Defined("Histo.Signal.Title.1")) && i>=ntot-nsig) 
	     // skip the signal if the signal title is defined
	     || params->GetValue("Histo.Signal.Title",".")==htitle
	     || params->GetValue("Histo.Signal.Title.1",".")==htitle
	     || params->GetValue("Histo.Signal.Title.2",".")==htitle
	     || params->GetValue("Histo.Signal.Title.3",".")==htitle
	     ) ) {
	    TH1F * hthis = (TH1F*) histograms[i]->Clone();
	    cout<<" Found signal in location "<<i+1<<" with name "<<htitle.Data()<<endl;
	    signalhistos.Add(hthis);
	} else {
	    TH1F * hthis = (TH1F*) histograms[i]->Clone();
	    addedhistos.Add(hthis); // Fill in the new TObjArray with a copy 
	    //cout << " Adding bkg " << i << " " << htitle.Data() << " " << hthis->Integral() << endl;
	    // add all of the backgrounds
	    if (i>1) {// i=0 is the data, and we must start with the second
		      // background to add the previous
		TH1F * hprevious = (TH1F*) addedhistos[i-2];
		if ( hthis->GetXaxis()->GetNbins() != hprevious->GetXaxis()->GetNbins() ) {
		    // Protection against _whoran histogram. 
		    // We cannot add two histograms with different numbers of bins!
		    cout<<"Error in AddHistos: incompatible number of bins!"<<endl;  
		    return;
		}
		hthis->Add(hprevious); // Do the addition
		addedhistos.RemoveAt(i-1); // And substitute whatever we had 
		addedhistos.AddAt(hthis,i-1);
		nbkg++;
		//cout << "Substituing bkg " << i << " + " << i-1 << " in addedhistos["<< i-1 <<"]" << endl;
	    }	    
	} // end of: if adding histograms
    }
    cout << " nbkg = " << nbkg << endl; 
    
    // Rebin histos if necessary, but first calculate KS:
    TH1F *hbkg = (TH1F*) addedhistos[nbkg];
    double KS = h0->KolmogorovTest(hbkg);
    double chi2ndf = h0->Chi2Test(hbkg, "UWUFOFCHI2/NDF");
    //cout << title.Data() << " KS = " << KS << " chi2/NDF = " << chi2ndf << endl;
    // Rebin? Set nrebin = 0 to NOT do rebinning. 
    // Will rebin only histos whose maximum x axis value exceeds 20. 
    // Anything with less will most probably be already made of integers, so no
    // need to rebin that! 
    Int_t nbinsx = h0->GetXaxis()->GetNbins();
    Int_t nbinsy = 100;
    Int_t nrebin = 5;
    if ( nbinsx > 750 && nbinsx <= 1000) nrebin = 30;
    if ( nbinsx > 400 && nbinsx <= 750 ) nrebin = 25;//20
    if ( nbinsx > 300 && nbinsx <= 400 ) nrebin = 25;//15
    if ( nbinsx > 200 && nbinsx <= 300 ) nrebin = 25;//15
    if ( nbinsx > 150 && nbinsx <= 200 ) nrebin = 10;//10
    if ( nbinsx > 100 && nbinsx <= 150 ) nrebin = 10;//10
    if ( nbinsx > 50 && nbinsx <= 100 )  nrebin = 10;//10
    if ( nbinsx > 20 && nbinsx <= 50 )   nrebin = 2;
    if ( nbinsx <= 20 ) nrebin = 1;  
    
    printf(" Saw nbins =%4i, rebinning by nrebin =%2i to final %3i bins \n",nbinsx,nrebin,int(nbinsx/nrebin));	

    if ( nrebin != 0 ) {
	h0->Rebin(nrebin); // data
	for (Int_t i = 0; i<=nbkg; i++){
	    TH1F * h = (TH1F*) addedhistos[i];
	    h->Rebin(nrebin);
	}
	for (Int_t i = 0; i<nsig; i++){
	    TH1F * h = (TH1F*) signalhistos[i];
	    h->Rebin(nrebin);
	}
    }

    // default text size: 0.045
    // make it bigger for the paper
    float textSize = 0.045;
    if(params->GetValue("Histo.Preliminary","yes")==TString("paper")) textSize=0.07;
    if(params->Defined("Histo.TextSize")) textSize=params->GetValue("Histo.TextSize",0.07);
    
    // Now, check largest dimensions so that we can plot all histograms at once.
    Float_t xmin=9999., xmax=-9999., ymin=9999., ymax=-9999.;
    for(Int_t i = 0; i<=nbkg; i++){
	TH1F * h = (TH1F*) addedhistos[i];
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+1 << ".";
	TString bSrcName(baseSrcName.str().c_str());
	
	TAxis *axis = h->GetXaxis();
	if( axis->GetXmin() < xmin ) xmin = axis->GetXmin();
	if( axis->GetXmax() > xmax ) xmax = axis->GetXmax();
	if( h->GetMinimum() < ymin ) ymin = h->GetMinimum();
	if( h->GetMaximum() > ymax ) ymax = h->GetMaximum();
    }
    ymax = TMath::Nint(ymax*1.25+1); // Make enough room for the big legend
    TString title = h0->GetTitle();
    
    //
    // now check if we should simply use the ranges that was passed to us.
    if(params->Defined("Histo.Xmin")) xmin = params->GetValue("Histo.Xmin",0.);
    if(params->Defined("Histo.Xmax")) xmax = params->GetValue("Histo.Xmax",0.);
    if(params->Defined("Histo.Ymin")) ymin = params->GetValue("Histo.Ymin",0.);
    if(params->Defined("Histo.Ymax")) ymax = params->GetValue("Histo.Ymax",0.);
    
    // Now make the frame:
    TH2F * frame = new TH2F("frame","",nbinsx,xmin,xmax,nbinsy,ymin,ymax);
    cout<<" frame has xmin "<<xmin<<", xmax "<<xmax<<", ymax "<<ymax<<endl;
    
    // get the x- and y-axis titles
    TString ytitle=params->GetValue("Histo.YTitle","");
    if ( params->Defined("Histo.XTitle")) {
	frame->SetXTitle(params->GetValue("Histo.XTitle",""));
    } else {
	frame->SetXTitle(h0->GetTitle());
    }
    frame->SetYTitle(ytitle.Data()); 
    // also set the text size for the X and Y axis titles and numbers
    // do this globally for the style we are using
    float axisLabelSize=textSize;
    frame->GetXaxis()->SetLabelSize(axisLabelSize);
    frame->GetYaxis()->SetLabelSize(axisLabelSize);
    frame->GetXaxis()->SetTitleSize(axisLabelSize);
    frame->GetYaxis()->SetTitleSize(axisLabelSize);
    
    frame->SetStats(false);
    // reduce the axis title offset if the fonts are very large
    if(textSize>0.055) frame->GetXaxis()->SetTitleOffset(1.0);
    // also change the X axis title offset to move it farther away from the numbers
    if(params->Defined("Histo.XTitle.Offset")) {
	float xtitoffset=params->GetValue("Histo.XTitle.Offset",1.0);
	frame->GetXaxis()->SetTitleOffset(xtitoffset);
    }
    
    // also change the y axis title offset to move it farther away from the numbers
    frame->GetYaxis()->SetTitleOffset(1.0);
    // reduce the axis title offset if the fonts are very large
    if(textSize>0.055) frame->GetYaxis()->SetTitleOffset(1.0);
    
    // set the axes divisions
    frame->GetXaxis()->SetNdivisions(505,true);
    if(params->Defined("Histo.XNdivisions")) frame->GetXaxis()->SetNdivisions(params->GetValue("Histo.XNdivisions",505),kTRUE);
    if(params->Defined("Histo.YNdivisions")) frame->GetYaxis()->SetNdivisions(params->GetValue("Histo.YNdivisions",505),kTRUE);
    
    // make sure the X axis title and Y axis title are in black!
    frame->GetXaxis()->SetTitleColor(1);
    frame->GetYaxis()->SetTitleColor(1);

    // Could plot in log scale...
    //gPad->SetLogy();

    // finally: Draw
    frame->Draw();
    
    // Draw the background ones:
    for(Int_t i=nbkg; i>=0; i--){
	TH1F * h = (TH1F*) addedhistos[i];
	h->SetStats(kFALSE);
	
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+2 << ".";// to account for the data which is Files.1
	TString bSrcName(baseSrcName.str().c_str());
	Int_t hcolor=params->GetValue(bSrcName+"Color",1); 	
	h->SetLineColor(1);      
	h->SetFillColor(hcolor);
        if (i==nbkg) printf(" Data Yield = %5.2f ; SumBkg = %5.2f ; Data-SumBkg diff = %5.2f%% \n",
	   		     h0->Integral(),h->Integral(),(h0->Integral()-h->Integral())*100./h0->Integral());
	printf(" plotting bkg i=%2i name=%20.20s file=%2i integral=%5.1f color=%2i\n",
	       i,sampletitles[i].Data(),i+2,h->Integral(),hcolor);
	int fillStyle=params->GetValue(bSrcName+"FillStyle",1001);
	h->SetFillStyle(fillStyle);
	h->DrawCopy("Hist,Same");
    }
    //
    // and draw the signal ones
    // draw them in reverse order so that the last one will be on top.
    //for(Int_t i=ntot-3; i<ntot; i++){
    for(Int_t i=nsig-1; i>=0; i--){
	ostringstream baseSrcName;
	baseSrcName << "Files." << ntot+1-nsig+i << ".";
	TString bSrcName(baseSrcName.str().c_str());
	
	Int_t hcolor=params->GetValue(bSrcName+"Color",1);
	TH1F * h = (TH1F*) signalhistos[i];
       	if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=90"))        h->Add (h, 1.07874865  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=100"))  h->Add (h, 1.62317373  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=110"))  h->Add (h, 2.31347600  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=120"))  h->Add (h, 3.25275183  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=130"))  h->Add (h, 4.54142919  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=140"))  h->Add (h, 6.19195046  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=150"))  h->Add (h, 8.38307290  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=160"))  h->Add (h, 11.31721008 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=170"))  h->Add (h, 14.85376469 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=180"))  h->Add (h, 19.54537459 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=190"))  h->Add (h, 25.44594010 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=200"))  h->Add (h, 32.94784356 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=220"))  h->Add (h, 54.09499080 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=240"))  h->Add (h, 86.85079034 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=260"))  h->Add (h, 136.31406761-1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=280"))  h->Add (h, 210.70375053-1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=300"))  h->Add (h, 319.79533099-1.000);
	
	printf(" plotting sig i=%2i name=%20.20s file=%2i integral=%5.1f color=%2i\n",
	       i,sampletitles[ntot-1-nsig+i].Data(),ntot+1-nsig+i,h->Integral(),hcolor);
	// create a white background around each line (helps readibility):
	TH1F *h1=h->Clone();
	h1->SetStats(kFALSE);
	h1->SetLineWidth(6);
	h1->SetLineColor(0);h1->SetFillColor(0);
	h1->SetLineStyle(1);
	h1->SetFillStyle(0);
	h1->Draw("HIST,SAME");
	// now draw the proper line:
	h->SetStats(kFALSE);
	h->SetLineWidth(6);
	h->SetLineColor(hcolor);h->SetFillColor(0);	
	Int_t hlinestyle = params->GetValue(bSrcName+"LineStyle",1);
	h->SetLineStyle(hlinestyle);
	h->SetFillStyle(0);	
	// finally, draw!
	h->Draw("HIST,SAME");      
    } // end of: drawing signal as separate lines
    
    // Data is special: 
    // change the default size of the little bar at the end of the error bar here
    gStyle->SetEndErrorSize(3);
    // also, maybe don't display the error bars along the X axis:
    //gStyle->SetErrorX(0);  // X error bars not displayed
    gStyle->SetErrorX(0.5);  // X error bars have width of a bin
    // now set the rest
    h0->SetMarkerSize(2);
    // if there are too many points (>80), keep the marker size smaller
    if(h0->GetNbinsX()>=50) h0->SetMarkerSize(1);
    //if(h0->GetNbinsX()>=100) h0->SetMarkerSize(1);
    h0->SetLineWidth(3);
    h0->SetMarkerStyle(8);
    h0->SetMarkerColor(1);
    h0->Draw("E1,SAME");
    
    // Print some comparison:
    //ostringstream basefactor;
    //basefactor << "Files." << nbkg+3 << "." << "Factor";
    //TString timesfactor(basefactor.str().c_str()); 
    //Double_t nprod = params->GetValue(timesfactor,1.000);
    //printf("Data Yield = %5.2f ; SumBkg = %5.2f ; SumBkg+Sig = %5.2f ; Data-SumBkg diff = %5.2f%% \n",
    //        h0->Integral(),hbkg2->Integral,(hbkg2->Integral()+(signalhistos[0]->Integral()/nprod),
    //        (h0->Integral()-hbkg2->Integral)*100./h0->Integral()));

    //
    // Print D0 and lumi:
    //
    TText *t1 = new TText();
    t1->SetTextFont(62);
    t1->SetTextColor(1);   
    t1->SetNDC();
    t1->SetTextAlign(12);
    t1->SetTextSize(textSize);
    TString prelim="D\328 Preliminary";
    if(oFileName.EndsWith(".eps")) {
	prelim="D\349 Preliminary L=3.7 fb^-1#";
    }
    else if(oFileName.EndsWith(".gif")) {
	prelim="D\328 Preliminary L=3.7 fb^-1#";
    }
    t1->DrawTextNDC(0.13,0.965,prelim.Data());

    // a counter of how much text we have added from the top
    int nAddTextLines=0;
    
    // any additional text?
    for(int iText=1;iText<20;iText++) {
	ostringstream baseTextName;
	baseTextName << "Histo.AddText." << iText;
	TString bTextName(baseTextName.str().c_str());
	if(params->Defined(bTextName)) {
	    // we are adding a line of text
	    TLatex *t2 = new TLatex();
	    t2->SetTextFont(62);
	    t2->SetTextColor(13);   
	    t2->SetTextAlign(32);
	    t2->SetNDC();
	    t2->SetTextSize(textSize);
	    TString addText(params->GetValue(bTextName,"."));
	    float x0=0.94;
	    float y0=0.96-(nAddTextLines)*0.05;
	    
	    // check if the user specified an alternative location for the text
	    if(params->Defined(bTextName+".X0")) x0=params->GetValue(bTextName+".X0",0.94);
	    if(params->Defined(bTextName+".Y0")) y0=params->GetValue(bTextName+".Y0",0.8);
	    if(params->Defined(bTextName+".TextSize")) t2->SetTextSize(params->GetValue(bTextName+".TextSize",textSize));
	    
	    // and increment the counter keeping track of how much we added,
	    // but only if the user didn't move the label around.
	    if(!params->Defined(bTextName+".X0")) nAddTextLines++;
	    printf("AddText %4.2f %4.2f %s\n",x0,y0,addText.Data());
	    
	    t2->DrawLatex(x0,y0,addText.Data()); 
	}
    }// end additional text
    
    // now draw the frame axis again so that we can see the tick marks
    frame->Draw("sameaxis");
    
    // Legend:
    TString showLegend(params->GetValue("Histo.ShowLegend","."));
    if( showLegend != "no" ){ 
	float lgdxmin=.65, lgdxmax=.90, lgdymin=.50, lgdymax=.91;
	if(showLegend=="yes" || showLegend=="right") {
	    
	} else if (showLegend=="left"){
	    lgdxmin=.16;
	    lgdxmax=.42;
	}
	TLegend *lgd = new TLegend(lgdxmin,lgdymin,lgdxmax,lgdymax); 
	// This line makes the legend transparent (not grey, ewwww!): 
	lgd->SetBorderSize(0); lgd->SetTextSize(textSize*0.9);// 10% less size 
	lgd->SetTextFont(62); lgd->SetFillColor(0);
	// Plot the legend in reverse order (but data goes first):
	NiceAddEntry(lgd,h0,params->GetValue("Files.1.Title","Data"),"PL");
	for(Int_t i = nbkg; i>=0; i--){
	    TH1F * h = (TH1F*) addedhistos[i];
	    TString lgd_entry= sampletitles[i]; // sampletitles runs from 0 (firstbkg) to ntot-1
	    NiceAddEntry(lgd,h,lgd_entry.Data(),"F");	
	}
	for(Int_t i = nsig-1; i>=0; i--){
	    TH1F * h = (TH1F*) signalhistos[i];
	    TString lgd_entry = sampletitles[i+nbkg+1]; // sampletitles runs from 0 (firstbkg) to ntot-1
	    ostringstream basefactor;
	    basefactor << "Files." << i+nbkg+3 << "." << "Factor";
	    TString timesfactor(basefactor.str().c_str());
	    Double_t nprod = params->GetValue(timesfactor,1.000);
	    if (nprod != 1.0 ) lgd_entry.Form("%s x%2.0f",lgd_entry.Data(),nprod);
	    //cout << i+nbkg+3 << " " << nprod << " " << lgd_entry.Data() << endl;
	    NiceAddEntry(lgd,h,lgd_entry.Data(),"L"); 
	}
	lgd->Draw("SAME");	
    }// show legend


    // Draw the KS:
    TLatex *ks = new TLatex();
    ks->SetTextFont(62);
    ks->SetTextColor(1);   
    TString ks_val = Form("KS = %3.2f",KS);
    ks->SetTextAlign(11); ks->SetTextSize(0.03); // ks->SetTextAngle(90); 
    ks->DrawTextNDC(0.83,0.93,ks_val.Data());
    TString chi2_val = Form("#chi^{2}/ndf = %3.1f",chi2ndf);
    ks->SetNDC(true); ks->DrawLatex(0.83,0.97,chi2_val.Data());
    //
    // Voila!
    //
}
Example #27
0
void Unfold2(int algo= 3,bool useSpectraFromFile=0, bool useMatrixFromFile=0, int doToy = 0, int isMC = 0,char *spectraFileName = (char*)"pbpb_spectra_akPu3PF.root",double recoJetPtCut = 60,double trackMaxPtCut = 0, int nBayesianIter = 4, int doBjets=0) // algo 2 =akpu2 ; 3 =akpu3 ; 4 =akpu4 ;1 = icpu5
{
  
  gStyle->SetErrorX(0.5);
  gStyle->SetPaintTextFormat("3.2f");
  gStyle->SetOptLogz(1);
  gStyle->SetPadRightMargin(0.13);	
  gStyle->SetOptTitle(0);

	const float pplumi=5.3e9;
        const bool SavePlot=kTRUE;

  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  // input files
  char *fileNamePP_data = (char*)"/net/hidsk0001/d00/scratch/maoyx/pPb/Btag/CodeMatt/NewFormatV4_bFractionMCTemplate_pppp1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  char *fileNamePbPb_data = (char*)"/net/hidsk0001/d00/scratch/maoyx/pPb/Btag/CodeMatt/AltBinningV6_bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  char *fileNamePP_mc = NULL;
  if(doBjets) fileNamePP_mc = (char*)"/net/hidsk0001/d00/scratch/kjung/histos/ppMC_ppReco_ak3PF_BjetTrig_noIPupperCut.root";
  else fileNamePP_mc = (char*)"/net/hidsk0001/d00/scratch/kjung/histos//ppMC_ppReco_ak3PF_QCDjetTrig_noIPupperCut.root";
  char *fileNamePbPb_mc = NULL;
  if(doBjets)fileNamePbPb_mc = (char*) "/net/hisrv0001/home/mnguyen/scratch/bTaggingOutput/ntuples/PbPbBMC_pt30by3_ipHICalibCentWeight_noTrig.root";
  else fileNamePbPb_mc = (char*) "/net/hisrv0001/home/mnguyen/scratch/bTaggingOutput/ntuples/PbPbQCDMC_pt30by3_ipHICalibCentWeight_noTrig.root";

  // grab ntuples
  TFile *infPbPb_mc = new TFile(fileNamePbPb_mc);
  TFile *infPP_mc = new TFile(fileNamePP_mc);


  // Output file
  TFile *pbpb_Unfo;
  if (isMC) pbpb_Unfo = new TFile(Form("pbpb_Unfo_%s_MC.root",algoName[algo]),"RECREATE");
  else pbpb_Unfo  = new TFile(Form("pbpb_Unfo_%s_jtpt%.0f_trk%.0f.root",algoName[algo],recoJetPtCut,trackMaxPtCut),"RECREATE");
  // Histograms used by RooUnfold
  UnfoldingHistos *uhist[nbins_cent+1];
		
  // Initialize Histograms   
	
  for (int i=0;i<=nbins_cent;i++) uhist[i] = new UnfoldingHistos(i);
	
  // Initialize reweighting functions
  
  TCut dataSelection;
  TCut dataSelectionPP;
  TCut TriggerSelectionPP;
  TCut TriggerSelectionPbPb80;

  if(doBjets)dataSelection = "weight*(abs(refparton_flavorForB)==5&&abs(jteta)<2)";
  else dataSelection = "weight*(abs(jteta)<2)";
  

  if (isMC) cout<<"This is a MC closure test"<<endl;
  else cout<< "This is a data analysis"<<endl;    		     
	     	
  // Setup jet data branches, basically the jet tree branches are assigned to this object when we loop over the events
	
  JetDataPbPb *dataPbPb   = new JetDataPbPb(fileNamePbPb_mc,(char*)"nt"); // PbPb data	
  JetDataPP *dataPP = new JetDataPP(fileNamePP_mc,(char*)"nt");	// pp data
	
  TFile *fSpectra(0);		
  if (useSpectraFromFile||useMatrixFromFile){
    fSpectra = new TFile(spectraFileName,"read");
  }
  
  // Come back to the output file dir
  pbpb_Unfo->cd();

  // Get Jet spectra from data file
  cout <<"Reading data..."<<endl;

  // This doesn't seem to be relevant for the moment -Matt
  /*	

  TTree *tPbPbJet = (TTree*)infPbPb_mc->Get("nt");
  TTree *tPPJet  = (TTree*)infPP_mc->Get("nt");


  TCanvas * cInput = new TCanvas("cInput","Input",800,400);
  cInput->Divide(2,1);
		
  cout <<"Spectra..."<<endl;	
	
  for (int i=0;i<=nbins_cent;i++){
    cout <<nbins_cent<<endl;
    TCut centCut = Form("bin<%.0f&&bin>=%.0f",boundaries_cent[i+1],boundaries_cent[i]);
    if (useSpectraFromFile) {
      uhist[i]->hMeas = (TH1F*)fSpectra->Get(Form("hMeas_cent%d",i));
    } else {
      if (!isMC) {
	tPbPbJet->Project(Form("hMeas_cent%d",i),"jtptB", dataSelection&&centCut&&TriggerSelectionPbPb80);
      }   
    }
		
    if (useMatrixFromFile) {
      cout <<"Matrix"<<endl;
      uhist[i]->hMatrixFit = (TH2F*) fSpectra->Get(Form("hMatrixFit_cent%d",i));
      uhist[i]->hMeasMatch = (TH1F*)((TH2F*) fSpectra->Get(Form("hMatrixFit_cent%d",i)))->ProjectionY();
      uhist[i]->hMeasMatch->Divide(uhist[i]->hMeas);
    } else {
      uhist[i]->hMeasMatch = 0;
    }
    uhist[i]->hMeas->Draw();
  }

  if (!isMC) tPPJet->Project(Form("hMeas_cent%d",nbins_cent),"jtpt",dataSelectionPP&&TriggerSelectionPP);
  */
  cout <<"MC..."<<endl;	
  
  TH1F *hCent = new TH1F("hCent","",nbins_cent,boundaries_cent);
 
		
  // Fill PbPb MC   
  if (!useMatrixFromFile) {
    for (Long64_t jentry2=0; jentry2<dataPbPb->tJet->GetEntries();jentry2++) {
      dataPbPb->tJet->GetEntry(jentry2);
      
      // change when we switch to centrality binning
      int cBin = 0;
      
      //int cBin = hCent->FindBin(dataPbPb->bin)-1;
      /*
	if (cBin>=nbins_cent) continue;
	if (cBin==-1) continue;
      */
      
      if ( dataPbPb->refpt  < 0. ) continue;
      if ( dataPbPb->jteta  > 2. || dataPbPb->jteta < -2. ) continue;
      if ( dataPbPb->refpt<0) dataPbPb->refpt=0;
      if (doBjets && fabs(dataPbPb->refparton_flavorForB)!=5) continue;
      if (doBjets&& dataPbPb->discr_ssvHighEff<2) continue;
      if (doBjets && dataPbPb->jtptB < recoJetPtCut) continue;
      if (!doBjets && dataPbPb->jtptA < recoJetPtCut) continue;
      //if ( dataPbPb->isTrig <1) continue;
      
      if(!doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptA>120) continue;
      if(doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptB>120) continue;

      if (!isMC||jentry2 % 2 == 1) {
	if(doBjets)uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptB,dataPbPb->weight);
	else uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptA,dataPbPb->weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[cBin]-> hGen->Fill(dataPbPb->refpt,dataPbPb->weight);   
	if(doBjets)uhist[cBin]-> hMeas->Fill(dataPbPb->jtptB,dataPbPb->weight);  	 
	else uhist[cBin]-> hMeas->Fill(dataPbPb->jtptA,dataPbPb->weight);  	 
	//uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtpt*(1.+0.02/nbins_cent*(nbins_cent-i)),dataPbPb->weight); 
	// FIXME!!!!!!  i is supposed to be a loop over centrality !!!!
	if(doBjets)uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptB*(1.+0.02/nbins_cent*(nbins_cent-0)),dataPbPb->weight); 
	else uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptA*(1.+0.02/nbins_cent*(nbins_cent-0)),dataPbPb->weight); 
      }
    }

    //pp will just fill the last index of the centrality array

    // fill pp MC
    for (Long64_t jentry2=0; jentry2<dataPP->tJet->GetEntries();jentry2++) {
      dataPP->tJet->GetEntry(jentry2);
      
      if ( dataPP->refpt<0) continue;
      if ( dataPP->jteta  > 2. || dataPP->jteta < -2. ) continue;
      if ( dataPP->refpt<0) dataPP->refpt=0;
      if ( doBjets && fabs(dataPP->refparton_flavorForB)!=5) continue;
      if ( doBjets && dataPP->discr_ssvHighEff<2) continue;
      if ( dataPP->jtpt < recoJetPtCut) continue;
      
      if (!isMC||jentry2 % 2 == 1) {
	uhist[nbins_cent]-> hMatrix->Fill(dataPP->refpt,dataPP->jtpt,dataPP->weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[nbins_cent]-> hGen->Fill(dataPP->refpt,dataPP->weight);   
	uhist[nbins_cent]-> hMeas->Fill(dataPP->jtpt,dataPP->weight); 
      }           
    }
  }

	

  cout <<"Response Matrix..."<<endl;
	
  TCanvas * cMatrix = new TCanvas("cMatrix","Matrix",800,400);
  cMatrix->Divide(2,1);

  for (int i=0;i<=nbins_cent;i++){
    cMatrix->cd(i+1);
    if (!useMatrixFromFile) {
      TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
      f->SetParameters(1e10,-8.8,40);
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	double sum=0;
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	  if (uhist[i]->hMatrix->GetBinContent(x,y)<=1*uhist[i]->hMatrix->GetBinError(x,y)) {
	    uhist[i]->hMatrix->SetBinContent(x,y,0);
	    uhist[i]->hMatrix->SetBinError(x,y,0);
	  }
	  sum+=uhist[i]->hMatrix->GetBinContent(x,y);
	}
				
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {	   
	  double ratio = 1;
	  uhist[i]->hMatrix->SetBinContent(x,y,uhist[i]->hMatrix->GetBinContent(x,y)*ratio);
	  uhist[i]->hMatrix->SetBinError(x,y,uhist[i]->hMatrix->GetBinError(x,y)*ratio);
	}
      }
    }
    uhist[i]->hResponse = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponse_cent%d",i));
    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {
	if (uhist[i]->hResponse->GetBinContent(x,y)<=0*uhist[i]->hResponse->GetBinError(x,y)) {
	  uhist[i]->hResponse->SetBinContent(x,y,0);
	  uhist[i]->hResponse->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponse->GetBinContent(x,y);
      }
			
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
      }
    }
		
    uhist[i]->hResponseNorm = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponseNorm_cent%d",i));
    for (int x=1;x<=uhist[i]->hResponseNorm->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {
	if (uhist[i]->hResponseNorm->GetBinContent(x,y)<=0*uhist[i]->hResponseNorm->GetBinError(x,y)) {
	  uhist[i]->hResponseNorm->SetBinContent(x,y,0);
	  uhist[i]->hResponseNorm->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponseNorm->GetBinContent(x,y);
      }
			
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	uhist[i]->hResponseNorm->SetBinContent(x,y,uhist[i]->hResponseNorm->GetBinContent(x,y)*ratio);
	uhist[i]->hResponseNorm->SetBinError(x,y,uhist[i]->hResponseNorm->GetBinError(x,y)*ratio);
      }
    }
		
    uhist[i]->hResponse->Draw("col");
		
    if (!useMatrixFromFile) uhist[i]->hMatrixFit = uhist[i]->hMatrix;
    uhist[i]->hMatrixFit->SetName(Form("hMatrixFit_cent%d",i));
  }

   cMatrix->Update();
  if (isMC==0) {
    // Use measured histogram from Matt & Kurt's file
	   
    // PbPb file:

    TFile *infMatt = new TFile(fileNamePbPb_data);
    TH1F *hMattPbPb = NULL;
    if(doBjets) hMattPbPb = (TH1F*) infMatt->Get("hRawBData");
    else hMattPbPb = (TH1F*) infMatt->Get("hIncJetsData");
    divideBinWidth(hMattPbPb);
           
    // Need to match the binning carefully, please double check whenever you change the binning
    for (int i=1;i<=hMattPbPb->GetNbinsX();i++)
      {
	uhist[0]->hMeas->SetBinContent(i+uhist[0]->hMeas->FindBin(61)-1,hMattPbPb->GetBinContent(i));  
	uhist[0]->hMeas->SetBinError(i+uhist[0]->hMeas->FindBin(61)-1,hMattPbPb->GetBinError(i));  
      }

    // pp file:
    // The file name needs to be updated!!!!!
    TFile *infMattPP = new TFile(fileNamePP_data);
    TH1F *hMattPP = NULL;
    if(doBjets)hMattPP = (TH1F*) infMattPP->Get("hRawBData");
    else hMattPP = (TH1F*) infMattPP->Get("hIncJetsData");
    divideBinWidth(hMattPP);
	   
    // Need to match the binning carefully, please double check whenever you change the binning
    for (int i=1;i<=hMattPP->GetNbinsX();i++)
      {
	uhist[nbins_cent]->hMeas->SetBinContent(i+uhist[nbins_cent]->hMeas->FindBin(61)-1,hMattPP->GetBinContent(i));  
	uhist[nbins_cent]->hMeas->SetBinError(i+uhist[nbins_cent]->hMeas->FindBin(61)-1,hMattPP->GetBinError(i));  
      }

  }

 
  pbpb_Unfo->cd();
	
  cout << "==================================== UNFOLD ===================================" << endl;
	
  //char chmet[100]; 
	
  // ======================= Reconstructed pp and PbPb spectra =========================================================
  TCanvas * cPbPb = new TCanvas("cPbPb","Comparison",1200,600);
  cPbPb->Divide(2,1); 
  cPbPb->cd(1);
	
	
  for (int i=0;i<=nbins_cent;i++) {
    cPbPb->cd(i+1)->SetLogy();   
    // Do Bin-by-bin
    TH1F *hBinByBinCorRaw = (TH1F*)uhist[i]->hResponse->ProjectionY(); 
    TH1F *hMCGen           = (TH1F*)uhist[i]->hResponse->ProjectionX(); // gen
    hBinByBinCorRaw->Divide(hMCGen);
    TF1 *f = new TF1("f","[0]+[1]*x");
    hBinByBinCorRaw->Fit("f","LL ","",90,300);
    TH1F* hBinByBinCor = (TH1F*)hBinByBinCorRaw->Clone();//functionHist(f,hBinByBinCorRaw,Form("hBinByBinCor_cent%d",i));
    delete hBinByBinCorRaw;
    delete hMCGen;
    uhist[i]->hRecoBinByBin = (TH1F*) uhist[i]->hMeas->Clone(Form("hRecoBinByBin_cent%d",i));
    uhist[i]->hRecoBinByBin->Divide(hBinByBinCor);
		
    // Do unfolding
    //if (isMC) uhist[i]->hMeas = (TH1F*)uhist[i]->hMatrix->ProjectionY()->Clone(Form("hMeas_cent%d",i));
    prior myPrior(uhist[i]->hMatrixFit,uhist[i]->hMeas,0);
  //  myPrior.unfold(uhist[i]->hMeas,1);
    myPrior.unfold(uhist[i]->hMeas,nBayesianIter);
    TH1F *hPrior;//=(TH1F*) functionHist(fPow,uhist[i]->hMeas,Form("hPrior_cent%d",i));
    hPrior = (TH1F*)uhist[i]->hGen->Clone("hPrior");//(TH1F*)uhist[i]->hMeas->Clone(Form("hPrior_cent%d",i));
    removeZero(hPrior);
		
    bayesianUnfold myUnfoldingJECSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingJECSys.unfold(uhist[i]->hMeasJECSys,nBayesianIter);
    bayesianUnfold myUnfoldingSmearSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingSmearSys.unfold(uhist[i]->hMeasSmearSys,nBayesianIter);
    bayesianUnfold myUnfolding(uhist[i]->hMatrixFit,myPrior.hPrior,0);
    myUnfolding.unfold(uhist[i]->hMeas,nBayesianIter);
    cout <<"Unfolding bin "<<i<<endl;

    // Iteration Systematics
    for (int j=2;j<=40;j++)
      {
	bayesianUnfold myUnfoldingSys(uhist[i]->hMatrixFit,hPrior,0);
	myUnfoldingSys.unfold(uhist[i]->hMeas,j);
	uhist[i]->hRecoIterSys[j]  = (TH1F*) myUnfoldingSys.hPrior->Clone(Form("hRecoRAA_IterSys%d_cent%d",j,i));
      }
		
		
    uhist[i]->hReco         = (TH1F*) uhist[i]->hRecoIterSys[nBayesianIter]->Clone(Form("Unfolded_cent%i",i));
    uhist[i]->hRecoJECSys   = (TH1F*) myUnfoldingJECSys.hPrior->Clone(Form("UnfoldedJeCSys_cent%i",i));
    uhist[i]->hRecoSmearSys   = (TH1F*) myUnfoldingSmearSys.hPrior->Clone(Form("UnfoldedSmearSys_cent%i",i));
    uhist[i]->hRecoBinByBin->SetName(Form("UnfoldedBinByBin_cent%i",i));
		
    if (doToy) {
      TCanvas *cToy = new TCanvas("cToy","toy",600,600);
      cToy->cd();
      int nExp=1000;
      TH1F *hTmp[nbins_truth+1];
      TH1F *hTmp2[nbins_truth+1];
      for (int j=1;j<=nbins_truth;j++) {
	hTmp[j] = new TH1F(Form("hTmp%d",j),"",200,0,10.+uhist[i]->hReco->GetBinContent(j)*2);
	hTmp2[j] = new TH1F(Form("hTmp2%d",j),"",200,0,10.+uhist[i]->hRecoBinByBin->GetBinContent(j)*2);
      }
      for (int exp =0; exp<nExp; exp++) {
	TH1F *hToy = (TH1F*)uhist[i]->hMeas->Clone();   
	TH2F *hMatrixToy = (TH2F*)uhist[i]->hMatrixFit->Clone();
	hToy->SetName("hToy");
	if (exp%100==0) cout <<"Pseudo-experiment "<<exp<<endl;
	for (int j=1;j<=hToy->GetNbinsX();j++) {
	  double value = gRandom->Poisson(uhist[i]->hMeas->GetBinContent(j));
	  hToy->SetBinContent(j,value);
	}
				
	for (int j=1;j<=hMatrixToy->GetNbinsX();j++) {
	  for (int k=1;k<=hMatrixToy->GetNbinsY();k++) {
	    double value = gRandom->Gaus(uhist[i]->hMatrixFit->GetBinContent(j,k),uhist[i]->hMatrixFit->GetBinError(j,k));
	    hMatrixToy->SetBinContent(j,k,value);
	  }
	}

	prior myPriorToy(hMatrixToy,hToy,0.0);
	myPriorToy.unfold(hToy,1);
	bayesianUnfold myUnfoldingToy(hMatrixToy,myPriorToy.hPrior,0.0);
	myUnfoldingToy.unfold(hToy,nBayesianIter);
	TH1F *hRecoTmp = (TH1F*) myUnfoldingToy.hPrior->Clone();
				
	for (int j=1;j<=hRecoTmp->GetNbinsX();j++) {
	  hTmp[j]->Fill(hRecoTmp->GetBinContent(j));
	}
	delete hToy;
	delete hRecoTmp;
	delete hMatrixToy;
      }
      TF1 *fGaus = new TF1("fGaus","[0]*TMath::Gaus(x,[1],[2])");
      for (int j=1;j<=nbins_truth;j++)
	{
	  f->SetParameters(hTmp[j]->GetMaximum(),hTmp[j]->GetMean(),hTmp[j]->GetRMS());
				
	  if (hTmp[j]->GetMean()>0) {
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hReco->SetBinError(j,f->GetParameter(2));
	  }	       
	  f->SetParameters(hTmp2[j]->GetMaximum(),hTmp2[j]->GetMean(),hTmp2[j]->GetRMS());
	  if (hTmp2[j]->GetMean()>0) {
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hRecoBinByBin->SetBinError(j,f->GetParameter(2));
	  }	       
	  delete hTmp[j];
	  delete hTmp2[j];
	}
      cPbPb->cd(i+1);
    }

    uhist[i]->hMeas->SetMarkerStyle(20);
    uhist[i]->hMeas->SetMarkerColor(1);
    uhist[i]->hReco->SetMarkerStyle(24);
    uhist[i]->hReco->SetMarkerColor(2);
    uhist[i]->hReco->SetLineColor(2);
    uhist[i]->hReco->SetName(Form("hReco_cent%d",i));
    uhist[i]->hReco->Draw("");    
    makeHistTitle(uhist[i]->hReco,"","Jet p_{T} (GeV/c)","dN_{jets} / dp_{T}");
    uhist[i]->hReco->GetYaxis()->SetTitleOffset(1.3);
    uhist[i]->hReco->GetXaxis()->SetTitleOffset(1.2);
    uhist[i]->hGen->SetLineWidth(1);
    uhist[i]->hGen->SetLineColor(1);
    if(isMC)uhist[i]->hGen->Draw("hist same");
    uhist[i]->hReco->Draw("same");    
    uhist[i]->hRecoBinByBin->SetMarkerStyle(28);
    uhist[i]->hRecoBinByBin->SetMarkerColor(4);
    uhist[i]->hRecoBinByBin->SetLineColor(4);
    uhist[i]->hRecoBinByBin->Draw("same");    
    uhist[i]->hReco->SetAxisRange(60,300);
    TH1F *hReproduced = (TH1F*)myUnfolding.hReproduced->Clone(Form("hReproduced_cent%d",i));
    hReproduced->SetMarkerColor(4);
    hReproduced->SetMarkerStyle(24);
    uhist[i]->hMeas->Draw("same");    
		
    TLegend *leg = new TLegend(0.5,0.5,0.9,0.9);
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg->AddEntry(uhist[i]->hReco,"Bayesian unfolded","pl");
    leg->AddEntry(uhist[i]->hRecoBinByBin,"Bin-by-bin unfolded","pl");
    if(isMC)leg->AddEntry(uhist[i]->hGen,"Generator level truth","l");
    leg->Draw();
  }	     
  
  cPbPb->Update();

 // ======================= Unfolding closure in MC =========================================================
  TCanvas * cRatio = new TCanvas("cRatio","Ratio",1200,600);
    TH1F * hReco[nbins_cent+1];
    TH1F * hRecoBinByBin[nbins_cent+1];
    TH1F * hMeas[nbins_cent+1];
    TH1F * hGen[nbins_cent+1];
    TLegend *leg[nbins_cent+1];
  TLine *line = new TLine(60,1,250,1);
	line->SetLineStyle(2);
	line->SetLineWidth(2);
 
    for (int i=0;i<=nbins_cent;i++) {
        hReco[i]          = (TH1F*)uhist[i]->hReco->Clone(Form("hReco_Cen%d", i));
        hRecoBinByBin[i]          = (TH1F*)uhist[i]->hRecoBinByBin->Clone(Form("hRecoBinByBin_Cen%d", i));
        hMeas[i]          = (TH1F*)uhist[i]->hMeas->Clone(Form("hMeas_Cen%d", i));
        if(isMC) hGen[i]          = (TH1F*)uhist[i]->hGen->Clone(Form("hGen_Cen%d", i));
    }
    
  if(isMC){
    cRatio->Divide(2,1);
      for (int i=0;i<=nbins_cent;i++) {
          
          hMeas[i]->Divide(hGen[i]);
          hRecoBinByBin[i]->Divide(hGen[i]);
          hReco[i]->Divide(hGen[i]);
          cRatio->cd(i+1);

		//hRecoPP->SetAxisRange(90,300,"X");
		hReco[i]->SetAxisRange(0,2,"Y");
		hReco[i]->SetMarkerStyle(24);
		hReco[i] ->SetLineColor(2);
		hReco[i] ->SetMarkerColor(2);
		hMeas[i]->SetMarkerStyle(20);
		hMeas[i]->SetLineColor(1);
		hMeas[i]->SetMarkerColor(1);
		hRecoBinByBin[i]->SetMarkerStyle(28);
		hRecoBinByBin[i]->SetLineColor(4);
		hRecoBinByBin[i]->SetMarkerColor(4);
		
		makeHistTitle(hReco[i],"","Jet p_{T} (GeV/c)","Reco / Truth");
		hReco[i]->GetYaxis()->SetTitleOffset(1.4);
		hReco[i]->GetXaxis()->SetTitleOffset(1.2);
		hReco[i]->Draw("");
		hRecoBinByBin[i]->Draw("same");
		hMeas[i]->Draw("same");
		line->Draw();
		
		leg[i] = myLegend(0.52,0.65,0.85,0.9);
		leg[i]->AddEntry(hReco[i],"Bayesian","pl");
		leg[i]->AddEntry(hRecoBinByBin[i],"Bin-by-bin","pl");
		leg[i]->AddEntry(hMeas[i],"no unfolding","pl");
		leg[i]->Draw();
		putCMSPrel(0.2,0.83,0.06);
		drawText("Anti-k_{T} Particle Flow Jets   R = 0.3",0.2,0.23,20);
		drawText("CMS Simulation",0.6,0.4,22);
		drawText("| #eta | <2 ",0.6,0.31,22);
      }
  }
  else {
      hMeas[nbins_cent]->Scale(1./CorFac[6]/5.3e9);
      hRecoBinByBin[nbins_cent]->Scale(1./CorFac[6]/5.3e9);
      hReco[nbins_cent]->Scale(1./CorFac[6]/5.3e9);
      cRatio->cd(1);
      
      for (int i=0;i<nbins_cent;i++) {
          hMeas[i]            ->Scale(1./CorFac[i]/1.0908e9/TAA[i]);
          hRecoBinByBin[i]            ->Scale(1./CorFac[i]/1.0908e9/TAA[i]);
          hReco[i]            ->Scale(1./CorFac[i]/1.0908e9/TAA[i]);
          
          hMeas[i]->Divide(hMeas[nbins_cent]);
          hRecoBinByBin[i]->Divide(hRecoBinByBin[nbins_cent]);
          hReco[i]->Divide(hReco[nbins_cent]);
          
          hReco[i]->SetAxisRange(0,2,"Y");
          hReco[i]->SetMarkerStyle(24);
          hReco[i] ->SetLineColor(2);
          hReco[i] ->SetMarkerColor(2);
          hMeas[i]->SetMarkerStyle(20);
          hMeas[i]->SetLineColor(1);
          hMeas[i]->SetMarkerColor(1);
          hRecoBinByBin[i]->SetMarkerStyle(28);
          hRecoBinByBin[i]->SetLineColor(4);
          hRecoBinByBin[i]->SetMarkerColor(4);
         // if(i==0){
          makeHistTitle(hReco[i],"","Jet p_{T} (GeV/c)","Spectra Ratio");
          hReco[i]->GetYaxis()->SetTitleOffset(1.4);
          hReco[i]->GetXaxis()->SetTitleOffset(1.2);
          hReco[i]->Draw("");
              leg[i] = myLegend(0.52,0.65,0.85,0.9);
              leg[i]->AddEntry(hReco[i],"Bayesian","pl");
              leg[i]->AddEntry(hRecoBinByBin[i],"Bin-by-bin","pl");
              leg[i]->AddEntry(hMeas[i],"no unfolding","pl");
              leg[i]->Draw();

       //   }
       //   else {
          hReco[i]->Draw("same");
          hRecoBinByBin[i]->Draw("same");
          hMeas[i]->Draw("same");
      //    }
       } 
         line->Draw();
          
          putCMSPrel(0.2,0.83,0.06);
          drawText(Form("#intL dt = %.f #mub^{-1}",150.),0.2,0.78,22);
          drawText("Anti-k_{T} Particle Flow Jets   R = 0.3",0.2,0.73,20);
          drawText("| #eta | <2 ",0.6,0.69,22);
  
  }
    cRatio->Update();

  pbpb_Unfo->Write();

  SysData systematics;

  // Iteration systematics
  TCanvas *cIterSys = new TCanvas("cIterSys","IterSys",1200,600);
  cIterSys->Divide(2,1);
  cIterSys->cd(2);
  TH1F *hRecoIterSysPP[100];
  TH1F *hRebinPP_tmp         = rebin(uhist[nbins_cent]->hReco, (char*)"hRebinPP_tmp");
  TLegend *legBayesianIterPP = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPP->AddEntry("","PP","");
         
  for (int j=2;j<7;j++) {
    hRecoIterSysPP[j] = rebin(uhist[nbins_cent]->hRecoIterSys[j],Form("hRecoIterSysPP_IterSys%d",j));
    hRecoIterSysPP[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPP[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPP[j]->Divide(hRebinPP_tmp);
    if (j==2){
    //  makeHistTitle(hRecoIterSysPP[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      makeHistTitle(hRecoIterSysPP[j],"","Jet p_{T} (GeV/c)","Ratio (Unfolded / Nominal)");
      hRecoIterSysPP[j]->SetTitleOffset(1.3,"Y");
      hRecoIterSysPP[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPP[j]->SetAxisRange(0,2,"Y");
      hRecoIterSysPP[j]->Draw(); 
    } else {
      hRecoIterSysPP[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[nbins_cent],hRecoIterSysPP[j],0,1.1);
    legBayesianIterPP->AddEntry(hRecoIterSysPP[j],Form("Iteration %d",j),"pl");     
  }
      
  legBayesianIterPP->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[nbins_cent],(char*)"hist same");


  cIterSys->cd(1);
  TH1F *hRecoIterSysPbPb[100];
  TH1F *hRebinPbPb_tmp         = rebin(uhist[0]->hReco, (char*)"hRebinPbPb_tmp");
  TLegend *legBayesianIterPbPb = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPbPb->AddEntry("","PbPb","");
  for (int j=2;j<7;j++) {
    hRecoIterSysPbPb[j] = rebin(uhist[0]->hRecoIterSys[j],Form("hRecoIterSysPbPb_IterSys%d",j));
    hRecoIterSysPbPb[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->Divide(hRebinPbPb_tmp);
    if (j==2){
    //  makeHistTitle(hRecoIterSysPbPb[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      makeHistTitle(hRecoIterSysPbPb[j],"","Jet p_{T} (GeV/c)","Ratio (Unfolded / Nominal)");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.3,"Y");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPbPb[j]->SetAxisRange(0,2,"Y");
      hRecoIterSysPbPb[j]->Draw(); 
    } else {
      hRecoIterSysPbPb[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[0],hRecoIterSysPbPb[j],0,1.1);
    legBayesianIterPbPb->AddEntry(hRecoIterSysPbPb[j],Form("Iteration %d",j),"pl");     
  }
  legBayesianIterPbPb->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[0],(char*)"hist same");
  
  cIterSys->Update();
  
  TString data ;
  if(isMC) data="MC";
  else data="Data";
 TString anaType ;
  if(doBjets) anaType="Bjet";
  else anaType="Inclusive";
  
  if(SavePlot){
    cMatrix->SaveAs(Form("plots/%s%s%sResponseMatrix.gif", data.Data(), anaType.Data(), algoName[algo]));
    cPbPb->SaveAs(Form("plots/%s%s%sJetSpectra.gif",  data.Data(), anaType.Data(), algoName[algo]));
    cRatio->SaveAs(Form("plots/%s%s%sJetRatio.gif",  data.Data(), anaType.Data(), algoName[algo]));
    cIterSys->SaveAs(Form("plots/%s%s%sIterationSys.gif",  data.Data(), anaType.Data(), algoName[algo]));
}
}
Example #28
0
void fit_h_Xm_extended() {
    TCanvas* c1;
	c1 = new TCanvas("c1","",1440,900);
	
    
	
    TFile *f;
	int mass[13]={600,800,1000,1200,1400,1600,1800,2000,2500,3000,3500,4000,4500};
	float width [4]={0.05,0.1,0.2,0.3};
	string widthdata[4]={"0.05","0.1","0.2","0.3"};
	
	//for(int i=0 ;i<4;i++){
		//for(int j=0)
	//}
for(int i=0;i<4;i++){
	for(int j=0;j<13;j++){

    


    f = TFile::Open(Form("offshell_root_files/Zprime_Zh_Zlephbb_w%s_M%d.root",widthdata[i].data(),mass[j]));
    TH1F* h =(TH1F*) f->FindObjectAny("h_Xm_extended");
	

    
    
	
	int bmin=0,bmax=0;

    for (int k=1;k<25001;k++){
		bmin=k;
		if (h->GetBinContent(k)!=0) break;
	}

	for (int k=25000;k>0;k--){
		bmax=k;
		if (h->GetBinContent(k)!=0) break;
	}
	if((bmin-300)<0)bmin=0;
	else bmin=bmin-300;
	bmax=bmax+bmax/10;
	
	
	cout <<bmin<<","<<bmax<<endl;
    //gStyle->SetOptFit(111111);
	//gStyle->SetStatW       (0.1);
    //gStyle->SetStatH       (0.1);
    //gStyle->SetStatX          (0.941349);
    //gStyle->SetStatY          (0.912491);
	
	fiveWidthLow= mass[j] -5* (width [i])*mass[j];
	fiveWidthUp= mass[j] +5* (width [i])*mass[j];
	
	float inte=h->Integral(fiveWidthLow,fiveWidthUp);
	inte=inte*100/(bmax-bmin);

	//h->Rebin((bmax-bmin)/100);
	int massfix=200;
	if(i>1&&j>8)massfix=400;
	if(i>2&&j>9)massfix=500;
	float widthfix=0;
	if(i>2&&j>9)widthfix=0.1;
	
	
	
	TF1* f1 = new TF1("f1","[2]*TMath::BreitWigner(x,[0],[1])");
	f1->SetNpx(2500);
	f1->SetParameters(mass[j],width [i]*mass[j],h->Integral());  
	//f1->SetLineColor(3);
	
	
	h->GetXaxis()->SetRangeUser(bmin,bmax);
    h->SetTitle(Form("offshell_root_files/Zprime_Zh_Zlephbb_w%s_M%d.root",widthdata[i].data(),mass[j]));
	TH1F*  h2=(TH1F*)  h->Clone("h2");
    //h->Fit(f1,"","",fiveWidthLow,fiveWidthUp);
	//h->Fit(f1,"L");
	TF1* f2 = new TF1("f2",fline,bmin,bmax,3);
	
	if(j>2)inte=h->Integral();
	f2->SetParameters(mass[j],width [i]*mass[j],h->Integral());  
	f2->SetNpx(2500);
	//f2->SetLineColor(3);
    //h2->Fit(f2);
	//TF1* fleft = new TF1("fleft","[2]*TMath::BreitWigner(x,[0],[1])");
    //TF1 *fleft = new TF1("fleft","[2]*TMath::BreitWigner(x,[0],[1])",bmin,bmax,3);
    //fleft->SetParameters(f2->GetParameters());
    //fleft->SetLineColor(3);
    h->SetMinimum(0);
    h->Draw();
	//fleft->Draw();
	//h2->Draw("same");
    //f1->Draw();
	if (i==0 && j==0)c1->Print("fit_h_Xm_extended.pdf(");
	else if (i==3 && j==12)c1->Print("fit_h_Xm_extended.pdf)");
    else c1->Print("fit_h_Xm_extended.pdf");
   
    
    c1->SaveAs(Form("png/Zprime_Zh_Zlephbb_w%s_M%d.png",widthdata[i].data(),mass[j]));
  

    //c1->Print("fit_h_Xm_extended.pdf)");
	
}
}

}
Example #29
0
//------------------------------------------------------------------------------
// DrawHistogram
//------------------------------------------------------------------------------
void DrawHistogram(TString  hname,
		   TString  xtitle,
		   Int_t    ngroup       = -1,
		   Int_t    precision    = 1,
		   TString  units        = "NULL",
		   Double_t xmin         = -999,
		   Double_t xmax         =  999,
		   Bool_t   moveOverflow = true)
{
  //TCanvas* canvas = new TCanvas(hname, hname, 550, 720);
  TCanvas* canvas = new TCanvas(hname, hname, 800, 800);

  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
  TPad* pad2 = new TPad("pad2", "pad2", 0, 0.0, 1, 0.3); 

  pad1->SetTopMargin   (0.08);
  pad1->SetBottomMargin(0.02);
  pad1->Draw();
      
  pad2->SetTopMargin   (0.08);
  pad2->SetBottomMargin(0.35);
  pad2->Draw();


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

  pad1->SetLogy(_setLogy);

  THStack* hstack = new THStack(hname, hname);

  TH1F* hist[nProcesses];

  //Save histograms to root file
  TFile* outfile;
  //TString fname = Form("files/%s_%djet.root", hname.Data(),_njet);
  TString fname = "files/0jet_"+hname+".root";
  if(_njet==1) fname = "files/1jet_"+hname+".root";
  outfile = new TFile(fname, "create");
  
  TH1F* data;
  TH1F* top;
  TH1F* tW;
  TH1F* WW;
  TH1F* WZ;
  TH1F* ZZ;
  TH1F* Wg;
  TH1F* WgSMu;
  TH1F* WgSEl;
  TH1F* Wjets;
  TH1F* Zjets;
  TH1F* DYtau;
  TH1F* Zgamma;
  TH1F* ggH;



  
  for (UInt_t ip=0; ip<nProcesses; ip++) {

    hist[ip] = (TH1F*)input[ip]->Get(hname);
    hist[ip]->SetName(hname + process[ip]);
    hist[ip]->SetTitle("");

    if(ip == iData)   data   = (TH1F*)hist[iData]->Clone("Data");     //data   -> Sumw2();
    if(ip == itt)     top    = (TH1F*)hist[itt]->Clone("top");        //top    -> Sumw2();
    if(ip == itW)     tW     = (TH1F*)hist[itW]->Clone("tW");         //tW     -> Sumw2();
    if(ip == iWW)     WW     = (TH1F*)hist[iWW]->Clone("WW");         //WW     -> Sumw2();
    if(ip == iWZ)     WZ     = (TH1F*)hist[iWZ]->Clone("WZ");   //VV     -> Sumw2();
    if(ip == iZZ)     ZZ     = (TH1F*)hist[iZZ]->Clone("ZZ");         //ZZ     -> Sumw2();
    if(ip == iWg)     Wg     = (TH1F*)hist[iWg]->Clone("Wg");         //Wg     -> Sumw2();
    if(ip == iWgSMu){
      WgSMu  = (TH1F*)hist[iWgSMu]->Clone("WgSMu");         //WgSMu     -> Sumw2();
      hist[iWgSMu]->Scale(1.5);
    }
    if(ip == iWgSEl){
      WgSEl  = (TH1F*)hist[iWgSEl]->Clone("WgSEl");         //WgSel     -> Sumw2();
      hist[iWgSEl]->Scale(1.5);         //WgSel     -> Sumw2();
    }
    if(ip == iWj)     Wjets  = (TH1F*)hist[iWj]->Clone("W+jets");     //Wjets  -> Sumw2();
    if(ip == iDY)     Zjets  = (TH1F*)hist[iDY]->Clone("Z+jets");     //Zjets  -> Sumw2();
    if(ip == iDYtau)  DYtau  = (TH1F*)hist[iDYtau]->Clone("DYtau");   //DYtau  -> Sumw2();
    if(ip == iZgamma) Zgamma = (TH1F*)hist[iZgamma]->Clone("Zgamma"); //Zgamma -> Sumw2();
    if(ip == iH125)   ggH    = (TH1F*)hist[iH125]->Clone("ggH");      //ggH    -> Sumw2();
    
    if (moveOverflow) MoveOverflowBins  (hist[ip], xmin, xmax);
    else              ZeroOutOfRangeBins(hist[ip], xmin, xmax);

    if (ngroup > 0) hist[ip]->Rebin(ngroup);

    if (ip == iWg) {
      //hist[ip]->Scale(0.01);
    }
    
    if (ip == iData) {
      hist[ip]->SetMarkerStyle(kFullCircle);
    }
    else {
      hist[ip]->SetFillColor(color[ip]);
      hist[ip]->SetFillStyle(1001);
      hist[ip]->SetLineColor(color[ip]);

      if (_dataDriven && ip == itt)    hist[ip]->Scale(ttScale[_njet]);
      if (_dataDriven && ip == itW)    hist[ip]->Scale(tWScale[_njet]);
      if (_dataDriven && ip == iWW)    hist[ip]->Scale(WWScale[_njet]);
      if (_dataDriven && ip == iDY)    hist[ip]->Scale(ZjScale[_njet]);
      if (_dataDriven && ip == iDYtau) hist[ip]->Scale(ZjScale[_njet]);

      if( ip != iZZ ) hstack->Add(hist[ip]);//TODO something wrong with ZZ
      
    }
  }

  if (_dataDriven)
  {
    top->Scale(ttScale[_njet]);
    tW->Scale(tWScale[_njet]);
    WW->Scale(WWScale[_njet]);
    Zjets->Scale(ZjScale[_njet]);
    DYtau->Scale(ZjScale[_njet]);
  }
  
  top  ->Add(tW);
  //VV   ->Add(ZZ);
  //VV   ->Add(Wg);  
  //Zjets->Add(DYtau);
  //Zjets->Add(Zgamma);

  data  -> Write();
  top   -> Write();
  WW    -> Write();
  //VV    -> Write();
  //Wjets -> Write();
  //Zjets -> Write();
  ggH   -> Write();
  
  outfile->Close();


  // All MC
  //----------------------------------------------------------------------------
  TH1F* allmc = (TH1F*)hist[iData]->Clone("allmc");

  allmc->SetFillColor  (kGray+2);
  allmc->SetFillStyle  (   3345);
  allmc->SetLineColor  (kGray+2);
  allmc->SetMarkerColor(kGray+2);
  allmc->SetMarkerSize (      0);

  for (UInt_t ibin=1; ibin<=allmc->GetNbinsX(); ibin++) {

    Double_t binValue = 0;
    Double_t binError = 0;

    for (UInt_t ip=0; ip<nProcesses; ip++) {

      if (ip == iData) continue;
      if (ip == iZZ) continue;

      Double_t binContent = hist[ip]->GetBinContent(ibin);
      
      binValue += binContent;
      binError += (hist[ip]->GetBinError(ibin) * hist[ip]->GetBinError(ibin));

      //We need to calculate systematic uncertainty for ggH case
//      if (_dataDriven)
//	binError += (systError[ip]*binContent * systError[ip]*binContent);
    }
    
    binError = sqrt(binError);

    allmc->SetBinContent(ibin, binValue);
    allmc->SetBinError  (ibin, binError);
  }


  // Axis labels
  //------------------------------------------------------------------
  TAxis* xaxis = hist[iData]->GetXaxis();
  TAxis* yaxis = hist[iData]->GetYaxis();

  TString ytitle = Form("entries / %s.%df", "%", precision);

  xaxis->SetTitle(xtitle);
  yaxis->SetTitle(Form(ytitle.Data(), hist[iData]->GetBinWidth(0)));
  yaxis->SetTitleOffset(1.6);

  if (!units.Contains("NULL")) {
    
    xaxis->SetTitle(Form("%s [%s]", xaxis->GetTitle(), units.Data()));
    yaxis->SetTitle(Form("%s %s",   yaxis->GetTitle(), units.Data()));
  }


  // Draw
  //--------------------------------------------------------------------
  xaxis->SetRangeUser(xmin, xmax);

  hist[iData]->Draw("ep");
  hstack     ->Draw("hist,same");
  allmc      ->Draw("e2,same");
  hist[iData]->Draw("ep,same");

  // Adjust scale
  //----------------------------------------------------------------------------
  Float_t theMax   = GetMaximumIncludingErrors(hist[iData], xmin, xmax);
  Float_t theMaxMC = GetMaximumIncludingErrors(allmc,       xmin, xmax);

  if (theMaxMC > theMax) theMax = theMaxMC;

  if (pad1->GetLogy()) {

    theMax = TMath::Power(10, TMath::Log10(theMax) + 2.7);

    hist[iData]->SetMinimum(0.05);
  }
  else theMax *= 1.55;

  hist[iData]->SetMaximum(theMax);


  // Legend
  //----------------------------------------------------------------------
  Double_t x0      = 0.720; 
  Double_t y0      = 0.834; 
  Double_t yoffset = 0.048;
  Double_t delta   = yoffset + 0.001;
  Double_t ndelta  = 0;

  Double_t YieldTop   = Yield(hist[itt]) + Yield(hist[itW]);
  Double_t YieldWZ    = Yield(hist[iWZ]);
  Double_t YieldVV    = Yield(hist[iWZ]) + Yield(hist[iZZ]) + Yield(hist[iWg]);
  //Double_t YieldZJets = Yield(hist[iDY]) + Yield(hist[iDYtau]);
  Double_t YieldZJets = Yield(hist[iDY]) + Yield(hist[iDYtau]) + Yield(hist[iZgamma]);

  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iData],  Form(" data (%.0f)", Yield(hist[iData])), "lp", 0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[itt],    Form(" tt (%.0f)",  Yield(hist[itt])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[itW],    Form(" tW (%.0f)",  Yield(hist[itW])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.49, y0 - ndelta, allmc,        Form(" all (%.0f)",  Yield(allmc)),       "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWW],    Form(" WW (%.0f)",   Yield(hist[iWW])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWZ],    Form(" WZ (%.0f)",   Yield(hist[iWZ])),  "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWg],    Form(" Wg (%.0f)",    Yield(hist[iWg])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWgSMu], Form(" Wg*Mu (%.0f)",    Yield(hist[iWgSMu])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWgSEl], Form(" Wg*El (%.0f)",    Yield(hist[iWgSEl])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iWj],    Form(" W+jets (%.0f)",Yield(hist[iWj])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.49, y0 - ndelta, hist[iZZ],    Form(" ZZ (%.0f)",    Yield(hist[iZZ])),   "f",  0.03, 0.2, yoffset); ndelta += delta;


  ndelta = 0;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iDY],    Form(" DY (%.0f)",    Yield(hist[iDY])),   "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iDYtau], Form(" DYtau (%.0f)", Yield(hist[iDYtau])),"f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iZgamma],Form(" Zg (%.0f)",   Yield(hist[iZgamma])),"f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[iDY],   Form(" Z+jets (%.0f)", YieldZJets),         "f",  0.03, 0.2, yoffset); ndelta += delta;
  //DrawLegend(x0 - 0.23, y0 - ndelta, hist[iH125], Form(" Higgs (%.0f)",  Yield(hist[iH125])), "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[iH125],  Form(" ggH (%.0f)",  Yield(hist[iH125])), "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[itt],  Form(" tt (%.0f)",  Yield(hist[itt])), "f",  0.03, 0.2, yoffset); ndelta += delta;
  DrawLegend(x0 - 0.23, y0 - ndelta, hist[itW],  Form(" tW (%.0f)",  Yield(hist[itW])), "f",  0.03, 0.2, yoffset); ndelta += delta;


  // Additional titles
  //----------------------------------------------------------------------------
  //TString channelLabel = "ee/#mu#mu/e#mu/#mue";
  TString channelLabel = "";

  //if (_channel == "EE")   channelLabel = "ee";
  //if (_channel == "MuMu") channelLabel = "#mu#mu";
  //if (_channel == "EMu")  channelLabel = "e#mu";
  //if (_channel == "MuE")  channelLabel = "#mue";
  //if (_channel == "SF")   channelLabel = "ee/#mu#mu";
  //if (_channel == "OF")   channelLabel = "e#mu/#mue";

  channelLabel += Form(" %d", _njet);

  if (_njet == 0) channelLabel += "-jets";
  if (_njet == 1) channelLabel += "-jet";
  if (_njet >= 2) channelLabel += "-jets";

  double nBin;
  double binWidth;
  nBin = allmc->GetSize();
  nBin -=2;
  binWidth = allmc->GetBinWidth(2);

  int Z1bin=70/binWidth;
  int Z2bin=110/binWidth;

  cout<<"number of bin: "<<nBin<<endl;
  cout<<"Z bin1: "<<Z1bin<<" Z bin2: "<<Z2bin<<endl;
  double nMcZ, nDataZ;
  nMcZ   = allmc->Integral(Z1bin,Z2bin);
  nDataZ = hist[iData]->Integral(Z1bin,Z2bin);
  double effiCorr;
  effiCorr=nDataZ/nMcZ;
  cout<<"efficiency correction factor: "<<effiCorr<<endl;
  double nMcGstar, nDataGstar, nMcGamma;
  nMcGstar   = hist[iWgSMu]->Integral(1,2);
  nMcGamma   = hist[iWg]->Integral(1,2);
  //nMcGstar   = allmc->Integral(1,2);
  nMcGstar *= effiCorr;
  nMcGamma *= effiCorr;
  nDataGstar = hist[iData]->Integral(1,2);
  double Kfactor;
  double KfactorErr;
  nDataGstar -= nMcGamma;
  Kfactor = nDataGstar/nMcGstar;
  KfactorErr =Kfactor* TMath::Sqrt(nDataGstar/nDataGstar/nDataGstar + nMcGstar/nMcGstar/nMcGstar);
  KfactorErr += 0.1;
  cout<<"Kfactor: "<<Kfactor<<"+"<<KfactorErr<<endl;

  //DrawTLatex(0.185, 0.975, 0.05, 13, channelLabel.Data(),"");
  DrawTLatex(0.940, 0.983, 0.05, 33, Form("L = %.1f fb^{-1}", _luminosity/1e3),"");
  DrawTLatex(0.45, 0.48, 0.04, 13, Form("K factor (Data/Wg*) = %.2f #pm %.2f", Kfactor, KfactorErr ),"");
  DrawTLatex(0.45, 0.43, 0.04, 13, Form("0< InvM(#mu^{+}#mu^{-}) <4 GeV"),"");

  //----------------------------------------------------------------------------
  // pad2
  //----------------------------------------------------------------------------
  pad2->cd();
    
  TH1F* ratio       = (TH1F*)hist[iData]->Clone("ratio");
  TH1F* uncertainty = (TH1F*)allmc->Clone("uncertainty");
    
  for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {

    Double_t mcValue = allmc->GetBinContent(ibin);
    Double_t mcError = allmc->GetBinError  (ibin);
    
    Double_t dtValue = ratio->GetBinContent(ibin);
    Double_t dtError = ratio->GetBinError  (ibin);

    Double_t ratioValue       = (mcValue > 0) ? dtValue/mcValue : 0.0;
    Double_t ratioError       = (mcValue > 0) ? dtError/mcValue : 0.0;
    Double_t uncertaintyError = (mcValue > 0) ? mcError/mcValue : 0.0;

    ratio->SetBinContent(ibin, ratioValue);
    ratio->SetBinError  (ibin, ratioError);

    uncertainty->SetBinContent(ibin, 1.0);
    uncertainty->SetBinError  (ibin, uncertaintyError);
  }


  TAxis* uaxis = (TAxis*)uncertainty->GetXaxis();
    
  uaxis->SetRangeUser(xmin, xmax);
    
    
  uncertainty->Draw("e2");
  ratio      ->Draw("ep,same");

  uncertainty->GetYaxis()->SetRangeUser(0, 2.5);


  // Save
  //----------------------------------------------------------------------
  pad2->cd(); SetAxis(uncertainty, hist[iData]->GetXaxis()->GetTitle(), "data / prediction", 0.10, 0.8);
  pad1->cd(); SetAxis(hist[iData], "", hist[iData]->GetYaxis()->GetTitle(),                  0.05, 1.6);

  canvas->cd();

  TString suffixLogy = (_setLogy) ? "_Log" : "_Lin";

  canvas->SaveAs(Form("%s/%s%s.%s",
		      _output.Data(),
		      hname.Data(),
		      suffixLogy.Data(),
		      _format.Data()));
}
Example #30
0
int main(int argc, char** argv)
{ 
 //Check if all nedeed arguments to parse are there                                                                                                                               
 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }
 
 // Parse the config file                                                                                                                                                          
 parseConfigFile (argv[1]) ;
 
 std::string treeName  = gConfigParser -> readStringOption("Input::treeName");
 std::string inputFile = gConfigParser -> readStringOption("Input::inputFile");
 double inputXSection  = gConfigParser -> readDoubleOption("Input::inputXSection");
 
 int entryMAX = gConfigParser -> readIntOption("Input::entryMAX");
 int entryMIN = gConfigParser -> readIntOption("Input::entryMIN");
 int entryMOD = gConfigParser -> readIntOption("Input::entryMOD");
 
 
 std::cout << ">>>>> input::entryMIN  " << entryMIN  << std::endl;  
 std::cout << ">>>>> input::entryMAX  " << entryMAX  << std::endl;  
 std::cout << ">>>>> input::entryMOD  " << entryMOD  << std::endl;  
 
 
 int dataFlag = 0;
 if (inputXSection == -1) dataFlag = 1; //==== it's a data sample!!!
 std::cerr << ">>>>> input:: --- dataFlag  " << dataFlag << std::endl;
// define map with events
  std::map<std::pair<int,std::pair<int,int> >,int> eventsMap;  
 
 
 int nStepToDo = 1000;
 try {
  nStepToDo = gConfigParser -> readIntOption("Input::nStepToDo");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
  nStepToDo = 1000;
 }
 std::cout << ">>>>> input::nStepToDo  " << nStepToDo  << std::endl;  
 
 
 // Open ntple
 TChain* chain = new TChain(treeName.c_str());
 chain->Add(inputFile.c_str());
 treeReader reader((TTree*)(chain));
 
 
 bool  debug = false; 
 try {
  debug = gConfigParser -> readBoolOption("Input::debug");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::debug  " << debug  << std::endl;  
 
 
 
 
 
 ///******************
 ///**** Triggers ****
 
 std::vector<std::string> HLTVector;
 try {
  HLTVector = gConfigParser -> readStringListOption("Options::HLTVector");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> Options::HLTVector size = " << HLTVector.size() << std::endl;  
 std::cout << ">>>>> >>>>>  "; 
 for (int iHLT = 0; iHLT < HLTVector.size(); iHLT++){
  std::cout << " " << HLTVector.at(iHLT) << ", ";
 }
 std::cout << std::endl; 
  
 ///****************************
 ///**** DATA JSON file ****
 
  std::string inFileNameJSON;
  try {
  inFileNameJSON = gConfigParser -> readStringOption("Input::inFileNameJSON");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> Input::inFileNameJSON  " << inFileNameJSON  << std::endl;  
 std::map<int, std::vector<std::pair<int, int> > > jsonMap;
 if( dataFlag == 1 ) {
   jsonMap = readJSONFile(inFileNameJSON);
}

 
 ///---- Efficiency preselections ---- 
 
 std::string histoNameEvents      = gConfigParser -> readStringOption("Input::histoNameEvents"); 
 std::cout << ">>>>> Input::inputFile                 " << inputFile  << std::endl;  
 std::cout << ">>>>> Input::inputXSection             " << inputXSection  << std::endl;  
 std::cout << ">>>>> Input::histoNameEvents      " << histoNameEvents  << std::endl;  
 
 // Open ntples
 TFile File(inputFile.c_str()) ; 
 TH1F* histoEvents = (TH1F*) File.Get(TString(histoNameEvents.c_str()));
 
 
 ///----------------------
 ///---- Preselection ----
 
 ///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 ///==== only retrocompatibility ====
 
 ///=================================
 
 double lepton_efficiency = 1;
 double jet_efficiency = 1;
 double eff_Channel_Filter = 1;
 double preselection_efficiency = 1.;

 ///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 ///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 ///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 ///-------------------
 ///---- selection ----
 std::string outFileName    = gConfigParser -> readStringOption("Output::outFileName");
 std::cout << ">>>>> Output::outFileName  " << outFileName  << std::endl;  
 
 int nStep = 10; ///==== number of steps in the analysis
 int numEntriesBefore;
 
 // define variable container
 Variables vars;
 InitializeTree(vars, outFileName);
 InitializeTreeTrigger(vars, HLTVector, reader);
 
 vars.XSection = inputXSection;
 vars.dataFlag = dataFlag;  ///~~~~ 0 = MC       1 = DATA
 
 if (entryMAX == -1) entryMAX = reader.GetEntries();
 else if (reader.GetEntries() < entryMAX) entryMAX = reader.GetEntries();
 numEntriesBefore = entryMAX - entryMIN;
 
 if (histoEvents) preselection_efficiency = numEntriesBefore / (1. * histoEvents->GetBinContent(1));
 else preselection_efficiency = 1;
 
 vars.numEntriesBefore = numEntriesBefore;
 vars.preselection_efficiency = preselection_efficiency;
 
 FillEfficiencyTree(vars);
 
 
 ///*************************************
 ///**** definition of electron ID ****
 ///**** https://twiki.cern.ch/twiki/bin/viewauth/CMS/SimpleCutBasedEleID
 ///**** https://twiki.cern.ch/twiki/bin/viewauth/CMS/SimpleCutBasedEleID2011
 
 
 std::vector<double> BarrelSelections;
 std::vector<double> EndcapSelections;
 
 
 
 double eleCombinedIsoBarrel      = gConfigParser -> readDoubleOption("Selection::eleCombinedIsoBarrel");
 double elesigmaIetaIetaBarrel    = gConfigParser -> readDoubleOption("Selection::elesigmaIetaIetaBarrel");
 double eledPhiBarrel             = gConfigParser -> readDoubleOption("Selection::eledPhiBarrel");
 double eledEtaBarrel             = gConfigParser -> readDoubleOption("Selection::eledEtaBarrel");
 
 double eleCombinedIsoEndcap    = gConfigParser -> readDoubleOption("Selection::eleCombinedIsoEndcap");
 double elesigmaIetaIetaEndcap  = gConfigParser -> readDoubleOption("Selection::elesigmaIetaIetaEndcap");
 double eledPhiEndcap           = gConfigParser -> readDoubleOption("Selection::eledPhiEndcap");
 double eledEtaEndcap           = gConfigParser -> readDoubleOption("Selection::eledEtaEndcap");
 
 double elemishits    = gConfigParser -> readDoubleOption("Selection::elemishits");
 double eledist       = gConfigParser -> readDoubleOption("Selection::eledist");
 double eledcot       = gConfigParser -> readDoubleOption("Selection::eledcot");
 
 double eledzPV     = gConfigParser -> readDoubleOption("Selection::eledzPV");
 double eledxyPV    = gConfigParser -> readDoubleOption("Selection::eledxyPV");
 
 
 BarrelSelections.push_back(eleCombinedIsoBarrel);
 BarrelSelections.push_back(elesigmaIetaIetaBarrel);
 BarrelSelections.push_back(eledPhiBarrel);
 BarrelSelections.push_back(eledEtaBarrel);
 BarrelSelections.push_back(elemishits);
 BarrelSelections.push_back(eledist);
 BarrelSelections.push_back(eledcot);
 BarrelSelections.push_back(eledzPV);
 BarrelSelections.push_back(eledxyPV);
 
 EndcapSelections.push_back(eleCombinedIsoEndcap);
 EndcapSelections.push_back(elesigmaIetaIetaEndcap);
 EndcapSelections.push_back(eledPhiEndcap);
 EndcapSelections.push_back(eledEtaEndcap);
 EndcapSelections.push_back(elemishits);
 EndcapSelections.push_back(eledist);
 EndcapSelections.push_back(eledcot);
 EndcapSelections.push_back(eledzPV);
 EndcapSelections.push_back(eledxyPV);
 
 
 ///**** https://twiki.cern.ch/twiki/bin/viewauth/CMS/SimpleCutBasedEleID   --> 2010 Data
 ///**** 95% ****
 
  /*
   BarrelSelections.push_back(0.15); ///==== iso Tk
   BarrelSelections.push_back(2.00); ///==== iso em
   BarrelSelections.push_back(0.12); ///==== iso had
   BarrelSelections.push_back(0.15); ///==== iso combined
   BarrelSelections.push_back(0.015); ///==== hOe
   BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
   BarrelSelections.push_back(0.8); ///==== dPhi
   BarrelSelections.push_back(0.007); ///==== dEta
   
   EndCapSelections.push_back(0.08); ///==== iso Tk
   EndCapSelections.push_back(0.06); ///==== iso em
   EndCapSelections.push_back(0.05); ///==== iso had
   EndCapSelections.push_back(0.10); ///==== iso combined
   EndCapSelections.push_back(0.07); ///==== hOe
   EndCapSelections.push_back(0.03); ///==== sigmaIetaIeta
   EndCapSelections.push_back(0.7); ///==== dPhi
   EndCapSelections.push_back(0.01); ///==== dEta
   */
  
 
    ///**** 90% ****
   /*
   BarrelSelections.push_back(0.12); ///==== iso Tk
   BarrelSelections.push_back(0.09); ///==== iso em
   BarrelSelections.push_back(0.10); ///==== iso had
   BarrelSelections.push_back(0.10); ///==== iso combined
   BarrelSelections.push_back(0.12); ///==== hOe
   BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
   BarrelSelections.push_back(0.8); ///==== dPhi
   BarrelSelections.push_back(0.007); ///==== dEta
    
   EndCapSelections.push_back(0.05); ///==== iso Tk
   EndCapSelections.push_back(0.06); ///==== iso em
   EndCapSelections.push_back(0.03); ///==== iso had
   EndCapSelections.push_back(0.07); ///==== iso combined
   EndCapSelections.push_back(0.05); ///==== hOe
   EndCapSelections.push_back(0.03); ///==== sigmaIetaIeta
   EndCapSelections.push_back(0.7); ///==== dPhi
   EndCapSelections.push_back(0.007); ///==== dEta
  */
   
    ///**** 80% ****
    /*
   BarrelSelections.push_back(0.09); ///==== iso Tk
   BarrelSelections.push_back(0.07); ///==== iso em
   BarrelSelections.push_back(0.10); ///==== iso had
   BarrelSelections.push_back(0.07); ///==== iso combined
   BarrelSelections.push_back(0.040); ///==== hOe
   BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
   BarrelSelections.push_back(0.06); ///==== dPhi
   BarrelSelections.push_back(0.004); ///==== dEta
    
   EndCapSelections.push_back(0.04); ///==== iso Tk
   EndCapSelections.push_back(0.05); ///==== iso em
   EndCapSelections.push_back(0.025); ///==== iso had
   EndCapSelections.push_back(0.06); ///==== iso combined
   EndCapSelections.push_back(0.025); ///==== hOe
   EndCapSelections.push_back(0.03); ///==== sigmaIetaIeta
   EndCapSelections.push_back(0.03); ///==== dPhi
   EndCapSelections.push_back(0.007); ///==== dEta
 */
  
  
  ///**** 70% ****
  /*
  BarrelSelections.push_back(0.05); ///==== iso Tk
  BarrelSelections.push_back(0.06); ///==== iso em
  BarrelSelections.push_back(0.03); ///==== iso had
  BarrelSelections.push_back(0.04); ///==== iso combined
  BarrelSelections.push_back(0.025); ///==== hOe
  BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
  BarrelSelections.push_back(0.004); ///==== dPhi
  BarrelSelections.push_back(0.004); ///==== dEta
  
  EndCapSelections.push_back(0.025); ///==== iso Tk
  EndCapSelections.push_back(0.025); ///==== iso em
  EndCapSelections.push_back(0.02); ///==== iso had
  EndCapSelections.push_back(0.03); ///==== iso combined
  EndCapSelections.push_back(0.025); ///==== hOe
  EndCapSelections.push_back(0.03); ///==== sigmaIetaIeta
  EndCapSelections.push_back(0.02); ///==== dPhi
  EndCapSelections.push_back(0.005); ///==== dEta
  */
  
  
  
  ///**** https://twiki.cern.ch/twiki/bin/viewauth/CMS/SimpleCutBasedEleID2011   --> 2011 Data
  
  ///**** 95% ****
  /*
  BarrelSelections.push_back(10000.); ///==== iso Tk
  BarrelSelections.push_back(10000.); ///==== iso em
  BarrelSelections.push_back(10000.); ///==== iso had
  BarrelSelections.push_back(0.150); ///==== iso combined
  BarrelSelections.push_back(10000.); ///==== hOe
  BarrelSelections.push_back(0.012); ///==== sigmaIetaIeta
  BarrelSelections.push_back(0.800); ///==== dPhi
  BarrelSelections.push_back(0.007); ///==== dEta
  
  EndCapSelections.push_back(10000.); ///==== iso Tk
  EndCapSelections.push_back(10000.); ///==== iso em
  EndCapSelections.push_back(10000.); ///==== iso had
  EndCapSelections.push_back(0.100); ///==== iso combined
  EndCapSelections.push_back(10000.); ///==== hOe
  EndCapSelections.push_back(0.031); ///==== sigmaIetaIeta
  EndCapSelections.push_back(0.7); ///==== dPhi
  EndCapSelections.push_back(0.011); ///==== dEta
  */
  
  ///**** 90% ****
  /* 
   BarrelSelections.push_back(10000.); ///==== iso Tk
   BarrelSelections.push_back(10000.); ///==== iso em
   BarrelSelections.push_back(10000.); ///==== iso had
   BarrelSelections.push_back(0.085); ///==== iso combined
   BarrelSelections.push_back(10000.); ///==== hOe
   BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
   BarrelSelections.push_back(0.071); ///==== dPhi
   BarrelSelections.push_back(0.007); ///==== dEta
    
   EndCapSelections.push_back(10000.); ///==== iso Tk
   EndCapSelections.push_back(10000.); ///==== iso em
   EndCapSelections.push_back(10000.); ///==== iso had
   EndCapSelections.push_back(0.051); ///==== iso combined
   EndCapSelections.push_back(10000.); ///==== hOe
   EndCapSelections.push_back(0.031); ///==== sigmaIetaIeta
   EndCapSelections.push_back(0.047); ///==== dPhi
   EndCapSelections.push_back(0.011); ///==== dEta
   */

  ///**** 85% ****
   /*
   BarrelSelections.push_back(10000.); ///==== iso Tk
   BarrelSelections.push_back(10000.); ///==== iso em
   BarrelSelections.push_back(10000.); ///==== iso had
   BarrelSelections.push_back(0.053); ///==== iso combined
   BarrelSelections.push_back(10000.); ///==== hOe
   BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
   BarrelSelections.push_back(0.039); ///==== dPhi
   BarrelSelections.push_back(0.005); ///==== dEta
   
   EndCapSelections.push_back(10000.); ///==== iso Tk
   EndCapSelections.push_back(10000.); ///==== iso em
   EndCapSelections.push_back(10000.); ///==== iso had
   EndCapSelections.push_back(0.042); ///==== iso combined
   EndCapSelections.push_back(10000.); ///==== hOe
   EndCapSelections.push_back(0.031); ///==== sigmaIetaIeta
   EndCapSelections.push_back(0.028); ///==== dPhi
   EndCapSelections.push_back(0.007); ///==== dEta
   */


 ///**** 80% ****
   /*
   BarrelSelections.push_back(10000.); ///==== iso Tk
   BarrelSelections.push_back(10000.); ///==== iso em
   BarrelSelections.push_back(10000.); ///==== iso had
   BarrelSelections.push_back(0.040); ///==== iso combined
   BarrelSelections.push_back(10000.); ///==== hOe
   BarrelSelections.push_back(0.01); ///==== sigmaIetaIeta
   BarrelSelections.push_back(0.027); ///==== dPhi
   BarrelSelections.push_back(0.005); ///==== dEta
   
   EndCapSelections.push_back(10000.); ///==== iso Tk
   EndCapSelections.push_back(10000.); ///==== iso em
   EndCapSelections.push_back(10000.); ///==== iso had
   EndCapSelections.push_back(0.033); ///==== iso combined
   EndCapSelections.push_back(10000.); ///==== hOe
   EndCapSelections.push_back(0.031); ///==== sigmaIetaIeta
   EndCapSelections.push_back(0.021); ///==== dPhi
   EndCapSelections.push_back(0.006); ///==== dEta
   */
   
  ///***********************************
  ///**** definition of muon ID ****
  std::vector<double> Selections;
  
  double muCombinedIso   = gConfigParser -> readDoubleOption("Selection::muCombinedIso");
  double muChi2Ndof      = gConfigParser -> readDoubleOption("Selection::muChi2Ndof");
  
  
  double muValidTrackerHits = gConfigParser -> readDoubleOption("Selection::muValidTrackerHits");
  double muValidMuonHits    = gConfigParser -> readDoubleOption("Selection::muValidMuonHits");
  
  double mutracker    = gConfigParser -> readDoubleOption("Selection::mutracker");
  double mustandalone = gConfigParser -> readDoubleOption("Selection::mustandalone");
  double muglobal     = gConfigParser -> readDoubleOption("Selection::muglobal");
  
  double mudzPV     = gConfigParser -> readDoubleOption("Selection::mudzPV");
  double mudxyPV    = gConfigParser -> readDoubleOption("Selection::mudxyPV");
  
  
  Selections.push_back(muCombinedIso);
  Selections.push_back(muChi2Ndof);
  Selections.push_back(muValidTrackerHits);
  Selections.push_back(muValidMuonHits);
  Selections.push_back(mutracker);
  Selections.push_back(mustandalone);
  Selections.push_back(muglobal);
  Selections.push_back(mudzPV);
  Selections.push_back(mudxyPV);
  
    
/*  
  Selections.push_back(0.15); ///==== iso Combined
  Selections.push_back(10); ///==== Chi2/ndof
  Selections.push_back(10); ///==== n ValidTrackerHits
  Selections.push_back(0); ///==== n ValidMuonHits
  Selections.push_back(1); ///==== tracker
  Selections.push_back(1); ///==== standalone
  Selections.push_back(1); ///==== global
  //Selections.push_back(1); ///==== goodMuon
  */
  
  
  double start, end;
  std::cout << ">>>>> analysis::entryMIN " << entryMIN << " ==> entryMAX " << entryMAX << ":" << reader.GetEntries() << std::endl;   
  
  int step = 0;
  start = clock();
  for(int iEvent = entryMIN ; iEvent < entryMAX ; ++iEvent) {
   reader.GetEntry(iEvent);
   if((iEvent%entryMOD) == 0) std::cout << ">>>>> analysis::GetEntry " << iEvent << " : " << entryMAX - entryMIN << std::endl;   
   
  ///==== define variables ==== 
  std::vector<ROOT::Math::XYZTVector>* jets = reader.Get4V("jets");
//   std::vector<ROOT::Math::XYZTVector>* muons = reader.Get4V("muons");
//   std::vector<ROOT::Math::XYZTVector>* electrons = reader.Get4V("electrons");
    
  ///*********************************************************************************************
  ///*********************************************************************************************
  
  ///=============================
  ///==== fill MC information ====
  SetMCVariables(vars, reader);
  
  ///=============================
  ///==== fill Primary Vertex ====
  SetPVVariables(vars, reader);
  
  ///================================
  ///==== fill Event information ====
  SetEventVariables(vars, reader);
  
  ///***************************************************
  ///**** STEP -1 - Check no copies in DATA ****
  ///***************************************************
  if (debug) std::cout << " STEP -1 " << std::endl;
  
  if( dataFlag == 1 )
  {
   std::pair<int,int> eventLSandID(reader.GetInt("lumiId")->at(0), reader.GetInt("eventId")->at(0));
   std::pair<int,std::pair<int,int> > eventRUNandLSandID(reader.GetInt("runId")->at(0), eventLSandID);
   
   if( eventsMap[eventRUNandLSandID] == 1 ) continue;
   else eventsMap[eventRUNandLSandID] = 1;
  }

  ///*************************************************
  ///**** Check comparison with JSON file ***
  ///*************************************************


  if( dataFlag == 1 )
    {
      int runId  = reader.GetInt("runId")->at(0);
      int lumiId = reader.GetInt("lumiId")->at(0);
      if(AcceptEventByRunAndLumiSection(runId, lumiId, jsonMap) == false) continue;      
    }


  
  ///****************************
  ///**** STEP 0 - Ntuplizer ****
  ///************* no additional selections applied 

  step = 0;  
  if (step > nStepToDo) {
   FillTree(vars);
   continue;
  }
  if (debug) std::cout << ">>> STEP 0 <<<" << std::endl;
   
   ///*********************************************
  ///**** STEP 1 - Jet cleaning + min pT ****
  ///************* it's performed another time here to make sure that the cleaning worked well
  ///************* Jet - electrons (pT > 5)
  ///************* Jet - muons     (pT > 5)
  ///************ In addition only jets with pT > 15 are considered from now on!
  ///************ No selections are applied here
   
  step = 1;
  if (step > nStepToDo) {
//    FillTree(vars);
   continue;
  }  
  if (debug) std::cout << ">>> STEP 1 <<<" << std::endl;
  
  std::vector<ROOT::Math::XYZTVector> leptons_jetCleaning;   
  // build the collection of electros for jet cleaning
  
  ///==== CLEANING WITH ELECTRONS ====
  for(unsigned int iEle = 0; iEle < (reader.Get4V("electrons")->size()); ++iEle)
  {
   if( reader.Get4V("electrons")->at(iEle).pt() < 5. ) continue;
//    bool flag =  IsEleIsolatedID_VBF(reader,BarrelSelections,EndcapSelections,iEle);
   bool flag =  IsEleIsolatedIDPUCorrected_VBF(reader,BarrelSelections,EndcapSelections,iEle);
   
   if (!flag) continue;
   
   leptons_jetCleaning.push_back( reader.Get4V("electrons")->at(iEle) );
  }
  
  ///==== CLEANING WITH MUONS ====
  for (int iMu = 0; iMu < reader.Get4V("muons")->size(); iMu++){    
   if (reader.Get4V("muons")->at(iMu).pt() < 5.0) continue;
   if (fabs(reader.Get4V("muons")->at(iMu).Eta()) > 2.5) continue;
//    bool flag =  IsMuIsolatedID_VBF(reader,Selections,iMu);
   bool flag =  IsMuIsolatedIDPUCorrected_VBF(reader,Selections,iMu);
   
   if (!flag) continue;

   leptons_jetCleaning.push_back( reader.Get4V("muons")->at(iMu) );
  }
  
  
  ///==== now clean jet collection ====
  
  int nJets = reader.Get4V("jets")->size();
  std::vector<int> whitelistJet; ///~~~~ all jets, 0 if rejected, 1 if accepted
  std::vector<int> blacklistJet; ///~~~~ list of numbers of jets that are "rejected"
  std::vector<int> blacklistJet_forCJV;
  std::vector<int> blacklistJet_forBtag;
  for (int iJet = 0; iJet < nJets; iJet++){
   bool skipJet = false;
   if (reader.Get4V("jets")->at(iJet).Et() < 15.0) skipJet = true;
   for(unsigned int iLep = 0; iLep < leptons_jetCleaning.size(); ++iLep) {
    ROOT::Math::XYZTVector lep = leptons_jetCleaning.at(iLep);
    if (ROOT::Math::VectorUtil::DeltaR(reader.Get4V("jets")->at(iJet),lep) < 0.3 ) skipJet = true;
   }
   if (skipJet) {
    whitelistJet.push_back(0); ///---- reject
    blacklistJet.push_back(iJet); ///---- reject ///== black list is in a different format
    blacklistJet_forCJV.push_back(iJet); ///---- reject ///== black list is in a different format
    blacklistJet_forBtag.push_back(iJet); ///---- reject ///== black list is in a different format
   }
   else {
    whitelistJet.push_back(1); ///---- select
   }
  }
     
   ///**************************************
   ///**** STEP 2 - Super-Preselections ****
   ///************* tighter preselections to start the analysis from the same point
   ///==== construct considered objets
   ///    Objects considered and selections
   
   ///   Muon
   ///   Pt>10GeV, eta<2.5
   ///   MuonId & Iso
   ///
   ///   Electron
   ///   Pt>10GeV & |eta|<2.5
   ///   eleId & Iso
   ///
   ///    At least two leptons 
   
   ///   Jet
   ///   Antikt5, L2L3 correction jets
   ///   At least two calo jets or two pf jets with pt>15 GeV
   
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  step = 2;
  if (step > nStepToDo) {
//    FillTree(vars);
   continue;
  }  
  if (debug) std::cout << ">>> STEP 2 <<<" << std::endl;
  
   ///   Electron
   ///   Pt>10GeV & |eta|<2.5
   ///   IsoTr / pTele <0.5
  ///   eleId & Iso
  std::vector<int> whitelistEle;
  std::vector<int> blacklistEle;
  int nEles = reader.Get4V("electrons")->size();
  for (int iEle = 0; iEle < nEles; iEle++){    
   bool skipEle = false;
   if (reader.Get4V("electrons")->at(iEle).pt() < 10.0) skipEle = true;
   if (fabs(reader.Get4V("electrons")->at(iEle).Eta()) > 2.5) skipEle = true;
//    bool flag =  IsEleIsolatedID_VBF(reader,BarrelSelections,EndcapSelections,iEle);
   bool flag =  IsEleIsolatedIDPUCorrected_VBF(reader,BarrelSelections,EndcapSelections,iEle);
   if (!flag) skipEle = true;
   
   if (skipEle) {
    whitelistEle.push_back(0); ///---- reject
    blacklistEle.push_back(iEle); ///---- reject ///== black list is in a different format
   }
   else {
    whitelistEle.push_back(1); ///---- select
   }
  }
       
   ///   Muon
   ///   Pt>10GeV, eta<2.5
   ///   MuonId & Iso
   std::vector<int> whitelistMu;
   std::vector<int> blacklistMu;
   int nMus = reader.Get4V("muons")->size();
   for (int iMu = 0; iMu < nMus; iMu++){    
    bool skipMu = false;
    if (reader.Get4V("muons")->at(iMu).pt() < 10.0) skipMu = true;
    if (fabs(reader.Get4V("muons")->at(iMu).Eta()) > 2.5) skipMu = true;    
//     bool flag =  IsMuIsolatedID_VBF(reader,Selections,iMu);
    bool flag =  IsMuIsolatedIDPUCorrected_VBF(reader,Selections,iMu);
    
    if (!flag) skipMu = true;

    if (skipMu) {
     whitelistMu.push_back(0); ///---- reject
     blacklistMu.push_back(iMu); ///---- reject ///== black list is in a different format
    }
    else {
     whitelistMu.push_back(1); ///---- select
    }
   }
      
   ///   At least 2 leptons
   
   int numMus_Accepted = GetNumList(whitelistMu);
   int numEles_Accepted = GetNumList(whitelistEle);
   
   int numLeptons_Accepted = numMus_Accepted + numEles_Accepted;
   if (numLeptons_Accepted < 2) continue;
   
   ///   Jet
   ///   At least two calo jets or two pf jets with pt>20 GeV
   
   int numJets_Accepted = GetNumList(whitelistJet);
   if (numJets_Accepted < 2) continue; ///==== at least 2 jets "isolated"
   
  ///*************************
  ///**** STEP 3 - Jet ID ****
  ///************* Identification of two tag jets

  step = 3;
  if (step > nStepToDo) {
//    FillTree(vars);
   continue;
  }  
  if (debug) std::cout << ">>> STEP 3 <<<" << std::endl;
  
  
  std::vector<int> itSelJet;
  double maxPt_jets_selected = SelectJets(itSelJet,*jets,"maxSumPt",-1.,&blacklistJet);
  
  int q1 = itSelJet.at(0);
  int q2 = itSelJet.at(1);
  ///---- check Pt order ----
  if (jets->at(q1).Pt() < jets->at(q2).Pt()) {
   int tempq = q1;
   q1 = q2;
   q2 = tempq;
  }

if (debug) std::cerr << " q1 = " << q1 << " : q2 = " << q2 << std::endl;


  ///---- update white/black list jets ----
  for (int iJet = 0; iJet < nJets; iJet++){
   if (q1 == iJet || q2 == iJet) {
    whitelistJet.at(iJet) = 1;
    blacklistJet.push_back(iJet); ///===>  blacklistJet used for CJV => no 2 tag jets to be considered!
    blacklistJet_forCJV.push_back(iJet); ///===>  blacklistJet used for CJV => no 2 tag jets to be considered!
   }
   else {
    whitelistJet.at(iJet) = 0;
   }
  }

 SetQJetVariables(vars, reader, q1, q2, blacklistJet_forCJV, blacklistJet_forBtag, blacklistJet_forBtag);

  ///********************************
  ///**** STEP 4 - Lepton ID ****
  ///************* Identification of the two leptons
  step = 4;
  if (step > nStepToDo) {
   FillTree(vars);
   continue;
  }  
  if (debug) std::cout << ">>> STEP 4 <<<" << std::endl;
  

  std::vector<ROOT::Math::XYZTVector> leptons;
  std::vector<int> leptonFlavours;    
  std::vector<int> leptonILep;    
  
  for(unsigned int iEle = 0; iEle < nEles; iEle++){
   if (whitelistEle.at(iEle) == 1){
    leptons.push_back( reader.Get4V("electrons")->at(iEle) );  
    leptonFlavours.push_back(11);
    leptonILep.push_back(iEle);
   }
  }
  
  for(unsigned int iMu = 0; iMu < nMus; iMu++){
   if (whitelistMu.at(iMu) == 1){
    leptons.push_back( reader.Get4V("muons")->at(iMu) );      
    leptonFlavours.push_back(13);
    leptonILep.push_back(iMu);
   }
  }
  
  std::vector<int> itSelLep;
  double maxPt_lept_selected = SelectJets(itSelLep,leptons,"maxSumPt",-1.,0);
  
  int l1 = itSelLep.at(0);
  int l2 = itSelLep.at(1);
  ///---- check Pt order ----
  if (leptons.at(l1).Pt() < leptons.at(l2).Pt()) {
   int templ = l1;
   l1 = l2;
   l2 = templ;
  }
  
  if (debug) std::cerr << " l1 = " << l1 << " : l2 = " << l2 << std::endl;
  
  SetLeptonsVariables(vars, reader, leptonILep.at(l1), leptonILep.at(l2),leptonFlavours.at(l1), leptonFlavours.at(l2));
  
  if (debug) std::cerr << ">> Lepton variables set" << std::endl;
  
  
  SetMetVariables(vars, reader, "PFMet", leptonILep.at(l1), leptonILep.at(l2),leptonFlavours.at(l1), leptonFlavours.at(l2));
  if (debug) std::cerr << ">> MET variables set" << std::endl;
   
   
  //---- lepton veto
  std::vector<int> blacklistLepton;
  blacklistLepton.push_back(l1);
  blacklistLepton.push_back(l2);
  
  vars.Nleptons_pT5  = getNumberPTThreshold(leptons,  5, &blacklistLepton);
  vars.Nleptons_pT10 = getNumberPTThreshold(leptons, 10, &blacklistLepton);
  vars.Nleptons_pT15 = getNumberPTThreshold(leptons, 15, &blacklistLepton);
  vars.Nleptons_pT20 = getNumberPTThreshold(leptons, 20, &blacklistLepton);
  vars.Nleptons_pT25 = getNumberPTThreshold(leptons, 25, &blacklistLepton);
  vars.Nleptons_pT30 = getNumberPTThreshold(leptons, 30, &blacklistLepton);

  if (debug) std::cerr << ">> Lepton multiplicity set" << std::endl;
  
  
  ///*********************************
  ///**** STEP 5 - Jet Selections ****
  ///************* Loose selections of tag jets
  step = 5;
  if (step > nStepToDo) {
   FillTree(vars);
   continue;
  }  
  if (debug) std::cout << ">>> STEP 5 <<<" << std::endl;
  
  ///----  hardcoded fixed preselections ---- VBF (begin) ----
  if (vars.q1_pT < 20.) continue;
  if (vars.q2_pT < 15.) continue;
  if (vars.M_qq <   0.) continue;
  if (vars.DEta_qq < 0.) continue;
  ///----  hardcoded fixed preselections ---- VBF (end) ----

  ///==== save trigger variables ====
  SetTriggerVariables(vars, reader);
  
  ///************************************
  ///**** STEP 6 - Final Production *****
  ///************************************
  ///**** No more selections applied ****

  step = 6;
  if (step > nStepToDo) {
   FillTree(vars);
   continue;
  }  
  if (debug) std::cout << ">>> STEP 6 <<<" << std::endl;

  ///==== if not already filled ... ====
  FillTree(vars);  
  ///=================================================
  
 }
 end = clock();
 std::cout <<"Time = " <<  ((double) (end - start)) << " (a.u.)" << std::endl;  
 
 SaveTree(vars);
 
 std::cerr << " === end === " << std::endl;
}