Exemple #1
0
void TestNonCentral(){

  RooWorkspace w("w");
  // k <2, must use sum
  w.factory("NonCentralChiSquare::nc(x[0,50],k[1.99,0,5],lambda[5])");
  // kk > 2 can use bessel
  w.factory("NonCentralChiSquare::ncc(x,kk[2.01,0,5],lambda)");
  // kk > 2, force sum
  w.factory("NonCentralChiSquare::nccc(x,kk,lambda)");
  ((RooNonCentralChiSquare*)w.pdf("nccc"))->SetForceSum(true);

  // a normal "central" chi-square for comparision when lambda->0
  w.factory("ChiSquarePdf::cs(x,k)");

  //w.var("kk")->setVal(4.); // test a large kk

  RooDataSet* ncdata = w.pdf("nc")->generate(*w.var("x"),100);
  RooDataSet* csdata = w.pdf("cs")->generate(*w.var("x"),100);
  RooPlot* plot = w.var("x")->frame();
  ncdata->plotOn(plot,MarkerColor(kRed));
  csdata->plotOn(plot,MarkerColor(kBlue));
  w.pdf("nc")->plotOn(plot,LineColor(kRed));
  w.pdf("ncc")->plotOn(plot,LineColor(kGreen));
  w.pdf("nccc")->plotOn(plot,LineColor(kYellow),LineStyle(kDashed));
  w.pdf("cs")->plotOn(plot,LineColor(kBlue),LineStyle(kDotted));
  plot->Draw();

}
Exemple #2
0
void FitterUtils::PlotShape2D(RooDataSet& originDataSet, RooDataSet& genDataSet, RooAbsPdf& shape, string plotsfile, string canvName, RooRealVar& B_plus_M, RooRealVar& misPT)
{
   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");

   //**************Plot Signal Zero Gamma

   TH2F* th2fKey = (TH2F*)shape.createHistogram("th2Shape", B_plus_M, Binning(20), YVar(misPT, Binning(20)));
   cout<<genDataSet.sumEntries()<<endl;
   TH2F* th2fGen = (TH2F*)genDataSet.createHistogram("th2fGen", B_plus_M, Binning(20), YVar(misPT, Binning(20)));

   RooPlot* plotM = B_plus_M.frame();
   originDataSet.plotOn(plotM);
   shape.plotOn(plotM);

   RooPlot* plotMisPT = misPT.frame();
   originDataSet.plotOn(plotMisPT);
   shape.plotOn(plotMisPT);

   TCanvas canv(canvName.c_str(), canvName.c_str(), 800, 800);
   canv.Divide(2,2);
   canv.cd(1); th2fGen->Draw("lego");
   canv.cd(2); th2fKey->Draw("surf");
   canv.cd(3); plotM->Draw();
   canv.cd(4); plotMisPT->Draw();

   canv.Write();

   f2.Close();
}
void rf314_paramfitrange()
{

  // D e f i n e   o b s e r v a b l e s   a n d   d e c a y   p d f 
  // ---------------------------------------------------------------

  // Declare observables
  RooRealVar t("t","t",0,5) ;
  RooRealVar tmin("tmin","tmin",0,0,5) ;

  // Make parameterized range in t : [tmin,5]
  t.setRange(tmin,RooConst(t.getMax())) ;

  // Make pdf
  RooRealVar tau("tau","tau",-1.54,-10,-0.1) ;
  RooExponential model("model","model",t,tau) ;



  // C r e a t e   i n p u t   d a t a 
  // ------------------------------------

  // Generate complete dataset without acceptance cuts (for reference)
  RooDataSet* dall = model.generate(t,10000) ;

  // Generate a (fake) prototype dataset for acceptance limit values
  RooDataSet* tmp = RooGaussian("gmin","gmin",tmin,RooConst(0),RooConst(0.5)).generate(tmin,5000) ;

  // Generate dataset with t values that observe (t>tmin)
  RooDataSet* dacc = model.generate(t,ProtoData(*tmp)) ;



  // F i t   p d f   t o   d a t a   i n   a c c e p t a n c e   r e g i o n
  // -----------------------------------------------------------------------

  RooFitResult* r = model.fitTo(*dacc,Save()) ;


 
  // P l o t   f i t t e d   p d f   o n   f u l l   a n d   a c c e p t e d   d a t a 
  // ---------------------------------------------------------------------------------

  // Make plot frame, add datasets and overlay model
  RooPlot* frame = t.frame(Title("Fit to data with per-event acceptance")) ;
  dall->plotOn(frame,MarkerColor(kRed),LineColor(kRed)) ;
  model.plotOn(frame) ;
  dacc->plotOn(frame) ;

  // Print fit results to demonstrate absence of bias
  r->Print("v") ;


  new TCanvas("rf314_paramranges","rf314_paramranges",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.6) ; frame->Draw() ;

  return ;
}
Exemple #4
0
void plot_toys()
{
  TFile* f = new TFile("/project/atlas/users/tlenz/HWWStatisticsCode_v31/CPmix_kHWW2dot65m_0j_trainv31_v31_allsys_topLumi_toys.root");
  RooWorkspace* w = (RooWorkspace*)f->Get("combined");

  RooDataSet* data = (RooDataSet*)w->data("obsData");
  RooDataSet* toydata = (RooDataSet*)w->data("toyData");
  RooDataSet* toydata2 = (RooDataSet*)w->data("toyData4");
  RooDataSet* thisAsimovData = (RooDataSet*)w->data("asimivData_profiled_for_epsilon_0"); //asimivData_profiled_for_epsilon_0
  
  RooPlot* frame1 = w->var("obs_x_em_signalLike_0j_2012")->frame();
  //  RooPlot* frame2 = w->var("obs_x_em_mainControl_0j_2012")->frame();
  // RooPlot* frame3 = w->var("obs_x_em_zbox_0j_2012")->frame();
  
  data->plotOn(frame1, Name("data"), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_signalLike_0j_2012"));
  //data->plotOn(frame2, Name("data"), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_mainControl_0j_2012"));
  //data->plotOn(frame3, Name("data"), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_zbox_0j_2012"));
  
  toydata->plotOn(frame1, Name("toy1"), LineColor(kRed), MarkerStyle(21), MarkerColor(kRed), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_signalLike_0j_2012"));
  //toydata->plotOn(frame2, Name("toy1"), LineColor(kRed), MarkerStyle(21), MarkerColor(kRed), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_mainControl_0j_2012"));
  //toydata->plotOn(frame3, Name("toy1"), LineColor(kRed), MarkerStyle(21), MarkerColor(kRed), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_zbox_0j_2012"));
  
  toydata2->plotOn(frame1, Name("toy4"), LineColor(kGreen), MarkerStyle(21), MarkerColor(kGreen), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_signalLike_0j_2012"));
  //toydata2->plotOn(frame2, Name("toy4"), LineColor(kGreen), MarkerStyle(21), MarkerColor(kGreen), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_mainControl_0j_2012"));
  //toydata2->plotOn(frame3, Name("toy4"), LineColor(kGreen), MarkerStyle(21), MarkerColor(kGreen), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_zbox_0j_2012"));
  
  thisAsimovData->plotOn(frame1, Name("asimov"), LineColor(kBlue), MarkerStyle(22), MarkerColor(kBlue), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_signalLike_0j_2012"));
  //thisAsimovData->plotOn(frame2, Name("asimov"), LineColor(kBlue), MarkerStyle(22), MarkerColor(kBlue), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_mainControl_0j_2012"));
  //thisAsimovData->plotOn(frame3, Name("asimov"), LineColor(kBlue), MarkerStyle(22), MarkerColor(kBlue), DataError(RooAbsData::Poisson), Cut("merged_cat==merged_cat::em_zbox_0j_2012"));
  
  TCanvas* c = new TCanvas("c","c",1800,600);
  //c->Divide(3,1);
  
  /*c->cd(1);*/ /*gPad->SetLogy();*/ frame1->Draw();
  
  
  //c->cd(2); frame2->Draw();
  //draw legend
  TLegend *leg = new TLegend(0.48, 0.60, 0.84, 0.80, NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.04);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(1001);
  leg->SetNColumns(1);
  leg->AddEntry(frame1->findObject("data"),"data","pl");
  leg->AddEntry(frame1->findObject("toy1"),"toy1","pl");
  leg->AddEntry(frame1->findObject("toy4"),"toy4","pl");
  leg->AddEntry(frame1->findObject("asimov"),"asimov","pl");
	leg->Draw();
	//c->cd(3); frame3->Draw();
	c->Print("toys_linear.pdf");
}
Exemple #5
0
void rf304_uncorrprod()
{

   // C r e a t e   c o m p o n e n t   p d f s   i n   x   a n d   y 
   // ----------------------------------------------------------------

   // Create two p.d.f.s gaussx(x,meanx,sigmax) gaussy(y,meany,sigmay) and its variables
   RooRealVar x("x","x",-5,5) ;
   RooRealVar y("y","y",-5,5) ;

   RooRealVar meanx("mean1","mean of gaussian x",2) ;
   RooRealVar meany("mean2","mean of gaussian y",-2) ;
   RooRealVar sigmax("sigmax","width of gaussian x",1) ;
   RooRealVar sigmay("sigmay","width of gaussian y",5) ;

   RooGaussian gaussx("gaussx","gaussian PDF",x,meanx,sigmax) ;  
   RooGaussian gaussy("gaussy","gaussian PDF",y,meany,sigmay) ;  



   // C o n s t r u c t   u n c o r r e l a t e d   p r o d u c t   p d f
   // -------------------------------------------------------------------

   // Multiply gaussx and gaussy into a two-dimensional p.d.f. gaussxy
   RooProdPdf  gaussxy("gaussxy","gaussx*gaussy",RooArgList(gaussx,gaussy)) ;



   // S a m p l e   p d f ,   p l o t   p r o j e c t i o n   o n   x   a n d   y  
   // ---------------------------------------------------------------------------

   // Generate 10000 events in x and y from gaussxy
   RooDataSet *data = gaussxy.generate(RooArgSet(x,y),10000) ;

   // Plot x distribution of data and projection of gaussxy on x = Int(dy) gaussxy(x,y)
   RooPlot* xframe = x.frame(Title("X projection of gauss(x)*gauss(y)")) ;
   data->plotOn(xframe) ;
   gaussxy.plotOn(xframe) ; 

   // Plot x distribution of data and projection of gaussxy on y = Int(dx) gaussxy(x,y)
   RooPlot* yframe = y.frame(Title("Y projection of gauss(x)*gauss(y)")) ;
   data->plotOn(yframe) ;
   gaussxy.plotOn(yframe) ; 



   // Make canvas and draw RooPlots
   TCanvas *c = new TCanvas("rf304_uncorrprod","rf304_uncorrprod",800, 400);
   c->Divide(2);
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; xframe->GetYaxis()->SetTitleOffset(1.4) ; xframe->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; yframe->GetYaxis()->SetTitleOffset(1.4) ; yframe->Draw() ;

}
Exemple #6
0
void rf301_composition()
{
  // S e t u p   c o m p o s e d   m o d e l   g a u s s ( x , m ( y ) , s )
  // -----------------------------------------------------------------------

  // Create observables
  RooRealVar x("x","x",-5,5) ;
  RooRealVar y("y","y",-5,5) ;

  // Create function f(y) = a0 + a1*y
  RooRealVar a0("a0","a0",-0.5,-5,5) ;
  RooRealVar a1("a1","a1",-0.5,-1,1) ;
  RooPolyVar fy("fy","fy",y,RooArgSet(a0,a1)) ;

  // Creat gauss(x,f(y),s)
  RooRealVar sigma("sigma","width of gaussian",0.5) ;
  RooGaussian model("model","Gaussian with shifting mean",x,fy,sigma) ;  


  // S a m p l e   d a t a ,   p l o t   d a t a   a n d   p d f   o n   x   a n d   y 
  // ---------------------------------------------------------------------------------

  // Generate 10000 events in x and y from model
  RooDataSet *data = model.generate(RooArgSet(x,y),10000) ;

  // Plot x distribution of data and projection of model on x = Int(dy) model(x,y)
  RooPlot* xframe = x.frame() ;
  data->plotOn(xframe) ;
  model.plotOn(xframe) ; 

  // Plot x distribution of data and projection of model on y = Int(dx) model(x,y)
  RooPlot* yframe = y.frame() ;
  data->plotOn(yframe) ;
  model.plotOn(yframe) ; 

  // Make two-dimensional plot in x vs y
  TH1* hh_model = model.createHistogram("hh_model",x,Binning(50),YVar(y,Binning(50))) ;
  hh_model->SetLineColor(kBlue) ;



  // Make canvas and draw RooPlots
  TCanvas *c = new TCanvas("rf301_composition","rf301_composition",1200, 400);
  c->Divide(3);
  c->cd(1) ; gPad->SetLeftMargin(0.15) ; xframe->GetYaxis()->SetTitleOffset(1.4) ; xframe->Draw() ;
  c->cd(2) ; gPad->SetLeftMargin(0.15) ; yframe->GetYaxis()->SetTitleOffset(1.4) ; yframe->Draw() ;
  c->cd(3) ; gPad->SetLeftMargin(0.20) ; hh_model->GetZaxis()->SetTitleOffset(2.5) ; hh_model->Draw("surf") ;

}
Exemple #7
0
int main(){
  
  RooMsgService::instance().setGlobalKillBelow(ERROR);
  
  TFile *bkgFile = TFile::Open("comb_svn/hgg.inputbkgdata_8TeV_MVA.root");
  RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get("cms_hgg_workspace");
  RooRealVar *mass = (RooRealVar*)bkgWS->var("CMS_hgg_mass");
  RooDataSet *data = (RooDataSet*)bkgWS->data("data_mass_cat0");

  RooRealVar *p1 = new RooRealVar("p1","p1",-2.,-10.,0.);
  RooRealVar *p2 = new RooRealVar("p2","p2",-0.001,-0.01,0.01);
  RooRealVar *p3 = new RooRealVar("p3","p3",-0.0001,-0.01,0.01);

  //RooPowerLawSum *pow1 = new RooPowerLawSum("pow","pow",*mass,RooArgList(*p1));
  //RooPowerLawSum *pow2 = new RooPowerLawSum("pow","pow",*mass,RooArgList(*p1,*p2));
  //RooPowerLawSum *pow3 = new RooPowerLawSum("pow","pow",*mass,RooArgList(*p1,*p2,*p3));

  RooExponentialSum *pow1 = new RooExponentialSum("pow1","pow1",*mass,RooArgList(*p1));
  RooExponentialSum *pow2 = new RooExponentialSum("pow2","pow2",*mass,RooArgList(*p1,*p2));
  RooExponentialSum *pow3 = new RooExponentialSum("pow3","pow3",*mass,RooArgList(*p1,*p2,*p3));

  TCanvas *canv = new TCanvas();
  RooPlot *frame = mass->frame();
  data->plotOn(frame);
  
  cout << "bus" << endl;
  pow1->fitTo(*data,PrintEvalErrors(-1),PrintLevel(-1),Warnings(-1),Verbose(-1));
  cout << "bus" << endl;
  pow1->plotOn(frame);
  pow2->fitTo(*data);
  pow2->plotOn(frame,LineColor(kRed),LineStyle(kDashed));
  pow3->fitTo(*data);
  pow3->plotOn(frame,LineColor(kGreen),LineStyle(7));
  frame->Draw();
  canv->Print("test.pdf");

  TFile *outFile = new TFile("test.root","RECREATE");

  TTree *tree = new TTree("tree","tree");

  vector<double> mu;
  mu.push_back(1.);
  mu.push_back(2.);
  mu.push_back(3.);
  mu.push_back(4.);
  vector<string> label;
  label.push_back("pol");
  label.push_back("pow");
  label.push_back("lau");
  label.push_back("exp");

  tree->Branch("mu",&mu);
  tree->Branch("label",&label);

  tree->Fill();
  outFile->cd();
  tree->Write();
  outFile->Close();
  return 0;
}
Exemple #8
0
void Plot(RooAbsPdf *iGen,RooAbsPdf *iFit,int iN,int iNEvents,RooRealVar &iVar,RooRealVar &iSig,RooRealVar &iMean,
	  RooRealVar &iScale,RooRealVar &iRes,RooDataSet *iData=0) { 
  TRandom1 *lRand = new TRandom1(0xDEADBEEF);
  RooDataSet * lSignal  = iGen->generate(iVar,iNEvents);
  if(iData == 0) {
    iFit->fitTo(*lSignal,Strategy(1));
    if(iMean.getError() < 0.05) iFit->fitTo(*lSignal,Strategy(2));
  } else {
    iFit->fitTo(*iData,Strategy(1));
    if(iMean.getError() < 0.05) iFit->fitTo(*iData,Strategy(2));
  }    
  iVar.setBins(30);
  RooPlot *lFrame1 = iVar.frame(RooFit::Title("XXX")) ;
  if(iData == 0) lSignal->plotOn(lFrame1);
  if(iData != 0) iData->plotOn(lFrame1);
  iFit->plotOn(lFrame1);
  TCanvas *iC =new TCanvas("A","A",800,600);
  iC->cd(); lFrame1->Draw();
  iC->SaveAs("Crap.png");
  if(iData != 0) { 
    RooPlot *lFrame2 = iVar.frame(RooFit::Title("XXX")) ;
    iData->plotOn(lFrame2);
    iGen->plotOn(lFrame2);
    TCanvas *iC1 =new TCanvas("B","B",800,600);
    iC1->cd(); lFrame2->Draw();
    iC1->SaveAs("Crap.png");
  }
}
Exemple #9
0
void MakeSpinPlots::DrawSpinBackground(TString tag, TString mcName,bool signal){
  bool drawSM = (smName!="" && smName!=mcName);

  TCanvas cv;
  double thisN  = ws->data(mcName+"_Combined")->reduce(TString("evtcat==evtcat::")+tag)->sumEntries();
  float norm = thisN; //607*lumi/12.*thisN/(totEB+totEE);
  cout << norm <<endl;
  if(signal) norm = ws->data(Form("Data_%s_%s_sigWeight",tag.Data(),mcName.Data()))->sumEntries();
  RooPlot *frame = ws->var("cosT")->frame(0,1,5);

  RooDataSet* bkgWeight = (RooDataSet*)ws->data(Form("Data_%s_%s_bkgWeight",tag.Data(),mcName.Data()));
  RooDataSet* tmp = (RooDataSet*)ws->data("Data_Combined")->reduce(TString("((mass>115 && mass<120) || (mass>130 && mass<135)) && evtcat==evtcat::")+tag);
  tmp->plotOn(frame,RooFit::Rescale(norm/tmp->sumEntries()));
  cout << "b" <<endl;
  ws->pdf(Form("%s_FIT_%s_cosTpdf",mcName.Data(),tag.Data()))->plotOn(frame,RooFit::LineColor(kGreen),RooFit::Normalization(norm/tmp->sumEntries()));
  if(drawSM) ws->pdf(Form("%s_FIT_%s_cosTpdf",smName.Data(),tag.Data()))->plotOn(frame,RooFit::LineColor(kRed),RooFit::Normalization(norm/tmp->sumEntries()));
  cout << "c   " <<bkgWeight <<endl;

  bkgWeight->plotOn(frame,RooFit::Rescale(norm/bkgWeight->sumEntries()),RooFit::MarkerColor(kBlue) );  
  if(signal){
    cout << "d" <<endl;
      
    ws->data(Form("Data_%s_%s_sigWeight",tag.Data(),mcName.Data()))->plotOn(frame,RooFit::MarkerStyle(4));
  }
  cout << "d" <<endl;
  
  frame->SetMaximum(frame->GetMaximum()*(signal?0.8:0.4)*norm/tmp->sumEntries());
  frame->SetMinimum(-1*frame->GetMaximum());
  TLegend l(0.6,0.2,0.95,0.45);
  l.SetFillColor(0);
  l.SetBorderSize(0);
  l.SetHeader(tag);
  l.AddEntry(frame->getObject(0),"Data m#in [115,120]#cup[130,135]","p");
  l.AddEntry(frame->getObject(1),mcName,"l");
  if(drawSM) l.AddEntry(frame->getObject(2),"SM Higgs","l");
  l.AddEntry(frame->getObject(2+drawSM),"background weighted Data","p");
  if(signal) l.AddEntry(frame->getObject(3+drawSM),"signal weighted Data","p");

  cout << "e" <<endl;

  frame->Draw();
  l.Draw("SAME");
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_%s%s_%s_%s.png",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data(),tag.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/C/CosThetaDist_%s%s_%s_%s.C",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data(),tag.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_%s%s_%s_%s.pdf",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data(),tag.Data()) );
}
Exemple #10
0
void test01()
{
  // S e t u p   m o d e l 
  // ---------------------

	TFile *openFile = new TFile("/tmp/kyolee/dimuonTree_upsiMiniTree_pA5tev_14nb_Run210498-210909_trigBit1_allTriggers0_pt4.root");
	TTree* tree = (TTree*)openFile->Get("UpsilonTree");	

  // Declare variables with associated name, title, initial value and allowed range
  RooRealVar mass("invariantMass","M_{#mu#mu} [GeV/c]",9.4,7,14) ;
  RooRealVar muPlusPt("muPlusPt","muPlusPt",0,40) ;
  RooRealVar muMinusPt("muMinusPt","muMinusPt",0,40) ;
  RooRealVar mean("mean","mean of gaussian",9.4,8,11) ;
  RooRealVar sigma("sigma","width of gaussian",1,0.1,10) ;

	RooDataSet* data = new RooDataSet("data", "data", RooArgSet(mass,muPlusPt,muMinusPt), Import(*tree), Cut("muPlusPt>4 && muMinusPt>4"));

 	data->Print();

  // Build gaussian p.d.f in terms of x,mean and sigma
  RooGaussian gauss("gauss","gaussian PDF",mass,mean,sigma) ;  

  // Construct plot frame in 'x'
  RooPlot* xframe = mass.frame(Title("Gaussian p.d.f.")) ;

	data->plotOn(xframe);

	/*
  // P l o t   m o d e l   a n d   c h a n g e   p a r a m e t e r   v a l u e s
  // ---------------------------------------------------------------------------

  // Plot gauss in frame (i.e. in x) 
  gauss.plotOn(xframe) ;

  // Change the value of sigma to 3
  sigma.setVal(3) ;

  // Plot gauss in frame (i.e. in x) and draw frame on canvas
  gauss.plotOn(xframe,LineColor(kRed)) ;
*/  

  // F i t   m o d e l   t o   d a t a
  // -----------------------------

  // Fit pdf to data
  gauss.fitTo(*data,Range(9,10)) ;
  gauss.plotOn(xframe) ;

  // Print values of mean and sigma (that now reflect fitted values and errors)
  mean.Print() ;
  sigma.Print() ;


  // Draw all frames on a canvas
  TCanvas* c = new TCanvas("rf101_basics","rf101_basics",800,400) ;
  c->cd(1) ; gPad->SetLeftMargin(0.15) ; xframe->GetYaxis()->SetTitleOffset(1.6) ; xframe->Draw() ;
 
}
Exemple #11
0
void FitterUtils::PlotShape1D(RooDataSet& originDataSet, RooDataSet& genDataSet, RooAbsPdf& shape, string plotsfile, string canvName, RooRealVar& B_plus_M)
{
   TFile f2(plotsfile.c_str(), "UPDATE");

   RooPlot* plotGen = B_plus_M.frame(Binning(20));
   genDataSet.plotOn(plotGen);

   RooPlot* plotM = B_plus_M.frame();
   originDataSet.plotOn(plotM);
   shape.plotOn(plotM);

   TCanvas canv(canvName.c_str(), canvName.c_str(), 800, 800);
   canv.Divide(1,2);
   canv.cd(1); plotGen->Draw();
   canv.cd(2); plotM->Draw();

   canv.Write();

   f2.Close();
}
Exemple #12
0
void rf903_numintcache(Int_t mode=0)
{
   // Mode = 0 : Run plain fit (slow)
   // Mode = 1 : Generate workspace with pre-calculated integral and store it on file (prepare for accelerated running)
   // Mode = 2 : Run fit from previously stored workspace including cached integrals (fast, requires run in mode=1 first)

   // C r e a t e ,   s a v e   o r   l o a d   w o r k s p a c e   w i t h   p . d . f .
   // -----------------------------------------------------------------------------------

   // Make/load workspace, exit here in mode 1
   RooWorkspace* w1 = getWorkspace(mode) ;
   if (mode==1) {

      // Show workspace that was created
      w1->Print() ;

      // Show plot of cached integral values
      RooDataHist* hhcache = (RooDataHist*) w1->expensiveObjectCache().getObj(1) ;
      if (hhcache) {

         new TCanvas("rf903_numintcache","rf903_numintcache",600,600) ;
         hhcache->createHistogram("a")->Draw() ;

      }
      else {
         Error("rf903_numintcache","Cached histogram is not existing in workspace");
      }
         return ;
   }

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

   // This is always slow (need to find maximum function value empirically in 3D space)
   RooDataSet* d = w1->pdf("model")->generate(RooArgSet(*w1->var("x"),*w1->var("y"),*w1->var("z")),1000) ;

   // This is slow in mode 0, but fast in mode 1
   w1->pdf("model")->fitTo(*d,Verbose(kTRUE),Timer(kTRUE)) ;

   // Projection on x (always slow as 2D integral over Y,Z at fitted value of a is not cached)
   RooPlot* framex = w1->var("x")->frame(Title("Projection of 3D model on X")) ;
   d->plotOn(framex) ;
   w1->pdf("model")->plotOn(framex) ;

   // Draw x projection on canvas
   new TCanvas("rf903_numintcache","rf903_numintcache",600,600) ;
   framex->Draw() ;

   // Make workspace available on command line after macro finishes
   gDirectory->Add(w1) ;

   return ;

}
Exemple #13
0
void rf208_convolution()
{
  // S e t u p   c o m p o n e n t   p d f s 
  // ---------------------------------------

  // Construct observable
  RooRealVar t("t","t",-10,30) ;

  // Construct landau(t,ml,sl) ;
  RooRealVar ml("ml","mean landau",5.,-20,20) ;
  RooRealVar sl("sl","sigma landau",1,0.1,10) ;
  RooLandau landau("lx","lx",t,ml,sl) ;
  
  // Construct gauss(t,mg,sg)
  RooRealVar mg("mg","mg",0) ;
  RooRealVar sg("sg","sg",2,0.1,10) ;
  RooGaussian gauss("gauss","gauss",t,mg,sg) ;


  // C o n s t r u c t   c o n v o l u t i o n   p d f 
  // ---------------------------------------

  // Set #bins to be used for FFT sampling to 10000
  t.setBins(10000,"cache") ; 

  // Construct landau (x) gauss
  RooFFTConvPdf lxg("lxg","landau (X) gauss",t,landau,gauss) ;



  // S a m p l e ,   f i t   a n d   p l o t   c o n v o l u t e d   p d f 
  // ----------------------------------------------------------------------

  // Sample 1000 events in x from gxlx
  RooDataSet* data = lxg.generate(t,10000) ;

  // Fit gxlx to data
  lxg.fitTo(*data) ;

  // Plot data, landau pdf, landau (X) gauss pdf
  RooPlot* frame = t.frame(Title("landau (x) gauss convolution")) ;
  data->plotOn(frame) ;
  lxg.plotOn(frame) ;
  landau.plotOn(frame,LineStyle(kDashed)) ;


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

}
Exemple #14
0
void FitterUtils::plot_fit_result(string plotsfile, RooAbsPdf &totPdf, RooDataSet dataGenTot)
{

   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");
   //**************Plot the results of the fit

   RooArgSet *var_set = totPdf.getObservables(dataGenTot);
   TIterator *iter = var_set->createIterator();
   RooRealVar *var;

   std::vector<RooPlot*> plots;
   RooPlot* frame;

   while((var = (RooRealVar*) iter->Next()))
   {

      frame = var->frame();
      dataGenTot.plotOn(frame);
      totPdf.plotOn(frame, Components("histPdfPartReco"), LineColor(kBlue));
      totPdf.plotOn(frame, Components("histPdfSignalZeroGamma"), LineColor(kGreen));
      totPdf.plotOn(frame, Components("histPdfSignalOneGamma"), LineColor(kMagenta));
      totPdf.plotOn(frame, Components("histPdfSignalTwoGamma"), LineColor(kOrange));
      totPdf.plotOn(frame, Components("histPdfJpsiLeak"), LineColor(14));
      totPdf.plotOn(frame, Components("combPDF"), LineColor(kBlack));
      totPdf.plotOn(frame, LineColor(kRed));

      plots.push_back(frame);

   }  

   if (!(plots.size())) return;

   TCanvas cFit("cFit", "cFit", 600, 800);
   cFit.Divide(1,2);
   cFit.cd(1); plots[0]->Draw();
   if (plots.size()>1){ 
      cFit.cd(2); plots[1]->Draw();
   }

   cFit.Write();
   f2.Close();


}
void rs602_HLFactoryCombinationexample() {

   using namespace RooStats;
   using namespace RooFit;

   // create a card
   TString card_name("HLFavtoryCombinationexample.rs");
   ofstream ofile(card_name);
   ofile << "// The simplest card for combination\n\n"
         << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n"
         << "flat1 = Polynomial(x,0);\n"
         << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n"
         << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n"
         << "flat2 = Polynomial(x,0);\n"
         << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n";

   ofile.close();

   HLFactory hlf("HLFavtoryCombinationexample",
               card_name,
               false);

   hlf.AddChannel("model1","sb_model1","flat1");
   hlf.AddChannel("model2","sb_model2","flat2");
   RooAbsPdf* pdf=hlf.GetTotSigBkgPdf();
   RooCategory* thecat = hlf.GetTotCategory();
   RooRealVar* x= static_cast<RooRealVar*>(hlf.GetWs()->arg("x"));

   RooDataSet* data = pdf->generate(RooArgSet(*x,*thecat),Extended());

   // --- Perform extended ML fit of composite PDF to toy data ---
   pdf->fitTo(*data) ;

   // --- Plot toy data and composite PDF overlaid ---
   RooPlot* xframe = x->frame() ;

   data->plotOn(xframe);
   thecat->setIndex(0);
   pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

   thecat->setIndex(1);
   pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

   gROOT->SetStyle("Plain");
   xframe->Draw();
}
void plotFromWorkspace() {
    TFile* file = new TFile("card_m125_1JetIncl_XX_workspace.root");

    RooWorkspace* w = (RooWorkspace*)file->Get("w");

    RooRealVar* m = (RooRealVar*)w->var("CMS_hmumu_mass");
    RooRealVar* e = (RooRealVar*)w->var("CMS_hmumu_merr");
    RooDataSet* d = (RooDataSet*)w->data("data_pseudo");
    RooAbsPdf * b = w->pdf("bkg_mass_merr_1JetIncl_XX_pdf");
    RooAbsPdf * s = w->pdf("sig_mass_merr_ggH_1JetIncl_XX_pdf");

    RooPlot* frame = m->frame();
    d->plotOn(frame);
    b->plotOn(frame);
    //s->plotOn(frame, RooFit::ProjWData(*e, *d), RooFit::LineColor(kOrange+1));
    //s->plotOn(frame, RooFit::LineColor(kOrange+1));
    frame->Draw();
}
Exemple #17
0
void rfExExpo(){
	// Declare Eponential Variables
	RooRealVar x("x","x",0,10);
	RooRealVar lambda("lambda","lambda",-3,-10,0);

	// Create an Exponential PDF with variables
	RooExponential expo("expo","eponential PDF",x,lambda);
	
	// Generate a dataset of 1000 and plot it, then plot the PDF
	RooDataSet* data = expo.generate(x,1000);
	RooPlot* xframe = x.frame(Title("Exponential p.d.f."));
	data->plotOn(xframe);
	expo.plotOn(xframe);
	
	// Draw the plot on a TCanvas
	TCanvas* c = new TCanvas("rfExExpo","rfExExpo",800,400);
	xframe->Draw();
}
Exemple #18
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) ;

}
Exemple #19
0
void MakeSpinPlots::DrawSpinSubTotBackground(TString mcName,bool signal){
  bool drawSM = (smName!="" && smName!=mcName);

  TCanvas cv;
  double thisN  = ws->data(mcName+"_Combined")->sumEntries();
  float norm = thisN;


  if(signal) norm = ws->var(Form("Data_%s_FULLFIT_Nsig",mcName.Data()))->getVal();
  RooPlot *frame = ws->var("cosT")->frame(0,1,10);

  RooDataSet* tmp = (RooDataSet*)ws->data(Form("Data_Combined"))->reduce("(mass>115 && mass<120) || (mass>130 && mass<135)");
  tmp->plotOn(frame,RooFit::Rescale(norm/tmp->sumEntries()));

  ws->pdf(Form("%s_FIT_cosTpdf",mcName.Data()))->plotOn(frame,RooFit::LineColor(kGreen),RooFit::Normalization(norm/tmp->sumEntries()));
  if(drawSM)  ws->pdf(Form("%s_FIT_cosTpdf",smName.Data()))->plotOn(frame,RooFit::LineColor(kRed),RooFit::Normalization(norm/tmp->sumEntries()));
  if(signal){
    RooDataHist *h = (RooDataHist*)ws->data( Form("Data_%s_Combined_bkgSub_cosT",mcName.Data()) );
    h->plotOn(frame,RooFit::MarkerStyle(4));
    std::cout << "Nsig: " << h->sumEntries() << std::endl;
  }

  
  frame->SetMaximum(frame->GetMaximum()*(signal?2.:1.2)*norm/tmp->sumEntries());
  frame->SetMinimum(-1*frame->GetMaximum());
  TLegend l(0.6,0.2,0.95,0.45);
  l.SetFillColor(0);
  l.SetBorderSize(0);
  l.SetHeader("Combined");
  l.AddEntry(frame->getObject(0),"Data m#in [115,120]#cup[130,135]","p");
  l.AddEntry(frame->getObject(1),mcName,"l");
  if(drawSM) l.AddEntry(frame->getObject(2),"SM Higgs","l");
  if(signal) l.AddEntry(frame->getObject(2+drawSM),"bkg-subtracted Data","p");
  
  frame->Draw();
  l.Draw("SAME");
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_SimpleSub_%s%s_%s.png",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/C/CosThetaDist_SimpleSub_%s%s_%s.C",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_SimpleSub_%s%s_%s.pdf",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data()) );
}
Exemple #20
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' that exports its contents to 
  // a same-name C++ namespace in CINT 'namespace w'.
  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() ;

  // U s e   w o r k s p a c e   c o n t e n t s   t h r o u g h   C I N T   C + +   n a m e s p a c e
  // -------------------------------------------------------------------------------------------------

  // 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) ;

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


  // 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)) ;


  // 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() ;


}
void FitterUtilsSimultaneousExpOfPolyTimesX::plot_kemu_fit_result(string plotsfile, RooAbsPdf &totKemuPdf, RooDataSet const& dataGenKemu)
{

   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");
   //**************Plot the results of the fit

   RooArgSet *var_set = totKemuPdf.getObservables(dataGenKemu);
   TIterator *iter = var_set->createIterator();
   RooRealVar *var;

   std::vector<RooPlot*> plots;
   RooPlot* frame;

   while((var = (RooRealVar*) iter->Next()))
   {
      frame = var->frame();
      dataGenKemu.plotOn(frame);
      totKemuPdf.plotOn(frame, LineColor(kRed));

      plots.push_back(frame);
   }

   if (!(plots.size())) return;

   TCanvas cFit("cKemuFit", "cKemuFit", 600, 800);
   cFit.Divide(1,2);
   cFit.cd(1); plots[0]->Draw();
   if (plots.size()>1){ 
      cFit.cd(2); plots[1]->Draw();
   }

   cFit.Write();
   f2.Close();
}
Exemple #22
0
void rf109_chi2residpull()
{

   // S e t u p   m o d e l 
   // ---------------------

   // Create observables
   RooRealVar x("x","x",-10,10) ;

   // Create Gaussian
   RooRealVar sigma("sigma","sigma",3,0.1,10) ;
   RooRealVar mean("mean","mean",0,-10,10) ;
   RooGaussian gauss("gauss","gauss",x,RooConst(0),sigma) ;

   // Generate a sample of 1000 events with sigma=3
   RooDataSet* data = gauss.generate(x,10000) ;

   // Change sigma to 3.15
   sigma=3.15 ;


   // P l o t   d a t a   a n d   s l i g h t l y   d i s t o r t e d   m o d e l
   // ---------------------------------------------------------------------------

   // Overlay projection of gauss with sigma=3.15 on data with sigma=3.0
   RooPlot* frame1 = x.frame(Title("Data with distorted Gaussian pdf"),Bins(40)) ;
   data->plotOn(frame1,DataError(RooAbsData::SumW2)) ;
   gauss.plotOn(frame1) ;


   // C a l c u l a t e   c h i ^ 2 
   // ------------------------------

   // Show the chi^2 of the curve w.r.t. the histogram
   // If multiple curves or datasets live in the frame you can specify
   // the name of the relevant curve and/or dataset in chiSquare()
   cout << "chi^2 = " << frame1->chiSquare() << endl ;


   // S h o w   r e s i d u a l   a n d   p u l l   d i s t s
   // -------------------------------------------------------

   // Construct a histogram with the residuals of the data w.r.t. the curve
   RooHist* hresid = frame1->residHist() ;

   // Construct a histogram with the pulls of the data w.r.t the curve
   RooHist* hpull = frame1->pullHist() ;

   // Create a new frame to draw the residual distribution and add the distribution to the frame
   RooPlot* frame2 = x.frame(Title("Residual Distribution")) ;
   frame2->addPlotable(hresid,"P") ;

   // Create a new frame to draw the pull distribution and add the distribution to the frame
   RooPlot* frame3 = x.frame(Title("Pull Distribution")) ;
   frame3->addPlotable(hpull,"P") ;



   TCanvas* c = new TCanvas("rf109_chi2residpull","rf109_chi2residpull",900,300) ;
   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() ;

}
Exemple #23
0
void rf703_effpdfprod()
{
  // D e f i n e   o b s e r v a b l e s   a n d   d e c a y   p d f
  // ---------------------------------------------------------------

  // Declare observables
  RooRealVar t("t","t",0,5) ;

  // Make pdf
  RooRealVar tau("tau","tau",-1.54,-4,-0.1) ;
  RooExponential model("model","model",t,tau) ;



  // D e f i n e   e f f i c i e n c y   f u n c t i o n
  // ---------------------------------------------------
  
  // Use error function to simulate turn-on slope
  RooFormulaVar eff("eff","0.5*(TMath::Erf((t-1)/0.5)+1)",t) ;



  // D e f i n e   d e c a y   p d f   w i t h   e f f i c i e n c y 
  // ---------------------------------------------------------------

  // Multiply pdf(t) with efficiency in t
  RooEffProd modelEff("modelEff","model with efficiency",model,eff) ;

  

  // P l o t   e f f i c i e n c y ,   p d f  
  // ----------------------------------------

  RooPlot* frame1 = t.frame(Title("Efficiency")) ;
  eff.plotOn(frame1,LineColor(kRed)) ;

  RooPlot* frame2 = t.frame(Title("Pdf with and without efficiency")) ;

  model.plotOn(frame2,LineStyle(kDashed)) ;
  modelEff.plotOn(frame2) ;



  // G e n e r a t e   t o y   d a t a ,   f i t   m o d e l E f f   t o   d a t a
  // ------------------------------------------------------------------------------

  // Generate events. If the input pdf has an internal generator, the internal generator
  // is used and an accept/reject sampling on the efficiency is applied. 
  RooDataSet* data = modelEff.generate(t,10000) ;

  // Fit pdf. The normalization integral is calculated numerically. 
  modelEff.fitTo(*data) ;

  // Plot generated data and overlay fitted pdf
  RooPlot* frame3 = t.frame(Title("Fitted pdf with efficiency")) ;
  data->plotOn(frame3) ;
  modelEff.plotOn(frame3) ;

  
  TCanvas* c = new TCanvas("rf703_effpdfprod","rf703_effpdfprod",1200,400) ;
  c->Divide(3) ;
  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.6) ; frame2->Draw() ;
  c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;

}
Exemple #24
0
void rf103_interprfuncs()
{
  /////////////////////////////////////////////////////////
  // G e n e r i c   i n t e r p r e t e d   p . d . f . //
  /////////////////////////////////////////////////////////

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

  // C o n s t r u c t   g e n e r i c   p d f   f r o m   i n t e r p r e t e d   e x p r e s s i o n
  // -------------------------------------------------------------------------------------------------

  // To construct a proper p.d.f, the formula expression is explicitly normalized internally by dividing 
  // it by a numeric integral of the expresssion over x in the range [-20,20] 
  //
  RooRealVar alpha("alpha","alpha",5,0.1,10) ;
  RooGenericPdf genpdf("genpdf","genpdf","(1+0.1*abs(x)+sin(sqrt(abs(x*alpha+0.1))))",RooArgSet(x,alpha)) ;


  // S a m p l e ,   f i t   a n d   p l o t   g e n e r i c   p d f
  // ---------------------------------------------------------------

  // Generate a toy dataset from the interpreted p.d.f
  RooDataSet* data = genpdf.generate(x,10000) ;

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

  // Make a plot of the data and the p.d.f overlaid
  RooPlot* xframe = x.frame(Title("Interpreted expression pdf")) ;
  data->plotOn(xframe) ;
  genpdf.plotOn(xframe) ;  


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // S t a n d a r d   p . d . f   a d j u s t   w i t h   i n t e r p r e t e d   h e l p e r   f u n c t i o n //
  //                                                                                                             //
  // Make a gauss(x,sqrt(mean2),sigma) from a standard RooGaussian                                               //
  //                                                                                                             //
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////


  // C o n s t r u c t   s t a n d a r d   p d f  w i t h   f o r m u l a   r e p l a c i n g   p a r a m e t e r
  // ------------------------------------------------------------------------------------------------------------

  // Construct parameter mean2 and sigma
  RooRealVar mean2("mean2","mean^2",10,0,200) ;
  RooRealVar sigma("sigma","sigma",3,0.1,10) ;

  // Construct interpreted function mean = sqrt(mean^2)
  RooFormulaVar mean("mean","mean","sqrt(mean2)",mean2) ;

  // Construct a gaussian g2(x,sqrt(mean2),sigma) ;
  RooGaussian g2("g2","h2",x,mean,sigma) ;


  // G e n e r a t e   t o y   d a t a 
  // ---------------------------------

  // Construct a separate gaussian g1(x,10,3) to generate a toy Gaussian dataset with mean 10 and width 3
  RooGaussian g1("g1","g1",x,RooConst(10),RooConst(3)) ;
  RooDataSet* data2 = g1.generate(x,1000) ;


  // F i t   a n d   p l o t   t a i l o r e d   s t a n d a r d   p d f 
  // -------------------------------------------------------------------

  // Fit g2 to data from g1
  RooFitResult* r = g2.fitTo(*data2,Save()) ;
  r->Print() ;

  // Plot data on frame and overlay projection of g2
  RooPlot* xframe2 = x.frame(Title("Tailored Gaussian pdf")) ;
  data2->plotOn(xframe2) ;
  g2.plotOn(xframe2) ;
 

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

  
}
Exemple #25
0
RooAddPdf fitZToMuMuGammaMassUnbinned(
  const char *filename = "ZMuMuGammaMass_36.1ipb_EE.txt",
//   const char *filename = "ZMuMuGammaMass_2.9ipb_EB.txt",
//   const char *filename = "ZMuMuGammaMass_2.9ipb_EE.txt",
//   const char *filename = "ZMuMuGammaMass_Zmumu_Spring10_EB.txt",
//   const char *filename = "DimuonMass_data_Nov4ReReco.txt",

  const char* plotOpt = "NEU",
  const int nbins = 60)
{
  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  gStyle->SetPadRightMargin(0.05);

  double minMass = 60;
  double maxMass = 120;
  RooRealVar  mass("mass","m(#mu#mu#gamma)", minMass, maxMass,"GeV/c^{2}");

  // Read data set

  RooDataSet *data = RooDataSet::read(filename,RooArgSet(mass));
//   RooDataSet *dataB = RooDataSet::read(filenameB,RooArgSet(mass));

// Build p.d.f.

////////////////////////////////////////////////
//             Parameters                     //
////////////////////////////////////////////////

//  Signal p.d.f. parameters
//  Parameters for a Gaussian and a Crystal Ball Lineshape
  RooRealVar  cbBias ("#Deltam_{CB}", "CB Bias", 0.05, -2, 2,"GeV/c^{2}");
  RooRealVar  cbSigma("#sigma_{CB}","CB Width", 1.38, 0.01, 10.0,"GeV/c^{2}");
  RooRealVar  cbCut  ("a_{CB}","CB Cut", 1.5, 0.1, 2.0);
  RooRealVar  cbPower("n_{CB}","CB Power", 1.3, 0.1, 20.0);

//   cbSigma.setConstant(kTRUE);
//   cbCut.setConstant(kTRUE);
//   cbPower.setConstant(kTRUE);

//  Parameters for Breit-Wigner
  RooRealVar bwMean("m_{Z}","BW Mean", 91.1876, "GeV/c^{2}");
  RooRealVar bwWidth("#Gamma_{Z}", "BW Width", 2.4952, "GeV/c^{2}");

  // Keep Breit-Wigner parameters fixed to the PDG values
//   bwMean.setConstant(kTRUE);
//   bwWidth.setConstant(kTRUE);


//  Background p.d.f. parameters
// Parameters for exponential
  RooRealVar expRate("#lambda_{exp}", "Exponential Rate", -0.119, -10, 1);

//   expRate.setConstant(kTRUE);



// fraction of signal
//  RooRealVar  frac("frac", "Signal Fraction", 0.1,0.,0.3.);
/*  RooRealVar  nsig("N_{S}", "#signal events", 9000, 0.,10000.);
  RooRealVar  nbkg("N_{B}", "#background events", 1000,2,10000.);*/
  RooRealVar  nsig("N_{S}", "#signal events", 29300, 0.1, 100000.);
  RooRealVar  nbkg("N_{B}", "#background events", 0, 0., 10000.);

//   nbkg.setConstant(kTRUE);



////////////////////////////////////////////////
//               P.D.F.s                      //
////////////////////////////////////////////////

// Di-photon mass signal p.d.f.
  RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth);
//   RooGaussian    signal("signal", "A  Gaussian Lineshape", mass, m0, sigma);
  RooCBShape     cball("cball", "A  Crystal Ball Lineshape", mass, cbBias, cbSigma, cbCut, cbPower);

  mass.setBins(100000, "fft");
  RooFFTConvPdf BWxCB("BWxCB","bw (X) crystall ball", mass, bw, cball);


// Di-photon mass background  p.d.f.
  RooExponential bg("bg","bkgd exp", mass, expRate);

// Di-photon mass model p.d.f.
  RooAddPdf      model("model", "signal + background mass model", RooArgList(BWxCB, bg), RooArgList(nsig, nbkg));


  TStopwatch t ;
  t.Start() ;
  model.fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));
//   signal->fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));

  t.Print() ;

  TCanvas *c = new TCanvas("c","Unbinned Invariant Mass Fit", 0,0,800,600);
// Plot the fit results
  RooPlot* plot = mass.frame(Range(minMass,maxMass),Bins(nbins));

// Plot 1
//   dataB->plotOn(plot, MarkerColor(kRed), LineColor(kRed));
  data->plotOn(plot);
//   model.plotOn(plot);
  model.plotOn(plot);
  //model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(nsig, nbkg, m0, sigma)));
  model.paramOn(plot,
                Format(plotOpt, AutoPrecision(2) ),
                Parameters(RooArgSet(cbBias,
                                     cbSigma,
                                     cbCut,
                                     cbPower,
                                     bwMean,
                                     bwWidth,
                                     expRate,
                                     nsig,
                                     nbkg)),
                Layout(.67, 0.97, 0.97),
                ShowConstants(kTRUE) );

//   model.plotOn(plot, Components("signal"), LineStyle(kDashed), LineColor(kRed));
  model.plotOn(plot, Components("bg"), LineStyle(kDashed), LineColor(kRed));


  plot->Draw();

//   TLatex *   tex = new TLatex(0.2,0.8,"CMS preliminary");
//   tex->SetNDC();
//   tex->SetTextFont(42);
//   tex->SetLineWidth(2);
//   tex->Draw();
//   tex->DrawLatex(0.2, 0.725, "7 TeV Data, L = 258 pb^{-1}");
//
//   float fsig_peak = NormalizedIntegral(model,
//                       mass,
//                       cbBias.getVal() - 2.5*cbSigma.getVal(),
//                       cbBias.getVal() + 2.5*cbSigma.getVal()
//                     );

//   float fbkg_peak = NormalizedIntegral(bg,
//                       mass,
//                       m0.getVal() - 2.5*sigma.getVal(),
//                       m0.getVal() + 2.5*sigma.getVal()
//                     );

/*  double nsigVal = fsig_peak * nsig.getVal();
  double nsigErr = fsig_peak * nsig.getError();
  double nsigErrRel = nsigErr / nsigVal;*/
//   double nbkgVal = fbkg_peak * nbkg.getVal();
//   double nbkgErr = fbkg_peak * nbkg.getError();
//   double nbkgErrRel = nbkgErr / nbkgVal;

//   cout << "nsig " << nsigVal << " +/- " << nsigErr << endl;
//   cout << "S/B_{#pm2.5#sigma} " << nsigVal/nbkgVal << " +/- "
//     << (nsigVal/nbkgVal)*sqrt(nsigErrRel*nsigErrRel + nbkgErrRel*nbkgErrRel)
//     << endl;

//   tex->DrawLatex(0.2, 0.6, Form("N_{S} = %.0f#pm%.0f", nsigVal, nsigErr) );
//   tex->DrawLatex(0.2, 0.525, Form("S/B_{#pm2.5#sigma} = %.1f", nsigVal/nbkgVal) );
//   tex->DrawLatex(0.2, 0.45, Form("#frac{S}{#sqrt{B}}_{#pm2.5#sigma} = %.1f", nsigVal/sqrt(nbkgVal)));

//   leg = new TLegend(0.65,0.6,0.9,0.75);
//   leg->SetFillColor(kWhite);
//   leg->SetLineColor(kWhite);
//   leg->SetShadowColor(kWhite);
//   leg->SetTextFont(42);

//   TLegendEntry * ldata  = leg->AddEntry(data, "Opposite Sign");
//   TLegendEntry * ldataB = leg->AddEntry(dataB, "Same Sign");
//   ldata->SetMarkerStyle(20);
//   ldataB->SetMarkerStyle(20);
//   ldataB->SetMarkerColor(kRed);

//   leg->Draw();

  return model;

}
Exemple #26
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() ;

}
void RooToyMCFit(){
    stringstream out;
   out.str("");
   out << "toyMC_" << _sigma_over_tau << "_" << _purity << "_" << mistag_rate << ".root";
   TFile* file = TFile::Open(out.str().c_str());
   TTree* tree = (TTree*)file->Get("ToyTree");
   tree->Print();

//    TFile* file = TFile::Open("ToyData/toyMC_453_0.912888_0.3_0.8_0.root");
//    TFile* file = TFile::Open("ToyData/toyMC_10000_0.9_0.3_0.8_0.root");
//    TTree* tree = (TTree*)file->Get("ToyTree1");

    RooRealVar tau("tau","tau",_tau,"ps"); tau.setConstant(kTRUE);
    RooRealVar dm("dm","dm",_dm,"ps^{-1}"); dm.setConstant(kTRUE);

    RooAbsReal* sin2beta;
    RooAbsReal* cos2beta;
    if(softlimit){
      RooRealVar x("x","x",_cos2beta,-3.,30000.); if(constBeta) x.setConstant(kTRUE);
      RooRealVar y("y","y",_sin2beta,-3.,30000.); if(constBeta) y.setConstant(kTRUE);
      cos2beta = new RooFormulaVar("cos2beta","cos2beta","@0/sqrt(@0*@0+@1*@1)",RooArgSet(x,y));
      sin2beta = new RooFormulaVar("sin2beta","sin2beta","@0/sqrt(@0*@0+@1*@1)",RooArgSet(y,x));
//      sin2beta = new RooFormulaVar("sin2beta","sin2beta","2/TMath::Pi()*TMath::ATan(@0)",RooArgSet(y));
//      cos2beta = new RooFormulaVar("cos2beta","cos2beta","2/TMath::Pi()*TMath::ATan(@0)",RooArgSet(x));
    }
    else{ 
      sin2beta = new RooRealVar("sin2beta","sin2beta",_sin2beta,-3.,3.); if(constBeta) ((RooRealVar*)sin2beta)->setConstant(kTRUE);
      cos2beta = new RooRealVar("cos2beta","cos2beta",_cos2beta,-3.,3.); if(constBeta) ((RooRealVar*)cos2beta)->setConstant(kTRUE);
    }
    RooRealVar dt("dt","#Deltat",-5.,5.,"ps");
    RooRealVar avgMisgat("avgMisgat","avgMisgat",mistag_rate,0.0,0.5); if(constMistag) avgMisgat.setConstant(kTRUE);
    RooRealVar delMisgat("delMisgat","delMisgat",0); delMisgat.setConstant(kTRUE);
    RooRealVar mu("mu","mu",0); mu.setConstant(kTRUE);

    tau.Print();
    dm.Print();
    sin2beta->Print();
    cos2beta->Print();
    avgMisgat.Print();

    RooRealVar moment("moment","moment",0.); moment.setConstant(kTRUE);
    RooRealVar parity("parity","parity",-1.); parity.setConstant(kTRUE);

    RooRealVar* K[8];
    RooAbsReal* Kb[8];
    RooArgList Kset;
    RooRealVar* C[8];
    RooRealVar* S[8];
    RooFormulaVar* a1[2][8];
    RooFormulaVar* b1[2][8];
    RooFormulaVar* a2[2][8];
    RooFormulaVar* b2[2][8];

    for(int i=0; i<8; i++){
        out.str("");
        out << "K" << i+1;
        K[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_K[i],0.,1.); Kset.add(*K[i]); if(constK) K[i]->setConstant(kTRUE);
        K[i]->Print();
        if(i!=7){
          out.str("");
          out << "Kb" << i+1;
          Kb[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_Kb[i],0.,1.); Kset.add(*Kb[i]); if(constK) ((RooRealVar*)Kb[i])->setConstant(kTRUE);
          Kb[i]->Print();
        }
        out.str("");
        out << "C" << i+1;
        C[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_C[i]); C[i]->setConstant(kTRUE);
        C[i]->Print();
        out.str("");
        out << "S" << i+1;
        S[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_S[i]); S[i]->setConstant(kTRUE);
        S[i]->Print();
    }
    Kb[7] = new RooFormulaVar("K8b","K8b","1-@0-@1-@2-@3-@4-@5-@6-@7-@8-@9-@10-@11-@12-@13-@14",Kset);

    for(int i=0; i<8; i++){
        out.str("");
        out << "a10_" << i+1;
        a1[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a1[0][i]->Print();
        out.str("");
        out << "a11_" << i+1;
        a1[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a1[1][i]->Print();
        out.str("");
        out << "a20_" << i+1;
        a2[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a2[0][i]->Print();
        out.str("");
        out << "a21_" << i+1;
        a2[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a2[1][i]->Print();

        out.str("");
        out << "b10_" << i+1;
        b1[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b1[0][i]->Print();
        out.str("");
        out << "b11_" << i+1;
        b1[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b1[1][i]->Print();
        out.str("");
        out << "b20_" << i+1;
        b2[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b2[0][i]->Print();
        out.str("");
        out << "b21_" << i+1;
        b2[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b2[1][i]->Print();

        cout << "bin = " << i+1 << endl;
        cout << "  a11 = " << a1[0][i]->getVal() << " b11 = " << b1[0][i]->getVal() << endl;
        cout << "  a12 = " << a1[1][i]->getVal() << " b12 = " << b1[1][i]->getVal() << endl;
        cout << "  a21 = " << a2[0][i]->getVal() << " b21 = " << b2[0][i]->getVal() << endl;
        cout << "  a22 = " << a2[1][i]->getVal() << " b22 = " << b2[1][i]->getVal() << endl;
    }

    RooRealVar* dgamma = new RooRealVar("dgamma","dgamma",0.); dgamma->setConstant(kTRUE);
    RooRealVar* f0 = new RooRealVar("f0","f0",1.);             f0->setConstant(kTRUE);
    RooRealVar* f1 = new RooRealVar("f1","f1",0.);             f1->setConstant(kTRUE);

    RooCategory tag("tag","tag");
    tag.defineType("B0",1);
    tag.defineType("anti-B0",-1);

    RooCategory bin("bin","bin");
    bin.defineType("1",1);
    bin.defineType("2",2);
    bin.defineType("3",3);
    bin.defineType("4",4);
    bin.defineType("5",5);
    bin.defineType("6",6);
    bin.defineType("7",7);
    bin.defineType("8",8);
    bin.defineType("-1",-1);
    bin.defineType("-2",-2);
    bin.defineType("-3",-3);
    bin.defineType("-4",-4);
    bin.defineType("-5",-5);
    bin.defineType("-6",-6);
    bin.defineType("-7",-7);
    bin.defineType("-8",-8);

    
    RooSuperCategory bintag("bintag","bintag",RooArgSet(bin,tag));

    tree->Print();

    RooDataSet d("data","data",tree,RooArgSet(dt,bin,tag));
    cout << "DataSet is ready." << endl;
    d.Print();

    RooRealVar mean("mean","mean",0.,"ps"); mean.setConstant(kTRUE);
    RooRealVar sigma("sigma","sigma",_sigma_over_tau*_tau,0.,1.5*_tau,"ps"); if(constSigma) sigma.setConstant(kTRUE);
    RooGaussModel rf("rf","rf",dt,mean,sigma);
//    RooTruthModel rf("rf","rf",dt);
    RooGaussian rfpdf("rfpdf","rfpdf",dt,mean,sigma);

    cout << "Preparing PDFs..." << endl;
//    RooRealVar* fsigs1[8];
//    RooRealVar* fsigs1b[8];
//    RooRealVar* fsigs2[8];
//    RooRealVar* fsigs2b[8];
    RooBDecay* sigpdfs1[8];
    RooBDecay* sigpdfs1b[8];
    RooBDecay* sigpdfs2[8];
    RooBDecay* sigpdfs2b[8];
    RooAddPdf* PDFs1[8];
    RooAddPdf* PDFs1b[8];
    RooAddPdf* PDFs2[8];
    RooAddPdf* PDFs2b[8];
    RooAddPdf* pdfs1[8];
    RooAddPdf* pdfs1b[8];
    RooAddPdf* pdfs2[8];
    RooAddPdf* pdfs2b[8];
    RooSimultaneous pdf("pdf","pdf",bintag);
    RooRealVar fsig("fsig","fsig",_purity,0.,1.); if(constFSig) fsig.setConstant(kTRUE);
    fsig.Print();
    for(int j=0; j<8; j++){
//        out.str("");
//        out << "fsig1" << j+1;
//        fsigs1[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.);  if(constFSig) fsigs1[j]->setConstant(kTRUE);
//        out.str("");
//        out << "fsig1b" << j+1;
//        fsigs1b[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.); if(constFSig) fsigs1b[j]->setConstant(kTRUE);
//        out.str("");
//        out << "fsig2" << j+1;
//        fsigs2[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.);  if(constFSig) fsigs2[j]->setConstant(kTRUE);
//        out.str("");
//        out << "fsig2b" << j+1;
//        fsigs2b[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.); if(constFSig) fsigs2b[j]->setConstant(kTRUE);

        out.str("");
        out << "sigpdf1" << j+1;
        sigpdfs1[j]  = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a1[0][j],*b1[0][j],dm,rf,RooBDecay::DoubleSided);
        out.str("");
        out << "sigpdf1b" << j+1;
        sigpdfs1b[j] = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a1[1][j],*b1[1][j],dm,rf,RooBDecay::DoubleSided);
        out.str("");
        out << "sigpdf2" << j+1;
        sigpdfs2[j]  = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a2[0][j],*b2[0][j],dm,rf,RooBDecay::DoubleSided);
        out.str("");
        out << "sigpdf2b" << j+1;
        sigpdfs2b[j] = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a2[1][j],*b2[1][j],dm,rf,RooBDecay::DoubleSided);

        out.str("");
        out << "PDF1" << j+1;
        PDFs1[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs1[j],rfpdf),RooArgList(fsig));
        out.str("");
        out << "PDF1b" << j+1;
        PDFs1b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs1b[j],rfpdf),RooArgList(fsig));
        out.str("");
        out << "PDF2" << j+1;
        PDFs2[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs2[j],rfpdf),RooArgList(fsig));
        out.str("");
        out << "PDF2b" << j+1;
        PDFs2b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs2b[j],rfpdf),RooArgList(fsig));

        //Adding mistaging
        out.str("");
        out << "pdf1" << j+1;
        pdfs1[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs2[j],*PDFs1[j]),RooArgList(avgMisgat));
        out.str("");
        out << "pdf1b" << j+1;
        pdfs1b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs2b[j],*PDFs1b[j]),RooArgList(avgMisgat));
        out.str("");
        out << "pdf2" << j+1;
        pdfs2[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs1[j],*PDFs2[j]),RooArgList(avgMisgat));
        out.str("");
        out << "pdf2b" << j+1;
        pdfs2b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs1b[j],*PDFs2b[j]),RooArgList(avgMisgat));

        out.str("");
        out << "{" << j+1 << ";B0}";
        pdf.addPdf(*pdfs1[j],out.str().c_str());
        out.str("");
        out << "{" << -(j+1) << ";B0}";
        pdf.addPdf(*pdfs1b[j],out.str().c_str());
        out.str("");
        out << "{" << j+1 << ";anti-B0}";
        pdf.addPdf(*pdfs2[j],out.str().c_str());
        out.str("");
        out << "{" << -(j+1) << ";anti-B0}";
        pdf.addPdf(*pdfs2b[j],out.str().c_str());
    }

    cout << "Fitting..." << endl;
    pdf.fitTo(d,Verbose(),Timer());
    dt.setBins(50);

    cout << "Drawing plots." << endl;
    for(int i=0; i<8; i++){
        RooPlot* dtFrame = dt.frame();
        out.str("");
        out << "tag == 1 && bin == " << i+1;
        RooDataSet* ds = d.reduce(out.str().c_str());
        ds->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kBlue));

        out.str("");
        out << "{" << j+1 << ";B0}";
        bintag = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*ds),Slice(bintag),LineColor(kBlue));
        double chi2 = dtFrame->chiSquare();

        out.str("");
        out << "tag == -1 && bin == " << i+1;
        RooDataSet* dsb = d.reduce(out.str().c_str());
        dsb->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kRed));

        out.str("");
        out << "{" << j+1 << ";anti-B0}";
        bintag = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*dsb),Slice(bintag),LineColor(kRed));
        double chi2b = dtFrame->chiSquare();

        out.str("");
        out << "#Delta t, toy MC, bin == " << i+1;
        TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
        cm->cd();
        dtFrame->GetXaxis()->SetTitleSize(0.05);
        dtFrame->GetXaxis()->SetTitleOffset(0.85);
        dtFrame->GetXaxis()->SetLabelSize(0.05);
        dtFrame->GetYaxis()->SetTitleOffset(1.6);

        TPaveText *ptB = new TPaveText(0.7,0.65,0.98,0.99,"brNDC");
        ptB->SetFillColor(0);
        ptB->SetTextAlign(12);
        out.str("");
        out << "bin = " << (i+1);
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(B^{0}) = " << chi2;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(#barB^{0}) = " << chi2b;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#sigma/#tau = " << _sigma_over_tau;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "purity = " << _purity;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "mistag = " << mistag_rate;
        ptB->AddText(out.str().c_str());

        dtFrame->Draw();
        ptB->Draw();

        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << (i+1) << ".root";
        cm->Print(out.str().c_str());
        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << (i+1) << ".png";
        cm->Print(out.str().c_str());
    }

    for(int i=0; i<8; i++){
        RooPlot* dtFrame = dt.frame();
        out.str("");
        out << "tag == 1 && bin == " << -(i+1);
        RooDataSet* ds2 = (RooDataSet*)d.reduce(out.str().c_str());
        ds2->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kBlue));

        out.str("");
        out << "{" << -(j+1) << ";B0}";
        bintag = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*ds2),Slice(bintag),LineColor(kBlue));
        double chi2 = dtFrame->chiSquare();

        out.str("");
        out << "tag == -1 && bin == " << -(i+1);
        RooDataSet* ds2b = (RooDataSet*)d.reduce(out.str().c_str());
        ds2b->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kRed));

        out.str("");
        out << "{" << -(j+1) << ";anti-B0}";
        bin = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*ds2b),Slice(bintag),LineColor(kRed));
        double chi2b = dtFrame->chiSquare();

        out.str("");
        out << "#Delta t, toy MC, bin == " << -(i+1);
        TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
        cm->cd();
        dtFrame->GetXaxis()->SetTitleSize(0.05);
        dtFrame->GetXaxis()->SetTitleOffset(0.85);
        dtFrame->GetXaxis()->SetLabelSize(0.05);
        dtFrame->GetYaxis()->SetTitleOffset(1.6);

        TPaveText *ptB = new TPaveText(0.7,0.65,0.98,0.99,"brNDC");
        ptB->SetFillColor(0);
        ptB->SetTextAlign(12);
        out.str("");
        out << "bin = " << -(i+1);
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(B^{0}) = " << chi2;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(#barB^{0}) = " << chi2b;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#sigma/#tau = " << _sigma_over_tau;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "purity = " << _purity;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "mistag = " << mistag_rate;
        ptB->AddText(out.str().c_str());

        dtFrame->Draw();
        ptB->Draw();

        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << -(i+1) << ".root";
        cm->Print(out.str().c_str());
        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << -(i+1) << ".png";
        cm->Print(out.str().c_str());
    }

    return;
}
Exemple #28
0
void MakePlots(RooWorkspace* ws){

  // Here we make plots of the discriminating variable (invMass) after the fit
  // and of the control variable (isolation) after unfolding with sPlot.
  std::cout << "make plots" << std::endl;

  // make our canvas
  TCanvas* cdata = new TCanvas("sPlot","sPlot demo", 400, 600);
  cdata->Divide(1,3);

  // get what we need out of the workspace
  RooAbsPdf* model = ws->pdf("model");
  RooAbsPdf* zModel = ws->pdf("zModel");
  RooAbsPdf* qcdModel = ws->pdf("qcdModel");

  RooRealVar* isolation = ws->var("isolation");
  RooRealVar* invMass = ws->var("invMass");

  // note, we get the dataset with sWeights
  RooDataSet* data = (RooDataSet*) ws->data("dataWithSWeights");

  // this shouldn't be necessary, need to fix something with workspace
  // do this to set parameters back to their fitted values.
  model->fitTo(*data, Extended() );

  //plot invMass for data with full model and individual componenets overlayed
  //  TCanvas* cdata = new TCanvas();
  cdata->cd(1);
  RooPlot* frame = invMass->frame() ; 
  data->plotOn(frame ) ; 
  model->plotOn(frame) ;   
  model->plotOn(frame,Components(*zModel),LineStyle(kDashed), LineColor(kRed)) ;   
  model->plotOn(frame,Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;   
    
  frame->SetTitle("Fit of model to discriminating variable");
  frame->Draw() ;
 

  // Now use the sWeights to show isolation distribution for Z and QCD.  
  // The SPlot class can make this easier, but here we demonstrait in more
  // detail how the sWeights are used.  The SPlot class should make this 
  // very easy and needs some more development.

  // Plot isolation for Z component.  
  // Do this by plotting all events weighted by the sWeight for the Z component.
  // The SPlot class adds a new variable that has the name of the corresponding
  // yield + "_sw".
  cdata->cd(2);

  // create weightfed data set 
  RooDataSet * dataw_z = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"zYield_sw") ;

  RooPlot* frame2 = isolation->frame() ; 
  dataw_z->plotOn(frame2, DataError(RooAbsData::SumW2) ) ; 
    
  frame2->SetTitle("isolation distribution for Z");
  frame2->Draw() ;

  // Plot isolation for QCD component.  
  // Eg. plot all events weighted by the sWeight for the QCD component.
  // The SPlot class adds a new variable that has the name of the corresponding
  // yield + "_sw".
  cdata->cd(3);
  RooDataSet * dataw_qcd = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"qcdYield_sw") ;
  RooPlot* frame3 = isolation->frame() ; 
  dataw_qcd->plotOn(frame3,DataError(RooAbsData::SumW2) ) ; 
    
  frame3->SetTitle("isolation distribution for QCD");
  frame3->Draw() ;

  //  cdata->SaveAs("SPlot.gif");

}
RooGaussian fitZToMuMuGammaMassUnbinned(const char *filename = "ZToMuMuGammaMass.txt",
  const char* plotOpt = "NEU",
  const int nbins = 25)
{
  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  gStyle->SetPadRightMargin(0.05);

  double minMass = 60;
  double maxMass = 120;
  RooRealVar  mass("mass","M(#mu#mu#gamma})", minMass, maxMass,"GeV/c^{2}");

  // Read data set

  RooDataSet *data = RooDataSet::read(filename,RooArgSet(mass));
//   RooDataSet *dataB = RooDataSet::read(filenameB,RooArgSet(mass));

// Build p.d.f.

////////////////////////////////////////////////
//             Parameters                     //
////////////////////////////////////////////////

//  Signal p.d.f. parameters
//  Parameters for a Gaussian and a Crystal Ball Lineshape
  RooRealVar  m0   ("m_{0}", "Bias", 91.19, minMass, maxMass,"GeV/c^{2}");
  RooRealVar  sigma("#sigma","Width", 3.0,1.0,10.0,"GeV/c^{2}");
  RooRealVar  cut  ("#alpha","Cut", 0.6,0.6,2.0);
  RooRealVar  power("power","Power", 10.0, 0.5, 20.0);


//  Background p.d.f. parameters
//  Parameters for a polynomial lineshape
  RooRealVar  c0("c_{0}", "c0", 0., -10, 10);
  RooRealVar  c1("c_{1}", "c1", 0., -100, 0);
  RooRealVar  c2("c_{2}", "c2", 0., -100, 100);
//  c0.setConstant();

// fraction of signal
//  RooRealVar  frac("frac", "Signal Fraction", 0.1,0.,0.3.);
  RooRealVar  nsig("N_{S}", "#signal events", 9000, 0.,10000.);
  RooRealVar  nbkg("N_{B}", "#background events", 1000,2,10000.);



////////////////////////////////////////////////
//               P.D.F.s                      //
////////////////////////////////////////////////

// Di-photon mass signal p.d.f.
  RooGaussian    signal("signal", "A  Gaussian Lineshape", mass, m0, sigma);
  // RooCBShape     signal("signal", "A  Crystal Ball Lineshape", mass, m0,sigma, cut, power);

// Di-photon mass background  p.d.f.
  RooPolynomial bg("bg", "Backgroung Distribution", mass, RooArgList(c0,c1));

// Di-photon mass model p.d.f.
//  RooAddPdf      model("model", "Di-photon mass model", signal, bg, frac);
  RooAddPdf      model("model", "Di-photon mass model", RooArgList(signal, bg), RooArgList(nsig, nbkg));


  TStopwatch t ;
  t.Start() ;
//   model->fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));
  signal->fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));

  t.Print() ;

  c = new TCanvas("c","Unbinned Invariant Mass Fit", 0,0,800,600);
// Plot the fit results
  RooPlot* plot = mass.frame(Range(minMass,maxMass),Bins(nbins));

// Plot 1
//   dataB->plotOn(plot, MarkerColor(kRed), LineColor(kRed));
  data->plotOn(plot);
//   model.plotOn(plot);
  model.plotOn(plot);
  //model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(nsig, nbkg, m0, sigma)));
  model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(m0, sigma)));

  /// model.plotOn(plot, Components("signal"), LineStyle(kDashed), LineColor(kRed));

//   model.plotOn(plot, Components("bg"), LineStyle(kDashed), LineColor(kRed));


  plot->Draw();

  TLatex *   tex = new TLatex(0.2,0.8,"CMS preliminary");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetLineWidth(2);
  tex->Draw();
  tex->DrawLatex(0.2, 0.725, "7 TeV Data, L = 258 pb^{-1}");

  float fsig_peak = NormalizedIntegral(signal,
                      mass,
                      m0.getVal() - 2.5*sigma.getVal(),
                      m0.getVal() + 2.5*sigma.getVal()
                    );

//   float fbkg_peak = NormalizedIntegral(bg,
//                       mass,
//                       m0.getVal() - 2.5*sigma.getVal(),
//                       m0.getVal() + 2.5*sigma.getVal()
//                     );

  double nsigVal = fsig_peak * nsig.getVal();
  double nsigErr = fsig_peak * nsig.getError();
  double nsigErrRel = nsigErr / nsigVal;
//   double nbkgVal = fbkg_peak * nbkg.getVal();
//   double nbkgErr = fbkg_peak * nbkg.getError();
//   double nbkgErrRel = nbkgErr / nbkgVal;

  cout << "nsig " << nsigVal << " +/- " << nsigErr << endl;
//   cout << "S/B_{#pm2.5#sigma} " << nsigVal/nbkgVal << " +/- "
//     << (nsigVal/nbkgVal)*sqrt(nsigErrRel*nsigErrRel + nbkgErrRel*nbkgErrRel)
//     << endl;

//   tex->DrawLatex(0.2, 0.6, Form("N_{S} = %.0f#pm%.0f", nsigVal, nsigErr) );
//   tex->DrawLatex(0.2, 0.525, Form("S/B_{#pm2.5#sigma} = %.1f", nsigVal/nbkgVal) );
//   tex->DrawLatex(0.2, 0.45, Form("#frac{S}{#sqrt{B}}_{#pm2.5#sigma} = %.1f", nsigVal/sqrt(nbkgVal)));

  leg = new TLegend(0.65,0.6,0.9,0.75);
  leg->SetFillColor(kWhite);
  leg->SetLineColor(kWhite);
  leg->SetShadowColor(kWhite);
  leg->SetTextFont(42);

//   TLegendEntry * ldata  = leg->AddEntry(data, "Opposite Sign");
//   TLegendEntry * ldataB = leg->AddEntry(dataB, "Same Sign");
//   ldata->SetMarkerStyle(20);
//   ldataB->SetMarkerStyle(20);
//   ldataB->SetMarkerColor(kRed);

  leg->Draw();

  return signal;

}
Exemple #30
0
void runUPWW() {
  
  int higgsMass=125;
  double intLumi=5.1;
  int nToys = 10;
  bool draw=true;
  
  using namespace RooFit;
  
  gROOT->ProcessLine(".L ~/tdrstyle.C");
  setTDRStyle();
  gStyle->SetPadLeftMargin(0.16);
  gROOT->ForceStyle();
  gROOT->ProcessLine(".L statsFactory.cc+");
  
  //
  // set up test kind 
  // 
  
  double sigRate;
  double bkgRate;
  
  if(higgsMass==125){
    sigRate = 7.;
    bkgRate = 66.;
  }else{
    cout << "HMMMM.... I don't know that mass point...BYE!" << endl;
    return;
  }
  
  RooRealVar* mll  = new RooRealVar("mll","dilepton mass [GeV]", 12, 80.);
  mll->setBins(17);
  
  RooArgSet* obs = new RooArgSet(*mll) ;
  
  // read signal hypothesis 1
  TChain *tsigHyp1 = new TChain("angles");
  tsigHyp1->Add(Form("datafiles/bdtpresel/%i/SMHiggsWW_%i_JHU.root",higgsMass, higgsMass));
  RooDataSet *sigHyp1Data = new RooDataSet("sigHyp1Data","sigHyp1Data",tsigHyp1,*obs);
  RooDataHist *sigHyp1Hist = sigHyp1Data->binnedClone(0);
  RooHistPdf* sigHyp1Pdf = new RooHistPdf("sigHyp1Pdf", "sigHyp1Pdf", *obs, *sigHyp1Hist);

  // read background
  TChain *bkgTree = new TChain("angles");
  bkgTree->Add(Form("datafiles/bdtpresel/%i/WW_madgraph_8TeV.root",higgsMass));
  RooDataSet *bkgData = new RooDataSet("bkgData","bkgData",bkgTree,*obs);
  RooDataHist *bkgHist = bkgData->binnedClone(0);
  RooHistPdf* bkgPdf = new RooHistPdf("bkgPdf", "bkgPdf", *obs, *bkgHist);
    
  char statResults[25];
  statsFactory *hwwuls;
  sprintf(statResults,"uls_hww125_%.0ffb.root", intLumi);
  hwwuls = new statsFactory(obs, sigHyp1Pdf, sigHyp1Pdf, statResults);
  hwwuls->runUpperLimitWithBackground(sigRate*intLumi, bkgRate*intLumi, bkgPdf, nToys);
  delete hwwuls;
  

  // draw plots 
  if(draw) {
    RooPlot* plot1 = mll->frame();
    TString plot1Name = "mll";
    TCanvas* c1 = new TCanvas("c1","c1",400,400); 
    
    bkgData->plotOn(plot1,MarkerColor(kBlack));
    bkgPdf->plotOn(plot1, LineColor(kBlack), LineStyle(kDashed));
    sigHyp1Data->plotOn(plot1,MarkerColor(kRed));
    sigHyp1Pdf->plotOn(plot1,LineColor(kRed), LineStyle(kDashed));      
    
    // draw...
    plot1->Draw();
    c1->SaveAs(Form("plots/ul/epsfiles/%s.eps", plot1Name.Data()));
    c1->SaveAs(Form("plots/ul/pngfiles/%s.png", plot1Name.Data()));
    
    delete c1;
  }
  
  
}