Ejemplo n.º 1
0
// ______________________________________________________________________________________
void SaveCanvas(const Char_t* name, Bool_t isNice = kTRUE) {
  // -- Write out canvas
  
  gSystem->Exec(Form("mkdir -p results/nice/%s/png",  name));
  gSystem->Exec(Form("mkdir -p results/nice/%s/pdf",  name));
  gSystem->Exec(Form("mkdir -p results/nice/%s/eps",  name));
  gSystem->Exec(Form("mkdir -p results/nice/%s/gif",  name));
  gSystem->Exec(Form("mkdir -p results/nice/%s/root", name));
  if (isNice) {
    gSystem->Exec(Form("mkdir -p results/nice/pdf"));
    gSystem->Exec(Form("mkdir -p results/nice/png"));
  }

  // -----------------------------------------------------
  
  for (Int_t idx = 0; idx < canA.GetEntriesFast() ; ++idx) {
    TCanvas* c = static_cast<TCanvas*>(canA.At(idx));
    if (!c)
      continue;
    
    c->SaveAs(Form("results/nice/%s/png/%s.png",   name, c->GetName()));
    c->SaveAs(Form("results/nice/%s/eps/%s.eps",   name, c->GetName()));
    c->SaveAs(Form("results/nice/%s/gif/%s.gif",   name, c->GetName()));
    c->SaveAs(Form("results/nice/%s/pdf/%s.pdf",   name, c->GetName()));
    c->SaveAs(Form("results/nice/%s/root/%s.C",    name, c->GetName()));
    c->SaveAs(Form("results/nice/%s/root/%s.root", name, c->GetName()));
    if (isNice) {
      c->SaveAs(Form("results/nice/pdf/%s.pdf",            c->GetName()));
      c->SaveAs(Form("results/nice/png/%s.png",            c->GetName()));
    }
  }
}
Ejemplo n.º 2
0
//--- Print all created canvasses ---
void printAllCanvases(const char* folder="plots")
{
   TSeqCollection * sc = dynamic_cast<TSeqCollection*>(gROOT->GetListOfCanvases());
   for (int i =0; i<sc->GetSize(); ++i) {
      TCanvas * c = dynamic_cast<TCanvas*>(sc->At(i));
      TString cname(c->GetName());
      printf("Canvas: %s/%s.gif\n",folder,cname.Data());
      c->Print(Form("%s/%s.gif",folder,cname.Data()));
   }
}
Ejemplo n.º 3
0
// Print all canvases in a single PS file
void printCanvasesPS(TString name){
  TPostScript * ps = new TPostScript(name,112);
  TIter iter(gROOT->GetListOfCanvases());
  TCanvas *c;
  while( (c = (TCanvas *)iter()) )
    {
      cout << "Printing " << c->GetName() << endl;
      ps->NewPage();
      c->Draw();
    }
  cout << " File " << name << " was created" << endl;
  ps->Close();
}
void KVSpiderIdentificator::SaveAsPdf(Option_t* opt_, const Char_t* path_)
{
   Draw(opt_);
   TCanvas* cc = (TCanvas*) gROOT->FindObject(_htot->GetName());
   _htot->RebinX(4);
   _htot->RebinY(4);

   CheckPath(path_);

   cc->Print(Form("%s/%s.pdf", path_, cc->GetName()), "pdf");
   cc->Close();
   delete cc;
}
Ejemplo n.º 5
0
//__________________________________________________________
void AliTRDCheckPedestal(const Int_t runNr){
  // Establish grid connection
  if(!TGrid::Connect("alien://")){printf("F-No grid connection\n");return;}
  // Set the storage to the OCDB of this runNr. It will be like
  // alien://folder=/alice/data/2016/OCDB
  AliCDBManager *man = AliCDBManager::Instance();
  man->SetDefaultStorageFromRun(runNr);
  // We derive the reference storage from it
  const AliCDBStorage *stor =  man->GetDefaultStorage();
  TString folder = stor->GetBaseFolder();
  folder.ReplaceAll("OCDB","Reference");
  man->SetDefaultStorage(Form("alien://folder=%s",folder.Data()));
  // Set the run number
  man->SetRun(runNr);

  // We abuse the folder name to derive the year
  TString yearString(folder);
  yearString.ReplaceAll("/alice/data/","");
  yearString.ReplaceAll("/Reference/","");
  const Int_t year = yearString.Atoi();
  printf("W-Experimental: Derived year %d from storage folder\n",year);
  
  // The reference data is stored per Local Data Concentrator
  std::vector<Int_t> LDCvec = GetLDCVector(year);
  // Loop over LDCs
  for(std::vector<Int_t>::iterator LDCit = LDCvec.begin();LDCit!=LDCvec.end();LDCit++){
    const TString padstatus = Form("TRD/DAQData/PadStatus%d",*LDCit);
    AliCDBEntry *entry = AliCDBManager::Instance()->Get(padstatus.Data());
    AliTRDCalibPadStatus *calpadstatus = dynamic_cast<AliTRDCalibPadStatus *>(entry->GetObject());
    if(!calpadstatus){printf("E-Can not find %s in %s \n",padstatus.Data(),folder.Data());continue;}

    //Create the noise pad with the RMS values of each channel
    AliTRDCalPad *noisePad = calpadstatus->CreateCalPad();
    // LDC -> SM mapping
    std::vector<Int_t> SMvec = GetSMVector(year,*LDCit);
    for(std::vector<Int_t>::iterator SMit=SMvec.begin();SMit!=SMvec.end();SMit++){
      const TString padstatussm = Form("PadNoise-LDC%d-SM%02d",*LDCit,*SMit);
      TCanvas *cpadstatusm = new TCanvas(padstatussm.Data(),padstatussm.Data(),50,50,600,800);
      cpadstatusm->Divide(3,2);
      // Draw each layer (or here plane)
      const Float_t zRange[2]={0.,0.2};
      for(Int_t iLayer = 0;iLayer<6;iLayer++){
  	cpadstatusm->cd(iLayer+1);
	noisePad->MakeHisto2DSmPl(*SMit,iLayer,0,0,zRange[0],zRange[1],-1)->Draw("colz");
      }
      cpadstatusm->SaveAs(Form("%s.pdf",cpadstatusm->GetName()));
    } // Loop over SMs of this LDC
  } // End of loop over LDCs
} // End of void AliTRDcheckPedestal
Ejemplo n.º 6
0
void superimposeHistos()
{
  TFile* bFile = TFile::Open("Electron_In_Jets_900GeV_bJets.root");
  TFile* cFile = TFile::Open("Electron_In_Jets_900GeV_cJets.root");
  TFile* udsgFile = TFile::Open("Electron_In_Jets_900GeV_udsgJets.root");
  
  TIter next(bFile->GetListOfKeys());
  TFile* newFile = new TFile("testFile.root", "RECREATE");
  while(TKey* key = (TKey*)next())
  {
    TH1F* bHist = (TH1F*)bFile->Get(key->GetName());
    bHist->SetFillColor(2);
    
    TH1F* cHist = (TH1F*)cFile->Get(key->GetName());
    cHist->SetFillColor(3);
    
    TH1F* udsgHist = (TH1F*)udsgFile->Get(key->GetName());
    udsgHist->SetFillColor(4);
    
    THStack* stack = new THStack(bHist->GetName(), bHist->GetTitle());
    stack->Add(udsgHist, "hist ][");
    stack->Add(cHist, "hist ][");
    stack->Add(bHist, "hist ][");
    
    TLegend* legend = new TLegend(0.5, 0.68, 0.88, 0.88);
    legend->AddEntry(bHist, "b-Jets");
    legend->AddEntry(cHist, "c-Jets");
    legend->AddEntry(udsgHist, "udsg-Jets");
    
    TCanvas* canvas = new TCanvas(bHist->GetName());
    stack->Draw();
    stack->GetXaxis()->SetTitle(bHist->GetXaxis()->GetTitle());
    legend->Draw();
    canvas->Write(canvas->GetName());
  }
  
  newFile->Close();
  bFile->Close();
  cFile->Close();
  udsgFile->Close();
}
Ejemplo n.º 7
0
TList* extractObjectFromFile(const char* fileName, const char* name)
{
  TList* objects = new TList();
  TFile file(fileName);
  gROOT->cd();
  TList* keyList = file.GetListOfKeys();
  for (int i = 0; i < keyList->GetSize(); ++i) {
    TKey* key = static_cast<TKey*>(keyList->At(i));
    std::cout<< key->GetName()<< std::endl;
    if (!strcmp(key->GetName(), name)) {
      objects->Add(key->ReadObj()->Clone());
    } else if (!strcmp(key->GetClassName(), "TCanvas")) {
      TCanvas* canvas = static_cast<TCanvas*>(key->ReadObj());
      if (!strcmp(canvas->GetName(), name))
        objects->Add(canvas->Clone());
      TList* objectsFromPad = extractObjectFromPad(canvas, name);
      for (int j = 0; j < objectsFromPad->GetSize(); ++j)
        objects->Add(objectsFromPad->At(j));
    }
  }
  file.Close();
  return objects;
}
void plot( TString var, TString data, TString pdf, double low=-1, double high=-1 ) {

  TFile *tf = TFile::Open( "root/FitOut.root" );
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");
  TCanvas *canv = new TCanvas("c","c",800,800);
  TPad *upperPad = new TPad(Form("%s_upper",canv->GetName()),"",0.,0.33,1.,1.);
  TPad *lowerPad = new TPad(Form("%s_lower",canv->GetName()),"",0.,0.,1.,0.33);
  canv->cd();
  upperPad->Draw();
  lowerPad->Draw();

  if ( low < 0 ) low = w->var(var)->getMin();
  if ( high < 0 ) high = w->var(var)->getMax();
  RooPlot *plot = w->var(var)->frame(Range(low,high));
  w->data(data)->plotOn(plot);
  w->pdf(pdf)->plotOn(plot);

  RooHist *underHist = plot->pullHist();
  underHist->GetXaxis()->SetRangeUser(plot->GetXaxis()->GetXmin(), plot->GetXaxis()->GetXmax());
  underHist->GetXaxis()->SetTitle(plot->GetXaxis()->GetTitle());
  underHist->GetYaxis()->SetTitle("Pull");
  underHist->GetXaxis()->SetLabelSize(0.12);
  underHist->GetYaxis()->SetLabelSize(0.12);
  underHist->GetXaxis()->SetTitleSize(0.2);
  underHist->GetXaxis()->SetTitleOffset(0.7);
  underHist->GetYaxis()->SetTitleSize(0.18);
  underHist->GetYaxis()->SetTitleOffset(0.38);

  plot->GetXaxis()->SetTitle("");
  upperPad->SetBottomMargin(0.1);
  upperPad->cd();
  plot->Draw();

  canv->cd();
  lowerPad->SetTopMargin(0.05);
  lowerPad->SetBottomMargin(0.35);
  lowerPad->cd();
  underHist->Draw("AP");

  double ymin = underHist->GetYaxis()->GetXmin();
  double ymax = underHist->GetYaxis()->GetXmax();
  double yrange = Max( Abs( ymin ), Abs( ymax ) );
  underHist->GetYaxis()->SetRangeUser( -1.*yrange, 1.*yrange );

  double xmin = plot->GetXaxis()->GetXmin();
  double xmax = plot->GetXaxis()->GetXmax();

  TColor *mycol3sig = gROOT->GetColor( kGray );
  mycol3sig->SetAlpha(0.5);
  TColor *mycol2sig = gROOT->GetColor( kGray+1 );
  mycol2sig->SetAlpha(0.5);
  TColor *mycol1sig = gROOT->GetColor( kGray+2 );
  mycol1sig->SetAlpha(0.5);

  TBox box3sig;
  box3sig.SetFillColor( mycol3sig->GetNumber() );
  //box3sig.SetFillColorAlpha( kGray, 0.5 );
  box3sig.SetFillStyle(1001);
  box3sig.DrawBox( xmin, -3., xmax, 3.);
  TBox box2sig;
  box2sig.SetFillColor( mycol2sig->GetNumber() );
  //box2sig.SetFillColorAlpha( kGray+1, 0.5 );
  box2sig.SetFillStyle(1001);
  box2sig.DrawBox( xmin, -2., xmax, 2.);
  TBox box1sig;
  box1sig.SetFillColor( mycol1sig->GetNumber() );
  //box1sig.SetFillColorAlpha( kGray+2, 0.5 );
  box1sig.SetFillStyle(1001);
  box1sig.DrawBox( xmin, -1., xmax, 1.);

  TLine lineErr;
  lineErr.SetLineWidth(1);
  lineErr.SetLineColor(kBlue-9);
  lineErr.SetLineStyle(2);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),1.,plot->GetXaxis()->GetXmax(),1.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-1.,plot->GetXaxis()->GetXmax(),-1.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),2.,plot->GetXaxis()->GetXmax(),2.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-2.,plot->GetXaxis()->GetXmax(),-2.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),3.,plot->GetXaxis()->GetXmax(),3.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-3.,plot->GetXaxis()->GetXmax(),-3.);

  TLine line;
  line.SetLineWidth(3);
  line.SetLineColor(kBlue);
  line.DrawLine(plot->GetXaxis()->GetXmin(),0.,plot->GetXaxis()->GetXmax(),0.);
  underHist->Draw("Psame");

  RooHist *redPull = new RooHist();
  int newp=0;
  for (int p=0; p<underHist->GetN(); p++) {
    double x,y;
    underHist->GetPoint(p,x,y);
    if ( TMath::Abs(y)>3 ) {
      redPull->SetPoint(newp,x,y);
      redPull->SetPointError(newp,0.,0.,underHist->GetErrorYlow(p),underHist->GetErrorYhigh(p));
      newp++;
    }
  }
  redPull->SetLineWidth(underHist->GetLineWidth());
  redPull->SetMarkerStyle(underHist->GetMarkerStyle());
  redPull->SetMarkerSize(underHist->GetMarkerSize());
  redPull->SetLineColor(kRed);
  redPull->SetMarkerColor(kRed);
  redPull->Draw("Psame");

  canv->Print(Form("tmp/%s.pdf",var.Data()));
  tf->Close();

}
Ejemplo n.º 9
0
//______________________________________________________________________________
void CheckTime(const Char_t* loc)
{
    // Check time.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // create arrays
    const Int_t nCh = 352;
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/tagger_time.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d", i);
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("func", "gaus(0)+pol1(3)", -1000 , 1000);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();
        
        TH2* h2 = (TH2*) f->Get("CaLib_Tagger_Time");

        // loop over channels
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d", j);
            fROOTout->cd(t);
            sprintf(t, "%d_%d", i, j);
            TH1* h = h2->ProjectionX(t, j+1, j+1);
            h->Rebin(2);
            
            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            TLine* tline = 0;
            
            // check entries
            if (h->GetEntries())
            {
                // fit gaussian to peak
                Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
                func->SetParameters(1, maxPos, 0.5, 1, 0.1);
                func->SetRange(maxPos - 2, maxPos + 2);
                func->SetParLimits(0, 0, 1000);
                for (Int_t k = 0; k < 10; k++)
                    if (!h->Fit(func, "RBQ")) break;

                // save position in file and memory
                maxPos = func->GetParameter(1);
                pedPos[j][i] = maxPos;

                h->GetXaxis()->SetRangeUser(maxPos - 10, maxPos + 10);
                h->Draw();
                
                tline = new TLine(maxPos, 0, maxPos, 10000);
                tline->SetLineColor(kRed);
                tline->SetLineWidth(2);
                tline->Draw();
            }
            else
            {
                h->Draw();
            }

            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            if (tline) delete tline;
        }
        
        delete h2;
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating time graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d", j);
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
Ejemplo n.º 10
0
void CreateTemplatesForW(TString CAT, TString CUT)
{
  gROOT->ForceStyle();
  
  RooMsgService::instance().setSilentMode(kTRUE);
  RooMsgService::instance().setStreamStatus(0,kFALSE);
  RooMsgService::instance().setStreamStatus(1,kFALSE);

  TFile *infMC   = TFile::Open("Histo_TT_TuneCUETP8M1_13TeV-powheg-pythia8.root");
  TFile *infData = TFile::Open("Histo_JetHT.root");
    
  TH1F *hMC,*hData;
  RooDataHist *roohMC,*roohData;
  RooAddPdf *signal,*qcd;
  
  TString VAR,TAG;
  float XMIN,XMAX;

  VAR = "mW";
  TAG = CUT+"_"+CAT;
  XMIN = 20.;
  XMAX = 160.;

  RooWorkspace *w = new RooWorkspace("w","workspace");

  //---- define observable ------------------------
  RooRealVar *x = new RooRealVar("mW","mW",XMIN,XMAX);
  w->import(*x);
  //---- first do the data template ---------------
  
  hData = (TH1F*)infData->Get("boosted/h_mW_"+CUT+"_0btag");
  hData->Rebin(5);
  roohData = new RooDataHist("roohistData","roohistData",RooArgList(*x),hData);  

  //---- QCD -----------------------------------
  RooRealVar bBkg0("qcd_b0","qcd_b0",0.5,0,1);
  RooRealVar bBkg1("qcd_b1","qcd_b1",0.5,0,1);
  RooRealVar bBkg2("qcd_b2","qcd_b2",0.5,0,1);
  RooRealVar bBkg3("qcd_b3","qcd_b3",0.5,0,1);

  RooBernstein qcd1("qcd_brn","qcd_brn",*x,RooArgList(bBkg0,bBkg1,bBkg2,bBkg3));

  RooRealVar mQCD("qcd_mean2" ,"qcd_mean2",40,0,100);
  RooRealVar sQCD("qcd_sigma2","qcd_sigma2",20,0,50);
  RooGaussian qcd2("qcd_gaus" ,"qcd_gaus",*x,mQCD,sQCD);

  RooRealVar fqcd("qcd_f1","qcd_f1",0.5,0,1);

  qcd = new RooAddPdf("qcd_pdf","qcd_pdf",qcd1,qcd2,fqcd);

  //---- plots ---------------------------------------------------
  TCanvas *canB = new TCanvas("Template_W_QCD_"+CUT+"_"+CAT,"Template_W_QCD_"+CUT+"_"+CAT,900,600);

  RooFitResult *res = qcd->fitTo(*roohData,RooFit::Save());
  res->Print();
  RooPlot *frameB = x->frame();
  roohData->plotOn(frameB);
  qcd->plotOn(frameB);
  qcd->plotOn(frameB,RooFit::Components("qcd_brn"),RooFit::LineColor(kRed),RooFit::LineWidth(2),RooFit::LineStyle(2));
  qcd->plotOn(frameB,RooFit::Components("qcd_gaus"),RooFit::LineColor(kGreen+1),RooFit::LineWidth(2),RooFit::LineStyle(2));
  frameB->GetXaxis()->SetTitle("m_{W} (GeV)");
  frameB->Draw();
  gPad->Update();
  canB->Print("plots/"+TString(canB->GetName())+".pdf");

  RooArgSet *parsQCD = (RooArgSet*)qcd->getParameters(roohData);
  parsQCD->setAttribAll("Constant",true);

  w->import(*qcd);

  //---- then do the signal templates -------------
  hMC = (TH1F*)infMC->Get("boosted/hWt_"+VAR+"_"+TAG);
  roohMC = new RooDataHist("roohistTT","roohistTT",RooArgList(*x),hMC);
  normMC = ((TH1F*)infMC->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();
  hMC->Rebin(2);
      
  RooRealVar m("ttbar_mean","ttbar_mean",90,70,100);
  RooRealVar s("ttbar_sigma","ttbar_sigma",20,0,50);
    
  RooGaussian sig_core("ttbar_core","ttbar_core",*x,m,s);
  
  RooRealVar bSig0("ttbar_b0","ttbar_b0",0.5,0,1);
  RooRealVar bSig1("ttbar_b1","ttbar_b1",0.5,0,1);
  RooRealVar bSig2("ttbar_b2","ttbar_b2",0.5,0,1); 
  RooRealVar bSig3("ttbar_b3","ttbar_b3",0.5,0,1);
  RooRealVar bSig4("ttbar_b4","ttbar_b4",0.5,0,1);
  RooRealVar bSig5("ttbar_b5","ttbar_b5",0.5,0,1); 
  RooRealVar bSig6("ttbar_b6","ttbar_b6",0.5,0,1);
  RooRealVar bSig7("ttbar_b7","ttbar_b7",0.5,0,1);
  RooRealVar bSig8("ttbar_b8","ttbar_b8",0.5,0,1);

  RooBernstein sig_tail("ttbar_tail","ttbar_tail",*x,RooArgList(bSig0,bSig1,bSig2,bSig3,bSig4,bSig5,bSig6,bSig7,bSig8)); 

  RooRealVar fcore("ttbar_fcore","ttbar_fcore",0.5,0,1);

  signal = new RooAddPdf("ttbar_pdf","ttbar_pdf",RooArgList(sig_core,sig_tail),RooArgList(fcore));

  TCanvas *canS = new TCanvas("Template_W_TT_"+CAT+"_"+CUT,"Template_W_TT_"+CAT+"_"+CUT,900,600);

  res = signal->fitTo(*roohMC,RooFit::Save());

  cout<<"mean = "<<m.getVal()<<" +/ "<<m.getError()<<", sigma = "<<s.getVal()<<" +/- "<<s.getError()<<endl;

  //res->Print();
  RooPlot *frameS = x->frame();
  roohMC->plotOn(frameS);
  signal->plotOn(frameS);
  signal->plotOn(frameS,RooFit::Components("ttbar_core"),RooFit::LineColor(kRed),RooFit::LineWidth(2),RooFit::LineStyle(2));
  signal->plotOn(frameS,RooFit::Components("ttbar_tail"),RooFit::LineColor(kGreen+1),RooFit::LineWidth(2),RooFit::LineStyle(2));
  frameS->GetXaxis()->SetTitle("m_{W} (GeV)");
  frameS->Draw();
  gPad->Update();
  canS->Print("plots/"+TString(canS->GetName())+".pdf");

  RooArgSet *parsSig = (RooArgSet*)signal->getParameters(roohMC);
  parsSig->setAttribAll("Constant",true);

  w->import(*signal);
  
  //w->Print();
  w->writeToFile("templates_W_"+CUT+"_"+CAT+"_workspace.root");
}                            
Ejemplo n.º 11
0
Archivo: exec3.C Proyecto: MycrofD/root
void exec3event(Int_t event, Int_t x, Int_t y, TObject *selected)
{
   TCanvas *c = (TCanvas *) gTQSender;
   printf("Canvas %s: event=%d, x=%d, y=%d, selected=%s\n", c->GetName(),
          event, x, y, selected->IsA()->GetName());
}
Ejemplo n.º 12
0
void performFit(string inputDir, string inputParameterFile, string label,
                string PassInputDataFilename, string FailInputDataFilename, 
                string PassSignalTemplateHistName, string FailSignalTemplateHistName)
{

  gBenchmark->Start("fitZCat");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  const Double_t mlow  = 60;
  const Double_t mhigh = 120;
  const Int_t    nbins = 24;

  TString effType = inputDir;

  // The fit variable - lepton invariant mass
  RooRealVar* rooMass_ = new RooRealVar("Mass","m_{ee}",mlow, mhigh, "GeV/c^{2}");
  RooRealVar Mass = *rooMass_;
  Mass.setBins(nbins);

  // Make the category variable that defines the two fits,
  // namely whether the probe passes or fails the eff criteria.
  RooCategory sample("sample","") ;
  sample.defineType("Pass", 1) ;
  sample.defineType("Fail", 2) ; 


  RooDataSet *dataPass  = RooDataSet::read((inputDir+PassInputDataFilename).c_str(),RooArgList(Mass));
  RooDataSet *dataFail  = RooDataSet::read((inputDir+FailInputDataFilename).c_str(),RooArgList(Mass));

  RooDataSet *dataCombined = new RooDataSet("dataCombined","dataCombined", RooArgList(Mass), RooFit::Index(sample), 
                                            RooFit::Import("Pass",*dataPass),
                                            RooFit::Import("Fail",*dataFail));



  //*********************************************************************************************
  //Define Free Parameters
  //*********************************************************************************************
  RooRealVar* ParNumSignal =  LoadParameters(inputParameterFile, label,"ParNumSignal");
  RooRealVar* ParNumBkgPass =  LoadParameters(inputParameterFile, label,"ParNumBkgPass");
  RooRealVar* ParNumBkgFail =  LoadParameters(inputParameterFile, label, "ParNumBkgFail");
  RooRealVar* ParEfficiency  = LoadParameters(inputParameterFile, label, "ParEfficiency");
  RooRealVar* ParPassBackgroundExpCoefficient = LoadParameters(inputParameterFile, label, "ParPassBackgroundExpCoefficient");
  RooRealVar* ParFailBackgroundExpCoefficient = LoadParameters(inputParameterFile, label, "ParFailBackgroundExpCoefficient");
  RooRealVar* ParPassSignalMassShift = LoadParameters(inputParameterFile, label, "ParPassSignalMassShift");
  RooRealVar* ParFailSignalMassShift = LoadParameters(inputParameterFile, label, "ParFailSignalMassShift");
  RooRealVar* ParPassSignalResolution = LoadParameters(inputParameterFile, label, "ParPassSignalResolution");
  RooRealVar* ParFailSignalResolution = LoadParameters(inputParameterFile, label, "ParFailSignalResolution");



// new RooRealVar  ("ParPassSignalMassShift","ParPassSignalMassShift",-2.6079e-02,-10.0, 10.0);   //ParPassSignalMassShift->setConstant(kTRUE);  
//   RooRealVar* ParFailSignalMassShift = new RooRealVar  ("ParFailSignalMassShift","ParFailSignalMassShift",7.2230e-01,-10.0, 10.0);   //ParFailSignalMassShift->setConstant(kTRUE);  
//   RooRealVar* ParPassSignalResolution = new RooRealVar ("ParPassSignalResolution","ParPassSignalResolution",6.9723e-01,0.0, 10.0);     ParPassSignalResolution->setConstant(kTRUE);  
//   RooRealVar* ParFailSignalResolution = new RooRealVar ("ParFailSignalResolution","ParFailSignalResolution",1.6412e+00,0.0, 10.0);     ParFailSignalResolution->setConstant(kTRUE);  

  //*********************************************************************************************
  //
  //Load Signal PDFs
  //
  //*********************************************************************************************

  TFile *Zeelineshape_file =  new TFile("res/photonEfffromZee.dflag1.eT1.2.gT40.mt15.root", "READ");
  TH1* histTemplatePass = (TH1D*) Zeelineshape_file->Get(PassSignalTemplateHistName.c_str());
  TH1* histTemplateFail = (TH1D*) Zeelineshape_file->Get(FailSignalTemplateHistName.c_str());

  //Introduce mass shift coordinate transformation 
//   RooFormulaVar PassShiftedMass("PassShiftedMass","@0-@1",RooArgList(Mass,*ParPassSignalMassShift));
//   RooFormulaVar FailShiftedMass("FailShiftedMass","@0-@1",RooArgList(Mass,*ParFailSignalMassShift));

  RooGaussian  *PassSignalResolutionFunction =  new RooGaussian("PassSignalResolutionFunction","PassSignalResolutionFunction",Mass,*ParPassSignalMassShift,*ParPassSignalResolution);
  RooGaussian  *FailSignalResolutionFunction =  new RooGaussian("FailSignalResolutionFunction","FailSignalResolutionFunction",Mass,*ParFailSignalMassShift,*ParFailSignalResolution);


  RooDataHist* dataHistPass = new RooDataHist("dataHistPass","dataHistPass", RooArgSet(Mass), histTemplatePass);
  RooDataHist* dataHistFail = new RooDataHist("dataHistFail","dataHistFail", RooArgSet(Mass), histTemplateFail);
  RooHistPdf* signalShapePassTemplatePdf = new RooHistPdf("signalShapePassTemplatePdf", "signalShapePassTemplatePdf", Mass, *dataHistPass, 1);
  RooHistPdf* signalShapeFailTemplatePdf = new RooHistPdf("signalShapeFailTemplatePdf", "signalShapeFailTemplatePdf", Mass, *dataHistFail, 1);

  RooFFTConvPdf* signalShapePassPdf = new RooFFTConvPdf("signalShapePassPdf","signalShapePassPdf"  , Mass, *signalShapePassTemplatePdf,*PassSignalResolutionFunction,2);
  RooFFTConvPdf* signalShapeFailPdf = new RooFFTConvPdf("signalShapeFailPdf","signalShapeFailPdf"  , Mass, *signalShapeFailTemplatePdf,*FailSignalResolutionFunction,2);


  // Now define some efficiency/yield variables  
  RooFormulaVar* NumSignalPass = new RooFormulaVar("NumSignalPass", "ParEfficiency*ParNumSignal", RooArgList(*ParEfficiency,*ParNumSignal));
  RooFormulaVar* NumSignalFail = new RooFormulaVar("NumSignalFail", "(1.0-ParEfficiency)*ParNumSignal", RooArgList(*ParEfficiency,*ParNumSignal));


  //*********************************************************************************************
  //
  // Create Background PDFs
  //
  //*********************************************************************************************
  RooExponential* bkgPassPdf = new RooExponential("bkgPassPdf","bkgPassPdf",Mass, *ParPassBackgroundExpCoefficient);
  RooExponential* bkgFailPdf = new RooExponential("bkgFailPdf","bkgFailPdf",Mass, *ParFailBackgroundExpCoefficient);


 //*********************************************************************************************
  //
  // Create Total PDFs
  //
  //*********************************************************************************************
  RooAddPdf pdfPass("pdfPass","pdfPass",RooArgList(*signalShapePassPdf,*bkgPassPdf), RooArgList(*NumSignalPass,*ParNumBkgPass));
  RooAddPdf pdfFail("pdfFail","pdfFail",RooArgList(*signalShapeFailPdf,*bkgFailPdf), RooArgList(*NumSignalFail,*ParNumBkgFail));

  // PDF for simultaneous fit
   RooSimultaneous totalPdf("totalPdf","totalPdf", sample);
   totalPdf.addPdf(pdfPass,"Pass");
//    totalPdf.Print();
   totalPdf.addPdf(pdfFail,"Fail");
   totalPdf.Print();


   //*********************************************************************************************
  //
  // Perform Fit
  //
  //*********************************************************************************************
   RooFitResult *fitResult = 0;

  // ********* Fix with Migrad first ********** //  
   fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
                              RooFit::Extended(true), RooFit::PrintLevel(-1));
   fitResult->Print("v");


//   // ********* Fit With Minos ********** //  
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//                               RooFit::Extended(true), RooFit::PrintLevel(-1), RooFit::Minos());
//    fitResult->Print("v");




//   // ********* Fix Mass Shift and Fit For Resolution ********** //  
//    ParPassSignalMassShift->setConstant(kTRUE); 
//    ParFailSignalMassShift->setConstant(kTRUE); 
//    ParPassSignalResolution->setConstant(kFALSE); 
//    ParFailSignalResolution->setConstant(kFALSE); 
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//    RooFit::Extended(true), RooFit::PrintLevel(-1));
//    fitResult->Print("v");


//   // ********* Do Final Fit ********** //  
//    ParPassSignalMassShift->setConstant(kFALSE); 
//    ParFailSignalMassShift->setConstant(kFALSE); 
//    ParPassSignalResolution->setConstant(kTRUE); 
//    ParFailSignalResolution->setConstant(kTRUE); 
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//                                             RooFit::Extended(true), RooFit::PrintLevel(-1));
//    fitResult->Print("v");





  double nSignalPass = NumSignalPass->getVal();
  double nSignalFail    = NumSignalFail->getVal();
  double denominator = nSignalPass + nSignalFail;

  printf("\nFit results:\n");
  if( fitResult->status() != 0 ){
    std::cout<<"ERROR: BAD FIT STATUS"<<std::endl;
  }

  printf("    Efficiency = %.4f +- %.4f\n", 
	 ParEfficiency->getVal(), ParEfficiency->getPropagatedError(*fitResult));  
  cout << "Signal Pass: "******"Signal Fail: " << nSignalFail << endl;

  cout << "*********************************************************************\n";
  cout << "Final Parameters\n";
  cout << "*********************************************************************\n";
  PrintParameter(ParNumSignal, label,"ParNumSignal");
  PrintParameter(ParNumBkgPass, label,"ParNumBkgPass");
  PrintParameter(ParNumBkgFail, label, "ParNumBkgFail");
  PrintParameter(ParEfficiency  , label, "ParEfficiency");
  PrintParameter(ParPassBackgroundExpCoefficient , label, "ParPassBackgroundExpCoefficient");
  PrintParameter(ParFailBackgroundExpCoefficient , label, "ParFailBackgroundExpCoefficient");
  PrintParameter(ParPassSignalMassShift , label, "ParPassSignalMassShift");
  PrintParameter(ParFailSignalMassShift , label, "ParFailSignalMassShift");
  PrintParameter(ParPassSignalResolution , label, "ParPassSignalResolution");
  PrintParameter(ParFailSignalResolution , label, "ParFailSignalResolution");
  cout << endl << endl;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  TFile *canvasFile = new TFile("Efficiency_FitResults.root", "UPDATE");


  RooAbsData::ErrorType errorType = RooAbsData::Poisson;

  Mass.setBins(NBINSPASS);
  TString cname = TString((label+"_Pass").c_str());
  TCanvas *c = new TCanvas(cname,cname,800,600);
  RooPlot* frame1 = Mass.frame();
  frame1->SetMinimum(0);
  dataPass->plotOn(frame1,RooFit::DataError(errorType));
  pdfPass.plotOn(frame1,RooFit::ProjWData(*dataPass), 
  RooFit::Components(*bkgPassPdf),RooFit::LineColor(kRed));
  pdfPass.plotOn(frame1,RooFit::ProjWData(*dataPass));
  frame1->Draw("e0");
  
  TPaveText *plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
  TPaveText *plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  TPaveText *plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
  char temp[100];
  sprintf(temp, "%.4f", LUMINOSITY);
  plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
  temp + string(" pb^{ -1}")).c_str());
  TPaveText *plotlabel4 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   double nsig = ParNumSignal->getVal();
   double nErr = ParNumSignal->getError();
   double e = ParEfficiency->getVal();
   double eErr = ParEfficiency->getError();
   double corr = fitResult->correlation(*ParEfficiency, *ParNumSignal);
   double err = ErrorInProduct(nsig, nErr, e, eErr, corr);
   sprintf(temp, "Signal = %.2f #pm %.2f", NumSignalPass->getVal(), err);
   plotlabel4->AddText(temp);
   TPaveText *plotlabel5 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", ParNumBkgPass->getVal(), ParNumBkgPass->getError());
   plotlabel5->AddText(temp);
   TPaveText *plotlabel6 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   plotlabel6->AddText("Passing probes");
   TPaveText *plotlabel7 = new TPaveText(0.6,0.72,0.8,0.77,"NDC");
   plotlabel7->SetTextColor(kBlack);
   plotlabel7->SetFillColor(kWhite);
   plotlabel7->SetBorderSize(0);
   plotlabel7->SetTextAlign(12);
   plotlabel7->SetTextSize(0.03); 
   sprintf(temp, "Eff = %.3f #pm %.3f", ParEfficiency->getVal(), ParEfficiency->getErrorHi());
   plotlabel7->AddText(temp);
   TPaveText *plotlabel8 = new TPaveText(0.6,0.72,0.8,0.66,"NDC");
   plotlabel8->SetTextColor(kBlack);
   plotlabel8->SetFillColor(kWhite);
   plotlabel8->SetBorderSize(0);
   plotlabel8->SetTextAlign(12);
   plotlabel8->SetTextSize(0.03);
   sprintf(temp, "#chi^{2}/DOF = %.3f", frame1->chiSquare());
   plotlabel8->AddText(temp);

  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  plotlabel7->Draw();
  plotlabel8->Draw();

//   c->SaveAs( cname + TString(".eps"));
  c->SaveAs( cname + TString(".gif"));
  canvasFile->WriteTObject(c, c->GetName(), "WriteDelete");

 
  Mass.setBins(NBINSFAIL);
  cname = TString((label+"_Fail").c_str());
  TCanvas* c2 = new TCanvas(cname,cname,800,600);
  RooPlot* frame2 = Mass.frame();
  frame2->SetMinimum(0);
  dataFail->plotOn(frame2,RooFit::DataError(errorType));
  pdfFail.plotOn(frame2,RooFit::ProjWData(*dataFail), 
  RooFit::Components(*bkgFailPdf),RooFit::LineColor(kRed));
  pdfFail.plotOn(frame2,RooFit::ProjWData(*dataFail));
  frame2->Draw("e0");

  plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
 plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
   sprintf(temp, "%.4f", LUMINOSITY);
   plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
                        temp + string(" pb^{ -1}")).c_str());
   plotlabel4 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   err = ErrorInProduct(nsig, nErr, 1.0-e, eErr, corr);
   sprintf(temp, "Signal = %.2f #pm %.2f", NumSignalFail->getVal(), err);
   plotlabel4->AddText(temp);
   plotlabel5 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", ParNumBkgFail->getVal(), ParNumBkgFail->getError());
   plotlabel5->AddText(temp);
   plotlabel6 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   plotlabel6->AddText("Failing probes");
   plotlabel7 = new TPaveText(0.6,0.72,0.8,0.77,"NDC");
   plotlabel7->SetTextColor(kBlack);
   plotlabel7->SetFillColor(kWhite);
   plotlabel7->SetBorderSize(0);
   plotlabel7->SetTextAlign(12);
   plotlabel7->SetTextSize(0.03);
   sprintf(temp, "Eff = %.3f #pm %.3f", ParEfficiency->getVal(), ParEfficiency->getErrorHi(), ParEfficiency->getErrorLo());
   plotlabel7->AddText(temp);
   plotlabel8 = new TPaveText(0.6,0.72,0.8,0.66,"NDC");
   plotlabel8->SetTextColor(kBlack);
   plotlabel8->SetFillColor(kWhite);
   plotlabel8->SetBorderSize(0);
   plotlabel8->SetTextAlign(12);
   plotlabel8->SetTextSize(0.03);
   sprintf(temp, "#chi^{2}/DOF = %.3f", frame2->chiSquare());
   plotlabel8->AddText(temp);

//   plotlabel->Draw();
//   plotlabel2->Draw();
//   plotlabel3->Draw();
  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  plotlabel7->Draw();
  plotlabel8->Draw();

  c2->SaveAs( cname + TString(".gif"));
//   c2->SaveAs( cname + TString(".eps"));
//   c2->SaveAs( cname + TString(".root"));
  canvasFile->WriteTObject(c2, c2->GetName(), "WriteDelete");

  canvasFile->Close();

  
  effTextFile.width(40);
  effTextFile << label;
  effTextFile.width(20);
  effTextFile  << setiosflags(ios::fixed) << setprecision(4) << left << ParEfficiency->getVal() ;
  effTextFile.width(20);
  effTextFile  << left << ParEfficiency->getErrorHi();
  effTextFile.width(20);
  effTextFile  << left << ParEfficiency->getErrorLo();
  effTextFile.width(14);
  effTextFile  << setiosflags(ios::fixed) << setprecision(2) << left << nSignalPass ;
  effTextFile.width(14);
  effTextFile << left << nSignalFail << endl;

} 
Ejemplo n.º 13
0
void distribution(const string folderNameWithRootFiles = "", const Int_t signalRegion0_controlRegion1 = 0, const Int_t mumu0_ee1 = 0, const Int_t data0_noData1 = 0, const string var = "met", const Int_t yAxisLog_flag = 0, const Int_t MCpoissonUncertainty_flag = 0, const Double_t xAxisMin = 0, const Double_t xAxisMax = -1, const Double_t yAxisMin = 0, const Double_t yAxisMax = -1, const Int_t binDensity_flag = 0, const Int_t MCnormalizedToData_flag = 0) {

  // if signalRegion0_controlRegion1 == 0 (default), will do met distribution in the monojet signal region, else it will do the control region

  // mumu0_ee1 is for lepton flavour in CS (not used in SR)

  // data0_noData1 is to use or not a data file to compared with MC

  // yAxisLog_flag is to choose whether or not to use log scale in Y axis (default is 0, that is, normal scale)
  // xAxisMin and xAxisMax are the ranges for x Axis. Default values are used if xAxisMin > xAxisMax (otherwise user values are used)

  TH1::SetDefaultSumw2();            //all the following histograms will automatically call TH1::Sumw2() 

  gROOT->SetStyle("Plain");  // to have white legend (on my pc it's already white, but in tier2 it appears grey)
  gStyle->SetFillColor(10);

  string filenameExtension = ".root";
  // string fileDirectoryPath = "spring15_25ns_rootfiles/";
  string fileDirectoryPath = "/cmshome/ciprianim/CMSSW721/output/" + folderNameWithRootFiles + "/";

  string plotDirectoryPath = fileDirectoryPath;
  // string plotDirectoryPath = "/cmshome/ciprianim/CMSSW721/pdfsFromAnalysis/plots/monojet/met_distribution/";
  //string plotDirectoryPath = "./distributions/";
  string plotFileExtension = ".pdf";
  string suffix;

  if (mumu0_ee1 == 0) suffix = "_mumu";
  else if (mumu0_ee1 == 1) suffix = "_ee";
  else {
    cout << "Error: mumu0_ee1 must be 0 or 1. End of programme." << endl;
    exit(EXIT_FAILURE);
  }

  TH1D* hvar = NULL;   // to get histogram from file
  string hvarName;          // name of histogram to take from file
  string xAxisName;        // name of X axis when plotting distribution. It is a tex string (with ROOT standard), e.g. "#slash{E}_{T} [GeV]" for MET

  // ===== TO BE MODIFIED =====

  // hvarName = "HmetNoLepDistribution";
  // xAxisName = "#slash{E}_{T} [GeV]";

  setDistribution(signalRegion0_controlRegion1, mumu0_ee1, var, hvarName, xAxisName);
    
  // =====================

  vector<TH1D*> hMC;
  TH1D* hdata = NULL;

  vector<string> sampleName;
  vector<string> MC_TexLabel;
  if (data0_noData1 == 1) setSampleName(signalRegion0_controlRegion1, sampleName, MC_TexLabel, mumu0_ee1);
  else setSampleName2lepSkim(signalRegion0_controlRegion1, sampleName, MC_TexLabel, mumu0_ee1);

  string data_TexLabel = "data";

  Int_t nFiles = (Int_t) sampleName.size();

  vector<Int_t> histColor;
   setHistColor(histColor, nFiles);

   string filenameBase;
   string canvasName;

   if (signalRegion0_controlRegion1 == 0) {

     filenameBase = "monojet_SR_spring15_25ns_";
     canvasName = var + "_monojetSR_";

   } else {

     canvasName = var + "_zjetsCS" + suffix;

     if (mumu0_ee1 == 0) filenameBase = "zmumujets_CS_spring15_25ns_";
     else if (mumu0_ee1 == 1) filenameBase = "zeejets_CS_spring15_25ns_";

   }
 

  vector<string> MCfileName;
  for (Int_t i = 0; i < nFiles; i++) {
    MCfileName.push_back(fileDirectoryPath + filenameBase + sampleName[i] + filenameExtension);
  }

  for(Int_t i = 0; i < nFiles; i++) {

    cout<<"fileName : "<<MCfileName[i]<<endl;

    TFile* f = TFile::Open(MCfileName[i].c_str(),"READ");
    if (!f || !f->IsOpen()) {
      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<MCfileName[i]<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);
    }

    //cout << "check 1 " << endl;    

    hvar = (TH1D*)f->Get(hvarName.c_str());
    if (!hvar) {
      cout << "Error: histogram not found in file ' " << MCfileName[i] << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hMC.push_back( (TH1D*)hvar->Clone() );

  } 

  // ==== FILE NAME WILL HAVE TO BE MODIFIED, NOW IT IS JUST A TEST =====

  string datafileName = fileDirectoryPath;

  if (data0_noData1 == 0) {

    if (signalRegion0_controlRegion1 == 0) {

      datafileName += "monojet_SR_spring15_25ns_DATA.root";

    } else {

      if (mumu0_ee1 == 0) datafileName += "zmumujets_CS_spring15_25ns_DATA.root";
      else if (mumu0_ee1 == 1) datafileName += "zeejets_CS_spring15_25ns_DATA.root";

    }

  }

  // ==== opening data file ======

  if (data0_noData1 == 0) {

    cout<<"fileName : "<<datafileName<<endl;

    TFile* f = TFile::Open(datafileName.c_str(),"READ");
    if (!f || !f->IsOpen()) {
      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<datafileName<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);
    }

    hvar = (TH1D*)f->Get(hvarName.c_str());

    if (!hvar) {
      cout << "Error: histogram not found in file ' " << datafileName << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hdata = (TH1D*)hvar->Clone();

  }

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

  THStack* hMCstack = new THStack("hMCstack","");
  Double_t stackNorm = 0.0;

  for (Int_t j = 0; j < nFiles; j++) {

    for (Int_t i = 1; i <= hMC[j]->GetNbinsX(); i++) {

      if (MCpoissonUncertainty_flag == 1) {

	hMC[j]->SetBinError(i,sqrt(hMC[j]->GetBinContent(i)));
	
      }

    }

    hMC[j]->SetFillColor(histColor[j]);
    stackNorm += hMC[j]->Integral();

  }

  // loop again on MC histograms to scale them and then fill the thstack

  for (Int_t j = 0; j < nFiles; j++) {

    if (data0_noData1 == 0 && MCnormalizedToData_flag != 0) {

      Double_t dataNorm = hdata->Integral();

      if (binDensity_flag != 0) hMC[j]->Scale(dataNorm/stackNorm,"width");
      else hMC[j]->Scale(dataNorm/stackNorm);

    } else if (binDensity_flag != 0) hMC[j]->Scale(1.0,"width");  // option width divides by bin width and manages the correct error setting

    hMCstack->Add(hMC[j]);

  }

  if (data0_noData1 == 0) {

    cout << "Events in data: " << hdata->Integral() << endl;
    cout << "Events in MC   : " << ((TH1D*) hMCstack->GetStack()->Last())->Integral() << endl;

  }
  
  if (data0_noData1 == 0 && binDensity_flag != 0) hdata->Scale(1.0,"width");
  //if (data0_noData1 == 0 && MCnormalizedToData_flag != 0)

  // now here we go with the canvas

  TH1D * ratioplot = NULL; // will use it for the ratio plots

  TPad *subpad_1 = NULL;  // will use it to access specific subpad in canvas
  TPad *subpad_2 = NULL; 

  TCanvas *c;
  if (data0_noData1 == 0) c = new TCanvas(canvasName.c_str(), (var + " distribution").c_str(), 700, 700);
  else c = new TCanvas(canvasName.c_str(), (var + " distribution").c_str());
  TLegend *leg = new TLegend(0.7,0.6,0.99,0.94);  

  // if there are data, split canvas to draw the dta/MC ratio plot

  if (data0_noData1 == 0) {

    subpad_1 = new TPad("pad_1","",0.0,0.28,1.0,1.0);
    if (yAxisLog_flag) subpad_1->SetLogy();
    //subpad_1->SetBottomMargin(0);
    subpad_2 = new TPad("pad_2","",0.0,0.0,1.0,0.32);
    subpad_2->SetGridy();
    //subpad_2->SetTopMargin(0);
    subpad_2->SetBottomMargin(0.3);
    subpad_1->Draw();
    subpad_2->Draw();

    subpad_1->cd();

  } else if (yAxisLog_flag) c->SetLogy();

  
  hMCstack->Draw("HIST");
  //if (yAxisMin > 0) hMCstack->SetMinimum(yAxisMin);

  if (yAxisMin < yAxisMax) {
    if (data0_noData1 == 0) subpad_1->Update();  // to be done after Draw() to access pad parameters such as default axis range
    else c->Update();  
    hMCstack->GetYaxis()->SetRangeUser(yAxisMin,yAxisMax);
  }

  // if (data0_noData1 == 0) {

  //   if (yAxisMin > 0) hMCstack->GetYaxis()->SetRangeUser(yAxisMin, subpad_1->GetY2());
  //   else hMCstack->GetYaxis()->SetRangeUser(yAxisMin, c->GetY2());

  // }

  //hMCstack->SetMaximum(4000.0);
  TH1D* stackCopy = (TH1D*)(((TH1D*)hMCstack->GetStack()->Last())->DrawCopy("E2 SAME"));
  stackCopy->SetFillColor(kBlack);
  stackCopy->SetFillStyle(3144);

  if (data0_noData1 == 1) {    //  when using data ( == 0) the x axis will not have labels (they will only be below in the ratio plot
    hMCstack->GetXaxis()->SetTitle(xAxisName.c_str());
    hMCstack->GetXaxis()->SetTitleSize(0.06);
    hMCstack->GetXaxis()->SetTitleOffset(0.6);
  }

  if (xAxisMin < xAxisMax) {
    if (data0_noData1 == 0) subpad_1->Update();  // to be done after Draw() to access pad parameters such as default axis range
    else c->Update();  
    hMCstack->GetXaxis()->SetRangeUser(xAxisMin,xAxisMax);
  }

  if (binDensity_flag == 0) hMCstack->GetYaxis()->SetTitle("events");
  else hMCstack->GetYaxis()->SetTitle("events / GeV");
  hMCstack->GetYaxis()->SetTitleSize(0.06);
  hMCstack->GetYaxis()->SetTitleOffset(0.8);
  hMCstack->GetYaxis()->CenterTitle();
  for (Int_t j = (nFiles-1); j >= 0; j--) {
    leg->AddEntry(hMC[j],Form("%s",MC_TexLabel[j].c_str()),"lf");
  }

  if (data0_noData1 == 0) {    
    hdata->SetMarkerStyle(8); // large dot
    hdata->Draw("EX0 SAME"); //X0 doesn't draw x error
    leg->AddEntry(hdata,Form("%s",data_TexLabel.c_str()),"p");
  }

  gStyle->SetStatStyle(0);
  leg->Draw(); 
  leg->SetMargin(0.3); 
  leg->SetBorderSize(0);

  if (data0_noData1 == 0) { // if using data, draw the ratio plot

    subpad_2->cd();
    ratioplot = new TH1D(*hdata);
    ratioplot->Divide(stackCopy);
    ratioplot->SetStats(0);
    ratioplot->SetTitle("");
    ratioplot->GetXaxis()->SetLabelSize(0.10);
    ratioplot->GetXaxis()->SetTitle(xAxisName.c_str());
    ratioplot->GetXaxis()->SetTitleSize(0.14);
    ratioplot->GetXaxis()->SetTitleOffset(0.8);
    ratioplot->GetYaxis()->SetLabelSize(0.10);
    ratioplot->GetYaxis()->SetTitle("data / MC");
    ratioplot->GetYaxis()->SetTitleSize(0.15);
    ratioplot->GetYaxis()->SetTitleOffset(0.3);
    ratioplot->GetYaxis()->CenterTitle();
    ratioplot->GetYaxis()->SetRangeUser(0.5,1.5);
    ratioplot->GetYaxis()->SetNdivisions(011);
    if (xAxisMin < xAxisMax) {
      //subpad_2->Update();  // to be done after Draw() to access pad parameters such as default axis range  
      ratioplot->GetXaxis()->SetRangeUser(xAxisMin,xAxisMax);
    }
    ratioplot->SetMarkerStyle(8);  //medium dot
    ratioplot->DrawCopy("E");  

  }

  c->SaveAs( (plotDirectoryPath + c->GetName() + plotFileExtension).c_str() );

}
Ejemplo n.º 14
0
//______________________________________________________________________________
void CheckPulsers(const Char_t* loc)
{
    // Some old pedestal checking method.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // number of channels
    Int_t nCh = gReadAR->GetNelements();

    // create arrays
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/pulser.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d_%s", i, gReadAR->GetElement(i)->GetTDC());
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("gausfunc", "gaus", 0 , 200);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();

        // loop over TDCs
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d_%s", j, gReadAR->GetElement(j)->GetTDC());
            fROOTout->cd(t);
            sprintf(t, "ADC%s", gReadAR->GetElement(j)->GetTDC());
            TH1D* h = (TH1D*) f->Get(t);
            
            // fit gaussian to pulser
            Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
            func->SetParameters(1, maxPos, 0.1);
            func->SetRange(maxPos - 2, maxPos + 2);
            h->Fit(func, "RBQ");
            maxPos = func->GetParameter(1);
            
            // save position in file and memory
            pedPos[j][i] = maxPos;

            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            h->Draw();
            
            TLine* tline = new TLine(maxPos, 0, maxPos, 10000);
            tline->SetLineColor(kRed);
            tline->SetLineWidth(2);
            tline->Draw();
            
            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            delete tline;
        }
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating pedestal graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d_%s", j, gReadAR->GetElement(j)->GetTDC());
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
Ejemplo n.º 15
0
void makePlots (string configFilePath){

  if (( nHistList % inputRootFile.size() == 0 )) 
    {
      for (int i=0; i<numHistos; i++) 
        {
	 
          TCanvas *c = new TCanvas(theHistNameStrings.at(i).c_str(), "", 81,58,500,602);
 
          TH1* h_mc;        // histograms for MC
          TH1* h_mc_clone;  // histograms for MC 
          TH1* h_data;      // histogram to store data points 
	  TH1* h_data_clone;
          TLegend *legend = new TLegend(0.2, 0.85-.035*inputLegend.size(), 0.5, 0.90,NULL,"brNDC");
          int whichHisto = 0;
	  
          for (int j=1;j<inputRootFile.size();j++)
	    {
	      
	      whichHisto=j*numHistos; 
	      
	      int a = 0;
	      bool foundHisto = false;
              
	      if (theHistNameStrings.at(i) == theHistNameStrings.at(i+whichHisto)) 
		{
		  foundHisto=true; 
		  a=i;
		}
	      
	      else 
		{
		  for (a = 0; a < numHistos; a++)
		    {
		      if (theHistNameStrings.at(i) == theHistNameStrings.at(a+whichHisto))
			{
			  foundHisto = true;
			  break;
			}
		    }
		}
	      //-----------------------------------------------------------
              
	      string hist2name = listHistos->At(a+whichHisto)->GetName();
	      if (foundHisto == true)
		{
                  h_data = (TH1*)listHistos->At(i);
                  h_data->SetMarkerStyle(inputMarkerStyle.at(0));
                  h_data = SetStyleh(h_data);
                  h_data->Sumw2();
                  int thelineStyle = inputSetLineStyle.at(j);
                  int thelineWidth = inputSetLineWidth.at(j);
                  int setcolor = inputColor.at(j);
                  int marker   = inputMarkerStyle.at(j);
                  h_data->SetMarkerColor(inputColor.at(0));
                  h_data->SetLineColor(inputColor.at(0));
                  if (j == 1) 
                    { 
		       if ( h_data->IsA()->InheritsFrom( "TH2" ) ) {
			 //n.b. that ProfileX will do nothing if the
			 //name you choose is alreayd taken!  so each
			 //profileX needs a unique name
			 TString profileName = TString::Format("%s_data_pfx",h_data->GetName());
			 TProfile *dataProf = ((TH2*)h_data)->ProfileX(profileName.Data());
			 dataProf->SetMinimum(h_data->GetMinimum()); //min/max values were stored in the original hist
			 dataProf->SetMaximum(h_data->GetMaximum());
			 dataProf->Draw("");
			 
			 //profileX cretaes a clone, so no need to
			 //clone again here.  Need to set the hist
			 //name so root doesn't complain
			 TString cloneName = TString::Format("%s_data_pfx_clone",h_data->GetName());
			 TString cloneName2 = TString::Format("%s_data_pfx_clone_px",h_data->GetName());
			 h_data_clone = ((TH2*)h_data)->ProfileX(cloneName.Data())->ProjectionX(cloneName2.Data());
		       }
		       else { //1d case
                         Float_t ymaxc = gPad->GetUymax();
                         //h_data->SetMaximum(ymaxc+0.15*ymaxc);
			 h_data->Draw("ep1");
			 h_data_clone = (TH1*)h_data->Clone();
		       }
                       //h_data->SetLineColor(1);
                       h_data->SetLineStyle(thelineStyle);
                       h_data->SetLineWidth(thelineWidth);
                       float rms_data = h_data->GetRMS();
                       float mean_data = h_data->GetMean();
                       std::stringstream legend_data;
                       legend_data.str("");
                       legend_data << inputLegend.at(0).c_str() << ": mean=" << setprecision(3)
                                   <<mean_data <<", rms=" << setprecision(3) <<rms_data<< endl;
                       legend->AddEntry(h_data,legend_data.str().c_str(), "lep");

                    }
		  h_mc = (TH1*)listHistos->At(a+whichHisto);
                  h_mc = SetStyleh(h_mc);
		  h_mc->SetName(hist2name.c_str());
                  //cout<<"NAME "<<h_mc->GetName()<<endl;
		  // Style
                  
		  string processlegend = (inputLegend.at(j)).c_str();
 
		  h_mc->SetLineStyle(thelineStyle);
		  h_mc->SetLineWidth(thelineWidth);
		  h_mc->SetLineColor(setcolor);
                  h_mc->SetMarkerStyle(marker);
                  h_mc->SetMarkerColor(setcolor);                 
 
                  string processlegend = (inputLegend.at(j)).c_str(); 

		  if ( h_mc->IsA()->InheritsFrom( "TH2" ) ) {
		    TString profileName = TString::Format("%s_mc_pfx", h_mc->GetName());
		    ((TH2*)h_mc)->ProfileX(profileName.Data())->Draw("SAME");
		    //profileX cretaes a clone, so no need to
		    //clone again here.  Need to set the hist
		    //name so root doesn't complain
		    TString cloneName = TString::Format("%s_mc_pfx_clone",h_mc->GetName());
		    TString cloneName2 = TString::Format("%s_mc_pfx_clone_px",h_mc->GetName());
		    h_mc_clone = ((TH2*)h_mc)->ProfileX(cloneName.Data())->ProjectionX(cloneName2.Data());
		  } else { //1d case
                    Float_t ymaxc = gPad->GetUymax();
                    h_mc->SetMaximum(ymaxc+0.15*ymaxc);
		    h_mc->Draw("epsame");
		    h_mc_clone = (TH1*)h_mc->Clone();
		  }
                  h_mc_clone->SetMarkerStyle(marker);
                  h_mc_clone->SetMarkerColor(setcolor);
                  float rms_mc = h_mc->GetRMS();
                  float mean_mc = h_mc->GetMean();
		  std::stringstream legend_mc;
                  legend_mc.str("");
                  legend_mc << processlegend.c_str() << " - "<< "mean: " << setprecision(3)
                              <<mean_mc <<" , rms: " << setprecision(3) <<rms_mc<< endl;
                  legend->AddEntry(h_mc, legend_mc.str().c_str(), "lep"); 
		}// close if (foundHisto)
 
	      legend->SetTextFont(42);
              legend->SetTextSize(.04);
              legend->SetMargin(0.15);
              legend->SetLineColor(1);
              legend->SetLineStyle(1);
              legend->SetLineWidth(1);
              legend->SetFillColor(0);
              legend->SetFillStyle(0);
              legend->SetBorderSize(0);
              legend->SetFillColor(kWhite);
              legend->Draw();
 
	      c->cd();
 	      
              if (j == 1)
                {
	           float startxbin = h_data_clone->GetXaxis()->GetBinWidth(h_data_clone->GetXaxis()->GetFirst()) * 
		      (h_data_clone->GetXaxis()->GetFirst() - 1);
	           float lastxbin  = h_data_clone->GetXaxis()->GetBinCenter(h_data_clone->GetXaxis()->GetNbins());
	      
	            double x1 = 0;
	            double x2 = lastxbin + h_data_clone->GetXaxis()->GetBinWidth(h_data_clone->GetXaxis()->GetNbins())/2.;
	      
	            if (h_data_clone->GetXaxis()->GetBinCenter(0) <= 0)
		        x1 = h_data_clone->GetXaxis()->GetBinCenter(0) + h_data_clone->GetXaxis()->GetBinWidth(0)/2. + startxbin;
	            else 
		        x1 = h_data_clone->GetXaxis()->GetBinCenter(0) - h_data_clone->GetXaxis()->GetBinWidth(0)/2. - startxbin;
	        } 
	  
	    } // close for loop inputRootFile
	  
	  TFile *hfile = (TFile*)gROOT->FindObject(HistosOutputRootFile.c_str());
	  if (hfile) {hfile->Close();}
	  hfile = new TFile(HistosOutputRootFile.c_str(),"UPDATE");

          for (int o = 0; o < inputHistoName.size(); o++)
             {
                if ( c->GetName() == inputHistoName.at(o) )
                  {
                     string save = configFilePath+"/"+inputHistoName.at(o)+".pdf";  
                     c->SaveAs(save.c_str());
                     c->Write();    
                     break;
                  }
             }

	  hfile->Close();
          c->Close();
	  
	}  // close foor loop numHistos     
      
    } // close if numHistos % inputRootFile.size() == 0
} // close  makePlots function
void plotphi(int top, bool phi=kFALSE){
  if (setup("vm","","pol__")==kFALSE) return;
  gStyle->SetOptFit(1111); //pcev = 1111
  //gStyle->SetTitleW(1.5);

  int itop = top-1;
  TFile* fy = _fyexp[itop];

  int nq2wbins = fy->GetNkeys();
  TIter nextkey(fy->GetListOfKeys());
  TKey *key;
  int iq2wbin = 0;
  while (key = (TKey*)nextkey()) {
    TString Q2Wdirname = key->GetName();
    if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
    cout << "Q2Wdirname = " << Q2Wdirname << endl;

    THStack* hs[10];
    TF1 *fphi = new TF1("fphi", "([0] + [1]*cos(x*TMath::DegToRad()) + [2]*cos(2*x*TMath::DegToRad()) + [3]*sin(x*TMath::DegToRad()))",0, 360);
    fphi->SetParameter(0,1);
    fphi->SetParameter(1,10);
    fphi->SetParameter(2,20);
    fphi->SetParameter(3,100);
    fphi->SetParName(0, "A");
    fphi->SetParName(1, "B");
    fphi->SetParName(2, "C");
    fphi->SetParName(3, "hPR");
    for (int i = 0; i < 10; i++)
    {
      TString hname_unp = TString::Format("%s/hPhi/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      TString hname_pos = TString::Format("%s/hPhi_POS/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      TString hname_neg = TString::Format("%s/hPhi_NEG/Varset1/theta/hphi_%02d",Q2Wdirname.Data(),i+1);
      cout << "hname_unp = " << hname_unp << endl;
      cout << "hname_pos = " << hname_pos << endl;
      cout << "hname_neg = " << hname_neg << endl;
      TH1D* hunp = (TH1D*)fy->Get(hname_unp);
      TH1D* hpos = (TH1D*)fy->Get(hname_pos);
      TH1D* hneg = (TH1D*)fy->Get(hname_neg);
      if (hunp==NULL || hpos==NULL || hneg==NULL) cout << "histogram not found" << endl;
      hunp->SetLineColor(kBlack);
      hpos->SetLineColor(kRed);
      hneg->SetLineColor(kBlue);
      hunp->Fit(fphi);
      hpos->Fit(fphi);
      hneg->Fit(fphi);

      //! Modify titles
      TObjArray *tarr;
      char t[100];

      TPaveText *ptunp = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tunp = hunp->GetTitle();
      tarr = tunp.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptunp->AddText(tarr->At(0)->GetName());
      ptunp->AddText(t);
      hunp->SetTitle("");

      TPaveText *ptpos = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tpos = hpos->GetTitle();
      tarr = tpos.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptpos->AddText(tarr->At(0)->GetName());
      ptpos->AddText(t);
      hpos->SetTitle("");

      TPaveText *ptneg = new TPaveText(0.0, 0.9, 1.0, 1, "NDC");
      TString tneg = hneg->GetTitle();
      tarr = tneg.Tokenize("|");
      sprintf(t, "%s:%s:%s", tarr->At(1)->GetName(), tarr->At(2)->GetName(), tarr->At(3)->GetName());
      ptneg->AddText(tarr->At(0)->GetName());
      ptneg->AddText(t);
      hneg->SetTitle("");

      //! Draw histograms
      TCanvas *c = new TCanvas(hpos->GetName(),hpos->GetName(),900, 600);
      c->Divide(3,1);
      c->cd(1);
      hunp->Draw();
      ptunp->Draw();
      c->cd(2);
      hpos->Draw();
      ptpos->Draw();
      c->cd(3);
      hneg->Draw();
      ptneg->Draw();
      TString dir = TString::Format("./polobs/top%d/%s/Varset1/theta", top, Q2Wdirname.Data());
      gSystem->mkdir(dir,1);
      c->SaveAs(TString::Format("%s/%s.png", dir.Data(), c->GetName()));
      c->Close();
      c->Delete();
    }
  }
}
Ejemplo n.º 17
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");
  }
}
void metDistribution(const Int_t signalRegion_flag = 1) {

  // if signalRegion_flag == 1 (default), will do met distribution in the monojet signal region, else it will do the control region

  gROOT->SetStyle("Plain");  // to have white legend (on my pc it's already white, but in tier2 it appears grey)
  gStyle->SetFillColor(10);

  string plotDirectoryPath = "/cmshome/ciprianim/CMSSW721/pdfsFromAnalysis/plots/monojet/met_distribution/";
  //string plotDirectoryPath = "./";
  string plotFileExtension = ".pdf";
  string suffix = "_mumu";

  TH1D* hmet = NULL;
  vector<TH1D*> hMCmetNoLep;

  vector<string> sampleName;
  vector<string> MC_TexLabel;
  setSampleName(signalRegion_flag, sampleName, MC_TexLabel);

  Int_t nFiles = (Int_t)sampleName.size();

  vector<Int_t> histColor;
   setHistColor(histColor, nFiles);

   string filenameBase;
   string canvasName;
   if (signalRegion_flag == 1) {
     filenameBase = "monojet_SR_spring15_25ns_";
     canvasName = "metDistribution_monojetSR";
   } else {
     filenameBase = "zmumujets_CS_spring15_25ns_";
     canvasName = "metDistribution_zjetsCS" + suffix;
   }
 
  string filenameExtension = ".root";

  vector<string> MCfileName;
  for (Int_t i = 0; i < nFiles; i++){
    MCfileName.push_back(filenameBase + sampleName[i] + filenameExtension);
  }

  for(Int_t i = 0; i < nFiles; i++) {

    cout<<"fileName : "<<MCfileName[i]<<endl;

    TFile* f = TFile::Open(MCfileName[i].c_str(),"READ");
    if (!f || !f->IsOpen()) {
      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<MCfileName[i]<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);
    }

    //cout << "check 1 " << endl;    

    hmet = (TH1D*)f->Get("HYieldsMetBin");
    if (!hmet) {
      cout << "Error: histogram not found in file ' " << MCfileName[i] << "'. End of programme." << endl;
      exit(EXIT_FAILURE);
    }
    hMCmetNoLep.push_back( (TH1D*)hmet->Clone() );

  } 

  THStack* hstack_metNoLep = new THStack("hstack_metNoLep","");

  for (Int_t j = 0; j < nFiles; j++) {

    for (Int_t i = 1; i <= hMCmetNoLep[j]->GetNbinsX(); i++) {

      hMCmetNoLep[j]->SetBinError(i,sqrt(hMCmetNoLep[j]->GetBinContent(i)));

    }

    hMCmetNoLep[j]->SetFillColor(histColor[j]);
    hstack_metNoLep->Add(hMCmetNoLep[j]);

  }

  // now here we go with the canvas
  // TH1D * ratioplot = NULL; // will use it for the ratio plots

  // TPad *subpad_1 = NULL;  // will use it to access specific subpad in canvas
  // TPad *subpad_2 = NULL; 
  TCanvas *c = new TCanvas(canvasName.c_str(),"met distribution");
  c->SetLogy();

  TLegend *leg = new TLegend(0.6,0.55,0.89,0.89);
  
  // subpad_1 = new TPad("pad_1","",0.0,0.28,1.0,1.0);
  // //subpad_1->SetBottomMargin(0);
  // subpad_2 = new TPad("pad_2","",0.0,0.0,1.0,0.32);
  // subpad_2->SetGridy();
  // //subpad_2->SetTopMargin(0);
  // subpad_2->SetBottomMargin(0.3);
  // subpad_1->Draw();
  // subpad_2->Draw();

  //subpad_1->cd();
  hstack_metNoLep->Draw("HIST");
  //hstack_metNoLep->SetMinimum(0.3);
  //hstack_metNoLep->SetMaximum(4000.0);
  TH1D* stackCopy = (TH1D*)(((TH1D*)hstack_metNoLep->GetStack()->Last())->DrawCopy("E2 SAME"));
  stackCopy->SetFillColor(kBlack);
  stackCopy->SetFillStyle(3017);
  hstack_metNoLep->GetXaxis()->SetTitle("#slash{E}_{T} [GeV]");
  hstack_metNoLep->GetXaxis()->SetTitleSize(0.06);
  hstack_metNoLep->GetXaxis()->SetTitleOffset(0.6);
  hstack_metNoLep->GetYaxis()->SetTitle("events");
  hstack_metNoLep->GetYaxis()->SetTitleSize(0.06);
  hstack_metNoLep->GetYaxis()->SetTitleOffset(0.8);
  hstack_metNoLep->GetYaxis()->CenterTitle();
  for (Int_t j = (nFiles-1); j >= 0; j--) {
    leg->AddEntry(hMCmetNoLep[j],Form("%s",MC_TexLabel[j].c_str()),"lf");
  }
  gStyle->SetStatStyle(0);
  leg->Draw(); 
  leg->SetMargin(0.3); 
  leg->SetBorderSize(0);

  // subpad_2->cd();
  // ratioplot = new TH1D(*hratio);
  // ratioplot->Divide(hBRratioOverAxe);
  // ratioplot->SetStats(0);
  // ratioplot->GetXaxis()->SetLabelSize(0.10);
  // ratioplot->GetXaxis()->SetTitle("#slash{E}_{T} [GeV]");
  // ratioplot->GetXaxis()->SetTitleSize(0.15);
  // ratioplot->GetXaxis()->SetTitleOffset(0.8);
  // ratioplot->GetYaxis()->SetLabelSize(0.10);
  // ratioplot->GetYaxis()->SetTitle("ratio");
  // ratioplot->GetYaxis()->SetTitleSize(0.15);
  // ratioplot->GetYaxis()->SetTitleOffset(0.3);
  // ratioplot->GetYaxis()->CenterTitle();
  // ratioplot->GetYaxis()->SetRangeUser(0.5,1.5);
  // ratioplot->GetYaxis()->SetNdivisions(011);
  // ratioplot->DrawCopy("HE");
  // ratioplot->SetMarkerStyle(8);  //medium dot
  c->SaveAs( (plotDirectoryPath + c->GetName() + plotFileExtension).c_str() );

}
Ejemplo n.º 19
0
void view()
{
  TFile* f = TFile::Open("result.root");

  int signalColorTable[20], backgroundColorTable[20];

  for ( int i=0; i<20; ++i )
  {
    signalColorTable[i] = kAzure+10-i;
    backgroundColorTable[i] = kOrange+10-i;
  }

  TList* signalPlots = makePlots((TDirectory*)f->Get("MC_Signal_EMEM"), signalColorTable);
  TList* backgroundPlots = makePlots((TDirectory*)f->Get("MC_Background_EMEM"), backgroundColorTable, true);

  if ( signalPlots == 0 || backgroundPlots == 0 ) return;

  const int nPlots = signalPlots->GetSize();
  for ( int i=0; i<nPlots; ++i )
  {
    THStack* hSignal = (THStack*)signalPlots->At(i);
    THStack* hBackground = (THStack*)backgroundPlots->At(i);

    TString histName = hSignal->GetName();
    bool doLog = histName.Contains("Pt");// || histName.Contains("RelIso");

    TCanvas* c = new TCanvas(TString("c")+hSignal->GetName(), hSignal->GetTitle(), 1200, 600);
    TPad* pad;

    c->Divide(2,1);

    TString xTitle, yTitle;

    pad = (TPad*)c->cd(1);
    if ( doLog ) pad->SetLogy();
    pad->SetBorderSize(0);
    pad->SetBorderMode(0);
    hBackground->Draw();

    xTitle = ((TH1*)hBackground->GetHists()->At(0))->GetXaxis()->GetTitle();
    yTitle = ((TH1*)hBackground->GetHists()->At(0))->GetYaxis()->GetTitle();
    hBackground->GetXaxis()->SetTitle(xTitle);
    hBackground->GetYaxis()->SetTitle(yTitle);

    pad->BuildLegend(0.6, 0.6, 0.98, 0.98);

    pad = (TPad*)c->cd(2);
    if ( doLog ) pad->SetLogy();
    pad->SetBorderSize(0);
    pad->SetBorderMode(0);
    hSignal->Draw("nostack");

    xTitle = ((TH1*)hSignal->GetHists()->At(0))->GetXaxis()->GetTitle();
    yTitle = ((TH1*)hSignal->GetHists()->At(0))->GetYaxis()->GetTitle();
    hSignal->GetXaxis()->SetTitle(xTitle);
    hSignal->GetYaxis()->SetTitle(yTitle);

    pad->BuildLegend(0.6, 0.7, 0.98, 0.98);

    c->Print(TString(c->GetName())+".png");
  }
}
Ejemplo n.º 20
0
void CreateBkgTemplates(float XMIN, float XMAX, TString OUTPATH, bool MERGE)
{
  gROOT->ProcessLineSync(".x ../common/styleCMSTDR.C");
  gROOT->ForceStyle();
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  const int NSEL(2);
  if (!MERGE) {const int NCAT[NSEL] = {4,3};}
  else {const int NCAT[NSEL] = {4,2};}
  if (!MERGE) {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,0.8,1}};}
  else {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,1}};}
  float LUMI[2] = {19784,18281};
  TString SELECTION[2] = {"NOM","VBF"};
  TString SELNAME[2] = {"NOM","PRK"};
  TString MASS_VAR[2] = {"mbbReg[1]","mbbReg[2]"};
  TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
  TString PATH("flat/");
  TFile *inf[9];
  TTree *tr;
  TH1F *hMbb[9],*hMbbYield[9],*hPass;
  TH1F *hZ,*hW,*hTT,*hST,*hTop;
  TH1F *hZYield,*hWYield,*hTTYield,*hSTYield,*hTopYield;
  char name[1000];
  float LUMI;
  float XSEC[9] = {56.4,11.1,3.79,30.7,11.1,1.76,245.8,650,1.2*1205};
  RooDataHist *roohist_Z[5],*roohist_T[5];
  RooRealVar *kJES[10],*kJER[10];
  RooWorkspace *w = new RooWorkspace("w","workspace");
  
  TString tMERGE = MERGE ? "_CATmerge56" : "";
  
  //RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
  int counter(0);
  for(int isel=0;isel<NSEL;isel++) {
    inf[0] = TFile::Open(PATH+"Fit_T_t-channel_sel"+SELECTION[isel]+".root");
    inf[1] = TFile::Open(PATH+"Fit_T_tW-channel_sel"+SELECTION[isel]+".root");
    inf[2] = TFile::Open(PATH+"Fit_T_s-channel_sel"+SELECTION[isel]+".root");
    inf[3] = TFile::Open(PATH+"Fit_Tbar_t-channel_sel"+SELECTION[isel]+".root");
    inf[4] = TFile::Open(PATH+"Fit_Tbar_tW-channel_sel"+SELECTION[isel]+".root");
    inf[5] = TFile::Open(PATH+"Fit_Tbar_s-channel_sel"+SELECTION[isel]+".root");
    inf[6] = TFile::Open(PATH+"Fit_TTJets_sel"+SELECTION[isel]+".root");
    inf[7] = TFile::Open(PATH+"Fit_ZJets_sel"+SELECTION[isel]+".root");
    inf[8] = TFile::Open(PATH+"Fit_WJets_sel"+SELECTION[isel]+".root");
     
    TCanvas *canZ = new TCanvas("canZ_"+SELECTION[isel],"canZ_"+SELECTION[isel],900,600); 
    TCanvas *canT = new TCanvas("canT_"+SELECTION[isel],"canT_"+SELECTION[isel],900,600);  
    canZ->Divide(2,2);
    canT->Divide(2,2);
    TCanvas *can = new TCanvas(); 
    
    sprintf(name,"CMS_vbfbb_scale_mbb_sel%s",SELECTION[isel].Data()); 
    kJES[isel] = new RooRealVar(name,name,1.0);
    sprintf(name,"CMS_vbfbb_res_mbb_sel%s",SELECTION[isel].Data()); 
    kJER[isel] = new RooRealVar(name,name,1.0);
    kJES[isel]->setConstant(kTRUE);
    kJER[isel]->setConstant(kTRUE);
  
    for(int icat=0;icat<NCAT[isel];icat++) {
		if (MERGE && SELECTION[isel]=="VBF" && icat==1) counter = 56;
      /*
      sprintf(name,"CMS_vbfbb_scale_mbb_CAT%d",counter); 
      kJES[counter] = new RooRealVar(name,name,1.0);
      sprintf(name,"CMS_vbbb_res_mbb_CAT%d",counter); 
      kJER[counter] = new RooRealVar(name,name,1.0);
      kJES[counter]->setConstant(kTRUE);
      kJER[counter]->setConstant(kTRUE);
      */ 
      for(int i=0;i<9;i++) {
        hPass = (TH1F*)inf[i]->Get("TriggerPass");
        sprintf(name,"Hbb/events",icat);
        tr = (TTree*)inf[i]->Get(name); 
        sprintf(name,"puWt[0]*%s*(mva%s>%1.2f && mva%s<=%1.2f)",TRIG_WT[isel].Data(),SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1]);
        TCut cut(name); 
        int NBINS(20);
        //if (icat > 1 && icat<=2) NBINS = 20; 
        if (icat > 2) NBINS = 12;
        sprintf(name,"hMbb%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbb[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbb[i]->Sumw2();
        can->cd();        
        tr->Draw(MASS_VAR[isel]+">>"+hMbb[i]->GetName(),cut);
        sprintf(name,"hMbbYield%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbbYield[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbbYield[i]->Sumw2();
        tr->Draw(MASS_VAR[isel]+">>"+hMbbYield[i]->GetName(),cut);
        hMbbYield[i]->Scale(LUMI[isel]*XSEC[i]/hPass->GetBinContent(1)); 
      }
      hZ  = (TH1F*)hMbb[7]->Clone("Z");
      hW  = (TH1F*)hMbb[8]->Clone("W");
      hTT = (TH1F*)hMbb[6]->Clone("TT");
      hST = (TH1F*)hMbb[0]->Clone("ST");
      hST->Add(hMbb[1]);
      hST->Add(hMbb[2]);
      hST->Add(hMbb[3]);
      hST->Add(hMbb[4]);
      hST->Add(hMbb[5]);
      hTop = (TH1F*)hTT->Clone("Top");
      hTop->Add(hST);
      //hZ->Add(hW);
      hZYield  = (TH1F*)hMbbYield[7]->Clone("ZYield");
      hWYield  = (TH1F*)hMbbYield[8]->Clone("WYield");
      hTTYield = (TH1F*)hMbbYield[6]->Clone("TTYield");
      hSTYield = (TH1F*)hMbbYield[0]->Clone("STYield");
      hSTYield->Add(hMbbYield[1]);
      hSTYield->Add(hMbbYield[2]);
      hSTYield->Add(hMbbYield[3]);
      hSTYield->Add(hMbbYield[4]);
      hSTYield->Add(hMbbYield[5]);
      hTopYield = (TH1F*)hTTYield->Clone("TopYield");
      hTopYield->Add(hSTYield);
      hZYield->Add(hWYield); 

      RooRealVar x("mbbReg_"+TString::Format("CAT%d",counter),"mbbReg_"+TString::Format("CAT%d",counter),XMIN,XMAX);

      sprintf(name,"yield_ZJets_CAT%d",counter);
      RooRealVar *YieldZ = new RooRealVar(name,name,hZYield->Integral());
      sprintf(name,"yield_WJets_CAT%d",counter);
      RooRealVar *YieldW = new RooRealVar(name,name,hWYield->Integral());
      sprintf(name,"yield_Top_CAT%d",counter);
      RooRealVar *YieldT = new RooRealVar(name,name,hTopYield->Integral());
      sprintf(name,"yield_TT_CAT%d",counter);
      RooRealVar *YieldTT = new RooRealVar(name,name,hTTYield->Integral());
      sprintf(name,"yield_ST_CAT%d",counter);
      RooRealVar *YieldST = new RooRealVar(name,name,hSTYield->Integral());

      sprintf(name,"roohist_Z_CAT%d",counter);
      roohist_Z[icat] = new RooDataHist(name,name,x,hZ);

      sprintf(name,"Z_mean_CAT%d",counter);
      RooRealVar mZ(name,name,95,80,110);
      sprintf(name,"Z_sigma_CAT%d",counter);
      RooRealVar sZ(name,name,12,9,20);

      sprintf(name,"Z_mean_shifted_CAT%d",counter);
      RooFormulaVar mZShift(name,"@0*@1",RooArgList(mZ,*(kJES[isel])));
      sprintf(name,"Z_sigma_shifted_CAT%d",counter);
      RooFormulaVar sZShift(name,"@0*@1",RooArgList(sZ,*(kJER[isel])));

      sprintf(name,"Z_a_CAT%d",counter);
      RooRealVar aZ(name,name,-1,-10,10);
      sprintf(name,"Z_n_CAT%d",counter);
      RooRealVar nZ(name,name,1,0,10);

      RooRealVar Zb0("Z_b0_CAT"+TString::Format("%d",counter),"Z_b0_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb1("Z_b1_CAT"+TString::Format("%d",counter),"Z_b1_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb2("Z_b2_CAT"+TString::Format("%d",counter),"Z_b2_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooBernstein Zbkg("Z_bkg_CAT"+TString::Format("%d",counter),"Z_bkg_CAT"+TString::Format("%d",counter),x,RooArgSet(Zb0,Zb1,Zb2));
      
      RooRealVar fZsig("fZsig_CAT"+TString::Format("%d",counter),"fZsig_CAT"+TString::Format("%d",counter),0.7,0.,1.);
      RooCBShape Zcore("Zcore_CAT"+TString::Format("%d",counter),"Zcore_CAT"+TString::Format("%d",counter),x,mZShift,sZShift,aZ,nZ);
    
      RooAddPdf modelZ("Z_model_CAT"+TString::Format("%d",counter),"Z_model_CAT"+TString::Format("%d",counter),RooArgList(Zcore,Zbkg),fZsig);
    
      RooFitResult *resZ = modelZ.fitTo(*roohist_Z[icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q"); 
  
      canZ->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_Z[icat]->plotOn(frame);
      modelZ.plotOn(frame,RooFit::LineWidth(2));
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      TPaveText *pave = new TPaveText(0.7,0.76,0.9,0.9,"NDC");
		pave->SetTextAlign(11);
      pave->SetFillColor(0);
      pave->SetBorderSize(0);
      pave->SetTextFont(62);
      pave->SetTextSize(0.045);
      pave->AddText(TString::Format("%s selection",SELNAME[isel].Data()));
		pave->AddText(TString::Format("CAT%d",counter));
		TText *lastline = pave->AddText("Z template");
		pave->SetY1NDC(pave->GetY2NDC()-0.055*3);
		TPaveText *paveorig = (TPaveText*)pave->Clone();
      paveorig->Draw();
    
      sprintf(name,"roohist_T_CAT%d",counter);
      if (icat < 3) { 
        roohist_T[icat] = new RooDataHist(name,name,x,hTopYield);
      }
      else {
        roohist_T[icat] = new RooDataHist(name,name,x,hSTYield);
      }

      sprintf(name,"Top_mean_CAT%d",counter);
      RooRealVar mT(name,name,130,0,200);
      sprintf(name,"Top_sigma_CAT%d",counter);
      RooRealVar sT(name,name,50,0,200);

      sprintf(name,"Top_mean_shifted_CAT%d",counter);
      RooFormulaVar mTShift(name,"@0*@1",RooArgList(mT,*(kJES[isel])));
      sprintf(name,"Top_sigma_shifted_CAT%d",counter);
      RooFormulaVar sTShift(name,"@0*@1",RooArgList(sT,*(kJER[isel])));

      sprintf(name,"Top_model_CAT%d",counter);

      RooGaussian *modelT = new RooGaussian(name,name,x,mTShift,sTShift); 
    
      RooFitResult *resT = modelT->fitTo(*roohist_T[icat],Save(),SumW2Error(kTRUE),"q");
      /*
      TF1 *tmp_func = new TF1("tmpFunc","gaus",XMIN,XMAX);
      tmp_func->SetParameters(1,a0.getVal(),a1.getVal());
      if (icat < 3) {
        float norm = tmp_func->Integral(XMIN,XMAX)/hTopYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hTopYield->Integral()/norm);
      }
      else {
        float norm = tmp_func->Integral(XMIN,XMAX)/hSTYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hSTYield->Integral()/norm);
      }  
      */
      canT->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_T[icat]->plotOn(frame);
      modelT->plotOn(frame,RooFit::LineWidth(2));
      //modelT->plotOn(frame,VisualizeError(*resT,1,kTRUE),FillColor(kGray),MoveToBack());
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      //tmp_func->Draw("sameL");
		lastline->SetTitle("Top template");
		pave->Draw();

      mZ.setConstant(kTRUE);
      sZ.setConstant(kTRUE);
      aZ.setConstant(kTRUE);
      nZ.setConstant(kTRUE);
      Zb0.setConstant(kTRUE);
      Zb1.setConstant(kTRUE);
      Zb2.setConstant(kTRUE);
      fZsig.setConstant(kTRUE);
      
      mT.setConstant(kTRUE);
      sT.setConstant(kTRUE);

      w->import(modelZ);
      w->import(*modelT);
      w->import(*YieldZ);
      w->import(*YieldT);
      w->import(*YieldTT);
      w->import(*YieldST);
      YieldZ->Print();
      YieldW->Print();
      YieldT->Print();
      YieldTT->Print();
      YieldST->Print();
      counter++;
    }// category loop
	 system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots ] && mkdir %s/plots",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots/bkgTemplates ] && mkdir %s/plots/bkgTemplates",OUTPATH.Data(),OUTPATH.Data()).Data());
	 TString FULLPATH(OUTPATH+"/plots/bkgTemplates");
	 canT->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canZ->GetName()));
	 canT->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canZ->GetName()));
	 delete can;
  }// selection loop
  system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
  system(TString::Format("[ ! -d %s/output ] && mkdir %s/output",OUTPATH.Data(),OUTPATH.Data()).Data());
  w->Print();
  w->writeToFile(TString::Format("%s/output/bkg_shapes_workspace%s.root",OUTPATH.Data(),tMERGE.Data()).Data());
}
Ejemplo n.º 21
0
void makePlots (string configFilePath){
  if ((  inputRootFileNum.size() > 0 )) 
    {
      for (int i=0; i<numHistos; i++) 
        {
          double y_max = 0.0;	 
          TCanvas *c = new TCanvas(theHistNameStrings.at(i).c_str(), "", 81,58,500,602);
 
          TH1* h_num;        // histograms for Numerator
          TH1* h_den;        // histohrams for Denominator
          int whichHisto = 0;

	  TMultiGraph *mg = new TMultiGraph();
          for (int j=0;j<inputRootFileNum.size();j++)
	    {
             whichHisto=j*numHistos; 
	      
	      int a = 0;
	      bool foundHisto = false;
	      if (theHistNameStrings.at(i) == theHistNameStrings.at(i+whichHisto)) 
		{
		  foundHisto=true; 
		  a=i;
		}
	      else 
		{
		  for (a = 0; a < numHistos; a++)
		    {
		      if (theHistNameStrings.at(i) == theHistNameStrings.at(a+whichHisto))
			{
			  foundHisto = true;
			  break;
			}
		    }
		}
	      //-----------------------------------------------------------
	      string hist2name = listHistosNum->At(a+whichHisto)->GetName();
	      if (foundHisto == true)
		{
                  h_num = (TH1*)listHistosNum->At(i+whichHisto);
                  h_den = (TH1*)listHistosDen->At(a+whichHisto);

                  TH1F* H_bins_num;
                  TH1F* H_bins_den;
                  int id = 0;
                  for (int k = 0; k < inputXtitle.size(); k++)
                   {
                     if (hist2name == inputHistoName.at(k)){
                      id=k;
                    }
                   }
                  if (inputdifferentBinSize.at(id)==1){
                     int Nbins = h_num->GetXaxis()->GetNbins();
                     int arrayD = (int*)inputNbins.at(id);
                     float *BINS = new float [arrayD];
                     for (int b = 0; b <= arrayD; b++ )
                       {
                          if (b < (arrayD-1))
                           {
                             BINS[b] = (float)b*(h_num->GetXaxis()->GetBinWidth(b));
                           }
                          else {
                             BINS[b] = (float)inputBinSize.at(id);
                          }
                       }
                     H_bins_num = new TH1F("h_NUM", "h_NUM", inputNbinMax.at(id), BINS);
                     H_bins_den = new TH1F("h_DEN", "h_DEN", inputNbinMax.at(id), BINS);
                     for (int b = 0; b <= (Nbins+1); b++ )
                       {
                         H_bins_num->SetBinContent(b, h_num->GetBinContent(b));
                         H_bins_den->SetBinContent(b, h_den->GetBinContent(b));
                       }
                  }

                  if (inputdifferentBinSize.at(id)==1){
                     TGraphAsymmErrors* gr1 = new TGraphAsymmErrors( H_bins_num, H_bins_den, "b(1,1) mode" );
                  } else{
                    cout << "h_num "<<h_num->GetXaxis()->GetNbins() << "  h_den "<<h_den->GetXaxis()->GetNbins()<<endl;
                    cout << "h_num "<<h_num->Integral() << "  h_den "<<h_den->Integral()<<endl;
                    TGraphAsymmErrors* gr1 = new TGraphAsymmErrors( h_num, h_den, "b(1,1) mode" );
                  }
		  int setcolor = inputColor.at(j);
		  int marker   = inputMarkerStyle.at(j);
                  string processlegend = (inputLegend.at(j)).c_str();
                  gr1->SetMarkerStyle(marker);
                  gr1->SetMarkerColor(setcolor);
                  gr1->SetTitle(processlegend.c_str());
                  gr1->SetFillStyle(0);
                  mg->SetTitle(hist2name.c_str());
                  mg->Add(gr1);
		}// close if (foundHisto)
 
	      c->cd();
 	      c->SetGrid(); 
	    } // close for loop inputRootFile

          mg->Draw("APsame");
          for (int k = 0; k < inputXtitle.size(); k++)
           {
              if (hist2name == inputHistoName.at(k))
               {
                 mg->GetXaxis()->SetTitle((inputXtitle.at(k)).c_str());
                 mg->GetYaxis()->SetTitle((inputYtitle.at(k)).c_str());
                 mg->GetXaxis()->SetTitleSize(0.05);
                 mg->GetYaxis()->SetTitleSize(0.05);
                 mg->SetMaximum((float)inputYrangeMax.at(k));
               }
           }
          c->Update();
          TLegend* legend = c->BuildLegend(0.55,0.8,0.90,0.94);
          //TLegend *legend = new TLegend(0.2, 0.85-.035*inputLegend.size(), 0.5, 0.90,NULL,"brNDC");
          legend->SetTextFont(42);
          legend->SetLineColor(1);
          legend->SetLineStyle(1);
          legend->SetLineWidth(1);
          legend->SetFillColor(0);
          legend->SetFillStyle(1001);
          legend->SetBorderSize(0);
          legend->SetFillColor(kWhite);

	  TFile *hfile = (TFile*)gROOT->FindObject(HistosOutputRootFile.c_str());
	  if (hfile) {hfile->Close();}
	  hfile = new TFile(HistosOutputRootFile.c_str(),"UPDATE");

          for (int o = 0; o < inputHistoName.size(); o++)
             {
                if ( c->GetName() == inputHistoName.at(o) )
                  {
                     string save = configFilePath+"/"+inputHistoName.at(o)+".pdf";  
                     c->SaveAs(save.c_str());
                     c->Write();    
                     break;
                  }
             }

	  hfile->Close();
          c->Close();
	  
	}  // close foor loop numHistos     
      
    } // close if numHistos % inputRootFile.size() == 0
} // close  makePlots function
void zlljets_ZpT_recoGenAna(const string fmumuName = "zmumujets_resoResp_noSkim_light.root", const string feeName = "zeejets_resoResp_noSkim_light.root", const char* suffix = "") {

  TH1::SetDefaultSumw2();   

  string plotDirectoryPath = "/cmshome/ciprianim/CMSSW721/pdfsFromAnalysis/plots/ZtoLLSamples/ZpTAnalysis/";
  //string plotDirectoryPath = "./tmpPlots/";  used when working in my pc
  string plotFileExtension = ".pdf";

  // index 0 of array is for muons, index 1 is for electrons, thus recoZpt[0] refers to Z->mumu ((maybe it will be better to change it)

  vector<string> fileName;
  fileName.push_back(fmumuName);
  fileName.push_back(feeName);

  vector<string> sample;
  sample.push_back("Z(#mu#mu)+jets");
  sample.push_back("Z(ee)+jets");

  vector<TH1D*> hZpTreco;
  vector<TH1D*> hZpTgen;
  vector<TH1D*> hZpTrecoGenRatio;
  vector<TH1D*> hZpTrecoGenRatio_pdf;

  Int_t nFiles = (Int_t)fileName.size();
  Int_t histColor[] = {kBlue,kOrange,kRed,kGreen};

  Double_t zptStart = 400.0;
  Double_t zptEnd = 800.0;
  TH1D *HZtoLLPt_RecoGenRatio_pdf_inRange[2];

  for(Int_t i = 0; i < 2; i++) {
	
    HZtoLLPt_RecoGenRatio_pdf_inRange[i] = new TH1D(Form("HZtoLLPt_RecoGenRatio_pdf_%d_Zpt%2.0lfTo%2.0lf",i+1,zptStart,zptEnd),"",100,0.5,1.5);

  }

  for(Int_t i = 0; i < nFiles; i++) {

    cout<<"fileName : "<<fileName[i]<<endl;

    TFile* f = TFile::Open(fileName[i].c_str(),"READ");
    
    if (!f || !f->IsOpen()) {

      cout<<"*******************************"<<endl;
      cout<<"Error opening file \""<<fileName[i]<<"\".\nApplication will be terminated."<<endl;
      cout<<"*******************************"<<endl;
      exit(EXIT_FAILURE);

    }

    hZpTreco.push_back((TH1D*)f->Get("HZtoLLRecoPt"));
    hZpTgen.push_back((TH1D*)f->Get("HZtoLLGenPt"));
    hZpTrecoGenRatio.push_back((TH1D*)f->Get("HZtoLLPt_RecoGenRatio"));
    hZpTrecoGenRatio_pdf.push_back((TH1D*)f->Get("HZtoLLPt_RecoGenRatio_pdf"));

    if ( !(hZpTreco[i] && hZpTgen[i] && hZpTrecoGenRatio[i] && hZpTrecoGenRatio_pdf[i] ) ) {

      cout << "Error: could not get histograms from file " << fileName[i] << endl;
      exit(EXIT_FAILURE);

    }
	 
  }

  Int_t startingBin = hZpTrecoGenRatio[0]->FindBin(zptStart) ;  // will consider ratio pdf for Zpt > 600 GeV  (they should be equal for Z->ee and Z->nunu)
  Int_t endingBin = hZpTrecoGenRatio[0]->FindBin(zptEnd) ;     // will consider ratio pdf for Zpt < 1000 GeV  (they should be equal for Z->ee and Z->nunu)
  cout << "ZpT bins from "<<startingBin<<" to "<<endingBin<< endl;

  for (Int_t j = 0; j < 2; j++) {

    for (Int_t i = startingBin; i < endingBin; i++) {

      HZtoLLPt_RecoGenRatio_pdf_inRange[j]->Fill(hZpTrecoGenRatio[j]->GetBinContent(i));

    }

    HZtoLLPt_RecoGenRatio_pdf_inRange[j]->Scale(1./HZtoLLPt_RecoGenRatio_pdf_inRange[j]->Integral(0,1 + HZtoLLPt_RecoGenRatio_pdf_inRange[j]->GetNbinsX()));

  }   // note that this distribution will be almost empty because it's the distribution of the mean of various ZpT points.

  //cout << " ****************  check ************** " << endl;

  for (Int_t j = 0; j < nFiles; j++) {

    hZpTreco[j]->SetStats(kFALSE);   // to avoid drawing statistic box
    hZpTreco[j]->SetLineColor(histColor[j]);
    // no need to use TH1::Scale() between reco and gen of Z->mumu or Z->ee, because histogram are filled for the same set of events, so integral
    // should be the same in principle
    //hZpTreco[j]->SetFillColorAlpha(histColor[j], 0.80);
    hZpTgen[j]->SetStats(kFALSE);   // to avoid drawing statistic box
    hZpTgen[j]->SetLineColor(histColor[j+2]);
    hZpTrecoGenRatio[j]->SetStats(kFALSE);
    //hZpTrecoGenRatio[j]->SetLineColor(histColor[j]);
    hZpTrecoGenRatio_pdf[j]->SetStats(kFALSE);
    hZpTrecoGenRatio_pdf[j]->SetLineColor(histColor[j+2]);
    HZtoLLPt_RecoGenRatio_pdf_inRange[j]->SetStats(kFALSE);
    HZtoLLPt_RecoGenRatio_pdf_inRange[j]->SetLineColor(histColor[j*2]);
    
  }

  TPad *subpad1 = NULL;  // will use it to access specific subpad in canvas
  TPad *subpad2 = NULL; 

  TCanvas *cZtomumuPtRecoGen = new TCanvas("cZtomumuPtRecoGen","",700,700);
  TLegend *legZtomumuPtRecoGen = new TLegend(0.70,0.7,0.89,0.89); 
  subpad1 = new TPad("pad1","",0.0,0.36,1.0,1.0);
  subpad1->SetLogy();
  subpad1->SetBottomMargin(0);
  subpad2 = new TPad("pad2","",0.0,0.0,1.0,0.36);
  subpad2->SetGrid();
  subpad2->SetTopMargin(0);
  subpad2->SetBottomMargin(0.2);
  subpad1->Draw();
  subpad2->Draw();
  //cout <<"Drawing histograms and ratio"<<endl;
  subpad1->cd();
  // hZpTreco[0]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // hZpTreco[0]->GetXaxis()->SetTitleSize(0.04);
  //hZpTreco[0]->GetXaxis()->SetLabelSize(0.04);
  hZpTreco[0]->GetYaxis()->SetTitle("# events");
  hZpTreco[0]->GetYaxis()->SetTitleSize(0.04);
  hZpTreco[0]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[0]->GetYaxis()->CenterTitle();
  //hZpTreco[0]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[0]->Draw("HE");
  hZpTgen[0]->Draw("HE SAME");
  legZtomumuPtRecoGen->AddEntry(hZpTreco[0],"Z(#mu#mu) reco","l");
  legZtomumuPtRecoGen->AddEntry(hZpTgen[0],"Z(#mu#mu) gen","l");
  gStyle->SetStatStyle(0);
  legZtomumuPtRecoGen->Draw(); 
  legZtomumuPtRecoGen->SetMargin(0.3); 
  legZtomumuPtRecoGen->SetBorderSize(0);
  subpad2->cd();
  hZpTrecoGenRatio[0]->GetXaxis()->SetLabelSize(0.08);
  hZpTrecoGenRatio[0]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  hZpTrecoGenRatio[0]->GetXaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[0]->GetXaxis()->SetTitleOffset(1.2);
  hZpTrecoGenRatio[0]->GetYaxis()->SetLabelSize(0.07);
  hZpTrecoGenRatio[0]->GetYaxis()->SetTitle("reco/gen ZpT");
  hZpTrecoGenRatio[0]->GetYaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[0]->GetYaxis()->SetTitleOffset(0.5);
  hZpTrecoGenRatio[0]->GetYaxis()->CenterTitle();
  hZpTrecoGenRatio[0]->Draw("E");
  hZpTrecoGenRatio[0]->SetMarkerStyle(7);  //medium dot
  cZtomumuPtRecoGen->SaveAs( (plotDirectoryPath + cZtomumuPtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  TPad *subpad1_bis = NULL;
  TPad *subpad2_bis = NULL;

  TCanvas *cZtoeePtRecoGen = new TCanvas("cZtoeePtRecoGen","",700,700);
  TLegend *legZtoeePtRecoGen = new TLegend(0.70,0.7,0.89,0.89); 
  subpad1_bis = new TPad("pad1","",0.0,0.36,1.0,1.0);
  subpad1_bis->SetLogy();
  subpad1_bis->SetBottomMargin(0);
  subpad2_bis = new TPad("pad2","",0.0,0.0,1.0,0.36);
  subpad2_bis->SetGrid();
  subpad2_bis->SetTopMargin(0);
  subpad2_bis->SetBottomMargin(0.2);
  subpad1_bis->Draw();
  subpad2_bis->Draw();
  //cout <<"Drawing histograms and ratio"<<endl;
  subpad1_bis->cd();
  // hZpTreco[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // hZpTreco[1]->GetXaxis()->SetTitleSize(0.04);
  //hZpTreco[1]->GetXaxis()->SetLabelSize(0.04);
  hZpTreco[1]->GetYaxis()->SetTitle("# events");
  hZpTreco[1]->GetYaxis()->SetTitleSize(0.04);
  hZpTreco[1]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[1]->GetYaxis()->CenterTitle();
  //hZpTreco[1]->GetYaxis()->SetLabelSize(0.04);
  hZpTreco[1]->Draw("HE");
  hZpTgen[1]->Draw("HE SAME");
  legZtoeePtRecoGen->AddEntry(hZpTreco[0],"Z(ee) reco","l");
  legZtoeePtRecoGen->AddEntry(hZpTgen[0],"Z(ee) gen","l");
  gStyle->SetStatStyle(0);
  legZtoeePtRecoGen->Draw(); 
  legZtoeePtRecoGen->SetMargin(0.3); 
  legZtoeePtRecoGen->SetBorderSize(0);
  subpad2_bis->cd();
  hZpTrecoGenRatio[1]->GetXaxis()->SetLabelSize(0.08);
  hZpTrecoGenRatio[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  hZpTrecoGenRatio[1]->GetXaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[1]->GetXaxis()->SetTitleOffset(1.2);
  hZpTrecoGenRatio[1]->GetYaxis()->SetLabelSize(0.07);
  hZpTrecoGenRatio[1]->GetYaxis()->SetTitle("reco/gen ZpT");
  hZpTrecoGenRatio[1]->GetYaxis()->SetTitleOffset(0.5);
  hZpTrecoGenRatio[1]->GetYaxis()->SetTitleSize(0.07);
  hZpTrecoGenRatio[1]->GetYaxis()->CenterTitle();
  hZpTrecoGenRatio[1]->Draw("E");
  hZpTrecoGenRatio[1]->SetMarkerStyle(7);  //medium dot
  cZtoeePtRecoGen->SaveAs( (plotDirectoryPath + cZtoeePtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  // TCanvas *cZtoeePtRecoGen = new TCanvas("cZtoeePtRecoGen","",700,700);
  // TLegend *legZtoeePtRecoGen = new TLegend(0.70,0.7,0.89,0.89);
  // cZtoeePtRecoGen->Divide(1,2,0,0);
  // cZtoeePtRecoGen->cd(1);
  // subpad1 = (TPad*)cZtoeePtRecoGen->GetPad(1);
  // subpad1->SetPad(0.0,0.36,0.98,0.99);
  // subpad1->SetLogy();
  // //cout <<"Drawing histograms and ratio"<<endl;
  // // hZpTreco[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // // hZpTreco[1]->GetXaxis()->SetTitleSize(0.04);
  // hZpTreco[1]->GetYaxis()->SetTitle("# events");
  // hZpTreco[1]->GetYaxis()->SetTitleSize(0.045);
  // hZpTreco[1]->GetYaxis()->CenterTitle();
  // //hZpTreco[1]->GetYaxis()->SetLabelSize(0.1);
  // hZpTreco[1]->Draw("HE");
  // hZpTgen[1]->Draw("HE SAME");
  // legZtoeePtRecoGen->AddEntry(hZpTreco[1],"Z(ee) reco","l");
  // legZtoeePtRecoGen->AddEntry(hZpTgen[1],"Z(ee) gen","l");
  // gStyle->SetStatStyle(0);
  // legZtoeePtRecoGen->Draw(); 
  // legZtoeePtRecoGen->SetMargin(0.3); 
  // legZtoeePtRecoGen->SetBorderSize(0);
  // cZtoeePtRecoGen->cd(2);
  // subpad2 = (TPad*)cZtoeePtRecoGen->GetPad(2);
  // subpad2->SetPad(0.0,0.0,0.98,0.36);
  // subpad2->SetGrid();
  // hZpTrecoGenRatio[1]->GetXaxis()->SetLabelSize(0.08);
  // hZpTrecoGenRatio[1]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  // hZpTrecoGenRatio[1]->GetXaxis()->SetTitleSize(0.06);
  // hZpTrecoGenRatio[1]->GetXaxis()->SetTitleOffset(1.2);
  // hZpTrecoGenRatio[1]->GetYaxis()->SetLabelSize(0.08);
  // hZpTrecoGenRatio[1]->Draw("E");
  // hZpTrecoGenRatio[1]->SetMarkerStyle(7);  //medium dot
  // cZtoeePtRecoGen->SaveAs( (plotDirectoryPath + cZtoeePtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  // now I normalize histograms to same area (here is 1) to compare Z->mumu and Z->ee which have different numbers of events

  for (Int_t j = 0; j < nFiles; j++) {

    hZpTreco[j]->Scale(1./hZpTreco[j]->Integral(0,1 + hZpTreco[j]->GetNbinsX()));  // normalize to unity, use integral including underflow & overflow bin
    hZpTgen[j]->Scale(1./hZpTgen[j]->Integral(0,1 + hZpTgen[j]->GetNbinsX()));
    hZpTrecoGenRatio_pdf[j]->Scale(1./hZpTrecoGenRatio_pdf[j]->Integral(0,1 + hZpTrecoGenRatio_pdf[j]->GetNbinsX()));

  }

  TCanvas *cZtollPtRecoGen = new TCanvas("cZtollPtRecoGen","");
  TLegend *legZtollPtRecoGen = new TLegend(0.70,0.7,0.89,0.89); 
  cZtollPtRecoGen->SetLogy();
  //cout <<"Drawing histograms and ratio"<<endl;
  hZpTreco[0]->GetXaxis()->SetTitle("Z_{pT}[GeV]");
  hZpTreco[0]->GetXaxis()->SetTitleSize(0.04);
  hZpTreco[0]->GetYaxis()->SetTitle("# events");
  hZpTreco[0]->GetYaxis()->SetTitleSize(0.045);
  hZpTreco[0]->GetYaxis()->CenterTitle();
  hZpTreco[0]->Draw("HE");
  hZpTgen[0]->Draw("HE SAME");
  hZpTreco[1]->Draw("HE SAME");
  hZpTgen[1]->Draw("HE SAME");
  legZtollPtRecoGen->AddEntry(hZpTreco[0],"Z(#mu#mu) reco","l");
  legZtollPtRecoGen->AddEntry(hZpTgen[0],"Z(#mu#mu) gen","l");
  legZtollPtRecoGen->AddEntry(hZpTreco[1],"Z(ee) reco","l");
  legZtollPtRecoGen->AddEntry(hZpTgen[1],"Z(ee) gen","l");
  gStyle->SetStatStyle(0);
  legZtollPtRecoGen->Draw(); 
  legZtollPtRecoGen->SetMargin(0.3); 
  legZtollPtRecoGen->SetBorderSize(0);
  cZtollPtRecoGen->SaveAs( (plotDirectoryPath + cZtollPtRecoGen->GetName() + suffix + plotFileExtension).c_str() );

  Int_t bins;
  Double_t firstEdge;
  Double_t lastEdge;
  TH1D *hZpTMuEleRecoRatio;
  TCanvas *cZpTMuEleRecoRatio;

  if( hZpTreco[0]->GetNbinsX() == hZpTreco[1]->GetNbinsX() ) {

    bins = hZpTreco[0]->GetNbinsX();
    firstEdge = hZpTreco[0]->GetXaxis()->GetBinLowEdge(1);
    lastEdge = hZpTreco[0]->GetXaxis()->GetBinUpEdge(bins);
    hZpTMuEleRecoRatio = new TH1D("hZpTMuEleRecoRatio","",bins,firstEdge,lastEdge);
    

    // cout << "hZpTreco[0]->GetNbinsX() : "<< hZpTreco[0]->GetNbinsX() << endl;
    // cout << "hZpTreco[1]->GetNbinsX() : "<< hZpTreco[1]->GetNbinsX() << endl;
    // cout << "hZpTMuEleGenRatio->GetNbinsX() : "<< hZpTMuEleGenRatio->GetNbinsX() << endl;

    if (!hZpTMuEleRecoRatio->Divide(hZpTreco[0],hZpTreco[1])) cout << " Error in hZpTMuEleRecoRatio->Divide(hZpTreco[0],hZpTreco[1])" << endl;
    hZpTMuEleRecoRatio->SetStats(kFALSE);
   
    cZpTMuEleRecoRatio = new TCanvas("cZpTMuEleRecoRatio","");
    hZpTMuEleRecoRatio->GetXaxis()->SetTitle("Z_{pT}[GeV]");
    hZpTMuEleRecoRatio->GetXaxis()->SetTitleSize(0.04);
    hZpTMuEleRecoRatio->GetYaxis()->SetTitle("reco pT_{Z(#mu#mu)} / pT_{Z(ee)} ");
    hZpTMuEleRecoRatio->GetYaxis()->SetTitleSize(0.045);
    hZpTMuEleRecoRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hZpTMuEleRecoRatio->GetYaxis()->CenterTitle();
    hZpTMuEleRecoRatio->Draw("E");
    gStyle->SetStatStyle(0);
    cZpTMuEleRecoRatio->SaveAs( (plotDirectoryPath + cZpTMuEleRecoRatio->GetName() + suffix + plotFileExtension).c_str() );
    
  }

  TH1D *hZpTMuEleGenRatio;
  TCanvas *cZpTMuEleGenRatio;

  if (hZpTgen[0]->GetNbinsX() == hZpTgen[1]->GetNbinsX()) {

    bins = hZpTgen[0]->GetNbinsX();
    firstEdge = hZpTgen[0]->GetXaxis()->GetBinLowEdge(1);
    lastEdge = hZpTgen[0]->GetXaxis()->GetBinUpEdge(bins);
    hZpTMuEleGenRatio = new TH1D("hZpTMuEleGenRatio","",bins,firstEdge,lastEdge);

    if (!hZpTMuEleGenRatio->Divide(hZpTgen[0],hZpTgen[1])) cout << " Error in hZpTMuEleGenRatio->Divide(hZpTgen[0],hZpTgen[1])" << endl;
    hZpTMuEleGenRatio->SetStats(kFALSE);

    cZpTMuEleGenRatio = new TCanvas("cZpTMuEleGenRatio","");
    hZpTMuEleGenRatio->GetXaxis()->SetTitle("Z_{pT}[GeV]");
    hZpTMuEleGenRatio->GetXaxis()->SetTitleSize(0.04);
    hZpTMuEleGenRatio->GetYaxis()->SetTitle("gen pT_{Z(#mu#mu)} / pT_{Z(ee)} ");
    hZpTMuEleGenRatio->GetYaxis()->SetTitleSize(0.045);
    hZpTMuEleGenRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hZpTMuEleGenRatio->GetYaxis()->CenterTitle();
    hZpTMuEleGenRatio->Draw("E");
    gStyle->SetStatStyle(0);
    cZpTMuEleGenRatio->SaveAs( (plotDirectoryPath + cZpTMuEleGenRatio->GetName() + suffix + plotFileExtension).c_str() );
 
  }


  TCanvas *cZpTRecoGenRatio_pdf = new TCanvas("cZpTRecoGenRatio_pdf","");
  TLegend *legZpTRecoGenRatio_pdf = new TLegend(0.78,0.78,0.89,0.89);
  hZpTrecoGenRatio_pdf[0]->GetXaxis()->SetTitle("reco Z_{pT}/gen Z_{pT}");
  hZpTrecoGenRatio_pdf[0]->GetXaxis()->SetTitleSize(0.04);
  hZpTrecoGenRatio_pdf[0]->GetXaxis()->SetRangeUser(0.7,1.3);
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->SetTitle("a.u. ");
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->SetTitleSize(0.045);
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->SetRangeUser(0.0,0.4);
  hZpTrecoGenRatio_pdf[0]->GetYaxis()->CenterTitle();
  hZpTrecoGenRatio_pdf[0]->Draw("HE");
  hZpTrecoGenRatio_pdf[1]->Draw("HE SAME");
  legZpTRecoGenRatio_pdf->AddEntry(hZpTrecoGenRatio_pdf[0],"Z(#mu#mu)","l");
  legZpTRecoGenRatio_pdf->AddEntry(hZpTrecoGenRatio_pdf[1],"Z(ee)","l");
  gStyle->SetStatStyle(0);
  legZpTRecoGenRatio_pdf->Draw(); 
  legZpTRecoGenRatio_pdf->SetMargin(0.3); 
  legZpTRecoGenRatio_pdf->SetBorderSize(0);
  cZpTRecoGenRatio_pdf->SaveAs( (plotDirectoryPath + cZpTRecoGenRatio_pdf->GetName() + suffix + plotFileExtension).c_str() );

  TCanvas *cZpTRecoGenRatio_pdf_inRange = new TCanvas(Form("ZpTRecoGenRatio_pdf_Zpt%2.0lfTo%2.0lf",zptStart,zptEnd),"");
  TLegend *legZpTRecoGenRatio_pdf_inRange = new TLegend(0.78,0.78,0.89,0.89);
  TPaveLabel *title = new TPaveLabel(0.1,0.94,0.9,0.98,Form("Zpt recoGen ratio: %2.0lf < ZpT < %2.0lf",zptStart,zptEnd));
  title->Draw();
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetXaxis()->SetTitle("reco Z_{pT}/gen Z_{pT}");
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetXaxis()->SetTitleSize(0.04);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetXaxis()->SetRangeUser(0.7,1.3);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->SetTitle("a.u. ");
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->SetTitleSize(0.045);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->SetRangeUser(0.0,0.4);
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->GetYaxis()->CenterTitle();
  HZtoLLPt_RecoGenRatio_pdf_inRange[0]->Draw("HE");
  HZtoLLPt_RecoGenRatio_pdf_inRange[1]->Draw("HE SAME");
  legZpTRecoGenRatio_pdf_inRange->AddEntry(HZtoLLPt_RecoGenRatio_pdf_inRange[0],"Z(#mu#mu)","l");
  legZpTRecoGenRatio_pdf_inRange->AddEntry(HZtoLLPt_RecoGenRatio_pdf_inRange[1],"Z(ee)","l");
  gStyle->SetStatStyle(0);
  legZpTRecoGenRatio_pdf_inRange->Draw(); 
  legZpTRecoGenRatio_pdf_inRange->SetMargin(0.3); 
  legZpTRecoGenRatio_pdf_inRange->SetBorderSize(0);
  cZpTRecoGenRatio_pdf_inRange->SaveAs( (plotDirectoryPath + cZpTRecoGenRatio_pdf_inRange->GetName() + suffix + plotFileExtension).c_str() );

}
Ejemplo n.º 23
0
void AccTimesEff::Loop()
{
   TStopwatch timer;
   timer.Start();
   // parameters /////////////////////////////////////////////////////////////
   vector<TString> files;
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9999ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-750_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_10000ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9998ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1250_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9998ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9997ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1750_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9997ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-2000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9999ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-2500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9999ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-3000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_10000ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-3500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9898ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-4000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9998ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-5000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9966ev.root");
   string outfileName = "accTimesEffHistos";

   // output file formats
   const bool saveSpec = 0;
   const bool saveAsPdf = 0;
   const bool saveAsPng = 1;
   const bool saveAsRoot = 0;
   TString plotDir = "./plots/";

   int font = 42; //62
   // selection cuts /////////////////////////////////////////////////////////
   float elePtCut = 35.;
   float muPtCut = 35.;
   float minInvMass = 0.;

   TH1::SetDefaultSumw2(kTRUE);

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

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

   TH1F *hGenEvts = new TH1F("hGenEvts", "hGenEvts", 145, 0., 5010.);
   hGenEvts->GetXaxis()->SetTitle("M_{Z'}^{truth}");
   hGenEvts->GetXaxis()->SetTitleFont(font);
   hGenEvts->GetXaxis()->SetLabelFont(font);
   hGenEvts->GetYaxis()->SetTitle("Events");
   hGenEvts->GetYaxis()->SetTitleFont(font);
   hGenEvts->GetYaxis()->SetLabelFont(font);
   hGenEvts->GetYaxis()->SetTitleOffset(1.2);
   hGenEvts->SetLineColor(kBlack);
   hGenEvts->SetLineWidth(2);
   hGenEvts->SetMarkerStyle(20);
   hGenEvts->SetMarkerColor(kBlack);
   TH1F *hGenEvtsEleInAcc = (TH1F*)hGenEvts->Clone("hGenEvtsEleInAcc");
   TH1F *hGenEvtsEleInAccEB = (TH1F*)hGenEvts->Clone("hGenEvtsEleInAccEB");
   TH1F *hGenEvtsEleInAccEE = (TH1F*)hGenEvts->Clone("hGenEvtsEleInAccEE");
   TH1F *hGenEvtsMuInAcc = (TH1F*)hGenEvts->Clone("hGenEvtsMuInAcc");
   TH1F *hGenEvtsInAcc = (TH1F*)hGenEvts->Clone("hGenEvtsInAcc");
   TH1F *hTrgEvts = (TH1F*)hGenEvts->Clone("hTrgEvts");
   hTrgEvts->SetTitle("hTrgEvts");
   TH1F *hRecoEvts = (TH1F*)hGenEvts->Clone("hRecoEvts");
   hRecoEvts->SetTitle("hRecoEvts");
   TH1F *hRecoEvtsEB = (TH1F*)hRecoEvts->Clone("hRecoEvtsEB");
   TH1F *hRecoEvtsEE = (TH1F*)hRecoEvts->Clone("hRecoEvtsEE");
   TH1F *hRecoEleEvts = (TH1F*)hRecoEvts->Clone("hRecoEleEvts");
   TH1F *hRecoEleEvtsEB = (TH1F*)hRecoEvts->Clone("hRecoEleEvtsEB");
   TH1F *hRecoEleEvtsEE = (TH1F*)hRecoEvts->Clone("hRecoEleEvtsEE");
   TH1F *hRecoMuEvts = (TH1F*)hRecoEvts->Clone("hRecoMuEvts");
   TH1F *hRecoNoTrgEvts = (TH1F*)hGenEvts->Clone("hRecoNoTrgEvts");
   hRecoNoTrgEvts->SetTitle("hRecoNoTrgEvts");
   TH1F *hRecoNoTrgEvtsEB = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEvtsEB");
   TH1F *hRecoNoTrgEvtsEE = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEvtsEE");
   TH1F *hRecoNoTrgEleEvts = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEleEvts");
   TH1F *hRecoNoTrgEleEvtsEB = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEleEvtsEB");
   TH1F *hRecoNoTrgEleEvtsEE = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEleEvtsEE");
   TH1F *hRecoNoTrgMuEvts = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgMuEvts");
   TH1F* hAcc;
   TH1F* hAccEle;
   TH1F* hAccEleEB;
   TH1F* hAccEleEE;
   TH1F* hAccMu;
   TH1F* hAccTimesTrgEff;
   TH1F* hTrgEff;
   TH1F* hAccTimesEff;
   TH1F* hAccTimesEffEB;
   TH1F* hAccTimesEffEE;
   TH1F* hAccTimesEffEle;
   TH1F* hAccTimesEffEleEB;
   TH1F* hAccTimesEffEleEE;
   TH1F* hAccTimesEffMu;
   TH1F* hAccTimesEffNoTrg;
   //TH1F* hAccTimesEffNoTrgEB;
   //TH1F* hAccTimesEffNoTrgEE;
   TH1F* hAccTimesEffNoTrgEle;
   TH1F* hAccTimesEffNoTrgEleEB;
   TH1F* hAccTimesEffNoTrgEleEE;
   TH1F* hAccTimesEffNoTrgMu;
   TH1F* hEffAftTrg;
   TH1F* hEffAftTrgEle;
   TH1F* hEffAftTrgEleEB;
   TH1F* hEffAftTrgEleEE;
   TH1F* hEffAftTrgMu;
   TH1F* hTrgRecoVsReco;
   //TH1F* hTrgRecoVsRecoEB;
   //TH1F* hTrgRecoVsRecoEE;
   TH1F* hTrgRecoVsRecoEle;
   TH1F* hTrgRecoVsRecoEleEB;
   TH1F* hTrgRecoVsRecoEleEE;
   TH1F* hTrgRecoVsRecoMu;

   // output file
   stringstream ssOutfile;
   ssOutfile << outfileName << ".root";
   TFile *output = new TFile(ssOutfile.str().c_str(), "recreate");

   ///////////////////////////////////////////////////////////////////////////
   //LOOP OVER FILES 
   ///////////////////////////////////////////////////////////////////////////
   for (unsigned int p = 0; p < files.size(); ++p) {
      TFile* input = new TFile(files[p]);
      TTree *thetree = (TTree*)input->Get("gsfcheckerjob/tree");
      Init(thetree);
      Long64_t nentries = fChain->GetEntriesFast();
      cout << nentries << " events" << endl;

      unsigned int evCounter = 0;
      /////////////////////////////////////////////////////////////////////////////////////////////
      //LOOP OVER EVENTS
      /////////////////////////////////////////////////////////////////////////////////////////////
      //nentries = 10000;
      for (Long64_t jentry = 0; jentry < nentries; ++jentry) {
         Long64_t ientry = LoadTree(jentry);
         if (ientry < 0) break;
         fChain->GetEntry(jentry);
         // if (Cut(ientry) < 0) continue;
         //if (jentry % 50000 == 0) cout << "Processing event " << jentry << endl;
         thetree->GetEntry(jentry);

         // fill the gen histograms
         hGenEvts->Fill(genelemom_mass[0]);

         // fill the acc histograms
         if (hardGenEle_pt[0] > elePtCut) {
            if (fabs(hardGenEle_eta[0]) < 1.442) {
               hGenEvtsEleInAcc->Fill(genelemom_mass[0]);
               hGenEvtsEleInAccEB->Fill(genelemom_mass[0]);
            }
            else if (fabs(hardGenEle_eta[0]) > 1.56 && fabs(hardGenEle_eta[0]) < 2.5) {
               hGenEvtsEleInAcc->Fill(genelemom_mass[0]);
               hGenEvtsEleInAccEE->Fill(genelemom_mass[0]);
            }
         }
         if (hardGenMu_pt[0] > muPtCut && fabs(hardGenMu_eta[0]) < 2.4) {
            hGenEvtsMuInAcc->Fill(genelemom_mass[0]);
            if (fabs(hardGenEle_eta[0]) < 1.442 || (fabs(hardGenEle_eta[0]) > 1.56 && fabs(hardGenEle_eta[0]) < 2.5)) {
               if (hardGenEle_pt[0] > elePtCut) hGenEvtsInAcc->Fill(genelemom_mass[0]);
            }
         }

         // trigger?
         if (HLT_Mu22_Photon22_CaloIdL) hTrgEvts->Fill(genelemom_mass[0]);

         // at least one gsf electron and one muon above the threshold
         if (gsf_size < 1 || muon_size < 1) continue;

         vector<int> GSF_passHEEP;
         vector<int> MU_passGOOD;
         /////////////////////////////////////////////////////////////////////////////////////////////
         //loop over electrons
         for (int j = 0; j < gsf_size; ++j) {
            //cleaning: fake electrons from muons
            bool fakeEle = false;
            for (int k = 0; k < muon_size; ++k) {
               float DeltaR = deltaR(gsf_eta[j], gsf_phi[j], muon_eta[k], muon_phi[k]);
               if (DeltaR < 0.1) {
                  fakeEle = true;
                  break;
               }
            }
            if (fakeEle) continue;

            if (PassHEEP(j)) GSF_passHEEP.push_back(j);
         }

         //loop over muons
         for (int j = 0; j < muon_size; ++j) {
            if (PassHighPtMu(j)) MU_passGOOD.push_back(j);
         }

         if (GSF_passHEEP.size() == 1) {
            if (HLT_Mu22_Photon22_CaloIdL) {
               hRecoEleEvts->Fill(genelemom_mass[0]);
               if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoEleEvtsEB->Fill(genelemom_mass[0]);
               if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoEleEvtsEE->Fill(genelemom_mass[0]);
            }
            hRecoNoTrgEleEvts->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoNoTrgEleEvtsEB->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoNoTrgEleEvtsEE->Fill(genelemom_mass[0]);
         } 
         if (MU_passGOOD.size() == 1) {
            if (HLT_Mu22_Photon22_CaloIdL) hRecoMuEvts->Fill(genelemom_mass[0]);
            hRecoNoTrgMuEvts->Fill(genelemom_mass[0]);
         }

         // veto when there are more than one good candidates
         if (GSF_passHEEP.size() != 1 || MU_passGOOD.size() != 1) continue;

         //HEEP ele + GOOD muon
         TLorentzVector ele1;
         TLorentzVector mu1;

         ele1.SetPtEtaPhiM(gsf_gsfet[GSF_passHEEP[0]], gsf_eta[GSF_passHEEP[0]], gsf_phi[GSF_passHEEP[0]], 0.000511);
         mu1.SetPtEtaPhiM(muon_pt[MU_passGOOD[0]], muon_eta[MU_passGOOD[0]], muon_phi[MU_passGOOD[0]], 0.10566);

         double invMass = (ele1 + mu1).M();

         //MASS CUT
         if (invMass < minInvMass) continue;

         if (HLT_Mu22_Photon22_CaloIdL) {
            hRecoEvts->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoEvtsEB->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoEvtsEE->Fill(genelemom_mass[0]);
         }
         hRecoNoTrgEvts->Fill(genelemom_mass[0]);
         if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoNoTrgEvtsEB->Fill(genelemom_mass[0]);
         if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoNoTrgEvtsEE->Fill(genelemom_mass[0]);
         ++evCounter;
        ///////////////////////////////////////////////////////////////////////
      } //END LOOP OVER EVENTS
        //////////////////////////////////////////////////////////////////////

     //////////////////////////////////////////////////////////////////////////
   } //END LOOP OVER FILES
     //////////////////////////////////////////////////////////////////////////
   hAcc = (TH1F*)hGenEvtsInAcc->Clone("hAcc");
   hAccEle = (TH1F*)hGenEvtsEleInAcc->Clone("hAccEle");
   hAccEleEB = (TH1F*)hGenEvtsEleInAccEB->Clone("hAccEleEB");
   hAccEleEE = (TH1F*)hGenEvtsEleInAccEE->Clone("hAccEleEE");
   hAccMu = (TH1F*)hGenEvtsMuInAcc->Clone("hAccMu");
   hAccTimesTrgEff = (TH1F*)hTrgEvts->Clone("hAccTimesTrgEff");
   hTrgEff = (TH1F*)hTrgEvts->Clone("hTrgEff");
   hAccTimesEff = (TH1F*)hRecoEvts->Clone("hAccTimesEff");
   hAccTimesEffEB = (TH1F*)hRecoEvtsEB->Clone("hAccTimesEffEB");
   hAccTimesEffEE = (TH1F*)hRecoEvtsEE->Clone("hAccTimesEffEE");
   hAccTimesEffEle = (TH1F*)hRecoEleEvts->Clone("hAccTimesEffEle");
   hAccTimesEffEleEB = (TH1F*)hRecoEleEvtsEB->Clone("hAccTimesEffEleEB");
   hAccTimesEffEleEE = (TH1F*)hRecoEleEvtsEE->Clone("hAccTimesEffEleEE");
   hAccTimesEffMu = (TH1F*)hRecoMuEvts->Clone("hAccTimesEffMu");
   hAccTimesEffNoTrg = (TH1F*)hRecoNoTrgEvts->Clone("hAccTimesEffNoTrg");
   //hAccTimesEffNoTrgEB = (TH1F*)hRecoNoTrgEvtsEB->Clone("hAccTimesEffNoTrgEB");
   //hAccTimesEffNoTrgEE = (TH1F*)hRecoNoTrgEvtsEE->Clone("hAccTimesEffNoTrgEE");
   hAccTimesEffNoTrgEle = (TH1F*)hRecoNoTrgEleEvts->Clone("hAccTimesEffNoTrgEle");
   hAccTimesEffNoTrgEleEB = (TH1F*)hRecoNoTrgEleEvtsEB->Clone("hAccTimesEffNoTrgEleEB");
   hAccTimesEffNoTrgEleEE = (TH1F*)hRecoNoTrgEleEvtsEE->Clone("hAccTimesEffNoTrgEleEE");
   hAccTimesEffNoTrgMu = (TH1F*)hRecoNoTrgMuEvts->Clone("hAccTimesEffNoTrgMu");
   hEffAftTrg = (TH1F*)hRecoEvts->Clone("hAccTimesEff");
   hEffAftTrgEle = (TH1F*)hRecoEleEvts->Clone("hAccTimesEffEle");
   hEffAftTrgEleEB = (TH1F*)hRecoEleEvtsEB->Clone("hAccTimesEffEleEB");
   hEffAftTrgEleEE = (TH1F*)hRecoEleEvtsEE->Clone("hAccTimesEffEleEE");
   hEffAftTrgMu = (TH1F*)hRecoMuEvts->Clone("hAccTimesEffMu");
   hTrgRecoVsReco = (TH1F*)hRecoEvts->Clone("hTrgRecoVsReco");
   //hTrgRecoVsRecoEB = (TH1F*)hRecoEvtsEB->Clone("hTrgRecoVsRecoEB");
   //hTrgRecoVsRecoEE = (TH1F*)hRecoEvtsEE->Clone("hTrgRecoVsRecoEE");
   hTrgRecoVsRecoEle = (TH1F*)hRecoEleEvts->Clone("hTrgRecoVsRecoEle");
   hTrgRecoVsRecoEleEB = (TH1F*)hRecoEleEvtsEB->Clone("hTrgRecoVsRecoEleEB");
   hTrgRecoVsRecoEleEE = (TH1F*)hRecoEleEvtsEE->Clone("hTrgRecoVsRecoEleEE");
   hTrgRecoVsRecoMu = (TH1F*)hRecoMuEvts->Clone("hTrgRecoVsRecoMu");
   hAcc->Divide(hGenEvts);
   hAccEle->Divide(hGenEvts);
   hAccEleEB->Divide(hGenEvts);
   hAccEleEE->Divide(hGenEvts);
   hAccMu->Divide(hGenEvts);
   hAccTimesTrgEff->Divide(hGenEvts);
   hTrgEff->Divide(hGenEvtsInAcc);
   hAccTimesEff->Divide(hGenEvts);
   hAccTimesEffEB->Divide(hGenEvts);
   hAccTimesEffEE->Divide(hGenEvts);
   hAccTimesEffEle->Divide(hGenEvts);
   hAccTimesEffEleEB->Divide(hGenEvts);
   hAccTimesEffEleEE->Divide(hGenEvts);
   hAccTimesEffMu->Divide(hGenEvts);
   hAccTimesEffNoTrg->Divide(hGenEvts);
   //hAccTimesEffNoTrgEB->Divide(hGenEvts);
   //hAccTimesEffNoTrgEE->Divide(hGenEvts);
   hAccTimesEffNoTrgEle->Divide(hGenEvts);
   hAccTimesEffNoTrgEleEB->Divide(hGenEvts);
   hAccTimesEffNoTrgEleEE->Divide(hGenEvts);
   hAccTimesEffNoTrgMu->Divide(hGenEvts);
   hEffAftTrg->Divide(hTrgEvts);
   hEffAftTrgEle->Divide(hTrgEvts);
   hEffAftTrgEleEB->Divide(hTrgEvts);
   hEffAftTrgEleEE->Divide(hTrgEvts);
   hEffAftTrgMu->Divide(hTrgEvts);
   hTrgRecoVsReco->Divide(hRecoNoTrgEvts);
   //hTrgRecoVsRecoEB->Divide(hRecoNoTrgEvtsEB);
   //hTrgRecoVsRecoEE->Divide(hRecoNoTrgEvtsEE);
   hTrgRecoVsRecoEle->Divide(hRecoNoTrgEleEvts);
   hTrgRecoVsRecoEleEB->Divide(hRecoNoTrgEleEvtsEB);
   hTrgRecoVsRecoEleEE->Divide(hRecoNoTrgEleEvtsEE);
   hTrgRecoVsRecoMu->Divide(hRecoNoTrgMuEvts);

   // plot
   TCanvas *accTimesEffPlot = new TCanvas("accTimesEffPlot", "acc x eff", 100, 100, 600, 600);
   TPad *accTimesEffPad = new TPad("accTimesEffPad", "acc x eff pad", 0., 0., 1., 1.);
   accTimesEffPad->SetBottomMargin(0.12);
   accTimesEffPad->SetBorderMode(0);
   accTimesEffPad->SetBorderSize(2);
   accTimesEffPad->SetFrameBorderMode(0);
   accTimesEffPad->SetFillColor(0);
   accTimesEffPad->SetFrameFillColor(0);
   accTimesEffPad->SetLeftMargin(0.11);
   accTimesEffPad->SetRightMargin(0.09);
   accTimesEffPad->SetTopMargin(0.08);
   accTimesEffPad->SetTickx(1);
   accTimesEffPad->SetTicky(1);
   accTimesEffPad->Draw();
   accTimesEffPad->cd();

   gStyle->SetTitleFont(font);
   gStyle->SetLabelFont(font);
   gStyle->SetLegendFont(font);
   gStyle->SetOptStat(0);
   gStyle->SetOptTitle(0);
   gStyle->SetOptFit(1111);
   gStyle->SetTitleXOffset(1.);
   gStyle->SetTitleYOffset(1.3);
   gPad->SetTicks(1, 1);
   gPad->SetGrid(1, 1);

   TH1F* hAccTimesEff2 = (TH1F*)hAccTimesEff->Clone("hAccTimesEff2");

   TF1 *fitFunc = new TF1("fitFunc", "[0] + [1]/ (x + [2]) + [3]*x", 10., 5010.);
   //TF1 *fitFuncEB = new TF1("fitFuncEB", "[0] + [1]/ (x + [2])", 10., 5010.);
   TF1 *fitFuncEB = new TF1("fitFuncEB", "[0] + [1]/ (x + [2]) + [3]*x", 10., 5010.);
   TF1 *fitFuncEE = new TF1("fitFuncEE", "[0] + [1]/ (x*x + [2])", 10., 5010.);
   fitFunc->SetLineColor(kBlue);
   fitFuncEB->SetLineColor(kBlue);
   fitFuncEE->SetLineColor(kBlue);
   hAccTimesEff->Fit("fitFunc", "", "", 480., 5010.);
   hAccTimesEffEB->Fit("fitFuncEB", "", "", 480., 5010.);
   hAccTimesEffEE->Fit("fitFuncEE", "", "", 480., 5010.);
   cout << "Chi^2 / NDF: " << fitFunc->GetChisquare() << " / " << fitFunc->GetNDF() << ", prob: " << fitFunc->GetProb() << endl;
   cout << "Chi^2 / NDF EB: " << fitFuncEB->GetChisquare() << " / " << fitFuncEB->GetNDF() << ", prob: " << fitFuncEB->GetProb() << endl;
   cout << "Chi^2 / NDF EE: " << fitFuncEE->GetChisquare() << " / " << fitFuncEE->GetNDF() << ", prob: " << fitFuncEE->GetProb() << endl;

   hAccTimesEff->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEff->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEff->Draw();
   TLatex *tex = new TLatex(0.22, 0.21, "P(M|p0,p1,p2,p3) = p0 + #frac{p1}{M+p2} + p3*M");
   tex->SetNDC();
   tex->SetTextFont(font);
   tex->SetLineWidth(2);
   tex->SetTextSize(0.03);
   tex->Draw();
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.17, 0.85, "trg + electron + muon");

   TCanvas *accTimesEffPlotEB = new TCanvas("accTimesEffPlotEB", "acc x eff, barrel electron + muon", 100, 100, 600, 600);
   TPad *accTimesEffPadEB = (TPad*)accTimesEffPad->Clone("accTimesEffPadEB");
   accTimesEffPadEB->Draw(); 
   accTimesEffPadEB->cd();
   hAccTimesEffEB->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffEB->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffEB->Draw();
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   //tex->DrawLatex(0.46, 0.21, "P(M|p0,p1,p2) = p0 + #frac{p1}{M+p2}");
   tex->DrawLatex(0.22, 0.21, "P(M|p0,p1,p2,p3) = p0 + #frac{p1}{M+p2} + p3*M");
   tex->DrawLatex(0.17, 0.85, "trg + barrel electron + muon");

   TCanvas *accTimesEffPlotEE = new TCanvas("accTimesEffPlotEE", "acc x eff, endcap electron + muon", 100, 100, 600, 600);
   TPad *accTimesEffPadEE = (TPad*)accTimesEffPad->Clone("accTimesEffPadEE");
   accTimesEffPadEE->Draw(); 
   accTimesEffPadEE->cd();
   hAccTimesEffEE->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffEE->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffEE->Draw();
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.45, 0.38, "P(M|p0,p1,p2) = p0 + #frac{p1}{M^{2}+p2}");
   tex->DrawLatex(0.17, 0.85, "trg + endcap electron + muon");

   TCanvas *accTimesEffObjPlot = new TCanvas("accTimesEffObjPlot", "acc x eff, objects", 100, 100, 600, 600);
   TPad *accTimesEffObjPad = (TPad*)accTimesEffPad->Clone("accTimesEffObjPad");
   accTimesEffObjPad->Draw(); 
   accTimesEffObjPad->cd();
   hAccTimesEffEle->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffEle->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffEle->SetMarkerStyle(kFullSquare);
   hAccTimesEffEle->SetMarkerColor(kViolet);
   hAccTimesEffEle->SetLineColor(kViolet);
   hAccTimesEffEle->Draw();
   hAccTimesEffEleEB->SetMarkerStyle(kFullTriangleUp);
   hAccTimesEffEleEB->SetMarkerColor(kRed);
   hAccTimesEffEleEB->SetLineColor(kRed);
   hAccTimesEffEleEB->Draw("same");
   hAccTimesEffEleEE->SetMarkerStyle(kFullTriangleDown);
   hAccTimesEffEleEE->SetMarkerColor(kBlue);
   hAccTimesEffEleEE->SetLineColor(kBlue);
   hAccTimesEffEleEE->Draw("same");
   hAccTimesEffMu->SetMarkerStyle(34);
   hAccTimesEffMu->SetMarkerColor(kGreen+1);
   hAccTimesEffMu->SetLineColor(kGreen+1);
   hAccTimesEffMu->Draw("same");
   hAccTimesEff2->Draw("same");
   TLegend* legend = new TLegend(0.592, 0.279, 0.881, 0.467);
   legend->SetTextFont(font);
   legend->SetTextSize(0.03);
   legend->SetBorderSize(0);
   legend->SetLineColor(1);
   legend->SetLineStyle(1);
   legend->SetLineWidth(1);
   legend->SetFillColor(19);
   legend->SetFillStyle(0);
   legend->AddEntry(hAccTimesEff, "total acc x eff");
   legend->AddEntry(hAccTimesEffMu, "muons");
   legend->AddEntry(hAccTimesEffEle, "all electrons");
   legend->AddEntry(hAccTimesEffEleEB, "barrel electrons");
   legend->AddEntry(hAccTimesEffEleEE, "endcap electrons");
   legend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.17, 0.85, "trg: HLT_Mu22_Photon22_CaloIdL");

   // acc x eff with no trg applied
   TCanvas *accTimesEffNoTrgObjPlot = new TCanvas("accTimesEffNoTrgObjPlot", "acc x eff, no trigger, objects", 100, 100, 600, 600);
   TPad *accTimesEffNoTrgObjPad = (TPad*)accTimesEffPad->Clone("accTimesEffNoTrgObjPad");
   accTimesEffNoTrgObjPad->Draw(); 
   accTimesEffNoTrgObjPad->cd();
   hAccTimesEffNoTrgEle->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffNoTrgEle->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffNoTrgEle->SetMarkerStyle(kFullSquare);
   hAccTimesEffNoTrgEle->SetMarkerColor(kViolet);
   hAccTimesEffNoTrgEle->SetLineColor(kViolet);
   hAccTimesEffNoTrgEle->Draw();
   hAccTimesEffNoTrgEleEB->SetMarkerStyle(kFullTriangleUp);
   hAccTimesEffNoTrgEleEB->SetMarkerColor(kRed);
   hAccTimesEffNoTrgEleEB->SetLineColor(kRed);
   hAccTimesEffNoTrgEleEB->Draw("same");
   hAccTimesEffNoTrgEleEE->SetMarkerStyle(kFullTriangleDown);
   hAccTimesEffNoTrgEleEE->SetMarkerColor(kBlue);
   hAccTimesEffNoTrgEleEE->SetLineColor(kBlue);
   hAccTimesEffNoTrgEleEE->Draw("same");
   hAccTimesEffNoTrgMu->SetMarkerStyle(34);
   hAccTimesEffNoTrgMu->SetMarkerColor(kGreen+1);
   hAccTimesEffNoTrgMu->SetLineColor(kGreen+1);
   hAccTimesEffNoTrgMu->Draw("same");
   hAccTimesEffNoTrg->Draw("same");
   TLegend* accXeffNoTrg = (TLegend*)legend->Clone("effAftTrgLegend");
   accXeffNoTrg->Clear();
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrg, "total acc x eff");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgMu, "muons");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgEle, "all electrons");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgEleEB, "barrel electrons");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgEleEE, "endcap electrons");
   accXeffNoTrg->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.17, 0.85, "trg: none");

   // efficiency on triggered events
   TCanvas *effAftTrgPlot = new TCanvas("effAftTrgPlot", "efficiency after trigger", 100, 100, 600, 600);
   TPad *effAftTrgPad = (TPad*)accTimesEffPad->Clone("effAftTrgPad");
   effAftTrgPad->Draw(); 
   effAftTrgPad->cd();
   hEffAftTrgEle->GetYaxis()->SetTitle("eff");
   hEffAftTrgEle->GetYaxis()->SetRangeUser(0., 1.);
   hEffAftTrgEle->SetMarkerStyle(kFullSquare);
   hEffAftTrgEle->SetMarkerColor(kViolet);
   hEffAftTrgEle->SetLineColor(kViolet);
   hEffAftTrgEle->Draw();
   hEffAftTrgEleEB->SetMarkerStyle(kFullTriangleUp);
   hEffAftTrgEleEB->SetMarkerColor(kRed);
   hEffAftTrgEleEB->SetLineColor(kRed);
   hEffAftTrgEleEB->Draw("same");
   hEffAftTrgEleEE->SetMarkerStyle(kFullTriangleDown);
   hEffAftTrgEleEE->SetMarkerColor(kBlue);
   hEffAftTrgEleEE->SetLineColor(kBlue);
   hEffAftTrgEleEE->Draw("same");
   hEffAftTrgMu->SetMarkerStyle(34);
   hEffAftTrgMu->SetMarkerColor(kGreen+1);
   hEffAftTrgMu->SetLineColor(kGreen+1);
   hEffAftTrgMu->Draw("same");
   hEffAftTrg->Draw("same");
   TLegend* effAftTrgLegend = (TLegend*)legend->Clone("effAftTrgLegend");
   effAftTrgLegend->Clear();
   effAftTrgLegend->AddEntry(hEffAftTrg, "total eff after trigger");
   effAftTrgLegend->AddEntry(hEffAftTrgMu, "muons");
   effAftTrgLegend->AddEntry(hEffAftTrgEle, "all electrons");
   effAftTrgLegend->AddEntry(hEffAftTrgEleEB, "barrel electrons");
   effAftTrgLegend->AddEntry(hEffAftTrgEleEE, "endcap electrons");
   effAftTrgLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.14, 0.15, "trg: HLT_Mu22_Photon22_CaloIdL");

   // acceptance
   TCanvas *accPlot = new TCanvas("accPlot", "acc", 100, 100, 600, 600);
   TPad *accPad = (TPad*)accTimesEffPad->Clone("accPad");
   accPad->Draw(); 
   accPad->cd();
   hAcc->GetYaxis()->SetTitle("acc");
   hAcc->GetYaxis()->SetRangeUser(0., 1.);
   hAccEle->SetMarkerStyle(kFullSquare);
   hAccEle->SetMarkerColor(kViolet);
   hAccEle->SetLineColor(kViolet);
   hAccEle->Draw();
   hAccEleEB->SetMarkerStyle(kFullTriangleUp);
   hAccEleEB->SetMarkerColor(kRed);
   hAccEleEB->SetLineColor(kRed);
   hAccEleEB->Draw("same");
   hAccEleEE->SetMarkerStyle(kFullTriangleDown);
   hAccEleEE->SetMarkerColor(kBlue);
   hAccEleEE->SetLineColor(kBlue);
   hAccEleEE->Draw("same");
   hAccMu->SetMarkerStyle(34);
   hAccMu->SetMarkerColor(kGreen+1);
   hAccMu->SetLineColor(kGreen+1);
   hAccMu->Draw("same");
   hAcc->Draw("same");
   TLegend* accLegend = (TLegend*)legend->Clone("accLegend");
   accLegend->Clear();
   accLegend->AddEntry(hAcc, "total acceptance");
   accLegend->AddEntry(hAccMu, "muons");
   accLegend->AddEntry(hAccEle, "all electrons");
   accLegend->AddEntry(hAccEleEB, "barrel electrons");
   accLegend->AddEntry(hAccEleEE, "endcap electrons");
   accLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");

   // reco with trg vs. reco
   TCanvas *trgRecoVsRecoPlot = new TCanvas("trgRecoVsRecoPlot", "reco with trg vs. reco", 100, 100, 600, 600);
   TPad *trgRecoVsRecoPad = (TPad*)accTimesEffPad->Clone("trgRecoVsRecoPad");
   trgRecoVsRecoPad->Draw(); 
   trgRecoVsRecoPad->cd();
   hTrgRecoVsRecoEle->GetYaxis()->SetTitle("eff");
   hTrgRecoVsRecoEle->GetYaxis()->SetRangeUser(0., 1.);
   hTrgRecoVsRecoEle->SetMarkerStyle(kFullSquare);
   hTrgRecoVsRecoEle->SetMarkerColor(kViolet);
   hTrgRecoVsRecoEle->SetLineColor(kViolet);
   hTrgRecoVsRecoEle->Draw();
   //hTrgRecoVsRecoEleEB->SetMarkerStyle(kFullTriangleUp);
   //hTrgRecoVsRecoEleEB->SetMarkerColor(kRed);
   //hTrgRecoVsRecoEleEB->SetLineColor(kRed);
   //hTrgRecoVsRecoEleEB->Draw("same");
   //hTrgRecoVsRecoEleEE->SetMarkerStyle(kFullTriangleDown);
   //hTrgRecoVsRecoEleEE->SetMarkerColor(kBlue);
   //hTrgRecoVsRecoEleEE->SetLineColor(kBlue);
   //hTrgRecoVsRecoEleEE->Draw("same");
   hTrgRecoVsRecoMu->SetMarkerStyle(34);
   hTrgRecoVsRecoMu->SetMarkerColor(kGreen+1);
   hTrgRecoVsRecoMu->SetLineColor(kGreen+1);
   hTrgRecoVsRecoMu->Draw("same");
   hTrgRecoVsReco->Draw("same");
   TLegend* trgRecoVsRecoLegend = (TLegend*)legend->Clone("trgRecoVsRecoLegend");
   trgRecoVsRecoLegend->Clear();
   trgRecoVsRecoLegend->AddEntry(hTrgRecoVsReco, "total");
   trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoMu, "muons");
   trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoEle, "electrons");
   //trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoEleEB, "barrel electrons");
   //trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoEleEE, "endcap electrons");
   trgRecoVsRecoLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");

   TCanvas *accTimesTrgEffPlot = new TCanvas("accTimesTrgEffPlot", "acc x trigger eff", 100, 100, 600, 600);
   TPad *accTimesTrgEffPad = (TPad*)accTimesEffPad->Clone("accTimesTrgEffPad");
   accTimesTrgEffPad->Draw(); 
   accTimesTrgEffPad->cd();
   hAccTimesTrgEff->GetYaxis()->SetTitle("acc x trg eff");
   hAccTimesTrgEff->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesTrgEff->SetMarkerStyle(20);
   hAccTimesTrgEff->SetMarkerColor(kCyan);
   hAccTimesTrgEff->SetLineColor(kCyan);
   hAccTimesTrgEff->Draw();
   hTrgEff->SetMarkerStyle(21);
   hTrgEff->SetMarkerColor(kMagenta);
   hTrgEff->SetLineColor(kMagenta);
   hTrgEff->Draw("same");
   TLegend* trgLegend = (TLegend*)legend->Clone("trgLegend");
   trgLegend->Clear();
   trgLegend->AddEntry(hTrgEff, "trigger eff in acc");
   trgLegend->AddEntry(hAccTimesTrgEff, "acc x trigger eff");
   trgLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");

   // safe in various file formats
   if (saveSpec) {
     if (saveAsPdf) {
        accTimesTrgEffPlot->Print(plotDir + accTimesTrgEffPlot->GetName() + ".pdf", "pdf");
        accTimesEffPlot->Print(plotDir + accTimesEffPlot->GetName() + ".pdf", "pdf");
        accTimesEffPlotEB->Print(plotDir + accTimesEffPlotEB->GetName() + ".pdf", "pdf");
        accTimesEffPlotEE->Print(plotDir + accTimesEffPlotEE->GetName() + ".pdf", "pdf");
        accTimesEffObjPlot->Print(plotDir + accTimesEffObjPlot->GetName() + ".pdf", "pdf");
        accTimesEffNoTrgObjPlot->Print(plotDir + accTimesEffNoTrgObjPlot->GetName() + ".pdf", "pdf");
        effAftTrgPlot->Print(plotDir + effAftTrgPlot->GetName() + ".pdf", "pdf");
        trgRecoVsRecoPlot->Print(plotDir + trgRecoVsRecoPlot->GetName() + ".pdf", "pdf");
        accPlot->Print(plotDir + accPlot->GetName() + ".pdf", "pdf");
     }
     if (saveAsPng) {
        accTimesTrgEffPlot->Print(plotDir + accTimesTrgEffPlot->GetName() + ".png", "png");
        accTimesEffPlot->Print(plotDir + accTimesEffPlot->GetName() + ".png", "png");
        accTimesEffPlotEB->Print(plotDir + accTimesEffPlotEB->GetName() + ".png", "png");
        accTimesEffPlotEE->Print(plotDir + accTimesEffPlotEE->GetName() + ".png", "png");
        accTimesEffObjPlot->Print(plotDir + accTimesEffObjPlot->GetName() + ".png", "png");
        accTimesEffNoTrgObjPlot->Print(plotDir + accTimesEffNoTrgObjPlot->GetName() + ".png", "png");
        effAftTrgPlot->Print(plotDir + effAftTrgPlot->GetName() + ".png", "png");
        trgRecoVsRecoPlot->Print(plotDir + trgRecoVsRecoPlot->GetName() + ".png", "png");
        accPlot->Print(plotDir + accPlot->GetName() + ".png", "png");
     }
     if (saveAsRoot) {
        accTimesTrgEffPlot->Print(plotDir + accTimesTrgEffPlot->GetName() + ".root", "root");
        accTimesEffPlot->Print(plotDir + accTimesEffPlot->GetName() + ".root", "root");
        accTimesEffPlotEB->Print(plotDir + accTimesEffPlotEB->GetName() + ".root", "root");
        accTimesEffPlotEE->Print(plotDir + accTimesEffPlotEE->GetName() + ".root", "root");
        accTimesEffObjPlot->Print(plotDir + accTimesEffObjPlot->GetName() + ".root", "root");
        accTimesEffNoTrgObjPlot->Print(plotDir + accTimesEffNoTrgObjPlot->GetName() + ".root", "root");
        effAftTrgPlot->Print(plotDir + effAftTrgPlot->GetName() + ".root", "root");
        trgRecoVsRecoPlot->Print(plotDir + trgRecoVsRecoPlot->GetName() + ".root", "root");
        accPlot->Print(plotDir + accPlot->GetName() + ".root", "root");
     }
   }

   // write histos to file
   output->cd();
   hGenEvts->Write();
   hGenEvtsEleInAcc->Write();
   hGenEvtsEleInAccEB->Write();
   hGenEvtsEleInAccEE->Write();
   hGenEvtsMuInAcc->Write();
   hGenEvtsInAcc->Write();
   hTrgEvts->Write();
   hRecoEvts->Write();
   hRecoEvtsEB->Write();
   hRecoEvtsEE->Write();
   hRecoEleEvts->Write();
   hRecoEleEvtsEB->Write();
   hRecoEleEvtsEE->Write();
   hRecoMuEvts->Write();
   hAccEle->Write();
   hAccEleEB->Write();
   hAccEleEE->Write();
   hAccMu->Write();
   hAccTimesTrgEff->Write();
   hTrgEff->Write();
   hAccTimesEff->Write();
   hAccTimesEffEB->Write();
   hAccTimesEffEE->Write();
   hAccTimesEffEle->Write();
   hAccTimesEffEleEB->Write();
   hAccTimesEffEleEE->Write();
   hAccTimesEffMu->Write();
   hEffAftTrg->Write();
   hEffAftTrgEle->Write();
   hEffAftTrgEleEB->Write();
   hEffAftTrgEleEE->Write();
   hEffAftTrgMu->Write();
   fitFunc->Write();
   fitFuncEB->Write();
   fitFuncEE->Write();

   output->Close();
   timer.Stop();
   timer.Print();
}
void advancedNoiseAnalysis( unsigned int runNumber, unsigned int loop = 1) {
  
  string inputFileName = "./histo/run00" + toString( runNumber ) + "-ped-histo.root";
  string outputFileName = "./histo/run00" + toString( runNumber ) + "-adv-noise.root";
  

  // before opening the input and the output files, try to see if they
  // are not opened yet and in case close them before continue   
  TList * listOfOpenedFile = (TList*) gROOT->GetListOfFiles();
  for ( int i = 0; i < listOfOpenedFile->GetSize() ; ++i ) {
    TFile * file = (TFile*) listOfOpenedFile->At( i ) ;
    TString fileName(file->GetName());
    TString inputFileName1( inputFileName.c_str() );
    TString outputFileName1( outputFileName.c_str() );

    if (  ( fileName.Contains( inputFileName1 ) ) ||
	  ( inputFileName1.Contains( fileName ) ) ||
	  ( fileName.Contains( outputFileName1 ) ) ||
	  ( outputFileName1.Contains( fileName ) ) ) {
      cout << "Closing " << fileName << " before reopen " << endl;
      file->Close();
    }
  }


  // close also all the previously opened canvas
  TList * listOfOpenedCanvas = (TList*) gROOT->GetListOfCanvases();
  for ( int i = 0 ; i < listOfOpenedCanvas->GetSize() ; ++i ) {
    TCanvas * canvas = (TCanvas*) listOfOpenedCanvas->At( i );
    TString canvasName2 = canvas->GetName();
    if ( canvasName2.Contains( "det" ) ) {
      canvas->Close();
    }
  }

	 
  // now safely open the file
  TFile * inputFile = TFile::Open( inputFileName.c_str() ) ;
  TFile * outputFile = TFile::Open( outputFileName.c_str(), "RECREATE") ;
  TList * outputHistoList = new TList;

  // look into the inputFile for a folder named
  string pedeProcessorFolderName = "PedestalAndNoiseCalculator";
  TDirectoryFile * pedeProcessorFolder = (TDirectoryFile*) inputFile->Get( pedeProcessorFolderName.c_str() );
  
  if ( pedeProcessorFolder == 0 ) { 
    cerr << "No pedestal processor folder found in file " << inputFileName << endl;
    return ;
  }

  // this folder should contain one folder for each loop.
  string loopFolderName = "loop-" + toString( loop );
  TDirectoryFile * loopFolder = (TDirectoryFile *) pedeProcessorFolder->Get( loopFolderName.c_str() );
  
  if ( loopFolder == 0 ) {
    cerr << "No " << loopFolderName << " found in file " << inputFileName << endl;
    return ;
  }

  // guess the number of sensors from the number of subfolder in the loopfolder
  size_t nDetector = loopFolder->GetListOfKeys()->GetSize();
  cout << "This file contains " << nDetector << " detectors" << endl;

  // prepare arrays to store the mean and the rms of the noise distribution
  if ( noiseMean == NULL ) {
    delete [] noiseMean;
    noiseMean = NULL;
  }
  if ( noiseRMS == NULL ) {
    delete [] noiseRMS;
    noiseRMS = NULL;
  }
  if ( channel == NULL ) {
    delete [] channel;
    channel = NULL;
  }

  noiseMean = new double[ nDetector * kNChan ];
  noiseRMS  = new double[ nDetector * kNChan ];
  channel   = new double[ kNChan ];

  string canvasName = "comparison";
  string canvasTitle = "Noise comparison";

  TCanvas * comparisonCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  comparisonCanvas->Divide(1,2);
  
  TPad * topPad = (TPad*) comparisonCanvas->cd(1);
  topPad->Divide( nDetector );
  
  TPad * middlePad = (TPad *) comparisonCanvas->cd(2);
  middlePad->Divide( kNChan );


  // for each detector we have to get the noise map and to prepare 4
  // separe histos and maps
  for ( unsigned int iDetector = 0; iDetector < nDetector; iDetector++ ) {

    // get the noise map.
    string noiseMapName = "detector-" + toString( iDetector ) ;
    noiseMapName += "/NoiseMap-d" + toString( iDetector )  ;
    noiseMapName += "-l" + toString( loop ) ;
 
    TH2D * noiseMap = ( TH2D* ) loopFolder->Get( noiseMapName.c_str() ); 
    

    // create a folder in the output file
    TDirectory * subfolder = outputFile->mkdir( string( "detector_" + toString( iDetector ) ).c_str(),
						string( "detector_" + toString( iDetector ) ).c_str()
						);
    subfolder->cd();

    
    string canvasName = "det" + toString( iDetector );
    string canvasTitle = "Detector " + toString( iDetector );
    
    TCanvas * canvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
    canvas->Divide( kNChan, 2 );

    // ok now start the loop on channels
    for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) { 
	
      if ( iDetector == 0 ) channel[iChan] = iChan - 0.5;

      string tempName = "NoiseMap_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      string tempTitle = "NoiseMap Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ;

      TH2D * noiseMapCh = new TH2D ( tempName.c_str() , tempTitle.c_str(), 
				     kXPixel / kNChan , -0.5 + xLimit[ iChan ] , -0.5 + xLimit[ iChan + 1 ],
				     kYPixel, -0.5, -0.5 + kYPixel );
      noiseMapCh->SetXTitle("X [pixel]");
      noiseMapCh->SetYTitle("Y [pixel]");
      noiseMapCh->SetZTitle("Noise [ADC]");
      noiseMapCh->SetStats( false );
      outputHistoList->Add( noiseMapCh ) ;

      tempName = "NoiseDist_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      
      tempTitle = "NoiseDist Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ; 

      TH1D * noiseDistCh = new TH1D( tempName.c_str(), tempTitle.c_str(), 50, 0., 10. );
      noiseDistCh->SetXTitle("Noise [ADC]");
      noiseDistCh->SetLineColor( kColor[iDetector]  );
      noiseDistCh->SetLineStyle( iChan + 2 );
      noiseDistCh->SetLineWidth( 2 );
      outputHistoList->Add( noiseDistCh );

      // let's start looping on pixels now
      for ( size_t yPixel = 1 ; yPixel <= kYPixel ; ++yPixel ) {
	for ( size_t xPixel = xLimit[ iChan ] + 1; xPixel <= xLimit[ iChan +1 ] ; ++xPixel ) {
	  double noise = noiseMap->GetBinContent( xPixel , yPixel );
	  noiseMapCh->Fill( xPixel - 1 , yPixel - 1, noise );
	  noiseDistCh->Fill( noise );
	  
	}
      }

      canvas->cd( iChan + 1 ) ;
      noiseMapCh->Draw("colz");
      canvas->cd( iChan + kNChan + 1  );
      noiseDistCh->Draw();
      
      topPad->cd( iDetector + 1 );
      if ( iChan == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }

      middlePad->cd( iChan + 1 );
      if ( iDetector == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }


      noiseMean[ kNChan * iDetector + iChan ] = noiseDistCh->GetMean();
      noiseRMS[ kNChan * iDetector  + iChan ] = noiseDistCh->GetRMS();
    }
    canvas->Write();

  }

  canvasName = "summary";
  canvasTitle = "Noise summary";

  TCanvas * summaryCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  summaryCanvas->SetGridx(1);
  TLegend * legend = new TLegend(0.5, 4.8, 1.5, 4.3,"","br");;
  

  for ( size_t iDetector = 0 ; iDetector < nDetector ; ++iDetector ) {
    
    TGraphErrors * gr = new TGraphErrors( kNChan, channel, &noiseMean[ iDetector * kNChan ], NULL, &noiseRMS[ iDetector * kNChan ] );
    gr->SetName( string( "NoisePerChannel_d" + toString( iDetector )).c_str());
    gr->SetTitle(string("Detector " + toString( iDetector )).c_str());
    gr->GetXaxis()->SetTitle("Channel #");
    gr->GetYaxis()->SetTitle("Noise [ADC]");
    gr->GetXaxis()->SetNdivisions( 5 );
    gr->GetXaxis()->SetLabelSize( 0 );
    gr->SetMarkerStyle( iDetector + 1 );
    gr->SetMarkerColor( kColor[iDetector] );
    gr->SetLineColor( kColor[iDetector] );
    gr->SetLineWidth( 2 );

    
    legend->AddEntry( gr, string("Detector " + toString( iDetector )).c_str(), "LP");

    if ( iDetector == 0 ) {
      gr->Draw("ALP");
    } else {
      gr->Draw("LP");
    }
    

  }

  
  
  legend->Draw();

  for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) {
    
    TPaveLabel * label = new TPaveLabel( iChan - 0.75 , 3.2 , iChan -0.25 , 3, string("Ch " + toString( iChan ) ).c_str());
    label->Draw();
  }


  summaryCanvas->Write();
  comparisonCanvas->Write();

  outputHistoList->Write();

  

 
} 
Ejemplo n.º 25
0
void format_plots_data(){
	cout<<"hello world"<<endl;
	CMSStyle();
	
		///////////////////////////// Switcehs //////////////////////////////////////

        int nKinemVars = nKinemVars_all;
	string *s_KinemVars = s_KinemVars_all;


	int printlevel = 1;
	bool saveImages = true;
	
	bool makediphoMassPlot = 1;
	bool makeBkgDemo = 1;
	bool makeBkg1 = 0;
	bool makeBkgRat = 0;	
		///////////////////////////// File Work ///////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Start File work" << endl;

		///INPUT FILES
	const int nDataAndMcFiles = 1;
	string Data = "Data";
	string s_DataAndMcFiles[nDataAndMcFiles]    = {Data};//** FOR INEDEXING
	string s_DataAndMcFiles_v4[nDataAndMcFiles] = {Data};

		///Output File
	TFile* fplots = new TFile(formatedplotsroot_data.c_str(),"RECREATE");

	TFileMap PostAnaAnaFiles;
	TFileMap MainAnaFiles;
	cout<<endl<<"Reading in data file "<<plotsAndBackground_data<<endl<<endl;
	PostAnaAnaFiles[Data] = new TFile(plotsAndBackground_data.c_str());
	MainAnaFiles[Data]    = new TFile(plotsroot_data.c_str());
	
//	PostAnaAnaFiles["st350ho200"] = new TFile(plotsAndBackground_mc.c_str());
//	MainAnaFiles["st350ho200"]    = new TFile(plotsroot_mc.c_str());

	cout<<endl<<"Writing finished plots to file "<<plotsroot_data<<endl<<endl;

                ///////////////////////////// STANDARD MARKINGS ///////////////////////////////////////
        TLatex * TEX_CMSPrelim;
        if(preliminary) TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS Preliminary");
        else TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS");
        PrettyLatex(TEX_CMSPrelim,0.03);
        TLatex * TEX_E_TeV = new TLatex(0.800251,0.953368,"#sqrt{s} = 8 TeV");
        PrettyLatex(TEX_E_TeV,0.03);
        TLatex * TEX_lumi_fb = new TLatex(0.621859,0.953368,Form("#intL dt = %.1f fb^{-1}",Integrated_Luminosity_Data));
        PrettyLatex(TEX_lumi_fb,0.03);


		///////////////////////////// Other Lists ///////////////////////////////////////	
	/*Debug*/ if(printlevel > 0) cout << "Make Other Lists" << endl;


	
		/////////////// FOR INDEXING, USE THESE /////////////////////////
		///	string s_MassBkgDists[nPhoMassAndBkgDists]={lowSB,tag,upperSB,bkg,tag_subbkg,lowSB_scaled,upperSB_scaled};
		/// string s_EventTopology[nEventTopologies]={"","1Jb","3J","3Jb","metCut"};
		/// string s_KinemVars[nKinemVars]={"MET","ST","PtGG","HT","MHT"};
		/// string s_DataAndMcFiles[nDataAndMcFiles]={Data,"MC_st350ho200"...}
		/////////////////////////////////////////////////////////////////



		//	const int nEventTopologies = 5; // the number of types of cuts selected, like 1JB...
		//string s_EventTopology[nEventTopologies] = {"","1Jb","3J","3Jb","metCut"};//** FOR INEDEXING
	string s_EventTopology_v2[nEventTopologies];//{"","_1Jb","_3J","_3Jb","_metCut"};
	string s_EventTopology_v3[nEventTopologies];//{"","_1Jb_","_3J_","_3Jb_","_metCut_"};
	//s_EventTopology_v2[0]=s_EventTopology[0];
	//s_EventTopology_v3[0]=s_EventTopology[0];
	for (int i=0; i<nEventTopologies; i++) {
		s_EventTopology_v2[i] = string("_")+s_EventTopology[i];
		s_EventTopology_v3[i] = string("_")+s_EventTopology[i]+"_";
	}

	//const int nPhoMassAndBkgDists //lsb, tag, usb...
	//	string s_MassBkgDists[] = {"lowSB","tag","upperSB","bkg","tag_subbkg","lowSB_scaled","upperSB_scaled"};
	//	string s_MassBkgDists_v2[] = {"_lowSB","_tag","_upperSB","_bkg","_tag_subbkg","_lowSB_scaled","_upperSB_scaled"};
	string s_MassBkgDists_v2[nPhoMassAndBkgDists];
	for (int i=0; i<nPhoMassAndBkgDists; i++) {s_MassBkgDists_v2[i]=string("_")+s_MassBkgDists[i];}

	string s_DataAndMcFiles_v2[nDataAndMcFiles];
	string s_DataAndMcFiles_v3[nDataAndMcFiles];
	s_DataAndMcFiles_v2[0]=Data;//{Data,"MC_st350ho200"...}
	s_DataAndMcFiles_v3[0]=Data;//{Data,"MC","MC","MC"...}
	for (int i=1; i<nDataAndMcFiles; i++) {s_DataAndMcFiles_v3[i]=string("MC_")+s_DataAndMcFiles[i];}
	for (int i=1; i<nDataAndMcFiles; i++) {s_DataAndMcFiles_v3[i]=string("MC");}

		///////////////////////////// LUMI SCALES ///////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Set Lumi Scales" << endl;
	Labledflaot lumiscalemap;
	lumiscalemap[Data] = 1.;
	const float Integrated_Luminosity_Data = 5.725; /*fb^-1*/
	lumiscalemap["st350ho200"] = (Integrated_Luminosity_Data * 447.4 /*fb*/)/((float) 1000000 /*events*/);


		//////////////////////////////////////////////////////////////////////////////
		///////////////////////////////Load h_mGG/////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Load h_mGG" << endl;
		//load mGG_unsliced histograms from all files. 
	Lable2Hist h_mGG_unsliced;
	for (int jFile=0; jFile<nDataAndMcFiles; jFile++) { //loop over all files
		LableHist tmp; // this is the collection of histograms, indexed by topology name
		/*Debug*/ if(printlevel > 2) cout << "first loop, jFile = "<<jFile << endl;
		for (int iTop = 0; iTop<nEventTopologies; iTop++) {
			/*Debug*/ if(printlevel > 4) cout << "second loop, iTop = "<<iTop <<endl;
			string instring = string("h_mGG") +s_EventTopology[iTop] + "_unsliced";
			/*Debug*/ if(printlevel > 4) cout << "loading "<<instring<< " from file " << s_DataAndMcFiles[jFile] << " for topology "<<s_EventTopology[iTop] <<endl;
			tmp[s_EventTopology[iTop]] = (TH1F*)PostAnaAnaFiles[s_DataAndMcFiles[jFile]]->Get(instring.c_str());
			/*Debug*/ if(printlevel > 4) cout << "succeeded"<<endl;
			
				//fix the root names
			string newname = instring+"_"+s_DataAndMcFiles[jFile];
			/*Debug*/ if(printlevel > 4) cout << "resetting name to "<<newname<<" for topology "<<s_EventTopology[iTop]<<endl;
//			/*Debug*/ if(printlevel > 6) cout << tmp[s_EventTopology[iTop]]->Integral()<<endl;
			
			tmp[s_EventTopology[iTop]]->SetName((newname).c_str());
			/*Debug*/ if(printlevel > 4) cout << "succeeded"<<endl;
		}
		/*Debug*/ if(printlevel > 2) cout << "Attempting to write tmp to h_mGG_unsliced with tag "<<s_DataAndMcFiles[jFile] << endl;
		h_mGG_unsliced[s_DataAndMcFiles[jFile]] = tmp;
		/*Debug*/ if(printlevel > 2) cout << "succeeded"<<endl;
	}
//	TH1F* h_mGG_unsliced = (TH1F*)fin.Get("h_mGG_unsliced");
//	TH1F* h_mGG_1Jb_unsliced = (TH1F*)fin.Get("h_mGG_1Jb_unsliced");
	
		////////////////////////////// Load Kin Var Plots //////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Load Kin Var Plots" << endl;
	Lable3HistArr KinVarHistMap;
	for (int jFile=0; jFile<nDataAndMcFiles; jFile++) {
		
		/*Debug*/ if(printlevel >2) cout << "first loop, jFile = "<<jFile <<endl;	
		Lable2HistArr tmpMapTopo;
		for (int iTop = 0; iTop<nEventTopologies; iTop++) {
			/*Debug*/ if(printlevel >4) cout << "second loop, iTop = "<<iTop <<endl;
			
			LableHistArr tmpMapKinVar;
			for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
				/*Debug*/ if(printlevel >6) cout << "third loop, kKinVar = "<<kKinVar <<endl;
				
					//there is no MET dist for metCut, so don't try to load it. 
				if (s_EventTopology[iTop].compare("metCut") == 0 && s_KinemVars[kKinVar].compare("MET") == 0) continue;
				if (iTop == 2 && kKinVar==0) {cout << endl<<endl<<" ***** ERROR!! your attempt to skip metCut|MET failed"<<endl<<endl; 	}
				
				TH1F** tmpHistArray = new TH1F*[nPhoMassAndBkgDists];
					//LoadHistSet(hMET, &fin, "MET");
				for (int lMassDist=0; lMassDist < nPhoMassAndBkgDists; lMassDist++){
					/*Debug*/ if(printlevel >8) cout << "forth loop, lMassDist = "<<lMassDist <<" out of "<<nPhoMassAndBkgDists<<endl;
					string instring = string("h")+s_KinemVars[kKinVar]+s_EventTopology[iTop]+"_"+s_MassBkgDists[lMassDist];
					/*Debug*/ if(printlevel >8) cout << "Load hist "<<instring<< " from file "<< s_DataAndMcFiles[jFile] << " into tmpHistArray["<<lMassDist<<"]"<<endl;

					tmpHistArray[lMassDist] = (TH1F*) PostAnaAnaFiles[s_DataAndMcFiles[jFile]]->Get( instring.c_str() );
						//fix the root name
					string newname = instring+"_"+s_DataAndMcFiles[jFile];
					/*Debug*/ if(printlevel >8) cout << "rename hist "<<newname <<endl;
					tmpHistArray[lMassDist]->SetName((newname).c_str());
					/*Debug*/ if(printlevel >8) cout << "success" <<endl;
					string newtitle = string(";")+s_KinemVars[kKinVar]+" (GeV)";
					tmpHistArray[lMassDist]->SetTitle((char*)newtitle.c_str());
				}//end for every Mass Dist
				/*Debug*/ if(printlevel >6) cout << "load hist array into tmpMapKinVar for "<< s_KinemVars[kKinVar] <<endl;
				tmpMapKinVar[s_KinemVars[kKinVar]] = tmpHistArray;
								
			}//End for each kinematic varraible
			/*Debug*/ if(printlevel >4) cout << "load hist array into tmpMapTopo for "<< s_EventTopology[iTop] <<endl;
			tmpMapTopo[s_EventTopology[iTop]] = tmpMapKinVar;
			
		}//end for each topology
		/*Debug*/ if(printlevel >2) cout << "load hist array into KinVarHistMap for "<< s_DataAndMcFiles[jFile] <<endl;
		KinVarHistMap[s_DataAndMcFiles[jFile]] = tmpMapTopo;
	}//end for each file

	/*Debug*/ if(printlevel >2){
		cout << "***KinVarHistMap should now be loaded, but did it work?***"<<endl;
		//cout << "Data 1Jb MHT tag name:" <<KinVarHistMap["Data"]["1Jb"]["MHT"][1]->GetName()<<endl;
		//cout << "Data 3Jb MHT tag name:" <<KinVarHistMap["Data"]["3Jb"]["MHT"][1]->GetName()<<endl;
		//cout << "Data 1Jb ST tag name:" <<KinVarHistMap["Data"]["1Jb"]["ST"][1]->GetName()<<endl;
		//cout << "Data 1Jb MHT sb name:" <<KinVarHistMap["Data"]["1Jb"]["MHT"][5]->GetName()<<endl;
		cout << "Data MHT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["MHT"][7]->GetBinContent(1)<<endl;
		cout << "Data HT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["HT"][7]->GetBinContent(1)<<endl;
		cout << "Data ST L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["ST"][7]->GetBinContent(1)<<endl;
		cout << "***If this is printing, then the answer is probably Yes ***"<<endl;
	}

	
//	h_mGG_unsliced->SetName("h_mGG_unsliced");
/*	TH1F * hMET[nPhoMassAndBkgDists];
	LoadHistSet(hMET, &fin, "MET");

	TH1F * hST_1Jb[nPhoMassAndBkgDists];
	LoadHistSet(hST_1Jb,&fin,"ST_1Jb");
	*/
	
		////////////////////////////////////////////////////////////////////
		/*Debug*/ if(printlevel > 0) cout << "Load the Fit Curves" << endl;
		//load the fit curves for the data. 
	TF1* mgg_fit_curve[nEventTopologies];
	for (int iTop=0; iTop<nEventTopologies; iTop++) {
		/*Debug*/ if(printlevel > 1) cout << "first loop, iTop = "<<iTop <<endl;
		string instring = string("mgg") + s_EventTopology_v3[iTop] + "fit";
		/*Debug*/ if(printlevel > 1) cout << "instring = "<<instring <<endl;//mggNULLfit, am I naming it wrong? 
		mgg_fit_curve[iTop] = (TF1*)PostAnaAnaFiles[Data]->Get(instring.c_str());
		/*Debug*/ if(printlevel > 1) cout << "supposidly loaded it, try it "<<endl;
		/*Debug*/ if(printlevel > 1) cout << mgg_fit_curve[iTop]->GetProb() <<endl;//seg faults the first time it's exectuted. 
		
/*	mgg_fit_curve[0] = (TF1*)fin.Get("mggfit");
	mgg_fit_curve[1] = (TF1*)fin.Get("mgg_1Jb_fit");
	mgg_fit_curve[2] = (TF1*)fin.Get("mgg_3J_fit");
	mgg_fit_curve[3] = (TF1*)fin.Get("mgg_3Jb_fit");
	mgg_fit_curve[4] = (TF1*)fin.Get("mgg_metCut_fit");*/
	}
	
	
		// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//     ___              __       ____           ___  __     __    
//    / _ \___ ___ ____/ /_ __  / __/__  ____  / _ \/ /__  / /____
//   / , _/ -_) _ `/ _  / // / / _// _ \/ __/ / ___/ / _ \/ __(_-<
//  /_/|_|\__/\_,_/\_,_/\_, / /_/  \___/_/   /_/  /_/\___/\__/___/
//                     /___/                                      
		/*Debug*/ if(printlevel > 0) cout << "Start Building Plots" << endl;

	fplots->cd();

		//if there is not a plots folder, make it. 
	
//     __  ___            ___  __     __ 
//    /  |/  /__ ____ _  / _ \/ /__  / /_
//   / /|_/ / _ `/ _ `/ / ___/ / _ \/ __/
//  /_/  /_/\_, /\_, / /_/  /_/\___/\__/ 
//         /___//___/ 


		/*Debug*/ if(printlevel > 0) cout << "Build mass plots" << endl;
	
		//diphoton mass plots, one for each data plot, for each topology. 
	if(makediphoMassPlot){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		/*Debug*/ if(printlevel > 1) cout << "first loop, iTop = "<<iTop <<endl;
		string canvName = string("c_mgg")+s_EventTopology_v2[iTop]+"_unsliced";
		/*Debug*/ if(printlevel > 1) cout << "made tempCanv with name "<<canvName  <<endl;
		TCanvas* tempCanv = newTCanvas((char*)canvName.c_str()); //char*error
		/*Debug*/ if(printlevel > 1) cout << "Enter the merky deptsh of diphoMassPlot"<<endl;
		diphoMassPlot(h_mGG_unsliced[Data][s_EventTopology[iTop]],tempCanv,mgg_fit_curve[iTop]);
		/*Debug*/ if(printlevel > 1) cout << "fin dinphoMass plot, try to write to fplots" <<endl;
		tempCanv->Write();
		if(saveImages) SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfjpgepspng");//save as all types
		//if(saveImages) SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
	}
	}
	

		// %%%%%%%%%%%%%%%%%%%%%%%% Kinematics and backgrounds %%%%%%%%%%%%%%%%%
//     ___  __        ___                   ___  __     __    
//    / _ )/ /_____ _/ _ \___ __ _  ___    / _ \/ /__  / /____
//   / _  /  '_/ _ `/ // / -_)  ' \/ _ \  / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, /____/\__/_/_/_/\___/ /_/  /_/\___/\__/___/
//            /___/                                           

	/*Debug*/ if(printlevel > 0) cout << "Build Kin Var plots type 1" << endl;
		//Arrangement 1
        TH1F * box = new TH1F("box","asdf",1,0,1);
        box->SetMarkerColor(kRed);
        box->SetMarkerStyle(25);
        box->SetMarkerSize(2);
        box->SetLineColor(0);
		///Demonstrate background. Plot two side bands with their ratio as a sub-plot. include a switchable Tag.


	if(makeBkgDemo){
	for (int iTop = 0; iTop<nEventTopologies; iTop++){
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++){
			/*Debug*/ if(printlevel >2) cout << "iTop="<<iTop<<" kKinVar="<<kKinVar<<endl;
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ){
				/*Debug*/ if(printlevel >2) cout << "skipping met plot for met cut"<<endl;
				continue;
			}
			string canvName = string("BkgFull_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			/*Debug*/ if(printlevel >6) {TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			/*Debug*/ if(printlevel >6) printf("Scan1 Ratio bin1 for %s %s  = %f\n",s_EventTopology[iTop].c_str(),s_KinemVars[kKinVar].c_str(),h[7]->GetBinContent(1));}
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			BkgDemo_Diplot(tempCanv,
					 KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]],
						   makeL1(0.2072864,0.7203704,0.4070352,0.9203704),
						   makeL2(0.51005,0.706436,0.708543,0.902669));
			//tempCanv->Write();
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
		}//edn for each kinematic varriable
	}//end for each topology
	}

//     ___  __       ___  ___  __     __    
//    / _ )/ /_____ <  / / _ \/ /__  / /____
//   / _  /  '_/ _ `/ / / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, /_/ /_/  /_/\___/\__/___/
//            /___/                         

		///Demostrate background-upper. Plot the two side bands together, but ignore the ratio. (Arr2)
	if(makeBkg1){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ) continue;
			string canvName = string("Bkg1_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			string canvNamelog = string("Bkg1Log_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			TCanvas* tempCanvlog = newTCanvas((char*)canvNamelog.c_str());
			tempCanvlog->SetTopMargin(0.06);
                        tempCanvlog->SetBottomMargin(0.15);

			TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			tempCanv->cd();
			//RaiseRangeRoof(h[5],1.25);
			//RaiseRangeRoof(h[1],1.25);
			//RaiseRangeRoof(h[6],1.25);
			PrettyHist(h[5],kBlue);
			PrettyHist(h[1],1);
			PrettyHist(h[6],kGreen);
			PrettyHist(h[3],kRed);

//			string cname = tempCanv->GetName();
//			if(cname.find("_HT")!=string::npos)//if found "_HT" in the name
//				h[5]->GetXaxis()->SetLabelSize(0.04);
				//SPECIAL
			if (s_KinemVars[kKinVar].compare("HT") == 0) {
				h[5]->GetXaxis()->SetLabelSize(0.04);}

			PrettyBlock2(h[5],kBlue,3354,2);//PrettyMarker(h[5],kBlue,4);
			//PrettyBlock(h[5],kBlue,string("//thatch"));//PrettyMarker(h[5],kBlue,4);
			PrettyMarker(h[1]);
			PrettyBlock2(h[6],kGreen,3345,2);//PrettyMarker(h[6],kGreen,4);
			h[3]->SetFillStyle(0);//open rectangle
                        h[3]->SetLineColor(kRed);
                        h[3]->SetLineWidth(4);
			//PrettyBlock(h[6],kGreen,string("\\thatch"));//PrettyMarker(h[6],kGreen,4);
			playNiceWithLegend(h[3],0.30,0.0);
                        playNiceWithLegend(h[6],0.30,0.0);
                        playNiceWithLegend(h[5],0.30,0.0);
                        playNiceWithLegend(h[1],0.30,0.0);
			h[6]->SetMinimum(0.0);
			SameRange(h[1],h[3]);
			SameRange(h[5],h[6],h[1]);
			SameRange(h[1],h[3]);
			h[5]->Draw("e2p");
			h[6]->Draw("e2psame");
			h[3]->Draw("e2psame");
			//if(showTag) h[1]->Draw("e1psame");//tag
			TLegend* l1 = makeL1_v2(0.443467,0.720207,0.643216,0.919689);
			if(showTag) l1->AddEntry(h[1],"Higgs Mass Region");
			l1->AddEntry(h[5],"Lower Mass Sideband");
			l1->AddEntry(h[6],"Upper Mass Sideband");
			l1->AddEntry(box,"Data Driven Background");//h[3
			l1->Draw("same");
		        TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");
			tempCanv->Write();
			if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types

			tempCanvlog->cd();
			h[5]->SetMinimum(0.05);
                        tempCanvlog->SetLogy();
			h[5]->Draw("e2p");
			h[6]->Draw("e2psame");
			h[3]->Draw("e2psame");
			l1->Draw("same");
			TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");
			if(saveImages)SaveCanvas(tempCanvlog,plotsdir+tempCanvlog->GetName(),"ggif");//save as all types
			
		}//edn for each kinematic varriable
	}//end for each topology
	}//end if


//     ___  __          ___       __  _        ___  __     __    
//    / _ )/ /_____ _  / _ \___ _/ /_(_)__    / _ \/ /__  / /____
//   / _  /  '_/ _ `/ / , _/ _ `/ __/ / _ \  / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, / /_/|_|\_,_/\__/_/\___/ /_/  /_/\___/\__/___/
//            /___/                                              

		///Demostrate background--Ratio. Plot the ratio of the two side bands, and nothing else. 
	if(makeBkgRat){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
			/*Debug*/ if(printlevel >6) cout << "Data MHT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["MHT"][7]->GetBinContent(1)<<endl;
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ) continue;
			string canvName = string("BkgRat_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			/*Debug*/ if(printlevel >6)	printf("Scan2 Ratio bin1 for %s %s  = %f\n",s_EventTopology[iTop].c_str(),s_KinemVars[kKinVar].c_str(),h[7]->GetBinContent(1));
			tempCanv->cd();
			PrettyHist(h[7],kTeal);
			h[7]->GetYaxis()->SetRangeUser(0.,2.);
			if (s_KinemVars[kKinVar].compare("HT") == 0) {
				h[7]->GetXaxis()->SetLabelSize(0.04);}

			PrettyMarker(h[7],kTeal);
			h[7]->Draw("e1p");
			TAxis* xaxis = h[7]->GetXaxis();
			TLine *OneLine = new TLine(xaxis->GetXmin(),1.0,xaxis->GetXmax(),1.0);
			OneLine->SetLineColor(kBlack);
			OneLine->SetLineWidth(2);
			OneLine->SetLineStyle(7);//dashed.
			OneLine->Draw("same");
			h[7]->Draw("e1psame");
			TLegend* l1 = makeL1_v2(0.330402,0.836788,0.530151,0.919689);
			l1->AddEntry(h[7],"Lower/Upper Sideband Ratio");
			l1->Draw("same");
			TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");

			tempCanv->Write();
			if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
		}//edn for each kinematic varriable
	}//end for each topology
	}//end if makeBkgRat

		///END MAKE PLOTS
	/*Debug*/ if(printlevel > 0) cout << "Close Files" << endl;
	fplots->Close(); 
		//itterate over the map. close everything. 
	for( TFileMap::iterator i=PostAnaAnaFiles.begin(); i!=PostAnaAnaFiles.end(); ++i){
		(*i).second->Close();
	}
	for( TFileMap::iterator i=MainAnaFiles.begin(); i!=MainAnaFiles.end(); ++i){
		(*i).second->Close();
	}


}//end format plots
Ejemplo n.º 26
0
void DrawSignalProperties(TString OPTION)
{
  gROOT->ForceStyle();
  const int NCAT = 7;
  const int N = 5;
  const int MASS[N] = {115,120,125,130,135};
  int COLOR[N] = {kBlack,kGreen+1,kRed+1,kBlue,kMagenta};
  int STYLE[N] = {20,21,22,23,24};
 
  TFile *fSig  = TFile::Open("workspace/signal_shapes_workspace_"+OPTION+".root");
  RooWorkspace *wSig = (RooWorkspace*)fSig->Get("w");

  float x[N],yMean[N][NCAT],ySigma[N][NCAT],yWidth[N][NCAT],eMean[N][NCAT],eSigma[N][NCAT];  

  TH1F *hWidth[N],*hMean[N],*hSigma[N];
  TH2F *hFractionGF = new TH2F("FractionGF","FractionGF",NCAT,0,NCAT,N,0,N); 
  for(int icat=0;icat<NCAT;icat++) {
    hFractionGF->GetXaxis()->SetBinLabel(icat+1,TString::Format("CAT%d",icat)); 
  }
  for(int im=0;im<N;im++) {
    hFractionGF->GetYaxis()->SetBinLabel(im+1,TString::Format("%d",MASS[im])); 
  }

  //---------------------------------------------------------------------
  TCanvas *can = new TCanvas("SignalProperties","SignalProperties",900,600);
  can->Divide(2,2);
  TCanvas *can2 = new TCanvas("GFFraction","GFFraction",900,600);
  TLegend *leg = new TLegend(0.18,0.2,0.9,0.9);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.07);
  

  for(int im=0;im<N;im++) {
    hWidth[im]      = new TH1F(TString::Format("width_m%d",MASS[im]),TString::Format("width_m%d",MASS[im]),NCAT,0,NCAT);
    hMean[im]       = new TH1F(TString::Format("mean_m%d",MASS[im]),TString::Format("mean_m%d",MASS[im]),NCAT,0,NCAT);
    hSigma[im]      = new TH1F(TString::Format("sigma_m%d",MASS[im]),TString::Format("sigma_m%d",MASS[im]),NCAT,0,NCAT);
    hWidth[im]->SetLineColor(COLOR[im]);
    hWidth[im]->SetMarkerColor(COLOR[im]);
    hWidth[im]->SetMarkerStyle(STYLE[im]);
    hMean[im]->SetLineColor(COLOR[im]);
    hMean[im]->SetMarkerColor(COLOR[im]);
    hMean[im]->SetMarkerStyle(STYLE[im]);
    hSigma[im]->SetLineColor(COLOR[im]);
    hSigma[im]->SetMarkerColor(COLOR[im]);
    hSigma[im]->SetMarkerStyle(STYLE[im]);
    x[im] = MASS[im];
    for(int icat=0;icat<NCAT;icat++) {
      if (im == 0) {
        hWidth[im]->GetXaxis()->SetBinLabel(icat+1,TString::Format("CAT%d",icat)); 
        hMean[im]->GetXaxis()->SetBinLabel(icat+1,TString::Format("CAT%d",icat));
        hSigma[im]->GetXaxis()->SetBinLabel(icat+1,TString::Format("CAT%d",icat));
      }
      
      yMean[im][icat]  = (RooRealVar*)wSig->var(TString::Format("mean_m%d_CAT%d",MASS[im],icat))->getValV(); 
      eMean[im][icat]  = (RooRealVar*)wSig->var(TString::Format("mean_m%d_CAT%d",MASS[im],icat))->getError();
      ySigma[im][icat] = (RooRealVar*)wSig->var(TString::Format("sigma_m%d_CAT%d",MASS[im],icat))->getValV(); 
      eSigma[im][icat] = (RooRealVar*)wSig->var(TString::Format("sigma_m%d_CAT%d",MASS[im],icat))->getError();  
      yWidth[im][icat] = (RooRealVar*)wSig->var(TString::Format("fwhm_m%d_CAT%d",MASS[im],icat))->getValV()/yMean[im][icat]; 

      hWidth[im]->SetBinContent(icat+1,yWidth[im][icat]);
      hMean[im]->SetBinContent(icat+1,yMean[im][icat]/x[im]);
      hMean[im]->SetBinError(icat+1,eMean[im][icat]/x[im]);
      hSigma[im]->SetBinContent(icat+1,ySigma[im][icat]/yMean[im][icat]);
      hSigma[im]->SetBinError(icat+1,(ySigma[im][icat]/yMean[im][icat])*sqrt(pow(eMean[im][icat]/yMean[im][icat],2)+pow(eSigma[im][icat]/ySigma[im][icat],2)));

      float gf  = (RooRealVar*)wSig->var(TString::Format("yield_signalGF_mass%d_CAT%d",MASS[im],icat))->getValV();
      float vbf = (RooRealVar*)wSig->var(TString::Format("yield_signalVBF_mass%d_CAT%d",MASS[im],icat))->getValV();
      float f   = gf/(gf+vbf);
      hFractionGF->SetBinContent(icat+1,im+1,f);
    }
    leg->AddEntry(hWidth[im],TString::Format("M_{H} = %d GeV",MASS[im]),"P");
    
    if (im == 0) {
      hWidth[im]->GetYaxis()->SetRangeUser(0.1,0.3);
      hWidth[im]->GetYaxis()->SetTitle("FWHM / m");
      hMean[im]->GetYaxis()->SetRangeUser(0.9,1.1);
      hMean[im]->GetYaxis()->SetTitle("m / M_{H}");
      hSigma[im]->GetYaxis()->SetRangeUser(0.04,0.16);
      hSigma[im]->GetYaxis()->SetTitle("#sigma / m");
      can->cd(1);
      hWidth[im]->Draw("LP");
      can->cd(2);
      hMean[im]->Draw("LP");
      can->cd(3);
      hSigma[im]->Draw("LP");
    }
    else {
      can->cd(1);
      hWidth[im]->Draw("LPsame");
      can->cd(2); 
      hMean[im]->Draw("LPsame");
      can->cd(3); 
      hSigma[im]->Draw("LPsame");
    }
    
  }

  can->cd(4);
  leg->Draw();
  can2->cd();
  gStyle->SetPalette(42,0);
  gStyle->SetPaintTextFormat("1.2g");
  hFractionGF->SetMarkerSize(2.0);
  hFractionGF->GetYaxis()->SetTitle("Higgs mass (GeV)");
  hFractionGF->GetXaxis()->SetTitle("Category");
  hFractionGF->Draw("COL TEXT");

 	can->SaveAs(TString::Format("plots/properties/%s.png",can->GetName()));
 	can2->SaveAs(TString::Format("plots/properties/%s.png",can2->GetName()));
}
Ejemplo n.º 27
0
void comparePlots(std::string fname="elec10", int mom=10, bool save=false) {

  gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite);
  gStyle->SetPadColor(kWhite);    gStyle->SetFillColor(kWhite);
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(1100);       gStyle->SetOptFit(0);

  std::string tags[2]   = {"Old", "New"};
  int  color[2]         = {2,4};
  int  marker[2]        = {20,21};
  int  style[2]         = {1,2};
  int  rebin[16]        = {20,20,20,20, 2, 2, 2, 2, 2, 2,10,10,10,10,10,10};
  int  type[16]         = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  int  edgex[16]        = { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0};
  std::string name1[16] = {"Etot0",    "Etot1",    "EtotG0",   "EtotG1",
			 "r1by250",  "r1by251",  "r1by90",   "r1by91", 
			 "r9by250",  "r9by251",	 "sEtaEta0", "sEtaEta1",
			 "sEtaPhi0", "sEtaPhi1", "sPhiPhi0", "sPhiPhi1"};
  char name[100];
  TFile *file[2];
  for (int i=0; i<2; ++i) {
    sprintf (name, "%s%d%s.root", fname.c_str(), mom, tags[i].c_str());
    file[i] = new TFile(name);
  }
  for (int k=0; k<16; ++k) {
    TH1D* hist[2];
    sprintf (name, "%s", name1[k].c_str());
    for (int i=0; i<2; ++i) {
      hist[i] = (TH1D*)file[i]->FindObjectAny(name);
      if (hist[i] != 0) {
	if (rebin[k] > 1) hist[i]->Rebin(rebin[k]);
	hist[i]->GetXaxis()->SetLabelOffset(0.005);
	hist[i]->GetXaxis()->SetTitleOffset(1.40);
	hist[i]->GetYaxis()->SetLabelOffset(0.005);
	hist[i]->GetYaxis()->SetTitleOffset(1.40);
	hist[i]->SetMarkerStyle(marker[i]);
	hist[i]->SetMarkerColor(color[i]);
	hist[i]->SetLineColor(color[i]);
	hist[i]->SetLineStyle(style[i]);
	hist[i]->SetLineWidth(2);
      }
    }
    if (hist[0] != 0 && hist[1] != 0) {
      double xmin = (edgex[k] == 0) ? 0.65 : 0.11;
      TLegend *legend = new TLegend(xmin, 0.70, xmin+0.25, 0.79);
      legend->SetFillColor(kWhite);
      sprintf (name, "c_%sE%d", name1[k].c_str(),mom);
      TCanvas *pad = new TCanvas(name, name, 700, 500);
      pad->SetRightMargin(0.10);
      pad->SetTopMargin(0.10);
      if (type[k] != 0) pad->SetLogy();
      double ytop(0.90), dy(0.05);
      for (int i=0; i<2; ++i) {
	if (i == 0) hist[i]->Draw("hist");
	else        hist[i]->Draw("sameshist");
	pad->Update();
	sprintf (name, "%d GeV Electron (%s)", mom, tags[i].c_str());
	legend->AddEntry(hist[i],name,"lp");
	TPaveStats* st1 = (TPaveStats*)hist[i]->GetListOfFunctions()->FindObject("stats");
	if (st1 != NULL) {
	  st1->SetLineColor(color[i]); st1->SetTextColor(color[i]);
	  st1->SetY1NDC(ytop-dy); st1->SetY2NDC(ytop);
	  st1->SetX1NDC(xmin); st1->SetX2NDC(xmin+0.25);
	  ytop -= dy;
	}
	pad->Modified();
	pad->Update();
      }
      legend->Draw("same");
      pad->Update();
      if (save) {
	sprintf (name, "%s.pdf", pad->GetName());
	pad->Print(name);
      }
    }
  }
}