Exemple #1
0
void draw_eta(){
        TString filenameData = "Eta_effData.root";
        TString filenameMC = "Eta_effMC.root";
	TString fileMC = "../newDoubleMuonTree/tnpZ_theTreeCleanedMC.root";
	TString fileData = "/afs/cern.ch/user/q/quwang/work/Trigger/CMSSW_7_6_3_patch2/src/MuonAnalysis/TagAndProbe/test/zmumu/tnpZ_DatanoCCC.root";//"doubleMuonTrees/tnpZ_theTreeCleaned.root";
        //TString fileMC = "newDoubleMuonTree/TnPtreeMC.root";
        //TString fileData = "doubleMuonTrees/tnpZ_Data_25ns_run2015D_doubleMuon.root";
        Eff( fileData, filenameData, "data");
        Eff( fileMC, filenameMC, "MC");

	TFile * hDataEta = new TFile("Eta_effData.root");
	TH2F * histDE = (TH2F *)hDataEta->Get("heta_eff");
	TFile * hMCEta = new TFile("Eta_effMC.root"); 
	TH2F * histME = (TH2F *)hMCEta->Get("heta_eff");
	TH2F * histDM_eta = (TH2F *)histDE->Clone("histDM_eta");
	histDM_eta->Sumw2();
	histDM_eta->Divide(histDE, histME, 1, 1, "b");
	histDM_eta->SetTitle("dZ eff Data/MC");
	histDM_eta->GetXaxis()->SetTitle("muon1 eta");
	histDM_eta->GetYaxis()->SetTitle("muon2 eta");
	
	TCanvas * C3 = new TCanvas();
	C3->Draw();
	histDM_eta->Draw("colz:TEXTE");
	C3->SaveAs("dZ_eta_DM.pdf");	
	



}
computePRfast(){
    chain->Add("/afs/cern.ch/work/h/hbrun/public/TnP_CLtree_DYJets.root");
    
    
    TString trigeringElectrons = "((absSCeta<1.479&&CL_sigmaIetaIeta<0.01&&CL_deltaPhiIn<0.15&&CL_deltaEtaIn<0.007&&CL_HoE<0.12&&(CL_isoECAL-1)/pt<0.2)||(absSCeta>=1.479&&CL_sigmaIetaIeta<0.03&&CL_deltaPhiIn<0.1&&CL_deltaEtaIn<0.009&&CL_HoE<0.1&&(CL_isoECAL)/pt<0.2)&&CL_isoHCAL<0.2&&CL_isoTracker<0.2)";
    TString looseID = trigeringElectrons+"&&CL_relatPFiso03<1&&CL_dZ<0.1&&CL_MVA>-0.1";
    TString tightID = looseID+"&&CL_relatPFiso03<0.15&&CL_dZ<0.04&&CL_MVA>0.5&&CL_passConversionVeto==0&&CL_hnHits<1";
    
    
    
    float ptBins[6]={10,15,20,25,50,200};
    float etaBins[4] = {0,  1.4442, 1.556, 2.5};
    
    TH2F *passingLooseID = new TH2F("passingLooseID","",3, etaBins, 5, ptBins);
    chain->Draw("pt:absSCeta>>passingLooseID",looseID+"&&mass>80&&mass<100&&eventMatched==1");//matched with MC truth and in the Z peak (similar with TnP)
    
    TH2F *passingTightID = new TH2F("passingTightID","",3, etaBins, 5, ptBins);
    chain->Draw("pt:absSCeta>>passingTightID",tightID+"&&mass>80&&mass<100&&eventMatched==1");//matched with MC truth and in the Z peak (similar with TnP)
    

    TH2F *promptRate = (TH2F*) passingTightID->Clone("promptRate");
    promptRate->Sumw2();
    promptRate->Divide(passingTightID, passingLooseID,1,1);
    
    
    //save in the file
    myFile->cd();
    promptRate->Write("effMC_Prompt_Rate");
    myFile->Close();
    
    
}
Exemple #3
0
void shakeErrors(TString inFileName, TString histName){
  TFile inFile(inFileName);
  TH2F* h = (TH2F*)gROOT->FindObject(histName);
  if(!h){
    std::cout<<"Could not access histogram!"<<std::endl;
    return;
  }

  TFile lowFile(TString("low_")+inFileName,"recreate");
  TH2F* hLow = (TH2F*)h->Clone(histName);
  for(int i=0; i<h->GetSize(); i++){
    hLow->SetBinContent( i, h->GetBinContent(i)-h->GetBinError(i) );
  }
  hLow->Write();
  lowFile.Close();

  TFile hiFile(TString("hi_")+inFileName,"recreate");
  TH2F* hHi = (TH2F*)h->Clone(histName);
  for(int i=0; i<h->GetSize(); i++){
    hHi->SetBinContent( i, h->GetBinContent(i)+h->GetBinError(i) );
  }
  hHi->Write();
  hiFile.Close();
}
TH2F* FixAndSetBorders( const TH2& hist, const char* name=0, const char* title=0, Double_t val=0 ) {
    TH2F* hist0 = (TH2F*)hist.Clone(); // histogram we can modify

    MirrorBorders( *hist0 );    // mirror values of border bins into overflow bins

    TH2F* hist1 = AddBorders( *hist0, "hist1", "hist1" );   
    // add new border of bins around original histogram,
    // ... so 'overflow' bins become normal bins
    SetBorders( *hist1, val );                              
    // set overflow bins to value 1

    TH2F* histX = AddBorders( *hist1, "histX", "histX" );   
    // add new border of bins around original histogram,
    // ... so 'overflow' bins become normal bins

    TH2F* hist3 = (TH2F*)histX->Clone();
    hist3->SetName( name!=0 ? name : "hist3" );
    hist3->SetTitle( title!=0 ? title : "hist3" );

    delete hist0; delete hist1; delete histX;
    return hist3; // this can be used for filled contour histograms
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeElectronNtuple(const string InputFilename, const string datasetName, 
                             const string OutputFilename, Int_t sampleType, 
                             const string normalizationFile = "") {


  Double_t normalizationWeight = 0;
  Bool_t useReweightFactor = kFALSE;
  TH2F *PtEtaReweightFactor = 0;
  Double_t overallWJetsNormalizationFactor = 0;

  //For Normalizing each sample individually
  if (sampleType == 0 || sampleType >= 10) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str());
    assert(electronTree);    
    MitNtupleElectron ele(electronTree);
    
    normalizationWeight = getNormalizationWeight(InputFilename, datasetName);
    //*************************************************************************************************
    //Create new normalized tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    outputFile->cd();    
    TTree *normalizedTree = electronTree->CloneTree(0);
    
    for (int n=0;n<electronTree->GetEntries();n++) { 
      ele.GetEntry(n);

      if (sampleType == 10) {
        if (ele.electron_branch_passedSelectionCut == 1) {
          if (datasetName == "s09-wwll10-mc3" || datasetName == "s09-ttbar-mc3") {
            //for mu-e there should be only 1 electron candidate
            ele.electron_branch_weight = normalizationWeight; 
            normalizedTree->Fill(); 
          } else if (datasetName == "s09-we-mc3" || datasetName == "s09-wm-mc3" || datasetName == "s09-wt-mc3") {
            //For the W->enu sample, fill only the fake electron candidates.
            ele.electron_branch_weight = normalizationWeight; 
            if (ele.electron_branch_electronType < 100) {
              normalizedTree->Fill(); 
            }
          } else {
            cout << "Warning: The specified dataset " << datasetName 
                 << " is not recognized to be one of the selection cut samples.\n";
          }
        }        
      } else {
        //For regular samples just fill all electrons
        ele.electron_branch_weight = normalizationWeight; 
        normalizedTree->Fill(); 
      }      
    }
    normalizedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << normalizedTree->GetEntries() << endl;
    outputFile->Close();     
  }
  //For Normalization of Background sample
  else if (sampleType == 1) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in W+Jets/W+gamma bkg
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);

      TH2F *WJetsFakeElectronPtEta = (TH2F*)reweightInputFile->Get("hWJetsFakeElectronPtEta");
      assert(WJetsFakeElectronPtEta);      
      WJetsFakeElectronPtEta = (TH2F*)(WJetsFakeElectronPtEta->Clone());
      WJetsFakeElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WJetsFakeElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *BkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , WJetsFakeElectronPtEta->GetXaxis()->GetNbins(), WJetsFakeElectronPtEta->GetXaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetXaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetXaxis()->GetNbins()), WJetsFakeElectronPtEta->GetYaxis()->GetNbins(), WJetsFakeElectronPtEta->GetYaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetYaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetYaxis()->GetNbins()));
      BkgFakeElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        BkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WJetsFakeElectronPtEta, BkgFakeElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Background Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedBkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedBkgFakeElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 

      ReweightedBkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedBkgFakeElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronPt.gif");
    ReweightedBkgFakeElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronEta.gif");
  } 
  
  //For Normalization of Signal sample
  else if (sampleType == 2) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in WW -> ee nunu signal
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);
      TH2F *WWSigElectronPtEta = (TH2F*)reweightInputFile->Get("hWWRealElectronPtEta");
      assert(WWSigElectronPtEta);      
      WWSigElectronPtEta = (TH2F*)(WWSigElectronPtEta->Clone());
      WWSigElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WWSigElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *SigSampleElectronPtEta = new TH2F("SigSampleElectronPtEta", ";Pt [GeV/c];#eta;" , WWSigElectronPtEta->GetXaxis()->GetNbins(), WWSigElectronPtEta->GetXaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetXaxis()->GetBinUpEdge(WWSigElectronPtEta->GetXaxis()->GetNbins()), WWSigElectronPtEta->GetYaxis()->GetNbins(), WWSigElectronPtEta->GetYaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetYaxis()->GetBinUpEdge(WWSigElectronPtEta->GetYaxis()->GetNbins()));
      SigSampleElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        SigSampleElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WWSigElectronPtEta, SigSampleElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Signal Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedSigRealElectronPtEta = new TH2F("ReweightedSigRealElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedSigRealElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 
      ReweightedSigRealElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedSigRealElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronPt.gif");
    ReweightedSigRealElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronEta.gif");
  } 
  else {
    cout << "Warning: Specified sampleType " << sampleType << " is not recognized.\n";
  }



}
void make_SMS_exclusion(TH2F *rawlimits,TH2F *xsec,int scantype,std::string& scanx, bool isobserved) {
  TH2F *limits = prep_histo(rawlimits,scantype); // this is to be independent of the style used at creation time
  //here we get some limits and the cross section; we want to make an exclusion plot!
  TH2F *rellimits = (TH2F*)limits->Clone("rellimits");
  TH2F *rellimitsd3 = (TH2F*)limits->Clone("rellimitsd3"); // one third the cross section ("divided by 3" -> d3)
  TH2F *rellimitst3 = (TH2F*)limits->Clone("rellimitst3"); // three times the cross section ("times 3" -> t3)
  
  if(!xsec ) {
    cout << "Watch out, cross section map is invalid!" << endl;
    delete limits;
    return;
  }
  
  rellimits->Divide(xsec);
  
  
  for(int i=1;i<=rellimits->GetNbinsX();i++) {
    for(int j=1;j<=rellimits->GetNbinsY();j++) {
      rellimitst3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))/3.0);
      rellimitsd3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))*3.0);
    }
  }
  

//  TH2F *exclusionshape = make_exclusion_shape(rellimits,1);
//  TH2F *exclusionshapet3 = make_exclusion_shape(rellimitst3,2);
//  TH2F *exclusionshaped3 = make_exclusion_shape(rellimitsd3,3);
  
  //Now let's produce the plots!
  
  set_range(xsec,scantype,false);
  set_range(limits,scantype,false);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  
  bool drawdoubleline=false; //draw nice thin line on top of thick outer line
  TGraph *exclline = MarcosExclusionLine(rellimits, scantype);
  TGraph *thinexcline = thin_line(exclline);
  
  TGraph *excllinet3 = MarcosExclusionLine(rellimitst3, scantype);
  excllinet3->SetLineStyle(2);
  TGraph *thinexclinet3 = thin_line(excllinet3);

  TGraph *excllined3 = MarcosExclusionLine(rellimitsd3, scantype);
  excllined3->SetLineStyle(3);
  TGraph *thinexclined3 = thin_line(excllined3);

//  produce_extensive_plots(xsec,limits,rellimits, rellimitst3, rellimitsd3,scantype);
  
  TCanvas *finalcanvas = new TCanvas("finalcanvas","finalcanvas");
  finalcanvas->SetLogz(1);
  finalcanvas->cd();
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");
  limits->Draw("COLZ");

  TLine *desertline;
  if(drawefficiencydesertline) {
	desertline = new TLine(375,50,1200,875);
	desertline->SetLineWidth(3);
	//desertline->SetLineWidth(4); // paper style
	desertline->SetLineColor(kBlack);
	desertline->Draw("same");
  }


//  fill_with_text(exclline,excllined3,excllinet3,finalcanvas,scantype,scanx);
  stringstream real;
  real << "Limits/";
  if(!isobserved) real << "expected/expected_";
  real << "final_exclusion__" << limits->GetName();
  
  if(Contains(limits->GetName(),"bestlimits")) {
    cout << "----------> " << limits->GetName() << endl;
    TFile *f = new TFile("limits.root","RECREATE");
    thinexcline->SetName("ExclusionLine");
    limits->SetName("UpperLimits");
    limits->Write();
    thinexcline->Write();
    f->Close();
  }
  
  
  exclline->Draw("l");
  if(drawdoubleline) thinexcline->Draw("");
  excllinet3->Draw("");
  if(drawdoubleline) thinexclinet3->Draw("");
  excllined3->Draw("");
  if(drawdoubleline) thinexclined3->Draw("");
  
  CompleteSave(finalcanvas,real.str());

  
  
  //-------------------------------------- extensive plots 
  
  TCanvas *ca = new TCanvas("ca","ca",2400,1200);
  ca->Divide(4,2);
  ca->cd(1);
  ca->cd(1)->SetLogz(1);
  xsec->GetZaxis()->SetRangeUser(0.001,1000);
  xsec->Draw("COLZ");
  TText *title0 = write_title("Reference Cross Section");
  title0->Draw("same");
  ca->cd(2);
  ca->cd(2)->SetLogz(1);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->Draw("COLZ");
  TText *title = write_title("Cross Section Upper Limit");
  title->Draw("same");
  ca->cd(3);
  ca->cd(3)->SetLogz(1);
  TH2F *limit_ref = (TH2F*)limits->Clone("limit_ref");
  limit_ref->Divide(xsec);
  limit_ref->GetZaxis()->SetRangeUser(limits_ratio_lower_bound,limits_ratio_upper_bound);
  limit_ref->Draw("COLZ");
  TText *title2 = write_title("Cross Section UL / XS");
  title2->Draw("same");
  ca->cd(4);
  ca->cd(4)->SetLogz(1);
  limits->SetTitle("");
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");

  limits->Draw("COLZ");


  ca->cd(4);
  exclline->Draw();
  thinexcline->Draw();
  excllinet3->Draw();
  thinexclinet3->Draw();
  excllined3->Draw();
  thinexclined3->Draw();
  stringstream partial;
  partial << "Limits/";
  if(!isobserved) real << "expected/expected_";
  partial << "exclusion__" << limits->GetName();
  fill_with_text(exclline,excllined3,excllinet3,ca->cd(4),scantype);
//  CompleteSave(ca,partial.str());

  ca->cd(5);
  (hardlimit(rellimitsd3))->Draw("COL");
  TText *c = write_title("Exclusion shape for #sigma_{ref}/3");
  c->Draw();
  excllined3->Draw("same");
  
  ca->cd(6);
  (hardlimit(rellimits))->Draw("COL");
  exclline->Draw("same");
  TText *b = write_title("Exclusion shape for #sigma_{ref}");
  b->Draw();
  
  ca->cd(7);
  (hardlimit(rellimitst3))->Draw("COL");
  excllinet3->Draw("same");
  TText *a = write_title("Exclusion shape for 3x#sigma_{ref}");
  a->Draw();
  
  CompleteSave(ca,partial.str()+"__PlusInfo");
  delete ca;
  delete limits;
  
  //---------------------------------------</extensive plots>
  delete finalcanvas;
}
void combineBins(int mass, double scale_factor = 1.0){ //mass = mass of tprime quark

  //define some parameters
  //char fname[100]={"data/mujets_821/tprime_mujets_2D_821ipb.root"}; //input file name
  char fname[100]={"data/ejets_3560/tprime_ejets_2D_3560ipb.root"}; //input file name
  char oname[256]; //output file name
  char sname[100]; //name of signal histogram
  //sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_15jul2011test.root",mass);
  sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_test.root",mass);
  sprintf(sname,"TPrime%i_HtvsMfit",mass);
  char bname[20][100]={ //array of data and background histograms
    "Data_HtvsMfit", //data histogram must be first in this list
    "TTjets_HtvsMfit",
    "Ewk_HtvsMfit",
    "TPrime%i_HtvsMfit_JESup",
    "TPrime%i_HtvsMfit_JESdown",
    "TTjets_HtvsMfit_JESup",
    "TTjets_HtvsMfit_JESdown",
    "Ewk_HtvsMfit_JESup",
    "Ewk_HtvsMfit_JESdown"
  };
  
  int nb=9; //number of histograms in list
  int n_skip=3; // starting with this index, do not consider for background normalization
  float femax=0.20; //max fractional error in each bin of background histogram

  TFile *f = TFile::Open(fname);
  if (f==NULL) {
    printf("Cannot open file '%s'\n",fname);
    return;
  }

  TH2F* hs; f->GetObject(sname,hs); 
  // Gena: scale signal template to proper cross section
  hs->Scale(scale_factor);
  if (hs==NULL) {
    printf("Cannot find histogram '%s' in '%s'\n",sname,fname);
    return;
  }

  //figure out the binning
  int nx = hs->GetNbinsX()+2;
  int ny = hs->GetNbinsY()+2;

  // cross check printout
  std::cout << "2D hist name: " << hs->GetName() << std::endl;
  std::cout << "Integral with overflow: " << hs->Integral(0,nx-1,0,ny-1) << std::endl;
  std::cout << "Integral no overflow: " << hs->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;

  TH2F *hb = (TH2F*)hs->Clone(); 
  hb->SetName("hb");
  hb->Reset();
  TH2F *hX[20];
  for (int i=0;i<nb;i++){
    std::string sBName(bname[i]);
    // GENA: get names for signal JES histos
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){

      sprintf(bname[i],sBName.c_str(),mass);
      std::cout << bname[i] << std::endl;
    }

    f->GetObject(bname[i],hX[i]); 

    // GENA: scale JES signal templates to proper cross section
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){
      hX[i]->Scale(scale_factor);      
    }
    if (hX[i]==NULL) {
      printf("Cannot find histogram '%s' in '%s'\n",bname[i],fname);
      return;
    }
    //hX[i]->Print("base");
    std::cout << "2D hist name: " << hX[i]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << hX[i]->Integral(0,nx-1,0,ny-1) << std::endl;
    std::cout << "Integral no overflow: " << hX[i]->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;
    //sum all background histograms into hb; do not add the data histogram
    if (i>0 && i<n_skip) hb->Add(hX[i]); 
  }

  //figure out the binning
  //int nx = hs->GetNbinsX()+2;
  //int ny = hs->GetNbinsY()+2;
  int nbin=nx*ny;
  std::cout << "number of bins: x="<<nx<<", y="<<ny<<std::endl;
  
  //book some 1d histograms with the same number of bins for diagnostics
  TH1F *h1sb = new TH1F("h1sb","h1sb",nbin,0,nbin);
  TH1F *h1s = new TH1F("h1s","h1s",nbin,0,nbin);
  TH1F *h1b = new TH1F("h1b","h1b",nbin,0,nbin);
  // GENA: vector to create 2D->1D bin map
  std::vector<std::vector<int> > vMap(nbin);

  float xs,xb;
  //xsb holds the s/b values for each bin
  //xx are the histogram contents 
  //(0=signal, 1=total background, 2=data, 3...nb-1=individual backgrounds) GENA: nb+1 ?
  float xsb[30000],xx[30000][20],xe[30000][20];
  int ibin; 
  double _sum = 0.0;
  for (int i=0;i<nx;i++){
    for (int j=0;j<ny;j++){

      ibin=hs->GetBin(i,j);

      // GENA: Will fill each bin with its original index
      vMap[ibin].push_back(ibin);

      xs=hs->GetBinContent(ibin);
      xb=hb->GetBinContent(ibin);
      //compute signal/background
      if (xb>0) {
	xsb[ibin]=xs/xb;
      }else{
	if (xs>0){
	  xsb[ibin]=999;
	}else{
	  xsb[ibin]=0;
	}
      }
      xx[ibin][0]=xs;
      xe[ibin][0]=hs->GetBinError(ibin);
      xx[ibin][1]=xb;
      xe[ibin][1]=hb->GetBinError(ibin);
      for (int k=0;k<nb;k++){
	xx[ibin][k+2]=hX[k]->GetBinContent(ibin);
	xe[ibin][k+2]=hX[k]->GetBinError(ibin);
      }
      if (xb>0) h1sb->SetBinContent(ibin,xs/xb);
      h1s->SetBinContent(ibin,xx[ibin][0]);
      h1s->SetBinError(ibin,xe[ibin][0]);
      h1b->SetBinContent(ibin,xx[ibin][1]);
      h1b->SetBinError(ibin,xe[ibin][1]);
      
      _sum += xx[ibin][0];
    }
  }

  std::cout << "SUM: " << _sum << std::endl;

  //sort all histogram bins in decreasing s/b
  int nswap=1;
  float xtmp;

  // GENA: for bin map
  int ibin_tmp;

  while (nswap>0) {
    nswap=0;
    for (int i=0;i<nbin-1;i++) {
      if (xsb[i]<xsb[i+1]){
	xtmp=xsb[i];
	xsb[i]=xsb[i+1];
	xsb[i+1]=xtmp;

	// GENA: for bin map
	ibin_tmp = vMap[i][0];
	vMap[i][0] = vMap[i+1][0];
	vMap[i+1][0] = ibin_tmp;

	for (int j=0;j<nb+2;j++){
	  xtmp=xx[i][j];
	  xx[i][j]=xx[i+1][j];
	  xx[i+1][j]=xtmp;

	  xtmp=xe[i][j];
	  xe[i][j]=xe[i+1][j];
	  xe[i+1][j]=xtmp;
	}
	nswap=nswap+1;
      }
    }
  }

  //these histograms have the bins ordered in decrerasing s/b for diagnostics
  TH1F *h1sb1 = new TH1F("h1sb1","h1sb1",nbin,0,nbin);
  TH1F *h1fe1 = new TH1F("h1fe1","h1fe1",nbin,0,nbin);
  TH1F *h1s1 = new TH1F("h1s1","h1s1",nbin,0,nbin);
  TH1F *h1b1 = new TH1F("h1b1","h1b1",nbin,0,nbin);
  for (int i=0;i<nbin;i++){
    h1sb1->SetBinContent(i+1,xsb[i]);
    if (xx[i][1]>0) h1fe1->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s1->SetBinContent(i+1,xx[i][0]);
    h1s1->SetBinError(i+1,xe[i][0]);
    h1b1->SetBinContent(i+1,xx[i][1]);
    h1b1->SetBinError(i+1,xe[i][1]);
  }


  //combine bins starting with the highest s/b until the fractional error in
  //the total backround in every bin is smaller than femax
  int ncomb=1;
  //float xtmp;
  float fe=0;
  while (ncomb>0) {
    ncomb=0;
    for (int i=0;i<nbin-1;i++){

      if (xx[i][1]>0){
	fe=xe[i][1]/xx[i][1]; //fractional error in background
      }else{
	fe=1;
      }
      if (fe>femax){

	// GENA: write down bin
	for (std::vector<int>::const_iterator vi=vMap[i+1].begin();
	     vi != vMap[i+1].end(); ++vi){
	  vMap[i].push_back(*vi);
	}
	//move all successive bins up
	vMap.erase(vMap.begin()+i+1);

	for (int k=0;k<nb+2;k++){ //add the next bin
	  xx[i][k]=xx[i][k]+xx[i+1][k];
	  xe[i][k]=sqrt(xe[i][k]*xe[i][k]+xe[i+1][k]*xe[i+1][k]);
	  for (int j=i+1;j<nbin-1;j++){ //move all successive bins up
	    xx[j][k]=xx[j+1][k];
	    xe[j][k]=xe[j+1][k];
	  }
	}
	ncomb++;
	nbin=nbin-1; //decrease the total number of bins

      }
    }
  }


  //GENA: open the map file
  std::ofstream mapFile;
  mapFile.open("bin.map");
  int bin_count = 0;
  for (std::vector<std::vector<int> >::const_iterator i=vMap.begin();
       i != vMap.end(); ++i){

    mapFile << " " << i-vMap.begin()+1 << ":";

    for(std::vector<int>::const_iterator j=i->begin();
	j != i->end(); ++j){
      mapFile << " " << *j;
      ++bin_count;
    }

    mapFile << std::endl;

  }
  //GENA: close the map file
  mapFile.close();

  //these are the output histograms
  TFile *f2 = TFile::Open(oname,"recreate");
  TH1F *h1feb2 = new TH1F("h1fe2","h1fe2",nbin,0,nbin);
  TH1F *h1s2 = new TH1F(sname,sname,nbin,0,nbin);
  TH1F *h1b2 = new TH1F("h1b2","h1b2",nbin,0,nbin);
  TH1F *h1X2[20];
  for (int i=0;i<nb;i++){
    h1X2[i] = new TH1F(bname[i],bname[i],nbin,0,nbin);
  }
  for (int i=0;i<nbin;i++){
    h1feb2->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s2->SetBinContent(i+1,xx[i][0]);
    h1s2->SetBinError(i+1,xe[i][0]);
    h1b2->SetBinContent(i+1,xx[i][1]);
    h1b2->SetBinError(i+1,xe[i][1]);
    for (int j=0;j<nb;j++){
      h1X2[j]->SetBinContent(i+1,xx[i][j+2]);
      h1X2[j]->SetBinError(i+1,xe[i][j+2]);
    }
  }
  
  std::cout << "Merged 1D hist name: " << h1s2->GetName() << std::endl;
  std::cout << "Integral with overflow: " << h1s2->Integral(0,nbin+1) << std::endl;
  std::cout << "Integral no overflow: " << h1s2->Integral(1,nbin) << std::endl << std::endl;
  h1s2->Write();
  for (int j=0;j<nb;j++){
    std::cout << "Merged 1D hist name: " << h1X2[j]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << h1X2[j]->Integral(0,nbin+1) << std::endl;
    std::cout << "Integral no overflow: " << h1X2[j]->Integral(1,nbin) << std::endl << std::endl;
    h1X2[j]->Write();
  }
  
  h1s2->Print("base");

  f2->Close();
  f->Close();

  std::cout << "map size: " << vMap.size() << " combined bins" << std::endl;
  std::cout << "total bins merged: " << bin_count << std::endl;
}
void twoDlinearcombination(TH2F* first, int firsttype, TH2F* second, int secondtype, TH2F* input, int inputtype, TH2F* finaloutput, int outputtype, TH2F* finaloutput2, int output2type){
	TH2F* output = (TH2F*) input->Clone();
	TH2F* output2 = (TH2F*) output->Clone();
	if(outputtype==kIntHist || outputtype==kSigHist){
		if(inputtype==kBSI25Hist && firsttype==kSigHist && secondtype==kBkgHist){
			output->Add(first, -25.0);
			output->Add(second, -1.0);
			output->Scale(0.2);
			if (outputtype == kSigHist){ delete output; output = (TH2F*) first->Clone(); }

			output2->Add(first, -25.0);
			output2->Add(second, -1.0);
			output2->Scale(0.2);
			if (output2type == kSigHist){ delete output2; output2 = (TH2F*) first->Clone(); }
		}
		if(inputtype==kBSI25Hist && firsttype==kBSIHist && secondtype==kBkgHist){
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi25 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi25,25,bsi,1,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi25, 25, bsi, 1, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}		
		if(inputtype==kBSI25Hist && firsttype==kBSI10Hist && secondtype==kBkgHist){
			//double scaleval = 1./(-50. + 25.*sqrt(10.));
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi10 = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi25 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi25,25,bsi10,10,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi25, 25, bsi10, 10, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}
		if(inputtype==kBSI10Hist && firsttype==kBSIHist && secondtype==kBkgHist){
			//double scaleval = 1./(10 - sqrt(10));
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi10 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi10,10,bsi,1,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi10, 10, bsi, 1, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}
		for (int binx = 1; binx <= output->GetNbinsX(); binx++){
			for (int biny = 1; biny <= output->GetNbinsY(); biny++){
				finaloutput->SetBinContent(binx, biny, output->GetBinContent(binx, biny));
				if (finaloutput2 != 0) finaloutput2->SetBinContent(binx,biny,output2->GetBinContent(binx,biny));
			}
		}
	}
	else{cout<<"Option not yet supported. Exiting..."<<endl; assert(0);};
	delete output;
	delete output2;
}
Exemple #9
0
void ana_Run11_eff()
{

  const int rebin = 1;

  TFile *f = TFile::Open("Rootfiles/Run11_eff.root","read");

  // Run with weigth
  TH2F *hMcPtVsEta = (TH2F*)f->Get("mcJpsiPtY");
  TH2F *hRcPtVsEta = (TH2F*)f->Get("hHt2JpsiPE");

  draw2D(hMcPtVsEta);
  draw2D(hRcPtVsEta);

  hMcPtVsEta->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hMcPt = (TH1F*)hMcPtVsEta->ProjectionY("hMcPt");
  hMcPt->Rebin(rebin);
  hMcPt->SetMarkerStyle(20);
  draw1D(hMcPt,"",kTRUE);

  hRcPtVsEta->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hRcPt = (TH1F*)hRcPtVsEta->ProjectionY("hRcPt");
  hRcPt->Rebin(rebin);
  hRcPt->SetMarkerStyle(21);
  hRcPt->SetMarkerColor(2);
  hRcPt->SetLineColor(2);
  hRcPt->Draw("sames P");

  TH1F *hRatio = (TH1F*)hRcPt->Clone("hRatio_fromRunning");
  hRatio->Rebin(100);
  hMcPt->Rebin(100);
  hRatio->Divide(hMcPt);
  cEff = draw1D(hRatio,"");

  // Run without weight
  TH2F *hMcPtVsEtaNoWeight = (TH2F*)f->Get("mcJpsiPtY_Or");
  draw2D(hMcPtVsEtaNoWeight);  

  TH2F *hMcPtVsRcNoWeight = (TH2F*)f->Get("hJpsiRcvsMC_Cut1");
  hMcPtVsRcNoWeight->RebinX(rebin);
  hMcPtVsRcNoWeight->RebinY(rebin);
  draw2D(hMcPtVsRcNoWeight);

  hMcPtVsEtaNoWeight->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hMcPtNoWeight = (TH1F*)hMcPtVsEtaNoWeight->ProjectionY("hMcPtNoWeight");
  hMcPtNoWeight->Rebin(rebin);
  hMcPtNoWeight->SetMarkerStyle(20);
  hMcPtNoWeight->SetMinimum(1);
  draw1D(hMcPtNoWeight,"",kTRUE);

  TH1F *hRcPtNoWeight = (TH1F*)hMcPtVsRcNoWeight->ProjectionX("hRcPtNoWeight");
  hRcPtNoWeight->SetMarkerStyle(21);
  hRcPtNoWeight->SetMarkerColor(2);
  hRcPtNoWeight->SetLineColor(2);
  hRcPtNoWeight->Draw("sames P");

  TH1F *hRatioNoWeight = (TH1F*)hRcPtNoWeight->Clone("hRatioNoWeight");
  hRatioNoWeight->Divide(hMcPtNoWeight);
  cEff->cd();
  hRatioNoWeight->SetMarkerColor(4);
  hRatioNoWeight->Draw("samesP");

  // weight with input histogram
  TH1F *hMcPtWeight = (TH1F*)hMcPtNoWeight->Clone("hMcPtWeight");
  TH2F *hMcPtVsRcWeight = (TH2F*)hMcPtVsRcNoWeight->Clone("hMcPtVsRcWeight");
  for(int ibin=1; ibin<=hMcPtVsRcNoWeight->GetNbinsX(); ibin++)
    {
      double scale = hMcPt->GetBinContent(ibin);
      hMcPtWeight->SetBinContent(ibin,hMcPtWeight->GetBinContent(ibin)*scale);
      hMcPtWeight->SetBinError(ibin,hMcPtWeight->GetBinError(ibin)*scale);
      for(int jbin=1; jbin<=hMcPtVsRcNoWeight->GetNbinsY(); jbin++)
	{
	  hMcPtVsRcWeight->SetBinContent(ibin,jbin,hMcPtVsRcWeight->GetBinContent(ibin,jbin)*scale);
	  hMcPtVsRcWeight->SetBinError(ibin,jbin,hMcPtVsRcWeight->GetBinError(ibin,jbin)*scale);
	}
    }
  TH1F *hRcPtWeight = (TH1F*)hMcPtVsRcWeight->ProjectionY("hRcPtWeight");
  hRcPtWeight->SetMarkerStyle(21);
  hRcPtWeight->SetMarkerColor(2);
  hRcPtWeight->SetLineColor(2);

  draw2D(hMcPtVsRcWeight);
  draw1D(hMcPtWeight,"",kTRUE);
  hRcPtWeight->Draw("sames P");
  
  TH1F *hRatioWeight = (TH1F*)hRcPtWeight->Clone("hRatioWeight");
  hRatioWeight->Divide(hMcPtWeight);
  cEff->cd();
  hRatioWeight->SetMarkerColor(6);
  hRatioWeight->Draw("samesP");

  TH1F *hCheck = (TH1F*)hRatioWeight->Clone("check");
  hCheck->Divide(hRatio);
  draw1D(hCheck);

  // weight with fitted function
  TCanvas *c = new TCanvas("Fit","Fit",800,600);
  SetPadMargin(gPad,0.15,0.15);
  gPad->SetLogy();
  TH1F *h = new TH1F("histogram",";;;",7,0,30);
  h->GetYaxis()->SetRangeUser(1e-7,100);
  h->Draw();

  TFile *fdata = TFile::Open("Rootfiles/Spectrum_in_bin.root","read");
  TGraphErrors	*gr = (TGraphErrors*)fdata->Get("gall");
  gr->SetMarkerColor(1);
  gr->SetLineColor(1);
  gr->GetXaxis()->SetRangeUser(0,30);
  gr->Draw("sames PE");
  TF1 *func = new TF1("func",InvPt,0,30,4);
  func->SetParameters(0.4,-0.4796,4.229,-7.54);
  gr->Fit(func,"RL");

  TH1F *hMcPtFunc = (TH1F*)hMcPtNoWeight->Clone("hMcPtFunc");
  TH2F *hMcPtVsRcFunc = (TH2F*)hMcPtVsRcNoWeight->Clone("hMcPtVsRcFunc");
  for(int ibin=1; ibin<=hMcPtVsRcFunc->GetNbinsX(); ibin++)
    {
      double scale = func->Eval(hMcPtFunc->GetBinCenter(ibin));
      hMcPtFunc->SetBinContent(ibin,hMcPtFunc->GetBinContent(ibin)*scale);
      hMcPtFunc->SetBinError(ibin,hMcPtFunc->GetBinError(ibin)*scale);
      for(int jbin=1; jbin<=hMcPtVsRcNoWeight->GetNbinsY(); jbin++)
	{
	  hMcPtVsRcFunc->SetBinContent(ibin,jbin,hMcPtVsRcFunc->GetBinContent(ibin,jbin)*scale);
	  hMcPtVsRcFunc->SetBinError(ibin,jbin,hMcPtVsRcFunc->GetBinError(ibin,jbin)*scale);
	}
    }
  TH1F *hRcPtFunc = (TH1F*)hMcPtVsRcFunc->ProjectionY("hRcPtFunc");
  hRcPtFunc->SetMarkerStyle(21);
  hRcPtFunc->SetMarkerColor(2);
  hRcPtFunc->SetLineColor(2);
  hMcPtVsRcFunc->GetZaxis()->SetRangeUser(1e-4,1e2);
  draw2D(hMcPtVsRcFunc);
  hMcPtFunc->GetYaxis()->SetRangeUser(1e-4,5e4);
  draw1D(hMcPtFunc,"",kTRUE);
  hRcPtFunc->Draw("sames P");

  TH1F *hRatioFunc = (TH1F*)hRcPtFunc->Clone("hRatioFunc");
  hRatioFunc->Rebin(100);
  hMcPtFunc->Rebin(100);
  hRatioFunc->Divide(hMcPtFunc);
  cEff->cd();
  hRatioFunc->SetMarkerColor(5);
  hRatioFunc->Draw("samesP");
  
  TH1F *hCheck2 = (TH1F*)hRatioFunc->Clone("check2");
  hCheck2->Divide(hRatio);
  draw1D(hCheck2);

}
void
CalcFakeRate(string infile, bool useData=true, bool doSystematics=false){  
  cout<<" UseData="<<useData<<" dosystematics="<<doSystematics<<endl;

  TFile *f = TFile::Open(infile.c_str(), "read"); assert(f);
  TH2F* hFakeRateNum = NULL;
  TH2F* hFakeRateAll = NULL;
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1);
  gStyle->SetTextFont(132);
  gStyle->SetTextSize(1.2);
  //gROOT->ForceStyle();

  bool useElectrons = infile.find("Muon") == string::npos;
  bool doWLep = infile.find("-TT") == string::npos;

  vector<string> allsamples;
  if(!useData){
    allsamples.push_back("WJetsToLNu");
    if(!doSystematics){
    allsamples.push_back("TTJets");
    allsamples.push_back("ZZ");
    allsamples.push_back("GVJets");
    allsamples.push_back("WWTo2L2Nu");
    allsamples.push_back("WZJetsTo3LNu");
    allsamples.push_back("DYJetsToLL");
    }
  }else{
    allsamples.push_back("data");
  }
  
  float offset = 0.01;
  float eta[] = {0., 1.5, 2.5}; int neta = 3;
  if(!useElectrons){
    eta[1] = 2.4;
    neta = 2;//eta[2] = 2.4;
  }

  //float pt [] = {0., 20., 40., 1000}; const int npt  = 4;
  //float pt [] = {0., 10., 20., 30., 1000}; const int npt  = 5;

  //float pt [] = {0., 10., 15., 25., 1000}; const int npt  = 5;
  //float pt [] = {0., 10., 15., 20., 30., 1000}; const int npt  = 6;
  float pt [] = {10., 15., 20., 30., 40., 100}; const int npt  = 6;

  //float pt [] = {0., 20., 25., 30., 50., 1000}; const int npt  = 6;
  hFakeRateNum = new TH2F("hFakeRateNum", "hFakeRateNum;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta);
  hFakeRateAll = new TH2F("hFakeRateAll", "hFakeRateAll;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta);
  string title = useElectrons ? "Electron Fake Rate" : "Muon Fake Rate";
  title += useData ? " from Data" : " from MC";
  title += !useData && doSystematics ? " Systematics" : "";
  title += " using W+Jets method";
  title += doWLep ? " on W lepton" : " on Z lepton";
  hFakeRateNum->SetTitle(title.c_str());

/////////This is for eta, pt agnotistic Fake Rate Calc
  float in_tot(0), out_tot(0);
  for(unsigned i=0; i<allsamples.size(); ++i){
    string hist_name = allsamples[i] + "/hNumEvts";
    TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist);
    int lastbin = hist->GetNbinsX();
    float in(0), out(0);

    in  = hist->GetBinContent(lastbin);
    out = hist->GetBinContent(lastbin-1);

    in_tot += in;
    out_tot += out;

    //cout<<"Sample: "<<allsamples[i]<<" = "<<in/out<<" = pass/total = "<<in<<"/"<<out<<endl;
    printf("  Sample: %s = %.2f%% : pass/total = %.2f / %.2f \n",allsamples[i].c_str(), in/out*100, in, out);
  }
  float  eff = in_tot/out_tot;
  float deff = TMath::Sqrt(eff * (1-eff)/out_tot);
  //cout<<"Total: "<<eff*100<<"% +/- "<<deff*100<<"% = in_tot/out_tot*100% = "<<in_tot<<"/"<<out_tot<<"*100%\n";
  printf("Total: %.2f%% +/- %.2f%% = in_tot/out_tot*100%% = %.2f/%.2f\n", eff*100, deff*100, in_tot, out_tot);


/////////This is for 2D Fake Rate Calc
  for(unsigned i=0; i<allsamples.size(); ++i){
    string hist_name = allsamples[i] + "/hNumEvts";
    TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist);
    int lastbin = hist->GetNbinsX();
    float in(0), out(0);
    string binNameNum   = hist->GetXaxis()->GetBinLabel(lastbin);
    string binNameDenom = hist->GetXaxis()->GetBinLabel(lastbin-1);
      
    string hist_nameNum = allsamples[i] + "/hEtaVsPt_" + binNameNum;
    TH2F* histNum = (TH2F*) f->Get(hist_nameNum.c_str()); assert(histNum);
      
    string hist_nameDenom = allsamples[i] + "/hEtaVsPt_" + binNameDenom;
    TH2F* histDenom = (TH2F*) f->Get(hist_nameDenom.c_str()); assert(histDenom);
/*
    cout<<" Total from 2D Plot is "<<histNum->Integral()<<" / "<<histDenom->Integral()<<endl; //By default, integral doesn't count over/underflow
    cout<<" Total from 2D Plot is "<<histNum->GetEntries()<<" / "<<histDenom->GetEntries()<<endl;

    float sUnder(0), sOver(0);
    for(int ybin = 0; ybin<= histDenom->GetYaxis()->GetNbins() + 1; ++ybin){
      for(int xbin = 0; xbin<= histDenom->GetXaxis()->GetNbins() +1; ++xbin){
        int bin = histDenom->GetBin(xbin, ybin);
        if(histDenom->IsBinOverflow(bin)) sOver += histDenom->GetBinContent(bin);
        if(histDenom->IsBinUnderflow(bin)) sUnder += histDenom->GetBinContent(bin);
      }
    }
    printf("Total overflow, underflow in denom histo is %.2f , %.2f\n", sOver, sUnder);
*/
    for(int ieta=0; ieta<neta-1; ++ieta){
      float ymin = eta[ieta]; 
      float ymax = eta[ieta+1]-offset;
      for(int ipt=0; ipt<npt-1; ++ipt){
        float xmin = pt[ipt]; 
        float xmax = pt[ipt+1];
          
        int xminbin,xmaxbin,yminbin,ymaxbin;
        xminbin = histNum->GetXaxis()->FindBin(xmin); //+ (ipt!=0);//Avoid overlap except for first bin
        xmaxbin = histNum->GetXaxis()->FindBin(xmax)-1 + (ipt == npt-1-1);
        yminbin = histNum->GetYaxis()->FindBin(ymin);
        ymaxbin = histNum->GetYaxis()->FindBin(ymax);
        
        /*
        cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t"
            <<xmin<<"-"<<xmax<<":"
            <<ymin<<"-"<<ymax<<":"
            <<"\t";
        cout<<"("<<ipt<<", "<<ieta<<")\t"
            <<xminbin<<"-"<<xmaxbin<<":"
            <<yminbin<<"-"<<ymaxbin
            <<endl;
        */      
        in  = histNum  ->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
        out = histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
          
        //Cory: Deal with negative eta (Y axis)
        yminbin = histNum->GetYaxis()->FindBin(-1*ymax);
        ymaxbin = histNum->GetYaxis()->FindBin(-1*ymin)-1;//avoid overlap
        /*
        cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t"
            <<xmin<<"-"<<xmax<<":"
            <<ymin<<"-"<<ymax<<":"
            <<"\t";
        cout<<"("<<ipt<<", "<<ieta<<")\t"
            <<xminbin<<"-"<<xmaxbin<<":"
            <<yminbin<<"-"<<ymaxbin
            <<endl;
        */
        in  += histNum  ->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
        out += histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin);

        //cout<<"("<<pt[ipt]<<","<<eta[ieta]<<") "<<in<<"/"<<out<<endl;
        //cout<<"("<<(pt[ipt]+pt[ipt+1])/2<<","<<(eta[ieta]+eta[ieta+1])/2<<") "<<in<<"/"<<out<<endl;
        hFakeRateNum   ->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, in);
        hFakeRateAll->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, out);

      }
    }

  }

  if(hFakeRateNum){
    //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum->GetArray(), hFakeRateAll->GetArray(), "");
    //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum, hFakeRateAll, "");
    TH2F* hFakeRate = (TH2F*) hFakeRateNum->Clone("hFakeRate");
    //hFakeRate->Divide(hFakeRateAll);
    //hFakeRate->Scale(100.); //make is a percent
    TCanvas c1;
    c1.SetLogx(1);


    //gStyle->SetTextFont(132);
    //gStyle->SetTextSize(1.2);
    hFakeRate->SetMarkerSize(3);
    //gStyle->SetPaintTextFormat("3.0f m");
    gStyle->SetPaintTextFormat("4.0f");
    hFakeRate->Draw("colz");

    TLatex latexLabel;
    latexLabel.SetNDC();
    latexLabel.SetTextSize(0.04);
    latexLabel.SetTextFont(42);
    latexLabel.SetTextAngle(90);
    latexLabel.SetTextAlign(22);
    for(int ybin = 1; ybin<= hFakeRate->GetYaxis()->GetNbins(); ++ybin){
      int nx = hFakeRate->GetXaxis()->GetNbins();
      TGraphAsymmErrors* gFakeRatePt = new TGraphAsymmErrors(nx);
      gFakeRatePt->SetMaximum(1.1);
      gFakeRatePt->SetMinimum(0.);
      gFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str());
      for(int xbin = nx; xbin >= 1; --xbin){
        float xcen = hFakeRate->GetXaxis()->GetBinCenter(xbin);
        float ycen = hFakeRate->GetYaxis()->GetBinCenter(ybin);
        
        double xpos, ypos;
        GetNDC(c1, xcen, ycen, xpos, ypos);
        int bin = hFakeRate->GetBin(xbin, ybin);
        float pass = hFakeRateNum->GetBinContent(bin);
        float tot  = hFakeRateAll->GetBinContent(bin);
        float mean    = tot>0 ? pass / tot : 0.;
        float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
        float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
        errDown = max(errDown, (float) 0.);
        hFakeRate->SetBinContent(bin, mean);
        //hFakeRate->SetBinError(bin, err);
        float err = (errUp + errDown)/2;
        printf("if(pt > %.0f) return Value(%.4f, %.4f); //pt %3.0f eta %.1f, bin %2i, (mean, err)= (%.4f, %.4f) (%.2f / %.2f) +%.4f -%.4f\n", 
               hFakeRate->GetXaxis()->GetBinLowEdge(xbin), mean, err, 
               hFakeRate->GetXaxis()->GetBinLowEdge(xbin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin), bin, mean, err, pass, tot, errUp, errDown);
        if(xbin != 1) latexLabel.DrawLatex(xpos, ypos, Form("%.0f^{+%.0f}_{-%.0f}%% (%.0f/%.0f)(%.f-%.f)GeV",mean*100, errUp*100, errDown*100, pass, tot, pt[xbin-1],pt[xbin]));
        

        gFakeRatePt->SetPoint      (xbin-1, xcen, mean);
        gFakeRatePt->SetPointEYhigh(xbin-1, errUp);
        gFakeRatePt->SetPointEYlow (xbin-1, errDown);
        gFakeRatePt->SetPointEXhigh(xbin-1, hFakeRate->GetXaxis()->GetBinLowEdge(xbin+1) - xcen);
        gFakeRatePt->SetPointEXlow (xbin-1, xcen - hFakeRate->GetXaxis()->GetBinLowEdge(xbin));

      }//pt loop
      c1.Clear();
      c1.SetLogx(1);
      //c1.SetGrid();
      gFakeRatePt->Draw("ap*");
      string outName = Form("WJetsFakeRatePt-Eta%.1fto%.1f-", hFakeRate->GetYaxis()->GetBinLowEdge(ybin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin+1));
      replace(outName.begin(), outName.end(), '.', 'p');
      outName += useElectrons ? "Elec" : "Muon";
      outName += useData ? "Data" : "MC";
      outName += !useData && doSystematics ? "Sys" : "";
      outName += doWLep ? "WLep" : "ZLep";
      outName += ".pdf";
      c1.Print(outName.c_str());
      
    }//eta loop
    
    c1.Clear();
    c1.SetLogx(1);
    string outName = "FakeRate";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    //Now make profiles
    c1.Clear();
    c1.SetLogx(0);
    //c1.SetGrid();

    TH1D* hFakeRateNumEta = hFakeRateNum->ProjectionY("hFakeRateNumEta", 0, -1, "e");
    TH1D* hFakeRateAllEta = hFakeRateAll->ProjectionY("hFakeRateAllEta", 0, -1, "e");
    //TH1D* hFakeRateEta = (TH1D*) hFakeRateNumEta->Clone("hFakeRateEta");

    int n = hFakeRateAllEta->GetXaxis()->GetNbins();
    TGraphAsymmErrors* hFakeRateEta = new TGraphAsymmErrors(n);//hFakeRateNumEta, hFakeRateAllEta);
    hFakeRateEta->SetMaximum(1.);
    hFakeRateEta->SetMinimum(0.);
    hFakeRateEta->SetTitle((title + ";#eta;Rate").c_str());

    //hFakeRateEta->SetMarkerStyle(21);    
    for(int xbin = 1; xbin <= n; ++xbin){
      float x = hFakeRateAllEta->GetXaxis()->GetBinCenter(xbin);
      float pass = hFakeRateNumEta->GetBinContent(xbin);
      float tot  = hFakeRateAllEta->GetBinContent(xbin);
      float mean    = tot>0 ? pass / tot : 0.;
      float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
      float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
      errDown = max(errDown, (float) 0.);
      hFakeRateEta->SetPoint      (xbin, x, mean);
      hFakeRateEta->SetPointEYhigh(xbin, errUp);
      hFakeRateEta->SetPointEYlow (xbin, errDown);
      //printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100);
    }
    
    //hFakeRateEta->Divide(hFakeRateAllEta);
    //hFakeRateEta->Scale(100.);
    hFakeRateEta->Draw("ap*");
    outName = "FakeRateEta";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    //Pt projections (split these by eta?)
    c1.Clear();
    c1.SetLogx(1);
    //c1.SetGrid();

    TH1D* hFakeRateNumPt = hFakeRateNum->ProjectionX("hFakeRateNumPt", 0, -1, "e");
    TH1D* hFakeRateAllPt = hFakeRateAll->ProjectionX("hFakeRateAllPt", 0, -1, "e");
    //TH1D* hFakeRatePt = (TH1D*) hFakeRateNumPt->Clone("hFakeRatePt");

    n = hFakeRateAllPt->GetXaxis()->GetNbins();
    TGraphAsymmErrors* hFakeRatePt = new TGraphAsymmErrors(n);//hFakeRateNumPt, hFakeRateAllPt);
    hFakeRatePt->SetMaximum(1.);
    hFakeRatePt->SetMinimum(0.);
    hFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str());

    for(int xbin = 1; xbin <= n; ++xbin){
      float x = hFakeRateAllPt->GetXaxis()->GetBinCenter(xbin);
      float pass = hFakeRateNumPt->GetBinContent(xbin);
      float tot  = hFakeRateAllPt->GetBinContent(xbin);
      float mean    = tot>0 ? pass / tot : 0.;
      float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
      float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
      errDown = max(errDown, (float) 0.);
      hFakeRatePt->SetPoint      (xbin, x, mean);
      hFakeRatePt->SetPointEYhigh(xbin, errUp);
      hFakeRatePt->SetPointEYlow (xbin, errDown);
      //cout<<"low edge is "<<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin)<<" up edge is "
      //    <<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1)<<endl;
      hFakeRatePt->SetPointEXhigh(xbin, hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1) - x);
      hFakeRatePt->SetPointEXlow (xbin, x - hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin));
      printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100);
    }
    


    //hFakeRatePt->Divide(hFakeRateAllPt);
    //hFakeRatePt->Scale(100.);
    hFakeRatePt->Draw("ap*");
    outName = "FakeRatePt";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    
  }


}
Exemple #11
0
exampleScript()
{
  gSystem->CompileMacro("betaHelperFunctions.h"      ,"kO") ;
  gSystem->CompileMacro("RooNormalFromFlatPdf.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaInverseCDF.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaPrimeInverseCDF.cxx" ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaPrimeGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("rooFitBetaHelperFunctions.h","kO") ;

  TFile betaTest("betaTest.root","RECREATE");
  betaTest.cd();
  
  RooWorkspace workspace("workspace");
  TString correlatedName("testVariable");
  TString observables("observables");
  TString nuisances("nuisances");

  RooAbsArg* betaOne = getCorrelatedBetaConstraint(workspace,"betaOne","",
						   0.5 , 0.1 ,
						   observables, nuisances,
						   correlatedName );

  printf("\n\n *** constraint name is %s from betaOne and %s\n\n", betaOne->GetName(), correlatedName.Data() ) ;

  RooAbsArg* betaTwo = getCorrelatedBetaConstraint(workspace,"betaTwo","",
						   0 , 0 ,
						   observables, nuisances,
						   correlatedName );

  RooAbsArg* betaThree = getCorrelatedBetaConstraint(workspace,"betaThree","",
						     0.2 , 0.01 ,
						     observables, nuisances,
						     correlatedName );

  RooAbsArg* betaFour = getCorrelatedBetaConstraint(workspace,"betaFour","",
						    0.7 , 0.1 ,
						    observables, nuisances,
						    correlatedName );

  RooAbsArg* betaFourC = getCorrelatedBetaConstraint(workspace,"betaFourC","",
						    0.7 , 0.1 ,
						    observables, nuisances,
						    correlatedName, kTRUE );

  RooAbsArg* betaPrimeOne = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeOne","",
							     1.0 , 0.5 ,
							     observables, nuisances,
							     correlatedName );

  RooAbsArg* betaPrimeOneC = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeOneC","",
							     1.0 , 0.5 ,
							     observables, nuisances,
							     correlatedName, kTRUE );

  RooAbsArg* betaPrimeTwo = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeTwo","",
							     0.7 , 0.5 ,
							     observables, nuisances,
							     correlatedName );

  RooAbsArg* betaPrimeThree = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeThree","",
							       0.1 , 0.05 ,
							       observables, nuisances,
							       correlatedName );

  RooAbsArg* betaPrimeFour = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeFour","",
							      7 , 1 ,
							      observables, nuisances,
							      correlatedName );

  RooRealVar* correlatedParameter = workspace.var(correlatedName);

  RooAbsPdf* normalFromFlat = workspace.pdf(correlatedName+"_Constraint");

  RooDataSet* data = normalFromFlat->generate(RooArgSet(*correlatedParameter),1e5);

  data->addColumn(*normalFromFlat);

  data->addColumn(*betaOne);
  data->addColumn(*betaTwo);
  data->addColumn(*betaThree);
  data->addColumn(*betaFour);
  data->addColumn(*betaFourC);
  
  data->addColumn(*betaPrimeOne);
  data->addColumn(*betaPrimeTwo);
  data->addColumn(*betaPrimeThree);
  data->addColumn(*betaPrimeFour);
  data->addColumn(*betaPrimeOneC);

  data->Print("v");

  workspace.Print() ;

  //Setup Plotting Kluges:

  RooRealVar normalPlotter  (correlatedName+"_Constraint" , correlatedName+"_Constraint"  ,0,1);
  RooPlot* normalPlot = normalPlotter.frame();
  data->plotOn(normalPlot);

  RooRealVar betaOnePlotter  ("betaOne_BetaInverseCDF"  ,"betaOne_BetaInverseCDF"  ,0,1);
  RooRealVar betaTwoPlotter  ("betaTwo_BetaInverseCDF"  ,"betaTwo_BetaInverseCDF"  ,0,1);
  RooRealVar betaThreePlotter("betaThree_BetaInverseCDF","betaThree_BetaInverseCDF",0,1);
  RooRealVar betaFourPlotter ("betaFour_BetaInverseCDF" ,"betaFour_BetaInverseCDF" ,0,1);
  RooRealVar betaFourCPlotter ("betaFourC_BetaInverseCDF" ,"betaFourC_BetaInverseCDF" ,0,1);

  RooRealVar betaPrimeOnePlotter  ("betaPrimeOne_BetaPrimeInverseCDF"  ,"betaPrimeOne_BetaPrimeInverseCDF"  ,0,4);
  RooRealVar betaPrimeOneCPlotter  ("betaPrimeOneC_BetaPrimeInverseCDF"  ,"betaPrimeOneC_BetaPrimeInverseCDF"  ,0,4);
  RooRealVar betaPrimeTwoPlotter  ("betaPrimeTwo_BetaPrimeInverseCDF"  ,"betaPrimeTwo_BetaPrimeInverseCDF"  ,0,4);
  RooRealVar betaPrimeThreePlotter("betaPrimeThree_BetaPrimeInverseCDF","betaPrimeThree_BetaPrimeInverseCDF",0,0.3);
  RooRealVar betaPrimeFourPlotter ("betaPrimeFour_BetaPrimeInverseCDF" ,"betaPrimeFour_BetaPrimeInverseCDF" ,4,12);

  RooPlot* betaOnePlot   = betaOnePlotter  .frame();
  RooPlot* betaTwoPlot   = betaTwoPlotter  .frame();
  RooPlot* betaThreePlot = betaThreePlotter.frame();
  RooPlot* betaFourPlot  = betaFourPlotter .frame();
  RooPlot* betaFourCPlot  = betaFourCPlotter .frame();

  data->plotOn(betaOnePlot  );
  data->plotOn(betaTwoPlot  );
  data->plotOn(betaThreePlot);
  data->plotOn(betaFourPlot );
  data->plotOn(betaFourCPlot );

  RooPlot* betaPrimeOnePlot   = betaPrimeOnePlotter  .frame();
  RooPlot* betaPrimeOneCPlot   = betaPrimeOneCPlotter  .frame();
  RooPlot* betaPrimeTwoPlot   = betaPrimeTwoPlotter  .frame();
  RooPlot* betaPrimeThreePlot = betaPrimeThreePlotter.frame();
  RooPlot* betaPrimeFourPlot  = betaPrimeFourPlotter .frame();

  data->plotOn(betaPrimeOnePlot  );
  data->plotOn(betaPrimeOneCPlot  );
  data->plotOn(betaPrimeTwoPlot  );
  data->plotOn(betaPrimeThreePlot);
  data->plotOn(betaPrimeFourPlot );

  TCanvas* underlyingVariable = new TCanvas("underlyingVariable","underlyingVariable",800,800);
  underlyingVariable->Divide(2,2);
  underlyingVariable->cd(1);
  RooPlot* underlyingPlot   = correlatedParameter->frame();
  data->plotOn(underlyingPlot);
  underlyingPlot->Draw();
  underlyingVariable->cd(2);
  normalPlot->Draw();
  underlyingVariable->cd(3);
  TH2F* underlying = data->createHistogram(*correlatedParameter,normalPlotter,50,50);
  underlying->Draw("col");
  TH2F* legoUnderlying = (TH2F*)underlying->Clone();
  underlyingVariable->cd(4);
  legoUnderlying->Draw("lego");

  underlyingVariable->SaveAs("underlyingVariable.pdf");
  
  TCanvas* betaCanvas = new TCanvas("betaCanvas","betaCanvas",800,800);
  
  betaCanvas->Divide(3,2);
  
  betaCanvas->cd(1);
  betaOnePlot->Draw();
  betaCanvas->cd(2);
  betaTwoPlot->Draw();
  betaCanvas->cd(3);
  betaThreePlot->Draw();
  betaCanvas->cd(4);
  betaFourPlot->Draw();
  betaCanvas->cd(5);
  betaFourCPlot->Draw();

  betaCanvas->SaveAs("betaVariables.pdf");

  TCanvas* betaPrimeCanvas = new TCanvas("betaPrimeCanvas","betaPrimeCanvas",1200,800);
  
  betaPrimeCanvas->Divide(3,2);
  
  betaPrimeCanvas->cd(1);
  betaPrimeOnePlot->Draw();
  betaPrimeCanvas->cd(2);
  betaPrimeTwoPlot->Draw();
  betaPrimeCanvas->cd(3);
  betaPrimeThreePlot->Draw();
  betaPrimeCanvas->cd(4);
  betaPrimeFourPlot->Draw();
  betaPrimeCanvas->cd(5);
  betaPrimeOneCPlot->Draw();

  betaPrimeCanvas->SaveAs("betaPrimeVariables.pdf");
  
  TCanvas* betaCorrelationsCanvas = new TCanvas("betaCorrelationsCanvas","betaCorrelationsCanvas",1600,800);
  
  betaCorrelationsCanvas->Divide(4,2);

  TH2F* oneTwo = data->createHistogram(betaOnePlotter,betaTwoPlotter,30,30);
  TH2F* oneThree = data->createHistogram(betaOnePlotter,betaThreePlotter,30,30);
  TH2F* oneFour = data->createHistogram(betaOnePlotter,betaFourPlotter,30,30);
  TH2F* twoThree = data->createHistogram(betaTwoPlotter,betaThreePlotter,30,30);
  TH2F* twoFour = data->createHistogram(betaTwoPlotter,betaFourPlotter,30,30);
  TH2F* threeFour = data->createHistogram(betaThreePlotter,betaFourPlotter,30,30);
  TH2F* twoFourC = data->createHistogram(betaTwoPlotter,betaFourCPlotter,30,30);
  TH2F* fourFourC = data->createHistogram(betaFourPlotter,betaFourCPlotter,30,30);

  betaCorrelationsCanvas->cd(1);
  oneTwo->DrawCopy("lego");
  betaCorrelationsCanvas->cd(2);
  oneThree->DrawCopy("lego");
  betaCorrelationsCanvas->cd(3);
  oneFour->DrawCopy("lego");
  betaCorrelationsCanvas->cd(4);
  twoThree->DrawCopy("lego");
  betaCorrelationsCanvas->cd(5);
  twoFour->DrawCopy("lego");
  betaCorrelationsCanvas->cd(6);
  threeFour->DrawCopy("lego");
  betaCorrelationsCanvas->cd(7);
  twoFourC->DrawCopy("lego");
  betaCorrelationsCanvas->cd(8);
  fourFourC->DrawCopy("lego");

  betaCorrelationsCanvas->SaveAs("betaCorrelations.pdf");

  TCanvas* betaPrimeCorrelationsCanvas = new TCanvas("betaPrimeCorrelationsCanvas","betaPrimeCorrelationsCanvas",1600,800);
  
  betaPrimeCorrelationsCanvas->Divide(4,2);

  TH2F* oneTwo = data->createHistogram(betaPrimeOnePlotter,betaPrimeTwoPlotter,30,30);
  TH2F* oneThree = data->createHistogram(betaPrimeOnePlotter,betaPrimeThreePlotter,30,30);
  TH2F* oneFour = data->createHistogram(betaPrimeOnePlotter,betaPrimeFourPlotter,30,30);
  TH2F* twoThree = data->createHistogram(betaPrimeTwoPlotter,betaPrimeThreePlotter,30,30);
  TH2F* twoFour = data->createHistogram(betaPrimeTwoPlotter,betaPrimeFourPlotter,30,30);
  TH2F* threeFour = data->createHistogram(betaPrimeThreePlotter,betaPrimeFourPlotter,30,30);
  TH2F* oneOneC = data->createHistogram(betaPrimeOnePlotter,betaPrimeOneCPlotter,30,30);

  betaPrimeCorrelationsCanvas->cd(1);
  oneTwo->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(2);
  oneThree->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(3);
  oneFour->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(4);
  twoThree->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(5);
  twoFour->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(6);
  threeFour->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(7);
  oneOneC->DrawCopy("lego");

  betaPrimeCorrelationsCanvas->SaveAs("betaPrimeCorrelations.pdf");

  RooProdPdf totalPdf("totalPdf","totalPdf",workspace.allPdfs());
  totalPdf.Print("v");

  RooArgSet* observableSet = workspace.set("observables");

  observableSet->Print();

  RooDataSet* allDataOne = totalPdf.generate(*observableSet,1);
  allDataOne->Print("v");

  correlatedParameter->setVal(0.25);

  RooDataSet* allDataTwo = totalPdf.generate(*observableSet,1);
  allDataTwo->Print("v");

  correlatedParameter->setVal(0.75);

  RooDataSet* allDataThree = totalPdf.generate(*observableSet,1);
  allDataThree->Print("v");

  //Testing for extreme values!

  for(int i = 0; i< 101; i++)
    {
      correlatedParameter->setVal((double)i/100.);
      cout << "Correlation parameter has value of " << correlatedParameter->getVal();
      cout << " and the pdf has an unnormalized value of " << normalFromFlat->getVal() << endl;
    }


}
Exemple #12
0
void drawICmap(const string& wwwPath = "",
	       const string& eosPath = "", 
	       const string& dirName = "", 
	       const string& iterNumber = "", 
	       const string& tagName = "") {

  gStyle->SetPalette(1, 0);  // raibow palette                                                
  gStyle->SetNumberContours(50); // default is 20 

  string filename = "root://eoscms//eos/cms" + eosPath + dirName + "/" + iterNumber + "/" + tagName + "calibMap.root";

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

  TH2F *mapEB = (TH2F*) f->Get("calibMap_EB");
  TH2F *h = NULL;
  h = (TH2F*) f->Get("calibMap_EEp");
  TH2F *mapEEp = (TH2F*) h->Clone();
  h = (TH2F*) f->Get("calibMap_EEm");
  TH2F *mapEEm = (TH2F*) h->Clone();

  if (!mapEB || !mapEEp || !mapEEm) {
    cout << "Error: could not get one or more histograms. End of programme" << endl;
    exit(EXIT_FAILURE);
  }

  TH2F *mapEB_new = new TH2F("mapEB_new","EB calib coefficients", 360, 0.5, 360.5, 171,-85.5,85.5 );

  // profile along ieta. ieta goea from -85 to 85, exluding 0, for a total of 170 non empty bins (they are 171 including ieta = 0 which is actually empty)
  // in the profile, ieta = 30 is the bin with x from 29.5 to 30.5
  // simila logic for profile along iphi
  TProfile * EB_ieta_profile = new TProfile("EB_ieta_profile","EB calib coefficients - i#eta profile",171,-85.5,85.5);
  TProfile * EB_iphi_profile = new TProfile("EB_iphi_profile","EB calib coefficients - i#phi profile",360,0.5,360.5);


  Int_t nbinsX = mapEB->GetNbinsX(); // ieta
  Int_t nbinsY = mapEB->GetNbinsY(); // iphi

  for (Int_t i = 1; i <= nbinsX; i++) {

      for (Int_t j = 1; j <= nbinsY; j++) {
	
	mapEB_new->Fill(j,(i-86.0),mapEB->GetBinContent(i,j));
	EB_ieta_profile->Fill((i-86.0),mapEB->GetBinContent(i,j));
	EB_iphi_profile->Fill(j,mapEB->GetBinContent(i,j));

      }

  }

  string wwwAllPath = wwwPath + dirName + "/" + iterNumber + "/2DMaps/";
  string name = "";
  TPaletteAxis *palette = NULL;

  //EB
  TCanvas *cEB = new TCanvas("cEB","IC map EB");
  mapEB_new->Draw("COLZ");
  mapEB_new->GetXaxis()->SetTitle("i #phi");
  mapEB_new->GetXaxis()->SetTitleSize(0.06);
  mapEB_new->GetXaxis()->SetTitleOffset(0.7);
  mapEB_new->GetYaxis()->SetTitle("i #eta");
  mapEB_new->GetYaxis()->SetTitleSize(0.06);
  mapEB_new->GetYaxis()->SetTitleOffset(0.8);
  mapEB_new->GetZaxis()->SetRangeUser(0.9,1.1);
  mapEB_new->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEB_new->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                                                                              
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                                                                                                                             
  name = wwwAllPath + "Barrel/IC_calibMapEB";
  cEB->SaveAs((name + ".pdf").c_str());
  cEB->SaveAs((name + ".png").c_str());

  TCanvas *cEB_ietaProfile = new TCanvas("cEB_ietaProfile","IC map EB - i#eta profile");
  EB_ieta_profile->Draw("HIST");
  EB_ieta_profile->GetXaxis()->SetTitle("i #eta");
  EB_ieta_profile->GetXaxis()->SetTitleSize(0.06);
  EB_ieta_profile->GetXaxis()->SetTitleOffset(0.7);
  EB_ieta_profile->GetYaxis()->SetTitle("IC");
  EB_ieta_profile->GetYaxis()->SetTitleSize(0.06);
  EB_ieta_profile->GetYaxis()->SetTitleOffset(0.8);
  // Double_t maxY = EB_ieta_profile->GetBinContent(EB_ieta_profile->GetMaximumBin());
  // Double_t scale_factor = 1.1;
  // Double_t minY = 999.9; // minimum would be 0, corresponding to ieta = 0; look for minimum excluding ieta = 0
  // for (Int_t ieta = -85; ieta<= 85; ieta++) {
  //   if (ieta == 0) continue;
  //   minY = (EB_ieta_profile->GetBinContent(ieta+86) < minY) ? EB_ieta_profile->GetBinContent(ieta+86) : minY;
  // }
  // Double_t offset = scale_factor * (maxY -minY); 
  // EB_ieta_profile->GetYaxis()->SetRangeUser(minY - offset, maxY + offset);
  EB_ieta_profile->GetYaxis()->SetRangeUser(0.89,0.99);
  EB_ieta_profile->SetStats(0);
  gPad->Update();
  name = wwwAllPath + "Barrel/IC_calibMapEB_ietaProfile";
  cEB_ietaProfile->SaveAs((name + ".pdf").c_str());
  cEB_ietaProfile->SaveAs((name + ".png").c_str());


  TCanvas *cEB_iphiProfile = new TCanvas("cEB_iphiProfile","IC map EB - i#phi profile");
  EB_iphi_profile->Draw("HIST");
  EB_iphi_profile->GetXaxis()->SetTitle("i #phi");
  EB_iphi_profile->GetXaxis()->SetTitleSize(0.06);
  EB_iphi_profile->GetXaxis()->SetTitleOffset(0.7);
  EB_iphi_profile->GetYaxis()->SetTitle("IC");
  EB_iphi_profile->GetYaxis()->SetTitleSize(0.06);
  EB_iphi_profile->GetYaxis()->SetTitleOffset(0.8);
  // maxY = EB_iphi_profile->GetBinContent(EB_iphi_profile->GetMaximumBin());
  // minY = EB_iphi_profile->GetBinContent(EB_iphi_profile->GetMinimumBin()); 
  // offset = scale_factor * (maxY -minY); 
  // EB_iphi_profile->GetYaxis()->SetRangeUser(minY - offset, maxY + offset);
  EB_iphi_profile->GetYaxis()->SetRangeUser(0.91,0.97);
  EB_iphi_profile->SetStats(0);
  gPad->Update();
  name = wwwAllPath + "Barrel/IC_calibMapEB_iphiProfile";
  cEB_iphiProfile->SaveAs((name + ".pdf").c_str());
  cEB_iphiProfile->SaveAs((name + ".png").c_str());


  //EE+
  TCanvas *cEEp = new TCanvas("cEEp","IC map EE+");
  mapEEp->Draw("COLZ");
  mapEEp->GetXaxis()->SetTitle("iX");
  mapEEp->GetXaxis()->SetTitleSize(0.06);
  mapEEp->GetXaxis()->SetTitleOffset(0.7);
  mapEEp->GetYaxis()->SetTitle("iY");
  mapEEp->GetYaxis()->SetTitleSize(0.06);
  mapEEp->GetYaxis()->SetTitleOffset(0.8);
  mapEEp->GetZaxis()->SetRangeUser(0.75,1.25);
  mapEEp->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEEp->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                    
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                    
  name = wwwAllPath + "Endcap/EEp/IC_calibMapEEp";
  cEEp->SaveAs((name + ".pdf").c_str());
  cEEp->SaveAs((name + ".png").c_str());

  //EE-
  TCanvas *cEEm = new TCanvas("cEEm","IC map EE-");
  mapEEm->Draw("COLZ");
  mapEEm->GetXaxis()->SetTitle("iX");
  mapEEm->GetXaxis()->SetTitleSize(0.06);
  mapEEm->GetXaxis()->SetTitleOffset(0.7);
  mapEEm->GetYaxis()->SetTitle("iY");
  mapEEm->GetYaxis()->SetTitleSize(0.06);
  mapEEm->GetYaxis()->SetTitleOffset(0.8);
  mapEEm->GetZaxis()->SetRangeUser(0.75,1.25);
  mapEEm->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEEm->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                    
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                    
  name = wwwAllPath + "Endcap/EEm/IC_calibMapEEm";
  cEEm->SaveAs((name + ".pdf").c_str());
  cEEm->SaveAs((name + ".png").c_str());

  


}
void draw_mSUGRA_exclusion(TH2F *ocrosssection, TH2F *oFilterEfficiency, TH2F *oabsXS, TH2F *limitmap, TH2F *expmap, TH2F *expplusmap, TH2F *expminusmap, TH2F *exp2plusmap, TH2F *exp2minusmap, bool isobserved) {
  TH2F *crosssection = (TH2F*)ocrosssection->Clone("crosssection");
//  TH2F *limitmap = (TH2F*)olimitmap->Clone(((string)olimitmap->GetName()+"clone").c_str());
  TH2F *cleanhisto = (TH2F*)limitmap->Clone("clean");
  for(int ix=1;ix<=cleanhisto->GetNbinsX();ix++) {
    for(int iy=1;iy<=cleanhisto->GetNbinsY();iy++) {
      cleanhisto->SetBinContent(ix,iy,0);
    }
  }
  
  
  TH2F *FilterEfficiency;
  TH2F *absXS;

  
  
  
  write_warning(__FUNCTION__,"You'll want to switch off 'wrongwaytodothis')");
  
  if(wrongwaytodothis) {
    //this part is the one you want to remove.
    TFile *Efficiencies = new TFile("FilterEfficiencyv3.root");
    FilterEfficiency = cast_into_shape((TH2F*) Efficiencies->Get("FilterEfficiency"),limitmap);
    assert(FilterEfficiency);
    assert(crosssection);
    absXS=(TH2F*)crosssection->Clone("absXS");
    crosssection->Multiply(FilterEfficiency);
  } else {
    //this part is the one you want to keep!
    FilterEfficiency=(TH2F*)oFilterEfficiency->Clone("FilterEfficiency");
    absXS=(TH2F*)oabsXS->Clone("absXS");
  }
    
  

  TH2F *limits = (TH2F*)limitmap->Clone("limits");
  set_range(limits,true,false);
  limitmap->Divide(crosssection);
  expminusmap->Divide(crosssection);
  expplusmap->Divide(crosssection);
  exp2minusmap->Divide(crosssection);
  exp2plusmap->Divide(crosssection);
  expmap->Divide(crosssection);
  TGraph *observed = get_mSUGRA_exclusion_line(limitmap, PlottingSetup::mSUGRA);
  observed->SetLineColor(kRed);
  TGraph *expminus = get_mSUGRA_exclusion_line(expminusmap, PlottingSetup::mSUGRA);
  TGraph *expplus  = get_mSUGRA_exclusion_line(expplusmap, PlottingSetup::mSUGRA);
  TGraph *exp2minus;
  if(draw2sigma) exp2minus = get_mSUGRA_exclusion_line(exp2minusmap, PlottingSetup::mSUGRA);
  TGraph *exp2plus;
  if(draw2sigma) exp2plus = get_mSUGRA_exclusion_line(exp2plusmap, PlottingSetup::mSUGRA);

  TGraph *expected = new TGraph(expminus->GetN()+expplus->GetN());
  TGraph *expected2; 
  if(draw2sigma) expected2 = new TGraph(exp2minus->GetN()+exp2plus->GetN());
  for(int i=0;i<=expminus->GetN();i++) {
    Double_t x,y;
    expminus->GetPoint(i,x,y);
    expected->SetPoint(i,x,y);
  }
    
  for(int i=0;i<=exp2minus->GetN();i++) {
    Double_t x,y;
    exp2minus->GetPoint(i,x,y);
    expected2->SetPoint(i,x,y);
  }
  for(int i=exp2plus->GetN()-1;i>=0;i--) {
    Double_t x,y;
    exp2plus->GetPoint(i,x,y);
    expected2->SetPoint(exp2minus->GetN()+(exp2plus->GetN()-i),x,y);
  }
  for(int i=expplus->GetN()-1;i>=0;i--) {
    Double_t x,y;
    expplus->GetPoint(i,x,y);
    expected->SetPoint(expminus->GetN()+(expplus->GetN()-i),x,y);
  }
  expected->SetFillColor(TColor::GetColor("#9FF781"));
  if(draw2sigma) expected2->SetFillColor(TColor::GetColor("#F3F781"));
  
  smooth_line(observed);
  smooth_line(expected);
  if(draw2sigma) smooth_line(expected2);
  
  TCanvas *te = new TCanvas("te","te");
  te->SetRightMargin(standardmargin);
//  decorate_mSUGRA(cleanhisto,te,expected,expected2,observed);
  TH2F *noh = new TH2F("noh","noh",1,1,2,1,1,2);
  SugarCoatThis(te,10,noh,observed);
//  expected->Draw("c");
//  observed->Draw("c");
  stringstream saveas;
  if((int)((string)limitmap->GetName()).find("limitmap")>0) {
    saveas << "Limits/";
    if(!isobserved) saveas << "expected/expected_";
    saveas << "final_exclusion_for_JZB_geq_" << ((string)limitmap->GetName()).substr(((string)limitmap->GetName()).find("limitmap")+8,10);
  } else {
    saveas << "Limits/";
    if(!isobserved) saveas << "expected/expected";
    saveas << "final_exclusion_for_bestlimits";
  }
  CompleteSave(te,saveas.str());
  delete te;
  
  TCanvas *overview = new TCanvas("overview","overview",1500,1000);
  
  set_range(crosssection,true,false);
  set_range(limits,true,false);
  set_range(limitmap,true,false);
  
  overview->Divide(3,2);
  overview->cd(1);
  overview->cd(1)->SetLogz(1);
  absXS->GetZaxis()->SetRangeUser(0.0001,100);
  absXS->Draw("COLZ");
  TText *title0 = write_title("Cross Section");
  title0->Draw("same");
  overview->cd(2);
  FilterEfficiency->GetZaxis()->SetRangeUser(0.01,0.7);
  FilterEfficiency->Draw("COLZ");
  TText *title0aa = write_title("Filter #epsilon");
  title0aa->Draw("same");
  overview->cd(3);
  overview->cd(3)->SetLogz(1);
  crosssection->GetZaxis()->SetRangeUser(0.0001,100);
  crosssection->Draw("COLZ");
  TText *title0a = write_title("Filter #epsilon x Cross Section");
  title0a->Draw("same");
  
  overview->cd(4);
  overview->cd(4)->SetLogz(1);
  limits->GetZaxis()->SetRangeUser(0.01,100);
  limits->Draw("COLZ");
  TText *title1 = write_title("Cross Section Upper Limit");
  title1->Draw("same");
  overview->cd(5);
  limitmap->Draw("COLZ");
  TText *title2 = write_title("UL/XS");
  title2->Draw("same");
  observed->Draw("c");
  overview->cd(6);
  overview->cd(6)->SetRightMargin(standardmargin);
//  decorate_mSUGRA(cleanhisto,overview->cd(4),expected,expected2,observed);
  SugarCoatThis(overview->cd(6),10,noh,observed);
//  observed->Draw("c");
  stringstream saveas2;
  if((int)((string)limitmap->GetName()).find("limitmap")>0) {
    saveas2 << "Limits/";
    if(!isobserved) saveas << "expected/expected_";
    saveas2 << "exclusion_overview_for_JZB_geq_" << ((string)limitmap->GetName()).substr(((string)limitmap->GetName()).find("limitmap")+8,10);
  } else {
    saveas2 << "Limits/";
    if(!isobserved) saveas << "expected/expected_";
    saveas2 << "exclusion_overview_for_bestlimits";
  }
  CompleteSave(overview,saveas2.str());
  delete overview;
  delete noh;
  delete crosssection;
  delete absXS;
  delete FilterEfficiency;
  
}
void DrawCalibrationPlotsEE (
 			     Char_t* infile1 = "data_LC_20120131_ALPHA_test_prompt/SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     Char_t* infile2 = "data_LC_20120131_ALPHA_test_prompt/Even_SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     Char_t* infile3 = "data_LC_20120131_ALPHA_test_prompt/Odd_SingleElectron_Run2011AB-WElectron-data_LC_20120131_ALPHA_test_prompt_EoPcaibEE_11032011_Z_R9_EE.root",
 			     //Char_t* infile1 = "FT_R_42_V21B/WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
 			     //Char_t* infile2 = "FT_R_42_V21B/Even_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
 			     //Char_t* infile3 = "FT_R_42_V21B/Odd_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_R9_EE.root",
			     int evalStat = 1,
                             bool isMC=false,
			     Char_t* fileType = "png", 
			     Char_t* dirName = ".")
{

  bool  printPlots = false;

  /// by xtal

  int nbins = 250;

  /// Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");

  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(11110); 
  gStyle->SetOptFit(0); 
  gStyle->SetFitFormat("6.3g"); 
  gStyle->SetPalette(1); 
 
  gStyle->SetTextFont(42);
  gStyle->SetTextSize(0.05);
  gStyle->SetTitleFont(42,"xyz");
  gStyle->SetTitleSize(0.05);
  gStyle->SetLabelFont(42,"xyz");
  gStyle->SetLabelSize(0.05);
  gStyle->SetTitleXOffset(0.8);
  gStyle->SetTitleYOffset(1.1);
  gROOT->ForceStyle();

  if ( !infile1 ) {
    cout << " No input file specified !" << endl;
    return;
  }


  if ( evalStat && (!infile2 || !infile3 )){
    cout << " No input files to evaluate statistical precision specified !" << endl;
    return;
  }

  cout << "Making calibration plots for: " << infile1 << endl;
  
  
  /// imput file with full statistic normlized to the mean in a ring

  TFile *f = new TFile(infile1);
  TH2F *hcmap[2];
  hcmap[0] = (TH2F*)f->Get("h_scale_map_EEM");
  hcmap[1] = (TH2F*)f->Get("h_scale_map_EEP");
    

  /// ring geometry for the endcap
  TH2F *hrings[2];
  hrings[0] = (TH2F*)hcmap[0]->Clone("hringsEEM");
  hrings[1] = (TH2F*)hcmap[0]->Clone("hringsEEP");
  hrings[0] ->Reset("ICMES");
  hrings[1] ->Reset("ICMES");
  hrings[0] ->ResetStats();
  hrings[1] ->ResetStats();

  FILE *fRing;
  fRing = fopen("macros/eerings.dat","r");
  int x,y,z,ir;
  while(fscanf(fRing,"(%d,%d,%d) %d \n",&x,&y,&z,&ir) !=EOF ) {
    if(z>0) hrings[1]->Fill(x,y,ir); 
    if(z<0) hrings[0]->Fill(x,y,ir);
  }

  TFile *f4 = TFile::Open("MCtruthIC_EE.root");
  TFile *f5 = TFile::Open("MCRecoIC_EE.root");

  TH2F *hcmapMcT_EEP = (TH2F*)f4->Get("h_scale_EEP");
  TH2F *hcmapMcT_EEM = (TH2F*)f4->Get("h_scale_EEM");
  TH2F *hcmapMcR_EEP = (TH2F*)f5->Get("h_scale_EEP");
  TH2F *hcmapMcR_EEM = (TH2F*)f5->Get("h_scale_EEM");
 
 
  ///--------------------------------------------------------------------------------
  ///--- Build the precision vs ring plot starting from the TH2F of IC folded and not
  ///--------------------------------------------------------------------------------

  char hname[100];
  char htitle[100];
  TH1F *hspread[2][50];
  TH1F* hspreadAll [40];

  TH2F* ICComparison [2];
  ICComparison[0] = (TH2F*) hcmapMcT_EEP->Clone("ICComparison_EEM");
  ICComparison[1] = (TH2F*) hcmapMcT_EEM->Clone("ICComparison_EEP");
  ICComparison[0]->Reset("ICMES");
  ICComparison[1]->Reset("ICMES");
  ICComparison[0]->ResetStats();
  ICComparison[1]->ResetStats();


  for (int k = 0; k < 2; k++){
         
    for (int iring = 0; iring < 40 ; iring++){
      if (k==0)
      {
       sprintf(hname,"hspreadAll_ring%02d",iring);
       hspreadAll[iring] = new TH1F(hname, hname, nbins,0.,2.);
       sprintf(hname,"hspreadEEM_MCTruth_ring%02d",iring);
       hspread[k][iring] = new TH1F(hname, hname, nbins,0.,2.);

      }
      else{ 
	
        sprintf(hname,"hspreadEEP_ring%02d",iring);
         hspread[k][iring] = new TH1F(hname, hname, nbins,0.,2.);
 
     }
    }
 }
  
 /// spread all distribution, spread for EE+ and EE- and comparison with the MC truth
  for (int k = 0; k < 2 ; k++){
    for (int ix = 1; ix < 101; ix++){
      for (int iy = 1; iy < 101; iy++){
	int iz = k;
	if (k==0) iz = -1;
	int mybin = hcmap[k] -> FindBin(ix,iy);
	int ring  = hrings[1]-> GetBinContent(mybin);
	float ic = hcmap[k]->GetBinContent(mybin);
        float ic2=0;
          if(k==0 && hcmapMcT_EEM->GetBinContent(mybin)!=0 && hcmapMcR_EEM->GetBinContent(mybin)!=0 ) ic2 = hcmapMcT_EEM->GetBinContent(mybin)/hcmapMcR_EEM->GetBinContent(mybin);
          else if(hcmapMcT_EEP->GetBinContent(mybin)!=0 && hcmapMcR_EEP->GetBinContent(mybin)!=0 ) ic2 = hcmapMcT_EEP->GetBinContent(mybin)/hcmapMcR_EEP->GetBinContent(mybin);
          
 	if ( ic>0 && ic2>0 )    {
	  hspread[k][ring]->Fill(ic);
          hspreadAll[ring]->Fill(ic);
          ICComparison[k]->Fill(ix,iy,ic/ic2);
	}
      }
    }
  }
  
  /// Graph Error for spread EE+ and EE-

  TGraphErrors *sigma_vs_ring[3];
  sigma_vs_ring[0] = new TGraphErrors();
  sigma_vs_ring[0]->SetMarkerStyle(20);
  sigma_vs_ring[0]->SetMarkerSize(1);
  sigma_vs_ring[0]->SetMarkerColor(kBlue+2);
  
  sigma_vs_ring[1] = new TGraphErrors();
  sigma_vs_ring[1]->SetMarkerStyle(20);
  sigma_vs_ring[1]->SetMarkerSize(1);
  sigma_vs_ring[1]->SetMarkerColor(kBlue+2);

  sigma_vs_ring[2] = new TGraphErrors();
  sigma_vs_ring[2]->SetMarkerStyle(20);
  sigma_vs_ring[2]->SetMarkerSize(1);
  sigma_vs_ring[2]->SetMarkerColor(kBlue+2);
 
  /// Graph for scale vs ring EE+, EE- and folded

  TGraphErrors *scale_vs_ring[3];
  scale_vs_ring[0] = new TGraphErrors();
  scale_vs_ring[0]->SetMarkerStyle(20);
  scale_vs_ring[0]->SetMarkerSize(1);
  scale_vs_ring[0]->SetMarkerColor(kBlue+2);

  scale_vs_ring[1] = new TGraphErrors();
  scale_vs_ring[1]->SetMarkerStyle(20);
  scale_vs_ring[1]->SetMarkerSize(1);
  scale_vs_ring[1]->SetMarkerColor(kBlue+2);

  scale_vs_ring[2] = new TGraphErrors();
  scale_vs_ring[2]->SetMarkerStyle(20);
  scale_vs_ring[2]->SetMarkerSize(1);
  scale_vs_ring[2]->SetMarkerColor(kBlue+2);
    
  
  TF1 *fgaus = new TF1("fgaus","gaus",-10,10);
  int np[3] = {0};

  /// Gaussian fit for EE+ and EE-

  for (int k = 0; k < 2 ; k++){
    for (int iring = 0; iring < 40; iring++){
      if (hspread[k][iring]-> GetEntries() == 0) continue;
      float e     = 0.5*hcmap[k]-> GetYaxis()->GetBinWidth(1);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hspread[k][iring]->GetRMS());
      fgaus->SetRange(1-5*hspread[k][iring]->GetRMS(),1+5*hspread[k][iring]->GetRMS());
      hspread[k][iring]->Fit("fgaus","QR");
      sigma_vs_ring[k]-> SetPoint(np[k],iring,fgaus->GetParameter(2));
      sigma_vs_ring[k]-> SetPointError(np[k], e ,fgaus->GetParError(2));
      scale_vs_ring[k]-> SetPoint(np[k],iring,fgaus->GetParameter(1));
      scale_vs_ring[k]-> SetPointError(np[k],e,fgaus->GetParError(1));
      np[k]++;    
    }
  }
  
    for (int iring = 0; iring < 40; iring++){
      if (hspreadAll[iring]-> GetEntries() == 0) continue;
      float e     = 0.5*hcmap[0]-> GetYaxis()->GetBinWidth(1);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hspreadAll[iring]->GetRMS());
      fgaus->SetRange(1-5*hspreadAll[iring]->GetRMS(),1+5*hspreadAll[iring]->GetRMS());
      hspreadAll[iring]->Fit("fgaus","QR");
      sigma_vs_ring[2]-> SetPoint(np[2],iring,fgaus->GetParameter(2));
      sigma_vs_ring[2]-> SetPointError(np[2], e ,fgaus->GetParError(2));
      scale_vs_ring[2]-> SetPoint(np[2],iring,fgaus->GetParameter(1));
      scale_vs_ring[2]-> SetPointError(np[2],e,fgaus->GetParError(1));
      np[2]++;    
    }

  /// Intercalibration constant vs phi
 
 /* TGraphErrors *IC_vs_phi[2];
  IC_vs_phi[0] = new TGraphErrors();
  IC_vs_phi[0]->SetMarkerStyle(20);
  IC_vs_phi[0]->SetMarkerSize(1);
  IC_vs_phi[0]->SetMarkerColor(kBlue+2);
  
  IC_vs_phi[1] = new TGraphErrors();
  IC_vs_phi[1]->SetMarkerStyle(20);
  IC_vs_phi[1]->SetMarkerSize(1);
  IC_vs_phi[1]->SetMarkerColor(kBlue+2);

  TH1F* Spread_vs_phi[2][360];
  
  for (int k = 0; k < 2; k++){
    for (int iphi = 0; iphi < 360 ; iphi++){
      if (k==0)
      {
       sprintf(hname,"hspread_vs_phi%02d_EEP",iphi);
       Spread_vs_phi[k][iphi] = new TH1F(hname, hname, nbins,0.,2.);

      }
      else{ 
        sprintf(hname,"hspread_vs_ring%02d_EEM",iphi);
        Spread_vs_phi[k][iphi] = new TH1F(hname, hname, nbins,0.,2.);}
     } 
   }
  

  for (int k = 0; k < 2 ; k++){
    for (int ix = 1; ix < 101; ix++){
      for (int iy = 1; iy < 101; iy++){
	float iphibin;
        if((atan2(iy-50.,ix-50.)-int(atan2(iy-50.,ix-50.)))*(360./(2.*3.14159)) <0.5) iphibin=floor(180.+atan2(iy-50.,ix-50.)*(360./(2.*3.14159)));
        else iphibin=ceil(180.+atan2(iy-50.,ix-50.)*(360./(2.*3.14159)));
       
        if(iphibin>359) iphibin=359;
	int mybin = hcmap[k] -> FindBin(ix,iy);
	float ic = hcmap[k]->GetBinContent(mybin);          
	if ( ic>0 )    {
	 Spread_vs_phi[k][iphibin] ->Fill(ic);
	}
      }
    }
  }
 
 int N[2]={0};
  for (int k = 0; k < 2 ; k++){
    for (int iphi = 0; iphi < 360; iphi++){
      if (Spread_vs_phi[k][iphi]-> GetEntries() == 0) continue;
      IC_vs_phi[k]-> SetPoint(N[k],iphi,Spread_vs_phi[k][iphi]->GetMean());
      IC_vs_phi[k]-> SetPointError(N[k],0,Spread_vs_phi[k][iphi]->GetRMS()/sqrt(Spread_vs_phi[k][iphi]->GetEntries()));

      N[k]++;    
    }
  }
  */

 ///----------------- Statistical Precision  and Residual --------------------

    TGraphErrors *statprecision_vs_ring[3];
    statprecision_vs_ring[0]  = new TGraphErrors();
    statprecision_vs_ring[0]->SetMarkerStyle(20);
    statprecision_vs_ring[0]->SetMarkerSize(1);
    statprecision_vs_ring[0]->SetMarkerColor(kRed+2);

    statprecision_vs_ring[1]  = new TGraphErrors();
    statprecision_vs_ring[1]->SetMarkerStyle(20);
    statprecision_vs_ring[1]->SetMarkerSize(1);
    statprecision_vs_ring[1]->SetMarkerColor(kRed+2);

    statprecision_vs_ring[2]  = new TGraphErrors();
    statprecision_vs_ring[2]->SetMarkerStyle(20);
    statprecision_vs_ring[2]->SetMarkerSize(1);
    statprecision_vs_ring[2]->SetMarkerColor(kRed+2);
    
    TGraphErrors *residual_vs_ring[3];
    residual_vs_ring[0] = new TGraphErrors();
    residual_vs_ring[0]->SetMarkerStyle(20);
    residual_vs_ring[0]->SetMarkerSize(1);
    residual_vs_ring[0]->SetMarkerColor(kGreen+2);
  
    residual_vs_ring[1] = new TGraphErrors();
    residual_vs_ring[1]->SetMarkerStyle(20);
    residual_vs_ring[1]->SetMarkerSize(1);
    residual_vs_ring[1]->SetMarkerColor(kGreen+2);
  
    residual_vs_ring[2] = new TGraphErrors();
    residual_vs_ring[2]->SetMarkerStyle(20);
    residual_vs_ring[2]->SetMarkerSize(1);
    residual_vs_ring[2]->SetMarkerColor(kGreen+2);

  
  if (evalStat){
    
    /// acquisition file for statistical precision

    TFile *f2 = new TFile(infile2);
    TFile *f3 = new TFile(infile3);
    TH2F *hcmap2[2];
    hcmap2[0] = (TH2F*)f2->Get("h_scale_map_EEM"); 
    hcmap2[1] = (TH2F*)f2->Get("h_scale_map_EEP");

    TH2F *hcmap3[2];
    hcmap3[0] = (TH2F*)f3->Get("h_scale_map_EEM"); 
    hcmap3[1] = (TH2F*)f3->Get("h_scale_map_EEP");

    TH1F *hstatprecision[2][40];
    TH1F *hstatprecisionAll[40];

    /// stat precision histos for each EE ring
    for (int k = 0; k < 2; k++){
      for (int iring = 0; iring < 40 ; iring ++){
      
	if (k==0)
	 { sprintf(hname,"hstatprecisionAll_ring%02d",iring);
           hstatprecisionAll[iring] = new TH1F(hname, hname, nbins,-2.,2.);
           sprintf(hname,"hstatprecisionEEM_ring%02d",iring);
           hstatprecision[k][iring] = new TH1F(hname, hname, nbins,-2.,2.);
          }
	else {
	      sprintf(hname,"hstatprecisionEEP_ring%02d",iring);
              hstatprecision[k][iring] = new TH1F(hname, hname, nbins,-2.,2.);
            }

      }
    }
    
    for (int k = 0; k < 2 ; k++){
      for (int ix = 1; ix < 102; ix++){
	for (int iy = 1; iy < 102; iy++){
	  int iz = k;
	  if (k==0) iz = -1;
	  int mybin = hcmap2[k] -> FindBin(ix,iy);
	  int ring  = hrings[1]-> GetBinContent(mybin);
	  float ic1 = hcmap2[k]->GetBinContent(mybin);
	  float ic2 = hcmap3[k]->GetBinContent(mybin);
          if (ic1>0 && ic2 >0){
	    hstatprecision[k][ring]->Fill((ic1-ic2)/(ic1+ic2)); /// sigma (diff/sum) gives the stat. precision on teh entire sample
            hstatprecisionAll[ring]->Fill((ic1-ic2)/(ic1+ic2));
	  }
	}
      }
    }

  
    TCanvas* c44 [120];
    /// Gaussian fit of the even/odd distribution (rms of the distribution can be also used)
    int n[3] = {0};
    for (int k = 0; k < 2; k++){
      for (int iring = 0; iring < 40 ; iring++){
	if ( hstatprecision[k][iring]->GetEntries() == 0) continue;
	float e     = 0.5*hcmap2[k]-> GetYaxis()->GetBinWidth(1);
	fgaus->SetParameter(1,1);
	fgaus->SetParameter(2,hstatprecision[k][iring]->GetRMS());
	fgaus->SetRange(-5*hstatprecision[k][iring]->GetRMS(),5*hstatprecision[k][iring]->GetRMS());
	TString name = Form("ff%d_%d",iring,k);

        hstatprecision[k][iring]->Fit("fgaus","QR");
       
	statprecision_vs_ring[k]-> SetPoint(n[k],iring,fgaus->GetParameter(2));
	statprecision_vs_ring[k]-> SetPointError(n[k],e,fgaus->GetParError(2));
	n[k]++;
      }
    }
    
    for (int iring = 0; iring < 40 ; iring++){
	if ( hstatprecisionAll[iring]->GetEntries() == 0) continue;
	float e     = 0.5*hcmap2[0]-> GetYaxis()->GetBinWidth(1);
	fgaus->SetParameter(1,1);
	fgaus->SetParameter(2,hstatprecisionAll[iring]->GetRMS());
	fgaus->SetRange(-5*hstatprecisionAll[iring]->GetRMS(),5*hstatprecisionAll[iring]->GetRMS());
	TString name = Form("ffAll%d",iring);
        hstatprecisionAll[iring]->Fit("fgaus","QR");
       
	statprecision_vs_ring[2]-> SetPoint(n[2],iring,fgaus->GetParameter(2));
	statprecision_vs_ring[2]-> SetPointError(n[2],e,fgaus->GetParError(2));
	n[2]++;
      }
     
    
    TH1F *hresidual[3];
    hresidual[0] = new TH1F("hresidualEEM","hresidualEEM",1000,0,1);
    hresidual[1] = new TH1F("hresidualEEP","hresidualEEP",1000,0,1);
    hresidual[2] = new TH1F("hresidualAll","hresidualAll",1000,0,1);

    TH1F *hstat[3];
    hstat[0] = new TH1F("hstatEEM","hstatEEM",1000,0,0.5);
    hstat[1] = new TH1F("hstatEEP","hstatEEP",1000,0,0.5);
    hstat[2] = new TH1F("hstatAll","hstatAll",1000,0,0.5);
   
    TH1F *hspre[3];
    hspre[0] = new TH1F("hspreEEM","hspreEEM",1000,0,0.5);
    hspre[1] = new TH1F("hspreEEP","hspreEEP",1000,0,0.5);
    hspre[2] = new TH1F("hspreAll","hspreAll",1000,0,0.5);

    /// Residual spread plot

    for (int k = 0; k < 3 ; k++){
      for (int i= 0; i < statprecision_vs_ring[k]-> GetN(); i++){
	double spread, espread;
	double stat, estat;
	double residual, eresidual;
	double xdummy,ex;
	sigma_vs_ring[k]-> GetPoint(i, xdummy, spread );
	espread = sigma_vs_ring[k]-> GetErrorY(i);
	statprecision_vs_ring[k]-> GetPoint(i, xdummy, stat );
	estat = statprecision_vs_ring[k]-> GetErrorY(i);
	ex = statprecision_vs_ring[k]-> GetErrorX(i);
	if (spread > stat ){
	  residual  = sqrt( spread*spread - stat*stat );
	  eresidual = sqrt( pow(spread*espread,2) + pow(stat*estat,2))/residual;
	}
	else {
	  residual = 0;
	  eresidual = 0;
	}
	residual_vs_ring[k]->SetPoint(i,xdummy, residual);
	residual_vs_ring[k]->SetPointError(i,ex,eresidual);
      }
    }
 
 }
  
  ///-----------------------------------------------------------------
  ///--- Draw plots
  ///-----------------------------------------------------------------
  TCanvas *cEEP[12];
  TCanvas *cEEM[12];

  /// --- plot 0 : map of coefficients 
  cEEP[0] = new TCanvas("cmapEEP","cmapEEP");
  cEEP[0] -> cd();
  cEEP[0]->SetLeftMargin(0.1); 
  cEEP[0]->SetRightMargin(0.13); 
  cEEP[0]->SetGridx();
  cEEP[0]->SetGridy();
  //  hcmap[1]->GetXaxis()->SetNdivisions(1020);
  hcmap[1]->GetXaxis() -> SetLabelSize(0.03);
  hcmap[1]->Draw("COLZ");
  hcmap[1]->GetXaxis() ->SetTitle("ix");
  hcmap[1]->GetYaxis() ->SetTitle("iy");
  hcmap[1]->GetZaxis() ->SetRangeUser(0.8,1.2);

  cEEM[0] = new TCanvas("cmapEEM","cmapEEM");
  cEEM[0] -> cd();
  cEEM[0]->SetLeftMargin(0.1); 
  cEEM[0]->SetRightMargin(0.13); 
  cEEM[0]->SetGridx();
  cEEM[0]->SetGridy();
  //hcmap[0]->GetXaxis()->SetNdivisions(1020);
  hcmap[0]->GetXaxis() -> SetLabelSize(0.03);
  hcmap[0]->Draw("COLZ");
  hcmap[0]->GetXaxis() ->SetTitle("ix");
  hcmap[0]->GetYaxis() ->SetTitle("iy");
  hcmap[0]->GetZaxis() ->SetRangeUser(0.8,1.2);

  /// --- plot 1 : ring precision vs ieta
  cEEP[1] = new TCanvas("csigmaEEP","csigmaEEP");
  cEEP[1]->SetGridx();
  cEEP[1]->SetGridy();
  sigma_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
  sigma_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("ring");
  sigma_vs_ring[1]->Draw("ap");
  if (evalStat){
    statprecision_vs_ring[1]->Draw("psame");
    sigma_vs_ring[1]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[1],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[1],"spread", "LP");
    leg->Draw("same");
  }

  cEEM[1] = new TCanvas("csigmaEEM","csigmaEEM");
  cEEM[1]->SetGridx();
  cEEM[1]->SetGridy();
  sigma_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
  sigma_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("ring");
  sigma_vs_ring[0]->Draw("ap");
  if (evalStat){
    statprecision_vs_ring[0]->Draw("psame");
    sigma_vs_ring[0]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[0],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[0],"spread", "LP");
    leg->Draw("same");
  }


  /// --- plot 5 : statistical precision vs ieta
  if (evalStat){
    cEEP[5] = new TCanvas("cstat","cstat");
    cEEP[5]->SetGridx();
    cEEP[5]->SetGridy();
    statprecision_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    statprecision_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    statprecision_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
    statprecision_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    statprecision_vs_ring[1]->Draw("ap");
    
    cEEP[6] = new TCanvas("cresidualP","cresidualP");
    cEEP[6]->SetGridx();
    cEEP[6]->SetGridy();
    residual_vs_ring[1]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[1]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[1]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[1]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[1]->Draw("ap");
 
    cEEM[5] = new TCanvas("cstatM","cstatM");
    cEEM[5]->SetGridx();
    cEEM[5]->SetGridy();
    statprecision_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    statprecision_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    statprecision_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
    statprecision_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    statprecision_vs_ring[0]->Draw("ap");
    
    cEEM[6] = new TCanvas("cresidualM","cresidualM");
    cEEM[6]->SetGridx();
    cEEM[6]->SetGridy();
    residual_vs_ring[0]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[0]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[0]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[0]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[0]->Draw("ap");
 
    cEEP[8] = new TCanvas("csigmaFolded","csigmaFolded");
    cEEP[8]->SetGridx();
    cEEP[8]->SetGridy();
    sigma_vs_ring[2]->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.20);
    sigma_vs_ring[2]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    sigma_vs_ring[2]->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
    sigma_vs_ring[2]->GetHistogram()->GetXaxis()-> SetTitle("ring");
    sigma_vs_ring[2]->Draw("ap");
    if (evalStat){
    statprecision_vs_ring[2]->Draw("psame");
    sigma_vs_ring[2]->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ring[2],"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ring[2],"spread", "LP");
    leg->Draw("same");
    }

    cEEP[9] = new TCanvas("cresidualFolded","cresidualFolded");
    cEEP[9]->SetGridx();
    cEEP[9]->SetGridy();
    residual_vs_ring[2]->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
    residual_vs_ring[2]->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
    residual_vs_ring[2]->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
    residual_vs_ring[2]->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
    residual_vs_ring[2]->Draw("ap");

    /// save precision for MC comparison

    if(isMC==true)
    {
     TFile * output = new TFile ("StatPrec_MC_EE.root","RECREATE");
     output->cd();
     statprecision_vs_ring[0]->SetName("gr_stat_prec_EEP");
     statprecision_vs_ring[1]->SetName("gr_stat_prec_EEM");
     statprecision_vs_ring[2]->SetName("gr_stat_prec");

     statprecision_vs_ring[0]->Write();
     statprecision_vs_ring[1]->Write();
     statprecision_vs_ring[2]->Write();
    }
  }
 
  /// Comparison Plot MC - Data
  TCanvas* canEEP[10], *canEEM[10];
  if(isMC == true)
  {
 
   canEEM[0] = new TCanvas("ICComparison MC EEM","ICComparison MC EEM");
   canEEM[0]->SetGridx();
   canEEM[0]->SetGridy();
   ICComparison[0]->GetXaxis() -> SetLabelSize(0.03);
   ICComparison[0]->Draw("COLZ");
   ICComparison[0]->GetXaxis() ->SetTitle("ix");
   ICComparison[0]->GetYaxis() ->SetTitle("iy");
   ICComparison[0]->GetZaxis() ->SetRangeUser(0.85,1.15);
 
   canEEP[0] = new TCanvas("ICComparison MC EEP","ICComparison MC EEP");
   canEEP[0]->SetGridx();
   canEEP[0]->SetGridy();
   ICComparison[1]->GetXaxis() -> SetLabelSize(0.03);
   ICComparison[1]->Draw("COLZ");
   ICComparison[1]->GetXaxis() ->SetTitle("ix");
   ICComparison[1]->GetYaxis() ->SetTitle("iy");
   ICComparison[1]->GetZaxis() ->SetRangeUser(0.85,1.15);

   TFile* output = new TFile ("IC_MC_4Correction.root","RECREATE");
   output->cd();
   ICComparison[0]->Write();
   ICComparison[1]->Write();
   output->Close();
  }

  TFile *exisistingEE = new TFile ("existingEE.root","READ");
  TH2F* exmap = (TH2F*) exisistingEE->Get("endcap");

  TH2F* warning_Map_EEP = (TH2F*) exmap->Clone("warning_Map_EEP");
  warning_Map_EEP->Reset("ICMES");
  warning_Map_EEP->Reset();

  TH2F* warning_Map_EEM = (TH2F*) exmap->Clone("warning_Map_EEM");
  warning_Map_EEM->Reset("ICMES");
  warning_Map_EEM->Reset();


  if(isMC == false)
  {
   std::ofstream outTxt ("Calibration_Coefficient_EE_dinamic_alpha.txt",std::ios::out);

   outTxt << "---------------------------------------------------------------" << std::endl;
   outTxt << std::fixed << std::setprecision(0) << std::setw(10) << "iX"
          << std::fixed << std::setprecision(0) << std::setw(10) << "iY"
          << std::fixed << std::setprecision(0) << std::setw(10) << "iZ"
          << std::fixed << std::setprecision(6) << std::setw(15) << "IC"
          << std::fixed << std::setprecision(6) << std::setw(15) << "error"
          << std::endl;
   outTxt << "---------------------------------------------------------------" << std::endl;

   for (int ix = 1; ix < hcmap[0]->GetNbinsX()+1 ; ix ++)
     {
       for (int iy = 1; iy < hcmap[0] -> GetNbinsY()+1; iy++)
	 {
	   if( exmap->GetBinContent(ix,iy) !=1) continue;
	   
	   double x,statPrec;
	   statprecision_vs_ring[0]->GetPoint(hrings[0]->GetBinContent(ix,iy),x,statPrec);
	   
	   outTxt << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[0]->GetXaxis()->GetBinLowEdge(ix)
		  << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[0]->GetYaxis()->GetBinLowEdge(iy)
		  << std::fixed << std::setprecision(0) << std::setw(10) << "-1";
	   
	   if( hcmap[0]->GetBinContent(ix,iy) == 0. )
	     {  
               outTxt << std::fixed << std::setprecision(6) << std::setw(15) << "-1."
                      << std::fixed << std::setprecision(6) << std::setw(15) << "999."
                      << std::endl;
	     }
	   else
	     {
	       outTxt << std::fixed << std::setprecision(6) << std::setw(15) << hcmap[0]->GetBinContent(ix,iy)
		      << std::fixed << std::setprecision(6) << std::setw(15) << statPrec
		      << std::endl;
	       
	       //warning_Map_EEM->Fill(ix,iy);
	     }
	  
	}
    }
    
    for (int ix = 1; ix < hcmap[1]->GetNbinsX()+1 ; ix ++)
      {
	for (int iy = 1; iy < hcmap[1] -> GetNbinsY()+1; iy++)
	  {
	    if( exmap->GetBinContent(ix,iy) !=1) continue;
	    
	    double x,statPrec;
	    statprecision_vs_ring[1]->GetPoint(hrings[1]->GetBinContent(ix,iy),x,statPrec);
	    
	    outTxt << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[1]->GetXaxis()->GetBinLowEdge(ix)
		   << std::fixed << std::setprecision(0) << std::setw(10) << hcmap[1]->GetYaxis()->GetBinLowEdge(iy)
		   << std::fixed << std::setprecision(0) << std::setw(10) << "1";
	    
	    if( hcmap[1]->GetBinContent(ix,iy) == 0. )
	      {
		outTxt << std::fixed << std::setprecision(6) << std::setw(15) << "-1."
		       << std::fixed << std::setprecision(6) << std::setw(15) << "999."
		       << std::endl;
	      }
	    else
	      {
		outTxt << std::fixed << std::setprecision(6) << std::setw(15) << hcmap[1]->GetBinContent(ix,iy)
		       << std::fixed << std::setprecision(6) << std::setw(15) << statPrec
		       << std::endl;
		
		//warning_Map_EEM->Fill(ix,iy);                                                                                                                               
	      }
	    
	  }
      }
  }
  
  
  canEEP[1] = new TCanvas("Warning_EEP","Warning_EEP");
  canEEP[1]->SetGridx();
  canEEP[1]->SetGridy();
  warning_Map_EEP->GetXaxis() -> SetLabelSize(0.03);
  warning_Map_EEP->Draw("COLZ");
  warning_Map_EEP->GetXaxis() ->SetTitle("ix");
  warning_Map_EEP->GetYaxis() ->SetTitle("iy");
  warning_Map_EEP->GetZaxis() ->SetRangeUser(0.85,1.15);

  canEEM[1] = new TCanvas("Warning_EEM","Warning_EEM");
  canEEM[1]->SetGridx();
  canEEM[1]->SetGridy();
  warning_Map_EEM->GetXaxis() -> SetLabelSize(0.03);
  warning_Map_EEM->Draw("COLZ");
  warning_Map_EEM->GetXaxis() ->SetTitle("ix");
  warning_Map_EEM->GetYaxis() ->SetTitle("iy");
  warning_Map_EEM->GetZaxis() ->SetRangeUser(0.85,1.15);



}
void makeErrorTemplatesPtSyst(TString channel="2e2mu") { 
    
  systSources[0][0] = "Resummation";
  systSources[0][1] = "TopMass";
  systSources[0][2] = "Mela";
  
  systSources[1][0] = "PDF-VBF";
  systSources[1][1] = "scale-VBF";
  systSources[1][2] = "Mela";
  
  systSources[5][0] = "SingleZ";
  systSources[5][1] = "PDF-ZZ";
  systSources[5][2] = "scale-ZZ";
  systSources[5][3] = "Mela"; 
 
  systSources[2][0] = "NLOLO_WH";
  systSources[3][0] = "NLOLO_ZH";

  TString aLongString;
  char fileName[200];
  char fileName2[200];

  //  for (Int_t lhc=8; lhc<9; lhc++) {
  for (Int_t lhc=7; lhc<9; lhc++) {
    for (Int_t k=0; k<nsamp; k++) {

      TString lhcs = "7";
      if (lhc==8) lhcs="8";
 
      aLongString = destDir + "/" + whichVar + "_" + dataFileNames[k] + /* "_" + channel*/ + "_TEMPL_"+ lhcs + "TeV.root";  
      TFile* ftemp = new TFile(aLongString,"UPDATE");
      
      TString whichVar2 = whichVar;
      whichVar2.ToLower();
      sprintf(fileName,"%sH_Default",whichVar2.Data());
      cout << aLongString << " " << fileName << endl;
      TH2F* baseHist = (TH2F*)ftemp->Get(fileName);
      cout << "Histo found OK " << ftemp << " " << baseHist << endl;

      TH2F* upHist = (TH2F*)baseHist->Clone();
      TH2F* downHist = (TH2F*)baseHist->Clone();

      //MC stats
      for (int i=1; i<=baseHist->GetNbinsX(); i++) { 
	for (int j=1; j<=baseHist->GetNbinsY(); j++) {
	  upHist->SetBinContent(i,j,(baseHist->GetBinError(i,j))*(baseHist->GetBinError(i,j)));
	  downHist->SetBinContent(i,j,(baseHist->GetBinError(i,j))*(baseHist->GetBinError(i,j)));
	}
      }
      cout << "Errors filled OK" << endl;
      cout << dataFileNames[k] << " entries " << baseHist->GetBinContent(100,10) << " "  << upHist->GetBinContent(100,10) << " " << downHist->GetBinContent(100,10) << endl ;

      //Other systs
      for (int ss = 0; ss < 5; ss++) {
	if (systSources[k][ss] != "") {

	  TH2F* thisHistUp;
	  TH2F* thisHistDown;

	  if (systSources[k][ss] == "Resummation") {
	    sprintf(fileName,"%sH_ResummationUp",whichVar2.Data());
            sprintf(fileName2,"%sH_ResummationDown",whichVar2.Data());
	  } else if (systSources[k][ss] == "Mela") {
            sprintf(fileName2,"%sH_Mela00-03",whichVar2.Data());
            sprintf(fileName,"%sH_Mela06-10",whichVar2.Data());
          } else {
	    sprintf(fileName,"%sH_%s",whichVar2.Data(),systSources[k][ss].Data());
	    sprintf(fileName2,"%sH_%s",whichVar2.Data(),systSources[k][ss].Data());  
	  }
	  thisHistUp = (TH2F*)((TH2F*)ftemp->Get(fileName))->Clone();
          cout << "Histo up found OK" << endl;
          thisHistDown = (TH2F*)((TH2F*)ftemp->Get(fileName2))->Clone();
          cout << "Histo down found OK" << endl;

	  for (int i=1; i<=baseHist->GetNbinsX(); i++) { 
	    for (int j=1; j<=baseHist->GetNbinsY(); j++) {
	      float upval = upHist->GetBinContent(i,j) + pow(thisHistUp->GetBinContent(i,j)-baseHist->GetBinContent(i,j),2);
	      float downval = upHist->GetBinContent(i,j) + pow(thisHistDown->GetBinContent(i,j)-baseHist->GetBinContent(i,j),2);
	      upHist->SetBinContent(i,j,upval);
	      downHist->SetBinContent(i,j,downval);
	    }
	  }

          if (k == 6) cout << "zx entries after syst " << systSources[k][ss] << " " << upHist->GetBinContent(100,10) << " " << downHist->GetBinContent(100,10) << endl;
	}
      }

      // Subtract or add
      for (int i=1; i<=baseHist->GetNbinsX(); i++) { 
	for (int j=1; j<=baseHist->GetNbinsY(); j++) {
	  float upval = baseHist->GetBinContent(i,j) + sqrt(upHist->GetBinContent(i,j));
          float downval = baseHist->GetBinContent(i,j) - sqrt(downHist->GetBinContent(i,j));
	  upHist->SetBinContent(i,j,upval);
	  downHist->SetBinContent(i,j,downval);
	}
      }

      if (k == 6 && lhc == 8) cout << "zx entries after sqrt " << baseHist->GetBinContent(100,10) << " " << upHist->GetBinContent(100,10) << " " << downHist->GetBinContent(100,10) << endl;

      ftemp->cd();
      upHist->SetName(whichVar2 + "H_TotalUp");
      adjustHistogram(upHist);
      upHist->Write();
      downHist->SetName(whichVar2 + "H_TotalDown");
      adjustHistogram(downHist); 
      downHist->Write();
    }      
  }
  return;
}
Exemple #16
0
void CCDimage14(int firstrun, int lastrun)
{
  gStyle->SetPalette(1,0); 
  gSystem->Load("libMaxCam");
  gSystem->Load("libWaveformTools.so");

  std::stringstream sstm;

  TH2F * sum = 0; 
  TH2I * count = 0;
  TH2F * p=0;
         sum = new TH2F("alpha_sum","alpha_sum",256,0,1024,256,0,1024); 
        count = new TH2I("alpha_count","alpha_count",256,0,1024,256,0,1024);
  const int c = 0;
 
  gROOT->cd(); 

  int runnum;
  int setnum;
  
    if		(firstrun>=889 && lastrun<=954)		{setnum=0;}
    else if	(firstrun>=955 && lastrun<=3868)	{setnum=1;}
    else if	(firstrun>=3876 && lastrun<=5789)	{setnum=2;}
	else if	(firstrun>=5792)					{setnum=3;}
	else
	{
	gApplication->Terminate();
	exit;}
  
  
for (int x = firstrun; x <= lastrun; x++){
	runnum=x;
	
       string origfile = "/net/nudsk0001/d00/scratch/dctpc_tmp/bigdctpc_data/BigDCTPC_run_";
       string skimfile = "/net/nudsk0001/d00/scratch/dctpc_tmp/bigdctpc_skim/BigDCTPC_run_";  
      
//            string origfile = "/net/hisrv0001/home/spitzj/myOutput_";
//      string skimfile = "/net/hisrv0001/home/spitzj//myOutput_";
      
      string skimend = "skim.root";
      string origend = ".root";
      string origfilename;
      string skimfilename;
      sstm.str("");
      if (x<10000){ origfile+="0"; skimfile+="0"; }
      if (x<1000){ origfile+="0"; skimfile+="0"; }
      if (x<100){ origfile+="0"; skimfile+="0"; }
      if (x<10){ origfile+="0"; skimfile+="0"; }
      sstm << origfile << x << origend;
      origfilename = sstm.str();
      sstm.str("");
      sstm << skimfile << x << skimend;
      skimfilename = sstm.str();
      cout << origfilename << endl;
      ifstream ifile(origfilename.c_str());
      ifstream ifile2(skimfilename.c_str());
      if(!ifile)
	  continue;
      if(!ifile2)
	continue;
  	DmtpcSkimDataset d;
  	d.openRootFile(skimfilename.c_str());    
  	d.loadDmtpcEvent(true,origfilename.c_str());
  	for (int i = 0; i < d.nevents(); i ++){
        if(i%100==0){
			cout<<"Event: "<<i<<endl;
		}

	//cout<<"here"<<endl
    d.getEvent(i);    
    //cout<<"here2"<<endl;
    for (int t =0 ; t < d.event()->ntracks(c); t++)
    {
      if(d.event()->maxpixel(0,t)>150){continue;}
      if(d.event()->spark(0)){continue;} 
      p = (TH2F*)d.event()->cluster(c)->getImage(); 
      vector<int> clust = d.event()->cluster(c)->getCluster(t); 
     
    	for (vector<int>::iterator it = clust.begin(); it!=clust.end(); it++)
		{
	  		sum->SetBinContent(*it, sum->GetArray()[*it] + p->GetArray()[*it]);
	  		count->SetBinContent(*it, count->GetArray()[*it] + 1); 
		}    
    }
  }
 }

  TH2F * normalized = (TH2F*) sum->Clone("normalized"); 
  normalized->SetName("normalized");
  normalized->Divide(count); 
  normalized->SetStats(0);
  normalized->Draw("COLZ");
  c1->Print(Form("CCDimage14_set_%d_runs_%d_%d.pdf",setnum,firstrun,lastrun));

  TFile *f=new TFile(Form("CCDimage14_set_%d_runs_%d_%d.root",setnum,firstrun,lastrun),"RECREATE");
  normalized->Write();
  f->Close();

  gApplication->Terminate();
}
Exemple #17
0
void Ex(){
  /*
  TRandom r1; 
  
  TH2F *his2 = new TH2F("his2","2d histogram",100,0,100,100,0,100);
  
  srand(123456);

  for(int i = 0; i < 10000; i++) his2->Fill(r1.Gaus(10,3),r1.Gaus(10,3));
  for(int i = 0; i < 10000; i++){
    double x = 4 + 100*(rand() % 1000)/1000.0; 

       his2->Fill(x, r1.Gaus(x,60/x));
   
       // x = 100*(rand() % 1000)/1000.0; 

       // his2->Fill(x, r1.Gaus(x,6*x));
    
  }

  for(int i = 0; i < 100; i++) his2->Fill(r1.Gaus(50,50),r1.Gaus(50,50));


  TCanvas *c4 = new TCanvas ("c4","",600,600);

  c4->cd();
  his2->Draw("colz");
  c4->SaveAs("TheINit.png");

  */
  

  
  TFile *f1 = new TFile("../../../CutTMVABarrel_ALeff.root");
  float genPt,ppt,peta,Sie_ie,iso_P,iso_C,iso_N,to_e,weighT;
  int nvtx;
  gStyle->SetOptStat(0);

  //Signal Tree                                                                        
  t_S->SetBranchAddress("Sieie",&Sie_ie);
  t_S->SetBranchAddress("isoP",&iso_P);
  t_S->SetBranchAddress("isoC",&iso_C);
  t_S->SetBranchAddress("isoN",&iso_N);
  t_S->SetBranchAddress("ToE",&to_e);
  t_S->SetBranchAddress("weighT",&weighT);

  t_S->SetBranchAddress("Nvtx",&nvtx);
  t_S->SetBranchAddress("Peta",&peta);
  t_S->SetBranchAddress("Ppt",&ppt);
  t_S->SetBranchAddress("genPt",&genPt);

  //Background Tree                                                                    
  t_B->SetBranchAddress("Sieie",&Sie_ie);
  t_B->SetBranchAddress("isoP",&iso_P);
  t_B->SetBranchAddress("isoC",&iso_C);
  t_B->SetBranchAddress("isoN",&iso_N);
  t_B->SetBranchAddress("ToE",&to_e);
  t_B->SetBranchAddress("weighT",&weighT);

  t_B->SetBranchAddress("Nvtx",&nvtx);
  t_B->SetBranchAddress("Peta",&peta);
  t_B->SetBranchAddress("Ppt",&ppt);

  double bins_l[67] = {0};
  for(int i = 0; i < 67 ; i++){

    if(i <= 50) bins_l[i] = i*2;
    if(i > 50  && i <= 55 ) bins_l[i] = 100 + (i - 50)*10;
    if(i > 55  && i < 60 ) bins_l[i] = 150 + (i - 55)*20;

    if(i >= 60) bins_l[i] = 250.0 + (i - 60.0)*100.0;


    //    cout<<" i: "<<i<<"   "<<bins_l[i]<<endl;

  }




  TH2F *isoNptS = new TH2F("isoNptS","Iso neutral hadrons vs Pt",66,bins_l,500,0,50);

  for(int i  = 0; i < t_S->GetEntries();i++){
    t_S->GetEntry(i);

    if(ppt < 25 ) continue;
    if(iso_N == 0) continue;

    isoNptS->Fill(ppt,iso_N);

  }


  cout<<"Builded the 2d HISTOGRAM"<<endl;
  TH2F *his2 = isoNptS->Clone();
  int dim = his2->GetXaxis()->GetNbins(); 
  double * cutV; 
  double * errVH; 
  double * errVL; 
  double * binc; 
  double * bincerH; 
  double * bincerL; 
  cutV   = new double[dim];
  errVH   = new double[dim];
  errVL   = new double[dim];
  binc   = new double[dim]; 
  bincerH = new double[dim];
  bincerL = new double[dim];
  
  for(int i  = 1; i < dim ; i++){
    double xval = 0; 
    double errXH = 0; 
    double errXL = 0; 
    
    r22 = his2->ProjectionY(" ",i,i+1," ");
    
    TH1F *h1 = r22->Clone();
    ErrCalc(h1,i,0.950,xval,errXL,errXH);
    
    cout<<"bin :"<<i<<" "<<xval<<"-"<<errXL<<"+ " << errXH<<endl;
    
    cutV[i-1]   = xval; 
    
    errVL[i-1]   = errXL; 
    errVH[i-1]   = errXH;
    
    binc[i-1] = his2->GetXaxis()->GetBinCenter(i);
    bincerL[i-1] = 0;
    bincerH[i-1] = 0;
  }
  TGraphAsymmErrors * IsoptScaling = new TGraphAsymmErrors(dim,binc,cutV,bincerL,bincerH,errVL,errVH);

  // double DownL = his2->GetXaxis()->GetBinCenter(1);
  //double UpperL = his2->GetXaxis()->GetBinCenter(dim);
  
  TF1 *fn1 = new TF1("fn1","exp([0]*x + [1])",25,600);

  IsoptScaling->Fit("fn1","R");

  

  gStyle->SetOptFit(1);
  
  TCanvas *c3 = new TCanvas("c3","Iso Pt",1200,600);
  c3->Divide(2,1);
  
  c3->cd(1);
  IsoptScaling->SetMarkerStyle(24); 
  IsoptScaling->SetMarkerSize(0.4);
  IsoptScaling->Draw("AP");
  IsoptScaling->GetXaxis()->SetTitle("Photon Pt GeVc^{-1}");
  IsoptScaling->GetYaxis()->SetTitle("Isolation Contour ");
  c3->cd(2); 
  his2->Draw("colz");
  his2->GetXaxis()->SetTitle("Photon Pt GeVc^{-1}");
  his2->GetYaxis()->SetTitle("Isolation PF::h ");

  c3->SaveAs("final.png");

  //lets fit this graph
  


}
void makeValidationPlots(TTree* tree, sel_t type,bool isMC) {

  SelectionStrings strings;

  TString tag="";

  TString lowString="",midString="",highString="";

  switch(type) {
  case kReal:
    tag = "_realselection";
    break;
  case kShift:
    tag = "_side";
    break;
  case kSingleIso:
    tag = "_singleIso";
    break;
  }
  if(isMC) {
    tag+="__DiPhotonJets";
  }
  Double_t Red[] = {0.00, 0.70, 0.90, 1.00, 1.00, 1.00, 1.00};
  Double_t Green[] ={0.00, 0.70, 0.90, 1.00, 0.90, 0.70, 0.00};
  Double_t Blue[] = {1.00, 1.00, 1.00, 1.00, 0.90, 0.70, 0.00};
  Double_t Length[] =  {0.00, 0.20, 0.35, 0.50, 0.65, 0.8, 1.00};

  TCanvas cv;

  std::vector<TH2F*> nSigs;
  std::vector<TH2F*> nSigs_gauss;

  cv.SetLogx();
  for(int iBox=0; iBox<SigRegionBinning::nBoxes; iBox++) {
    TString boxName = SigRegionBinning::getRegionName(static_cast<SigRegionBinning::BinningRegion>(iBox));
    switch(type) {
    case kReal:
      lowString = strings.baseSelection+" && mgg>103 && mgg<120";
      midString = strings.baseSelection+" && "+strings.mggSigRegion[iBox];
      highString = strings.baseSelection+" && mgg>131 && mgg<160";
      break;
    case kShift:
      lowString = strings.baseSelection+" && mgg>130 && mgg<140";
      midString = strings.baseSelection+" && mgg>140 && mgg<150";
      highString = strings.baseSelection+" && mgg>150 && mgg<160";
      break;
    case kSingleIso:
      lowString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && mgg>103 && mgg<120";
      midString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && "+strings.mggSigRegion[iBox];
      highString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && mgg>131 && mgg<160";      
      break;
    }


    TH2F* low = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"low");
    TH2F* mid = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"mid");
    TH2F* high = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"high");
  
    TH2F* nsig = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"nsig_"+boxName);
    TH2F* nsig_gauss = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"nsig_gauss_"+boxName);

    low->SetMinimum(0.1);
    mid->SetMinimum(0.1);
    high->SetMinimum(0.1);

    tree->Project("low","Rsq:MR",lowString+" && "+strings.boxDefs[iBox]);
    tree->Project("mid","Rsq:MR",midString+" && "+strings.boxDefs[iBox]);
    tree->Project("high","Rsq:MR",highString+" && "+strings.boxDefs[iBox]);

    //SigRegionBinning::formatSigRegionPlot(low);
    //SigRegionBinning::formatSigRegionPlot(mid);
    //SigRegionBinning::formatSigRegionPlot(high);

    //get the difference in the prediction
    TH2F* low_norm = (TH2F*)low->Clone("low_norm");
    TH2F* high_norm = (TH2F*)high->Clone("high_norm");

    low_norm->Scale(1./low_norm->Integral());
    high_norm->Scale(1./high_norm->Integral());

    TH2F* pred_diff = (TH2F*)high_norm->Clone("pred_diff");
    pred_diff->Add(low_norm,-1);

    TH2F* norm_av = (TH2F*)low_norm->Clone("norm_av");
    norm_av->Add(high_norm);
    norm_av->Scale(0.5);

    TH2F* pred_per_diff = (TH2F*)pred_diff->Clone("pred_per_diff");
    pred_per_diff->Divide(norm_av);
    cv.SetLogx(1);
    cv.SetLogy(0);
    pred_per_diff->Draw("COLZ TEXT");
    cv.SaveAs("RsqMR_high_minus_low_div_av_"+boxName+tag+".png");
    cv.SetLogx(1);
    cv.SetLogy(0);

    TH1D* low_1D = SigRegionBinning::make1DProj(low);
    TH1D* high_1D = SigRegionBinning::make1DProj(high);
    
    pred_per_diff->SetYTitle("high - low / (high+low/2)");
    TH1D* pred_per_diff_1D = SigRegionBinning::make1DProj(pred_per_diff);
    cv.SetLogx(0);
    cv.SetLogy(0);
    pred_per_diff_1D->Draw();
    cv.SaveAs("RsqMR_1D_high_minus_low_div_av_"+boxName+tag+".png");
    cv.SetLogx(1);
    cv.SetLogy(0);
    
    TFile out("RsqMR_1D_high_minus_low_div_av_"+boxName+tag+".root","RECREATE");
    low->Write();
    high->Write();
    low_1D->Write();
    high_1D->Write();
    pred_per_diff_1D->Write();
    pred_per_diff->Write();
    out.Close();



    TH2F* sideband_tot = (TH2F*)low->Clone("sideband_tot");
    sideband_tot->Add(high);


    sideband_tot->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_low_plus_high_"+boxName+tag+".png");
    cv.SetLogz(0);

    float sf = mid->Integral()/sideband_tot->Integral();
    std::cout << "sf: " << sf << std::endl;
    TH2F* sideband_pred = (TH2F*)sideband_tot->Clone("sideband_pred");

    sideband_pred->Scale(sf);

    sideband_pred->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_sideband_pred_"+boxName+tag+".png");
    cv.SetLogz(0);

    mid->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_mid_"+boxName+tag+".png");
    cv.SetLogz(0);

    TH1D* pred_1D = SigRegionBinning::make1DProj(sideband_pred,true,sf);
    TH1D* mid_1D  = SigRegionBinning::make1DProj(mid);
    cv.SetLogx(0);
    cv.SetLogy();
    mid_1D->SetMarkerStyle(20);
    mid_1D->SetMarkerColor(kBlack);
    mid_1D->SetMarkerSize(1.4);

    pred_1D->SetFillColor(kRed);
    pred_1D->SetFillStyle(3001);
    pred_1D->SetLineColor(kRed);
    pred_1D->SetLineWidth(2);
    pred_1D->SetMarkerSize(0);
    pred_1D->Draw("L E2");
    pred_1D->Draw("LSAME");
    mid_1D->Draw("PSAME");
    cv.SaveAs("RsqMR_1D_obs_sideband_pred_"+boxName+tag+".png");    
    cv.SetLogx(1);
    cv.SetLogy(0);


    TH2F* perdiff = (TH2F*)mid->Clone("perdiff");
    perdiff->Add(sideband_pred,-1);
    perdiff->Divide(perdiff);
    perdiff->Draw("COLZ TEXT");

    cv.SaveAs("RsqMR_percentDiff_"+boxName+tag+".png");
    

    for(int iXbin=1; iXbin<=sideband_pred->GetNbinsX(); iXbin++) {
      for(int iYbin=1; iYbin<=sideband_pred->GetNbinsY(); iYbin++) {
	float obs = mid->GetBinContent(iXbin,iYbin);
	float exp = sideband_pred->GetBinContent(iXbin,iYbin);
	float err = TMath::Sqrt(sideband_tot->GetBinContent(iXbin,iYbin))*sf;
	float ns = fabs(TMath::NormQuantile(SigRegionBinning::pValue(obs,exp,err/exp)/2));
	if(obs<exp) ns*=-1;

	nsig->SetBinContent(iXbin,iYbin,ns);
	std::cout << "\t" << iXbin << "  " << iYbin << "  " << nsig->GetBinContent(iXbin,iYbin) << std::endl;

	float gauss_err = TMath::Sqrt(TMath::Power(err,2)+exp);
	if(gauss_err==0) gauss_err=1;
	nsig_gauss->SetBinContent(iXbin,iYbin,(obs-exp)/gauss_err);

      }
    }
    
    SigRegionBinning::formatSigRegionPlot(nsig); 
    SigRegionBinning::formatSigRegionPlot(nsig_gauss); 
    //cv.SetLogx();

    nSigs.push_back(nsig);
    nSigs_gauss.push_back(nsig_gauss);
    

    delete low;
    delete mid;
    delete high;
    delete sideband_tot;
    delete sideband_pred;

  }

  for(int iBox=0; iBox<SigRegionBinning::nBoxes; iBox++) {
    TString boxName = SigRegionBinning::getRegionName(static_cast<SigRegionBinning::BinningRegion>(iBox));
    TColor::CreateGradientColorTable(7,Length,Red,Green,Blue,999);
    TH2F* nsig = nSigs.at(iBox);

    nsig->SetMaximum(5.1);
    nsig->SetMinimum(-5.1);
    nsig->SetContour(999);


    nsig->Draw("COLZ TEXT0");
    cv.SaveAs("RsqMR_low_plus_high_RAWSUM_NSIGMA_"+boxName+tag+".png");
    
    TH2F* nsig_gauss = nSigs_gauss.at(iBox);
    nsig_gauss->SetMaximum(5.1);
    nsig_gauss->SetMinimum(-5.1);
    nsig_gauss->SetContour(999);

    nsig_gauss->Draw("COLZ");
    cv.SaveAs("RsqMR_low_plus_high_RAWSUM_NSIGMAGAUSS_"+boxName+tag+".png");
    

    TH1D* nsig_gauss_1D = SigRegionBinning::make1DProj(nsig_gauss);

    nsig_gauss_1D->SetLineColor(kBlack);
    nsig_gauss_1D->SetLineWidth(1.5);
    nsig_gauss_1D->SetMinimum(-5.1);
    nsig_gauss_1D->SetMaximum(5.1);
    nsig_gauss_1D->SetYTitle("Number of Sigma");
    cv.SetLogx(0);
    cv.SetLogy(0);
    nsig_gauss_1D->Draw();
    cv.SaveAs("RsqMR_low_plus_high_1D_RAWSUM_NSIGMAGAUSS_"+boxName+tag+".png");
    cv.SetLogx(1);
  }
}
Exemple #19
0
void acceptance(const char* file = "upsilonGun.root", const char* outputName = "acceptance.root") {
  Int_t genUpsSize;
  Float_t genUpsPt[NMAX];
  Float_t genUpsEta[NMAX];
  Float_t genUpsPhi[NMAX];
  Float_t genUpsRapidity[NMAX];
  Int_t genMuSize;
  Float_t genMuPt[NMAX];
  Float_t genMuEta[NMAX];
  Float_t genMuPhi[NMAX];
  Int_t genMuCharge[NMAX];
  Int_t recoMuSize;
  Float_t recoMuPt[NMAX];
  Float_t recoMuEta[NMAX];
  Float_t recoMuPhi[NMAX];
  Int_t recoMuCharge[NMAX];

  TFile* f1 = new TFile(file);
  TTree* t = (TTree*)f1->Get("UpsTree");
  t->SetBranchAddress("genUpsSize",&genUpsSize);
  t->SetBranchAddress("genUpsPt",genUpsPt);
  t->SetBranchAddress("genUpsEta",genUpsEta);
  t->SetBranchAddress("genUpsPhi",genUpsPhi);
  t->SetBranchAddress("genUpsRapidity",genUpsRapidity);
  t->SetBranchAddress("genMuSize",&genMuSize);
  t->SetBranchAddress("genMuPt",genMuPt);
  t->SetBranchAddress("genMuEta",genMuEta);
  t->SetBranchAddress("genMuPhi",genMuPhi);
  t->SetBranchAddress("genMuCharge",genMuCharge);
  t->SetBranchAddress("recoMuSize",&recoMuSize);
  t->SetBranchAddress("recoMuPt",recoMuPt);
  t->SetBranchAddress("recoMuEta",recoMuEta);
  t->SetBranchAddress("recoMuPhi",recoMuPhi);
  t->SetBranchAddress("recoMuCharge",recoMuCharge);

  TH2F* genPtRap = new TH2F("genUps","",4,0,20,4,-2,2);
  TH1F* genPt = new TH1F("genUps1D","",4,0,20);
  genPtRap->Sumw2();
  genPt->Sumw2();
  genPtRap->SetTitle(";Upsilon pT (GeV/c);Upsilon Rapidity;");
  genPt->SetTitle(";Upsilon pT (GeV/c);Acceptance;");
  TH2F* recoPtRap = (TH2F*)genPtRap->Clone("recoUps");
  TH1F* recoPt = (TH1F*)genPt->Clone("recoUps1D");
  recoPtRap->Sumw2();
  recoPt->Sumw2();

  for(int i=0; i<t->GetEntries(); i++){
    if(i%100000 == 0)
      std::cout<<i<<std::endl;
    t->GetEntry(i);

    // calculate cosTheta
    TLorentzVector genUps; genUps.SetPtEtaPhiM(genUpsPt[0], genUpsEta[0], genUpsPhi[0], 9.46);
    TLorentzRotation boost(-genUps.BoostVector());
    int mp = genMuCharge[0]>0 ? 0 : 1;
    TLorentzVector genMuPlus; genMuPlus.SetPtEtaPhiM(genMuPt[mp], genMuEta[mp], genMuPhi[mp], 0.106);
    genMuPlus *= boost;
    Float_t cosThetaStar = genMuPlus.Vect().Dot(genUps.Vect())/genMuPlus.Vect().Mag()/genUps.Vect().Mag();

    // set the weight
    Float_t weight = 1;

    genPtRap->Fill( genUpsPt[0], genUpsRapidity[0], weight );
    genPt->Fill( genUpsPt[0], weight );

    Float_t recoUpsPt = 0;
    Float_t recoUpsRapidity = 0;
    double minDeltaM = 1000;
    for(int tr1=0; tr1<recoMuSize; tr1++){
      for(int tr2=tr1+1; tr2<recoMuSize; tr2++){
        if ( recoMuCharge[tr1]*recoMuCharge[tr2] == -1 && recoMuPt[tr1] >= 3.5 && recoMuPt[tr2] >= 3.5 && fabs(recoMuEta[tr1]) < 2.1 && fabs(recoMuEta[tr2]) < 2.1 ){
          TLorentzVector mu1; mu1.SetPtEtaPhiM(recoMuPt[tr1], recoMuEta[tr1], recoMuPhi[tr1], 0.106);
          TLorentzVector mu2; mu2.SetPtEtaPhiM(recoMuPt[tr2], recoMuEta[tr2], recoMuPhi[tr2], 0.106);
          TLorentzVector recoUps(mu1 + mu2);
          double deltaM = fabs(recoUps.M()-9.46);
          if( deltaM < minDeltaM ){
            recoUpsPt = recoUps.Pt();
            recoUpsRapidity = recoUps.Rapidity();
            minDeltaM = deltaM;
          }
        }
      }
    }
    if( minDeltaM < 1.0 ){
      recoPtRap->Fill( recoUpsPt, recoUpsRapidity, weight );
      recoPt->Fill( recoUpsPt, weight );
    }
  }

  TFile out(outputName,"recreate");
  TH2F* acc = (TH2F*)genPtRap->Clone("acceptance");
  TH1F* acc1D = (TH1F*)genPt->Clone("acceptance1D");
  acc->Sumw2();
  acc1D->Sumw2();
  acc->Divide(recoPtRap,genPtRap,1,1,"B");
  acc1D->Divide(recoPt,genPt,1,1,"B");
  acc->Write();
  acc1D->Write();
  out.Close();
}
void makeMuVMassPlot(bool iUseWWType = false) { 
  SetStyle();
  TCanvas *lCan = new TCanvas("A","A",600,600);
  // lCan->SetGridx(1);
  //lCan->SetGridy(1);
  lCan->SetRightMargin(0.14);

  double *lTX1 = new double[2];
  double *lTX2 = new double[2];
  double lMinNLL = 1000;
  double lVMin = 0;
  double *lMin = new double[36];     
  if(!iUseWWType) for(int i0 = 0; i0 < 36; i0++) { lMin[i0] = getMinNLL(110+i0*1.); if(lMin[i0] < lVMin) {lVMin = lMin[i0]; lTX1[0] = 110+i0*1.;}}
  //lMin[17] = (lMin[16]+lMin[18])/2.;
  //lMin[21] = (lMin[20]+lMin[22])/2.;
  //lMin[29] = (lMin[28]+lMin[30])/2.;
  //lMin[34] = (lMin[33]+lMin[35])/2.;

  TFile *lFile = new TFile("/afs/cern.ch/user/p/pharris/public/massscan/cmb+.root");
  TTree *lTree = lFile->FindObjectAny("limit");
  TH2F *lH = new TH2F("2D","2D",36,109.5,145.5,50,-2.,3.);
  float  lNLL  = 0; lTree->SetBranchAddress("nll"     ,&lNLL);
  float  lMNLL = 0; lTree->SetBranchAddress("deltaNLL",&lMNLL);
  double lMH   = 0; lTree->SetBranchAddress("mh"      ,&lMH);
  float  lR    = 0; lTree->SetBranchAddress("r"       ,&lR);
  
  if(iUseWWType) { 
    for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { 
      lTree->GetEntry(i0);
      if(lR < 0.1 && lR > 0)  lMin[int(lMH-110)] = -lMNLL;
    }
    lVMin = 10000;
    for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { 
      lTree->GetEntry(i0);
      double pMin =  lMin[int(lMH-110)] + lMNLL;
      if(pMin < lVMin) lVMin = pMin;
    }
  }
  for(int i0 = 0; i0 < lTree->GetEntries(); i0++) { 
    lTree->GetEntry(i0);
    //if(lMH == 125) continue;
    lNLL = 0.; //lMin  = 0.;
    lH->SetBinContent(lH->GetXaxis()->FindBin(lMH),lH->GetYaxis()->FindBin(lR),(lMNLL+lMin[lH->GetXaxis()->FindBin(lMH)-1]-lVMin)); 
    if(lMH == lTX1[0] && lMNLL < lMinNLL) {lMinNLL = lMNLL; lTX2[0] = lR;}
  }
  TH2F* lHC = lH->Clone("2D_v2");
  double lCont[3];
  lCont[0] = 1.17; 
  lCont[1] = 3.0;
  lCont[2] = 9.0;
  lHC->SetContour(2,lCont);
  //lCan->SetLogz();
  lHC->Draw("cont z list");
  lCan->Update();
  lHC->Draw("colz");

  TObjArray *lContours = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
  int lTotalConts = lContours->GetSize();
  double *lTX = new double[2]; lTX[0] = 110;  lTX[1] = 145; 
  double *lTY = new double[2]; lTY[0] = -0.5; lTY[1] = 2.5;
  TGraph *lFirst = new TGraph(2,lTX,lTY); lFirst->SetLineColor(kWhite);
  lFirst->GetXaxis()->SetRangeUser(110,148);
  lFirst->Draw("al"); lFirst->SetTitle("");
  lH->GetYaxis()->SetRangeUser(-0.5,2.5);
  lFirst->GetXaxis()->SetTitle("m_{H}[GeV]");
  lFirst->GetXaxis()->SetTitleOffset(1.0);
  lFirst->GetYaxis()->SetTitle("#mu_{best-fit}");
  lFirst->GetYaxis()->SetTitleOffset(1.2);

  lH->GetXaxis()->SetTitle("m_{H}[GeV]");
  lH->GetXaxis()->SetTitleOffset(1.0);
  lH->GetYaxis()->SetTitle("#mu_{best-fit}");
  lH->GetYaxis()->SetTitleOffset(1.2);

  lTX1[1] = lTX1[0]; lTX2[1] = lTX2[1]+0.001;
  TGraph *lSecond = new TGraph(1,lTX1,lTX2); lSecond->SetMarkerStyle(34); lSecond->SetMarkerSize(3.5);
  //lSecond->Draw("p");
  
  TLegend *lL = new TLegend(0.65,0.15,0.85,0.35); lL->SetBorderSize(0); lL->SetFillColor(0); lL->SetFillStyle(0); 
  for(i0 = 0; i0 < lTotalConts; i0++){
    pContLevel = (TList*)lContours->At(lTotalConts-1.-i0);
    // Get first graph from list on curves on this level
    std::vector<double> lX; 
    std::vector<double> lY; 
    pCurv = (TGraph*)pContLevel->First();
    for(int i1 = 0; i1 < pContLevel->GetSize(); i1++){
      for(int i2  = 0; i2 < pCurv->GetN(); i2++) {lX.push_back(pCurv->GetX()[i2]); lY.push_back(pCurv->GetY()[i2]);}
      //pCurv->GetPoint(0, x0, y0);
      pCurv->SetLineColor(kBlack);//kGreen+i0);
      pCCurv = (TGraph*)pCurv->Clone();
      if(i0 == 0) pCCurv->SetFillColor(0);
      if(i0 == 1) pCCurv->SetFillColor(0);
      //if(i0 == 1) pCCurv->SetLineStyle(kDashed);
      pCCurv->SetLineWidth(3);
      pCCurv->GetXaxis()->SetRangeUser(0,3.0);
      //if(i0 == 0) pCCurv->Draw("AL");
      //if(i0 != -10) pCCurv->Draw("LC");
      //l.DrawLatex(x0,y0,val);
      pCurv = (TGraph*)pContLevel->After(pCurv); // Get Next graph
    }
    TGraph *lTotal = new TGraph(lX.size(),&lX[0],&lY[0]);
    lTotal->SetLineWidth(3);
    lTotal->SetFillColor(kGreen+i0*2);
    lTotal->SetFillStyle(3001);
    //lTotal->Draw("lf");
    
    //if(i0 == 0) lTotal->Draw("alf");
    //if(i0 == 0) lTotal->Draw("alf");
    //for(int iX = 0; iX < lTotal->GetN(); iX++) cout << "===> " << lTotal->GetX()[iX] << " -- " << lTotal->GetY()[iX] << endl;
    //if(i0 != -10) lTotal->Draw("lfC");
    bool pSwitch = false;
    int  pSign   = -1.;   if(lTotal->GetX()[0] > lTotal->GetX()[1]) pSign = 1;
    double pXOld = lTotal->GetX()[lTotal->GetN()-1];
    std::vector<double> pXLeft;
    std::vector<double> pXRight;
    std::vector<double> pYLeft;
    std::vector<double> pYRight;
    for(int iX = 0; iX < lTotal->GetN(); iX++) { 
      double pX = lTotal->GetX()[iX];
      if(pSign*pX > pSign*pXOld ) {pSwitch = !pSwitch; pSign *= -1;}
      if(!pSwitch) {pXLeft.push_back(lTotal->GetX()[iX]); pYLeft.push_back(lTotal->GetY()[iX]); }
      if(pSwitch) {pXRight.push_back(lTotal->GetX()[iX]); pYRight.push_back(lTotal->GetY()[iX]); }
      pXOld = pX;
    }
    TGraph *lLeftTotal  = new TGraph(pXLeft.size() ,&pXLeft[0],&pYLeft[0]);
    TGraph *lRightTotal = new TGraph(pXRight.size(),&pXRight[0],&pYRight[0]);
    lLeftTotal->SetLineColor(kRed);
    lRightTotal->SetLineColor(kBlue);
    lLeftTotal->SetLineStyle(kDashed);
    lRightTotal->SetLineStyle(kDashed);
    //lLeftTotal->Draw("l");
    //lRightTotal->Draw("l");
    
    TGraphSmooth *lGS0 = new TGraphSmooth("normal");
    TGraphSmooth *lGS1 = new TGraphSmooth("normal");
    TGraph *lSmooth0 = lGS0->SmoothSuper(lRightTotal,"",0.,0.);
    TGraph *lSmooth1 = lGS1->SmoothSuper(lLeftTotal,"",0.,0.) ;
    lSmooth0->Draw("l");
    lSmooth1->Draw("l");
    std::vector<double> pXSmooth;
    std::vector<double> pYSmooth;
    std::vector<double> pXSmooth1;
    std::vector<double> pYSmooth1;
    cout << "==" << lSmooth0->GetN() << " -- " <<lSmooth1->GetN() << endl;
    for(int iX = 0; iX < lSmooth0->GetN(); iX++) {pXSmooth.push_back(lSmooth0->GetX()[iX]);                    pYSmooth.push_back(lSmooth0->GetY()[iX]);}
    for(int iX = 0; iX < lSmooth1->GetN(); iX++) {pXSmooth.push_back(lSmooth1->GetX()[lSmooth1->GetN()-iX-1]); pYSmooth.push_back(lSmooth1->GetY()[lSmooth1->GetN()-iX-1]);}

    for(int iX = 0; iX < lSmooth0->GetN(); iX++) {pXSmooth1.push_back(lSmooth0->GetX()[iX]);                    pYSmooth1.push_back(lSmooth0->GetY()[iX]);}
    for(int iX = 0; iX < lSmooth1->GetN(); iX++) {pXSmooth1.push_back(lSmooth1->GetX()[lSmooth1->GetN()-iX-1]); pYSmooth1.push_back(lSmooth1->GetY()[lSmooth1->GetN()-iX-1]);}
    //if(i0 == 1) {pXSmooth1.push_back(lSmooth1->GetX()[0]); pYSmooth1.push_back(lSmooth1->GetY()[0]);}
    TGraph *pSmoothShape  = new TGraph(pXSmooth.size() ,&pXSmooth [0],&pYSmooth [0]);
    TGraph *pSmoothShape1 = new TGraph(pXSmooth1.size(),&pXSmooth1[0],&pYSmooth1[0]);
    if(i0 == 1) {TLine  *lLine = new TLine(pXSmooth1[0],pYSmooth1[0],pXSmooth1[pXSmooth1.size()-1],pYSmooth1[pYSmooth1.size()-1]); lLine->Draw();}
    pSmoothShape1->SetLineColor(kBlack);
    pSmoothShape1->SetLineWidth(2);
    pSmoothShape->SetFillColor(kGreen+i0*2);
    pSmoothShape->SetFillStyle(3001);
    pSmoothShape->Draw("lf");
    pSmoothShape1->Draw("l");
    if(i0 == 0) lL->AddEntry(lTotal,"95% CL","lf");
    if(i0 == 1) lL->AddEntry(lTotal,"68% CL","lf");
  }
  lL->AddEntry(lSecond,"BestFit","p");
  lSecond->Draw("lp");
  lL->Draw();
  
  std::string masslabel = "m_{H}"; double mass = 125;
  TString label = TString::Format("%s = 135 GeV", masslabel.c_str());//, 125.);
  TPaveText* textlabel = new TPaveText(0.18, 0.81, 0.50, 0.90, "NDC");
  textlabel->SetBorderSize(   0 );
  textlabel->SetFillStyle (   0 );
  textlabel->SetTextAlign (  12 );
  textlabel->SetTextSize  (0.04 );
  textlabel->SetTextColor (   1 );
  textlabel->SetTextFont  (  62 );
  textlabel->AddText(label);
  //textlabel->Draw();
  CMSPrelim("Preliminary, H#rightarrow#tau#tau,L = 24.3 fb^{-1}", "", 0.145, 0.835);
  gPad->RedrawAxis();
  lCan->Update();

  lCan->SaveAs("cmb+_muvmass.png");
  lCan->SaveAs("cmb+_muvmass.pdf");
  lCan->SaveAs("cmb+_muvmass.eps");
}
Exemple #21
0
int cleanData(TString rawdatafiles="files.txt",TString keyfilename = "keys.txt", TString cleandir="./clean/")
{

   TString key = "clean";

   const int nreqmod = 0;
   TString reqmod[nreqmod];
   
   bool pass;
   DmtpcKeys k(keyfilename,rawdatafiles,key,cleandir,nreqmod,reqmod,pass);
   if(!pass) return -1;

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

   TFile* routfile;
   TTree* cleantree;
   TClonesArray* cleanimage;
   TH2F* tempimg;

   for(int f=0; f<k.getNFiles(); f++)
   {
      cout << k.getFile(f) << endl;
      
      //Create DMPTC Database and draw out tree
      DmtpcDataset d;
      d.openRootFile(k.getRootDirName()+k.getFile(f));
      TTree* rawtree = d.tree();

      //Add friends
      k.addFriends(rawtree,f);

      //name outputfile, open up outputfile
      TString routfilename = k.getFile(f);
      routfilename.ReplaceAll(".root",key+".root");
      routfile = new TFile(cleandir+routfilename,"CREATE");
      
      if(routfile->IsOpen())
      {
	 routfile->cd();
      }
      else
      {
	 cout << "Output file already exists; Aborting!" << endl;
	 return -1;
      }

      d.getEvent(0);
      const int ncamera = d.event()->ccdData()->GetEntries();
      const int nbinsx = d.event()->ccdData(0)->GetNbinsX();
      const int nbinsy = d.event()->ccdData(0)->GetNbinsY();

      //create tree to store clean images and sparking data
      cleantree = new TTree(key,"Cleaned Images");
      cleanimage = new TClonesArray("TH2F",ncamera);
      Bool_t spark[ncamera];
      double integral[ncamera];

      //Add branches
      cleantree->Branch("cleanimage","TClonesArray",&cleanimage,128000,0);
      cleantree->Branch("spark",&spark,"spark[2]/O");
      cleantree->Branch("integral",&integral,"integral[2]/D");
      gROOT->cd();

      //open up file for bias frame saving
      TString biasoutfilename = routfilename;
      biasoutfilename.ReplaceAll(key+".root","bias.root");

      TFile* biasoutfile = new TFile(cleandir+biasoutfilename,"RECREATE");

      TH2F* biasframe = d.event()->ccdData(0);
      TTree* biastree = new TTree("bias","Bias Information");

      biastree->Branch("biasframe","TH2F",&biasframe,128000,0);

      gROOT->cd();

      double threshhold[ncamera];
      int nframes[ncamera];
      for(int i=0; i<ncamera; i++){threshhold[i]=200; nframes[i]=0;}

      TH2F* secondarybias[ncamera];

      //find the spark cut
      const int nev = rawtree->GetEntries();
      double countthresh[nev];
      double sparkcut[ncamera];


      for(int j=0; j<ncamera; j++)
      {
	 cout << j << ":" << endl;
	 countthresh[j] =d.getBiasFrame(j+1)->Integral()/(65536);
	 sparkcut[j] =  MaxCamImageTools::countPixelsAboveThreshold(d.getBiasFrame(j+1),countthresh[j])-2000;

	 cout << "count: " << countthresh[j] << "\t cut: " << sparkcut[j] << endl;

	 
      }
      
      //Grab every 100th image to make bias frame; must check for sparks
      for(int i=0; i<nev; i=i+100)
      {
	 cout << i << endl;
	 d.getEvent(i);
	 for(int u=0; u<ncamera; u++)
	 {
	    tempimg = (TH2F*)d.event()->ccdData(u)->Clone("backimg");
//	    MaxCamImageTools::killLonePixels2(tempimg,1300);
	    int nabove = MaxCamImageTools::countPixelsAboveThreshold(tempimg,countthresh[u]);
	    if(nabove<sparkcut[u])
	    {
	       if(nframes[u]==0) 
	       {
		  secondarybias[u]=(TH2F*)tempimg->Clone("average");
	       }
	       else
	       {
		  secondarybias[u]->Add(tempimg,1);
	       }
	       nframes[u]++;
	    }
	    
	 }
	 
      }

      gROOT->Delete("backimg;*");

      for(int i=0; i<ncamera; i++)
      {
	 secondarybias[i]->Scale(1/double(nframes[i]));
 	 biasframe = secondarybias[i];
 	 biasoutfile->cd();
 	 biastree->Fill();
 	 gROOT->cd();
	 
      }

      cout << "All preclean activities done" << endl;
      c->Update();

      //cleaning should go here
      for(int i = 0; i<nev; i++)
//      for(int i = 0; i<100; i++) //For testing
      {
	 cout << i << endl;
	 d.getEvent(i);
	 for(int u=0; u<ncamera; u++)
	 {
//	    c->cd(u+1);

	    
	    //create cloned image
	    tempimg = (TH2F*)d.event()->ccdData(u);

	    //check for sparking
	    int nabove = MaxCamImageTools::countPixelsAboveThreshold(tempimg,countthresh[u]);

	    if(nabove < sparkcut[u])
	       spark[u]=0;
	    else
	       spark[u]=1;

	    if(spark[u] == 1) cout << "SPARK!" << endl;


	    //subtract of temp bias
	    tempimg->Add(secondarybias[u],-1);
	    //kill lone pixels
	    MaxCamImageTools::killLonePixels2(tempimg,threshhold[u]);
   
	    
	    //additionally correct
	    double perpx = tempimg->Integral()/(nbinsx*nbinsy);

	    if(spark[u]==0)
	       MaxCamImageTools::subtractPedestal(tempimg,perpx);

	    integral[u] = tempimg->Integral();
	    
	    //add to TClonesArray
	    new((*cleanimage)[u]) TH2F(*tempimg);
	    


	 }
	 routfile->cd();
	 cleantree->Fill();
	 gROOT->cd();

      }

      routfile->cd();
      cleantree->Write();

      delete cleantree;

      routfile->Close();

      biasoutfile->cd();
      biastree->Write();
      
      delete biastree;
      
      biasoutfile->Close();

   }

      
   return 0;
}
Exemple #22
0
void plotHistHi() {



  gStyle->SetOptStat(0);

  set_plot_style();

  TFile *f = new TFile("./../root_files/hists.root");


  // sim-to-reco hists
  TH2F *hSim = (TH2F*) f->Get("hitrkEffAnalyzer/hsim"); hSim->GetYaxis()->SetRangeUser(0,10);
  TH2F *hAcc = (TH2F*) f->Get("hitrkEffAnalyzer/hacc"); hAcc->GetYaxis()->SetRangeUser(0,10);
  TH2F *hEff = (TH2F*) f->Get("hitrkEffAnalyzer/heff"); hEff->GetYaxis()->SetRangeUser(0,10);
  TH2F *hMul = (TH2F*) f->Get("hitrkEffAnalyzer/hmul"); hMul->GetYaxis()->SetRangeUser(0,10);

  // reco-to-sim hists
  TH2F *hRec = (TH2F*) f->Get("hitrkEffAnalyzer/hrec"); hRec->GetYaxis()->SetRangeUser(0,10);
  TH2F *hFak = (TH2F*) f->Get("hitrkEffAnalyzer/hfak"); hFak->GetYaxis()->SetRangeUser(0,10);
  TH2F *hSec = (TH2F*) f->Get("hitrkEffAnalyzer/hsec"); hSec->GetYaxis()->SetRangeUser(0,10);

  // ratio histograms
  TH2F *rAcc = (TH2F*) hAcc->Clone("rAcc");
  TH2F *rEff = (TH2F*) hEff->Clone("rEff");
  TH2F *rMul = (TH2F*) hMul->Clone("rMul");
  TH2F *rFak = (TH2F*) hFak->Clone("rFak");
  TH2F *rSec = (TH2F*) hSec->Clone("rSec");
  //TH2F *rDec = (TH2F*) hDec->Clone("rDec");

  //---------------------------------------------

  // acceptance fraction
  TCanvas *c1 = new TCanvas("c1","Acceptance Fraction",600,500);
  gPad->SetRightMargin(0.15);
  rAcc->Divide(hAcc,hSim,1,1,"B");
  rAcc->SetStats(0);
  rAcc->SetMaximum(1.0); rAcc->SetMinimum(0.0);
  rAcc->SetTitle("Geometrical Acceptance");
  rAcc->Draw("colz");

  // reco efficiency fraction
  TCanvas *c2 = new TCanvas("c2","Reco Efficiency Fraction",600,500);
  gPad->SetRightMargin(0.15);
  rEff->Divide(hEff,hAcc,1,1,"B");
  rEff->SetStats(0);
  rEff->SetMaximum(1.0); rEff->SetMinimum(0.0);
  rEff->SetTitle("Algorithmic Efficiency");
  rEff->Draw("colz");

  // multiple reco fraction
  TCanvas *c3 = new TCanvas("c3","Multiple Reco Fraction",600,500);
  gPad->SetRightMargin(0.15);
  rMul->Divide(hMul,hAcc,1,1,"B");
  rMul->SetStats(0);
  rMul->SetMaximum(0.00049); rMul->SetMinimum(0.0);
  rMul->SetTitle("Multiple Reconstruction Fraction");
  rMul->Draw("colz");

  // fake reco fraction
  TCanvas *c4 = new TCanvas("c4","Fake Reco Fraction",600,500);
  gPad->SetRightMargin(0.15);
  rFak->Divide(hFak,hRec,1,1,"B");
  rFak->SetStats(0);
  rFak->SetMaximum(0.1); rFak->SetMinimum(0.0);
  rFak->SetTitle("Fake Reconstruction Fraction");
  rFak->Draw("colz");

  // secondary reco fraction
  TCanvas *c5 = new TCanvas("c5","Secondary Fraction",600,500);  
  gPad->SetRightMargin(0.15);
  rSec->Divide(hSec,hRec,1,1,"B");
  rSec->SetStats(0);
  rSec->SetMaximum(0.05); rSec->SetMinimum(0.0);
  rSec->SetTitle("Non-Primary Reconstruction Fraction");
  rSec->Draw("colz");

  //---------------------------------------------

  // find bins corresponding to projections for below
  Int_t ptbin04=hSim->GetYaxis()->FindBin(0.91);
  Int_t ptbin20=hSim->GetYaxis()->FindBin(2.01);
  Int_t ptbins=hSim->GetYaxis()->GetNbins();
  Int_t etabin24m=hSim->GetXaxis()->FindBin(-2.39);
  Int_t etabin24p=hSim->GetXaxis()->FindBin(2.39);
  Int_t etabin10m=hSim->GetXaxis()->FindBin(-0.99);
  Int_t etabin10p=hSim->GetXaxis()->FindBin(0.99);

  cout << "etabin10m: " << etabin10m << " etabin10p: " << etabin10p << endl;
  cout << "etabin10m: " << etabin24m << " etabin10p: " << etabin24p << endl;

  // projected hists: pt > 0.9 GeV/c
  TH1D* hSimEta = (TH1D*) hSim->ProjectionX("hSimEta",ptbin04,ptbins,"e");
  TH1D* hAccEta = (TH1D*) hAcc->ProjectionX("hAccEta",ptbin04,ptbins,"e");
  TH1D* hEffEta = (TH1D*) hEff->ProjectionX("hEffEta",ptbin04,ptbins,"e");
  TH1D* hMulEta = (TH1D*) hMul->ProjectionX("hMulEta",ptbin04,ptbins,"e");
  TH1D* hRecEta = (TH1D*) hRec->ProjectionX("hRecEta",ptbin04,ptbins,"e");
  TH1D* hFakEta = (TH1D*) hFak->ProjectionX("hFakEta",ptbin04,ptbins,"e");
  TH1D* hSecEta = (TH1D*) hSec->ProjectionX("hSecEta",ptbin04,ptbins,"e");

  // projected hists: pt > 2.0 GeV/c
  TH1D* hSimEta2 = (TH1D*) hSim->ProjectionX("hSimEta2",ptbin20,ptbins,"e");
  TH1D* hAccEta2 = (TH1D*) hAcc->ProjectionX("hAccEta2",ptbin20,ptbins,"e");
  TH1D* hEffEta2 = (TH1D*) hEff->ProjectionX("hEffEta2",ptbin20,ptbins,"e");
  TH1D* hMulEta2 = (TH1D*) hMul->ProjectionX("hMulEta2",ptbin20,ptbins,"e");
  TH1D* hRecEta2 = (TH1D*) hRec->ProjectionX("hRecEta2",ptbin20,ptbins,"e");
  TH1D* hFakEta2 = (TH1D*) hFak->ProjectionX("hFakEta2",ptbin20,ptbins,"e");
  TH1D* hSecEta2 = (TH1D*) hSec->ProjectionX("hSecEta2",ptbin20,ptbins,"e");

  TH1D* hDumEta = new TH1D("hDumEta",";#eta",60,-2.4,2.4); hDumEta->SetMaximum(1.0);
  hDumEta->GetXaxis()->CenterTitle(); hDumEta->GetYaxis()->SetTitleOffset(1.8);
  TH1D* hDumEta2 = (TH1D*) hDumEta->Clone("hDumEta2"); hDumEta2->SetMaximum(0.1); 
  TH1D* hDumEta3 = (TH1D*) hDumEta->Clone("hDumEta3"); hDumEta3->SetMaximum(0.00049); 


  // projected hists: abs(eta) < 1.0
  TH1D* hSimPt  = (TH1D*) hSim->ProjectionY("hSimPt",etabin10m,etabin10p,"e");
  TH1D* hAccPt  = (TH1D*) hAcc->ProjectionY("hAccPt",etabin10m,etabin10p,"e");
  TH1D* hEffPt  = (TH1D*) hEff->ProjectionY("hEffPt",etabin10m,etabin10p,"e");
  TH1D* hMulPt  = (TH1D*) hMul->ProjectionY("hMulPt",etabin10m,etabin10p,"e");
  TH1D* hRecPt  = (TH1D*) hRec->ProjectionY("hRecPt",etabin10m,etabin10p,"e");
  TH1D* hFakPt  = (TH1D*) hFak->ProjectionY("hFakPt",etabin10m,etabin10p,"e");
  TH1D* hSecPt  = (TH1D*) hSec->ProjectionY("hSecPt",etabin10m,etabin10p,"e");

  // projected hists: abs(eta) < 2.4
  TH1D* hSimPt2  = (TH1D*) hSim->ProjectionY("hSimPt2",etabin24m,etabin24p,"e");
  TH1D* hAccPt2  = (TH1D*) hAcc->ProjectionY("hAccPt2",etabin24m,etabin24p,"e");
  TH1D* hEffPt2  = (TH1D*) hEff->ProjectionY("hEffPt2",etabin24m,etabin24p,"e");
  TH1D* hMulPt2  = (TH1D*) hMul->ProjectionY("hMulPt2",etabin24m,etabin24p,"e");
  TH1D* hRecPt2  = (TH1D*) hRec->ProjectionY("hRecPt2",etabin24m,etabin24p,"e");
  TH1D* hFakPt2  = (TH1D*) hFak->ProjectionY("hFakPt2",etabin24m,etabin24p,"e");
  TH1D* hSecPt2  = (TH1D*) hSec->ProjectionY("hSecPt2",etabin24m,etabin24p,"e");
  
  TH1D* hDumPt = new TH1D("hDumPt",";p_{T} [GeV/c]",80,0.0,10.0); hDumPt->SetMaximum(1.0);
  hDumPt->GetXaxis()->CenterTitle(); hDumPt->GetYaxis()->SetTitleOffset(1.8);
  TH1D* hDumPt2 = (TH1D*) hDumPt->Clone("hDumPt2"); hDumPt2->SetMaximum(0.1); 
  TH1D* hDumPt3 = (TH1D*) hDumPt->Clone("hDumPt3"); hDumPt3->SetMaximum(0.00049); 

  // Acceptance
  TGraphAsymmErrors *gAccEta = new TGraphAsymmErrors(); gAccEta->SetName("gAccEta");
  gAccEta->BayesDivide(hAccEta,hSimEta);
  gAccEta->SetMarkerStyle(25);
  gAccEta->SetLineStyle(2);
  gAccEta->SetLineColor(2);
  gAccEta->SetMarkerColor(2);

  TGraphAsymmErrors *gAccPt = new TGraphAsymmErrors(); gAccPt->SetName("gAccPt");
  gAccPt->BayesDivide(hAccPt,hSimPt);
  gAccPt->SetMarkerStyle(24);
  gAccPt->SetLineColor(4);
  gAccPt->SetMarkerColor(4);

  TGraphAsymmErrors *gAccEta2 = new TGraphAsymmErrors(); gAccEta2->SetName("gAccEta2");
  gAccEta2->BayesDivide(hAccEta2,hSimEta2);
  gAccEta2->SetMarkerStyle(24);
  gAccEta2->SetLineColor(4);
  gAccEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gAccPt2 = new TGraphAsymmErrors(); gAccPt2->SetName("gAccPt2");
  gAccPt2->BayesDivide(hAccPt2,hSimPt2);
  gAccPt2->SetMarkerStyle(25);
  gAccPt2->SetLineStyle(2);
  gAccPt2->SetLineColor(2);
  gAccPt2->SetMarkerColor(2);

  TLegend *legEta = new TLegend(0.35,0.3,0.65,0.5);
  legEta->SetFillColor(0); legEta->SetBorderSize(0);
  legEta->AddEntry(gAccEta,"p_{T} > 0.9 GeV/c","lp");
  legEta->AddEntry(gAccEta2,"p_{T} > 2.0 GeV/c","lp");

  TLegend *legPt = new TLegend(0.4,0.3,0.6,0.5);
  legPt->SetFillColor(0); legPt->SetBorderSize(0);
  legPt->AddEntry(gAccPt2,"|#eta| < 2.4","lp");
  legPt->AddEntry(gAccPt,"|#eta| < 1.0","lp");

  TCanvas *c6 = new TCanvas("c6","Acceptance Fraction",900,500);
  c6->Divide(2,1);
  hDumEtaAcc=(TH1F*) hDumEta->Clone("hDumEtaAcc");
  hDumEtaAcc->GetYaxis()->SetTitle("Geometrical acceptance");
  hDumPtAcc=(TH1F*) hDumPt->Clone("hDumPtAcc");
  hDumPtAcc->GetYaxis()->SetTitle("Geometrical acceptance");
  c6->cd(1); hDumEtaAcc->Draw(); gAccEta->Draw("pc"); gAccEta2->Draw("pc"); legEta->Draw();
  c6->cd(2); hDumPtAcc->Draw(); gAccPt->Draw("pc"); gAccPt2->Draw("pc"); legPt->Draw();


  // Efficiency
  TGraphAsymmErrors *gEffEta = new TGraphAsymmErrors(); gEffEta->SetName("gEffEta");
  gEffEta->BayesDivide(hEffEta,hAccEta);
  gEffEta->SetMarkerStyle(25);
  gEffEta->SetLineStyle(2);
  gEffEta->SetLineColor(2);
  gEffEta->SetMarkerColor(2);

  TGraphAsymmErrors *gEffPt = new TGraphAsymmErrors(); gEffPt->SetName("gEffPt");
  gEffPt->BayesDivide(hEffPt,hAccPt);
  gEffPt->SetMarkerStyle(24);
  gEffPt->SetLineColor(4);
  gEffPt->SetMarkerColor(4);

  TGraphAsymmErrors *gEffEta2 = new TGraphAsymmErrors(); gEffEta2->SetName("gEffEta2");
  gEffEta2->BayesDivide(hEffEta2,hAccEta2);
  gEffEta2->SetMarkerStyle(24);
  gEffEta2->SetLineColor(4);
  gEffEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gEffPt2 = new TGraphAsymmErrors(); gEffPt2->SetName("gEffPt2");
  gEffPt2->BayesDivide(hEffPt2,hAccPt2);
  gEffPt2->SetMarkerStyle(25);
  gEffPt2->SetLineStyle(2);
  gEffPt2->SetLineColor(2);
  gEffPt2->SetMarkerColor(2);

  TCanvas *c7 = new TCanvas("c7","Efficiency Fraction",900,500);
  c7->Divide(2,1);
  hDumEtaEff=(TH1F*) hDumEta->Clone("hDumEtaEff");
  hDumEtaEff->GetYaxis()->SetTitle("Algorithmic efficiency");
  hDumPtEff=(TH1F*) hDumPt->Clone("hDumPtEff");
  hDumPtEff->GetYaxis()->SetTitle("Algorithmic efficiency");
  c7->cd(1); hDumEtaEff->Draw(); gEffEta->Draw("pc"); gEffEta2->Draw("pc"); legEta->Draw();
  c7->cd(2); hDumPtEff->Draw(); gEffPt->Draw("pc"); gEffPt2->Draw("pc"); legPt->Draw();

  // Multiple Reco
  TGraphAsymmErrors *gMulEta = new TGraphAsymmErrors(); gMulEta->SetName("gMulEta");
  gMulEta->BayesDivide(hMulEta,hAccEta);
  gMulEta->SetMarkerStyle(25);
  gMulEta->SetLineStyle(2);
  gMulEta->SetLineColor(2);
  gMulEta->SetMarkerColor(2);

  TGraphAsymmErrors *gMulPt = new TGraphAsymmErrors(); gMulPt->SetName("gMulPt");
  gMulPt->BayesDivide(hMulPt,hAccPt);
  gMulPt->SetMarkerStyle(24);
  gMulPt->SetLineColor(4);
  gMulPt->SetMarkerColor(4);

  TGraphAsymmErrors *gMulEta2 = new TGraphAsymmErrors(); gMulEta2->SetName("gMulEta2");
  gMulEta2->BayesDivide(hMulEta2,hAccEta2);
  gMulEta2->SetMarkerStyle(24);
  gMulEta2->SetLineColor(4);
  gMulEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gMulPt2 = new TGraphAsymmErrors(); gMulPt2->SetName("gMulPt2");
  gMulPt2->BayesDivide(hMulPt2,hAccPt2);
  gMulPt2->SetMarkerStyle(25);
  gMulPt2->SetLineStyle(2);
  gMulPt2->SetLineColor(2);
  gMulPt2->SetMarkerColor(2);

  TCanvas *c8 = new TCanvas("c8","Multiple Fraction",900,500);
  c8->Divide(2,1);
  hDumEtaMul=(TH1F*) hDumEta3->Clone("hDumEtaMul");
  hDumEtaMul->GetYaxis()->SetTitle("Multiple Reconstruction Fraction");
  hDumPtMul=(TH1F*) hDumPt3->Clone("hDumPtMul");
  hDumPtMul->GetYaxis()->SetTitle("Multiple Reconstruction Fraction");
  legEta2 = (TLegend*) legEta->Clone(); legEta2->SetY1(0.65); legEta2->SetY2(0.85);
  legPt2 = (TLegend*) legPt->Clone(); legPt2->SetY1(0.65); legPt2->SetY2(0.85);
  c8->cd(1); hDumEtaMul->Draw(); gMulEta->Draw("pc"); gMulEta2->Draw("pc"); legEta2->Draw();
  c8->cd(2); hDumPtMul->Draw(); gMulPt->Draw("pc"); gMulPt2->Draw("pc"); legPt2->Draw();

  // Fakes
  TGraphAsymmErrors *gFakEta = new TGraphAsymmErrors();  gFakEta->SetName("gFakEta");
  gFakEta->BayesDivide(hFakEta,hRecEta);
  gFakEta->SetMarkerStyle(25);
  gFakEta->SetLineStyle(2);
  gFakEta->SetLineColor(2);
  gFakEta->SetMarkerColor(2);

  TGraphAsymmErrors *gFakPt = new TGraphAsymmErrors(); gFakPt->SetName("gFakPt");
  gFakPt->BayesDivide(hFakPt,hRecPt);
  gFakPt->SetMarkerStyle(24);
  gFakPt->SetLineColor(4);
  gFakPt->SetMarkerColor(4);

  TGraphAsymmErrors *gFakEta2 = new TGraphAsymmErrors(); gFakEta2->SetName("gFakEta2");
  gFakEta2->BayesDivide(hFakEta2,hRecEta2);
  gFakEta2->SetMarkerStyle(24);
  gFakEta2->SetLineColor(4);
  gFakEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gFakPt2 = new TGraphAsymmErrors();  gFakPt2->SetName("gFakPt2");
  gFakPt2->BayesDivide(hFakPt2,hRecPt2);
  gFakPt2->SetMarkerStyle(25);
  gFakPt2->SetLineStyle(2);
  gFakPt2->SetLineColor(2);
  gFakPt2->SetMarkerColor(2);

  TCanvas *c9 = new TCanvas("c9","Fake Fraction",900,500);
  c9->Divide(2,1);
  hDumEtaFak=(TH1F*) hDumEta2->Clone("hDumEtaMul");
  hDumEtaFak->GetYaxis()->SetTitle("Fake Reconstruction Fraction");
  hDumPtFak=(TH1F*) hDumPt2->Clone("hDumPtMul");
  hDumPtFak->GetYaxis()->SetTitle("Fake Reconstruction Fraction");
  c9->cd(1); hDumEtaFak->Draw(); gFakEta->Draw("pc"); gFakEta2->Draw("pc"); legEta2->Draw();
  c9->cd(2); hDumPtFak->Draw(); gFakPt->Draw("pc"); gFakPt2->Draw("pc"); legPt2->Draw();

  // Secondaries
  TGraphAsymmErrors *gSecEta = new TGraphAsymmErrors(); gSecEta->SetName("gSecEta");
  gSecEta->BayesDivide(hSecEta,hRecEta);
  gSecEta->SetMarkerStyle(25);
  gSecEta->SetLineStyle(2);
  gSecEta->SetLineColor(2);
  gSecEta->SetMarkerColor(2);

  TGraphAsymmErrors *gSecPt = new TGraphAsymmErrors(); gSecPt->SetName("gSecPt");
  gSecPt->BayesDivide(hSecPt,hRecPt);
  gSecPt->SetMarkerStyle(24);
  gSecPt->SetLineColor(4);
  gSecPt->SetMarkerColor(4);

  TGraphAsymmErrors *gSecEta2 = new TGraphAsymmErrors(); gSecEta2->SetName("gSecEta2");
  gSecEta2->BayesDivide(hSecEta2,hRecEta2);
  gSecEta2->SetMarkerStyle(24);
  gSecEta2->SetLineColor(4);
  gSecEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gSecPt2 = new TGraphAsymmErrors();  gSecPt2->SetName("gSecPt2");
  gSecPt2->BayesDivide(hSecPt2,hRecPt2);
  gSecPt2->SetMarkerStyle(25);
  gSecPt2->SetLineStyle(2);
  gSecPt2->SetLineColor(2);
  gSecPt2->SetMarkerColor(2);

  TCanvas *c10 = new TCanvas("c10","Secondary Fraction",900,500);
  c10->Divide(2,1);
  hDumEtaSec=(TH1F*) hDumEta2->Clone("hDumEtaMul");
  hDumEtaSec->GetYaxis()->SetTitle("Non-Primary Reconstruction Fraction");
  hDumPtSec=(TH1F*) hDumPt2->Clone("hDumPtMul");
  hDumPtSec->GetYaxis()->SetTitle("Non-Primary Reconstruction Fraction");
  c10->cd(1); hDumEtaSec->Draw(); gSecEta->Draw("pc"); gSecEta2->Draw("pc"); legEta2->Draw();
  c10->cd(2); hDumPtSec->Draw(); gSecPt->Draw("pc"); gSecPt2->Draw("pc"); legPt2->Draw();

  /*
  printCanvases(c1,"hitrk_can1",0,1);
  printCanvases(c2,"hitrk_can2",0,1);
  printCanvases(c3,"hitrk_can3",0,1);
  printCanvases(c4,"hitrk_can4",0,1);
  printCanvases(c5,"hitrk_can5",0,1);
  printCanvases(c6,"hitrk_can6",0,1);
  printCanvases(c7,"hitrk_can7",0,1);
  printCanvases(c8,"hitrk_can8",0,1);
  printCanvases(c9,"hitrk_can9",0,1);
  printCanvases(c10,"hitrk_can10",0,1);
  */


  /*
  TFile *f = new TFile("trkEffPY8.root","RECREATE");
  gAccPt->Write(); gAccPt2->Write(); gAccEta->Write(); gAccEta2->Write();
  gEffPt->Write(); gEffPt2->Write(); gEffEta->Write(); gEffEta2->Write();
  gMulPt->Write(); gMulPt2->Write(); gMulEta->Write(); gMulEta2->Write();
  gFakPt->Write(); gFakPt2->Write(); gFakEta->Write(); gFakEta2->Write();
  gSecPt->Write(); gSecPt2->Write(); gSecEta->Write(); gSecEta2->Write();
  f->Close();
  */
}
int main(int argc, char**argv)
{

// Set style options
	gROOT->Reset();
	gROOT->SetStyle("Plain");

	gStyle->SetPadTickX(1);
	gStyle->SetPadTickY(1);
	gStyle->SetOptTitle(0);
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(0);
	gStyle->SetFitFormat("6.3g");
	gStyle->SetPalette(1);

	gStyle->SetTextFont(42);
	gStyle->SetTextSize(0.05);
	gStyle->SetTitleFont(42, "xyz");
	gStyle->SetTitleSize(0.05);
	gStyle->SetLabelFont(42, "xyz");
	gStyle->SetLabelSize(0.05);
	gROOT->ForceStyle();

/// Input File MCTruth IC Map , RECO IC map, MC IC set after calibration (Usually set with miscalibration 5%)
/// and StatPrecision IC coefficient obtained from CalibrationBarrel.cpp

	if(argc != 2) {
		std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
		return 1;
	}

	std::string configFileName = argv[1];
	std::shared_ptr<edm::ParameterSet> parameterSet = edm::readConfig(configFileName);
	edm::ParameterSet Options = parameterSet -> getParameter<edm::ParameterSet>("Options");

	std::string inputFile = "NULL";
	if(Options.existsAs<std::string>("inputFile"))
		inputFile = Options.getParameter<std::string>("inputFile");

	std::string fileMCTruth = "NULL";
	if(Options.existsAs<std::string>("fileMCTruth"))
		fileMCTruth = Options.getParameter<std::string>("fileMCTruth");

	std::string fileMCRecoIC = "NULL";
	if(Options.existsAs<std::string>("fileMCRecoIC"))
		fileMCRecoIC = Options.getParameter<std::string>("fileMCRecoIC");

	std::string fileStatPrecision = "NULL";
	if(Options.existsAs<std::string>("fileStatPrecision"))
		fileStatPrecision = Options.getParameter<std::string>("fileStatPrecision");

	TApplication* theApp = new TApplication("Application", &argc, argv);


	TFile *f1 = TFile::Open(fileMCTruth.c_str());
	TFile *f2 = TFile::Open(fileMCRecoIC.c_str());
	TFile *f3 = TFile::Open(inputFile.c_str());
	TFile *f4 = TFile::Open(fileStatPrecision.c_str());

	if( f1 == 0 || f2 == 0 || f3 == 0 || f4 == 0) return -1;

	TH2F *hcmapMcT = (TH2F*)f1->Get("h_scale_map");
	TH2F *hcmapMcR = (TH2F*)f2->Get("h_scale_map");

	TH2F * hcmap1 = (TH2F*)hcmapMcT->Clone("hcmap1");
	hcmap1->Reset();
	TH1F * hringdiff = new TH1F("hringdiff", "difference of ring average", 100, -0.1, 0.1);

	for (int jbin = 1; jbin < hcmap1-> GetNbinsY(); jbin++) {
		for (int ibin = 1; ibin < hcmap1-> GetNbinsX() + 1; ibin++) {
			hcmap1->SetBinContent(ibin, jbin, hcmapMcT->GetBinContent(ibin, jbin) / hcmapMcR->GetBinContent(ibin, jbin));
		}
	}


	TH2F * miscalib_map = (TH2F*) f3 -> Get("h_scalib_EB");
	TH2F *hcL3 = (TH2F*)f3->Get("h_scale_map");

	TH2F *hcmap2 = (TH2F*)hcL3 ->Clone("hcmap2");
	hcmap2->Reset();

	for (int jbin = 1; jbin < hcmap2-> GetNbinsY() + 1; jbin++) {
		for (int ibin = 1; ibin < hcmap2-> GetNbinsX() + 1; ibin++) {
			hcmap2->SetBinContent(ibin, jbin, miscalib_map->GetBinContent(ibin, jbin)*hcL3->GetBinContent(ibin, jbin));
		}
	}

/// IC Histogramm in Eta ring and 2D map difference
	TH2F * h2 = new TH2F("h2", "h2", 400, 0.5, 1.5, 400, 0.5, 1.5);
	TH2F * h2diff = (TH2F*)hcmap1->Clone("h2diff");
	h2diff->Reset();
	TH1F *hdiff = new TH1F("hdiff", "hdiff", 400, -0.5, 0.5);

	char hname[100];

	TH1F *hspread[172];
	for (int jbin = 1; jbin < hcmap1-> GetNbinsY() + 1; jbin++) {
		int etaring = hcmap1-> GetYaxis()->GetBinCenter(jbin);
		sprintf(hname, "hspread_ring_ieta%02d", etaring);
		hspread[jbin - 1] = new TH1F(hname, hname, 400, -0.5, 0.5);
	}

	for (int jbin = 1; jbin < hcmap1-> GetNbinsY() + 1; jbin++) {
		float etaring = hcmap1-> GetYaxis()->GetBinCenter(jbin);
		for (int ibin = 1; ibin < hcmap1-> GetNbinsX() + 1; ibin++) {
			float c1 = hcmap1->GetBinContent(ibin, jbin);
			float c2 = hcmap2->GetBinContent(ibin, jbin);
			if (c1 != 0 && c2 != 0 ) {
				hspread[jbin - 1]->Fill( c1 - c2 );
				h2->Fill(c1, c2);
				h2diff->SetBinContent(ibin, jbin, c1 - c2);
				if (fabs(etaring) < 40) hdiff->Fill(c1 - c2);

			}
		}
	}

/// Final Plot in eta ring (stat prescision and scale)
	TGraphErrors *sigma_vs_ieta = new TGraphErrors();
	sigma_vs_ieta->SetMarkerStyle(20);
	sigma_vs_ieta->SetMarkerSize(1);
	sigma_vs_ieta->SetMarkerColor(kBlue + 2);

	TGraphErrors *rms_vs_ieta = new TGraphErrors();
	rms_vs_ieta->SetMarkerStyle(24);
	rms_vs_ieta->SetMarkerSize(1);
	rms_vs_ieta->SetMarkerColor(kBlue + 2);

	TGraphErrors *scale_vs_ieta = new TGraphErrors();
	scale_vs_ieta->SetMarkerStyle(20);
	scale_vs_ieta->SetMarkerSize(1);
	scale_vs_ieta->SetMarkerColor(kBlue + 2);

/// Gaussian Fit of spread coefficient dstribution
	TF1 *fgaus = new TF1("fgaus", "gaus", -1, 1);
	int np = 0;
	for (int i = 1; i < hcmap1-> GetNbinsY() + 1; i++) {
		float etaring = hcmap1-> GetYaxis()->GetBinCenter(i);
		if (etaring == 0.5) continue;
		if ( hspread[i - 1]->GetEntries() == 0) {
			sigma_vs_ieta-> SetPoint(np, etaring, -100);
			np++;
			continue;
		}
		hspread[i - 1]->Fit("fgaus", "Q");
		sigma_vs_ieta-> SetPoint(np, etaring, fgaus->GetParameter(2));
		sigma_vs_ieta-> SetPointError(np, 0, fgaus->GetParError(2));
		rms_vs_ieta  -> SetPoint(np, etaring, hspread[i - 1]->GetRMS());
		rms_vs_ieta  -> SetPointError(np, 0, hspread[i - 1]->GetRMSError() );
		scale_vs_ieta-> SetPoint(np, etaring, fgaus->GetParameter(1));
		scale_vs_ieta-> SetPointError(np, 0, fgaus->GetParError(1));
		if( fabs(etaring) < 20 ) {
			hringdiff->Fill( fgaus->GetParameter(1) );
		}
		np++;
	}

	/// Final Plot
	TGraphErrors* gr_stat_prec = (TGraphErrors*) f4->Get("gr_stat_prec");
	TCanvas *csigma = new TCanvas("csigma", "csigma");
	csigma->SetGridx();
	csigma->SetGridy();
	sigma_vs_ieta->GetHistogram()->GetYaxis()-> SetRangeUser(0.00, 0.2);
	sigma_vs_ieta->GetHistogram()->GetXaxis()-> SetRangeUser(-85, 85);
	sigma_vs_ieta->GetHistogram()->GetYaxis()-> SetTitle("#sigma");
	sigma_vs_ieta->GetHistogram()->GetXaxis()-> SetTitle("ieta");
	sigma_vs_ieta->Draw("ap");
	rms_vs_ieta->Draw("psame");
	gr_stat_prec->Draw("psame");


/// Residual Plot (spread - statistical precision)
	TGraphErrors* residual = new TGraphErrors();

	for(int pp = 0; pp < gr_stat_prec->GetN(); pp++) {
		double eta1, eta2, tot, stat;
		gr_stat_prec->GetPoint(pp, eta1, stat);
		sigma_vs_ieta->GetPoint(pp, eta2, tot);
		if(eta1 != eta2) {
			cout << "error different ring " << eta1 << "  " << eta2 << endl;
		}
		double res = tot * tot - stat * stat;
		if (res > 0) res = sqrt(res);
		else res = -sqrt(fabs(res));
		double errres = sqrt( pow(tot * sigma_vs_ieta->GetErrorY(pp), 2) + pow(stat * gr_stat_prec->GetErrorY(pp), 2)) / fabs(res);
		residual->SetPoint(pp, eta1, res);
		residual->SetPointError(pp, 0, errres);
	}

/// Residual spread plot
	TCanvas *cres = new TCanvas("cres", "cresidual");
	cres->SetGridx();
	cres->SetGridy();
	residual->GetHistogram()->GetYaxis()-> SetRangeUser(-0.1, 0.1);
	residual->GetHistogram()->GetXaxis()-> SetRangeUser(-85, 85);
	residual->GetHistogram()->GetYaxis()-> SetTitle("residual");
	residual->GetHistogram()->GetXaxis()-> SetTitle("ieta");
	residual ->SetMarkerStyle(20);
	residual->SetMarkerSize(1);
	residual->SetMarkerColor(kGreen + 2);
	residual->GetYaxis()->SetTitle("residual");
	residual->GetXaxis()->SetTitle("i#eta");
	residual->Draw("ap");

/// scale vs eta plot
	TCanvas *cscale = new TCanvas("cscale", "cscale");
	cscale->SetGridx();
	cscale->SetGridy();
	scale_vs_ieta->GetHistogram()->GetYaxis()-> SetRangeUser(-0.1, 0.1);
	scale_vs_ieta->GetHistogram()->GetXaxis()-> SetRangeUser(-85, 85);
	scale_vs_ieta->GetHistogram()->GetYaxis()-> SetTitle("c_{1}-c_{2}");
	scale_vs_ieta->GetHistogram()->GetXaxis()-> SetTitle("ieta");
	scale_vs_ieta->Draw("ap");

/// IC Diff map
	TCanvas *cmap2 = new TCanvas("cmap2", "cmap2", 500, 500);
	cmap2->SetGridx();
	cmap2->SetGridy();
	cmap2 -> cd();
	cmap2->SetLeftMargin(0.1);
	cmap2->SetRightMargin(0.15);
	h2->GetXaxis()->SetRangeUser(0.85, 1.15);
	h2->GetYaxis()->SetRangeUser(0.85, 1.15);
	h2->GetXaxis()->SetTitle("C_{1}");
	h2->GetYaxis()->SetTitle("C_{2}");
	h2->Draw("colz");

	TCanvas *cdiff = new TCanvas("cdiff", "cdiff", 700, 500);
	cdiff->SetGridx();
	cdiff->SetGridy();
	cdiff -> cd();
	cdiff->SetLeftMargin(0.1);
	cdiff->SetRightMargin(0.15);
	h2diff->GetZaxis()->SetRangeUser(-0.05, 0.05);
	h2diff->GetXaxis()->SetTitle("i#phi");
	h2diff->GetYaxis()->SetTitle("i#eta");
	h2diff->Draw("colz");

	theApp->Run();

	return 0;
}