コード例 #1
0
ファイル: utilities.cpp プロジェクト: ald77/ra4_stats
void DefineSet(RooWorkspace &w,
               const string &set_name,
               const vector<string> &var_names){
  if(var_names.size()==0){
    w.defineSet(set_name.c_str(), "");
  }else{
    string cat_names = var_names.at(0);
    for(size_t ivar = 1; ivar < var_names.size(); ++ivar){
      cat_names += ("," + var_names.at(ivar));
    }
    w.defineSet(set_name.c_str(), cat_names.c_str());
  }
}
コード例 #2
0
void makeDataset( TString fname, TString tname, TString outfname ) {

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

  w->factory( "Dst_M[1950.,2070.]" );
  w->factory( "D0_M[1810.,1920.]" );
  w->factory( "D0_LTIME_ps[0.00,5.]" );

  RooArgSet *observables = new RooArgSet();
  observables->add( *w->var("Dst_M") );
  observables->add( *w->var("D0_M") );
  observables->add( *w->var("D0_LTIME_ps") );
  w->defineSet("observables", *observables);

  w->var("Dst_M")->setBins(240);
  w->var("D0_M")->setBins(220);
  w->var("D0_LTIME_ps")->setBins(200);

  double Dst_M = -999.;
  double D0_M = -999.;
  double D0_LTIME_ps = -999.;

  TFile *tf = TFile::Open(fname);
  TTree *tree = (TTree*)tf->Get(tname);

  tree->SetBranchAddress( "Dst_M", &Dst_M );
  tree->SetBranchAddress( "D0_M" , &D0_M );
  tree->SetBranchAddress( "D0_LTIME_ps", &D0_LTIME_ps );

  RooDataSet *data = new RooDataSet("Data","Data",*observables);
  RooDataHist *dataH = new RooDataHist("DataHist","Data",*observables);

  for ( int ev=0; ev<tree->GetEntries(); ev++) {

    tree->GetEntry(ev);

    if ( ev%10000 == 0 ) cout << ev << " / " << tree->GetEntries() << endl;

    if ( Dst_M < w->var("Dst_M")->getMin() || Dst_M > w->var("Dst_M")->getMax() ) continue;
    if ( D0_M < w->var("D0_M")->getMin() || D0_M > w->var("D0_M")->getMax() ) continue;
    if ( D0_LTIME_ps < w->var("D0_LTIME_ps")->getMin() || D0_LTIME_ps > w->var("D0_LTIME_ps")->getMax() ) continue;

    w->var("Dst_M")->setVal(Dst_M);
    w->var("D0_M")->setVal(D0_M);
    w->var("D0_LTIME_ps")->setVal(D0_LTIME_ps);

    data->add( *observables );
    dataH->add( *observables );

  }
  tf->Close();

  w->import(*data);
  w->import(*dataH);

  w->writeToFile(outfname);

}
コード例 #3
0
int main(int argc, char* argv[]) {

     doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

     

    epdf->Var("sig_yield");
    epdf->Var("sig_yield").setVal(153000);
    epdf->Var("sig_yield").setConstant(false);
    //decay time
    epdf->Var("obsTime");
    epdf->Var("obsTime").SetTitle("t_{#kern[-0.2]{B}_{#kern[-0.1]{ d}}^{#kern[-0.1]{ 0}}}");
    epdf->Var("obsTime").setUnit("ps");
    epdf->Var("obsTime").setRange(0.,16.);

    // tag, respectively the initial state of the produced B meson
    epdf->Cat("obsTag");
    epdf->Cat("obsTag").defineType("B_S",1);
    epdf->Cat("obsTag").defineType("Bbar_S",-1);

    //finalstate
    epdf->Cat("catFinalState");
    epdf->Cat("catFinalState").defineType("f",1);
    epdf->Cat("catFinalState").defineType("fbar",-1);

    epdf->Var("obsEtaOS");
    epdf->Var("obsEtaOS").setRange(0.0,0.5);


     std::vector<double> knots;
            knots.push_back(0.07);
            knots.push_back(0.10);
            knots.push_back(0.138);
            knots.push_back(0.16);
            knots.push_back(0.23);
            knots.push_back(0.28);
            knots.push_back(0.35);
            knots.push_back(0.42);
            knots.push_back(0.44);
            knots.push_back(0.48);
            knots.push_back(0.5);

            // empty arg list for coefficients
            RooArgList* list = new RooArgList();

            // create first coefficient
            RooRealVar* coeff_first = &(epdf->Var("parCSpline1"));
            coeff_first->setRange(0,10000);
            coeff_first->setVal(1);
            coeff_first->setConstant(false);
            list->add( *coeff_first );

            for (unsigned int i=1; i <= knots.size(); ++i){
               std::string number = boost::lexical_cast<std::string>(i);
               RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
               coeff->setRange(0,10000);
               coeff->setVal(1);
               coeff->setConstant(false);
               list->add( *coeff );
            }

            // create last coefficient
            RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
            coeff_last->setRange(0,10000);
            coeff_last->setVal(1);
            coeff_last->setConstant(false);
            list->add( *coeff_last );



            list->Print();

            doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
            //doofit::roofit::pdfs::DooCubicSplinePdf* splinePdf = new doofit::roofit::pdfs::DooCubicSplinePdf("splinePdf", epdf->Var("obsEtaOS"), knots, *list,0,0.5);



     //Koeffizienten
            DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

            epdf->AddRealToStore(coeff_ch);
            epdf->AddRealToStore(coeff_sh);
            epdf->AddRealToStore(coeff_c);
            epdf->AddRealToStore(coeff_s);


    ///////////////////Generiere PDF's/////////////////////
    //Zeit
    epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
    epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));


     //Zusammenfassen der Parameter in einem RooArgSet
     RooArgSet Observables;
     Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));


     epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"),epdf->Real("sig_yield"));



     //Multipliziere Signal und Untergrund PDF mit ihrer jeweiligen Zerfalls PDF//
     //Untergrund * Zerfall
     /*epdf->Product("pdf_bkg", RooArgSet(epdf->Pdf("pdf_bkg_mass_expo"), epdf->Pdf("pdf_bkg_mass_time")));
     //Signal * Zerfall
     epdf->Product("pdf_sig", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss"),epdf->Pdf("pdfSigTime")));
    //Addiere PDF's
     epdf->Add("pdf_total", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss*pdf_sig_time_decay"), epdf->Pdf("pdf_bkg_mass*pdf_bkg_time_decay")), RooArgSet(epdf->Var("bkg_Yield"),epdf->Var("sig_Yield")));*/





     RooWorkspace ws;
                 ws.import(epdf->Pdf("pdfExtend"));
                 ws.defineSet("Observables",Observables, true);

                 ws.Print();

                 doofit::config::CommonConfig cfg_com("common");
                 cfg_com.InitializeOptions(argc, argv);
                 doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
                 cfg_tfac.InitializeOptions(cfg_com);
                 doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
                 cfg_tstudy.InitializeOptions(cfg_tfac);

                 // set a previously defined workspace to get PDF from (not mandatory, but convenient)
                 cfg_tfac.set_workspace(&ws);

                 // Check for a set --help flag and if so, print help and exit gracefully
                 // (recommended).
                 cfg_com.CheckHelpFlagAndPrintHelp();

                 // More custom code, e.g. to set options internally.
                 // Not required as configuration via command line/config file is enough.
                 cfg_com.PrintAll();

                 // Print overview of all options (optional)
                 // cfg_com.PrintAll();

                 // Initialize the toy factory module with the config objects and start
                 // generating toy samples.
                 doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
                 doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);




          RooDataSet* data = tfac.Generate();
          data->Print();
          epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt");
          epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt.new");

          //epdf->Pdf("pdfExtend").fitTo(*data);
          //epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-fit-result.txt");
		      RooFitResult* fit_result = epdf->Pdf("pdfExtend").fitTo(*data, RooFit::Save(true));
       	  tstudy.StoreFitResult(fit_result);

          /*using namespace doofit::plotting;

          PlotConfig cfg_plot("cfg_plot");
          cfg_plot.InitializeOptions();
          cfg_plot.set_plot_directory("/net/lhcb-tank/home/chasenberg/Ergebnis/dootoycp_spline-lhcb/time/");
          // plot PDF and directly specify components
          Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
          myplot.PlotItLogNoLogY();

          PlotConfig cfg_plotEta("cfg_plotEta");
          cfg_plotEta.InitializeOptions();
          cfg_plotEta.set_plot_directory("/net/lhcb-tank/home/chasenberg/Ergebnis/dootoycp_spline-lhcb/eta/");
          // plot PDF and directly specify components
          Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
          myplotEta.PlotIt();*/

 }
コード例 #4
0
ファイル: IntervalExamples.C プロジェクト: Y--/root
void IntervalExamples()
{

   // Time this macro
   TStopwatch t;
   t.Start();


   // set RooFit random seed for reproducible results
   RooRandom::randomGenerator()->SetSeed(3001);

   // make a simple model via the workspace factory
   RooWorkspace* wspace = new RooWorkspace();
   wspace->factory("Gaussian::normal(x[-10,10],mu[-1,1],sigma[1])");
   wspace->defineSet("poi","mu");
   wspace->defineSet("obs","x");

   // specify components of model for statistical tools
   ModelConfig* modelConfig = new ModelConfig("Example G(x|mu,1)");
   modelConfig->SetWorkspace(*wspace);
   modelConfig->SetPdf( *wspace->pdf("normal") );
   modelConfig->SetParametersOfInterest( *wspace->set("poi") );
   modelConfig->SetObservables( *wspace->set("obs") );

   // create a toy dataset
   RooDataSet* data = wspace->pdf("normal")->generate(*wspace->set("obs"),100);
   data->Print();

   // for convenience later on
   RooRealVar* x = wspace->var("x");
   RooRealVar* mu = wspace->var("mu");

   // set confidence level
   double confidenceLevel = 0.95;

   // example use profile likelihood calculator
   ProfileLikelihoodCalculator plc(*data, *modelConfig);
   plc.SetConfidenceLevel( confidenceLevel);
   LikelihoodInterval* plInt = plc.GetInterval();

   // example use of Feldman-Cousins
   FeldmanCousins fc(*data, *modelConfig);
   fc.SetConfidenceLevel( confidenceLevel);
   fc.SetNBins(100); // number of points to test per parameter
   fc.UseAdaptiveSampling(true); // make it go faster

   // Here, we consider only ensembles with 100 events
   // The PDF could be extended and this could be removed
   fc.FluctuateNumDataEntries(false);

   // Proof
   //  ProofConfig pc(*wspace, 4, "workers=4", kFALSE);    // proof-lite
   //ProofConfig pc(w, 8, "localhost");    // proof cluster at "localhost"
   //  ToyMCSampler* toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   //  toymcsampler->SetProofConfig(&pc);     // enable proof

   PointSetInterval* interval = (PointSetInterval*) fc.GetInterval();


   // example use of BayesianCalculator
   // now we also need to specify a prior in the ModelConfig
   wspace->factory("Uniform::prior(mu)");
   modelConfig->SetPriorPdf(*wspace->pdf("prior"));

   // example usage of BayesianCalculator
   BayesianCalculator bc(*data, *modelConfig);
   bc.SetConfidenceLevel( confidenceLevel);
   SimpleInterval* bcInt = bc.GetInterval();

   // example use of MCMCInterval
   MCMCCalculator mc(*data, *modelConfig);
   mc.SetConfidenceLevel( confidenceLevel);
   // special options
   mc.SetNumBins(200);        // bins used internally for representing posterior
   mc.SetNumBurnInSteps(500); // first N steps to be ignored as burn-in
   mc.SetNumIters(100000);    // how long to run chain
   mc.SetLeftSideTailFraction(0.5); // for central interval
   MCMCInterval* mcInt = mc.GetInterval();

   // for this example we know the expected intervals
   double expectedLL = data->mean(*x)
      + ROOT::Math::normal_quantile(  (1-confidenceLevel)/2,1)
      / sqrt(data->numEntries());
   double expectedUL = data->mean(*x)
      + ROOT::Math::normal_quantile_c((1-confidenceLevel)/2,1)
      / sqrt(data->numEntries()) ;

   // Use the intervals
   std::cout << "expected interval is [" <<
      expectedLL << ", " <<
      expectedUL << "]" << endl;

   cout << "plc interval is [" <<
      plInt->LowerLimit(*mu) << ", " <<
      plInt->UpperLimit(*mu) << "]" << endl;

   std::cout << "fc interval is ["<<
      interval->LowerLimit(*mu) << " , "  <<
      interval->UpperLimit(*mu) << "]" << endl;

   cout << "bc interval is [" <<
      bcInt->LowerLimit() << ", " <<
      bcInt->UpperLimit() << "]" << endl;

   cout << "mc interval is [" <<
      mcInt->LowerLimit(*mu) << ", " <<
      mcInt->UpperLimit(*mu) << "]" << endl;

   mu->setVal(0);
   cout << "is mu=0 in the interval? " <<
      plInt->IsInInterval(RooArgSet(*mu)) << endl;


   // make a reasonable style
   gStyle->SetCanvasColor(0);
   gStyle->SetCanvasBorderMode(0);
   gStyle->SetPadBorderMode(0);
   gStyle->SetPadColor(0);
   gStyle->SetCanvasColor(0);
   gStyle->SetTitleFillColor(0);
   gStyle->SetFillColor(0);
   gStyle->SetFrameFillColor(0);
   gStyle->SetStatColor(0);


   // some plots
   TCanvas* canvas = new TCanvas("canvas");
   canvas->Divide(2,2);

   // plot the data
   canvas->cd(1);
   RooPlot* frame = x->frame();
   data->plotOn(frame);
   data->statOn(frame);
   frame->Draw();

   // plot the profile likelihood
   canvas->cd(2);
   LikelihoodIntervalPlot plot(plInt);
   plot.Draw();

   // plot the MCMC interval
   canvas->cd(3);
   MCMCIntervalPlot* mcPlot = new MCMCIntervalPlot(*mcInt);
   mcPlot->SetLineColor(kGreen);
   mcPlot->SetLineWidth(2);
   mcPlot->Draw();

   canvas->cd(4);
   RooPlot * bcPlot = bc.GetPosteriorPlot();
   bcPlot->Draw();

   canvas->Update();

   t.Stop();
   t.Print();

}
コード例 #5
0
ファイル: rf510_wsnamedsets.C プロジェクト: adevress/root-1
void fillWorkspace(RooWorkspace& w) 
{
  // C r e a t e   m o d e l
  // -----------------------

  // Declare observable x
  RooRealVar x("x","x",0,10) ;

  // Create two Gaussian PDFs g1(x,mean1,sigma) anf g2(x,mean2,sigma) and their parameters
  RooRealVar mean("mean","mean of gaussians",5,0,10) ;
  RooRealVar sigma1("sigma1","width of gaussians",0.5) ;
  RooRealVar sigma2("sigma2","width of gaussians",1) ;

  RooGaussian sig1("sig1","Signal component 1",x,mean,sigma1) ;  
  RooGaussian sig2("sig2","Signal component 2",x,mean,sigma2) ;  
  
  // Build Chebychev polynomial p.d.f.  
  RooRealVar a0("a0","a0",0.5,0.,1.) ;
  RooRealVar a1("a1","a1",-0.2,0.,1.) ;
  RooChebychev bkg("bkg","Background",x,RooArgSet(a0,a1)) ;

  // Sum the signal components into a composite signal p.d.f.
  RooRealVar sig1frac("sig1frac","fraction of component 1 in signal",0.8,0.,1.) ;
  RooAddPdf sig("sig","Signal",RooArgList(sig1,sig2),sig1frac) ;

  // Sum the composite signal and background 
  RooRealVar bkgfrac("bkgfrac","fraction of background",0.5,0.,1.) ;
  RooAddPdf  model("model","g1+g2+a",RooArgList(bkg,sig),bkgfrac) ;

  // Import model into p.d.f.
  w.import(model) ;


  // E n c o d e   d e f i n i t i o n   o f   p a r a m e t e r s   i n   w o r k s p a c e
  // ---------------------------------------------------------------------------------------


  // Define named sets "parameters" and "observables", which list which variables should be considered
  // parameters and observables by the users convention
  // 
  // Variables appearing in sets _must_ live in the workspace already, or the autoImport flag
  // of defineSet must be set to import them on the fly. Named sets contain only references
  // to the original variables, therefore the value of observables in named sets already
  // reflect their 'current' value
  RooArgSet* params = (RooArgSet*) model.getParameters(x) ;
  w.defineSet("parameters",*params) ;
  w.defineSet("observables",x) ;


  // E n c o d e   r e f e r e n c e   v a l u e   f o r   p a r a m e t e r s   i n   w o r k s p a c e
  // ---------------------------------------------------------------------------------------------------


  // Define a parameter 'snapshot' in the p.d.f.
  // Unlike a named set, a parameter snapshot stores an independent set of values for
  // a given set of variables in the workspace. The values can be stored and reloaded
  // into the workspace variable objects using the loadSnapshot() and saveSnapshot()
  // methods. A snapshot saves the value of each variable, any errors that are stored
  // with it as well as the 'Constant' flag that is used in fits to determine if a 
  // parameter is kept fixed or not.

  // Do a dummy fit to a (supposedly) reference dataset here and store the results
  // of that fit into a snapshot
  RooDataSet* refData = model.generate(x,10000) ;
  model.fitTo(*refData,PrintLevel(-1)) ;
  
  // The kTRUE flag imports the values of the objects in (*params) into the workspace
  // If not set, the present values of the workspace parameters objects are stored
  w.saveSnapshot("reference_fit",*params,kTRUE) ;

  // Make another fit with the signal componentforced to zero
  // and save those parameters too

  bkgfrac.setVal(1) ;
  bkgfrac.setConstant(kTRUE) ;
  bkgfrac.removeError() ;
  model.fitTo(*refData,PrintLevel(-1)) ;  
  
  w.saveSnapshot("reference_fit_bkgonly",*params,kTRUE) ;
  

}
コード例 #6
0
void hggfitmceerr(double nommass=123., double tgtr=1., int ijob=0) {
    
  //gSystem->cd("/scratch/bendavid/root/bare/fitplotsJun10test/");
  
  int seed = 65539+ijob+1; 
  
  TString dirname = "/scratch/bendavid/root/bare/hggfiteerrtestall_large2/";
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);
  
  
  //nommass=150.;
 // gSystem->cd("/scratch/bendavid/root/bare/fitplotsJun8_150_2x/");
  
  gRandom->SetSeed(seed);
  RooRandom::randomGenerator()->SetSeed(seed);    
  
//   TFile *fin = TFile::Open("/home/mingyang/cms/hist_approval/hgg-2013Moriond/merged/hgg-2013Moriond_s12-h150gg-gf-v7a_noskim.root");
//   TDirectory *hdir = (TDirectory*)fin->FindObjectAny("PhotonTreeWriterPresel");
//   TTree *htree = (TTree*)hdir->Get("hPhotonTree");

//   TFile *fdin = TFile::Open("/home/mingyang/cms/hist/hgg-2013Moriond/merged/hgg-2013Moriond_r12_ABCD.root");
//   TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPresel");
//   TTree *dtree = (TTree*)ddir->Get("hPhotonTree");  
  
  //TCut selcut = "(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)";
  TCut selcut = "(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)";
  //TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut selweight = "xsecweight(procidx)*mcweight*kfact(procidx,ph1.ispromptgen,ph2.ispromptgen)";
  
  TCut sigFcut = "(procidx==0 || procidx==3)";
  TCut sigVcut = "(procidx==1 || procidx==2)";
  
  TCut bkgPPcut = "(procidx==4)";
  TCut bkgPFcut = "(procidx==5 || procidx==6)";
  TCut bkgFFcut = "(procidx==7 || procidx==8)";
  
  
  
  TCut bkgcut = "(procidx>3)";
  TCut bkgcutnoq = "(procidx>3 && procidx<7)";
  
  TCut prescalenone = "(1==1)";
  TCut evenevents = "(evt%2==0)";
  TCut oddevents =  "(evt%2==1)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale50 = "(evt%50==0)";
  TCut prescale100 = "(evt%100==0)";
  
  
  
  TCut fcut = prescale50;  
  
  
  float xsecs[50];

  
  //TCut selcutsingle = "ph.pt>25. && ph.isbarrel && ph.ispromptgen";
  //TCut selcutsingle = "ph.pt>25.&& ph.ispromptgen";
  TCut selcutsingle = "ph.genpt>16.&& ph.ispromptgen";
  TCut selweightsingle = "xsecweight(procidx)";
  
  
//   TChain *tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonMvaMod/JetPub/JetCorrectionMod/SeparatePileUpMod/ElectronIDMod/MuonIDMod/PhotonPairSelectorPresel/PhotonTreeWriterPresel/hPhotonTreeSingle");
//   tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV/merged/hgg-2013Final8TeV_s12-diphoj-v7n_noskim.root");

  TChain *tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonMvaMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle");
  tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV_reg_trans/merged/hgg-2013Final8TeV_reg_trans_s12-pj20_40-2em-v7n_noskim.root");
  tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV_reg_trans/merged/hgg-2013Final8TeV_reg_trans_s12-pj40-2em-v7n_noskim.root");
  
  xsecs[0] = 0.001835*81930.0;
  xsecs[1] = 0.05387*8884.0;
  initweights(tree,xsecs,1.);
  
  double weightscale = xsecweights[1];
  xsecweights[0] /= weightscale;
  xsecweights[1] /= weightscale;  
 
  
  
  tree->SetCacheSize(64*1024*1024);
  
  

  RooRealVar energy("energy","ph.e",0);
  RooRealVar sceta("sceta","ph.sceta",0.);
  RooRealVar idmva("idmva","ph.idmva",0.,-1.,1.);  
  RooRealVar eerr("eerr","(ph.isbarrel + 0.5*!ph.isbarrel)*ph.eerr/ph.e",0.);
  RooRealVar evt("evt","evt",0.);
  
  
  RooArgList vars;
  vars.add(energy);
  vars.add(sceta);
  //vars.add(idmva);
  
  
  RooArgList condvars(vars);
  
  vars.add(eerr);  
  
  RooArgList condvarsid(vars);
  
  vars.add(idmva);
  vars.add(evt);
  

//   RooPowerLaw("testpow","",pt1,pt2);
//   return;
  

//    new TCanvas;
//    tree->Draw("mass>>htmpall(80,100.,180.)",bkgcut*selcut*selweight,"HIST");
// 
//    new TCanvas;
//    tree->Draw("mass>>htmpallid(80,100.,180.)",idcut*bkgcut*selcut*selweight,"HIST");   
//    
//    new TCanvas;
//    tree->Draw("mass>>htmp(80,100.,180.)",bkgcutnoq*selcut*selweight,"HIST");   
// //   
//    return;
    
  
  
  //RooRealVar weightvar("weightvar","(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2 && evt%100!=0)",1.);
  RooRealVar weightvar("weightvar","",1.);
  //RooRealVar weightvar("weightvar","(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)",1.);
  
  weightvar.SetTitle(selcutsingle*selweightsingle);
  RooDataSet *hdataSingle = RooTreeConvert::CreateDataSet("hdataSingle",tree,vars,weightvar);    
  
  int ngauseerr = 4;
  //int nparmseerr = 3*ngauseerr + 2;
  //int nparmseerr = 3*ngauseerr + 2;
  int nparmseerr = 5*ngauseerr;
  
  RooArgList tgtseerr;
  RooGBRFunction funceerr("funceerr","",condvars,nparmseerr);
 
  int iparmeerr = 0;  
  
  
  RooArgList eerrgauspdfs;
  RooArgList eerrgauscoeffs;
  
  double stepeerr = 0.07/double(std::max(1,ngauseerr-1));
  
//    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_eerr_%i",0),"",0.007+stepeerr*0);
//    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_eerr_%i",0),"",0.01);
// //   //RooRealVar *gsigmaRvar = new RooRealVar(TString::Format("gsigmaRvar_eerr_%i",0),"",0.02);
// //   
// //   //if (0==0) gmeanvar->setVal(0.007);
// //   
//    gmeanvar->setConstant(false);
//    gsigmavar->setConstant(false);
// //   //gsigmaRvar->setConstant(false);
// //   
// //   
//    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_eerr_%i",0),"",funceerr,iparmeerr++,*gmeanvar);
//    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_eerr_%i",0),"",funceerr,iparmeerr++,*gsigmavar);
// //   //RooGBRTarget *gsigmaR = new RooGBRTarget(TString::Format("gsigmaR_eerr_%i",0),"",funceerr,iparmeerr++,*gsigmaRvar);
// // 
//    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_eerr_%i",0),"",*gmean,0.,0.5);   
//    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_eerr_%i",0),"",*gsigma,1e-7,0.5);
//   //RooRealConstraint *gsigmaRlim = new RooRealConstraint(TString::Format("gsigmaRlim_eerr_%i",0),"",*gsigmaR,1e-7,0.2);  
//   
//   tgtseerr.add(*gmean);
//   tgtseerr.add(*gsigma);
  
  for (int igaus=0; igaus<ngauseerr; ++igaus) {
    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_eerr_%i",igaus),"",0.007+stepeerr*igaus);
    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_eerr_%i",igaus),"",0.01);
    RooRealVar *galphavar = new RooRealVar(TString::Format("galphavar_eerr_%i",igaus),"",1.0);
    RooRealVar *gnvar = new RooRealVar(TString::Format("gnvar_eerr_%i",igaus),"",2.);    
    RooRealVar *gfracvar = new RooRealVar(TString::Format("gfracvar_eerr_%i",igaus),"",1.0);  
    
    //if (igaus==0) gmeanvar->setVal(0.007);
    
    gmeanvar->setConstant(false);
    gsigmavar->setConstant(false);
    galphavar->setConstant(false);
    gnvar->setConstant(false);    
    gfracvar->setConstant(false);
    
    
    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_eerr_%i",igaus),"",funceerr,iparmeerr++,*gmeanvar);
    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_eerr_%i",igaus),"",funceerr,iparmeerr++,*gsigmavar);
    RooGBRTarget *galpha = new RooGBRTarget(TString::Format("galpha_eerr_%i",igaus),"",funceerr,iparmeerr++,*galphavar);
    RooGBRTarget *gn = new RooGBRTarget(TString::Format("gn_eerr_%i",igaus),"",funceerr,iparmeerr++,*gnvar);    
    RooGBRTarget *gfrac = new RooGBRTarget(TString::Format("gfrac_eerr_%i",igaus),"",funceerr,iparmeerr++,*gfracvar);

    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_eerr_%i",igaus),"",*gmean,0.,0.5);   
    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_eerr_%i",igaus),"",*gsigma,1e-5,0.1);
    RooRealConstraint *galphalim = new RooRealConstraint(TString::Format("galphalim_eerr_%i",igaus),"",*galpha,0.05,8.);
    RooRealConstraint *gnlim = new RooRealConstraint(TString::Format("gnlim_eerr_%i",igaus),"",*gn,1.01,5000.);
    //RooRealConstraint *gfraclim = new RooRealConstraint(TString::Format("gfraclim_eerr_%i",igaus),"",*gfrac,0.,1.);
    RooAbsReal *gfraclim = new RooProduct(TString::Format("gfraclim_eerr_%i",igaus),"",RooArgList(*gfrac,*gfrac));
 
    
    if (igaus==0) {
      gfraclim = new RooConstVar(TString::Format("gfraclimconst_eerr_%i",igaus),"",1.);
    }
    else {
      tgtseerr.add(*gfrac);   
    }
    
    //RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim);
    //RooBifurGauss *gpdf = new RooBifurGauss(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim,*galphalim);
    
    
    if (igaus==0) {
      RooRevCBFast *gpdf = new RooRevCBFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim,*galphalim, *gnlim);
    
      tgtseerr.add(*gmean);
      tgtseerr.add(*gsigma);
      tgtseerr.add(*galpha);
      tgtseerr.add(*gn);
      
      eerrgauspdfs.add(*gpdf);      
    
    }
    else {
      RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim);
    
      tgtseerr.add(*gmean);
      tgtseerr.add(*gsigma);
      
      eerrgauspdfs.add(*gpdf);

    }      
      
    
    eerrgauscoeffs.add(*gfraclim);    
    
  }
  RooCondAddPdf eerrpdf("eerrpdf","",eerrgauspdfs,eerrgauscoeffs);  
  
  
  RooAbsPdf *pdf0 = static_cast<RooAbsPdf*>(eerrgauspdfs.at(0));
  
  
  int ngaus = 6;
  int nparms = 4*ngaus;
  
  RooArgList tgtsid;
  RooGBRFunction funcid("funcid","",condvarsid,nparms);  
  
  RooArgList gauspdfs;
  RooArgList gauscoeffs;
  
  double step = 0.5/double(std::max(1,ngaus-1));
  
  int iparm = 0;
  for (int igaus=0; igaus<ngaus; ++igaus) {
    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_%i",igaus),"",-0.2+step*igaus);
    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_%i",igaus),"",0.1);
    RooRealVar *gsigmaRvar = new RooRealVar(TString::Format("gsigmaRvar_%i",igaus),"",0.1);
    RooRealVar *gfracvar = new RooRealVar(TString::Format("gfracvar_%i",igaus),"",1.0);  
    
    gmeanvar->setConstant(false);
    gsigmavar->setConstant(false);
    gsigmaRvar->setConstant(false);
    gfracvar->setConstant(false);
    
    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_%i",igaus),"",funcid,iparm++,*gmeanvar);
    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_%i",igaus),"",funcid,iparm++,*gsigmavar);
    RooGBRTarget *gsigmaR = new RooGBRTarget(TString::Format("gsigmaR_%i",igaus),"",funcid,iparm++,*gsigmaRvar);
    RooGBRTarget *gfrac = new RooGBRTarget(TString::Format("gfrac_%i",igaus),"",funcid,iparm++,*gfracvar);

    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_%i",igaus),"",*gmean,-1.,1.);   
    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_%i",igaus),"",*gsigma,1e-4,2.);
    RooRealConstraint *gsigmaRlim = new RooRealConstraint(TString::Format("gsigmaRlim_%i",igaus),"",*gsigmaR,1e-4,2.);
    //RooRealConstraint *gfraclim = new RooRealConstraint(TString::Format("gfraclim_%i",igaus),"",*gfrac,0.,1.);
    
    RooAbsReal *gfraclim = new RooProduct(TString::Format("gfraclim_%i",igaus),"",RooArgList(*gfrac,*gfrac));
 
    
    if (igaus==0) {
      gfraclim = new RooConstVar(TString::Format("gfraclimconst_%i",igaus),"",1.);
    }
    else {
      tgtsid.add(*gfrac);   
    }    
    
    
    RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_%i",igaus),"",idmva,*gmeanlim,*gsigmalim);
    //RooBifurGauss *gpdf = new RooBifurGauss(TString::Format("gdf_%i",igaus),"",idmva,*gmeanlim,*gsigmalim,*gsigmaRlim);
    
    gauspdfs.add(*gpdf);
    gauscoeffs.add(*gfraclim);
    
    tgtsid.add(*gmean);
    tgtsid.add(*gsigma);
    //tgtsid.add(*gsigmaR);
    //tgtsid.add(*gfrac);    
  }
  RooCondAddPdf idpdf("idpdf","",gauspdfs,gauscoeffs);
  
  RooConstVar etermconst("etermconst","",0.);  
  RooAbsReal &eterm = etermconst;
  RooRealVar dummy("dummy","",1.0);
   

  std::vector<RooAbsData*> vdata;
  vdata.push_back(hdataSingle);

  
  std::vector<RooAbsReal*> vpdf;
  vpdf.push_back(&eerrpdf);
  //vpdf.push_back(pdf0);

  std::vector<RooAbsReal*> vpdfid;
  vpdfid.push_back(&idpdf);  
 
  
  RooHybridBDTAutoPdf bdtpdf("bdtpdf","",funceerr,tgtseerr,eterm,dummy,vdata,vpdf);
  bdtpdf.SetPrescaleInit(100);
  bdtpdf.SetMinCutSignificance(5.0);
  bdtpdf.SetShrinkage(0.1);
  bdtpdf.SetMinWeightTotal(200.);
  bdtpdf.SetMaxNodes(200);
  bdtpdf.TrainForest(1e6);   
  
  RooHybridBDTAutoPdf bdtpdfid("bdtpdfid","",funcid,tgtsid,eterm,dummy,vdata,vpdfid);
  bdtpdfid.SetPrescaleInit(100);
  bdtpdfid.SetMinCutSignificance(5.0);
  bdtpdfid.SetShrinkage(0.1);
  bdtpdfid.SetMinWeightTotal(200.);
  bdtpdfid.SetMaxNodes(200);
  bdtpdfid.TrainForest(1e6);    
  
  
  RooAbsReal *finalcdferr = eerrpdf.createCDF(eerr);
  
  RooFormulaVar transerr("transerr","","sqrt(2.)*TMath::ErfInverse(2.*@0-1.)",*finalcdferr);
  


  RooAbsReal *finalcdfid = idpdf.createCDF(idmva);
  
  RooFormulaVar transid("transid","","sqrt(2.)*TMath::ErfInverse(2.*@0-1.)",*finalcdfid);
  
  
  RooWorkspace *wsout = new RooWorkspace("wsfiteerr");
  wsout->import(*hdataSingle);
  
  wsout->import(eerrpdf,RecycleConflictNodes());
  wsout->import(idpdf,RecycleConflictNodes());
//   wsout->import(transerr,RecycleConflictNodes());
//   wsout->import(transid,RecycleConflictNodes());
  
  wsout->defineSet("datavars",vars,true);
    
  wsout->writeToFile("hggfiteerr.root");  
  
  
    
  
  RooRealVar *cdfidvar = (RooRealVar*)hdataSingle->addColumn(*finalcdfid);    
  RooRealVar *transidvar = (RooRealVar*)hdataSingle->addColumn(transid);
    
  RooGaussianFast unormpdfid("unormpdfid","",*transidvar,RooConst(0.),RooConst(1.));    

  RooRealVar *cdferrvar = (RooRealVar*)hdataSingle->addColumn(*finalcdferr);    
  RooRealVar *transerrvar = (RooRealVar*)hdataSingle->addColumn(transerr);
    
  RooGaussianFast unormpdferr("unormpdferr","",*transerrvar,RooConst(0.),RooConst(1.));    
  
  
  //RooDataSet *testdata = (RooDataSet*)hdataSingle->reduce("abs(sceta)>1.3 && abs(sceta)<1.4");
  RooDataSet *testdata = hdataSingle;
    
  
  new TCanvas;
  RooPlot *eerrplot = eerr.frame(0.,0.1,200);
  testdata->plotOn(eerrplot);
  eerrpdf.plotOn(eerrplot,ProjWData(*testdata));
  eerrplot->Draw();    
  

  
  new TCanvas;
  RooPlot *transplot = transerrvar->frame(-5.,5.,100);
  hdataSingle->plotOn(transplot);
  unormpdferr.plotOn(transplot);
  transplot->Draw();
  //return;
  
  new TCanvas;
  RooPlot *cdfploterr = cdferrvar->frame(0.,1.,100);
  hdataSingle->plotOn(cdfploterr);
  //unormpdf.plotOn(transplot);
  cdfploterr->Draw();
  //return;    
  
  
  
  new TCanvas;
  RooPlot *idplot = idmva.frame(-1.,1.,200);
  testdata->plotOn(idplot);
  idpdf.plotOn(idplot,ProjWData(*testdata));
  idplot->Draw();  
  

  
  new TCanvas;
  RooPlot *transplotid = transidvar->frame(-5.,5.,100);
  testdata->plotOn(transplotid);
  unormpdfid.plotOn(transplotid);
  transplotid->Draw();
  //return;
  
  new TCanvas;
  RooPlot *cdfplotid = cdfidvar->frame(0.,1.,100);
  testdata->plotOn(cdfplotid);
  //unormpdf.plotOn(transplot);
  cdfplotid->Draw();
  //return;        
  

  TH1 *herrid = testdata->createHistogram("herrid",eerr,Binning(30,0.,0.1), YVar(idmva,Binning(30,-0.5,0.6)));
  TH1 *herre = testdata->createHistogram("herre",energy,Binning(30,0.,200.), YVar(eerr,Binning(30,0.,0.1)));
  TH1 *hideta = testdata->createHistogram("hideta",sceta,Binning(40,-2.5,2.5), YVar(idmva,Binning(30,-0.5,0.6)));

  TH1 *herridtrans = testdata->createHistogram("herridtrans",*transerrvar,Binning(30,-5.,5.), YVar(*transidvar,Binning(30,-5.,5.)));
  TH1 *herrtranse = testdata->createHistogram("herrtranse",energy,Binning(30,0.,200.), YVar(*transerrvar,Binning(30,-5.,5.)));
  TH1 *hidtranseta = testdata->createHistogram("hidtranseta",sceta,Binning(40,-2.5,2.5), YVar(*transidvar,Binning(30,-5.,5.)));  

  new TCanvas;
  herrid->Draw("COLZ");

  new TCanvas;
  herre->Draw("COLZ");
  
  new TCanvas;
  hideta->Draw("COLZ");    
  
  
  new TCanvas;
  herridtrans->Draw("COLZ");

  new TCanvas;
  herrtranse->Draw("COLZ");
  
  new TCanvas;
  hidtranseta->Draw("COLZ");  
  

  
//   new TCanvas;
//   RooRealVar *meanvar = (RooRealVar*)hdataSingle->addColumn(eerrmeanlim);
//   RooPlot *meanplot = meanvar->frame(0.,0.1,200);
//   hdataSingle->plotOn(meanplot);
//   meanplot->Draw();
  

  return;
  
}
コード例 #7
0
ファイル: runBATCalculator.C プロジェクト: Kaoschuks/bat
void runBATCalculator()
{
    // Definiton of a RooWorkspace containing the statistics model. Later the
    // information for BATCalculator is retrieved from the workspace. This is
    // certainly a bit of overhead but better from an educative point of view.
    cout << "preparing the RooWorkspace object" << endl;

    RooWorkspace* myWS = new RooWorkspace("myWS", true);

    // combined prior for signal contribution
    myWS->factory("Product::signal({sigma_s[0,20],L[5,15],epsilon[0,1]})");
    myWS->factory("N_bkg[0,3]");
    // define prior functions
    // uniform prior for signal crosssection
    myWS->factory("Uniform::prior_sigma_s(sigma_s)");
    // (truncated) prior for efficiency
    myWS->factory("Gaussian::prior_epsilon(epsilon,0.51,0.0765)");
    // (truncated) Gaussian prior for luminosity
    myWS->factory("Gaussian::prior_L(L,10,1)");
    // (truncated) Gaussian prior for bkg crosssection
    myWS->factory("Gaussian::prior_N_bkg(N_bkg,0.52,0.156)");

    // Poisson distribution with mean signal+bkg
    myWS->factory("Poisson::model(n[0,300],sum(signal,N_bkg))");

    // define the global prior function
    myWS->factory("PROD::prior(prior_sigma_s,prior_epsilon,prior_L,prior_N_bkg)");

    // Definition of observables and parameters of interest
    myWS->defineSet("obsSet", "n");
    myWS->defineSet("poiSet", "sigma_s");
    myWS->defineSet("nuisanceSet", "N_bkg,L,epsilon");

    // ->model complete (Additional information can be found in the
    // RooStats manual)

    //  feel free to vary the parameters, but don't forget to choose reasonable ranges for the
    // variables. Currently the Bayesian methods will often not work well if the variable ranges
    // are either too short (for obvious reasons) or too large (for technical reasons).

    // A ModelConfig object is used to associate parts of your workspace with their statistical
    // meaning (it is also possible to initialize BATCalculator directly with elements from the
    // workspace but if you are sharing your workspace with others or if you want to use several
    // different methods the use of ModelConfig will most often turn out to be the better choice.)

    // setup the ModelConfig object
    cout << "preparing the ModelConfig object" << endl;

    ModelConfig modelconfig("modelconfig", "ModelConfig for this example");
    modelconfig.SetWorkspace(*myWS);

    modelconfig.SetPdf(*(myWS->pdf("model")));
    modelconfig.SetParametersOfInterest(*(myWS->set("poiSet")));
    modelconfig.SetPriorPdf(*(myWS->pdf("prior")));
    modelconfig.SetNuisanceParameters(*(myWS->set("nuisanceSet")));
    modelconfig.SetObservables(*(myWS->set("obsSet")));


    // use BATCalculator to the derive credibility intervals as a function of the observed number of
    // events in the hypothetical experiment

    // define vector with tested numbers of events
    TVectorD obsEvents;
    // define vectors which will be filled with the lower and upper limits for each tested number
    // of observed events
    TVectorD BATul;
    TVectorD BATll;

    // fix upper limit of tested observed number of events
    int obslimit = 10;

    obsEvents.ResizeTo(obslimit);
    BATul.ResizeTo(obslimit);
    BATll.ResizeTo(obslimit);


    cout << "starting the calculation of Bayesian credibility intervals with BATCalculator" << endl;
    // loop over observed number of events in the hypothetical experiment
    for (int obs = 1; obs <= obslimit; obs++) {

        obsEvents[obs - 1] = (static_cast<double>(obs));

        // prepare data input for the the observed number of events
        // adjust number of observed events in the workspace. This is communicated to ModelConfig!
        myWS->var("n")->setVal(obs);
        // create data
        RooDataSet data("data", "", *(modelconfig.GetObservables()));
        data.add( *(modelconfig.GetObservables()));

        // prepare BATCalulator
        BATCalculator batcalc(data, modelconfig);

        // give the BATCalculator a unique name (always a good idea in ROOT)
        TString namestring = "mybatc_";
        namestring += obs;
        batcalc.SetName(namestring);

        // fix amount of posterior probability in the calculated interval.
        // the name confidence level is incorrect here
        batcalc.SetConfidenceLevel(0.90);

        // fix length of the Markov chain. (in general: the longer the Markov chain the more
        // precise will be the results)
        batcalc.SetnMCMC(20000);

        // retrieve SimpleInterval object containing the information about the interval (this
        // triggers the actual calculations)
        SimpleInterval* interval = batcalc.GetInterval1D("sigma_s");

        std::cout << "BATCalculator: 90% credibility interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or 95% credibility upper limit\n";

        // add the interval borders for the current number of observed events to the vectors
        // containing the lower and upper limits
        BATll[obs - 1] = interval->LowerLimit();
        BATul[obs - 1] = interval->UpperLimit();

        // clean up for next loop element
        batcalc.CleanCalculatorForNewData();
        delete interval;
    }
    cout << "all limits calculated" << endl;

    // summarize the results in a plot

    TGraph* grBATll = new TGraph(obsEvents, BATll);
    grBATll->SetLineColor(kGreen);
    grBATll->SetLineWidth(200);
    grBATll->SetFillStyle(3001);
    grBATll->SetFillColor(kGreen);

    TGraph* grBATul = new TGraph(obsEvents, BATul);
    grBATul->SetLineColor(kGreen);
    grBATul->SetLineWidth(-200);
    grBATul->SetFillStyle(3001);
    grBATul->SetFillColor(kGreen);

    // create and draw multigraph
    TMultiGraph* mg = new TMultiGraph("BayesianLimitsBATCalculator", "BayesianLimitsBATCalculator");
    mg->SetTitle("example of Bayesian credibility intervals derived with BATCAlculator ");

    mg->Add(grBATll);
    mg->Add(grBATul);

    mg->Draw("AC");

    mg->GetXaxis()->SetTitle ("# observed events");
    mg->GetYaxis()->SetTitle("limits on signal S (size of test: 0.1)");

    mg->Draw("AC");
}
void retrieve_input_from_histo(RooWorkspace &w){



// Variable definition
   /*
  */

/*********  GLOBAL VARIABLES   ********************/

/*   Default ---
  double Bkg_norm_factor_obs  	= 0.5 ;		// Normalizzation factor for background (N_Data_CR / N_Co_CR)
  double err_Norm_factor_obs  	= 0.05;
  double S_tot 			= 1000.;	// Total events in SR for AmBe
  double B_tot 			= 10000.;	// Total events in SR for Co60
  double Acceptance_SR_obs	= 0.9;		// Cut Acceptance for Signal
  double err_Acceptance_SR 	= 0.01;
  double N_tot_theory 		= 5.;  	   	// Total Expected Signal Events for a given mass and Xsec.
   */

  double Bkg_norm_factor_obs  	= 0.0378 ;	// Normalizzation factor for background (N_Data_CR / N_Co_CR)
  double err_Norm_factor_obs  	= 0.0013;
  double S_tot 			= 123552;	// Total events in ALL REGIONS for AmBe (--> the Eff_i are the efficiencies relative to the total)
  double B_tot 			= 24318;	// Total events in SR for Co60
  double Acceptance_SR_obs	= 0.9;		// Cut Acceptance for Signal
  double err_Acceptance_SR 	= 0.05;
  double N_tot_theory 		= 10.;  	// Total Expected Signal Events for a given mass and Xsec. Set to 10 because gives mu in range [0.,100]
/**************************************************/  



//---- retrieving global variables ----//
  TFile *histos  = TFile::Open("h_for_limits.root");
  TH1D  *h_ambe_SR = (TH1D*)histos->Get("ambe_SR");
  TH1D  *h_co60_SR = (TH1D*)histos->Get("co60_SR");
  TH1D  *h_DM_SR = (TH1D*)histos->Get("DM_SR");




//----- Model for Global Variables  -----//
   w.factory("N_tot_theory[10]");
   w.factory("Acceptance_SR[0.9,0.0,1]");
   w.factory("mu[1.,0.,100]");
   w.factory("Bkg_norm_factor[0.7, 0.0,10.0]");
   w.factory("S_tot[1000.0]");


   w.factory("Gaussian:costraint_bkg_norm(Bkg_norm_factor_obs[0,10], Bkg_norm_factor, err_Norm_factor[1])"); // approximation (should be kind of complicated cauchy....)
   w.factory("Gaussian:costarint_sig_acc(Acceptance_SR_obs[0,1], Acceptance_SR, err_Acceptance_SR[0.01])");// this has the problem of boundaries acceptance cannot be larger than 1.  --->Lognormal???

   RooArgSet nuissanceParameter ;//(*w.var("Bkg_norm_factor"),*w.var("Acceptance_SR"));
   RooArgSet g_obs(*w.var("Bkg_norm_factor_obs"), *w.var("Acceptance_SR_obs"));
   RooArgSet obs;

//----- Setting Value to Global Variables ------//
   w.var("N_tot_theory")->setVal(N_tot_theory); 		// Total expected Signal events
   w.var("Bkg_norm_factor_obs")->setVal(Bkg_norm_factor_obs); 	// Ratio between data in CR and Co in CR
   w.var("err_Norm_factor")->setVal(err_Norm_factor_obs); 	// Set error on norm factor
   w.var("Acceptance_SR_obs")->setVal(Acceptance_SR_obs); 
   w.var("err_Acceptance_SR")->setVal(err_Acceptance_SR);
   w.var("S_tot")->setVal(S_tot); 				// Total events of AmBe in SR 

   w.var("N_tot_theory")->setConstant(true); 
   w.var("S_tot")->setConstant(true); 
   w.var("Bkg_norm_factor_obs")->setConstant(true); 
   w.var("err_Norm_factor")->setConstant(true); 
   w.var("Acceptance_SR_obs")->setConstant(true); 
   w.var("err_Acceptance_SR")->setConstant(true); 

//-------- Setting Value of NP to Observed!!   ---------------//
   w.var("Acceptance_SR")->setVal(w.var("Acceptance_SR_obs")->getValV());
   w.var("Acceptance_SR")->setMax(w.var("Acceptance_SR_obs")->getValV() + w.var("err_Acceptance_SR")->getValV() * 10.);// Set to 10 sigma.
   w.var("Bkg_norm_factor")->setMax(w.var("Bkg_norm_factor_obs")->getValV() + w.var("err_Norm_factor")->getValV()*10.); //set to 10 sigma.
   w.var("Bkg_norm_factor")->setVal(w.var("Bkg_norm_factor_obs")->getValV());// Set to observed value!!!

  //--- Set NP to constant!!!  ONLY FOR TEST!!
   w.var("Acceptance_SR")->setConstant(true);
   w.var("Bkg_norm_factor")->setConstant(true);
  
  
  TString total_model = "PROD:model(";

  //bin-auxiliary measure variables
  double S_bin = 0.;
  double B_bin =0.;
  double nobs_bin =0.;
  
 /*****************  LOOP OVER  BINS   *******************/
  for (int bin_itr = 1; bin_itr <= h_ambe_SR->GetNbinsX() ; bin_itr++){


   //retrieve bin info
  /*  Default
   S_bin = 500.;   // Observed events in bin_i for AmBe
   B_bin = 100.;   // Observed events in bin_i for Co60
   nobs_bin = 45.; // Observed events in bin_i for DM data
   */
   S_bin    = h_ambe_SR->GetBinContent(bin_itr);   // Observed events in bin_i for AmBe
   B_bin    = h_co60_SR->GetBinContent(bin_itr);   // Observed events in bin_i for Co60
   nobs_bin = h_DM_SR->GetBinContent(bin_itr); // Observed events in bin_i for DM data

   TString bin_name(TString::Itoa(bin_itr, 10));

   w.factory("prod:N_s_"+bin_name+"(N_tot_theory, Acceptance_SR, Eff_AmBe_bin_"+bin_name+"[0.01,0.0,1], mu)");
   w.factory("prod:N_b_"+bin_name+"(N_Co_SR_bin_"+bin_name+"[100.0,0.0,1000.0], Bkg_norm_factor)"); 
   w.factory("sum:nexp_"+bin_name+"(N_s_"+bin_name+", N_b_"+bin_name+")");
// Poisson of (n | s+b)
   w.factory("Poisson:pdf_"+bin_name+"(nobs_"+bin_name+"[0.0,1000.0],nexp_"+bin_name+")");


// Poisson constraint --- Stat uncertainty on the bin content
   w.factory("prod:S_"+bin_name+"_exp(S_tot, Eff_AmBe_bin_"+bin_name+")");   // put 1000. to right AmBe amount
   w.factory("Poisson:AmBe_bin_"+bin_name+"(S_"+bin_name+"[500,0.0,50000.0],S_"+bin_name+"_exp)");  // change 50 for multiple bin, put 1000. to right AmBe amount
   w.factory("Poisson:Co_SR_bin_"+bin_name+"(B_"+bin_name+"[0.0,1000.0], N_Co_SR_bin_"+bin_name+")");  //change 100 for multiple bin, put 1000. to right Co tot amount in SR

   w.factory("PROD:model_"+bin_name+"(pdf_"+bin_name+",AmBe_bin_"+bin_name+",Co_SR_bin_"+bin_name+")");
// Set input variables -- Global OBSERVABLESerr_Norm_factor
   w.var("S_"+bin_name)->setMax(w.var("S_tot")->getValV());  // the range of the poisson needs to be defined
   w.var("S_"+bin_name)->setVal(S_bin); 	  		//  Events in bin i for AmBe

   w.var("B_"+bin_name)->setMax(B_tot);  // set to TOT Co in SR
   w.var("B_"+bin_name)->setVal(B_bin);    // Set observed event in SR Co
 
   w.var("S_"+bin_name)->setConstant(true); 
   w.var("B_"+bin_name)->setConstant(true); 


// Set range and value for nuissance parameters
   w.var("N_Co_SR_bin_"+bin_name)->setMax(B_bin + sqrt(B_bin)*10.); //set to 10 sigma.
   w.var("N_Co_SR_bin_"+bin_name)->setVal(B_bin);  		// set to observed value!!
   w.var("Eff_AmBe_bin_"+bin_name)->setVal(S_bin/ S_tot ); // Set to observed value!!!
   w.var("Eff_AmBe_bin_"+bin_name)->setMax( (S_bin + sqrt(S_bin)*10.) / S_tot ); // Set to observed value!!!
   if(w.var("Eff_AmBe_bin_"+bin_name)->getMax() > 1.) cout << "WARNING!!! Eff_AmBe_bin_"+bin_name+" efficiency > 1. " << endl;

   // Set NP to constant
   w.var("N_Co_SR_bin_"+bin_name)->setConstant(true);
   w.var("Eff_AmBe_bin_"+bin_name)->setConstant(true);

//Set Observed events!
   w.var("nobs_"+bin_name)->setVal(nobs_bin);

   // Do not Add NP !!!
//   nuissanceParameter.add(*w.var("N_Co_SR_bin_"+bin_name));
//   nuissanceParameter.add(*w.var("Eff_AmBe_bin_"+bin_name));
   g_obs.add(*w.var("S_"+bin_name));
   g_obs.add(*w.var("B_"+bin_name));

   obs.add(*w.var("nobs_"+bin_name));

   total_model.Append("model_"+bin_name+", ");

} 
/************************************************************************/

total_model.Append("costraint_bkg_norm, costarint_sig_acc)");

w.factory(total_model);

w.defineSet("nuissance_parameter",nuissanceParameter);
w.defineSet("observables",obs);
w.defineSet("g_observables",g_obs);


histos->Close();

  // RooArgSet set = w.allPdfs();
//   set.Print();
// Set input Observables
//  w.var("nobs_"+bin_name+"")->setVal(40);

/*   // various printing
   w.pdf("AmBe_bin_i")->Print("all");

// Building the model
   ModelConfig mc("ModelConfig",&w);
   mc.SetPdf(*w.pdf("model"));
   mc.SetParametersOfInterest(*w.var("mu"));
   //mc.SetPriorPdf(*w.pdf("prior_s"));

// Setting nuissance parameter
   RooArgSet nuissanceParameter (*w.var("Bkg_norm_factor"),*w.var("Acceptance_SR"));
   nuissanceParameter.add(*w.var("N_Co_SR_bin_i"));
   nuissanceParameter.add(*w.var("Eff_AmBe_bin_i"));
   mc.SetNuisanceParameters(nuissanceParameter);

// need now to set the global observable
   RooArgSet g_obs(*w.var("S_i"), *w.var("B_i"));
//   g_obs.add(*w.var("N_tot_theory"));
//   g_obs.add(*w.var("S_tot"));
   g_obs.add(*w.var("Bkg_norm_factor_obs"));
//   g_obs.add(*w.var("err_Norm_factor"));
   g_obs.add(*w.var("Acceptance_SR_obs"));
//   g_obs.add(*w.var("err_Acceptance_SR"));
   mc.SetGlobalObservables(g_obs);

   RooArgSet observables(*w.var("nobs_i"));
   //observables.add(variousbins...);
   mc.SetObservables(observables);


// this is needed for the hypothesis tests
   mc.SetSnapshot(*w.var("mu"));


// make data set with the number of observed events
RooDataSet data("data","", observables);
data.add(observables);

// import data set in workspace and save it in a file
   w.import(data);

// import model in the workspace 
   w.import(mc);

   w.writeToFile("CountingModel.root", true);
*/


}
コード例 #9
0
int main(int argc, char* argv[]) {

 doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

    

 epdf->Var("sig_yield");
 epdf->Var("sig_yield").setVal(153000);
 epdf->Var("sig_yield").setConstant(false);
 //decay time
 epdf->Var("obsTime");
 epdf->Var("obsTime").SetTitle("t_{#kern[-0.2]{B}_{#kern[-0.1]{ d}}^{#kern[-0.1]{ 0}}}");
 epdf->Var("obsTime").setUnit("ps");
 epdf->Var("obsTime").setRange(0.,16.);

 // tag, respectively the initial state of the produced B meson
 epdf->Cat("obsTag");
 epdf->Cat("obsTag").defineType("B_S",1);
 epdf->Cat("obsTag").defineType("Bbar_S",-1);

  //finalstate
  epdf->Cat("catFinalState");
  epdf->Cat("catFinalState").defineType("f",1);
  epdf->Cat("catFinalState").defineType("fbar",-1);

  epdf->Var("obsEtaOS");
  epdf->Var("obsEtaOS").setRange(0.0,0.5);


  std::vector<double> knots;
    knots.push_back(0.07);
    knots.push_back(0.10);
    knots.push_back(0.138);
    knots.push_back(0.16);
    knots.push_back(0.23);
    knots.push_back(0.28);
    knots.push_back(0.35);
    knots.push_back(0.42);
    knots.push_back(0.44);
    knots.push_back(0.48);
    knots.push_back(0.5);

  // empty arg list for coefficients
  RooArgList* list = new RooArgList();

  // create first coefficient
  RooRealVar* coeff_first = &(epdf->Var("parCSpline1"));
  coeff_first->setRange(0,10000);
  coeff_first->setVal(1);
  coeff_first->setConstant(false);
  list->add( *coeff_first );

  for (unsigned int i=1; i <= knots.size(); ++i){
    std::string number = boost::lexical_cast<std::string>(i);
    RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
    coeff->setRange(0,10000);
    coeff->setVal(1);
    coeff->setConstant(false);
    list->add( *coeff );
    }
  
  // create last coefficient
  RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
  coeff_last->setRange(0,10000);
  coeff_last->setVal(1);
  coeff_last->setConstant(false);
  list->add( *coeff_last );
  list->Print();
  // define Eta PDF
  doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
  
  //Berechne die Tagging Assymetrie
  epdf->Var("p0");
  epdf->Var("p0").setVal(0.369);
  epdf->Var("p0").setConstant(true);

  epdf->Var("p1");
  epdf->Var("p1").setVal(0.952);
  epdf->Var("p1").setConstant(true);

  epdf->Var("delta_p0");
  epdf->Var("delta_p0").setVal(0.019);
  epdf->Var("delta_p0").setConstant(true);

  epdf->Var("delta_p1");
  epdf->Var("delta_p1").setVal(-0.012);
  epdf->Var("delta_p1").setConstant(true);

  epdf->Var("etamean");
  epdf->Var("etamean").setVal(0.365);
  epdf->Var("etamean").setConstant(true);

  epdf->Formula("omega","@0 +@1/2 +(@2+@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
  epdf->Formula("omegabar","@0 -@1/2 +(@2-@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
      


  //Koeffizienten
  DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_ch);
  epdf->AddRealToStore(coeff_sh);
  epdf->AddRealToStore(coeff_c);
  epdf->AddRealToStore(coeff_s);

  ///////////////////Generiere PDF's/////////////////////
  //Zeit
  epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
  epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));

  //Zusammenfassen der Parameter in einem RooArgSet
  RooArgSet Observables;
  Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));

  epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"),epdf->Real("sig_yield"));

  RooWorkspace ws;
    ws.import(epdf->Pdf("pdfExtend"));
    ws.defineSet("Observables",Observables, true);
    ws.Print();

    doofit::config::CommonConfig cfg_com("common");
    cfg_com.InitializeOptions(argc, argv);
    doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
    cfg_tfac.InitializeOptions(cfg_com);
    doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
    cfg_tstudy.InitializeOptions(cfg_tfac);

    // set a previously defined workspace to get PDF from (not mandatory, but convenient)
    cfg_tfac.set_workspace(&ws);
    cfg_com.CheckHelpFlagAndPrintHelp();

    // Initialize the toy factory module with the config objects and start
    // generating toy samples.
    doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
    doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);

  //Generate data
  RooDataSet* data = tfac.Generate();
  data->Print();
  epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt");
  epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt.new");


  //FIT-PDF-Koeffizienten
  epdf->Var("asym_prodFit");
  epdf->Var("asym_prodFit").setVal(-0.0108);
  epdf->Var("asym_prodFit").setConstant(false);

  DecRateCoeff *coeff_cFit = new DecRateCoeff("coef_cosFit","coef_cosFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sFit = new DecRateCoeff("coef_sinFit","coef_sinFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_shFit = new DecRateCoeff("coef_sinhFit","coef_sinhFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_chFit = new DecRateCoeff("coef_coshFit","coef_coshFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_chFit);
  epdf->AddRealToStore(coeff_shFit);
  epdf->AddRealToStore(coeff_cFit);
  epdf->AddRealToStore(coeff_sFit);

  ///////////////////Generiere PDF's/////////////////////
  //Zeit
  
  epdf->BDecay("pdfSigTimeFit",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_coshFit"),epdf->Real("coef_sinhFit"),epdf->Real("coef_cosFit"),epdf->Real("coef_sinFit"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));

  //Zusammenfassen der Parameter in einem RooArgSet
  RooArgSet ObservablesFit;
  ObservablesFit.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));

  epdf->Extend("pdfExtendFit", epdf->Pdf("pdfSigTimeFit"),epdf->Real("sig_yield"));
  
  
  RooFitResult* fit_result = epdf->Pdf("pdfExtendFit").fitTo(*data, RooFit::Save(true));
  tstudy.StoreFitResult(fit_result);
  //epdf->Pdf("pdfExtendFit").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt");
  //epdf->Pdf("pdfExtendFit").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt.new");

  //Plotten auf lhcb
  /*using namespace doofit::plotting;

  PlotConfig cfg_plot("cfg_plot");
  cfg_plot.InitializeOptions();
  cfg_plot.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_float-lhcb/dgamma/time/");
  // plot PDF and directly specify components
  Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
  myplot.PlotItLogNoLogY();

  PlotConfig cfg_plotEta("cfg_plotEta");
  cfg_plotEta.InitializeOptions();
  cfg_plotEta.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_float-lhcb/dgamma/eta/");
  // plot PDF and directly specify components
  Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
  myplotEta.PlotIt();*/

 }
コード例 #10
0
ファイル: sig.C プロジェクト: cms-analysis/ZprimeDiLeptons
void makeModel(RooWorkspace& w) {

   TFile *_file0 = TFile::Open("plots/htotal_root_ZprimeRecomass.root");
   TH1F *Histo = (TH1F*)_file0->Get("htotaldata");
   RooRealVar invm("invm","invm",200.,4000.);    
   RooDataHist* data = new RooDataHist("data","data",invm,Import(*Histo)) ;
   

//   TTree* tree = new TTree("simple","data from ascii file");
//   Long64_t nlines = tree->ReadFile("list_mll_200_2016.txt","x1:x2:x3:invm:x5:x6");
//   Long64_t nlines = tree->ReadFile("a.txt","x1:x2:x3:invm:x5:x6");
//   printf(" found %lld pointsn",nlines);
//   tree->Write();
//   tree->GetEntries();

   RooRealVar mass("mass","mass", 300., 200., 1600.);
   RooRealVar nsig("nsig","Number of signal events", 0., 5000.);
   RooRealVar nbkg("nbkg","Number of background events", 0., 300000.);
   w.import(mass);
   w.import(nsig);
   w.import(nbkg);

//   RooRealVar invm("invm","Invariant mass", 200., 4000.);
//   RooDataSet* data = new RooDataSet("data", "Data", invm, RooFit::Import(*tree));

   data->Print("v");
   w.import(invm);
   w.import(*data);
 
   w.factory("expr::sigma('invm*(0.01292 + 0.00001835 * invm - 0.0000000002733 * invm*invm)',invm)");
   w.factory("expr::width('0.03*invm',invm)");
 
   w.factory("CEXPR::bkgpdf('exp(24.9327 - 2.39287e-03*invm + 3.19926e-07*invm*invm - 3.38799e-11*invm*invm*invm)*pow(invm,-3.3634)',invm)");
   w.factory("Voigtian::sigpdf(invm,mass,width,sigma)");

   w.factory("SUM::model(nbkg*bkgpdf, nsig*sigpdf)");

   RooAbsPdf* sigpdf = w.pdf("sigpdf");
   RooAbsPdf* bkgpdf = w.pdf("bkgpdf");
   RooAbsPdf* model  = w.pdf("model");

   RooStats::ModelConfig* mc = new ModelConfig("mc",&w);
   mc->SetPdf(*w.pdf("model"));
   mc->SetParametersOfInterest(*w.var("nsig"));
   mc->SetObservables(*w.var("invm"));
   w.defineSet("nuisParams","nbkg");

   mc->SetNuisanceParameters(*w.set("nuisParams"));
   w.var("mass")->setConstant(true);

   w.import(*mc);

   w.Print("tree");

   w.writeToFile("MyModel_workspace.root");
  
   TCanvas* c1 = new TCanvas("c1","Control Plots", 900, 700);
   RooPlot* plot = w.var("invm")->frame();
   w.data("data")->plotOn(plot);
   w.pdf("model")->plotOn(plot);
   w.pdf("model")->plotOn(plot, Components("bkgpdf"),LineStyle(kDashed));
   w.pdf("model")->plotOn(plot, Components("sigpdf"),LineColor(kRed));
   plot->Draw();

   return;

}
コード例 #11
0
int main(int argc, char* argv[]) {

     doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

     //Observable
     epdf->Var("obsMass").setVal(5280);
     epdf->Var("obsMass").setRange(5200.,5500.);
     epdf->Var("obsTime").setVal(1.3);
     epdf->Var("obsTime").setRange(0.3, 18.3);
  
     //Zusammenfassen der Parameter in einem RooArgSet
     RooArgSet Observables;
     Observables.add(RooArgSet(epdf->Var("obsMass"), epdf->Var("obsTime")));

     //Anlegen der Parameter
     /*epdf->Var("pdf_sig_mass_mean").setRange(5230, 5330);
     epdf->Var("pdf_sig_mass_mean").setVal(5280);
     epdf->Var("pdf_sig_mass_width").setRange(1.0, 15);
     epdf->Var("pdf_sig_mass_width").setVal(10);
     epdf->Var("pdf_bkg_mass_lambda").setRange(-0.0074, 0.0);
     epdf->Var("pdf_bkg_mass_lambda").setVal(-0.001);
     epdf->Var("sig_Yield").setRange(0.0, 10000);
     epdf->Var("sig_Yield").setVal(5000);
     epdf->Var("bkg_Yield").setRange(0.0, 10000);
     epdf->Var("bkg_Yield").setVal(5000);*/
  
     ///////////////////Generiere PDF's/////////////////////
  
     //Signal PDF's//
     epdf->DoubleGaussianScaled("pdf_sig_mass_gauss", epdf->Var("obsMass"),  epdf->Var("pdf_sig_mass_mean"), epdf-> Var("pdf_sig_mass_width"), epdf->Var("scale"), epdf->Var("fraction"), "Sigma");
     //Untergrund PDF
     epdf->Exponential("pdf_bkg_mass_expo", epdf->Var("obsMass"),epdf->Var("pdf_bkg_mass_lambda"));
  

     //Zerfalls PDF's//
     //Resolution Model
     epdf->GaussModel("pdf_resolution", epdf->Var("obsTime"), epdf->Var("pdf_res_mean"), epdf->Var("obsTimeErr"));
     //Zerfalls PDF des Untergrunds
     epdf->Decay("pdf_bkg_time_decay", epdf->Var("obsTime"),epdf->Var("pdf_bkg_time_tau"), epdf->Model("pdf_resolution"));
     //Zerfall PDF des Signals
     epdf->Decay("pdf_sig_time_decay", epdf->Var("obsTime"),epdf->Var("pdf_sig_time_tau"), epdf->Model("pdf_resolution"));


     //Multipliziere Signal und Untergrund PDF mit ihrer jeweiligen Zerfalls PDF//
     //Untergrund * Zerfall
     epdf->Product("pdf_bkg_mass*pdf_bkg_time_decay", RooArgSet(epdf->Pdf("pdf_bkg_mass_expo"), epdf->Pdf("pdf_bkg_time_decay")));
     //Signal * Zerfall
     epdf->Product("pdf_sig_mass_gauss*pdf_sig_time_decay", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss"),epdf->Pdf("pdf_sig_time_decay")));




     //Addiere PDF's
     epdf->Add("pdf_total", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss*pdf_sig_time_decay"), epdf->Pdf("pdf_bkg_mass*pdf_bkg_time_decay")), RooArgSet(epdf->Var("bkg_Yield"),epdf->Var("sig_Yield")));


    	    


     

     RooWorkspace ws;
     ws.import(epdf->Pdf("pdf_total"));
     ws.defineSet("Observables",Observables, true);

     ws.Print();

     doofit::config::CommonConfig cfg_com("common");
     cfg_com.InitializeOptions(argc, argv);
     doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
     cfg_tfac.InitializeOptions(cfg_com);
     doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
     cfg_tstudy.InitializeOptions(cfg_tfac);

     // set a previously defined workspace to get PDF from (not mandatory, but convenient)
     cfg_tfac.set_workspace(&ws);

     // Check for a set --help flag and if so, print help and exit gracefully
     // (recommended).
     cfg_com.CheckHelpFlagAndPrintHelp();

     // More custom code, e.g. to set options internally.
     // Not required as configuration via command line/config file is enough.


     // Print overview of all options (optional)
     // cfg_com.PrintAll();

     // Initialize the toy factory module with the config objects and start
     // generating toy samples.
     doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
     doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);


     //for(int i=0;i<100;i++)
     //{
     RooDataSet* data = tfac.Generate();
     epdf->Pdf("pdf_total").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/parameters_generate2.txt");
     epdf->Pdf("pdf_total").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/parameters_generate2.txt.new");

     // fitting on the generated dataset is your responsibility
     RooFitResult* fit_result = epdf->Pdf("pdf_total").fitTo(*data, RooFit::Save(true));
  
     /*using namespace doofit::plotting;

     PlotConfig cfg_plot("cfg_plot");
     cfg_plot.InitializeOptions();

     // plot PDF and directly specify component
     //Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdf_total")));
     Plot myplot(cfg_plot, epdf->Var("obsMass"), *data, RooArgList(epdf->Pdf("pdf_total")));
     myplot.PlotIt();*/

     //Speichern der Ergebnisse
     tstudy.StoreFitResult(fit_result);
     //}
     /*tstudy.FinishFitResultSaving();
     tstudy.ReadFitResults();
     tstudy.EvaluateFitResults();
     tstudy.PlotEvaluatedParameters();*/
    


 }
コード例 #12
0
ファイル: hf_tprime.C プロジェクト: TENorbert/TambeENorbert
Int_t Tprime::SetParameterPoints( std::string sbModelName,
                                  std::string bModelName ) {
    //
    // Fit the data with S+B model.
    // Make a snapshot of the S+B parameter point.
    // Profile with POI=0.
    // Make a snapshot of the B parameter point
    // (B model is the S+B model with POI=0
    //

    Double_t poi_value_for_b_model = 0.0;

    // get S+B model config from workspace
    RooStats::ModelConfig * pSbModel = (RooStats::ModelConfig *)pWs->obj(sbModelName.c_str());
    pSbModel->SetWorkspace(*pWs);

    // get parameter of interest set
    const RooArgSet * poi = pSbModel->GetParametersOfInterest();

    // get B model config from workspace
    RooStats::ModelConfig * pBModel = (RooStats::ModelConfig *)pWs->obj(bModelName.c_str());
    pBModel->SetWorkspace(*pWs);

    // make sure that data has been loaded
    if (!data) return -1;

    // find parameter point for global maximum with the S+B model,
    // with conditional MLEs for nuisance parameters
    // and save the parameter point snapshot in the Workspace
    RooAbsReal * nll = pSbModel->GetPdf()->createNLL(*data);
    RooAbsReal * profile = nll->createProfile(RooArgSet());
    profile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
    RooArgSet * poiAndNuisance = new RooArgSet();
    if(pSbModel->GetNuisanceParameters())
        poiAndNuisance->add(*pSbModel->GetNuisanceParameters());
    poiAndNuisance->add(*pSbModel->GetParametersOfInterest());
    pWs->defineSet("SPlusBModelParameters", *poiAndNuisance);
    pWs->saveSnapshot("SPlusBFitParameters",*poiAndNuisance);
    pSbModel->SetSnapshot(*poi);
    RooArgSet * sbModelFitParams = (RooArgSet *)poiAndNuisance->snapshot();
    cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
    sbModelFitParams->Print("v");
    delete profile;
    delete nll;
    delete poiAndNuisance;
    delete sbModelFitParams;

    //

    // Find a parameter point for generating pseudo-data
    // with the background-only data.
    // Save the parameter point snapshot in the Workspace
    nll = pBModel->GetPdf()->createNLL(*data);
    profile = nll->createProfile(*poi);
    ((RooRealVar *)poi->first())->setVal(poi_value_for_b_model);
    profile->getVal(); // this will do fit and set nuisance parameters to profiled values
    poiAndNuisance = new RooArgSet();
    if(pBModel->GetNuisanceParameters())
        poiAndNuisance->add(*pBModel->GetNuisanceParameters());
    poiAndNuisance->add(*pBModel->GetParametersOfInterest());
    pWs->defineSet("parameterPointToGenerateData", *poiAndNuisance);
    pWs->saveSnapshot("parametersToGenerateData",*poiAndNuisance);
    pBModel->SetSnapshot(*poi);
    RooArgSet * paramsToGenerateData = (RooArgSet *)poiAndNuisance->snapshot();
    cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
    paramsToGenerateData->Print("v");
    delete profile;
    delete nll;
    delete poiAndNuisance;
    delete paramsToGenerateData;

    return 0;
}