Пример #1
0
void PEs(RooAbsPdf *iGen,RooAbsPdf *iFit,int iN,int iNEvents,RooRealVar &iVar,RooRealVar &iSig,RooRealVar &iMean,
	 RooRealVar &iScale,RooRealVar &iRes) { 
  double iM0 = iMean.getVal(); double iS0 = iSig.getVal();
  //iScale.setVal(iMeanScale); iRes.setVal(iSigScale);
  TRandom1 *lRand = new TRandom1(0xDEADBEEF);
  TNtuple * lDN= new TNtuple( "xxx","xxx","ntot:m_r:m:merr:sig_r:sig:sigerr");
  for(int i0=0;i0<iN;i0++){
    if(i0 % 10 == 0) cout << "+++++++++++++++++++++++++++ running ======> " << i0 << endl;
    int lN    = lRand->Poisson(iNEvents);
    RooDataSet * lSignal  = iGen->generate(iVar,lN);
    iMean.setVal(iM0); iSig.setVal(iS0);
    iFit->fitTo(*lSignal,Strategy(1));//,Save(kTRUE),PrintLevel(1));
    if(iMean.getError() < 0.05) iFit->fitTo(*lSignal,Strategy(2));
    Float_t values[]={
      (Float_t) lN,
      (Float_t) 90.78/iScale.getVal(),
      (Float_t) iMean.getVal(),
      (Float_t) iMean.getError(),
      (Float_t) iSig.getVal(),
      (Float_t) iSig.getVal(),
      (Float_t) iSig.getError()
    };
    lDN->Fill(values);
  }
  TFile *lF = new TFile("XXX.root","RECREATE");
  lDN->Write();
  lF->Close();
}
Пример #2
0
TGraph *graphLH(std::string nuisname, double err ){

	w->loadSnapshot("bestfitall"); // SetTo BestFit values as start

	// Get The parameter we want 
	RooRealVar *nuis =(RooRealVar*) w->var(nuisname.c_str());
	double bf = nuis->getVal();
	double nll_0=nll->getVal();


	TGraph *gr = new TGraph(2*npoints+1);
	for (int i=-1*npoints;i<=npoints;i++){
		nuis->setVal(bf+err*( ((float)i)*nsigma/npoints));
		double nll_v = nll->getVal();
		gr->SetPoint(i+npoints,nuis->getVal(),nll_v-nll_0);
	}

	gr->SetTitle("");
	gr->GetYaxis()->SetTitle("NLL - obs data");
	gr->GetYaxis()->SetTitleOffset(1.1);
	gr->GetXaxis()->SetTitleSize(0.05);
	gr->GetYaxis()->SetTitleSize(0.05);
	gr->GetXaxis()->SetTitle(nuisname.c_str());
	gr->SetLineColor(4);
	gr->SetLineWidth(2);
	gr->SetMarkerStyle(21);
	gr->SetMarkerSize(0.6);
	
	return gr;
	
}
pair<double,double> bkgEvPerGeV(RooWorkspace *work, int m_hyp, int cat, int spin=false){
  
  RooRealVar *mass = (RooRealVar*)work->var("CMS_hgg_mass");
  if (spin) mass = (RooRealVar*)work->var("mass");
  mass->setRange(100,180);
  RooAbsPdf *pdf = (RooAbsPdf*)work->pdf(Form("pdf_data_pol_model_8TeV_cat%d",cat));
  RooAbsData *data = (RooDataSet*)work->data(Form("data_mass_cat%d",cat));
  RooPlot *tempFrame = mass->frame();
  data->plotOn(tempFrame,Binning(80));
  pdf->plotOn(tempFrame);
  RooCurve *curve = (RooCurve*)tempFrame->getObject(tempFrame->numItems()-1);
  double nombkg = curve->Eval(double(m_hyp));
 
  RooRealVar *nlim = new RooRealVar(Form("nlim%d",cat),"",0.,0.,1.e5);
  //double lowedge = tempFrame->GetXaxis()->GetBinLowEdge(FindBin(double(m_hyp)));
  //double upedge  = tempFrame->GetXaxis()->GetBinUpEdge(FindBin(double(m_hyp)));
  //double center  = tempFrame->GetXaxis()->GetBinUpCenter(FindBin(double(m_hyp)));

  nlim->setVal(nombkg);
  mass->setRange("errRange",m_hyp-0.5,m_hyp+0.5);
  RooAbsPdf *epdf = 0;
  epdf = new RooExtendPdf("epdf","",*pdf,*nlim,"errRange");
		
  RooAbsReal *nll = epdf->createNLL(*data,Extended(),NumCPU(4));
  RooMinimizer minim(*nll);
  minim.setStrategy(0);
  minim.setPrintLevel(-1);
  minim.migrad();
  minim.minos(*nlim);
  
  double error = (nlim->getErrorLo(),nlim->getErrorHi())/2.;
  data->Print(); 
  return pair<double,double>(nombkg,error); 
}
Пример #4
0
RooStats::ModelConfig * Tprime::SetBModel( void ) {
    //
    // Define model config and parameter snapshot to describe the b model.
    // Import to workspace.
    //

    std::string legend = "[Tprime::SetBModel]: ";

    // full signal+background model
    //RooStats::ModelConfig * pSBModel = (RooStats::ModelConfig *)pWs->genobj("ModelConfig");

    // let's make the b model (bg-only) from the alt model (s+b) with xsec=0
    //RooStats::ModelConfig * pBModel =
    //  new RooStats::ModelConfig(*(RooStats::ModelConfig *)pWs->genobj("ModelConfig"));
    RooStats::ModelConfig * _sbModel = (RooStats::ModelConfig *)pWs->genobj("ModelConfig");
    RooStats::ModelConfig * pBModel = _sbModel->Clone("BModel");

    //pBModel->SetName("BModel");

    pBModel->SetWorkspace(*pWs);

    //pBModel->SetParametersOfInterest(RooArgSet());
    pWs->import(*pBModel);

    // set POI to the b model value and take snapshot
    RooRealVar * pPoi = (RooRealVar *)pBModel->GetParametersOfInterest()->first();
    pPoi->setVal(0.0);
    pBModel->SetSnapshot(*pPoi);

    pBModel->Print();

    return pBModel;
}
Пример #5
0
void testResolution() { 
  Prep();
  RooRealVar    lXVar  ("XVar","mass(GeV/c^{2})",100,60,150); lXVar.setBins(1000);
  RooRealVar l1Sigma("sigma1","sigma1",1.6 ,0.,15.);  //l1Sigma.setConstant(kTRUE);
  RooRealVar l2Sigma("sigma2","sigma2",1.6,0.,15.);   l2Sigma.setConstant(kTRUE);
  RooRealVar l3Sigma("sigma3","sigma3",2.90,0.,35.);  l3Sigma.setConstant(kTRUE);
  RooRealVar lN     ("n"     ,"n"     ,1.00,-15,15.); lN.setConstant(kTRUE);
  RooRealVar lExp   ("exp"   ,"exp"   ,-0.003,-15,15.); //lExp.setConstant(kTRUE);
  RooRealVar lR0Mean("xmean","xmean",0,-10,10);    lR0Mean.setConstant(kTRUE);
  RooRealVar lR1Mean("mean","mean",90.8,60,150);   //lR1Mean.setConstant(kTRUE);
  RooVoigtianShape     lGAdd("Add","Add",lXVar,lR1Mean,l1Sigma,l2Sigma,lN,l3Sigma,true);
  
  RooRealVar    lSPar  ("SPar","SPar", 1.,0., 2.);
  RooFormulaVar lXShift("uparshift","@0*@1",RooArgList(lXVar,lSPar));
  TH1F *lMass = getMass(0,-5,5,-1.5,1.5);
  RooDataHist *lMHist = new RooDataHist("M" ,"M" ,RooArgSet(lXVar),lMass);
  RooHistPdf  *lMPdf  = new RooHistPdf ("MH","MH",lXShift,lXVar,*lMHist,5); 
  RooRealVar lGSigma("gsigma","gsigma",1.6 ,0.,15.);  
  RooGaussian   lGaus1("gaus1","gaus1",lXVar,lR0Mean,lGSigma);
  RooFFTConvPdf  lConv("Conv","Conv",lXVar,*lMPdf,lGaus1);

  RooDataSet *lData = new RooDataSet("crap","crap",RooArgSet(lXVar)); 
  fillData(lData,lXVar,0,-5,5,-1.5,1.5);
  lConv.fitTo(*lData,Strategy(2));
  lGSigma.setVal(lGSigma.getVal());
  lSPar.setVal(lSPar.getVal()*1.01);
  //cout << "=====> Check " << l1Sigma.getVal() << " --- " << lR1Mean.getVal() << "----" << lSPar.getVal() << endl;
  PEs(&lConv,&lGAdd,2000,500,lXVar,l1Sigma,lR1Mean,lSPar,lGSigma);
  lData = 0;
  Plot(&lConv,&lGAdd,2000,50000,lXVar,l1Sigma,lR1Mean,lSPar,lGSigma,lData);
}
Пример #6
0
//
// set value and range for a variable in the workspace
//
void setValRange (RooWorkspace* workspace, const char* name, double val, double vmin, double vmax)
{
  RooRealVar* var = workspace->var(name);
  if ( var ) {
    if ( vmax>vmin )  var->setRange(vmin,vmax);
    var->setVal(val);
  }
}
Пример #7
0
void UL_significance_Hybrid(Model* model,int n_toys,int random_seed=0,double sig=1){
  cout<<"///////////////////////////////////////////////////////////////////////////////////////////"<<endl;
  cout<<"Calculating significance with the Hybrid method"<<endl;
  cout<<"///////////////////////////////////////////////////////////////////////////////////////////"<<endl;
  
  //set the random seed
  RooRandom::randomGenerator()->SetSeed(random_seed);
    
   //get the calculator
  HybridCalculatorOriginal myhc(*model->get_data(),*model->get_sb_likelihood(),*model->get_b_likelihood());
  
  //for numbercounting experiments
  myhc.PatchSetExtended(false);
  
  //set likelihood ratio as the test statistics
  myhc.SetTestStatistic(1);
  
  //define the systematics to be used
  if (model->get_nuisance_set()) {
    myhc.UseNuisance(true);
    myhc.SetNuisancePdf(*model->get_nuisance_prior_pdf());
    myhc.SetNuisanceParameters(*model->get_nuisance_set());
  } else {
    myhc.UseNuisance(false);                            
  }
  
  //define the number of toys to be done
  myhc.SetNumberOfToys(n_toys);

  //RooArgSet* poi= model->get_POI_set();
  //  poi->first()->Set(sig);
  RooRealVar* firstPOI = (RooRealVar*) model->get_POI_set()->first();
  firstPOI->setVal(sig);

  //get the Hypotestresult
  HybridResult* hcResult = myhc.GetHypoTest();
  double significance = hcResult->Significance();
  double CLS= hcResult->CLs();
  double CLB= hcResult->CLb();
  double CLsplusb= hcResult->CLsplusb();
  double CLSerror= hcResult->CLsError(); 
  



  cout<<"POI: "<<sig<<endl;
  cout <<"significance:" << significance<<endl;
  cout<<"CLs: "<<CLS<<endl;
  cout<<"CLb: "<<CLB<<endl;
  cout<<"CLsplusb: "<<CLsplusb<<endl;
  cout<<"CLserror: "<<CLSerror<<endl;

  HybridPlot* plot=hcResult->GetPlot("hcPlot","p Values Plot",100);
  TCanvas *c1=new TCanvas;
  plot->Draw();
  c1->SaveAs("hybrid_REsult");
  
}
Пример #8
0
//____________________________________
void MakePlots(RooWorkspace* wks) {

  // Make plots of the data and the best fit model in two cases:
  // first the signal+background case
  // second the background-only case.

  // get some things out of workspace
  RooAbsPdf* model = wks->pdf("model");
  RooAbsPdf* sigModel = wks->pdf("sigModel");
  RooAbsPdf* zjjModel = wks->pdf("zjjModel");
  RooAbsPdf* qcdModel = wks->pdf("qcdModel");

  RooRealVar* mu = wks->var("mu");
  RooRealVar* invMass = wks->var("invMass");
  RooAbsData* data = wks->data("data");


  //////////////////////////////////////////////////////////
  // Make plots for the Alternate hypothesis, eg. let mu float

  mu->setConstant(kFALSE);

  model->fitTo(*data,Save(kTRUE),Minos(kFALSE), Hesse(kFALSE),PrintLevel(-1));

  //plot sig candidates, full model, and individual componenets
  new TCanvas();
  RooPlot* frame = invMass->frame() ;
  data->plotOn(frame ) ;
  model->plotOn(frame) ;
  model->plotOn(frame,Components(*sigModel),LineStyle(kDashed), LineColor(kRed)) ;
  model->plotOn(frame,Components(*zjjModel),LineStyle(kDashed),LineColor(kBlack)) ;
  model->plotOn(frame,Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;

  frame->SetTitle("An example fit to the signal + background model");
  frame->Draw() ;
  //  cdata->SaveAs("alternateFit.gif");

  //////////////////////////////////////////////////////////
  // Do Fit to the Null hypothesis.  Eg. fix mu=0

  mu->setVal(0); // set signal fraction to 0
  mu->setConstant(kTRUE); // set constant

  model->fitTo(*data, Save(kTRUE), Minos(kFALSE), Hesse(kFALSE),PrintLevel(-1));

  // plot signal candidates with background model and components
  new TCanvas();
  RooPlot* xframe2 = invMass->frame() ;
  data->plotOn(xframe2, DataError(RooAbsData::SumW2)) ;
  model->plotOn(xframe2) ;
  model->plotOn(xframe2, Components(*zjjModel),LineStyle(kDashed),LineColor(kBlack)) ;
  model->plotOn(xframe2, Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;

  xframe2->SetTitle("An example fit to the background-only model");
  xframe2->Draw() ;
  //  cbkgonly->SaveAs("nullFit.gif");

}
Пример #9
0
///
/// Set all observables to 'truth' values computed from the
/// current parameters.
///
void PDF_Abs::setObservablesTruth()
{
	obsValSource = "truth";
	for ( int i=0; i<nObs; i++ )
	{
		RooRealVar* pObs = (RooRealVar*)((RooArgList*)observables)->at(i);
		pObs->setVal(((RooRealVar*)((RooArgList*)theory)->at(i))->getVal());
	}
}
double effRmsFromSigmaCB(double meanCB, double meanCB_err, double sigmaCB, double sigmaCB_err) {

  RooRealVar mass("zmass","m(e^{+}e^{-})",75,105,"GeV/c^{2}");

  float zwidth=2.4952;
  RooRealVar bwMean("m_{Z}","BW Mean", 91.1876, "GeV/c^{2}");
  RooRealVar bwWidth("#Gamma_{Z}", "BW Width", zwidth, "GeV/c^{2}");

  RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", 0.00, -10, 10, "GeV/c^{2}"); // typical value
  RooRealVar cbSigma("#sigma_{CB}", "CB Width", 1.5, 0.8, 5.0, "GeV/c^{2}");
  RooRealVar cbCut  ("a_{CB}","CB Cut", 1.0, 1.0, 3.0); // typical value
  RooRealVar cbPower("n_{CB}","CB Order", 2.5, 0.1, 20.0); // typical value

  float mean_lo = meanCB - meanCB_err;
  float mean_hi = meanCB + meanCB_err;
  float sigma_lo = sigmaCB - sigmaCB_err;
  float sigma_hi = sigmaCB + sigmaCB_err;

  int nstep_mean = 10;
  int nstep_sigma = 10;
  
  float step_mean = 2*meanCB_err/float(nstep_mean);
  float step_sigma = 2*sigmaCB_err/float(nstep_sigma);

  double max_rms = 0.0;
  double min_rms = 999.;
  
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING);

  int nsteps=0;
  for(float mean=mean_lo; mean<mean_hi; mean+=step_mean) {
    for(float sigma=sigma_lo; sigma<sigma_hi; sigma+=step_sigma) {

      cbBias.setVal(meanCB);
      cbSigma.setVal(sigma);

      RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth);
      RooCBShape  cball("cball", "Crystal Ball", mass, cbBias, cbSigma, cbCut, cbPower);
      RooFFTConvPdf BWxCB("BWxCB", "bw X crystal ball", mass, bw, cball);
      
      RooDataSet *gendata = BWxCB.generate(mass,1000);
      TH1D *genh = (TH1D*) gendata->createHistogram("genh",mass,RooFit::Binning(100,75,105));
      
      math::HistogramTools ht(genh);
      double rms = ht.effectiveSigma();
      rms = sqrt(pow(rms,2)-pow(zwidth,2));
      if(rms > max_rms) max_rms=rms;
      if(rms < min_rms) min_rms=rms;
      delete genh;
      nsteps++;
    }
  }
  return (max_rms-min_rms)/sqrt(12)/sqrt(nsteps);
}
Пример #11
0
void FitterUtils::initiateParams(int nGenSignalZeroGamma, int nGenSignalOneGamma, int nGenSignalTwoGamma, RooRealVar const& expoConstGen, RooRealVar& nSignal, RooRealVar& nPartReco, 
      RooRealVar& nComb, RooRealVar& fracZero, RooRealVar& fracOne, RooRealVar& expoConst, RooRealVar&  nJpsiLeak, bool constPartReco, RooRealVar const& fracPartRecoSigma)
{
   TRandom rand;
   rand.SetSeed();

   int nGenSignal = nGenSignalZeroGamma + nGenSignalOneGamma + nGenSignalTwoGamma;

   double nGenSignal2;
   double nGenPartReco2;
   if(!constPartReco)
   {
      nGenSignal2 = rand.Uniform(nGenSignal-5*sqrt(nGenSignal), nGenSignal+5*sqrt(nGenSignal));
      nGenPartReco2 = rand.Uniform(nGenPartReco-5*sqrt(nGenPartReco), nGenPartReco+5*sqrt(nGenPartReco));
   }
   if(constPartReco)
   { 
      double nGenSigPartReco( nGenSignal+nGenPartReco );
      double nGenSigPartReco2( rand.Uniform( nGenSigPartReco-5*sqrt(nGenSigPartReco), nGenSigPartReco+5*sqrt(nGenSigPartReco) ) );
      double fracPartReco1( nGenPartReco/(1.*nGenSignal));
      double fracPartReco2( rand.Uniform(fracPartReco1-5*fracPartRecoSigma.getVal(), fracPartReco1+5*fracPartRecoSigma.getVal()) ); 

      nGenPartReco2 = fracPartReco2*nGenSigPartReco2 / (1+fracPartReco2); 
      nGenSignal2 = nGenSigPartReco2 / (1+fracPartReco2); 
   }
   double nGenComb2 = rand.Uniform(nGenComb-5*sqrt(nGenComb), nGenComb+5*sqrt(nGenComb));
   double nGenJpsiLeak2 = rand.Uniform(nGenJpsiLeak-5*sqrt(nGenJpsiLeak), nGenJpsiLeak+5*sqrt(nGenJpsiLeak));


   nSignal.setVal(nGenSignal2);
   nSignal.setRange(TMath::Max(0.,nGenSignal2-10.*sqrt(nGenSignal)) , nGenSignal2+10*sqrt(nGenSignal));

   nPartReco.setVal(nGenPartReco2);
   nPartReco.setRange(TMath::Max(0.,nGenPartReco2-10.*sqrt(nGenPartReco)), nGenPartReco2+10*sqrt(nGenPartReco));


   nComb.setVal(nGenComb2);
   nComb.setRange(TMath::Max(0.,nGenComb2-10.*sqrt(nGenComb)), nGenComb2+10*sqrt(nGenComb));

   nJpsiLeak.setVal(nGenJpsiLeak2);
   nJpsiLeak.setRange(TMath::Max(0., nGenJpsiLeak2-10*sqrt(nGenJpsiLeak)), nGenJpsiLeak2+10*sqrt(nGenJpsiLeak));

   double fracGenZero(nGenSignalZeroGamma/(1.*nGenSignal));
   double fracGenOne(nGenSignalOneGamma/(1.*nGenSignal));

   fracZero.setVal(rand.Gaus(fracGenZero, sqrt(nGenSignalZeroGamma)/(1.*nGenSignal))) ;
   fracZero.setRange(0., 1.);
   fracOne.setVal(rand.Gaus(fracGenOne, sqrt(nGenSignalOneGamma)/(1.*nGenSignal))) ;
   fracOne.setRange(0., 1.);

   expoConst.setVal(rand.Uniform( expoConstGen.getVal() - 5*expoConstGen.getError(), expoConstGen.getVal() + 5*expoConstGen.getError() ) );
   expoConst.setRange( expoConstGen.getVal() - 10*expoConstGen.getError(), expoConstGen.getVal() + 10*expoConstGen.getError() );
}
Пример #12
0
void fillData(RooDataSet *iData,RooRealVar &lXVar,int iCharge,float iPhiMin,float iPhiMax,float iEtaMin,float iEtaMax) { 
  TFile *lFile = new TFile("ZTP.root");
  TTree *lTree = (TTree*) lFile->FindObjectAny("WNtupleIdEffNT");
  int   lCharge = 0; lTree->SetBranchAddress("charge",&lCharge);
  float lEta    = 0; lTree->SetBranchAddress("eta"   ,&lEta);
  float lPhi    = 0; lTree->SetBranchAddress("phi"   ,&lPhi);
  float lMt     = 0; lTree->SetBranchAddress("mt"    ,&lMt);
  float lPt     = 0; lTree->SetBranchAddress("pt"    ,&lPt);
  float lOPt    = 0; lTree->SetBranchAddress("jetpt" ,&lOPt);
  float lOEta   = 0; lTree->SetBranchAddress("jeteta",&lOEta);
  float lOPhi   = 0; lTree->SetBranchAddress("jetphi",&lOPhi);
  for(int i0 = 0; i0 < lTree->GetEntries();i0++) { 
    lTree->GetEntry(i0);
    if(lMt < 60)                   continue;
    if(lCharge > 0 && iCharge < 0) continue;
    if(lCharge < 0 && iCharge > 0) continue;
    if(lPhi < iPhiMin || lPhi > iPhiMax) continue;
    if(lEta < iEtaMin || lEta > iEtaMax) continue;
    lXVar.setVal(fabs(lMt));
    if(lCharge > 0) lXVar.setVal(correct(lMt,lPhi,lOPhi,lEta,lOEta));
    if(lCharge < 0) lXVar.setVal(correct(lMt,lOPhi,lPhi,lOEta,lEta));
    iData->add(RooArgSet(lXVar));
  }
}
Пример #13
0
///
/// Set each parameter in workspace to the values found
/// in the fit result
///
void Utils::setParameters(RooWorkspace* w, RooFitResult* values){
	RooArgList list = values->floatParsFinal();
	list.add(values->constPars());
	TIterator* it = list.createIterator();
	while(RooRealVar* p = (RooRealVar*)it->Next()){
		RooRealVar* var = dynamic_cast<RooRealVar*>(w->allVars().find(p->GetName()));
		if(!(var)){
			std::cout <<  "WARNING in Utils::setParameters(RooWorkspace,RooFitResult) -- no Var found with name "
				<< p->GetName() << " in Workspace!" << endl;
		}
		else{
			var->setVal(p->getVal());
		}
	}
	return;
};
Пример #14
0
///
/// Set all observables to 'toy' values drawn from the
/// PDF using the current parameter values. A certain number
/// of toys is pregenerated to speed up when doing mulitple toy fits.
///
void PDF_Abs::setObservablesToy()
{
	obsValSource = "toy";
	if( !pdf ){ cout<< "PDF_Abs::setObservables(): ERROR: pdf not initialized."<<endl; exit(1); }
	if ( toyObservables==0 || iToyObs==nToyObs )
	{
		RooRandom::randomGenerator()->SetSeed(0);
		if ( iToyObs==nToyObs ) delete toyObservables;
		toyObservables = pdf->generate(*(RooArgSet*)observables, nToyObs);
		iToyObs=0;
	}
	for ( int i=0; i<nObs; i++ )
	{
		RooRealVar* pObs = (RooRealVar*)((RooArgList*)observables)->at(i);
		pObs->setVal(((RooRealVar*)toyObservables->get(iToyObs)->find(pObs->GetName()))->getVal());
	}
	iToyObs+=1;
}
Пример #15
0
double getChisq(RooAbsData &dat, RooAbsPdf &pdf, RooRealVar &var, bool prt=false) {

    // Find total number of events
    double nEvt;
    double nTot=0.0;

    for(int j=0; j<dat.numEntries(); j++) {
        dat.get(j);
        nEvt=dat.weight();
        nTot+=nEvt;
    }

    // Find chi-squared equivalent 2NLL
    //RooRealVar *var=(RooRealVar*)(pdf.getParameters(*dat)->find("CMS_hgg_mass"));
    double totNLL=0.0;
    double prbSum=0.0;

    for(int j=0; j<dat.numEntries(); j++) {
        double m=dat.get(j)->getRealValue(var.GetName());
        if ( m < var.getMin() || m > var.getMax())  continue;
        // Find probability density and hence probability
        var.setVal(m);
        double prb = var.getBinWidth(0)*pdf.getVal(var);
        prbSum+=prb;

        dat.get(j);
        nEvt=dat.weight();

        double mubin=nTot*prb;
        double contrib(0.);
        if (nEvt < 1) contrib = mubin;
        else contrib=mubin-nEvt+nEvt*log(nEvt/mubin);
        totNLL+=contrib;

        if(prt) cout << "Bin " << j << " prob = " << prb << " nEvt = " << nEvt << ", mu = " << mubin << " contribution " << contrib << endl;
    }

    totNLL*=2.0;
    if(prt) cout << pdf.GetName() << " nTot = " << nTot << " 2NLL constant = " << totNLL << endl;

    return totNLL;
}
Пример #16
0
RooDataSet *th22dataset(TH2F *hist){
  RooRealVar *v1 = new RooRealVar("constTerm","",0.01,0,0.02);
  RooRealVar *v2 = new RooRealVar("alpha","",0.0,0,0.2);
  RooRealVar *nll = new RooRealVar("nll",0,0,1e20);
  RooArgSet argSet(*v1,*v2, *nll);
  RooDataSet *dataset = new RooDataSet(TString(hist->GetName())+"_dataset", "", argSet,"nll");
  
  for(Int_t iBinX=1; iBinX <= hist->GetNbinsX(); iBinX++){
    for(Int_t iBinY=1; iBinY <= hist->GetNbinsY(); iBinY++){
      Double_t binContent=hist->GetBinContent(iBinX, iBinY);
      if(binContent!=0){
	v1->setVal(hist->GetXaxis()->GetBinCenter(iBinX));
	v2->setVal(hist->GetYaxis()->GetBinCenter(iBinY));
	nll->setVal(binContent);
	dataset->add(argSet);
      }
    }
  }
  return dataset;
}
Пример #17
0
///
/// Fit a pdf to the minimum, but keep angular parameters in a range of
/// [0,2pi]. If after an initial fit, a parameter has walked outside this
/// interval, add multiples of 2pi to bring it back. Then, refit.
/// All variables that have unit 'rad' are taken to be angles.
///
RooFitResult* Utils::fitToMinBringBackAngles(RooAbsPdf *pdf, bool thorough, int printLevel)
{
	countAllFitBringBackAngle++;
	RooFitResult* r = fitToMin(pdf, thorough, printLevel);
	bool refit = false;
	TIterator* it = r->floatParsFinal().createIterator();
	while ( RooRealVar* p = (RooRealVar*)it->Next() ){
		if ( ! isAngle(p) ) continue;
		if ( p->getVal()<0.0 || p->getVal()>2.*TMath::Pi() ){
			RooArgSet *pdfPars = pdf->getParameters(RooArgSet());
			RooRealVar *pdfPar = (RooRealVar*)pdfPars->find(p->GetName());
			pdfPar->setVal(bringBackAngle(p->getVal()));
			refit = true;
			delete pdfPars;
		}
	}
	if ( refit ){
		countFitBringBackAngle++;
		delete r;
		r = fitToMin(pdf, thorough, printLevel);
	}
	delete it;
	return r;
}
void FitterUtilsSimultaneousExpOfPolyTimesX::initiateParams(int nGenSignalZeroGamma, int nGenSignalOneGamma, int nGenSignalTwoGamma,
      RooRealVar& nKemu, RooRealVar& nSignal, RooRealVar& nPartReco,
      RooRealVar& nComb, RooRealVar& fracZero, RooRealVar& fracOne,
      RooRealVar&  nJpsiLeak, bool constPartReco, RooRealVar const& fracPartRecoSigma,
      RooRealVar& l1Kee, RooRealVar& l2Kee, RooRealVar& l3Kee, RooRealVar& l4Kee, RooRealVar& l5Kee,
      RooRealVar& l1Kemu, RooRealVar& l2Kemu, RooRealVar& l3Kemu, RooRealVar& l4Kemu, RooRealVar& l5Kemu,
      RooRealVar const& l1KeeGen, RooRealVar const& l2KeeGen, RooRealVar const& l3KeeGen, RooRealVar const& l4KeeGen, RooRealVar const& l5KeeGen 

      )
{
  FitterUtilsExpOfPolyTimesX::initiateParams(nGenSignalZeroGamma, nGenSignalOneGamma, nGenSignalTwoGamma,
           nSignal, nPartReco, nComb, fracZero, fracOne, nJpsiLeak, constPartReco, fracPartRecoSigma,
           l1Kee, l2Kee, l3Kee, l4Kee, l5Kee,
           l1KeeGen, l2KeeGen, l3KeeGen, l4KeeGen, l5KeeGen ); 



  TRandom rand;
  rand.SetSeed();

  nKemu.setVal(rand.Uniform(nGenKemu-5*sqrt(nGenKemu), nGenKemu+5*sqrt(nGenKemu)));
  nKemu.setRange(nGenKemu-10*sqrt(nGenKemu), nGenKemu+10*sqrt(nGenKemu));

  l1Kemu.setVal(rand.Uniform( l1KeeGen.getVal() - 5*l1KeeGen.getError(), l1KeeGen.getVal() + 5*l1KeeGen.getError() ) );
  l1Kemu.setRange( l1KeeGen.getVal() - 10*l1KeeGen.getError(), l1KeeGen.getVal() + 10*l1KeeGen.getError() );

  l2Kemu.setVal(rand.Uniform( l2KeeGen.getVal() - 5*l2KeeGen.getError(), l2KeeGen.getVal() + 5*l2KeeGen.getError() ) );
  l2Kemu.setRange( l2KeeGen.getVal() - 10*l2KeeGen.getError(), l2KeeGen.getVal() + 10*l2KeeGen.getError() );

  l3Kemu.setVal(rand.Uniform( l3KeeGen.getVal() - 5*l3KeeGen.getError(), l3KeeGen.getVal() + 5*l3KeeGen.getError() ) );
  l3Kemu.setRange( l3KeeGen.getVal() - 10*l3KeeGen.getError(), l3KeeGen.getVal() + 10*l3KeeGen.getError() );

  l4Kemu.setVal(rand.Uniform( l4KeeGen.getVal() - 5*l4KeeGen.getError(), l4KeeGen.getVal() + 5*l4KeeGen.getError() ) );
  l4Kemu.setRange( l4KeeGen.getVal() - 10*l4KeeGen.getError(), l4KeeGen.getVal() + 10*l4KeeGen.getError() );

  l5Kemu.setVal(rand.Uniform( l5KeeGen.getVal() - 5*l5KeeGen.getError(), l5KeeGen.getVal() + 5*l5KeeGen.getError() ) );
  l5Kemu.setRange( l5KeeGen.getVal() - 10*l5KeeGen.getError(), l5KeeGen.getVal() + 10*l5KeeGen.getError() );

}
Пример #19
0
void draw_data_mgg(TString folderName,bool blind=true,float min=103,float max=160)
{
  TFile inputFile(folderName+"/data.root");
  
  const int nCat = 5;
  TString cats[5] = {"HighPt","Hbb","Zbb","HighRes","LowRes"};

  TCanvas cv;

  for(int iCat=0; iCat < nCat; iCat++) {

    RooWorkspace *ws  = (RooWorkspace*)inputFile.Get(cats[iCat]+"_mgg_workspace");
    RooFitResult* res = (RooFitResult*)ws->obj("fitresult_pdf_data");

    RooRealVar * mass = ws->var("mgg");
    mass->setRange("all",min,max);
    mass->setRange("blind",121,130);
    mass->setRange("low",106,121);
    mass->setRange("high",130,160);

    mass->setUnit("GeV");
    mass->SetTitle("m_{#gamma#gamma}");
    
    RooAbsPdf * pdf = ws->pdf("pdf");
    RooPlot *plot = mass->frame(min,max,max-min);
    plot->SetTitle("");
    
    RooAbsData* data = ws->data("data")->reduce(Form("mgg > %f && mgg < %f",min,max));
    double nTot = data->sumEntries();
    if(blind) data = data->reduce("mgg < 121 || mgg>130");
    double nBlind = data->sumEntries();
    double norm = nTot/nBlind; //normalization for the plot
    
    data->plotOn(plot);
    pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::Range("Full"),RooFit::LineWidth(0.1) );
    plot->Print();

    //add the fix error band
    RooCurve* c = plot->getCurve("pdf_Norm[mgg]_Range[Full]_NormRange[Full]");
    const int Nc = c->GetN();
    //TGraphErrors errfix(Nc);
    //TGraphErrors errfix2(Nc);
    TGraphAsymmErrors errfix(Nc);
    TGraphAsymmErrors errfix2(Nc);
    Double_t *x = c->GetX();
    Double_t *y = c->GetY();
    double NtotalFit = ws->var("Nbkg1")->getVal()*ws->var("Nbkg1")->getVal() + ws->var("Nbkg2")->getVal()*ws->var("Nbkg2")->getVal();
    for( int i = 0; i < Nc; i++ )
      {
	errfix.SetPoint(i,x[i],y[i]);
	errfix2.SetPoint(i,x[i],y[i]);
	mass->setVal(x[i]);      
	double shapeErr = pdf->getPropagatedError(*res)*NtotalFit;
	//double totalErr = TMath::Sqrt( shapeErr*shapeErr + y[i] );
	//total normalization error
	double totalErr = TMath::Sqrt( shapeErr*shapeErr + y[i]*y[i]/NtotalFit ); 
	if ( y[i] - totalErr > .0 )
	  {
	    errfix.SetPointError(i, 0, 0, totalErr, totalErr );
	  }
	else
	  {
	    errfix.SetPointError(i, 0, 0, y[i] - 0.01, totalErr );
	  }
	//2sigma
	if ( y[i] -  2.*totalErr > .0 )
	  {
	    errfix2.SetPointError(i, 0, 0, 2.*totalErr,  2.*totalErr );
	  }
	else
	  {
	    errfix2.SetPointError(i, 0, 0, y[i] - 0.01,  2.*totalErr );
	  }
	/*
	std::cout << x[i] << " " << y[i] << " "
		  << " ,pdf get Val: " << pdf->getVal()
		  << " ,pdf get Prop Err: " << pdf->getPropagatedError(*res)*NtotalFit
		  << " stat uncertainty: " << TMath::Sqrt(y[i]) << " Ntot: " << NtotalFit <<  std::endl;
	*/
      }
    errfix.SetFillColor(kYellow);
    errfix2.SetFillColor(kGreen);


    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kGreen),RooFit::Range("Full"), RooFit::VisualizeError(*res,2.0,kFALSE));
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kYellow),RooFit::Range("Full"), RooFit::VisualizeError(*res,1.0,kFALSE));
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kGreen),RooFit::Range("Full"), RooFit::VisualizeError(*res,2.0,kTRUE));
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kYellow),RooFit::Range("Full"), RooFit::VisualizeError(*res,1.0,kTRUE));
    plot->addObject(&errfix,"4");
    plot->addObject(&errfix2,"4");
    plot->addObject(&errfix,"4");
    data->plotOn(plot);
    TBox blindBox(121,plot->GetMinimum()-(plot->GetMaximum()-plot->GetMinimum())*0.015,130,plot->GetMaximum());
    blindBox.SetFillColor(kGray);
    if(blind) {
      plot->addObject(&blindBox);
      pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kGreen),RooFit::Range("Full"), RooFit::VisualizeError(*res,2.0,kTRUE));
      pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kYellow),RooFit::Range("Full"), RooFit::VisualizeError(*res,1.0,kTRUE));
    }
    //plot->addObject(&errfix,"4");
    //data->plotOn(plot);

    //pdf->plotOn(plot,RooFit::Normalization( norm ) );
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::Range("Full"),RooFit::LineWidth(1.5) );
    pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::Range("Full"), RooFit::LineWidth(1));
    data->plotOn(plot);
    /*
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::Range("all"),RooFit::LineWidth(0.8) );
    //pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kGreen),RooFit::Range("all"), RooFit::VisualizeError(*res,2.0,kFALSE));
    //pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kYellow),RooFit::Range("all"), RooFit::VisualizeError(*res,1.0,kFALSE));
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kGreen),RooFit::Range("all"), RooFit::VisualizeError(*res,2.0,kTRUE));
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kYellow),RooFit::Range("all"), RooFit::VisualizeError(*res,1.0,kTRUE));
    data->plotOn(plot);
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::Range("all"),RooFit::LineWidth(0.8) );
    */
    TLatex lbl0(0.1,0.96,"CMS Preliminary");
    lbl0.SetNDC();
    lbl0.SetTextSize(0.042);
    plot->addObject(&lbl0);
    
    TLatex lbl(0.4,0.96,Form("%s Box",cats[iCat].Data()));
    lbl.SetNDC();
    lbl.SetTextSize(0.042);
    plot->addObject(&lbl);

    TLatex lbl2(0.6,0.96,"#sqrt{s}=8 TeV  L = 19.78 fb^{-1}");
    lbl2.SetNDC();
    lbl2.SetTextSize(0.042);
    plot->addObject(&lbl2);


    int iObj=-1;
    TNamed *obj;
    while( (obj = (TNamed*)plot->getObject(++iObj)) ) {
      obj->SetName(Form("Object_%d",iObj));
    }

    plot->Draw();
    TString tag = (blind ? "_BLIND" : "");
    cv.SaveAs(folderName+"/figs/mgg_data_"+cats[iCat]+tag+TString(Form("_%0.0f_%0.0f",min,max))+".png");
    cv.SaveAs(folderName+"/figs/mgg_data_"+cats[iCat]+tag+TString(Form("_%0.0f_%0.0f",min,max))+".pdf");
    cv.SaveAs(folderName+"/figs/mgg_data_"+cats[iCat]+tag+TString(Form("_%0.0f_%0.0f",min,max))+".C");
      
  }
  
}
Пример #20
0
void compute_p0(const char* inFileName,
	    const char* wsName = "combined",
	    const char* modelConfigName = "ModelConfig",
	    const char* dataName = "obsData",
	    const char* asimov1DataName = "asimovData_1",
	    const char* conditional1Snapshot = "conditionalGlobs_1",
	    const char* nominalSnapshot = "nominalGlobs",
	    string smass = "130",
	    string folder = "test")
{
  double mass;
  stringstream massStr;
  massStr << smass;
  massStr >> mass;

  double mu_profile_value = 1; // mu value to profile the obs data at wbefore generating the expected
  bool doConditional      = 1; // do conditional expected data
  bool remakeData         = 0; // handle unphysical pdf cases in H->ZZ->4l
  bool doUncap            = 1; // uncap p0
  bool doInj              = 0; // setup the poi for injection study (zero is faster if you're not)
  bool doObs              = 1; // compute median significance
  bool doMedian           = 1; // compute observed significance

  TStopwatch timer;
  timer.Start();

  TFile f(inFileName);
  RooWorkspace* ws = (RooWorkspace*)f.Get(wsName);
  if (!ws)
  {
    cout << "ERROR::Workspace: " << wsName << " doesn't exist!" << endl;
    return;
  }
  ModelConfig* mc = (ModelConfig*)ws->obj(modelConfigName);
  if (!mc)
  {
    cout << "ERROR::ModelConfig: " << modelConfigName << " doesn't exist!" << endl;
    return;
  }
  RooDataSet* data = (RooDataSet*)ws->data(dataName);
  if (!data)
  {
    cout << "ERROR::Dataset: " << dataName << " doesn't exist!" << endl;
    return;
  }

  mc->GetNuisanceParameters()->Print("v");

  ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
  ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
  ROOT::Math::MinimizerOptions::SetDefaultPrintLevel(1);
  cout << "Setting max function calls" << endl;

  ws->loadSnapshot("conditionalNuis_0");
  RooArgSet nuis(*mc->GetNuisanceParameters());

  RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();

  RooAbsPdf* pdf = mc->GetPdf();

  string condSnapshot(conditional1Snapshot);
  RooArgSet nuis_tmp2 = *mc->GetNuisanceParameters();
  RooNLLVar* obs_nll = doObs ? (RooNLLVar*)pdf->createNLL(*data, Constrain(nuis_tmp2)) : NULL;

  RooDataSet* asimovData1 = (RooDataSet*)ws->data(asimov1DataName);
  RooRealVar* emb = (RooRealVar*)mc->GetNuisanceParameters()->find("ATLAS_EMB");
  if (!asimovData1 || (string(inFileName).find("ic10") != string::npos && emb))
  {
    if (emb) emb->setVal(0.7);
    cout << "Asimov data doesn't exist! Please, allow me to build one for you..." << endl;
    string mu_str, mu_prof_str;
    asimovData1 = makeAsimovData(mc, doConditional, ws, obs_nll, 1, &mu_str, &mu_prof_str, mu_profile_value, true);
    condSnapshot="conditionalGlobs"+mu_prof_str;
  }
  
  if (!doUncap) mu->setRange(0, 40);
  else mu->setRange(-40, 40);

  RooAbsPdf* pdf = mc->GetPdf();

  RooArgSet nuis_tmp1 = *mc->GetNuisanceParameters();
  RooNLLVar* asimov_nll = (RooNLLVar*)pdf->createNLL(*asimovData1, Constrain(nuis_tmp1));

  //do asimov
  mu->setVal(1);
  mu->setConstant(0);
  if (!doInj) mu->setConstant(1);

  int status,sign;
  double med_sig=0,obs_sig=0,asimov_q0=0,obs_q0=0;

  if (doMedian)
  {
    ws->loadSnapshot(condSnapshot.c_str());
    if (doInj) ws->loadSnapshot("conditionalNuis_inj");
    else ws->loadSnapshot("conditionalNuis_1");
    mc->GetGlobalObservables()->Print("v");
    mu->setVal(0);
    mu->setConstant(1);
    status = minimize(asimov_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double asimov_nll_cond = asimov_nll->getVal();

    mu->setVal(1);
    if (doInj) ws->loadSnapshot("conditionalNuis_inj");
    else ws->loadSnapshot("conditionalNuis_1");
    if (doInj) mu->setConstant(0);
    status = minimize(asimov_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double asimov_nll_min = asimov_nll->getVal();
    asimov_q0 = 2*(asimov_nll_cond - asimov_nll_min);
    if (doUncap && mu->getVal() < 0) asimov_q0 = -asimov_q0;

    sign = int(asimov_q0 != 0 ? asimov_q0/fabs(asimov_q0) : 0);
    med_sig = sign*sqrt(fabs(asimov_q0));

    ws->loadSnapshot(nominalSnapshot);
  }

  if (doObs)
  {

    ws->loadSnapshot("conditionalNuis_0");
    mu->setVal(0);
    mu->setConstant(1);
    status = minimize(obs_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(obs_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double obs_nll_cond = obs_nll->getVal();

    mu->setConstant(0);
    status = minimize(obs_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(obs_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double obs_nll_min = obs_nll->getVal();



    obs_q0 = 2*(obs_nll_cond - obs_nll_min);
    if (doUncap && mu->getVal() < 0) obs_q0 = -obs_q0;

    sign = int(obs_q0 == 0 ? 0 : obs_q0 / fabs(obs_q0));
    if (!doUncap && (obs_q0 < 0 && obs_q0 > -0.1 || mu->getVal() < 0.001)) obs_sig = 0; 
    else obs_sig = sign*sqrt(fabs(obs_q0));
  }

  // Report results
  cout << "obs: " << obs_sig << endl;

  cout << "Observed significance: " << obs_sig << endl;
  cout << "Corresponding to a p-value of " << (1-ROOT::Math::gaussian_cdf( obs_sig )) << endl;
  if (med_sig)
  {
    cout << "Median test stat val: " << asimov_q0 << endl;
    cout << "Median significance:   " << med_sig << endl;
  }


  f.Close();

  stringstream fileName;
  fileName << "root-files/" << folder << "/" << mass << ".root";
  system(("mkdir -vp root-files/" + folder).c_str());
  TFile f2(fileName.str().c_str(),"recreate");

  TH1D* h_hypo = new TH1D("hypo","hypo",2,0,2);
  h_hypo->SetBinContent(1, obs_sig);
  h_hypo->SetBinContent(2, med_sig);

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

  timer.Stop();
  timer.Print();
  
}
Пример #21
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;

	}
Пример #22
0
RooWorkspace* makeInvertedANFit(TTree* tree, float forceSigma=-1, bool constrainMu=false, float forceMu=-1) {
  RooWorkspace *ws = new RooWorkspace("ws","");

  std::vector< TString (*)(TString, RooRealVar&, RooWorkspace&) > bkgPdfList;
  bkgPdfList.push_back(makeSingleExp);
  bkgPdfList.push_back(makeDoubleExp);
#if DEBUG==0
  //bkgPdfList.push_back(makeTripleExp);
  bkgPdfList.push_back(makeModExp);
  bkgPdfList.push_back(makeSinglePow);
  bkgPdfList.push_back(makeDoublePow);
  bkgPdfList.push_back(makePoly2);
  bkgPdfList.push_back(makePoly3);
#endif



  RooRealVar mgg("mgg","m_{#gamma#gamma}",103,160,"GeV");
  mgg.setBins(38);

  mgg.setRange("sideband_low", 103,120);
  mgg.setRange("sideband_high",131,160);
  mgg.setRange("signal",120,131);

  RooRealVar MR("MR","",0,3000,"GeV");
  MR.setBins(60);
  
  RooRealVar Rsq("t1Rsq","",0,1,"GeV");
  Rsq.setBins(20);

  RooRealVar hem1_M("hem1_M","",-1,2000,"GeV");
  hem1_M.setBins(40);

  RooRealVar hem2_M("hem2_M","",-1,2000,"GeV");
  hem2_M.setBins(40);

  RooRealVar ptgg("ptgg","p_{T}^{#gamma#gamma}",0,500,"GeV");
  ptgg.setBins(50);

  RooDataSet data("data","",tree,RooArgSet(mgg,MR,Rsq,hem1_M,hem2_M,ptgg));

  RooDataSet* blind_data = (RooDataSet*)data.reduce("mgg<121 || mgg>130");

  std::vector<TString> tags;
  //fit many different background models
  for(auto func = bkgPdfList.begin(); func != bkgPdfList.end(); func++) {
    TString tag = (*func)("bonly",mgg,*ws);
    tags.push_back(tag);
    ws->pdf("bonly_"+tag+"_ext")->fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
    RooFitResult* bres = ws->pdf("bonly_"+tag+"_ext")->fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
    bres->SetName(tag+"_bonly_fitres");
    ws->import(*bres);

    //make blinded fit
    RooPlot *fmgg_b = mgg.frame();
    blind_data->plotOn(fmgg_b,RooFit::Range("sideband_low,sideband_high"));
    TBox blindBox(121,fmgg_b->GetMinimum()-(fmgg_b->GetMaximum()-fmgg_b->GetMinimum())*0.015,130,fmgg_b->GetMaximum());
    blindBox.SetFillColor(kGray);
    fmgg_b->addObject(&blindBox);
    ws->pdf("bonly_"+tag+"_ext")->plotOn(fmgg_b,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("sideband_low,sideband_high"));
    fmgg_b->SetName(tag+"_blinded_frame");
    ws->import(*fmgg_b);
    delete fmgg_b;
    

    //set all the parameters constant
    RooArgSet* vars = ws->pdf("bonly_"+tag)->getVariables();
    RooFIter iter = vars->fwdIterator();
    RooAbsArg* a;
    while( (a = iter.next()) ){
      if(string(a->GetName()).compare("mgg")==0) continue;
      static_cast<RooRealVar*>(a)->setConstant(kTRUE);
    }

    //make the background portion of the s+b fit
    (*func)("b",mgg,*ws);

    RooRealVar sigma(tag+"_s_sigma","",5,0,100);
    if(forceSigma!=-1) {
      sigma.setVal(forceSigma);
      sigma.setConstant(true);
    }
    RooRealVar mu(tag+"_s_mu","",126,120,132);
    if(forceMu!=-1) {
      mu.setVal(forceMu);
      mu.setConstant(true);
    }
    RooGaussian sig(tag+"_sig_model","",mgg,mu,sigma);
    RooRealVar Nsig(tag+"_sb_Ns","",5,0,100);
    RooRealVar Nbkg(tag+"_sb_Nb","",100,0,100000);
    

    RooRealVar HiggsMass("HiggsMass","",125.1);
    RooRealVar HiggsMassError("HiggsMassError","",0.24);
    RooGaussian HiggsMassConstraint("HiggsMassConstraint","",mu,HiggsMass,HiggsMassError);


    RooAddPdf fitModel(tag+"_sb_model","",RooArgList( *ws->pdf("b_"+tag), sig ),RooArgList(Nbkg,Nsig));

    RooFitResult* sbres;
    RooAbsReal* nll;
    if(constrainMu) {
      fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
      sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
      nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    } else {
      fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE));
      sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE));
      nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE));
    }
    sbres->SetName(tag+"_sb_fitres");
    ws->import(*sbres);
    ws->import(fitModel);

    RooPlot *fmgg = mgg.frame();
    data.plotOn(fmgg);
    fitModel.plotOn(fmgg);
    ws->pdf("b_"+tag+"_ext")->plotOn(fmgg,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("Full"));
    fmgg->SetName(tag+"_frame");
    ws->import(*fmgg);
    delete fmgg;


    RooMinuit(*nll).migrad();

    RooPlot *fNs = Nsig.frame(0,25);
    fNs->SetName(tag+"_Nsig_pll");
    RooAbsReal *pll = nll->createProfile(Nsig);
    //nll->plotOn(fNs,RooFit::ShiftToZero(),RooFit::LineColor(kRed));
    pll->plotOn(fNs);
    ws->import(*fNs);

    delete fNs;

    RooPlot *fmu = mu.frame(125,132);
    fmu->SetName(tag+"_mu_pll");
    RooAbsReal *pll_mu = nll->createProfile(mu);
    pll_mu->plotOn(fmu);
    ws->import(*fmu);

    delete fmu;

  }

  RooArgSet weights("weights");
  RooArgSet pdfs_bonly("pdfs_bonly");
  RooArgSet pdfs_b("pdfs_b");

  RooRealVar minAIC("minAIC","",1E10);
  //compute AIC stuff
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooAbsPdf *p_bonly = ws->pdf("bonly_"+*t);
    RooAbsPdf *p_b = ws->pdf("b_"+*t);
    RooFitResult *sb = (RooFitResult*)ws->obj(*t+"_bonly_fitres");
    RooRealVar k(*t+"_b_k","",p_bonly->getParameters(RooArgSet(mgg))->getSize());
    RooRealVar nll(*t+"_b_minNll","",sb->minNll());
    RooRealVar Npts(*t+"_b_N","",blind_data->sumEntries());
    RooFormulaVar AIC(*t+"_b_AIC","2*@0+2*@1+2*@1*(@1+1)/(@2-@1-1)",RooArgSet(nll,k,Npts));
    ws->import(AIC);
    if(AIC.getVal() < minAIC.getVal()) {
      minAIC.setVal(AIC.getVal());
    }
    //aicExpSum+=TMath::Exp(-0.5*AIC.getVal()); //we will need this precomputed  for the next step
    pdfs_bonly.add(*p_bonly);
    pdfs_b.add(*p_b);
  }
  ws->import(minAIC);
  //compute the AIC weight
  float aicExpSum=0;
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    aicExpSum+=TMath::Exp(-0.5*(AIC->getVal()-minAIC.getVal())); //we will need this precomputed  for the next step    
  }
  std::cout << "aicExpSum: " << aicExpSum << std::endl;

  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    RooRealVar *AICw = new RooRealVar(*t+"_b_AICWeight","",TMath::Exp(-0.5*(AIC->getVal()-minAIC.getVal()))/aicExpSum);
    if( TMath::IsNaN(AICw->getVal()) ) {AICw->setVal(0);}
    ws->import(*AICw);
    std::cout << *t << ":  " << AIC->getVal()-minAIC.getVal() << "    " << AICw->getVal() << std::endl;
    weights.add(*AICw);
  }
  RooAddPdf bonly_AIC("bonly_AIC","",pdfs_bonly,weights);
  RooAddPdf b_AIC("b_AIC","",pdfs_b,weights);

  //b_AIC.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
  //RooFitResult* bres = b_AIC.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
  //bres->SetName("AIC_b_fitres");
  //ws->import(*bres);

  //make blinded fit
  RooPlot *fmgg_b = mgg.frame(RooFit::Range("sideband_low,sideband_high"));
  blind_data->plotOn(fmgg_b,RooFit::Range("sideband_low,sideband_high"));
  TBox blindBox(121,fmgg_b->GetMinimum()-(fmgg_b->GetMaximum()-fmgg_b->GetMinimum())*0.015,130,fmgg_b->GetMaximum());
  blindBox.SetFillColor(kGray);
  fmgg_b->addObject(&blindBox);
  bonly_AIC.plotOn(fmgg_b,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("sideband_low,sideband_high"));
  fmgg_b->SetName("AIC_blinded_frame");
  ws->import(*fmgg_b);
  delete fmgg_b;
    
#if 1

  RooRealVar sigma("AIC_s_sigma","",5,0,100);
  if(forceSigma!=-1) {
    sigma.setVal(forceSigma);
    sigma.setConstant(true);
  }
  RooRealVar mu("AIC_s_mu","",126,120,132);
  if(forceMu!=-1) {
    mu.setVal(forceMu);
    mu.setConstant(true);
  }
  RooGaussian sig("AIC_sig_model","",mgg,mu,sigma);
  RooRealVar Nsig("AIC_sb_Ns","",5,0,100);
  RooRealVar Nbkg("AIC_sb_Nb","",100,0,100000);
  
  
  RooRealVar HiggsMass("HiggsMass","",125.1);
  RooRealVar HiggsMassError("HiggsMassError","",0.24);
  RooGaussian HiggsMassConstraint("HiggsMassConstraint","",mu,HiggsMass,HiggsMassError);
  
  
  RooAddPdf fitModel("AIC_sb_model","",RooArgList( b_AIC, sig ),RooArgList(Nbkg,Nsig));

  RooFitResult* sbres;
  RooAbsReal *nll;

  if(constrainMu) {
    fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
  } else {
    fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE));
    sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE));
    nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE));
  }

  assert(nll!=0);
  
  sbres->SetName("AIC_sb_fitres");
  ws->import(*sbres);
  ws->import(fitModel);
  
  RooPlot *fmgg = mgg.frame();
  data.plotOn(fmgg);
  fitModel.plotOn(fmgg);
  ws->pdf("b_AIC")->plotOn(fmgg,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("Full"));
  fmgg->SetName("AIC_frame");
  ws->import(*fmgg);
  delete fmgg;

  RooMinuit(*nll).migrad();
  
  RooPlot *fNs = Nsig.frame(0,25);
  fNs->SetName("AIC_Nsig_pll");
  RooAbsReal *pll = nll->createProfile(Nsig);
  //nll->plotOn(fNs,RooFit::ShiftToZero(),RooFit::LineColor(kRed));
  pll->plotOn(fNs);
  ws->import(*fNs);
  delete fNs;


  RooPlot *fmu = mu.frame(125,132);
  fmu->SetName("AIC_mu_pll");
  RooAbsReal *pll_mu = nll->createProfile(mu);
  pll_mu->plotOn(fmu);
  ws->import(*fmu);

  delete fmu;

  std::cout << "min AIC: " << minAIC.getVal() << std::endl;
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    RooRealVar *AICw = ws->var(*t+"_b_AICWeight");
    RooRealVar* k = ws->var(*t+"_b_k");
    printf("%s & %0.0f & %0.2f & %0.2f \\\\\n",t->Data(),k->getVal(),AIC->getVal()-minAIC.getVal(),AICw->getVal());
    //std::cout << k->getVal() << " " << AIC->getVal()-minAIC.getVal() << " " << AICw->getVal() << std::endl;
  }
#endif
  return ws;
}
Пример #23
0
//put very small data entries in a binned dataset to avoid unphysical pdfs, specifically for H->ZZ->4l
RooDataSet* makeData(RooDataSet* orig, RooSimultaneous* simPdf, const RooArgSet* observables, RooRealVar* firstPOI, double mass, double& mu_min)
{

  double max_soverb = 0;

  mu_min = -10e9;

  map<string, RooDataSet*> data_map;
  firstPOI->setVal(0);
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();
  TList* datalist = orig->split(*(RooAbsCategory*)cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  RooRealVar* weightVar = new RooRealVar("weightVar","weightVar",1);
  while ((ds = (RooAbsData*)dataItr->Next()))
  {
    string typeName(ds->GetName());
    cat->setLabel(typeName.c_str());
    RooAbsPdf* pdf = simPdf->getPdf(typeName.c_str());
    cout << "pdf: " << pdf << endl;
    RooArgSet* obs = pdf->getObservables(observables);
    cout << "obs: " << obs << endl;

    RooArgSet obsAndWeight(*obs, *weightVar);
    obsAndWeight.add(*cat);
    stringstream datasetName;
    datasetName << "newData_" << typeName;
    RooDataSet* thisData = new RooDataSet(datasetName.str().c_str(),datasetName.str().c_str(), obsAndWeight, WeightVar(*weightVar));

    RooRealVar* firstObs = (RooRealVar*)obs->first();
    //int ibin = 0;
    int nrEntries = ds->numEntries();
    for (int ib=0;ib<nrEntries;ib++)
    {
      const RooArgSet* event = ds->get(ib);
      const RooRealVar* thisObs = (RooRealVar*)event->find(firstObs->GetName());
      firstObs->setVal(thisObs->getVal());

      firstPOI->setVal(0);
      double b = pdf->expectedEvents(*firstObs)*pdf->getVal(obs);
      firstPOI->setVal(1);
      double s = pdf->expectedEvents(*firstObs)*pdf->getVal(obs) - b;

      if (s > 0)
      {
	mu_min = max(mu_min, -b/s);
	double soverb = s/b;
	if (soverb > max_soverb)
	{
	  max_soverb = soverb;
	  cout << "Found new max s/b: " << soverb << " in pdf " << pdf->GetName() << " at m = " << thisObs->getVal() << endl;
	}
      }

      if (b == 0 && s != 0)
      {
	cout << "Expecting non-zero signal and zero bg at m=" << firstObs->getVal() << " in pdf " << pdf->GetName() << endl;
      }
      if (s+b <= 0) 
      {
	cout << "expecting zero" << endl;
	continue;
      }


      double weight = ds->weight();
      if ((typeName.find("ATLAS_H_4mu") != string::npos || 
	   typeName.find("ATLAS_H_4e") != string::npos ||
	   typeName.find("ATLAS_H_2mu2e") != string::npos ||
	   typeName.find("ATLAS_H_2e2mu") != string::npos) && fabs(firstObs->getVal() - mass) < 10 && weight == 0)
      {
	cout << "adding event: " << firstObs->getVal() << endl;
	thisData->add(*event, pow(10., -9.));
      }
      else
      {
	//weight = max(pow(10.0, -9), weight);
	thisData->add(*event, weight);
      }
    }



    data_map[string(ds->GetName())] = (RooDataSet*)thisData;
  }

  
  RooDataSet* newData = new RooDataSet("newData","newData",RooArgSet(*observables, *weightVar), 
				       Index(*cat), Import(data_map), WeightVar(*weightVar));

  orig->Print();
  newData->Print();
  //newData->tree()->Scan("*");
  return newData;

}
void generateSigHist_for_combineMaker(Float_t lum =10, Int_t cc1 = 0, Int_t cc2 = 9) {

    const Int_t NCAT(4); // 4 categories in the source file
    TString myCut[NCAT] = {"EBHighR9","EBLowR9","EEHighR9","EELowR9"};
    //Float_t lum =10;
    TString lum_string = TString::Format("%g", lum);
    TFile *file=TFile::Open("workspaces/HighMassGG_m1500_01_mgg_lum_"+lum_string+".root");
    RooWorkspace *w_all = (RooWorkspace*)file->Get("w_all");

    RooRealVar *mgg = (RooRealVar*)w_all->var("mgg");
    RooRealVar *MH = (RooRealVar*)w_all->var("MH");
    RooRealVar *kpl = (RooRealVar*)w_all->var("kpl");

    RooNumConvPdf* numConv[NCAT];
    RooFormulaVar* norm[NCAT];

    // necessary to set a window as it is not saved when RooNumConvPdf is saved
    RooRealVar* W = new RooRealVar("W","W",500);
    W->setConstant();
    RooRealVar* C = new RooRealVar("C","C",0);
    C->setConstant();

    cout << "READ PDFs FROM WORKSPACE : SIGNAL FROM 4 CATEGORIES" << endl;
    cout << "READ ROOFORMULAs FROM WORKSPACE : NORMALIZATION OF 4 CATEGORIES" << endl;
    cout << "SET WINDOW FOR THE 4 CONVOLUTIONS (PDFs)" << endl;
    cout << "..." << endl;
    for(Int_t c = 0; c<NCAT; c++) {

        numConv[c] = (RooNumConvPdf*)w_all->pdf("mggSig_cat"+myCut[c]);
        norm[c] = (RooFormulaVar*)w_all->function("mggSig_cat"+myCut[c]+"_norm");
        numConv[c]->setConvolutionWindow(*C,*W);
    }
    cout << endl;
    cout << "ADD PDFs TO FORM THE TWO CATEGORIES EBEB AND EBEE" << endl;
    RooFormulaVar *mggSig_catEBEB_norm = new RooFormulaVar("mggSig_catEBEB_norm","mggSig_catEBEB_norm","@0+@1",RooArgList(*norm[0],*norm[1]));
    RooFormulaVar *mggSig_catEBEE_norm = new RooFormulaVar("mggSig_catEBEE_norm","mggSig_catEBEE_norm","@0+@1",RooArgList(*norm[2],*norm[3]));

    RooFormulaVar *frac1EBEB = new RooFormulaVar("frac1EBEB","frac1EBEB","@0/@1",RooArgList(*norm[0],*mggSig_catEBEB_norm));
    RooFormulaVar *frac2EBEB = new RooFormulaVar("frac2EBEB","frac2EBEB","@0/@1",RooArgList(*norm[1],*mggSig_catEBEB_norm));
    RooFormulaVar *frac1EBEE = new RooFormulaVar("frac1EBEE","frac1EBE","@0/@1",RooArgList(*norm[2],*mggSig_catEBEE_norm));
    RooFormulaVar *frac2EBEE = new RooFormulaVar("frac2EBEE","frac2EBEE","@0/@1",RooArgList(*norm[3],*mggSig_catEBEE_norm));

    RooAddPdf* mggSig_catEBEB = new RooAddPdf("mggSig_catEBEB","mggSig_catEBEB",RooArgList(*numConv[0],*numConv[1]),RooArgList(*frac1EBEB,*frac2EBEB));
    RooAddPdf* mggSig_catEBEE = new RooAddPdf("mggSig_catEBEE","mggSig_catEBEE",RooArgList(*numConv[2],*numConv[3]),RooArgList(*frac1EBEE,*frac2EBEE));

    cout << endl << endl ;
    cout << "READ CFG FROM BACKGROUND_FINAL TO BE USED IN COMBINE_MAKER.PY" << endl;
    TFile *fcfg = TFile::Open("../../Analysis/macros/workspace_cic2_dijet_lum_10/full_analysis_anv1_v18_bkg_ws_300.root");
    TObjString *cfg = (TObjString*)fcfg->Get("cfg");

    const Int_t nCouplings(9);
    Double_t couplings[nCouplings] = {0.01, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.175, 0.2};

    cout << endl << endl ;
    cout << "SCAN OVER MH AND KAPPA VALUES TO GET DIFFERENT PDFs FOR EACH SET OF PARAMETERS..." << endl;

    for(Int_t icoupling = cc1; icoupling < cc2; icoupling++) {

        //CREATE FOLDER FOR THE COUPLING
        TString coupling_string = TString::Format("%g",couplings[icoupling]);
        coupling_string.ReplaceAll(".","");
        TString inDir("../../Analysis/macros/workspace_cic2_signalDataHist_lum_"+lum_string+"/");
        gSystem->mkdir(inDir);

        for(Int_t mass = 1000; mass < 5100 ; mass+=100) {

            TString mass_string = TString::Format("%d",mass);
            TString signame("grav_"+coupling_string+"_"+mass_string);
            cout << endl;
            cout << "********************************************" << endl;
            cout << "SET MH and KAPPA values" << endl << "kappa: " << couplings[icoupling] << endl << "mass: " << mass << endl;
            cout << "********************************************" << endl;
            MH->setVal(mass);
            kpl->setVal(couplings[icoupling]);

            cout << "CREATE ROODATAHIST WITH NORM..." << endl;
            RooDataHist* dhEBEB = mggSig_catEBEB->generateBinned(RooArgSet(*mgg),mggSig_catEBEB_norm->getVal(), RooFit::ExpectedData());
            RooDataHist* dhEBEE = mggSig_catEBEE->generateBinned(RooArgSet(*mgg),mggSig_catEBEE_norm->getVal(), RooFit::ExpectedData());

            dhEBEB->SetName("signal_"+signame+"_EBEB");
            dhEBEB->SetTitle("signal_"+signame+"_EBEB");
            dhEBEE->SetName("signal_"+signame+"_EBEE");
            dhEBEE->SetTitle("signal_"+signame+"_EBEE");

            //CREATE ROOHISTPDF
            //RooHistPdf *fhEBEB = new RooHistPdf("mggHistPdf_catEBEB","mggHistPdf_catEBEB",RooArgSet(*mgg),*dhEBEB);
            //RooHistPdf *fhEBEE = new RooHistPdf("mggHistPdf_catEBEE","mggHistPdf_catEBEE",RooArgSet(*mgg),*dhEBEE);

            //SAVE ALL IN A WORKSPACE WITH FILE NAME corresponding to MASS AND COUPLING VALUE
            RooWorkspace *wtemplates = new RooWorkspace("wtemplates","wtemplates");

            //wtemplates->import(*fhEBEB);
            //wtemplates->import(*fhEBEE);
            //wtemplates->import(*mggSig_catEBEB_norm,RecycleConflictNodes());
            //wtemplates->import(*mggSig_catEBEE_norm,RecycleConflictNodes());
            wtemplates->import(*dhEBEB);
            wtemplates->import(*dhEBEE);
            //wtemplates->import(*numConv[0],RecycleConflictNodes());

            cout << "******************************************" << endl;
            cout << "WORKSPACE CONTENT FOR COUPLING " << couplings[icoupling] << " AND MASS " << mass << endl;
            wtemplates->Print("V");

            //WRITE IN FILE
            TString filename = inDir+"300_"+signame+".root";
            TFile *fileOutput = TFile::Open(filename,"recreate");
            cfg->Write("cfg");
            wtemplates->Write("wtemplates");
            cout << "workspace imported to " << filename << endl;

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



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

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

   }
   else
      filename = infile;

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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


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

   double CLb=0;
   double CLbinclusive=0;

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

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

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

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

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

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

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

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

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

            // Cleanup
            delete globtmp ;
            delete tmp ;
         }
      }

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

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


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

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



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

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

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

      histOfUL->Fill(thisUL);

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

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

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

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

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

   delete profile;
   delete nll;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  RooRealVar* correlatedParameter = workspace.var(correlatedName);

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

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

  data->addColumn(*normalFromFlat);

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

  data->Print("v");

  workspace.Print() ;

  //Setup Plotting Kluges:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  observableSet->Print();

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

  correlatedParameter->setVal(0.25);

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

  correlatedParameter->setVal(0.75);

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

  //Testing for extreme values!

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


}
Пример #28
0
// 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;
}
Пример #29
0
void fitSingleMass( const std::string& basedir, float mass, const std::string&  width, TGraphErrors* gr_mean, TGraphErrors* gr_sigma, TGraphErrors* gr_width, TGraphErrors* gr_alpha1, TGraphErrors* gr_n1, TGraphErrors* gr_alpha2, TGraphErrors* gr_n2 ) {


  std::string outdir = "genSignalShapes";
  system( Form("mkdir -p %s", outdir.c_str()) );


  std::string dataset( Form( "GluGluSpin0ToZGamma_ZToLL_W_%s_M_%.0f_TuneCUEP8M1_13TeV_pythia8", width.c_str(), mass ) );
  std::cout << "-> Starting: " << dataset << std::endl;

  system( Form("ls %s/%s/crab_%s/*/0000/genAna_1.root >> toBeAdded.txt", basedir.c_str(), dataset.c_str(), dataset.c_str() ) );
  TChain* tree = new TChain("mt2");
  ifstream ifs("toBeAdded.txt");
  while( ifs.good() ) {
    std::string fileName;
    ifs >> fileName;
    TString fileName_tstr(fileName);
    if( !fileName_tstr.Contains("pnfs") ) continue;
    tree->Add(Form("$DCAP/%s/mt2", fileName.c_str()) );
  }
  system( "rm toBeAdded.txt" );

  if( tree->GetEntries()==0 ) return;

  int ngenPart;
  tree->SetBranchAddress( "ngenPart", &ngenPart );
  float genPart_pt[100];
  tree->SetBranchAddress( "genPart_pt", genPart_pt );
  float genPart_eta[100];
  tree->SetBranchAddress( "genPart_eta", genPart_eta );
  float genPart_phi[100];
  tree->SetBranchAddress( "genPart_phi", genPart_phi );
  float genPart_mass[100];
  tree->SetBranchAddress( "genPart_mass", genPart_mass );
  int genPart_pdgId[100];
  tree->SetBranchAddress( "genPart_pdgId", genPart_pdgId );
  int genPart_motherId[100];
  tree->SetBranchAddress( "genPart_motherId", genPart_motherId );
  int genPart_status[100];
  tree->SetBranchAddress( "genPart_status", genPart_status );



  RooRealVar* x = new RooRealVar("boss_mass", "boss_mass", mass, 0.5*mass, 1.5*mass );

  RooDataSet* data = new RooDataSet( "data", "data", RooArgSet(*x) );



  int nentries = tree->GetEntries();


  for( int iEntry = 0; iEntry<nentries; ++iEntry ) {

    if( iEntry % 25000 == 0 ) std::cout << "  Entry: " << iEntry << " / " << nentries << std::endl;

    tree->GetEntry(iEntry);

    TLorentzVector leptPlus;
    TLorentzVector leptMinus;
    TLorentzVector photon;
    bool foundLeptPlus = false;
    bool foundLeptMinus = false;
    bool foundPhoton = false;
    bool tauEvent = false;

    for( int iPart=0; iPart<ngenPart; ++iPart ) {

      if( genPart_status[iPart]!=1 ) continue;

      if( abs(genPart_pdgId[iPart])==15 ) {
        tauEvent = true;
        break;
      }

      if( (genPart_pdgId[iPart]==+11 || genPart_pdgId[iPart]==+13) && genPart_motherId[iPart]==23 ) {
        leptMinus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptMinus = true;
      }
      if( (genPart_pdgId[iPart]==-11 || genPart_pdgId[iPart]==-13) && genPart_motherId[iPart]==23 ) {
        leptPlus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptPlus = true;
      }
      if( genPart_pdgId[iPart]==22 && genPart_motherId[iPart]==25 ) {
        photon.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundPhoton = true;
      }

    } // for genparts

    if( tauEvent ) continue;
    if( !foundLeptPlus || !foundLeptMinus || !foundPhoton ) continue;


    if( photon.Pt() < 40. ) continue;
    float ptMax = TMath::Max( leptPlus.Pt(), leptMinus.Pt() );
    float ptMin = TMath::Min( leptPlus.Pt(), leptMinus.Pt() );
    if( ptMax<25. ) continue;
    if( ptMin<20. ) continue;
    if( fabs( photon.Eta() ) > 2.5 ) continue;
    if( fabs( photon.Eta())>1.44 && fabs( photon.Eta())<1.57 ) continue;
    if( fabs( leptPlus.Eta() ) > 2.4 ) continue;
    if( fabs( leptMinus.Eta() ) > 2.4 ) continue;
    if( photon.DeltaR( leptPlus  ) < 0.4 ) continue;
    if( photon.DeltaR( leptMinus ) < 0.4 ) continue;

    TLorentzVector zBoson = leptPlus + leptMinus;
    if( zBoson.M() < 50. ) continue;

    TLorentzVector boss = zBoson + photon;
    if( boss.M() < 200. ) continue;

    if( photon.Pt()/boss.M()< 40./150. ) continue;

    x->setVal(boss.M());

    data->add(RooArgSet(*x));

  }


  //RooRealVar* bw_mean  = new RooRealVar( "bw_mean", "Breit-Wigner Mean" , mass, 0.2*mass, 1.8*mass );
  //RooRealVar* bw_gamma = new RooRealVar( "bw_gamma", "Breit-Wigner Width", 0.01*mass, 0., 0.3*mass );
  //RooBreitWigner* model = new RooBreitWigner( "bw", "Breit-Wigner", *x, *bw_mean, *bw_gamma);

  // Crystal-Ball
  RooRealVar mean( "mean", "mean", mass, 0.9*mass, 1.1*mass );
  RooRealVar sigma( "sigma", "sigma", 0.015*mass, 0., 0.07*mass );
  RooRealVar alpha1( "alpha1", "alpha1", 1.2, 0., 2.5 );
  RooRealVar n1( "n1", "n1", 3., 0., 5. );
  RooRealVar alpha2( "alpha2", "alpha2", 1.2, 0., 2.5 );
  RooRealVar n2( "n2", "n2", 3., 0., 10. );
  RooDoubleCBShape* model = new RooDoubleCBShape( "cb", "cb", *x, mean, sigma, alpha1, n1, alpha2, n2 );

  model->fitTo( *data );

  int npoints = gr_mean->GetN();
  gr_mean  ->SetPoint( npoints, mass, mean.getVal() );
  gr_sigma ->SetPoint( npoints, mass, sigma.getVal() );
  gr_width ->SetPoint( npoints, mass, sigma.getVal()/mean.getVal() );
  gr_alpha1->SetPoint( npoints, mass, alpha1.getVal() );
  gr_alpha2->SetPoint( npoints, mass, alpha2.getVal() );
  gr_n1    ->SetPoint( npoints, mass, n1.getVal() );
  gr_n2    ->SetPoint( npoints, mass, n2.getVal() );

  gr_mean  ->SetPointError( npoints, 0., mean.getError() );
  gr_sigma ->SetPointError( npoints, 0., sigma.getError() );
  gr_width ->SetPointError( npoints, 0., sigma.getError()/mean.getVal() );
  gr_alpha1->SetPointError( npoints, 0., alpha1.getError() );
  gr_alpha2->SetPointError( npoints, 0., alpha2.getError() );
  gr_n1    ->SetPointError( npoints, 0., n1.getError() );
  gr_n2    ->SetPointError( npoints, 0., n2.getError() );

  //gr_mean ->SetPoint     ( npoints, mass, bw_mean->getVal() );
  //gr_gamma->SetPoint     ( npoints, mass, bw_gamma->getVal() );
  //gr_width->SetPoint     ( npoints, mass, bw_gamma->getVal()/bw_mean->getVal() );
  //gr_mean ->SetPointError( npoints,   0., bw_mean->getError() );
  //gr_gamma->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );
  //gr_width->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );

  RooPlot* plot = x->frame();
  data->plotOn(plot);
  model->plotOn(plot);

  TCanvas* c1 = new TCanvas( "c1", "", 600, 600 );
  c1->cd();

  plot->Draw();
    
  c1->SaveAs( Form("%s/fit_m%.0f_%s.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s.pdf", outdir.c_str(), mass, width.c_str()) );

  c1->SetLogy();

  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.pdf", outdir.c_str(), mass, width.c_str()) );


  //delete bw_mean;
  //delete bw_gamma;

  delete c1;
  delete data;
  delete model;
  delete plot;
  delete x;

}
Пример #30
0
int main(int argc, char **argv)
{
	bool printeff = true;
	string fc = "none";
	
	gROOT->ProcessLine(".x lhcbStyle.C");

	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);

			if(arg.find("-E")!=string::npos) fc = str;
			if(arg=="-peff") printeff = true;
		}
	}
	
	int nexp = 100;
	int nbins = 6;
	double q2min[] = {8.,15.,11.0,15,16,18};
	double q2max[] = {11.,20.,12.5,16,18,20};

	TString datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/candLb.root";
	TreeReader * data = new TreeReader("candLb2Lmumu");
	data->AddFile(datafilename);
	TreeReader * datajpsi = new TreeReader("candLb2JpsiL");
	datajpsi->AddFile(datafilename);

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

	string options = "-quiet-noPlot-lin-stdAxis-XM(#Lambda#mu#mu) (MeV/c^{2})-noCost-noParams";
	Analysis::SetPrintLevel("s");

	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5621.,5400.,6000.);
	MM->setRange("Signal",5600,5640);
	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);

	//TGraphAsymmErrors * fL_vs_q2 = new TGraphAsymmErrors();
	//TCanvas * ceff = new TCanvas();

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

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-0.75,0.75);
	RooRealVar * fL = new RooRealVar("fL","fL",0.6,0.,1.);
	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.,-0.5,0.5);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";
	RooAbsPdf * teoPdf = new RooGenericPdf("teoPdf",afbLpdf,RooArgSet(*cosThetaL,*afb,*fL));
	RooAbsPdf * teoPdfB = new RooGenericPdf("teoPdfB",afbBpdf,RooArgSet(*cosThetaB,*afbB));

	TreeReader * mydata = datajpsi;
	Str2VarMap jpsiParsLL = getJpsiPars("LL", CutsDef::LLcut, histFile);
	Str2VarMap jpsiParsDD = getJpsiPars("DD", CutsDef::DDcut, histFile);

	vector<TH1 *> fLsysh, afbsysh, afbBsysh, fLsysh_frac, afbsysh_frac, afbBsysh_frac;

	for(int i = 0; i < nbins; i++)
	{
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		if(i>0) { mydata = data; MM->setRange(5400,6000); }
		else { q2name = "jpsi"; MM->setRange(5500,5850); }
		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]);	
		
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		/**               GET AND FIT EFFICIENCIES                  **/

		RooAbsPdf * effDDpdf = NULL, * effLLpdf = NULL, * effLLBpdf = NULL, * effDDBpdf = NULL;	
		getEfficiencies(q2min[i],q2max[i],&effLLpdf,&effDDpdf,&effLLBpdf,&effDDBpdf,printeff);
		cout << "Efficiencies extracted" << endl;
		histFile->cd();


		/**                    FIT AFB                  **/


		afb->setVal(0);
		afbB->setVal(-0.37);
		fL->setVal(0.6);

		RooAbsPdf * corrPdfLL = new RooProdPdf("sigPdfLL"+q2name,"corrPdfLL",*teoPdf,*effLLpdf);
		RooAbsPdf * corrPdfDD = new RooProdPdf("sigPdfDD"+q2name,"corrPdfDD",*teoPdf,*effDDpdf);
		RooAbsPdf * corrPdfLLB = new RooProdPdf("sigPdfLLB"+q2name,"corrPdfLLB",*teoPdfB,*effLLBpdf);
		RooAbsPdf * corrPdfDDB = new RooProdPdf("sigPdfDDB"+q2name,"corrPdfDDB",*teoPdfB,*effDDBpdf);

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

		histFile->cd();
		double fracDDv[2], fracLLv[2];
		double nsigDD, nsigLL;
		RooDataSet * dataLL = getDataAndFrac("LL",q2name,mydata,cutLL,MM,&fracLLv[0],jpsiParsLL,&nsigLL);
		RooDataSet * dataDD = getDataAndFrac("DD",q2name,mydata,cutDD,MM,&fracDDv[0],jpsiParsDD,&nsigDD);
		double nevts = nsigDD+nsigLL;

		cout << fixed << setprecision(3) << fracDDv[0] << "   " << fracDDv[1] << endl;
		RooRealVar * fracLL = new RooRealVar("fracLL","fracLL",fracLLv[0]);
		RooRealVar * fracDD = new RooRealVar("fracDD","fracDD",fracDDv[0]);

		RooAbsPdf * bkgLL = NULL, * bkgLLB = NULL, * bkgDD = NULL, * bkgDDB = NULL;
		buildBkgPdfs(q2min[i],q2max[i],"LL",CutsDef::LLcut,&bkgLL,&bkgLLB);
		buildBkgPdfs(q2min[i],q2max[i],"DD",CutsDef::DDcut,&bkgDD,&bkgDDB);
	
		cout << "Backgrounds extracted" << endl;

		RooAbsPdf * modelLL = new RooAddPdf("modelLL","modelLL",RooArgSet(*corrPdfLL,*bkgLL),*fracLL);
		RooAbsPdf * modelDD = new RooAddPdf("modelDD","modelDD",RooArgSet(*corrPdfDD,*bkgDD),*fracDD);
		RooAbsPdf * modelLLB = new RooAddPdf("modelLLB","modelLLB",RooArgSet(*corrPdfLLB,*bkgLLB),*fracLL);
		RooAbsPdf * modelDDB = new RooAddPdf("modelDDB","modelDDB",RooArgSet(*corrPdfDDB,*bkgDDB),*fracDD);

		// CREATE COMBINED DATASET
		RooDataSet * combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*MM,*cosThetaL,*cosThetaB),Index(*samples),Import("DD",*dataDD),Import("LL",*dataLL));

		Str2VarMap params;
		params["fL"] = fL;
		params["afb"] = afb;	
		Str2VarMap paramsB;
		paramsB["afbB"] = afbB;

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

		RooFitResult * res = safeFit(combModel,combData,params,&isInAllowedArea);	
	
		// FIT COS HADRON
		RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
		combModelB->addPdf(*modelLLB,"LL");
		combModelB->addPdf(*modelDDB,"DD");

		RooFitResult * resB = safeFit(combModelB,combData,paramsB,&isInAllowedAreaB);

		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 << "lepton:  " << res->edm() << "   "  << res->covQual() << endl;
		cout << "baryon:  " << resB->edm() << "   "  << resB->covQual() << endl;
		cout << endl;

		TH1F * fLsys = new TH1F(Form("fLsys_%i",i),"fLsys",40,-1,1);
		TH1F * afbsys = new TH1F(Form("afbsys_%i",i),"afbsys",40,-1,1);
		TH1F * afbBsys = new TH1F(Form("afbBsys_%i",i),"afbBsys",40,-1,1);
		TH1F * fLsys_frac = new TH1F(Form("fLsys_frac%i",i),"fLsys",40,-1,1);
		TH1F * afbsys_frac = new TH1F(Form("afbsys_frac%i",i),"afbsys",40,-1,1);
		TH1F * afbBsys_frac = new TH1F(Form("afbBsys_frac%i",i),"afbBsys",40,-1,1);


		RooAbsPdf * mybkgDD_2 = NULL, * mybkgDDB_2 = NULL;
		buildBkgPdfs(q2min[i],q2max[i],"DD",CutsDef::DDcut,&mybkgDD_2,&mybkgDDB_2,"RooKeyPdf");

		//cout << nevts << endl;
		//TRandom3 r(0);

		for(int e = 0; e < nexp; e++)
		{
			histFile->cd();
			RooAbsPdf * toypdf = (RooAbsPdf *)modelDD->Clone();
			Analysis * toy = new Analysis("toy",cosThetaL,modelDD,nevts);
			RooAbsPdf * toypdfB = (RooAbsPdf *)modelDDB->Clone();
			Analysis * toyB = new Analysis("toyB",cosThetaB,modelDDB,nevts);
			
			afb->setVal(0);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			safeFit(toypdf,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(toypdfB,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);
			double def_afb = afb->getVal();
			double def_fL = fL->getVal();
			double def_afbB = afbB->getVal();

			afb->setVal(0);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			RooAbsPdf * modelDD_2 = new RooAddPdf("modelDD_2","modelDD",RooArgSet(*corrPdfDD,*mybkgDD_2),*fracDD);
			RooAbsPdf * modelDDB_2 = new RooAddPdf("modelDDB_2","modelDDB",RooArgSet(*corrPdfDDB,*mybkgDDB_2),*fracDD);
			safeFit(modelDD_2,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(modelDDB_2,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);
			double oth_afb = afb->getVal();
			double oth_fL = fL->getVal();
			double oth_afbB = afbB->getVal();

			fLsys->Fill(oth_fL-def_fL);
			afbsys->Fill(oth_afb-def_afb);
			afbBsys->Fill(oth_afbB-def_afbB);
			

			afb->setVal(0.);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			//double rdm_frac = r.Gaus(fracDDv[0],fracDDv[1]);
			double rdm_frac = fracDDv[0] + fracDDv[1];
			RooRealVar * fracDD_2 = new RooRealVar("fracDD_2","fracDD_2",rdm_frac);	
			RooAbsPdf * modelDD_3 = new RooAddPdf("modelDD_3","modelDD",RooArgSet(*corrPdfDD,*bkgDD),*fracDD_2);
			RooAbsPdf * modelDDB_3 = new RooAddPdf("modelDDB_3","modelDDB",RooArgSet(*corrPdfDDB,*bkgDDB),*fracDD_2);
			safeFit(modelDD_3,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(modelDDB_3,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);

			double frc_afb = afb->getVal();
			double frc_fL = fL->getVal();
			double frc_afbB = afbB->getVal();

			fLsys_frac->Fill(frc_fL-def_fL);
			afbsys_frac->Fill(frc_afb-def_afb);
			afbBsys_frac->Fill(frc_afbB-def_afbB);
			
		}

		afbsysh.push_back(afbsys);
		afbBsysh.push_back(afbBsys);
		fLsysh.push_back(fLsys);
		afbsysh_frac.push_back(afbsys_frac);
		afbBsysh_frac.push_back(afbBsys_frac);
		fLsysh_frac.push_back(fLsys_frac);

	}

	
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << fLsysh[q]->GetMean() << " +/- " << fLsysh[q]->GetMeanError() << endl;
		cout << "Afb sys = " << afbsysh[q]->GetMean() << " +/- " << afbsysh[q]->GetMeanError() << endl;
		cout << "AfbB sys = " << afbBsysh[q]->GetMean() << " +/- " << afbBsysh[q]->GetMeanError() << endl;
	}

	cout << "#################################################################" << endl;
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << fLsysh_frac[q]->GetMean() << " +/- " << fLsysh_frac[q]->GetMeanError() << endl;
		cout << "Afb sys = " << afbsysh_frac[q]->GetMean() << " +/- " << afbsysh_frac[q]->GetMeanError() << endl;
		cout << "AfbB sys = " << afbBsysh_frac[q]->GetMean() << " +/- " << afbBsysh_frac[q]->GetMeanError() << endl;
	}

	cout << "#################################################################" << endl;
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << TMath::Sqrt(TMath::Power(fLsysh_frac[q]->GetMean(),2) + TMath::Power(fLsysh[q]->GetMean(),2) )  << endl;
		cout << "Afb sys = " << TMath::Sqrt(TMath::Power(afbsysh_frac[q]->GetMean(),2) + TMath::Power(afbsysh[q]->GetMean(),2) ) << endl;
		cout << "AfbB sys = " << TMath::Sqrt(TMath::Power(afbBsysh_frac[q]->GetMean(),2) + TMath::Power(afbBsysh[q]->GetMean(),2) ) << endl;
	}

}