Ejemplo n.º 1
0
bool isgood(TH1F h, float sigma){
  if(sigma == -1) return true;
  bool Flag = true;
  int imaxbin = h.GetMaximumBin();
  float bincenter = h.GetBinCenter(imaxbin);
  for(int ibin=0;ibin<h.GetNbinsX();ibin++){
      if((h.GetBinCenter(ibin)<(bincenter-sigma)) || (h.GetBinCenter(ibin)>(bincenter+sigma))){
          if(h.GetBinContent(ibin)!=0){
              Flag = false;
              break;
          }
      }
  }

  if(Flag){
  h.SetBinContent(imaxbin,0);
  imaxbin = h.GetMaximumBin();
  bincenter = h.GetBinCenter(imaxbin);
  for(int ibin=0;ibin<h.GetNbinsX();ibin++){
      if((h.GetBinCenter(ibin)<(bincenter-sigma)) || (h.GetBinCenter(ibin)>(bincenter+sigma))){
          if(h.GetBinContent(ibin)!=0){
              Flag = false;
              break;
          }
      }
  }
  }
  return Flag;
}
Ejemplo n.º 2
0
void VetoTimes()
{
  TH1F* Time;
  Char_t Buff[256];

  for(Int_t ch=0; ch<384; ch++)
  {
    sprintf(Buff, "Veto_Time%d", ch);
    Time = (TH1F*)gROOT->FindObject(Buff);
    printf("%6.1f\n", (Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 500.0)/0.05000);
  }
}
Ejemplo n.º 3
0
void PIDPedes()
{
  TH1F* Energy;
  Char_t Buff[256];

  for(Int_t ch=0; ch<24; ch++)
  {
    sprintf(Buff, "PID_Energy%d", ch);
    Energy = (TH1F*)gROOT->FindObject(Buff);
    printf("%4.0f\n", Energy->GetMaximumBin()*Energy->GetBinWidth(Energy->GetMaximumBin()));
  }
}
Ejemplo n.º 4
0
void PIDTimes()
{
  TH1F* Time;
  Char_t Buff[256];

  for(Int_t ch=0; ch<24; ch++)
  {
    sprintf(Buff, "PID_Time%d", ch);
    Time = (TH1F*)gROOT->FindObject(Buff);
    printf("%5.1f\n", Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 200.0);
  }
}
Ejemplo n.º 5
0
void LadderTimes()
{
  TH1F* Time;
  Double_t par[4];
  Double_t Max;
  Char_t Buff[256];

  for(Int_t ch=0; ch<352; ch++)
  {
    sprintf(Buff, "Ladder_Time%d", ch);
    Time = (TH1F*)gROOT->FindObject(Buff);
    Max = Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 1000.0;
   
    TF1* gauss = new TF1("gauss", "gaus", Max-8, Max+8);
    Time->Fit(gauss, "RQ+");
    gauss->GetParameters(&par[0]);
    
    printf("%5.2f\n", par[1]/0.117710);
  }
}
Ejemplo n.º 6
0
void AlignTopAndBottomTOFs(string ArrayPart="NV",Float_t Start=-5,Float_t End=25){
  
  for (int bar=1;bar<13;bar++){
    stringstream nameTop;
    stringstream nameBottom;

    nameTop<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_TopCutTOFPr";
    TH1F * CurrentTop = (TH1F*)gDirectory->Get(nameTop.str().c_str());


    nameBottom<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_BottomCutTOFPr";
    TH1F * CurrentBottom = (TH1F*)gDirectory->Get(nameBottom.str().c_str());
  
    // TCanvas *c=new TCanvas("c");
    // c->cd(1);
    // CurrentTop->Draw();
    // CurrentBottom->Draw("same");

    int binsTop = CurrentTop->GetNbinsX();

    int binsBottom= CurrentBottom->GetNbinsX();
  
    if ( binsTop !=binsBottom){
      cout<<"Nubmer of bins for the top channel not the same as for the bottom channel"<<endl;
      cout<<"This was for "<<CurrentTop->GetName()<<" and "<<CurrentBottom->GetName()<<endl;
      return;
    }
  
    int bins=binsTop;
  
    double topLow = CurrentTop->GetBinLowEdge(1);//ROOT histograms start at bin 1. bin 0 is underflow
    double topHigh= CurrentBottom->GetBinLowEdge(binsTop) +CurrentBottom->GetBinWidth(binsTop);//ROOT histograms end at bin N. N+1 is overflow bin.

    double NanoSecsPerBin = ((topHigh-topLow)*4)/binsTop;
  
    //    cout<<topLow<<" "<<topHigh<<endl;
    //    cout<<"NanoSecsPerBin "<<NanoSecsPerBin<<endl;
  
 
    int ForthOfBins = TMath::Floor(0.25* bins);
    int EighthOfBins = TMath::Floor( (1.0/8)* bins);

    int NumberOfShifts = 2*EighthOfBins; // 1/8 of the number of bins *2 for left/right shifts
  
    int TopZeroBin = CurrentTop->GetMaximumBin();
  
    int StartBin = CurrentTop->FindBin(Start);
    int EndBin = CurrentTop->FindBin(End);

    //Find shift That moves Bottom -> Top
    vector <double> TheChi2s;
    vector <int> TheShifts;
    for (int i=0;i<NumberOfShifts;i++){
      double binShift = (i - NumberOfShifts/2);

      double chi2=0;
      // cout<<"Looking in bin range "<<TopZeroBin-EighthOfBins<<" "<<TopZeroBin+EighthOfBins<<endl;
      // cout<<"That is from "<<CurrentTop->GetBinCenter(TopZeroBin-EighthOfBins)<<" "<<CurrentTop->GetBinCenter(TopZeroBin+EighthOfBins)<<endl;

      for (int bin=StartBin ;bin<EndBin;bin++){
	double b = CurrentBottom->GetBinContent(bin + binShift);
	double t = CurrentTop->GetBinContent(bin);
	if (b !=0 && t!=0){
	  double temp =((b-t)*(b-t))/( TMath::Sqrt(t) );
	  chi2+=temp;
	}
      }
    
      TheChi2s.push_back(chi2);
      TheShifts.push_back(binShift);

    }
  
    ///Find miminum by linear search 
    double min = 9999999999.0;
    int MinSpot=-1;
    for (int i=0;i<NumberOfShifts;i++){
      if ( TheChi2s[i] < min){
	min=TheChi2s[i];
	MinSpot=i;
      }
    }

    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"B  "<<"1  0  "<<fixed<<setw(6)<<setprecision(4)<<TheShifts[MinSpot]/4.0*NanoSecsPerBin<<endl;
    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"T  "<<"1  0  0"<<endl;

  }


  cout<<"There were "<<NanoSecsPerBin<<" nano secs per bin"<<endl;
  // TGraph * graph = new TGraph();
  
  // cout<<"Size of Chi2s "<<TheChi2s.size()<<endl;
  // cout<<"Num "<<NumberOfShifts<<endl;

  // for (int i=0;i<NumberOfShifts;i++){
  //   graph->SetPoint(i,TheShifts[i],TheChi2s[i]);
  // }

  // TCanvas *c2 = new TCanvas("c2");
  // c2->cd(1);
  // graph->Draw("A*");


}
void display(){
  
  gROOT->ProcessLine(".x lhcbStyle.C");
  gStyle->SetPalette(1);
	
  string filename = "../analysed/SET9THL914.root";
	TFile* file = new TFile(filename.c_str(),"OPEN");

	int nBinsX=32; int nBinsY=32;
	int nPixelsX=64; int nPixelsY=64;
	
  std::cout<<"Making global intercept tot map"<<std::endl;
  // Global intercept map (not per pixel)
	TH2F* hToTMap = new TH2F("hToTMap","hToTMap",nBinsX,0,nPixelsX,nBinsY,0,nPixelsY);
	for(int x=0;x<nBinsX;x++){
		for(int y=0;y<nBinsY;y++){
			int id = x + y*nBinsX;
			// Get the ToT distribution for this location
			string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixMap"+makestring(id);
			TH1F* totMapHisto = 0;
			totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
			if(totMapHisto == 0) continue;
			if(totMapHisto->GetEntries() < 20) continue;
	
			// Fit the tot distribution and enter the value in the ToT map
			totMapHisto->Fit("gaus","0q");
			TF1* fit = totMapHisto->GetFunction("gaus");
			hToTMap->Fill(x*floor(nPixelsX/nBinsX),y*floor(nPixelsY/nBinsY),fit->GetParameter(1));
			
			delete fit; delete totMapHisto;
		}
	}
	// Plot the map of ToT
	TCanvas* canv = new TCanvas();
	hToTMap->GetXaxis()->SetTitle("Column");
	hToTMap->GetYaxis()->SetTitle("Row");
  hToTMap->GetZaxis()->SetTitle("Mean charge (ToT)");
	hToTMap->SetMaximum(9);
	hToTMap->SetMinimum(5);
	hToTMap->DrawCopy("colz");

  
  std::cout<<"Making per pixel tot map"<<std::endl;
  // Per pixel map
  TH2F* hToTMapPerPixel = new TH2F("hToTMapPerPixel","hToTMapPerPixel",nPixelsX,0,nPixelsX,nPixelsY,0,nPixelsY);
  for(int x=0;x<nPixelsX;x++){
    for(int y=0;y<nPixelsY;y++){
      int id = x + y*nPixelsX;
      // Get the ToT distribution for this location
      string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixPixel"+makestring(id);
      TH1F* totMapHisto = 0;
      totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
      if(totMapHisto == 0) continue;
      if(totMapHisto->GetEntries() < 10) continue;
      
      // Fit the tot distribution and enter the value in the ToT map
      totMapHisto->Fit("gaus","0q");
      TF1* fit = totMapHisto->GetFunction("gaus");
      hToTMapPerPixel->Fill(x,y,fit->GetParameter(1));
      
      delete fit; delete totMapHisto;
    }
  }
  // Plot the map of ToT
  TCanvas* canv2 = new TCanvas();
  hToTMapPerPixel->GetXaxis()->SetTitle("Column");
  hToTMapPerPixel->GetYaxis()->SetTitle("Row");
  hToTMapPerPixel->GetZaxis()->SetTitle("Mean charge (ToT)");
  hToTMapPerPixel->SetMaximum(10);
  hToTMapPerPixel->SetMinimum(0);
  hToTMapPerPixel->DrawCopy("colz");

  std::cout<<"Making pixel response tot maps"<<std::endl;
  // Pixel response maps
  int responseBins=100;
  double responseWidth=0.05;
  TH2F* hToTMapPixelResponseX = new TH2F("hToTMapPixelResponseX","hToTMapPixelResponseX",responseBins+1,-responseWidth,responseWidth,15,0,15);
  for(double rID=0;rID<responseBins;rID++){
    // Get the ToT distribution for this location
    string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseX"+makestringD(rID);
    TH1F* totMapHisto = 0;
    totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
    if(totMapHisto == 0) continue;
    if(totMapHisto->GetEntries() < 1) continue;
 		// loop over all tot bins
    for(int i=0;i<45;i++){
      hToTMapPixelResponseX->Fill(2.*responseWidth*(rID/100.)-responseWidth,i,totMapHisto->GetBinContent(totMapHisto->FindBin(i)));
    }
    delete totMapHisto;
  }
  // Plot the map of ToT
  TCanvas* canv3 = new TCanvas();
  hToTMapPixelResponseX->GetXaxis()->SetTitle("Track distance x (mm)");
  hToTMapPixelResponseX->GetYaxis()->SetTitle("ToT");
  hToTMapPixelResponseX->DrawCopy("colz");

  TH1F* hToTProfilePixelResponseY = new TH1F("hToTProfilePixelResponseY","hToTProfilePixelResponseY",responseBins+1,-responseWidth,responseWidth);
  TH2F* hToTMapPixelResponseY = new TH2F("hToTMapPixelResponseY","hToTMapPixelResponseY",responseBins+1,-responseWidth,responseWidth,16,0,16);
  for(double rID=0;rID<responseBins;rID++){
    // Get the ToT distribution for this location
    string histoname = "/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY"+makestringD(rID);
    TH1F* totMapHisto = 0;
    totMapHisto = (TH1F*)gDirectory->Get(histoname.c_str());
    if(totMapHisto == 0) continue;
    if(totMapHisto->GetEntries() < 1) continue;
    // loop over all tot bins
    for(int i=0;i<45;i++){
      hToTMapPixelResponseY->Fill(2.*responseWidth*(rID/100.)-responseWidth,i,totMapHisto->GetBinContent(totMapHisto->FindBin(i)));
    }
    hToTProfilePixelResponseY->Fill(2.*responseWidth*(rID/100.)-responseWidth+0.001,totMapHisto->GetXaxis()->GetBinCenter(totMapHisto->GetMaximumBin()));
    delete totMapHisto;
  }
  // Plot the map of ToT
  TCanvas* canv4 = new TCanvas();
  hToTMapPixelResponseY->GetXaxis()->SetTitle("Track distance y (mm)");
  hToTMapPixelResponseY->GetYaxis()->SetTitle("ToT");
  hToTMapPixelResponseY->GetZaxis()->SetTitle("Number of events");
  hToTMapPixelResponseY->DrawCopy("colz");
//  drawline(-0.03,1,7);
//  drawline(0.03,1,7);
	
  TCanvas* canv6 = new TCanvas();
  hToTProfilePixelResponseY->GetXaxis()->SetTitle("Track distance y (mm)");
  hToTProfilePixelResponseY->GetYaxis()->SetTitle("Most probable ToT");
  hToTProfilePixelResponseY->DrawCopy("");



  
  TCanvas* canv5 = new TCanvas();
  TH1F* sidebandLow = (TH1F*)gDirectory->Get("/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY20");
  TH1F* sidebandHigh = (TH1F*)gDirectory->Get("/tpanal/ClicpixAnalysis/hClusterTOTAssociated1pixResponseY80");
  sidebandHigh->GetXaxis()->SetTitle("ToT (single pixel)");
  sidebandHigh->GetXaxis()->SetRangeUser(0,20);
  sidebandHigh->DrawCopy("");
  sidebandLow->SetLineColor(2);
  sidebandLow->DrawCopy("same");

}
Ejemplo n.º 8
0
void DrawVariable(TString DIR,TString VAR,float LUMI,bool LOG,int REBIN,float XMIN,float XMAX,TString XTITLE,bool isINT,int XNDIV,bool PRINT)
{
  gROOT->ForceStyle();
  const int N = 14;

  TString SAMPLE[N] = {
    "JetHT",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8"
  };
  float XSEC[N] = {1.0,0.5*832,3539,1460.,136.02,80.95,35.6,35.6,3.67e+5,2.94e+4,6.524e+03,1.064e+03,121.5,2.542e+01};

  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("DataVsMC_"+DIR+"_"+VAR,"DataVsMC_"+DIR+"_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    h[i] = (TH1F*)inf[i]->Get(DIR+"/hWt_"+VAR);
    if (!h[i]) {
      cout<<"Histogram "<<"hWt_"+VAR<<" does not exist !!!"<<endl;
      break;
    } 
    h[i]->SetDirectory(0);
    h[i]->Sumw2();
    h[i]->Rebin(REBIN);
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();   
      //cout<<SAMPLE[i]<<" "<<norm<<endl;
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[8]->Clone("hQCD");
  for(int i=9;i<N;i++) {
    hQCD->Add(h[i]);
  }
 
  TH1F *hST = (TH1F*)h[4]->Clone("hST");
  hST->Add(h[5]);
  hST->Add(h[6]);
  hST->Add(h[7]);
  h[0]->SetLineWidth(2);//data
  hQCD->SetFillColor(kBlue-10);//QCD
  h[1]->SetFillColor(kOrange);//ttbar
  h[2]->SetFillColor(kGreen-10);//WJets
  h[3]->SetFillColor(kGreen-8);//ZJets
  hST->SetFillColor(kOrange-1);//ST

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-h[1]->Integral()-h[2]->Integral()-h[3]->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(h[1]);
  hBkg->Add(h[2]);
  hBkg->Add(h[3]);
  hBkg->Add(h[4]);
  hBkg->Add(hST);
  //hBkg->SetFillColor(kGray);

  cout<<"======== "<<VAR<<"====================="<<endl;
  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"WJets events: "<<h[2]->Integral()<<endl;
  cout<<"ZJets events: "<<h[3]->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTbar events: "<<h[1]->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  if (LOG) {   
    hs->Add(h[2]);
    hs->Add(h[3]);
    hs->Add(hST); 
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  else {
    hs->Add(h[3]);
    hs->Add(hST);
    hs->Add(h[2]);
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.7,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(h[1],"TTbar","F"); 
  leg->AddEntry(hST,"ST","F"); 
  leg->AddEntry(h[2],"WJets","F");
  leg->AddEntry(h[3],"ZJets","F"); 
  
  can->SetBottomMargin(0.25);
  TH1F *hAux = (TH1F*)h[0]->Clone("aux");
  hAux->Reset();
  hAux->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hAux->GetXaxis()->CenterLabels();
  } 
  hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));  
  if (LOG) {
    gPad->SetLogy(); 
    hAux->GetYaxis()->SetRangeUser(0.5,2*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));
  }
  hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
  hAux->GetXaxis()->SetTitle("");
  hAux->GetXaxis()->SetLabelSize(0.0);
  hAux->Draw();
  hs->Draw("hist same");
  //hBkg->Draw("sames hist"); 
  h[0]->Draw("sames E");
  
  leg->Draw();
  gPad->RedrawAxis();

  TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
  pad->SetTopMargin(0.77);
  pad->SetRightMargin(0.15);
  pad->SetFillColor(0);
  pad->SetFillStyle(0);
  pad->Draw();
  pad->cd(0);
  pad->SetGridy();
  hRatio->GetXaxis()->SetTitleOffset(0.95);
  hRatio->GetYaxis()->SetTitleOffset(1.5);
  hRatio->GetYaxis()->SetTickLength(0.06);
  hRatio->GetYaxis()->SetTitleSize(0.03);
  hRatio->GetYaxis()->SetLabelSize(0.03);
  hRatio->GetYaxis()->SetTitle("Data/MC");
  hRatio->GetXaxis()->SetTitle(XTITLE);
  hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
  hRatio->GetYaxis()->SetNdivisions(505);
  hRatio->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hRatio->GetXaxis()->CenterLabels();
  }
  hRatio->Draw();
  if (PRINT) {
    can->Print("plots/"+TString(can->GetName())+".pdf"); 
    can->Print("plots/"+TString(can->GetName())+".png");
  }
}
Ejemplo n.º 9
0
void checkflat(int icent = 0, int ihar=0){
    int color[nsub]={1,2,3,4,5,6,7,8};
    float pi = acos(-1.0);
    TString str;
    TFile *fin;
        TH1::SetDefaultSumw2();
        gStyle->SetOptStat(kFALSE);
        int iharE=0;
     if(nhar==1||nhar==2) iharE=1;
        int n = ihar+1.0+iharE;
    int nrun = GetTotalRun();
    float FitGood[nsub][1000];
    float FitGooderr[nsub][1000];
    float runlist[1000];
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        TH1F* hunpsi = new TH1F("unpsi","unpsi",100,-pi,pi);
        TH1F* h = new TH1F("h","",100,-4,4);
        for(int irun=0;irun<nrun;irun++){
        std::ifstream corrs("run15pAl200MBPro104.Lst");
        int index=0; int run=0;
        for(int jrun=0;jrun<irun+1;jrun++){
        corrs>>index>>run;
        }
        runlist[irun] = run;
       // system(Form("hadd -f /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d_*.root",run,run));
        fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root",run));
        for(int isub=0;isub<nsub;isub++){
        str = choosesub(isub);
        if(str=="ABORT") continue;
        hpsi->Reset();
        hunpsi->Reset();
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          TH1F* hunpsitemp = (TH1F*)fin->Get(Form("psi_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
          hunpsi->Add(hunpsitemp);
        }
        TF1 *fun = new TF1("fun","pol0",-pi,pi);
        TCanvas *c1 = new TCanvas("c1","c1",600,450);
        h->GetXaxis()->SetTitle(Form("#Psi_{%d}",n));
        h->GetYaxis()->SetTitle(Form("# of events"));
        h->GetYaxis()->SetRangeUser(hunpsi->GetBinContent(hunpsi->GetMinimumBin())*0.9,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.1);
        h->Draw("C");
       // h->GetYaxis()->SetRangeUser(0,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.2);
      if(hpsi->GetEntries()>1000){
	hpsi->Fit("fun","QR0");
	float par=fun->GetParameter(0);
	float parerr=fun->GetParError(0);
        FitGood[isub][irun]=fun->GetChisquare()/fun->GetNDF();
        FitGooderr[isub][irun]=0;
        fun->SetLineColor(4);
        fun->Draw("same");
      }
        else{
        FitGood[isub][irun]=0;
        FitGooderr[isub][irun]=0;
        }
        if(irun!=104) continue;
	hpsi->SetMarkerStyle(20);
	hpsi->SetMarkerSize(0.8);
	hpsi->SetMarkerColor(2);
	hpsi->SetLineColor(2);
	hunpsi->SetMarkerStyle(20);
	hunpsi->SetMarkerSize(0.8);
	hunpsi->SetMarkerColor(1);
	hunpsi->SetLineColor(1);
        TLegend *leg = new TLegend(0.4,0.7,0.8,0.85);
        leg->SetTextSize(0.04);
        leg->SetFillColor(0);
        leg->SetBorderSize(0);
        leg->AddEntry(hunpsi,Form("Run%d %s",run,str.Data()));
        leg->AddEntry(hunpsi,"before flattening","L");
        leg->AddEntry(hpsi,"After flattening","L");
        hpsi->Draw("Csame");
        hunpsi->Draw("Csame");
        leg->Draw("same");
        c1->Print(Form("run-by-run/checkflat_%d_%d_%d_%d.png",icent,ihar,isub,irun));
        delete c1;
        }
        fin->Close();
    }  
        TGraphErrors *grRun[nsub];
    TCanvas *c1 = new TCanvas("c1","c1",600,450);
    TCanvas *c2 = new TCanvas("c2","c2",600,450);
    TH1F* h1 = new TH1F("h1","",4000,436000,439000);
    h1->GetXaxis()->SetTitle(Form("Run Number"));
    h1->GetYaxis()->SetTitle("Fit #chi^{2}/Ndf");
    h1->GetXaxis()->SetRangeUser(runlist[0]-15,runlist[nrun-1]+15);
    h1->GetYaxis()->SetRangeUser(0,4);
    TLegend *leg = new TLegend(0.65,0.75,0.88,0.85);
    leg->SetTextSize(0.035);
    leg->SetBorderSize(0);
    leg->SetFillColor(0);
    c1->cd();
    h1->Draw("0");
        for(int isub=0;isub<nsub;isub++){
            if(isub!=4 && isub!=5) continue;
            grRun[isub] = new TGraphErrors(nrun,runlist,FitGood[isub],0,FitGooderr[isub]);
            grRun[isub] -> SetMarkerColor(isub-3);
            grRun[isub] -> SetMarkerSize(1.);
            grRun[isub] -> SetMarkerStyle(16+isub);
            grRun[isub] -> SetLineColor(isub-3);
            grRun[isub] -> Draw("Psame");
            leg->AddEntry(grRun[isub],choosesub(isub).Data(),"P");
        leg->Draw("same");
        }
      c1->Print(Form("run-by-run/fitsum%d.png",n));
}
Ejemplo n.º 10
0
void calCrystalDepo(TTree *t1041, int ThisModule = -99, bool IsBatch =0){
  if(IsBatch) gROOT->SetBatch();

  TString ThisModuleString = TString::Itoa(ThisModule,10);
  int UpOrDown = ThisModule/abs(ThisModule);
  float Scale = 1.;
  if(UpOrDown == -1) Scale = 0.5;
  cout << "Creating energy distributions of events with maximum deposition in module: " << ThisModuleString << endl;
//Define Histograms

//This histogram is a tool
  TH1F* MatrixDepo = new TH1F("MatrixDepo", "Deposition on Matrix", 68, -17, 17);

  TH1F* fracDep = new TH1F("fracDep", "Highest Amplitude Crystal/Total Deposition", 100, 0, 1.2);
  TH1F* MaxBin = new TH1F("MaxBin", "Deposition of Highest Amplitude Crystal", 100,400*Scale,7000*Scale);
  TH1F* Integral = new TH1F("Integral", "Integral", 100,4000*Scale,13000*Scale);
  TH1F* SigNoise = new TH1F("SigNoise", "Signa/Pedestal", 100, 0, 2.);

//

  gStyle->SetOptStat(0);
  

  Mapper *mapper=Mapper::Instance();

  TBEvent *event = new TBEvent();
  t1041->SetBranchAddress("tbevent", &event);
  bool haverechits=false;
  vector<TBRecHit> *rechits=0;

  if(t1041->GetListOfBranches()->FindObject("tbrechits")) {
    cout <<"found rechits"<<endl;
    t1041->SetBranchAddress("tbrechits",&rechits);
    haverechits=true;
  }

  Int_t start=0; Int_t end=t1041->GetEntries();  
  
  int nEntries=0;
//  end = 10;
  for (Int_t i=start; i<end; i++) {
    t1041->GetEntry(i);
    if (i==0) mapper->SetEpoch(event->GetTimeStamp());
    if(haverechits && rechits->size() < 1) continue;

    MatrixDepo->Reset();
    float maxDepoModuleID = -99;
    float maxDepo = 0;
    float secondMaxDepo = 0;
    float secondMaxDepoModuleID = -99;
    float totdep = 0;
    float totalnoise = 0;
    float sumrms = 0;
    for (Int_t j = 0; j < event->NPadeChan(); j++){
      if (haverechits && j>=(int)rechits->size()) break;
      double ped,sig, max, maxTime;
      int channelID;
      if (haverechits){
	TBRecHit &hit=rechits->at(j);
	ped=hit.Pedestal();
	sig=hit.NoiseRMS();
	max=hit.AMax();
	maxTime=hit.TRise();
	channelID=hit.GetChannelID();
      }

      double x,y;
      int moduleID,fiberID;
      mapper->ChannelID2ModuleFiber(channelID,moduleID,fiberID);
      mapper->ModuleXY(moduleID,x,y);

      MatrixDepo->Fill(moduleID, max);      
      if(UpOrDown > 0 && moduleID > 0)	totalnoise+=ped;
      if(UpOrDown < 0 && moduleID < 0)	totalnoise+=ped;
    }

    int minx = 0;
    int maxx = 0;
    if(UpOrDown > 0){
      minx = MatrixDepo->GetXaxis()->FindBin(0.);
      maxx = MatrixDepo->GetXaxis()->FindBin(17.);
      MatrixDepo->GetXaxis()->SetRange(minx, maxx);
    }
    if(UpOrDown < 0){
      minx = MatrixDepo->GetXaxis()->FindBin(-17.);
      maxx = MatrixDepo->GetXaxis()->FindBin(0.);	
      MatrixDepo->GetXaxis()->SetRange(minx, maxx);
    }

//    cout << "TOTAL NOISE: " << totalnoise << endl;

    float maxbin = MatrixDepo->GetBinContent(MatrixDepo->GetMaximumBin());
    float integral = MatrixDepo->Integral(minx,maxx);

    maxDepoModuleID = MatrixDepo->GetBinLowEdge(MatrixDepo->GetMaximumBin());

    if( abs(ThisModule) != 99 && maxDepoModuleID != ThisModule ) continue;
    if( abs(ThisModule) == 100 ){
	if( abs(maxDepoModuleID) != 6 &&
	    abs(maxDepoModuleID) != 7 &&
	    abs(maxDepoModuleID) != 10 &&
	    abs(maxDepoModuleID) != 11) continue;
    }

    
//    if(sumrms/totdep > 0.3) continue;
//      if( maxDepo/totdep < 0.2 ||  maxDepo/totdep > 0.5) continue;
      if( maxbin/integral < .55) continue;
//      if( totdep/totalnoise < 1.) continue;
//      if( totdep < 950) continue;
//    if(sumrms/totdep < 0.3) cout << totdep << endl;




    MaxBin->Fill(maxbin);
    Integral->Fill(integral);
    fracDep->Fill(maxbin/integral);
//    cout << maxbin/integral;
//    SigNoise->Fill(integral/totalnoise);
//    cout << maxbin << endl;

    nEntries++;
  }

  TString FileFig;
  TCanvas *c5=new TCanvas("c5","Average Peak Height",800,800);
  c5->SetGrid();
  fracDep->Draw();
  FileFig = "energy/R9_Module_"+ThisModuleString+".png";
  c5->SaveAs(FileFig);

  TCanvas *c7=new TCanvas("c7","MAXBIN",800,800);
  c7->SetGrid();
//  MaxBin->Fit("gaus", "","", 4100, 6000);
  MaxBin->Draw();
  FileFig = "energy/eMaxCrystal_Module_"+ThisModuleString+".png";
  c7->SaveAs(FileFig);

  TCanvas *c8=new TCanvas("c8","Integral",800,800);
  c8->SetGrid();
//  TF1* fit = new TF1("fit","p0*exp(-(0.5)*((x-760)/p1)^2)",0, 3000);
//  fit->SetParameters(500, 50);
  Integral->Fit("gaus");//, "", "", 3000, 4000);
  gStyle->SetOptFit();
  Integral->Draw();
  FileFig = "energy/eMatrix_Module_"+ThisModuleString+".png";
  c8->SaveAs(FileFig);

  TCanvas *c9=new TCanvas("c9","Integral",800,800);
  c9->SetGrid();
  SigNoise->Draw();
  FileFig = "energy/SignalToNoise_Module"+ThisModuleString+".png";
  c9->SaveAs(FileFig);


}
Ejemplo n.º 11
0
void DrawVariable(TString VAR,bool SHAPE,int REBIN,float XMIN,float XMAX,TString XTITLE,bool PRINT,bool BLIND=false,float BLIND_MIN=0,float BLIND_MAX=0)
{
  gROOT->ForceStyle();
  const int N = 20;

  TString SAMPLE[N] = {
    "JetHT",
    "ttHJetTobb_M125_13TeV_amcatnloFXFX_madspin_pythia8",
    "ttHJetToNonbb_M125_13TeV_amcatnloFXFX_madspin_pythia8_mWCutfix",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "TTWJetsToQQ_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8",
    "TTZToQQ_TuneCUETP8M1_13TeV-amcatnlo-pythia8",
    "WZ_TuneCUETP8M1_13TeV-pythia8",
    "WWTo4Q_13TeV-powheg",
    "ZZTo4Q_13TeV_amcatnloFXFX_madspin_pythia8"
  };

  float XSEC[N] = {
    1.0,
    0.2934,
    0.2151,
    347700, 
    32100,
    6831,
    1207,
    119.9,
    25.24,
    1460,
    3539,
    832,
    217,
    35.6,
    35.6,
    0.4062,
    0.5297,
    47.13,
    51.723,
    22.29
  }; 
 
  float LUMI(5760);
  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("can_"+VAR,"can_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    //cout<<inf[i]->GetName()<<" "<<VAR<<endl;
    h[i]   = (TH1F*)inf[i]->Get("ttH/h_"+VAR);
    h[i]->SetDirectory(0);
    h[i]->Rebin(REBIN);
    h[i]->Sumw2();
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();
      //cout<<inf[i]->GetName()<<" "<<norm<<endl; 
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    else {
      h[i]->SetLineWidth(2);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[3]->Clone("hQCD");
  hQCD->Add(h[4]);
  hQCD->Add(h[5]);
  hQCD->Add(h[6]); 
  hQCD->Add(h[7]);
  hQCD->Add(h[8]);

  TH1F *hVV = (TH1F*)h[17]->Clone("hVV");
  hVV->Add(h[18]);
  hVV->Add(h[19]);

  TH1F *hST = (TH1F*)h[12]->Clone("hST");
  hST->Add(h[13]);
  hST->Add(h[14]);

  h[1]->SetLineColor(kRed);//ttHbb
  h[1]->SetFillColor(kRed-9);
  h[1]->SetLineWidth(2);
  h[2]->SetLineColor(kRed);//ttHNobb
  h[2]->SetFillColor(kRed-10);
  h[2]->SetLineWidth(2);

  TH1F *hTT     = (TH1F*)h[11]->Clone("TTbar");
  TH1F *hTTZ    = (TH1F*)h[16]->Clone("TTZ");
  TH1F *hTTW    = (TH1F*)h[15]->Clone("TTW");
  TH1F *hWJets  = (TH1F*)h[10]->Clone("WJets");
  TH1F *hDYJets = (TH1F*)h[9]->Clone("DYJets");
 
  hQCD->SetFillColor(kBlue-10);//QCD
  hTT->SetFillColor(kOrange);
  hST->SetFillColor(kOrange-1);//ST
  hVV->SetFillColor(kMagenta-10);//VV
  hTTZ->SetFillColor(kYellow-10);//ttZ
  hTTW->SetFillColor(kYellow-9);//ttW
  hWJets->SetFillColor(kGreen-10);//WJets
  hDYJets->SetFillColor(kGreen-8);//ZJets
 
 

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-hTT->Integral()-hWJets->Integral()-hDYJets->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(hTT);
  hBkg->Add(hST);
  hBkg->Add(hTTW);
  hBkg->Add(hTTZ);
  hBkg->Add(hWJets);
  hBkg->Add(hDYJets);
  hBkg->Add(hVV);
  hBkg->SetFillColor(kGray);

  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"ttHJetTobb:   "<<h[1]->Integral()<<endl;
  cout<<"ttHJetToNonbb:"<<h[2]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"TTbar events: "<<hTT->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTZ events:   "<<hTTZ->Integral()<<endl;  
  cout<<"TTW events:   "<<hTTW->Integral()<<endl;
  cout<<"WJets events: "<<hWJets->Integral()<<endl;
  cout<<"DYJets events:"<<hDYJets->Integral()<<endl;
  cout<<"VV events:    "<<hVV->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  hs->Add(hVV);
  hs->Add(hTTW);
  hs->Add(hTTZ);
  hs->Add(hWJets);
  hs->Add(hDYJets);
  hs->Add(hST);
  hs->Add(hTT);
  hs->Add(hQCD);

  if (BLIND) {
    for(int i=0;i<h[0]->GetNbinsX();i++) {
      if (h[0]->GetBinCenter(i+1) > BLIND_MIN && h[0]->GetBinCenter(i+1) < BLIND_MAX) {
        h[0]->SetBinContent(i+1,0);
        h[0]->SetBinError(i+1,0);
      } 
    }
  }

  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.55,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(hTT,"TTbar","F");
  leg->AddEntry(hST,"ST","F");
  leg->AddEntry(hTTZ,"ttZ","F");
  leg->AddEntry(hTTW,"ttW","F");
  leg->AddEntry(hWJets,"WJets","F");
  leg->AddEntry(hDYJets,"ZJets","F");
  leg->AddEntry(hVV,"Diboson","F");
  leg->AddEntry(h[1],"ttHbb","L");
  leg->AddEntry(h[2],"ttHNonbb","L");
  
  if (SHAPE) {
    h[1]->SetFillStyle(3001);
    h[2]->SetFillStyle(3001);
    h[0]->Scale(1./h[0]->Integral());
    h[1]->Scale(1./h[1]->Integral());
    h[2]->Scale(1./h[2]->Integral());
    hQCD->Scale(1./hQCD->Integral());
    hBkg->Scale(1./hBkg->Integral());
    double max = TMath::Max(h[0]->GetBinContent(h[0]->GetMaximumBin()),hBkg->GetBinContent(hBkg->GetMaximumBin()));
    hBkg->SetMaximum(1.1*max);
    hBkg->GetXaxis()->SetTitle(XTITLE);
    hBkg->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hBkg->Draw("hist");
    h[0]->Draw("same E"); 
    //h[1]->Draw("same hist"); 
    leg->Draw();
    gPad->RedrawAxis();
    can->Print("can_"+VAR+"_norm.pdf"); 
  }
  else {
    can->SetBottomMargin(0.25);
    gPad->SetLogy(); 
    //h[1]->Scale(h[0]->Integral()/h[1]->Integral());
    h[1]->SetFillColor(0);
    TH1F *hAux = (TH1F*)h[0]->Clone("aux");
    hAux->Reset();
    hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(h[1]->GetBinContent(h[1]->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin()))); 
    
    hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
    hAux->GetXaxis()->SetTitle("");
    hAux->GetXaxis()->SetLabelSize(0.0);
    hAux->Draw();
    hs->Draw("hist same"); 
    h[0]->Draw("same E");
    h[1]->Draw("same hist");
    h[2]->Draw("same hist");
    leg->Draw();
    gPad->RedrawAxis();

    TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
    pad->SetTopMargin(0.77);
    pad->SetRightMargin(0.15);
    pad->SetFillColor(0);
    pad->SetFillStyle(0);
    pad->Draw();
    pad->cd(0);
    pad->SetGridy();
    hRatio->GetXaxis()->SetTitleOffset(0.95);
    hRatio->GetYaxis()->SetTitleOffset(1.5);
    hRatio->GetYaxis()->SetTickLength(0.06);
    hRatio->GetYaxis()->SetTitleSize(0.03);
    hRatio->GetYaxis()->SetLabelSize(0.03);
    hRatio->GetYaxis()->SetTitle("Data/MC");
    hRatio->GetXaxis()->SetTitle(XTITLE);
    hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hRatio->GetYaxis()->SetNdivisions(505);
    hRatio->Draw();
    if (PRINT) {
      can->Print("plots/can_"+VAR+"_abs.pdf"); 
      can->Print("plots/can_"+VAR+"_abs.png");
    }
  }
}
Ejemplo n.º 12
0
int main(int argc, char *argv[])
{
  if (argc < 4)
    {
      cout << "Usage: ./simData [numfiles] [Elow] [Ehigh] [geometry]\n";
      return -1;
    }

  Char_t temp2[500];
  ofstream outfile0, outfile1;
  
  Int_t num_files = atoi(argv[1]);
  Int_t Emin = atoi(argv[2]);
  Int_t Emax = atoi(argv[3]);
  Char_t *geometry = argv[4];  

  //Int_t EnergyRange = 800;
  //Int_t nbins = EnergyRange/binWidthEnergy;
  Int_t nbins = 1; //this is just remnant for now.
  //Double_t Energy_min = 0., Energy_max = (double)binWidthEnergy;
  Char_t temp[200], temp1[100], file0[100], file1[100];
  Char_t *calDir = getenv("UCNA_CAL_DIR"); 
  Char_t *G4Dir = getenv("G4WORKDIR");
  sprintf(file0, "%s/Sims/Beta_%i-%ikev_%s_east.dat", calDir, Emin, Emax, geometry);
  sprintf(file1, "%s/Sims/Beta_%i-%ikev_%s_west.dat", calDir, Emin, Emax, geometry);
  cout << file0 << endl;
  outfile0.open(file0);
  outfile1.open(file1);


  TChain *chain = new TChain("anaTree");

  
      
  for (Int_t file_number = 0; file_number<num_files; file_number++)
    {
	  
      sprintf(temp2, "%s/output/%sgeo_n1_1mil/analyzed_%i.root", G4Dir, geometry, file_number);
      chain->Add(temp2);
    }


  TH1F *east = new TH1F("east", "East Side", 200, 0., 50.);
  TH1F *west = new TH1F("west", "West Side", 200, 0., 50.); 

  for (int i = 0; i<nbins; i++)
    {
      east->Reset();
      west->Reset();
	  

      sprintf(temp, "MWPCEnergy.MWPCEnergyE>1e-5 && MWPCEnergy.MWPCEnergyE<50. && MWPCEnergy.MWPCEnergyW<0.01 && Edep.EdepW<0.1 && Edep.EdepE>%f && Edep.EdepE<%f",(double)Emin,(double)Emax);
      sprintf(temp1, "MWPCEnergy.MWPCEnergyE>>east");
      chain->Draw(temp1, temp);
	  

      sprintf(temp, "MWPCEnergy.MWPCEnergyW>1e-5 && MWPCEnergy.MWPCEnergyW<50. && MWPCEnergy.MWPCEnergyE<0.01 && Edep.EdepE<0.1 && Edep.EdepW>%f && Edep.EdepW<%f",(double)Emin,(double)Emax);
      sprintf(temp1, "MWPCEnergy.MWPCEnergyW>>west");
      chain->Draw(temp1, temp);

	 
      TF1 *f1 = new TF1("f1", "landau", 0.05, 20.);
      //f1->SetParLimits(0, 0., 1.e10);
      //f1->SetParLimits(1, 0., 1.e7);
      
      Double_t max_bin = east->GetBinCenter(east->GetMaximumBin());
      f1->SetParameters(5.e4,max_bin, 0.1);
      cout << endl << endl << "For Energy Range: " << Emin << " to " << Emax << endl;
      
      //sprintf(num, "his%i", i)     
      east->Fit("f1","RM");
      outfile0 << Emin << " " << Emax << " " << f1->GetParameter(1) << endl;
      delete f1;
      f1=NULL;

      TF1 *f2 = new TF1("f2", "landau", 0.05, 20.);
      //f2->SetParLimits(0, 0., 1.e10);
      //f2->SetParLimits(1, 0., 1.e7);

      max_bin = west->GetBinCenter(west->GetMaximumBin());
      f2->SetParameters(5.e4,max_bin,0.1);
      cout << endl << endl << "For Energy Range: " << Emin << " to " << Emax << endl;
      
      //sprintf(num, "his%i", i)     
      west->Fit("f2","RM");
      outfile1 << Emin << " " << Emax << " " << f2->GetParameter(1) << endl;
      

      //Energy_min=Energy_min + (double)binWidthEnergy;
      //Energy_max=Energy_max + (double)binWidthEnergy;
      
    }
  outfile0.close();
  outfile1.close();

}    
Ejemplo n.º 13
0
//TString inputsel = "&&nTaggableJetsPt20MatchedTagged>1";
void plotHhhTop(){
  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  gROOT->SetBatch();

  //std::vector
  double binning_[]={0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.,225.,250.,275.,300.,325.,350.,400.,500.,700.,1000.,1500.};

  TFile *HhhFile    = new TFile("/scratch/ojalvo/HhhGenStudies/Hhhttbb300.root");
  TFile *TOPFile = new TFile("/scratch/ojalvo/LTau_103/TOP2.root");
  TFile *MTEMFile = new TFile("/scratch/ojalvo/LTau_103/MTEM.root");

  TString selection="pt1>20&&pt2>20"+inputsel;//
  //TString selection="pt1>20&&pt2>20&&vertices>0&&diLeptons==0&&lPFIsoDB<0.1&&tauIso<1.5&&tightElectrons==0&&tightMuons<=1&&mt1<30&&J1Pt>20&&J2Pt>20";//

  TCanvas *Tcan= new TCanvas("Tcan","",100,20,600,800); Tcan->cd();  Tcan->SetFillColor(0); 

  TPad* pad1 = new TPad("pad1","The pad",0,0.2,1,1);
  TPad* pad2 = new TPad("pad2","the other pad",0,0,1,0.2);
  pad1->SetFillColor(0);
  //pad1->SetLogy();
  pad1->Draw();  pad1->cd();  pad1->SetLeftMargin(0.2);  pad1->SetBottomMargin(0.13);

  TLegend *leg = new TLegend(0.55,0.75,0.99,0.99);//  Leg = new TLegend(0.74,0.65,0.99,0.95);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetHeader("");
  leg->SetShadowColor(0);

  TTree* HhhTree = (TTree*)HhhFile->Get("muTauEventTreeFinal/eventTree");

  //TH1F* Shape = new TH1F("hist1","hist1",31,&binning_[0]);
  TH1F* Shape = new TH1F("hist1","hist1",bins,lo,hi);
  HhhTree->Draw(var+">>+hist1","("+selection+")");
  Shape->SetLineColor(kBlue);  Shape->SetFillColor(kBlue);
  Shape->SetFillStyle(3002);
  Shape->SetLineWidth(4);
  //Shape->Sumw2();

  
  TTree* TOPTree = (TTree*)TOPFile->Get("muTauEventTreeFinal/eventTree");
  TH1F* Shape1 = new TH1F("hist2","hist2",bins,lo,hi);
  TOPTree->Draw(+var+">>+hist2","("+selection+")","same");

  Shape1->SetLineColor(kRed);
  Shape1->SetFillColor(kRed);
  Shape1->SetFillStyle(3002);
  Shape1->SetLineWidth(4);
  Shape1->Scale(Shape->Integral()/Shape1->Integral());

  //Shape1->Sumw2();

  TTree* MTEMTree = (TTree*)MTEMFile->Get("muTauEventTree/eventTree");
  TH1F* Shape2 = new TH1F("hist1","hist1",bins,lo,hi);
  MTEMTree->Draw(var+">>+hist1","("+selection+")","same");
  Shape2->SetLineColor(kBlack);
  Shape2->SetLineStyle(2);
  Shape2->SetLineWidth(4);
  Shape2->Scale(Shape->Integral()/Shape2->Integral());
  

  Shape->GetXaxis()->SetTitle(var);
  Shape->GetYaxis()->SetTitle("A.U.");
  Shape1->Draw("same");
  Shape->Draw("same");

  ///////////stupid thing to sent max bin
  float max, max1, max2 = 0;
  max = Shape->GetBinContent(Shape->GetMaximumBin());
  max1 = Shape1->GetBinContent(Shape1->GetMaximumBin());
  max2 = Shape2->GetBinContent(Shape2->GetMaximumBin());

  if(max>max1&&max>max2)
    Shape->SetMaximum(max*1.1);
  else if(max1>max&&max1>max2)
    Shape->SetMaximum(max1*1.1);
  else 
    Shape->SetMaximum(max2*1.1);

  ///
  leg->AddEntry(Shape,"300GeV H Signal","l");
  leg->AddEntry(Shape1,"t#bar{t}","l");
  leg->AddEntry(Shape2,"Z #rightarrow #tau#tau","l");
  //leg->AddEntry(Shape2,"Embedded 50 GeV<M(#mu#mu)<250 GeV","l");

  leg->Draw();

  
  Tcan->cd();
  /*
  pad2->Draw();
  pad2->cd();   
  pad2->SetBottomMargin(0.1);
  pad2->SetTopMargin(0.1);
  pad2->SetLeftMargin(0.2); 

  TH1F *Den = new TH1F("Den","hist",bins,lo,hi);
  TH1F *Num = new TH1F("Num","hist",bins,lo,hi);
  //Shape->Sumw2();
  TH1F *Eff = (TH1F*)Shape1->Clone();
  Eff->SetLineColor(kBlue);
  Eff->Sumw2();
  TH1F *Eff1 = (TH1F*)Shape->Clone();
  Eff1->SetLineColor(kMagenta);
  TH1F *Div = (TH1F*)Shape2->Clone();
  Div->Sumw2();
  Eff->Divide(Div);
  //Eff1->Divide(Shape3);
  //Eff2->Divide(Shape4);
  Eff->GetYaxis()->SetRangeUser(0.5,1.5);
  Eff->GetYaxis()->SetNdivisions(3);
  Eff->GetYaxis()->SetLabelSize(0.1);
  Eff->GetYaxis()->SetTitleSize(0.1);
  Eff->GetYaxis()->SetTitleOffset(0.1);
  //Eff->GetYaxis()->SetTitle(myGroup + " / " + group);                                                                                                                                                                                                  
  Eff->GetYaxis()->SetTitle("Ratio");
  Eff->GetXaxis()->SetNdivisions(-1);
  Eff->GetXaxis()->SetTitle("");
  Eff->GetXaxis()->SetLabelSize(0.0001);
  Eff->SetMarkerColor(kBlack);
  Eff->Draw("histp");
  TLine line;
  line.DrawLine(Eff->GetXaxis()->GetXmin(),1,Eff->GetXaxis()->GetXmax(),1);

  TLine lineUp;
  lineUp.DrawLine(Eff->GetXaxis()->GetXmin(),0.75,Eff->GetXaxis()->GetXmax(),0.75);

  TLine lineDown;
  lineDown.DrawLine(Eff->GetXaxis()->GetXmin(),1.25,Eff->GetXaxis()->GetXmax(),1.25);

  TF1 *f2 = new TF1("f2","x",0.5,1.5);

  TGaxis *newyaxis = new TGaxis(lo,0.5,lo,1.5,"f2");
  newyaxis->SetNdivisions(4);
  newyaxis->SetLabelSize(0.12);


  pad2->cd();
  TLine *center = new TLine(lo,1,hi,1);
  center->SetLineStyle(2);
  Eff->Draw("ap");
  //Eff1->Draw("apsame");
  //Eff2->Draw("apsame");

  center->Draw();
  line.Draw();
  lineDown.SetLineColor(kBlue);
  lineDown.Draw();
  lineUp.SetLineColor(kBlue);
  lineUp.SetLineStyle(2);
  lineUp.Draw();
  newyaxis->Draw();

  */  
  Tcan->SaveAs("~/www/htt/GenStudies/"+var+"Top.png");

  float eventsTotal=Shape1->Integral();
  TH1F* Shape5 = new TH1F("hist5","hist5",bins,lo,hi);
  HhhTree->Draw(var+">>+hist5","("+selection+"&&mJJ==mJJCSVSort)");
  std::cout<< " Fraction of Events with mJJ matched "<< Shape5->Integral()/eventsTotal  <<std::endl;
  /*
  TCanvas *Tcan2= new TCanvas("Tcan2","",100,20,600,600); Tcan2->cd();  Tcan2->SetFillColor(0); 
  gStyle->SetPalette(1);
  TH2D* Shape2D = new TH2D("hist2D","hist2D",50,0,350,50,0,300);
  MTEMTree->Draw("svMass:mJJCSVSort>>hist2D",selection+"&&mJJCSVSort<300&&svMass<300","COLZ");
  Shape2D->GetXaxis()->SetTitle("mJJ");
  Shape2D->GetYaxis()->SetTitle("M(#tau#tau)");
  Shape2D->Smooth();
  Tcan2->SaveAs("~/www/htt/GenStudies/"+var+"2DMTEM.png");
  */
}
Ejemplo n.º 14
0
void compareDataMC( vector<TChain*> chmc , vector<char*> labels , TChain* chdata , char* var , 
		    TCut sel , TCut weight , int nbins ,  float xmin , float xmax ,  
		    char* xtitle , bool overlayData , bool residual , bool drawLegend , bool log , char* flavor ){

  TPad* fullpad = new TPad();
  TPad* plotpad = new TPad();
  TPad* respad  = new TPad();

  if( residual ){
    fullpad = new TPad("fullpad","fullpad",0,0,1,1);
    fullpad->Draw();
    fullpad->cd();

    plotpad = new TPad("plotpad","plotpad",0,0,1,0.8);
    plotpad->Draw();
    plotpad->cd();
    if( log ) plotpad->SetLogy();
  }
  else{
    if( log ) gPad->SetLogy();
  }

  TString tvar(var);
  tvar.ReplaceAll("()","");
  tvar.ReplaceAll(".","");
  const char* myvar = tvar;

  cout << "Plotting var " << myvar << " flavor " << flavor << endl;

  int colors[]={6,2,7,4,5,8,9,15,12};
  int sigcolors[]={4,1,7,4,5,8,9,15,12};
  int isigmc = 0;

  assert( chmc.size() == labels.size() );
  const unsigned int nmc = chmc.size();

  THStack* mcstack = new THStack("mcstack","mcstack");
  TH1F*    mctothist = new TH1F();
  TH1F*    smtothist = new TH1F();
  TH1F*    mchist[nmc];
  TH1F*    datahist = new TH1F(Form("%s_datahist_%s",myvar,flavor),Form("%s_datahist_%s",myvar,flavor),nbins,xmin,xmax);

  vector<TH1F*> sighist;

  float trigeff = 1.0;
  //if     ( TString(flavor).Contains("ee")  ) trigeff = 1.00;
  //else if( TString(flavor).Contains("mm")  ) trigeff = 0.90;
  //else if( TString(flavor).Contains("em")  ) trigeff = 0.95;
  //else if( TString(flavor).Contains("all") ) trigeff = 0.95;

  TCut trigweight(Form("%.2f",trigeff));

  for( unsigned int imc = 0 ; imc < nmc ; imc++ ){
  //for( int imc = nmc-1 ; imc > -1 ; imc-- ){

    bool isSignal = TString( labels.at(imc) ).Contains("T2");

    mchist[imc] = new TH1F(Form("%s_mc_%i_%s",myvar,imc,flavor),Form("%s_mc_%i_%s",myvar,imc,flavor),nbins,xmin,xmax);
    mchist[imc]->Sumw2();

    chmc.at(imc)->Draw(Form("TMath::Min(%s,%f)>>%s_mc_%i_%s",var,xmax-0.01,myvar,imc,flavor),sel*weight*trigweight);

    if( isSignal ){
      mchist[imc]->SetFillColor( 0 );
      //mchist[imc]->SetLineStyle(2);
      mchist[imc]->SetLineWidth(2);
      mchist[imc]->SetLineColor( sigcolors[isigmc++] );
      if( TString( labels.at(imc) ).Contains("X5") ){
	mchist[imc]->Scale(5);
	cout << "Scaling signal MC by 5" << endl;
      }
      if( TString( labels.at(imc) ).Contains("X6") ){
	mchist[imc]->Scale(6);
	cout << "Scaling signal MC by 6" << endl;
      }
      if( TString( labels.at(imc) ).Contains("X10") ){
	mchist[imc]->Scale(10);
	cout << "Scaling signal MC by 10" << endl;
      }
    }else{
      mchist[imc]->SetLineWidth(1);
      mchist[imc]->SetFillColor( colors[imc] );
      mchist[imc]->SetLineColor( 1 );
    }

    //mcstack->Add( mchist[imc] );

    if( !isSignal ){
      mcstack->Add( mchist[imc] );

      if( imc == 0 ){
	mctothist = (TH1F*) mchist[imc]->Clone();
	smtothist = (TH1F*) mchist[imc]->Clone();
      }
      else{
	mctothist->Add(mchist[imc]);
	smtothist->Add(mchist[imc]);
      }
    }
    else{
      mctothist->Add(mchist[imc]);
      sighist.push_back( mchist[imc] );
    }

    cout << "MC yield " << labels[imc] << " " << Form("%.2f",mchist[imc]->Integral()) << endl;
  }

  chdata->Draw(Form("TMath::Min(%s,%f)>>%s_datahist_%s",var,xmax-0.01,myvar,flavor),sel);

  if( overlayData ){

    float max = datahist->GetMaximum() + datahist->GetBinError(datahist->GetMaximumBin());
    if( mctothist->GetMaximum() > max ) max = mctothist->GetMaximum();
    if( log ) datahist->SetMaximum( 15 * max );
    else      datahist->SetMaximum( 1.4 * max );

    datahist->GetXaxis()->SetTitle(xtitle);
    datahist->Draw("E1");
    mcstack->Draw("samehist");
    
    for( unsigned int isig = 0 ; isig < sighist.size() ; isig++ ){
      sighist.at(isig)->Add(smtothist);
      sighist.at(isig)->Draw("samehist");
    } 

    datahist->Draw("sameE1");
    datahist->Draw("sameaxis");

    if(!log) datahist->GetYaxis()->SetRangeUser(0.,1.4*max);
    
  }
  else{
    float max = mctothist->GetMaximum();
    if( log ) mctothist->SetMaximum( 15 * max );
    else      mctothist->SetMaximum( 1.4 * max );

    mctothist->SetLineColor(0);
    mctothist->SetFillColor(0);

    mctothist->GetXaxis()->SetTitle(xtitle);
    mctothist->Draw("hist");
    mcstack->Draw("samehist");

    for( unsigned int isig = 0 ; isig < sighist.size() ; isig++ ){
      sighist.at(isig)->Add(smtothist);
      sighist.at(isig)->Draw("samehist");
    } 

    mctothist->Draw("sameaxis");
  }

  if( drawLegend ){
    TLegend* myleg = getLegend( chmc , labels , overlayData );
    myleg->Draw();
  }

  TLatex *text = new TLatex();
  text->SetNDC();
  text->SetTextSize(0.04);
  text->DrawLatex(0.2,0.88,"CMS Preliminary");
  //text->DrawLatex(0.2,0.83,"0.98 fb^{-1} at #sqrt{s} = 7 TeV");
  text->DrawLatex(0.2,0.83,"#sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 1.0 fb^{-1}");

  if     ( TString(flavor).Contains("e")  )  text->DrawLatex(0.2,0.78,"e-channel");
  else if( TString(flavor).Contains("m")  )  text->DrawLatex(0.2,0.78,"#mu-channel");
  else if( TString(flavor).Contains("all") ) text->DrawLatex(0.2,0.78,"e/#mu-channel");

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

    respad = new TPad("respad","respad",0,0.8,1,1);
    respad->Draw();
    respad->cd();

    //gPad->SetGridy();

    TH1F* ratio = (TH1F*) datahist->Clone(Form("%s_ratio",datahist->GetName()));
    ratio->Divide(smtothist);

    ratio->GetYaxis()->SetTitleOffset(0.3);
    ratio->GetYaxis()->SetTitleSize(0.2);
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetYaxis()->SetLabelSize(0.2);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->GetYaxis()->SetTitle("data/SM  ");
    ratio->GetXaxis()->SetLabelSize(0);
    ratio->GetXaxis()->SetTitleSize(0);
    ratio->SetMarkerSize(1);
    ratio->Draw();

    TLine line;
    line.SetLineWidth(1);
    line.DrawLine(datahist->GetXaxis()->GetXmin(),1,datahist->GetXaxis()->GetXmax(),1);

  }






}
Ejemplo n.º 15
0
void DrawQCDClosure(TString VAR,TString XTITLE)
{
  gROOT->ForceStyle();
  TString FileName[7] = {"QCD_HT200to300","QCD_HT300to500","QCD_HT500to700","QCD_HT700to1000","QCD_HT1000to1500","QCD_HT1500to2000","QCD_HT2000toInf"};
  float XSEC[7]       = {1.74e+6,3.67e+5,2.94e+4,6.524e+03,1.064e+03,121.5,2.542e+01};
  TFile *inf[7];
  TH1F  *h[7],*h1[7];

  TCanvas *can = new TCanvas("can_QCDClosure_"+VAR,"can_QCDClosure_"+VAR,900,600);
  can->cd(1);
  can->SetBottomMargin(0.3);
  can->SetRightMargin(0.15);

  for(int i=0;i<7;i++) {
    inf[i] = TFile::Open("Histo_"+FileName[i]+".root");
    TH1F *hTriggerPass = (TH1F*)inf[i]->Get("hadtopL/TriggerPass");
    h[i]   = (TH1F*)inf[i]->Get("hadtopL/h_"+VAR);
    h1[i]   = (TH1F*)inf[i]->Get("hadtop/h_"+VAR);
    h[i]->Sumw2();
    h1[i]->Sumw2();
    h[i]->Rebin(5);
    h1[i]->Rebin(5);
    h[i]->Scale(XSEC[i]/hTriggerPass->GetBinContent(1));
    h1[i]->Scale(XSEC[i]/hTriggerPass->GetBinContent(1));
    cout<<hTriggerPass->GetBinContent(1)<<endl;
  }

  TH1F *hQCD  = (TH1F*)h[0]->Clone("hQCD");
  TH1F *hQCD1 = (TH1F*)h1[0]->Clone("hQCD1");
  for(int i=0;i<7;i++) {
    hQCD->Add(h[i]);
    hQCD1->Add(h1[i]);
  } 
  hQCD->SetFillColor(kGray);

  hQCD->Scale(1./hQCD->Integral());
  hQCD1->Scale(1./hQCD1->Integral());
  hQCD->GetXaxis()->SetLabelSize(0.0);
  double max = 1.1*TMath::Max(hQCD->GetBinContent(hQCD->GetMaximumBin()),hQCD1->GetBinContent(hQCD1->GetMaximumBin()));
  hQCD->SetMinimum(1e-5);
  hQCD->SetMaximum(max);
  hQCD->Draw("hist");
  hQCD1->Draw("sameE");
  gPad->RedrawAxis();

  TLegend *leg = new TLegend(0.86,0.65,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"Control","F");
  leg->AddEntry(hQCD1,"Signal","LP");
  leg->Draw();

  TH1F *hRatio = (TH1F*)hQCD1->Clone("Ratio");
  hRatio->Divide(hQCD);

  TPad* pad = new TPad("pad", "pad", 0., 0., 1., 1.);
  pad->SetTopMargin(0.7);
  pad->SetRightMargin(0.15);
  pad->SetFillColor(0);
  pad->SetFillStyle(0);
  pad->Draw();
  pad->cd(0);
  gPad->SetGridy();
  hRatio->GetXaxis()->SetTitle(XTITLE);
  hRatio->GetYaxis()->SetNdivisions(505);
  hRatio->GetYaxis()->SetRangeUser(0,2);
  hRatio->GetYaxis()->SetLabelSize(0.04);
  hRatio->Draw();
}
Ejemplo n.º 16
0
void DrawFits(TemplateFIT * FIT,FileSaver finalHistos,FileSaver Plots){

	std::string pathdata  = (FIT->GetName() + "/Fit Results/Data");
	std::string pathtemplP= (FIT->GetName() + "/Fit Results/ScaledTemplatesP");
	std::string pathtemplD= (FIT->GetName() + "/Fit Results/ScaledTemplatesD");	
	std::string pathtemplHe=(FIT->GetName() + "/Fit Results/ScaledTemplatesHe");	

	std::string pathfit   = (FIT->GetName() + "/Fit Results/FractionFits");
	std::string pathtrans = (FIT->GetName() + "/Fit Results/TrasnferFunctions");
	std::string pathres   = (FIT->GetName() + "/Fit Results/");
	
	TFile * infile = finalHistos.GetFile();	


	for(int i=1; i<FIT->GetBinning().size();i++){
		
		std::string pathbinP    = pathtemplP + "/Bin"+to_string(i);
		std::string pathbinD    = pathtemplD + "/Bin"+to_string(i);
		std::string pathbinHe   = pathtemplHe+ "/Bin"+to_string(i);
		std::string pathbindata = pathdata   + "/Bin"+to_string(i);
		std::string pathbinfit  = pathfit    + "/Bin"+to_string(i);

		std::vector<TH1F*> TemplatesP=GetListOfTemplates(infile, pathbinP);
		std::vector<TH1F*> TemplatesD=GetListOfTemplates(infile, pathbinD);		
		std::vector<TH1F*> TemplatesHe=GetListOfTemplates(infile, pathbinHe);		
		std::vector<TH1F*> Datas     =GetListOfTemplates(infile, pathbindata);
		std::vector<TH1F*> Fits      =GetListOfTemplates(infile, pathbinfit);
		std::vector<TH1F*> Transfer  =GetListOfTemplates(infile, pathtrans);

		cout<<pathbinHe<<" "<<TemplatesHe.size()<<" "<<TemplatesHe[0]<<endl;
	

		TCanvas * c1 = new TCanvas("Modified Templates");
		c1->SetCanvasSize(2000,1500);

		for(int j=TemplatesP.size()-1;j>=0;j--){
			if(j==0) PlotDistribution(gPad, TemplatesP[j],"Reconstructed Mass [GeV/c^2]","Counts",1,"same",1,TemplatesP[j]->GetBinContent(TemplatesP[j]->GetMaximumBin())*1.13,10);
			else     PlotDistribution(gPad, TemplatesP[j],"Reconstructed Mass [GeV/c^2]","Counts",colorbase + j,"same",1,TemplatesP[j]->GetBinContent(TemplatesP[j]->GetMaximumBin())*1.13,7,"",false,false,true);		
		}
	
		Plots.Add(c1);
		Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());	


		TCanvas * c2 = new TCanvas("Modified T. Fits");
                c2->SetCanvasSize(2000,1500);

		PlotDistribution(gPad, TemplatesP[0], "Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Original Protons MC Template");
		PlotDistribution(gPad, TemplatesD[0], "Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,10,"Original Deuterons MC Template");
		PlotDistribution(gPad, TemplatesHe[0],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,10,"Original He Fragm. MC Template");

		for(int j=TemplatesP.size()-1;j>=1;j--){
                        PlotDistribution(gPad, TemplatesP[j],"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,1e5,1,"",false,false,true);
			PlotDistribution(gPad, TemplatesD[j],"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,1,"",false,false,true);
                	//PlotDistribution(gPad, TemplatesHe[j],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,1,"",false,false,true);
		}
		PlotDistribution(gPad, Datas[0],"Reconstructed Mass [GeV/c^2]","Counts",1,"ePsame",1,1e5,3,"ISS data",false,true);
	


		Plots.Add(c2);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());
		
		
		TCanvas * c3 = new TCanvas("Template Fits");
                c3->SetCanvasSize(2000,1500);

		PlotDistribution(gPad, TemplatesP[0] ,"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,2,"Original Protons MC Template");
		PlotDistribution(gPad, TemplatesD[0] ,"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,2,"Original Deuterons MC Template");
		PlotDistribution(gPad, TemplatesHe[0],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,2,"Original He Fragm. MC Template");
		PlotDistribution(gPad, TemplatesP[1] ,"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Best #chi^{2} Protons MC Template");
		PlotDistribution(gPad, TemplatesD[1] ,"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,1e5,10,"Best #chi^{2} Deuterons MC Template");
		PlotDistribution(gPad, TemplatesHe[1],"Reconstructed Mass [GeV/c^2]","Counts",3,"same",1,1e5,10,"Best #chi^{2} he Fragm. MC Template");
		

		PlotDistribution(gPad, Datas[0],"Reconstructed Mass [GeV/c^2]","Counts",1,"ePsame",1,1e5,3,"ISS data",false,true);
		if(Fits.size()>0) PlotDistribution(gPad, Fits[0],"Reconstructed Mass [gev/c^2]","counts",6,"same",1,1e5,4,"Fraction Fit");
	

		Plots.Add(c3);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());

		TCanvas * c5 = new TCanvas("Transfer Functions");
                c5->SetCanvasSize(2000,1500);

		for(int j=0;j<Transfer.size();j++){
			Transfer[j]->Smooth(3);
			PlotDistribution(gPad, Transfer[j],"Reconstructed Mass [GeV/c^2]","Prim. / (Prim. + Sec.)",j,"hist,same",0,1,7,("Bin. "+to_string(j)).c_str(),false,false);
		}

		Plots.Add(c5);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits").c_str());

	

		TCanvas * c4 = new TCanvas("ChiSquare");
                c4->SetCanvasSize(2000,1500);
		gPad->SetLogz();	
		TH2F * Chi = (TH2F*) infile->Get((FIT->GetName()+"/Fit Results/Spreads/ChiSquare/ChiSquare Bin "+to_string(i)).c_str());
                Chi->GetZaxis()->SetRangeUser(0.2,100);
                PlotTH2F(gPad, Chi, "Additive #sigma","Mean shift", "colz");	


		Plots.Add(c4);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());

		TCanvas * c6 = new TCanvas("OverCutoff Events");
                c6->SetCanvasSize(2000,1500);
			
		TH1F * OverCutoffP = (TH1F *) TemplatesP[1]->Clone();
		OverCutoffP->Multiply(Transfer[i]);
		TH1F * OverCutoffD = (TH1F *) TemplatesD[1]->Clone();
		OverCutoffD->Multiply(Transfer[i]);
		TH1F * NoCutoffP = (TH1F *) TemplatesP[1]->Clone();

		NoCutoffP->Scale(
			OverCutoffP->GetBinContent(OverCutoffP->GetMaximumBin())/
			NoCutoffP->GetBinContent(NoCutoffP->GetMaximumBin()) );

		PlotDistribution(gPad, NoCutoffP,"Reconstructed Mass [GeV/c^2]","Primary Counts",2,"same",1,Datas[1]->GetBinContent(Datas[1]->GetMaximumBin())*1.13,3,"Best #chi^{2} Protons MC Template");
		PlotDistribution(gPad, OverCutoffP,"Reconstructed Mass [GeV/c^2]","Counts",2,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Best #chi^{2} Protons MC (Cutoff filtered)");
		PlotDistribution(gPad, OverCutoffD,"Reconstructed Mass [GeV/c^2]","Counts",4,"same",1,Datas[0]->GetBinContent(Datas[0]->GetMaximumBin())*1.13,10,"Best #chi^{2} Deutons MC (Cutoff filtered)");
		PlotDistribution(gPad, Datas[1],"Reconstructed Mass [GeV/c^2]","Primary Counts",1,"ePsame",1,Datas[1]->GetBinContent(Datas[1]->GetMaximumBin())*1.13,3,"ISS data",false,true);
	

		Plots.Add(c6);
                Plots.writeObjsInFolder((FIT->GetName()+"/Fits/Bin"+to_string(i)).c_str());


	

	}

	return;

}
Ejemplo n.º 17
0
//............................................
// Constructor for accpetance from a ROOT Tfile
SlicedAcceptance::SlicedAcceptance( string type, string fileName,string histName, bool fluctuate, bool quiet ) :
	slices(), nullSlice(new AcceptanceSlice(0.,0.,0.)), tlow(), thigh(), beta(), _sortedSlices(false), maxminset(false), t_min(0.), t_max(0.), _hasChecked(false), _storedDecision(false)
{
	if(!quiet) cout << "Root file being used for acceptance" << endl;
	(void)type;
	if( type != "RootFile" ) {   }//do nothing for now

	string fullFileName = StringProcessing::FindFileName( fileName, quiet );

	if( !quiet ) cout << "Opening: " << fullFileName << endl;

	TFile* file = TFile::Open(TString(fullFileName));
 	if(!quiet) cout << "File " << fullFileName << " opened!" << endl;
	TH1F* histo = (TH1F*)file->Get(TString(histName));
	if(!quiet) cout << "Histo " << histName << " opened!" << endl;
	histo->Draw();
	if(!quiet) cout << "Histo " << histName << " drawn!" << endl;
//	histo->Sumw2();

	if(fluctuate){
	cout << "WARNING! You have fluctuated the acceptance." << endl;
	cout << "WARNING! This is for systematic studies only. " << endl;
	cout << "WARNING! Projections and pull fits will have a different fluctuated acceptance to the PDF you fit with." << endl;
	cout << "WARNING! ONLY USE FluctuateAcceptance:True FOR SYSTEMATIC STUDIES" << endl;
	TRandom3 * rng = new TRandom3(0);	
	//Randomly fluctuate bin contents within error: 
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
	if(!quiet)	cout << "Bin content and error before: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l);
		histo->SetBinContent(l,rng->Gaus(histo->GetBinContent(l),histo->GetBinError(l)));
	if(!quiet)	cout <<  " and after: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l) << endl;
	}
	delete rng;
	}

	histo->Scale(1./(histo->GetBinContent(histo->GetMaximumBin())));
	histo->SetMinimum(0);


	double maxend = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double height;
	double start;
	double end  = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double dheight;
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
		height = histo->GetBinContent(l);
		dheight = height;
		for (int n = l; n>0; n--){
			if(histo->GetBinContent(n)<height){
				dheight = height - histo->GetBinContent(n);
				cout << l << " " << n << " " << dheight << endl;
				break;
			}
		}
		start = histo->GetBinLowEdge(l);
		end = maxend;
		for (int m = l; m <= histo->GetNbinsX(); ++m){
			double thisbinheight = histo->GetBinContent(m);
			if(thisbinheight<height){
				end = histo->GetBinLowEdge(m);
				break;
			}
		}
		slices.push_back( new AcceptanceSlice( start, end, dheight ) );
	if(!quiet)	cout << start << "	" << end << "      " << dheight << endl;
	}
	histo->Delete();
//	delete histo;
	file->Close();
	delete file;

	if( !quiet ) cout << "Time Acc Slices: " << slices.size() << endl;
	if( slices.size() == 1 )
	{
		cout << "SlicedAcceptance: SERIOUS ERROR" << endl;
		exit(0);
	}
	//....done.....


	_sortedSlices = this->isSorted();

	if( _sortedSlices )
	{
		if( !quiet ) cout << "Sliced Acceptance is using sorted horizontal slices" << endl;
	}
	else
	{
		if( !quiet ) cout << "Sliced Acceptance is NOT using sorted horizontal slices" << endl;
	}
}
Ejemplo n.º 18
0
void compareSherpaMadgraph(std::string sherpafile, std::string madgraphfile,
                           std::string var,
                           float xmin=-9999.0, float xmax=-9999.0,
                           bool logScale=false,
                           std::string output="test")
{

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

    TH1F* hsherpa;
    TH1F* hmadgraph;

    char tempName[300];


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

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

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

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

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

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

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

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


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

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

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

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

    }

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

    }


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


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


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

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


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

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

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



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


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

    std::string filename;
    std::string psname = dirName + "/" + var;
    if(output !="test")
        psname = dirName+ "/" + output;
    else
        psname = dirName+ "/" + var;
    filename = psname + ".eps";
    c1->Print(filename.data());
    filename = psname + ".gif";
    c1->Print(filename.data());
    filename = psname + ".pdf";
    c1->Print(filename.data());
    //   c1->Close();
}
Ejemplo n.º 19
0
int recoEff01multi(vector<FileEntry> fileVec, string name, string toPlot, int nBins, double lo, double hi, string unit, string cutAll = "", string cutPass = "")
{
    setTDRStyle();
    TCanvas *c1 = new TCanvas("c1","c1",400,400); // distribution of all (=100%)
    TCanvas *c2 = new TCanvas("c2","c2",300,800); // efficiency
    string plotstring = "(" + toString(nBins) + "," + toString(lo) + "," + toString(hi) + ")";
    int i(0);
    Double_t binwidth = (hi-lo)/nBins;
    double h0Entries(0);
    double maxValue(0);
    // prepare the legend
    TLegend *legend = new TLegend(0.40,0.75,0.83,0.90);
    legend->SetFillStyle(1000);
    legend->SetBorderSize(1.);
    legend->SetTextSize(0.03);
    legend->SetFillColor(0);
    TLegend *legendEff = new TLegend(0.20,0.76,0.82,0.90);
    legendEff->SetFillStyle(1000);
    legendEff->SetBorderSize(1.);
    legendEff->SetTextSize(0.04);
    legendEff->SetFillColor(0);
    // do the plots
    for(vector<FileEntry>::iterator it = fileVec.begin(); it!=fileVec.end(); it++)
    {
	// first draw the 100% plot
	c1->cd();
	it->tree->Draw((toPlot+it->particle+">>h"+toString(i)+plotstring).c_str(), cutAll.c_str(), (i!=0 ? "same" : ""));
	TH1F *h = (TH1F*)gDirectory->GetList()->FindObject(("h"+toString(i)).c_str());
	h->SetMarkerStyle(8);
	h->SetMarkerColor(it->markercol);
	h->Sumw2();
	h->SetMinimum(0.0);
	h->SetTitle("");
	h->GetXaxis()->SetTitle((toPlot+" (MC)"+(unit.size()>0 ? " ["+unit+"]" : "")).c_str());
	h->GetXaxis()->SetLabelOffset(+0.006);
	h->GetXaxis()->SetTitleOffset(1.00);
	h->GetXaxis()->SetNdivisions(10505);
	h->GetYaxis()->SetTitle((unit.size()>0 ? "Entries per " + toString(binwidth) + " " + unit : "Entries per bin").c_str());
	legend->AddEntry(h, (it->title+" ("+toString(h->GetEntries())+" entries)").c_str(),"p");
	// now for the pass plot
	c2->cd();
	it->tree->Draw((toPlot+it->particle+">>heff"+toString(i)+plotstring).c_str(), cutPass.c_str(), (i!=0 ? "same" : ""));
	TH1F *heff = (TH1F*)gDirectory->GetList()->FindObject(("heff"+toString(i)).c_str());
	heff->Sumw2();
	heff->Divide(h);
	heff->SetMinimum(0.0);
	heff->SetMaximum(1.0);
	heff->SetMarkerStyle(7);
	heff->SetMarkerColor(it->markercol);
	if (i==0)
	    heff->Draw("pe");
	else
	    heff->Draw("samepe");
	heff->SetTitle("");
	heff->GetXaxis()->SetTitle((toPlot+" (MC)"+(unit.size()>0 ? " ["+unit+"]" : "")).c_str());
	heff->GetXaxis()->SetLabelOffset(-0.016);
	heff->GetXaxis()->SetTitleOffset(0.40);
	heff->GetXaxis()->SetNdivisions(10505);
	heff->GetYaxis()->SetTitle("Efficiency MC/reco");
	legendEff->AddEntry(h, (it->title+" ("+toString(h->GetEntries())+" entries)").c_str(),"p");
	// revisiting h and detect scaling factor
	if (i==0)
	    h0Entries = h->GetEntries();
	else
	{
	    const double scalefactor = h0Entries / h->GetEntries();
	    h->Scale(scalefactor);
	}
	maxValue = std::max(h->GetBinContent(h->GetMaximumBin()),maxValue);
	// counter increase
	i++;
    }
    gPad->SetLeftMargin(0.15);
    gPad->SetRightMargin(0.15);
    gPad->SetBottomMargin(0.05);
    gPad->SetTopMargin(0.04);
    const double scaleMax(1.35);
    for(i=0; i!=fileVec.size(); i++)
	((TH1F*)gDirectory->GetList()->FindObject(("h"+toString(i)).c_str()))->SetMaximum(maxValue*scaleMax);
    TGaxis::SetMaxDigits(4);
    c1->cd();
    gPad->SetLeftMargin(0.15);
    gPad->SetRightMargin(0.15);
    gPad->SetBottomMargin(0.15);
    gPad->SetTopMargin(0.08);
    legend->Draw();
    c2->cd();
    gPad->SetLeftMargin(0.15);
    gPad->SetRightMargin(0.15);
    gPad->SetBottomMargin(0.05);
    gPad->SetTopMargin(0.04);
    legendEff->Draw();
    c1->SaveAs(("recoEff01plotMulti_"+name+"_MC.pdf").c_str());
    c2->SaveAs(("recoEff01plotMulti_"+name+"_eff.pdf").c_str());

    return 0;
}
Ejemplo n.º 20
0
int ntuAnalyzer(std::string fileName)
{
  setGlobalStyle();
  
  //###############################
  //## run274200 ##
  unsigned int HT250Calo  = 9; //index of DST_HT250_CaloScouting_v   old:1 ref:9
  float HT250Calo_rate = 1928;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      ++bin;
    }

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

  totRateVsCut->SetTitle("Rate Ref");

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

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

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

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


  return 0;
}
void 
HTT_TT_X(bool scaled=true, bool log=false, float min=0., float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("emu_0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(directory) == std::string("emu_0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(directory) == std::string("emu_boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(directory) == std::string("emu_boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(directory) == std::string("emu_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("emu_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("emu_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  ZH#rightarrow#lltau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  ZH#rightarrowll#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile);
  TH1F* ZZ  = refill((TH1F*)input->Get(TString::Format("%s/ZZ"   , directory)), "ZZ"); InitHist(ZZ, "", "", kMagenta-10, 1001);
  TH1F* GGToZZ2L2L  = refill((TH1F*)input->Get(TString::Format("%s/GGToZZ2L2L"   , directory)), "GGToZZ2L2L"); InitHist(GGToZZ2L2L, "", "", kMagenta-10, 1001);
  TH1F* Zjets    = refill((TH1F*)input->Get(TString::Format("%s/Zjets"     , directory)), "Zjets"  ); InitHist(Zjets  , "", "", kRed    + 2, 1001);
#ifndef DROP_SIGNAL
  TH1F* ZH_htt    = refill((TH1F*)input->Get(TString::Format("%s/ZH_htt"  , directory)+"125"), "ZH_htt"  ); InitSignal(ZH_htt); ZH_htt->Scale(SIGNAL_SCALE);
  TH1F* ZH_hww    = refill((TH1F*)input->Get(TString::Format("%s/ZH_hww"  , directory)+"125"), "ZH_hww"  ); InitSignal(ZH_hww); ZH_hww->Scale(SIGNAL_SCALE);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)ZZ->Clone("ref");
  ref->Add(GGToZZ2L2L);
  ref->Add(Zjets  );

  double unscaled[5];
  unscaled[0] = ZZ->Integral();
  unscaled[1] = GGToZZ2L2L->Integral();
  unscaled[2] = Zjets  ->Integral();
#ifndef DROP_SIGNAL
  unscaled[3] = ZH_htt  ->Integral();
  unscaled[4] = ZH_hww  ->Integral();
#endif

  if(scaled){
    rescale(ZZ, 1);
    rescale(GGToZZ2L2L, 2);
    rescale(Zjets,   3);
#ifndef DROP_SIGNAL
    rescale(ZH_htt,   4);
    rescale(ZH_hww,   5);
#endif
  }

  TH1F* scales[5];
  scales[0] = new TH1F("scales-ZZ", "", 5, 0, 5);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZZ->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-GGToZZ2L2L", "", 5, 0, 5);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (GGToZZ2L2L->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-Zjets"  , "", 5, 0, 5);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (Zjets  ->Integral()/unscaled[2]-1.) : 0.);
#ifndef DROP_SIGNAL
  scales[3] = new TH1F("scales-ZH_htt"  , "", 5, 0, 5);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (ZH_htt  ->Integral()/unscaled[3]-1.) : 0.);
  scales[4] = new TH1F("scales-ZH_hww"  , "", 5, 0, 5);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ZH_hww  ->Integral()/unscaled[4]-1.) : 0.);
#endif

  GGToZZ2L2L->Add(Zjets);
  ZZ  ->Add(GGToZZ2L2L);
  if(log){
#ifndef DROP_SIGNAL
    ZH_htt  ->Add(ZH_hww );
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ZH_htt   ->Add(ZH_hww);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  float maxZZ=ZZ->GetBinContent(ZZ->GetMaximumBin()); float maxdata=data->GetBinContent(data->GetMaximumBin());
  if (maxdata>maxZZ)
     data->SetMaximum(1.8*maxdata);
  else
     data->SetMaximum(1.8*maxZZ);
  data->Draw("e");

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

//  //CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);  
  CMSPrelim(dataset, "", 0.16, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  if (directory=="eett_zh") 
    chan->AddText("#tau#tau");
  else
    chan->AddText("#mu#mu#tau#tau");
  chan->Draw();
//
//  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
//  cat->SetBorderSize(   0 );
//  cat->SetFillStyle(    0 );
//  cat->SetTextAlign(   12 );
//  cat->SetTextSize ( 0.05 );
//  cat->SetTextColor(    1 );
//  cat->SetTextFont (   62 );
//  cat->AddText(category_extra);
//  cat->Draw();
//
//#ifdef MSSM
//  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
//  massA->SetBorderSize(   0 );
//  massA->SetFillStyle(    0 );
//  massA->SetTextAlign(   12 );
//  massA->SetTextSize ( 0.03 );
//  massA->SetTextColor(    1 );
//  massA->SetTextFont (   62 );
//  massA->AddText("m_{A}=$MAGeV");
//  massA->Draw();
//
//  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
//  tanb->SetBorderSize(   0 );
//  tanb->SetFillStyle(    0 );
//  tanb->SetTextAlign(   12 );
//  tanb->SetTextSize ( 0.03 );
//  tanb->SetTextColor(    1 );
//  tanb->SetTextFont (   62 );
//  tanb->AddText("tan#beta=$TANB");
//  tanb->Draw();
// 
//  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
//  scen->SetBorderSize(   0 );
//  scen->SetFillStyle(    0 );
//  scen->SetTextAlign(   12 );
//  scen->SetTextSize ( 0.03 );
//  scen->SetTextColor(    1 );
//  scen->SetTextFont (   62 );
//  scen->AddText("mhmax");
//  scen->Draw();
//#endif
//
//#ifdef MSSM  
//  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.90);
//  SetLegendStyle(leg);
//  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
//#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
//#ifndef DROP_SIGNAL
//  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ZH_htt  , TString::Format("%.0f#timesZH(125 GeV)#rightarrowll#tau#tau", SIGNAL_SCALE) , "L" );
//  }
//  else{
//    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
//  }
//#endif
//#endif
  leg->AddEntry(data , "observed"                       , "LP");
  leg->AddEntry(ZZ  , "ZZ"           , "F" );
  leg->AddEntry(Zjets, "Reducible"                       , "F" );
//  leg->AddEntry(EWK  , "electroweak"                    , "F" );
//  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();
//
////#ifdef MSSM
////  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
////  mssm->SetBorderSize(   0 );
////  mssm->SetFillStyle(    0 );
////  mssm->SetTextAlign(   12 );
////  mssm->SetTextSize ( 0.03 );
////  mssm->SetTextColor(    1 );
////  mssm->SetTextFont (   62 );
////  mssm->AddText("(m_{A}=250, tan#beta=5)");
////  mssm->Draw();
////#else
////  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
////  mssm->SetBorderSize(   0 );
////  mssm->SetFillStyle(    0 );
////  mssm->SetTextAlign(   12 );
////  mssm->SetTextSize ( 0.03 );
////  mssm->SetTextColor(    1 );
////  mssm->SetTextFont (   62 );
////  mssm->AddText("m_{H}=125");
////  mssm->Draw();
////#endif
//
//  /*
//    Ratio Data over MC
//  */
//  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
//  canv0->SetGridx();
//  canv0->SetGridy();
//  canv0->cd();
//
//  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
//  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
//  rat1->Divide(Ztt);
//  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
//    if(rat1->GetBinContent(ibin+1)>0){
//      // catch cases of 0 bins, which would lead to 0-alpha*0-1
//      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
//    }
//    zero->SetBinContent(ibin+1, 0.);
//  }
//  rat1->SetLineColor(kBlack);
//  rat1->SetFillColor(kGray );
//  rat1->SetMaximum(+0.5);
//  rat1->SetMinimum(-0.5);
//  rat1->GetYaxis()->CenterTitle();
//  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
//  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
//  rat1->Draw();
//  zero->SetLineColor(kBlack);
//  zero->Draw("same");
//  canv0->RedrawAxis();
//
//  /*
//    Ratio After fit over Prefit
//  */
//  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
//  canv1->SetGridx();
//  canv1->SetGridy();
//  canv1->cd();
//
//  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
//  rat2->Divide(ref);
//  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
//    if(rat2->GetBinContent(ibin+1)>0){
//      // catch cases of 0 bins, which would lead to 0-alpha*0-1
//      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
//    }
//  }
//  rat2->SetLineColor(kRed+ 3);
//  rat2->SetFillColor(kRed-10);
//  rat2->SetMaximum(+0.3);
//  rat2->SetMinimum(-0.3);
//  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
//  rat2->GetYaxis()->CenterTitle();
//  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
//  rat2->GetXaxis()->SetRange(0, 28);
//  rat2->Draw();
//  zero->SetLineColor(kBlack);
//  zero->Draw("same");
//  canv1->RedrawAxis();
//
//  /*
//    Relative shift per sample
//  */
//  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
//  canv2->SetGridx();
//  canv2->SetGridy();
//  canv2->cd();
//
//  InitHist  (scales[0], "", "", kMagenta-10, 1001);
//  InitHist  (scales[1], "", "", kRed    + 2, 1001);
//  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
//  InitHist  (scales[3], "", "", kOrange - 4, 1001);
//#ifndef DROP_SIGNAL
//  InitSignal(scales[4]);
//  InitSignal(scales[5]);
//  InitSignal(scales[6]);
//#endif
//  scales[0]->Draw();
//  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
//  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
//  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
//  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
//#ifdef MSSM
//  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
//#else
//  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
//#endif
//  scales[0]->SetMaximum(+1.0);
//  scales[0]->SetMinimum(-1.0);
//  scales[0]->GetYaxis()->CenterTitle();
//  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
//  scales[1]->Draw("same");
//  scales[2]->Draw("same");
//  scales[3]->Draw("same");
//#ifndef DROP_SIGNAL
//  scales[4]->Draw("same");
//  scales[5]->Draw("same");
//  scales[6]->Draw("same");
//#endif
//  zero->Draw("same");
//  canv2->RedrawAxis();
//
//  /*
//    prepare output
//  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd(); 
  data ->Write("data_obs");
  ZZ->Write("ZZ"   );
  Zjets  ->Write("Zjets"     );
  ZH_htt->Write("ZH_htt"   );
  ZH_hww  ->Write("ZH_hww"     );
//#ifdef MSSM
//  ggH  ->Write("ggH"     );
//  bbH  ->Write("bbH"     );
//#else
//#ifndef DROP_SIGNAL
//  ggH  ->Write("ggH"     );
//  qqH  ->Write("qqH"     );
//  VH   ->Write("VH"      );
//#endif
//#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Ejemplo n.º 22
0
void compareDataMC( vector<TChain*> chmc , vector<char*> labels , TChain* chdata , char* var , 
		    TCut sel , TCut weight , int nbins ,  float xmin , float xmax ,  
		    char* xtitle , bool overlayData , bool residual , bool drawLegend , bool log , char* flavor ){

  TPad* fullpad = new TPad();
  TPad* plotpad = new TPad();
  TPad* respad  = new TPad();

  if( residual ){
    fullpad = new TPad("fullpad","fullpad",0,0,1,1);
    fullpad->Draw();
    fullpad->cd();

    plotpad = new TPad("plotpad","plotpad",0,0,1,0.8);
    plotpad->Draw();
    plotpad->cd();
    if( log ) plotpad->SetLogy();
  }
  else{
    if( log ) gPad->SetLogy();
  }

  TString tvar(var);
  tvar.ReplaceAll("()","");
  tvar.ReplaceAll(".","");
  const char* myvar = tvar;

  cout << "Plotting var " << myvar << " flavor " << flavor << endl;

  //int colors[]={6,2,7,4,5,8,9,15,12};
  int colors[]={kBlue-6,kRed+2,7,5,5,8,9,15,12};

  assert( chmc.size() == labels.size() );
  const unsigned int nmc = chmc.size();

  THStack* mcstack = new THStack("mcstack","mcstack");
  TH1F*    mctothist = new TH1F();
  TH1F*    mchist[nmc];
  TH1F*    datahist = new TH1F(Form("%s_datahist_%s",myvar,flavor),Form("%s_datahist_%s",myvar,flavor),nbins,xmin,xmax);

  float trigeff = 1.0;
  //if     ( TString(flavor).Contains("ee")  ) trigeff = 1.00;
  //else if( TString(flavor).Contains("mm")  ) trigeff = 0.90;
  //else if( TString(flavor).Contains("em")  ) trigeff = 0.95;
  //else if( TString(flavor).Contains("all") ) trigeff = 0.95;
  if     ( TString(flavor).Contains("ee")  ) sel+="leptype==0";
  else if( TString(flavor).Contains("mm")  ) sel+="leptype==1";
  else if( TString(flavor).Contains("em")  ) sel+="leptype==2";
  //else if( TString(flavor).Contains("all") ) 

  TCut trigweight(Form("%.2f",trigeff));

  for( unsigned int imc = 0 ; imc < nmc ; imc++ ){
  //for( int imc = nmc-1 ; imc > -1 ; imc-- ){

    mchist[imc] = new TH1F(Form("%s_mc_%i_%s",myvar,imc,flavor),Form("%s_mc_%i_%s",myvar,imc,flavor),nbins,xmin,xmax);
    mchist[imc]->Sumw2();

    chmc.at(imc)->Draw(Form("TMath::Min(%s,%f)>>%s_mc_%i_%s",var,xmax-0.01,myvar,imc,flavor),sel*weight*trigweight);

    if( TString( labels.at(imc) ).Contains("LM") || TString( labels.at(imc) ).Contains("T2tt") ){
      mchist[imc]->SetFillColor( 0 );
      mchist[imc]->SetLineStyle(2);
    }else{
      mchist[imc]->SetFillColor( colors[imc] );
    }

    // if( strcmp(labels[imc],"ttfake")  == 0 || strcmp(labels[imc],"wjets")  == 0 ){
    //   cout << "Scaling " << labels[imc] << " by 3.8" << endl;
    //   mchist[imc]->Scale(3.8);
    // }

    mcstack->Add( mchist[imc] );

    if( imc == 0 ) mctothist = (TH1F*) mchist[imc]->Clone();
    else           mctothist->Add(mchist[imc]);

    cout << "MC yield " << labels[imc] << " " << Form("%.2f",mchist[imc]->Integral()) << endl;
  }

  chdata->Draw(Form("TMath::Min(%s,%f)>>%s_datahist_%s",var,xmax-0.01,myvar,flavor),sel);

  if( overlayData ){

    float max = datahist->GetMaximum() + datahist->GetBinError(datahist->GetMaximumBin());
    if( mctothist->GetMaximum() > max ) max = mctothist->GetMaximum();
    if( log ) datahist->SetMaximum( 15 * max );
    else      datahist->SetMaximum( 1.4 * max );

    datahist->GetXaxis()->SetTitle(xtitle);
    datahist->Draw("E1");
    mcstack->Draw("samehist");
    datahist->Draw("sameE1");
    datahist->Draw("sameaxis");
    
    if(!log) datahist->GetYaxis()->SetRangeUser(0.,1.4*max);
    
    cout << "data yield " << datahist->Integral() << endl;

  }
  else{
    mctothist->GetXaxis()->SetTitle(xtitle);
    mctothist->Draw();
    mcstack->Draw("same");
    mctothist->Draw("sameaxis");
  }

  if( drawLegend ){
    TLegend* myleg = getLegend( chmc , labels , overlayData );
    myleg->Draw();
  }

  TLatex *text = new TLatex();
  text->SetNDC();
  text->SetTextSize(0.05);
  text->DrawLatex(0.2,0.88,"CMS Preliminary");
  //text->DrawLatex(0.2,0.83,"0.98 fb^{-1} at #sqrt{s} = 7 TeV");
  text->DrawLatex(0.2,0.83,"#sqrt{s} = 7 TeV, #scale[0.6]{#int}Ldt = 4.3 fb^{-1}");

  if     ( TString(flavor).Contains("ee")  ) text->DrawLatex(0.2,0.78,"Events with ee");
  else if( TString(flavor).Contains("mm")  ) text->DrawLatex(0.2,0.78,"Events with #mu#mu");
  else if( TString(flavor).Contains("em")  ) text->DrawLatex(0.2,0.78,"Events with e#mu");
  else if( TString(flavor).Contains("all") ) text->DrawLatex(0.2,0.78,"Events with ee/#mu#mu/e#mu");

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

    respad = new TPad("respad","respad",0,0.8,1,1);
    respad->Draw();
    respad->cd();

    gPad->SetGridy();

    TH1F* ratio = (TH1F*) datahist->Clone(Form("%s_ratio",datahist->GetName()));
    ratio->Divide(mctothist);

    ratio->GetYaxis()->SetTitleOffset(0.3);
    ratio->GetYaxis()->SetTitleSize(0.2);
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetYaxis()->SetLabelSize(0.2);
    //ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->GetYaxis()->SetRangeUser(0.,2.);
    ratio->GetYaxis()->SetTitle("data/MC  ");
    ratio->GetXaxis()->SetLabelSize(0);
    ratio->GetXaxis()->SetTitleSize(0);
    ratio->SetMarkerSize(0.7);
    ratio->Draw();

    TLine line;
    line.SetLineWidth(1);
    line.DrawLine(datahist->GetXaxis()->GetXmin(),1,datahist->GetXaxis()->GetXmax(),1);

  }






}