Пример #1
0
void gen1(const char* output, const char* suffix) {
  // S e t u p   m o d e l 
  // ---------------------

   gRandom = new TRandom();
   gRandom->SetSeed(0);
   RooWorkspace *ws = new RooWorkspace("workspace");
  // Declare variables x,mean,sigma with associated name, title, initial value and allowed range
  ws->factory("invMass[2,5]");
  RooRealVar *invMass = ws->var("invMass");
  RooRealVar *weight = new RooRealVar("weight","weight",1,0,1e6);
  ws->factory(Form("Gaussian::siga_nonorm_%s(invMass,m_%s[3,2.5,3.5],sigmaa_%s[0.02,0.,0.5])",suffix,suffix,suffix));
  ws->factory(Form("Gaussian::sigb_nonorm_%s(invMass,m_%s,sigmab_%s[0.1,0.,0.5])",suffix,suffix,suffix));
  ws->factory(Form("SUM::sig_nonorm_%s(f_%s[0.8,0,1]*siga_nonorm_%s,sigb_nonorm_%s)",suffix,suffix,suffix,suffix));
  ws->factory(Form("RooExtendPdf::sig_%s(sig_nonorm_%s,Nsig_%s[1e4,-1e5,1e5])",suffix,suffix,suffix));
  ws->factory(Form("Gaussian::sig2_nonorm_%s(invMass,m2_%s[3.5,3.,4.],sigma2_%s[0.1,0.,0.5])",suffix,suffix,suffix));
  ws->factory(Form("RooFormulaVar::Nsig2_%s('@0*@1',{Nsig_%s,frac_%s[0.5,-10,10]})",suffix,suffix,suffix));
  ws->factory(Form("RooExtendPdf::sig2_%s(sig2_nonorm_%s,Nsig2_%s)",suffix,suffix,suffix));
  ws->factory(Form("Chebychev::bkg_nonorm_%s(invMass,{lambda0_%s[0.1,-1.5,1.5],lambda1_%s[0.1,-1.5,1.5]})",suffix,suffix,suffix));
  ws->factory(Form("RooExtendPdf::bkg_%s(bkg_nonorm_%s,Nbkg_%s[1e4,-1e5,1e5])",suffix,suffix,suffix));
  // ws->factory(Form("SUM::tot_%s( sig_%s,  bkg_%s)",suffix,suffix,suffix));
  // RooAbsPdf *thepdf = ws->pdf(Form("tot_%s",suffix));
  RooAbsPdf *thepdf = new RooAddPdf(Form("tot_%s",suffix), Form("tot_%s",suffix), 
        RooArgList(*ws->pdf(Form("sig_%s",suffix)), *ws->pdf(Form("sig2_%s",suffix)), *ws->pdf(Form("bkg_%s",suffix))));
  ws->import(*thepdf);

  // G e n e r a t e   e v e n t s 
  // -----------------------------

  // Generate a dataset of 1000 events in x from gauss
  RooDataSet* data = thepdf->generate(*invMass,2e4,Name(Form("data_%s",suffix))) ;  
  ws->import(*data);

  ws->writeToFile(output);
}
Пример #2
0
//____________________________________
void AddData(RooWorkspace* wks){
  // Add a toy dataset

  Int_t nEvents = 150;
  RooAbsPdf* model = wks->pdf("model");
  RooRealVar* invMass = wks->var("invMass");

  RooDataSet* data = model->generate(*invMass,nEvents);

  wks->import(*data, Rename("data"));

}
Пример #3
0
MakeBiasStudy::MakeBiasStudy() {
  int Nmodels = 8;
  //RooRealVar* mass = ws->var("mass");
  RooRealVar *mass = new RooRealVar("mass","mass", 100,180);
  RooRealVar *nBkgTruth = new RooRealVar("TruthNBkg","", 0,1e9);
  //  RooAbsData* realData = ws->data("Data_Combined")->reduce( Form("evtcat==evtcat::%s",cat.Data()) );

  double Bias[Nmodels][Nmodels];
  double BiasE[Nmodels][Nmodels];
  MakeAICFits MakeAIC_Fits;
  for(int truthType = 0; truthType < Nmodels; truthType++){

    RooAbsPdf *truthPdf = MakeAIC_Fits.getBackgroundPdf(truthType,mass);
    RooExtendPdf *truthExtendedPdf = new RooExtendPdf("truthExtendedPdf","",*truthPdf,*nBkgTruth);
    //truthExtendedPdf.fitTo(*realData,RooFit::Strategy(0),RooFit::NumCPU(NUM_CPU),RooFit::Minos(kFALSE),RooFit::Extended(kTRUE));
    //truthExtendedPdf.fitTo(*realData,RooFit::Strategy(2),RooFit::NumCPU(NUM_CPU),RooFit::Minos(kFALSE),RooFit::Extended(kTRUE));
    
    double BiasWindow = 2.00;
    mass->setRange("biasRegion", mh-BiasWindow, mh+BiasWindow);
    double TruthFrac = truthExtendedPdf->createIntegral(mass,RooFit::Range("biasRegion"),RooFit::NormSet(*mass))->getVal();
    double NTruth = TruthFrac * nBkgTruth->getVal();
    double NTruthE = TruthFrac * nBkgTruth->getError();
    
    RooDataSet* truthbkg = truthPdf->generate(RooArgSet(*mass),nBkgTruth);

    for(int modelType = 0; modelType < Nmodels; modelType++){
      RooAbsPdf* ModelShape = MakeAIC_Fits.getBackgroundPdf(modelType,mass);
      RooRealVar *nBkgFit = new RooRealVar("FitNBkg", "", 0, 1e9);
      RooExtendPdf ModelExtendedPdf = new RooExtendPdf("ModelExtendedPdf", "",*ModelShape, *nBkgFit);
      ModelExtendedPdf.fitTo(truthbkg, RooFit::Strategy(0),RooFit::NumCPU(NUM_CPU),RooFit::Minos(kFALSE),RooFit::Extended(kTRUE));
      ModelExtendedPdf.fitTo(truthbkg, RooFit::Strategy(2),RooFit::NumCPU(NUM_CPU),RooFit::Minos(kFALSE),RooFit::Extended(kTRUE));

      double FitFrac = ModelExtendedPdf.createIntegral(mass,RooFit::Range("biasRegion"),RooFit::NormSet(mass))->getVal();
      double NFit = FitFrac * nBkgFit->getVal();
      double NFitE = FitFrac * nBkgFit->getError();

      Bias[truthType][modelType] = fabs(NFit - NTruth);
      BiasE[truthType][modelType] = fabs(NFitE - NTruthE);
    }

    
  }
  
  for(int i = 0; i < Nmodels; i++) { 
    std::cout <<  "===== Truth Model : " << MakeBiasStudy::Category(i) << " ===== " << std::endl; 
    for (int j = 0; j < Nmodels; j++) { 
      std::cout << "Fit Model: " << MakeBiasStudy::Category(j) << "  , Bias = " << Bias[i][j] << " +/- " << BiasE[i][j] << std::endl; 
    }   
  }
  

}
Пример #4
0
   RooDataSet*GenericPDFModel::GenerateDataSet(RooAbsPdf& parDist, const RooArgList* params)
   {
      // Generate dataset for the observables using the given parameter probability distribution
      // If optional parameter list params is given, it is used instead of the default
      // defined parameter list of the model

      Info("GenerateDataSet","Generating %d datapoints with parameter distribution %s",
           GetNumGen(), parDist.GetName());
      RooProdPdf Multimodel("Multimodel","observables for parameter distributions", parDist,
                            Conditional(*theModel,GetObservables()));
      // get marginalized distributions model for observables
      if(!params) params = &GetParameters();
      RooAbsPdf* margin = Multimodel.createProjection(*params);
      RooDataSet* data = margin->generate(GetObservables(),fNGen);
      delete margin;
      return data;
   }
Пример #5
0
//____________________________________
void AddData(RooWorkspace* ws){
  // Add a toy dataset

  // how many events do we want?
  Int_t nEvents = 1000;

  // get what we need out of the workspace to make toy data
  RooAbsPdf* model = ws->pdf("model");
  RooRealVar* invMass = ws->var("invMass");
  RooRealVar* isolation = ws->var("isolation");
 
  // make the toy data
  std::cout << "make data set and import to workspace" << std::endl;
  RooDataSet* data = model->generate(RooArgSet(*invMass, *isolation),nEvents);
  
  // import data into workspace
  ws->import(*data, Rename("data"));

}
Пример #6
0
void rf510_wsnamedsets()
{
  // C r e a t e   m o d e l   a n d   d a t a s e t
  // -----------------------------------------------

  RooWorkspace* w = new RooWorkspace("w") ;
  fillWorkspace(*w) ;

  // Exploit convention encoded in named set "parameters" and "observables"
  // to use workspace contents w/o need for introspected
  RooAbsPdf* model = w->pdf("model") ;

  // Generate data from p.d.f. in given observables
  RooDataSet* data = model->generate(*w->set("observables"),1000) ;

  // Fit model to data
  model->fitTo(*data) ;
  
  // Plot fitted model and data on frame of first (only) observable
  RooPlot* frame = ((RooRealVar*)w->set("observables")->first())->frame() ;
  data->plotOn(frame) ;
  model->plotOn(frame) ;

  // Overlay plot with model with reference parameters as stored in snapshots
  w->loadSnapshot("reference_fit") ;
  model->plotOn(frame,LineColor(kRed)) ;
  w->loadSnapshot("reference_fit_bkgonly") ;
  model->plotOn(frame,LineColor(kRed),LineStyle(kDashed)) ;


  // Draw the frame on the canvas
  new TCanvas("rf510_wsnamedsets","rf503_wsnamedsets",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


  // Print workspace contents
  w->Print() ;


  // Workspace will remain in memory after macro finishes
  gDirectory->Add(w) ;

}
Пример #7
0
void rf105_funcbinding()
{

   // B i n d   T M a t h : : E r f   C   f u n c t i o n
   // ---------------------------------------------------

   // Bind one-dimensional TMath::Erf function as RooAbsReal function
   RooRealVar x("x","x",-3,3) ;
   RooAbsReal* errorFunc = bindFunction("erf",TMath::Erf,x) ;

   // Print erf definition
   errorFunc->Print() ;

   // Plot erf on frame 
   RooPlot* frame1 = x.frame(Title("TMath::Erf bound as RooFit function")) ;
   errorFunc->plotOn(frame1) ;


   // B i n d   R O O T : : M a t h : : b e t a _ p d f   C   f u n c t i o n
   // -----------------------------------------------------------------------

   // Bind pdf ROOT::Math::Beta with three variables as RooAbsPdf function
   RooRealVar x2("x2","x2",0,0.999) ;
   RooRealVar a("a","a",5,0,10) ;
   RooRealVar b("b","b",2,0,10) ;
   RooAbsPdf* beta = bindPdf("beta",ROOT::Math::beta_pdf,x2,a,b) ;

   // Perf beta definition
   beta->Print() ;

   // Generate some events and fit
   RooDataSet* data = beta->generate(x2,10000) ;
   beta->fitTo(*data) ;

   // Plot data and pdf on frame
   RooPlot* frame2 = x2.frame(Title("ROOT::Math::Beta bound as RooFit pdf")) ;
   data->plotOn(frame2) ;
   beta->plotOn(frame2) ;



   // B i n d   R O O T   T F 1   a s   R o o F i t   f u n c t i o n
   // ---------------------------------------------------------------

   // Create a ROOT TF1 function
   TF1 *fa1 = new TF1("fa1","sin(x)/x",0,10);

   // Create an observable 
   RooRealVar x3("x3","x3",0.01,20) ;

   // Create binding of TF1 object to above observable
   RooAbsReal* rfa1 = bindFunction(fa1,x3) ;

   // Print rfa1 definition
   rfa1->Print() ;

   // Make plot frame in observable, plot TF1 binding function
   RooPlot* frame3 = x3.frame(Title("TF1 bound as RooFit function")) ;
   rfa1->plotOn(frame3) ;



   TCanvas* c = new TCanvas("rf105_funcbinding","rf105_funcbinding",1200,400) ;
   c->Divide(3) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;

}
Пример #8
0
exampleScript()
{
  gSystem->CompileMacro("betaHelperFunctions.h"      ,"kO") ;
  gSystem->CompileMacro("RooNormalFromFlatPdf.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaInverseCDF.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaPrimeInverseCDF.cxx" ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaPrimeGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("rooFitBetaHelperFunctions.h","kO") ;

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

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

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

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

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

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

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

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

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

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

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

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

  RooRealVar* correlatedParameter = workspace.var(correlatedName);

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

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

  data->addColumn(*normalFromFlat);

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

  data->Print("v");

  workspace.Print() ;

  //Setup Plotting Kluges:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  observableSet->Print();

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

  correlatedParameter->setVal(0.25);

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

  correlatedParameter->setVal(0.75);

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

  //Testing for extreme values!

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


}
void OneSidedFrequentistUpperLimitWithBands(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData") {



   double confidenceLevel=0.95;
   int nPointsToScan = 20;
   int nToyMC = 200;

   // -------------------------------------------------------
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }


   // -------------------------------------------------------
   // Now get the data and workspace

   // get the workspace out of the file
   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
   if(!w){
      cout <<"workspace not found" << endl;
      return;
   }

   // get the modelConfig out of the file
   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

   // get the modelConfig out of the file
   RooAbsData* data = w->data(dataName);

   // make sure ingredients are found
   if(!data || !mc){
      w->Print();
      cout << "data or ModelConfig was not found" <<endl;
      return;
   }

   // -------------------------------------------------------
   // Now get the POI for convenience
   // you may want to adjust the range of your POI

   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
   /*  firstPOI->setMin(0);*/
   /*  firstPOI->setMax(10);*/

   // --------------------------------------------
   // Create and use the FeldmanCousins tool
   // to find and plot the 95% confidence interval
   // on the parameter of interest as specified
   // in the model config
   // REMEMBER, we will change the test statistic
   // so this is NOT a Feldman-Cousins interval
   FeldmanCousins fc(*data,*mc);
   fc.SetConfidenceLevel(confidenceLevel);
   /*  fc.AdditionalNToysFactor(0.25); // degrade/improve sampling that defines confidence belt*/
   /*  fc.UseAdaptiveSampling(true); // speed it up a bit, don't use for expected limits*/
   fc.SetNBins(nPointsToScan); // set how many points per parameter of interest to scan
   fc.CreateConfBelt(true); // save the information in the belt for plotting

   // -------------------------------------------------------
   // Feldman-Cousins is a unified limit by definition
   // but the tool takes care of a few things for us like which values
   // of the nuisance parameters should be used to generate toys.
   // so let's just change the test statistic and realize this is
   // no longer "Feldman-Cousins" but is a fully frequentist Neyman-Construction.
   /*  ProfileLikelihoodTestStatModified onesided(*mc->GetPdf());*/
   /*  fc.GetTestStatSampler()->SetTestStatistic(&onesided);*/
   /* ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true); */
   ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());
   testStat->SetOneSided(true);

   // Since this tool needs to throw toy MC the PDF needs to be
   // extended or the tool needs to know how many entries in a dataset
   // per pseudo experiment.
   // In the 'number counting form' where the entries in the dataset
   // are counts, and not values of discriminating variables, the
   // datasets typically only have one entry and the PDF is not
   // extended.
   if(!mc->GetPdf()->canBeExtended()){
      if(data->numEntries()==1)
         fc.FluctuateNumDataEntries(false);
      else
         cout <<"Not sure what to do about this model" <<endl;
   }

   // We can use PROOF to speed things along in parallel
   // However, the test statistic has to be installed on the workers
   // so either turn off PROOF or include the modified test statistic
   // in your `$ROOTSYS/roofit/roostats/inc` directory,
   // add the additional line to the LinkDef.h file,
   // and recompile root.
   if (useProof) {
      ProofConfig pc(*w, nworkers, "", false);
      toymcsampler->SetProofConfig(&pc); // enable proof
   }

   if(mc->GetGlobalObservables()){
      cout << "will use global observables for unconditional ensemble"<<endl;
      mc->GetGlobalObservables()->Print();
      toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
   }


   // Now get the interval
   PointSetInterval* interval = fc.GetInterval();
   ConfidenceBelt* belt = fc.GetConfidenceBelt();

   // print out the interval on the first Parameter of Interest
   cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
      interval->LowerLimit(*firstPOI) << ", "<<
      interval->UpperLimit(*firstPOI) <<"] "<<endl;

   // get observed UL and value of test statistic evaluated there
   RooArgSet tmpPOI(*firstPOI);
   double observedUL = interval->UpperLimit(*firstPOI);
   firstPOI->setVal(observedUL);
   double obsTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*data,tmpPOI);


   // Ask the calculator which points were scanned
   RooDataSet* parameterScan = (RooDataSet*) fc.GetPointsToScan();
   RooArgSet* tmpPoint;

   // make a histogram of parameter vs. threshold
   TH1F* histOfThresholds = new TH1F("histOfThresholds","",
                                       parameterScan->numEntries(),
                                       firstPOI->getMin(),
                                       firstPOI->getMax());
   histOfThresholds->GetXaxis()->SetTitle(firstPOI->GetName());
   histOfThresholds->GetYaxis()->SetTitle("Threshold");

   // loop through the points that were tested and ask confidence belt
   // what the upper/lower thresholds were.
   // For FeldmanCousins, the lower cut off is always 0
   for(Int_t i=0; i<parameterScan->numEntries(); ++i){
      tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
      //cout <<"get threshold"<<endl;
      double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
      double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
      histOfThresholds->Fill(poiVal,arMax);
   }
   TCanvas* c1 = new TCanvas();
   c1->Divide(2);
   c1->cd(1);
   histOfThresholds->SetMinimum(0);
   histOfThresholds->Draw();
   c1->cd(2);

   // -------------------------------------------------------
   // Now we generate the expected bands and power-constraint

   // First: find parameter point for mu=0, with conditional MLEs for nuisance parameters
   RooAbsReal* nll = mc->GetPdf()->createNLL(*data);
   RooAbsReal* profile = nll->createProfile(*mc->GetParametersOfInterest());
   firstPOI->setVal(0.);
   profile->getVal(); // this will do fit and set nuisance parameters to profiled values
   RooArgSet* poiAndNuisance = new RooArgSet();
   if(mc->GetNuisanceParameters())
      poiAndNuisance->add(*mc->GetNuisanceParameters());
   poiAndNuisance->add(*mc->GetParametersOfInterest());
   w->saveSnapshot("paramsToGenerateData",*poiAndNuisance);
   RooArgSet* paramsToGenerateData = (RooArgSet*) poiAndNuisance->snapshot();
   cout << "\nWill use these parameter points to generate pseudo data for bkg only" << endl;
   paramsToGenerateData->Print("v");


   RooArgSet unconditionalObs;
   unconditionalObs.add(*mc->GetObservables());
   unconditionalObs.add(*mc->GetGlobalObservables()); // comment this out for the original conditional ensemble

   double CLb=0;
   double CLbinclusive=0;

   // Now we generate background only and find distribution of upper limits
   TH1F* histOfUL = new TH1F("histOfUL","",100,0,firstPOI->getMax());
   histOfUL->GetXaxis()->SetTitle("Upper Limit (background only)");
   histOfUL->GetYaxis()->SetTitle("Entries");
   for(int imc=0; imc<nToyMC; ++imc){

      // set parameters back to values for generating pseudo data
      //    cout << "\n get current nuis, set vals, print again" << endl;
      w->loadSnapshot("paramsToGenerateData");
      //    poiAndNuisance->Print("v");

      RooDataSet* toyData = 0;
      // now generate a toy dataset
      if(!mc->GetPdf()->canBeExtended()){
         if(data->numEntries()==1)
            toyData = mc->GetPdf()->generate(*mc->GetObservables(),1);
         else
            cout <<"Not sure what to do about this model" <<endl;
      } else{
         //      cout << "generating extended dataset"<<endl;
         toyData = mc->GetPdf()->generate(*mc->GetObservables(),Extended());
      }

      // generate global observables
      // need to be careful for simpdf
      //    RooDataSet* globalData = mc->GetPdf()->generate(*mc->GetGlobalObservables(),1);

      RooSimultaneous* simPdf = dynamic_cast<RooSimultaneous*>(mc->GetPdf());
      if(!simPdf){
         RooDataSet *one = mc->GetPdf()->generate(*mc->GetGlobalObservables(), 1);
         const RooArgSet *values = one->get();
         RooArgSet *allVars = mc->GetPdf()->getVariables();
         *allVars = *values;
         delete allVars;
         delete values;
         delete one;
      } else {

         //try fix for sim pdf
         TIterator* iter = simPdf->indexCat().typeIterator() ;
         RooCatType* tt = NULL;
         while((tt=(RooCatType*) iter->Next())) {

            // Get pdf associated with state from simpdf
            RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

            // Generate only global variables defined by the pdf associated with this state
            RooArgSet* globtmp = pdftmp->getObservables(*mc->GetGlobalObservables()) ;
            RooDataSet* tmp = pdftmp->generate(*globtmp,1) ;

            // Transfer values to output placeholder
            *globtmp = *tmp->get(0) ;

            // Cleanup
            delete globtmp ;
            delete tmp ;
         }
      }

      //    globalData->Print("v");
      //    unconditionalObs = *globalData->get();
      //    mc->GetGlobalObservables()->Print("v");
      //    delete globalData;
      //    cout << "toy data = " << endl;
      //    toyData->get()->Print("v");

      // get test stat at observed UL in observed data
      firstPOI->setVal(observedUL);
      double toyTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);
      //    toyData->get()->Print("v");
      //    cout <<"obsTSatObsUL " <<obsTSatObsUL << "toyTS " << toyTSatObsUL << endl;
      if(obsTSatObsUL < toyTSatObsUL) // not sure about <= part yet
         CLb+= (1.)/nToyMC;
      if(obsTSatObsUL <= toyTSatObsUL) // not sure about <= part yet
         CLbinclusive+= (1.)/nToyMC;


      // loop over points in belt to find upper limit for this toy data
      double thisUL = 0;
      for(Int_t i=0; i<parameterScan->numEntries(); ++i){
         tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
         double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
         firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
         //   double thisTS = profile->getVal();
         double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

         //   cout << "poi = " << firstPOI->getVal()
         // << " max is " << arMax << " this profile = " << thisTS << endl;
         //      cout << "thisTS = " << thisTS<<endl;
         if(thisTS<=arMax){
            thisUL = firstPOI->getVal();
         } else{
            break;
         }
      }



      /*
      // loop over points in belt to find upper limit for this toy data
      double thisUL = 0;
      for(Int_t i=0; i<histOfThresholds->GetNbinsX(); ++i){
         tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
         cout <<"----------------  "<<i<<endl;
         tmpPoint->Print("v");
         cout << "from hist " << histOfThresholds->GetBinCenter(i+1) <<endl;
         double arMax = histOfThresholds->GetBinContent(i+1);
         // cout << " threhold from Hist = aMax " << arMax<<endl;
         // double arMax2 = belt->GetAcceptanceRegionMax(*tmpPoint);
         // cout << "from scan arMax2 = "<< arMax2 << endl; // not the same due to TH1F not TH1D
         // cout << "scan - hist" << arMax2-arMax << endl;
         firstPOI->setVal( histOfThresholds->GetBinCenter(i+1));
         //   double thisTS = profile->getVal();
         double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

         //   cout << "poi = " << firstPOI->getVal()
         // << " max is " << arMax << " this profile = " << thisTS << endl;
         //      cout << "thisTS = " << thisTS<<endl;

         // NOTE: need to add a small epsilon term for single precision vs. double precision
         if(thisTS<=arMax + 1e-7){
            thisUL = firstPOI->getVal();
         } else{
            break;
         }
      }
      */

      histOfUL->Fill(thisUL);

      // for few events, data is often the same, and UL is often the same
      //    cout << "thisUL = " << thisUL<<endl;

      delete toyData;
   }
   histOfUL->Draw();
   c1->SaveAs("one-sided_upper_limit_output.pdf");

   // if you want to see a plot of the sampling distribution for a particular scan point:
   /*
   SamplingDistPlot sampPlot;
   int indexInScan = 0;
   tmpPoint = (RooArgSet*) parameterScan->get(indexInScan)->clone("temp");
   firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
   toymcsampler->SetParametersForTestStat(tmpPOI);
   SamplingDistribution* samp = toymcsampler->GetSamplingDistribution(*tmpPoint);
   sampPlot.AddSamplingDistribution(samp);
   sampPlot.Draw();
      */

   // Now find bands and power constraint
   Double_t* bins = histOfUL->GetIntegral();
   TH1F* cumulative = (TH1F*) histOfUL->Clone("cumulative");
   cumulative->SetContent(bins);
   double band2sigDown, band1sigDown, bandMedian, band1sigUp,band2sigUp;
   for(int i=1; i<=cumulative->GetNbinsX(); ++i){
      if(bins[i]<RooStats::SignificanceToPValue(2))
         band2sigDown=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(1))
         band1sigDown=cumulative->GetBinCenter(i);
      if(bins[i]<0.5)
         bandMedian=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(-1))
         band1sigUp=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(-2))
         band2sigUp=cumulative->GetBinCenter(i);
   }
   cout << "-2 sigma  band " << band2sigDown << endl;
   cout << "-1 sigma  band " << band1sigDown << " [Power Constraint)]" << endl;
   cout << "median of band " << bandMedian << endl;
   cout << "+1 sigma  band " << band1sigUp << endl;
   cout << "+2 sigma  band " << band2sigUp << endl;

   // print out the interval on the first Parameter of Interest
   cout << "\nobserved 95% upper-limit "<< interval->UpperLimit(*firstPOI) <<endl;
   cout << "CLb strict [P(toy>obs|0)] for observed 95% upper-limit "<< CLb <<endl;
   cout << "CLb inclusive [P(toy>=obs|0)] for observed 95% upper-limit "<< CLbinclusive <<endl;

   delete profile;
   delete nll;

}
Пример #10
0
void FitterUtils::generate()
{
   //***************Get the PDFs from the workspace

   TFile fw(workspacename.c_str(), "UPDATE");   
   RooWorkspace* workspace = (RooWorkspace*)fw.Get("workspace");
   RooRealVar *B_plus_M = workspace->var("B_plus_M");
   RooRealVar *misPT = workspace->var("misPT");
   RooRealVar *T = workspace->var("T");
   RooRealVar *n = workspace->var("n");
   RooRealVar *expoConst = workspace->var("expoConst");
   RooRealVar *trueExp = workspace->var("trueExp");
   RooRealVar *fractionalErrorJpsiLeak = workspace->var("fractionalErrorJpsiLeak");

   cout<<"VALUE OF T IN GENERATE: "<<T->getVal()<<" +- "<<T->getError()<<endl;
   cout<<"VALUE OF n IN GENERATE: "<<n->getVal()<<" +- "<<n->getError()<<endl;

   RooHistPdf *histPdfSignalZeroGamma = (RooHistPdf *) workspace->pdf("histPdfSignalZeroGamma");
   RooHistPdf *histPdfSignalOneGamma = (RooHistPdf *) workspace->pdf("histPdfSignalOneGamma");
   RooHistPdf *histPdfSignalTwoGamma = (RooHistPdf *) workspace->pdf("histPdfSignalTwoGamma");
   RooHistPdf *histPdfPartReco = (RooHistPdf *) workspace->pdf("histPdfPartReco");
   RooHistPdf *histPdfJpsiLeak(0);
   if(nGenJpsiLeak>1) histPdfJpsiLeak = (RooHistPdf *) workspace->pdf("histPdfJpsiLeak");


   RooAbsPdf *combPDF;

   if (fit2D)
   {  
      combPDF =  new RooPTMVis("combPDF", "combPDF", *misPT, *B_plus_M, *T, *n, *expoConst);
   }
   else
   {
      combPDF =  new RooExponential("combPDF", "combPDF", *B_plus_M, *expoConst);
   }

   double trueExpConst(trueExp->getValV());
   expoConst->setVal(trueExpConst);


   //***************Prepare generation

   int nGenSignalZeroGamma(floor(nGenFracZeroGamma*nGenSignal));
   int nGenSignalOneGamma(floor(nGenFracOneGamma*nGenSignal));
   int nGenSignalTwoGamma(floor(nGenSignal-nGenSignalZeroGamma-nGenSignalOneGamma));


   RooArgSet argset2(*B_plus_M);
   if (fit2D) argset2.add(*misPT);

   cout<<"Preparing the generation of events 1";

   RooRandom::randomGenerator()->SetSeed();
   RooAbsPdf::GenSpec* GenSpecSignalZeroGamma = histPdfSignalZeroGamma->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenSignalZeroGamma)); cout<<" 2 ";
   RooAbsPdf::GenSpec* GenSpecSignalOneGamma = histPdfSignalOneGamma->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenSignalOneGamma)); cout<<" 3 ";
   RooAbsPdf::GenSpec* GenSpecSignalTwoGamma = histPdfSignalTwoGamma->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenSignalTwoGamma)); cout<<" 4 ";
   RooAbsPdf::GenSpec* GenSpecPartReco =  histPdfPartReco->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenPartReco)); cout<<" 5 "<<endl;
   RooAbsPdf::GenSpec* GenSpecComb = combPDF->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenComb));
   RooAbsPdf::GenSpec* GenSpecJpsiLeak(0);
   if(nGenJpsiLeak>1) GenSpecJpsiLeak = histPdfJpsiLeak->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenJpsiLeak));


   cout<<"Variable loaded:"<<endl;
   B_plus_M->Print(); expoConst->Print(); //B_plus_DTFM_M_zero->Print();
   if (fit2D) misPT->Print(); 


   //***************Generate some datasets

   cout<<"Generating signal Zero Photon"<<endl;
   RooDataSet* dataGenSignalZeroGamma = histPdfSignalZeroGamma->generate(*GenSpecSignalZeroGamma);//(argset, 250, false, true, "", false, true);
   dataGenSignalZeroGamma->SetName("dataGenSignalZeroGamma"); dataGenSignalZeroGamma->SetTitle("dataGenSignalZeroGamma");
   cout<<"Generating signal One Photon"<<endl;
   RooDataSet* dataGenSignalOneGamma = histPdfSignalOneGamma->generate(*GenSpecSignalOneGamma);//(argset, 250, false, true, "", false, true);
   dataGenSignalOneGamma->SetName("dataGenSignalOneGamma"); dataGenSignalOneGamma->SetTitle("dataGenSignalOneGamma");
   cout<<"Generating signal two Photons"<<endl;
   RooDataSet* dataGenSignalTwoGamma = histPdfSignalTwoGamma->generate(*GenSpecSignalTwoGamma);//(argset, 250, false, true, "", false, true);
   dataGenSignalTwoGamma->SetName("dataGenSignalTwoGamma"); dataGenSignalTwoGamma->SetTitle("dataGenSignalTwoGamma");
   cout<<"Generating combinatorial"<<endl;
   RooDataSet* dataGenComb = combPDF->generate(*GenSpecComb);//(argset, 100, false, true, "", false, true);
   dataGenComb->SetName("dataGenComb"); dataGenComb->SetTitle("dataGenComb");
   cout<<"Generating PartReco"<<endl;
   RooDataSet* dataGenPartReco = histPdfPartReco->generate(*GenSpecPartReco);//argset, 160, false, true, "", false, true);
   dataGenPartReco->SetName("dataGenPartReco"); dataGenPartReco->SetTitle("dataGenPartReco");
   RooDataSet* dataGenJpsiLeak(0);
   if(nGenJpsiLeak>1)
   {
      cout<<"Generating Leaking JPsi"<<endl;
      dataGenJpsiLeak = histPdfJpsiLeak->generate(*GenSpecJpsiLeak);//argset, 160, false, true, "", false, true);
      dataGenJpsiLeak->SetName("dataGenJpsiLeak"); dataGenJpsiLeak->SetTitle("dataGenJpsiLeak");
   }

   //*************Saving the generated datasets in a workspace

   RooWorkspace workspaceGen("workspaceGen", "workspaceGen");

   workspaceGen.import(*dataGenSignalZeroGamma);
   workspaceGen.import(*dataGenSignalOneGamma);
   workspaceGen.import(*dataGenSignalTwoGamma);
   workspaceGen.import(*dataGenComb);
   workspaceGen.import(*dataGenPartReco);
   if(nGenJpsiLeak>1) workspaceGen.import(*dataGenJpsiLeak);
    
   
   workspaceGen.Write("", TObject::kOverwrite);


   //delete workspace;
   fw.Close();


   delete dataGenSignalZeroGamma;
   delete dataGenSignalOneGamma;
   delete dataGenSignalTwoGamma;
   delete dataGenComb;
   delete dataGenPartReco;
   if(nGenJpsiLeak>1) delete dataGenJpsiLeak;

   delete GenSpecSignalZeroGamma;
   delete GenSpecSignalOneGamma;
   delete GenSpecSignalTwoGamma;
   delete GenSpecComb;
   delete GenSpecPartReco;
   delete combPDF;
   if(nGenJpsiLeak>1) delete GenSpecJpsiLeak;

   delete histPdfSignalZeroGamma; 
   delete histPdfSignalOneGamma;
   delete histPdfSignalTwoGamma;
   delete histPdfPartReco;
   if(nGenJpsiLeak>1) delete histPdfJpsiLeak;


}
int compute(RooFitResult* fit, int nbdata, const int nEff, double* eff, double* et, double* et_errmax, double* et_errmin,
	    double et_plateau, double& eff_plateau, double& eff_plateau_errmax, double& eff_plateau_errmin,                       
	    bool draw, bool verbose)                                                                                              
{
  
  // Extract fit parameters //
  std::cout<<"erereo4"<<std::endl;
  RooArgList param = fit->floatParsFinal() ;
  std::cout<<"erereo6"<<std::endl;
  double err[5] ;
  double mu[5] ;

  for(Int_t i = 0; i < param.getSize(); i++) {

    RooRealVar* var = ( dynamic_cast<RooRealVar*>( param.at(i) ) );
    //var->Print() ;
    mu[i] = var->getVal() ;
    err[i] = var->getError() ;
  }
  
  std::cout<<"erereo5"<<std::endl;
  double min, max;
  
  min = mu[0]-5*err[0] ;
  if (mu[0]-5*err[0]<0) min = 0. ;
  RooRealVar alpha("alpha","#alpha",mu[0],min,mu[0]+5*err[0]);
  
  min = mu[1]-5*err[1] ;
  if (mu[1]-5*err[1]<5) min = 5. ;
  RooRealVar mean("mean","mean",mu[1],min,mu[1]+5*err[1]);
  
  min = mu[2]-5*err[2] ;
  if (mu[2]-5*err[2]<1) min = 1. ;
  RooRealVar n("n","n",mu[2],min,mu[2]+5*err[2]);
  
  min = mu[3]-5*err[3] ;
  if (mu[3]-5*err[3]<0.6) min = 0.6 ; 

  max = mu[3]+5*err[3] ;
  if (mu[3]+5*err[3]>1.) max = 1. ; 
  RooRealVar norm("norm","N",mu[3],min,max);
  
  min = mu[4]-5*err[4] ;
  if (mu[4]-5*err[4]<0.) min = 0. ; 
  RooRealVar sigma("sigma","#sigma",mu[4],min,mu[4]+5*err[4]);
  
  RooRealVar xaxis("x","x",0,150) ;


  // Create PDF and generate nbdata sets of CB parameters
  RooAbsPdf* parabPdf = fit->createHessePdf(RooArgSet(norm,alpha,n,mean,sigma)) ;
  RooDataSet* data = parabPdf->generate(RooArgSet(norm,alpha,n,mean,sigma),nbdata) ;

  // Generate histo to extract error bar on efficiency(xaxis)
  xaxis = et_plateau ;
  cout << "Generate histo to extract error bars" << endl;
  genHisto(nbdata, data, nEff, eff, et, et_errmax, et_errmin, eff_plateau, eff_plateau_errmax, eff_plateau_errmin,
	   xaxis, mean, sigma, alpha, n, norm, draw, verbose);

  /* int genHisto(int nbdata, RooDataSet* data, const int nEff, double* eff, double* et, double* et_errmax, double* et_errmin,
                  double& eff_plateau, double& eff_plateau_errmax, double& eff_plateau_errmin, 
		  RooRealVar xaxis, RooRealVar mean, RooRealVar sigma, RooRealVar alpha, RooRealVar n, RooRealVar norm,
		  bool draw, bool verbose)

     int compute(RooFitResult* fit, int nbdata, const int nEff, double* eff, double* et, double* et_errmax, double* et_errmin,
                 double et_plateau, double& eff_plateau, double& eff_plateau_errmax, double& eff_plateau_errmin,
                 bool draw, bool verbose)
  */

  return 1;
}
Пример #12
0
void rf509_wsinteractive()
{
  // C r e a t e  a n d   f i l l   w o r k s p a c e
  // ------------------------------------------------

  // Create a workspace named 'w'
  // With CINT w could exports its contents to 
  // a same-name C++ namespace in CINT 'namespace w'.
  // but this does not work anymore in CLING. 
  // so this tutorial is an example on how to 
  // change the code
  RooWorkspace* w = new RooWorkspace("w",kTRUE) ;

  // Fill workspace with p.d.f. and data in a separate function
  fillWorkspace(*w) ;

  // Print workspace contents
  w->Print() ;

  // this does not work anymore with CLING 
  // use normal workspace functionality 

 
  // U s e   w o r k s p a c e   c o n t e n t s   
  // ----------------------------------------------


  // Old syntax to use the name space prefix operator to access the workspace contents
  //
  //RooDataSet* d = w::model.generate(w::x,1000) ;
  //RooFitResult* r = w::model.fitTo(*d) ;

  // use normal workspace methods
  RooAbsPdf * model = w->pdf("model");
  RooRealVar * x = w->var("x");

  RooDataSet* d = model->generate(*x,1000) ;
  RooFitResult* r = model->fitTo(*d) ;

  // old syntax to access the variable x
  // RooPlot* frame = w::x.frame() ;

  RooPlot* frame = x->frame() ;
  d->plotOn(frame) ;

  // OLD syntax to ommit x::
  // NB: The 'w::' prefix can be omitted if namespace w is imported in local namespace
  // in the usual C++ way
  //
  // using namespace w;
  // model.plotOn(frame) ;
  // model.plotOn(frame,Components(bkg),LineStyle(kDashed)) ;

  // new correct syntax 
  RooAbsPdf *bkg = w->pdf("bkg");
  model->plotOn(frame);
  model->plotOn(frame,Components(*bkg),LineStyle(kDashed)) ;

  // Draw the frame on the canvas
  new TCanvas("rf509_wsinteractive","rf509_wsinteractive",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


}
Пример #13
0
void rf104_classfactory()
{
   // W r i t e   c l a s s   s k e l e t o n   c o d e
   // --------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b
   // To use this class,
   //    - Edit the file MyPdfV1.cxx and implement the evaluate() method in terms of x,a and b
   //    - Compile and link class with '.x MyPdfV1.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV1","x,A,B") ;


   // W i t h   a d d e d   i n i t i a l   v a l u e   e x p r e s s i o n
   // ---------------------------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b and given formula expression
   // To use this class,
   //    - Compile and link class with '.x MyPdfV2.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV2","x,A,B","","A*fabs(x)+pow(x-B,2)") ;


   // W i t h   a d d e d   a n a l y t i c a l   i n t e g r a l   e x p r e s s i o n
   // ---------------------------------------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b, given formula expression _and_
   // given expression for analytical integral over x
   // To use this class,
   //    - Compile and link class with '.x MyPdfV3.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV3","x,A,B","","A*fabs(x)+pow(x-B,2)",kTRUE,kFALSE,
            "x:(A/2)*(pow(x.max(rangeName),2)+pow(x.min(rangeName),2))+(1./3)*(pow(x.max(rangeName)-B,3)-pow(x.min(rangeName)-B,3))") ;



   // U s e   i n s t a n c e   o f   c r e a t e d   c l a s s
   // ---------------------------------------------------------

   // Compile MyPdfV3 class (only when running in CINT)
   gROOT->ProcessLineSync(".x MyPdfV3.cxx+") ;

   // Create instance of MyPdfV3 class
   RooRealVar a("a","a",1) ;
   RooRealVar b("b","b",2,-10,10) ;
   RooRealVar y("y","y",-10,10);
   MyPdfV3 pdf("pdf","pdf",y,a,b) ;

   // Generate toy data from pdf and plot data and p.d.f on frame
   RooPlot* frame1 = y.frame(Title("Compiled class MyPdfV3")) ;
   RooDataSet* data = pdf.generate(y,1000) ;
   pdf.fitTo(*data) ;
   data->plotOn(frame1) ;
   pdf.plotOn(frame1) ;


   // -----------------------------------------------------------------
   // C o m p i l e d   v e r s i o n   o f   e x a m p l e   r f 1 0 3
   // =================================================================

   // Declare observable x
   RooRealVar x("x","x",-20,20) ;

   // The RooClassFactory::makePdfInstance() function performs code writing, compiling, linking
   // and object instantiation in one go and can serve as a straight replacement of RooGenericPdf

   RooRealVar alpha("alpha","alpha",5,0.1,10) ;
   RooAbsPdf* genpdf = RooClassFactory::makePdfInstance("GenPdf","(1+0.1*fabs(x)+sin(sqrt(fabs(x*alpha+0.1))))",RooArgSet(x,alpha)) ;

   // Generate a toy dataset from the interpreted p.d.f
   RooDataSet* data2 = genpdf->generate(x,50000) ;

   // Fit the interpreted p.d.f to the generated data
   genpdf->fitTo(*data2) ;

   // Make a plot of the data and the p.d.f overlaid
   RooPlot* frame2 = x.frame(Title("Compiled version of pdf of rf103")) ;
   data2->plotOn(frame2) ;
   genpdf->plotOn(frame2) ;

   // Draw all frames on a canvas
   TCanvas* c = new TCanvas("rf104_classfactory","rf104_classfactory",800,400) ;
   c->Divide(2) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;

}
Пример #14
0
void LeptonPreselectionCMG( PreselType type, RooWorkspace * w ) {
	const Options & opt = Options::getInstance(); 
	if (type == ELE)
		cout << "Running Electron Preselection :" << endl;
	else if (type == MU)
		cout << "Running Muon Preselection :" << endl;
	else if (type == EMU)
		cout << "Running Electron-Muon Preselection() ..." << endl;
	else if (type == PHOT)
		cout << "Running Photon Preselection :" << endl;

	string systVar;
	try {
		systVar = opt.checkStringOption("SYSTEMATIC_VAR");
	} catch (const std::string & exc) {
		cout << exc << endl;
	}
	if (systVar == "NONE")
		systVar.clear();

#ifdef CMSSWENV
	JetCorrectionUncertainty jecUnc("Summer13_V4_MC_Uncertainty_AK5PFchs.txt");
#endif

	string inputDir = opt.checkStringOption("INPUT_DIR");
	string outputDir = opt.checkStringOption("OUTPUT_DIR");
	string sampleName = opt.checkStringOption("SAMPLE_NAME");
	string inputFile = inputDir + '/' + sampleName + ".root";
	cout << "\tInput file: " << inputFile << endl;

	bool isSignal = opt.checkBoolOption("SIGNAL");
	TGraph * higgsW = 0;
	TGraph * higgsI = 0;
	if (isSignal) {
		double higgsM = opt.checkDoubleOption("HIGGS_MASS");
		if (higgsM >= 400) {
			string dirName = "H" + double2string(higgsM);
			bool isVBF = opt.checkBoolOption("VBF");
			string lshapeHistName = "cps";
			string intHistName = "nominal";
			
			if (systVar == "LSHAPE_UP") {
				intHistName = "up";
			} else if (systVar == "LSHAPE_DOWN") {
				intHistName = "down";
			}

			if (isVBF) {
				TFile weightFile("VBF_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();

			} else {
				TFile weightFile("GG_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();
				TFile interfFile("newwgts_interf.root");
				higgsI = (TGraph *) ( (TDirectory *) interfFile.Get(dirName.c_str()))->Get( intHistName.c_str() )->Clone();
			}
		}
	}

	TFile * file = new TFile( inputFile.c_str() );
	if (!file->IsOpen())
		throw string("ERROR: Can't open the file: " + inputFile + "!");
	TDirectory * dir = (TDirectory *) file->Get("dataAnalyzer");
	TH1D * nEvHisto = (TH1D *) dir->Get("cutflow");
	TH1D * puHisto = (TH1D *) dir->Get("pileup");
	TTree * tree = ( TTree * ) dir->Get( "data" );
	Event ev( tree );
	const int * runP = ev.getSVA<int>("run"); 
	const int * lumiP = ev.getSVA<int>("lumi"); 
	const int * eventP = ev.getSVA<int>("event"); 
	const bool * trigBits = ev.getAVA<bool>("t_bits");
	const int * trigPres = ev.getAVA<int>("t_prescale");
	const float * metPtA = ev.getAVA<float>("met_pt");
	const float * metPhiA = ev.getAVA<float>("met_phi");
	const float * rhoP = ev.getSVA<float>("rho");
	const float * rho25P = ev.getSVA<float>("rho25");
	const int * nvtxP = ev.getSVA<int>("nvtx"); 
	const int * niP = ev.getSVA<int>("ngenITpu"); 
	
#ifdef PRINTEVENTS
	string eventFileName;
	if (type == ELE)
		eventFileName = "events_ele.txt";
	else if (type == MU)
		eventFileName = "events_mu.txt";
	else if (type == EMU)
		eventFileName = "events_emu.txt";

	EventPrinter evPrint(ev, type, eventFileName);
	evPrint.readInEvents("diff.txt");
	evPrint.printElectrons();
	evPrint.printMuons();
	evPrint.printZboson();
	evPrint.printJets();
	evPrint.printHeader();
#endif

	string outputFile = outputDir + '/' + sampleName;

	if (systVar.size())
		outputFile += ('_' + systVar);

	if (type == ELE)
		outputFile += "_elePresel.root";
	else if (type == MU)
		outputFile += "_muPresel.root";
	else if (type == EMU)
		outputFile += "_emuPresel.root";
	else if (type == PHOT)
		outputFile += "_phPresel.root";
	cout << "\tOutput file: " << outputFile << endl;

	TFile * out = new TFile( outputFile.c_str(), "recreate" );
	TH1D * outNEvHisto = new TH1D("nevt", "nevt", 1, 0, 1);
	outNEvHisto->SetBinContent(1, nEvHisto->GetBinContent(1));
	outNEvHisto->Write("nevt");

	TH1D * outPuHisto = new TH1D( *puHisto );
	outPuHisto->Write("pileup");

	std::vector< std::tuple<std::string, std::string> > eleVars;
	eleVars.push_back( std::make_tuple("ln_px", "F") );
	eleVars.push_back( std::make_tuple("ln_py", "F") );
	eleVars.push_back( std::make_tuple("ln_pz", "F") );
	eleVars.push_back( std::make_tuple("ln_en", "F") );
	eleVars.push_back( std::make_tuple("ln_idbits", "I") );
	eleVars.push_back( std::make_tuple("ln_d0", "F") );
	eleVars.push_back( std::make_tuple("ln_dZ", "F") );
	eleVars.push_back( std::make_tuple("ln_nhIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_gIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_chIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_trkLostInnerHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addEleVars;
	addEleVars.push_back( std::make_tuple("egn_sceta", "F") );
	addEleVars.push_back( std::make_tuple("egn_detain", "F") );
	addEleVars.push_back( std::make_tuple("egn_dphiin", "F") );
	addEleVars.push_back( std::make_tuple("egn_sihih", "F") );
	addEleVars.push_back( std::make_tuple("egn_hoe", "F") );
	addEleVars.push_back( std::make_tuple("egn_ooemoop", "F") );
	addEleVars.push_back( std::make_tuple("egn_isConv", "B") );

	std::vector< std::tuple<std::string, std::string> > muVars;
	muVars.push_back( std::make_tuple("ln_px", "F") );
	muVars.push_back( std::make_tuple("ln_py", "F") );
	muVars.push_back( std::make_tuple("ln_pz", "F") );
	muVars.push_back( std::make_tuple("ln_en", "F") );
	muVars.push_back( std::make_tuple("ln_idbits", "I") );
	muVars.push_back( std::make_tuple("ln_d0", "F") );
	muVars.push_back( std::make_tuple("ln_dZ", "F") );
	muVars.push_back( std::make_tuple("ln_nhIso04", "F") );
	muVars.push_back( std::make_tuple("ln_gIso04", "F") );
	muVars.push_back( std::make_tuple("ln_chIso04", "F") );
	muVars.push_back( std::make_tuple("ln_puchIso04", "F") );
	muVars.push_back( std::make_tuple("ln_trkchi2", "F") );
	muVars.push_back( std::make_tuple("ln_trkValidPixelHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addMuVars;
	addMuVars.push_back( std::make_tuple("mn_trkLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_pixelLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_innerTrackChi2", "F") );
	addMuVars.push_back( std::make_tuple("mn_validMuonHits", "F") );
	addMuVars.push_back( std::make_tuple("mn_nMatchedStations", "F") );

	unsigned run;
	unsigned lumi;
	unsigned event;
	double pfmet;
	int nele;
	int nmu;
	int nsoftmu;
	double l1pt;
	double l1eta;
	double l1phi;
	double l2pt;
	double l2eta;
	double l2phi;
	double zmass;
	double zpt;
	double zeta;
	double mt;
	int nsoftjet;
	int nhardjet;
	double maxJetBTag;
	double minDeltaPhiJetMet;
	double detajj;
	double mjj;
	int nvtx;
	int ni;
	int category;
	double weight;
	double hmass;
	double hweight;

	TTree * smallTree = new TTree("HZZ2l2nuAnalysis", "HZZ2l2nu Analysis Tree");
	smallTree->Branch( "Run", &run, "Run/i" );
	smallTree->Branch( "Lumi", &lumi, "Lumi/i" );
	smallTree->Branch( "Event", &event, "Event/i" );
	smallTree->Branch( "PFMET", &pfmet, "PFMET/D" );
	smallTree->Branch( "NELE", &nele, "NELE/I" );
	smallTree->Branch( "NMU", &nmu, "NMU/I" );
	smallTree->Branch( "NSOFTMU", &nsoftmu, "NSOFTMU/I" );
	smallTree->Branch( "L1PT", &l1pt, "L1PT/D" );
	smallTree->Branch( "L1ETA", &l1eta, "L1ETA/D" );
	smallTree->Branch( "L1PHI", &l1phi, "L1PHI/D" );
	smallTree->Branch( "L2PT", &l2pt, "L2PT/D" );
	smallTree->Branch( "L2ETA", &l2eta, "L2ETA/D" );
	smallTree->Branch( "L2PHI", &l2phi, "L2PHI/D" );
	smallTree->Branch( "ZMASS", &zmass, "ZMASS/D" );
	smallTree->Branch( "ZPT", &zpt, "ZPT/D" );
	smallTree->Branch( "ZETA", &zeta, "ZETA/D" );
	smallTree->Branch( "MT", &mt, "MT/D" );
	smallTree->Branch( "NSOFTJET", &nsoftjet, "NSOFTJET/I" );
	smallTree->Branch( "NHARDJET", &nhardjet, "NHARDJET/I" );
	smallTree->Branch( "MAXJETBTAG", &maxJetBTag, "MAXJETBTAG/D" );
	smallTree->Branch( "MINDPJETMET", &minDeltaPhiJetMet, "MINDPJETMET/D" );
	smallTree->Branch( "DETAJJ", &detajj, "DETAJJ/D" );
	smallTree->Branch( "MJJ", &mjj, "MJJ/D" );
	smallTree->Branch( "NVTX", &nvtx, "NVTX/I" );
	smallTree->Branch( "nInter" , &ni, "nInter/I" );
	smallTree->Branch( "CATEGORY", &category, "CATEGORY/I" );
	smallTree->Branch( "Weight" , &weight, "Weight/D" );
	smallTree->Branch( "HMASS", &hmass, "HMASS/D" );
	smallTree->Branch( "HWEIGHT", &hweight, "HWEIGHT/D" );

	bool isData = opt.checkBoolOption("DATA");

	unsigned long nentries = tree->GetEntries();

	RooDataSet * events = nullptr;

	PhotonPrescale photonPrescales;

	vector<int> thresholds;
	if (type == PHOT) {
		if (w == nullptr)
			throw string("ERROR: No mass peak pdf!");
		RooRealVar * zmass = w->var("mass");
		zmass->setRange(76.0, 106.0);
		RooAbsPdf * pdf = w->pdf("massPDF");
		events = pdf->generate(*zmass, nentries);

		photonPrescales.addTrigger("HLT_Photon36_R9Id90_HE10_Iso40_EBOnly", 36, 3, 7);
		photonPrescales.addTrigger("HLT_Photon50_R9Id90_HE10_Iso40_EBOnly", 50, 5, 8);
		photonPrescales.addTrigger("HLT_Photon75_R9Id90_HE10_Iso40_EBOnly", 75, 7, 9);
		photonPrescales.addTrigger("HLT_Photon90_R9Id90_HE10_Iso40_EBOnly", 90, 10, 10);
	}

	TH1D ptSpectrum("ptSpectrum", "ptSpectrum", 200, 55, 755);
	ptSpectrum.Sumw2();

	unordered_set<EventAdr> eventsSet;
	for ( unsigned long iEvent = 0; iEvent < nentries; iEvent++ ) {
//		if (iEvent < 6060000)
//			continue;

		if ( iEvent % 10000 == 0) {
			cout << string(40, '\b');
			cout << setw(10) << iEvent << " / " << setw(10) << nentries << " done ..." << std::flush;
		}

		tree->GetEntry( iEvent );

		run = -999;
		lumi = -999;
		event = -999;
		pfmet = -999;
		nele = -999;
		nmu = -999;
		nsoftmu = -999;
		l1pt = -999;
		l1eta = -999;
		l1phi = -999;
		l2pt = -999;
		l2eta = -999;
		l2phi = -999;
		zmass = -999;
		zpt = -999;
		zeta = -999;
		mt = -999;
		nsoftjet = -999;
		nhardjet = -999;
		maxJetBTag = -999;
		minDeltaPhiJetMet = -999;
		detajj = -999;
		mjj = -999;
		nvtx = -999;
		ni = -999;
		weight = -999;
		category = -1;
		hmass = -999;
		hweight = -999;

		run = *runP;
		lumi = *lumiP;
		event = *eventP;

		EventAdr tmp(run, lumi, event);
		if (eventsSet.find( tmp ) != eventsSet.end()) {
			continue;
		}
		eventsSet.insert( tmp );

		if (type == ELE && isData) {
			if (trigBits[0] != 1 || trigPres[0] != 1)
				continue;
		}

		if (type == MU && isData) {
			if ( (trigBits[2] != 1 || trigPres[2] != 1)
				&& (trigBits[3] != 1 || trigPres[3] != 1)
				&& (trigBits[6] != 1 || trigPres[6] != 1)
			   )
				continue;
		}

		if (type == EMU && isData) {
			if ( (trigBits[4] != 1 || trigPres[4] != 1)
				&& (trigBits[5] != 1 || trigPres[5] != 1)
			   )
				continue;
		}

		vector<Electron> electrons = buildLeptonCollection<Electron, 11>(ev, eleVars, addEleVars);
		vector<Muon> muons = buildLeptonCollection<Muon, 13>(ev, muVars, addMuVars);

		float rho = *rhoP;
		float rho25 = *rho25P;

		vector<Electron> looseElectrons;
		vector<Electron> selectedElectrons;
		for (unsigned j = 0; j < electrons.size(); ++j) {
			try {
			TLorentzVector lv = electrons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesVetoID() &&
					electrons[j].isPFIsolatedLoose(rho25)
				) {
				looseElectrons.push_back(electrons[j]);
			}

			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesMediumID() &&
					electrons[j].isPFIsolatedMedium(rho25)
				) {
				selectedElectrons.push_back(electrons[j]);
			}
			} catch (const string & exc) {
				cout << exc << endl;
				cout << "run = " << run << endl;
				cout << "lumi = " << lumi << endl;
				cout << "event = " << event << endl;
			}
		}

		vector<Muon> looseMuons;
		vector<Muon> softMuons;
		vector<Muon> selectedMuons;
		for (unsigned j = 0; j < muons.size(); ++j) {
			TLorentzVector lv = muons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isLooseMuon() &&
					muons[j].isPFIsolatedLoose()
				) {
				looseMuons.push_back(muons[j]);
			} else if (
					lv.Pt() > 3 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isSoftMuon()
				) {
				softMuons.push_back(muons[j]);
			}
			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isTightMuon() &&
					muons[j].isPFIsolatedTight()
				) {
				selectedMuons.push_back(muons[j]);
			}
		}

		vector<Lepton> looseLeptons;
		for (unsigned i = 0; i < looseElectrons.size(); ++i)
			looseLeptons.push_back(looseElectrons[i]);
		for (unsigned i = 0; i < looseMuons.size(); ++i)
			looseLeptons.push_back(looseMuons[i]);
		for (unsigned i = 0; i < softMuons.size(); ++i)
			looseLeptons.push_back(softMuons[i]);

#ifdef PRINTEVENTS
		evPrint.setElectronCollection(selectedElectrons);
		evPrint.setMuonCollection(selectedMuons);
#endif

		vector<Photon> photons = selectPhotonsCMG( ev );
		vector<Photon> selectedPhotons;
		for (unsigned i = 0; i < photons.size(); ++i) {
			if (photons[i].isSelected(rho) && photons[i].lorentzVector().Pt() > 55)
				selectedPhotons.push_back( photons[i] );
		}

		if (type == PHOT) {
			vector<Electron> tmpElectrons;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < looseElectrons.size(); ++j) {
					TLorentzVector elVec = looseElectrons[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), elVec.Eta(), elVec.Phi());
					if ( dR > 0.05 )
						tmpElectrons.push_back( looseElectrons[j] );
				}
			}
			looseElectrons = tmpElectrons;
		}

		string leptonsType;
		Lepton * selectedLeptons[2] = {0};
		if (type == ELE) {
			if (selectedElectrons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedElectrons[1];
			}
		} else if (type == MU) {
			if (selectedMuons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedMuons[0];
				selectedLeptons[1] = &selectedMuons[1];
			}
		} else if (type == EMU) {
			if (selectedElectrons.size() < 1 || selectedMuons.size() < 1) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedMuons[0];
			}
		} else if (type == PHOT) {
			if (selectedPhotons.size() != 1) {
				continue;
			}
		}

		nele = looseElectrons.size();
		nmu = looseMuons.size();
		nsoftmu = softMuons.size();

		TLorentzVector Zcand;

		if (type == ELE || type == MU || type == EMU) {
			TLorentzVector lep1 = selectedLeptons[0]->lorentzVector();
			TLorentzVector lep2 = selectedLeptons[1]->lorentzVector();

			if (lep2.Pt() > lep1.Pt() && type != EMU) {
				TLorentzVector temp = lep1;
				lep1 = lep2;
				lep2 = temp;
			}

			l1pt = lep1.Pt();
			l1eta = lep1.Eta();
			l1phi = lep1.Phi();

			l2pt = lep2.Pt();
			l2eta = lep2.Eta();
			l2phi = lep2.Phi();

			Zcand = lep1 + lep2;
			zmass = Zcand.M();
		} else if (type == PHOT) {
			Zcand = selectedPhotons[0].lorentzVector();
			zmass = events->get(iEvent)->getRealValue("mass");
		}

		zpt = Zcand.Pt();
		zeta = Zcand.Eta();

		if (type == PHOT) {
			unsigned idx = photonPrescales.getIndex(zpt);
			if (trigBits[idx])
				weight = trigPres[idx];
			else
				continue;
			ptSpectrum.Fill(zpt, weight);
		}

		TLorentzVector met;
		met.SetPtEtaPhiM(metPtA[0], 0.0, metPhiA[0], 0.0);
		TLorentzVector clusteredFlux;

		unsigned mode = 0;
		if (systVar == "JES_UP")
			mode = 1;
		else if (systVar == "JES_DOWN")
			mode = 2;
		TLorentzVector jecCorr;

#ifdef CMSSWENV
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, jecUnc, &jecCorr, mode );
#else
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, &jecCorr, mode );
#endif

		met -= jecCorr;

		mode = 0;
		if (systVar == "JER_UP")
			mode = 1;
		else if (systVar == "JER_DOWN")
			mode = 2;
		TLorentzVector smearCorr = smearJets( jetsAll, mode );
		if (isData && smearCorr != TLorentzVector())
			throw std::string("Jet smearing corrections different from zero in DATA!");
		met -= smearCorr;

		vector<Jet> selectedJets;
		for (unsigned i = 0; i < jetsAll.size(); ++i) {
			if (
					jetsAll[i].lorentzVector().Pt() > 10
					&& fabs(jetsAll[i].lorentzVector().Eta()) < 4.7
					&& jetsAll[i].passesPUID() &&
					jetsAll[i].passesPFLooseID()
				)
				selectedJets.push_back( jetsAll[i] );
		}
		if (type == PHOT) {
			vector<Jet> tmpJets;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < selectedJets.size(); ++j) {
					TLorentzVector jVec = selectedJets[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), jVec.Eta(), jVec.Phi());
					if ( dR > 0.4 )
						tmpJets.push_back( selectedJets[j] );
				}
			}
			selectedJets = tmpJets;
		}

		if (systVar == "UMET_UP" || systVar == "UMET_DOWN") {
			for (unsigned i = 0; i < jetsAll.size(); ++i)
				clusteredFlux += jetsAll[i].lorentzVector();
			for (unsigned i = 0; i < looseElectrons.size(); ++i)
				clusteredFlux += looseElectrons[i].lorentzVector();
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				clusteredFlux += looseMuons[i].lorentzVector();

			TLorentzVector unclusteredFlux = -(met + clusteredFlux);
			if (systVar == "UMET_UP")
				unclusteredFlux *= 1.1;
			else
				unclusteredFlux *= 0.9;
			met = -(clusteredFlux + unclusteredFlux);
		}

		if (systVar == "LES_UP" || systVar == "LES_DOWN") {
			TLorentzVector diff;
			double sign = 1.0;
			if (systVar == "LES_DOWN")
				sign = -1.0;
			for (unsigned i = 0; i < looseElectrons.size(); ++i) {
				TLorentzVector tempEle = looseElectrons[i].lorentzVector();
				if (looseElectrons[i].isEB())
					diff += sign * 0.02 * tempEle;
				else
					diff += sign * 0.05 * tempEle;
			}
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				diff += sign * 0.01 * looseMuons[i].lorentzVector();

			met -= diff;
		}

		pfmet = met.Pt();

		double px = met.Px() + Zcand.Px();
		double py = met.Py() + Zcand.Py();
		double pt2 = px * px + py * py;
		double e = sqrt(zpt * zpt + zmass * zmass) + sqrt(pfmet * pfmet + zmass * zmass);
		double mt2 = e * e - pt2;
		mt = (mt2 > 0) ? sqrt(mt2) : 0;

		vector<Jet> hardjets;
		vector<Jet> softjets;
		maxJetBTag = -999;
		minDeltaPhiJetMet = 999;
		for ( unsigned j = 0; j < selectedJets.size(); ++j ) {
			TLorentzVector jet = selectedJets[j].lorentzVector();

			if ( jet.Pt() > 30 ) {
				hardjets.push_back( selectedJets[j] );
			}
			if ( jet.Pt() > 15 )
				softjets.push_back( selectedJets[j] );
		}
		nhardjet = hardjets.size();
		nsoftjet = softjets.size();
//		if ( type == PHOT && nsoftjet == 0 )
//			continue;

		if (nhardjet > 1) {
			sort(hardjets.begin(), hardjets.end(), [](const Jet & a, const Jet & b) {
					return a.lorentzVector().Pt() > b.lorentzVector().Pt();
				});
			TLorentzVector jet1 = hardjets[0].lorentzVector();
			TLorentzVector jet2 = hardjets[1].lorentzVector();
			const double maxEta = max( jet1.Eta(), jet2.Eta() );
			const double minEta = min( jet1.Eta(), jet2.Eta() );
			bool passCJV = true;
			for (unsigned j = 2; j < hardjets.size(); ++j) {
				double tmpEta = hardjets[j].lorentzVector().Eta();
				if ( tmpEta > minEta && tmpEta < maxEta )
					passCJV = false;
			}
			const double tmpDelEta = std::fabs(jet2.Eta() - jet1.Eta());
			TLorentzVector diJetSystem = jet1 + jet2;
			const double tmpMass = diJetSystem.M();
			if ( type == PHOT) {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && zeta > minEta && maxEta > zeta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			} else {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && l1eta > minEta && l2eta > minEta && maxEta > l1eta && maxEta > l2eta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			}
		}

		category = evCategory(nhardjet, nsoftjet, detajj, mjj, type == PHOT);

		minDeltaPhiJetMet = 10;
		for ( unsigned j = 0; j < hardjets.size(); ++j ) {
			TLorentzVector jet = hardjets[j].lorentzVector();
			if ( hardjets[j].getVarF("jn_jp") > maxJetBTag && fabs(jet.Eta()) < 2.5 )
				maxJetBTag = hardjets[j].getVarF("jn_jp");
			double tempDelPhiJetMet = deltaPhi(met.Phi(), jet.Phi());
			if ( tempDelPhiJetMet < minDeltaPhiJetMet )
				minDeltaPhiJetMet = tempDelPhiJetMet;
		}

		nvtx = *nvtxP;

		if (isData)
			ni = -1;
		else
			ni = *niP;

		if (isSignal) {
			const int nMC = ev.getSVV<int>("mcn");
			const int * mcID = ev.getAVA<int>("mc_id");
			int hIdx = 0;
			for (; hIdx < nMC; ++hIdx)
				if (fabs(mcID[hIdx]) == 25)
					break;
			if (hIdx == nMC)
				throw string("ERROR: Higgs not found in signal sample!");

			float Hpx = ev.getAVV<float>("mc_px", hIdx);
			float Hpy = ev.getAVV<float>("mc_py", hIdx);
			float Hpz = ev.getAVV<float>("mc_pz", hIdx);
			float Hen = ev.getAVV<float>("mc_en", hIdx);
			TLorentzVector higgs;
			higgs.SetPxPyPzE( Hpx, Hpy, Hpz, Hen );
			hmass = higgs.M();

			if (higgsW) {
				hweight = higgsW->Eval(hmass);
				if (higgsI)
					hweight *= higgsI->Eval(hmass);
			} else
				hweight = 1;
		}

		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == ELE || type == MU || type == EMU) && ((nele + nmu + nsoftmu) > 2) )
			continue;
		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == PHOT) && ((nele + nmu + nsoftmu) > 0) )
			continue;
		if ( opt.checkBoolOption("ZPT_CUT") && zpt < 55 )
			continue;
		// for different background estimation methods different window should be applied:
		// * sample for photons should have 76.0 < zmass < 106.0
		// * sample for non-resonant background should not have this cut applied
		if ( opt.checkBoolOption("TIGHT_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("WIDE_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("BTAG_CUT") && ( maxJetBTag > 0.264) )
			continue;
		if ( opt.checkBoolOption("DPHI_CUT") && ( minDeltaPhiJetMet < 0.5) )
			continue;


#ifdef PRINTEVENTS
		evPrint.setJetCollection(hardjets);
		evPrint.setMET(met);
		evPrint.setMT(mt);
		string channelType;
		if (type == ELE)
			channelType = "ee";
		else if (type == MU)
			channelType = "mumu";
		else if (type == EMU)
			channelType = "emu";
		if (category == 1)
			channelType += "eq0jets";
		else if (category == 2)
			channelType += "geq1jets";
		else
			channelType += "vbf";
		evPrint.setChannel(channelType);
		unsigned bits = 0;
		bits |= (0x7);
		bits |= ((zmass > 76.0 && zmass < 106.0) << 3);
		bits |= ((zpt > 55) << 4);
		bits |= (((nele + nmu + nsoftmu) == 2) << 5);
		bits |= ((maxJetBTag < 0.275) << 6);
		bits |= ((minDeltaPhiJetMet > 0.5) << 7);
		evPrint.setBits(bits);
		evPrint.print();
#endif
		
		smallTree->Fill();
	}
	cout << endl;
	
	TCanvas canv("canv", "canv", 800, 600);
	//effNum.Sumw2();
	//effDen.Sumw2();
	//effNum.Divide(&effDen);
	//effNum.Draw();
	canv.SetGridy();
	canv.SetGridx();
	//canv.SaveAs("triggEff.ps");
	//canv.Clear();
	ptSpectrum.SetMarkerStyle(20);
	ptSpectrum.SetMarkerSize(0.5);
	ptSpectrum.Draw("P0E");
	//ptSpectrum.Draw("COLZ");
	canv.SetLogy();
	canv.SaveAs("ptSpectrum.ps");

	delete file;
	smallTree->Write("", TObject::kOverwrite);
	delete smallTree;
	delete out;
}