Пример #1
0
TH1 *
YieldMean_LowExtrapolationHisto(TH1 *h, TF1 *f, Double_t min, Double_t binwidth)
{
  /* find lowest edge in histo */
  Int_t binlo;
  Double_t lo;
  for (Int_t ibin = 1; ibin < h->GetNbinsX() + 1; ibin++) {
    if (h->GetBinContent(ibin) != 0.) {
      binlo = ibin;
      lo = h->GetBinLowEdge(ibin);
      break;
    }
  }
  
  Int_t nbins = (lo - min) / binwidth;
  if(nbins<1)
	return 0x0;		
  TH1 *hlo = new TH1F("hlo", "", nbins, min, lo);
  
  /* integrate function in histogram bins */
  Double_t cont, err, width;
  for (Int_t ibin = 0; ibin < hlo->GetNbinsX(); ibin++) {
    width = hlo->GetBinWidth(ibin + 1);
    cont = f->Integral(hlo->GetBinLowEdge(ibin + 1), hlo->GetBinLowEdge(ibin + 2), (Double_t *)0, 1.e-6);
    err = f->IntegralError(hlo->GetBinLowEdge(ibin + 1), hlo->GetBinLowEdge(ibin + 2), (Double_t *)0, (Double_t *)0, 1.e-6);
    hlo->SetBinContent(ibin + 1, cont / width);
    hlo->SetBinError(ibin + 1, err / width);
  }

  return hlo;
}
Пример #2
0
TH1 *
YieldMean_HighExtrapolationHisto(TH1 *h, TF1 *f, Double_t max, Double_t binwidth)
{
  /* find highest edge in histo */
  Int_t binhi;
  Double_t hi;
  for (Int_t ibin = h->GetNbinsX(); ibin > 0; ibin--) {
    if (h->GetBinContent(ibin) != 0.) {
      binhi = ibin + 1;
      hi = h->GetBinLowEdge(ibin + 1);
      break;
    }
  }
  if(max<hi) {
	Printf("Warning! You should probably set a higher max value (Max = %f, hi = %f)", max, hi);
    return 0x0;
  }
  Int_t nbins = (max - hi) / binwidth;
 if(nbins<1)
	return 0x0;	 
  TH1 *hhi = new TH1F("hhi", "", nbins, hi, max);
  
  /* integrate function in histogram bins */
  Double_t cont, err, width;
  for (Int_t ibin = 0; ibin < hhi->GetNbinsX(); ibin++) {
    width = hhi->GetBinWidth(ibin + 1);
    cont = f->Integral(hhi->GetBinLowEdge(ibin + 1), hhi->GetBinLowEdge(ibin + 2), (Double_t *)0, 1.e-6);
    err = f->IntegralError(hhi->GetBinLowEdge(ibin + 1), hhi->GetBinLowEdge(ibin + 2), (Double_t *)0, (Double_t *)0, 1.e-6);
    hhi->SetBinContent(ibin + 1, cont / width);
    hhi->SetBinError(ibin + 1, err / width);
  }

  return hhi;
}
Пример #3
0
Double_t fitgp0( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){
    cout << hs << " does not exist\n";
    return 0;
  }

  h->SetMarkerStyle(21);
  h->SetMarkerSize(0.8);
  h->SetStats(1);
  gStyle->SetOptFit(101);

  gROOT->ForceStyle();

  double dx = h->GetBinWidth(1);
  double nmax = h->GetBinContent(h->GetMaximumBin());
  double xmax = h->GetBinCenter(h->GetMaximumBin());
  double nn = 7*nmax;

  int nb = h->GetNbinsX();
  double n1 = h->GetBinContent(1);
  double n9 = h->GetBinContent(nb);
  double bg = 0.5*(n1+n9);

  double x1 = h->GetBinCenter(1);
  double x9 = h->GetBinCenter(nb);

  // create a TF1 with the range from x1 to x9 and 4 parameters
  TF1 *gp0Fcn = new TF1( "gp0Fcn", gp0Fit, x1, x9, 4 );

  gp0Fcn->SetParName( 0, "mean" );
  gp0Fcn->SetParName( 1, "sigma" );
  gp0Fcn->SetParName( 2, "area" );
  gp0Fcn->SetParName( 3, "BG" );

  gp0Fcn->SetNpx(500);
  gp0Fcn->SetLineWidth(4);
  gp0Fcn->SetLineColor(kMagenta);
  gp0Fcn->SetLineColor(kGreen);

  // set start values for some parameters:
  gp0Fcn->SetParameter( 0, xmax ); // peak position
  gp0Fcn->SetParameter( 1, 4*dx ); // width
  gp0Fcn->SetParameter( 2, nn ); // N
  gp0Fcn->SetParameter( 3, bg );

  // N: not drawing
  // Q: quiet
  // R: use specified range
  h->Fit( "gp0Fcn", "NQR", "ep" );

  return gp0Fcn->GetParameter(1);

}
Пример #4
0
void scaleToBinWidth(TH1 &h1){
  double nBins = h1.GetXaxis()->GetNbins();
  for (int iBin = h1.GetXaxis()->GetFirst(); iBin <= h1.GetXaxis()->GetLast(); iBin++){
    double iW = h1.GetBinWidth(iBin);
    double old = h1.GetBinContent(iBin);
    h1.SetBinContent(iBin,old/iW);
  }


}
Пример #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
Double_t fitep0sigma( char* hs, int binlow=-999, int binhigh=999) {

  TH1 *h = (TH1*)gDirectory->Get(hs);
  if( h == NULL ){ cout << hs << " does not exist\n"; return 0; }

  double dx = h->GetBinWidth(1);
  double nmax = h->GetBinContent(h->GetMaximumBin());
  double xmax = h->GetBinCenter(h->GetMaximumBin());
  double nn = 7*nmax;

  int nb = h->GetNbinsX();
  double n1 = h->GetBinContent(1);
  double n9 = h->GetBinContent(nb);
  double bg = 0.5*(n1+n9);

  double x1, x9;
  if(binlow < -900 && binhigh > 900) {
    x1 = h->GetBinCenter(1);
    x9 = h->GetBinCenter(nb);
  }
  else {
    x1 = binlow;
    x9 = binhigh;
  }

  // create a TF1 with the range from x1 to x9 and 5 parameters
  TF1 *ep0Fcn = new TF1( "ep0Fcn", ep0Fit, x1, x9, 5 );

  ep0Fcn->SetParName( 0, "mean" );
  ep0Fcn->SetParName( 1, "sigma" );
  ep0Fcn->SetParName( 2, "pow" );
  ep0Fcn->SetParName( 3, "area" );
  ep0Fcn->SetParName( 4, "BG" );

  // Start values for some parameters:
  ep0Fcn->SetParameter( 0, xmax ); // peak position
  ep0Fcn->SetParameter( 1, 4*dx ); // width
  ep0Fcn->SetParameter( 2, 3.3 ); // pow
  ep0Fcn->SetParameter( 3, nn ); // N
  ep0Fcn->SetParameter( 4, bg );
    
  h->Fit("ep0Fcn", "Q R", "ep" );
  TF1 *fit = h->GetFunction("ep0Fcn");
  return fit->GetParameter(1);
}
Пример #7
0
Double_t fitfulllang( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){
    cout << hs << " does not exist\n";
    return 0;
  }

  double aa = h->GetEntries();//normalization

  // find peak:
  int ipk = h->GetMaximumBin();
  double xpk = h->GetBinCenter(ipk);
  double sm = xpk / 9; // sigma
  double ns = sm; // noise

  // fit range:
  int ib0 = ipk/2;
  int ib9 = h->GetNbinsX() - 1;

  double x0 = h->GetBinLowEdge(ib0);
  double x9 = h->GetBinLowEdge(ib9) + h->GetBinWidth(ib9);

  // create a TF1 with the range from x0 to x9 and 4 parameters
  TF1 *fitFcn = new TF1( "fitFcn", fitLandauGauss, x0, x9, 4 );

  fitFcn->SetParName( 0, "peak" );
  fitFcn->SetParName( 1, "sigma" );
  fitFcn->SetParName( 2, "area" );
  fitFcn->SetParName( 3, "smear" );

  fitFcn->SetNpx(500);
  fitFcn->SetLineWidth(4);
  fitFcn->SetLineColor(kMagenta);

  // set start values:
  fitFcn->SetParameter( 0, xpk ); // peak position, defined above
  fitFcn->SetParameter( 1, sm ); // width
  fitFcn->SetParameter( 2, aa ); // area
  fitFcn->SetParameter( 3, ns ); // noise

  h->Fit("fitFcn", "NQR", "ep" );// R = range from fitFcn
  return fitFcn->GetParameter(0);
}
Пример #8
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;
}
Пример #9
0
double fittp0sigma( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){ cout << hs << " does not exist\n"; return 0; }

  double dx = h->GetBinWidth(1);
  double nmax = h->GetBinContent(h->GetMaximumBin());
  double xmax = h->GetBinCenter(h->GetMaximumBin());
  double nn = 7*nmax;

  int nb = h->GetNbinsX();
  double n1 = h->GetBinContent(1);
  double n9 = h->GetBinContent(nb);
  double bg = 0.5*(n1+n9);

  double x1 = h->GetBinCenter(1);
  double x9 = h->GetBinCenter(nb);

  // create a TF1 with the range from x1 to x9 and 5 parameters
  TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 );

  tp0Fcn->SetParName( 0, "mean" );
  tp0Fcn->SetParName( 1, "sigma" );
  tp0Fcn->SetParName( 2, "nu" );
  tp0Fcn->SetParName( 3, "area" );
  tp0Fcn->SetParName( 4, "BG" );
   
  // set start values for some parameters:
  tp0Fcn->SetParameter( 0, xmax ); // peak position
  tp0Fcn->SetParameter( 1, 4*dx ); // width
  tp0Fcn->SetParameter( 2, 2.2 ); // nu
  tp0Fcn->SetParameter( 3, nn ); // N
  tp0Fcn->SetParameter( 4, bg );
    
  h->Fit( "tp0Fcn", "Q R", "ep" );
  // h->Fit("tp0Fcn","V+","ep");
  TF1 *fit = h->GetFunction("tp0Fcn");
  return fit->GetParameter(1);
}
Пример #10
0
// 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;
}
void likelihoodrefs( TDirectory *lhdir ) {
   Bool_t newCanvas = kTRUE;
   
   const UInt_t maxCanvas = 200;
   TCanvas** c = new TCanvas*[maxCanvas];
   Int_t width  = 670;
   Int_t height = 380;

   // avoid duplicated printing
   std::vector<std::string> hasBeenUsed;
   const TString titName = lhdir->GetName();
   UInt_t ic = -1;   

   TIter next(lhdir->GetListOfKeys());
   TKey *key;
   while ((key = TMVAGlob::NextKey(next,"TH1"))) { // loop over all TH1
      TH1 *h = (TH1*)key->ReadObj();
      TH1F *b( 0 );
      TString hname( h->GetName() );

      // avoid duplicated plotting
      Bool_t found = kFALSE;
      for (UInt_t j = 0; j < hasBeenUsed.size(); j++) {
         if (hasBeenUsed[j] == hname.Data()) found = kTRUE;
      }
      if (!found) {

         // draw original plots
         if (hname.EndsWith("_sig_nice")) {

            if (newCanvas) {
               char cn[20];
               sprintf( cn, "cv%d_%s", ic+1, titName.Data() );
               ++ic;
               TString n = hname;	  
               c[ic] = new TCanvas( cn, Form( "%s reference for variable: %s", 
                                              titName.Data(),(n.ReplaceAll("_sig","")).Data() ), 
                                    ic*50+50, ic*20, width, height ); 
               c[ic]->Divide(2,1);
               newCanvas = kFALSE;
            }      

            // signal
            Int_t color = 4; 
            TPad * cPad = (TPad*)c[ic]->cd(1);
            TString plotname = hname;

            h->SetMaximum(h->GetMaximum()*1.3);
            h->SetMinimum( 0 );
            h->SetMarkerColor(color);
            h->SetMarkerSize( 0.7 );
            h->SetMarkerStyle( 24 );
            h->SetLineWidth(1);
            h->SetLineColor(color);
            color++;
            h->Draw("e1");
            Double_t hSscale = 1.0/(h->GetSumOfWeights()*h->GetBinWidth(1));

            TLegend *legS= new TLegend( cPad->GetLeftMargin(), 
                                        1-cPad->GetTopMargin()-.14, 
                                        cPad->GetLeftMargin()+.77, 
                                        1-cPad->GetTopMargin() );
            legS->SetBorderSize(1);
            legS->AddEntry(h,"Input data (signal)","p");

            // background
            TString bname( hname );	
            b = (TH1F*)lhdir->Get( bname.ReplaceAll("_sig","_bgd") );
            cPad = (TPad*)c[ic]->cd(2);
            color = 2;
            b->SetMaximum(b->GetMaximum()*1.3);
            b->SetMinimum( 0 );
            b->SetLineWidth(1);
            b->SetLineColor(color);
            b->SetMarkerColor(color);
            b->SetMarkerSize( 0.7 );
            b->SetMarkerStyle( 24 );
            b->Draw("e1");       
            Double_t hBscale = 1.0/(b->GetSumOfWeights()*b->GetBinWidth(1));
            TLegend *legB= new TLegend( cPad->GetLeftMargin(), 
                                        1-cPad->GetTopMargin()-.14, 
                                        cPad->GetLeftMargin()+.77, 
                                        1-cPad->GetTopMargin() );
            legB->SetBorderSize(1);
            legB->AddEntry(b,"Input data (backgr.)","p");

            // register
            hasBeenUsed.push_back( bname.Data() );

            // the PDFs --------------

            // check for splines
            h = 0;
            b = 0;
            TString pname = hname; pname.ReplaceAll("_nice","");            
            for (int i=0; i<= 5; i++) {
               TString hspline = pname + Form( "_smoothed_hist_from_spline%i", i );
               h = (TH1F*)lhdir->Get( hspline );
               if (h) {
                  b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") );
                  break;
               }
            }

            // check for KDE
            if (h == 0 && b == 0) {
               TString hspline = pname +"_smoothed_hist_from_KDE";
               h = (TH1F*)lhdir->Get( hspline );
               if (h) {
                  b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") );
               }
            }
               
            // found something ?
            if (h == 0 || b == 0) {
               cout << "--- likelihoodrefs.C: did not find spline for histogram: " << pname.Data() << endl;
            }
            else {
               
               Double_t pSscale = 1.0/(h->GetSumOfWeights()*h->GetBinWidth(1));
               h->Scale( pSscale/hSscale );
               color = 4;
               c[ic]->cd(1);
               h->SetLineWidth(2);
               h->SetLineColor(color);
               legS->AddEntry(h,"Estimated PDF (norm. signal)","l");
               h->Draw("histsame");
               legS->Draw();
	  
               Double_t pBscale = 1.0/(b->GetSumOfWeights()*b->GetBinWidth(1));
               b->Scale( pBscale/hBscale );
               color = 2;
               c[ic]->cd(2);
               b->SetLineColor(color);
               b->SetLineWidth(2);
               legB->AddEntry(b,"Estimated PDF (norm. backgr.)","l");
               b->Draw("histsame");

               // draw the legends
               legB->Draw();
	  
               hasBeenUsed.push_back( pname.Data() );
            }	  

            c[ic]->Update();

            // write to file
            TString fname = Form( "root_mva/plots/%s_refs_c%i", titName.Data(), ic+1 );
            TMVAGlob::imgconv( c[ic], fname );
            //	c[ic]->Update();

            newCanvas = kTRUE;
            hasBeenUsed.push_back( hname.Data() );
         }
      }
   }
}
Пример #12
0
//
//----------------------------------------------------------------------
//
int fittp0( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){

    cout << hs << " does not exist\n";

  }

  else{
   
    h->SetMarkerStyle(21);
    h->SetMarkerSize(0.8);
    h->SetStats(1);
    gStyle->SetOptFit(101);

    gROOT->ForceStyle();

    double dx = h->GetBinWidth(1);
    double nmax = h->GetBinContent(h->GetMaximumBin());
    double xmax = h->GetBinCenter(h->GetMaximumBin());
    double nn = 7*nmax;

    int nb = h->GetNbinsX();
    double n1 = h->GetBinContent(1);
    double n9 = h->GetBinContent(nb);
    double bg = 0.5*(n1+n9);

    double x1 = h->GetBinCenter(1);
    double x9 = h->GetBinCenter(nb);
    cout << hs << ": " << x1 << " - " << x9 << endl;

    // create a TF1 with the range from x1 to x9 and 5 parameters

    TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 );

    tp0Fcn->SetParName( 0, "mean" );
    tp0Fcn->SetParName( 1, "sigma" );
    tp0Fcn->SetParName( 2, "nu" );
    tp0Fcn->SetParName( 3, "area" );
    tp0Fcn->SetParName( 4, "BG" );

    tp0Fcn->SetNpx(500);
    tp0Fcn->SetLineWidth(4);
    tp0Fcn->SetLineColor(kMagenta);
    tp0Fcn->SetLineColor(kGreen);
   
    // set start values for some parameters:

    cout << hs << " " << dx << ", " << nn << ", " << xmax << endl;

    tp0Fcn->SetParameter( 0, xmax ); // peak position
    tp0Fcn->SetParameter( 1, 4*dx ); // width
    tp0Fcn->SetParameter( 2, 2.2 ); // nu
    tp0Fcn->SetParameter( 3, nn ); // N
    tp0Fcn->SetParameter( 4, bg );
    
    h->Fit( "tp0Fcn", "R", "ep" );
    // h->Fit("tp0Fcn","V+","ep");

    h->Draw("histepsame");  // data again on top
  }
}
Пример #13
0
// Main function to create the pdf's
int main(int argc, char**argv){
  TString version = "80X";

  // Define binning for pdfs (details and more options in binningConfigurations.h)
  binClass bins;
  if(version.Contains("v2")) 		bins = getV2Binning();
  if(version.Contains("80X")) 		bins = get76XBinning();
  else return 1;

  // For different jet types (if _antib is added bTag is applied)
  for(TString jetType : {"AK4chs","AK4chs_antib"}){ //,"AK4","AK4_antib"}){
    std::cout << "Building pdf's for " << jetType << "..." << std::endl;

    treeLooper t("QCD_AllPtBins", jetType);										// Init tree (third argument is the directory path, if other than default in treeLooper.h)
    bins.setReference("pt",  &t.pt);											// Give the binning class a pointer to the variables used to bin in
    bins.setReference("eta", &t.eta);
    bins.setReference("rho", &t.rho);

    // Creation of the pdfs
    std::map<TString, TH1D*> pdfs;
    for(TString binName : bins.getAllBinNames()){
      for(TString type : {"quark","gluon"}){
        TString histName = "_" + type + "_" + binName;
        pdfs["axis2" + histName] = new TH1D("axis2" + histName, "axis2" + histName, 100, 0, 8);				// Has been 200 bins before, but seemed to have a bit too much fluctuations still
        pdfs["mult"  + histName] = new TH1D("mult"  + histName, "mult"  + histName, 140, 2.5, 142.5);
        pdfs["ptD"   + histName] = new TH1D("ptD"   + histName, "ptD"   + histName, 100, 0, 1);				// Also 200 before
      }
    }


    // Fill pdfs
    TString binName;
    while(t.next()){
      if(!bins.getBinName(binName)) 								continue;		// Find bin and return false if outside ranges
      if(t.jetIdLevel < 3) 									continue;		// Select tight jets
      if(!t.matchedJet) 								 	continue; 		// Only matched jets
      if(t.nGenJetsInCone != 1 || t.nJetsForGenParticle != 1 || t.nGenJetsForGenParticle != 1) 	continue;		// Use only jets matched to exactly one gen jet and gen particle, and no other jet candidates
      if((fabs(t.partonId) > 3 && t.partonId != 21)) 						continue; 		// Keep only udsg
      if(t.bTag) 										continue;		// Anti-b tagging (always false if jetType does not contain "antib")
      if(!t.balanced) 										continue;		// Take only two leading jets with pt3 < 0.15*(pt1+pt2)  (surpresses small radiated jets with pt <<< pthat)
      if(t.mult < 3)										continue;		// Avoid jets with less than 3 particles (otherwise axis2=0)
      TString type = (t.partonId == 21? "gluon" : "quark");								// Define q/g
      TString histName = "_" + type + "_" + binName;

      pdfs["axis2" + histName]->Fill(t.axis2, t.weight);								// "axis2" already contains the log
      pdfs["mult"  + histName]->Fill(t.mult,  t.weight);
      pdfs["ptD"   + histName]->Fill(t.ptD,   t.weight);
    }

    // Try to add statistics from neighbours (first make copy, so you don't get an iterative effect)
    std::map<TString, TH1D*> pdfsCopy;
    for(auto& pdf : pdfs) pdfsCopy[pdf.first] = (TH1D*) pdf.second->Clone(pdf.first + "clone");
    for(TString binName : bins.getAllBinNames()){
      for(TString var : {"axis2","mult","ptD"}){
        for(TString neighbour : bins.getNeighbourBins(binName, var)){							// If neighbours are defined: add their statistics
          for(TString type : {"quark","gluon"}){
            pdfs[var + "_" + type + "_" + binName]->Add(pdfsCopy[var + "_" + type + "_" + neighbour]);
          }
        }
      }
    }
    for(auto& copy : pdfsCopy) delete copy.second;

    // Store the mean and RMS of the original histogram (because they could be changed by rebinning operations)
    std::map<TString, float> mean;
    std::map<TString, float> rms;
    for(auto& pdf : pdfs){
      if(pdf.second->GetEntries() == 0){ std::cout << "Error: no entries in " << pdf.first << std::endl; exit(1);}	// Force to exit when no entries in pdfs: the binning configuration should be altered to avoid this
      mean[pdf.first] = pdf.second->GetMean();
      rms[pdf.first]  = pdf.second->GetRMS();
    }


    // Check "smoothness" of the pdf: if fluctuations seem really big, we do a rebinning
    std::map<TString, int> rebinFactor;
    for(auto& pdf : pdfs){
      bool isBelow      = (mean[pdf.first] < mean[switchQG(pdf.first)]);						// Define region between low(meanQ, meanG) - RMS <--> high(meanQ, meanG) + RMS
      TString low	= isBelow? pdf.first : switchQG(pdf.first);							// Most events will be within those borders, so we should not allow empty bins here
      TString high	= isBelow? switchQG(pdf.first) : pdf.first;							// (an empty bin for 1 of the three variables already results in L = 0 or 1)
      int leftBin	= pdf.second->FindBin(mean[low] - rms[low]) - 1;
      int rightBin	= pdf.second->FindBin(mean[high] + rms[high]) + 1;
     
      int leftBin2      = 0;												// Define region of the peak: most extreme bins which exceed 80% of the maximum
      int rightBin2     = 0;												// We will check for bins within this region which go below 70%
      for(int bin = 1; bin < pdf.second->GetNbinsX(); ++bin){								// In such cases the fluctuations are really high and a larger bin width is preferred
        if(pdf.second->GetBinContent(bin) > pdf.second->GetMaximum()*0.8){						// (Maybe the thresholds could still be optimized a bit more though)
          if(!leftBin2) leftBin2  = bin;
          else          rightBin2 = bin;
        }
      }


      int leftBin3      = 0;												// Define region of the peak: most extreme bins which exceed 90% of the maximum
      int rightBin3     = 0;												// We will check for bins within this region which go below 80%
      for(int bin = 1; bin < pdf.second->GetNbinsX(); ++bin){								// In such cases the fluctuations are really high and a larger bin width is preferred
        if(pdf.second->GetBinContent(bin) > pdf.second->GetMaximum()*0.9){						// (Maybe the thresholds could still be optimized a bit more though)
          if(!leftBin3) leftBin3  = bin;
          else          rightBin3 = bin;
        }
      }

      int emptyBins     = 0;
      int maxEmptyBins  = 0;
      for(int bin = 1; bin < pdf.second->GetNbinsX(); ++bin){
        if(     bin >= leftBin  && bin <= rightBin  && pdf.second->GetBinContent(bin) <= 0)                            ++emptyBins;
        else if(bin >= leftBin2 && bin <= rightBin2 && pdf.second->GetBinContent(bin) <= pdf.second->GetMaximum()*0.7) ++emptyBins;
        else if(bin >= leftBin3 && bin <= rightBin3 && pdf.second->GetBinContent(bin) <= pdf.second->GetMaximum()*0.8) ++emptyBins;
        else {
          if(emptyBins > maxEmptyBins) maxEmptyBins = emptyBins;
          emptyBins = 0;
        }
      }
      rebinFactor[pdf.first] = std::max(maxEmptyBins, emptyBins);
    }

    for(auto& pdf : pdfs) rebinFactor[pdf.first] = std::max(rebinFactor[pdf.first], rebinFactor[switchQG(pdf.first)]);	// Use same rebin factor in quark and gluon pdf (otherwise bias if second derivate of pdf is non-zero)
    
    for(auto& pdf : pdfs){
      if(rebinFactor[pdf.first] > 19)     std::cout << "This pdf has a lot of emtpy bins and fluctuations:" << std::endl;
      if(rebinFactor[pdf.first] > 9)      rebin(pdf.second, 20);
      else if(rebinFactor[pdf.first] > 4) rebin(pdf.second, 10);
      else if(rebinFactor[pdf.first] > 3) rebin(pdf.second, 5);
      else if(rebinFactor[pdf.first] > 1) rebin(pdf.second, 4);
      else if(rebinFactor[pdf.first] > 0) rebin(pdf.second, 2);
    }


    // Normalization of the pdf's
    for(auto& pdf : pdfs) pdf.second->Scale(1./pdf.second->Integral(0, pdf.second->GetNbinsX() + 1));			// Scale to integral=1 (also include underflow/overflow)


    // Try to average out leftover fluctuations and empty bins
    for(auto& pdf : pdfs){
      if(pdf.first.Contains("gluon")) continue;

      TH1* tempQ = (TH1*) pdf.second->Clone();
      TH1* tempG = (TH1*) pdfs[switchQG(pdf.first)]->Clone();
      for(int i = 1; i < pdf.second->GetNbinsX() + 1; ++i){								// Do not consider underflow/overflow
        float contentQ = tempQ->GetBinContent(i);
        float contentG = tempG->GetBinContent(i);
        float width    = tempQ->GetBinWidth(i);

        if((1.5*contentQ < tempQ->GetBinContent(i-1) && 1.5*contentQ < tempQ->GetBinContent(i+1)) ||			// Try to average out some extreme fluctuations (i.e. only allow a difference of max 50% between two neighbouring bins)
           (1.5*contentG < tempG->GetBinContent(i-1) && 1.5*contentG < tempG->GetBinContent(i+1)) ||
           (contentQ < 1.5*tempQ->GetBinContent(i-1) && contentQ < 1.5*tempQ->GetBinContent(i+1)) ||
           (contentG < 1.5*tempG->GetBinContent(i-1) && contentG < 1.5*tempG->GetBinContent(i+1))){
          if(i-1 > 0 && i+1 < pdf.second->GetNbinsX() + 1){
            contentQ += tempQ->GetBinContent(i-1) + tempQ->GetBinContent(i+1);
            contentG += tempG->GetBinContent(i-1) + tempG->GetBinContent(i+1);
            width    += tempQ->GetBinWidth(i-1)   + tempQ->GetBinWidth(i+1);
          }
        }

        int j = 1;
        while(contentQ <= 0 || contentG <= 0){										// Average empty bins
          if(tempQ->Integral(0, i-j) <= 0) break;									// but not when surpassing the extreme edges of the pdf (see next part)
          if(tempG->Integral(0, i-j) <= 0) break;
          if(tempQ->Integral(i+j, tempQ->GetNbinsX()+1) <= 0) break;
          if(tempG->Integral(i+j, tempG->GetNbinsX()+1) <= 0) break;
          if(i-j == 0) break;
          if(i+j == pdf.second->GetNbinsX()) break;
          contentQ += tempQ->GetBinContent(i-j) + tempQ->GetBinContent(i+j);
          contentG += tempG->GetBinContent(i-j) + tempG->GetBinContent(i+j);
          width    += tempQ->GetBinWidth(i-j)   + tempQ->GetBinWidth(i+j);
          ++j;
        }

        pdf.second->SetBinContent(i, contentQ/width);
        pdfs[switchQG(pdf.first)]->SetBinContent(i, contentG/width);
      }
      delete tempQ;
      delete tempG;
    }


    // Now there are still empty bins left on the edges of the pdf, for which we assign extreme values to avoid a 0
    // (relative though, so it does not dominate the pdf's when we want to inspect them in the ROOT file; 0.000001/0.000999 has the same effect as 0.001/0.999)
    for(auto& pdf : pdfs){
      if(pdf.first.Contains("gluon")) continue;
      for(int i = 0; i <= pdf.second->GetNbinsX() + 1; ++i){
        if(pdf.second->GetBinContent(i) <= 0 || pdfs[switchQG(pdf.first)]->GetBinContent(i) <= 0){
          bool isBelow = (mean[pdf.first] < mean[switchQG(pdf.first)]);
          if(isBelow == pdf.second->GetBinCenter(i) < mean[pdf.first]){
            pdf.second->SetBinContent(i, 0.000999);
            pdfs[switchQG(pdf.first)]->SetBinContent(i, 0.000001);
          } else {
            pdf.second->SetBinContent(i, 0.000001);
            pdfs[switchQG(pdf.first)]->SetBinContent(i, 0.000999);
          }
        }
      }
    }


    // Apply the likelihood weight
    for(auto& pdf : pdfs){
      TString thisBin = pdf.first(pdf.first.Index(TRegexp("eta")), pdf.first.Length());
      TString thisVar = pdf.first(0, pdf.first.Index(TRegexp("_")));
      for(int i = 0; i < pdf.second->GetNbinsX() + 1; ++i){
        pdf.second->SetBinContent(i, std::pow(pdf.second->GetBinContent(i), bins.getWeight(thisBin, (thisVar == "mult"? 0 : (thisVar == "ptD" ? 1 : 2 )))));
      }
    }


    // Make file and write binnings
    TFile *pdfFile = new TFile("pdfQG_"+jetType + "_13TeV_" + version + ".root","RECREATE");
    pdfFile->cd();
    bins.writeBinsToFile();

    // Write to file
    for(TString var : {"axis2","ptD","mult"}) pdfFile->mkdir(var);
    for(auto& pdf : pdfs){
      for(TString var: {"axis2","ptD","mult"}) if(pdf.first.Contains(var)) pdfFile->cd(var);
      pdf.second->SetTitle(pdf.first);
      pdf.second->Write();

      TString thisBin = pdf.first(pdf.first.Index(TRegexp("eta")), pdf.first.Length());
      for(auto i : bins.getLinkedBins(thisBin)){									// Store copies for merged bins
        TString copyBin = pdf.first;
        copyBin.ReplaceAll(thisBin, i);
        pdf.second->Write(copyBin);
      }
    }

    for(auto& pdf : pdfs) delete pdf.second;
    for(auto& file : {pdfFile}){ file->Close(); delete file;}
  }
  return 0;
}
Пример #14
0
void ptBestFit(float BIN_SIZE=5.0,bool BLIND=false,TString MASS,TString NAME)
{
  gROOT->ProcessLine(".x ../../common/styleCMSTDR.C");
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
  gROOT->ForceStyle();
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gROOT->SetBatch(1);
  gStyle->SetPadRightMargin(0.04);
  gStyle->SetPadLeftMargin(0.16);
  gStyle->SetPadTopMargin(0.06);
  gStyle->SetPadBottomMargin(0.10);
  gStyle->SetTitleFont(42,"XY");
  gStyle->SetTitleSize(0.0475,"XY");
  gStyle->SetTitleOffset(0.9,"X");
  gStyle->SetTitleOffset(1.5,"Y");
  gStyle->SetLabelSize(0.0375,"XY");

  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  float XMIN = 80;
  float XMAX = 200; 

  TFile *f1 = TFile::Open("datacards/datacard_m"+MASS+"_"+NAME+".root");
  TFile *f2 = TFile::Open("combine/mlfit.vbfHbb_"+NAME+"_mH"+MASS+".root");
  TFile *f3 = TFile::Open("root/sig_shapes_workspace_B80-200.root");
  TFile *f4 = TFile::Open("root/data_shapes_workspace_"+NAME+".root");

  RooWorkspace *w = (RooWorkspace*)f1->Get("w");
  //w->Print();
  RooAbsPdf *bkg_model = (RooAbsPdf*)w->pdf("model_s");
  RooFitResult *res_s  = (RooFitResult*)f2->Get("fit_s"); 
  RooFitResult *res_b  = (RooFitResult*)f2->Get("fit_b");
  RooRealVar *rFit     = dynamic_cast<RooRealVar *>(res_s->floatParsFinal()).find("r");
  RooDataSet *data     = (RooDataSet*)w->data("data_obs");
  
  int nparS=0,nparB=0;
  cout << res_s->floatParsFinal().getSize() << endl;
  cout << res_b->floatParsFinal().getSize() << endl;
  nparS = res_s->floatParsFinal().getSize();
  nparB = res_b->floatParsFinal().getSize();  
  float chi2sumS = 0.;
  float chi2sumB = 0.;
  int nparsum = 0;
//  if (BLIND) {
//    res_b->Print();
//  }
//  else {
//    res_s->Print();
//  }
  
  w->allVars().assignValueOnly(res_s->floatParsFinal());
//  w->Print();
//  w->allVars()->Print();

  RooWorkspace *wSig = (RooWorkspace*)f3->Get("w"); 
  RooWorkspace *wDat = (RooWorkspace*)f4->Get("w"); 

  const RooSimultaneous *sim = dynamic_cast<const RooSimultaneous *> (bkg_model);
  const RooAbsCategoryLValue &cat = (RooAbsCategoryLValue &) sim->indexCat();
  TList *datasets = data->split(cat,true);
  TIter next(datasets);
  //int count = 0; 
  for(RooAbsData *ds = (RooAbsData*)next();ds != 0; ds = (RooAbsData*)next()) {
	 //if (count > 0) return 0;
	 //count++;
    RooAbsPdf *pdfi = sim->getPdf(ds->GetName());
    RooArgSet *obs = (RooArgSet*)pdfi->getObservables(ds);
    RooRealVar *x = dynamic_cast<RooRealVar *>(obs->first());

    RooRealVar *yield_vbf = (RooRealVar*)wSig->var("yield_signalVBF_mass"+MASS+"_"+TString(ds->GetName()));
    RooRealVar *yield_gf  = (RooRealVar*)wSig->var("yield_signalGF_mass"+MASS+"_"+TString(ds->GetName()));
    TString ds_name(ds->GetName());
    //----- get the QCD normalization -----------
    RooRealVar *qcd_norm_final = dynamic_cast<RooRealVar *>(res_s->floatParsFinal()).find("CMS_vbfbb_qcd_norm_"+ds_name);
    RooRealVar *qcd_yield      = (RooRealVar*)wDat->var("yield_data_"+ds_name);

    float Nqcd  = exp(log(1.5)*qcd_norm_final->getVal())*qcd_yield->getVal();
    float eNqcd = log(1.5)*qcd_norm_final->getError()*Nqcd;
    cout<<"QCD normalization = "<<Nqcd<<" +/- "<<eNqcd<<endl;
    
    TH1 *hCoarse = (TH1*)ds->createHistogram("coarseHisto_"+ds_name,*x);
    float norm = hCoarse->Integral();
  
	 int rebin = BIN_SIZE/hCoarse->GetBinWidth(1);
    hCoarse->Rebin(rebin);

    float MIN_VAL = TMath::Max(0.9*hCoarse->GetBinContent(hCoarse->GetMinimumBin()),1.0);
    float MAX_VAL = 1.3*hCoarse->GetBinContent(hCoarse->GetMaximumBin());
    RooDataHist ds_coarse("ds_coarse_"+ds_name,"ds_coarse_"+ds_name,*x,hCoarse);

    TH1F *hBlind = (TH1F*)hCoarse->Clone("blindHisto_"+ds_name);
    for(int i=0;i<hBlind->GetNbinsX();i++) {
      double x0 = hBlind->GetBinCenter(i+1);
      if (x0 > 100 && x0 < 150) {
        hBlind->SetBinContent(i+1,0);
        hBlind->SetBinError(i+1,0);
      }
    }
    
    RooDataHist ds_blind("ds_blind_"+ds_name,"ds_blind_"+ds_name,*x,hBlind); 
    
    RooHist *hresid,*hresid0;
    RooPlot *frame1 = x->frame();
    RooPlot *frame2 = x->frame();
    
    if (BLIND) {
		//cout << "Blind case: " << ds_coarse.GetName() << endl;
      ds_coarse.plotOn(frame1,LineColor(0),MarkerColor(0));
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack());
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(3));
      ds_blind.plotOn(frame1);
      hresid = frame1->residHist();
      frame2->addPlotable(hresid,"pE1");
    }
    else {    
		//cout << "Non-blind case: " << ds_coarse.GetName() << endl;
		ds_coarse.plotOn(frame1);
      pdfi->plotOn(frame1);
		//cout << pdfi->getParameters(ds_coarse)->selectByAttrib("Constant",kFALSE)->getSize() << endl;
      cout<<"chi2/ndof (bkg+sig) = "<<frame1->chiSquare()<<endl;
		cout << ds_coarse.numEntries() << endl;
		chi2sumS += frame1->chiSquare()*ds_coarse.numEntries();
		nparsum += ds_coarse.numEntries();
		//hresid0 = frame1->residHist();
      //pdfi->plotOn(frame1,VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack());
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name),LineWidth(2),LineStyle(5),LineColor(kGreen+2));
      pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(2),LineColor(kBlack)); 
      cout<<"chi2/ndof (bkg) = "<<frame1->chiSquare()<<endl;
		chi2sumB += frame1->chiSquare()*ds_coarse.numEntries();
		pdfi->plotOn(frame1,Components("shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name),LineWidth(2),LineStyle(2),LineColor(kBlack),VisualizeError(*res_s,1,kTRUE),FillColor(0),MoveToBack()); 
      hresid = frame1->residHist();
      frame2->addPlotable(hresid,"pE1");
    
      float yield_sig = rFit->getValV()*(yield_vbf->getValV()+yield_gf->getValV());
      RooAbsPdf *signal_pdf = (RooAbsPdf*)w->pdf("shapeSig_qqH_"+ds_name);
      signal_pdf->plotOn(frame2,LineWidth(2),LineColor(kRed),Normalization(yield_sig,RooAbsReal::NumEvent),MoveToBack());
    }
//	 hresid0->Print();
//	 hresid->Print();
//	 double x2,y2;
//	 for (int i=0; i<3; ++i) {
//		 hresid0->GetPoint(i,x2,y2);
//		 cout << "BKG+SIG\t" << x2 << "\t" << y2 << endl;
//		 hresid->GetPoint(i,x2,y2);
//		 cout << "BKG\t" << x2 << "\t" << y2 << endl;
//		 ds_coarse.get(i);
//		 cout << ds_coarse.weightError(RooAbsData::SumW2) << endl;
//		 cout << endl;
//	 }

    TCanvas* canFit = new TCanvas("Higgs_fit_"+ds_name,"Higgs_fit_"+ds_name,900,750);
    canFit->cd(1)->SetBottomMargin(0.4);
    frame1->SetMinimum(MIN_VAL);
    frame1->SetMaximum(MAX_VAL);
    frame1->GetYaxis()->SetNdivisions(510);
    frame1->GetXaxis()->SetTitleSize(0);
    frame1->GetXaxis()->SetLabelSize(0);
    frame1->GetYaxis()->SetTitle(TString::Format("Events / %1.1f GeV",BIN_SIZE));
    frame1->Draw();
    gPad->Update();
    
    TList *list = (TList*)gPad->GetListOfPrimitives();
    //list->Print();
    TH1F *hUncH  = new TH1F("hUncH"+ds_name,"hUncH"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX);
    TH1F *hUncL  = new TH1F("hUncL"+ds_name,"hUncL"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX);
    TH1F *hUnc2H = new TH1F("hUnc2H"+ds_name,"hUnc2H"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX);
    TH1F *hUnc2L = new TH1F("hUnc2L"+ds_name,"hUnc2L"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); 
    TH1F *hUncC  = new TH1F("hUncC"+ds_name,"hUncC"+ds_name,(XMAX-XMIN)/BIN_SIZE,XMIN,XMAX); 
    
    RooCurve *errorBand,*gFit,*gQCDFit,*gBkgFit;
    
	//list->Print();
    if (BLIND) {
      errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
      gFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
    }
    else {
      //errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband");
      errorBand = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]_errorband_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
      gFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]");
    } 
    gQCDFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+"]");  
    gBkgFit = (RooCurve*)list->FindObject("pdf_bin"+ds_name+"_Norm[mbbReg_"+ds_name+"]"+"_Comp[shapeBkg_qcd_"+ds_name+",shapeBkg_top_"+ds_name+",shapeBkg_zjets_"+ds_name+"]");
    for(int i=0;i<hUncH->GetNbinsX();i++) {
      double x0 = hUncH->GetBinCenter(i+1);
      double e1 = fabs(errorBand->Eval(x0)-gBkgFit->Eval(x0));
      //double e1 = fabs(errorBand->Eval(x0)-gFit->Eval(x0));
      double e2 = eNqcd/hUncH->GetNbinsX();
      hUncH->SetBinContent(i+1,sqrt(pow(e2,2)+pow(e1,2)));
      hUnc2H->SetBinContent(i+1,2*sqrt(pow(e2,2)+pow(e1,2)));
      hUncL->SetBinContent(i+1,-sqrt(pow(e2,2)+pow(e1,2)));
      hUnc2L->SetBinContent(i+1,-2*sqrt(pow(e2,2)+pow(e1,2)));
		hUncC->SetBinContent(i+1,0.);
    }
   
    TPad* pad = new TPad("pad", "pad", 0., 0., 1., 1.);
    pad->SetTopMargin(0.63);
    pad->SetFillColor(0);
    pad->SetFillStyle(0);
    pad->Draw();
    pad->cd(0);
    hUnc2H->GetXaxis()->SetTitle("m_{bb} (GeV)");
    hUnc2H->GetYaxis()->SetTitle("Data - Bkg");
    //hUnc2H->GetYaxis()->SetTitle("Data - Fit");
    double YMAX = 1.1*frame2->GetMaximum();
    double YMIN = -1.1*frame2->GetMaximum();
    hUnc2H->GetYaxis()->SetRangeUser(YMIN,YMAX);
    hUnc2H->GetYaxis()->SetNdivisions(507);
//    hUnc2H->GetXaxis()->SetTitleOffset(0.9);
//    hUnc2H->GetYaxis()->SetTitleOffset(1.0);
    hUnc2H->GetYaxis()->SetTickLength(0.0);
//    hUnc2H->GetYaxis()->SetTitleSize(0.05);
//    hUnc2H->GetYaxis()->SetLabelSize(0.04);
    hUnc2H->GetYaxis()->CenterTitle(kTRUE);
    hUnc2H->SetFillColor(kGreen);
    hUnc2L->SetFillColor(kGreen);
    hUncH->SetFillColor(kYellow);
    hUncL->SetFillColor(kYellow);
	 hUncC->SetLineColor(kBlack);
	 hUncC->SetLineStyle(7);
    hUnc2H->Draw("HIST");
    hUnc2L->Draw("same HIST");
    hUncH->Draw("same HIST");
    hUncL->Draw("same HIST");
	 hUncC->Draw("same HIST");
	 frame2->GetYaxis()->SetTickLength(0.03/0.4);
    frame2->Draw("same");

    TList *list1 = (TList*)gPad->GetListOfPrimitives();
    //list1->Print();
    RooCurve *gSigFit = (RooCurve*)list1->FindObject("shapeSig_qqH_"+ds_name+"_Norm[mbbReg_"+ds_name+"]");

    TLegend *leg = new TLegend(0.70,0.61,0.94,1.-gStyle->GetPadTopMargin()-0.01);
	 leg->SetTextFont(42);
	 leg->SetFillStyle(-1);
	 //leg->SetHeader(ds_name+" (m_{H}="+MASS+")");
    leg->SetHeader(TString::Format("Category %d",atoi(ds_name(3,1).Data())+1));
    leg->AddEntry(hBlind,"Data","P");
    if (!BLIND) {
      leg->AddEntry(gSigFit,"Fitted signal","L");
    }
	 TLine *gEmpty = new TLine(0.0,0.0,0.0,0.0);
	 gEmpty->SetLineWidth(0);
	 TLegendEntry *l1 = leg->AddEntry(gEmpty,"(m_{H} = "+MASS+" GeV)","");
	 l1->SetTextSize(0.038*0.97*0.85);
    leg->AddEntry(gFit,"Bkg. + signal","L");
    leg->AddEntry(gBkgFit,"Bkg.","L");
    leg->AddEntry(gQCDFit,"QCD","L");
    leg->AddEntry(hUnc2H,"2#sigma bkg. unc.","F");
    leg->AddEntry(hUncH,"1#sigma bkg. unc.","F");
    leg->SetFillColor(0);
    leg->SetBorderSize(0);
    leg->SetTextFont(42);
    leg->SetTextSize(0.038*0.98);
    leg->Draw(); 
	 leg->SetY1(leg->GetY2()-leg->GetNRows()*0.045*0.96);
     
    TPaveText *paveCMS = new TPaveText(gStyle->GetPadLeftMargin()+0.02,0.7,gStyle->GetPadLeftMargin()+0.15,1.-gStyle->GetPadTopMargin()-0.01,"NDC");
	 paveCMS->SetTextFont(62);
	 paveCMS->SetTextSize(gStyle->GetPadTopMargin()*3./4.);
	 paveCMS->SetBorderSize(0);
	 paveCMS->SetFillStyle(-1);
	 paveCMS->SetTextAlign(12);
	 paveCMS->AddText("CMS");
	 paveCMS->Draw();
	 gPad->Update();
	 paveCMS->SetY1NDC(paveCMS->GetY2NDC()-paveCMS->GetListOfLines()->GetSize()*gStyle->GetPadTopMargin());

	 TPaveText *paveLumi = new TPaveText(0.5,1.-gStyle->GetPadTopMargin(),0.98,1.00,"NDC");
	 paveLumi->SetTextFont(42);
	 paveLumi->SetTextSize(gStyle->GetPadTopMargin()*3./4.);
	 paveLumi->SetBorderSize(0);
	 paveLumi->SetFillStyle(-1);
	 paveLumi->SetTextAlign(32);
	 paveLumi->AddText(TString::Format("%.1f fb^{-1} (8TeV)",(atoi(ds_name(3,1).Data())<4 ? 19.8 : 18.3)).Data());//+ 18.2 ;
	 paveLumi->Draw();

	 TString path=".";
	 //TString path="BiasV10_limit_BRN5p4_dX0p1_B80-200_CAT0-6/output/";
	 system(TString::Format("[ ! -d %s/plot ] && mkdir %s/plot",path.Data(),path.Data()).Data());
	 system(TString::Format("[ ! -d %s/plot/fits ] && mkdir %s/plot/fits",path.Data(),path.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.pdf",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.png",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s.eps",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 TText *l = (TText*)paveCMS->AddText("Preliminary");
	 l->SetTextFont(52);
	 paveCMS->Draw();
	 gPad->Update();
	 paveCMS->SetY1NDC(paveCMS->GetY2NDC()-paveCMS->GetListOfLines()->GetSize()*gStyle->GetPadTopMargin());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.pdf",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.png",path.Data(),MASS.Data(),ds_name.Data()).Data());
	 canFit->SaveAs(TString::Format("%s/plot/fits/Fit_mH%s_%s_prelim.eps",path.Data(),MASS.Data(),ds_name.Data()).Data());

    delete ds;
  }

  cout << "chi2sumS: " << chi2sumS << endl;
  cout << "chi2sumB: " << chi2sumB << endl;
  cout << "nparS: " << nparS << endl;
  cout << "nparB: " << nparB << endl;
  cout << "nbinsum: " << nparsum << endl;
  cout << "chi2sumS/(nbinsum - nparS): " << chi2sumS / (float)(nparsum - nparS) << endl;
  cout << "chi2sumB/(nbinsum - nparB): " << chi2sumB / (float)(nparsum - nparB) << endl;
  delete datasets; 
}
Пример #15
0
void AnalysisSparse(Bool_t save_output = kFALSE)
{
  gStyle->SetGridColor(kGray);
  //  TString tmpstr(fname);
  //  if (tmpstr.Contains("data")) {
  //    Printf("!!! Real Data !!!");
  //    mc = kFALSE;
  //  }
  TString gtitle = Form("Monte Carlo, %s", graph_name.Data());
  grapht = graph_name.Data();
  Double_t grx[999], gry[999], gry2[999], gry3[999], gry4[999],
    gry_eff[999], gry_fix[999], grxE[999];
  Double_t gry22[999], gry22E[999], grx22E[999];
  Double_t gry_true[999], gry_true_eff[999], gry_true_effE[999];
  TH1::AddDirectory(kFALSE);
  TFile::SetCacheFileDir(gSystem->HomeDirectory());
  TFile *f = TFile::Open(fname.Data(), "CACHEREAD");
  if (!f) return;
  TList *l; f->GetObject(lname.Data(), l);
  if (!l) return;
  Int_t bf[999], bl[999];
  Int_t nn = FindExactRange(((THnSparse *)(l->FindObject(s1name.Data())))->
                            Projection(1), del_step, bf, bl);
  //  Int_t nn = FindRange5(bf, bl);
  Bool_t binhaluska = kFALSE;
  if (binAnders) {
    nn = 8;
    bf[0] = 6;bf[1] =  9;bf[2] = 11;bf[3] = 16;bf[4] = 21;bf[5] = 26;
    bl[0] = 8;bl[1] = 10;bl[2] = 15;bl[3] = 20;bl[4] = 25;bl[5] = 30;

    bf[6] = 31;bf[7] = 41;
    bl[6] = 40;bl[7] = 50;
  }
  Printf("number of intervals = %d =>", nn);

  Int_t count = 0;
  Double_t ptmean = 0, value = 0;
  Int_t fitStatus = -1;
  gStyle->SetOptStat(0);
  TCanvas *c = new TCanvas("c", "Signal & Background");
  c->Divide(5, 5); c->Modified(); c->Draw();
  TCanvas *c2 = (TCanvas *)c->DrawClone("c2");
  c2->SetTitle("Phi mesons (raw)"); c2->Modified(); c2->Draw();
  TCanvas *c3, *c4;
  if (mc) {
    c3 = (TCanvas *)c->DrawClone("c3");
    c3->SetTitle("Phi mesons (gen)"); c3->Modified(); c3->Draw();
    c4 = (TCanvas *)c->DrawClone("c4");
    c4->SetTitle("Phi mesons (true)"); c4->Modified(); c4->Draw();
  }

  for (Int_t i = 0; i < nn; i++) {
    c->cd(count + 1)->SetGrid();
    h1 = (TH1D *)PullHisto(l, s1name.Data(), bf[i], bl[i], ptmean);
    h1->SetLineColor(kRed);
    h1->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
    h1->Draw("hist");

    h3_p = (TH1D *)PullHisto(l, s3name_p.Data(), bf[i], bl[i], ptmean);
    h3_m = (TH1D *)PullHisto(l, s3name_m.Data(), bf[i], bl[i], ptmean);
    // !!!!!!!!!!!!!!!!!!!!!!!!
    if (count==0) h3_p = h1;
    // !!!!!!!!!!!!!!!!!!!!!!!!
    else {
      h3_p->Add(h3_m);
      //      h3_p->Add((TH1D *)PullHisto(l, smix.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixpp.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixmm.Data(), bf[i], bl[i], ptmean));
      Norm(h1, h3_p, norm[0], norm[1]);
    }
    h3_p->SetLineColor(kBlue);
    h3_p->Draw("hist, same");

    if (mc) {
      c3->cd(count + 1)->SetGrid();
      Printf("%s", s1namegen.Data());
      hg = (TH1D *)PullHisto(l, s1namegen.Data(), bf[i], bl[i], ptmean);
      hg->SetLineColor(kMagenta);
      hg->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      hg->Draw("hist");
      c4->cd(count + 1)->SetGrid();
      ht = (TH1D *)PullHisto(l, s1nametrue.Data(), bf[i], bl[i], ptmean);
      ht->SetLineColor(kMagenta-5);
      ht->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      ht->Draw("hist");
    }
    c2->cd(count + 1)->SetGrid();
    TH1 *hh = (TH1 *)h1->Clone("hh");
    hh->SetLineColor(kRed+1);
    hh->Add(h3_p, -1);
    /// !!!!!!!!!!!!!!!!!!!!!!
    //////////    if ((ilist == 3) && (count < 2)) hh->Reset();
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    hh->Draw("hist");

    // !!!!!!!!!!!!!!!!!!
    ff->SetParameters(0.1, 1.02, 0.004, -25000., 0., 0., 0.);
    ff->SetLineColor(hh->GetLineColor());
    ff->SetLineWidth(1);
    //    ff->SetLineStyle(kDashed);
    // where fit
    Double_t fmin = 1.02-2*0.004;
    Double_t fmax = 1.02+2*0.004;
    //    Double_t fmin = 0.995;
    //    Double_t fmax = 1.185;
    // !!!!!!!!!!!!!!!!!!
    Bool_t hisfun = kFALSE; // kFALSE = integral from function
    Double_t   hisfun_k = 1.0/hh->GetBinWidth(10);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    if (binhaluska)
      if (i > 9) hisfun_k = 0.5/hh->GetBinWidth(10);
    Printf("======= %f", hisfun_k);
    // !!!!!!!!!!!!!!!!!!
    // wehere integral (his or fun)
    Double_t fmini = 1.02-2*0.004;
    Double_t fmaxi = 1.02+2*0.004;
    hh->Fit(ff, "Q", "", fmin, fmax);
    hh->Fit(ff, "Q", "", fmin, fmax);
    fitStatus = hh->Fit(ff, "Q", "", fmin, fmax);
    TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
    pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
                       ff->GetParameter(5), ff->GetParameter(6));
    pp3->SetLineWidth(1);
    pp3->SetLineColor(h3_p->GetLineColor());
    pp3->Draw("same");
    // ff->SetRange(fmin, fmax);
    // ff->DrawCopy("same");

    value              = hh->Integral(hh->FindBin(fmini), hh->FindBin(fmaxi));
    if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k -
                   pp3->Integral(fmini, fmaxi)*hisfun_k;
    if (value < 0) value = 0;

    if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
      printf(" SKIP Data");
      value = 0;
    }
    grx[count] = ptmean;
    if (binhaluska) {
      if (count < 10) grxE[count] = 0.25; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      else            grxE[count] = 0.50; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
    else
      //      grxE[count] = (1.30-1.10)/2.0; // !!!!!!!!!!!!!!!!!!!!!!!!!!
      grxE[count] = 0.05;
    gry[count] = value;

    Double_t tmp1 = h1->Integral(h1->FindBin(fmini), h1->FindBin(fmaxi));
    Double_t tmp2 = h3_p->Integral(h3_p->FindBin(fmini), h3_p->FindBin(fmaxi));
    Double_t tmp_sg = tmp1 - tmp2;
    Double_t tmp_bg = tmp2;

    // if ((tmp_sg <= -tmp_bg) || (tmp_bg < 33.0)) {
    //   gry3[count] = 0.0;
    //   gry4[count] = 0.0;
    // }
    // else {
    gry3[count] = tmp_sg/tmp_bg;
    gry4[count] = tmp_sg/TMath::Sqrt(tmp_sg + tmp_bg);
    // }

    //    Printf("%4.2f, %10f, %10f, %10f", ptmean, tmp1, tmp2, gry3[count]);


    if (mc) {
      c3->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      hg->Fit(ff, "Q", "", fmin, fmax);
      hg->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = hg->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = hg->Integral(hg->FindBin(fmini), hg->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP MC");
        value = -1;
      }
      gry2[count]    = value;
      Double_t superfactor = CalculateFactor(l, 0.1);
      if (useCF) {
        gry22E[i] = TMath::Sqrt(gry2[i])*superfactor;
        //        gry22E[i] = 0.0001;
        gry22[i]  = gry2[i]*superfactor;
        grx22E[i] = 0.05;
      }
      gry_eff[count] = gry[count]/gry2[count];

      c4->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      ht->Fit(ff, "Q", "", fmin, fmax);
      ht->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = ht->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = ht->Integral(ht->FindBin(fmini), ht->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP true");
        value = -1;
      }
      gry_true[count]     = value;
      gry_true_eff[count] = gry_true[count]/gry2[count];
      // Propagation of uncertainty (A/B)
      Double_t AAA  = gry_true[count];
      Double_t AAAE = TMath::Sqrt(AAA);
      Double_t BBB  = gry2[count];
      Double_t BBBE = TMath::Sqrt(BBB);
      Double_t EEE  = TMath::Sqrt((AAAE/AAA)*(AAAE/AAA)+(BBBE/BBB)*(BBBE/BBB));
      EEE = EEE*gry_true_eff[count];
      gry_true_effE[count] = EEE;
    }

    Printf("=> %6.4f", ptmean);
    count++;
  }

  new TCanvas();
  TGraph *gr = new TGraph(count, grx, gry);
  gr->SetMarkerStyle(8);
  gr->SetMarkerColor(hh->GetLineColor());
  gr->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr->SetTitle(Form("raw phi, %s", gtitle.Data()));
  gr->Draw("AP");

  cc3 = new TCanvas();
  TGraph *gr3 = new TGraph(count, grx, gry3);
  gr3->SetMarkerStyle(22);
  gr3->SetMarkerColor(kBlue+1);
  gr3->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr3->SetTitle(Form("SIG / BKG, %s", gtitle.Data()));
  gr3->SetMinimum(0);
  gr3->Draw("AP");

  cc4 = new TCanvas();
  TGraph *gr4 = new TGraph(count, grx, gry4);
  gr4->SetMarkerStyle(23);
  gr4->SetMarkerColor(kBlue-1);
  gr4->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr4->SetTitle(Form("Significance, %s", gtitle.Data()));
  gr4->SetMinimum(0);
  gr4->Draw("AP");

  ccc = new TCanvas("ccc","ccc",0,0,900,300);
  ccc->Divide(2, 1, 0.001, 0.001);
  ccc->cd(1); gr3->Draw("AP");
  ccc->cd(2); gr4->Draw("AP");

  TString blabla = "mc";
  if (!mc) blabla = "data";
  // gr3->SaveAs(Form("SB_%s_%s.C", blabla.Data(), grapht.Data()));
  // gr4->SaveAs(Form("Sig_%s_%s.C", blabla.Data(), grapht.Data()));
  // ccc->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  // c->SaveAs(Form("%s_%s_0.eps", blabla.Data(), grapht.Data()));
  // c2->SaveAs(Form("%s_%s_1.eps", blabla.Data(), grapht.Data()));

  //  cc3->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  //  gr3->SaveAs(Form("sig_bck_%s_%s.C", blabla.Data(), grapht.Data()));

  if (mc) {
    new TCanvas();
    TGraph *gr2 = new TGraph(count, grx, gry2);
    gr2->SetMarkerStyle(8);
    gr2->SetMarkerColor(hg->GetLineColor());
    gr2->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr2->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr2->Draw("AP");

    new TCanvas();
    TGraphErrors *gr22 = new TGraphErrors(count, grx, gry22, grx22E, gry22E);
    gr22->SetMarkerStyle(8);
    gr22->SetMarkerColor(kCyan);
    gr22->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr22->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr22->Draw("AP");


    c = new TCanvas();
    c->SetGrid();
    TGraph *gr_e = new TGraph(count, grx, gry_eff);
    gr_e->SetMarkerStyle(22);
    gr_e->SetMarkerColor(kBlack);
    gr_e->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_e->SetTitle(Form("efficiency (raw), %s", grapht.Data()));
    gr_e->Draw("AP");
    Printf("Save as '\033[1meffi_raw_%s\033[0m' file", grapht.Data());
    for (Int_t i = 0; i < gr_e->GetN(); i++)
      Printf("%f %f", gr_e->GetX()[i], gr_e->GetY()[i]);

    cvb = new TCanvas();
    cvb->cd();
    TGraph *gr_true = new TGraph(count, grx, gry_true);
    gr_true->SetMarkerStyle(8);
    gr_true->SetMarkerColor(ht->GetLineColor());
    gr_true->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true->SetTitle(Form("true phi, %s", gtitle.Data()));
    gr_true->Draw("AP");
    c = new TCanvas();
    c->cd();
    c->SetGrid();
    TGraphErrors *gr_true_eff = new TGraphErrors(count, grx, gry_true_eff,
                                                 grxE, gry_true_effE);
    gr_true_eff->SetMarkerStyle(20);
    //    gr_true_eff->SetMarkerSize(0.75);
    gr_true_eff->SetMarkerColor(kBlack);
    gr_true_eff->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true_eff->SetTitle(Form("efficiency (true), %s", grapht.Data()));
    gr_true_eff->Draw("AEP");
    m_gr->Add(gr_true_eff);
    Printf("Save as '\033[1meffi_true_%s\033[0m' file", grapht.Data());
    TString tout;
    Double_t oux, ouy, ouxe, ouye;
    for (Int_t i = 0; i < gr_true_eff->GetN(); i++) {
      oux = gr_true_eff->GetX()[i];
      ouy = gr_true_eff->GetY()[i];
      ouy = MinusCheck(ouy);
      ouxe = gr_true_eff->GetErrorX(i);
      ouye = gr_true_eff->GetErrorY(i);
      ouye = NanCheck(ouye);
      Printf("%f %f %f %f", gr_true_eff->GetX()[i], gr_true_eff->GetY()[i],
             gr_true_eff->GetErrorX(i), gr_true_eff->GetErrorY(i));
      if (!save_output) continue;
      gSystem->mkdir(dir_prefix.Data());
      tout = Form("%f %f %f %f", oux, ouy, ouxe, ouye);
      if (i == 0)
        tout = Form("Printf(\"%s\"); > %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      else
        tout = Form("Printf(\"%s\"); >> %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      //      Printf(":::::: %s", tout.Data());
      gROOT->ProcessLine(tout.Data());
    }
    // ------------------
    c = new TCanvas("cfinal", "mc_effi", 1200, 450);
    c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
    c->cd(1);
    gr_true->SetMinimum(0);
    gr_true->SetTitle(Form("phi (true & raw), %s", gtitle.Data()));
    gr_true->SetMarkerColor(kGreen+1);
    gr_true->Draw("AP");
    gr->SetMarkerColor(kRed+1);
    gr->Draw("P");
    c->cd(2)->SetGrid();
    gr_true_eff->SetMinimum(0);
    gr_true_eff->SetTitle(Form("efficiency, %s", grapht.Data()));
    gr_true_eff->SetMarkerColor(kGreen+1);
    gr_true_eff->Draw("AP");
    gr_e->SetMarkerColor(kRed+1);
    gr_e->Draw("P");
    //    c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
    return;
  }

  //  TGraph *geff = new TGraph(Form("effi_raw_%s", grapht.Data()));
  //  TGraph *geff = new TGraph(Form("effi_true_%s", grapht.Data()));
  //  TGraph *geff = new TGraph("effi_true_Phi2010_qualityonly");
  TGraph *geff = new TGraph("effi_true_PhiNsigma_qualityonly");
  if (geff->IsZombie()) return;
  geff->SetMarkerStyle(22);
  geff->SetMarkerColor(kBlack);
  geff->GetXaxis()->SetTitle("p_{t}, GeV/c");
  geff->SetTitle(Form("efficiency, %s", grapht.Data()));
  c = new TCanvas();
  c->SetGrid();
  geff->Draw("AP");
  Double_t tpcsigma = 9999.9;
  if (ilist == 1) tpcsigma = 1.0;
  if (ilist == 2) tpcsigma = 1.5;
  if (ilist == 3) tpcsigma = 2.0;
  if (ilist == 4) tpcsigma = 2.5;
  if (ilist == 5) tpcsigma = 3.0;
  Double_t sss = TMath::Erf(tpcsigma/TMath::Sqrt(2.0));
  if (noSigma) sss = 1.0;
  Printf("sigma = %10f", sss);

  // for (Int_t i = 0; i < count; i++)
  //   geff->GetY()[i] = (sss*sss)/(geff->GetY()[i]);
  // geff->SetMaximum(1.0);
  // geff->Draw("AP");

  for (Int_t i = 0; i < count; i++) {
    Double_t deno = geff->Eval(grx[i])*sss*sss;
    if (deno < 0.00001) deno = 1;
    gry_fix[i] = gry[i]/deno;
  }
  new TCanvas;
  TGraph *gr_fix = new TGraph(count, grx, gry_fix);
  gr_fix->SetMarkerStyle(21);
  gr_fix->SetMarkerColor(hh->GetLineColor());
  gr_fix->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr_fix->SetTitle(Form("corrected phi * #sigma^{2}, %s", gtitle.Data()));
  if (noSigma)
    gr_fix->SetTitle(Form("corrected phi (no #sigma), %s", gtitle.Data()));
  gr_fix->Draw("AP");

  //---------------------
  c = new TCanvas("cfinald", "data_correct", 1200, 450);
  c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
  c->cd(1);
  gr->SetMinimum(0);
  gr->SetMarkerColor(kBlack);
  gr->Draw("AP");
  c->cd(2);
  gr_fix->SetMinimum(0);
  gr_fix->SetMarkerColor(kGreen+3);
  gr_fix->Draw("AP");
  TString bla9 = Form("qualityonly_PID2_%s", grapht.Data());
  if (noSigma) bla9 = Form("%s_noSig.C", bla9.Data());
  else         bla9 = Form("%s.C", bla9.Data());
  //  gr_fix->SaveAs(bla9.Data());
  //  TPad *cp = new TPad("cpf", "", 0.45,0.45,0.99,0.92);
  TPad *cp = new TPad("cpf", "", 0.60,0.55,0.99,0.93);
  cp->SetLogy(); cp->Draw(); cp->cd();
  TGraph *cloneg = ((TGraph *)gr_fix->Clone());
  cloneg->SetTitle(); cloneg->SetMarkerSize(0.8);
  cloneg->Draw("AP");
  //  c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
  f->Close();
}
Пример #16
0
void MakePi0Analysis(){

  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.01);
  gStyle->SetPadTopMargin(0.09);
  gStyle->SetPadBottomMargin(0.11);
  //gStyle->SetOptStat(0);
  //gStyle->SetOptTitle(1);
  //gStyle->SetPadTickX(1);
  //gStyle->SetPadTickY(1);
  TGaxis::SetMaxDigits(3);
  
  Double_t bins[] = {1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0, 3.2, 3.4, 3.6,3.8,4.0,4.5, 5.0, 5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,10.0,11,12}; //Nicolas LHC12d PHI
  const Int_t binnum = sizeof(bins)/sizeof(Double_t) - 1;
  
  TString cwd = gSystem->WorkingDirectory();

  TH1F* fHistPeakMean  = new TH1F("fHistPeakMean","",binnum,bins);
  TH1F* fHistPeakWidth = new TH1F("fHistPeakWidth","",binnum,bins);
  TH1F* fHistRawYield  = new TH1F("fHistRawYield","",binnum,bins);
  TH1F* fHistRawYieldPerEvent  = new TH1F("fHistRawYieldPerEvent","",binnum,bins);
  
  TCanvas *c1[binnum];
  TCanvas *c2[binnum];
  TCanvas *c3;

  TFile* ef     = TFile::Open("../AnalysisResults.root");
  TList* list   = (TList*)ef->Get("list_kINT7_Pi0");
  TList *listEv = (TList*)ef->Get("list_kINT7_Event");
  
  TH1F* fHistEvents = (TH1F*)listEv->FindObject("fHistAnalyzedEvents");
  Double_t nEvt = fHistEvents->GetEntries();
  
  TString tofName[] = {"","_TOFcut1","_TOFcut2"};
  TString fitName[] = {"CrystalBall","AsymmGauss"};
  TString modName[] = {"","_M1","_M3"};
  
  Int_t ntof = 3;
  
  Double_t signal_range_min=0.11;
  Double_t signal_range_max=0.15;
  Double_t bg_range_min=0.050;
  Double_t bg_range_max=0.250;
  
  for(Int_t itof=0; itof<ntof; ++itof){
    for(Int_t iMod=0; iMod<1; iMod++){
      for(Int_t iFit=0; iFit<2; iFit++){
	for(Int_t iPol=0; iPol<3; iPol++){
	  
	  Int_t pol = iPol;

	  TString fNameSame = "fHistMassTwoGammas"+tofName[itof]+modName[iMod];
	  TString fNameMix  = "fHistMixMassTwoGammas"+tofName[itof]+modName[iMod];
	  
	  THnSparse *fTHnSparseRecPi0;
	  THnSparse *fTHnSparseRecMixPi0;
	  THnSparse *fTHnSparseGeneratePi0;
	  
	  TH2* hPi0A08    = 0x0;
	  TH2* hMixPi0A08 = 0x0;
	  hPi0A08    = (TH2*)list->FindObject(fNameSame)->Clone();
	  hMixPi0A08 = (TH2*)list->FindObject(fNameMix)->Clone();

	  Int_t sbin = 0;
	  Int_t lbin = 0;
      
	  TH1F* fHistFinalRatio[binnum];
	  TH1F* fHistFinalSame[binnum];
	  TH1F* fHistFinalBG[binnum];
	  TH1F* fHistFinalSignal[binnum];
	  TH1F* fHistOnlyFitSignal[binnum];
	  
	  TF1* fFitFinalRatio[binnum];
	  TF1* fFitFinalSignal[binnum];
	  TF1* fFitOnlyFitSignal[binnum];

	  for(Int_t i=0; i<binnum; i++){    
	    
	    Double_t bin_width = (bins[i+1]-bins[i]);
	    Double_t bin_mean  = (bins[i+1]+bins[i])/2;
	    
	    Int_t rebin = 1;
	    
	    if(bin_mean>5.0){
	      rebin=10;
	    }
	    else{
	      rebin=5;
	    }
	    
	    Int_t sproj_bin = hPi0A08->GetYaxis()->FindBin(bins[i]);
	    Int_t lproj_bin = hPi0A08->GetYaxis()->FindBin(bins[i+1])-1;
	    
	    TH1* fHistBasicSame = (TH1*)hPi0A08   ->ProjectionX(Form("fHistBasicSame_No%d",i+1),sproj_bin,lproj_bin,""); 
	    TH1* fHistBasicMix  = (TH1*)hMixPi0A08->ProjectionX(Form("fHistBasicMix_No%d",i+1),sproj_bin,lproj_bin,""); 
	    fHistBasicSame->Rebin(rebin);
	    fHistBasicMix->Rebin(rebin);
	    fHistBasicSame->Sumw2();
	    fHistBasicMix->Sumw2();
	    fHistBasicSame->GetYaxis()->SetTitle(Form("dN/dM per %.0f MeV/c^{2}",fHistBasicSame->GetBinWidth(1)*1000));
	    fHistBasicMix->GetYaxis()->SetTitle(Form("dN/dM per %.0f MeV/c^{2}",fHistBasicSame->GetBinWidth(1)*1000));
	    fHistBasicSame->GetXaxis()->SetRange(fHistBasicSame->GetXaxis()->FindBin(0.),fHistBasicSame->GetXaxis()->FindBin(0.3)-1);
	    fHistBasicMix->GetXaxis()->SetRange(fHistBasicSame->GetXaxis()->FindBin(0.),fHistBasicSame->GetXaxis()->FindBin(0.3)-1);
	    fHistBasicSame->SetMarkerStyle(20);
	    fHistBasicMix->SetMarkerStyle(24);
	    fHistBasicSame->SetMarkerColor(kBlack);
	    fHistBasicMix->SetMarkerColor(kBlue);
	    fHistBasicSame->SetLineColor(kBlack);
	    fHistBasicMix->SetLineColor(kBlue);
	    
	    fHistFinalSame[i]     = (TH1F*)fHistBasicSame->Clone();
	    fHistOnlyFitSignal[i] = (TH1F*)fHistBasicSame->Clone();
	    fHistOnlyFitSignal[i]->SetName(Form("fHistOnlyFitSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);


	    TH1F* fHistOnlyFit_Signal = (TH1F*)fHistOnlyFitSignal[i]->Clone();
	    TH1F* fHistOnlyFit_BG     = (TH1F*)fHistOnlyFitSignal[i]->Clone();
	    
	    TH1F* fHistRatio     = (TH1F*)fHistBasicSame->Clone();
	    fHistRatio->Divide(fHistBasicMix);
	    fHistRatio->SetName(Form("cRatioSameBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    
	    TH1F* fHistRatio_Signal = (TH1F*)fHistRatio->Clone();
	    TH1F* fHistRatio_BG     = (TH1F*)fHistRatio->Clone();
	    
	    Int_t ssignal_bin = fHistRatio_Signal->GetXaxis()->FindBin(signal_range_min);
	    Int_t lsignal_bin = fHistRatio_Signal->GetXaxis()->FindBin(signal_range_max);
	    Int_t sbg_bin = fHistRatio_BG->GetXaxis()->FindBin(bg_range_min);
	    Int_t lbg_bin = fHistRatio_BG->GetXaxis()->FindBin(bg_range_max);
	    
	    for(Int_t j=ssignal_bin; j<lsignal_bin; ++j){
	      fHistRatio_BG->SetBinContent(j,0);
	      fHistRatio_BG->SetBinError(j,0);
	      fHistOnlyFit_BG->SetBinContent(j,0);
	      fHistOnlyFit_BG->SetBinError(j,0);
	    }
	    for(Int_t j=sbg_bin; j<ssignal_bin; ++j){
	      fHistRatio_Signal->SetBinContent(j,0);
	      fHistRatio_Signal->SetBinError(j,0);
	      fHistOnlyFit_Signal->SetBinContent(j,0);
	      fHistOnlyFit_Signal->SetBinError(j,0);
	    }
	    for(Int_t j=lsignal_bin; j<lbg_bin; ++j){
	      fHistRatio_Signal->SetBinContent(j,0);
	      fHistRatio_Signal->SetBinError(j,0);
	      fHistOnlyFit_Signal->SetBinContent(j,0);
	      fHistOnlyFit_Signal->SetBinError(j,0);
	    }
	    
	    ///////////////////////////////////////////////////////////////////////////////////////////////////
	    // Combinatrial background analysis
	    ///////////////////////////////////////////////////////////////////////////////////////////////////
	    
	    TF1 *fFitRatio_Signal = NULL;
	    if(iFit==0){
	      fFitRatio_Signal = new TF1("fFitRatio_Signal",
					 "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]",
					 signal_range_min,signal_range_max);
	      fFitRatio_Signal->SetParameters(1.,6.,0.135,0.005,0.01);
	      fFitRatio_Signal->FixParameter(0,1.16053);
	      fFitRatio_Signal->FixParameter(1,6.);
	      fFitRatio_Signal->SetParLimits(2,0.130,0.140);
	      fFitRatio_Signal->SetParLimits(3,0.005,0.03);
	    }
	    else if(iFit==1){//[0]=A, [1]=M_pi0, [2]=sigma, [3]=lamda
	      fFitRatio_Signal = new TF1("fFitRatio_Signal",
					 "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) )",
					 signal_range_min,signal_range_max);
	      fFitRatio_Signal->SetParameters(1,0.135,6.46624e-03,7.47626e-03);
	      fFitRatio_Signal->SetParLimits(1,0.130,0.140);
	      fFitRatio_Signal->SetParLimits(2,0.001,0.03);
	      fFitRatio_Signal->SetParLimits(3,0.001,0.03);
	    }
	    
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    fHistRatio_Signal->Fit(fFitRatio_Signal,"RNQ");
	    
	    TF1 *fFitRatio_BG = 0x0;
	    if(pol==0){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]",0,1);
	    }
	    else if(pol==1){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]+[1]*x",0,1);
	    }
	    else if(pol==2){
	      fFitRatio_BG = new TF1("fFitRatio_BG","[0]+[1]*x+[2]*x*x",0,1);
	    }
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    fHistRatio_BG->Fit(fFitRatio_BG,"RNQ","",bg_range_min,bg_range_max);
	    
	    TF1 *fFitRatio_SignalBG = 0x0;
	    TF1 *fFitScale = 0x0;
	    
	    if(iFit==0){
	      if(pol==0){
		fFitRatio_SignalBG= new TF1("fFitRatio_SignalBG",
					    "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]",0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol0",0.,1);
	      }
	      else if(pol==1){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]+[6]*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol1",0,1);
	      }
	      else if(pol==2){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])+[5]+[6]*x+[7]*x*x",0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_Signal->GetParameter(4));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(6,fFitRatio_BG->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(7,fFitRatio_BG->GetParameter(2));
		fFitScale = new TF1("fFitScale","pol2",0,1);
	      }
	      
	      fFitRatio_SignalBG->FixParameter(0,1.16053);
	      fFitRatio_SignalBG->FixParameter(1,6.);
	      fFitRatio_SignalBG->SetParLimits(2,0.130,0.140);
	      fFitRatio_SignalBG->SetParLimits(3,0.005,0.03);
	    }
	    
	    if(iFit==1){
	      if(pol==0){
		fFitRatio_SignalBG= new TF1("fFitRatio_SignalBG",
					    "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]",
					    0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitScale = new TF1("fFitScale","pol0",0,1);
	      }
	      else if(pol==1){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]+[5]*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(1));
		fFitScale = new TF1("fFitScale","pol1",0,1);
	      }
	      else if(pol==2){
		fFitRatio_SignalBG = new TF1("fFitRatio_SignalBG",
					     "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) ) + [4]+[5]*x+[6]*x*x",
					     0,1);
		fFitRatio_SignalBG->SetParameter(0,fFitRatio_Signal->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(1,fFitRatio_Signal->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(2,fFitRatio_Signal->GetParameter(2));
		fFitRatio_SignalBG->SetParameter(3,fFitRatio_Signal->GetParameter(3));
		fFitRatio_SignalBG->SetParameter(4,fFitRatio_BG->GetParameter(0));
		fFitRatio_SignalBG->SetParameter(5,fFitRatio_BG->GetParameter(1));
		fFitRatio_SignalBG->SetParameter(6,fFitRatio_BG->GetParameter(2));
		fFitScale = new TF1("fFitScale","pol2",0,1);
	      }
	      fFitRatio_SignalBG->SetParLimits(1,0.130,0.140);
	      fFitRatio_SignalBG->SetParLimits(2,0.005,0.03);
	      fFitRatio_SignalBG->SetParLimits(3,0.005,0.03);
	    }

	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    fHistRatio->Fit(fFitRatio_SignalBG,"NRQ","",bg_range_min,bg_range_max);
	    
	    fHistFinalRatio[i] = (TH1F*)fHistRatio->Clone();;
	    fFitFinalRatio[i]  = (TF1*)fFitRatio_SignalBG->Clone();
	    
	    if(iFit==0){
	      if(pol==0){
		fFitScale->SetParameter(0,fFitRatio_SignalBG->GetParameter(5));
	      }
	      else if(pol==1){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6));
	      }
	      else if(pol==2){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6),fFitRatio_SignalBG->GetParameter(7));
	      }
	    }	
	    if(iFit==1){
	      if(pol==0){
		fFitScale->SetParameter(0,fFitRatio_SignalBG->GetParameter(4));
	      }
	      else if(pol==1){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(4),fFitRatio_SignalBG->GetParameter(5));
	      }
	      else if(pol==2){
		fFitScale->SetParameters(fFitRatio_SignalBG->GetParameter(4),fFitRatio_SignalBG->GetParameter(5),fFitRatio_SignalBG->GetParameter(6));
	      }
	    }	
	    
	    c3 = new TCanvas("c3","c3",600,600);
	    c3->cd();
	    fHistRatio->Draw();
	    fFitRatio_SignalBG->Draw("same");
	    fFitScale->Draw("same");
	    c3->SetName(Form("cRatioSameBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    tfout->WriteTObject(c3);

	    TH1F* fHistScaledMix = (TH1F*)fHistBasicMix->Clone();
	    fHistScaledMix->Multiply(fFitScale);
	    fHistFinalBG[i] = (TH1F*)fHistScaledMix->Clone();;
	    
	    TH1F* fHistSignal = (TH1F*)fHistBasicSame->Clone();
	    fHistSignal->SetName(Form("fHistSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistScaledMix->SetName(Form("fHistScaledMix_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    tfout->WriteTObject(fHistSignal);
	    tfout->WriteTObject(fHistScaledMix);
	    
	    for(Int_t j=0; j<fHistBasicSame->GetXaxis()->FindBin(0.3); ++j){
	      Double_t same   = fHistSignal->GetBinContent(j);
	      Double_t e_same = fHistSignal->GetBinError(j);
	      Double_t mix    = fHistScaledMix->GetBinContent(j);
	      Double_t e_mix  = fHistScaledMix->GetBinError(j);
	      
	      Double_t signal   = same - mix;
	      Double_t e_signal = sqrt(pow(e_same,2)+pow(e_mix,2));
	      
	      if(same>0){
		signal   = same - mix;
		e_signal = sqrt(pow(e_same,2)+pow(e_mix,2));
	      }
	      else{
		signal   = same;
		e_signal = e_same;
	      }
	      
	      fHistSignal->SetBinContent(j,signal);
	      fHistSignal->SetBinError(j,e_signal);
	    }
	    
	    fHistFinalSignal[i] = (TH1F*)fHistSignal->Clone();
	    fHistFinalSignal[i]->SetTitle(Form("%.2f < #it{p}_{T} %.2f (GeV/c)", bins[i], bins[i+1]));

	    TF1 *fFitSignal = NULL;
	    
	    if(iFit==0){
	      fFitSignal = new TF1("fFitSignal", "[4]*((x-[2])/[3] > -[0] ? 1.0:0.0 )*exp(-pow(x-[2],2)/(2*pow([3],2))) + ((x-[2])/[3] <= -[0] ? 1.0:0.0 )*[4]*pow([1]/[0],[1])*exp(-[0]*[0]/2) * pow([1]/[0]-[0]-(x-[2])/[3],-[1])",
				   0,0.3);
	      fFitSignal->SetParameters(1.,6.,0.135,0.005,0.01);

	      fFitSignal->FixParameter(0,1.16053);
	      fFitSignal->FixParameter(1,6.);

	      fFitSignal->SetParLimits(2,0.120,0.140);
	      fFitSignal->SetParLimits(3,0.005,0.03);
	    
	    }	
	    else if(iFit==1){
	      fFitSignal = new TF1("fFitSignal",
				   "[0] *( ([1]>x ? 1.0:0.0 ) * (1 - exp(-0.5*pow((x-[1])/[2],2))) * exp((x-[1])/[3]) + exp(-0.5*pow((x-[1])/[2],2)) )",
				   0,0.3);
	      fFitSignal->SetParameters(1,0.135,6.46624e-03,7.47626e-03);
	      fFitSignal->SetParLimits(1,0.125,0.140);
	      fFitSignal->SetParLimits(2,0.001,0.01);
	      fFitSignal->SetParLimits(3,0.001,0.01);
	    }
	    
	    fHistSignal->Fit(fFitSignal,"RNQ","",signal_range_min,signal_range_max);
	    fHistSignal->Fit(fFitSignal,"RNQ","",0.12,signal_range_max);
	    
	    
	    if(iFit==0){
	      fHistSignal->Fit(fFitSignal,"RNQ","",0.12,0.150);
	    }	
	    else{
	      fHistSignal->Fit(fFitSignal,"RNQ","",0.12,0.150);
	    }

	    fFitFinalSignal[i]  = (TF1*)fFitSignal->Clone();
	    
	    Double_t mean   = 0;
	    Double_t e_mean = 0;
	    Double_t signal_sigma   = 0;
	    Double_t e_signal_sigma = 0;
	    Double_t signal_window_min = 0;
	    Double_t signal_window_max = 0;
	    
	    if(iFit==0){
	      mean   = fFitSignal->GetParameter(2);
	      e_mean = fFitSignal->GetParError(2);
	      signal_sigma   = fabs(fFitSignal->GetParameter(3));
	      e_signal_sigma = fabs(fFitSignal->GetParError(3));
	      
	      signal_window_min = mean - signal_sigma*5;
	      signal_window_max = mean + signal_sigma*3;
	      
	    }
	    else if(iFit==1){
	      mean   = fFitSignal->GetParameter(1);
	      e_mean = fFitSignal->GetParError(1);
	      signal_sigma   = fabs(fFitSignal->GetParameter(2));
	      e_signal_sigma = fabs(fFitSignal->GetParError(2));
	      signal_window_min = mean - signal_sigma*5;
	      signal_window_max = mean + signal_sigma*3;
	    }
	  
	    fHistPeakMean->SetBinContent(i+1,mean);
	    fHistPeakMean->SetBinError(i+1,e_mean);
	    fHistPeakWidth->SetBinContent(i+1,signal_sigma);
	    fHistPeakWidth->SetBinError(i+1,e_signal_sigma);
	    
	    Int_t signal_window_bin_min = fHistSignal->GetXaxis()->FindBin(signal_window_min);
	    Int_t signal_window_bin_max = fHistSignal->GetXaxis()->FindBin(signal_window_max);
	    
	    Double_t num_pi0 = 0;
	    Double_t e_num_pi0 = 0;
	    
	    for(Int_t j=signal_window_bin_min; j<signal_window_bin_max; ++j){
	      num_pi0   += fHistSignal->GetBinContent(j);
	      e_num_pi0 += pow(fHistSignal->GetBinError(j),2);
	    }
	    e_num_pi0 = sqrt(e_num_pi0);
	    
	    fHistRawYield->SetBinContent(i+1,num_pi0/bin_width);
	    fHistRawYield->SetBinError(i+1,e_num_pi0/bin_width);
	    
	  }

	  fHistRawYield->SetName(Form("fHistRawYieldPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistRawYield);
	  
	  fHistRawYieldPerEvent = (TH1F*)fHistRawYield->Clone();
	  fHistRawYieldPerEvent->Scale(1./nEvt);
	  fHistRawYieldPerEvent->SetName(Form("fHistRawYieldPerEventPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistRawYieldPerEvent);
	  
	  fHistPeakMean->SetName(Form("fHistPeakMeanPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  fHistPeakWidth->SetName(Form("fHistPeakWidthPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	  tfout->WriteTObject(fHistPeakMean);
	  tfout->WriteTObject(fHistPeakWidth);
	  
	  c1[itof] = new TCanvas("c1"+fitName[iFit]+tofName[itof],"",1200,1800);
	  c2[itof] = new TCanvas("c2"+fitName[iFit]+tofName[itof],"",1200,1800);
	  
	  c1[itof]->Divide(4,6);
	  for(Int_t i=0; i<binnum; ++i){
	    c1[itof]->cd(i+1);
	    fHistFinalSignal[i]->Draw();
	    fFitFinalSignal[i]->Draw("same");
	  }
	  
	  c1[itof]->SaveAs(Form("cInvariantMassSpectrumPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]+".eps");
	  
	  c2[itof]->Divide(4,6);
	  for(Int_t i=0; i<binnum; ++i){
	    c2[itof]->cd(i+1);
	    fHistFinalSame[i]->Draw();
	    fHistFinalBG[i]->Draw("same");
	  }
	  c2[itof]->SaveAs(Form("cSameScaledMixPol%d",pol)+fitName[iFit]+tofName[itof]+modName[iMod]+".eps");
	  
	  for(Int_t i=0; i<binnum; ++i){
	    
	    fHistFinalSignal[i]->SetName(Form("fHistFinalSignal_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fFitFinalSignal[i]->SetName(Form("fFitFinalSignal_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistFinalSame[i]->SetName(Form("fHistFinalSame_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    fHistFinalBG[i]->SetName(Form("fHistFinalBG_No%d_Pol%d",i+1,iPol)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    
	    tfout->WriteTObject(fHistFinalSignal[i]);
	    tfout->WriteTObject(fFitFinalSignal[i]);
	    tfout->WriteTObject(fHistFinalSame[i]);
	    tfout->WriteTObject(fHistFinalBG[i]);
	    
	    c3 = new TCanvas("c3","",600,600);
	    c3->cd(1);
	    fHistFinalSame[i]->Draw();
	    fHistFinalBG[i]->Draw("same");
	    c3->SetName(Form("cRawSignalBG_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    //tfout->WriteTObject(c3);
	  }
	  for(Int_t i=0; i<binnum; ++i){
	    c3 = new TCanvas("c3","",600,600);
	    c3->cd(1);
	    fHistFinalSignal[i]->Draw("");
	    fFitFinalSignal[i]->Draw("same");
	    c3->SetName(Form("cRawSignal_Pol%d_No%d",pol,i+1)+fitName[iFit]+tofName[itof]+modName[iMod]);
	    //tfout->WriteTObject(c3);
	  }
	  
	}	
      }
    }
  }  
  
}
Пример #17
0
// 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++;
         }
      }
   }
}
Пример #18
0
Bool_t fitsHere(TLegend *l,Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
    Bool_t fits = true;
    TList *list = l->GetListOfPrimitives();
    for (Int_t k = 0; list->At(k) != 0 && fits; k++)
    {
        TObject *obj = ((TLegendEntry*)(list->At(k)))->GetObject();
        if (obj == 0) continue;
        TClass *cl = obj->IsA();

        //Histogram, drawn as a histogram
        if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
         && cl != TProfile::Class() && ((TH1*)obj)->GetMarkerColor() == kWhite)
        {
            Int_t where = 0;
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i) < x1) continue;   //to the left of the legend
                if (h->GetBinLowEdge(i)                     > x2) continue;   //to the right of the legend
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;   //inside the legend
                if (h->GetBinContent(i) < y1)
                {
                    if (where == 0) where = -1;             //below the legend
                    if (where == 1) fits = false;           //a previous bin was above it so there's a vertical line through it
                }
                if (h->GetBinContent(i) > y2)
                {
                    if (where == 0) where = 1;              //above the legend
                    if (where == -1) fits = false;          //a previous bin was below it so there's a vertical line through it
                }
            }
            continue;
        }
        //Histogram, drawn with Draw("P")
        else if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
              && cl != TProfile::Class())
        //Probably TProfile would be the same but I haven't tested it
        {
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i)/2 < x1) continue;
                if (h->GetBinLowEdge(i)                       > x2) continue;
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y2 && h->GetBinContent(i) - h->GetBinError(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y1 && h->GetBinContent(i) - h->GetBinError(i) < y1) fits = false;
            }
        }
        else if (cl->InheritsFrom("TF1") && !cl->InheritsFrom("TF2"))
        {
            //TF1 *f = (TF1*)obj;
            //Double_t max = f->GetMaximum(x1,x2);
            //Double_t min = f->GetMinimum(x1,x2);
            //if (min < y2 && max > y1) fits = false;
        }
        // else if (cl->InheritsFrom(...... add more objects here
        else
        {
            cout << "Don't know how to place the legend around objects of type " << obj->ClassName() << "." << endl
                 << "Add this class into placeLegend.C if you want it to work properly." << endl
                 << "The legend will still be placed around any other objects." << endl;
        }
    }
    return fits;
}