예제 #1
0
  void getPlotData() {
    TH1 * h = (TH1*) m_file->Get(m_direc.c_str());

    for (int i=0; i<h->GetXaxis()->GetNbins(); i++) {
      m_xs.push_back(h->GetXaxis()->GetBinCenter(i));
      m_ys.push_back(h->GetBinContent(i));
    }

    m_plot->m_xAxisTitle = std::string(h->GetXaxis()->GetTitle());
    m_plot->m_yAxisTitle = std::string(h->GetYaxis()->GetTitle());
    m_plot->m_title = std::string(h->GetTitle());

    std::stringstream ssN, ssMu, ssSig, ssUF, ssOF;
    ssN << std::setprecision(4) << h->GetEntries();
    ssMu << std::setprecision(4) << h->GetMean();
    ssSig << std::setprecision(4) << h->GetRMS();
    ssUF << std::setprecision(4) << h->GetBinContent(0);
    ssOF << std::setprecision(4) << h->GetBinContent(h->GetNbinsX() + 1);

    m_statsTitles.push_back("N:");
    m_statsTitles.push_back("mu:");
    m_statsTitles.push_back("sig:");
    m_statsTitles.push_back("UF:");
    m_statsTitles.push_back("OF:");

    m_statsValues.push_back(ssN.str());
    m_statsValues.push_back(ssMu.str());
    m_statsValues.push_back(ssSig.str());
    m_statsValues.push_back(ssUF.str());
    m_statsValues.push_back(ssOF.str());
  }
void counts(int run, int lumistart, int lumiend, string type, map<string,vector<tripletI> > &cnt, vector<tripletD> &cntref, string hlttype, bool docnt, bool doref) {
   TString filename = basedir + Form("/DQM_V0001_HLTpb_R000%i.root",run);
   TFile *f = new TFile(filename);
   if (!f->IsOpen()) {
      cout << "Error, could not open " << filename << endl;
      return;
   }
   TString tdirname = Form("DQMData/Run %i/HLT/Run summary/TriggerRates/",run) + TString(type);
   f->cd(tdirname);
   TProfile *hlumi = (TProfile*) f->Get(Form("DQMData/Run %i/HLT/Run summary/LumiMonitoring/lumiVsLS",run));
   if (extrapol) extrapolate(hlumi);

   // if HLT: accept, error, pass L1 seed, pass prescaler, reject

   TIter next(gDirectory->GetListOfKeys());
   TKey *key;
   while ((key = (TKey*)next())) {
      TClass *cl = gROOT->GetClass(key->GetClassName());
      
      // it must be an histogram
      if (!cl->InheritsFrom("TH1")) continue;
      TH1 *h = (TH1*)key->ReadObj();

      // the name must match one of the requested patterns
      bool match=false; TString hname(h->GetName());
      for (vector<TRegexp>::const_iterator it=patterns.begin(); it!=patterns.end(); it++) {
         if (hname(*it).Length()!=0) {
            match=true;
            break;
         }
      }
      if (!match) continue;

      int nlumis = (lumiend+1-lumistart);

      if (extrapol) extrapolate(h);

      if (type != "HLT") fill(cnt[h->GetName()], h, run, lumistart, lumiend, docnt);
      else {
         string htitle(h->GetTitle());
         if (htitle.find(hlttype) == string::npos) continue;
         else {
            TString thepath; Ssiz_t from=0; TString(htitle).Tokenize(thepath,from," ");
            fill(cnt[thepath.Data()], h, run, lumistart, lumiend, docnt);
         }
      }
   }

   if (doref) {
      fill(cntref, hlumi, run, lumistart, lumiend);
   }

   f->Close();
   delete f;
}
예제 #3
0
  /** 
   * Create ratios to other data 
   * 
   * @param ib      Bin number  
   * @param res     Result
   * @param alice   ALICE result if any
   * @param cms     CMS result if any
   * @param all     Stack to add ratio to 
   */
  void Ratio2Stack(Int_t ib, TH1* res, TGraph* alice, TGraph* cms, THStack* all)
  {
    if (!all || !res || !(alice || cms)) return;

    Int_t        off  = 5*ib;
    TGraph*      gs[] = { (alice ? alice : cms), (alice ? cms : 0), 0 };
    TGraph**     pg   = gs;
    while (*pg) { 
      TGraph*     g = *pg;
      const char* n = (g == alice ? "ALICE" : "CMS");

      TH1*    r = static_cast<TH1*>(res->Clone(Form("ratio%s", n)));
      TString tit(r->GetTitle());
      tit.ReplaceAll("Corrected", Form("Ratio to %s", n));
      r->SetTitle(tit);
      r->SetMarkerColor(g->GetMarkerColor());
      r->SetLineColor(g->GetLineColor());

      TObject* tst = r->FindObject("legend");
      if (tst) r->GetListOfFunctions()->Remove(tst);

      for (Int_t i = 1; i <= r->GetNbinsX(); i++) {
	Double_t c = r->GetBinContent(i);
	Double_t e = r->GetBinError(i);
	Double_t o = g->Eval(r->GetBinCenter(i));
	if (o < 1e-12) { 
	  r->SetBinContent(i, 0);
	  r->SetBinError(i, 0);
	  continue;
	}
	r->SetBinContent(i, (c - o) / o + off);
	r->SetBinError(i, e / o);
      }
      all->Add(r);
      pg++;
    }
    TLegend* leg = StackLegend(all);
    if (!leg) return;
      
    TString   txt      = res->GetTitle();
    txt.ReplaceAll("Corrected P(#it{N}_{ch}) in ", "");
    if      (ib == 0) txt.Append(" "); // (#times1)");
    // else if (ib == 1) txt.Append(" (#times10)");
    else              txt.Append(Form(" (+%d)", off));

    TObject* dummy = 0;
    TLegendEntry* e = leg->AddEntry(dummy, txt, "p");
    e->SetMarkerStyle(res->GetMarkerStyle());
    e->SetMarkerSize(res->GetMarkerSize());
    e->SetMarkerColor(kBlack);
    e->SetFillColor(0);
    e->SetFillStyle(0);
    e->SetLineColor(kBlack);
  }
예제 #4
0
RooHistN::RooHistN(const TH1 &data1, const TH1 &data2, Double_t nominalBinWidth, Double_t nSigma, Double_t xErrorFrac) :
  TGraphAsymmErrors(), _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
{
  // Create a histogram from the asymmetry between the specified TH1 objects
  // which may have fixed or variable bin widths, but which must both have
  // the same binning. The asymmetry is calculated as (1-2)/(1+2). Error bars are
  // calculated using Binomial statistics. Prints a warning and rounds
  // any bins with non-integer contents. Use the optional parameter to
  // specify the confidence level in units of sigma to use for
  // calculating error bars. The nominal bin width specifies the
  // default used by addAsymmetryBin(), and is used to set the relative
  // normalization of bins with different widths. If not set, the
  // nominal bin width is calculated as range/nbins.

  initialize();
  // copy the first input histogram's name and title
  SetName(data1.GetName());
  SetTitle(data1.GetTitle());
  // calculate our nominal bin width if necessary
  if(_nominalBinWidth == 0) {
    const TAxis *axis= ((TH1&)data1).GetXaxis();
    if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins();
  }
  setYAxisLabel(Form("Asymmetry (%s - %s)/(%s + %s)",
		     data1.GetName(),data2.GetName(),data1.GetName(),data2.GetName()));
  // initialize our contents from the input histogram contents
  Int_t nbin= data1.GetNbinsX();
  if(data2.GetNbinsX() != nbin) {
    coutE(InputArguments) << "RooHistN::RooHistN: histograms have different number of bins" << endl;
    return;
  }
  for(Int_t bin= 1; bin <= nbin; bin++) {
    Axis_t x= data1.GetBinCenter(bin);
    if(fabs(data2.GetBinCenter(bin)-x)>1e-10) {
      coutW(InputArguments) << "RooHistN::RooHistN: histograms have different centers for bin " << bin << endl;
    }
    Stat_t y1= data1.GetBinContent(bin);
    Stat_t y2= data2.GetBinContent(bin);
    addAsymmetryBin(x,roundBin(y1),roundBin(y2),data1.GetBinWidth(bin),xErrorFrac);
  }
  // we do not have a meaningful number of entries
  _entries= -1;
}
예제 #5
0
RooHistN::RooHistN(const TH1 &data, Double_t nominalBinWidth, Double_t nSigma, RooAbsData::ErrorType etype, Double_t xErrorFrac) :
  TGraphAsymmErrors(), _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
{
  // Create a histogram from the contents of the specified TH1 object
  // which may have fixed or variable bin widths. Error bars are
  // calculated using Poisson statistics. Prints a warning and rounds
  // any bins with non-integer contents. Use the optional parameter to
  // specify the confidence level in units of sigma to use for
  // calculating error bars. The nominal bin width specifies the
  // default used by addBin(), and is used to set the relative
  // normalization of bins with different widths. If not set, the
  // nominal bin width is calculated as range/nbins.

  initialize();
  // copy the input histogram's name and title
  SetName(data.GetName());
  SetTitle(data.GetTitle());
  // calculate our nominal bin width if necessary
  if(_nominalBinWidth == 0) {
    const TAxis *axis= ((TH1&)data).GetXaxis();
    if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins();
  }
  // TH1::GetYaxis() is not const (why!?)
  setYAxisLabel(const_cast<TH1&>(data).GetYaxis()->GetTitle());
  
  // initialize our contents from the input histogram's contents
  Int_t nbin= data.GetNbinsX();
  for(Int_t bin= 1; bin <= nbin; bin++) {
    Axis_t x= data.GetBinCenter(bin);
    Stat_t y= data.GetBinContent(bin);
    Stat_t dy = data.GetBinError(bin) ;
    if (etype==RooAbsData::Poisson) {
      addBin(x,roundBin(y),data.GetBinWidth(bin),xErrorFrac);
    } else {
      addBinWithError(x,y,dy,dy,data.GetBinWidth(bin),xErrorFrac);
    }
  }
  // add over/underflow bins to our event count
  _entries+= data.GetBinContent(0) + data.GetBinContent(nbin+1);
}
예제 #6
0
void writeFile(const char* inRootFile)
{
  TFile inRoot(inRootFile);
  if(!inRoot.IsOpen()){
    cout << "Cannot open " << inRootFile << endl;
    return;
  }
  TIterator* iterator = inRoot.GetListOfKeys()->MakeIterator();
  TKey* key;

  TString outText = inRootFile;
  outText.Replace(0,outText.Last('/')+1,"");

  ofstream os(outText.Data());

  char buf[500];

  int count(0);
  while( (key=dynamic_cast<TKey*>(iterator->Next())) != 0){
    cout << key->GetName() << endl;
    TH1* h = (TH1*)inRoot.Get(key->GetName());
    if(h->GetDimension()!=1) continue;

    if(++count>1) break;

    int nBin = h->GetNbinsX();
    os << "name: " << h->GetName() << endl
       << "title: " << h->GetTitle() << endl
       << "bins: " << h->GetNbinsX() << endl
       << "min: " << h->GetXaxis()->GetBinLowEdge(1) 
       << ", max: " << h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()) << endl;

    for(int i=1; i<=nBin; i++){
      os << "bin: " << i << " value: " << (float)h->GetBinContent(i)
	 << " error: " << (float)h->GetBinError(i) << endl;
    }
  }
   
}
예제 #7
0
TString* get_var_names( Int_t nVars )
{
   const TString directories[6] = { "InputVariables_NoTransform",
                                    "InputVariables_DecorrTransform",
                                    "InputVariables_PCATransform",
				    "InputVariables_Id",
				    "InputVariables_Norm",
				    "InputVariables_Deco"};

   TDirectory* dir = 0;
   for (Int_t i=0; i<6; i++) {
      dir = (TDirectory*)Network_GFile->Get( directories[i] );
      if (dir != 0) break;
   }
   if (dir==0) {
      cout << "*** Big troubles in macro \"network.C\": could not find directory for input variables, "
           << "and hence could not determine variable names --> abort" << endl;
      return 0;
   }
   cout << "--> go into directory: " << dir->GetName() << endl;
   dir->cd();

   TString* vars = new TString[nVars];
   Int_t ivar = 0;

   // loop over all objects in directory
   TIter next(dir->GetListOfKeys());
   TKey* key = 0;
   while ((key = (TKey*)next())) {
      if (key->GetCycle() != 1) continue;

      if(!TString(key->GetName()).Contains("__S") &&
	 !TString(key->GetName()).Contains("__r")) continue;

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

      if (ivar > nVars-1) break;
   }      
   
   if (ivar != nVars-1) { // bias layer is also in nVars counts
      cout << "*** Troubles in \"network.C\": did not reproduce correct number of "
           << "input variables: " << ivar << " != " << nVars << endl;
   }

   return vars;

   // ------------- old way (not good) -------------

   //    TString fname = "weights/TMVAnalysis_MLP.weights.txt";
   //    ifstream fin( fname );
   //    if (!fin.good( )) { // file not found --> Error
   //       cout << "Error opening " << fname << endl;
   //       exit(1);
   //    }
   
   //    Int_t   idummy;
   //    Float_t fdummy;
   //    TString dummy = "";
   
   //    // file header with name
   //    while (!dummy.Contains("#VAR")) fin >> dummy;
   //    fin >> dummy >> dummy >> dummy; // the rest of header line
   
   //    // number of variables
   //    fin >> dummy >> idummy;
   //    // at this point, we should have idummy == nVars
   
   //    // variable mins and maxes
   //    TString* vars = new TString[nVars];
   //    for (Int_t i = 0; i < idummy; i++) fin >> vars[i] >> dummy >> dummy >> dummy;
   
   //    fin.close();
   
   //    return vars;
}
예제 #8
0
파일: variables.C 프로젝트: sixie/EWKAna
// input: - Input file (result from TMVA),
//        - normal/decorrelated/PCA
//        - use of TMVA plotting TStyle
void variables( TString fin = "TMVA.root", TString dirName = "InputVariables_Id", TString title = "TMVA Input Variables",
                Bool_t isRegression = kFALSE, Bool_t useTMVAStyle = kTRUE )
{
   TString outfname = dirName;
   outfname.ToLower(); outfname.ReplaceAll( "input", ""  );

   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // obtain shorter histogram title 
   TString htitle = title; 
   htitle.ReplaceAll("variables ","variable");
   htitle.ReplaceAll("and target(s)","");
   htitle.ReplaceAll("(training sample)","");

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );

   TDirectory* dir = (TDirectory*)file->Get( dirName );
   if (dir==0) {
      cout << "No information about " << title << " available in directory " << dirName << " of file " << fin << endl;
      return;
   }
   dir->cd();

   // how many plots are in the directory?
   Int_t noPlots = TMVAGlob::GetNumberOfInputVariables( dir ) +
      TMVAGlob::GetNumberOfTargets( dir );

   // 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 = 550; height = 0.90*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.50*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.55*width; break;
     xPad = 1; yPad = 1; width = 550; height = 0.90*width; break;
   }

   Int_t noPadPerCanv = xPad * yPad ;

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

   // loop over all objects in directory
   TCanvas* canv = 0;
   TKey*    key  = 0;
   Bool_t   createNewFig = kFALSE;
   TIter next(dir->GetListOfKeys());
   while ((key = (TKey*)next())) {
      if (key->GetCycle() != 1) continue;

      if (!TString(key->GetName()).Contains("__Signal") && 
          !(isRegression && TString(key->GetName()).Contains("__Regression"))) continue;

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

      //normalize to 1
      NormalizeHist(sig);      

      // create new canvas
      if (countPad%noPadPerCanv==0) {
         ++countCanvas;
         canv = new TCanvas( Form("canvas%d", countCanvas), title,
                             countCanvas*50+50, countCanvas*20, width, height );
         canv->Divide(xPad,yPad);
         canv->SetFillColor(kWhite);
         canv->Draw();
      }

      TPad* cPad = (TPad*)canv->cd(countPad++%noPadPerCanv+1);
      cPad->SetFillColor(kWhite);

      // find the corredponding backgrouns histo
      TString bgname = hname;
      bgname.ReplaceAll("__Signal","__Background");
      TH1 *bgd = (TH1*)dir->Get(bgname);
      if (bgd == NULL) {
         cout << "ERROR!!! couldn't find background histo for" << hname << endl;
         exit;
      }
      //normalize to 1
      NormalizeHist(bgd);


      // this is set but not stored during plot creation in MVA_Factory
      TMVAGlob::SetSignalAndBackgroundStyle( sig, (isRegression ? 0 : bgd) );            

      sig->SetTitle( TString( htitle ) + ": " + sig->GetTitle() );
      TMVAGlob::SetFrameStyle( sig, 1.2 );

      // normalise both signal and background
//       if (!isRegression) TMVAGlob::NormalizeHists( sig, bgd );
//       else {
//          // change histogram title for target
//          TString nme = sig->GetName();
//          if (nme.Contains( "_target" )) {
//             TString tit = sig->GetTitle();
//             sig->SetTitle( tit.ReplaceAll("Input variable", "Regression target" ) );
//          }
//       }
      sig->SetTitle( "" );            
      

      // finally plot and overlay
      Float_t sc = 1.1;
      if (countPad == 1) sc = 1.3;
      sig->SetMaximum( TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*sc );
      sig->Draw( "hist" );
      cPad->SetLeftMargin( 0.17 );

      sig->GetYaxis()->SetTitleOffset( 1.50 );
      if (!isRegression) {
         bgd->Draw("histsame");
         TString ytit = TString("(1/N) ") + sig->GetYaxis()->GetTitle();
         ytit = TString("Fraction of Events");
         sig->GetYaxis()->SetTitle( ytit ); // histograms are normalised
      }

      if (countPad == 1) sig->GetXaxis()->SetTitle("Leading Lepton p_{T} [GeV/c]");
      if (countPad == 2) sig->GetXaxis()->SetTitle("Trailing Lepton p_{T} [GeV/c]");
      if (countPad == 3) sig->GetXaxis()->SetTitle("#Delta#phi(l,l)");
      if (countPad == 4) sig->GetXaxis()->SetTitle("#Delta R(l,l)");
      if (countPad == 5) sig->GetXaxis()->SetTitle("Dilepton Mass [GeV/c^{2}]");
      if (countPad == 6) sig->GetXaxis()->SetTitle("Dilepton Flavor Final State");
      if (countPad == 7) sig->GetXaxis()->SetTitle("M_{T} (Higgs) [GeV/c^{2}]");
      if (countPad == 8) sig->GetXaxis()->SetTitle("#Delta#phi(Dilepton System, MET)");
      if (countPad == 9) sig->GetXaxis()->SetTitle("#Delta#phi(Dilepton System, Jet)");


      // Draw legend
//       if (countPad == 1 && !isRegression) {
         TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                       1-cPad->GetTopMargin()-.15, 
                                       cPad->GetLeftMargin()+.4, 
                                       1-cPad->GetTopMargin() );

         if(countPad == 1 || countPad == 2 ||countPad == 3 ||countPad == 4 ||countPad == 5 ||countPad == 7  ) {
           legend= new TLegend( 0.50, 
                                1-cPad->GetTopMargin()-.15, 
                                0.90, 
                                1-cPad->GetTopMargin() );
         }

         legend->SetFillStyle(0);
         legend->AddEntry(sig,"Signal","F");
         legend->AddEntry(bgd,"Background","F");
         legend->SetBorderSize(0);
         legend->SetMargin( 0.3 );
         legend->SetTextSize( 0.03 );
         legend->Draw("same");
//       } 

      // redraw axes
      sig->Draw("sameaxis");

      // text for overflows
      Int_t    nbin = sig->GetNbinsX();
      Double_t dxu  = sig->GetBinWidth(0);
      Double_t dxo  = sig->GetBinWidth(nbin+1);
      TString uoflow = "";
      if (isRegression) {
         uoflow = Form( "U/O-flow: %.1f%% / %.1f%%", 
                        sig->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100 );
      }
      else {
         uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                        sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                        sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
      }
  
      TText* t = new TText( 0.98, 0.14, uoflow );
      t->SetNDC();
      t->SetTextSize( 0.040 );
      t->SetTextAngle( 90 );
//       t->AppendPad();    

      // save canvas to file
      if (countPad%noPadPerCanv==0) {
         TString fname = Form( "plots/%s_c%i", outfname.Data(), countCanvas );
         TMVAGlob::plot_logo();
         TMVAGlob::imgconv( canv, fname );
         createNewFig = kFALSE;
      }
      else {
         createNewFig = kTRUE;
      }
   }
   
   if (createNewFig) {
      TString fname = Form( "plots/%s_c%i", outfname.Data(), countCanvas );
      TMVAGlob::plot_logo();
      TMVAGlob::imgconv( canv, fname );
      createNewFig = kFALSE;
   }

   return;
}
예제 #9
0
파일: DrawKs.C 프로젝트: ktf/AliPhysics
TH1* GetCentK(TDirectory* top, Double_t c1, Double_t c2, Int_t s,
	      TLegend* l)
{
  TString dname; dname.Form("cent%06.2f_%06.2f", c1, c2);
  dname.ReplaceAll(".", "d");
  TDirectory* d = top->GetDirectory(dname);
  if (!d) {
    Warning("GetCetnK", "Directory %s not found in %s",
	    dname.Data(), top->GetName());
    return;
  }

  TDirectory* det = d->GetDirectory("details");
  if (!det) {
    Warning("GetCetnK", "Directory details not found in %s",
	    d->GetName());
    d->ls();
    return;
  }

  TObject* o = det->Get("scalar");
  if (!o) {
    Warning("GetCetnK", "Object scalar not found in %s",
	    det->GetName());
    return;
  }

  if (!o->IsA()->InheritsFrom(TH1::Class())) {
    Warning("GetCetnK", "Object %s is not a TH1, but a %s",
	    o->GetName(), o->ClassName());
    return;
  }
  TH1* h = static_cast<TH1*>(o->Clone());
  Color_t col = cc[(s-1)%10];
  h->SetLineColor(col);
  h->SetMarkerColor(col);
  h->SetFillColor(col);
  h->SetFillStyle(1001);
  // h->SetTitle(Form("%5.2f-%5.2f%% #times %d", c1, c2, s));
  h->SetTitle(Form("%2.0f-%2.0f%% + %d", c1, c2, s-1));
  TF1* f = new TF1("", "[0]",-2.2,2.2);
  f->SetParameter(0,s-1);
  f->SetLineColor(col);
  f->SetLineStyle(7);
  f->SetLineWidth(1);
  // h->Scale(s);
  h->Add(f);
  h->GetListOfFunctions()->Add(f);
  f->SetParameter(0,s);
  for (Int_t i = 1; i <= h->GetNbinsX(); i++) {
    if (TMath::Abs(h->GetBinCenter(i)) > 2) {
      h->SetBinContent(i,0);
      h->SetBinError(i,0);
    }
  }
  
  TLegendEntry* e = l->AddEntry(h, h->GetTitle(), "f");
  e->SetFillColor(col);
  e->SetFillStyle(1001);
  e->SetLineColor(col);

  return h;
}
예제 #10
0
void DrawTwoInPad(TVirtualPad* p,
                  Int_t        sub,
                  TH1*         h1,
                  TH1*         h2,
		  Bool_t       ratio,
		  Bool_t       logy=false,
		  Bool_t       legend=false)
{
  TVirtualPad* pp = p->cd(sub);
  pp->SetRightMargin(0.02);
  pp->SetLeftMargin(0.10);
  TVirtualPad* ppp = pp;
  if (ratio) {
    pp->Divide(1,2,0,0);
    ppp = pp->cd(1);				
    ppp->SetRightMargin(0.02);
  }
  if (logy) ppp->SetLogy();
  TH1* hs[] = { h1, h2, 0 };
  if (h1->GetMaximum() < h2->GetMaximum()) {
    hs[0] = h2;
    hs[1] = h1;
  }
  TH1** ph = hs;
  Double_t size = (ratio ? 0.1 : 0.05);
  Double_t off  = (ratio ? 0.6 : 0.5);
  h1->SetFillStyle(3004);
  h2->SetFillStyle(3005);
  while (*ph) {
    TString opt("hist");
    if (ph != hs) opt.Append(" same");

    TH1* copy = (*ph)->DrawCopy(opt);
    copy->GetXaxis()->SetLabelSize(2*size);
    copy->GetYaxis()->SetLabelSize(size);
    copy->GetYaxis()->SetTitleSize(size);
    copy->GetYaxis()->SetTitleOffset(off);
    copy->SetYTitle(copy->GetTitle());
    copy->SetTitle("");
    copy->SetDirectory(0);
    ph++;
  }
  TString s1 = h1->GetYaxis()->GetTitle();
  TString s2 = h2->GetYaxis()->GetTitle();
  
  if (legend) { 
    TLegend* l = new TLegend(0.6, 0.1, 0.9, 0.9);
    l->SetBorderSize(0);
    TLegendEntry* e = l->AddEntry("dummy", s1, "lf");
    l->SetFillColor(kWhite);
    e->SetFillColor(kBlack);
    e->SetFillStyle(h1->GetFillStyle());
    e = l->AddEntry("dummy", s2, "lf");
    e->SetFillColor(kBlack);
    e->SetFillStyle(h2->GetFillStyle());
    l->Draw();
  }
  if (!ratio) return;
  ppp = pp->cd(2);
  ppp->SetRightMargin(0.02);
  TH1* r = static_cast<TH1*>(h1->Clone(Form("ratio%s", h1->GetName())));
  r->SetDirectory(0);
  r->SetTitle("");
  r->GetXaxis()->SetLabelSize(size);
  r->GetYaxis()->SetLabelSize(size);
  r->GetYaxis()->SetTitleSize(0.9*size);
  r->GetYaxis()->SetTitleOffset(0.9*off);
  r->SetMarkerStyle(20);
  r->SetMarkerColor(h1->GetFillColor()+1);
  r->SetFillStyle(3007);
  r->SetYTitle(Form("#frac{%s}{%s}", s1.Data(), s2.Data()));

  // r->Add(h2, -1);
  // r->Divide(h1);
  if (!r->IsA()->InheritsFrom(TProfile::Class())) {
    r->GetSumw2()->Set(0); // r->Sumw2(false);
    h2->GetSumw2()->Set(0); // h2->Sumw2(false);
  }
  r->Divide(h2);
  Printf("%s", r->GetName());
  for (UShort_t bin = 1; bin <= r->GetNbinsX(); bin++) {
    Printf("  bin # %2d: Diff=%g+/-%g", bin, r->GetBinContent(bin),
	   r->GetBinError(bin));
    r->SetBinError(bin, 0);
  }
  r->GetSumw2()->Set(0); //r->Sumw2(false);
  r->SetMarkerSize(4);
  r->SetMaximum(r->GetMaximum()*1.2);
  r->SetMinimum(r->GetMinimum()*0.8);
  r->Draw("hist text30");  
  p->Modified();
  p->Update();
  p->cd();
}
예제 #11
0
TObjArray* ProcessSummary(TObjArray* arrs, int icl, const char* pref)
{
  // Process TObjArray (e.g. for set of pt bins) of TObjArray of KMCTrackSummary objects:
  // pick the KMCTrackSummary for "summary class" icl (definition of acceptable track) and create
  // graphs vs bin.
  // These graphs are returned in new TObjArray
  //
  TString prefs = pref;
  if (!gs) gs = new TF1("gs","gaus",-1,1);
  //
  int nb = arrs->GetEntriesFast();
  TObjArray* sums = (TObjArray*) arrs->At(0);
  int nclass = sums->GetEntriesFast();
  if (icl>=nclass) {printf("summary set has %d classes only, %d requested\n",nclass,icl);return 0;}
  //
  KMCTrackSummary* sm = (KMCTrackSummary*)sums->At(icl);
  //
  TH1* h;
  //
  h = sm->GetHMCSigDCARPhi();  // MC resolution in transverse DCA 
  TGraphErrors * grSigD = 0;
  if (h) {
    grSigD = new TGraphErrors(nb);
    grSigD->SetName(Form("%s%s",prefs.Data(),h->GetName()));
    grSigD->SetTitle(Form("%s%s",prefs.Data(),h->GetTitle()));
  }
  //
  TGraphErrors * grSigZ = 0;
  h = sm->GetHMCSigDCAZ();    // MC resolution in Z DCA
  if (h) {
    grSigZ = new TGraphErrors(nb);
    grSigZ->SetName(Form("%s%s",prefs.Data(),h->GetName()));
    grSigZ->SetTitle(Form("%s%s",prefs.Data(),h->GetTitle()));
  }
  //
  TGraphErrors * grSigAD = 0; // anaitical estimate for resolution in transverse DCA 
  {
    grSigAD = new TGraphErrors(nb);
    grSigAD->SetName(Form("%s%s",prefs.Data(),"sigmaDan"));
    grSigAD->SetTitle(Form("%s%s",prefs.Data(),"#sigmaD an"));
  }
  //
  TGraphErrors * grSigAZ = 0; // anaitical estimate for resolution in Z DCA 
  {
    grSigAZ = new TGraphErrors(nb);
    grSigAZ->SetName(Form("%s%s",prefs.Data(),"sigmaZan"));
    grSigAZ->SetTitle(Form("%s%s",prefs.Data(),"#sigmaZ an"));
  }
  //
  //
  TGraphErrors * grSigPt = 0; // MC res. in pt
  {
    grSigPt = new TGraphErrors(nb);
    grSigPt->SetName(Form("%s%s",prefs.Data(),"sigmaPt"));
    grSigPt->SetTitle(Form("%s%s",prefs.Data(),"#sigmaPt"));
  }
  //
  TGraphErrors * grSigAPt = 0; // analitycal res. in pt
  {
    grSigAPt = new TGraphErrors(nb);
    grSigAPt->SetName(Form("%s%s",prefs.Data(),"sigmaPtan"));
    grSigAPt->SetTitle(Form("%s%s",prefs.Data(),"#sigmaPt an"));
  }

  //
  TGraphErrors * grEff = 0; // MC efficiency
  {
    grEff = new TGraphErrors(nb);
    grEff->SetName(Form("%s_rate",prefs.Data()));
    grEff->SetTitle(Form("%s Rate",prefs.Data()));
  }
  //
  TGraphErrors * grUpd = 0; // number of Kalman track updates
  {
    grUpd = new TGraphErrors(nb);
    grUpd->SetName(Form("%s_updCalls",prefs.Data()));
    grUpd->SetTitle(Form("%s Updates",prefs.Data()));
  }
  //
  for (int ib=0;ib<nb;ib++) {
    sums = (TObjArray*) arrs->At(ib);
    sm = (KMCTrackSummary*)sums->At(icl);
    KMCProbe& prbRef = sm->GetRefProbe();
    KMCProbe& prbAn  = sm->GetAnProbe();
  
    double pt = prbRef.Pt();
    //
    if (grSigAD) {
      grSigAD->SetPoint(ib, pt,prbAn.GetSigmaY2()>0 ? TMath::Sqrt(prbAn.GetSigmaY2()) : 0.);
    }
    //
    if (grSigAZ) {
      grSigAZ->SetPoint(ib, pt,prbAn.GetSigmaZ2()>0 ? TMath::Sqrt(prbAn.GetSigmaZ2()) : 0.);
    }
    //
    if (grSigAPt) {
      double pts = TMath::Sqrt(prbAn.GetSigma1Pt2());
      grSigAPt->SetPoint(ib, pt,pts>0 ? pts*pt : 0.);
    }
    //
    if (grSigPt) {
      h = sm->GetHMCSigPt();
      h->Fit(gs,"0q");
      grSigPt->SetPoint(ib, pt, gs->GetParameter(2));
      grSigPt->SetPointError(ib, 0, gs->GetParError(2));
    }
    //
     if (grSigD) {
      h = sm->GetHMCSigDCARPhi();
      h->Fit(gs,"0q");
      grSigD->SetPoint(ib, pt,gs->GetParameter(2));
      grSigD->SetPointError(ib, 0,gs->GetParError(2));      
    }
    //
    if (grSigZ) {
      h = sm->GetHMCSigDCAZ();
      h->Fit(gs,"0q");
      grSigZ->SetPoint(ib, pt,gs->GetParameter(2));
      grSigZ->SetPointError(ib, 0,gs->GetParError(2));      
    }
    //
    if (grEff) {
      grEff->SetPoint(ib, pt,sm->GetEff());
      grEff->SetPointError(ib, 0,sm->GetEffErr());
    }
    //
    if (grUpd) {
      grUpd->SetPoint(ib, pt,sm->GetUpdCalls());
      grUpd->SetPointError(ib, 0, 0);
    }
  }
  //
  TObjArray* dest = new TObjArray();
  dest->AddAtAndExpand(grSigAD,kSigAD);
  dest->AddAtAndExpand(grSigAZ,kSigAZ);  
  dest->AddAtAndExpand(grSigAPt,kSigAPt);  
  dest->AddAtAndExpand(grSigD,kSigD);
  dest->AddAtAndExpand(grSigZ,kSigZ);  
  dest->AddAtAndExpand(grSigPt,kSigPt);  
  dest->AddAtAndExpand(grEff,kEff);
  dest->AddAtAndExpand(grUpd,kUpd);
  //
  if (!prefs.IsNull()) dest->SetName(pref);
  return dest;
}
예제 #12
0
void comparisonJetMCData(string plot,int rebin){
  string tmp;

  string dir="/gpfs/cms/data/2011/Observables/Approval/";
	
  if (isAngularAnalysis){
    mcfile=dir+"MC_zjets"+version;
    back_w=dir+"MC_wjets"+version;
    back_ttbar=dir+"MC_ttbar"+version;
    WW=dir+"MC_diW"+version;
    ZZ=dir+"MC_siZ"+version;
    WZ=dir+"MC_diWZ"+version;
    datafile=dir+"DATA"+version;
    mcfiletau=dir+"MC_zjetstau"+version;
  }
  // List of files

  TFile *dataf = TFile::Open(datafile.c_str()); //data file
  TFile *mcf = TFile::Open(mcfile.c_str()); //MC file
  TFile *mcftau = TFile::Open(mcfiletau.c_str()); //MC file
  TFile *ttbarf = TFile::Open(back_ttbar.c_str()); //MC background file
  TFile *wf = TFile::Open(back_w.c_str());


  TFile *qcd23emf = TFile::Open(qcd23em.c_str());
  TFile *qcd38emf = TFile::Open(qcd38em.c_str());
  TFile *qcd817emf = TFile::Open(qcd817em.c_str());

  TFile *qcd23bcf = TFile::Open(qcd23bc.c_str());
  TFile *qcd38bcf = TFile::Open(qcd38bc.c_str());
  TFile *qcd817bcf = TFile::Open(qcd817bc.c_str());

  TFile *WZf = TFile::Open(WZ.c_str());
  TFile *ZZf = TFile::Open(ZZ.c_str());
  TFile *WWf = TFile::Open(WW.c_str());


  // Canvas
  if (CanvPlot) delete CanvPlot;
  CanvPlot = new TCanvas("CanvPlot","CanvPlot",0,0,800,600);

  // Getting, defining ...
  dataf->cd("validationJEC");
  if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");
	
  TObject * obj;
  gDirectory->GetObject(plot.c_str(),obj);

  TH1 *data;
  TH2F *data2; 
  TH1D *data3; 

  THStack *hs = new THStack("hs","Total MC");


  int flag=-1;
  if ((data = dynamic_cast<TH1F *>(obj)) ){
    flag=1;
    gROOT->Reset();
    gROOT->ForceStyle();
    gStyle->SetPadRightMargin(0.03);
    gPad->SetLogy(1);
    gPad->Modified();
    gPad->Update();
  }
  if ((data2 = dynamic_cast<TH2F *>(obj)) ){
    flag=2;
    gStyle->SetPalette(1);
    gStyle->SetPadRightMargin(0.15);
    gPad->Modified();
  }



  //===================
  // Dirty jobs :)
  if (flag==1){
    CanvPlot->cd();
    TPad *pad1 = new TPad("pad1","pad1",0.01,0.33,0.99,0.99);
    pad1->Draw();
    pad1->cd();
    pad1->SetTopMargin(0.1);
    pad1->SetBottomMargin(0.01);
    pad1->SetRightMargin(0.1);
    pad1->SetFillStyle(0);
    pad1->SetLogy(1);
    TString str=data->GetTitle();
    if (str.Contains("jet") && !str.Contains("zMass") && !str.Contains("Num") && !str.Contains("Eta") && !str.Contains("Phi") && !str.Contains("eld") && !str.Contains("meanPtZVsNjet")) {
      if (!isAngularAnalysis) rebin=1;
    }

    //======================
    // DATA
    Double_t dataint = data->Integral();
    data->SetLineColor(kBlack);
    data->Rebin(rebin);
    if(str.Contains("nJetVtx")) data->GetXaxis()->SetRangeUser(0,10);	
    if(str.Contains("zMass")) data->GetXaxis()->SetRangeUser(70,110);	
    data->SetMinimum(1.);
    data->Sumw2();

    //Canvas style copied from plotsHistsRatio.C
    data->SetLabelSize(0.0);
    data->GetXaxis()->SetTitleSize(0.00);
    data->GetYaxis()->SetLabelSize(0.07);
    data->GetYaxis()->SetTitleSize(0.08);
    data->GetYaxis()->SetTitleOffset(0.76);
    data->SetTitle("");
    gStyle->SetOptStat(0);

    data->GetYaxis()->SetLabelSize(0.06);
    data->GetYaxis()->SetTitleSize(0.06);
    data->GetYaxis()->SetTitleOffset(0.8);

    data->Draw("E1");


    TLegend* legend = new TLegend(0.725,0.27,0.85,0.72);
    legend->SetFillColor(0);
    legend->SetFillStyle(0);
    legend->SetBorderSize(0);
    legend->SetTextSize(0.060);
    legend->AddEntry(data,"data","p");

    // hack to calculate some yields in restricted regions...
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    if(str.Contains("invMass") && !str.Contains("PF")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z ci sono tra 60 e 120 GeV
	if(j>10&&j<=50) num2 += data->GetBinContent(j); // ... tra 70 e 110
	if(j>15&&j<=45) num3 += data->GetBinContent(j); // ... tra 75 e 105
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the invmass histo\n";
      printf("Number of Z in 60-120 %i --- 70-110 %i --- 75-105 %i \n",num1,num2,num3);
      cout << "\n";
    }
    if(str.Contains("zYieldVsjets") && !str.Contains("Vtx")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z
	if(j>1) num2 += data->GetBinContent(j); // ... +1,2,3,4... jets
	if(j>2) num3 += data->GetBinContent(j); // ... +2,3,4... jets
	if(j>3) num4 += data->GetBinContent(j); // ..    if(str=="jet_pT"){
	if(j>4) num5 += data->GetBinContent(j); // ... +4... jets
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the zYieldVsjets histo\n";
      printf("Number of Z+n jet %i --- >1 %i --- >2 %i --- >3 %i --- >4 %i \n",num1,num2,num3,num4,num5);
      cout << "\n";
    }    

    //======================
    // Z + jets signal
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    TH1F* mc;
    gDirectory->GetObject(plot.c_str(),mc);
    TH1F * hsum;
    if(mc){
      hsum =  (TH1F*) mc->Clone();
      hsum->SetTitle("hsum");
      hsum->SetName("hsum");
      hsum->Reset();

      Double_t mcint = mc->Integral();
      mc->SetFillColor(kRed);
      mc->Sumw2();
      if(lumiweights==0) mc->Scale(dataint/mcint);
		
      // Blocco da propagare negli altri MC
      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) mc->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else mc->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) mc->Scale(zjetsScale);
      }

      // fin qui
      if(lumiweights==1) mc->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      mc->Rebin(rebin);
      if(lumiweights==0) mc->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(mc);
      legend->AddEntry(mc,"Z+jets","f");
    }

    //======================
    // ttbar
    ttbarf->cd("validationJEC");
    if (isMu) ttbarf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ttbarf->cd("validationJEC/");
      if (isMu) ttbarf->cd("validationJECmu/");
    }

    TH1F* ttbar;
    gDirectory->GetObject(plot.c_str(),ttbar);
	
    if(ttbar){
      ttbar->SetFillColor(kBlue);
      ttbar->Sumw2();

      if(ttNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ttbar->Scale( dataLumi2011pix / (ttNumEvents / ttbarXsect));
	    else ttbar->Scale( dataLumi2011 / (ttNumEvents / ttbarXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Apix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011A / (ttNumEvents / ttbarXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Bpix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011B / (ttNumEvents / ttbarXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ttbar->Scale(ttwemean);
      }
      // fin qui
		
      if(lumiweights==1) ttbar->Scale(1./ttwemean);  // perche' i Weights non fanno 1...
      ttbar->Rebin(rebin);
      if(lumiweights==0) ttbar->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ttbar);
      if(lumiweights==1)legend->AddEntry(ttbar,"ttbar","f");

      //////////
      //Storing the bckgrounds!
      //////////
      cout<<str<<endl;
      if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ttbar,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ttbar,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ttbar,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ttbar,"jet_pT4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ttbar,"jet_Multiplicity");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ttbar,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ttbar,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ttbar,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ttbar,"jet_eta4");
      if(str=="HT") evaluateAndFillBackgrounds(ttbar,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ttbar,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ttbar,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ttbar,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ttbar,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ttbar,"PhiStar");
      }
    }

    //======================
    // w+jets
    wf->cd("validationJEC");
    if (isMu) wf->cd("validationJECmu/");
    if (isAngularAnalysis) {
      wf->cd("validationJEC/");
      if (isMu) wf->cd("validationJECmu/");      
    }

    TH1F* w;
    gDirectory->GetObject(plot.c_str(),w);
    if(w){

      w->SetFillColor(kViolet+2);
      w->Sumw2();

      if(wNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) w->Scale( dataLumi2011pix / (wNumEvents / wjetsXsect));
	    else w->Scale( dataLumi2011 / (wNumEvents / wjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Apix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011A / (wNumEvents / wjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Bpix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011B / (wNumEvents / wjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) w->Scale(wwemean);
      }
      // fin qui
		
      if(lumiweights==1) w->Scale(1./wwemean);  // perche' i Weights non fanno 1...
      w->Rebin(rebin);
      if(lumiweights==0) w->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(w);
      if(lumiweights==1)legend->AddEntry(w,"W+jets","f");
    }

    //======================
    // wz+jets
    WZf->cd("validationJEC");
    if (isMu) WZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WZf->cd("validationJEC/");
      if (isMu) WZf->cd("validationJECmu/");
    }

    TH1F* wz;
    gDirectory->GetObject(plot.c_str(),wz);
    if(wz){
      wz->SetFillColor(kYellow+2);
      wz->Sumw2();

      if(wzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) wz->Scale( dataLumi2011pix / (wzEvents / WZXsect));
	    else wz->Scale( dataLumi2011 / (wzEvents / WZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Apix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011A / (wzEvents / WZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Bpix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011B / (wzEvents / WZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) wz->Scale(wzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) wz->Scale(1./wzwemean);  // perche' i Weights non fanno 1...
      wz->Rebin(rebin);
      if(lumiweights==0) wz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(wz);
      legend->AddEntry(wz,"WZ+jets","f");


      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(wz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(wz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(wz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(wz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(wz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(wz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(wz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(wz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(wz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(wz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(wz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(wz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(wz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(wz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(wz,"PhiStar");
     }
    }
    
		
    //======================
    // zz+jets
    ZZf->cd("validationJEC");
    if (isMu) ZZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ZZf->cd("validationJEC/");
      if (isMu) ZZf->cd("validationJECmu/");
    }

    TH1F* zz;
    gDirectory->GetObject(plot.c_str(),zz);
    if(zz){
      zz->SetFillColor(kOrange+2);
      zz->Sumw2();

      if(zzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) zz->Scale( dataLumi2011pix / (zzEvents / ZZXsect));
	    else zz->Scale( dataLumi2011 / (zzEvents / ZZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Apix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011A / (zzEvents / ZZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Bpix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011B / (zzEvents / ZZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) zz->Scale(zzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) zz->Scale(1./zzwemean);  // perche' i Weights non fanno 1...
      zz->Rebin(rebin);
      if(lumiweights==0) zz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(zz);
      legend->AddEntry(zz,"ZZ+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(zz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(zz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(zz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(zz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(zz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(zz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(zz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(zz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(zz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(zz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(zz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(zz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(zz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(zz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(zz,"PhiStar");
     }  
    }
    
    //======================
    // ww+jets
    WWf->cd("validationJEC");
    if (isMu) WWf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WWf->cd("validationJEC/");
      if (isMu) WWf->cd("validationJECmu/");
    }

    TH1F* ww;
    gDirectory->GetObject(plot.c_str(),ww);
    if(ww){
      ww->SetFillColor(kBlack);
      ww->Sumw2();

      if(wwEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ww->Scale( dataLumi2011pix / (wwEvents / WWXsect));
	    else ww->Scale( dataLumi2011 / (wwEvents / WWXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Apix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011A / (wwEvents / WWXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Bpix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011B / (wwEvents / WWXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ww->Scale(wwjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) ww->Scale(1./wwwemean);  // perche' i Weights non fanno 1...
      ww->Rebin(rebin);
      if(lumiweights==0) ww->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ww);
      legend->AddEntry(ww,"WW+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ww,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ww,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ww,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ww,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ww,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ww,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ww,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ww,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ww,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(ww,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ww,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ww,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ww,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ww,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ww,"PhiStar");
     }
    }

    /// Tau 

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

    mcftau->cd("validationJEC");
    if (isMu) mcftau->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcftau->cd("validationJEC/");
      if (isMu) mcftau->cd("validationJECmu/");
    }

    TH1F* tau;
    gDirectory->GetObject(plot.c_str(),tau);
    if(tau){
      tau->SetFillColor(kGreen);
      tau->Sumw2();

      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) tau->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else tau->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) tau->Scale(zjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) tau->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      tau->Rebin(rebin);
      if(lumiweights==0) tau->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      tau->Scale(1./1000.); //aaaaaaa
      hsum->Add(tau);
      legend->AddEntry(tau,"#tau#tau+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(tau,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(tau,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(tau,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(tau,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(tau,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(tau,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(tau,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(tau,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(tau,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(tau,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(tau,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(tau,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(tau,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(tau,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(tau,"PhiStar");
     }
    }


    /////////
    // Print the bkg contributions
    ////////

    for(int j=0;j<bckg_leadingJetPt.size();j++){      
      cout<<bckg_leadingJetPt[j]<<endl;
    }	

    //======================
    // QCD EM enriched
    qcd23emf->cd("validationJEC");
    TH1F* qcd23emp;
    gDirectory->GetObject(plot.c_str(),qcd23emp);

    if(qcd23emp){
      TH1D * qcdTotEM =  (TH1D*) qcd23emp->Clone(); 
      qcdTotEM->SetTitle("qcd em");
      qcdTotEM->SetName("qcd em");
      qcdTotEM->Reset();
      qcdTotEM->Rebin(rebin);

      qcd38emf->cd("validationJEC");
      TH1F* qcd38emp;
      gDirectory->GetObject(plot.c_str(),qcd38emp);


      qcd817emf->cd("validationJEC");
      TH1F* qcd817emp;
      gDirectory->GetObject(plot.c_str(),qcd817emp);

      qcd23emp->Rebin(rebin);
      qcd23emp->Sumw2();
      qcd23emp->Scale(qcd23emScale); 
      qcd38emp->Rebin(rebin);
      qcd38emp->Sumw2();
      qcd38emp->Scale(qcd38emScale); 
      qcd817emp->Rebin(rebin);
      qcd817emp->Sumw2();
      qcd817emp->Scale(qcd817emScale); 

      qcdTotEM->SetFillColor(kOrange+1);
      qcdTotEM->Add(qcd23emp);
      qcdTotEM->Add(qcd38emp);
      qcdTotEM->Add(qcd817emp);

      hsum->Add(qcdTotEM);

      //if(lumiweights==1)legend->AddEntry(qcdTotEM,"QCD em","f");
    }

    //======================
    // QCD bc
    qcd23bcf->cd("validationJEC");
    TH1F* qcd23bcp;
    TH1D * qcdTotBC;
    bool  qcdbcempty=true;
    gDirectory->GetObject(plot.c_str(),qcd23bcp);

    if(qcd23bcp){
      qcdTotBC =  (TH1D*) qcd23bcp->Clone(); 
      qcdTotBC->SetTitle("qcd bc");
      qcdTotBC->SetName("qcd bc");
      qcdTotBC->Reset();
      qcdTotBC->Rebin(rebin);

      qcd38bcf->cd("validationJEC");
      TH1F* qcd38bcp;
      gDirectory->GetObject(plot.c_str(),qcd38bcp);

      qcd817bcf->cd("validationJEC");
      TH1F* qcd817bcp;
      gDirectory->GetObject(plot.c_str(),qcd817bcp);

      qcd23bcp->Rebin(rebin);
      qcd23bcp->Sumw2();
      qcd23bcp->Scale(qcd23bcScale); 
      qcd38bcp->Rebin(rebin);
      qcd38bcp->Sumw2();
      qcd38bcp->Scale(qcd38bcScale); 
      qcd817bcp->Rebin(rebin);
      qcd817bcp->Sumw2();
      qcd817bcp->Scale(qcd817bcScale); 

      qcdTotBC->SetFillColor(kGreen+2);
      qcdTotBC->Add(qcd23bcp);
      qcdTotBC->Add(qcd38bcp);
      qcdTotBC->Add(qcd817bcp);

      hsum->Add(qcdTotBC);
      if (qcdTotBC->GetEntries()>0) qcdbcempty=false; 

      //if(lumiweights==1)legend->AddEntry(qcdTotBC,"QCD bc","f");
    }

    //======================
    // Add here other backgrounds


    //======================
    // Stacked Histogram
    //if(qcd23em) 	hs->Add(qcdTotEM);
    if(!qcdbcempty) 	hs->Add(qcdTotBC);
    if(w)  	        hs->Add(w);
    if (ww)         hs->Add(ww);
    if(tau)		hs->Add(tau); //Z+Jets
    if (zz)         hs->Add(zz);
    if (wz)         hs->Add(wz);
    if (ttbar)	hs->Add(ttbar);
    if(mc)		hs->Add(mc); //Z+Jets

    // per avere le statistiche
    if(lumiweights==1) hsum->Draw("HISTO SAME");


    //======================
    // Setting the stats
    //pad1->Update(); // altrimenti non becchi la stat
    
    //TPaveStats *r2;
    //if(lumiweights==0) r2 = (TPaveStats*)mc->FindObject("stats");
    //if(lumiweights==1) r2 = (TPaveStats*)hsum->FindObject("stats");
    //r2->SetY1NDC(0.875);     //Uncomment if you wonna add your statistics in the top right corner
    //r2->SetY2NDC(0.75); 
    //r2->SetTextColor(kRed);
		
    if(lumiweights==1) hs->Draw("HISTO SAME");
    gPad->RedrawAxis();
    data->Draw("E1 SAME");
    //r2->Draw(); //here to reactivate the stats
    legend->Draw();
    TLegend* lumi = new TLegend(0.45,0.3,0.75,0.2);
    lumi->SetFillColor(0);
    lumi->SetFillStyle(0);
    lumi->SetBorderSize(0);
    //lumi->AddEntry((TObject*)0,"#int L dt =4.9 1/fb","");
    lumi->Draw();
    string channel;
    if (isMu) channel="Z#rightarrow#mu#mu";
    if (!isMu) channel="Z#rightarrow ee";
    TLatex *latexLabel=CMSPrel(4.890,channel,0.55,0.85); // make fancy label
    latexLabel->Draw("same");

    CanvPlot->Update();

	


    //===============//
    // RATIO DATA MC //
    //===============//
    CanvPlot->cd();
    TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.32);
    pad2->Draw();
    pad2->cd();
    pad2->SetTopMargin(0.01);
    pad2->SetBottomMargin(0.3);
    pad2->SetRightMargin(0.1);
    pad2->SetFillStyle(0);

    TH1D * ratio =  (TH1D*) data->Clone();
    ratio->SetTitle("");
    ratio->SetName("ratio");
    ratio->Reset();

    ratio->Sumw2();
    //data->Sumw2();
    hsum->Sumw2(); // FIXME controlla che sia corretto questo... 
    ratio->SetMarkerSize(.5);
    ratio->SetLineColor(kBlack);
    ratio->SetMarkerColor(kBlack);
    //gStyle->SetOptStat("m");
    TH1F* sumMC;

    hs->Draw("nostack"); 
 
   sumMC=(TH1F*) hs->GetHistogram();
    cout<<sumMC->GetEntries()<<endl;
    ratio->Divide(data,hsum,1.,1.);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->SetMarkerSize(0.8);
    //pad2->SetTopMargin(1);

   //Canvas style copied from plotsHistsRatio.C
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetXaxis()->SetTitleSize(0.14);
    ratio->GetXaxis()->SetLabelSize(0.14);
    ratio->GetYaxis()->SetLabelSize(0.11);
    ratio->GetYaxis()->SetTitleSize(0.11);
    ratio->GetYaxis()->SetTitleOffset(0.43);
    ratio->GetYaxis()->SetTitle("ratio data/MC");   

    ratio->Draw("E1");
		
    TLine *OLine = new TLine(ratio->GetXaxis()->GetXmin(),1.,ratio->GetXaxis()->GetXmax(),1.);
    OLine->SetLineColor(kBlack);
    OLine->SetLineStyle(2);
    OLine->Draw();
 
    TLegend* label = new TLegend(0.60,0.9,0.50,0.95);
    label->SetFillColor(0);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    //horrible mess
    double binContent = 0;
    double binSum = 0;
    double weightSum = 0;
    double binError = 1;
    double totalbins = ratio->GetSize() -2;
    for(unsigned int bin=1;bin<=totalbins;bin++){
      binContent = ratio->GetBinContent(bin);
      binError = ratio->GetBinError(bin);
      if(binError!=0){
	binSum += binContent/binError;
	weightSum += 1./binError;
      }
    }
    double ymean = binSum / weightSum;
    //double ymean = ratio->GetMean(2);
    stringstream sYmean;
    sYmean << ymean;
    string labeltext=sYmean.str()+" mean Y";
    //label->AddEntry((TObject*)0,labeltext.c_str(),""); // mean on Y
    //label->Draw();
		
    //TPaveStats *r3 = (TPaveStats*)ratio->FindObject("stats");
    //r3->SetX1NDC(0.01);
    //r3->SetX2NDC(0.10); 
    //r3->SetY1NDC(0.20);
    //r3->SetY2NDC(0.50); 
    //gStyle->SetOptStat("mr");
    //r3->SetTextColor(kWhite);
    //r3->SetLineColor(kWhite);
    //r3->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+".png";
    CanvPlot->Print(tmp.c_str());

  }
  else if (flag==2){
    //CanvPlot.Divide(2,1);
    //CanvPlot.cd(1);

    // data
    dataf->cd("validationJEC");
    if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");

    gDirectory->GetObject(plot.c_str(),data2);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    TPaveStats *r1 = (TPaveStats*)data2->FindObject("stats");
    //r1->SetX1NDC(0.70); Uncomment if you wonna draw your stat in the top right corner
    //r1->SetX2NDC(0.85); 
    //r1->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"data.png";
    CanvPlot->Print(tmp.c_str());


    //CanvPlot.cd(2);
    // montecarlo
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    gDirectory->GetObject(plot.c_str(),data2);

    data2->SetMinimum(1);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    //TPaveStats *r2 = (TPaveStats*)data2->FindObject("stats");
    //r2->SetX1NDC(0.70);
    //r2->SetX2NDC(0.85); 
    //r2->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"mc.png";
    CanvPlot->Print(tmp.c_str());
  }
  //	else { cout << "You're getting an exception! Most likely there's no histogram here... \n"; }

  delete data;
  delete data2;
  delete hs;
  //delete CanvPlot;

  dataf->Close();
  mcf->Close();
  ttbarf->Close();
  wf->Close();
  qcd23emf->Close();
  qcd38emf->Close();
  qcd817emf->Close();
  qcd23bcf->Close();
  qcd38bcf->Close();
  qcd817bcf->Close();
  WZf->Close();
  ZZf->Close();
  
  if (isAngularAnalysis){
    if (bckg_leadingJetPt.size()>0 && bckg_2leadingJetPt.size()>0 && bckg_3leadingJetPt.size()>0 && bckg_4leadingJetPt.size()>0  && bckg_JetMultiplicity.size()>0 && bckg_HT.size()>0 && bckg_leadingJetEta.size()>0 && bckg_PhiStar.size()>0 && cold){
      fzj->cd();
      treeBKG_->Fill();
      treeBKG_->Write();
      TH1F *leadhisto=new TH1F("leadhisto","leading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto2=new TH1F("leadhisto2","subleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto3=new TH1F("leadhisto3","subsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto4=new TH1F("leadhisto4","subsubsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *multiphisto=new TH1F("multiphisto","jet multiplicity background contribution",bckg_JetMultiplicity.size(),0,bckg_JetMultiplicity.size());

      TH1F *HT=new TH1F("HT","HT background contribution",bckg_HT.size(),0,bckg_HT.size());
      TH1F *HT1=new TH1F("HT1","HT background contribution when >= 1 jet",bckg_HT1.size(),0,bckg_HT1.size());
      TH1F *HT2=new TH1F("HT2","HT background contribution when >= 2 jets",bckg_HT2.size(),0,bckg_HT2.size());
      TH1F *HT3=new TH1F("HT3","HT background contribution when >= 3 jets",bckg_HT3.size(),0,bckg_HT3.size());
      TH1F *HT4=new TH1F("HT4","HT background contribution when >= 4 jets",bckg_HT4.size(),0,bckg_HT4.size());

      TH1F *leadhistoeta=new TH1F("leadhistoeta","leading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta2=new TH1F("leadhistoeta2","subleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta3=new TH1F("leadhistoeta3","subsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta4=new TH1F("leadhistoeta4","subsubsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());

      TH1F *PhiStar=new TH1F("PhiStar","PhiStar background contribution",bckg_PhiStar.size(),0,bckg_PhiStar.size());

      for (int i=0; i< bckg_leadingJetPt.size(); i++){
	leadhisto->Fill(i,bckg_leadingJetPt[i]);
	leadhisto2->Fill(i,bckg_2leadingJetPt[i]);
	leadhisto3->Fill(i,bckg_3leadingJetPt[i]);
	leadhisto4->Fill(i,bckg_4leadingJetPt[i]);
      }
      leadhisto->Write();
      leadhisto2->Write();
      leadhisto3->Write();
      leadhisto4->Write();

      for (int i=0; i< bckg_leadingJetEta.size(); i++){
	leadhistoeta->Fill(i,bckg_leadingJetEta[i]);
	leadhistoeta2->Fill(i,bckg_2leadingJetEta[i]);
	leadhistoeta3->Fill(i,bckg_3leadingJetEta[i]);
	leadhistoeta4->Fill(i,bckg_4leadingJetEta[i]);
      }
      leadhistoeta->Write();
      leadhistoeta2->Write();
      leadhistoeta3->Write();
      leadhistoeta4->Write();
      //fzj->Close();

      for (int i=0; i< bckg_JetMultiplicity.size(); i++){
	multiphisto->Fill(i,bckg_JetMultiplicity[i]);
      }
      multiphisto->Write();
      
      ///////////////

      for (int i=0; i< bckg_HT.size(); i++){
	HT->Fill(i,bckg_HT[i]);
      }
      HT->Write();
      
      for (int i=0; i< bckg_HT1.size(); i++){
	HT1->Fill(i,bckg_HT1[i]);
      }
      HT1->Write();
      
      for (int i=0; i< bckg_HT2.size(); i++){
	HT2->Fill(i,bckg_HT2[i]);
      }
      HT2->Write();
      
      for (int i=0; i< bckg_HT3.size(); i++){
	HT3->Fill(i,bckg_HT3[i]);
      }
      HT3->Write();
      
      for (int i=0; i< bckg_HT4.size(); i++){
	HT4->Fill(i,bckg_HT4[i]);
      }
      HT4->Write();

      //Phi star
      for (int i=0; i< bckg_PhiStar.size(); i++){
	PhiStar->Fill(i,bckg_PhiStar[i]);
      }
      PhiStar->Write();

    cold=false;
    }
  }
  return;
}
예제 #13
0
파일: plots.C 프로젝트: ShipSoft/FairRoot
/********************************************************************************
 *    Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH    *
 *                                                                              *
 *              This software is distributed under the terms of the             * 
 *         GNU Lesser General Public Licence version 3 (LGPL) version 3,        *  
 *                  copied verbatim in the file "LICENSE"                       *
 ********************************************************************************/
plots(Int_t nEvents = 1000, Int_t iout=1, TString mcEngine="TGeant3")
{

  // Input data definitions
  //-----User Settings:-----------------------------------------------
  TString  MCFile     ="testrun_" + mcEngine + ".root";
  TString  ParFile       ="testparams_" + mcEngine + ".root";
  TString  RecoFile       ="testreco_"+ mcEngine + ".root";;
  

  // -----   Reconstruction run   -------------------------------------------
  FairRunAna *fRun= new FairRunAna();

  fRun->SetInputFile(MCFile.Data());
  fRun->AddFriend(RecoFile.Data());

  FairRuntimeDb* rtdb = fRun->GetRuntimeDb();
  FairParRootFileIo* parInput1 = new FairParRootFileIo();
  parInput1->open(ParFile.Data());
  rtdb->setFirstInput(parInput1);

  TFile *f1 = TFile::Open(MCFile);
  TFile *f2 = TFile::Open(RecoFile);

  TTree *t1 = f1->Get("cbmsim");
  TTree *t2 = f2->Get("cbmsim");
	
  FairMCEventHeader *MCEventHeader  = new FairMCEventHeader();
  TClonesArray *MCTracks   = new TClonesArray("FairMCTrack");
  TClonesArray *TutorialDetPoints  = new TClonesArray("FairTutorialDet4Point");
  TClonesArray *TutorialDetHits    = new TClonesArray("FairTutorialDet4Hit");

  t1->SetBranchAddress("MCEventHeader.",&MCEventHeader);
  t1->SetBranchAddress("MCTrack",       &MCTracks);
  t1->SetBranchAddress("TutorialDetPoint",      &TutorialDetPoints);
  t2->SetBranchAddress("TutorialDetHit",        &TutorialDetHits);

  FairMCTrack     *MCTrack;
  FairTutorialDet4Point    *Point;
  FairTutorialDet4Hit      *Hit;

  //histograms 
  fRun->SetOutputFile("test.ana.root");
  TFile *fHist = fRun->GetOutputFile();

  Float_t xrange=80.;
  Float_t yrange=80.;

  TH2F* dxx    = new TH2F("dxx","Hit; x; Delta x;",100,-xrange,xrange,50.,-10.,10.);
  TH2F* dyy    = new TH2F("dyy","Hit; y; Delta y;",100,-yrange,yrange,50.,-10.,10.);
  TH1F* pullx    = new TH1F("pullx","Hit; pullx;",100.,-5.,5.);
  TH1F* pully    = new TH1F("pully","Hit; pully;",100.,-5.,5.);
  TH1F* pullz    = new TH1F("pullz","Hit; pullz;",50.,-10.,10.);
  TH1F* pointx    = new TH1F("pointx","Hit; posx;",200.,-80.,80.);
  TH1F* pointy    = new TH1F("pointy","Hit; posy;",200.,-80.,80.);
 
  Int_t nMCTracks, nPoints, nHits;
  Float_t x_point, y_point, z_point, tof_point, SMtype_point, mod_point, cel_point, gap_point;  
  Float_t x_poi, y_poi, z_poi; 
  Float_t SMtype_poi, mod_poi, cel_poi, gap_poi;
  Float_t p_MC, px_MC, py_MC, pz_MC;
  Float_t x_hit, y_hit, z_hit, dy_hit;

  Int_t nevent = t1->GetEntries();	

  if (nevent > nEvents) nevent=nEvents;

  cout << "total number of events to process: " << nevent 
       <<endl;

// Event loop
	
for (Int_t iev=0; iev< nevent; iev++) {
  // get entry	
  t1->GetEntry(iev);
  t2->GetEntry(iev);
		
  nMCTracks = MCTracks->GetEntriesFast();
  nPoints = TutorialDetPoints->GetEntriesFast();
  nHits = TutorialDetHits->GetEntriesFast();
    		
  cout << " Event"  << iev << ":";
  cout << nMCTracks << " MC tracks ";
  cout << nPoints << "  points ";
  cout << nHits << " Hits "<<endl;
    
  // Hit loop					
  for (Int_t j =0; j<nHits; j++) {
    Hit   = (FairTutorialDet4Hit*) TutorialDetHits->At(j);
    Int_t l = Hit->GetRefIndex();
    Point = (FairTutorialDet4Point*) TutorialDetPoints->At(l);

    // Point info
    x_poi	= Point -> GetX();
    y_poi	= Point -> GetY();
    z_poi	= Point -> GetZ();

    // Hit	info		
    x_hit	= Hit->GetX();
    y_hit	= Hit->GetY();
    z_hit	= Hit->GetZ();
    dy_hit	= Hit->GetDy();
//    Int_t flg_hit = Hit->GetFlag();

    Float_t delta_x	= x_poi - x_hit;
    Float_t delta_y	= y_poi - y_hit;
    Float_t delta_z	= z_poi - z_hit;
			
    dxx ->Fill(x_poi,delta_x);
    dyy ->Fill(y_poi,delta_y);
    pullx ->Fill(delta_x);
    pully ->Fill(delta_y);
    pullz ->Fill(delta_z);
    pointx ->Fill(x_hit);
    pointy ->Fill(y_hit);
		
  } //  Hit loop end

} // event loop end 


// save histos to file
// TFile *fHist = TFile::Open("data/auaumbias.hst.root","RECREATE");
 cout << "Processing done, outflag =" <<iout << endl;
 if (iout==1){
   fHist->Write();
   if(0){ // explicit writing 
     TIter next(gDirectory->GetList());
     TH1 *h;
     TObject* obj;
     while(obj= (TObject*)next()){
       if(obj->InheritsFrom(TH1::Class())){
         h = (TH1*)obj;
         cout << "Write histo " << h->GetTitle() << endl;
         h->Write();
       }
     }
   }
   fHist->ls();
   fHist->Close();
  }

  // -----   Finish   -------------------------------------------------------

  cout << endl << endl;

  // Extract the maximal used memory an add is as Dart measurement
  // This line is filtered by CTest and the value send to CDash
  FairSystemInfo sysInfo;
  Float_t maxMemory=sysInfo.GetMaxMemory();
  cout << "<DartMeasurement name=\"MaxMemory\" type=\"numeric/double\">";
  cout << maxMemory;
  cout << "</DartMeasurement>" << endl;

  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();

  Float_t cpuUsage=ctime/rtime;
  cout << "<DartMeasurement name=\"CpuLoad\" type=\"numeric/double\">";
  cout << cpuUsage;
  cout << "</DartMeasurement>" << endl;

  cout << endl << endl;
  cout << "Output file is "    << outFile << endl;
  cout << "Parameter file is " << parFile << endl;
  cout << "Real time " << rtime << " s, CPU time " << ctime
       << "s" << endl << endl;
  cout << "Macro finished successfully." << endl;

  // ------------------------------------------------------------------------
}
예제 #14
0
string FullTitle(const TH1 &h) {
    return string(h.GetTitle())
           +";"+h.GetXaxis()->GetTitle()
           +";"+h.GetYaxis()->GetTitle();
}
예제 #15
0
  /** 
   * Process a single eta bin 
   * 
   * @param measured     Input collection of measured data
   * @param corrections  Input collection of correction data
   * @param method       Unfolding method to use 
   * @param regParam     Regularisation parameter
   * @param out          Output directory. 
   *
   * @return Stack of histograms or null 
   */
  THStack* ProcessBin(TCollection* measured, 
		      TCollection* corrections, 
		      UInt_t       method,
		      Double_t     regParam, 
		      TDirectory*  out)
  {
    Printf("   Processing %s ...", measured->GetName());
    // Try to get the data 
    TH1* inRaw    = GetH1(measured,    "rawDist");
    TH1* inTruth  = GetH1(corrections, "truth");
    TH1* inTruthA = GetH1(corrections, "truthAccepted");
    TH1* inTrgVtx = GetH1(corrections, "triggerVertex");
    TH2* inResp   = GetH2(corrections, "response");
    if (!inRaw || !inTruth || !inTruthA || !inTrgVtx || !inResp) 
      return 0;
    
    // Make output directory
    TDirectory* dir = out->mkdir(measured->GetName());
    dir->cd();

    // Copy the input to the output 
    TH1* outRaw    = static_cast<TH1*>(inRaw    ->Clone("measured"));
    TH1* outTruth  = static_cast<TH1*>(inTruth  ->Clone("truth"));
    TH1* outTruthA = static_cast<TH1*>(inTruthA ->Clone("truthAccepted"));
    TH1* outTrgVtx = static_cast<TH1*>(inTrgVtx ->Clone("triggerVertex"));
    TH2* outResp   = static_cast<TH2*>(inResp   ->Clone("response"));

    // Make our response matrix 
    RooUnfoldResponse matrix(0, 0, inResp);
    
    // Store regularization parameter 
    Double_t             r        = regParam;
    RooUnfold::Algorithm algo     = (RooUnfold::Algorithm)method;
    RooUnfold*           unfolder = RooUnfold::New(algo, &matrix, inRaw, r);
    unfolder->SetVerbose(0);

    // Do the unfolding and get the result
    TH1* res = unfolder->Hreco();
    res->SetDirectory(0);

    // Make a copy to store on the output 
    TH1* outUnfold = static_cast<TH1*>(res->Clone("unfolded"));
    TString tit(outUnfold->GetTitle());
    tit.ReplaceAll("Unfold Reponse matrix", "Unfolded P(#it{N}_{ch})");
    outUnfold->SetTitle(tit);

    // Clone the unfolded results and divide by the trigger/vertex
    // bias correction
    TH1* outCorr   = static_cast<TH1*>(outUnfold->Clone("corrected"));
    outCorr->Divide(inTrgVtx);
    tit.ReplaceAll("Unfolded", "Corrected");
    outCorr->SetTitle(tit);

    // Now normalize the output to integral=1 
    TH1*  hists[] = { outRaw, outUnfold, outCorr, 0 };
    TH1** phist   = hists;
    while (*phist) { 
      TH1* h = *phist;
      if (h) { 
	Double_t intg = h->Integral(1, h->GetXaxis()->GetXmax());
	h->Scale(1. / intg, "width");
      }
      phist++;
    }
    
    // And make ratios
    TH1* ratioTrue = static_cast<TH1*>(outCorr->Clone("ratioCorrTruth"));
    tit = ratioTrue->GetTitle();
    tit.ReplaceAll("Corrected", "Corrected/MC 'truth'");
    ratioTrue->SetTitle(tit);
    ratioTrue->Divide(outTruth);
    ratioTrue->SetYTitle("P_{corrected}(#it{N}_{ch})/P_{truth}(#it{N}_{ch})");

    TH1* ratioAcc  = static_cast<TH1*>(outUnfold->Clone("ratioUnfAcc"));
    tit = ratioAcc->GetTitle();
    tit.ReplaceAll("Unfolded", "Unfolded/MC selected");
    ratioAcc->SetTitle(tit);
    ratioAcc->Divide(outTruthA);
    ratioAcc->SetYTitle("P_{unfolded}(#it{N}_{ch})/P_{MC}(#it{N}_{ch})");
    

    // Make a stack 
    tit = measured->GetName();
    tit.ReplaceAll("m", "-");
    tit.ReplaceAll("p", "+");
    tit.ReplaceAll("d", ".");
    tit.ReplaceAll("_", "<#it{#eta}<");
    THStack* stack = new THStack("all", tit);
    stack->Add(outTruth,  "E2");
    stack->Add(outTruthA, "E2");
    stack->Add(outRaw,    "E1");
    stack->Add(outUnfold, "E1");
    stack->Add(outCorr,   "E1");
    dir->Add(stack);

    // Rest of the function is devoted to making the output look nice 
    outRaw   ->SetDirectory(dir); 
    outTruth ->SetDirectory(dir);  
    outTruthA->SetDirectory(dir);  
    outTrgVtx->SetDirectory(dir);  
    outResp  ->SetDirectory(dir);  
    outUnfold->SetDirectory(dir);   
    outCorr  ->SetDirectory(dir); 

    outRaw   ->SetMarkerStyle(20);  // Measured is closed
    outTruth ->SetMarkerStyle(24);  // MC is open
    outTruthA->SetMarkerStyle(24);  // MC is open
    outTrgVtx->SetMarkerStyle(20);  // Derived is closed
    outUnfold->SetMarkerStyle(20);  // Derived is closed   
    outCorr  ->SetMarkerStyle(20);  // Derived is closed 

    outRaw   ->SetMarkerSize(0.9); 
    outTruth ->SetMarkerSize(1.6);  
    outTruthA->SetMarkerSize(1.4);  
    outTrgVtx->SetMarkerSize(1.0);  
    outUnfold->SetMarkerSize(0.9);   
    outCorr  ->SetMarkerSize(1.0);
 
    outRaw   ->SetMarkerColor(kColorMeasured); 
    outTruth ->SetMarkerColor(kColorTruth);  
    outTruthA->SetMarkerColor(kColorAccepted);  
    outTrgVtx->SetMarkerColor(kColorTrgVtx);  
    outUnfold->SetMarkerColor(kColorUnfolded);   
    outCorr  ->SetMarkerColor(kColorCorrected); 

    outRaw   ->SetFillColor(kColorError);     
    outTruth ->SetFillColor(kColorError);  
    outTruthA->SetFillColor(kColorError);  
    outTrgVtx->SetFillColor(kColorError);  
    outUnfold->SetFillColor(kColorError);   
    outCorr  ->SetFillColor(kColorError); 

    outRaw   ->SetFillStyle(0); 
    outTruth ->SetFillStyle(1001);  
    outTruthA->SetFillStyle(1001);  
    outTrgVtx->SetFillStyle(0);  
    outUnfold->SetFillStyle(0);   
    outCorr  ->SetFillStyle(0);

    outRaw   ->SetLineColor(kBlack); 
    outTruth ->SetLineColor(kBlack);  
    outTruthA->SetLineColor(kBlack);  
    outTrgVtx->SetLineColor(kBlack);  
    outUnfold->SetLineColor(kBlack);   
    outCorr  ->SetLineColor(kBlack); 

    // Legend 
    TLegend* l = StackLegend(stack);
    l->AddEntry(outRaw,     "Raw",                 "lp");
    l->AddEntry(outTruth,   "MC 'truth'",          "fp");
    l->AddEntry(outTruthA,  "MC 'truth' accepted", "fp");
    l->AddEntry(outUnfold,  "Unfolded",            "lp");
    l->AddEntry(outCorr,    "Corrected",           "lp");

    return stack;
  }
예제 #16
0
파일: mvas.C 프로젝트: aocampor/UGentSUSY
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void mvas( TString fin = "TMVA.root", HistType htype = MVAType, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas *c = 0;

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if( ! gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory") ) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);

      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {
         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         cout << "--- Found directory for method: " << methodName << "::" << methodTitle << flush;
         TString hname = "MVA_" + methodTitle;
         if      (htype == ProbaType  ) hname += "_Proba";
         else if (htype == RarityType ) hname += "_Rarity";
         TH1* sig = dynamic_cast<TH1*>(titDir->Get( hname + "_S" ));
         TH1* bgd = dynamic_cast<TH1*>(titDir->Get( hname + "_B" ));

         if (sig==0 || bgd==0) {
            if     (htype == MVAType)     
               cout << "mva distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == ProbaType)   
               cout << "probability distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == RarityType)  
               cout << "rarity distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == CompareType) 
               cout << "overtraining check not available (this is normal for Cut classifier)" << endl;
            else cout << endl;
         } 
         else {
            cout << endl;
            // chop off useless stuff
            sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
            if      (htype == ProbaType) 
               sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) );
            else if (htype == RarityType) 
               sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) );
            else if (htype == CompareType) 
               sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) );
         
            // create new canvas
            TString ctitle = ((htype == MVAType) ? 
                              Form("TMVA response %s",methodTitle.Data()) : 
                              (htype == ProbaType) ? 
                              Form("TMVA probability %s",methodTitle.Data()) :
                              (htype == CompareType) ? 
                              Form("TMVA comparison %s",methodTitle.Data()) :
                              Form("TMVA Rarity %s",methodTitle.Data()));
         
            TString cname = ((htype == MVAType) ? 
                             Form("output_%s",methodTitle.Data()) : 
                             (htype == ProbaType) ? 
                             Form("probability_%s",methodTitle.Data()) :
                             (htype == CompareType) ? 
                             Form("comparison_%s",methodTitle.Data()) :
                             Form("rarity_%s",methodTitle.Data()));

            c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, 
                             countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); 
    
            // set the histogram style
            TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
   
            // normalise both signal and background
            TMVAGlob::NormalizeHists( sig, bgd );
   
            // frame limits (choose judicuous x range)
            Float_t nrms = 4;
            cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl;
            cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl;
            Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
                                                  bgd->GetMean() - nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmin() );
            Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
                                                  bgd->GetMean() + nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmax() );
            Float_t ymin = 0;
            Float_t maxMult = (htype == CompareType) ? 1.3 : 1.2;
            Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
   
            // build a frame
            Int_t nb = 500;
            TString hFrameName(TString("frame") + methodTitle);
            TObject *o = gROOT->FindObject(hFrameName);
            if(o) delete o;
            TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                                    nb, xmin, xmax, nb, ymin, ymax );
            frame->GetXaxis()->SetTitle( methodTitle + ((htype == MVAType || htype == CompareType) ? " response" : "") );
            if      (htype == ProbaType  ) frame->GetXaxis()->SetTitle( "Signal probability" );
            else if (htype == RarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" );
            frame->GetYaxis()->SetTitle("Normalized");
            TMVAGlob::SetFrameStyle( frame );
   
            // eventually: draw the frame
            frame->Draw();  
    
            c->GetPad(0)->SetLeftMargin( 0.105 );
            frame->GetYaxis()->SetTitleOffset( 1.2 );

            // Draw legend               
            TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                          c->GetLeftMargin() + (htype == CompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() );
            legend->SetFillStyle( 1 );
            legend->AddEntry(sig,TString("Signal")     + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->AddEntry(bgd,TString("Background") + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->SetBorderSize(1);
            legend->SetMargin( (htype == CompareType ? 0.2 : 0.3) );
            legend->Draw("same");

            // overlay signal and background histograms
            sig->Draw("samehist");
            bgd->Draw("samehist");
   
            if (htype == CompareType) {
               // if overtraining check, load additional histograms
               TH1* sigOv = 0;
               TH1* bgdOv = 0;

               TString ovname = hname += "_Train";
               sigOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_S" ));
               bgdOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_B" ));
      
               if (sigOv == 0 || bgdOv == 0) {
                  cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl;
               }
               else {
                  cout << "--- Found comparison histograms for overtraining check" << endl;

                  TLegend *legend2= new TLegend( 1 - c->GetRightMargin() - 0.42, 1 - c->GetTopMargin() - 0.12,
                                                 1 - c->GetRightMargin(), 1 - c->GetTopMargin() );
                  legend2->SetFillStyle( 1 );
                  legend2->SetBorderSize(1);
                  legend2->AddEntry(sigOv,"Signal (training sample)","P");
                  legend2->AddEntry(bgdOv,"Background (training sample)","P");
                  legend2->SetMargin( 0.1 );
                  legend2->Draw("same");
               }
               Int_t col = sig->GetLineColor();
               sigOv->SetMarkerColor( col );
               sigOv->SetMarkerSize( 0.7 );
               sigOv->SetMarkerStyle( 20 );
               sigOv->SetLineWidth( 1 );
               sigOv->SetLineColor( col );
               sigOv->Draw("e1same");
      
               col = bgd->GetLineColor();
               bgdOv->SetMarkerColor( col );
               bgdOv->SetMarkerSize( 0.7 );
               bgdOv->SetMarkerStyle( 20 );
               bgdOv->SetLineWidth( 1 );
               bgdOv->SetLineColor( col );
               bgdOv->Draw("e1same");

               ymax = TMath::Max( ymax, TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult );
               frame->GetYaxis()->SetLimits( 0, ymax );
      
               // for better visibility, plot thinner lines
               sig->SetLineWidth( 1 );
               bgd->SetLineWidth( 1 );

               // perform K-S test
               cout << "--- Perform Kolmogorov-Smirnov tests" << endl;
               Double_t kolS = sig->KolmogorovTest( sigOv );
               Double_t kolB = bgd->KolmogorovTest( bgdOv );
               cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl;

               TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB );
               TText* tt = new TText( 0.12, 0.74, probatext );
               tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); 
            }

            // redraw axes
            frame->Draw("sameaxis");

            // text for overflows
            Int_t    nbin = sig->GetNbinsX();
            Double_t dxu  = sig->GetBinWidth(0);
            Double_t dxo  = sig->GetBinWidth(nbin+1);
            TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                                   sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                                   sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
            TText* t = new TText( 0.975, 0.115, uoflow );
            t->SetNDC();
            t->SetTextSize( 0.030 );
            t->SetTextAngle( 90 );
            t->AppendPad();    
   
            // update canvas
            c->Update();

            // save canvas to file

            TMVAGlob::plot_logo(1.058);
            if (Save_Images) {
               if      (htype == MVAType)     TMVAGlob::imgconv( c, Form("plots/mva_%s",     methodTitle.Data()) );
               else if (htype == ProbaType)   TMVAGlob::imgconv( c, Form("plots/proba_%s",   methodTitle.Data()) ); 
               else if (htype == CompareType) TMVAGlob::imgconv( c, Form("plots/overtrain_%s", methodTitle.Data()) ); 
               else                           TMVAGlob::imgconv( c, Form("plots/rarity_%s",  methodTitle.Data()) ); 
            }
            countCanvas++;
         }
      }
   }
}
예제 #17
0
  //____________________________________________________________________
  void DrawResCollection(TCollection* top, const TString& name)
  {
    TCollection* c = GetCollection(top, name, false);
    if (!c) return;

    THStack* s = GetStack(c, "all");
    s->SetTitle("");
    DrawInPad(fBody, 0, s, "nostack", kLogy);
    TLegend* l = new TLegend(.5, .75, .98, .98, "P(#it{N}_{ch})");
    l->SetBorderSize(0);
    // l->SetBorderMode(0);
    l->SetFillColor(0);
    l->SetFillStyle(0);
    TIter next(s->GetHists());
    TH1*  h = 0;
    Bool_t hasTrue = false;
    while ((h = static_cast<TH1*>(next()))) { 
      TString n(h->GetTitle());
      if (n.BeginsWith("True")) { hasTrue = true; continue; }
      n.ReplaceAll("Raw P(#it{N}_{ch}) in ", "");
      TLegendEntry* e = l->AddEntry("dummy", n, "p");
      e->SetMarkerStyle(h->GetMarkerStyle());
    }
    if (hasTrue) {
      TLegendEntry* e = l->AddEntry("dummy", "Raw", "p");
      e->SetMarkerStyle(20);
      e->SetMarkerColor(kRed+1);
      e = l->AddEntry("dummy", "MC truth", "p");
      e->SetMarkerStyle(24);
      e->SetMarkerColor(kBlue+1);
      e = l->AddEntry("dummy", "MC truth selected", "p");
      e->SetMarkerStyle(24);
      e->SetMarkerColor(kOrange+1);
    }
    fBody->cd();
    l->Draw();
    
    PrintCanvas(Form("%s results", name.Data()));

    // return;

    TIter       nextO(c);
    TObject*    o = 0;
    while ((o = nextO())) { 
      Double_t etaMin = 999;
      Double_t etaMax = 999;
      TCollection* bin = GetEtaBin(o, etaMin, etaMax);
      if (!bin) continue;

      fBody->Divide(2,3);
      DrawInPad(fBody, 1, GetH1(bin, "rawDist"),      "",     kLogy);
      DrawInPad(fBody, 1, GetH1(bin, "truthAccepted", false),
		"same", kSilent);
      DrawInPad(fBody, 1, GetH1(bin, "truth", false),"same", kSilent|kLegend);
      DrawInPad(fBody, 2, GetH1(bin, "coverage"));
      DrawInPad(fBody, 3, GetH2(bin, "corr"),            "colz");
      DrawInPad(fBody, 4, GetH2(bin, "response", false), "colz", kLogz|kSilent);
      DrawInPad(fBody, 5, GetH1(bin, "triggerVertex", false), "", kSilent);
      
      PrintCanvas(Form("%+5.1f < #eta < %+5.1f", etaMin, etaMax));
    }
  }