Exemplo n.º 1
0
TH2F* ZMassVsDRHist2D(TString name, TString bininfo, DiMuPlottingSystem* dps)
{
  // Plot a 2D hist of the dimuon mass vs ZPt for either positive or negative reco muons. 
  // This function uses the DiMuonPlottingSystem class which facilitates the application of cuts. 

  // Get the titles and units straight.
  TString xtitle = TString("dR");

  TString title = TString ("Z Mass vs ");
  title+=xtitle;
  xtitle+= TString("");

  TString ytitle = TString("Z Mass (GeV)");

  // Initialize some pointers to be filled. h2 takes in reco2 info which will be added to reco1 info in order to get
  // all of the positive or all of the negative reco muons.
  TH2F* h = 0;

  TString dR = TString("((reco1.phi - reco2.phi)**2 + (reco1.eta - reco2.eta)**2 )**0.5");

  h = dps->hist2D("recoCandMass:"+dR, bininfo, "");

  // Print out the number of muons in the different histograms to make sure they add up right.
  std::cout << "nentries: " << h->GetEntries() << std::endl;

  // Set the title info for the histogram.
  h->SetTitle(title);
  h->GetXaxis()->SetTitle(xtitle);
  h->GetYaxis()->SetTitle(ytitle);
  h->SetName(name);
  std::cout << "xtitle: " << h->GetXaxis()->GetTitle() << std::endl;
  std::cout << "title: " << h->GetTitle() << std::endl;

  h->Draw("colz");
  std::cout << "nxbins: " << h->GetXaxis()->GetNbins() << std::endl;
  std::cout << "nybins: " << h->GetYaxis()->GetNbins() << std::endl;
  std::cout << "nbinsx: " << h->GetNbinsX() << std::endl;

  return h;
}
Exemplo n.º 2
0
int main(int argc, char** argv){

 ///==================================================
 ///==== Draw Distribution with and without scale ====
 ///==================================================

 ///===============================================================================
 gROOT->Reset();
 gROOT->SetStyle("Plain");
 gStyle->SetPalette(1);
 gStyle->SetOptStat(0);
 gStyle->SetOptFit(0);

 const Int_t __NRGBs = 5;
 const Int_t __NCont = 76;
 Double_t __stops[__NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
 Double_t __red[__NRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
 Double_t __green[__NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
 Double_t __blue[__NRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };

 TColor::CreateGradientColorTable(__NRGBs, __stops, __red, __green, __blue, __NCont);
 gStyle->SetNumberContours(__NCont);
 ///===============================================================================
 

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

 // Parse the config file
 parseConfigFile (argv[1]) ;

 std::string treeNameDATA  = gConfigParser -> readStringOption("InputDATA::treeName");
 std::string inputFileDATA = gConfigParser -> readStringOption("InputDATA::inputFile");
 double luminosity = gConfigParser -> readDoubleOption("InputDATA::luminosity");
 std::cout << ">>>>> InputDATA::treeName   " << treeNameDATA  << std::endl;
 std::cout << ">>>>> InputDATA::inputFile  " << inputFileDATA  << std::endl;
 std::cout << ">>>>> InputDATA::luminosity " << luminosity  << std::endl;

 std::string treeNameMC  = gConfigParser -> readStringOption("InputMC::treeName");
 std::vector< std::string > inputFileMC = gConfigParser -> readStringListOption("InputMC::inputFile");
 std::vector< std::string > inputSampleMC = gConfigParser -> readStringListOption("InputMC::nameSample");
 std::vector< double > xSecAndEfficiency = gConfigParser -> readDoubleListOption("InputMC::xsecEff");

 std::cout << ">>>>> InputMC::treeName  " << treeNameMC  << std::endl;
 std::cout << ">>>>> InputMC::inputFile size " << inputFileMC.size()  << std::endl;
 if (inputFileMC.size() != xSecAndEfficiency.size() || inputFileMC.size() != inputSampleMC.size()) {
     std::cerr << " >>>> Error: different number of samples and cross sections" << std::endl;
     return 0;
    }
 int nMC = inputFileMC.size();
 for (int iMC = 0; iMC < nMC; iMC++) {
    std::cout << ">>>>> InputMC::inputFile[" << iMC << "] = " << inputSampleMC.at(iMC) << " => " << inputFileMC.at(iMC)  << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity * xSecAndEfficiency.at(iMC) << std::endl;
 }


 int binX = gConfigParser -> readIntOption("Options::binX");
 double minX = gConfigParser -> readDoubleOption("Options::minX");
 double maxX = gConfigParser -> readDoubleOption("Options::maxX");
 std::string variableX = gConfigParser -> readStringOption("Options::variableX");
 std::cout << ">>>>> Options::binX      " << binX  << std::endl;
 std::cout << ">>>>> Options::minX      " << minX  << std::endl;
 std::cout << ">>>>> Options::maxX      " << maxX  << std::endl;
 std::cout << ">>>>> Options::variableX " << variableX.c_str() << std::endl;

 int binY = gConfigParser -> readIntOption("Options::binY");
 double minY = gConfigParser -> readDoubleOption("Options::minY");
 double maxY = gConfigParser -> readDoubleOption("Options::maxY");
 std::string variableY = gConfigParser -> readStringOption("Options::variableY");
 std::cout << ">>>>> Options::binY      " << binY  << std::endl;
 std::cout << ">>>>> Options::minY      " << minY  << std::endl;
 std::cout << ">>>>> Options::maxY      " << maxY  << std::endl;
 std::cout << ">>>>> Options::variableY " << variableY.c_str() << std::endl;
 
 int binRatio = gConfigParser -> readIntOption("Options::binRatio");
 double minRatio = gConfigParser -> readDoubleOption("Options::minRatio");
 double maxRatio = gConfigParser -> readDoubleOption("Options::maxRatio");
 std::cout << ">>>>> Options::minRatio      " << minRatio  << std::endl;
 std::cout << ">>>>> Options::maxRatio      " << maxRatio  << std::endl;
 
 
 std::string outputFile = gConfigParser -> readStringOption("Output::outputFile");
 std::cout << ">>>>> Output::outputFile  " << outputFile  << std::endl;


//  TString AdditionalCut = Form("eta > 1.5");// || eta < -1.5)");// && eleFBrem<0.5");
 TString AdditionalCut = Form("eta < -1.5");// || eta < -1.5)");// && eleFBrem<0.5");
//  TString AdditionalCut = Form("(eta > 1.5 || eta < -1.5)");// && abs(eleFBrem)<1");
 
 
 
 EColor vColor[100] = {
  kBlue,(EColor)(kBlue+1),(EColor) (kBlue+2),
  kRed,(EColor) (kRed+1),(EColor) (kRed+2),
  kGreen,(EColor) (kGreen+1),(EColor) (kGreen+2),
  kTeal,(EColor) (kTeal+1),
  kOrange,(EColor) (kOrange+1),
  kMagenta,(EColor) (kMagenta+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)};
 
 ///==== DATA ====
 TFile* fileInDATA = new TFile(inputFileDATA.c_str(),"READ");

 ///==== W ====
 TFile* fileInMC[nMC];
 for (int iMC = 0; iMC < nMC; iMC++) {
    fileInMC[iMC] = new TFile(inputFileMC.at(iMC).c_str(),"READ");
 }

 ///==== output ====
 TFile* outFile = new TFile(outputFile.c_str(),"RECREATE");
 outFile->cd();


 ///==== Prepare input trees ====
 TLegend* leg = new TLegend(0.55,0.7,0.95,0.95);
 leg->SetFillColor(0);

 TLegend* legDown = new TLegend(0.55,0.1,0.95,0.35);
 legDown->SetFillColor(0);

 TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str());
 int initialNumber;
 TH2F* HistoDATA = new TH2F("DATA","DATA",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioDATA = new TH1F("RatioDATA","RatioDATA",binRatio,minRatio,maxRatio);
 TString DrawDATA = Form("%s:%s >> DATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoDATA->SetMarkerSize(1);
 HistoDATA->SetMarkerStyle(20); 
 HistoDATA->GetXaxis()->SetTitle(variableX.c_str());
 HistoDATA->GetYaxis()->SetTitle(variableY.c_str());
 leg->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");
 legDown->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");

 DrawDATA = Form("(%s) / (%s) >> RatioDATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoRatioDATA->SetMarkerSize(1);
 HistoRatioDATA->SetMarkerStyle(20); 
 HistoRatioDATA->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
 
 TH2F* HistoMC[nMC];
 TH1F* HistoRatioMC[nMC];

 TH2F* HistoMC_SUM = new TH2F("HistoMC_SUM","HistoMC_SUM",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioMC_SUM = new TH1F("HistoRatioMC_SUM","HistoRatioMC_SUM",binRatio,minRatio,maxRatio);
 
 SetColorAndStyleHisto(*(HistoRatioMC_SUM),kBlue); 
 
 TTree* MyTreeMC[nMC];
 THStack* hsMC = new THStack("hsMC","hsMC");
 
 double MC_Expected = 0;
 
 for (int iMC = 0; iMC < nMC; iMC++) {
// for (int iMC = nMC-1; iMC >= 0; iMC--) {
  MyTreeMC[iMC] = (TTree*) fileInMC[iMC]->Get(treeNameMC.c_str());
  MyTreeMC[iMC]->SetBranchAddress("initialNumber",&initialNumber);
  MyTreeMC[iMC]->GetEntry(0);
  xSecAndEfficiency.at(iMC) = xSecAndEfficiency.at(iMC) / initialNumber; ///==== normalize to initial number of events
  HistoMC[iMC] = new TH2F(inputSampleMC.at(iMC).c_str(),inputSampleMC.at(iMC).c_str(),binX,minX,maxX,binY,minY,maxY);
  HistoRatioMC[iMC] = new TH1F(Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),binRatio,minRatio,maxRatio);
  
  TString Draw = Form("%s:%s >> %s",variableY.c_str(),variableX.c_str(),inputSampleMC.at(iMC).c_str());
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());

  Draw = Form("(%s) / (%s) >> %s",variableY.c_str(),variableX.c_str(),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()));
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());  
  HistoRatioMC[iMC]->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  std::cout << ">>>>>> " << inputSampleMC.at(iMC) << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity << " : " << HistoMC[iMC]->GetEntries() << " = " << luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries() << std::endl;
  std::cout << "    >> " << Draw.Data() << std::endl;
  std::cout << "    >> " << HistoMC[iMC]->GetEntries() << " Entries" << std::endl;
 
  MC_Expected += luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries();
  
  HistoMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  HistoRatioMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  
  SetColorAndStyleHisto(*(HistoMC[iMC]),vColor[iMC]);
  SetColorAndStyleHisto(*(HistoRatioMC[iMC]),vColor[iMC]);
  
  HistoMC[iMC]->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC[iMC]->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoMC_SUM->Add(HistoMC[iMC]);
  HistoMC_SUM->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC_SUM->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoRatioMC_SUM->Add(HistoRatioMC[iMC]);
  HistoRatioMC_SUM->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  hsMC->Add(HistoMC[iMC]);
  if (iMC == 0) hsMC->Add(HistoMC[iMC]);
  leg->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
  legDown->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
 }
  
  
 ///==== make fit ====
 
 TH1D* htemp_prof = smartGausProfileXSQRTN(HistoDATA,2);  
 TGraphErrors grH = buildGEfromH_Personalized(*htemp_prof);
 grH.SetMarkerStyle(22);
 grH.SetMarkerSize(0.7);
 grH.SetMarkerColor(kBlue);
 grH.SetFillColor(kBlue);
 grH.SetFillStyle(3335);
 grH.SetLineWidth(1);
 grH.SetLineColor(kBlue);
 grH.GetXaxis()->SetTitle(variableX.c_str());
 grH.GetYaxis()->SetTitle(variableY.c_str());
 

 ///----------------------
 ///---- Plot results ----
 ///----------------------
 std::cerr << " MC expected : DATA = " << MC_Expected << " : " << HistoDATA->GetEntries() << std::endl;
 
 std::cerr << " HistoDATA->GetMaximum() = " << HistoDATA->GetMaximum() << std::endl;
 std::cerr << " HistoDATA->GetEntries() = " << HistoDATA->GetEntries() << std::endl;
 outFile->cd();
 
 TCanvas cResultDistro("cResultDistro","cResultDistro",900,900);
 cResultDistro.Divide(2,2);
 cResultDistro.cd(1);
 HistoDATA->DrawClone("colz");
 gPad->SetGrid();
 TString tLumiName = Form("#int L = %.4f pb^{-1}",luminosity);
 TLatex tLumi(1.5 * HistoDATA->GetMean(1),0.2 * HistoDATA->GetMaximum(),tLumiName.Data());
 tLumi.DrawClone();
 
 
 cResultDistro.cd(2);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 TString tEleName = Form("%d electrons",(int) HistoDATA->GetEntries());
 TLatex tEle(2.0 * HistoRatioDATA->GetMean(1),0.3 * HistoRatioDATA->GetMaximum(),tEleName.Data());
 tEle.DrawClone();
 gPad->SetGrid();

 
 cResultDistro.cd(3);
 grH.Draw("APL");
 double minFit = gConfigParser -> readDoubleOption("Options::minFit");
 double maxFit = gConfigParser -> readDoubleOption("Options::maxFit");
 std::cout << ">>>>> Options::minFit      " << minFit  << std::endl;
 std::cout << ">>>>> Options::maxFit      " << maxFit  << std::endl;
 
 TF1* funz = new TF1 ("funz","pol1",minFit,maxFit);
//  funz->FixParameter(0,0);
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 grH.Fit("funz","RMQ");
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffDATA = funz->GetParameter(1);
 double errCoeffDATA = funz->GetParError(1);
 
 gPad->SetGrid();
 
 
 cResultDistro.cd(4);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 tEle.DrawClone();
 gPad->SetGrid();
 gPad->SetLogy();
 
 
 TString nameImage = Form("%s_%s_%d.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImage.Data());
 TString nameImageRoot = Form("%s_%s_%d.root",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImageRoot.Data());

 
 
 TCanvas cResultDistroMC("cResultDistroMC","cResultDistroMC",800,800);
 cResultDistroMC.Divide(2,2);
 
 //  cResultDistroMC.Divide(2,nMC);
//  for (int iMC = 0; iMC < nMC; iMC++) {
//   cResultDistroMC.cd(2*iMC+1);
//   HistoMC[iMC]->DrawClone("colz");
//   HistoDATA->DrawClone("BOXsame");
//   cResultDistroMC.cd(2*iMC+2);
//   HistoRatioMC[iMC]->DrawNormalized("");
//   HistoRatioDATA->DrawNormalized("E1same");  
//  }

 cResultDistroMC.cd(1);
 HistoMC_SUM->DrawClone("colz");
 HistoDATA->DrawClone("BOXsame");
 gPad->SetGrid();
 
 ///==== make fit ====
 
 cResultDistroMC.cd(3);
 
 TH1D* MChtemp_prof = smartGausProfileXSQRTN(HistoMC_SUM,2);  
 TGraphErrors MCgrH = buildGEfromH_Personalized(*MChtemp_prof);
 MCgrH.SetMarkerStyle(22);
 MCgrH.SetMarkerSize(0.7);
 MCgrH.SetMarkerColor(kRed);
 MCgrH.SetFillColor(kRed);
 MCgrH.SetFillStyle(3335);
 MCgrH.SetLineWidth(1);
 MCgrH.SetLineColor(kRed);
 MCgrH.GetXaxis()->SetTitle(variableX.c_str());
 MCgrH.GetYaxis()->SetTitle(variableY.c_str());
 
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 MCgrH.Fit("funz","RMQ");
 
 std::cerr << " ================= " << std::endl;
 std::cerr << " ======= MC ====== " << std::endl;
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffMC = funz->GetParameter(1);
 double errCoeffMC = funz->GetParError(1);
 
 MCgrH.Draw("APL");
 gPad->SetGrid();
 
 
 cResultDistroMC.cd(4);
 MCgrH.Draw("APL");
 grH.Draw("PLSAME");
 gPad->SetGrid();
 
 
 TString nameImageLog = Form("%s_%s_%d_MC.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistroMC.SaveAs(nameImageLog.Data());
  
 
 std::cerr << " 1 - alpha = " << coeffDATA / coeffMC 
           << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
           << std::endl;


 std::cerr << " alpha = " << 1-coeffDATA / coeffMC 
	   << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
	   << std::endl;
   
   

//  TCanvas cResultDistro_1("cResultDistro_1","cResultDistro_1",800,800);
//  HistoRatioMC_SUM->Draw();
//  HistoRatioDATA->Draw("E1same");
//  tEle.DrawClone();
//  gPad->SetGrid();
//  gPad->SetLogy();
   
}
Exemplo n.º 3
0
void rulevisHists( TDirectory *rfdir, TDirectory *vardir, TDirectory *corrdir, TMVAGlob::TypeOfPlot type) {
   //
   if (rfdir==0)   return;
   if (vardir==0)  return;
   if (corrdir==0) return;
   //
   const TString rfName    = rfdir->GetName();
   const TString maintitle = rfName + " : Rule Importance";
   const TString rfNameOpt = "_RF2D_";
   const TString outfname[TMVAGlob::kNumOfMethods] = { "rulevisHists",
                                                       "rulevisHists_decorr",
                                                       "rulevisCorr_pca",
                                                       "rulevisCorr_gaussdecorr" };

   const TString outputName = outfname[type]+"_"+rfdir->GetName();
   //
   TIter rfnext(rfdir->GetListOfKeys());
   TKey *rfkey;
   Double_t rfmax;
   Double_t rfmin;
   Bool_t allEmpty=kTRUE;
   Bool_t first=kTRUE;
   while ((rfkey = (TKey*)rfnext())) {
      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(rfkey->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;
      TH2F *hrf = (TH2F*)rfkey->ReadObj();
      TString hname= hrf->GetName();
      if (hname.Contains("__RF_")){ // found a new RF plot
         Double_t valmin = hrf->GetMinimum();
         Double_t valmax = hrf->GetMaximum();
         if (first) {
            rfmin=valmin;
            rfmax=valmax;
            first = kFALSE;
         } else {
            if (valmax>rfmax) rfmax=valmax;
            if (valmin<rfmin) rfmin=valmin;
         }
         if (hrf->GetEntries()>0) allEmpty=kFALSE;
      }
   }
   if (first) {
      cout << "ERROR: no RF plots found..." << endl;
      return;
   }

   const Int_t nContours = 100;
   Double_t contourLevels[nContours];
   Double_t dcl = (rfmax-rfmin)/Double_t(nContours-1);
   //
   for (Int_t i=0; i<nContours; i++) {
      contourLevels[i] = rfmin+dcl*Double_t(i);
   }

   ///////////////////////////
   vardir->cd();
 
   // how many plots are in the directory?
   Int_t noPlots = ((vardir->GetListOfKeys())->GetEntries()) / 2;
 
   // define Canvas layout here!
   // default setting
   Int_t xPad;  // no of plots in x
   Int_t yPad;  // no of plots in y
   Int_t width; // size of canvas
   Int_t height;
   switch (noPlots) {
   case 1:
      xPad = 1; yPad = 1; width = 500; height = 0.7*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.7*width; break;
   case 3:
      xPad = 3; yPad = 1; width = 900; height = 0.4*width; break;
   case 4:
      xPad = 2; yPad = 2; width = 600; height = width; break;
   default:
      xPad = 3; yPad = 2; width = 800; height = 0.7*width; break;
   }
   Int_t noPad = xPad * yPad ;   

   // this defines how many canvases we need
   const Int_t noCanvas = 1 + (Int_t)((noPlots - 0.001)/noPad);
   TCanvas **c = new TCanvas*[noCanvas];
   for (Int_t ic=0; ic<noCanvas; ic++) c[ic] = 0;

   // counter variables
   Int_t countCanvas = 0;
   Int_t countPad    = 1;

   // loop over all objects in directory
   TIter next(vardir->GetListOfKeys());
   TKey *key;
   TH1F *sigCpy=0;
   TH1F *bgdCpy=0;
   //
   Bool_t first = kTRUE;

   while ((key = (TKey*)next())) {

      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH1")) continue;
      sig = (TH1F*)key->ReadObj();
      TString hname= sig->GetName();

      // check for all signal histograms
      if (hname.Contains("__S")){ // found a new signal plot
         //         sigCpy = new TH1F(*sig);
         // create new canvas
         if ((c[countCanvas]==NULL) || (countPad>noPad)) {
            char cn[20];
            sprintf( cn, "rulehist%d_", countCanvas+1 );
            TString cname(cn);
            cname += rfdir->GetName();
            c[countCanvas] = new TCanvas( cname, maintitle,
                                          countCanvas*50+200, countCanvas*20, width, height ); 
            // style
            c[countCanvas]->Divide(xPad,yPad);
            countPad = 1;
         }       

         // save canvas to file
         TPad *cPad = (TPad *)(c[countCanvas]->GetPad(countPad));
         c[countCanvas]->cd(countPad);
         countPad++;

         // find the corredponding background histo
         TString bgname = hname;
         bgname.ReplaceAll("__S","__B");
         hkey = vardir->GetKey(bgname);
         bgd = (TH1F*)hkey->ReadObj();
         if (bgd == NULL) {
            cout << "ERROR!!! couldn't find backgroung histo for" << hname << endl;
            exit;
         }

         TString rfname = hname;
         rfname.ReplaceAll("__S","__RF");
         TKey *hrfkey = rfdir->GetKey(rfname);
         TH2F *hrf = (TH2F*)hrfkey->ReadObj();
         Double_t wv = hrf->GetMaximum();
         //         if (rfmax>0.0)
         //            hrf->Scale(1.0/rfmax);
         hrf->SetMinimum(rfmin); // make sure it's zero  -> for palette axis
         hrf->SetMaximum(rfmax); // make sure max is 1.0 -> idem
         hrf->SetContour(nContours,&contourLevels[0]);

         // this is set but not stored during plot creation in MVA_Factory
         //         TMVAGlob::SetSignalAndBackgroundStyle( sigK, bgd );
         sig->SetFillStyle(3002);
         sig->SetFillColor(1);
         sig->SetLineColor(1);
         sig->SetLineWidth(2);

         bgd->SetFillStyle(3554);
         bgd->SetFillColor(1);
         bgd->SetLineColor(1);
         bgd->SetLineWidth(2);

         // chop off "signal" 
         TString title(hrf->GetTitle());
         title.ReplaceAll("signal","");

         // finally plot and overlay       
         Float_t sc = 1.1;
         if (countPad==2) sc = 1.3;
         sig->SetMaximum( TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*sc );
         Double_t smax = sig->GetMaximum();

         if (first) {
            hrf->SetTitle( maintitle );
            first = kFALSE;
         } else {
            hrf->SetTitle( "" );
         }
         hrf->Draw("colz ah");
         TMVAGlob::SetFrameStyle( hrf, 1.2 );

         sig->Draw("same ah");
         bgd->Draw("same ah");
         // draw axis using range [0,smax]
         hrf->GetXaxis()->SetTitle( title );
         hrf->GetYaxis()->SetTitleOffset( 1.30 );
         hrf->GetYaxis()->SetTitle("Events");
         hrf->GetYaxis()->SetLimits(0,smax);
         hrf->Draw("same axis");

         cPad->SetRightMargin(0.13);
         cPad->Update();

         // Draw legend
         if (countPad==2){
            TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                          1-cPad->GetTopMargin()-.18, 
                                          cPad->GetLeftMargin()+.4, 
                                          1-cPad->GetTopMargin() );
            legend->AddEntry(sig,"Signal","F");
            legend->AddEntry(bgd,"Background","F");
            legend->Draw("same");
            legend->SetBorderSize(1);
            legend->SetMargin( 0.3 );
            legend->SetFillColor(19);
            legend->SetFillStyle(1);
         } 

         // save canvas to file
         if (countPad > noPad) {
            c[countCanvas]->Update();
            TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
            TMVAGlob::imgconv( c[countCanvas], fname );
            //        TMVAGlob::plot_logo(); // don't understand why this doesn't work ... :-(
            countCanvas++;
         }
      }
   }

   if (countPad <= noPad) {
      c[countCanvas]->Update();
      TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
      TMVAGlob::imgconv( c[countCanvas], fname );
   }
}
Exemplo n.º 4
0
void createEntry(TString infostream, std::vector<TString> fileList_, bool save, unsigned int verbose){

  // extract relavant information from infostream
  TString recoTreeLocation        =getStringEntry(infostream,1,":");
  TString genTreeLocation         =getStringEntry(infostream,2,":");
  TString outputRecoFolderLocation=getStringEntry(infostream,3,":");
  TString outputGenFolderLocation =getStringEntry(infostream,4,":");
  TString newVarName              =getStringEntry(infostream,5,":");
  TString newVarBinning           =getStringEntry(infostream,6,":");
  TString fillFrom                =getStringEntry(infostream,7,":");
  TString eventWeight             =getStringEntry(infostream,8,":");
  TString withCondition           =getStringEntry(infostream,9,":");

  //loop files
  for(unsigned int fileix=0; fileix<fileList_.size(); ++fileix){
    TString name=fileList_[fileix];
    if(verbose>1) std::cout  << std::endl << "processing file " << name << std::endl;
    // check if ttbarSG file is processed
    bool ttbarSG= (name.Contains("Sig")) ? true : false;
    bool ttbarCentral = (ttbarSG&&!(name.Contains("Up")||name.Contains("Down")||name.Contains("Mcatnlo")||name.Contains("Powheg"))) ? true : false;
    // container for values read from tree
    std::map< TString, float > value_;
    // A open file
    TFile* file = TFile::Open(name, "Update");
    if(!file||file->IsZombie()) std::cout << "ERROR: file " << name << " does not exist or is broken" << std::endl;
    else{
      file->cd();
      // B1 open reco tree
      TTree* recotree=(TTree*)(file->Get(recoTreeLocation+"/tree")->Clone());
      if(!recotree||recotree->IsZombie()){
	std::cout << "ERROR: can not load the chosen recotree " << recoTreeLocation+"/tree in file " << name << std::endl;
      }
      else{
	// info output
	if(fileix==0&&verbose>1) std::cout << "recotree: " << recoTreeLocation+"/tree" << std::endl;
	// activate all branches
	recotree->SetBranchStatus("*",1);
	// get all branches from recotree
	TObjArray* branches=recotree->GetListOfBranches();
	// loop all branches
	TObjArrayIter branch(branches);
	TObject* object;
	while ( ( object = branch() ) ) {
	  // get single branch
	  TString branchname=(TString)object->GetName();
	  // info output
	  if(fileix==0&&verbose>1) std::cout << "->reco branch : " << branchname << std::endl;	  
	  // set branch address for access
	  recotree->SetBranchAddress(branchname,(&value_[branchname]));
	}
	// B2a create reco histo
	int nbins =(getStringEntry(newVarBinning,1,",")).Atoi();
	double min=(getStringEntry(newVarBinning,2,",")).Atof();
	double max=(getStringEntry(newVarBinning,3,",")).Atof();
	TH1F* newRecPlot=new TH1F( newVarName+"Rec", newVarName, nbins , min , max);
	// B2b create reco branch entry 
	Float_t newRec1;
	Float_t newRec2;
	TBranch *newRecBranch1 = recotree->Branch(newVarName+"Lep", &newRec1, newVarName+"Lep"+"/F");
	TBranch *newRecBranch2 = recotree->Branch(newVarName+"Had", &newRec2, newVarName+"Had"+"/F");
	// info output
	if(fileix==0&&verbose>1){
	  std::cout << "will add new reco plot: new TH1F(" << newVarName << ", " << newVarName;
	  std::cout << ", " << nbins <<  ", " << min << ", " << max << ") in " << outputRecoFolderLocation << std::endl;
	  std::cout << "will add new branches " << newVarName+"Lep" << " and " << newVarName+"Had";
	  std::cout << ") in tree " << recoTreeLocation+"/tree" << std::endl;
	}
	// B3a create gen-reco histo
	TH2F* newRecGenPlot;
	Float_t newRecGen1;
	Float_t newRecGen2;
	TBranch *newRecGenBranch1 =0;
	TBranch *newRecGenBranch2 =0;
	if(ttbarSG){
	  newRecGenPlot=new TH2F( newVarName+"_", newVarName+"_", nbins , min , max, nbins , min , max);
	  if(fileix==0&&verbose>1){
	    std::cout << "will add new gen-reco plot: new TH2F(" << newVarName+"_" << ", " << newVarName+"_";
	    std::cout << ", " << nbins <<  ", " << min << ", " << max << ", " << std::endl;
	    std::cout << ", " << nbins <<  ", " << min << ", " << max << ")" << std::endl;
	  }
	  // B3b create gen branch entry 
	  newRecGenBranch1 = recotree->Branch(newVarName+"Lep"+"PartonTruth", &newRecGen1, newVarName+"Lep"+"PartonTruth"+"/F");
	  newRecGenBranch2 = recotree->Branch(newVarName+"Had"+"PartonTruth", &newRecGen2, newVarName+"Had"+"PartonTruth"+"/F");
	}
	// B4 fill reco plots from tree
	// loop recotree
	for(unsigned int event=0; event<recotree->GetEntries(); ++event){
	  recotree->GetEntry(event);
	  // B4a fill rec branch
	  newRec1=value_["topPtLep"]*value_["topPtLep"];
	  newRec2=value_["topPtHad"]*value_["topPtHad"];
	  newRecBranch1->Fill();
	  newRecBranch2->Fill();
	  // B4b fill rec plot
	  newRecPlot->Fill(newRec1, value_["weight"]);
	  newRecPlot->Fill(newRec2, value_["weight"]);
	  // fill rec-gen plot
	  if(newRecGenPlot){
	    newRecGen1=value_["topPtLepPartonTruth"]*value_["topPtLepPartonTruth"];
	    newRecGen2=value_["topPtHadPartonTruth"]*value_["topPtHadPartonTruth"];
	    newRecGenBranch1->Fill();
	    newRecGenBranch2->Fill();
	    newRecGenPlot->Fill(newRecGen1, newRec1, value_["weight"]);
	    newRecGenPlot->Fill(newRecGen2, newRec2, value_["weight"]);	    
	  }
	}
	// B5 saving
	if(save){
	  if(fileList_.size()==1){
	    TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", ""));
	    if(newRecPlot   ) saveToRootFile("test.root", newRecPlot   , true, 1, outputRecoFolderLocation+"/"+debugName);
	    if(newRecGenPlot) saveToRootFile("test.root", newRecGenPlot, true, 1, outputRecoFolderLocation+"/"+debugName);
	  }
	  file->cd(outputRecoFolderLocation);
	  if(newRecPlot   ) newRecPlot   ->Write(newRecPlot->GetTitle()   , TObject::kOverwrite);
	  if(newRecGenPlot) newRecGenPlot->Write(newRecGenPlot->GetTitle(), TObject::kOverwrite);
	  if(recotree) recotree->Write(recotree->GetTitle(), TObject::kOverwrite);
	  file->cd();
	} // end if save
      } // end if recotree
      if(ttbarSG){
	if(verbose>1) std::cout << "-> ttbarSG file! gen and reco-gen will be derived" << std::endl;
	// C open gen tree
	TTree* gentree=(TTree*)(file->Get(genTreeLocation+"/tree")->Clone());
	if(!gentree||gentree->IsZombie()){
	  std::cout << "ERROR: can not load the chosen gentree " << genTreeLocation+"/tree in file " << name << std::endl;
	}
	else{
	  // info output
	  if(fileix==0&&verbose>1) std::cout << "gentree: " << genTreeLocation+"/tree" << std::endl;
	  // activate all branches
	  gentree->SetBranchStatus("*",1);
	  // get all branches from recotree
	  TObjArray* branches=gentree->GetListOfBranches();
	  // loop all branches
	  TObjArrayIter branch(branches);
	  TObject* object;
	  while ( ( object = branch() ) ) {
	    // get single branch
	    TString branchname=(TString)object->GetName();
	    // info output
	    if(fileix==0&&verbose>1) std::cout << "->gen branch : " << branchname << std::endl;	  
	    // set branch address for access
	    gentree->SetBranchAddress(branchname,(&value_[branchname]));
	  }
	  // C2a create gen histo
	  int nbins =(getStringEntry(newVarBinning,1,",")).Atoi();
	  double min=(getStringEntry(newVarBinning,2,",")).Atof();
	  double max=(getStringEntry(newVarBinning,3,",")).Atof();
	  TH1F* newGenPlot=new TH1F( newVarName+"Gen", newVarName, nbins , min , max);
	  // C2b create gen branch entry 
	  Float_t newGen1;
	  Float_t newGen2;
	  TBranch *newGenBranch1 = gentree->Branch(newVarName+"Lep", &newGen1, newVarName+"Lep"+"/F");
	  TBranch *newGenBranch2 = gentree->Branch(newVarName+"Had", &newGen2, newVarName+"Had"+"/F");
	  // info output
	  if(fileix==0&&verbose>1){
	    std::cout << "will add new gen plot: new TH1F(" << newVarName << ", " << newVarName;
	    std::cout << ", " << nbins <<  ", " << min << ", " << max << ")" << std::endl;
	  }
	  // C3 fill gen plots from tree
	  // loop gentree
	  for(unsigned int event=0; event<gentree->GetEntries(); ++event){
	    gentree->GetEntry(event);
	    // C3a fill gen branches
	    newGen1=value_["topPtLep"]*value_["topPtLep"];
	    newGen2=value_["topPtHad"]*value_["topPtHad"];
	    newGenBranch1->Fill();
	    newGenBranch2->Fill();
	    // C3b fill gen plot
	    newGenPlot->Fill(newGen1, value_["weight"]);
	    newGenPlot->Fill(newGen2, value_["weight"]);
	  }
	  // C4 saving
	  if(save){
	    if(fileList_.size()==1){
	      TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", ""));
	      if(newGenPlot   ) saveToRootFile("test.root", newGenPlot   , true, 1, outputGenFolderLocation+"/"+debugName );
	    }
	    file->cd(outputGenFolderLocation);
	    if(newGenPlot) newGenPlot->Write(newGenPlot->GetTitle(), TObject::kOverwrite);
	    if(gentree ) gentree->Write(gentree->GetTitle(), TObject::kOverwrite);
	    file->cd();
	  } // end if save
	  // D process additional folders
	  if(verbose>1&&ttbarCentral) std::cout << "   -> central ttbarSG file! need to process additional folders for systematic variations" << std::endl;
	} // end if gentree
      } // end if ttbarSG
    } // end if file
    // close file
    file->Close();
  } // end loop files
}