Beispiel #1
0
//void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfile="ROOTfiles/NPFitPP.root", TString outputfile="outfMasshisto/mass")
void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfit="0", TString outputfile="outfMasshisto/mass")
{
  _nominalcut = nominalcut;
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptStat(0);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(0.8);

  collisionsystem = collsyst;
  infname = outputfile;
  varname=varname_;
  vartex=vartex_;
  isLarger=isLarger_;

  //TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, float NPpar[]);
  TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, TString npfit);
  //void getNPFnPar(TString npfname, float par[]);
  //float NPpar[2];
  //getNPFnPar(npfile, NPpar);
  //std::cout<<"NP parameter 0: "<<NPpar[0]<<std::endl;
  //std::cout<<"NP parameter 1: "<<NPpar[1]<<std::endl;
  
  Float_t varstep;
  if(varbins==1) varstep = 0.5;
  else varstep = (varmax-varmin)/(varbins-1);
  TH1F* hMCCut = new TH1F("hMCCut","",varbins,varmin,varmax+varstep);
  TH1F* hMCNoCut = new TH1F("hMCNoCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaCut = new TH1F("hDaCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaNoCut = new TH1F("hDaNoCut","",varbins,varmin,varmax+varstep);
  for(float i=0;i<varbins+1;i++)
    {
      Float_t yield,yieldErr;
      Float_t ivar = varmin+(i-1)*varstep;
      //TF1* fMC = fit(ivar,i,1, NPpar);
      TF1* fMC = fit(ivar,i,1, npfit);
      yield = fMC->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fMC->Integral(minhisto,maxhisto)/binwidthmass*fMC->GetParError(0)/fMC->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hMCNoCut->SetBinContent(j+1,yield);
              hMCNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hMCCut->SetBinContent(i,yield);
          hMCCut->SetBinError(i,yieldErr);
        }
      //TF1* fDa = fit(ivar,i,0, NPpar);
      TF1* fDa = fit(ivar,i,0, npfit);
      yield = fDa->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fDa->Integral(minhisto,maxhisto)/binwidthmass*fDa->GetParError(0)/fDa->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hDaNoCut->SetBinContent(j+1,yield);
              hDaNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hDaCut->SetBinContent(i,yield);
          hDaCut->SetBinError(i,yieldErr);
        }
    }

  TCanvas* cMCRatio = new TCanvas("cMCRatio","",600,600);
  TH1F* hMCRatio = (TH1F*)hMCCut->Clone("hMCRatio");
  hMCRatio->SetTitle(Form(";%s;hMCRatio",vartex.Data()));
  hMCRatio->Divide(hMCNoCut);
  hMCRatio->Draw();

  TCanvas* cDaRatio = new TCanvas("cDaRatio","",600,600);
  TH1F* hDaRatio = (TH1F*)hDaCut->Clone("hDaRatio");
  hDaRatio->SetTitle(Form(";%s;hDaRatio",vartex.Data()));
  hDaRatio->Divide(hDaNoCut);
  hDaRatio->Draw();

  TCanvas* chDoubleRatio = new TCanvas("chDoubleRatio","",600,600);
  TH1F* hDoubleRatio = (TH1F*)hDaRatio->Clone("hDoubleRatio");
  hDoubleRatio->SetTitle(Form(";%s;hDoubleRatio",vartex.Data()));
  hDoubleRatio->Divide(hMCRatio);
  hDoubleRatio->Draw();

  Float_t aDoubleRatio[varbins],aDoubleRatioErr[varbins],aX[varbins],aZero[varbins];
  Float_t AbsMax = max(fabs(hDoubleRatio->GetMaximum()-1), fabs(hDoubleRatio->GetMinimum()-1));
  for(int i=0;i<varbins;i++)
    {
      aDoubleRatio[i] = hDoubleRatio->GetBinContent(i+1);
      aDoubleRatioErr[i] = hDoubleRatio->GetBinError(i+1);
      aX[i] = varmin+i*varstep;
      aZero[i] = 0;
    }
  TGraphErrors* gDoubleRatio = new TGraphErrors(varbins,aX,aDoubleRatio,aZero,aDoubleRatioErr);
  TH2F* hemptyDoubleRatio = new TH2F("hemptyDoubleRatio","",20,varmin-0.5*varstep,varmax+0.5*varstep,10.,0.,2.);
  hemptyDoubleRatio->GetXaxis()->SetTitle(Form("%s",vartex.Data()));
  hemptyDoubleRatio->GetYaxis()->SetTitle("(Yield^{Data}_{Cuts}/Yield^{Data}_{NoCuts})/(Yield^{MC}_{Cuts}/Yield^{MC}_{NoCuts})");
  hemptyDoubleRatio->GetXaxis()->SetTitleOffset(1.);
  hemptyDoubleRatio->GetYaxis()->SetTitleOffset(1.4);
  hemptyDoubleRatio->GetXaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetYaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetXaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetYaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetYaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelSize(0.04);
  hemptyDoubleRatio->GetYaxis()->SetLabelSize(0.04);
  TLine* lDoubleRatio = new TLine(varmin-0.5*varstep, 1., varmax+0.5*varstep, 1.);
  lDoubleRatio->SetLineWidth(1);
  lDoubleRatio->SetLineStyle(7);
  lDoubleRatio->SetLineColor(1);
  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  TCanvas* cDoubleRatio = new TCanvas("cDoubleRatio","",600,600);
  hemptyDoubleRatio->Draw();
  gDoubleRatio->Draw("psame");
  lDoubleRatio->Draw();
  texCms->Draw();
  texCol->Draw();
  TLatex* texAbsMax = new TLatex(0.88,0.85, Form("max diff: %.3f",AbsMax));
  texAbsMax->SetNDC();
  texAbsMax->SetTextAlign(32);
  texAbsMax->SetTextSize(0.04);
  texAbsMax->SetTextFont(42);
  texAbsMax->Draw();
	
  cDoubleRatio->SaveAs(Form("plotRatios/%s_%s_DoubleRatio.pdf",collisionsystem.Data(),varname.Data()));

  TFile* outf = new TFile(Form("outfDoubleratio/f%s_%s_DoubleRatio.root",collisionsystem.Data(),varname.Data()),"recreate");
  outf->cd();
  hDoubleRatio->Write();
  outf->Close();
}
Beispiel #2
0
void doCoinc3(const char *fileIn="SAVO-01-SAVO-02-SAVO-03-2016-01-26.root"){
  Int_t adayMin = (yearRange[0]-2007) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2007) * 1000 + monthRange[1]*50 + dayRange[1];

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

  TFile *fo = new TFile("output-SAVO-010203.root","RECREATE");
  h->Write();
  h2->Write();
  hDeltaTheta12->Write();
  hDeltaPhi12->Write();
  hThetaRel12->Write();
  hDeltaThetaBack12->Write();
  hDeltaPhiBack12->Write();
  hThetaRelBack12->Write();
  hDeltaTheta13->Write();
  hDeltaPhi13->Write();
  hThetaRel13->Write();
  hDeltaThetaBack13->Write();
  hDeltaPhiBack13->Write();
  hThetaRelBack13->Write();
  fo->Close();
  
}
Beispiel #3
0
void toyMC(int nsteps = 1e6) {
    
    Float_t LA = 9.2;
    Float_t LB = 10.3;
    
    Float_t SF = 492./LB;
    Float_t eSF = TMath::Sqrt(23.*23.+19.7*19.7)/LB;
//     Float_t OF = 358./LA;
//     Float_t eOF = 27./LA;
    Float_t OF = 358./LB;
    Float_t eOF = 31./LB;
    
    Float_t SigB = 188.+238-414;
    
    
    TH1F* hSig = new TH1F("hSig ; SF-R_{SF/OF}#timesOF ; ","Signal component",600,-100.,500.);
    
    hSig->SetLineColor(kRed+2);
    
    TRandom3* ran = new TRandom3();
    
    for ( int i=0; i<nsteps; ++i ) {
        
        Float_t nBSF = ran->Gaus(SF*LB,eSF*LB);
        Float_t nBOF = ran->Gaus(OF*LB,eOF*LB);
        Float_t rsfof = ran->Gaus(1.0,0.05);
        
        hSig->Fill(nBSF-nBOF*rsfof);
        
    }
    
    
    TCanvas* mycan = new TCanvas("mycan","",100,10,900,600);
    mycan->SetLogy();
    TH1F* hSigNorm = hSig->DrawNormalized("");
    hSigNorm->SetMinimum(1e-5);
    hSigNorm->Draw();
    
    // Find 95% CL range
    float integral = 0;
    int binStart = -1;
    while ( integral <= 0.025 ) {
        ++binStart;
        integral += hSigNorm->GetBinContent(binStart);
    }
    std::cout << integral << " up to " << hSigNorm->GetBinCenter(binStart) << std::endl;
    integral = 0;
    int binEnd = hSigNorm->GetNbinsX()+2;
    while ( integral <= 0.025 ) {
        --binEnd;
        integral += hSigNorm->GetBinContent(binEnd);
    }
    std::cout << integral << " up to " << hSigNorm->GetBinCenter(binEnd) << std::endl;
    
    // Draw 95% CL
    TBox* range95 = new TBox(hSigNorm->GetBinCenter(binStart),hSigNorm->GetMinimum(),hSigNorm->GetBinCenter(binEnd),1.2*hSigNorm->GetMaximum());
    range95->SetFillColor(kBlue-9);
    range95->SetFillStyle(1000);
    range95->SetLineColor(range95->GetFillColor());
    range95->Draw();
    
    hSigNorm->SetTitle("hSigNorm; \"S\" #equiv SF - R_{SF/OF}#timesOF ; pdf");
    hSigNorm->Draw("same");
    
    std::cout << "Integrating from 0 to " << SigB << ": " << std::endl;
    std::cout << hSigNorm->Integral(0,hSigNorm->FindBin(SigB)) <<std::endl;
    
    TLegend* legend = new TLegend(0.6,0.7,0.95,0.9,"","brNDC");
    legend->SetBorderSize(0);
    legend->AddEntry(hSigNorm,"Expected \"S\" for block B","l");
    legend->AddEntry(range95,"95% region","f");
    legend->Draw();

    mycan->RedrawAxis();
    mycan->SaveAs("toyMCexp.pdf");

    TArrow* a = new TArrow(SigB,hSigNorm->GetMaximum(),SigB,hSigNorm->GetMinimum()*1.1,0.02);
    a->SetLineColor(kBlue+2);
    a->Draw();


    TLegend* legend2 = new TLegend(0.6,0.6,0.95,0.7,"","brNDC");
    legend2->SetBorderSize(0);
    legend2->AddEntry(a,"Observed (p-value 0.6%)","l");
    legend2->Draw();
    

    mycan->SaveAs("toyMC.pdf");
    
}
bool createPlot(TString hname, TString dirname, TFile *V1file, TString runstring1, TString relstring1, TFile *V2file, TString runstring2, TString relstring2, TCanvas *canvas, int scale) {
  setTDRStyle();

  int SetScale = scale;

  //IF =0 --> No scale applied ('direct' comparison)
  //IF =1 --> Scale INDIVIDUALLY (scale histograms individually) 
  //IF =2 --> Scale all GLOBALLY (scale all histograms to #tracks=1)
  //IF =3 --> Scale all GLOBALLY nEVENTS (scale all histos to nEntries in nTracks per Event)

  bool DrawRatio = true;
  canvas->cd();
  TPad* mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);
  mainpad->Draw();
  mainpad->cd();

  // ************ Get name of histos and get histos ************* //

  if (dirname.Contains("GeneralProperties/GoodTracks",TString::kExact)){
    if ((hname != "FractionOfGoodTracks") && (hname != "NumberOfGoodTracks")){
      hname.Prepend("GoodTrack");
    }
  }
  
  TString basename1 = "DQMData/Run ";
  basename1.Append(runstring1);

  TString hnameV1 = basename1;
  hnameV1.Append(dirname+"/");
  hnameV1.Append(hname);

  if (hname != "vtxNbr"){
    hnameV1.Append("_GenTk");
  }

  TH1F * hBinTempV1 = (TH1F*)V1file->Get(hnameV1);
  if ( hBinTempV1 == (TH1F*) NULL ) {
    cout << "histV1 failed on " << hnameV1  << endl << " for file " << V1file->GetName() << endl;
    exit(1);
  }

  TString basename2 = "DQMData/Run ";
  basename2.Append(runstring2);

  TString hnameV2 = basename2;
  hnameV2.Append(dirname+"/");
  hnameV2.Append(hname);
  
  if (hname != "vtxNbr"){
    hnameV2.Append("_GenTk");
  }

  TH1F * hBinTempV2 = (TH1F*)V2file->Get(hnameV2);
  if ( hBinTempV2 == (TH1F*) NULL ) {
    cout << "histV2 failed on " << hnameV2  << endl << " for file " << V2file->GetName() << endl;
    exit(1);
  }

  // Check that bins match for ratio plot

  TH1F * histV1 = 0;
  TH1F * histV2 = 0;

  Double_t h1_xlow = hBinTempV1->GetXaxis()->GetBinLowEdge(hBinTempV1->GetXaxis()->GetFirst());
  Double_t h2_xlow = hBinTempV2->GetXaxis()->GetBinLowEdge(hBinTempV2->GetXaxis()->GetFirst());

  Double_t h1_xup = hBinTempV1->GetXaxis()->GetBinUpEdge(hBinTempV1->GetXaxis()->GetLast());
  Double_t h2_xup = hBinTempV2->GetXaxis()->GetBinUpEdge(hBinTempV2->GetXaxis()->GetLast());

  Int_t h1_nbins = hBinTempV1->GetNbinsX();
  Int_t h2_nbins = hBinTempV2->GetNbinsX();

  Double_t h1_binWidth = (h1_xup - h1_xlow) / (Double_t)h1_nbins;
  Double_t h2_binWidth = (h2_xup - h2_xlow) / (Double_t)h2_nbins;

  if ((h1_xlow == h2_xlow) && (h1_xup == h2_xup) && (h1_binWidth == h2_binWidth)){
    histV1 = (TH1F*)V1file->Get(hnameV1);
    histV2 = (TH1F*)V2file->Get(hnameV2);
  }
  else if((h1_xlow == h2_xlow) && (h1_xup < h2_xup) && (h1_binWidth == h2_binWidth)){ // Fill h1 from h1xlow to h1high with h1 info, and up to h2high, fill zero 
    histV2 = (TH1F*)V2file->Get(hnameV2); // copy histV2 

    histV1 = new TH1F(hBinTempV1->GetName(),hBinTempV1->GetTitle(),h2_nbins,h2_xlow,h2_xup);
    histV1->SetXTitle(hBinTempV1->GetXaxis()->GetTitle());
    histV1->SetYTitle(hBinTempV1->GetYaxis()->GetTitle());
    for (Int_t ibin = 1; ibin <= h2_nbins; ibin++){
      if (ibin <= h1_nbins){
	histV1->SetBinContent(ibin,hBinTempV1->GetBinContent(ibin));
      }
      else if (ibin > h1_nbins){
	histV1->SetBinContent(ibin,0.0); 
      }
    }
  }
  else if((h1_xlow == h2_xlow) && (h1_xup > h2_xup) && (h1_binWidth == h2_binWidth)){ // Fill h1 from h1xlow to h1high with h1 info, and up to h2high, fill zero 
    histV1 = (TH1F*)V1file->Get(hnameV1); // copy histV1 

    histV2 = new TH1F(hBinTempV2->GetName(),hBinTempV2->GetTitle(),h1_nbins,h1_xlow,h1_xup);
    histV2->SetXTitle(hBinTempV2->GetXaxis()->GetTitle());
    histV2->SetYTitle(hBinTempV2->GetYaxis()->GetTitle());
    for (Int_t ibin = 1; ibin <= h1_nbins; ibin++){
      if (ibin <= h2_nbins){
	histV2->SetBinContent(ibin,hBinTempV2->GetBinContent(ibin));
      }
      else if (ibin > h2_nbins){
	histV2->SetBinContent(ibin,0.0); 
      }
    }
  }
  else{
    cout << "Bin Check Failed... here's what happened: " << endl;
    cout << "histV1 failed on " << hnameV1  << endl << " for file " << V1file->GetName() << endl;
    cout << "       bin info: " << h1_xlow << " " << h1_xup << " " << h1_nbins << endl;
    cout << "histV2 failed on " << hnameV2  << endl << " for file " << V2file->GetName() << endl;
    cout << "       bin info: " << h2_xlow << " " << h2_xup << " " << h2_nbins << endl;
    exit(1);
  }

  // Don't look at zero bin -- > Also could use this for truncation and bin setting -->Range is binlower to upper
  //  Int_t range_upper = histV1->GetXaxis()->GetLast();
  //  histV1->GetXaxis()->SetRangeUser(1,range_upper);
  //  histV2->GetXaxis()->SetRangeUser(1,range_upper);

  //******************* Get histo integrals ***********************//
  double V1_integral = 1.0;
  double V2_integral = 1.0;

  TH1F * hNormTempV1 = 0;
  TH1F * hNormTempV2 = 0;

  if (SetScale==1){    
    V1_integral = histV1->Integral();
    V2_integral = histV2->Integral();
  }
  else if ( (SetScale==2) || (SetScale==3) ){
    if (hname != "NumberOfTracks"){
      TString hTempNameV1 = basename1;
      hTempNameV1.Append("/Tracking/Run summary/TrackParameters/GeneralProperties/NumberOfTracks_GenTk");
      hNormTempV1 = (TH1F*)V1file->Get(hTempNameV1);
      
      TString hTempNameV2 = basename2;
      hTempNameV2.Append("/Tracking/Run summary/TrackParameters/GeneralProperties/NumberOfTracks_GenTk");
      hNormTempV2 = (TH1F*)V2file->Get(hTempNameV2);
    }
    else{
      hNormTempV1 = (TH1F*)histV1->Clone("hNormTempV1");
      hNormTempV2 = (TH1F*)histV2->Clone("hNormTempV2");
    }

    if (SetScale==2){
      V1_integral = hNormTempV1->GetBinContent(2);
      V2_integral = hNormTempV2->GetBinContent(2);

      std::cout << "The number of single tracks for V1 is " << V1_integral << std::endl;
      std::cout << "The number of single tracks for V2 is " << V2_integral << std::endl;
    }
    else if (SetScale==3){
      V1_integral = hNormTempV1->GetEntries();
      V2_integral = hNormTempV2->GetEntries();

      std::cout << "The number of events for V1 is " << V1_integral << std::endl;
      std::cout << "The number of events for V2 is " << V2_integral << std::endl;
    }
  }

  //*****NORMALIZING V1-V2****************************************

  if(V1_integral>V2_integral) {
    histV1->Scale(V2_integral / V1_integral);
    histV2->Scale(1);
  } 
  else if(V2_integral>V1_integral){
    histV1->Scale(1);
    histV2->Scale(V1_integral / V2_integral);
  }

  //*****NORMALIZING V1-V2*end***************************************

  //***Name the files under comparison***
  TString V1_V1run = "Run "+runstring1+" ("+relstring1+")";
  TString V2_V2run = "Run "+runstring2+" ("+relstring2+")";

  histV1->SetName(V1_V1run);
  histV2->SetName(V2_V2run);

  double max = 0;
  double V1max = histV1->GetBinContent(histV1->GetMaximumBin());
  double V2max = histV2->GetBinContent(histV2->GetMaximumBin());

  max = (V1max>V2max) ? V1max : V2max;
  histV1->Draw();
  histV1->SetLineStyle(1);
  histV1->GetYaxis()->SetLabelSize(0.038);
  histV1->SetLineWidth(5);
  histV1->SetLineColor(kRed);
  histV1->SetMaximum(max*(1.1));
  histV2->Draw();
  histV2->SetLineWidth(3);
  histV2->SetLineStyle(1);
  histV2->SetLineColor(kBlue);



  if( hname.Contains("NumberOfTracks",TString::kExact)
      || hname.Contains("NumberOfGoodTracks",TString::kExact)
      || hname.Contains("TrackPt",TString::kExact)
      || hname.Contains("Chi2Prob",TString::kExact)
      ){
    mainpad->SetLogy(1);
  }
  else{
    mainpad->SetLogy(0);
  }

  if (hname.Contains("NumberOfTracks",TString::kExact)){
    histV1->GetXaxis()->SetRangeUser(0,500);
    histV2->GetXaxis()->SetRangeUser(0,500);
  }
  
  if (hname.Contains("NumberOfGoodTracks",TString::kExact)) {
    histV1->GetXaxis()->SetRangeUser(0,200);
    histV2->GetXaxis()->SetRangeUser(0,200);
  }

  if (hname.Contains("Chi2oNDF",TString::kExact)) {
    histV1->GetXaxis()->SetRangeUser(0,10);
    histV2->GetXaxis()->SetRangeUser(0,10);
  }

  if (hname.Contains("vtxNbr")){
    histV1->GetXaxis()->SetTitle("Number of Primary Vertices per Event");
    histV1->GetYaxis()->SetTitle("Number of Events");
  }

  histV1->Draw(); // Draw old histo first, ratio is new/old
  histV2->Draw("sames");

  mainpad->Update();

  TPaveStats *st1 = (TPaveStats*)(histV1->GetListOfFunctions()->FindObject("stats"));

  st1->SetX1NDC(0.77);
  st1->SetY1NDC(0.80);

  st1->SetX2NDC(0.98);
  st1->SetY2NDC(0.97);
  Double_t defaulth = st1->GetY2NDC() - st1->GetY1NDC();
  Double_t gaph = 0.02;
  TPaveStats *st2 = (TPaveStats*)(histV2->GetListOfFunctions()->FindObject("stats"));
  st2->SetX1NDC(0.77);  
  st2->SetY1NDC(st1->GetY1NDC() - 1.0*defaulth - gaph);
  st2->SetX2NDC(0.98);    
  st2->SetY2NDC(st1->GetY1NDC() - gaph);

  TLegend *leg = new TLegend(0.32,0.86,0.76,0.97);
  leg->SetTextSize(0.042);
  leg->SetTextFont(42);
  leg->SetFillColor(10); 
  leg->SetBorderSize(1); // no frame, no shadow
  leg->AddEntry(histV1, V1_V1run, "L" );
  leg->AddEntry(histV2, V2_V2run, "L" );
  leg->Draw("SAME");

  // Draw ratio histogram
  if (DrawRatio){
    canvas->cd();
    TPad* respad = new TPad("respad","respad",0.0,0.78,1.0,0.95);
    respad->SetTopMargin(1.05);
    respad->Draw();
    respad->cd();
    TH1F* hratio = (TH1F*) histV2->Clone("hratio");
    hratio->Divide(histV1);
    hratio->SetMaximum(hratio->GetMaximum()*1.1);
    hratio->SetMinimum(hratio->GetMinimum()/1.1);
    //if (hratio->GetMinimum()==0.0) hratio->SetMinimum(1.0/hratio->GetMaximum());
    //    hratio->SetMinimum(1.0/hratio->GetMaximum());
    hratio->GetYaxis()->SetLabelSize(0.1);
    //    hratio->GetYaxis()->SetRangeUser(0,2);
    hratio->GetXaxis()->SetLabelSize(0);
    hratio->GetXaxis()->SetTitleSize(0);
    hratio->GetYaxis()->SetTitleSize(0.22);
    hratio->GetYaxis()->SetTitleOffset(0.26);
    hratio->GetYaxis()->SetLabelSize(0.2);
    hratio->GetYaxis()->SetNdivisions(5);
    hratio->GetYaxis()->SetTitle("NEW/REF");
    hratio->Draw();
  }

  // Compare parameters of histograms
  double Entries1 = histV1->GetEntries();
  double Entries2 = histV2->GetEntries();
  if (Entries1 != Entries2) {
    std::cout<<" Difference in # of ENTRIES for " <<hname<< std::endl;
    std::cout<<"\t Entries1 = " << Entries1 << "\t Entries2 = " << Entries2 << std::endl;
  }

  double Mean1 = histV1->GetMean();
  double Mean2 = histV2->GetMean();
  if (Mean1 != Mean2) {
    std::cout<<" Difference in MEANS for " <<hname<< std::endl;
    std::cout<<"\t Mean1 = " << Mean1 << "\t Mean2 = " << Mean2 << std::endl;
  }

  double RMS1 = histV1->GetRMS();
  double RMS2 = histV2->GetRMS();
  if (RMS1 != RMS2) {
    std::cout<<" Difference in RMS for " <<hname<< std::endl;
    std::cout<<"\t RMS1 = " << RMS1 << "\t RMS2 = " << RMS2 << std::endl;
  }

  TString filename = hname;

  if (hname.Contains("vtxNbr")){
    filename = "NumberOfPrimaryVertices";
  }

  if (dirname.Contains("GeneralProperties/GoodTracks",TString::kExact))
    filename.Prepend("RunComparison/GoodTracks_");
  else filename.Prepend("RunComparison/");

  filename.Append(".png");

  canvas->Print(filename);

  if ( histV1 ) {histV1->Delete();}
  if ( histV2 ) {histV2->Delete();}

  if ( hNormTempV1 ) {hNormTempV1->Delete();}
  if ( hNormTempV2 ) {hNormTempV2->Delete();}

  //  if ( hBinTempV1 ) {hBinTempV1->Delete();} // why cant this work?! 
  //  if ( hBinTempV2 ) {hBinTempV2->Delete();}

  return true;
}
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

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

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

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

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

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

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

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

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

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

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

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

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

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

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

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

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

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

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

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

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

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

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

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


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

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

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

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

      }
    }
  }
  else{
    telC = NULL;
  }

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

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

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

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

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

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

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


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

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

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

    neventsGR++;

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

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

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

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

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

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

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


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

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

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

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

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

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

  h->SetStats(0);

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

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


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

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

  h->Draw();
  
  new TCanvas;

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

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

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

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

  return nsecGR*1./86400;
  
}
Beispiel #6
0
int main ( int argc, char *argv[] )
{

  StopStyle();
  std::vector<std::string> vDec;
  //vDec.push_back("PhaseI");
  //vDec.push_back("PhaseII3");
  //vDec.push_back("PhaseII4");

  vDec.push_back("PhaseI_0PU");
  vDec.push_back("PhaseI_140PU");
  vDec.push_back("PhaseII3_140PU");
  vDec.push_back("PhaseII4_140PU");


  std::vector<std::string> vLep;
  vLep.push_back("EleEta");
  //vLep.push_back("ElePt");
  vLep.push_back("MuonEta"); 
  //vLep.push_back("MuonPt");
  //vLep.push_back("TauEta"); 
  //vLep.push_back("TauPt");
  //vLep.push_back("JetEta"); 
  //vLep.push_back("JetPt");
  //vLep.push_back("JetPt");
  //vLep.push_back("MET");
  //vLep.push_back("MHT");

    int cut = 0;
    //int cut = 5; //Before lepton veto
    //int cut = 14; //After METCut
  std::vector<int> VColor;
  VColor.push_back(1);
  VColor.push_back(2);
  VColor.push_back(4);
  VColor.push_back(6);
  VColor.push_back(kGreen+2);
  VColor.push_back(kOrange+9);
  VColor.push_back(60);


  TCanvas *c1 = new TCanvas("fd", "dfdf", 600, 500);
  TLegend *lg = NULL;
  //c1->SetGridx();
  //c1->SetGridy();

  for (int j = 0; j < vLep.size(); ++j)
  {
    if (vLep.at(j).find("Pt") != std::string::npos)
      lg = new TLegend(0.602349,0.1631356,0.8389262,0.4576271,NULL,"brNDC");
    else if (vLep.at(j).find("EleEta") != std::string::npos )
      //lg = new TLegend(0.3691275,0.1751055,0.6057047,0.4683544,"W(e#nu) + jets","brNDC");
      lg = new TLegend(0.3238255,0.1673729,0.5486577,0.4618644,"W(e#nu) + jets","brNDC");
    else if (vLep.at(j).find("MuonEta") != std::string::npos)
      //lg = new TLegend(0.3691275,0.1751055,0.6057047,0.4683544,"W(#mu#nu) + jets","brNDC");
      lg = new TLegend(0.3238255,0.1673729,0.5486577,0.4618644,"W(#mu#nu) + jets","brNDC");

      //lg = new TLegend(0.3791946,0.1737288,0.6157718,0.4682203,NULL,"brNDC");
    else if (vLep.at(j).find("JetEta") != std::string::npos)
      lg = new TLegend(0.3657718,0.7139831,0.6241611,0.9533898,NULL,"brNDC");
    else if (vLep.at(j).find("TauEta") != std::string::npos)
      lg = new TLegend(0.3842282,0.654661,0.6208054,0.9491525,NULL,"brNDC");
    else
      lg = new TLegend(0.3791946,0.1737288,0.6157718,0.4682203,NULL,"brNDC");


    //else if (vLep.at(j).find("EleEta") != std::string::npos)
    lg->SetBorderSize(0);
    lg->SetFillStyle(0); //transparent hollow?
    lg->SetTextFont(62); 
    //lg->SetTextSize(0.03);
    lg->SetTextSize(0.04);

    double ymin = 0.0;
    double ymax = 0.0;
    TAxis *yaxis = NULL;
    TAxis *xaxis = NULL;


    for (int i = 0; i < vDec.size(); ++i)
    {

      char pu[10];
      char det[10];
      sscanf(vDec.at(i).c_str(), "%[^_]_%s", det, pu);

      std::cout <<  " pu " << pu << "  "<< strcmp(pu, "0PU") << std::endl;

      std::string pileup ="" ;
      if (strcmp(pu, "0PU") == 0)  pileup = "NoPileUp";
      if (strcmp(pu, "50PU") == 0) pileup = "50PileUp";
      if (strcmp(pu, "140PU") == 0) pileup = "140PileUp";
      std::cout << " pileup " << pileup <<" dec " << det << std::endl;

      HTSample *HT = new HTSample("LPC_MHTCUT/", "Wlv*_14TEV_HT", pileup, det);
      HT->InitSample(3000*1000);
      c1->cd();
      c1->Update();

      TH1F* reco = NULL;
      TH1F* gen = NULL;
      //TH2D* reco = NULL;
      //TH2D* gen = NULL;


      std::cout << " " << vLep.at(j) << std::endl;
      if (vLep.at(j) != "MET" && vLep.at(j) != "MHT")
      {
        TString reconame = "AppMatched"+vLep.at(j);
        TString genname = "AppGen"+vLep.at(j);
        //reco = (TH2D*)HT->GetTH2D(reconame.Data(), cut);
        //gen = (TH2D*)HT->GetTH2D(genname.Data(), cut);
        reco = (TH1F*)HT->GetTH1(reconame.Data(), cut);
        gen = (TH1F*)HT->GetTH1(genname.Data(), cut);
      } else {
        //reco = (TH1F*)HT->GetTH1(vLep.at(j), cut);
        //gen = (TH1F*)HT->GetTH1("GenMet");
      }


      if (vLep.at(j).find("Pt") != std::string::npos)
      {
        reco->Rebin(5);
        gen->Rebin(5);
        
      }
      //TH1F* reco = (TH1F*)HT->GetTH1("JetEta", cut);
      //TH1F* gen = (TH1F*)HT->GetTH1("GenJetEta", cut);
      //TH1F* reco = (TH1F*)HT->GetTH1("MuonPt", cut);
      //reco->Rebin(5);
      //TH1F* gen = (TH1F*)HT->GetTH1("GenMuonPt", cut);
      //gen->Rebin(5);
      //TH1F* reco = (TH1F*)HT->GetTH1("ElePt", cut);
      //
      //TH1F* gen = (TH1F*)HT->GetTH1("GenElePt", cut);

      reco->Divide(gen);
      reco->SetTitle("");
      //gen->Draw();
      //gen->SetLineColor(1);
      reco->SetLineWidth(3);
      reco->SetLineColor(VColor.at(i));

      ymin = ymin < reco->GetMinimum() ? ymin : reco->GetMinimum();
      ymax = ymax > reco->GetMaximum() ? ymax : reco->GetMaximum();
      if (i == 0)
      {
        yaxis = reco->GetYaxis();
        xaxis = reco->GetXaxis();
        reco->Draw();
      }
      else
      {
        reco->Draw("same");
      }

      reco->GetYaxis()->SetTitle("Efficiency");

      if (vDec.at(i).find("PU") != std::string::npos)
      {

        std::cout << " vDec.at(i)" << vDec.at(i) << std::endl;
        std::cout<<"Run to \033[0;31m"<<__func__<<"\033[0m at \033[1;36m"<< __FILE__<<"\033[0m, line \033[0;34m"<< __LINE__<<"\033[0m"<< std::endl; 
        if (vDec.at(i) == "PhaseI_0PU")    
        {
          lg->AddEntry(reco, "Phase I, <PU>=0",   "fl");
          reco->SetLineColor(1);
        }
        if (vDec.at(i) == "PhaseI_140PU")  
        { 
          lg->AddEntry(reco, "Phase I, <PU>=140", "fl");
          reco->SetLineColor(4);
        }
        if (vDec.at(i) == "PhaseII3_140PU") 
        {
          lg->AddEntry(reco, "Phase II Conf3, <PU>=140", "fl");
          //lg->AddEntry(reco, "PhaseII3 <PU>=140", "fl");
          reco->SetLineColor(kGreen+2);
        }
        if (vDec.at(i) == "PhaseII4_140PU") 
        {
          lg->AddEntry(reco, "Phase II Conf4, <PU>=140", "fl");
          reco->SetLineColor(2);
        }


        //TString leg = vDec.at(i);
        //lg->AddEntry(reco, leg.ReplaceAll("_", " "), "l");
      }
      TString xlabel = reco->GetXaxis()->GetTitle();
      std::cout << xlabel << std::endl;
      if (xlabel =="#Pt_{Matched m} [GeV]") 
        std::cout<<"Run to \033[0;31m"<<__func__<<"\033[0m at \033[1;36m"<< __FILE__<<"\033[0m, line \033[0;34m"<< __LINE__<<"\033[0m"<< std::endl; 
      if (xlabel =="#eta_{Matched e}" ) xlabel = "#eta_{e}";
      if (xlabel =="#eta_{Matched m}" ) xlabel = "#eta_{#mu}";
      if (xlabel =="#eta_{Matched t}" ) xlabel = "#eta_{t}";
      if (xlabel =="#Pt_{Matched e} [GeV] " ) xlabel = "#P_{T}^{e} [GeV]";
      if (xlabel =="#Pt_{Matched m} [GeV] " ) xlabel = "#P_{T}^{#mu} [GeV]";
      if (xlabel =="#Pt_{Matched t} [GeV] " ) xlabel = "#P_{T}^{t} [GeV]";
      reco->GetXaxis()->SetTitle(xlabel);



      reco->GetYaxis()->SetTitleOffset(1.0);
      reco->GetXaxis()->SetTitleOffset(0.9);
      reco->GetYaxis()->SetTitleSize(0.06);
      reco->GetXaxis()->SetTitleSize(0.06);
      reco->GetYaxis()->SetLabelSize(0.05);
      reco->GetXaxis()->SetLabelSize(0.05);
      //reco->GetYaxis()->SetRangeUser(0.1*ymin, 5*ymax);
      //c1->Print("Pt.png");
      //c1->Print("MuonEta_0.png");
      //c1->Print("EleEta_0.png");
      //TH1F* jet = (TH1F*)HT->GetTH1("JetPTScale", cut);
      //jet->Draw();
      //c1->Print("Jet.png");

      delete HT;

    }

    yaxis->SetRangeUser(0.8*ymin, 1.2*ymax);
    xaxis->SetRangeUser(-4.5, 4.5);
    lg->Draw();
    DrawTitle();
    c1->RedrawAxis();

    std::stringstream ss;
    ss << "Efficiency_"<<vLep.at(j)<< "_"<< cut<< ".png";
    c1->Print(ss.str().c_str());
    ss.str("");
    ss << "Efficiency_"<<vLep.at(j)<< "_"<< cut<< ".pdf";
    c1->Print(ss.str().c_str());
    ss.str("");
    ss << "Efficiency_"<<vLep.at(j)<< "_"<< cut<< ".C";
    c1->Print(ss.str().c_str());
    ss.str("");
    ss << "Efficiency_"<<vLep.at(j)<< "_"<< cut<< ".root";
    c1->Print(ss.str().c_str());
  }

  return EXIT_SUCCESS;
}				// ----------  end of function main  ----------
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!
    //
}
Beispiel #8
0
// i must be between 0 and Num_selection_cuts-1
// option = 1 (muon-pt), option = 2 (transverse mass)
void doPlots(unsigned i, TFile * _file0, int option)
{

  //  gStyle->Reset();
  gStyle->SetFillColor(1);


  string algo = algo_desc_short[tracking_option]; 
  char temp[1024]; sprintf(temp, " (%4.2f pb^{-1})", Lumi_ipb);
  string desc = algo_desc_long[tracking_option] + " muons, " + 
    cuts_desc_long[i] + temp;

  TCanvas * c1 = new TCanvas();
  c1->SetLogy();
  THStack *hs = new THStack("hs",desc.c_str());  

  string prefix = "";
  if(option == 1)
    prefix = "hPT";
  else if(option == 2)
    prefix = "hTM";

  string histo = prefix + algo + "_" + cuts_desc_short[i];
  string histoW = "W/" + histo;
  TH1F * w = (TH1F* ) _file0->Get(histoW.c_str());
  if(badHisto(w, "W"))
    return;

  string histoWlpt = "Wlowpt/" + histo;
  TH1F * wlpt = (TH1F* ) _file0->Get(histoWlpt.c_str());
  if(badHisto(wlpt, "Wlowpt"))
    return;

  string histoQ = "QCD/" + histo;
  TH1F * qcd = (TH1F* )_file0->Get(histoQ.c_str());
  if(badHisto(qcd, "QCD"))
    return;

  string histoZ = "Z/" + histo;
  TH1F * z = (TH1F* )_file0->Get(histoZ.c_str());
  if(badHisto(z, "Z"))
    return;
  
  string histoT = "Top/" + histo;
  TH1F * top = (TH1F* )_file0->Get(histoT.c_str());
  if(badHisto(top, "Top"))
    return;

  string histo10 = "wprime1.0/" + histo;
  TH1F * wp10 = (TH1F* )_file0->Get(histo10.c_str());
  if(badHisto(wp10, "wprime1.0"))
    return;

  string histo15 = "wprime1.5/" + histo;
  TH1F * wp15 = (TH1F* )_file0->Get(histo15.c_str());
  if(badHisto(wp15, "wprime1.5"))
    return;

  string histo20 = "wprime2.0/" + histo;
  TH1F * wp20 = (TH1F* )_file0->Get(histo20.c_str());
  if(badHisto(wp20, "wprime2.0"))
    return;

  string hdata = "data/" + histo;
  TH1F * data = (TH1F*) _file0->Get(hdata.c_str());
  if(badHisto(data, "data"))
    return;

  top->SetLineColor(kMagenta);
  z->SetLineColor(kOrange);
  qcd->SetLineColor(kGray+2);
  w->SetLineColor(kAzure+1);
  wlpt->SetLineColor(kAzure+1);
  wp10->SetLineColor(kRed);
  wp15->SetLineColor(kRed+1);
  wp20->SetLineColor(kRed+2);
  

  top->SetFillColor(kMagenta);
  z->SetFillColor(kOrange);
  qcd->SetFillColor(kGray+2);
  w->SetFillColor(kAzure+1);
  wlpt->SetFillColor(kAzure+1);
  wp10->SetFillColor(kRed);
  wp15->SetFillColor(kRed+1);
  wp20->SetFillColor(kRed+2);

  const int fill_style_bgd = 3001;
  const int fill_style_sig = 3001;

  top->SetFillStyle(fill_style_bgd);
  z->SetFillStyle(fill_style_bgd);
  qcd->SetFillStyle(fill_style_bgd);
  w->SetFillStyle(fill_style_bgd);
  wlpt->SetFillStyle(fill_style_bgd);
  
  wp10->SetFillStyle(fill_style_sig);
  wp15->SetFillStyle(fill_style_sig);
  wp20->SetFillStyle(fill_style_sig);
  
  hs->Add(z);
  hs->Add(qcd);  
  hs->Add(top);
  hs->Add(w);
  hs->Add(wlpt);
  

  // this is needed when background is eliminated and the y-axis is linear (as opposed to log)
  if(data->GetMaximum() < wp10->GetMaximum())data->SetMaximum(wp10->GetMaximum());
  // this is needed when background is zero in the tails and wprime (say at 2.0 TeV) is not displayed
  if(data->GetMinimum() < 0.00001)data->SetMinimum(0.00001);

  if (i == Num_selection_cuts-1)
    {
      string desc = "";
      if(option == 1)
	desc = " p_{T} distribution";
      else if(option == 2)
	desc = " muon + (ckt-corrected) pfMET M_{T} distribution";
      string new_title = algo_desc_long[tracking_option] + desc;
      data->SetTitle(new_title.c_str());
    }
  //data->SetMarkerStyle(20);
  //data->SetMarkerSize(1.3);
  data->SetMarkerStyle(8);
  //data->SetMarkerSize(1.2);
  if(option == 1)
    {
      data->GetXaxis()->SetTitle("Muon p_{T} (GeV/c)");
      data->GetXaxis()->SetRangeUser(25, 500);
    }
  else if(option == 2)
    {
      data->GetXaxis()->SetTitle("M_{T} (GeV/c^{2})");
      data->GetXaxis()->SetRangeUser(50, 800);
    }
  data->Draw("e");
  hs->Draw("same");
  
  wp10->Draw("same");
  wp15->Draw("same");
  wp20->Draw("same");

  char temp2[1024]; sprintf(temp2, " data (%4.2f pb^{-1})", Lumi_ipb);
  
  TLegend * lg = new TLegend(0.59, 0.67, 0.89, 0.89);
  lg->SetTextSize(0.03);
  lg->SetBorderSize(0);
  lg->SetFillColor(0);
  lg->AddEntry(z, "Drell Yan (Z/Z*)", "F");
  lg->AddEntry(qcd, "QCD", "F");
  lg->AddEntry(top, "Top", "F");
  lg->AddEntry(w, "W/W*", "F");
  lg->AddEntry(wp10, "W ' (1.0 TeV)", "F");
  lg->AddEntry(wp15, "W ' (1.5 TeV)", "F");
  lg->AddEntry(wp20, "W ' (2.0 TeV)", "F");
  lg->AddEntry(data, temp2, "LP");
  lg->Draw();

  string desc2 = "";
  if(option == 1)
    desc2 = "MuPt";
  else
    desc2 = "TM";
  char temp3[1024]; sprintf(temp3, "_%4.2fipb_", Lumi_ipb);
  string file = desc2 + temp3 + cuts_desc_short[i] + ".gif";
  c1->SaveAs(file.c_str());
  //  delete c1;

}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
int main (int argc, char ** argv) {

  // check number of inpt parameters
  if(argc < 2){
    cerr<<"Forgot to parse the cfg file --> exit "<<endl;
    return -1;
  }

  // Set Root style from global enviroment path                                                                                                                               
  string ROOTStyle;
  if(getenv ("ROOTStyle")!=NULL){
    ROOTStyle = getenv ("ROOTStyle");
    gROOT->ProcessLine((".x "+ROOTStyle+"/setTDRStyle.C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetPadTopMargin(0.09);
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetErrorX(0.5);


  // parse config file parameter
  if (gConfigParser) return 1 ;
  gConfigParser = new ConfigParser();

  TString config ; 
  config.Form("%s",argv[1]);

  if(!(gConfigParser->init(config))){
      cout << ">>> parseConfigFile::Could not open configuration file " << config << endl;
      return -1;
  }

  // import base directory where samples are located and txt file with the directory name + other info
  string InputBaseDirectory  = gConfigParser -> readStringOption("Input::InputBaseDirectory");

  // import from cfg file the cross section value for this sample
  float CrossSection   = gConfigParser -> readFloatOption("Input::CrossSection");

  // total number of events
  int maxEventNumber   = gConfigParser -> readFloatOption("Input::EventsNumber");

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

  // take the cut list
  string InputCutList  = gConfigParser -> readStringOption("Input::InputCutList");

  // Read the cut file
  vector <cutContainer> CutList;
  if(ReadInputCutFile(InputCutList,CutList) <= 0){
    cerr<<" Empty Cut List File or not Exisisting --> Exit "<<endl; return -1;}

  // take the variable list to be plotted
  string InputVariableList  = gConfigParser -> readStringOption("Input::InputVariableList");
  vector<variableContainer> variableList;

  if(ReadInputVariableFile(InputVariableList,variableList) <= 0 ){
    cerr<<" Empty Variable List File or not Exisisting --> Exit "<<endl; return -1;}

  // take lumi and other parameters
  float lumi  =  gConfigParser -> readFloatOption("Option::Lumi"); // fb^(-1)
  lumi *= 1000. ;   // transform into pb^(-1)

  finalStateString    = gConfigParser -> readStringOption("Option::finalStateString");

  matchingCone        = gConfigParser -> readFloatOption("Option::matchingCone"); 
  minLeptonCleaningPt = gConfigParser -> readFloatOption("Option::minLeptonCleaningPt"); 
  minLeptonCutPt      = gConfigParser -> readFloatOption("Option::minLeptonCutPt");
  minJetCutPt         = gConfigParser -> readFloatOption("Option::minJetCutPt");
  usePuppiAsDefault   = gConfigParser -> readBoolOption("Option::usePuppiAsDefault");
  leptonIsoCut_mu     = gConfigParser -> readFloatOption("Option::leptonIsoCutMu");
  leptonIsoCut_el     = gConfigParser -> readFloatOption("Option::leptonIsoCutEl");
  leptonIsoCutLoose   = gConfigParser -> readFloatOption("Option::leptonIsoCutLoose");

  // output directory
  string outputPlotDirectory = gConfigParser -> readStringOption("Output::outputPlotDirectory");
  system(("mkdir -p output/"+outputPlotDirectory).c_str());
  system(("rm -r output/"+outputPlotDirectory+"/*").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/xs").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/norm").c_str());


  ///// Start the analysis  
  map<string,TH1F*> histoCutEff ;

  TChain* chain = new TChain (treeName.c_str()) ;  
  chain->Add ((InputBaseDirectory+"/*.root").c_str()) ;
  int totEvent = chain->GetEntries();

  readTree* reader  = new readTree((TTree*)(chain));

  cout<<"Lumi (fb-1) "<<lumi/1000<<" entries before "<<totEvent<<" cross section "<<CrossSection<<" Nevents before selections "<<lumi*CrossSection<<" weight "<<lumi*CrossSection/float(totEvent)<<endl;

  float weight = 1.0*lumi*CrossSection/float(totEvent) ;

  // make the plot container 
  vector<histoContainer> plotVector;

  for(size_t iCut = 0; iCut < CutList.size(); iCut++){
    histoCutEff["WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName] = new TH1F(("WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName).c_str(),"",15,0,15);
    for(size_t iVar = 0; iVar < variableList.size(); iVar++){
      plotVector.push_back(histoContainer(CutList.at(iCut).cutLayerName,variableList.at(iVar)));
    }
  }

  int passingLHEFilter = 0 ;
  
  int maximumEvents = chain->GetEntries () ;
  if (maxEventNumber > 0 && maxEventNumber < maximumEvents) 
    maximumEvents = maxEventNumber ;
  
  // Loop on the events
  for(int iEvent = 0; iEvent < maximumEvents ; iEvent++){

    reader->fChain->GetEntry(iEvent) ;

    if (iEvent % 100000 == 0) cout << "reading event " << iEvent << "\n" ;

    // filter LHE level leptons
    if(TString(finalStateString).Contains("UU")){
      if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) != 13)
        continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) != 11) continue;
    }
    else if(TString(finalStateString).Contains("EU")){
      if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) !=13) continue ;
    }
    else if(TString(finalStateString).Contains("UE")){
      if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) !=11) continue ;
    }
    else{
      cerr<<"problem with lhe level filter definition --> skip event"<<endl;
      continue;
    }

    passingLHEFilter++;

    // if an event pass the cut, fill the associated map                                                              
    leptonContainer lepton1,lepton2,parton1,parton2,neutrino1,neutrino2,vboson1,vboson2;

    lepton1.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt1,reader->leptonLHEeta1,reader->leptonLHEphi1,reader->leptonLHEm1);
    lepton1.charge_  = reader->leptonLHEch1;
    lepton1.flavour_ = reader->leptonLHEpid1;  

    lepton2.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt2,reader->leptonLHEeta2,reader->leptonLHEphi2,reader->leptonLHEm2);
    lepton2.charge_  = reader->leptonLHEch2;
    lepton2.flavour_ = reader->leptonLHEpid2;  

    parton1.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt1,reader->jetLHEPartoneta1,reader->jetLHEPartonphi1,0.);
    parton2.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt2,reader->jetLHEPartoneta2,reader->jetLHEPartonphi2,0.);

    neutrino1.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt1,reader->neutrinoLHEeta1,reader->neutrinoLHEphi1,0.);
    neutrino1.charge_  = 0.;
    neutrino1.flavour_ = reader->neutrinoLHEpid1;  

    neutrino2.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt2,reader->neutrinoLHEeta2,reader->neutrinoLHEphi2,0.);
    neutrino2.charge_  = 0.;
    neutrino2.flavour_ = reader->neutrinoLHEpid2;  

    vboson1.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt1,reader->vbosonLHEeta1,reader->vbosonLHEphi1,reader->vbosonLHEm1);
    vboson1.charge_  = reader->vbosonLHEch1;
    vboson1.flavour_ = reader->vbosonLHEpid1;  
    
    vboson2.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt2,reader->vbosonLHEeta2,reader->vbosonLHEphi2,reader->vbosonLHEm2);
    vboson2.charge_  = reader->vbosonLHEch2;
    vboson2.flavour_ = reader->vbosonLHEpid2;  

    float minDR_1 = 999;
    float minDR_2 = 999;

    vector<leptonContainer> lepton, neutrino;
    lepton.push_back(lepton1);
    lepton.push_back(lepton2);
    neutrino.push_back(neutrino1);
    neutrino.push_back(neutrino2);

    leptonContainer leptFromV1, leptFromV2, neuFromV1, neuFromV2;

    for(size_t iLep= 0; iLep < lepton.size(); iLep++){
      for(size_t iNeu = 0; iNeu < neutrino.size(); iNeu++){
	if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_) < minDR_1 ){
	  minDR_1    = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_);
	  leptFromV1 = lepton.at(iLep);
	  neuFromV1  = neutrino.at(iNeu);
	}

	if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_) < minDR_2){
	  minDR_2    = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_);
	  leptFromV2 = lepton.at(iLep);
	  neuFromV2  = neutrino.at(iNeu);
	}	

      }
    }

    if(leptFromV1.lepton4V_ == leptFromV2.lepton4V_ or neuFromV1.lepton4V_ == neuFromV2.lepton4V_){
      cerr<<" bad matching with gen W "<<endl;
      continue;
    }
		       

    double costheta1 = 0;
    double costheta2 = 0;
    double Phi  = 0;
    double costhetastar  = 0;
    double Phi1  = 0;

    double costheta1_vbf = 0;
    double costheta2_vbf = 0;
    double Phi_vbf = 0;
    double costhetastar_vbf = 0;
    double Phi1_vbf = 0;


    TLorentzVector VV = vboson1.lepton4V_ + vboson2.lepton4V_;

    if(leptFromV1.charge_ > 0  and leptFromV2.charge_ > 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);
    }
    else if(leptFromV1.charge_ < 0  and leptFromV2.charge_ < 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);

    }

    else if(leptFromV1.charge_ < 0  and leptFromV2.charge_ > 0){
      computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);
    }
    else if(leptFromV1.charge_ > 0  and leptFromV2.charge_ < 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);

    }
    else{ cerr<<" wrong charge composition "<<endl;
      continue;
    }
    
    float mTR = 0;
    float mR  = 0;

    TLorentzVector L_met ,L_dijet, L_dilepton, L_LLmet; 

    L_met      = neutrino1.lepton4V_ + neutrino2.lepton4V_;
    L_dijet    = parton1.lepton4V_   + parton2.lepton4V_;
    L_dilepton = lepton1.lepton4V_   + lepton2.lepton4V_;
    L_LLmet    = L_dilepton + L_met ;

    computeRazor(lepton1.lepton4V_,lepton2.lepton4V_,L_met,mTR,mR);

    if(lepton1.lepton4V_.Pt() < minLeptonCutPt or lepton2.lepton4V_.Pt() < minLeptonCutPt) continue;

    // Loop  on the cut list --> one cut for each polarization
    for(size_t iCut = 0; iCut < CutList.size(); iCut++){

      // cut the events
      string name = "WW_EWK";
      if(!passCutContainerSelection(reader,
                                    CutList.at(iCut),
                                    name,
				    int(iCut),
                                    usePuppiAsDefault,
                                    minLeptonCutPt,
                                    minLeptonCleaningPt,
                                    leptonIsoCut_mu,
                                    leptonIsoCut_el,
                                    leptonIsoCutLoose,
                                    matchingCone,
                                    minJetCutPt,
                                    histoCutEff,
				    finalStateString)) continue;

      
      float asimL = (lepton1.lepton4V_.Pt()-lepton2.lepton4V_.Pt())/(lepton1.lepton4V_.Pt()+lepton2.lepton4V_.Pt()) ;


      float asimJ    = (parton1.lepton4V_.Pt()-parton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()+parton2.lepton4V_.Pt()) ;
      float Rvar     = (lepton1.lepton4V_.Pt()*lepton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()*parton2.lepton4V_.Pt()) ;

      // loop on variables
      for(size_t iVar = 0; iVar < variableList.size(); iVar++){
        histoContainer tmpPlot;
        tmpPlot.cutName = CutList.at(iCut).cutLayerName;
        tmpPlot.varName = variableList.at(iVar).variableName;
        vector<histoContainer>::iterator itVec ;
        itVec = find(plotVector.begin(),plotVector.end(),tmpPlot);
        if(itVec == plotVector.end()){
          cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<"  "<<variableList.at(iVar).variableName<<endl;
          continue ;
        }
	
	// vector boson info
	if(variableList.at(iVar).variableName == "ptV1"){
          itVec->histogram->Fill(vboson1.lepton4V_.Pt(),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "ptV2"){
          itVec->histogram->Fill(vboson2.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaV1"){
          itVec->histogram->Fill(vboson1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaV2"){
          itVec->histogram->Fill(vboson2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptVV"){
          itVec->histogram->Fill(L_dijet.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mVV"){
          itVec->histogram->Fill(L_dijet.M(),weight) ;
        }

	// decay information
	if(variableList.at(iVar).variableName == "costheta1"){
          itVec->histogram->Fill(fabs(costheta1),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "costheta2"){
          itVec->histogram->Fill(fabs(costheta2),weight) ;
        }
	if(variableList.at(iVar).variableName == "costheta1_vbf"){
          itVec->histogram->Fill(fabs(costheta1_vbf),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "costheta2_vbf"){
          itVec->histogram->Fill(fabs(costheta2_vbf),weight) ;
        }

	if(variableList.at(iVar).variableName == "Phi"){
          itVec->histogram->Fill(fabs(Phi),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "Phi1"){
          itVec->histogram->Fill(fabs(Phi1),weight) ;
        }
	if(variableList.at(iVar).variableName == "Phi_vbf"){
          itVec->histogram->Fill(fabs(Phi_vbf),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "Phi1_vbf"){
          itVec->histogram->Fill(fabs(Phi1_vbf),weight) ;
        }

	else if(variableList.at(iVar).variableName == "costhetastar"){
          itVec->histogram->Fill(fabs(costhetastar),weight) ;
        }
	else if(variableList.at(iVar).variableName == "costhetastar_vbf"){
          itVec->histogram->Fill(fabs(costhetastar_vbf),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mTR"){
          itVec->histogram->Fill(mTR,weight) ;
	}

	else if(variableList.at(iVar).variableName == "mR"){
          itVec->histogram->Fill(mR,weight) ;
	}

	// jet info

	if(variableList.at(iVar).variableName == "ptj1"){
          itVec->histogram->Fill(parton1.lepton4V_.Pt(),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "ptj2"){
          itVec->histogram->Fill(parton2.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaj1"){
          itVec->histogram->Fill(parton1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaj2"){
          itVec->histogram->Fill(parton2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "detajj"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.Eta()-parton2.lepton4V_.Eta()),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptjj"){
          itVec->histogram->Fill(L_dijet.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mjj"){
          itVec->histogram->Fill(L_dijet.M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "Asim_j"){
          itVec->histogram->Fill(asimJ,weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_JJ"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptl1"){
          itVec->histogram->Fill(lepton1.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptl2"){
          itVec->histogram->Fill(lepton2.lepton4V_.Pt(),weight) ;
        }
 
	else if(variableList.at(iVar).variableName == "etal1"){
          itVec->histogram->Fill(lepton1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etal2"){
          itVec->histogram->Fill(lepton2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mll"){
          itVec->histogram->Fill(L_dilepton.M(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptll"){
          itVec->histogram->Fill(L_dilepton.Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(lepton2.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "Asim_l"){
          itVec->histogram->Fill(asimL,weight) ;
        }

	else if(variableList.at(iVar).variableName == "met"){
          itVec->histogram->Fill(L_met.Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "R"){
          itVec->histogram->Fill(Rvar,weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LMet"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLMet"){
          itVec->histogram->Fill((lepton1.lepton4V_ + L_met).Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_TLMet"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTLMet"){
          itVec->histogram->Fill((lepton2.lepton4V_ + L_met).Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_LLMet"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLLMet"){
          itVec->histogram->Fill((L_dilepton + L_met).Pt(),weight) ;
        }
	///
	else if(variableList.at(iVar).variableName == "DeltaPhi_LJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_dijet)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptJJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+L_dijet).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(L_dijet)),weight) ;
        }


	else if(variableList.at(iVar).variableName == "ptLJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptTJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptJJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+L_dijet).Pt(),weight) ;
        }

 
	else if(variableList.at(iVar).variableName == "DeltaPhi_LJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton1.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_dijet)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptLJLL"){
          itVec->histogram->Fill((L_dilepton+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptTJLL"){
          itVec->histogram->Fill((L_dilepton+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptJJLL"){
          itVec->histogram->Fill((L_dilepton+L_dijet).Pt(),weight) ;
        }

	///
	else if(variableList.at(iVar).variableName == "DeltaPhi_JJMet"){
          itVec->histogram->Fill(fabs(L_dijet.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptJJMet"){
          itVec->histogram->Fill((L_dijet+L_met).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LJMet"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLJMet"){
          itVec->histogram->Fill((parton1.lepton4V_+L_met).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJMet"){
          itVec->histogram->Fill(fabs(parton2.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTJMet"){
          itVec->histogram->Fill((parton2.lepton4V_+L_met).Pt(),weight) ;
        }
 
	else if(variableList.at(iVar).variableName == "mlljj"){
          itVec->histogram->Fill((L_dilepton+L_dijet).M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mlljjmet"){
          itVec->histogram->Fill((L_dilepton+L_dijet+L_met).M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mTH"){
          itVec->histogram->Fill(sqrt(2*L_dilepton.Pt()*L_met.Pt()*(1-TMath::Cos(L_dilepton.DeltaPhi(L_met)))),weight) ;
        } 
      } // loop on variables
      
    } // Loop  on the cut list

  } // Loop on the events

  
  TFile* outputEfficiency = new TFile(("output/"+outputPlotDirectory+"/outputEfficiency.root").c_str(),"RECREATE");

  for(map<string,TH1F*>::const_iterator itMap = histoCutEff.begin(); itMap !=  histoCutEff.end(); itMap++){
    itMap->second->Scale(1./itMap->second->GetBinContent(1));
    itMap->second->Write();
  }

  outputEfficiency->Close();    

  
  // make the canvas and basic banners                                                                                                                                         
  TCanvas *cCanvas = new TCanvas("cCanvas","",1,52,550,550);
  cCanvas->SetTicks();
  cCanvas->SetFillColor(0);
  cCanvas->SetBorderMode(0);
  cCanvas->SetBorderSize(2);
  cCanvas->SetTickx(1);
  cCanvas->SetTicky(1);
  cCanvas->SetRightMargin(0.05);
  cCanvas->SetBottomMargin(0.12);
  cCanvas->SetFrameBorderMode(0);

  cCanvas->cd();

  TPad* upperPad = new TPad("upperPad", "upperPad", .005, .180, .995, .980);
  TPad* lowerPad = new TPad("lowerPad", "lowerPad", .005, .005, .995, .18);
  lowerPad->SetGridx();
  lowerPad->SetGridy();
  upperPad->SetLeftMargin(0.12);
  upperPad->SetRightMargin(0.1);
  lowerPad->SetLeftMargin(0.12);
  lowerPad->SetRightMargin(0.1);
  lowerPad->SetTopMargin(0.002);

  lowerPad->Draw();
  upperPad->Draw();

  TCanvas *cCanvasNorm = new TCanvas("cCanvasNorm","",1,52,550,550);
  cCanvasNorm->SetTicks();
  cCanvasNorm->SetFillColor(0);
  cCanvasNorm->SetBorderMode(0);
  cCanvasNorm->SetBorderSize(2);
  cCanvasNorm->SetTickx(1);
  cCanvasNorm->SetTicky(1);
  cCanvasNorm->SetRightMargin(0.05);
  cCanvasNorm->SetBottomMargin(0.12);
  cCanvasNorm->SetFrameBorderMode(0);

  TLatex * tex = new TLatex(0.88,0.92," 14 TeV");
  tex->SetNDC();
  tex->SetTextAlign(31);
  tex->SetTextFont(42);
  tex->SetTextSize(0.045);
  tex->SetLineWidth(2);
  TLatex * tex2 = new TLatex(0.14,0.92,"Delphes");
  tex2->SetNDC();
  tex2->SetTextFont(61);
  tex2->SetTextSize(0.045);
  tex2->SetLineWidth(2);
  TLatex * tex3 = new TLatex(0.295,0.92,"Simulation Preliminary");
  tex3->SetNDC();
  tex3->SetTextFont(52);
  tex3->SetTextSize(0.04);
  tex3->SetLineWidth(2);

  TLegend* legend = new TLegend(0.55,0.75,0.85,0.89);
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.04);
  legend->SetTextFont(42);
  legend->SetNColumns (3) ;
 
  // make the plot on the same canvas for each variable (legend entry is the cut layer name)  
  vector<TH1F*>  numerator ;
  vector<TH1F*>  denominator ;
  for(size_t iVar = 0; iVar < variableList.size(); iVar++){ // loop on var
   
    numerator.clear();
    denominator.clear();

    for(size_t iCut = 0; iCut < CutList.size(); iCut++){ // loop on cuts
        histoContainer tmpPlot;
        tmpPlot.cutName = CutList.at(iCut).cutLayerName;
        tmpPlot.varName = variableList.at(iVar).variableName;
        vector<histoContainer>::iterator itVec ;
        itVec = find(plotVector.begin(),plotVector.end(),tmpPlot);
        if(itVec == plotVector.end()){
          cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<"  "<<variableList.at(iVar).variableName<<endl;
        }

       
        itVec->histogram->GetXaxis()->SetTitleSize(0.04);
        itVec->histogram->GetXaxis()->SetTitleOffset(1.16);
        itVec->histogram->GetXaxis()->SetLabelSize(0.04);

        itVec->histogram->GetYaxis()->SetRangeUser(0.001,itVec->histogram->GetMaximum()*1.25);
        itVec->histogram->GetYaxis()->SetTitleSize(0.05);
        itVec->histogram->GetYaxis()->SetTitleOffset(1.20);
        itVec->histogram->GetYaxis()->SetLabelSize(0.04);

        itVec->histogram->SetLineColor(iCut+1);

        if(iCut %2 == 0)
          itVec->histogram->SetLineStyle(1);
        else
          itVec->histogram->SetLineStyle(2);

        itVec->histogram->SetLineWidth(2);
        itVec->histogram->GetYaxis()->SetTitle("#sigma x lumi");

        upperPad->cd();

        if(iCut == 0) 
          itVec->histogram->Draw("hist");
        else
          itVec->histogram->Draw("hist same");

        legend->AddEntry(itVec->histogram,CutList.at(iCut).cutLayerName.c_str(),"l");

        if(itVec->findCutByLabel("LL")) numerator.push_back(itVec->histogram);
        denominator.push_back(itVec->histogram);

	cCanvasNorm->cd();

	TH1F* htempNorm = (TH1F*) itVec->histogram->Clone((string(itVec->histogram->GetName())+"_norm").c_str());
	htempNorm->Scale(1./itVec->histogram->Integral());

	htempNorm->GetYaxis()->SetRangeUser(0.,htempNorm->GetMaximum()*1.5);

        if(iCut == 0)
          htempNorm->Draw("hist");
        else
          htempNorm->Draw("hist same");
    }
    
    // make ratio plot
    lowerPad->cd();
    
    TH1F* numTotal = 0;
    TH1F* denTotal = 0;
    TH1F* ratio    = 0;
    TH1F* ratioW   = 0;

    for(size_t itNum = 0; itNum < numerator.size(); itNum ++){
      if(itNum == 0 and ratio == 0) 
        numTotal = (TH1F*) numerator.at(itNum)->Clone(("Num_"+string(numerator.at(itNum)->GetName())).c_str());
      else if(ratio !=0) 
        numTotal->Add(numerator.at(itNum));
    }

    for(size_t itDen = 0; itDen < denominator.size(); itDen ++){
      if(itDen == 0 and denTotal == 0 ) {
        denTotal = (TH1F*) denominator.at(itDen)->Clone(("Den_"+string(denominator.at(itDen)->GetName())).c_str());
      }
      else if(denTotal !=0){  
        denTotal->Add(denominator.at(itDen));
      }
    }
    
    ratio = new TH1F(("Ratio_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1));
    ratio->GetYaxis()->SetTitle("S/(#sqrt{S+B})");
    ratio->SetMarkerSize(1.1);

    ratioW = new TH1F(("ratioW_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1));
    ratioW->GetYaxis()->SetTitle("weighted S/(#sqrt{S+B})");
    ratioW->SetMarkerSize(1.1);

    TString name = "norm_" ;
    name += denTotal->GetName () ;
    TH1F * norm_denTotal = (TH1F *) denTotal->Clone (name) ;
    norm_denTotal->Scale (1. / norm_denTotal->GetMaximum ()) ; 
    // weight the S/sqrt (B) by the shape of the total, 
    // so that only bins with a lot of stats become visibly significant
    for(int iBin = 0; iBin < ratio->GetNbinsX()+1; iBin++){
      if(denTotal->GetBinContent(iBin) !=0){ 
        ratioW->SetBinContent(iBin,
			      norm_denTotal->GetBinContent (iBin) * numTotal->GetBinContent(iBin) / 
			      sqrt(denTotal->GetBinContent(iBin)));
        ratio->SetBinContent(iBin,
			     numTotal->GetBinContent(iBin) / sqrt(denTotal->GetBinContent(iBin)));
      }
      else 
	ratio->SetBinContent(iBin,0.);
    }
 
    ratio->GetXaxis()->SetTitle("");
    ratio->SetLineColor(kBlue);
    ratio->SetLineStyle(2);
    ratio->SetLineWidth(2);
    ratio->GetXaxis()->SetLabelOffset(999);
    ratio->GetXaxis()->SetLabelSize(0);
    ratio->GetYaxis()->SetLabelSize(0.15);
    ratio->GetYaxis()->SetTitleSize(0.15);
    ratio->GetYaxis()->SetTitleOffset(0.30);
    ratio->GetYaxis()->SetNdivisions(504);

    ratioW->GetXaxis()->SetTitle("");
    ratioW->SetLineColor(kBlack);
    ratioW->SetLineWidth(2);
    ratioW->GetXaxis()->SetLabelOffset(999);
    ratioW->GetXaxis()->SetLabelSize(0);
    ratioW->GetYaxis()->SetLabelSize(0.15);
    ratioW->GetYaxis()->SetTitleSize(0.15);
    ratioW->GetYaxis()->SetTitleOffset(0.30);
    ratioW->GetYaxis()->SetNdivisions(504);

    ratio->GetYaxis()->SetRange(min(ratio->GetMinimum(),ratioW->GetMinimum())*0.9,max(ratio->GetMaximum(),ratioW->GetMaximum())*1.1);    


    TH1F * frame = lowerPad->DrawFrame (ratio->GetXaxis ()->GetXmin (), 0., 
                                        ratio->GetXaxis ()->GetXmax (), 2.) ;
    frame->GetXaxis()->SetTitle (ratio->GetXaxis ()->GetTitle ()) ;
    frame->GetYaxis()->SetTitle (ratio->GetYaxis ()->GetTitle ()) ;
    frame->GetXaxis()->SetLabelOffset(999);
    frame->GetXaxis()->SetLabelSize(0);
    frame->GetYaxis()->SetLabelSize(0.15);
    frame->GetYaxis()->SetTitleSize(0.15);
    frame->GetYaxis()->SetTitleOffset(0.30);
    frame->GetYaxis()->SetNdivisions(504);

    ratio->Draw("P");    
    ratioW->Draw("Lsame");    
    
    upperPad->cd();
    
    tex->Draw("same");
    tex2->Draw("same");
    tex3->Draw("same");
    legend->Draw("same");

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".png").c_str(),"png");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".root").c_str(),"root");

    cCanvasNorm->cd();

    tex->Draw("same");
    tex2->Draw("same");
    tex3->Draw("same");
    legend->Draw("same");

    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf");
    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".png").c_str(),"png");
    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".root").c_str(),"root");

    
    legend->Clear();
    
  } // loop on var

  cout<<"LHE filter efficiency : "<<passingLHEFilter<<" totEvent "<<totEvent<<" efficiency "<<float(passingLHEFilter)/float(totEvent)*100<<" % "<<endl;
  
  //Normalize histograms
  for(size_t ihisto = 0; ihisto < plotVector.size(); ihisto++){
    if(plotVector.at(ihisto).varName == "DeltaPhi_LL")
      cout<<"Events Histo "<<plotVector.at(ihisto).histogram->GetName()<<" unweighted "<<plotVector.at(ihisto).histogram->GetEntries()<<" weighted "<<plotVector.at(ihisto).histogram->Integral(0,plotVector.at(ihisto).histogram->GetNbinsX()+1)<<endl;
  }	          

  return 0 ;
}  
Beispiel #10
0
void plotMVAOutput( bool printgif = false ){

  //gROOT->ProcessLine(".x selection.h");

  //char* path    = "Trainings/H130_WWTo2L2Nu/output";
  //char* path    = "Trainings/H130_WWTo2L2Nu_WJetsToLNu/output";
  char* path    = "Trainings/H130_allbkg_4vars/output";

  //char* mvaname = "MVA_PDERS";
  //char* mvaname = "MVA_MLPBNN";
  //char* mvaname = "MVA_BDT";
  //char* mvaname = "LikelihoodPCA";

  vector<char*> mvanames;
  mvanames.push_back("BDT");
  mvanames.push_back("MLPBNN");
  const unsigned int nmva = mvanames.size();

  int rebin     = 10;
  int colors[]  = { 5 , 2 , 4 , 3 , 7 , 8 , 6 , 9 , 10};

  vector<char*> samples;
  samples.push_back("WWTo2L2Nu");
  samples.push_back("GluGluToWWTo4L");
  samples.push_back("WZ");
  samples.push_back("ZZ");
  samples.push_back("TTJets");
  samples.push_back("tW");
  samples.push_back("WJetsToLNu");
  samples.push_back("DY");
  const unsigned int nsamples = samples.size();

  char* higgssample = "Higgs130";
  //char* higgssample = "Higgs160";
  //char* higgssample = "Higgs200";

  TCanvas *can[nmva];


  for( unsigned int imva = 0 ; imva < nmva ; ++imva ){


    TFile*   file     = new TFile();
    TH1F*    hist     = new TH1F();
    TH1F*    bkghist  = new TH1F();
    THStack* bkgstack = new THStack("bkgstack","bkgstack");
    TLegend *leg      = new TLegend(0.3,0.7,0.5,0.9);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);

    //loop over backgrounds
    for( unsigned int i = 0 ; i < nsamples ; ++i ){

      file = TFile::Open(Form("%s/%s.root",path,samples.at(i)));
      hist = cloneHist( (TH1F*) file->Get( Form("MVA_%s",mvanames.at(imva) ) ) );
   
      hist->SetFillColor(colors[i]);
    
      leg->AddEntry(hist,samples.at(i),"f");
  
      if( i == 0 ) bkghist = (TH1F*) hist->Clone();
      else         bkghist -> Add(hist);

      hist->Rebin( rebin );
      bkgstack->Add(hist);

    }

    //higgs sample
    file = TFile::Open(Form("%s/%s.root",path,higgssample));
    TH1F* higgshist = cloneHist( (TH1F*) file->Get( Form("MVA_%s",mvanames.at(imva) ) ) );
    higgshist->SetLineWidth(2);
    leg->AddEntry(higgshist,higgssample,"l");



    float bkg    = 0;
    float sig    = 0;
    float minbkg = 1.48;
    //float minbkg = 1.10;
    float cut    = 0.;

    for( int ibin = 1 ; ibin < bkghist->GetNbinsX() ; ibin++ ){

      bkg = bkghist->Integral( ibin , 10000 );
      sig = higgshist->Integral( ibin , 10000 );

      if( bkg < minbkg ){
        cut = bkghist->GetBinCenter(ibin);
        cout << endl;
        cout << "S/B       " << sig/bkg    << endl;
        cout << "Sig       " << sig        << endl;
        cout << "Bkg       " << bkg        << endl;
        cout << "cut value " << cut        << endl;
        break;
      }

    }

    float cutsig = sig;
    float cutbkg = bkg;
 
    float maxfom      = -1;
    float maxfom_sig  = -1;
    float maxfom_bkg  = -1;
    float cutval      = -1;
  

    for( int ibin = 1 ; ibin < bkghist->GetNbinsX() ; ibin++ ){

      bkg = bkghist->Integral( ibin , 10000 );
      sig = higgshist->Integral( ibin , 10000 );

      float fom = sig / sqrt( sig + bkg + pow( 0.35 * bkg , 2 ) );
    
      if( fom > maxfom ){
        maxfom  = fom;
        maxfom_sig = sig;
        maxfom_bkg = bkg;
        cutval  = bkghist->GetBinCenter(ibin);
      }

    }

    cout << endl;
    cout << "Max FOM   " << maxfom        << endl;
    cout << "Sig       " << maxfom_sig    << endl;
    cout << "Bkg       " << maxfom_bkg    << endl;
    cout << "cut value " << cutval        << endl;


    bkghist->Rebin( rebin );
    higgshist->Rebin( rebin );

    can[imva] = new TCanvas(Form("can_%i",imva),Form("can_%i",imva),800,600);
    can[imva]->cd();

    //gPad->SetLogy();
    bkghist->GetXaxis()->SetTitle(Form("%s output",mvanames.at(imva)));
    bkghist->Draw();
    bkgstack->Draw("same");
    higgshist->Scale(10.);
    higgshist->Draw("same");
    bkghist->Draw("axissame");
    //leg->Draw();

    TLatex *t = new TLatex();
    t->SetNDC();
    t->SetTextColor(2);
    t->DrawLatex(0.2,0.85,Form("FOM: %.2f",maxfom));
    t->SetTextColor(1);
    t->DrawLatex(0.2,0.80,Form("Sig: %.2f",maxfom_sig));
    t->DrawLatex(0.2,0.75,Form("Bkg: %.2f",maxfom_bkg));

    t->SetTextColor(4);
    t->DrawLatex(0.2,0.55,Form("S/B: %.2f",cutsig/cutbkg));
    t->SetTextColor(1);
    t->DrawLatex(0.2,0.50,Form("Sig: %.2f",cutsig));
    t->DrawLatex(0.2,0.45,Form("Bkg: %.2f",cutbkg));
  
    TLine  line;
    line.SetLineColor(2);
    line.DrawLine( cutval , bkghist->GetMinimum() , cutval , 1.05 * bkghist->GetMaximum() );
    line.SetLineColor(4);
    line.DrawLine( cut , bkghist->GetMinimum() , cut , 1.05 * bkghist->GetMaximum() );

    if( printgif ) can[imva]->Print(Form("plots/%s.gif",mvanames.at(imva)));
  }
}
Beispiel #11
0
void plotSingleBackground(TFile *f, float xfit, float xcut, bool isMu) {
  TH1F *h = f->Get("decayLengthSignificance2D_BackgroundMC");

  h->SetMarkerColor(kBlack);
  h->SetMarkerStyle(kFullSquare);

  gPad->SetLeftMargin(0.15);
  gPad->SetBottomMargin(0.15);
  gPad->SetTopMargin(0.10);
  gPad->SetRightMargin(0.04);

  h->GetXaxis()->SetTitle("L_{xy}/#sigma");
  h->GetYaxis()->SetTitle("Number of background events");
  h->GetYaxis()->SetTitleOffset(1.2);
  h->Draw();
  gPad->SetLogy();
  
  float xmax = h->GetXaxis()->GetXmax();
  float ymax = h->GetMaximum();

  TF1 *f1 = new TF1("f1", "[0]*exp(-x/[1]) + [2]*exp(-x/[3])");
  if (isMu) {
    f1->SetParameter(0, 750);
    f1->SetParameter(1, 0.25);
    f1->SetParameter(2, 90);
    f1->SetParameter(3, 0.6);
  } else {
    f1->SetParameter(0, 35);
    f1->SetParameter(1, 0.4);
    f1->SetParameter(2, 2);
    f1->SetParameter(3, 3);
  }

  float fitmin = 0;
  //if (!isMu) fitmin = 3;
  h->Fit(f1, "EM", "", fitmin, xfit);

  f1->SetLineColor(kRed);

  TF1 *f2 = new TF1("f2", "[0]*exp(-x/[1]) + [2]*exp(-x/[3])", xfit, xmax);
  for (int i=0; i<=3; i++)
    f2->SetParameter(i, f1->GetParameter(i));
  f2->SetLineColor(kRed);
  f2->SetLineStyle(kDashed);
  f2->Draw("same");
  
  if (!isMu) {
    TLine *l1 = new TLine(xfit, h->GetMinimum(), xfit, ymax);
    l1->SetLineColor(kRed);
    l1->SetLineWidth(2);
    l1->SetLineStyle(kDashed);
    l1->Draw();
  }

  TLine *l2 = new TLine(xcut, h->GetMinimum(), xcut, ymax);
  l2->SetLineColor(kBlue);
  l2->SetLineWidth(2);
  l2->SetLineStyle(kDashed);
  l2->Draw();

  TArrow *a2 = new TArrow(xcut, ymax/50, xcut+2, ymax/50, 0.02, "|>");
  a2->SetLineWidth(2);
  a2->SetLineColor(kBlue);
  a2->SetFillColor(kBlue);
  a2->Draw();
  TText *at2 = new TText(xcut+2.5, ymax/50, "Signal region");
  at2->SetTextSize(0.03);
  at2->SetTextColor(kBlue);
  at2->SetTextAlign(12);
  at2->Draw();

  TLatex *t1;
  if (isMu) {
    h->SetTitle("CMS Preliminary #sqrt{s}=7 TeV L=1.2 fb^{-1}"); 
    t1 = new TLatex(xmax-4, ymax/5, "#mu^{+}#mu^{-}");
  } else {
    h->SetTitle("CMS Preliminary #sqrt{s}=7 TeV L=1.1 fb^{-1}"); 
    t1 = new TLatex(xmax-4, ymax/5, "e^{+}e^{-}");
  }
  t1->SetTextFont(42);
  t1->Draw();

  float intbkgnd = f2->Integral(xcut, xmax);

  TF1 *f3 = f2->Clone("f3");
  float interr2 = 0;
  float errplus2 = 0;
  float errminus2 = 0;
  for (int i=0; i<4; i++) {
    f3->SetParameter(i, f1->GetParameter(i)+f1->GetParError(i));
    float intplus = f3->Integral(xcut, xmax);
    f3->SetParameter(i, f1->GetParameter(i)-f1->GetParError(i));
    float intminus = f3->Integral(xcut, xmax);
    f3->SetParameter(i, f1->GetParameter(i));
    float interr = (intplus - intminus)/2;
    interr2 += interr*interr;
    errplus2 += (intplus - intbkgnd)*(intplus - intbkgnd);
    errminus2 += (intbkgnd - intminus)*(intbkgnd - intminus);
  }  
  //std::cout << intplus << " " << intminus << std::endl;
  // float interr = (intplus - intminus)/2;
  float interr = sqrt(interr2);
  float errplus = sqrt(errplus2);
  float errminus = sqrt(errminus2);

  std::cout << "Integral from " << xcut << " to " << xmax << " = " << intbkgnd
	    << " + " << errplus << " - " << errminus
	    << " (+/- " << interr << ")" << std::endl;

}
Beispiel #12
0
//---------------------------------------------------------------
double *binnedFit(TString fiName, vector<double> xlim, double mtop, TLatex *channel_tex, TString outdir, double lumi)
//---------------------------------------------------------------
{
  using namespace RooFit;
  // reduce RooFit's verbosity on the INFO level
  RooMsgService::instance().getStream(1).removeTopic(Minimization);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(ObjectHandling);
  RooMsgService::instance().getStream(1).removeTopic(Eval);
  RooMsgService::instance().getStream(1).removeTopic(Fitting);
  RooMsgService::instance().setSilentMode(true);
  RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);

  TFile *res = TFile::Open(fiName);

  RooRealVar mtl("mass", "M_{J/#psi+l}", 0., 250., "GeV");
  //RooRealVar mean("mean", "mass", (xlim[1]+xlim[0])/2., (xlim[1]+3.*xlim[0])/4., (3.*xlim[1]+xlim[0])/4.);
  RooRealVar mean("mean", "mass", 70., 60., 80.);
  RooRealVar width("width", "width", 25., 15., 40.);

  TH1F *histo = (TH1F*)res->Get("MTriLept-allPair");
  h_myStyle(histo,38,38,3002,histo->GetMinimum(),1.2*histo->GetMaximum(),510,510,20,38,1.,0.);
  RooDataHist *datahist = new RooDataHist("datahist", "datahist", RooArgList(mtl), histo, 1.);
  RooGaussian pdf("gaus", "gaus", mtl, mean, width);
  pdf.fitTo(*datahist, Range(xlim[0], xlim[1]), SumW2Error(kTRUE), PrintLevel(-1), PrintEvalErrors(-1));

  TCanvas *cn = new TCanvas("cn", "cn", 800, 800);
  cn->cd();
  RooPlot *massframe = mtl.frame();
  datahist->plotOn(massframe, MarkerColor(38), LineColor(38), DataError(RooAbsData::SumW2));
  pdf.plotOn(massframe, LineColor(38), Range(xlim[0], xlim[1]));
  massframe->Draw();
  histo->Draw("samehist");
  TLegend *leg = new TLegend(0.58,0.82,0.93,0.92,NULL,"brNDC");
  if (mtop < 1e-6)
    leg->SetHeader(TString::Format("#tilde{M}_{J/#psi+l} = (%3.1f #pm %3.1f) GeV", mean.getVal(), mean.getError()));
  else
    leg->SetHeader(TString::Format("#splitline{M_{t}^{gen} = %3.1f GeV}{#tilde{M}_{J/#psi+l} = (%3.1f #pm %3.1f) GeV}", mtop+0.5, mean.getVal(), mean.getError()));
  leg_myStyle(leg);
  leg->Draw("same");
  channel_tex->Draw("same");
  if (mtop < 1e-6)
    cms_myStyle(lumi, true);
  else
    cms_myStyle(lumi, false);
  TString outFile = outdir;
  if (mtop < 1e-6)
    outFile += "GausianBinnedFit_Data";
  else
    outFile += TString::Format("GaussianBinnedFit_%d_5", (int)mtop);
  cn->SaveAs(outFile+".pdf");
  cn->SaveAs(outFile+".C");
  cn->SaveAs(outFile+".jpg");
  cn->SaveAs(outFile+".eps");

  res->Close();

  double *mean_err = new double[2];
  mean_err[0] = mean.getVal();
  mean_err[1] = mean.getError();

  return mean_err;
}