void AnalyzeToy::extract_signal()
{
   calculate_yield();
   MakeSpinSPlot splotter(toyData);
   splotter.addSpecies("signal",ws->pdf("model_signal_mass"),signalYield);
   splotter.addSpecies("background",ws->pdf("model_bkg_mass"),backgroundYield);
   splotter.addVariable(ws->var("mass"));
   splotter.calculate();
   RooDataSet *sweights = splotter.getSWeightDataSet();
   sweights->SetName("sweights");

   RooRealVar weight("weight","",-5.,5.);
   RooArgSet event;
   event.add(*mass);
   event.add(*cosT);
   event.add(weight);

   extractedData = new RooDataSet("extractedData","",event,WeightVar("weight"));

   Long64_t nEntries = toyData->numEntries();
   for(int i=0;i<nEntries;i++)
   {
      double weight_double=0;
      weight_double += sweights->get(i)->getRealValue("signal_sw");
//      weight_double += sweights->get(i)->getRealValue("background_sw");

      mass->setVal(toyData->get(i)->getRealValue("mass"));
      cosT->setVal(toyData->get(i)->getRealValue("cosT"));
      extractedData->add(event,weight_double);
   }
   delete toyData;
}
Exemple #2
0
///
/// Set all parameters to values found in
/// a provided fit result.
///
void PDF_Abs::loadExtParameters(RooFitResult *r)
{
	RooArgSet *tmp = new RooArgSet();
	tmp->add(r->floatParsFinal());
	tmp->add(r->constPars());
	setParameters(parameters, tmp);
	delete tmp;
}
void makeDataset( TString fname, TString tname, TString outfname ) {

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

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

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

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

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

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

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

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

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

    tree->GetEntry(ev);

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

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

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

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

  }
  tf->Close();

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

  w->writeToFile(outfname);

}
void defineDatasets( RooWorkspace *w ) {

  w->factory( "B_s0_DTF_B_s0_M [5000,5800]" );
  w->factory( "eventNumber [0, 10e10]" );
  w->factory( "DataCat[HadronTOS2011,GlobalTIS2011,HadronTOS2012,GlobalTIS2012]" );

  w->var("B_s0_DTF_B_s0_M")->SetTitle("m(K^{+}#pi^{-}K^{-}#pi^{+})");
  w->var("B_s0_DTF_B_s0_M")->setUnit("MeV");

  RooArgSet *observables = new RooArgSet();
  observables->add( *w->var("B_s0_DTF_B_s0_M") );
  observables->add( *w->var("eventNumber") );
  observables->add( *w->cat("DataCat") );
  w->defineSet( "observables", *observables );
  delete observables;

  RooArgSet *categories = new RooArgSet();
  categories->add( *w->cat("DataCat") );
  w->defineSet( "categories", *categories );
  delete categories;

  vector<TString> dsets;
  dsets.push_back( "Data" );
  dsets.push_back( "Data2011" );
  dsets.push_back( "Data2012" );
  dsets.push_back( "Data2011HadronTOS" );
  dsets.push_back( "Data2011GlobalTIS" );
  dsets.push_back( "Data2012HadronTOS" );
  dsets.push_back( "Data2012GlobalTIS" );
  dsets.push_back( "Bs2KstKst"           );
  dsets.push_back( "Bs2KstKst1430"       );
  dsets.push_back( "Bs2Kst1430Kst1430"   );
  dsets.push_back( "Bs2KpiKpiPhaseSpace" );
  dsets.push_back( "Bd2KstKst"           );
  dsets.push_back( "Bd2PhiKst"           );
  dsets.push_back( "Bs2PhiKst"           );
  dsets.push_back( "Bd2RhoKst"           );
  dsets.push_back( "Lb2pKpipi"           );
  dsets.push_back( "Lb2ppipipi"          );

  for (int i=0; i<dsets.size(); i++) {
    RooDataSet *data = new RooDataSet( dsets[i], dsets[i], *w->set("observables") );
    w->import( *data );
    delete data;
  }
}
void SetConstants(RooWorkspace * pWs, RooStats::ModelConfig * pMc){
  //
  // Fix all variables in the PDF except observables, POI and
  // nuisance parameters. Note that global observables are fixed.
  // If you need global observables floated, you have to set them
  // to float separately.
  //

  pMc->SetWorkspace(*pWs);

  RooAbsPdf * pPdf = pMc->GetPdf(); // we do not own this

  RooArgSet * pVars = pPdf->getVariables(); // we do own this

  RooArgSet * pFloated = new RooArgSet(*pMc->GetObservables());
  pFloated->add(*pMc->GetParametersOfInterest());
  pFloated->add(*pMc->GetNuisanceParameters());

  TIterator * pIter = pVars->createIterator(); // we do own this

  for(TObject * pObj = pIter->Next(); pObj; pObj = pIter->Next() ){
    std::string _name = pObj->GetName();
    RooRealVar * pFloatedObj = (RooRealVar *)pFloated->find(_name.c_str());
    if (pFloatedObj){
      ((RooRealVar *)pObj)->setConstant(kFALSE);
    }
    else{
      ((RooRealVar *)pObj)->setConstant(kTRUE);
    }
    //pObj->Print();
  }

  delete pIter;
  delete pVars;
  delete pFloated;

  return;
}
Exemple #6
0
void 
RA4WorkSpace::finalize ()
{
  //
  // check
  //
  if ( !hasEle_ && !hasMu_ ) {
    std::cout << "no channel has been defined" << std::endl;
    return;
  }
  //
  // combined model
  RooArgSet modelSet;
  if ( !constEff_ )  modelSet.add(*pdfMcEff_);
  if ( !constKappa_ )  modelSet.add(*pdfMcKappa_);
  if ( !constSCont_ )  modelSet.add(*pdfMcSCont_);
  // RooArgSet modelSet(*pdfMcEff_,*pdfMcKappa_,*pdfMcSCont_);
  if ( hasEle_ ) {
    for ( unsigned int i=0; i<4; ++i )  modelSet.add(*pdfReg_[i][0]);
  }
  if ( hasMu_ ) {
    for ( unsigned int i=0; i<4; ++i )  modelSet.add(*pdfReg_[i][1]);
  }
  RooProdPdf model("model","model",modelSet);
  wspace_->import(model);
  //
  // priors
  //
  wspace_->factory("Uniform::prior_poi({s})");
  RooUniform priorNuis("prior_nuis","prior_nuis",*setNuis_);
  wspace_->import(priorNuis);
  wspace_->factory("PROD::prior(prior_poi,prior_nuis)"); 
  wspace_->Print("v");

  finalized_ = true;
}
//#include <typeinfo.h>
void addFlatNuisances(std::string fi){
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
  TFile *fin = TFile::Open(fi.c_str());
  RooWorkspace *wspace = (RooWorkspace*)fin->Get("w_hmumu");

  wspace->Print("");

  RooStats::ModelConfig *mc = (RooStats::ModelConfig*)wspace->genobj("ModelConfig");
  RooArgSet *nuis = (RooArgSet*) mc->GetNuisanceParameters();
  std::cout << "Before...." << std::endl;
  nuis->Print();
  
  RooRealVar *mgg = (RooRealVar*)wspace->var("mmm");
  // Get all of the "flat" nuisances to be added to the nusiances:
  RooArgSet pdfs = (RooArgSet) wspace->allVars();
  RooAbsReal *pdf;
  TIterator *it_pdf = pdfs.createIterator();
  

  while ( (pdf=(RooAbsReal*)it_pdf->Next()) ){
  	  if (!(std::string(pdf->GetName()).find("zmod") != std::string::npos )) {
  	   if (!(std::string(pdf->GetName()).find("__norm") != std::string::npos )) {
	   	continue;
	   }
	  }
	  pdf->Print();
	  RooArgSet* pdfpars = (RooArgSet*)pdf->getParameters(RooArgSet(*mgg));
	  pdfpars->Print();

	  std::string newname_pdf = (std::string("unconst_")+std::string(pdf->GetName()));
	  wspace->import(*pdf,RooFit::RenameVariable(pdf->GetName(),newname_pdf.c_str()));
	  pdf->SetName(newname_pdf.c_str());
	  nuis->add(*pdf);
  }
 
  wspace->var("MH")->setVal(125.0);
  std::cout << "After..." << std::endl;
  nuis->Print();
  mc->SetNuisanceParameters(*nuis);
  //RooWorkspace *wspace_new = wspace->Clone();
  //mc->SetWorkspace(*wspace_new);
  //wspace_new->import(*mc,true);

  TFile *finew = new TFile((std::string(fin->GetName())+std::string("_unconst.root")).c_str(),"RECREATE");
  //wspace_new->SetName("w");
  finew->WriteTObject(wspace);
  finew->Close();
}
void dtfit_sigmc(){
    TChain* tree = new TChain("TEvent");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmc_s1.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmc_s2.root");

    RooArgSet argset;
    RooRealVar mbc("mbc","mbc",mbc_min,mbc_max,"GeV"); argset.add(mbc);
    RooRealVar de("de","#DeltaE",-0.15,0.3,"GeV"); argset.add(de);
    de.setRange("signal",de_min,de_max);
    RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
    RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
    RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
    RooRealVar bdtgs("bdtgs","bdtgs",0.98,1.); argset.add(bdtgs);
    RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

    RooDataSet ds("ds","ds",tree,argset);
    ds.Print();
}
void SHyFT::fit(bool verbose)
{
  if ( verbose ) cout << "Fitting" << endl;
  RooArgSet nllset;
  for(unsigned int i=0;i<bins_.size();++i) {
    nllset.add(*bins_[i]->nll());
  }
  
  RooAddition nllsum("nllsum","nllsum",nllset);
  RooMinuit m(nllsum);

  if ( verbose ) m.setVerbose(kTRUE);
  else {
    m.setVerbose(kFALSE);
    m.setPrintLevel(-1);
  }
  m.migrad();
  m.hesse();
  //  m.minos();
  if ( verbose ) {
    RooFitResult * f = m.save();
    f->Print("v");
  }
}
Exemple #10
0
int main(int argc, char **argv)
{
	bool printSw = true;
	//TString massModel = "Gauss-m[5622]";
	string massModel = "DCB-m[5622]";
	TString effbase = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/results/";
	bool printeff = false;
	TString dodata = "data";
	bool fitsingle = false;
	TString wstr = "physRate_polp006";
	TString decayToDo = "Lb2Lmumu";
	if(dodata=="genMC") wstr += "_noDecay";

	gROOT->ProcessLine(".x lhcbStyle.C");


	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * nsig_sw = new RooRealVar("nsig_sw","nsig_sw",1,-1.e6,1.e6);
	RooRealVar * MCweight = new RooRealVar(wstr,wstr,1.,-1.e10,1.e10);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5620.,5500.,5900.);
	TString datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb.root";
	if(dodata=="MC") datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb_MC.root";
	if(dodata=="genMC") datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/"+(string)decayToDo+"_geomMC_Pythia8_NBweighted.root";
	TreeReader * data;
	if(dodata!="genMC") data = new TreeReader("cand"+decayToDo);
	else data = new TreeReader("MCtree");
	data->AddFile(datafilename);

	TFile * histFile = new TFile("Afb_hist.root","recreate");

	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);

	int nbins = 1;//CutsDef::nq2bins;
	double q2min[] = {15.,11.0,15,16,18};//&CutsDef::q2min_highfirst[0];
	double q2max[] = {20.,12.5,16,18,20};//&CutsDef::q2max_highfirst[0];
	
	//int nbins = CutsDef::nq2bins
	//double *q2min = &CutsDef::q2min[0];
	//double *q2max = &CutsDef::q2max[0];


	TGraphErrors * Afb_vs_q2 = new TGraphErrors();
	TGraphErrors * AfbB_vs_q2 = new TGraphErrors();
	TGraphErrors * fL_vs_q2 = new TGraphErrors();
	TCanvas * ceff = new TCanvas();

	RooCategory * samples = new RooCategory("samples","samples");
	samples->defineType("DD");
	samples->defineType("LL");

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-100,100);
	RooRealVar * fL = new RooRealVar("fL","fL",0.7,-1.,10.);
	//RooRealVar * afb = new RooRealVar("afb","afb",0.,-1.,1.);
	//RooRealVar * fL = new RooRealVar("fL","fL",0.7,0.,1.);
	RooRealVar * origafb = new RooRealVar("afb","afb",0.,-1.,1.);
	RooRealVar * origfL = new RooRealVar("fL","fL",0.7,-1.,10.);
	TString afbLpdf = "((3./8.)*(1.-fL)*(1 + TMath::Power(cosThetaL,2)) + afb*cosThetaL + (3./4.)*fL*(1 - TMath::Power(cosThetaL,2)))";
	RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-100,100);
	//RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	RooRealVar * origafbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";

	vector< vector< double > > afb_errs, afbB_errs, fL_errs;
	TList * LLlist = new TList, * DDlist = new TList;

	TCanvas * cDD = new TCanvas();
	TCanvas * cLL = new TCanvas();
	TCanvas * cDDB = new TCanvas();
	TCanvas * cLLB = new TCanvas();

	for(int i = 0; i < nbins; i++)
	{
		//if(q2min[i] < 8) continue;
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e",q2min[i],q2max[i]);	
		//TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e && (Lb_MassConsLambda > 5680 || Lb_MassConsLambda < 5590)",q2min[i],q2max[i]); 
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		TFile * effFile = NULL;
		TH1F * effDD = NULL, * effLL = NULL, * effLLB = NULL, * effDDB = NULL;
		if(q2min[i] == 15 && q2max[i] == 20)
		{
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_DD.root");
			effDD  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_LL.root");
			effLL  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_DD.root");
			effDDB  = (TH1F *)effFile->Get("htot_nodet_eff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_LL.root");
			effLLB  = (TH1F *)effFile->Get("htot_nodet_eff");
		}
		else
		{

			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_DD.root");
			TH2F * effDD2D  = (TH2F *)effFile->Get("htot_eff");
			effDD = (TH1F*)GetSliceX(effDD2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_LL.root");
			TH2F * effLL2D  = (TH2F *)effFile->Get("htot_eff");
			effLL = (TH1F*)GetSliceX(effLL2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_DD.root");
			TH2F * effDDB2D  = (TH2F *)effFile->Get("hupper_eff");
			effDDB = (TH1F*)GetSliceX(effDDB2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_LL.root");
			TH2F * effLLB2D  = (TH2F *)effFile->Get("hupper_eff");
			effLLB = (TH1F*)GetSliceX(effLLB2D,(q2max[i]+q2min[i])/2.);
		}

		ceff->cd();

		/**                    FIT EFFICIENCY                  **/

		RooDataHist * hLL = new RooDataHist("hLL","hLL",*cosThetaL,effLL);
		RooDataHist * hDD = new RooDataHist("hDD","hDD",*cosThetaL,effDD);
		RooRealVar * c1LL = new RooRealVar("c1LL","",0.,-1.,1);
		RooRealVar * c1DD = new RooRealVar("c1DD","",0.,-1.,1);
		RooRealVar * c2LL = new RooRealVar("c2LL","",0.,-1.,1);
		RooRealVar * c2DD = new RooRealVar("c2DD","",0.,-1.,1);
		TString effLLstr = "(1 + c1LL*cosThetaL + c2LL*TMath::Power(cosThetaL,2))";
		TString effDDstr = "(1 + c1DD*cosThetaL + c2DD*TMath::Power(cosThetaL,2))";
		RooAbsPdf * effLLpdf = new RooGenericPdf("effLLpdf", "", effLLstr, RooArgSet(*cosThetaL, *c1LL, *c2LL));
		RooAbsPdf * effDDpdf = new RooGenericPdf("effDDpdf", "", effDDstr, RooArgSet(*cosThetaL, *c1DD, *c2DD));
		effLLpdf->fitTo(*hLL,PrintLevel(-1));
		effDDpdf->fitTo(*hDD,PrintLevel(-1));
		fixParams(effLLpdf,cosThetaL);
		fixParams(effDDpdf,cosThetaL);	

		RooDataHist * hLLB = new RooDataHist("hLLB","hLLB",*cosThetaB,effLLB);
		RooDataHist * hDDB = new RooDataHist("hDDB","hDDB",*cosThetaB,effDDB);
		RooRealVar * cB1LL = new RooRealVar("cB1LL","",0,-1.,1);
		RooRealVar * cB1DD = new RooRealVar("cB1DD","",0,-1.,1);
		RooRealVar * cB2LL = new RooRealVar("cB2LL","",0,-1.,1);
		RooRealVar * cB2DD = new RooRealVar("cB2DD","",0,-1.,1);
		TString effLLBstr = "(1 + cB1LL*cosThetaB + cB2LL*TMath::Power(cosThetaB,2))";
		TString effDDBstr = "(1 + cB1DD*cosThetaB + cB2DD*TMath::Power(cosThetaB,2))";
		RooAbsPdf * effLLpdfB = new RooGenericPdf("effLLpdfB", "", effLLBstr, RooArgSet(*cosThetaB, *cB1LL, *cB2LL));
		RooAbsPdf * effDDpdfB = new RooGenericPdf("effDDpdfB", "", effDDBstr, RooArgSet(*cosThetaB, *cB1DD, *cB2DD));
		effLLpdfB->fitTo(*hLLB,PrintLevel(-1));
		effDDpdfB->fitTo(*hDDB,PrintLevel(-1));
		fixParams(effLLpdfB,cosThetaB);
		fixParams(effDDpdfB,cosThetaB);

		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaL -> " << c1LL->getVal() << "  " << c2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaL -> " << c1DD->getVal() << "  " << c2DD->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaB -> " << cB1LL->getVal() << "  " << cB2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaB -> " << cB1DD->getVal() << "  " << cB2DD->getVal() << endl;


		if(printeff) {
			GetFrame(cosThetaL, hLL,effLLpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("DDeffFit"+q2name+".pdf");
			GetFrame(cosThetaL, hDD,effDDpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("LLeffFit"+q2name+".pdf");
			GetFrame(cosThetaB, hLLB,effLLpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("DDeffFitB"+q2name+".pdf");
			GetFrame(cosThetaB, hDDB,effDDpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("LLeffFitB"+q2name+".pdf"); }

			/**                    FIT AFB                  **/


			afb->setVal(0);
			afbB->setVal(0);
			fL->setVal(0.7);

			TString LLnorm = "1./( 1. + (2./3.)*afb*c1LL + (2./5.)*c2LL - (1./5.)*c2LL*fL )*"+effLLstr;
			TString DDnorm = "1./( 1. + (2./3.)*afb*c1DD + (2./5.)*c2DD - (1./5.)*c2DD*fL )*"+effDDstr;
			RooAbsPdf * corrPdfLL = new RooGenericPdf(Form("corrPdfLL_%i",i),LLnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
			RooAbsPdf * corrPdfDD = new RooGenericPdf(Form("corrPdfDD_%i",i),DDnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );

			TString LLnormB = "1./( (2./3.)*( 2*afbB*cB1LL + cB2LL + 3.) )*"+effLLBstr;
			TString DDnormB = "1./( (2./3.)*( 2*afbB*cB1DD + cB2DD + 3.) )*"+effDDBstr;
			RooAbsPdf * corrPdfLLB = new RooGenericPdf(Form("corrPdfLLB_%i",i),LLnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
			RooAbsPdf * corrPdfDDB = new RooGenericPdf(Form("corrPdfDDB_%i",i),DDnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );

			TCut cutLL = CutsDef::LLcut + (TCut)curq2cut;
			TCut cutDD = CutsDef::DDcut + (TCut)curq2cut;

			if(dodata=="genMC")
			{
				corrPdfLLB = new RooGenericPdf("corrPdfLL",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
				corrPdfDDB = new RooGenericPdf("corrPdfDD",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );
				corrPdfLL = new RooGenericPdf("corrPdfLL",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
				corrPdfDD = new RooGenericPdf("corrPdfDD",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );
				cutLL = (TCut)curq2cut;
				cutDD = (TCut)curq2cut;
			}

			Analysis * anaLL = new Analysis(Form("LL_mass_%i",i),"Lb",data,&cutLL,MM);
			anaLL->AddVariable(cosThetaL);
			anaLL->AddVariable(cosThetaB);
			anaLL->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaLL->SetWeight(wstr);
			RooDataSet * dataLL = anaLL->GetDataSet("-recalc-docuts");

			Analysis * anaDD = new Analysis(Form("DD_mass_%i",i),"Lb",data,&cutDD,MM);
			anaDD->AddVariable(cosThetaL);
			anaDD->AddVariable(cosThetaB);
			anaDD->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaDD->SetWeight(wstr);
			RooDataSet * dataDD = anaDD->GetDataSet("-recalc-docuts");

			RooDataSet * sdataDD, * sdataLL;

			if(dodata=="data")
			{
				sdataLL = anaLL->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataLL,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_"+q2name+".pdf");
				}

				sdataDD = anaDD->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataDD,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_"+q2name+".pdf");
				}
			}		
			else { sdataLL = dataLL; sdataDD = dataDD; }

			histFile->cd();
			TTree * LLTree = (TTree*)sdataLL->tree();
			LLTree->SetName(Form("treeLL_%i",i));
			LLlist->Add(LLTree);
			TTree * DDTree = (TTree*)sdataDD->tree();
			DDTree->SetName(Form("treeDD_%i",i));
			DDlist->Add(DDTree);


			// CREATE COMBINED DATASET
			RooDataSet * combData;
			if(dodata=="data") combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*nsig_sw),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar("nsig_sw"));
			else combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*MCweight),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar(wstr));


			// FIT COS LEPTON
			RooSimultaneous * combModel = new RooSimultaneous(Form("combModel_%i",i),"",*samples);
			combModel->addPdf(*corrPdfLL,"LL");
			combModel->addPdf(*corrPdfDD,"DD");

			combModel->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLL->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaL,corrPdfLL,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDD->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaL,corrPdfDD,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_DD_"+q2name+".pdf");

			Afb_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afb->getVal());
			Afb_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afb->getError());
			fL_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,fL->getVal());
			fL_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,fL->getError());
				
			// FIT COS HADRON
			RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
			combModelB->addPdf(*corrPdfLLB,"LL");
			combModelB->addPdf(*corrPdfDDB,"DD");

			combModelB->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLLB->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaB,corrPdfLLB,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDDB->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaB,corrPdfDDB,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_DD_"+q2name+".pdf");

			AfbB_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afbB->getVal());
			AfbB_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afbB->getError());
			
			cout << endl << fixed << setprecision(6) << "AfbB = " << afbB->getVal() << " +/- " << afbB->getError() << endl;
			cout << "Afb = " << afb->getVal() << " +/- " << afb->getError() << endl;
			cout << "fL = " << fL->getVal() << " +/- " << fL->getError() << endl;
			cout << endl;
			cout << "------------------------ FELDMAN AND COUSINS ------------------------" << endl;

			vector < RooDataSet * > datas;
			vector < RooAbsPdf * > pdfs, pdfsB;
			vector < TString > cat;
			cat.push_back("LL");
			cat.push_back("DD");
			datas.push_back(sdataLL);
			datas.push_back(sdataDD);

			RooArgSet * origPars = new RooArgSet();
			origPars->add(*origafb);
			origPars->add(*origfL);
			
			pdfs.push_back(corrPdfLL);
			pdfs.push_back(corrPdfDD);

			vector< double > afb_err, afbB_err, fL_err;
/*
			double fLval = fL->getVal(), fLerr = fL->getError();
			FeldmanCousins * FC = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,afb,"nsig_sw");
			//FC->SetNPointsToScan(20);
			//FC->SetNExp(1000);
			if(q2min[i]==18) afb_err = FC->ExtractLimits(origPars,-0.3,0.3);
			else if( (afb->getVal()-1.4*afb->getError()) > -1 && (afb->getVal()+1.4*afb->getError()) < 1 )
		       afb_err = FC->ExtractLimits(origPars,afb->getVal()-1.4*afb->getError(),afb->getVal()+1.4*afb->getError());
		    else afb_err = FC->ExtractLimits(origPars,-0.4,0.4);

			//FeldmanCousins * FCfL = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,fL,"nsig_sw");
			//if(q2min[i]==11) fL_err = FCfL->ExtractLimits(origPars,0.,0.6);
			//else if (q2min[i]==18) fL_err = FCfL->ExtractLimits(origPars,0.75,0.992);
			//( (fLval-1.3*fLerr) > 0 && (fLval+1.3*fLerr) <= 1 )
			//else fL_err = FCfL->ExtractLimits(origPars,fLval-1.3*fLerr,fLval+1.3*fLerr);

			afb_errs.push_back(afb_err);
			//fL_errs.push_back(fL_err);

 			RooArgSet * origParsB = new RooArgSet();
			origParsB->add(*origafbB);
			pdfsB.push_back(corrPdfLLB);
			pdfsB.push_back(corrPdfDDB);

			FeldmanCousins * FCB = new FeldmanCousins(q2name,cat,datas,pdfsB,cosThetaB,afbB,"nsig_sw");
			if( (afbB->getVal()-1.5*afbB->getError()) > -1 && (afbB->getVal()+1.5*afbB->getError()) < 1 )
			   afbB_err = FCB->ExtractLimits(origParsB,afbB->getVal()-1.5*afbB->getError(),afbB->getVal()+1.5*afbB->getError());
			else afbB_err = FCB->ExtractLimits(origParsB,-0.4,0.4);

			afbB_errs.push_back(afbB_err);
*/
			delete effDD;
			delete effLL;
			delete effLLB;
			delete effDDB;
	}

	cDD->Print("DDeff.pdf");
	cLL->Print("LLeff.pdf");
	cDDB->Print("DDBeff.pdf");
	cLLB->Print("LLBeff.pdf");


	Afb_vs_q2->GetXaxis()->SetTitle("q^{2}");
	Afb_vs_q2->GetYaxis()->SetTitle("Afb");
	Afb_vs_q2->SetMaximum(1);
	Afb_vs_q2->SetMinimum(-1);
	Afb_vs_q2->Draw("AP");
	ceff->Print("Afb_vs_q2.pdf");
	AfbB_vs_q2->GetXaxis()->SetTitle("q^{2}");
	AfbB_vs_q2->GetYaxis()->SetTitle("AfbB");
	AfbB_vs_q2->SetMaximum(1);
	AfbB_vs_q2->SetMinimum(-1);
	AfbB_vs_q2->Draw("AP");
	ceff->Print("AfbB_vs_q2.pdf");
	fL_vs_q2->GetXaxis()->SetTitle("q^{2}");
	fL_vs_q2->GetYaxis()->SetTitle("fL");
	fL_vs_q2->Draw("AP");
	ceff->Print("fL_vs_q2.pdf");

	for(int bb = 0; bb < Afb_vs_q2->GetN(); bb++)
	{
		double qq, qqerr, afbv, afbBv, fLv;
		Afb_vs_q2->GetPoint(bb,qq,afbv);
		qqerr = Afb_vs_q2->GetErrorX(bb);
		AfbB_vs_q2->GetPoint(bb,qq,afbBv);
		fL_vs_q2->GetPoint(bb,qq,fLv);
		cout << fixed << setprecision(1) << qq-qqerr << " - " << qq+qqerr;
		cout << fixed << setprecision(4); 
		//cout << " & $" << afbv << "_{-" << TMath::Abs(afb_errs[bb][0] - afbv) << "}^{+" << TMath::Abs(afb_errs[bb][1] - afbv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		//cout << " & $" << afbBv << "_{-" << TMath::Abs(afbB_errs[bb][0] - afbBv) << "}^{+" << TMath::Abs(afbB_errs[bb][1]-afbBv) << "} \\text{(stat)} \\pm \\text{(sys)}$ " ;
		//cout << " & $" << fLv << "_{-" << TMath::Abs(fL_errs[bb][0] - fLv) << "}^{+" << TMath::Abs(fL_errs[bb][1] - fLv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		cout << "  \\\\ " << endl;
	}

	histFile->cd();
	TTree * finalLLtree = (TTree*)TTree::MergeTrees(LLlist);
	TTree * finalDDtree = (TTree*)TTree::MergeTrees(DDlist);
	finalLLtree->SetName("LL_data");
	finalDDtree->SetName("DD_data");
	finalLLtree->Write();
	finalDDtree->Write();

	delete ceff;
	histFile->Write();
	delete histFile;

	}
int main(int argc, char* argv[]) {

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

     

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

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

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

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


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

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

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

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

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



            list->Print();

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



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

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


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


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


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



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





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

                 ws.Print();

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

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

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

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

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

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




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

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

          /*using namespace doofit::plotting;

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

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

 }
// implementation
void TwoBinInstructional( void ){
  
  // let's time this example
  TStopwatch t;
  t.Start();

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

  // make model
  RooWorkspace * pWs = new RooWorkspace("ws");

  // derived from data
  pWs->factory("xsec[0.2,0,2]"); // POI
  pWs->factory("bg_b[10,0,50]");    // data driven nuisance

  // predefined nuisances
  pWs->factory("lumi[100,0,1000]");
  pWs->factory("eff_a[0.2,0,1]");
  pWs->factory("eff_b[0.05,0,1]");
  pWs->factory("tau[0,1]");
  pWs->factory("xsec_bg_a[0.05]"); // constant
  pWs->var("xsec_bg_a")->setConstant(1);

  // channel a (signal): lumi*xsec*eff_a + lumi*bg_a + tau*bg_b
  pWs->factory("prod::sig_a(lumi,xsec,eff_a)");
  pWs->factory("prod::bg_a(lumi,xsec_bg_a)");
  pWs->factory("prod::tau_bg_b(tau, bg_b)");
  pWs->factory("Poisson::pdf_a(na[14,0,100],sum::mu_a(sig_a,bg_a,tau_bg_b))");

  // channel b (control): lumi*xsec*eff_b + bg_b
  pWs->factory("prod::sig_b(lumi,xsec,eff_b)");
  pWs->factory("Poisson::pdf_b(nb[11,0,100],sum::mu_b(sig_b,bg_b))");

  // nuisance constraint terms (systematics)
  pWs->factory("Lognormal::l_lumi(lumi,nom_lumi[100,0,1000],sum::kappa_lumi(1,d_lumi[0.1]))");
  pWs->factory("Lognormal::l_eff_a(eff_a,nom_eff_a[0.20,0,1],sum::kappa_eff_a(1,d_eff_a[0.05]))");
  pWs->factory("Lognormal::l_eff_b(eff_b,nom_eff_b[0.05,0,1],sum::kappa_eff_b(1,d_eff_b[0.05]))");
  pWs->factory("Lognormal::l_tau(tau,nom_tau[0.50,0,1],sum::kappa_tau(1,d_tau[0.05]))");
  //pWs->factory("Lognormal::l_bg_a(bg_a,nom_bg_a[0.05,0,1],sum::kappa_bg_a(1,d_bg_a[0.10]))");

  // complete model PDF
  pWs->factory("PROD::model(pdf_a,pdf_b,l_lumi,l_eff_a,l_eff_b,l_tau)");

  // Now create sets of variables. Note that we could use the factory to
  // create sets but in that case many of the sets would be duplicated
  // when the ModelConfig objects are imported into the workspace. So,
  // we create the sets outside the workspace, and only the needed ones
  // will be automatically imported by ModelConfigs

  // observables
  RooArgSet obs(*pWs->var("na"), *pWs->var("nb"), "obs");

  // global observables
  RooArgSet globalObs(*pWs->var("nom_lumi"), *pWs->var("nom_eff_a"), *pWs->var("nom_eff_b"), 
		      *pWs->var("nom_tau"),
		      "global_obs");

  // parameters of interest
  RooArgSet poi(*pWs->var("xsec"), "poi");

  // nuisance parameters
  RooArgSet nuis(*pWs->var("lumi"), *pWs->var("eff_a"), *pWs->var("eff_b"), *pWs->var("tau"), "nuis");

  // priors (for Bayesian calculation)
  pWs->factory("Uniform::prior_xsec(xsec)"); // for parameter of interest
  pWs->factory("Uniform::prior_bg_b(bg_b)"); // for data driven nuisance parameter
  pWs->factory("PROD::prior(prior_xsec,prior_bg_b)"); // total prior

  // create data
  pWs->var("na")->setVal(14);
  pWs->var("nb")->setVal(11);
  RooDataSet * pData = new RooDataSet("data","",obs);
  pData->add(obs);
  pWs->import(*pData);
  //pData->Print();

  // signal+background model
  ModelConfig * pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*pWs);
  pSbModel->SetPdf(*pWs->pdf("model"));
  pSbModel->SetPriorPdf(*pWs->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);

  // set all but obs, poi and nuisance to const
  SetConstants(pWs, pSbModel);
  pWs->import(*pSbModel);


  // background-only model
  // use the same PDF as s+b, with xsec=0
  // POI value under the background hypothesis
  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)pWs->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*pWs);
  pWs->import(*pBModel);


  // find global maximum with the signal+background model
  // with conditional MLEs for nuisance parameters
  // and save the parameter point snapshot in the Workspace
  //  - safer to keep a default name because some RooStats calculators
  //    will anticipate it
  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  if(pSbModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

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

  // inspect workspace
  pWs->Print();

  // save workspace to file
  pWs->writeToFile("ws_twobin.root");

  // clean up
  delete pWs;
  delete pData;
  delete pSbModel;
  delete pBModel;

} // ----- end of tutorial ----------------------------------------
Exemple #13
0
void new_RA4(){
  
  // let's time this challenging example
  TStopwatch t;
  t.Start();

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

  // make model
  RooWorkspace* wspace = new RooWorkspace("wspace");

  wspace->factory("Gaussian::sigCons(prime_SigEff[0,-5,5], nom_SigEff[0,-5,5], 1)");
  wspace->factory("expr::SigEff('1.0*pow(1.20,@0)',prime_SigEff)"); // // 1+-20%, 1.20=exp(20%)

  wspace->factory("Poisson::on(non[0,50], sum::splusb(prod::SigUnc(s[0,0,50],SigEff),mainb[8.8,0,50],dilep[0.9,0,20],tau[2.3,0,20],QCD[0.,0,10],MC[0.1,0,4]))");

  wspace->factory("Gaussian::mcCons(prime_rho[0,-5,5], nom_rho[0,-5,5], 1)");
  wspace->factory("expr::rho('1.0*pow(1.39,@0)',prime_rho)"); // // 1+-39%
  wspace->factory("Poisson::off(noff[0,200], prod::rhob(mainb,rho,mu_plus_e[0.74,0.01,10],1.08))");
  wspace->factory("Gaussian::mcCons2(mu_plus_enom[0.74,0.01,4], mu_plus_e, sigmatwo[.05])");

  wspace->factory("Gaussian::dilep_pred(dilep_nom[0.9,0,20], dilep, sigma3[2.2])");
  wspace->factory("Gaussian::tau_pred(tau_nom[2.3,0,20], tau, sigma4[0.5])");
  wspace->factory("Gaussian::QCD_pred(QCD_nom[0.0,0,10], QCD, sigma5[1.0])");
  wspace->factory("Gaussian::MC_pred(MC_nom[0.1,0.01,4], MC, sigma7[0.14])");

  wspace->factory("PROD::model(on,off,mcCons,mcCons2,sigCons,dilep_pred,tau_pred,QCD_pred,MC_pred)");

  RooArgSet obs(*wspace->var("non"), *wspace->var("noff"), *wspace->var("mu_plus_enom"), *wspace->var("dilep_nom"), *wspace->var("tau_nom"), "obs");
  obs.add(*wspace->var("QCD_nom"));  obs.add(*wspace->var("MC_nom"));
  RooArgSet globalObs(*wspace->var("nom_SigEff"), *wspace->var("nom_rho"), "global_obs");
  // fix global observables to their nominal values
  wspace->var("nom_SigEff")->setConstant();
  wspace->var("nom_rho")->setConstant();

  RooArgSet poi(*wspace->var("s"), "poi");
  RooArgSet nuis(*wspace->var("mainb"), *wspace->var("prime_rho"), *wspace->var("prime_SigEff"), *wspace->var("mu_plus_e"), *wspace->var("dilep"), *wspace->var("tau"), "nuis");
  nuis.add(*wspace->var("QCD"));  nuis.add(*wspace->var("MC"));


  wspace->factory("Uniform::prior_poi({s})");
  wspace->factory("Uniform::prior_nuis({mainb,mu_plus_e,dilep,tau,QCD,MC})");
  wspace->factory("PROD::prior(prior_poi,prior_nuis)");

  wspace->var("non")->setVal(8); //observed
  //wspace->var("non")->setVal(12); //expected observation
  wspace->var("noff")->setVal(7); //observed events in control region
  wspace->var("mu_plus_enom")->setVal(0.74);
  wspace->var("dilep_nom")->setVal(0.9);
  wspace->var("tau_nom")->setVal(2.3);
  wspace->var("QCD")->setVal(0.0);
  wspace->var("MC")->setVal(0.1);


  RooDataSet * data = new RooDataSet("data","",obs);
  data->add(obs);
  wspace->import(*data);


  /////////////////////////////////////////////////////
  // Now the statistical tests
  // model config
  ModelConfig* pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*wspace);
  pSbModel->SetPdf(*wspace->pdf("model"));
  pSbModel->SetPriorPdf(*wspace->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);
  wspace->import(*pSbModel);

  // set all but obs, poi and nuisance to const
  SetConstants(wspace, pSbModel);
  wspace->import(*pSbModel);


  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)wspace->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*wspace);
  wspace->import(*pBModel);


  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*data);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  //if(pSbModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  pNll = pBModel->GetPdf()->createNLL(*data);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  //if(pBModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  // inspect workspace
  wspace->Print();

  // save workspace to file
  wspace->writeToFile("tight.root");
  //wspace->writeToFile("tight_median.root");


  // clean up
  delete wspace;
  delete data;
  delete pSbModel;
  delete pBModel;

}
/*
 * Prepares the workspace to be used by the hypothesis test calculator
 */
void workspace_preparer(char *signal_file_name, char *signal_hist_name_in_file, char *background_file_name, char *background_hist_name_in_file, char *data_file_name, char *data_hist_name_in_file, char *config_file) {

    // Include the config_reader class.
    TString path = gSystem->GetIncludePath();
    path.Append(" -I/home/max/cern/cls/mario");
    gSystem->SetIncludePath(path);
    gROOT->LoadMacro("config_reader.cxx");

    // RooWorkspace used to store values.
    RooWorkspace * pWs = new RooWorkspace("ws");

    // Create a config_reader (see source for details) to read the config
    // file.
    config_reader reader(config_file, pWs);

    // Read MR and RR bounds from the config file.
    double MR_lower = reader.find_double("MR_lower");
    double MR_upper = reader.find_double("MR_upper");
    double RR_lower = reader.find_double("RR_lower");
    double RR_upper = reader.find_double("RR_upper");
    double MR_initial = (MR_lower + MR_upper)/2;
    double RR_initial = (RR_lower + RR_upper)/2;

    // Define the Razor Variables
    RooRealVar MR = RooRealVar("MR", "MR", MR_initial, MR_lower, MR_upper);
    RooRealVar RR = RooRealVar("RSQ", "RSQ", RR_initial, RR_lower, RR_upper);

    // Argument lists
    RooArgList pdf_arg_list(MR, RR, "input_args_list");
    RooArgSet pdf_arg_set(MR, RR, "input_pdf_args_set");



    /***********************************************************************/
    /* PART 1: IMPORTING SIGNAL AND BACKGROUND HISTOGRAMS                  */
    /***********************************************************************/

    /*
     * Get the signal's unextended pdf by converting the TH2D in the file
     * into a RooHistPdf
     */
    TFile *signal_file = new TFile(signal_file_name);
    TH2D *signal_hist = (TH2D *)signal_file->Get(signal_hist_name_in_file);
    RooDataHist *signal_RooDataHist = new RooDataHist("signal_roodatahist",
            "signal_roodatahist",
            pdf_arg_list,
            signal_hist);

    RooHistPdf *unextended_sig_pdf = new RooHistPdf("unextended_sig_pdf",
            "unextended_sig_pdf",
            pdf_arg_set,
            *signal_RooDataHist);

    /*
     * Repeat this process for the background.
     */
    TFile *background_file = new TFile(background_file_name);
    TH2D *background_hist =
        (TH2D *)background_file->Get(background_hist_name_in_file);
    RooDataHist *background_RooDataHist =
        new RooDataHist("background_roodatahist", "background_roodatahist",
                        pdf_arg_list, background_hist);
    RooHistPdf *unextended_bkg_pdf = new RooHistPdf("unextended_bkg_pdf",
            "unextended_bkg_pdf",
            pdf_arg_set,
            *background_RooDataHist);

    /*
     * Now, we want to create the bprime variable, which represents the
     * integral over the background-only sample.  We will perform the
     * integral automatically (that's why this is the only nuisance
     * parameter declared in this file - its value can be determined from
     * the input histograms).
     */
    ostringstream bprime_string;
    ostringstream bprime_pdf_string;
    bprime_string << "bprime[" << background_hist->Integral() << ", 0, 999999999]";
    bprime_pdf_string << "Poisson::bprime_pdf(bprime, " << background_hist->Integral() << ")";
    pWs->factory(bprime_string.str().c_str());
    pWs->factory(bprime_pdf_string.str().c_str());


    /*
     * This simple command will create all values from the config file
     * with 'make:' at the beginning and a delimiter at the end (see config
     * _reader if you don't know what a delimiter is).  In other
     * words, the luminosity, efficiency, transfer factors, and their pdfs
     * are created from this command.  The declarations are contained in the
     * config file to be changed easily without having to modify this code.
     */
    reader.factory_all();


    /*
     * Now, we want to create the extended pdfs from the unextended pdfs, as
     * well as from the S and B values we manufactured in the config file.
     * S and B are the values by which the signal and background pdfs,
     * respectively, are extended.  Recall that they were put in the
     * workspace in the reader.facotry_all() command.
     */
    RooAbsReal *S = pWs->function("S");
    RooAbsReal *B = pWs->function("B");

    RooExtendPdf *signalpart = new RooExtendPdf("signalpart", "signalpart",
            *unextended_sig_pdf, *S);
    RooExtendPdf *backgroundpart =
        new RooExtendPdf("backgroundpart", "backgroundpart",
                         *unextended_bkg_pdf, *B);

    RooArgList *pdf_list = new RooArgList(*signalpart, *backgroundpart,
                                          "list");
    // Add the signal and background pdfs to make a TotalPdf
    RooAddPdf *TotalPdf = new RooAddPdf("TotalPdf", "TotalPdf", *pdf_list);

    RooArgList *pdf_prod_list = new RooArgList(*TotalPdf,
            *pWs->pdf("lumi_pdf"),
            *pWs->pdf("eff_pdf"),
            *pWs->pdf("rho_pdf"),
            *pWs->pdf("bprime_pdf"));
    // This creates the final model pdf.
    RooProdPdf *model = new RooProdPdf("model", "model", *pdf_prod_list);

    /*
     * Up until now, we have been using the workspace pWs to contain all of
     * our values.  Now, all of our values that we require are in use in the
     * RooProdPdf called "model".  So, we need to import "model" into a
     * RooWorkspace.  To avoid recopying values into the rooworkspace, when
     * the values may already be present (which can cause problems), we will
     * simply create a new RooWorkspace to avoid confusion and problems.  The
     * new RooWorkspace is created here.
     */
    RooWorkspace *newworkspace = new RooWorkspace("newws");
    newworkspace->import(*model);

    // Immediately delete pWs, so we don't accidentally use it again.
    delete pWs;

    // Show off the newworkspace
    newworkspace->Print();

    // observables
    RooArgSet obs(*newworkspace->var("MR"), *newworkspace->var("RSQ"), "obs");

    // global observables
    RooArgSet globalObs(*newworkspace->var("nom_lumi"), *newworkspace->var("nom_eff"), *newworkspace->var("nom_rho"));

    //fix global observables to their nominal values
    newworkspace->var("nom_lumi")->setConstant();
    newworkspace->var("nom_eff")->setConstant();
    newworkspace->var("nom_rho")->setConstant();

    //Set Parameters of interest
    RooArgSet poi(*newworkspace->var("sigma"), "poi");


    //Set Nuisnaces

    RooArgSet nuis(*newworkspace->var("prime_lumi"), *newworkspace->var("prime_eff"), *newworkspace->var("prime_rho"), *newworkspace->var("bprime"));

    // priors (for Bayesian calculation)
    newworkspace->factory("Uniform::prior_signal(sigma)"); // for parameter of interest
    newworkspace->factory("Uniform::prior_bg_b(bprime)"); // for data driven nuisance parameter
    newworkspace->factory("PROD::prior(prior_signal,prior_bg_b)"); // total prior


    //Observed data is pulled from histogram.
    //TFile *data_file = new TFile(data_file_name);
    TFile *data_file = new TFile(data_file_name);
    TH2D *data_hist = (TH2D *)data_file->Get(data_hist_name_in_file);
    RooDataHist *pData = new RooDataHist("data", "data", obs, data_hist);
    newworkspace->import(*pData);

    // Now, we will draw our data from a RooDataHist.
    /*TFile *data_file = new TFile(data_file_name);
    TTree *data_tree = (TTree *) data_file->Get(data_hist_name_in_file);
    RooDataSet *pData = new RooDataSet("data", "data", data_tree, obs);
    newworkspace->import(*pData);*/


    // Craft the signal+background model
    ModelConfig * pSbModel = new ModelConfig("SbModel");
    pSbModel->SetWorkspace(*newworkspace);
    pSbModel->SetPdf(*newworkspace->pdf("model"));
    pSbModel->SetPriorPdf(*newworkspace->pdf("prior"));
    pSbModel->SetParametersOfInterest(poi);
    pSbModel->SetNuisanceParameters(nuis);
    pSbModel->SetObservables(obs);
    pSbModel->SetGlobalObservables(globalObs);

    // set all but obs, poi and nuisance to const
    SetConstants(newworkspace, pSbModel);
    newworkspace->import(*pSbModel);


    // background-only model
    // use the same PDF as s+b, with sig=0
    // POI value under the background hypothesis
    // (We will set the value to 0 later)

    Double_t poiValueForBModel = 0.0;
    ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)newworkspace->obj("SbModel"));
    pBModel->SetName("BModel");
    pBModel->SetWorkspace(*newworkspace);
    newworkspace->import(*pBModel);

    // find global maximum with the signal+background model
    // with conditional MLEs for nuisance parameters
    // and save the parameter point snapshot in the Workspace
    //  - safer to keep a default name because some RooStats calculators
    //    will anticipate it
    RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData);
    RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
    pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
    RooArgSet * pPoiAndNuisance = new RooArgSet();
    if(pSbModel->GetNuisanceParameters())
        pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
    pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
    cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
    pPoiAndNuisance->Print("v");
    pSbModel->SetSnapshot(*pPoiAndNuisance);
    delete pProfile;
    delete pNll;
    delete pPoiAndNuisance;


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

    // save workspace to file
    newworkspace->writeToFile("ws_twobin.root");

    // clean up
    delete newworkspace;
    delete pData;
    delete pSbModel;
    delete pBModel;


} // ----- end of tutorial ----------------------------------------
Exemple #15
0
    void ztonunu1() {

    // RooMsgService::instance().addStream(DEBUG,Topic(Tracing),ClassName("RooPoisson"),OutputFile("debug.log")) ;

       float acc_mm_mean( 0.98 ) ; float acc_mm_err(  0.02 ) ;
       float acc_ee_mean( 0.98 ) ; float acc_ee_err(  0.02 ) ;
       float eff_mm_mean( 0.77 ) ; float eff_mm_err(  0.08 ) ;
       float eff_ee_mean( 0.76 ) ; float eff_ee_err(  0.08 ) ;


       RooRealVar* rv_Nsbee  = new RooRealVar( "Nsbee"  ,"Nsbee"  , 0., 100. ) ;
       RooRealVar* rv_Nsbmm  = new RooRealVar( "Nsbmm"  ,"Nsbmm"  , 0., 100. ) ;
       RooRealVar* rv_Nsigee = new RooRealVar( "Nsigee" ,"Nsigee" , 0., 100. ) ;
       RooRealVar* rv_Nsigmm = new RooRealVar( "Nsigmm" ,"Nsigmm" , 0., 100. ) ;

       rv_Nsbee->setVal( 5 ) ;
       rv_Nsbmm->setVal( 3 ) ;

       rv_Nsigee->setVal( 4 ) ;
       rv_Nsigmm->setVal( 3 ) ;


       RooRealVar* rv_mu_Znnsb  = new RooRealVar( "mu_Znnsb"  , "mu_Znnsb"  , 0., 100. ) ;
       RooRealVar* rv_mu_Znnsig = new RooRealVar( "mu_Znnsig" , "mu_Znnsig" , 0., 100. ) ;


       rv_mu_Znnsb->setVal( 37 ) ; // starting value
       rv_mu_Znnsig->setVal( 17. ) ; // starting value

       RooRealVar* rv_bfRatio = new RooRealVar( "bfRatio", "bfRatio", 0., 10. ) ;

       rv_bfRatio->setVal( 5.95 ) ;
       rv_bfRatio->setConstant( kTRUE ) ;

       RooRealVar* rv_acc_mm = new RooRealVar( "acc_mm", "acc_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_acc_ee = new RooRealVar( "acc_ee", "acc_ee", 0.001, 1.000 ) ;

       RooRealVar* rv_eff_mm = new RooRealVar( "eff_mm", "eff_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_eff_ee = new RooRealVar( "eff_ee", "eff_ee", 0.001, 1.000 ) ;

       rv_acc_mm->setVal( acc_mm_mean ) ;
       rv_acc_ee->setVal( acc_ee_mean ) ;
       rv_eff_mm->setVal( eff_mm_mean ) ;
       rv_eff_ee->setVal( eff_ee_mean ) ;

       RooRealVar* rv_lumi_ratio = new RooRealVar( "lumi_ratio", "lumi_ratio", 0., 10. ) ;

       rv_lumi_ratio -> setVal( 686./869. ) ;
       rv_lumi_ratio -> setConstant( kTRUE) ;



       RooFormulaVar* rv_mu_Zeesb = new RooFormulaVar( "mu_Zeesb",
                       "mu_Znnsb * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsb = new RooFormulaVar( "mu_Zmmsb",
                       "mu_Znnsb * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zeesig = new RooFormulaVar( "mu_Zeesig",
                       "mu_Znnsig * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsig = new RooFormulaVar( "mu_Zmmsig",
                       "mu_Znnsig * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;



       RooFormulaVar* rv_n_sbee  = new RooFormulaVar( "n_sbee"  , "mu_Zeesb"  , RooArgSet( *rv_mu_Zeesb  ) ) ;
       RooFormulaVar* rv_n_sbmm  = new RooFormulaVar( "n_sbmm"  , "mu_Zmmsb"  , RooArgSet( *rv_mu_Zmmsb  ) ) ;
       RooFormulaVar* rv_n_sigee = new RooFormulaVar( "n_sigee" , "mu_Zeesig" , RooArgSet( *rv_mu_Zeesig ) ) ;
       RooFormulaVar* rv_n_sigmm = new RooFormulaVar( "n_sigmm" , "mu_Zmmsig" , RooArgSet( *rv_mu_Zmmsig ) ) ;



       RooGaussian* pdf_acc_mm = new RooGaussian( "pdf_acc_mm", "Gaussian pdf for Z to mumu acceptance",
                       *rv_acc_mm, RooConst( acc_mm_mean ), RooConst( acc_mm_err ) ) ;


       RooGaussian* pdf_acc_ee = new RooGaussian( "pdf_acc_ee", "Gaussian pdf for Z to ee acceptance",
                       *rv_acc_ee, RooConst( acc_ee_mean ), RooConst( acc_ee_err ) ) ;




       RooGaussian* pdf_eff_mm = new RooGaussian( "pdf_eff_mm", "Gaussian pdf for Z to mumu efficiency",
                       *rv_eff_mm, RooConst( eff_mm_mean ), RooConst( eff_mm_err ) ) ;



       RooGaussian* pdf_eff_ee = new RooGaussian( "pdf_eff_ee", "Gaussian pdf for Z to ee efficiency",
                       *rv_eff_ee, RooConst( eff_ee_mean ), RooConst( eff_ee_err ) ) ;



       RooPoisson* pdf_Nsbee   = new RooPoisson( "pdf_Nsbee"  , "Nsb , Z to ee Poisson PDF", *rv_Nsbee  , *rv_n_sbee  ) ;
       RooPoisson* pdf_Nsbmm   = new RooPoisson( "pdf_Nsbmm"  , "Nsb , Z to mm Poisson PDF", *rv_Nsbmm  , *rv_n_sbmm  ) ;
       RooPoisson* pdf_Nsigee  = new RooPoisson( "pdf_Nsigee" , "Nsig, Z to ee Poisson PDF", *rv_Nsigee , *rv_n_sigee ) ;
       RooPoisson* pdf_Nsigmm  = new RooPoisson( "pdf_Nsigmm" , "Nsig, Z to mm Poisson PDF", *rv_Nsigmm , *rv_n_sigmm ) ;

       RooArgSet pdflist ;
       pdflist.add( *pdf_acc_mm ) ;
       pdflist.add( *pdf_acc_ee ) ;
       pdflist.add( *pdf_eff_mm ) ;
       pdflist.add( *pdf_eff_ee ) ;
       pdflist.add( *pdf_Nsbee  ) ;
       pdflist.add( *pdf_Nsbmm  ) ;
       pdflist.add( *pdf_Nsigee  ) ;
       pdflist.add( *pdf_Nsigmm  ) ;

       RooProdPdf* znnLikelihood = new RooProdPdf( "znnLikelihood", "Z to nunu likelihood", pdflist ) ;


       RooArgSet observedParametersList ;
       observedParametersList.add( *rv_Nsbee ) ;
       observedParametersList.add( *rv_Nsbmm ) ;
       observedParametersList.add( *rv_Nsigee ) ;
       observedParametersList.add( *rv_Nsigmm ) ;

       RooDataSet* dsObserved = new RooDataSet( "ztonn_rds", "Z to nunu dataset", observedParametersList ) ;
       dsObserved->add( observedParametersList ) ;
       //// RooDataSet* dsObserved = znnLikelihood->generate( observedParametersList, 1) ;

       RooWorkspace* znnWorkspace = new RooWorkspace("ztonn_ws") ;
       znnWorkspace->import( *znnLikelihood ) ;
       znnWorkspace->import( *dsObserved ) ;

       znnWorkspace->Print() ;

       dsObserved->printMultiline(cout, 1, kTRUE, "") ;
       RooFitResult* fitResult = znnLikelihood->fitTo( *dsObserved, Verbose(true), Save(true) ) ;

       printf("\n\n----- Constant parameters:\n") ;
       RooArgList constPars = fitResult->constPars() ;
       for ( int pi=0; pi<constPars.getSize(); pi++ ) {
          constPars[pi].Print() ;
       } // pi.

       printf("\n\n----- Floating parameters:\n") ;
       RooArgList floatPars = fitResult->floatParsFinal() ;
       for ( int pi=0; pi<floatPars.getSize(); pi++ ) {
          floatPars[pi].Print() ;
       } // pi.
       printf("\n\n") ;



       ProfileLikelihoodCalculator plc_znn_sb(  *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsb ) ) ;
       ProfileLikelihoodCalculator plc_znn_sig( *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsig ) ) ;

       plc_znn_sb.SetTestSize(0.32) ;
       plc_znn_sig.SetTestSize(0.32) ;

       ConfInterval* sb_znn_interval = plc_znn_sb.GetInterval() ;
       float sbZnnLow  = ((LikelihoodInterval*) sb_znn_interval)->LowerLimit(*rv_mu_Znnsb) ;
       float sbZnnHigh = ((LikelihoodInterval*) sb_znn_interval)->UpperLimit(*rv_mu_Znnsb) ;
       printf("\n\n znn SB interval %6.1f to %6.1f\n", sbZnnLow, sbZnnHigh ) ;

       ConfInterval* sig_znn_interval = plc_znn_sig.GetInterval() ;
       float sigZnnLow  = ((LikelihoodInterval*) sig_znn_interval)->LowerLimit(*rv_mu_Znnsig) ;
       float sigZnnHigh = ((LikelihoodInterval*) sig_znn_interval)->UpperLimit(*rv_mu_Znnsig) ;
       printf("\n\n znn SIG interval %6.1f to %6.1f\n", sigZnnLow, sigZnnHigh ) ;



       TCanvas* c_prof_sb = new TCanvas("c_prof_sb","SB Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sb((LikelihoodInterval*)sb_znn_interval) ;
       plot_znn_sb.Draw() ;
       c_prof_sb->SaveAs("znn_sb_profile.png") ;

       TCanvas* c_prof_sig = new TCanvas("c_prof_sig","sig Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sig((LikelihoodInterval*)sig_znn_interval) ;
       plot_znn_sig.Draw() ;
       c_prof_sig->SaveAs("znn_sig_profile.png") ;


    }
Exemple #16
0
void splitws(string inFolderName, double mass, string channel) {
  cout << "Splitting workspace in " << channel << endl;

  int flatInterpCode = 4;
  int shapeInterpCode = 4;

  bool do2011 = 0;

  if (inFolderName.find("2011") != string::npos) do2011 = 1;

  bool conditionalAsimov = 0;
  bool doData = 1;
  //if (inFolderName.find("_blind_") != string::npos) {
    //conditionalAsimov = 0;
  //}
  //else {
    //conditionalAsimov = 1;
  //}

  set<string> channelNames;

  if (channel == "01j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "0j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "1j") {
    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF01j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF0j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF1j") {
    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF01j") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF0j") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF1j") {
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "2j") {
    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF2j") {
    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF2j") {
    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));

    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else {
    cout << "Channel " << channel << " not defined. Please check!" << endl;
    exit(1);
  }

  // bool fix = 1;
  stringstream inFileName;

  inFileName << "workspaces/" << inFolderName << "/" << mass << ".root";
  TFile f(inFileName.str().c_str());
  
  RooWorkspace* w = (RooWorkspace*)f.Get("combWS");
  if (!w) w = (RooWorkspace*)f.Get("combined");
  
  RooDataSet* data = (RooDataSet*)w->data("combData");
  if (!data) data = (RooDataSet*)w->data("obsData");
  
  ModelConfig* mc = (ModelConfig*)w->obj("ModelConfig");
  
  RooRealVar* weightVar = w->var("weightVar");
  
  RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();
  if (!mu) mu = w->var("SigXsecOverSM");

  const RooArgSet* mc_obs = mc->GetObservables();
  const RooArgSet* mc_nuis = mc->GetNuisanceParameters();
  const RooArgSet* mc_globs = mc->GetGlobalObservables();
  const RooArgSet* mc_poi = mc->GetParametersOfInterest();

  RooArgSet nuis = *mc_nuis;
  RooArgSet antiNuis = *mc_nuis;

  RooArgSet globs = *mc_globs;
  RooArgSet antiGlobs = *mc_globs;

  RooArgSet allParams;

  RooSimultaneous* simPdf = (RooSimultaneous*)mc->GetPdf();
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();

  RooArgSet nuis_tmp = nuis;
  RooArgSet fullConstraints = *simPdf->getAllConstraints(*mc_obs,nuis_tmp,false);

  vector<string> foundChannels;
  vector<string> skippedChannels;  

  cout << "Getting constraints" << endl;
  map<string, RooDataSet*> data_map;
  map<string, RooAbsPdf*> pdf_map;
  RooCategory* decCat = new RooCategory("dec_channel","dec_channel");
  // int i = 0;
  TIterator* catItr = cat->typeIterator();
  RooCatType* type;
  RooArgSet allConstraints;
  while ((type = (RooCatType*)catItr->Next())) {
    RooAbsPdf* pdf =  simPdf->getPdf(type->GetName());

    string typeName(type->GetName());
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end())  {
      skippedChannels.push_back(typeName);
      continue;
    }
    cout << "On channel " << type->GetName() << endl;
    foundChannels.push_back(typeName);

    decCat->defineType(type->GetName());
    // pdf->getParameters(*data)->Print("v");

    RooArgSet nuis_tmp1 = nuis;
    RooArgSet nuis_tmp2 = nuis;
    RooArgSet* constraints = pdf->getAllConstraints(*mc_obs, nuis_tmp1, true);
    constraints->Print();
    allConstraints.add(*constraints);
  }

  catItr->Reset();

  while ((type = (RooCatType*)catItr->Next())) {
    RooAbsPdf* pdf =  simPdf->getPdf(type->GetName());

    string typeName(type->GetName());
    cout << "Considering type " << typeName << endl;
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end()) continue;
    cout << "On channel " << type->GetName() << endl;

    RooArgSet nuis_tmp1 = nuis;
    RooArgSet nuis_tmp2 = nuis;
    RooArgSet* constraints = pdf->getAllConstraints(*mc_obs, nuis_tmp1, true);

    cout << "Adding pdf to map: " << typeName << " = " << pdf->GetName() << endl;
    pdf_map[typeName] = pdf;

    RooProdPdf prod("prod","prod",*constraints);

    RooArgSet* params = pdf->getParameters(*data);
    antiNuis.remove(*params);
    antiGlobs.remove(*params);

    allParams.add(*params);
    // cout << type->GetName() << endl;
  }
  // return;

  RooArgSet decNuis;
  TIterator* nuiItr = mc_nuis->createIterator();
  TIterator* parItr = allParams.createIterator();
  RooAbsArg* nui, *par;
  while ((par = (RooAbsArg*)parItr->Next())) {
    nuiItr->Reset();
    while ((nui = (RooAbsArg*)nuiItr->Next())) {
      if (par == nui) decNuis.add(*nui);
    }
  }

  RooArgSet decGlobs;
  TIterator* globItr = mc_globs->createIterator();
  parItr->Reset();
  RooAbsArg* glob;
  while ((par = (RooAbsArg*)parItr->Next())) {
    globItr->Reset();
    while ((glob = (RooAbsArg*)globItr->Next())) {
      if (par == glob) decGlobs.add(*glob);
    }
  }

  // antiNuis.Print();

  // nuis.Print();
  // globs.Print();

  // i = 0;
  TList* datalist = data->split(*cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  while ((ds = (RooAbsData*)dataItr->Next())) {
    string typeName(ds->GetName());
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end()) continue;

    cout << "Adding dataset to map: " << ds->GetName() << endl;
    data_map[string(ds->GetName())] = (RooDataSet*)ds;

    cout << ds->GetName() << endl;
  }

  RooSimultaneous* decPdf = new RooSimultaneous("decPdf","decPdf",pdf_map,*decCat); 
  RooArgSet decObs = *decPdf->getObservables(data);
  // decObs.add(*(RooAbsArg*)weightVar);
  decObs.add(*(RooAbsArg*)decCat);
  decObs.Print();

  nuis.remove(antiNuis);
  globs.remove(antiGlobs);
  // nuis.Print("v");

  RooDataSet* decData = new RooDataSet("obsData","obsData",RooArgSet(decObs,*(RooAbsArg*)weightVar),Index(*decCat),Import(data_map),WeightVar(*weightVar));

  decData->Print();

  RooArgSet poi(*(RooAbsArg*)mu);
  RooWorkspace decWS("combined");
  ModelConfig decMC("ModelConfig",&decWS);
  decMC.SetPdf(*decPdf);
  decMC.SetObservables(decObs);
  decMC.SetNuisanceParameters(decNuis);
  decMC.SetGlobalObservables(decGlobs);
  decMC.SetParametersOfInterest(poi);

  decMC.Print();
  decWS.import(*decPdf);
  decWS.import(decMC);
  decWS.import(*decData);
  // decWS.Print();

  ModelConfig* mcInWs = (ModelConfig*)decWS.obj("ModelConfig");
  decPdf = (RooSimultaneous*)mcInWs->GetPdf();

  // setup(mcInWs);
  // return;

  mcInWs->GetNuisanceParameters()->Print("v");
  mcInWs->GetGlobalObservables()->Print("v");
  // decData->tree()->Scan("*");

  // Make asimov data
  RooArgSet funcs = decWS.allFunctions();
  TIterator* it = funcs.createIterator();
  TObject* tempObj = 0;
  while((tempObj=it->Next()))
  {
    FlexibleInterpVar* flex = dynamic_cast<FlexibleInterpVar*>(tempObj);
    if(flex) {
      flex->setAllInterpCodes(flatInterpCode);
    }
    PiecewiseInterpolation* piece = dynamic_cast<PiecewiseInterpolation*>(tempObj);
    if(piece) {
      piece->setAllInterpCodes(shapeInterpCode);
    }
  }

  RooDataSet* dataInWs = (RooDataSet*)decWS.data("obsData");
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 0);
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 1);
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 2);

  system(("mkdir -vp workspaces/"+inFolderName+"_"+channel).c_str());
  stringstream outFileName;
  outFileName << "workspaces/" << inFolderName << "_" << channel << "/" << mass << ".root";
  cout << "Exporting" << endl;

  decWS.writeToFile(outFileName.str().c_str());

  cout << "\nIncluded the following channels: " << endl;
  for (int i=0;i<(int)foundChannels.size();i++) {
    cout << "-> " << foundChannels[i] << endl;
  }

  cout << "\nSkipping the following channels: " << endl;
  
  for (int i=0;i<(int)skippedChannels.size();i++) {
    cout << "-> " << skippedChannels[i] << endl;
  }

  cout << "Done" << endl;

  // decPdf->fitTo(*decData, Hesse(0), Minos(0), PrintLevel(0));
}
Exemple #17
0
void MakeWorkspace( void ){
  //
  // this function implements a RooFit model for a counting experiment
  //

  // create workspace
  RooWorkspace * pWs = new RooWorkspace("myWS");
  
  // observable: number of events
  pWs->factory( "n[0.0]" );

  // integrated luminosity with systematics
  pWs->factory( "lumi_nom[5000.0, 4000.0, 6000.0]" );
  pWs->factory( "lumi_kappa[1.045]" );
  pWs->factory( "cexpr::alpha_lumi('pow(lumi_kappa,beta_lumi)',lumi_kappa,beta_lumi[0,-5,5])" );
  pWs->factory( "prod::lumi(lumi_nom,alpha_lumi)" );
  pWs->factory( "Gaussian::constr_lumi(beta_lumi,glob_lumi[0,-5,5],1)" );

  // cross section - parameter of interest
  pWs->factory( "xsec[0.001,0.0,0.1]" );

  // selection efficiency * acceptance with systematics
  pWs->factory( "efficiency_nom[0.1, 0.05, 0.15]" );
  pWs->factory( "efficiency_kappa[1.10]" );
  pWs->factory( "cexpr::alpha_efficiency('pow(efficiency_kappa,beta_efficiency)',efficiency_kappa,beta_efficiency[0,-5,5])" );
  pWs->factory( "prod::efficiency(efficiency_nom,alpha_efficiency)" );
  pWs->factory( "Gaussian::constr_efficiency(beta_efficiency,glob_efficiency[0,-5,5],1)" );

  // signal yield
  pWs->factory( "prod::nsig(lumi,xsec,efficiency)" );

  // background yield with systematics
  pWs->factory( "nbkg_nom[10.0, 5.0, 15.0]" );
  pWs->factory( "nbkg_kappa[1.10]" );
  pWs->factory( "cexpr::alpha_nbkg('pow(nbkg_kappa,beta_nbkg)',nbkg_kappa,beta_nbkg[0,-5,5])" );
  pWs->factory( "prod::nbkg(nbkg_nom,alpha_lumi,alpha_nbkg)" );
  pWs->factory( "Gaussian::constr_nbkg(beta_nbkg,glob_nbkg[0,-5,5],1)" );

  // full event yield
  pWs->factory("sum::yield(nsig,nbkg)");

  // Core model: Poisson probability with mean signal+bkg
  pWs->factory( "Poisson::model_core(n,yield)" );

  // define Bayesian prior PDF for POI
  pWs->factory( "Uniform::prior(xsec)" );

  // model with systematics
  pWs->factory( "PROD::model(model_core,constr_lumi,constr_efficiency,constr_nbkg)" );

  // create set of observables (will need it for datasets and ModelConfig later)
  RooRealVar * pObs = pWs->var("n"); // get the pointer to the observable
  RooArgSet obs("observables");
  obs.add(*pObs);

  // create the dataset
  pObs->setVal(11); // this is your observed data: we counted ten events
  RooDataSet * data = new RooDataSet("data", "data", obs);
  data->add( *pObs );

  // import dataset into workspace
  pWs->import(*data);

  // create set of global observables (need to be defined as constants)
  pWs->var("glob_lumi")->setConstant(true);
  pWs->var("glob_efficiency")->setConstant(true);
  pWs->var("glob_nbkg")->setConstant(true);
  RooArgSet globalObs("global_obs");
  globalObs.add( *pWs->var("glob_lumi") );
  globalObs.add( *pWs->var("glob_efficiency") );
  globalObs.add( *pWs->var("glob_nbkg") );

  // create set of parameters of interest (POI)
  RooArgSet poi("poi");
  poi.add( *pWs->var("xsec") );
  
  // create set of nuisance parameters
  RooArgSet nuis("nuis");
  nuis.add( *pWs->var("beta_lumi") );
  nuis.add( *pWs->var("beta_efficiency") );
  nuis.add( *pWs->var("beta_nbkg") );

  // create signal+background Model Config
  RooStats::ModelConfig sbHypo("SbHypo");
  sbHypo.SetWorkspace( *pWs );
  sbHypo.SetPdf( *pWs->pdf("model") );
  sbHypo.SetObservables( obs );
  sbHypo.SetGlobalObservables( globalObs );
  sbHypo.SetParametersOfInterest( poi );
  sbHypo.SetNuisanceParameters( nuis );
  sbHypo.SetPriorPdf( *pWs->pdf("prior") ); // this is optional

  // fix all other variables in model:
  // everything except observables, POI, and nuisance parameters
  // must be constant
  pWs->var("lumi_nom")->setConstant(true);
  pWs->var("efficiency_nom")->setConstant(true);
  pWs->var("nbkg_nom")->setConstant(true);
  pWs->var("lumi_kappa")->setConstant(true);
  pWs->var("efficiency_kappa")->setConstant(true);
  pWs->var("nbkg_kappa")->setConstant(true);
  RooArgSet fixed("fixed");
  fixed.add( *pWs->var("lumi_nom") );
  fixed.add( *pWs->var("efficiency_nom") );
  fixed.add( *pWs->var("nbkg_nom") );
  fixed.add( *pWs->var("lumi_kappa") );
  fixed.add( *pWs->var("efficiency_kappa") );
  fixed.add( *pWs->var("nbkg_kappa") );
  
  // set parameter snapshot that corresponds to the best fit to data
  RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data );
  RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
  pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
  pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
  sbHypo.SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // import S+B ModelConfig into workspace
  pWs->import( sbHypo );

  // create background-only Model Config from the S+B one
  RooStats::ModelConfig bHypo = sbHypo;
  bHypo.SetName("BHypo");
  bHypo.SetWorkspace(*pWs);

  // set parameter snapshot for bHypo, setting xsec=0
  // it is useful to understand how this block of code works
  // but you can also use it as a recipe to make a parameter snapshot
  pNll = bHypo.GetPdf()->createNLL( *data );
  RooArgSet poiAndGlobalObs("poiAndGlobalObs");
  poiAndGlobalObs.add( poi );
  poiAndGlobalObs.add( globalObs );
  pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
  ((RooRealVar *)poi.first())->setVal( 0 );  // set xsec=0 here
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
  pPoiAndNuisance->add( nuis );
  pPoiAndNuisance->add( poi );
  bHypo.SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // import model config into workspace
  pWs->import( bHypo );

  // print out the workspace contents
  pWs->Print();

  // save workspace to file
  pWs -> SaveAs("workspace.root");

  return;
}
void Back_2dFit(void){
  TFile *ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/fil_b2dh_gen.root");
  TTree *tree = (TTree*)ifile->Get("TEvent");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("comb",-1);

  RooArgSet argset;
  
  const double mbcMin = 5.20;
  const double mbcMax = 5.29;
  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbcMin,mbcMax,"GeV"); argset.add(mbc);
  mbc.setRange("Signal",mbc_min,mbc_max);
  mbc.setRange("mbcSignal",mbc_min,mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset);
  RooDataSet* ds0 = ds.reduce(RooArgSet(de,mbc));
  RooDataHist* dh = ds0->binnedClone();
  ds.Print();
  dh->Print();

  ////////////
  // de pdf //
  ////////////
//  RooRealVar c1("c1","c1",mc_c1,-1.,0.); if(cComb) c1.setConstant(kTRUE);
//  RooRealVar c2("c2","c2",mc_c2,0.,0.1); if(cComb) c2.setConstant(kTRUE);
  RooRealVar c3("c3","c3",mc_c1,-1.,0.); if(cComb) c3.setConstant(kTRUE);
  RooRealVar c4("c4","c4",mc_c2,0.,0.1); if(cComb) c4.setConstant(kTRUE);
  RooChebychev pdf_de("pdf_de","pdf_de",de,RooArgSet(c3,c4));

  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argpar("argpar","argus shape parameter",mc_argpar,-100.,-1.); if(cComb)
  argpar.setConstant(kTRUE);
  RooRealVar argedge("argedge","argedge",mc_argedge,5.285,5.292); if(cComb) argedge.setConstant(kTRUE);
  RooArgusBG pdf_mbc("pdf_mbc","Argus PDF",mbc,argedge,argpar);

  /////////
  // pdf //
  /////////
  RooProdPdf pdf("pdf","pdf",RooArgList(pdf_de,pdf_mbc));

  pdf.fitTo(*dh,Verbose(),Timer(true));

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(deFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E, Signal","#Delta E, Signal",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out;
  out.str("");
  out << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  TPaveText *pt = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  pt->AddText(out.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,200);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,200);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(mbcFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}, Signal","M_{bc}, Signal",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  out.str("");
  out << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  TPaveText *ptmbc = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  ptmbc->AddText(out.str().c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT = new TLine(mbc_max,0,mbc_max,150);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT = new TLine(mbc_min,0,mbc_min,150);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();
  
  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();
  
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,-0.15,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  cmmbc->Update();
}
Exemple #19
0
void dzRooFit(const int _mode = 1, const int _h0mode = 10,const int EXP = -1){
    TFile *omegafile;
    switch(_mode){
    case 1:
      omegafile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_sigPi0_s4_full.root");
      break;
    case 2:
      omegafile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_sigEta_full.root");
      break;
    case 3:
      omegafile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_sigOmega_s1_full.root");
      break;
    }
    TTree *omegatree = (TTree*)omegafile->Get("TEvent");

  const double dz_min = -1.5;
  const double dz_max =  1.5;

  RooArgSet argset;
  RooCategory b0f("b0f","b0f");
  b0f.defineType("sig",1);
  b0f.defineType("badpi0",5);
  argset.add(b0f);

  RooCategory exp("exp","exp");
  if(EXP>0){
    exp.defineType("expNo",EXP);
  }
  if(EXP == -2 || EXP == -3){
    exp.defineType("7",7);
    exp.defineType("9",9);
    exp.defineType("11",11);
    exp.defineType("13",13);
    exp.defineType("15",15);
    exp.defineType("17",17);
    exp.defineType("21",21);
    exp.defineType("23",23);
    exp.defineType("25",25);
    exp.defineType("27",27);
  }
  if(EXP == -1 || EXP == -3){
    exp.defineType("31",31);
    exp.defineType("33",33);
    exp.defineType("35",35);
    exp.defineType("37",37);
    exp.defineType("39",39);
    exp.defineType("41",41);
    exp.defineType("43",43);
    exp.defineType("45",45);
    exp.defineType("47",47);
    exp.defineType("49",49);
    exp.defineType("51",51);
    exp.defineType("55",55);
    exp.defineType("61",61);
    exp.defineType("63",63);
    exp.defineType("65",65);
  }
  argset.add(exp); 

  RooCategory nptag("nptag","nptag");
  nptag.defineType("nonp",0);
//  argset.add(nptag);

  RooRealVar dz("dz","dz",dz_min,dz_max,"mm");    argset.add(dz);
  RooRealVar sz_asc("sz_asc","dz_asc",0.01,0.15); argset.add(sz_asc);
  RooRealVar sz_sig("sz_sig","dz_sig",0.01,0.15); argset.add(sz_sig);
  RooRealVar chisq_z_asc("chisq_z_asc","chisq_z_asc",0.,200); argset.add(chisq_z_asc);
  RooRealVar chisq_z_sig("chisq_z_sig","chisq_z_sig",0.,200); argset.add(chisq_z_sig);

//  RooDataSet pids("pids","pids",pitree,argset);
  RooDataSet omegads("omegads","omegads",omegatree,argset,"(dz>0 || dz<0) && sz_asc>0 && sz_sig>0 && chisq_z_asc>0 && chisq_z_sig>0");
//  pids.Print();
  omegads.Print();

  RooRealVar tau("tau","tau",0.196,0.01,1,"mm"); tau.setConstant(kTRUE);
  RooRealVar dz0Om("dz0Om","dz0Om",0,-3.,3.,"mm"); dz0Om.setConstant(kTRUE);
  RooRealVar s01sigOm("s01sigOm","s01sigOm",2,0.1,5.);
  RooRealVar s02sigOm("s02sigOm","s02sigOm",13,0.1,27.);
  RooRealVar fsigOm("fsigOm","fsigOm",0.9,0.,1.);

//  RooGaussModel g1Om("g1Om","g1Om",dz,dz0Om,s01Om,sz);
//  RooGaussModel g2Om("g2Om","g2Om",dz,dz0Om,s02Om,sz);
  RooDecay dec1SigOm("dec1SigOm","dec1SigOm",dz,tau,g1sigOm,RooDecay::DoubleSided);
  RooDecay dec2SigOm("dec2SigOm","dec2SigOm",dz,tau,g2sigOm,RooDecay::DoubleSided);
  RooAddPdf pdfsigOm("pdfsigOm","pdfsigOm",RooArgList(dec1SigOm,dec2SigOm),RooArgSet(fsigOm));
  if(EXP!=55 && EXP>0){
    fsigOm.setVal(1.);
    fsigOm.setConstant(kTRUE);
    s02sigOm.setConstant(kTRUE);
  }
//  RooDecay pdfsigOm("pdfsigOm","pdpsigOm",z_sig,tau,g1sigOm,RooDecay::SingleSided);

//  pdfsigPi.fitTo(pids,ConditionalObservables(szSigPi));
  RooFitResult* fitRes = pdfsigOm.fitTo(omegads,Verbose(),ConditionalObservables(sz_asc));
//  fitRes->Print();

///////////
// Plots //
///////////
  RooPlot* zFrameSig = z_asc.frame();

  omegads.plotOn(zFrameSig,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdfsigOm.plotOn(zFrameSig,LineColor(kRed),ProjWData(omegads));
  TCanvas* z_cm_sig = new TCanvas("z_{sig}, cm","z_{sig}, mm",700,500);
  z_cm_sig->cd();
  omegads.statOn(zFrameSig,Layout(0.6,0.98,0.9),What("MR"),Label("#omega^{0}"),Format("NE",AutoPrecision(1)));
  TPad *pad1 = new TPad("pad1","pad1",0.01,0.00,0.99,0.99);
  pad1->Draw();
  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);
  zFrameSig->GetXaxis()->SetTitleOffset(0.75);
  zFrameSig->GetXaxis()->SetLabelSize(0.05);
  zFrameSig->GetXaxis()->SetTitleSize(0.06);
  zFrameSig->GetYaxis()->SetTitleOffset(1.6);
  zFrameSig->Draw();
  z_cm_sig->Update();
  stringstream out;
  out.str("");
  out << "pics/zAscFit_Exp" << EXP << ".png";
  z_cm_sig->Print(out.str().c_str());
  out.str("");
  out << "pics/zAscFit_Exp" << EXP << ".root";
  z_cm_sig->Print(out.str().c_str());

  return;
}
void Purity_2d_fit_etagg_v2(bool data = false) {
    TChain* tree = new TChain("TEvent");
    if(!data) tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
    else      tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_data.root");

    const int _mode = 2;
    const int _h0mode = 10;
    const int _b0f = -1;
//  gROOT->ProcessLine(".L pdfs/RooRhoDeltaEPdf.cxx+");

    RooCategory b0f("b0f","b0f");
    b0f.defineType("signal",1);
    b0f.defineType("fsr",10);
    b0f.defineType("bad_pi0",5);
    b0f.defineType("peak1",3);
    b0f.defineType("peak2",4);
    b0f.defineType("peak3",11);
    b0f.defineType("peak4",20);
    b0f.defineType("comb",-1);

    RooArgSet argset;

    const double mbcMin = 5.20;
    const double mbcMax = 5.29;
    double deMin = -0.15;
    if(keysflag) deMin = -0.3;
    const double deMax = 0.3;
    const double elliscaleDe  = TMath::Sqrt(4./TMath::Pi());
    const double elliscaleMbc = TMath::Sqrt(4./TMath::Pi());

    RooRealVar mbc_center("mbc_center","mbc_center",0.5*(mbc_min+mbc_max),mbc_min,mbc_max);
    mbc_center.setConstant(kTRUE);
    RooRealVar mbc_center_eq("mbc_center_eq","mbc_center_eq",mr_argedge_3-0.5*(mbc_max-mbc_min)*elliscaleMbc,mbc_min,mbc_max);
    mbc_center_eq.setConstant(kTRUE);
    RooRealVar de_center("de_center","de_center",0.5*(de_min+de_max),de_min,de_max);
    de_center.setConstant(kTRUE);
    RooRealVar mbc_radius("mbc_radius","mbc_radius",0.5*(mbc_max-mbc_min)*elliscaleMbc,0,0.5*(mbcMax-mbcMin));
    mbc_radius.setConstant(kTRUE);
    RooRealVar de_radius("de_radius","de_radius",0.5*(de_max-de_min)*elliscaleDe,0.,0.5*(deMax-deMin));
    de_radius.setConstant(kTRUE);
    RooRealVar mbc_radius1("mbc_radius1","mbc_radius1",0.5*(mbc_max-mbc_min),0,0.5*(mbcMax-mbcMin));
    mbc_radius1.setConstant(kTRUE);
    RooRealVar de_radius1("de_radius1","de_radius1",0.5*(de_max-de_min),0.,0.5*(deMax-deMin));
    de_radius1.setConstant(kTRUE);

    cout << 0.5*(mbc_min+mbc_max) << " " << 0.5*(mbc_max-mbc_min) << endl;
    cout << 0.5*(de_min+de_max) << " " << 0.5*(de_max-de_min) << endl;

    mbc_center.Print();
    mbc_center_eq.Print();

    const double BDTG_MIN = bdtg_cut_etagg;
    const double BDTG_MAX = 1;
    RooCategory mode("mode","mode");
    mode.defineType("eta",2);
    RooCategory h0mode("h0mode","h0mode");
    h0mode.defineType("gg",10);
    argset.add(mode);
    argset.add(h0mode);

    RooRealVar mbc("mbc","M_{bc}",0.5*(mbc_min+mbc_max),mbcMin,mbcMax,"GeV");
    argset.add(mbc);
    mbc.setRange("Signal",mbc_min,mbc_max);
    mbc.setRange("mbcSignal",mbc_min,mbc_max);
    mbc.setRange("deSignal",mbcMin,mbcMax);

    RooRealVar de("de","#DeltaE",deMin,deMax,"GeV");
    argset.add(de);
    de.setRange("Signal",de_min,de_max);
    de.setRange("mbcSignal",deMin,deMax);
    de.setRange("deSignal",de_min,de_max);

    RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV");
    argset.add(md);
    RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV");
    argset.add(mk);
    RooRealVar mh0("mh0","mh0",EtaMass-meta_cut,EtaMass+meta_cut,"GeV");
    argset.add(mh0);
    RooRealVar bdtg("bdtg","bdtg",BDTG_MIN,1.);
    argset.add(bdtg);
    RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut);
    argset.add(atckpi_max);

    if(!data) argset.add(b0f);
    RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");
//  RooDataSet* ds0 = ds.reduce(RooArgSet(de,mbc));

    stringstream out;
    if(!data) {
        out.str("");
        out << "de<" << de_max << " && de>" << de_min;
        out << " && mbc>" << mbc_min << " && mbc<" << mbc_max;
        Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
        sigtable->Print();
        sigtable->Print("v");

        Roo1DTable* fulltable = ds.table(b0f);
        fulltable->Print();
        fulltable->Print("v");
    }

//  RooDataHist* dh = ds0->binnedClone();

    ds.Print();

    ////////////////
    // Signal PDF //
    ////////////////
    ////////////
    // de pdf //
    ////////////
    if(!(_mode!=1 && _h0mode == 20 && _b0f == -1)) {
        RooRealVar de0("de0","de0",get_de0(_mode,_h0mode,_b0f),-0.2,0.1);
        if(cSIG) de0.setConstant(kTRUE);
        RooRealVar s1("s1","s1",get_s1(_mode,_h0mode,_b0f),0.,0.5);
        if(cSIG) s1.setConstant(kTRUE);
        RooGaussian g1("g1","g1",de,de0,s1);

        RooRealVar deCBl("deCBl","deCBl",get_deCBl(_mode,_h0mode,_b0f),-0.2,0.1);
        if(cSIG) deCBl.setConstant(kTRUE);
        RooRealVar sCBl("sCBl","sCBl",get_sCBl(_mode,_h0mode,_b0f),0.,0.5);
        if(cSIG) sCBl.setConstant(kTRUE);
        RooRealVar nl("nl","nl",get_nl(_mode,_h0mode,_b0f),0.,100.);
        if(cSIG) nl.setConstant(kTRUE);
//  RooRealVar nl("nl","nl",1.,0.,100.); nl.setConstant(kTRUE);
        RooRealVar alphal("alphal","alphal",get_alphal(_mode,_h0mode,_b0f),-10.,10.);
        if(cSIG) alphal.setConstant(kTRUE);

        RooRealVar deCBr("deCBr","deCBr",get_deCBr(_mode,_h0mode,_b0f),-0.2,0.1);
        if(cSIG) deCBr.setConstant(kTRUE);
        RooRealVar sCBr("sCBr","sCBr",get_sCBr(_mode,_h0mode,_b0f),0.,0.5);
        if(cSIG) sCBr.setConstant(kTRUE);
        RooRealVar nr("nr","nr",get_nr(_mode,_h0mode,_b0f),0.,100.);
        if(cSIG) nr.setConstant(kTRUE);
        RooRealVar alphar("alphar","alphar",get_alphar(_mode,_h0mode,_b0f),-10.,10.);
        if(cSIG) alphar.setConstant(kTRUE);

        RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
        RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

        RooRealVar fCBl("fCBl","fCBl",get_fCBl(_mode,_h0mode,_b0f),0.,1.);
        if(cSIG) fCBl.setConstant(kTRUE);
        RooRealVar fCBr("fCBr","fCBr",get_fCBr(_mode,_h0mode,_b0f),0.,1.);
        if(cSIG) fCBr.setConstant(kTRUE);

        RooAddPdf pdf_de_sig("pdf_de_sig","pdf_de_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));
    }

    if((_mode==3&&_h0mode == 20 || _mode==2) && _b0f == -1) {
        RooRealVar de0_201("de0_201","de0_201",get_de0(_mode,_h0mode,1),-0.1,0.1);
        de0_201.setConstant(kTRUE);
        RooRealVar s1_201("s1_201","s1_201",get_s1(_mode,_h0mode,1),0.,0.5);
        s1_201.setConstant(kTRUE);
        RooGaussian g1_201("g1_201","g1_201",de,de0_201,s1_201);

        RooRealVar deCBl_201("deCBl_201","deCBl_201",get_deCBl(_mode,_h0mode,1),-0.1,0.1);
        deCBl_201.setConstant(kTRUE);
        RooRealVar sCBl_201("sCBl_201","sCBl_201",get_sCBl(_mode,_h0mode,1),0.,0.5);
        sCBl_201.setConstant(kTRUE);
        RooRealVar nl_201("nl_201","nl_201",get_nl(_mode,_h0mode,1),0.,100.);
        nl_201.setConstant(kTRUE);
        RooRealVar alphal_201("alphal_201","alphal_201",get_alphal(_mode,_h0mode,1),-10.,10.);
        alphal_201.setConstant(kTRUE);
        RooRealVar deCBr_201("deCBr_201","deCBr_201",get_deCBr(_mode,_h0mode,1),-0.1,0.1);
        deCBr_201.setConstant(kTRUE);
        RooRealVar sCBr_201("sCBr_201","sCBr_201",get_sCBr(_mode,_h0mode,1),0.,0.5);
        sCBr_201.setConstant(kTRUE);
        RooRealVar nr_201("nr_201","nr_201",get_nr(_mode,_h0mode,1),0.,100.);
        nr_201.setConstant(kTRUE);
        RooRealVar alphar_201("alphar_201","alphar_201",get_alphar(_mode,_h0mode,1),-10.,10.);
        alphar_201.setConstant(kTRUE);
        RooCBShape CBl_201("CBl_201","CBl_201",de,deCBl_201,sCBl_201,alphal_201,nl_201);
        RooCBShape CBr_201("CBr_201","CBr_201",de,deCBr_201,sCBr_201,alphar_201,nr_201);

        RooRealVar fCBl_201("fCBl_201","fCBl_201",get_fCBl(_mode,_h0mode,1),0.,1.);
        fCBl_201.setConstant(kTRUE);
        RooRealVar fCBr_201("fCBr_201","fCBr_201",get_fCBr(_mode,_h0mode,1),0.,1.);
        fCBr_201.setConstant(kTRUE);

        RooAddPdf pdf_de_201("pdf_de_201","pdf_de_201",RooArgList(CBl_201,CBr_201,g1_201),RooArgSet(fCBl_201,fCBr_201));

        RooRealVar de0_205("de0_205","de0_205",get_de0(_mode,_h0mode,5),-0.1,0.1);
        de0_205.setConstant(kTRUE);
        RooRealVar s1_205("s1_205","s1_205",get_s1(_mode,_h0mode,5),0.,0.5);
        s1_205.setConstant(kTRUE);
        RooGaussian g1_205("g1_205","g1_205",de,de0_205,s1_205);

        RooRealVar deCBl_205("deCBl_205","deCBl_205",get_deCBl(_mode,_h0mode,5),-0.1,0.1);
        deCBl_205.setConstant(kTRUE);
        RooRealVar sCBl_205("sCBl_205","sCBl_205",get_sCBl(_mode,_h0mode,5),0.,0.5);
        sCBl_205.setConstant(kTRUE);
        RooRealVar nl_205("nl_205","nl_205",get_nl(_mode,_h0mode,5),0.,100.);
        nl_205.setConstant(kTRUE);
        RooRealVar alphal_205("alphal_205","alphal_205",get_alphal(_mode,_h0mode,5),-10.,10.);
        alphal_205.setConstant(kTRUE);
        RooCBShape CBl_205("CBl_205","CBl_205",de,deCBl_205,sCBl_205,alphal_205,nl_205);

        RooRealVar fCBl_205("fCBl_205","fCBl_205",get_fCBl(_mode,_h0mode,5),0.,1.);
        fCBl_205.setConstant(kTRUE);

        RooAddPdf pdf_de_205("pdf_de_205","pdf_de_205",RooArgList(CBl_205,g1_205),RooArgSet(fCBl_205));

        RooRealVar f_201("f_201","f_201",get_f201(_mode,_h0mode),0.,1.);
        if(cSIG) f_201.setConstant(kTRUE);
        RooAddPdf pdf_de_sig("pdf_de_sig","pdf_de_sig",RooArgList(pdf_de_201,pdf_de_205),RooArgSet(f_201));
    }

    /////////////
    // mbc pdf //
    /////////////
    const bool cond_flag = false;//(b0f == 5);
    if(cond_flag) {
        RooRealVar cond("cond","cond",mr_cond_3,-0.1.,1.);
        if(cRHO) cond.setConstant(kTRUE);
        RooRealVar condr("condr","condr",mr_condr_3,-1000.,1.);
        if(cRHO) condr.setConstant(kTRUE);

        RooRealVar _sl("_sl","_sl",get_sl(_mode,_h0mode,_b0f),0.,0.5);
        if(cSIG) _sl.setConstant(kTRUE);
        RooRealVar _sr("_sr","_sr",get_sr(_mode,_h0mode,_b0f),0.0005,0.5);
        if(cSIG) _sr.setConstant(kTRUE);
        RooFormulaVar sl("sl","sl","@0+@1*@2",RooArgList(_sl,cond,de));
        RooFormulaVar sr("sr","sr","@0+@1*@2",RooArgList(_sr,condr,de));

        RooRealVar _sll("_sll","_sll",get_sll(_mode,_h0mode,_b0f),0.,0.5);
        if(cSIG) _sll.setConstant(kTRUE);
        RooRealVar _srr("_srr","_srr",get_srr(_mode,_h0mode,_b0f),0.0005,0.5);
        if(cSIG) _srr.setConstant(kTRUE);
        RooFormulaVar sll("sll","sll","@0+@1*@2",RooArgList(_sll,cond,de));
        RooFormulaVar srr("srr","srr","@0+@1*@2",RooArgList(_srr,condr,de));
    } else {
Exemple #21
0
void BDT_cuts_norm(){
    
    
    gROOT->ProcessLine(".L ~/cern/project/lhcbStyle.C");
    lhcbStyle();
    
    const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt.root");
    const std::string treename = "withbdt";
    
    const std::string filenameMC("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_MC_2011_2012_norm_withbdt.root");
    
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    TFile* fileMC = TFile::Open( filenameMC.c_str() );
    if( !fileMC ) std::cout << "file " << filenameMC << " does not exist" << std::endl;
    TTree* treeMC = (TTree*)fileMC->Get( treename.c_str() );
    if( !treeMC ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    
    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi pK^{-})", 5550., 5700., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5630., 5610., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 30.0, 5.0, 300.0);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.8, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 0.7, 0.2, 10.0);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);
    RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0);
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); 
    RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 ));
    RooRealVar cbRatio("cbRatio","cb Ratio", 0.8, 0.1, 1.0);
    RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e0, 1e6);
    RooRealVar bgYield("bgYield","bg Yield", 1e4, 1e0, 1e6);
    
    
    
    //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!!
    /*
    EXT PARAMETER                                INTERNAL      INTERNAL
  NO.   NAME      VALUE            ERROR       STEP SIZE       VALUE
   1  alpha1       2.18020e+00   2.85078e-02   1.38432e-04  -2.56034e-01
   2  alpha2      -2.79102e+00   6.74385e-02   1.51818e-04  -1.49177e-02
   3  cbRatio      3.07172e-01   1.49204e-02   1.72642e-04  -5.69984e-01
   4  mean         5.61985e+03   9.58397e-03   5.56682e-05  -9.66293e-02
   5  n1           1.49358e+00   8.14447e-02   2.09300e-04  -9.70542e-01
   6  n2           1.45276e+00   1.09864e-01   2.59028e-04  -8.39538e-01
   7  sigma1       8.46303e+00   1.32851e-01   2.86985e-05  -1.01453e+00
   8  sigma2       4.93976e+00   3.42842e-02   5.03572e-06  -1.44512e+00
    */
    alpha1.setVal( 2.18020e+00 );
    alpha2.setVal( -2.79102e+00 );
    n1.setVal( 1.49358e+00 );
    n2.setVal( 1.45276e+00 );
    frac2.setVal( 3.07172e-01 );
    sigma1.setVal( 8.46303e+00 );
    sigma2.setVal( 4.93976e+00 );
    
    alpha1.setConstant( true );
    alpha2.setConstant( true );
    frac2.setConstant( true );
    n1.setConstant( true );
    n2.setConstant( true );
    sigma1.setConstant( true );
    sigma2.setConstant( true );
    
    // -- bg, mass shape
    RooRealVar a1("a1","a1", -0.1, -0.5, 0.5);
    RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1);
    RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.);
    RooRealVar sigma3("sigma3","sigma3", 5., 1., 10.);
    RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    //RooAddPdf bg("bg","bg", RooArgList(comb), RooArgList(frac3));
    
    // -- add signal & bg
    RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield));  
    
    
    double efficiencies1[40];
    double efficiencies1_error[40];
    double bdt_cuts[40];
    double efficiencies2[40];
    double efficiencies2_error[40];
    double sideband_bg_val[40];
    
    double MC_pre = treeMC->GetEntries();
    
    double effvals[40];
    
    
    //loop starting here
    for(int i=0; i < 40; i=i+1) {
        double cut_val = -1.0 + i*0.05;
        //double cut_val = -1.0; // testing
        bdt_cuts[i] = cut_val;
        
        std::stringstream c;
        c << "bdtg3" << " >= " << cut_val;
        const std::string cut = c.str();
        
        //std::cout << cut;
    
        RooArgSet obs;
        obs.add(Lambda_b0_DTF_MASS_constr1);
        //obs.add(chi_c_Mp);
        //obs.add(mass_pK);
        obs.add(Jpsi_M);
        obs.add(chi_c_M);
        obs.add(bdtg3); 
    
        RooDataSet ds("ds","ds", obs, RooFit::Import(*tree), RooFit::Cut(cut.c_str())); 
    
        RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();
    
        RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() );
        
        double sig_val = sigYield.getVal();
        double bg_val = bgYield.getVal();
        double sig_error = sigYield.getError();
        double bg_error = bgYield.getError();
        
        double efficiency1 = (sig_val)/(sqrt(sig_val + bg_val));
        efficiencies1[i] = efficiency1;
        
        double efficiency1_error_sq = (pow(sig_error,2)/(sig_val+bg_val) + (pow(sig_val,2)*(pow(sig_error,2)+pow(bg_error,2))/(4*pow((sig_val+bg_val),3))));
        
        double efficiency1_error = sqrt(efficiency1_error_sq);
        efficiencies1_error[i] = efficiency1_error;
        
        /*
        double MC_post = treeMC->GetEntries(cut.c_str());
        
        double eff_val = MC_post/MC_pre; 
        
        //something here to get the sideband background count
        
        
        Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.);
        RooFitResult * sideband = bg.fitTo( ds, RooFit::Range("R") );
        sideband->Print();
        
        Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.);
        RooAbsReal* integral = pdf.createIntegral(Lambda_b0_DTF_MASS_constr1, RooFit::Range("R"));
        //std::cout << integral->getVal() << std::endl;
        //std::cout << integral->getError() << std::endl;
        //Double_t sideband_bg_val = integral->getVal();
        //double sideband_bg_error = integral->getError();
        
        std::stringstream r;
        r << "bdtg3" << " >= " << cut_val << " && Lambda_b0_DTF_MASS_constr1 >= 5650 && Lambda_b0_DTF_MASS_constr1 <= 5700";
        const std::string cut2 = r.str();
        
        double integ = tree->GetEntries(cut2.c_str());
        //double integ = integral->getVal();
        
        double efficiency2 = eff_val/(5./2. + sqrt(integ));
        efficiencies2[i] = efficiency2;
        
        effvals[i]=eff_val;
        
        
        std::cout << "\n" << integ << std::endl;
        std::cout << "\n" << eff_val << std::endl;
        std::cout << "\n" << efficiency2 << std::endl;
        */
        
        //double efficiency2_error = efficiency2*sqrt(pow(eff_error/eff_val,2)+(1/(4*sideband_bg_val))*pow(sideband_bg_error/(5/2+sideband_bg_val),2));
        
        //std::cout << "\n\n" << "BDT cut value = " << cut_val << "\n" ;
        //std::cout << "S = " << sig_val << " +/- " << sig_error << "\n" ;
        //std::cout << "B = " << bg_val << " +/- " << bg_error << "\n" ;
        //std::cout << "S/sqrt(S+B) = " << efficiency << " +/- " << efficiency_error << "\n\n" ;
        
        //ds.plotOn( plot );
        //pdf.plotOn( plot );
        
        //RooPlot* plotPullMass = mass.frame();
        
        //plotPullMass->addPlotable( plot->pullHist() );
        //plotPullMass->SetMinimum();
        //plotPullMass->SetMaximum();
        
        //std::cout << cut_val;
    }
    
    
    TCanvas *c1 = new TCanvas(); 
    
    //double zeros[20];
    //for (i=0, i<20, i++) zeros[i]=0.0;
    
    TGraphErrors* graph = new TGraphErrors(40, bdt_cuts, efficiencies1, 0, efficiencies1_error);
    
    graph->SetTitle("S/sqrt(S+B) vs BDTG3 cut");
    //graph->SetMarkerColor(4);
    //graph->SetMarkerStyle(20);
    //graph->SetMarkerSize(1.0);
    graph->GetXaxis()->SetTitle("BDTG3 cut (>)");
    graph->GetXaxis()->SetRangeUser(-1.0,1.0);
    graph->GetYaxis()->SetTitle("S/sqrt(S+B)");
    //graph->Fit("pol5"); 
    graph->Draw("AP");
    c1->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_S_sqrtS+B.pdf");
    //return c1;
    
    //std::cout << efficiencies1_error[5] << std::endl;
    
    //gStyle->SetOptFit(1011);
    /*TCanvas *c2 = new TCanvas();
    
    TGraph* graph2 = new TGraph(40, bdt_cuts, efficiencies2);
    
    graph2->SetTitle("eff/[5/2+sqrt(B)] vs BDTG3 cut");
    graph2->SetMarkerColor(4);
    graph2->SetMarkerStyle(20);
    graph2->SetMarkerSize(1.0);
    graph2->GetXaxis()->SetTitle("BDTG3 cut (>)");
    graph2->GetXaxis()->SetRangeUser(-1.0,1.0);
    graph2->GetYaxis()->SetTitle("eff/[5/2+sqrt(B)]");
    //graph2->Fit("pol7"); 
    graph2->Draw("AP");
    c2->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_Punzi.png");
    //return c2;
    */
    
    
    
    /*
    TCanvas* c = new TCanvas();
    
    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0);
    pad1->SetBottomMargin(0.1);
    pad1->SetTopMargin(0.1);
    pad1->Draw();
    c->cd();
    TPad* pad2 = new TPad("pad2","pad2", 0, 0, 1, 0.3);
    pad2->SetBottomMargin(0.1);
    pad2->SetTopMargin(0.0);
    pad2->Draw();
    
    
    //pdf.plotOn( plot, RooFit::Components( DfbPdf ), RooFit::LineColor( kRed ), RooFit::LineStyle(kDashed) );
    //pdf.plotOn( plot, RooFit::Components( promptPdf ), RooFit::LineColor( kBlue ), RooFit::LineStyle(kDotted) );
    //pdf.plotOn( plot, RooFit::Components( bgPdf ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashDotted) );
    
    pad1->cd();
    plot->Draw();
    
    pad2->cd();
    plotPullMass->Draw("AP");
    
    c->SaveAs(out_file_mass);
    
    RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
            ds, &pdf, RooArgList(sigYield, bgYield) );
    
    
    RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ;
    */
    /*   
    TCanvas* d = new TCanvas();
    RooPlot* w_mass_chicp = mass_chicp.frame();
    dataw_z->plotOn(w_mass_chicp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_chicp->Draw();
    d->SaveAs("m_chicp_sweighted.png");
    
    TCanvas* e = new TCanvas();
    RooPlot* w_mass_pK = mass_pK.frame();
    dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_pK->Draw();
    e->SaveAs("m_pK_sweighted.png");
    */
    /*
    TCanvas* f = new TCanvas();
    RooPlot* w_mass_Jpsi = mass_Jpsi.frame();
    dataw_z->plotOn(w_mass_Jpsi, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_Jpsi->Draw();
    f->SaveAs("m_Jpsi_sweighted.png");
    
    TCanvas* g = new TCanvas();
    RooPlot* w_mass_Chic = mass_Chic.frame();
    dataw_z->plotOn(w_mass_Chic, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_Chic->Draw();
    g->SaveAs("m_Chic_sweighted.png");
    */
    
    
}
void BackSlice_fit(const int m_mode = 1, const bool bbflag = false){
  // mode 1 -> pi0
  // mode 2 -> eta -> gg
  // mode 3 -> eta -> pi+pi-pi0
  // mode 4 -> omega
//  const bool projection_flag = true;
//  const bool save_flag       = true;

  double BDTG_MIN = 0;
  double BDTG_MAX = 1;

  RooCategory mode("mode","mode");
  RooCategory h0mode("h0mode","h0mode");
  RooArgSet argset;

  switch(m_mode){
  case 1:
    mode.defineType("pi0",1);
    h0mode.defineType("gg",10);
    BDTG_MIN = bdtg_cut_pi0;
    break;
  case 2:
    mode.defineType("eta",2);
    h0mode.defineType("gg",10);
    BDTG_MIN = bdtg_cut_etagg;
    break;
  case 3:
    mode.defineType("eta",2);
    h0mode.defineType("ppp",20);
    BDTG_MIN = bdtg_cut_etappp;
    break;
  case 4:
    mode.defineType("omega",3);
    h0mode.defineType("ppp",20);
    BDTG_MIN = bdtg_cut_omega;
    break;
  }

  argset.add(mode); argset.add(h0mode);

  TFile *ifile;
  if(!bbflag){
    //ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_cont_0-1_full.root");
    ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
  } else{
    ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_bb_0-1_full.root");
  }
  TTree *tree = (TTree*)ifile->Get("TEvent");

//  string cuts;
  RooCategory b0f("b0f","b0f");
  b0f.defineType("comb",-1);
  argset.add(b0f);

  const double mbcMin = 5.20;
  const double mbcMax = 5.29;
  const double deMin  = -0.3;
  const double deMax  =  0.3;

  RooRealVar mbc("mbc","M_{bc}",mbcMin,mbcMax,"GeV"); argset.add(mbc);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);

//  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
//  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
//  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtg("bdtg","bdtg",BDTG_MIN,BDTG_MAX); argset.add(bdtg);
//  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  const int NSlices = 10;
  double c1_arr[NSlices], c1_arr_err[NSlices];
  double c2_arr[NSlices], c2_arr_err[NSlices];
  double mbc_arr[NSlices], mbc_arr_err[NSlices];
  double chisq_arr[NSlices];
  stringstream out;
  double dmbc = (mbcMax-mbcMin)/NSlices;

  RooDataSet ds("ds","ds",tree,argset);
  ds.Print();

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c1("c1","c1",mc_c1,-10.,10.);// if(cComb && false) c1.setConstant(kTRUE);
  RooRealVar c2("c2","c2",0,-10.,10.);// c2.setConstant(kTRUE);
  RooChebychev pdf("pdf","pdf",de,RooArgSet(c1,c2));

  RooDataSet* ds0;
  for(int i=0; i<NSlices; i++){
    out.str("");
    out << "mbc>" << mbcMin+i*dmbc << " && mbc<" << mbcMin+(i+1)*dmbc;
    ds0 = (RooDataSet*)ds.reduce(RooArgSet(de),out.str().c_str());

    pdf.fitTo(*ds0,Verbose(),Timer(true));

    c1_arr[i] = c1.getVal(); c1_arr_err[i] = c1.getError();
    c2_arr[i] = c2.getVal(); c2_arr_err[i] = c2.getError();
    mbc_arr[i] = mbcMin+(0.5+i)*dmbc; mbc_arr_err[i] = 0;

    RooPlot* deFrame = de.frame();
    ds0->plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
    pdf.plotOn(deFrame,LineWidth(2));

//    out.str("");
//    out << "dE, Signal " << i;
//    TCanvas* cmmbc = new TCanvas(out.str().c_str(),out.str().c_str(),600,600);
//    cmmbc->cd();

//    TPad *pad1 = new TPad("pad1","pad1",0.01,0.00,0.99,0.99);
//    pad1->Draw();

//    pad1->cd();
//    pad1->SetLeftMargin(0.15);
//    pad1->SetFillColor(0);

//    deFrame->GetXaxis()->SetTitleSize(0.05);
//    deFrame->GetXaxis()->SetTitleOffset(0.85);
//    deFrame->GetXaxis()->SetLabelSize(0.04);
//    deFrame->GetYaxis()->SetTitleOffset(1.6);
//    deFrame->Draw();

    chisq_arr[i] = deFrame->chiSquare();
  }

  for(int i=0; i<NSlices; i++){
    cout << c1_arr[i] << " " << c2_arr[i] << " " << chisq_arr[i] << endl;
  }

  TGraphErrors* gr_c1 = new TGraphErrors(NSlices,mbc_arr,c1_arr,mbc_arr_err,c1_arr_err);
  gr_c1->SetTitle("c_{1}");
  gr_c1->SetMarkerSize(1);
  gr_c1->SetMarkerColor(kBlue);
  gr_c1->SetMarkerStyle(21);
  TGraphErrors* gr_c2 = new TGraphErrors(NSlices,mbc_arr,c2_arr,mbc_arr_err,c2_arr_err);
  gr_c2->SetTitle("c_{2}");
  gr_c2->SetMarkerSize(1);
  gr_c2->SetMarkerColor(kBlue);
  gr_c2->SetMarkerStyle(21);
  TGraphErrors* gr_chisq = new TGraphErrors(NSlices,mbc_arr,chisq_arr,mbc_arr_err,mbc_arr_err);
  gr_chisq->SetTitle("Chi2");
  gr_chisq->SetMarkerSize(1);
  gr_chisq->SetMarkerColor(kBlue);
  gr_chisq->SetMarkerStyle(21);

  TCanvas* cm = new TCanvas("de","#Delta E, Cmb background",800,400);
  cm->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.01,0.49,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.51,0.01,0.99,0.99);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetGrid();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);
  gr_c1->Draw("AP");
  gr_c1->Fit("pol2");

  pad2->cd();
  pad2->SetGrid();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  gr_c2->Draw("AP");
  gr_c2->Fit("pol2");

  cm->Update();

  TCanvas* cm_chi2 = new TCanvas("chi2","#chi^{2}",400,400);
  cm_chi2->cd();
  cm_chi2->SetLeftMargin(0.15);
  cm_chi2->SetFillColor(0);
  gr_chisq->Draw("AP");

  cm_chi2->Update();

  return;
}
void Purity_1d_fit(int type = 0){
  TChain* tree = new TChain("TEvent");
  if(!type) tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
  else      tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_data.root");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
  b0f.defineType("rho",3);
  b0f.defineType("comb",-1);

  RooArgSet argset;

  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbc_min,mbc_max,"GeV"); argset.add(mbc);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  if(!type) argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");
//  RooDataSet* ds0 = ds.reduce(RooArgSet(de));
  
  stringstream out;
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");

    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }

//  RooDataHist* dh = ds0->binnedClone();

//  ds0->Print();

  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0("de0","de0",m_de0,-0.1,0.1); if(cSig) de0.setConstant(kTRUE);
  RooRealVar s1("s1","s1",m_s1,0.,0.5); if(cSig) s1.setConstant(kTRUE);
  RooGaussian g1("g1","g1",de,de0,s1);

  RooRealVar deCBl("deCBl","deCBl",m_deCBl,-0.1,0.1); if(cSig) deCBl.setConstant(kTRUE);
  RooRealVar sCBl("sCBl","sCBl",m_sCBl,0.,0.5); if(cSig) sCBl.setConstant(kTRUE);
  RooRealVar nl("nl","nl",m_nl,0.,100.); if(cSig) nl.setConstant(kTRUE);
  RooRealVar alphal("alphal","alphal",m_alphal,-10.,10.); if(cSig) alphal.setConstant(kTRUE);

  RooRealVar deCBr("deCBr","deCBr",m_deCBr,-0.1,0.1); if(cSig) deCBr.setConstant(kTRUE);
  RooRealVar sCBr("sCBr","sCBr",m_sCBr,0.,0.5); if(cSig) sCBr.setConstant(kTRUE);
  RooRealVar nr("nr","nr",m_nr,0.,100.); if(cSig) nr.setConstant(kTRUE);
  RooRealVar alphar("alphar","alphar",m_alphar,-10.,10.); if(cSig) alphar.setConstant(kTRUE);

  RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
  RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

  RooRealVar fCBl("fCBl","fCBl",m_fCBl,0.,1.); if(cSig) fCBl.setConstant(kTRUE);
  RooRealVar fCBr("fCBr","fCBr",m_fCBr,0.,1.); if(cSig) fCBr.setConstant(kTRUE);

  RooAddPdf pdf_sig("pdf_sig","pdf_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c1("c1","c1",mc_c1_1d,-10.,10.); if(cComb) c1.setConstant(kTRUE);
  RooRealVar c2("c2","c2",mc_c2_1d,-10.,10.); if(cComb) c2.setConstant(kTRUE);
  RooChebychev pdf_comb("pdf_comb","pdf_comb",de,RooArgSet(c1,c2));

  /////////////
  // Rho PDF //
  /////////////
  ////////////
  // de pdf //
  ////////////
if(de_rho_param == 0){
  RooRealVar exppar("exppar","exppar",mr_exppar,-40.,-25.);// if(cRho) exppar.setConstant(kTRUE);
  RooExponential pdf_rho("pdf_rho","pdf_rho",de,exppar);
  }
  
  RooRealVar de0r("de0r","de0r",mr_de0r,-0.2,0.12); if(cRho) de0r.setConstant(kTRUE);
  
  if(de_rho_param == 1){
   RooRealVar slopel("slopel","slopel",mr_slopel,-1000,-500.); if(cRho) slopel.setConstant(kTRUE);
   RooRealVar sloper("sloper","sloper",mr_sloper,-10000,0.); if(cRho) sloper.setConstant(kTRUE);
   RooRealVar steep("steep","steep",mr_steep,7.,9.); if(cRho) steep.setConstant(kTRUE);
   RooRealVar p5("p5","p5",mr_p5,0.01,1000.); if(cRho) p5.setConstant(kTRUE);
   RooRhoDeltaEPdf pdf_rho("pdf_rho","pdf_rho",de,de0r,slopel,sloper,steep,p5);
  }
  
  if(de_rho_param == -1){
   RooRealVar x0("x0","x0",mr_x0_1d,-0.2,0.12); if(cRho) x0.setConstant(kTRUE);
   RooRealVar p1("p1","p1",mr_p1_1d,-1000.,100.); if(cRho) p1.setConstant(kTRUE);
   RooRealVar p2("p2","p2",mr_p2_1d,0.,100.); if(cRho) p2.setConstant(kTRUE);
   RooGenericPdf pdf_rho("pdf_rho","1+@0*@1-@2*TMath::Log(1+TMath::Exp(@2*(@0-@1)/@3))",RooArgSet(de,x0,p1,p2));
  }
  //////////////////
  // Complete PDF //
  //////////////////
  RooRealVar Nsig("Nsig","Nsig",700,100.,1500.);// fsig.setConstant(kTRUE);
  RooRealVar Nrho("Nrho","Nrho",400,100,1500.);// frho.setConstant(kTRUE);
  RooRealVar Ncmb("Ncmb","Ncmb",1000,100,100000);// frho.setConstant(kTRUE);
  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_rho,pdf_comb),RooArgList(Nsig,Nrho,Ncmb));

  pdf.fitTo(ds,Verbose(),Timer(true));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intRho  = pdf_rho.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*Nrho.getVal();
   const double nrho_err = intRho->getVal()*Nrho.getError();
   const double nrho_err_npq = TMath::Sqrt(nrho*(Nrho.getVal()-nrho)/Nrho.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);
   cout << "Nsig = " << nsig <<" +- " << nsig_err << endl;
   cout << "Nrho = " << nrho <<" +- " << nrho_err << endl;
   cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << endl;
   
  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_rho),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_comb),LineStyle(kDashed));
  pdf.plotOn(deFrame,LineWidth(2));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out1;
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  pt->AddText(out1.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,50);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,50);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");
    
    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }
  
  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "Nrho = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;
}
	/// \brief Needed if the PDF has more than one observable
	/// The constructors only fill in one observable
	void AddObservable( RooRealVar * newobs ) { obs->add(*newobs); }
// internal routine to run the inverter
HypoTestInverterResult *
RooStats::HypoTestInvTool::RunInverter(RooWorkspace * w,
                                       const char * modelSBName, const char * modelBName, 
                                       const char * dataName, int type,  int testStatType, 
                                       bool useCLs, int npoints, double poimin, double poimax, 
                                       int ntoys,
                                       bool useNumberCounting,
                                       const char * nuisPriorName ){

   std::cout << "Running HypoTestInverter on the workspace " << w->GetName() << std::endl;
  
   w->Print();
  
  
   RooAbsData * data = w->data(dataName); 
   if (!data) { 
      Error("StandardHypoTestDemo","Not existing data %s",dataName);
      return 0;
   }
   else 
      std::cout << "Using data set " << dataName << std::endl;
  
   if (mUseVectorStore) { 
      RooAbsData::setDefaultStorageType(RooAbsData::Vector);
      data->convertToVectorStore() ;
   }
  
  
   // get models from WS
   // get the modelConfig out of the file
   ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);
   ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
  
   if (!sbModel) {
      Error("StandardHypoTestDemo","Not existing ModelConfig %s",modelSBName);
      return 0;
   }
   // check the model 
   if (!sbModel->GetPdf()) { 
      Error("StandardHypoTestDemo","Model %s has no pdf ",modelSBName);
      return 0;
   }
   if (!sbModel->GetParametersOfInterest()) {
      Error("StandardHypoTestDemo","Model %s has no poi ",modelSBName);
      return 0;
   }
   if (!sbModel->GetObservables()) {
      Error("StandardHypoTestInvDemo","Model %s has no observables ",modelSBName);
      return 0;
   }
   if (!sbModel->GetSnapshot() ) { 
      Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }
  
   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) { 
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) { 
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) { 
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar) 
            RooStats::SetAllConstant(*bnuisPar);
      }
   }
  
   if (!bModel || bModel == sbModel) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("_with_poi_0"));      
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return 0;
      double oldval = var->getVal();
      var->setVal(0);
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
   }
   else { 
      if (!bModel->GetSnapshot() ) { 
         Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi and 0 values ",modelBName);
         RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
         if (var) { 
            double oldval = var->getVal();
            var->setVal(0);
            bModel->SetSnapshot( RooArgSet(*var)  );
            var->setVal(oldval);
         }
         else { 
            Error("StandardHypoTestInvDemo","Model %s has no valid poi",modelBName);
            return 0;
         }         
      }
   }

   // check model  has global observables when there are nuisance pdf
   // for the hybrid case the globobs are not needed
   if (type != 1 ) { 
      bool hasNuisParam = (sbModel->GetNuisanceParameters() && sbModel->GetNuisanceParameters()->getSize() > 0);
      bool hasGlobalObs = (sbModel->GetGlobalObservables() && sbModel->GetGlobalObservables()->getSize() > 0);
      if (hasNuisParam && !hasGlobalObs ) {  
         // try to see if model has nuisance parameters first 
         RooAbsPdf * constrPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisanceConstraintPdf_sbmodel");
         if (constrPdf) { 
            Warning("StandardHypoTestInvDemo","Model %s has nuisance parameters but no global observables associated",sbModel->GetName());
            Warning("StandardHypoTestInvDemo","\tThe effect of the nuisance parameters will not be treated correctly ");
         }
      }
   }


  
   // run first a data fit 
  
   const RooArgSet * poiSet = sbModel->GetParametersOfInterest();
   RooRealVar *poi = (RooRealVar*)poiSet->first();
  
   std::cout << "StandardHypoTestInvDemo : POI initial value:   " << poi->GetName() << " = " << poi->getVal()   << std::endl;  
  
   // fit the data first (need to use constraint )
   TStopwatch tw; 

   bool doFit = initialFit;
   if (testStatType == 0 && initialFit == -1) doFit = false;  // case of LEP test statistic
   if (type == 3  && initialFit == -1) doFit = false;         // case of Asymptoticcalculator with nominal Asimov
   double poihat = 0;

   if (minimizerType.size()==0) minimizerType = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
   else 
      ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerType.c_str());
    
   Info("StandardHypoTestInvDemo","Using %s as minimizer for computing the test statistic",
        ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str() );
   
   if (doFit)  { 

      // do the fit : By doing a fit the POI snapshot (for S+B)  is set to the fit value
      // and the nuisance parameters nominal values will be set to the fit value. 
      // This is relevant when using LEP test statistics

      Info( "StandardHypoTestInvDemo"," Doing a first fit to the observed data ");
      RooArgSet constrainParams;
      if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
      RooStats::RemoveConstantParameters(&constrainParams);
      tw.Start(); 
      RooFitResult * fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                                       Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel), Constrain(constrainParams), Save(true) );
      if (fitres->status() != 0) { 
         Warning("StandardHypoTestInvDemo","Fit to the model failed - try with strategy 1 and perform first an Hesse computation");
         fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(true), Hesse(false),Minimizer(minimizerType.c_str(),"Migrad"), Strategy(1), PrintLevel(mPrintLevel+1), Constrain(constrainParams), Save(true) );
      }
      if (fitres->status() != 0) 
         Warning("StandardHypoTestInvDemo"," Fit still failed - continue anyway.....");
  
  
      poihat  = poi->getVal();
      std::cout << "StandardHypoTestInvDemo - Best Fit value : " << poi->GetName() << " = "  
                << poihat << " +/- " << poi->getError() << std::endl;
      std::cout << "Time for fitting : "; tw.Print(); 
  
      //save best fit value in the poi snapshot 
      sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
      std::cout << "StandardHypoTestInvo: snapshot of S+B Model " << sbModel->GetName() 
                << " is set to the best fit value" << std::endl;
  
   }

   // print a message in case of LEP test statistics because it affects result by doing or not doing a fit 
   if (testStatType == 0) {
      if (!doFit) 
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit is not done and the TS will use the nuisances at the model value");
      else 
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit has been done and the TS will use the nuisances at the best fit value");
   }


   // build test statistics and hypotest calculators for running the inverter 
  
   SimpleLikelihoodRatioTestStat slrts(*sbModel->GetPdf(),*bModel->GetPdf());

   // null parameters must includes snapshot of poi plus the nuisance values 
   RooArgSet nullParams(*sbModel->GetSnapshot());
   if (sbModel->GetNuisanceParameters()) nullParams.add(*sbModel->GetNuisanceParameters());
   if (sbModel->GetSnapshot()) slrts.SetNullParameters(nullParams);
   RooArgSet altParams(*bModel->GetSnapshot());
   if (bModel->GetNuisanceParameters()) altParams.add(*bModel->GetNuisanceParameters());
   if (bModel->GetSnapshot()) slrts.SetAltParameters(altParams);
  
   // ratio of profile likelihood - need to pass snapshot for the alt
   RatioOfProfiledLikelihoodsTestStat 
      ropl(*sbModel->GetPdf(), *bModel->GetPdf(), bModel->GetSnapshot());
   ropl.SetSubtractMLE(false);
   if (testStatType == 11) ropl.SetSubtractMLE(true);
   ropl.SetPrintLevel(mPrintLevel);
   ropl.SetMinimizer(minimizerType.c_str());
  
   ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
   if (testStatType == 3) profll.SetOneSided(true);
   if (testStatType == 4) profll.SetSigned(true);
   profll.SetMinimizer(minimizerType.c_str());
   profll.SetPrintLevel(mPrintLevel);

   profll.SetReuseNLL(mOptimize);
   slrts.SetReuseNLL(mOptimize);
   ropl.SetReuseNLL(mOptimize);

   if (mOptimize) { 
      profll.SetStrategy(0);
      ropl.SetStrategy(0);
      ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   }
  
   if (mMaxPoi > 0) poi->setMax(mMaxPoi);  // increase limit
  
   MaxLikelihoodEstimateTestStat maxll(*sbModel->GetPdf(),*poi); 
   NumEventsTestStat nevtts;

   AsymptoticCalculator::SetPrintLevel(mPrintLevel);
  
   // create the HypoTest calculator class 
   HypoTestCalculatorGeneric *  hc = 0;
   if (type == 0) hc = new FrequentistCalculator(*data, *bModel, *sbModel);
   else if (type == 1) hc = new HybridCalculator(*data, *bModel, *sbModel);
   // else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false, mAsimovBins);
   // else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true, mAsimovBins);  // for using Asimov data generated with nominal values 
   else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false );
   else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true );  // for using Asimov data generated with nominal values 
   else {
      Error("StandardHypoTestInvDemo","Invalid - calculator type = %d supported values are only :\n\t\t\t 0 (Frequentist) , 1 (Hybrid) , 2 (Asymptotic) ",type);
      return 0;
   }
  
   // set the test statistic 
   TestStatistic * testStat = 0;
   if (testStatType == 0) testStat = &slrts;
   if (testStatType == 1 || testStatType == 11) testStat = &ropl;
   if (testStatType == 2 || testStatType == 3 || testStatType == 4) testStat = &profll;
   if (testStatType == 5) testStat = &maxll;
   if (testStatType == 6) testStat = &nevtts;

   if (testStat == 0) { 
      Error("StandardHypoTestInvDemo","Invalid - test statistic type = %d supported values are only :\n\t\t\t 0 (SLR) , 1 (Tevatron) , 2 (PLR), 3 (PLR1), 4(MLE)",testStatType);
      return 0;
   }
  
  
   ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
   if (toymcs && (type == 0 || type == 1) ) { 
      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) { 
         if (useNumberCounting)   Warning("StandardHypoTestInvDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else { 
         // for not extended pdf
         if (!useNumberCounting  )  { 
            int nEvents = data->numEntries();
            Info("StandardHypoTestInvDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            toymcs->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestInvDemo","using a number counting pdf");
            toymcs->SetNEventsPerToy(1);
         }
      }

      toymcs->SetTestStatistic(testStat);
    
      if (data->isWeighted() && !mGenerateBinned) { 
         Info("StandardHypoTestInvDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set mGenerateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      toymcs->SetGenerateBinned(mGenerateBinned);
  
      toymcs->SetUseMultiGen(mOptimize);
    
      if (mGenerateBinned &&  sbModel->GetObservables()->getSize() > 2) { 
         Warning("StandardHypoTestInvDemo","generate binned is activated but the number of ovservable is %d. Too much memory could be needed for allocating all the bins",sbModel->GetObservables()->getSize() );
      }

      // set the random seed if needed
      if (mRandomSeed >= 0) RooRandom::randomGenerator()->SetSeed(mRandomSeed); 
    
   }
  
   // specify if need to re-use same toys
   if (reuseAltToys) {
      hc->UseSameAltToys();
   }
  
   if (type == 1) { 
      HybridCalculator *hhc = dynamic_cast<HybridCalculator*> (hc);
      assert(hhc);
    
      hhc->SetToys(ntoys,ntoys/mNToysRatio); // can use less ntoys for b hypothesis 
    
      // remove global observables from ModelConfig (this is probably not needed anymore in 5.32)
      bModel->SetGlobalObservables(RooArgSet() );
      sbModel->SetGlobalObservables(RooArgSet() );
    
    
      // check for nuisance prior pdf in case of nuisance parameters 
      if (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() ) {

         // fix for using multigen (does not work in this case)
         toymcs->SetUseMultiGen(false);
         ToyMCSampler::SetAlwaysUseMultiGen(false);

         RooAbsPdf * nuisPdf = 0; 
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  { 
            Info("StandardHypoTestInvDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the model");
            if (bModel->GetPdf() && bModel->GetObservables() ) 
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else 
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }   
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  { 
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestInvDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());            
            }
            else { 
               Error("StandardHypoTestInvDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return 0;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestInvDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();
      
         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) { 
            Warning("StandardHypoTestInvDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;
      
         hhc->ForcePriorNuisanceAlt(*nuisPdf);
         hhc->ForcePriorNuisanceNull(*nuisPdf);
      
      
      }
   } 
   else if (type == 2 || type == 3) { 
      if (testStatType == 3) ((AsymptoticCalculator*) hc)->SetOneSided(true);  
      if (testStatType != 2 && testStatType != 3)  
         Warning("StandardHypoTestInvDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");
   }
   else if (type == 0 || type == 1) 
      ((FrequentistCalculator*) hc)->SetToys(ntoys,ntoys/mNToysRatio); 

  
   // Get the result
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
  
  
  
   HypoTestInverter calc(*hc);
   calc.SetConfidenceLevel(0.95);
  
  
   calc.UseCLs(useCLs);
   calc.SetVerbose(true);
  
   // can speed up using proof-lite
   if (mUseProof && mNWorkers > 1) { 
      ProofConfig pc(*w, mNWorkers, "", kFALSE);
      toymcs->SetProofConfig(&pc);    // enable proof
   }
  
  
   if (npoints > 0) {
      if (poimin > poimax) { 
         // if no min/max given scan between MLE and +4 sigma 
         poimin = int(poihat);
         poimax = int(poihat +  4 * poi->getError());
      }
      std::cout << "Doing a fixed scan  in interval : " << poimin << " , " << poimax << std::endl;
      calc.SetFixedScan(npoints,poimin,poimax);
   }
   else { 
      //poi->setMax(10*int( (poihat+ 10 *poi->getError() )/10 ) );
      std::cout << "Doing an  automatic scan  in interval : " << poi->getMin() << " , " << poi->getMax() << std::endl;
   }
  
   tw.Start();
   HypoTestInverterResult * r = calc.GetInterval();
   std::cout << "Time to perform limit scan \n";
   tw.Print();
  
   if (mRebuild) {
      calc.SetCloseProof(1);
      tw.Start();
      SamplingDistribution * limDist = calc.GetUpperLimitDistribution(true,mNToyToRebuild);
      std::cout << "Time to rebuild distributions " << std::endl;
      tw.Print();
    
      if (limDist) { 
         std::cout << "expected up limit " << limDist->InverseCDF(0.5) << " +/- " 
                   << limDist->InverseCDF(0.16) << "  " 
                   << limDist->InverseCDF(0.84) << "\n"; 
      
         //update r to a new updated result object containing the rebuilt expected p-values distributions
         // (it will not recompute the expected limit)
         if (r) delete r;  // need to delete previous object since GetInterval will return a cloned copy
         r = calc.GetInterval();
      
      }
      else 
         std::cout << "ERROR : failed to re-build distributions " << std::endl; 
   }
  
   return r;
}
Exemple #26
0
void fit_MC_norm(std::string input_file = "/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/reduced_Lb2JpsipK_MC_2011_2012_norm.root", std::string out_file_mass = "~/cern/plots/fitting/Lb2JpsipK_MC_2011_2012_cut_mass_fit.png"){
                                                                                    //
    gROOT->ProcessLine(".L ~/cern/scripts/lhcbStyle.C");
    //lhcbStyle();

    const std::string filename(input_file.c_str());
    const std::string treename = "DecayTree";

    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;


    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi pK^{-})", 5450., 5850., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    //RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3350., 3750., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5620., 5595., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 100., 1., 1000.);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.8, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 0.7, 0.2, 10.0);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);

    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); 
    /*
    // the chi_c2 component
    RooRealVar mean3("mean3","mean3", 5570., 5520., 5580.);
    RooRealVar sigma3("sigma3","sigma3", 10., 1., 20.);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    */
    RooRealVar cbRatio("cbRatio","cbRatio", 0.8, 0.1, 1.0);
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
  

    /*
    alpha1.setVal( 2.1  );
    alpha2.setVal( -4.9 );
    n1.setVal( 3.2 );
    n2.setVal( 7.9 );
    cbRatio.setVal( 0.6808 );
    alpha1.setConstant( true );
    alpha2.setConstant( true );
    cbRatio.setConstant( true );
    n1.setConstant( true );
    n2.setConstant( true );
    */

    // -- add signal & bg
    //RooAddPdf pdf("pdf", "pdf", RooArgList(gauss1, gauss2), RooArgList( frac2 ));  
    RooAddPdf pdf("pdf", "pdf", RooArgList(cb1, cb2), RooArgList( cbRatio ));  

    
    RooArgSet obs;
    obs.add(Lambda_b0_DTF_MASS_constr1);
    obs.add(Jpsi_M);
    //obs.add(chi_c_M);
    //obs.add(bkgcat_chic);
    RooDataSet ds("ds","ds", obs, RooFit::Import(*tree)); 
 //RooFit::Cut("Lambda_b0_DTF_MASS_constr1 > 5580")
    RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();

    plot->SetAxisRange(5500., 5750.);


    pdf.fitTo( ds );

    ds.plotOn( plot, RooFit::Binning(200) );
    pdf.plotOn( plot );
    //gauss3.plotOn( plot );



    RooPlot* plotPullMass = Lambda_b0_DTF_MASS_constr1.frame();

    plotPullMass->addPlotable( plot->pullHist() );
    //plotPullMass->SetMinimum();
    //plotPullMass->SetMaximum();
    plotPullMass->SetAxisRange(5500., 5750.);
    TCanvas* c = new TCanvas();
    c->cd();

    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0);
    pad1->SetBottomMargin(0.1);
    pad1->SetTopMargin(0.1);
    pad1->Draw();
    
    //TPad* pad2 = new TPad("pad2","pad2", 0, 0.05, 1, 0.4);
    TPad* pad2 = new TPad("pad2","pad2", 0, 0, 1, 0.3);
    pad2->SetBottomMargin(0.1);
    pad2->SetTopMargin(0.0);
    pad2->Draw();

    pdf.plotOn( plot, RooFit::Components( cb1 ), RooFit::LineColor( kRed ), RooFit::LineStyle(kDashed) );
    pdf.plotOn( plot, RooFit::Components( cb2 ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDotted) );
    //pdf.plotOn( plot, RooFit::Components( bgPdf ), RooFit::LineColor( kBlue ), RooFit::LineStyle(kDashDotted) );

    pad1->cd();
    //pad1->SetLogy();
    plot->Draw();

    pad2->cd();
    plotPullMass->Draw("AP");

    c->SaveAs(out_file_mass.c_str());


}
void Raa3S_Workspace(const char* name_pbpb="chad_ws_fits/centFits/ws_PbPbData_262548_263757_0cent10_0.0pt50.0_0.0y2.4.root", const char* name_pp="chad_ws_fits/centFits/ws_PPData_262157_262328_-1cent1_0.0pt50.0_0.0y2.4.root", const char* name_out="fitresult_combo.root"){

   //TFile File(filename);

   //RooWorkspace * ws = test_combine(name_pbpb, name_pp);

   TFile *f = new TFile("fitresult_combo_333.root") ;
   RooWorkspace * ws1 = (RooWorkspace*) f->Get("wcombo");

   //File.GetObject("wcombo", ws);
   ws1->Print();
   RooAbsData * data = ws1->data("data"); //dataOS, dataSS

   // RooDataSet * US_data = (RooDataSet*) data->reduce( "QQsign == QQsign::PlusMinus");
   // US_data->SetName("US_data");
   // ws->import(* US_data);
   // RooDataSet * hi_data = (RooDataSet*) US_data->reduce("dataCat == dataCat::hi");
   // hi_data->SetName("hi_data");
   // ws->import(* hi_data);
   // hi_data->Print();

   RooRealVar* raa3 = new RooRealVar("raa3","R_{AA}(#Upsilon (3S))",0.5,-1,1);
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",0);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",1);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*raa3, *leftEdge, *rightEdge));
   ws1->import(step);
   ws1->factory( "Uniform::flat(raa3)" );

   //pp Luminosities, Taa and efficiency ratios Systematics

   ws1->factory( "Taa_hi[5.662e-9]" );
   ws1->factory( "Taa_kappa[1.062]" ); // was 1.057
   ws1->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" );
   ws1->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" );
   ws1->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" );

   ws1->factory( "lumipp_hi[5.4]" );
   ws1->factory( "lumipp_kappa[1.037]" ); // was 1.06
   ws1->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" );
   ws1->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" );
   ws1->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" );

   // ws->factory( "effRat1[1]" );
   // ws->factory( "effRat2[1]" );
   ws1->factory( "effRat3_hi[0.95]" );
   ws1->factory( "effRat_kappa[1.054]" );
   ws1->factory( "expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])" );
   // ws->factory( "prod::effRat1_nom(effRat1_hi,alpha_effRat)" );
   ws1->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" );
   // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" );
   ws1->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" );
   //  
   ws1->factory("Nmb_hi[1.161e9]");
   ws1->factory("prod::denominator(Taa_nom,Nmb_hi)");
   ws1->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)");
   RooAbsReal *lumiOverTaaNmbmodified = ws1->function("lumiOverTaaNmbmodified"); //RooFormulaVar *lumiOverTaaNmbmodified = ws->function("lumiOverTaaNmbmodified");
   //  
   //  RooRealVar *raa1 = ws->var("raa1");
   //  RooRealVar* nsig1_pp = ws->var("nsig1_pp");
   //  RooRealVar* effRat1 = ws->function("effRat1_nom");
   //  RooRealVar *raa2 = ws->var("raa2");
   //  RooRealVar* nsig2_pp = ws->var("nsig2_pp");
   //  RooRealVar* effRat2 = ws->function("effRat2_nom");
   RooRealVar* nsig3_pp = ws1->var("R_{#frac{3S}{1S}}_pp"); //RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   cout << nsig3_pp << endl;
   RooAbsReal* effRat3 = ws1->function("effRat3_nom"); //RooRealVar* effRat3 = ws->function("effRat3_nom");
   //  
   //  RooFormulaVar nsig1_hi_modified("nsig1_hi_modified", "@0*@1*@3/@2", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1));
   //  ws->import(nsig1_hi_modified);
   //  RooFormulaVar nsig2_hi_modified("nsig2_hi_modified", "@0*@1*@3/@2", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2));
   //  ws->import(nsig2_hi_modified);
   RooFormulaVar nsig3_hi_modified("nsig3_hi_modified", "@0*@1*@3/@2", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3));
   ws1->import(nsig3_hi_modified);

   //  // background yield with systematics
   ws1->factory( "nbkg_hi_kappa[1.10]" );
   ws1->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" );
   ws1->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" );
   ws1->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" );
   RooAbsPdf* sig1S_hi = ws1->pdf("sig1S_hi"); //RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi");
   RooAbsPdf* sig2S_hi = ws1->pdf("sig2S_hi");
   RooAbsPdf* sig3S_hi = ws1->pdf("sig3S_hi");
   RooAbsPdf* LSBackground_hi = ws1->pdf("nbkg_hi_nom");
   RooRealVar* nsig1_hi = ws1->var("N_{#Upsilon(1S)}_hi");
   RooRealVar* nsig2_hi = ws1->var("R_{#frac{2S}{1S}}_hi");
   RooAbsReal* nsig3_hi = ws1->function("nsig3_hi_modified"); //RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified");
   cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl;
   RooRealVar* norm_nbkg_hi = ws1->var("n_{Bkgd}_hi");

   RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi);
   RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi);

   ////////////////////////////////////////////////////////////////////////////////

   ws1->factory( "nbkg_pp_kappa[1.03]" );
   ws1->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" );
   ws1->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" );
   ws1->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" );
   RooAbsPdf* sig1S_pp = ws1->pdf("sig1S_pp"); //RooAbsPdf* sig1S_pp = ws1->pdf("cbcb_pp");
   RooAbsPdf* sig2S_pp = ws1->pdf("sig2S_pp");
   RooAbsPdf* sig3S_pp = ws1->pdf("sig3S_pp");
   RooAbsPdf* LSBackground_pp = ws1->pdf("nbkg_pp_nom");
   RooRealVar* nsig1_pp = ws1->var("N_{#Upsilon(1S)}_pp");
   RooRealVar* nsig2_pp = ws1->var("R_{#frac{2S}{1S}}_pp"); //RooRealVar* nsig2_pp = ws1->var("N_{#Upsilon(2S)}_pp");
   // RooRealVar* nsig3_pp = ws1->var("N_{#Upsilon(3S)}_pp");
   RooRealVar* norm_nbkg_pp = ws1->var("n_{Bkgd}_pp");

   RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp);
   RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp);

   RooAddPdf model_num("model_num", "model_num", pdfs_hi,norms_hi); 
   ws1->import(model_num);
   ws1->factory("PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)");

   RooAddPdf model_den("model_den", "model_den", pdfs_pp,norms_pp); 
   ws1->import(model_den);
   ws1->factory("PROD::model_pp(model_den, constr_nbkg_pp)");

   ws1->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)");



   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws1->var("invariantMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws1->cat("dataCat"));    
   //  /////////////////////////////////////////////////////////////////////
   ws1->var("glob_lumipp")->setConstant(true);
   ws1->var("glob_Taa")->setConstant(true);
   ws1->var("glob_effRat")->setConstant(true);
   ws1->var("glob_nbkg_pp")->setConstant(true);
   ws1->var("glob_nbkg_hi")->setConstant(true);
   RooArgSet globalObs("global_obs");
   globalObs.add( *ws1->var("glob_lumipp") );
   globalObs.add( *ws1->var("glob_Taa") );
   globalObs.add( *ws1->var("glob_effRat") );
   globalObs.add( *ws1->var("glob_nbkg_hi") );
   globalObs.add( *ws1->var("glob_nbkg_pp") );
   cout << "66666" << endl;

   // ws1->Print();

   RooArgSet poi("poi");
   poi.add( *ws1->var("raa3") );



   cout << "77777" << endl;
   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   nuis.add( *ws1->var("beta_lumipp") );
   nuis.add( *ws1->var("beta_nbkg_hi") );
   nuis.add( *ws1->var("beta_nbkg_pp") );
   nuis.add( *ws1->var("beta_Taa") );
   nuis.add( *ws1->var("beta_effRat") );

   cout << "88888" << endl;
   ws1->var("#alpha_{CB}_hi")->setConstant(true);
   ws1->var("#alpha_{CB}_pp")->setConstant(true);
   ws1->var("#sigma_{CB1}_hi")->setConstant(true);
   ws1->var("#sigma_{CB1}_pp")->setConstant(true);
   ws1->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true);
   ws1->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true);
   //ws1->var("Centrality")->setConstant(true); //delete
   ws1->var("N_{#varUpsilon(1S)}_hi")->setConstant(true);
   ws1->var("N_{#varUpsilon(1S)}_pp")->setConstant(true);
   //ws1->var("N_{#Upsilon(2S)}_hi")->setConstant(true);
   //ws1->var("N_{#Upsilon(2S)}_pp")->setConstant(true);
   //ws1->var("N_{#Upsilon(3S)}_pp")->setConstant(true);

   ws1->var("R_{#frac{2S}{1S}}_hi")->setConstant(true); //new
   ws1->var("R_{#frac{2S}{1S}}_pp")->setConstant(true); //new
   ws1->var("R_{#frac{3S}{1S}}_hi")->setConstant(true); //new
   ws1->var("R_{#frac{3S}{1S}}_pp")->setConstant(true); //new

   ws1->var("Nmb_hi")->setConstant(true);
   // ws1->var("QQsign")->setConstant(true);
   ws1->var("Taa_hi")->setConstant(true);
   ws1->var("Taa_kappa")->setConstant(true);
   // ws1->var("beta_Taa")->setConstant(true);
   // ws1->var("beta_effRat")->setConstant(true);
   // ws1->var("beta_lumipp")->setConstant(true);
   // ws1->var("beta_nbkg_hi")->setConstant(true);
   // ws1->var("beta_nbkg_pp")->setConstant(true);
   // ws1->var("dataCat")->setConstant(true);
   ws1->var("decay_hi")->setConstant(true);
   ws1->var("decay_pp")->setConstant(true);
   ws1->var("effRat3_hi")->setConstant(true);
   ws1->var("effRat_kappa")->setConstant(true);
   // ws1->var("glob_Taa")->setConstant(true);
   // ws1->var("glob_effRat")->setConstant(true);
   // ws1->var("glob_lumipp")->setConstant(true);
   // ws1->var("glob_nbkg_hi")->setConstant(true);
   // ws1->var("glob_nbkg_pp")->setConstant(true);
   // ws1->var("invariantMass")->setConstant(true);
   ws1->var("leftEdge")->setConstant(true);
   ws1->var("lumipp_hi")->setConstant(true);
   ws1->var("lumipp_kappa")->setConstant(true);
   ws1->var("m_{ #varUpsilon(1S)}_hi")->setConstant(true); //ws1->var("mass1S_hi")->setConstant(true);
   ws1->var("m_{ #varUpsilon(1S)}_pp")->setConstant(true); //ws1->var("mass1S_pp")->setConstant(true);
   ws1->var("muMinusPt")->setConstant(true);
   ws1->var("muPlusPt")->setConstant(true);
   ws1->var("n_{Bkgd}_hi")->setConstant(true);
   ws1->var("n_{Bkgd}_pp")->setConstant(true);
   ws1->var("nbkg_hi_kappa")->setConstant(true);
   ws1->var("nbkg_pp_kappa")->setConstant(true);
   //ws1->var("n_{CB}")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   ws1->var("n_{CB}_hi")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   ws1->var("n_{CB}_pp")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   // ws1->var("raa3")->setConstant(true);
   ws1->var("rightEdge")->setConstant(true);
   ws1->var("sigmaFraction_hi")->setConstant(true);
   ws1->var("sigmaFraction_pp")->setConstant(true);
   ws1->var("turnOn_hi")->setConstant(true);
   ws1->var("turnOn_pp")->setConstant(true);
   ws1->var("dimuPt")->setConstant(true); //ws1->var("upsPt")->setConstant(true);
   ws1->var("dimuRapidity")->setConstant(true); //ws1->var("upsRapidity")->setConstant(true);
   ws1->var("vProb")->setConstant(true);
   ws1->var("width_hi")->setConstant(true);
   ws1->var("width_pp")->setConstant(true);
   // ws1->var("x3raw")->setConstant(true);
   //  RooArgSet fixed_again("fixed_again");
   //  fixed_again.add( *ws1->var("leftEdge") );
   //  fixed_again.add( *ws1->var("rightEdge") );
   //  fixed_again.add( *ws1->var("Taa_hi") );
   //  fixed_again.add( *ws1->var("Nmb_hi") );
   //  fixed_again.add( *ws1->var("lumipp_hi") );
   //  fixed_again.add( *ws1->var("effRat1_hi") );
   //  fixed_again.add( *ws1->var("effRat2_hi") );
   //  fixed_again.add( *ws1->var("effRat3_hi") );
   //  fixed_again.add( *ws1->var("nsig3_pp") );
   //  fixed_again.add( *ws1->var("nsig1_pp") );
   //  fixed_again.add( *ws1->var("nbkg_hi") );
   //  fixed_again.add( *ws1->var("alpha") );
   //  fixed_again.add( *ws1->var("nbkg_kappa") );
   //  fixed_again.add( *ws1->var("Taa_kappa") );
   //  fixed_again.add( *ws1->var("lumipp_kappa") );
   // fixed_again.add( *ws1->var("mean_hi") );
   // fixed_again.add( *ws1->var("mean_pp") );
   // fixed_again.add( *ws1->var("width_hi") );
   // fixed_again.add( *ws1->var("turnOn_hi") );
   // fixed_again.add( *ws1->var("bkg_a1_pp") );
   // fixed_again.add( *ws1->var("bkg_a2_pp") );
   // fixed_again.add( *ws1->var("decay_hi") );
   // fixed_again.add( *ws1->var("raa1") );
   // fixed_again.add( *ws1->var("raa2") );
   //  fixed_again.add( *ws1->var("nsig2_pp") );
   // fixed_again.add( *ws1->var("sigma1") );
   //  fixed_again.add( *ws1->var("nbkg_pp") );
   // fixed_again.add( *ws1->var("npow") );
   // fixed_again.add( *ws1->var("muPlusPt") );
   // fixed_again.add( *ws1->var("muMinusPt") );
   // fixed_again.add( *ws1->var("mscale_hi") );
   // fixed_again.add( *ws1->var("mscale_pp") );
   //  
   // ws1->Print();
   cout << "99999" << endl;

   // create signal+background Model Config
   RooStats::ModelConfig sbHypo("SbHypo");
   sbHypo.SetWorkspace( *ws1 );
   sbHypo.SetPdf( *ws1->pdf("joint") );
   sbHypo.SetObservables( obs );
   sbHypo.SetGlobalObservables( globalObs );
   sbHypo.SetParametersOfInterest( poi );
   sbHypo.SetNuisanceParameters( nuis );
   sbHypo.SetPriorPdf( *ws1->pdf("step") ); // this is optional

   // ws1->Print();
   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(10) );
   cout << "111111" << endl;
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   cout << "444444" << endl;
   RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3"));
   cout << "222222" << endl;
   pNll->plotOn(framepoi,ShiftToZero());
   cout << "333333" << endl;
   
   RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
   pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
   pProfile->plotOn(framepoi,LineColor(kRed));
   framepoi->SetMinimum(0);
   framepoi->SetMaximum(3);
   TCanvas *cpoi = new TCanvas();
   cpoi->cd(); framepoi->Draw();
   cpoi->SaveAs("cpoi.pdf");

   ((RooRealVar *)poi.first())->setMin(0.);
   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
   // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeSB = pObs->frame(Title("SBhypo"));
   data->plotOn(xframeSB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfSB = sbHypo.GetPdf();
   RooCategory *dataCat = ws1->cat("dataCat");
   pdfSB->plotOn(xframeSB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c1 = new TCanvas();
   c1->cd(); xframeSB->Draw();
   c1->SaveAs("c1.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;
   ws1->import( sbHypo );
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws1);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   ((RooRealVar *)poi.first())->setVal( 0 );  // set raa3=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeB = pObs->frame(Title("Bhypo"));
   data->plotOn(xframeB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfB = bHypo.GetPdf();
   pdfB->plotOn(xframeB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c2 = new TCanvas();
   c2->cd(); xframeB->Draw();
   c2->SaveAs("c2.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;

   // import model config into workspace
   bHypo.SetWorkspace(*ws1);
   ws1->import( bHypo );
   /////////////////////////////////////////////////////////////////////
   ws1->Print();
   bHypo.Print();
   sbHypo.Print();

   // save workspace to file
   ws1 -> SaveAs(name_out);

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


  double confidenceLevel=0.95;
  // degrade/improve number of pseudo-experiments used to define the confidence belt.  
  // value of 1 corresponds to default number of toys in the tail, which is 50/(1-confidenceLevel)
  double additionalToysFac = 1.;  
  int nPointsToScan = 30; // number of steps in the parameter of interest 
  int nToyMC = 100; // number of toys used to define the expected limit and band

  TStopwatch t;
  t.Start();
  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  const char* filename = "";
  if (!strcmp(infile,""))
    filename = "results/example_combined_GaussExample_model.root";
  else
    filename = infile;
  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified byt not found, quit
  if(!file && strcmp(infile,"")){
    cout <<"file not found" << endl;
    return;
  } 

  // if default file not found, try to create it
  if(!file ){
    // Normally this would be run on the command line
    cout <<"will run standard hist2workspace example"<<endl;
    gROOT->ProcessLine(".! prepareHistFactory .");
    gROOT->ProcessLine(".! hist2workspace config/example.xml");
    cout <<"\n\n---------------------"<<endl;
    cout <<"Done creating example input"<<endl;
    cout <<"---------------------\n\n"<<endl;
  }

  // now try to access the file again
  file = TFile::Open(filename);
  if(!file){
    // if it is still not there, then we can't continue
    cout << "Not able to run hist2workspace to create example input" <<endl;
    return;
  }

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

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

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

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

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

  cout << "Found data and ModelConfig:" <<endl;
  mc->Print();

  /////////////////////////////////////////////////////////////
  // Now get the POI for convenience
  // you may want to adjust the range of your POI
  ////////////////////////////////////////////////////////////
  RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  //  firstPOI->setMin(0);
  //  firstPOI->setMax(10);

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

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


  // test speedups:
  testStat->SetReuseNLL(true);
  //  toymcsampler->setUseMultiGen(true); // not fully validated

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

  // We can use PROOF to speed things along in parallel
  ProofConfig pc(*w, 4, "",false); 
  if(mc->GetGlobalObservables()){
    cout << "will use global observables for unconditional ensemble"<<endl;
    mc->GetGlobalObservables()->Print();
    toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
  }
  toymcsampler->SetProofConfig(&pc);	// enable proof


  // Now get the interval
  PointSetInterval* interval = fc.GetInterval();
  ConfidenceBelt* belt = fc.GetConfidenceBelt();
 
  // print out the iterval on the first Parameter of Interest
  cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
    interval->LowerLimit(*firstPOI) << ", "<<
    interval->UpperLimit(*firstPOI) <<"] "<<endl;

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


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

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

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

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

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


  double CLb=0;
  double CLbinclusive=0;

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

    // set parameters back to values for generating pseudo data
    w->loadSnapshot("paramsToGenerateData");

    // in 5.30 there is a nicer way to generate toy data  & randomize global obs
    RooAbsData* toyData = toymcsampler->GenerateToyData(*paramsToGenerateData);

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


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

      if(thisTS<=arMax){
	thisUL = firstPOI->getVal();
      } else{
	break;
      }
    }
    

    histOfUL->Fill(thisUL);

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

  // if you want to see a plot of the sampling distribution for a particular scan point:

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

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

  cout << "-2 sigma  band " << band2sigDown << endl;
  cout << "-1 sigma  band " << band1sigDown  << endl;
  cout << "median of band " << bandMedian << " [Power Constriant)]" << endl;
  cout << "+1 sigma  band " << band1sigUp << endl;
  cout << "+2 sigma  band " << band2sigUp << endl;

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

  delete profile;
  delete nll;

}
Exemple #29
0
double ro_fit4( TH1F * h2, int p4,int p3,int p2,int p1 ){


 TCanvas *chi=(TCanvas*)gROOT->GetListOfCanvases()->FindObject("c_hist");
  if (chi!=NULL){
    chi->cd();
  }

  int npeaks=4;
  if (npeaks>NMAX){ printf("TOO MANY PEAKS\n",""); return 1;}

  TH1F *h2;
  double pk[NMAX];
  double si[NMAX];
  double ar[NMAX];
  double al[NMAX];
  double n1;

  double min=h2->GetXaxis()->GetFirst(),
    max=h2->GetXaxis()->GetLast(),
    smin=(max-min)/1000,
    smax=(max-min),
    amin=h2->Integral( min, max )/1000.,
    amax=h2->Integral( min, max ),
    almin=0.,
    almax=100.,
    nmin=1.0,
    nmax=100.;


  pk[0]=p4;
  pk[1]=p3;
  pk[2]=p2;
  pk[3]=p1;



  for (int i=0;i<npeaks;i++){
    //    pk[i]=1.0*(i+1)/(1+npeaks)*(max-min) +min;
    si[i]=4.3.;
    ar[i]=1.0*(amax+amin)/npeaks/2; //area
    al[i]=1.3;
  }
  n1=5.1;

  smin=0.5* si[0];
  smax=2.*si[0];

  int tag=1;
  int i;
  printf("%d peaks : ",  npeaks);
  for (i=0;i<npeaks;i++){
    printf( "%8.2f ",pk[i] );
  }
  printf("\n#########   TAG %7d\n",  tag++);



  //================ MAIN variable 1D ==============
  RooRealVar       x("x",    "x",   min, max);
  /*
   *
   *  CHEBYSHEV  HERE
   */
  char sbg="p1";
 // Build Chebychev polynomial p.d.f.  
 // RooRealVar a0("a0","a0", 0.) ;
  RooRealVar a0("a0","a0",    0., -10, 10) ;
  RooRealVar a1("a1","a1",    0., -10, 10) ;
  RooRealVar a2("a2","a2",    0., -10, 10) ;
  RooRealVar a3("a3","a3",    0., -10, 10) ;
  RooArgSet setcheb;
  if ( sbg=="pn" ){ setcheb.add(a0);a0=0.;a0.setConstant(kTRUE);bgarea=0.;bgarea.setConstant(kTRUE);}
  if ( sbg=="p0" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE); }
  if ( sbg=="p1" ){ setcheb.add(a0); }
  if ( sbg=="p2" ){ setcheb.add(a1);setcheb.add(a0); }
  if ( sbg=="p3" ){ setcheb.add(a2);setcheb.add(a1); setcheb.add(a0);}
  if ( sbg=="p4" ){ setcheb.add(a3);setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  RooChebychev bkg("bkg","Background",x, setcheb ) ;


  RooRealVar mean1("mean1", "mean_", pk[0], min,max);
  RooRealVar mean2("mean2", "mean_", pk[1], min,max);
  RooRealVar mean3("mean3", "mean_", pk[2], min,max);
  RooRealVar mean4("mean4", "mean_", pk[3], min,max);
  RooRealVar mean5("mean5", "mean_", pk[4], min,max);
  RooRealVar mean6("mean6", "mean_", pk[5], min,max);
  RooRealVar mean7("mean7", "mean_", pk[6], min,max);
  RooRealVar mean8("mean8", "mean_", pk[7], min,max);
  RooRealVar mean9("mean9", "mean_", pk[8], min,max);
  RooRealVar meana("meana", "mean_", pk[9], min,max);
  RooRealVar meanb("meanb", "mean_", pk[10], min,max);
  RooRealVar meanc("meanc", "mean_", pk[11], min,max);
  RooRealVar meand("meand", "mean_", pk[12], min,max);
  RooRealVar meane("meane", "mean_", pk[13], min,max);
  RooRealVar meanf("meanf", "mean_", pk[14], min,max);

  RooRealVar sigm1("sigm1", "sigma", si[0], smin, smax);
  RooRealVar sigm2("sigm2", "sigma", si[1], smin, smax);
  RooRealVar sigm3("sigm3", "sigma", si[2], smin, smax);
  RooRealVar sigm4("sigm4", "sigma", si[3], smin, smax);
  RooRealVar sigm5("sigm5", "sigma", si[4], smin, smax);
  RooRealVar sigm6("sigm6", "sigma", si[5], smin, smax);
  RooRealVar sigm7("sigm7", "sigma", si[6], smin, smax);
  RooRealVar sigm8("sigm8", "sigma", si[7], smin, smax);
  RooRealVar sigm9("sigm9", "sigma", si[8], smin, smax);
  RooRealVar sigma("sigma", "sigma", si[9], smin, smax);
  RooRealVar sigmb("sigmb", "sigma", si[10], smin, smax);
  RooRealVar sigmc("sigmc", "sigma", si[11], smin, smax);
  RooRealVar sigmd("sigmd", "sigma", si[12], smin, smax);
  RooRealVar sigme("sigme", "sigma", si[13], smin, smax);
  RooRealVar sigmf("sigmf", "sigma", si[14], smin, smax);

  RooRealVar    fs2("fs2","fs2", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs3("fs3","fs3", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs4("fs4","fs4", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs5("fs5","fs5", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs6("fs6","fs6", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs7("fs7","fs7", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs8("fs8","fs8", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fs9("fs9","fs9", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fsa("fsa","fsa", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fsb("fsb","fsb", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fsc("fsc","fsc", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fsd("fsd","fsd", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fse("fse","fse", 0.0 ); // factor sigma = 1==free or 0==fix
  RooRealVar    fsf("fsf","fsf", 0.0 ); // factor sigma = 1==free or 0==fix

  RooFormulaVar fsigm2( "fsigm2", " fs2*sigm2 + (1.0-fs2)*sigm1" , RooArgSet(sigm1,sigm2,fs2) );
  RooFormulaVar fsigm3( "fsigm3", " fs3*sigm3 + (1.0-fs3)*sigm1" , RooArgSet(sigm1,sigm3,fs3) );
  RooFormulaVar fsigm4( "fsigm4", " fs4*sigm4 + (1.0-fs4)*sigm1" , RooArgSet(sigm1,sigm4,fs4) );
  RooFormulaVar fsigm5( "fsigm5", " fs5*sigm5 + (1.0-fs5)*sigm1" , RooArgSet(sigm1,sigm5,fs5) );
  RooFormulaVar fsigm6( "fsigm6", " fs6*sigm6 + (1.0-fs6)*sigm1" , RooArgSet(sigm1,sigm6,fs6) );
  RooFormulaVar fsigm7( "fsigm7", " fs7*sigm7 + (1.0-fs7)*sigm1" , RooArgSet(sigm1,sigm7,fs7) );
  RooFormulaVar fsigm8( "fsigm8", " fs8*sigm8 + (1.0-fs8)*sigm1" , RooArgSet(sigm1,sigm8,fs8) );
  RooFormulaVar fsigm9( "fsigm9", " fs9*sigm9 + (1.0-fs9)*sigm1" , RooArgSet(sigm1,sigm9,fs9) );
  RooFormulaVar fsigma( "fsigma", " fsa*sigma + (1.0-fsa)*sigm1" , RooArgSet(sigm1,sigma,fsa) );
  RooFormulaVar fsigmb( "fsigmb", " fsb*sigmb + (1.0-fsb)*sigm1" , RooArgSet(sigm1,sigmb,fsb) );
  RooFormulaVar fsigmc( "fsigmc", " fsc*sigmc + (1.0-fsc)*sigm1" , RooArgSet(sigm1,sigmc,fsc) );
  RooFormulaVar fsigmd( "fsigmd", " fsd*sigmd + (1.0-fsd)*sigm1" , RooArgSet(sigm1,sigmd,fsd) );
  RooFormulaVar fsigme( "fsigme", " fse*sigme + (1.0-fse)*sigm1" , RooArgSet(sigm1,sigme,fse) );
  RooFormulaVar fsigmf( "fsigmf", " fsf*sigmf + (1.0-fsf)*sigm1" , RooArgSet(sigm1,sigmf,fsf) );


  // -------- fsx   0== FIX to sigm1;    1==free sigma
  fs2.setVal( 0.0 );  
  fs3.setVal( 0.0 );  
  fs4.setVal( 0.0 );  
  fs5.setVal( 1.0 );  
  fs6.setVal( 1.0 );  
  fs7.setVal( 1.0 );  
  fs8.setVal( 1.0 );  
  fs9.setVal( 1.0 );  
  fsa.setVal( 1.0 );  
  fsb.setVal( 1.0 );  
  fsc.setVal( 1.0 );  
  fsd.setVal( 1.0 );  
  fse.setVal( 1.0 );  
  fsf.setVal( 1.0 );  
  
  fs2.setConstant( kTRUE );  
  fs3.setConstant( kTRUE );  
  fs4.setConstant( kTRUE );  
  fs5.setConstant( kTRUE );  
  fs6.setConstant( kTRUE );  
  fs7.setConstant( kTRUE );  
  fs8.setConstant( kTRUE );  
  fs9.setConstant( kTRUE );  
  fsa.setConstant( kTRUE );  
  fsb.setConstant( kTRUE );  
  fsc.setConstant( kTRUE );  
  fsd.setConstant( kTRUE );  
  fse.setConstant( kTRUE );  
  fsf.setConstant( kTRUE );  

  if (fs2.getVal()==0.0){sigm2.setConstant( kTRUE );}
  if (fs3.getVal()==0.0){sigm3.setConstant( kTRUE );}
  if (fs4.getVal()==0.0){sigm4.setConstant( kTRUE );}
  if (fs5.getVal()==0.0){sigm5.setConstant( kTRUE );}
  if (fs6.getVal()==0.0){sigm6.setConstant( kTRUE );}
  if (fs7.getVal()==0.0){sigm7.setConstant( kTRUE );}
  if (fs8.getVal()==0.0){sigm8.setConstant( kTRUE );}
  if (fs9.getVal()==0.0){sigm9.setConstant( kTRUE );}
  if (fsa.getVal()==0.0){sigma.setConstant( kTRUE );}
  if (fsb.getVal()==0.0){sigmb.setConstant( kTRUE );}
  if (fsc.getVal()==0.0){sigmc.setConstant( kTRUE );}
  if (fsd.getVal()==0.0){sigmd.setConstant( kTRUE );}
  if (fse.getVal()==0.0){sigme.setConstant( kTRUE );}
  if (fsf.getVal()==0.0){sigmf.setConstant( kTRUE );}


  // extra thing that goes to RootSet
  RooRealVar area1("area1", "area_", ar[0], amin, amax);
  RooRealVar area2("area2", "area_", ar[1], amin, amax);
  RooRealVar area3("area3", "area_", ar[2], amin, amax);
  RooRealVar area4("area4", "area_", ar[3], amin, amax);
  RooRealVar area5("area5", "area_", ar[4], amin, amax);
  RooRealVar area6("area6", "area_", ar[5], amin, amax);
  RooRealVar area7("area7", "area_", ar[6], amin, amax);
  RooRealVar area8("area8", "area_", ar[7], amin, amax);
  RooRealVar area9("area9", "area_", ar[8], amin, amax);
  RooRealVar areaa("areaa", "area_", ar[9], amin, amax);
  RooRealVar areab("areab", "area_", ar[10], amin, amax);
  RooRealVar areac("areac", "area_", ar[11], amin, amax);
  RooRealVar aread("aread", "area_", ar[12], amin, amax);
  RooRealVar areae("areae", "area_", ar[13], amin, amax);
  RooRealVar areaf("areaf", "area_", ar[14], amin, amax);


  RooRealVar   bgarea("bgarea", "bgarea",  1.0*(amin+amax)/2., 0, amax);  

  //=================== only one instance ===================
  RooRealVar alph1("alph1", "alph1",  al[0], almin, almax );
  RooRealVar ncbs1("n1", "n1",  n1, nmin, nmax );

  RooCBShape cb1("cb1","CBS", x,mean1, sigm1,alph1,ncbs1);
  RooCBShape cb2("cb2","CBS", x,mean2,fsigm2,alph1,ncbs1);
  RooCBShape cb3("cb3","CBS", x,mean3,fsigm3,alph1,ncbs1);
  RooCBShape cb4("cb4","CBS", x,mean4,fsigm4,alph1,ncbs1);
  RooCBShape cb5("cb5","CBS", x,mean5,fsigm5,alph1,ncbs1);
  RooCBShape cb6("cb6","CBS", x,mean6,fsigm6,alph1,ncbs1);
  RooCBShape cb7("cb7","CBS", x,mean7,fsigm7,alph1,ncbs1);
  RooCBShape cb8("cb8","CBS", x,mean8,fsigm8,alph1,ncbs1);
  RooCBShape cb9("cb9","CBS", x,mean9,fsigm9,alph1,ncbs1);
  RooCBShape cba("cba","CBS", x,meana,fsigma,alph1,ncbs1);
  RooCBShape cbb("cbb","CBS", x,meanb,fsigmb,alph1,ncbs1);
  RooCBShape cbc("cbc","CBS", x,meanc,fsigmc,alph1,ncbs1);
  RooCBShape cbd("cbd","CBS", x,meand,fsigmd,alph1,ncbs1);
  RooCBShape cbe("cbe","CBS", x,meane,fsigme,alph1,ncbs1);
  RooCBShape cbf("cbf","CBS", x,meanf,fsigmf,alph1,ncbs1);

  RooExtendPdf ecb1("ecb1","ECBS", cb1, area1 );
  RooExtendPdf ecb2("ecb2","ECBS", cb2, area2 );
  RooExtendPdf ecb3("ecb3","ECBS", cb3, area3 );
  RooExtendPdf ecb4("ecb4","ECBS", cb4, area4 );
  RooExtendPdf ecb5("ecb5","ECBS", cb5, area5 );
  RooExtendPdf ecb6("ecb6","ECBS", cb6, area6 );
  RooExtendPdf ecb7("ecb7","ECBS", cb7, area7 );
  RooExtendPdf ecb8("ecb8","ECBS", cb8, area8 );
  RooExtendPdf ecb9("ecb9","ECBS", cb9, area9 );
  RooExtendPdf ecba("ecba","ECBS", cba, areaa );
  RooExtendPdf ecbb("ecbb","ECBS", cbb, areab );
  RooExtendPdf ecbc("ecbc","ECBS", cbc, areac );
  RooExtendPdf ecbd("ecbd","ECBS", cbd, aread );
  RooExtendPdf ecbe("ecbe","ECBS", cbe, areae );
  RooExtendPdf ecbf("ecbf","ECBS", cbf, areaf );

 RooArgList erl;  
 if (npeaks>0)erl.add( ecb1 );  
 if (npeaks>1)erl.add( ecb2 );  
 if (npeaks>2)erl.add( ecb3 );  
 if (npeaks>3)erl.add( ecb4 );  
 if (npeaks>4)erl.add( ecb5 );  
 if (npeaks>5)erl.add( ecb6 );  
 if (npeaks>6)erl.add( ecb7 );  
 if (npeaks>7)erl.add( ecb8 );  
 if (npeaks>8)erl.add( ecb9 );  
 if (npeaks>9)erl.add( ecba );  
 if (npeaks>10)erl.add( ecbb );  
 if (npeaks>11)erl.add( ecbc );  
 if (npeaks>12)erl.add( ecbd );  
 if (npeaks>13)erl.add( ecbe );  
 if (npeaks>14)erl.add( ecbf );  

  RooExtendPdf ebkg("ebkg","EBkg", bkg, bgarea );
  erl.add( ebkg ); 



 RooAddPdf emodelV("emodel","emultiplet", erl  );
 emodelV.Print("v");



 RooDataHist datah("datah","datah with x",x,h2);
 RooPlot* xframe = x.frame();
 datah.plotOn(xframe,  DrawOption("logy") );

 // RooPlot* xframe = x.frame();
 /*
 bkg.plotOn( xframe, LineColor(kBlue)  );
 cb1.plotOn( xframe, LineColor(kRed)  );
 */
 // xframe->Draw();

 /*
  *  Here I believe to put the parameters for fit????
  *
  */
 /*
 
 RooArgList rl;  
 if (npeaks>0)rl.add( cb1 );  
 if (npeaks>1)rl.add( cb2 );  
 if (npeaks>2)rl.add( cb3 );  
 if (npeaks>3)rl.add( cb4 );  
 if (npeaks>4)rl.add( cb5 );  
 if (npeaks>5)rl.add( cb6 );  
 if (npeaks>6)rl.add( cb7 );  
 if (npeaks>7)rl.add( cb8 );  
 if (npeaks>8)rl.add( cb9 );  
 if (npeaks>9)rl.add( cba );  
 if (npeaks>10)rl.add( cbb );  
 if (npeaks>11)rl.add( cbc );  
 if (npeaks>12)rl.add( cbd );  
 if (npeaks>13)rl.add( cbe );  
 if (npeaks>14)rl.add( cbf );  

 
 rl.add( bkg ); 

 // asi zastoupeni jednotlivych piku viz vyse------------
 // RooArgSet rs;
 RooArgList rs;
 if (npeaks>0)rs.add( area1 );  
 if (npeaks>1)rs.add( area2 );  
 if (npeaks>2)rs.add( area3 );  
 if (npeaks>3)rs.add( area4 );  
 if (npeaks>4)rs.add( area5 );  
 if (npeaks>5)rs.add( area6 );  
 if (npeaks>6)rs.add( area7 );  
 if (npeaks>7)rs.add( area8 );  
 if (npeaks>8)rs.add( area9 );  
 if (npeaks>9)rs.add( areaa );  
 if (npeaks>10)rs.add( areab );  
 if (npeaks>11)rs.add( areac );  
 if (npeaks>12)rs.add( aread );  
 if (npeaks>13)rs.add( areae );  
 if (npeaks>14)rs.add( areaf );  
 
 rs.add( bgarea );
 //if # coefficients(rs)+1=functions(rl) => coef.are interpreted as fractions


 RooAddPdf modelV("model","multiplet", rl, rs );
 modelV.Print("v");
 */

 /*
  *  WITH CUSTOMIZER - I can change parameters inside. But
  *             - then all is a clone and I dont know how to reach it.->Iterations...difficlt
I try  something with RooFormulaVar     
  */
 

 fitresult = emodelV.fitTo( datah , Save()  );  
 fitresult->Print("v") ;
 fitresult->floatParsFinal().Print("s") ;
 
  //    model->Print();  // not interesting........
 emodelV.plotOn(xframe, LineColor(kRed),   DrawOption("l0z") );

 emodelV.plotOn(xframe, Components(ecb1),LineColor(kGreen),LineStyle(kDashed) );


 emodelV.plotOn(xframe, Components(RooArgSet(ecb1,ebkg)),LineColor(kBlue),LineStyle(kDashed) );
 emodelV.plotOn(xframe, Components(RooArgSet(ecb2,ebkg)),LineColor(kBlue),LineStyle(kDashed) );
 emodelV.plotOn(xframe, Components(RooArgSet(ecb3,ebkg)),LineColor(kBlue),LineStyle(kDashed) );
 emodelV.plotOn(xframe, Components(RooArgSet(ecb4,ebkg)),LineColor(kBlue),LineStyle(kDashed) );

 emodelV.plotOn(xframe, Components( RooArgSet(ebkg) ), LineColor(kRed) );
 

 xframe->Draw();
 printf("FWHM  = =  %f chan\n",   sigm1.getVal()*2.3548 );
 printf("FWHM  = =  %f keV\n",   sigm1.getVal()*2.3548 *5804.0/p1 );
 return sigm1.getVal()*2.3548 *5804.0/p1 ;
 


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



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

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

   }
   else
      filename = infile;

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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


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

   double CLb=0;
   double CLbinclusive=0;

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

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

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

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

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

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

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

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

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

            // Cleanup
            delete globtmp ;
            delete tmp ;
         }
      }

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

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


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

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



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

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

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

      histOfUL->Fill(thisUL);

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

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

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

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

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

   delete profile;
   delete nll;

}