void simplePrintResults() { vector<string> filenames; filenames.push_back("Output/Test2/result/FIT_DATA_Psi2SJpsi_PPPrompt_Bkg_SecondOrderChebychev_pt65300_rap016_cent0200_262620_263757.root"); const char* parname = "N_Jpsi_PP"; vector<string>::iterator it = filenames.begin(); for (it; it<filenames.end(); it++) { TFile *f = new TFile(it->c_str()); if (!f) { cout << "Error, " << *it << " not found" << endl; continue; } RooWorkspace *ws = (RooWorkspace*) f->Get("workspace"); if (!ws) { cout << "Error, workspace not found in " << *it << endl; continue; } RooRealVar *var = ws->var(parname); if (!ws) { cout << "Error, variable " << parname << " not found in " << *it << endl; continue; } cout << *it << " " << var->getVal() << " +- " << var->getError() << endl; } }
RooStats::ModelConfig * Tprime::SetBModel( void ) { // // Define model config and parameter snapshot to describe the b model. // Import to workspace. // std::string legend = "[Tprime::SetBModel]: "; // full signal+background model //RooStats::ModelConfig * pSBModel = (RooStats::ModelConfig *)pWs->genobj("ModelConfig"); // let's make the b model (bg-only) from the alt model (s+b) with xsec=0 //RooStats::ModelConfig * pBModel = // new RooStats::ModelConfig(*(RooStats::ModelConfig *)pWs->genobj("ModelConfig")); RooStats::ModelConfig * _sbModel = (RooStats::ModelConfig *)pWs->genobj("ModelConfig"); RooStats::ModelConfig * pBModel = _sbModel->Clone("BModel"); //pBModel->SetName("BModel"); pBModel->SetWorkspace(*pWs); //pBModel->SetParametersOfInterest(RooArgSet()); pWs->import(*pBModel); // set POI to the b model value and take snapshot RooRealVar * pPoi = (RooRealVar *)pBModel->GetParametersOfInterest()->first(); pPoi->setVal(0.0); pBModel->SetSnapshot(*pPoi); pBModel->Print(); return pBModel; }
void PEs(RooAbsPdf *iGen,RooAbsPdf *iFit,int iN,int iNEvents,RooRealVar &iVar,RooRealVar &iSig,RooRealVar &iMean, RooRealVar &iScale,RooRealVar &iRes) { double iM0 = iMean.getVal(); double iS0 = iSig.getVal(); //iScale.setVal(iMeanScale); iRes.setVal(iSigScale); TRandom1 *lRand = new TRandom1(0xDEADBEEF); TNtuple * lDN= new TNtuple( "xxx","xxx","ntot:m_r:m:merr:sig_r:sig:sigerr"); for(int i0=0;i0<iN;i0++){ if(i0 % 10 == 0) cout << "+++++++++++++++++++++++++++ running ======> " << i0 << endl; int lN = lRand->Poisson(iNEvents); RooDataSet * lSignal = iGen->generate(iVar,lN); iMean.setVal(iM0); iSig.setVal(iS0); iFit->fitTo(*lSignal,Strategy(1));//,Save(kTRUE),PrintLevel(1)); if(iMean.getError() < 0.05) iFit->fitTo(*lSignal,Strategy(2)); Float_t values[]={ (Float_t) lN, (Float_t) 90.78/iScale.getVal(), (Float_t) iMean.getVal(), (Float_t) iMean.getError(), (Float_t) iSig.getVal(), (Float_t) iSig.getVal(), (Float_t) iSig.getError() }; lDN->Fill(values); } TFile *lF = new TFile("XXX.root","RECREATE"); lDN->Write(); lF->Close(); }
TGraph *graphLH(std::string nuisname, double err ){ w->loadSnapshot("bestfitall"); // SetTo BestFit values as start // Get The parameter we want RooRealVar *nuis =(RooRealVar*) w->var(nuisname.c_str()); double bf = nuis->getVal(); double nll_0=nll->getVal(); TGraph *gr = new TGraph(2*npoints+1); for (int i=-1*npoints;i<=npoints;i++){ nuis->setVal(bf+err*( ((float)i)*nsigma/npoints)); double nll_v = nll->getVal(); gr->SetPoint(i+npoints,nuis->getVal(),nll_v-nll_0); } gr->SetTitle(""); gr->GetYaxis()->SetTitle("NLL - obs data"); gr->GetYaxis()->SetTitleOffset(1.1); gr->GetXaxis()->SetTitleSize(0.05); gr->GetYaxis()->SetTitleSize(0.05); gr->GetXaxis()->SetTitle(nuisname.c_str()); gr->SetLineColor(4); gr->SetLineWidth(2); gr->SetMarkerStyle(21); gr->SetMarkerSize(0.6); return gr; }
RooAbsPdf *MakeModelNoSignal(RooDataHist *data, RooRealVar *mww, char *name) { char *modelName = (char*)calloc(50, sizeof(char)); strcat(modelName, name); strcat(modelName, "model"); char *signalName = (char*)calloc(50, sizeof(char)); char *backgroundName = (char*)calloc(50, sizeof(char)); strcat(signalName, name); strcat(signalName, "signal"); strcat(backgroundName, name); strcat(backgroundName, "background"); char *meanName = (char*)calloc(50, sizeof(char)); strcat(meanName, name); strcat(meanName, "mean"); char *sigmaName = (char*)calloc(50, sizeof(char)); strcat(sigmaName, name); strcat(sigmaName, "sigma"); char *decayName = (char*)calloc(50, sizeof(char)); strcat(decayName, name); strcat(decayName, "decay"); char *weightName = (char*)calloc(50, sizeof(char)); strcat(weightName, name); strcat(weightName, "weight"); RooRealVar *decay = new RooRealVar(decayName, "decay", -10, 10, "GeV"); RooExponential *background = new RooExponential(backgroundName, "background", *mww, *decay); background->fitTo(*data); decay->setConstant(); return background; }
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"); } }
void Fitter::addBernFitModel(RooArgList *pdfs,RooArgList*coeffs, bool isLast) { if (nBernstein <=0 ) return; RooArgList * args = new RooArgList(); for(int b=0;b<nBernstein; b++) { string name = Form("fitmodel_bern_param_%d",b); RooRealVar *tmp = new RooRealVar(name.c_str(), name.c_str(), startBern_[b],0.01,100.); vars_ [ name ] = tmp; args -> add( *tmp ); } string name = Form("fitmodel_bern_%d",nBernstein); RooAbsPdf *bern; if (nBernstein ==1 ) bern= new RooBernsteinFast<1>(name.c_str(),name.c_str(),*x_, *args); if (nBernstein ==2 ) bern= new RooBernsteinFast<2>(name.c_str(),name.c_str(),*x_, *args); if (nBernstein ==3 ) bern= new RooBernsteinFast<3>(name.c_str(),name.c_str(),*x_, *args); if (nBernstein ==4 ) bern= new RooBernsteinFast<4>(name.c_str(),name.c_str(),*x_, *args); if (nBernstein ==5 ) bern= new RooBernsteinFast<5>(name.c_str(),name.c_str(),*x_, *args); if (nBernstein ==6 ) bern= new RooBernsteinFast<6>(name.c_str(),name.c_str(),*x_, *args); if (nBernstein ==7 ) bern= new RooBernsteinFast<7>(name.c_str(),name.c_str(),*x_, *args); pdfs->add( *bern ); if ( not isLast ){ // if I have other pdfs add fraction RooRealVar *f = new RooRealVar( Form("fitmodel_bern_frac") ,Form("fitmodel_bern_frac") , 0.3, 0.01,1.0 ); vars_[ f->GetName() ] = f; coeffs -> add ( *f ); } }
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 chi2(int xmin = 0, int xmax = 200, TString filename="../DsubMC/met2j0bIso2ewkScale_0_200.root", int nparam = 2){ RooAbsData::ErrorType errorType = RooAbsData::SumW2; file = new TFile(filename); RooRealVar* h = new RooRealVar("h","h",xmin,xmax); //Get Data TH1D* hData = file->Get("dataih"); hData->SetName("hData"); //hData->Draw(); RooDataHist* data = new RooDataHist("data","data",*h,hData); //Get Summed MC TH1D* hMC = file->Get("hh"); hMC->SetName("hMC"); hMC->Draw(); RooDataHist rdhMC("MC","MC",*h,hMC); RooHistPdf pdfMC("MCpdf","MCpdf",*h,rdhMC); //make (plot) the curves RooPlot* hFrame = h->frame(Name("hFrame")); data->plotOn(hFrame,RooFit::DataError(errorType)); pdfMC.plotOn(hFrame,ProjWData(*data),Components(pdfMC),Name("h_total")); //Determine Chi^2 double chi2fit = hFrame->chiSquare("h_total", "h_data", nparam); cout<<"Chi 2 / dof: "<<chi2fit<<endl; //Determine K-S double ks = hMC->KolmogorovTest(hData); cout<<"Kolmogorov-Smirnov: "<<ks<<endl; }
double Tprime::printMcmcUpperLimit( double peak, std::string filename ) { // // print out the upper limit on the first Parameter of Interest // RooStats::ModelConfig * _mc = (RooStats::ModelConfig *)pWs->genobj("ModelConfig"); RooRealVar * firstPOI = (RooRealVar*) _mc->GetParametersOfInterest()->first(); double _limit = mcInt->UpperLimit(*firstPOI); cout << "\n95% upper limit on " <<firstPOI->GetName()<<" is : "<< _limit <<endl; if (filename.size()!=0) { std::ofstream aFile; // append to file if exists aFile.open(filename.c_str(), std::ios_base::app); char buf[1024]; sprintf(buf, "%7.1f %7.6f", peak, _limit); aFile << buf << std::endl; // close outfile here so it is safe even if subsequent iterations crash aFile.close(); } return _limit; }
void PDF_GLWADS_Dpi_K3pi::setUncertainties(config c) { switch(c) { case lumi1fb: { obsErrSource = "1fb-1, ExpNll/sept2012K3PIResult.root"; TString File = this->dir+"/ExpNll/sept2012K3PIResult.root"; TFile *fr = TFile::Open(File); RooFitResult *r = (RooFitResult*)fr->Get("fitresult_model_reducedData_binned"); assert(r); for ( int i=0; i<nObs; i++ ) { RooRealVar* pObs = (RooRealVar*)((RooArgList*)observables)->at(i); RooRealVar* pRes = (RooRealVar*)r->floatParsFinal().find(obsTmkToMalcolm(pObs->GetName())); assert(pRes); StatErr[i] = pRes->getError(); } SystErr[0] = 0.010; // afav_dpi_obs SystErr[1] = 0.00011; // rp_dpi_obs SystErr[2] = 0.00011; // rm_dpi_obs fr->Close(); delete r; delete fr; break; } default: cout << "PDF_GLWADS_Dpi_K3pi::setUncertainties() : ERROR : config "+ConfigToTString(c)+" not found." << endl; exit(1); } }
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; }
void PDF_GLWADS_DKDpi_K3pi::setObservables(config c) { switch(c) { case truth:{ setObservablesTruth(); break; } case toy:{ setObservablesToy(); break; } case lumi1fb:{ obsValSource = "1fb-1, ExpNll/sept2012K3PIResult.root"; TString File = this->dir+"/ExpNll/sept2012K3PIResult.root"; TFile *fr = TFile::Open(File); RooFitResult *r = (RooFitResult*)fr->Get("fitresult_model_reducedData_binned"); assert(r); TIterator* it = observables->createIterator(); while ( RooRealVar* pObs = (RooRealVar*)it->Next() ) { RooRealVar* pRes = (RooRealVar*)r->floatParsFinal().find(obsTmkToMalcolm(pObs->GetName())); pObs->setVal(pRes->getVal()); } fr->Close(); delete r; delete fr; break; } case lumi3fb:{ obsValSource = "3fb-1 ANA v7 unblind"; // https://twiki.cern.ch/twiki/pub/LHCbPhysics/B2D0K/LHCb-ANA-2014-071-v7.pdf (see Vavas email 04/08/15) // these get transformed over from the new inputs using ExpNll/transportGLWADS_new_to_old.py // in the case of the DK only (robust) combination some of the observables don't exist // usemap as the temp store std::map< TString, double > vals; vals["rkp_k3pi_obs"] = 0.0793; vals["afav_dk_k3pi_obs"] = -0.0004; vals["afav_dpi_k3pi_obs"] = 0.0; vals["rp_dk_k3pi_obs"] = 0.018369; vals["rm_dk_k3pi_obs"] = 0.009611; vals["rp_dpi_k3pi_obs"] = 0.003683; vals["rm_dpi_k3pi_obs"] = 0.003857; // now can loop the observables and set the values TIterator* it = observables->createIterator(); while ( RooRealVar* pObs = (RooRealVar*)it->Next() ){ pObs->setVal(vals[pObs->GetName()]); } vals.clear(); break; } default:{ cout << "PDF_GLWADS_DKDpi_K3pi::setObservables() : ERROR : config "+ConfigToTString(c)+" not found." << endl; exit(1); } } }
void checkBestFitPoint(std::string workspace, std::string fitFile, bool splusb){ // Open the ws file... TFile *fd_=0; TFile *fw_=0; gSystem->Load("$CMSSW_BASE/lib/$SCRAM_ARCH/libHiggsAnalysisCombinedLimit.so"); gROOT->SetBatch(true); gStyle->SetOptFit(0); gStyle->SetOptStat(0); gStyle->SetPalette(1,0); fw_ = TFile::Open(workspace.c_str()); w = (RooWorkspace*) fw_->Get("w"); w->Print(); RooDataSet *data = (RooDataSet*) w->data("data_obs"); if (splusb) { mc_s = (RooStats::ModelConfig*)w->genobj("ModelConfig"); } else { mc_s = (RooStats::ModelConfig*)w->genobj("ModelConfig_bonly"); } std::cout << "make nll"<<std::endl; nll = mc_s->GetPdf()->createNLL( *data,RooFit::Constrain(*mc_s->GetNuisanceParameters()) ,RooFit::Extended(mc_s->GetPdf()->canBeExtended())); // Now get the best fit result fd_ = TFile::Open(fitFile.c_str()); RooFitResult *fit; if (splusb) { fit =(RooFitResult*)fd_->Get("fit_s"); } else { fit =(RooFitResult*)fd_->Get("fit_b"); } RooArgSet fitargs = fit->floatParsFinal(); std::cout << "Got the best fit values" <<std::endl; w->saveSnapshot("bestfitall",fitargs,true); TString filename; if (splusb) { filename = "minimum_s.pdf"; } else { filename = "minimum_b.pdf"; } // Now make the plots! TCanvas *c = new TCanvas("c","",600,600); c->SaveAs((filename+"[")); TIterator* iter(fitargs->createIterator()); for (TObject *a = iter->Next(); a != 0; a = iter->Next()) { RooRealVar *rrv = dynamic_cast<RooRealVar *>(a); std::string name = rrv->GetName(); TGraph *gr = graphLH(name,rrv->getError()); gr->Draw("ALP"); c->SaveAs((filename+"[")); } c->SaveAs((filename+"]")); }
// // set value and range for a variable in the workspace // void setValRange (RooWorkspace* workspace, const char* name, double val, double vmin, double vmax) { RooRealVar* var = workspace->var(name); if ( var ) { if ( vmax>vmin ) var->setRange(vmin,vmax); var->setVal(val); } }
void UL_significance_Hybrid(Model* model,int n_toys,int random_seed=0,double sig=1){ cout<<"///////////////////////////////////////////////////////////////////////////////////////////"<<endl; cout<<"Calculating significance with the Hybrid method"<<endl; cout<<"///////////////////////////////////////////////////////////////////////////////////////////"<<endl; //set the random seed RooRandom::randomGenerator()->SetSeed(random_seed); //get the calculator HybridCalculatorOriginal myhc(*model->get_data(),*model->get_sb_likelihood(),*model->get_b_likelihood()); //for numbercounting experiments myhc.PatchSetExtended(false); //set likelihood ratio as the test statistics myhc.SetTestStatistic(1); //define the systematics to be used if (model->get_nuisance_set()) { myhc.UseNuisance(true); myhc.SetNuisancePdf(*model->get_nuisance_prior_pdf()); myhc.SetNuisanceParameters(*model->get_nuisance_set()); } else { myhc.UseNuisance(false); } //define the number of toys to be done myhc.SetNumberOfToys(n_toys); //RooArgSet* poi= model->get_POI_set(); // poi->first()->Set(sig); RooRealVar* firstPOI = (RooRealVar*) model->get_POI_set()->first(); firstPOI->setVal(sig); //get the Hypotestresult HybridResult* hcResult = myhc.GetHypoTest(); double significance = hcResult->Significance(); double CLS= hcResult->CLs(); double CLB= hcResult->CLb(); double CLsplusb= hcResult->CLsplusb(); double CLSerror= hcResult->CLsError(); cout<<"POI: "<<sig<<endl; cout <<"significance:" << significance<<endl; cout<<"CLs: "<<CLS<<endl; cout<<"CLb: "<<CLB<<endl; cout<<"CLsplusb: "<<CLsplusb<<endl; cout<<"CLserror: "<<CLSerror<<endl; HybridPlot* plot=hcResult->GetPlot("hcPlot","p Values Plot",100); TCanvas *c1=new TCanvas; plot->Draw(); c1->SaveAs("hybrid_REsult"); }
RooRealVar* LoadParameters(string filename, string label, string parname ) { RooRealVar *newVar = 0; // now read in the parameters from the file. Stored in the file as // parameter manager | name | initial val | min | max | step fstream parameter_file(filename.c_str(), ios::in); if (! parameter_file) { cout << "Error: Couldn't open parameters file " << filename << endl; return false; } string name; string category; double initial_val, min, max, step; char c; Bool_t foundPar = kFALSE; while (true) { // skip white spaces and look for a # while(parameter_file.get(c)) { if (isspace(c) || c == '\n') continue; else if (c == '#') while (c != '\n') parameter_file.get(c); else { parameter_file.putback(c); break; } } if (parameter_file.fail()) break; parameter_file >> category >> name >> initial_val >> min >> max >> step; if (parameter_file.fail()) break; if (category == label && parname == name) { // create a new fit parameter newVar = new RooRealVar(name.c_str(),name.c_str(),initial_val,min, max); if (step == 0) { newVar->setConstant(kTRUE); } break; } } //end while loop if (!newVar) { cout << "Could not load parameter " << parname << " from file " << filename << " , category " << label << endl; assert(newVar); } return newVar; }
/// /// Set all observables to 'truth' values computed from the /// current parameters. /// void PDF_Abs::setObservablesTruth() { obsValSource = "truth"; for ( int i=0; i<nObs; i++ ) { RooRealVar* pObs = (RooRealVar*)((RooArgList*)observables)->at(i); pObs->setVal(((RooRealVar*)((RooArgList*)theory)->at(i))->getVal()); } }
/// /// Set each parameter in setMe to the value found in values. /// Do nothing if parameter is not found in values. /// void Utils::setParameters(const RooAbsCollection* setMe, const RooAbsCollection* values) { TIterator* it = setMe->createIterator(); while ( RooRealVar* p = (RooRealVar*)it->Next() ){ RooRealVar *var = (RooRealVar*)values->find(p->GetName()); if ( var ) p->setVal(var->getVal()); } delete it; }
void FitterUtils::initiateParams(RooArgSet* parset) { RooRealVar *var; TIterator *iter = parset->createIterator(); while((var = (RooRealVar*) iter->Next())) { if ( !var->isConstant() ) var->randomize(); } }
//#include "/uscms_data/d3/cvernier/DiH_13TeV/CMSSW_7_1_5/src/HiggsAnalysis/CombinedLimit/interface/RooMultiPdf.h" //#include "HiggsAnalysis/CombinedLimit/interface/RooMultiPdf.h" void makeRooMultiPdfWorkspace(){ // Load the combine Library gSystem->Load("libHiggsAnalysisCombinedLimit.so"); // Open the dummy H->gg workspace TFile *f_hgg = TFile::Open("w_background_Bern.root"); RooWorkspace *w_hgg = (RooWorkspace*)f_hgg->Get("HbbHbb"); // The observable (CMS_hgg_mass in the workspace) RooRealVar *mass = w_hgg->var("x"); // Get three of the functions inside, exponential, linear polynomial, power law RooAbsPdf *pdf_exp = w_hgg->pdf("bg_exp"); RooAbsPdf *pdf_pol = w_hgg->pdf("bg"); // Fit the functions to the data to set the "prefit" state (note this can and should be redone with combine when doing // bias studies as one typically throws toys from the "best-fit" RooAbsData *data = w_hgg->data("data_obs"); pdf_exp->fitTo(*data); // index 0 pdf_pol->fitTo(*data); // index 2 // Make a plot (data is a toy dataset) RooPlot *plot = mass->frame(); data->plotOn(plot); pdf_exp->plotOn(plot,RooFit::LineColor(kBlue)); pdf_pol->plotOn(plot,RooFit::LineColor(kRed)); plot->SetTitle("PDF fits to toy data"); plot->Draw(); // Make a RooCategory object. This will control which of the pdfs is "active" RooCategory cat("pdf_index","Index of Pdf which is active"); // Make a RooMultiPdf object. The order of the pdfs will be the order of their index, ie for below // 0 == exponential // 1 == linear function // 2 == powerlaw RooArgList mypdfs; mypdfs.add(*pdf_exp); mypdfs.add(*pdf_pol); RooMultiPdf multipdf("roomultipdf","All Pdfs",cat,mypdfs); // As usual make an extended term for the background with _norm for freely floating yield RooRealVar norm("roomultipdf_norm","Number of background events",0,10000); // Save to a new workspace TFile *fout = new TFile("background_pdfs.root","RECREATE"); RooWorkspace wout("backgrounds","backgrounds"); wout.import(cat); wout.import(norm); wout.import(multipdf); wout.Print(); wout.Write(); }
void rf706_histpdf_modified_makeroohistpdf() { // gROOT->SetBatch(kTRUE); //load data TFile *inHistos= new TFile("output/histos.root", "READ"); TH1F * h100 = (TH1F*)inHistos->Get("cutmassLb7"); TFile * inHistos2 = new TFile("../lambda/output/histos.root", "READ"); TH1F * h200 = (TH1F*)inHistos2->Get("cutmassLb7"); double massLb = 5500; double massLbmin = 5300; double massLbmax = 5650; RooRealVar *mass = new RooRealVar("mass","m(#Lambda_{b})",massLb,"MeV"); RooDataHist *hist1 = new RooDataHist("hist1","1D",RooArgList(*mass),h100); RooDataHist *hist2 = new RooDataHist("hist2","1D",RooArgList(*mass),h200); // Represent data in hist1 as pdf in *mass RooHistPdf histpdf1 = makeroohistpdf(hist1,mass) ; // Plot binned data and histogram pdf overlaid RooPlot* frame1 = mass->frame(Title("#Sigma^{0} data with RooHistPdf")) ; frame1->SetMaximum(1100); hist1->plotOn(frame1) ; histpdf1.plotOn(frame1) ; histpdf1.paramOn(frame1) ; TCanvas* c1 = new TCanvas("rf706_histpdf","rf706_histpdf",800,400) ; c1->Divide(1,2); c1->cd(1); frame1->Draw() ; //see what happens if I try to fit histpdf1 to lambda data RooHistPdf histpdf2 = makeroohistpdf(hist1,mass); RooAbsReal * nll = histpdf2.createNLL(*hist2,Extended(kTRUE)); RooMinuit m(*nll); m.setVerbose(kTRUE); m.migrad(); m.minos(); RooPlot* frame2 = mass->frame(Title("#Lambda^{0} data fit with RooHistPdf from #Sigma^{0} data")); frame2->SetMaximum(1100); hist2->plotOn(frame2); histpdf2.plotOn(frame2); histpdf2.paramOn(frame2); c1->cd(2); frame2->Draw(); //save histpdf1 // cout<<"saving histpdf1..."<<endl; // histpdf1.RooHistPdf::SavePrimitive(std::cout); // gROOT->SetPrimitive(kFALSE); }
double effRmsFromSigmaCB(double meanCB, double meanCB_err, double sigmaCB, double sigmaCB_err) { RooRealVar mass("zmass","m(e^{+}e^{-})",75,105,"GeV/c^{2}"); float zwidth=2.4952; RooRealVar bwMean("m_{Z}","BW Mean", 91.1876, "GeV/c^{2}"); RooRealVar bwWidth("#Gamma_{Z}", "BW Width", zwidth, "GeV/c^{2}"); RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", 0.00, -10, 10, "GeV/c^{2}"); // typical value RooRealVar cbSigma("#sigma_{CB}", "CB Width", 1.5, 0.8, 5.0, "GeV/c^{2}"); RooRealVar cbCut ("a_{CB}","CB Cut", 1.0, 1.0, 3.0); // typical value RooRealVar cbPower("n_{CB}","CB Order", 2.5, 0.1, 20.0); // typical value float mean_lo = meanCB - meanCB_err; float mean_hi = meanCB + meanCB_err; float sigma_lo = sigmaCB - sigmaCB_err; float sigma_hi = sigmaCB + sigmaCB_err; int nstep_mean = 10; int nstep_sigma = 10; float step_mean = 2*meanCB_err/float(nstep_mean); float step_sigma = 2*sigmaCB_err/float(nstep_sigma); double max_rms = 0.0; double min_rms = 999.; RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); int nsteps=0; for(float mean=mean_lo; mean<mean_hi; mean+=step_mean) { for(float sigma=sigma_lo; sigma<sigma_hi; sigma+=step_sigma) { cbBias.setVal(meanCB); cbSigma.setVal(sigma); RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth); RooCBShape cball("cball", "Crystal Ball", mass, cbBias, cbSigma, cbCut, cbPower); RooFFTConvPdf BWxCB("BWxCB", "bw X crystal ball", mass, bw, cball); RooDataSet *gendata = BWxCB.generate(mass,1000); TH1D *genh = (TH1D*) gendata->createHistogram("genh",mass,RooFit::Binning(100,75,105)); math::HistogramTools ht(genh); double rms = ht.effectiveSigma(); rms = sqrt(pow(rms,2)-pow(zwidth,2)); if(rms > max_rms) max_rms=rms; if(rms < min_rms) min_rms=rms; delete genh; nsteps++; } } return (max_rms-min_rms)/sqrt(12)/sqrt(nsteps); }
void GetNominalValueNuisancePara(){ TIterator *it = mc->GetNuisanceParameters()->createIterator(); RooRealVar *var = NULL; if (MapNuisanceParamNom.size() > 0) MapNuisanceParamNom.clear(); std::cout << "Nuisance parameter names and values" << std::endl; while ((var = (RooRealVar*)it->Next()) != NULL){ const double val = var->getVal(); MapNuisanceParamNom[(string)var->GetName()] = val; } return; }
// grab the initial parameters and errors for making pull distributions: // Take these from a fit file to the data themselves void fillInitialParams(RooArgSet *args, std::map<std::string, std::pair<double,double> > &vals){ TIterator* iter(args->createIterator()); for (TObject *a = iter->Next(); a != 0; a = iter->Next()) { RooRealVar *rrv = dynamic_cast<RooRealVar *>(a); std::string name = rrv->GetName(); std::pair<double,double> valE(rrv->getVal(),rrv->getError()); vals.insert( std::pair<std::string,std::pair<double ,double> > (name,valE)) ; } }
/// /// Set the uncertainties of an observable. To be used /// in setUncertainties() of the derived PDF classes. /// This function fills the StatErr and SystErr arrays /// in the correct place. /// /// \param obsName - observable name /// \param stat - statistical error /// \param syst - systematic error /// void PDF_Abs::setUncertainty(TString obsName, float stat, float syst) { for ( int i=0; i<nObs; i++ ){ RooRealVar* obs = (RooRealVar*)observables->at(i); if ( TString(obs->GetName()).EqualTo(obsName) ){ StatErr[i] = stat; SystErr[i] = syst; return; } } cout << "PDF_Abs::setUncertainty() : ERROR : observable "+name+" not found!" << endl; exit(1); }
TGraphAsymmErrors *plotEffPt(RooDataSet *a, int aa) { const RooArgSet *set = a->get(); RooRealVar *xAx = (RooRealVar*)set->find("pt"); RooRealVar *eff = (RooRealVar*)set->find("efficiency"); const int nbins = xAx->getBinning().numBins(); double tx[nbins], txhi[nbins], txlo[nbins]; double ty[nbins], tyhi[nbins], tylo[nbins]; for (int i=0; i<nbins; i++) { a->get(i); ty[i] = eff->getVal(); tx[i] = xAx->getVal(); txhi[i] = fabs(xAx->getErrorHi()); txlo[i] = fabs(xAx->getErrorLo()); tyhi[i] = fabs(eff->getErrorHi()); tylo[i] = fabs(eff->getErrorLo()); } cout<<"NBins : "<<nbins<<endl; const double *x = tx; const double *xhi = txhi; const double *xlo = txlo; const double *y = ty; const double *yhi = tyhi; const double *ylo = tylo; TGraphAsymmErrors *b = new TGraphAsymmErrors(); if(aa == 1) { *b = TGraphAsymmErrors(nbins,x,y,xlo,xhi,ylo,yhi); } if(aa == 0) { *b = TGraphAsymmErrors(nbins,x,y,0,0,ylo,yhi); } b->SetMaximum(1.1); b->SetMinimum(0.0); b->SetMarkerStyle(20); b->SetMarkerColor(kRed+2); b->SetMarkerSize(1.0); b->SetTitle(""); b->GetXaxis()->SetTitleSize(0.05); b->GetYaxis()->SetTitleSize(0.05); b->GetXaxis()->SetTitle("p_{T} [GeV/c]"); b->GetYaxis()->SetTitle("Efficiency"); b->GetXaxis()->CenterTitle(); //b->Draw("apz"); for (int i=0; i<nbins; i++) { cout << x[i] << " " << y[i] << " " << yhi[i] << " " << ylo[i] << endl; } return b; }
pair<double,double> bkgEvPerGeV(RooWorkspace *work, int m_hyp, int cat, int spin=false){ RooRealVar *mass = (RooRealVar*)work->var("CMS_hgg_mass"); if (spin) mass = (RooRealVar*)work->var("mass"); mass->setRange(100,180); RooAbsPdf *pdf = (RooAbsPdf*)work->pdf(Form("pdf_data_pol_model_8TeV_cat%d",cat)); RooAbsData *data = (RooDataSet*)work->data(Form("data_mass_cat%d",cat)); RooPlot *tempFrame = mass->frame(); data->plotOn(tempFrame,Binning(80)); pdf->plotOn(tempFrame); RooCurve *curve = (RooCurve*)tempFrame->getObject(tempFrame->numItems()-1); double nombkg = curve->Eval(double(m_hyp)); RooRealVar *nlim = new RooRealVar(Form("nlim%d",cat),"",0.,0.,1.e5); //double lowedge = tempFrame->GetXaxis()->GetBinLowEdge(FindBin(double(m_hyp))); //double upedge = tempFrame->GetXaxis()->GetBinUpEdge(FindBin(double(m_hyp))); //double center = tempFrame->GetXaxis()->GetBinUpCenter(FindBin(double(m_hyp))); nlim->setVal(nombkg); mass->setRange("errRange",m_hyp-0.5,m_hyp+0.5); RooAbsPdf *epdf = 0; epdf = new RooExtendPdf("epdf","",*pdf,*nlim,"errRange"); RooAbsReal *nll = epdf->createNLL(*data,Extended(),NumCPU(4)); RooMinimizer minim(*nll); minim.setStrategy(0); minim.setPrintLevel(-1); minim.migrad(); minim.minos(*nlim); double error = (nlim->getErrorLo(),nlim->getErrorHi())/2.; data->Print(); return pair<double,double>(nombkg,error); }
/// /// Store the errors as RooFit error into the observables /// to have them easily available for the pull computation. /// void PDF_Abs::storeErrorsInObs() { if ( covMatrix==0 ) { cout << "PDF_Abs::storeErrorsInObs() : ERROR : covMatrix not initialized." << endl; return; } for ( int i=0; i<nObs; i++ ) { RooRealVar* pObs = (RooRealVar*)((RooArgList*)observables)->at(i); pObs->setError(sqrt(covMatrix[i][i])); } }
//____________________________________ void DoSPlot(RooWorkspace* ws){ std::cout << "Calculate sWeights" << std::endl; // get what we need out of the workspace to do the fit RooAbsPdf* model = ws->pdf("model"); RooRealVar* zYield = ws->var("zYield"); RooRealVar* qcdYield = ws->var("qcdYield"); RooDataSet* data = (RooDataSet*) ws->data("data"); // fit the model to the data. model->fitTo(*data, Extended() ); // The sPlot technique requires that we fix the parameters // of the model that are not yields after doing the fit. RooRealVar* sigmaZ = ws->var("sigmaZ"); RooRealVar* qcdMassDecayConst = ws->var("qcdMassDecayConst"); sigmaZ->setConstant(); qcdMassDecayConst->setConstant(); RooMsgService::instance().setSilentMode(true); // Now we use the SPlot class to add SWeights to our data set // based on our model and our yield variables RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot", *data, model, RooArgList(*zYield,*qcdYield) ); // Check that our weights have the desired properties std::cout << "Check SWeights:" << std::endl; std::cout << std::endl << "Yield of Z is " << zYield->getVal() << ". From sWeights it is " << sData->GetYieldFromSWeight("zYield") << std::endl; std::cout << "Yield of QCD is " << qcdYield->getVal() << ". From sWeights it is " << sData->GetYieldFromSWeight("qcdYield") << std::endl << std::endl; for(Int_t i=0; i < 10; i++) { std::cout << "z Weight " << sData->GetSWeight(i,"zYield") << " qcd Weight " << sData->GetSWeight(i,"qcdYield") << " Total Weight " << sData->GetSumOfEventSWeight(i) << std::endl; } std::cout << std::endl; // import this new dataset with sWeights std::cout << "import new dataset with sWeights" << std::endl; ws->import(*data, Rename("dataWithSWeights")); }