Ejemplo n.º 1
0
void trig_pt()
{
  TCanvas *myCan=new TCanvas("myCan","myCan");
  myCan->SetGrid();
  TFile *f_MC= new TFile("TnP_WptCutToTrig_MCptminus.root","read");
  RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTree/Tnp_WptCut_to_Mu15_eta2p1_pt/cnt_eff");
  cout<<"ntry: "<<datasetMC->numEntries()<<endl;
  double XMC[Nbin],XMCerrL[Nbin],XMCerrH[Nbin],YMC[Nbin],YMCerrLo[Nbin],YMCerrHi[Nbin];
  for(int i(0); i<datasetMC->numEntries();i++)
  {
    const RooArgSet &pointMC=*datasetMC->get(i);
    RooRealVar &ptMC=pointMC["pt"],&effMC = pointMC["efficiency"];
    XMC[i]=ptMC.getVal();
    XMCerrL[i]=-ptMC.getAsymErrorLo();
    XMCerrH[i]=ptMC.getAsymErrorHi();
    YMC[i]=effMC.getVal();
    YMCerrLo[i]=-effMC.getAsymErrorLo();
    YMCerrHi[i]=effMC.getAsymErrorHi();
  }
  grMC=new TGraphAsymmErrors(11,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);
  grMC->SetLineColor(kRed);
  grMC->SetMarkerColor(kRed);
  grMC->Draw("AP");
  //grMC->Draw("psame");
  myCan->SaveAs("trig_McMinus_pt.png");
  myCan->SaveAs("trig_McMinus_pt.eps");

}
Ejemplo n.º 2
0
void glbToId_eta()
{
  TCanvas *myCan=new TCanvas("myCan","myCan");
  myCan->SetGrid();
  TFile *f_MC= new TFile("TnP_GlbToID_MCetaplus_WptTight2012_eta.root","read");
  RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTree/WptTight2012_eta/fit_eff");
  //RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTree/WptTight2012_eta/cnt_eff");
  cout<<"ntry: "<<datasetMC->numEntries()<<endl;
  double XMC[Nbin],XMCerrL[Nbin],XMCerrH[Nbin],YMC[Nbin],YMCerrLo[Nbin],YMCerrHi[Nbin];
  for(int i(0); i<datasetMC->numEntries();i++)
  {
    const RooArgSet &pointMC=*datasetMC->get(i);
    RooRealVar &etaMC=pointMC["eta"],&effMC = pointMC["efficiency"];
    XMC[i]=etaMC.getVal();
    XMCerrL[i]=-etaMC.getAsymErrorLo();
    XMCerrH[i]=etaMC.getAsymErrorHi();
    YMC[i]=effMC.getVal();
    YMCerrLo[i]=-effMC.getAsymErrorLo();
    YMCerrHi[i]=effMC.getAsymErrorHi();
  }
  grMC=new TGraphAsymmErrors(Nbin,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);
  grMC->SetLineColor(kRed);
  grMC->SetMarkerColor(kRed);
  grMC->Draw("AP");
  //grMC->Draw("psame");
  myCan->SaveAs("glbToId_MCplus_eta.png");
  myCan->SaveAs("glbToId_MCplus_eta.eps");

}
Ejemplo n.º 3
0
void sc_wptCut_P_et()
{
  TCanvas *myCan=new TCanvas("myCan","myCan");
  myCan->SetGrid();
  /************************
  TFile *f_RD= new TFile("TnP_Z_Trigger_RDpt.root","read");
  RooDataSet *dataset = (RooDataSet*)f_RD->Get("tpTree/Track_To_TightCombRelIso_Mu15_eta2p1_pt/fit_eff");
  cout<<"ntry: "<<dataset->numEntries()<<endl;
  double X[11],XerrL[11],XerrH[11],Y[11],YerrLo[11],YerrHi[11];
  for(int i(0); i<dataset->numEntries();i++)
  {
    const RooArgSet &point=*dataset->get(i);
    RooRealVar &pt=point["pt"],&eff = point["efficiency"];
    X[i]=pt.getVal();
    XerrL[i]=-pt.getAsymErrorLo();
    XerrH[i]=pt.getAsymErrorHi();
    Y[i]=eff.getVal();
    YerrLo[i]=-eff.getAsymErrorLo();
    YerrHi[i]=eff.getAsymErrorHi();
  }
  gr=new TGraphAsymmErrors(11,X,Y,XerrL,XerrH,YerrLo,YerrHi);
  gr->Draw("AP");
***************************/
  TFile *f_MC= new TFile("efficiency-mc-SCToPfElectron_et_P.root","read");
  RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("SuperClusterToPFElectron/SCtoWptCut_efficiency/cnt_eff");
  //RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTree/Track_with_TightCombRelIso_to_Mu15_eta2p1_pt/fit_eff");
  cout<<"ntry: "<<datasetMC->numEntries()<<endl;

  double XMC[binSize],XMCerrL[binSize],XMCerrH[binSize],YMC[binSize],YMCerrLo[binSize],YMCerrHi[binSize];
  for(int i(0); i<datasetMC->numEntries();i++)
  {
    const RooArgSet &pointMC=*datasetMC->get(i);
    RooRealVar &ptMC=pointMC["probe_sc_et"],&effMC = pointMC["efficiency"];
    XMC[i]=ptMC.getVal();
    XMCerrL[i]=-ptMC.getAsymErrorLo();
    XMCerrH[i]=ptMC.getAsymErrorHi();
    YMC[i]=effMC.getVal();
    YMCerrLo[i]=-effMC.getAsymErrorLo();
    YMCerrHi[i]=effMC.getAsymErrorHi();
  }
  grMC=new TGraphAsymmErrors(binSize,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);
  grMC->SetLineColor(kRed);
  grMC->SetMarkerColor(kRed);
  //myCan->SetLogx();
  grMC->Draw("AP");
  //grMC->Draw("psame");
  TLine *myLine=new TLine(25,0,25,1);
  myLine->Draw("same");
  myCan->SaveAs("sc_wptCut_P_et.png");
  myCan->SaveAs("sc_wptCut_P_et.eps");

}
Ejemplo n.º 4
0
RooDataHist * genHistFromModelPdf(const char * name, RooAbsPdf *model,  RooRealVar *var,    double ScaleLumi,  int range, int rebin, int seed ) {
  double genEvents =  model->expectedEvents(*var);
  TRandom3 *rndm = new TRandom3();
  rndm->SetSeed(seed);
  double nEvt = rndm->PoissonD( genEvents) ;
  int intEvt = ( (nEvt- (int)nEvt) >= 0.5) ? (int)nEvt +1 : int(nEvt);
  RooDataSet * data = model->generate(*var ,   intEvt   );
  cout<< " expected events for " << name << " = "<< genEvents << endl; 
  cout<< " data->numEntries() for name " << name << " == " << data->numEntries()<< endl;
  // cout<< " nEvt from PoissonD for" << name << " == " << nEvt<< endl;
  //cout<< " cast of nEvt  for" << name << " == " << intEvt<< endl; 
  RooAbsData *binned_data = data->binnedClone();
  TH1 * toy_hist = binned_data->createHistogram( name, *var, Binning(range/rebin )  );
  for(int i = 1; i <= toy_hist->GetNbinsX(); ++i) {
    toy_hist->SetBinError( i,  sqrt( toy_hist->GetBinContent(i)) );
    if(toy_hist->GetBinContent(i) == 0.00) {
      cout<< " WARNING: histo " << name << " has 0 enter in bin number " << i << endl;   
    }
    if(toy_hist->GetBinContent(i) < 0.1) {
      toy_hist->SetBinContent(i, 0.0);
      toy_hist->SetBinError(i, 0.0);
      cout<< " WARNING: setting value 0.0 to histo " << name << " for bin number " << i << endl;   
    }  
  }
  RooDataHist * toy_rooHist = new RooDataHist(name, name , RooArgList(*var), toy_hist );
  return toy_rooHist; 
}
pair<double,double> datEvents(RooWorkspace *work, int m_hyp, int cat, bool spin=false){
  
  vector<double> result;
  RooDataSet *data = (RooDataSet*)work->data(Form("data_mass_cat%d",cat));
  double evs = data->numEntries();
  double evsPerGev;
  if (!spin) evsPerGev = data->sumEntries(Form("CMS_hgg_mass>=%4.1f && CMS_hgg_mass<%4.1f",double(m_hyp)-0.5,double(m_hyp)+0.5));
  else evsPerGev = data->sumEntries(Form("mass>=%4.1f && mass<%4.1f",double(m_hyp)-0.5,double(m_hyp)+0.5));
  return pair<double,double>(evs,evsPerGev);
}
Ejemplo n.º 6
0
void wspaceread_backgrounds(int channel = 1)
{

	gSystem->AddIncludePath("-I$ROOFITSYS/include");
	gROOT->ProcessLine(".L ~/tdrstyle.C");
	
	string schannel;
	if (channel == 1) schannel = "4mu";
	if (channel == 2) schannel = "4e";
	if (channel == 3) schannel = "2mu2e";
	std::cout << "schannel = " << schannel << std::endl;

	// R e a d   w o r k s p a c e   f r o m   f i l e
	// -----------------------------------------------
	
	// Open input file with workspace (generated by rf14_wspacewrite)
	char infile[192];
	sprintf(infile,"/scratch/hep/ntran/dataFiles/HZZ4L/datasets/datasets/%s/ZZAnalysisTree_ZZTo4L_lowmass.root",schannel.c_str());
	TFile *f = new TFile(infile) ;
	char outfile[192];
	sprintf( outfile, "figs/pdf_%s_bkg_highmass.eps", schannel.c_str() );
	//f->ls();
	
	
	RooDataSet* set = (RooDataSet*) f->Get("data");
	RooArgSet* obs = set->get() ;
	obs->Print();
	RooRealVar* CMS_zz4l_mass = (RooRealVar*) obs->find("CMS_zz4l_mass") ;
	
	for (int i=0 ; i<set->numEntries() ; i++) { 
		set->get(i) ; 
		//cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
	} 
	
	gSystem->Load("PDFs/RooqqZZPdf_cxx.so");
	//gSystem->Load("PDFs/RooggZZPdf_cxx.so");

	// LO contribution

	//RooRealVar m4l("m4l","m4l",100.,1000.);
	RooRealVar a1("a1","a1",224.,100.,1000.);
	RooRealVar a2("a2","a2",-209.,-1000.,1000.);
	RooRealVar a3("a3","a3",121.,20.,1000.);
	RooRealVar a4("a4","a4",-0.022,-10.,10.);
	RooRealVar b1("b1","b1",181.,100.,1000.);
	RooRealVar b2("b2","b2",707.,0.,1000.);
	RooRealVar b3("b3","b3",60.,20.,1000.);
	RooRealVar b4("b4","b4",0.04,-10.,10.);
	RooRealVar b5("b5","b5",5.,0.,1000.);
	RooRealVar b6("b6","b6",0.,-10.,10.);
	RooRealVar frac_bkg("frac_bkg","frac_bkg",0.5,0.,1.);
	
	//a1.setConstant(kTRUE);
	//a2.setConstant(kTRUE);
	//a3.setConstant(kTRUE);
	//a4.setConstant(kTRUE);
	//b1.setConstant(kTRUE);
	//b2.setConstant(kTRUE);
	//b3.setConstant(kTRUE);
	//b4.setConstant(kTRUE);
	//b5.setConstant(kTRUE);
	//b6.setConstant(kTRUE);

	RooqqZZPdf bkg_qqzz("bkg_qqzz","bkg_qqzz",*CMS_zz4l_mass,a1,a2,a3,a4,b1,b2,b3,b4,b5,b6,frac_bkg);

	RooFitResult *r = bkg_qqzz.fitTo( *set, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

	// Plot Y
	RooPlot* frameM4l = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
	set->plotOn(frameM4l) ;
	bkg_qqzz.plotOn(frameM4l) ;
	
	TCanvas *c = new TCanvas("c","c",800,600);
	c->cd();
	frameM4l->Draw();
	
	
	
	/*
	// Retrieve workspace from file
	RooWorkspace* w = (RooWorkspace*) f->Get("workspace") ;
	
	w->Print();
	
	///*
	RooRealVar* CMS_zz4l_mass = w->var("CMS_zz4l_mass") ;
	RooAbsPdf* background_nonorm = w->pdf("background_nonorm") ;
	//RooAbsData* backgroundData = w->data("backgroundData") ;
	RooAbsData* data_bkg_red = w->data("data_bkg_red") ;
	
	RooArgSet* obs = data_bkg_red->get() ; 
	RooRealVar* xdata = obs->find(CMS_zz4l_mass.GetName()) ; 
	for (int i=0 ; i<data_bkg_red->numEntries() ; i++) { 
		data_bkg_red->get(i) ; 
		cout << xdata->getVal() << " = " << data_bkg_red->weight() << endl ; 
	} 
	std::cout << "nEntries = " << data_bkg_red->numEntries() << std::endl;
	obs->Print();

	
	RooFitResult *r = background_nonorm->fitTo( *data_bkg_red, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;
	
	// Get parameters
	char varName[192];
	sprintf(varName, "CMS_zz%s_Nbkg", schannel.c_str());
	RooRealVar* Nbkg = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_bkgfrac", schannel.c_str());
	RooRealVar* bkgfrac = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_a1", schannel.c_str());
	RooRealVar* a1 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_a2", schannel.c_str());
	RooRealVar* a2 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_a3", schannel.c_str());
	RooRealVar* a3 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_b1", schannel.c_str());
	RooRealVar* b1 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_b2", schannel.c_str());
	RooRealVar* b2 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_b3", schannel.c_str());
	RooRealVar* b3 = w->var(varName) ;
	
	std::cout << "Nbkg: " << Nbkg->getVal() << std::endl;
	std::cout << "frac_bkg = " << bkgfrac->getVal() << " +/- " << bkgfrac->getError() << std::endl;
	std::cout << "a1 = " << a1->getVal() << " +/- " << a1->getError() << "; ";
	std::cout << "a2 = " << a2->getVal() << " +/- " << a2->getError() << "; ";
	std::cout << "a3 = " << a3->getVal() << " +/- " << a3->getError() << "; " << std::endl;
	std::cout << "b1 = " << b1->getVal() << " +/- " << b1->getError() << "; ";
	std::cout << "b2 = " << b2->getVal() << " +/- " << b2->getError() << "; ";
	std::cout << "b3 = " << b3->getVal() << " +/- " << b3->getError() << "; " << std::endl;
	
	// Plot data and PDF overlaid
	RooPlot* xframe = CMS_zz4l_mass->frame(Title("Model and data read from workspace")) ;
	//backgroundData->plotOn(xframe) ;
	data_bkg_red->plotOn(xframe) ;
	background_nonorm->plotOn(xframe) ;
	
	TCanvas* c = new TCanvas("c","c",800,600);
	c->cd();
	xframe->Draw();
	c->SaveAs(outfile);
	//*/
	
}
Ejemplo n.º 7
0
void drawPlot(string workspaceFilename, string inputFilename, string outFilename, 
                      Int_t EnergyType,
                      Int_t CategoryBin,
                      double minMass, double maxMass, 
                      double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, 
                      const char* plotOpt, const int nbins) {


  TFile *workspaceFile = new TFile(workspaceFilename.c_str(), "read");
  RooWorkspace* w = (RooWorkspace*)workspaceFile->Get("ZeeMassScaleAndResolutionFit");
 
  


  //Create Data Set
  RooRealVar *mass = (RooRealVar*)w->var("mass");

  // Reading everything from root tree instead
  citana::ZeeEventTree *zeeTree = new citana::ZeeEventTree();
  zeeTree->LoadTree(inputFilename.c_str(), citana::ZeeEventTree::kCITZeeEvent);
  
  RooArgSet zMassArgSet(*mass);
  RooDataSet* data = new RooDataSet("data", "ntuple parameters", zMassArgSet);

  for (int i = 0; i < zeeTree->tree_->GetEntries(); i++) {
    zeeTree->tree_->GetEntry(i);

    //*************************************************************************
    //Electron Selection
    //*************************************************************************
    if (!(zeeTree->fEle1PassHZZICHEP2012 == 1 && zeeTree->fEle2PassHZZICHEP2012 == 1)) continue;

    //*************************************************************************
    //Compute electron four vector;
    //*************************************************************************
    double ele1pt = zeeTree->fEle1Pt;
    double ele2pt = zeeTree->fEle2Pt;
    if (EnergyType == 1) {
      ele1pt = zeeTree->fEle1EnergyRegressionWithTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle1Eta);
      ele2pt = zeeTree->fEle2EnergyRegressionWithTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle2Eta);
    }
    else if (EnergyType == 2) {
      ele1pt = zeeTree->fEle1EnergyRegressionWithTrkVar / TMath::CosH(zeeTree->fEle1Eta);
      ele2pt = zeeTree->fEle2EnergyRegressionWithTrkVar / TMath::CosH(zeeTree->fEle2Eta);
    }
    else if (EnergyType == 3) {
      ele1pt = zeeTree->fEle1EnergyRegressionNoTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle1Eta);
      ele2pt = zeeTree->fEle2EnergyRegressionNoTrkVarTwoPtBins / TMath::CosH(zeeTree->fEle2Eta);
    }
    else if (EnergyType == 4) {
      ele1pt = zeeTree->fEle1EnergyRegressionNoTrkVar / TMath::CosH(zeeTree->fEle1Eta);
      ele2pt = zeeTree->fEle2EnergyRegressionNoTrkVar / TMath::CosH(zeeTree->fEle2Eta);
    }
    TLorentzVector ele1FourVector;
    ele1FourVector.SetPtEtaPhiM(ele1pt, zeeTree->fEle1Eta, zeeTree->fEle1Phi, ELECTRONMASS);
    TLorentzVector ele2FourVector;
    ele2FourVector.SetPtEtaPhiM(ele2pt, zeeTree->fEle2Eta, zeeTree->fEle2Phi, ELECTRONMASS);
    
    //*************************************************************************
    //pt and eta cuts on electron
    //*************************************************************************
    if (! (ele1pt > 7 && ele2pt > 7 
           && fabs( zeeTree->fEle1Eta) < 2.5 
           && fabs( zeeTree->fEle2Eta) < 2.5 )) continue;

    //*************************************************************************
    //pt bins and eta bins
    //*************************************************************************
    Int_t Ele1PtBin = -1;
    Int_t Ele1EtaBin = -1;
    Int_t Ele2PtBin = -1;
    Int_t Ele2EtaBin = -1;
    if (ele1pt > 10 && ele1pt < 20) Ele1PtBin = 0;
    else if (ele1pt < 30) Ele1PtBin = 1;
    else if (ele1pt < 40) Ele1PtBin = 2;
    else Ele1PtBin = 3;
    if (ele2pt > 10 && ele2pt < 20) Ele2PtBin = 0;
    else if (ele2pt < 30) Ele2PtBin = 1;
    else if (ele2pt < 40) Ele2PtBin = 2;
    else Ele2PtBin = 3;
    if (fabs(zeeTree->fEle1SCEta) < 1.0) Ele1EtaBin = 0;
    else if (fabs(zeeTree->fEle1SCEta) < 1.479) Ele1EtaBin = 1;
    else Ele1EtaBin = 2;
    if (fabs(zeeTree->fEle2SCEta) < 1.0) Ele2EtaBin = 0;
    else if (fabs(zeeTree->fEle2SCEta) < 1.479) Ele2EtaBin = 1;
    else Ele2EtaBin = 2;

    if (CategoryBin == 0) { 
      if (!(Ele1EtaBin == 0 && Ele2EtaBin == 0)) continue; 
    }
    else if (CategoryBin == 1) {
      if (!(Ele1EtaBin == 1 && Ele2EtaBin == 1)) continue; 
    }
    else if (CategoryBin == 2) {
      if (!(Ele1EtaBin == 2 && Ele2EtaBin == 2)) continue;
    }
    
    //*************************************************************************
    // restrict range of mass
    //*************************************************************************
    double zMass = (ele1FourVector+ele2FourVector).M();
    if (zMass < minMass || zMass > maxMass) continue;

    //*************************************************************************
    //set mass variable
    //*************************************************************************
    zMassArgSet.setRealValue("mass", zMass);

    data->add(zMassArgSet);
  }

  cout << "dataset size: " << data->numEntries() << endl;


  RooRealVar *cbBias = (RooRealVar*)w->var("#Deltam_{CB}");
  RooRealVar *cbSigma = (RooRealVar*)w->var("sigma_{CB}");
  RooRealVar *cbCut   = (RooRealVar*)w->var("a_{CB}");
  RooRealVar *cbPower = (RooRealVar*)w->var("n_{CB}");

//   // Now if it's a restricted fit, fix values of cbCut and cbPower to MC values.
//   if (isRestricted) {
//     cbCut.setConstant(kTRUE);
//     cbPower.setConstant(kTRUE);
//   }

  // Mass model for signal electrons p.d.f.
  RooAddPdf *model = (RooAddPdf*)w->pdf("model");


  TCanvas* c = new TCanvas("c","c", 0,0,800,600);

  //========================== Plotting  ============================
  //Create a frame
  RooPlot* plot = mass->frame(Range(minMass,maxMass),Bins(nbins));
  // Add data and model to canvas
  plot->SetTitle("");
  plot->GetYaxis()->SetTitleOffset(1.4);
  plot->GetXaxis()->SetTitle("m_{ee} (GeV/c^{2})");

  data->plotOn(plot);
  model->plotOn(plot);
//   model->paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(*cbBias, *cbSigma, *cbCut, *cbPower)), Layout(0.60,0.90,0.90));
  model->paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(*cbBias, *cbSigma, *cbCut, *cbPower)), Layout(0.12,0.38,0.60));
  plot->getAttText()->SetTextSize(.025);
  plot->Draw();

  // Print Fit Values
  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(.04);
  tex->SetTextFont(2);
  tex->DrawLatex(0.195,0.775, "Run 2012A/B");
  tex->Draw();
//   tex->SetTextSize(0.022);
//   tex->DrawLatex(0.195, 0.75, "Z #rightarrow ee^{+}");
//   tex->SetTextSize(0.024);
//   tex->DrawLatex(0.645, 0.59, Form("BW Mean = %.2f GeV/c^{2}", bwMean.getVal()));
//   tex->DrawLatex(0.645, 0.54, Form("BW #sigma = %.2f GeV/c^{2}", bwWidth.getVal()));
  c->Update();
  c->SaveAs((outFilename + ".gif").c_str());


}
Ejemplo n.º 8
0
//____________________________________
void DoSPlot(RooWorkspace* ws){
  std::cout << "Calculate sWeights" << std::endl;

  RooAbsPdf* model = ws->pdf("model");
  RooRealVar* nsig = ws->var("nsig");
  RooRealVar* nBbkg = ws->var("nBbkg");
  RooRealVar* nbkg = ws->var("nbkg");
  RooRealVar* nbkg2 = ws->var("nbkg2");
  RooDataSet* data = (RooDataSet*) ws->data("data");

  // fit the model to the data.
  model->fitTo(*data, Extended() );

  RooMsgService::instance().setSilentMode(true);

  // Now we use the SPlot class to add SWeights to our data set
  // based on our model and our yield variables
  RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
					       *data, model, RooArgList(*nsig,*nBbkg,*nbkg,*nbkg2) );


  // Check that our weights have the desired properties

  std::cout << "Check SWeights:" << std::endl;

  std::cout << std::endl <<  "Yield of sig is " 
	    << nsig->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nsig") << std::endl;

  std::cout << std::endl <<  "Yield of Bbkg is " 
	    << nBbkg->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nBbkg") << std::endl;

  std::cout << std::endl <<  "Yield of bkg is " 
	    << nbkg->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nbkg") << std::endl;

  std::cout << std::endl <<  "Yield of bkg2 is " 
	    << nbkg2->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nbkg2") << std::endl;

  cout << endl;   cout << endl;   cout << endl;
  float sum20=0;
  float sum50=0;
  float sum100=0;
  float sum200=0;
  float sum300=0;
  float sum600=0;
  float sum900=0;
  float sum1200=0;
  float total=0;

  // saving weights into a file
  ofstream myfile;
  myfile.open ("weights.txt");
  // plot the weight event by event with the Sum of events values as cross-check
  for(Int_t i=0; i < data->numEntries(); i++) {
      //myfile << sData->GetSWeight(i,"nsig") << " " << sData->GetSWeight(i,"nBbkg") << " " << sData->GetSWeight(i,"nbkg") << " " << sData->GetSWeight(i,"nbkg2") << endl;  
      //myfile << sData->GetSWeight(i,"nsig") <<endl;
    myfile << (unsigned int) data->get(i)->getRealValue("run")
             << " " << (unsigned int) data->get(i)->getRealValue("event")
	   << " " << (float) data->get(i)->getRealValue("FourMu_Mass")
             << " " << sData->GetSWeight(i,"nsig")
             << endl;
     // std::cout << "nsig Weight   " << sData->GetSWeight(i,"nsig") 
     //		<< "   nBbkg Weight   " << sData->GetSWeight(i,"nBbkg")
     //		<< "   nbkg Weight   " << sData->GetSWeight(i,"nbkg")
     //		<< "   nbkg2 Weight  " << sData->GetSWeight(i,"nbkg2")
//		<< "   Total Weight   " << sData->GetSumOfEventSWeight(i) 
//		<< std::endl;
      total+=sData->GetSWeight(i,"nsig");         
      if(i<20) sum20+=sData->GetSWeight(i,"nsig");
      if(i<50) sum50+=sData->GetSWeight(i,"nsig");
      if(i<100) sum100+=sData->GetSWeight(i,"nsig");
      if(i<200) sum200+=sData->GetSWeight(i,"nsig");
      if(i<300) sum300+=sData->GetSWeight(i,"nsig");
      if(i<600) sum600+=sData->GetSWeight(i,"nsig");
      if(i<900) sum900+=sData->GetSWeight(i,"nsig");
      if(i<1200) sum1200+=sData->GetSWeight(i,"nsig");

    }
  myfile.close();

  std::cout << std::endl;

  std::cout<<"Sum of the sWeights is: "<<total<<std::endl;
  std::cout<<"Sum of the first 20 sWeights is: "<<sum20<<std::endl;
  std::cout<<"Sum of the first 50 sWeights is: "<<sum50<<std::endl;
  std::cout<<"Sum of the first 100 sWeights is: "<<sum100<<std::endl;
  std::cout<<"Sum of the first 200 sWeights is: "<<sum200<<std::endl;
  std::cout<<"Sum of the first 300 sWeights is: "<<sum300<<std::endl;
  std::cout<<"Sum of the first 600 sWeights is: "<<sum600<<std::endl;
  std::cout<<"Sum of the first 900 sWeights is: "<<sum900<<std::endl;
  std::cout<<"Sum of the first 1200 sWeights is: "<<sum1200<<std::endl;
  std::cout<<"Total # of events: "<<data->numEntries()<<std::endl;

  // import this new dataset with sWeights
  std::cout << "import new dataset with sWeights" << std::endl;
  ws->import(*data, Rename("dataWithSWeights"));

}
Ejemplo n.º 9
0
// The actual job
void backgroundFits_qqzz_1Dw(int channel, int sqrts, int VBFtag)
{
  if(sqrts==7)return;
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << schannel << endl;

  TString ssqrts = (long) sqrts + TString("TeV");

  cout << "schannel = " << schannel << "  sqrts = " << sqrts << " VBFtag = " << VBFtag << endl;

  TString outfile;
  if(VBFtag<2) outfile = "CardFragments/qqzzBackgroundFit_" + ssqrts + "_" + schannel + "_" + Form("%d",int(VBFtag)) + ".txt";
  if(VBFtag==2) outfile = "CardFragments/qqzzBackgroundFit_" + ssqrts + "_" + schannel + ".txt";
  ofstream of(outfile,ios_base::out);
  of << "### background functions ###" << endl;


  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  gROOT->ProcessLine(".L ../CreateDatacards/include/tdrstyle.cc");
  setTDRStyle(false);
  gStyle->SetPadLeftMargin(0.16);

  TString filepath;
  if (sqrts==7) {
    filepath = filePath7TeV;
  } else if (sqrts==8) {
    filepath = filePath8TeV;
  }

  TChain* tree = new TChain("SelectedTree");
  tree->Add( filepath+ "/" + (schannel=="2e2mu"?"2mu2e":schannel) + "/HZZ4lTree_ZZTo*.root");


  RooRealVar* MC_weight = new RooRealVar("MC_weight","MC_weight",0.,2.) ; 
  RooRealVar* ZZMass = new RooRealVar("ZZMass","ZZMass",100.,1000.);
  RooRealVar* NJets30 = new RooRealVar("NJets30","NJets30",0.,100.);
  RooArgSet ntupleVarSet(*ZZMass,*NJets30,*MC_weight);
  RooDataSet *set = new RooDataSet("set","set",ntupleVarSet,WeightVar("MC_weight"));

  Float_t myMC,myMass;
  Short_t myNJets;
  int nentries = tree->GetEntries();

  tree->SetBranchAddress("ZZMass",&myMass);
  tree->SetBranchAddress("MC_weight",&myMC);
  tree->SetBranchAddress("NJets30",&myNJets);

  for(int i =0;i<nentries;i++) {
    tree->GetEntry(i);
    if(VBFtag==1 && myNJets<2)continue;
    if(VBFtag==0 && myNJets>1)continue;

    ntupleVarSet.setRealValue("ZZMass",myMass);
    ntupleVarSet.setRealValue("MC_weight",myMC);
    ntupleVarSet.setRealValue("NJets30",(double)myNJets);

    set->add(ntupleVarSet, myMC);
  }

  double totalweight = 0.;
  double totalweight_z = 0.;
  for (int i=0 ; i<set->numEntries() ; i++) { 
    //set->get(i) ; 
    RooArgSet* row = set->get(i) ;
    //row->Print("v");
    totalweight += set->weight();
    if (row->getRealValue("ZZMass") < 200) totalweight_z += set->weight();
  } 
  cout << "nEntries: " << set->numEntries() << ", totalweight: " << totalweight << ", totalweight_z: " << totalweight_z << endl;

  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
	
  //// ---------------------------------------
  //Background
  RooRealVar CMS_qqzzbkg_a0("CMS_qqzzbkg_a0","CMS_qqzzbkg_a0",115.3,0.,200.);
  RooRealVar CMS_qqzzbkg_a1("CMS_qqzzbkg_a1","CMS_qqzzbkg_a1",21.96,0.,200.);
  RooRealVar CMS_qqzzbkg_a2("CMS_qqzzbkg_a2","CMS_qqzzbkg_a2",122.8,0.,200.);
  RooRealVar CMS_qqzzbkg_a3("CMS_qqzzbkg_a3","CMS_qqzzbkg_a3",0.03479,0.,1.);
  RooRealVar CMS_qqzzbkg_a4("CMS_qqzzbkg_a4","CMS_qqzzbkg_a4",185.5,0.,200.);
  RooRealVar CMS_qqzzbkg_a5("CMS_qqzzbkg_a5","CMS_qqzzbkg_a5",12.67,0.,200.);
  RooRealVar CMS_qqzzbkg_a6("CMS_qqzzbkg_a6","CMS_qqzzbkg_a6",34.81,0.,100.);
  RooRealVar CMS_qqzzbkg_a7("CMS_qqzzbkg_a7","CMS_qqzzbkg_a7",0.1393,0.,1.);
  RooRealVar CMS_qqzzbkg_a8("CMS_qqzzbkg_a8","CMS_qqzzbkg_a8",66.,0.,200.);
  RooRealVar CMS_qqzzbkg_a9("CMS_qqzzbkg_a9","CMS_qqzzbkg_a9",0.07191,0.,1.);
  RooRealVar CMS_qqzzbkg_a10("CMS_qqzzbkg_a10","CMS_qqzzbkg_a10",94.11,0.,200.);
  RooRealVar CMS_qqzzbkg_a11("CMS_qqzzbkg_a11","CMS_qqzzbkg_a11",-5.111,-100.,100.);
  RooRealVar CMS_qqzzbkg_a12("CMS_qqzzbkg_a12","CMS_qqzzbkg_a12",4834,0.,10000.);
  RooRealVar CMS_qqzzbkg_a13("CMS_qqzzbkg_a13","CMS_qqzzbkg_a13",0.2543,0.,1.);
	
  if (channel == 1){
    ///* 4mu
    CMS_qqzzbkg_a0.setVal(103.854);
    CMS_qqzzbkg_a1.setVal(10.0718);
    CMS_qqzzbkg_a2.setVal(117.551);
    CMS_qqzzbkg_a3.setVal(0.0450287);
    CMS_qqzzbkg_a4.setVal(185.262);
    CMS_qqzzbkg_a5.setVal(7.99428);
    CMS_qqzzbkg_a6.setVal(39.7813);
    CMS_qqzzbkg_a7.setVal(0.0986891);
    CMS_qqzzbkg_a8.setVal(49.1325);
    CMS_qqzzbkg_a9.setVal(0.0389984);
    CMS_qqzzbkg_a10.setVal(98.6645);
    CMS_qqzzbkg_a11.setVal(-7.02043);
    CMS_qqzzbkg_a12.setVal(5694.66);
    CMS_qqzzbkg_a13.setVal(0.0774525);
    //*/
  }
  else if (channel == 2){
    ///* 4e
    CMS_qqzzbkg_a0.setVal(111.165);
    CMS_qqzzbkg_a1.setVal(19.8178);
    CMS_qqzzbkg_a2.setVal(120.89);
    CMS_qqzzbkg_a3.setVal(0.0546639);
    CMS_qqzzbkg_a4.setVal(184.878);
    CMS_qqzzbkg_a5.setVal(11.7041);
    CMS_qqzzbkg_a6.setVal(33.2659);
    CMS_qqzzbkg_a7.setVal(0.140858);
    CMS_qqzzbkg_a8.setVal(56.1226);
    CMS_qqzzbkg_a9.setVal(0.0957699);
    CMS_qqzzbkg_a10.setVal(98.3662);
    CMS_qqzzbkg_a11.setVal(-6.98701);
    CMS_qqzzbkg_a12.setVal(10.0536);
    CMS_qqzzbkg_a13.setVal(0.110576);
    //*/
  }
  else if (channel == 3){
    ///* 2e2mu
    CMS_qqzzbkg_a0.setVal(110.293);
    CMS_qqzzbkg_a1.setVal(11.8334);
    CMS_qqzzbkg_a2.setVal(116.91);
    CMS_qqzzbkg_a3.setVal(0.0433151);
    CMS_qqzzbkg_a4.setVal(185.817);
    CMS_qqzzbkg_a5.setVal(10.5945);
    CMS_qqzzbkg_a6.setVal(29.6208);
    CMS_qqzzbkg_a7.setVal(0.0826);
    CMS_qqzzbkg_a8.setVal(53.1346);
    CMS_qqzzbkg_a9.setVal(0.0882081);
    CMS_qqzzbkg_a10.setVal(85.3776);
    CMS_qqzzbkg_a11.setVal(-13.3836);
    CMS_qqzzbkg_a12.setVal(7587.95);
    CMS_qqzzbkg_a13.setVal(0.325621);
    //*/
  }
  else {
    cout << "disaster" << endl;
  }
    
  RooqqZZPdf_v2* bkg_qqzz = new RooqqZZPdf_v2("bkg_qqzz","bkg_qqzz",*ZZMass,
					      CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
					      CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7,CMS_qqzzbkg_a8,
					      CMS_qqzzbkg_a9,CMS_qqzzbkg_a10,CMS_qqzzbkg_a11,CMS_qqzzbkg_a12,CMS_qqzzbkg_a13);
  RooArgSet myASet(*ZZMass, CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
		   CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7);
  myASet.add(CMS_qqzzbkg_a8);
  myASet.add(CMS_qqzzbkg_a9);
  myASet.add(CMS_qqzzbkg_a10);
  myASet.add(CMS_qqzzbkg_a11);
  myASet.add(CMS_qqzzbkg_a12);
  myASet.add(CMS_qqzzbkg_a13);
 
  RooFitResult *r1 = bkg_qqzz->fitTo( *set, Save(kTRUE), SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

  cout << endl;
  cout << "------- Parameters for " << schannel << " sqrts=" << sqrts << endl;
  cout << "  a0_bkgd = " << CMS_qqzzbkg_a0.getVal() << endl;
  cout << "  a1_bkgd = " << CMS_qqzzbkg_a1.getVal() << endl;
  cout << "  a2_bkgd = " << CMS_qqzzbkg_a2.getVal() << endl;
  cout << "  a3_bkgd = " << CMS_qqzzbkg_a3.getVal() << endl;
  cout << "  a4_bkgd = " << CMS_qqzzbkg_a4.getVal() << endl;
  cout << "  a5_bkgd = " << CMS_qqzzbkg_a5.getVal() << endl;
  cout << "  a6_bkgd = " << CMS_qqzzbkg_a6.getVal() << endl;
  cout << "  a7_bkgd = " << CMS_qqzzbkg_a7.getVal() << endl;
  cout << "  a8_bkgd = " << CMS_qqzzbkg_a8.getVal() << endl;
  cout << "  a9_bkgd = " << CMS_qqzzbkg_a9.getVal() << endl;
  cout << "  a10_bkgd = " << CMS_qqzzbkg_a10.getVal() << endl;
  cout << "  a11_bkgd = " << CMS_qqzzbkg_a11.getVal() << endl;
  cout << "  a12_bkgd = " << CMS_qqzzbkg_a12.getVal() << endl;
  cout << "  a13_bkgd = " << CMS_qqzzbkg_a13.getVal() << endl;
  cout << "}" << endl;
  cout << "---------------------------" << endl;


  of << "qqZZshape a0_bkgd   " << CMS_qqzzbkg_a0.getVal() << endl;
  of << "qqZZshape a1_bkgd   " << CMS_qqzzbkg_a1.getVal() << endl;
  of << "qqZZshape a2_bkgd   " << CMS_qqzzbkg_a2.getVal() << endl;
  of << "qqZZshape a3_bkgd   " << CMS_qqzzbkg_a3.getVal() << endl;
  of << "qqZZshape a4_bkgd   " << CMS_qqzzbkg_a4.getVal() << endl;
  of << "qqZZshape a5_bkgd   " << CMS_qqzzbkg_a5.getVal() << endl;
  of << "qqZZshape a6_bkgd   " << CMS_qqzzbkg_a6.getVal() << endl;
  of << "qqZZshape a7_bkgd   " << CMS_qqzzbkg_a7.getVal() << endl;
  of << "qqZZshape a8_bkgd   " << CMS_qqzzbkg_a8.getVal() << endl;
  of << "qqZZshape a9_bkgd   " << CMS_qqzzbkg_a9.getVal() << endl;
  of << "qqZZshape a10_bkgd  " << CMS_qqzzbkg_a10.getVal() << endl;
  of << "qqZZshape a11_bkgd  " << CMS_qqzzbkg_a11.getVal() << endl;
  of << "qqZZshape a12_bkgd  " << CMS_qqzzbkg_a12.getVal() << endl;
  of << "qqZZshape a13_bkgd  " << CMS_qqzzbkg_a13.getVal() << endl;
  of << endl << endl;
  of.close();

  cout << endl << "Output written to: " << outfile << endl;
  
    
  double qqzznorm;
  if (channel == 1) qqzznorm = 20.5836;
  else if (channel == 2) qqzznorm = 13.8871;
  else if (channel == 3) qqzznorm = 32.9883;
  else { cout << "disaster!" << endl; }

  ZZMass->setRange("fullrange",100.,1000.);
  ZZMass->setRange("largerange",100.,600.);
  ZZMass->setRange("zoomrange",100.,200.);
    
  double rescale = qqzznorm/totalweight;
  double rescale_z = qqzznorm/totalweight_z;
  cout << "rescale: " << rescale << ", rescale_z: " << rescale_z << endl;


  // Plot m4l and
  RooPlot* frameM4l = ZZMass->frame(Title("M4L"),Range(100,600),Bins(250)) ;
  set->plotOn(frameM4l, MarkerStyle(20), Rescale(rescale)) ;
  
  //set->plotOn(frameM4l) ;
  RooPlot* frameM4lz = ZZMass->frame(Title("M4L"),Range(100,200),Bins(100)) ;
  set->plotOn(frameM4lz, MarkerStyle(20), Rescale(rescale)) ;


  int iLineColor = 1;
  string lab = "blah";
  if (channel == 1) { iLineColor = 2; lab = "4#mu"; }
  if (channel == 3) { iLineColor = 4; lab = "2e2#mu"; }
  if (channel == 2) { iLineColor = 6; lab = "4e"; }

  bkg_qqzz->plotOn(frameM4l,LineColor(iLineColor),NormRange("largerange")) ;
  bkg_qqzz->plotOn(frameM4lz,LineColor(iLineColor),NormRange("zoomrange")) ;
    
//second shape to compare with (if previous comparison code unceommented)
  //bkg_qqzz_bkgd->plotOn(frameM4l,LineColor(1),NormRange("largerange")) ;
  //bkg_qqzz_bkgd->plotOn(frameM4lz,LineColor(1),NormRange("zoomrange")) ;
    
  
  double normalizationBackground_qqzz = bkg_qqzz->createIntegral( RooArgSet(*ZZMass), Range("fullrange") )->getVal();
  cout << "Norm all = " << normalizationBackground_qqzz << endl;
    
  frameM4l->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4l->GetYaxis()->SetTitle("a.u.");
  frameM4lz->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4lz->GetYaxis()->SetTitle("a.u.");

  char lname[192];
  sprintf(lname,"qq #rightarrow ZZ #rightarrow %s", lab.c_str() );
  char lname2[192];
  sprintf(lname2,"Shape Model, %s", lab.c_str() );
  // dummy!
  TF1* dummyF = new TF1("dummyF","1",0.,1.);
  TH1F* dummyH = new TH1F("dummyH","",1, 0.,1.);
  dummyF->SetLineColor( iLineColor );
  dummyF->SetLineWidth( 2 );

  dummyH->SetLineColor( kBlue );
  TLegend * box2 = new TLegend(0.4,0.70,0.80,0.90);
  box2->SetFillColor(0);
  box2->SetBorderSize(0);
  box2->AddEntry(dummyH,"Simulation (POWHEG+Pythia)  ","pe");
  box2->AddEntry(dummyH,lname,"");
  box2->AddEntry(dummyH,"","");
  box2->AddEntry(dummyF,lname2,"l");
    
  TPaveText *pt = new TPaveText(0.15,0.955,0.4,0.99,"NDC");
  pt->SetFillColor(0);
  pt->SetBorderSize(0);
  pt->AddText("CMS Preliminary 2012");
  TPaveText *pt2 = new TPaveText(0.84,0.955,0.99,0.99,"NDC");
  pt2->SetFillColor(0);
  pt2->SetBorderSize(0);
  TString entag;entag.Form("#sqrt{s} = %d TeV",sqrts);
  pt2->AddText(entag.Data());

  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  frameM4l->GetYaxis()->SetRangeUser(0,0.4);
  if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.7);
  box2->Draw();
  pt->Draw();
  pt2->Draw();
  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  if(VBFtag<2) outputName =  outputPath + "bkgqqzz_" + schannel + "_" + Form("%d",int(VBFtag));
  if(VBFtag==2) outputName =  outputPath + "bkgqqzz_" + schannel;
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
    
  TCanvas *c2 = new TCanvas("c2","c2",1000,500);
  c2->Divide(2,1);
  c2->cd(1);
  frameM4l->Draw();
  box2->Draw("same");
  c2->cd(2);
  frameM4lz->Draw();
  box2->Draw("same");
  
  if (VBFtag<2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + "_" + Form("%d",int(VBFtag));
  if (VBFtag==2) outputName = outputPath + "bkgqqzz_" + schannel + "_z";
  c2->SaveAs(outputName + ".eps");
  c2->SaveAs(outputName + ".png");

  /* TO make the ratio btw 2 shapes, if needed for compairson
  TCanvas *c3 = new TCanvas("c3","c3",1000,500);
   if(sqrts==7)
    sprintf(outputName, "bkgFigs7TeV/bkgqqzz_%s_ratio.eps",schannel.c_str());
  else if(sqrts==8)
    sprintf(outputName, "bkgFigs8TeV/bkgqqzz_%s_ratio.eps",schannel.c_str());

   const int nPoints = 501.;
  double masses[nPoints] ;
  int j=0;
  for (int i=100; i<601; i++){
    masses[j] = i;
    j++;
  }
  cout<<j<<endl;
  double effDiff[nPoints];
  for (int i = 0; i < nPoints; i++){
    ZZMass->setVal(masses[i]);
    double eval = (bkg_qqzz_bkgd->getVal(otherASet)-bkg_qqzz->getVal(myASet))/(bkg_qqzz->getVal(myASet));
    //cout<<bkg_qqzz_bkgd->getVal(otherASet)<<" "<<bkg_qqzz->getVal(myASet)<<" "<<eval<<endl;
    effDiff[i]=eval;
  }
  TGraph* grEffDiff = new TGraph( nPoints, masses, effDiff );
  grEffDiff->SetMarkerStyle(20);
  grEffDiff->Draw("AL");

  //c3->SaveAs(outputName);
  */

  if (VBFtag<2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + "_" + Form("%d",int(VBFtag)) + ".root";
  if (VBFtag==2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + ".root";
  TFile* outF = new TFile(outputName,"RECREATE");
  outF->cd();
  c2->Write();
  frameM4l->Write();
  frameM4lz->Write();	
  outF->Close();


  delete c;
  delete c2;
}
Ejemplo n.º 10
0
// The actual job
void backgroundFits_ggzz_1Dw(int channel, int sqrts, int VBFtag)
{
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << schannel << endl;

  TString ssqrts = (long) sqrts + TString("TeV");

  cout << "schannel = " << schannel << "  sqrts = " << sqrts << " VBFtag = "<< VBFtag << endl;

  TString outfile;
  outfile = "CardFragments/ggzzBackgroundFit_" + ssqrts + "_" + schannel + "_" + Form("%d",int(VBFtag)) + ".txt";
  ofstream of(outfile,ios_base::out);

  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  gROOT->ProcessLine(".L ../CreateDatacards/include/tdrstyle.cc");
  setTDRStyle(false);
  gStyle->SetPadLeftMargin(0.16);
	
  TString filepath;filepath.Form("AAAOK/ZZ%s/ZZ4lAnalysis.root",schannel.Data());
  TFile *f = TFile::Open(filepath);
  TTree *tree = f->Get("ZZTree/candTree");

  RooRealVar* MC_weight = new RooRealVar("MC_weight","MC_weight",0.,2.) ; 
  RooRealVar* ZZMass = new RooRealVar("ZZMass","ZZMass",100,100.,1000.);
  RooRealVar* NJets30 = new RooRealVar("NJets30","NJets30",0.,5.);
  RooArgSet ntupleVarSet(*ZZMass,*NJets30,*MC_weight);
  RooDataSet *set = new RooDataSet("set","set",ntupleVarSet,WeightVar("MC_weight"));
  //RooArgSet ntupleVarSet(*ZZMass,*NJets30);  
  //RooDataSet *set = new RooDataSet("set","set",ntupleVarSet);

  Float_t myMC,myMass;
  Int_t myNJets;
  int nentries = tree->GetEntries();

  Float_t myPt,myJetPt,myJetEta,myJetPhi,myJetMass,myFisher;
  Int_t myExtralep,myBJets;
  tree->SetBranchAddress("ZZMass",&myMass);
  tree->SetBranchAddress("genHEPMCweight",&myMC);
  tree->SetBranchAddress("nCleanedJetsPt30",&myNJets);
  tree->SetBranchAddress("ZZPt",&myPt);
  tree->SetBranchAddress("nExtraLep",&myExtralep);
  tree->SetBranchAddress("nCleanedJetsPt30BTagged",&myBJets);
  tree->SetBranchAddress("DiJetDEta",&myFisher);

  for(int i =0;i<nentries;i++) {
    tree->GetEntry(i);
    if(myMass<100.)continue;
    int cat = category(myExtralep,myPt, myMass,myNJets, myBJets,/* jetpt, jeteta, jetphi, jetmass,*/myFisher);
    if(VBFtag != cat )continue;

    ntupleVarSet.setRealValue("ZZMass",myMass);
    ntupleVarSet.setRealValue("MC_weight",myMC);
    ntupleVarSet.setRealValue("NJets30",(double)cat);

    set->add(ntupleVarSet, myMC);
  }

  //RooRealVar* ZZLD = new RooRealVar("ZZLD","ZZLD",0.,1.);
  //char cut[10];
  //sprintf(cut,"ZZLD>0.5");
  //RooDataSet* set = new RooDataSet("set","set",tree,RooArgSet(*ZZMass,*MC_weight,*ZZLD),cut,"MC_weight");

  double totalweight = 0.;
  for (int i=0 ; i<set->numEntries() ; i++) { 
    set->get(i) ; 
    totalweight += set->weight();
    //cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
  } 
  cout << "nEntries: " << set->numEntries() << ", totalweight: " << totalweight << endl;
		
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
	
  //// ---------------------------------------
  //Background
  RooRealVar CMS_qqzzbkg_a0("CMS_qqzzbkg_a0","CMS_qqzzbkg_a0",115.3,0.,200.);
  RooRealVar CMS_qqzzbkg_a1("CMS_qqzzbkg_a1","CMS_qqzzbkg_a1",21.96,0.,200.);
  RooRealVar CMS_qqzzbkg_a2("CMS_qqzzbkg_a2","CMS_qqzzbkg_a2",122.8,0.,200.);
  RooRealVar CMS_qqzzbkg_a3("CMS_qqzzbkg_a3","CMS_qqzzbkg_a3",0.03479,0.,1.);
  RooRealVar CMS_qqzzbkg_a4("CMS_qqzzbkg_a4","CMS_qqzzbkg_a4",185.5,0.,200.);
  RooRealVar CMS_qqzzbkg_a5("CMS_qqzzbkg_a5","CMS_qqzzbkg_a5",12.67,0.,200.);
  RooRealVar CMS_qqzzbkg_a6("CMS_qqzzbkg_a6","CMS_qqzzbkg_a6",34.81,0.,100.);
  RooRealVar CMS_qqzzbkg_a7("CMS_qqzzbkg_a7","CMS_qqzzbkg_a7",0.1393,0.,1.);
  RooRealVar CMS_qqzzbkg_a8("CMS_qqzzbkg_a8","CMS_qqzzbkg_a8",66.,0.,200.);
  RooRealVar CMS_qqzzbkg_a9("CMS_qqzzbkg_a9","CMS_qqzzbkg_a9",0.07191,0.,1.);
	
  RooggZZPdf_v2* bkg_ggzz = new RooggZZPdf_v2("bkg_ggzz","bkg_ggzz",*ZZMass,
					      CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
					      CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7,CMS_qqzzbkg_a8,CMS_qqzzbkg_a9);
	
  //// ---------------------------------------
	
  RooFitResult *r1 = bkg_ggzz->fitTo( *set, Save(kTRUE), SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

  cout << endl;
  cout << "------- Parameters for " << schannel << " sqrts=" << sqrts << endl;
  cout << "  a0_bkgd = " << CMS_qqzzbkg_a0.getVal() << endl;
  cout << "  a1_bkgd = " << CMS_qqzzbkg_a1.getVal() << endl;
  cout << "  a2_bkgd = " << CMS_qqzzbkg_a2.getVal() << endl;
  cout << "  a3_bkgd = " << CMS_qqzzbkg_a3.getVal() << endl;
  cout << "  a4_bkgd = " << CMS_qqzzbkg_a4.getVal() << endl;
  cout << "  a5_bkgd = " << CMS_qqzzbkg_a5.getVal() << endl;
  cout << "  a6_bkgd = " << CMS_qqzzbkg_a6.getVal() << endl;
  cout << "  a7_bkgd = " << CMS_qqzzbkg_a7.getVal() << endl;
  cout << "  a8_bkgd = " << CMS_qqzzbkg_a8.getVal() << endl;
  cout << "  a9_bkgd = " << CMS_qqzzbkg_a9.getVal() << endl;
  cout << "---------------------------" << endl << endl;  

  of << "ggZZshape a0_bkgd  " << CMS_qqzzbkg_a0.getVal() << endl;
  of << "ggZZshape a1_bkgd  " << CMS_qqzzbkg_a1.getVal() << endl;
  of << "ggZZshape a2_bkgd  " << CMS_qqzzbkg_a2.getVal() << endl;
  of << "ggZZshape a3_bkgd  " << CMS_qqzzbkg_a3.getVal() << endl;
  of << "ggZZshape a4_bkgd  " << CMS_qqzzbkg_a4.getVal() << endl;
  of << "ggZZshape a5_bkgd  " << CMS_qqzzbkg_a5.getVal() << endl;
  of << "ggZZshape a6_bkgd  " << CMS_qqzzbkg_a6.getVal() << endl;
  of << "ggZZshape a7_bkgd  " << CMS_qqzzbkg_a7.getVal() << endl;
  of << "ggZZshape a8_bkgd  " << CMS_qqzzbkg_a8.getVal() << endl;
  of << "ggZZshape a9_bkgd  " << CMS_qqzzbkg_a9.getVal() << endl;
  of << endl;
  of.close();

  cout << endl << "Output written to: " << outfile << endl;

  int iLineColor = 1;
  string lab = "blah";
  if (channel == 1) { iLineColor = 2; lab = "4#mu"; }
  if (channel == 3) { iLineColor = 4; lab = "2e2#mu"; }
  if (channel == 2) { iLineColor = 6; lab = "4e"; }
  char lname[192];
  sprintf(lname,"gg #rightarrow ZZ #rightarrow %s", lab.c_str() );
  char lname2[192];
  sprintf(lname2,"Shape Model, %s", lab.c_str() );
  // dummy!                                                                                                                                               
  TF1* dummyF = new TF1("dummyF","1",0.,1.);
  TH1F* dummyH = new TH1F("dummyH","",1, 0.,1.);
  dummyF->SetLineColor( iLineColor );
  dummyF->SetLineWidth( 2 );
  
  TLegend * box2 = new TLegend(0.5,0.70,0.90,0.90);
  box2->SetFillColor(0);
  box2->SetBorderSize(0);
  box2->AddEntry(dummyH,"Simulation (GG2ZZ)  ","pe");
  box2->AddEntry(dummyH,lname,"");
  box2->AddEntry(dummyH,"","");
  box2->AddEntry(dummyF,lname2,"l");

  TPaveText *pt = new TPaveText(0.15,0.955,0.4,0.99,"NDC");
  pt->SetFillColor(0);
  pt->SetBorderSize(0);
  pt->AddText("CMS Preliminary 2012");
  TPaveText *pt2 = new TPaveText(0.84,0.955,0.99,0.99,"NDC");
  pt2->SetFillColor(0);
  pt2->SetBorderSize(0);

  // Plot m4l and 
  RooPlot* frameM4l = ZZMass->frame(Title("M4L"),Bins(200)) ;
  set->plotOn(frameM4l, MarkerStyle(24)) ;
  bkg_ggzz->plotOn(frameM4l,LineColor(iLineColor)) ;
  set->plotOn(frameM4l) ;

  //comaprison with different shape, if needed (uncommenting also the code above)
  //bkg_ggzz_bkgd->plotOn(frameM4l,LineColor(1),NormRange("largerange")) ;

  frameM4l->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4l->GetYaxis()->SetTitle("a.u.");
  //frameM4l->GetYaxis()->SetRangeUser(0,0.03);
  //if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.05);
  //if(VBFtag<2){
  //  if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.01);
  //  else frameM4l->GetYaxis()->SetRangeUser(0,0.005);
  //}
  frameM4l->GetXaxis()->SetRangeUser(100,1000);
  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  box2->Draw();
  pt->Draw();
  pt2->Draw();

  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  outputName =  outputPath + "bkgggzz_" + schannel + "_" + Form("%d",int(VBFtag));
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
  c->SaveAs(outputName + ".root");
  delete c;

  frameM4l->GetXaxis()->SetRangeUser(100,200);
  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  box2->Draw();
  pt->Draw();
  pt2->Draw();

  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  outputName =  outputPath + "bkgggzz_lowZoom_" + schannel + "_" + Form("%d",int(VBFtag));
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
  c->SaveAs(outputName + ".root");
  delete c;
} 
Ejemplo n.º 11
0
int main() {

  TFile *tf = TFile::Open("root/MassFitResult.root");
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");

  RooDataSet *data = (RooDataSet*)w->data("Data2012HadronTOS");
  //w->loadSnapshot("bs2kstkst_mc_pdf_fit");

  //RooRealVar *bs2kstkst_l      = new RooRealVar("bs2kstkst_l"      , "", -5., -20., 0.);
  //RooConstVar *bs2kstkst_zeta  = new RooConstVar("bs2kstkst_zeta" , "", 0.);
  //RooConstVar *bs2kstkst_fb    = new RooConstVar("bs2kstkst_fb"   , "", 0.);
  //RooRealVar *bs2kstkst_sigma  = new RooRealVar("bs2kstkst_sigma"  , "", 15, 10, 100);
  //RooRealVar *bs2kstkst_mu     = new RooRealVar("bs2kstkst_mu"     , "", 5350, 5400 );
  //RooRealVar *bs2kstkst_a      = new RooRealVar("bs2kstkst_a"      , "", 2.5,0,10);
  //RooRealVar *bs2kstkst_n      = new RooRealVar("bs2kstkst_n"      , "", 2.5,0,10);
  //RooRealVar *bs2kstkst_a2     = new RooRealVar("bs2kstkst_a2"     , "", 2.5,0,10);
  //RooRealVar *bs2kstkst_n2     = new RooRealVar("bs2kstkst_n2"     , "", 2.5,0,10);

  //RooIpatia2 *sig = new RooIpatia2("sig","",*w->var("B_s0_DTF_B_s0_M"), *bs2kstkst_l, *bs2kstkst_zeta, *bs2kstkst_fb, *bs2kstkst_sigma, *bs2kstkst_mu, *bs2kstkst_a, *bs2kstkst_n, *bs2kstkst_a2, *bs2kstkst_n2);
  //RooAbsPdf *sig = (RooAbsPdf*)w->pdf("bs2kstkst_mc_pdf");
  RooIpatia2 *sig = new RooIpatia2("bs2kstkst_mc_pdf","bs2kstkst_mc_pdf",*w->var("B_s0_DTF_B_s0_M"),*w->var("bs2kstkst_l"),*w->var("bs2kstkst_zeta"),*w->var("bs2kstkst_fb"),*w->var("bs2kstkst_sigma"),*w->var("bs2kstkst_mu"),*w->var("bs2kstkst_a"),*w->var("bs2kstkst_n"),*w->var("bs2kstkst_a2"),*w->var("bs2kstkst_n2"));

  RooAbsPdf *bkg = (RooAbsPdf*)w->pdf("bkg_pdf_HadronTOS2012");

  RooRealVar *sY = (RooRealVar*)w->var("bs2kstkst_y_HadronTOS2012");
  RooRealVar *bY = (RooRealVar*)w->var("bkg_y_HadronTOS2012");

  cout << sig << bkg << sY << bY << endl;

  RooAddPdf *pdf = new RooAddPdf("test","test", RooArgList(*sig,*bkg), RooArgList(*sY,*bY) );

  pdf->fitTo(*data, Extended() );

  // my sw
  double syVal = sY->getVal();
  double byVal = bY->getVal();

  // loop events
  int numevents = data->numEntries();

  sY->setVal(0.);
  bY->setVal(0.);

  RooArgSet *pdfvars = pdf->getVariables();

  vector<double> fsvals;
  vector<double> fbvals;

  for ( int ievt=0; ievt<numevents; ievt++ ) {

    RooStats::SetParameters(data->get(ievt), pdfvars);

    sY->setVal(1.);
    double f_s = pdf->getVal( RooArgSet(*w->var("B_s0_DTF_B_s0_M")) );
    fsvals.push_back(f_s);
    sY->setVal(0.);

    bY->setVal(1.);
    double f_b = pdf->getVal( RooArgSet(*w->var("B_s0_DTF_B_s0_M")) );
    fbvals.push_back(f_b);
    bY->setVal(0.);

    //cout << f_s << " " << f_b << endl;

  }

  TMatrixD covInv(2,2);
  covInv[0][0] = 0;
  covInv[0][1] = 0;
  covInv[1][0] = 0;
  covInv[1][1] = 0;

  for ( int ievt=0; ievt<numevents; ievt++ ) {
    data->get(ievt);
    double dsum=0;
    dsum += fsvals[ievt] * syVal;
    dsum += fbvals[ievt] * byVal;

    covInv[0][0] += fsvals[ievt]*fsvals[ievt] / (dsum*dsum);
    covInv[0][1] += fsvals[ievt]*fbvals[ievt] / (dsum*dsum);
    covInv[1][0] += fbvals[ievt]*fsvals[ievt] / (dsum*dsum);
    covInv[1][1] += fbvals[ievt]*fbvals[ievt] / (dsum*dsum);

  }

  covInv.Print();

  cout << covInv.Determinant() << endl;

  TMatrixD covMatrix(TMatrixD::kInverted,covInv);

  covMatrix.Print();

  RooStats::SPlot *sD = new RooStats::SPlot("sD","sD",*data,pdf,RooArgSet(*sY,*bY),RooArgSet(*w->var("eventNumber")));
}
Ejemplo n.º 12
0
void IntervalExamples()
{

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


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

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

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

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

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

   // set confidence level
   double confidenceLevel = 0.95;

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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


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


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

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

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

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

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

   canvas->Update();

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

}
Ejemplo n.º 13
0
void embeddedToysVBF_1DKD(int nEvts=50, int nToys=100,
		  sample mySample = kScalar_fa3_0){
  

  RooRealVar* kd = new RooRealVar("psMELA","psMELA",0,1);
  kd->setBins(50);
  RooPlot* kdframe1 = kd->frame();
  
  // 0- template
  TFile f1("ggH2j_KDdistribution_ps.root", "READ"); 
  TH2F *h_KD_ps = (TH2F*)f1.Get("h_KD");
  h_KD_ps->SetName("h_KD_ps");
  RooDataHist rdh_KD_ps("rdh_KD_ps","rdh_KD_ps",RooArgList(*kd),h_KD_ps);
  RooHistPdf pdf_KD_ps("pdf_KD_ps","pdf_KD_ps",RooArgList(*kd),rdh_KD_ps); 

  // 0+ template
  TFile f2("ggH2j_KDdistribution_sm.root", "READ"); 
  TH2F *h_KD_sm = (TH2F*)f2.Get("h_KD");
  h_KD_sm->SetName("h_KD_sm");
  RooDataHist rdh_KD_sm("rdh_KD_sm","rdh_KD_sm",RooArgList(*kd),h_KD_sm);
  RooHistPdf pdf_KD_sm("pdf_KD_sm","pdf_KD_sm",RooArgList(*kd),rdh_KD_sm); 

  RooRealVar rrv_fa3("fa3","fa3",0.5,0.,1.);  //free parameter of the model
  RooAddPdf model("model","ps+sm",pdf_KD_ps,pdf_KD_sm,rrv_fa3);  
  rrv_fa3.setConstant(kFALSE);

 TCanvas* c = new TCanvas("modelPlot","modelPlot",400,400);
  rdh_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  pdf_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  rdh_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  pdf_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  model.plotOn(kdframe1,LineColor(kRed));
  kdframe1->Draw();
  c->SaveAs("model1DPlot.png");
  c->SaveAs("model1DPlot.eps");

  double fa3Val=-99;
  if (mySample == kScalar_fa3_0)
    fa3Val=0.;
  else if (mySample == kScalar_fa3_1)
    fa3Val=1;
  else{
    cout<<"fa3Val not correct!"<<endl;
      return 0;
  }

  TCanvas* c = new TCanvas("modelPlot","modelPlot",400,400);
  rdh_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  pdf_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  rdh_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  pdf_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  model.plotOn(kdframe1,LineColor(kRed));
  kdframe1->Draw();

  
  TChain* myChain = new TChain("newTree");
  myChain->Add(inputFileNames[mySample]);
  
  if(!myChain || myChain->GetEntries()<=0) {
    cout<<"error in the tree"<<endl;
    return 0;
  }
  
   RooDataSet* data = new RooDataSet("data","data",myChain,RooArgSet(*kd),"");

    cout << "Number of events in data: " << data->numEntries() << endl;
  
  // initialize tree to save toys to 
  TTree* results = new TTree("results","toy results");
  
  double fa3,fa3Error, fa3Pull;
  double fa2,fa2Error, fa2Pull;
  double phia2, phia2Error, phia2Pull;
  double phia3, phia3Error, phia3Pull;

  results->Branch("fa3",&fa3,"fa3/D");
  results->Branch("fa3Error",&fa3Error,"fa3Error/D");
  results->Branch("fa3Pull",&fa3Pull,"fa3Pull/D");

  //---------------------------------

  RooDataSet* toyData;
  int embedTracker=0;
  RooArgSet *tempEvent;

  RooFitResult *toyfitresults;
  RooRealVar *r_fa3;

  for(int i = 0 ; i<nToys ; i++){
    cout <<i<<"<-----------------------------"<<endl;
    //if(toyData) delete toyData;
    toyData = new RooDataSet("toyData","toyData",RooArgSet(*kd));

    if(nEvts+embedTracker > data->sumEntries()){
      cout << "Playground::generate() - ERROR!!! Playground::data does not have enough events to fill toy!!!!  bye :) " << endl;
      toyData = NULL;
      abort();
      return 0;
    }

    for(int iEvent=0; iEvent<nEvts; iEvent++){
      if(iEvent==1)
	cout << "generating event: " << iEvent << " embedTracker: " << embedTracker << endl;
      tempEvent = (RooArgSet*) data->get(embedTracker);
      toyData->add(*tempEvent);
      embedTracker++;
    }

    toyfitresults =model.fitTo(*toyData,Save());
    cout<<toyfitresults<<endl;
    r_fa3 = (RooRealVar *) toyfitresults->floatParsFinal().find("fa3");

    fa3 = r_fa3->getVal();
    fa3Error = r_fa3->getError();
    fa3Pull = (r_fa3->getVal() - fa3Val) / r_fa3->getError();

    // fill TTree
    results->Fill();
    //model.clear();
  }

  char nEvtsString[100];
  sprintf(nEvtsString,"_%iEvts",nEvts);

  // write tree to output file (ouputFileName set at top)
  TFile *outputFile = new TFile("embeddedToysVBF_fa3Corr_"+sampleName[mySample]+nEvtsString+".root","RECREATE");
  results->Write();
  outputFile->Close();

}
Ejemplo n.º 14
0
void track_pt(const int charge)
{
  if (charge==1)
  char  ch[20] = "plus"; 
  else if (charge==-1)
  char ch[20] = "minus";
  ofstream txtfile;
  char txtfname[100];
  char histfname[100];
  sprintf(txtfname,"pt_%s.txt",ch);
  sprintf(histfname,"pt_%s.png",ch);
  txtfile.open(txtfname);
  txtfile << fixed << setprecision(4);
  TCanvas *myCan=new TCanvas("myCan","myCan",800,600);
  gStyle->SetLineWidth(2.);
  gStyle->SetLabelSize(0.04,"xy");
  gStyle->SetTitleSize(0.05,"xy");
  gStyle->SetTitleOffset(1.1,"x");
  gStyle->SetTitleOffset(1.2,"y");
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadRightMargin(0.1);
  gStyle->SetPadBottomMargin(0.16);
  gStyle->SetPadLeftMargin(0.12);

  myCan->SetGrid();
  TLegend* Lgd = new TLegend(.8, .25,.9,.35);
  if (charge==1){
    TFile *f_MC= new TFile("TnP_Tracking_dr030e030_MCptplus.root","read");
    TFile *f_RD= new TFile("TnP_Tracking_dr030e030_RDptplus.root","read");
  }else if (charge==-1){
    TFile *f_MC= new TFile("TnP_Tracking_dr030e030_MCptminus.root","read");
    TFile *f_RD= new TFile("TnP_Tracking_dr030e030_RDptminus.root","read");
  }
  line = new TLine(15,1,80,1);
  line->SetLineStyle(2);
  line->SetLineWidth(3);
  
  TPaveText *title = new TPaveText(.1,1,.95,.95,"NDC");
  title->SetFillStyle(0);
  title->SetBorderSize(0);
  title->SetTextSize(0.04);
  title->AddText("CMS Preliminary, 18.9 pb^{-1} at #sqrt{s}=8 TeV");

  RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTreeSta/eff_pt_dr030e030/fit_eff");
  cout<<"ntry: "<<datasetMC->numEntries()<<endl;
  double XMC[Nbin],XMCerrL[Nbin],XMCerrH[Nbin],YMC[Nbin],YMCerrLo[Nbin],YMCerrHi[Nbin],ErrMC[Nbin];
  for(int i(0); i<datasetMC->numEntries();i++)
  {
    const RooArgSet &pointMC=*datasetMC->get(i);
    RooRealVar &ptMC=pointMC["pt"],&effMC = pointMC["efficiency"];
    XMC[i]=ptMC.getVal();
    XMCerrL[i]=-ptMC.getAsymErrorLo();
    XMCerrH[i]=ptMC.getAsymErrorHi();
    YMC[i]=effMC.getVal();
    YMCerrLo[i]=-effMC.getAsymErrorLo();
    YMCerrHi[i]=effMC.getAsymErrorHi();
    ErrMC[i]=TMath::Max(YMCerrLo[i],YMCerrHi[i]);
  }
  grMC=new TGraphAsymmErrors(Nbin,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);
  grMC->SetLineColor(kRed);
  grMC->SetMarkerColor(kRed);
  grMC->SetMarkerStyle(21);
  grMC->SetMinimum(0.7);
  grMC->SetMaximum(1.11);
  grMC->GetXaxis()->SetNdivisions(505);
  grMC->GetXaxis()->SetTitle("Muon p_{T} [GeV/c]");
  grMC->GetYaxis()->SetTitle("Tracking Efficiency");
  grMC->Draw("AP");

  RooDataSet *datasetRD = (RooDataSet*)f_RD->Get("tpTreeSta/eff_pt_dr030e030/fit_eff");
  double XRD[Nbin],XRDerrL[Nbin],XRDerrH[Nbin],YRD[Nbin],YRDerrLo[Nbin],YRDerrHi[Nbin],ErrRD[Nbin];
  for(int i(0); i<datasetRD->numEntries();i++)
  {
    const RooArgSet &pointRD=*datasetRD->get(i);
    RooRealVar &ptRD=pointRD["pt"],&effRD = pointRD["efficiency"];
    XRD[i]=ptRD.getVal();
    XRDerrL[i]=-ptRD.getAsymErrorLo();
    XRDerrH[i]=ptRD.getAsymErrorHi();
    YRD[i]=effRD.getVal();
    YRDerrLo[i]=-effRD.getAsymErrorLo();
    YRDerrHi[i]=effRD.getAsymErrorHi();
    ErrRD[i]=TMath::Max(YRDerrLo[i],YRDerrHi[i]);
  }

  double SF[Nbin],SFerr[Nbin],SFerrL[Nbin],SFerrH[Nbin];
  for(int i(0); i<datasetRD->numEntries();i++)
  {
    SF[i]=YRD[i]/YMC[i];
    SFerrL[i]=YRD[i]*sqrt(YMCerrLo[i]*YMCerrLo[i]/(YMC[i]*YMC[i])+YRDerrLo[i]*YRDerrLo[i]/(YRD[i]*YRD[i]))/YMC[i];
    SFerrH[i]=YRD[i]*sqrt(YMCerrHi[i]*YMCerrHi[i]/(YMC[i]*YMC[i])+YRDerrHi[i]*YRDerrHi[i]/(YRD[i]*YRD[i]))/YMC[i];
    SFerr[i]=TMath::Max(SFerrL[i],SFerrH[i]);
    txtfile << i << "\t" << YMC[i] << "\t" << ErrMC[i] << "\t" << YRD[i] << "\t" << ErrRD[i] << "\t" << SF[i] << "\t" << SFerr[i] << endl;
  }

  grRD=new TGraphAsymmErrors(Nbin,XRD,YRD,XRDerrL,XRDerrH,YRDerrLo,YRDerrHi);
  grRD->SetLineColor(kBlack);
  grRD->SetMarkerColor(kBlack);
  
  grSF=new TGraphAsymmErrors(Nbin,XRD,SF,0,0,SFerrL,SFerrH);
  grSF->SetLineColor(8);
  grSF->SetMarkerStyle(25);
  grSF->SetMarkerColor(8);
  
  Lgd->AddEntry(grMC,"MC","pl");
  Lgd->AddEntry(grRD,"RD","pl");
  Lgd->SetFillStyle(0);
  Lgd->Draw();
  grRD->Draw("PSAME");
  grSF->Draw("PSAME");
  line->Draw();
  title->Draw();

  myCan->SaveAs(histfname);
  txtfile.close();
}
Ejemplo n.º 15
0
void glbToId_eta()
{
  ofstream txtfile;
  char txtfname[100];
  char histfname[100];
  sprintf(txtfname,"eta_plus.txt");
  sprintf(histfname,"eta_plus.png");
  //sprintf(txtfname,"eta_minus.txt");
  //sprintf(histfname,"eta_minus.png");
  txtfile.open(txtfname);
  txtfile << fixed << setprecision(4);
  TCanvas *myCan=new TCanvas("myCan","myCan",800,600);
  gStyle->SetLineWidth(2.);
  gStyle->SetLabelSize(0.04,"xy");
  gStyle->SetTitleSize(0.05,"xy");
  gStyle->SetTitleOffset(1.1,"x");
  gStyle->SetTitleOffset(1.2,"y");
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadRightMargin(0.1);
  gStyle->SetPadBottomMargin(0.16);
  gStyle->SetPadLeftMargin(0.12);

  myCan->SetGrid();
  TLegend* Lgd = new TLegend(.8, .25,.9,.35);
  
  TFile *f_MCndof2= new TFile("TnP_GlbToID_MCetaplus_Wpteta_eta.root","read");
  TFile *f_MCndof4= new TFile("TnP_GlbToID_MCetaplus_ndof4_Wpteta_eta.root","read");

  //TFile *f_MCndof2= new TFile("TnP_GlbToID_MCetaminus_Wpteta_eta.root","read");
  //TFile *f_MCndof4= new TFile("TnP_GlbToID_MCetaminus_ndof4_Wpteta_eta.root","read");
  RooDataSet *datasetMC = (RooDataSet*)f_MCndof2->Get("tpTree/Wpteta_eta/fit_eff");
  cout<<"ntry: "<<datasetMC->numEntries()<<endl;
  double XMC[Nbin],XMCerrL[Nbin],XMCerrH[Nbin],YMC[Nbin],YMCerrLo[Nbin],YMCerrHi[Nbin],ErrMC[Nbin];
  for(int i(0); i<datasetMC->numEntries();i++)
  {
    const RooArgSet &pointMC=*datasetMC->get(i);
    RooRealVar &etaMC=pointMC["eta"],&effMC = pointMC["efficiency"];
    XMC[i]=etaMC.getVal();
    XMCerrL[i]=-etaMC.getAsymErrorLo();
    XMCerrH[i]=etaMC.getAsymErrorHi();
    YMC[i]=effMC.getVal();
    YMCerrLo[i]=-effMC.getAsymErrorLo();
    YMCerrHi[i]=effMC.getAsymErrorHi();
    ErrMC[i]=TMath::Max(YMCerrLo[i],YMCerrHi[i]);
  }

  grMC=new TGraphAsymmErrors(Nbin,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);
  grMC->SetLineColor(kRed);
  grMC->SetMarkerColor(kRed);
  grMC->SetMinimum(0.5);
  grMC->SetMaximum(1.1);
  grMC->GetXaxis()->SetNdivisions(505);
  grMC->GetXaxis()->SetTitle("Muon #eta");
  grMC->GetYaxis()->SetTitle("ID+ISO Efficiency");
  grMC->Draw("AP");

  RooDataSet *datasetRD = (RooDataSet*)f_MCndof4->Get("tpTree/Wpteta_eta/fit_eff");
  double XRD[Nbin],XRDerrL[Nbin],XRDerrH[Nbin],YRD[Nbin],YRDerrLo[Nbin],YRDerrHi[Nbin],ErrRD[Nbin];
  for(int i(0); i<datasetRD->numEntries();i++)
  {
    const RooArgSet &pointRD=*datasetRD->get(i);
    RooRealVar &etaRD=pointRD["eta"],&effRD = pointRD["efficiency"];
    XRD[i]=etaRD.getVal();
    XRDerrL[i]=-etaRD.getAsymErrorLo();
    XRDerrH[i]=etaRD.getAsymErrorHi();
    YRD[i]=effRD.getVal();
    YRDerrLo[i]=-effRD.getAsymErrorLo();
    YRDerrHi[i]=effRD.getAsymErrorHi();
    ErrRD[i]=TMath::Max(YRDerrLo[i],YRDerrHi[i]);
  }
  txtfile << "Bins \t MC ndof>2\t\t\t MC ndof>4 \t\t\t Scale Factor ndof4/ndof2 "  << endl;
  for(int i(0); i<datasetRD->numEntries();i++)
  {
    txtfile << i << "\t" << YMC[i] << "+/-" << ErrMC[i] << "\t\t" << YRD[i] << "+/-" << ErrRD[i] << "\t\t" << YRD[i]/YMC[i] << "+/-" << YRD[i]*sqrt(ErrMC[i]*ErrMC[i]/(YMC[i]*YMC[i])+ErrRD[i]*ErrRD[i]/(YRD[i]*YRD[i]))/YMC[i] << endl;
  }

  grRD=new TGraphAsymmErrors(Nbin,XRD,YRD,XRDerrL,XRDerrH,YRDerrLo,YRDerrHi);
  grRD->SetLineColor(kBlack);
  grRD->SetMarkerColor(kBlack);
  Lgd->AddEntry(grMC,"MC ndof>2","pl");
  Lgd->AddEntry(grRD,"MC ndof>4","pl");
  Lgd->SetFillStyle(0);
  Lgd->Draw();
  grRD->Draw("PSAME");
  
  myCan->SaveAs(histfname);
  txtfile.close();
}
Ejemplo n.º 16
0
int main(){

  BaBarStyle p;
  p.SetBaBarStyle();
  //gROOT->SetStyle("Plain");

  Bool_t doNorm = kTRUE;
  Bool_t doComparison = kFALSE;
  Bool_t doFract = kFALSE;
  Bool_t doFit = kFALSE;
  Bool_t doPlots = kFALSE;

  //define DalitzSpace for generation
  EvtPDL pdl;
  pdl.readPDT("evt.pdl");
  EvtDecayMode mode("D0 -> K- pi+ pi0");
  EvtDalitzPlot dalitzSpace(mode);

  RooRealVar m2Kpi_d0mass("m2Kpi_d0mass","m2Kpi_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AB),dalitzSpace.qAbsMax(EvtCyclic3::AB));
  RooRealVar m2Kpi0_d0mass("m2Kpi0_d0mass","m2Kpi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AC),dalitzSpace.qAbsMax(EvtCyclic3::AC));
  RooRealVar m2pipi0_d0mass("m2pipi0_d0mass","m2pipi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::BC),dalitzSpace.qAbsMax(EvtCyclic3::BC));
  RooCategory D0flav("D0flav","D0flav");
  D0flav.defineType("D0",-1);
  D0flav.defineType("antiD0",1);

  //this is just to plot the m23 pdf
  Float_t total = pow(dalitzSpace.bigM(),2) + pow(dalitzSpace.mA(),2) + pow(dalitzSpace.mB(),2) + pow(dalitzSpace.mC(),2);
  RooRealVar totalm("totalm","totalm",total);
  RooFormulaVar mass13a("mass13a","@0-@1-@2",RooArgSet(totalm,m2Kpi_d0mass,m2pipi0_d0mass));

  cout << "read the dataset" << endl;

  TFile hello("DataSet_out_tmp.root");
  gROOT->cd();
  RooDataSet *data = (RooDataSet*)hello.Get("fulldata");
  RooDataSet *data_1 = (RooDataSet*)data->reduce("D0flav ==  1 && isWS == 0 && d0LifetimeErr < 0.5 && d0Lifetime > -2. && d0Lifetime < 4.");
  RooDataSet *finaldata = (RooDataSet*)data_1->reduce("deltaMass > 0.1449 && deltaMass < 0.1459 && d0Mass > 1.8495 && d0Mass < 1.8795");
  RooDataSet *leftdata = (RooDataSet*)(RooDataSet*)data_1->reduce("d0Mass > 1.74 && d0Mass < 1.79");
  RooDataSet *rightdata = (RooDataSet*)data_1->reduce("d0Mass > 1.94 && d0Mass < 1.99");

  //here we set the weights for the dataset
  finaldata->setWeightVar(0);
  leftdata->setWeightVar(0);
  rightdata->setWeightVar(0);

  //if you want to have a little dataset to test, uncomment next line and rename finaldata above
  //RooDataSet *finaldata = finaldata_1->reduce(EventRange(1,1000));
  cout << "*************************************************************" << endl;
  cout << "The final data entry    " << finaldata->numEntries() << endl;
  cout << "*************************************************************" << endl;

  //Construct signal pdf
  string dirname = "configmaps/effmapping_RS_CP/";

  RooKpipi0pdf *D0pdf = new RooKpipi0pdf("D0pdf","D0pdf",m2Kpi_d0mass,m2Kpi0_d0mass,&dalitzSpace,dirname,1);
  RooKpipi0pdf *D0pdf23 = new RooKpipi0pdf("D0pdf23","D0pdf23",m2Kpi_d0mass,mass13a,&dalitzSpace,dirname,1);

  if(doNorm) D0pdf->getManager()->calNorm();

  //When we plot the 1D projection, need to calculate the 1D integral
  //set the precision here
  //cout << "config integrator " << endl;
  RooNumIntConfig *cfg = RooAbsReal::defaultIntegratorConfig();
  cfg->setEpsAbs(1E-3);
  cfg->setEpsRel(1E-3);
  cfg->method1D().setLabel("RooSegmentedIntegrator1D");
  //cfg.getConfigSection("RooSegmentedIntegrator1D").setRealValue("numSeg",3);
  //cfg->method1D()->Print("v");
  D0pdf->setIntegratorConfig(*cfg);
  D0pdf23->setIntegratorConfig(*cfg);

  cout << "about to init" << endl;

  m2Kpi_d0mass.setBins(150);
  m2Kpi0_d0mass.setBins(150);
  m2pipi0_d0mass.setBins(150);

  //background description
  //RooBkg combdalitz("combdalitz","combdalitz",m2Kpi_d0mass,m2Kpi0_d0mass,&dalitzSpace);
  //RooBkg combdalitz23("combdalitz23","combdalitz23",m2Kpi_d0mass,mass13a,&dalitzSpace);

  RooRealVar Nsig("Nsig","Nsig", 653962. + 2218.);
  RooRealVar Nbkg("Nbkg","Nbkg", 2255. + 551.);

  RooDataHist* dbdalitz = new RooDataHist("dbdalitz","dbdalitz",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*finaldata);
  RooDataHist* dbdalitz23 = new RooDataHist("dbdalitz23","dbdalitz23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*finaldata);

  ////////////////////////////////////////
  //background parametrization using sidebands histograms
  ////////////////////////////////////////
  TH2F *lefth = m2Kpi_d0mass.createHistogram("lefth",m2Kpi0_d0mass);
  leftdata->fillHistogram(lefth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
  TH2F *righth = m2Kpi_d0mass.createHistogram("righth",m2Kpi0_d0mass);
  rightdata->fillHistogram(righth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));

  TH2F *lefth23 = m2Kpi_d0mass.createHistogram("lefth23",m2pipi0_d0mass);
  leftdata->fillHistogram(lefth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass));
  TH2F *righth23 = m2Kpi_d0mass.createHistogram("righth23",m2pipi0_d0mass);
  rightdata->fillHistogram(righth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass));

  righth->Scale(lefth->Integral()/righth->Integral());
  lefth->Sumw2();
  righth->Sumw2();
  righth23->Scale(lefth23->Integral()/righth23->Integral());
  lefth23->Sumw2();
  righth23->Sumw2();

  RooDataHist *lefthist = new RooDataHist("lefthist","lefthist",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),lefth);
  RooDataHist *righthist = new RooDataHist("righthist","righthist",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),righth);
  RooDataHist *lefthist23 = new RooDataHist("lefthist23","lefthist23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),lefth23);
  RooDataHist *righthist23 = new RooDataHist("righthist23","righthist23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),righth23);

  RooHistPdf leftpdf("leftpdf","leftpdf",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*lefthist,4);
  RooHistPdf rightpdf("rightpdf","rightpdf",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*righthist,4);
  RooHistPdf leftpdf23("leftpdf23","leftpdf23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*lefthist23,4);
  RooHistPdf rightpdf23("rightpdf23","rightpdf23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*righthist23,4);

  RooRealVar fcomb("fcomb","fcomb",0.738);
  RooAddPdf combdalitz("combdalitz","combdalitz",RooArgList(leftpdf,rightpdf),RooArgList(fcomb));
  RooAddPdf combdalitz23("combdalitz23","combdalitz23",RooArgList(leftpdf23,rightpdf23),RooArgList(fcomb));
  ///////////////////////////////////////

  RooAddPdf totpdf("totpdf","totpdf",RooArgList(*D0pdf,combdalitz),RooArgList(Nsig,Nbkg));
  RooAddPdf totpdf23("totpdf23","totpdf23",RooArgList(*D0pdf23,combdalitz23),RooArgList(Nsig,Nbkg));

  if(doFit){
    // Start Minuit session on Chi2
    RooChi2Var chi2("chi2","chi2",totpdf,*dbdalitz);
    RooMinuit m2(chi2);
    m2.migrad();
    m2.hesse();
    RooFitResult* fitRes = m2.save();
    fitRes->Print("v");
    RooArgSet results(fitRes->floatParsFinal());
    RooArgSet conresults(fitRes->constPars());
    results.add(conresults);
    results.writeToFile("fit_isobar_RS.txt");

    //save the stupid result
    TFile f("fit_RSDalitz_result.root","RECREATE");
    fitRes->Write();
    f.Close();
  }

  if(doFract) {

    cout << "Calculating fit fractions" << endl;
    TFile f("fit_RSDalitz_result.root");
    RooFitResult* fitRes = (RooFitResult*)f.Get("chi2");

    //now calculate the fit fractions
    const Int_t nRes = D0pdf->getManager()->getnRes();

    //recalculate the normalization if necessary
    D0pdf->getManager()->calNorm();

    EvtComplex normarray[nRes][nRes];

    const Int_t myRes = 12;
    TH1F fitty[myRes];

    //read the integral value from the cache file.
    //In this way we don't need to compute the normalization everytime during MIGRAD
    char int_name[50];
    D0pdf->getManager()->getFileName(int_name);

    ifstream f1;
    f1.open(int_name);
    if (!f1){
      cout << "Error opening file " << endl;
      assert(0);
    }
  
    Double_t re=0.,im=0.;
    //Read in the cache file and store back to array
    for(Int_t j=0;j<nRes;j++) {
      char thname[100];
      sprintf(thname,"thname_%d",j);
      if(j < myRes) fitty[j] = TH1F(thname,thname,30,0.,1.);
      for(Int_t k=0;k<nRes;k++){
	f1 >> re >> im;       
	normarray[j][k] = EvtComplex(re,im);
      }
    }   

    EvtComplex mynorm[myRes][myRes];
    Int_t m = 0, l = 0;
    for(Int_t i=0;i<myRes;i++){
      for(Int_t j=0;j<myRes;j++){
	if(i==0) l = 7;
	else if(i==1) l = 6;
	else if(i==2) l = 11;
	else if(i==3) l = 4;
	else if(i==4) l = 5;
	else if(i==5) l = 3;
	else if(i==6) l = 9;
	else if(i==7) l = 10;
	else if(i==8) l = 12;
	else if(i==9) l = 8;
	else if(i==10) l = 2;
	else if(i==11) l = 0;

	if(j==0) m = 7;
	else if(j==1) m = 6;
	else if(j==2) m = 11;
	else if(j==3) m = 4;
	else if(j==4) m = 5;
	else if(j==5) m = 3;
	else if(j==6) m = 9;
	else if(j==7) m = 10;
	else if(j==8) m = 12;
	else if(j==9) m = 8;
	else if(j==10) m = 2;
	else if(j==11) m = 0;

	mynorm[i][j] = normarray[l][m];
      }
    }

    //do 100 experiments and extract parameters using covariance matrix
    for(Int_t l=0;l<300;l++){
      RooArgList listpar = fitRes->randomizePars();
      if(l==0) listpar.Print();

      Double_t mynormD0 = 0.;
      EvtComplex coeff_i(0.,0.), coeff_j(0.,0.);
      for(Int_t i=0;i<2*myRes;i++){
	for(Int_t j=0;j<2*myRes;j++){
	  if(i==(2*myRes - 2)) coeff_i = EvtComplex(1.,0.);
	  else coeff_i = EvtComplex(((RooAbsReal*)listpar.at(i))->getVal()*cos(((RooAbsReal*)listpar.at(i+1))->getVal()),
				    ((RooAbsReal*)listpar.at(i))->getVal()*sin(((RooAbsReal*)listpar.at(i+1))->getVal()));

	  if(j==(2*myRes - 2)) coeff_j = EvtComplex(1.,0.);
	  else coeff_j = EvtComplex(((RooAbsReal*)listpar.at(j))->getVal()*cos(((RooAbsReal*)listpar.at(j+1))->getVal()),
				    ((RooAbsReal*)listpar.at(j))->getVal()*sin(((RooAbsReal*)listpar.at(j+1))->getVal()));

	  mynormD0 += real(coeff_i*conj(coeff_j)*(mynorm[i/2][j/2]));
	  j++;
	}
	i++;
      }

      //now calculate the fit fractions
      for(Int_t i=0;i<2*myRes;i++){
	Double_t fitfrac = 0.;
	if(i==(2*myRes - 2)) fitfrac = abs(mynorm[i/2][i/2])/mynormD0;
	else fitfrac = abs2( ((RooAbsReal*)listpar.at(i))->getVal())*abs(mynorm[i/2][i/2])/mynormD0;
	fitty[i/2].Fill(fitfrac);
	i++;
      }
    }// nexperiments

    Double_t tot_frac = 0.;
    for(Int_t i=0;i<myRes;i++){
      tot_frac += fitty[i].GetMean();
      cout << "Resonance " << i << ": fit fraction = " << fitty[i].GetMean() << " +/- " << fitty[i].GetRMS() << endl;
    }

    cout << "Total fit fraction = " << tot_frac << endl;
    cout << "///////////////////////////" << endl;
  }

  if(doPlots){
    //Make the plots
    // REMEBER: if you want roofit to consider the reweighted errors, you must put DataError(RooAbsData::SumW2))
    //******************************************************
    RooPlot* xframe = m2Kpi_d0mass.frame();
    dbdalitz->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));
    totpdf.plotOn(xframe);
    xframe->getAttLine()->SetLineWidth(1);
    xframe->getAttLine()->SetLineStyle(1);
    xframe->SetTitle("");
    xframe->GetXaxis()->SetTitle("s_{12} [GeV^{2}/c^{4}]");
    xframe->GetYaxis()->SetTitle("Events/4 MeV^{2}/c^{4}");
    Double_t chi2Kpi = xframe->chiSquare();

    RooPlot* yframe = m2Kpi0_d0mass.frame();
    dbdalitz->plotOn(yframe,MarkerSize(0.1),DrawOption("z"));
    totpdf.plotOn(yframe);
    yframe->getAttLine()->SetLineWidth(1);
    yframe->getAttLine()->SetLineStyle(1);
    yframe->SetTitle("");
    yframe->GetXaxis()->SetTitle("s_{13} [GeV^{2}/c^{4}]");
    yframe->GetYaxis()->SetTitle("Events/5 MeV^{2}/c^{4}");
    Double_t chi2Kpi0 = yframe->chiSquare();
    /*
    RooPlot* zframe = m2pipi0_d0mass.frame(0.,2.3);
    dbdalitz23->plotOn(zframe,MarkerSize(0.1),DrawOption("z"));
    totpdf23.plotOn(zframe);
    zframe->getAttLine()->SetLineWidth(1);
    zframe->getAttLine()->SetLineStyle(1);
    zframe->SetTitle("");
    zframe->GetXaxis()->SetTitle("m^{2}_{#pi^{+}#pi^{0}}");
    Double_t chi2pipi0 = zframe->chiSquare();

    cout << "Chi2 for Kpi = " << chi2Kpi << endl;
    cout << "Chi2 for Kpi0 = " << chi2Kpi0 << endl;
    cout << "Chi2 for pipi0 = " << chi2pipi0 << endl;

    RooPlot* pullFramem12 = m2Kpi_d0mass.frame() ;
    pullFramem12->SetTitle("");
    pullFramem12->GetXaxis()->SetTitle("");
    pullFramem12->addPlotable(xframe->pullHist()) ;
    pullFramem12->SetMaximum(5.);
    pullFramem12->SetMinimum(-5.);

    RooPlot* pullFramem13 = m2Kpi0_d0mass.frame() ;
    pullFramem13->SetTitle("");
    pullFramem13->GetXaxis()->SetTitle("");
    pullFramem13->addPlotable(yframe->pullHist()) ;
    pullFramem13->SetMaximum(5.);
    pullFramem13->SetMinimum(-5.);

    RooPlot* pullFramem23 = m2pipi0_d0mass.frame() ;
    pullFramem23->SetTitle("");        
    pullFramem23->GetXaxis()->SetTitle("");
    pullFramem23->addPlotable(zframe->pullHist()) ;
    pullFramem23->SetMaximum(5.);
    pullFramem23->SetMinimum(-5.);

    TCanvas *c2 = new TCanvas("c2","residuals",1200,200);
    c2->Divide(3,1);
    c2->cd(1);pullFramem12->Draw();
    c2->cd(2);pullFramem13->Draw();
    c2->cd(3);pullFramem23->Draw();
    c2->SaveAs("RSresiduals.eps");
    */
    totpdf.plotOn(xframe,Project(m2Kpi0_d0mass),Components(RooArgSet(combdalitz)),DrawOption("F"),FillColor(kRed));
    totpdf.plotOn(yframe,Project(m2Kpi_d0mass),Components(RooArgSet(combdalitz)),DrawOption("F"),FillColor(kRed));
    //totpdf23.plotOn(zframe,Project(m2Kpi_d0mass),Components(RooArgSet(combdalitz23)),DrawOption("F"),FillColor(kRed));

    TPaveText *box_m12 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m12->AddText("(b)");
    box_m12->SetFillColor(10);

    TPaveText *box_m13 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m13->AddText("(c)");
    box_m13->SetFillColor(10);

    TCanvas c1("c1","c1",600,600);
    c1.cd();
    xframe->Draw();box_m12->Draw("SAME");
    c1.SaveAs("RSfit_m2Kpi.eps");

    TCanvas c2("c2","c2",600,600);
    c2.cd();
    yframe->Draw();box_m13->Draw("SAME");
    c2.SaveAs("RSfit_m2Kpi0.eps");
    /*
    TCanvas *c1 = new TCanvas("c1","allevents",1200,400);
    c1->Divide(3,1);
    c1->cd(1);xframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->cd(2);yframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->cd(3);zframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->SaveAs("RSsigfit.eps");
    */
  }

  if(doComparison){
    RooDataSet *littledata = (RooDataSet*)finaldata->reduce(EventRange(1,70000));
    RooArgSet VarList1(m2Kpi_d0mass,m2Kpi0_d0mass);
    Int_t num_entries = littledata->numEntries();
    RooDataSet* genpdf = D0pdf->generate(VarList1,num_entries);

    Int_t nbinx = 20;
    Int_t nbiny = 20;
    m2Kpi_d0mass.setBins(nbinx);
    m2Kpi0_d0mass.setBins(nbiny);

    TH2F* pdfhist = new TH2F("pdfhist","pdfhist",nbinx,0.39,3.,nbiny,0.39,3.);
    TH2F* datahist = new TH2F("datahist","datahist",nbinx,0.39,3.,nbiny,0.39,3.);
    pdfhist = genpdf->createHistogram(m2Kpi_d0mass,m2Kpi0_d0mass);
    datahist = finaldata->createHistogram(m2Kpi_d0mass,m2Kpi0_d0mass);
    pdfhist->GetXaxis()->SetTitle("m_{K#pi}^{2}");
    pdfhist->GetYaxis()->SetTitle("m_{K#pi^{0}}^{2}");

    pdfhist->Scale(datahist->Integral()/pdfhist->Integral());

    pdfhist->Add(datahist,-1.);

    TCanvas c2;
    c2.cd();pdfhist->Draw("LEGO2Z");
    c2.SaveAs("RSsigdiff.eps");

    TFile ftmp("prova.root","RECREATE");
    ftmp.cd();pdfhist->Write();
    ftmp.Close();

  }

  return 0;
}//end of the macro
Ejemplo n.º 17
0
int main(int argc, char *argv[]){

	OptionParser(argc,argv);
	

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


  
	system(Form("mkdir -p %s",outdir_.c_str()));

	vector<string> procs;
	split(infilenames_,infilenamesStr_,boost::is_any_of(","));
  
   TPython::Exec("import os,imp,re");
   for (unsigned int i =0 ; i<infilenames_.size() ; i++){
     TFile *infile =  TFile::Open(infilenames_[i].c_str());
	   string outname  =(string) TPython::Eval(Form("'%s'.split(\"/\")[-1].replace('root','_reduced.root')",infilenames_[i].c_str())); 
     TFile *outfile = TFile::Open(outname.c_str(),"RECREATE") ;
    TDirectory* saveDir = outfile->mkdir("tagsDumper");
    saveDir->cd();

    RooWorkspace *inWS = (RooWorkspace*) infile->Get("tagsDumper/cms_hgg_13TeV");
    RooRealVar *intLumi = (RooRealVar*)inWS->var("IntLumi");
    RooWorkspace *outWS = new RooWorkspace("cms_hgg_13TeV");
    outWS->import(*intLumi);
    std::list<RooAbsData*> data =  (inWS->allData()) ;
    std::cout <<" [INFO] Reading WS dataset contents: "<< std::endl;
        for (std::list<RooAbsData*>::const_iterator iterator = data.begin(), end = data.end(); iterator != end; ++iterator )  {
              RooDataSet *dataset = dynamic_cast<RooDataSet *>( *iterator );
              if (dataset) {
              RooDataSet *datasetReduced = (RooDataSet*) dataset->emptyClone(dataset->GetName(),dataset->GetName());
                TRandom3 r;
                r.Rndm();
                double x[dataset->numEntries()];
                r.RndmArray(dataset->numEntries(),x);
                int desiredEntries = floor(0.5+ dataset->numEntries()*fraction_);
                int modFraction = floor(0.5+ 1/fraction_);
                int finalEventCount=0;
                for (int j =0; j < dataset->numEntries() ; j++){
                    if( j%modFraction==0){
                      finalEventCount++;
                    }
                 }
                float average_weight= dataset->sumEntries()/finalEventCount;
                for (int j =0; j < dataset->numEntries() ; j++){
                    if( j%modFraction==0){
                    dataset->get(j);
                    datasetReduced->add(*(dataset->get(j)),average_weight);
                    }
                }
              float entriesIN =dataset->sumEntries();
              float entriesOUT =datasetReduced->sumEntries();
           if(verbose_){
              std::cout << "Original dataset " << *dataset <<std::endl;
              std::cout << "Reduced       dataset " << *datasetReduced <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "fraction (obs) : " << entriesOUT/entriesIN << std::endl;
              std::cout << "fraction (exp) : " << fraction_ << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datasetReduced);
                }
                
             RooDataHist *datahist = dynamic_cast<RooDataHist *>( *iterator );

              if (datahist) {
              RooDataHist *datahistOUT = (RooDataHist*) datahist->emptyClone(datahist->GetName(),datahist->GetName());
                TRandom3 r;
                r.Rndm();
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistOUT->add(*(datahist->get(j)),datahist->weight());
                }
              float w =datahistOUT->sumEntries();
              float z =datahist->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "Reduced  datahist " << *datahistOUT<<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : " << w/(z) <<std::endl;
              std::cout << "WH fraction (exp) : " << fraction_ << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistOUT);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
Ejemplo n.º 18
0
void wspaceread_signals2e2mu(int channel = 3)
{

	gSystem->AddIncludePath("-I$ROOFITSYS/include");
	gROOT->ProcessLine(".L ~/tdrstyle.C");
	setTDRStyle();
	//gSystem->Load("PDFs/RooRelBW1_cxx.so");
	//gSystem->Load("PDFs/RooRelBW2_cxx.so");
	gSystem->Load("../PDFs/HZZ4LRooPdfs_cc.so");

	string schannel;
	if (channel == 1) schannel = "4mu";
	if (channel == 2) schannel = "4e";
	if (channel == 3) schannel = "2mu2e";
	std::cout << "schannel = " << schannel << std::endl;

	const int nPoints = 17.;
	int masses[nPoints] = {120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600};
	double mHVal[nPoints] = {120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600};
	double widths[nPoints] = {3.48e-03,4.88e-03,8.14e-03,1.73e-02,8.30e-02,3.80e-01,6.31e-01,1.04e+00,1.43e+00,4.04e+00,8.43e+00,1.52e+01,2.92e+01,46.95,6.80e+01,93.15,1.23e+02};
	// R e a d   w o r k s p a c e   f r o m   f i l e
	// -----------------------------------------------
	
	double a_meanBW[nPoints];
	double a_gammaBW[nPoints];
	double a_meanCB[nPoints];
	double a_sigmaCB[nPoints];
	double a_alphaCB[nPoints];
	double a_nCB[nPoints];
		
	for (int i = 0; i < nPoints; i++){
	//for (int i = 0; i < 1; i++){
		
		// Open input file with workspace (generated by rf14_wspacewrite)
		char infile[192];
		sprintf(infile,"/scratch/hep/ntran/dataFiles/HZZ4L/datasets/datasets_baseline/%s/ZZAnalysisTree_H%i%s.root",schannel.c_str(),masses[i],schannel.c_str());
		TFile *f = new TFile(infile) ;
		char outfile[192];
		sprintf( outfile, "figs/pdf_%s_bkg_highmass.eps", schannel.c_str() );
		//f->ls();
		
		double windowVal = max( widths[i], 1. );
		if (mHVal[i] >= 275){ lowside = 180.; }
		else { lowside = 100.; }
		double low_M = max( (mHVal[i] - 20.*windowVal), lowside) ;
		double high_M = min( (mHVal[i] + 15.*windowVal), 900.) ;

		//double windowVal = max( widths[i], 1.);
		//double windowVal = max ( widths[i], 1. );
		//low_M = max( (mHVal[i] - 25.*windowVal), 100.) ;
		//high_M = min( (mHVal[i] + 20.*windowVal), 1000.) ;
		//low_M = max( (mHVal[i] - 15.*windowVal), 100.) ;
		//high_M = min( (mHVal[i] + 10.*windowVal), 1000.) ;
		std::cout << "lowM = " << low_M << ", highM = " << high_M << std::endl;
			
		RooDataSet* set = (RooDataSet*) f->Get("data");
		RooArgSet* obs = set->get() ;
		obs->Print();
		RooRealVar* CMS_zz4l_mass = (RooRealVar*) obs->find("CMS_zz4l_mass") ;
		CMS_zz4l_mass->setRange(low_M,high_M);
		for (int a=0 ; a<set->numEntries() ; a++) { 
			set->get(a) ; 
			//cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
		} 
		
		// constraining parameters...
		double l_sigmaCB = 0., s_sigmaCB = 3.;
		if (mHVal[i] >= 500.){ l_sigmaCB = 10.; s_sigmaCB = 12.; }
		
		double s_n_CB = 2.6+(-1.1/290.)*(mHVal[i]-110.);
		if (mHVal[i] >= 400){ s_n_CB = 1.5; }

		
		RooRealVar mean_CB("mean_CB","mean_CB",0.,-25.,25);
		RooRealVar sigma_CB("sigma_CB","sigma_CB",s_sigmaCB,l_sigmaCB,30.);
		RooRealVar alpha_CB("alpha_CB","alpha_CB",0.95,0.8,1.2);
		RooRealVar n_CB("n_CB","n_CB",s_n_CB,1.5,2.8);
		RooCBShape signalCB("signalCB","signalCB",*CMS_zz4l_mass,mean_CB,sigma_CB,alpha_CB,n_CB);
		
		RooRealVar mean_BW("mean_BW","mean_BW", mHVal[i] ,100.,1000.);
		RooRealVar gamma_BW("gamma_BW","gamma_BW",widths[i],0.,200.);
		//RooBreitWigner signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		//RooRelBW1 signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		
		RooRelBWUF signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW);
		//RooRelBW1 signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooBreitWigner signalBW1("signalBW1", "signalBW1",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooRelBW1 signalBW2("signalBW2", "signalBW2",*CMS_zz4l_mass,mean_BW,gamma_BW);
		
		//Set #bins to be used for FFT sampling to 10000
		CMS_zz4l_mass->setBins(100000,"fft") ;

		//Construct BW (x) CB
		RooFFTConvPdf* sig_ggH = new RooFFTConvPdf("sig_ggH","BW (X) CB",*CMS_zz4l_mass,signalBW,signalCB, 2);
		// Buffer fraction for cyclical behavior
		sig_ggH->setBufferFraction(0.2);
		
		mean_BW.setConstant(kTRUE);
		gamma_BW.setConstant(kTRUE);
		n_CB.setConstant(kTRUE);
		alpha_CB.setConstant(kTRUE);
		
		RooFitResult *r = sig_ggH.fitTo( *set, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;
		
		a_meanBW[i] = mean_BW.getVal();
		a_gammaBW[i] = gamma_BW.getVal();
		a_meanCB[i] = mean_CB.getVal();
		a_sigmaCB[i] = sigma_CB.getVal();;
		a_alphaCB[i] = alpha_CB.getVal();;
		a_nCB[i] = n_CB.getVal();;
		
		
		// Plot Y
		RooPlot* frameM4l = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
		set->plotOn(frameM4l) ;
		sig_ggH.plotOn(frameM4l) ;

		RooPlot* testFrame = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
		signalBW.plotOn(testFrame) ;
		signalBW1.plotOn(testFrame, LineColor(kBlack)) ;
		signalBW2.plotOn(testFrame, LineColor(kRed)) ;
				
		TCanvas *c = new TCanvas("c","c",800,600);
		c->cd();
		frameM4l->Draw();
		char plotName[192];
		sprintf(plotName,"sigFigs/m%i.eps",masses[i]);
		
		c->SaveAs(plotName);

		TCanvas *c3 = new TCanvas("c3","c3",800,600);
		c3->cd();
		testFrame->Draw();
		//char plotName[192];
		sprintf(plotName,"sigFigs/shape%i.eps",masses[i]);
		
		c3->SaveAs(plotName);
		
		
		delete f;
		delete set;
		delete c;
	}
	

	TGraph* gr_meanBW = new TGraph( nPoints, mHVal, a_meanBW );
	TGraph* gr_gammaBW = new TGraph( nPoints, mHVal, a_gammaBW );
	TGraph* gr_meanCB = new TGraph( nPoints, mHVal, a_meanCB );
	TGraph* gr_sigmaCB = new TGraph( nPoints, mHVal, a_sigmaCB );
	TGraph* gr_alphaCB = new TGraph( nPoints, mHVal, a_alphaCB );
	TGraph* gr_nCB = new TGraph( nPoints, mHVal, a_nCB );
	
	TF1 *polyFunc1= new TF1("polyFunc1","[0]+[1]*x+[2]*(x-[3])*(x-[3])+[4]*x*x*x*x", 120., 600.);
	polyFunc1->SetParameters(1., 1., 1., 100.,0.1);
	TF1 *polyFunc2= new TF1("polyFunc2","[0]+[1]*x+[2]*(x-[3])*(x-[3])+[4]*x*x*x*x", 120., 600.);
	polyFunc2->SetParameters(1., 1., 1., 100.,0.1);
	
	
	TCanvas *c = new TCanvas("c","c",1200,800);
	c->Divide(3,2);
	//c->SetGrid();
	//TH1F *hr = c->DrawFrame(0.,0.,610.,1.);
	c->cd(1);
	gr_meanBW->Draw("alp");
	gr_meanBW->GetXaxis()->SetTitle("mean BW");
	c->cd(2);
	gr_gammaBW->Draw("alp");
	gr_gammaBW->GetXaxis()->SetTitle("gamma BW");
	c->cd(3);
	gr_meanCB->Fit(polyFunc1,"Rt");
	gr_meanCB->Draw("alp");
	gr_meanCB->GetXaxis()->SetTitle("mean CB");
	c->cd(4);
	gr_sigmaCB->Fit(polyFunc2,"Rt");
	gr_sigmaCB->Draw("alp");
	gr_sigmaCB->GetXaxis()->SetTitle("sigma CB");
	c->cd(5);
	gr_alphaCB->Draw("alp");
	gr_alphaCB->GetXaxis()->SetTitle("alpha CB");
	c->cd(6);
	gr_nCB->Draw("alp");
	gr_nCB->GetXaxis()->SetTitle("n CB");
	c->SaveAs("sigFigs/params.eps");
	
	std::cout << "mean_CB = " << polyFunc1->GetParameter(0) << " + " << polyFunc1->GetParameter(1) << "*m + " << polyFunc1->GetParameter(2) << "*(m - " << polyFunc1->GetParameter(3) << ")*(m - " << polyFunc1->GetParameter(3);
	std::cout << ") + " << polyFunc1->GetParameter(4) << "*m*m*m*m;" << std::endl;
	std::cout << "sigma_CB = " << polyFunc2->GetParameter(0) << " + " << polyFunc2->GetParameter(1) << "*m + " << polyFunc2->GetParameter(2) << "*(m - " << polyFunc2->GetParameter(3) << ")*(m - " << polyFunc2->GetParameter(3);
	std::cout << ") + " << polyFunc2->GetParameter(4) << "*m*m*m*m;" << std::endl;
	
	
	// calculate sysetmatic errors from interpolation...
	double sum_meanCB = 0;
	double sum_sigmaCB = 0;
	for (int i = 0; i < nPoints; i++){
		double tmp_meanCB = (polyFunc1->Eval(mHVal[i]) - a_meanCB[i]);
		sum_meanCB += (tmp_meanCB*tmp_meanCB);
		double tmp_sigmaCB = (polyFunc2->Eval(mHVal[i]) - a_sigmaCB[i])/a_sigmaCB[i];
		sum_sigmaCB += (tmp_sigmaCB*tmp_sigmaCB);
		std::cout << "mean: " << tmp_meanCB << ", sigma: " << tmp_sigmaCB << std::endl;
	}
	double rms_meanCB = sqrt( sum_meanCB/( (double) nPoints) );
	double rms_sigmaCB = sqrt( sum_sigmaCB/( (double) nPoints) );
	std::cout << "err (meanCB) = " << rms_meanCB << ", err (sigmaCB) = " << rms_sigmaCB << std::endl;
	
	
	
	
	
}
Ejemplo n.º 19
0
int main(int argc, const char** argv){
  bool ReDoCuts=false;

  TCut TwelveCut = "gamma_CL>0.1&&BDT_response>0.36&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  TCut ElevenCut = "gamma_CL>0.1&&BDT_response>0.30&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  
  //______________________________MAKE CUT FILE FOR 2012___________________________________
  if(ReDoCuts){
    DataFile MCA(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MCB(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    TreeReader* MC12Reader=  new TreeReader("DecayTree");
    MC12Reader->AddFile(MCA);
    MC12Reader->AddFile(MCB);
    MC12Reader->Initialize();
    
    TFile* MC12Cut = new TFile("CutFile12.root","RECREATE");
    TTree* MC12CutTree=MC12Reader->CopyTree(TwelveCut,-1,"DecayTree");
    TRandom3 *MCRand = new TRandom3(224);
    TH1I * MCnCands12= new TH1I("MCnCands12","MCnCands12",10,0,10);
    TTree*MC12SingleTree=HandyFunctions::GetSingleTree(MCRand,MC12CutTree,MCnCands12,NULL);
    MCnCands12->Write();
    MC12SingleTree->Write();
    MC12Cut->Close();
    
    //________________________________MAKE CUT FILE FOR 2011__________________________________
    
    DataFile MC11A(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MC11B(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleB");
    
    TreeReader* MC11Reader= new TreeReader("DecayTree");
    MC11Reader->AddFile(MC11A);
    MC11Reader->AddFile(MC11B);
    MC11Reader->Initialize();
    
    TFile* MC11Cut = new TFile("CutFile11.root","RECREATE");
    TTree* MC11CutTree=MC11Reader->CopyTree(ElevenCut,-1,"DecayTree");

    TH1I * MCnCands11= new TH1I("MCnCands11","MCnCands11",10,0,10);
    TTree* MC11SingleTree=HandyFunctions::GetSingleTree(MCRand,MC11CutTree,MCnCands11,NULL);
    MCnCands11->Write();
    MC11SingleTree->Write();
    MC11Cut->Close();
  //_________________________________ MAKE FLAT TREES  ____________________________________
  
    TFile* MC12Input = new TFile("CutFile12.root");
    TTree* MC12InputTree=(TTree*)MC12Input->Get("DecayTree");
    Float_t MCEta_Mass12[20]; MC12InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass12);
    Int_t isSingle12; MC12InputTree->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MC12FlatOut = new TFile("MCMinimalFile12.root","RECREATE");
    TTree* MC12FlatTree = MC12InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF12; MC12FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=MC12InputTree->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      MC12InputTree->GetEntry(i);
      if(isSingle12==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF12=MCEta_Mass12[0];
      MC12FlatTree->Fill();
    }
    
    MC12FlatTree->Write();
    MC12FlatOut->Close();
    
    TFile* MC11Input = new TFile("CutFile11.root");
    TTree* MC11InputTree=(TTree*)MC11Input->Get("DecayTree");
    Float_t MCEta_Mass11[20]; MC11InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass11);
    Int_t isSingle11; MC11InputTree->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MC11FlatOut = new TFile("MCMinimalFile11.root","RECREATE");
    TTree* MC11FlatTree = MC11InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF11; MC11FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=MC11InputTree->GetEntries();
    
    for(int i=0;i<Entries11;++i){
      MC11InputTree->GetEntry(i);
      if(isSingle11==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF11=MCEta_Mass11[0];
      MC11FlatTree->Fill();
    }
    
    MC11FlatTree->Write();
    MC11FlatOut->Close();
  }
  
  //_____________________________________________LOAD ROODATASETS___________________________________

  TFile* MCFlatInput12= new TFile("MCMinimalFile12.root");
  TTree* MCFlatInputTree12=(TTree*)MCFlatInput12->Get("DecayTree");

  TFile* MCFlatInput11= new TFile("MCMinimalFile11.root");
  TTree* MCFlatInputTree11=(TTree*)MCFlatInput11->Get("DecayTree");

  RooRealVar MCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar MCEtaMass("eta_prime_MM","eta_prime_MM",700.0,1200.0);
  RooRealVar BDT_response("BDT_response","BDT_response",-1.0,1.0);
  RooRealVar gamma_CL("gamma_CL","gamma_CL",0.1,1.0);
  RooArgSet Args(MCBMass,MCEtaMass,BDT_response,gamma_CL);

  RooDataSet* MCData12 = new RooDataSet("MCData12","MCData12",Args,Import(*MCFlatInputTree12));
  
  std::cout <<" Data File 12 Loaded"<<std::endl;
  
  RooDataSet* MCData11 = new RooDataSet("MCData11","MCData11",Args,Import(*MCFlatInputTree11));

  std::cout<<" Data File 11 loaded"<<std::endl;

  RooDataSet* MCDataAll= new RooDataSet("MCDataAll","MCDataAll",Args);

  MCDataAll->append(*MCData12);
  MCDataAll->append(*MCData11);
  
  RooPlot* massFrame = MCBMass.frame(Title("Data Import Check"),Bins(50));
  MCDataAll->plotOn(massFrame);
  
  RooPlot *BDTFrame = BDT_response.frame(Title("BDT Cut Check"),Bins(50));
  MCDataAll->plotOn(BDTFrame);
  TCanvas C;
  C.Divide(2,1);
  C.cd(1);
  massFrame->Draw();
  C.cd(2);
  BDTFrame->Draw();
  C.SaveAs("ImportChecks.eps");

  //________________________________MAKE MCROODATACATEGORIES__________________________________

  RooDataSet* MCBData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCBMass));
  MCBData->Print("v");
  
  RooDataSet* MCEtaData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCEtaMass));
  MCEtaData->Print("v");

  RooCategory MCMassType("MCMassType","MCMassType") ;
  MCMassType.defineType("B") ;
  MCMassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet MCcombData("MCcombData","MC combined data",Args,Index(MCMassType),Import("B",*MCBData),Import("Eta",*MCEtaData));

  
  //=============================================== MC FIT MODEL===================================
  
  RooRealVar Mean("Mean","Mean",5279.29,5276.0,5284.00);
  RooRealVar Sigma("Sigma","Sigma",20.54,17.0,24.8);
  RooRealVar LAlpha("LAlpha","LAlpha",-1.064,-2.5,0.0);
  RooRealVar RAlpha("RAlpha","RAlpha",1.88,0.0,5.0);
  RooRealVar LN("LN","LN",13.0,0.0,40.0);
  RooRealVar RN("RN","RN",2.56,0.0,6.0);

  RooCBShape CBLeft("CBLeft","CBLeft",MCBMass,Mean,Sigma,LAlpha,LN);
  
  RooCBShape CBRight("CBRight","CBRight",MCBMass,Mean,Sigma,RAlpha,RN);

  RooRealVar FitFraction("FitFraction","FitFraction",0.5,0.0,1.0);
  RooAddPdf DCB("DCB","DCB",RooArgList(CBRight,CBLeft),FitFraction);

  RooRealVar SignalYield("SignalYield","SignalYield",4338.0,500.0,10000.0);
  //  RooExtendPdf ExtDCB("ExtDCB","ExtDCB",DCB,SignalYield);
  
  //==============================ETA DCB ++++++++++++++++++++++++++++++
  
  RooRealVar MCEtamean("MCEtamean","MCEtamean",958.0,955.0,960.0);
  RooRealVar MCEtasigma("MCEtasigma","MCEtasigma",9.16,8.0,14.0);
  RooRealVar EtaLAlpha("EtaLAlpha","EtaLAlpha",-1.45,-5.0,1.0);
  RooRealVar EtaRAlpha("EtaRAlpha","EtaRAlpha",1.76,0.0,4.0);
  RooRealVar EtaLN("EtaLN","EtaLN",0.1,0.0,20.0);
  RooRealVar EtaRN("EtaRN","EtaRN",0.1,0.0,20.0);

  RooCBShape EtaCBLeft("EtaCBLeft","EtaCBLeft",MCEtaMass,MCEtamean,MCEtasigma,EtaLAlpha,EtaLN);
  
  RooCBShape EtaCBRight("EtaCBRight","EtaCBRight",MCEtaMass,MCEtamean,MCEtasigma,EtaRAlpha,EtaRN);

  RooRealVar EtaFitFraction("EtaFitFraction","EtaFitFraction",0.22,0.1,1.0);
  RooAddPdf EtaDCB("EteaDCB","EtaDCB",RooArgList(EtaCBRight,EtaCBLeft),EtaFitFraction);

  RooProdPdf MCSignalPdf("MCSignalPdf","MCSignalPdf",RooArgSet(EtaDCB,DCB));
  
  RooExtendPdf ExtendedMCSignalPdf("ExtendedMCSignalPdf","ExtendedMCSignalPdf",MCSignalPdf,SignalYield);

  RooSimultaneous MCsimPdf("MCsimPdf","MC simultaneous pdf",MCMassType) ;
  //  MCsimPdf.addPdf(ExtDCB,"B");
  //  MCsimPdf.addPdf(ExtendedMCEtaDCB,"Eta"); 

  //============================== DO the MC FIT =======================================
  //MCsimPdf.fitTo(MCcombData,Extended(kTRUE),Minos(kTRUE));
  //ExtendedMCEtaDCB.fitTo(*MCEtaData,Extended(kTRUE),Minos(kTRUE));
  //ExtDCB.fitTo(*MCBData,Extended(
  ExtendedMCSignalPdf.fitTo(*MCDataAll,Extended(kTRUE),Minos(kTRUE));
  
  RooPlot* MCframe1 = MCBMass.frame(Range(5100.0,5500.0),Bins(50),Title("B mass projection"));
  MCDataAll->plotOn(MCframe1);
  ExtendedMCSignalPdf.plotOn(MCframe1);
  ExtendedMCSignalPdf.paramOn(MCframe1);
  
  RooPlot* MCframe2 = MCEtaMass.frame(Range(880.0,1020.0),Bins(50),Title("Eta mass projection")) ;
  MCDataAll->plotOn(MCframe2);
  ExtendedMCSignalPdf.plotOn(MCframe2);
  ExtendedMCSignalPdf.paramOn(MCframe2);
  
  TCanvas* MCc = new TCanvas("rf501_simultaneouspdf","rf403_simultaneouspdf",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; MCframe1->GetYaxis()->SetTitleOffset(1.4) ; MCframe1->Draw() ;
  MCc->SaveAs("MCSimulCanvas.pdf");

  TCanvas* MCcEta = new TCanvas(" Eta Canvas","Eta Canvas",1200,1000);
  gPad->SetLeftMargin(0.15) ; MCframe2->GetYaxis()->SetTitleOffset(1.4) ; MCframe2->Draw() ;
  MCcEta->SaveAs("MCEtaCanvas.pdf");

  TFile* MCFits= new TFile("MCFitResult.root","RECREATE");
  //  TCanvas* DecMCB=HandyFunctions::DecoratePlot(MCframe1);
  //  TCanvas* DecMCEta=HandyFunctions::DecoratePlot(MCframe2);
  //DecMCEta->Write();
  //  DecMCB->Write();
  MCc->Write();
  MCcEta->Write();

  std::cout<<"MC Eta Chi2 = "<<MCframe2->chiSquare()<<std::endl;
  std::cout<<"MC B Chi2 = "<<MCframe1->chiSquare()<<std::endl;

  //___________________________________ CUT DOWN COLLISION DATA ______________________________
  if(ReDoCuts){
    DataFile TwelveA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleA");

    DataFile TwelveB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    DataFile ElevenA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleA");

    DataFile ElevenB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleB");		

    TRandom3* DataRand= new TRandom3(224);
    TH1I* DataNCand12= new TH1I("DataNCand12","DataNCand12",10,0,10);
    TH1I* DataNCand11= new TH1I("DataNCand11","DataNCand11",10,0,10);
    
    TreeReader* UncutDataReader12= new TreeReader("DecayTree");
    UncutDataReader12->AddFile(TwelveA);
    UncutDataReader12->AddFile(TwelveB);
    UncutDataReader12->Initialize();
    
    TFile* CutDataFile12 = new TFile("CutDataFile12.root","RECREATE");
    TTree* CutDataTree12 = UncutDataReader12->CopyTree(TwelveCut,-1,"DecayTree");
    TTree* SingleCutDataTree12=HandyFunctions::GetSingleTree(DataRand,CutDataTree12,DataNCand12,NULL);
    SingleCutDataTree12->Write();
    CutDataFile12->Close();
    
    TreeReader* UncutDataReader11= new TreeReader("DecayTree");
    UncutDataReader11->AddFile(ElevenB);
    UncutDataReader11->AddFile(ElevenA);
    UncutDataReader11->Initialize();
    
    TFile* CutDataFile11 = new TFile("CutDataFile11.root","RECREATE");
    TTree* CutDataTree11 = UncutDataReader11->CopyTree(ElevenCut,-1,"DecayTree");
    TTree* SingleCutDataTree11=HandyFunctions::GetSingleTree(DataRand,CutDataTree11,DataNCand11,NULL);
    SingleCutDataTree11->Write();
    CutDataFile11->Close();
  

    TFile* DataInput12 = new TFile("CutDataFile12.root");
    TTree* DataInputTree12=(TTree*)DataInput12->Get("DecayTree");
    DataInputTree12->SetBranchStatus("*",0);
    DataInputTree12->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree12->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree12->SetBranchStatus("eta_prime_MM",1);
    DataInputTree12->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass12[20]; DataInputTree12->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass12);
    Int_t isSingle12; DataInputTree12->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MinimalDataFile12 = new TFile("MinimalDataFile12.root","RECREATE");
    TTree* MinimalDataTree12= DataInputTree12->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF12; MinimalDataTree12->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=DataInputTree12->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      DataInputTree12->GetEntry(i);
      if(isSingle12==0)continue;
      Bu_DTFNoFix_eta_prime_MF12=Eta_Mass12[0];
      MinimalDataTree12->Fill();
    }
    
    MinimalDataTree12->Write();
    MinimalDataFile12->Close();
    
    TFile* DataInput11 = new TFile("CutDataFile11.root");
    TTree* DataInputTree11=(TTree*)DataInput11->Get("DecayTree");
    DataInputTree11->SetBranchStatus("*",0);
    DataInputTree11->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree11->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree11->SetBranchStatus("eta_prime_MM",1);
    DataInputTree11->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass11[20]; DataInputTree11->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass11);
    Int_t isSingle11; DataInputTree11->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MinimalDataFile11 = new TFile("MinimalDataFile11.root","RECREATE");
    TTree* MinimalDataTree11= DataInputTree11->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF11; MinimalDataTree11->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=DataInputTree11->GetEntries();
    
    for(int i=0;i<Entries11;++i){
    DataInputTree11->GetEntry(i);
    if(isSingle11==0)continue;
    Bu_DTFNoFix_eta_prime_MF11=Eta_Mass11[0];
    MinimalDataTree11->Fill();
    }
    MinimalDataTree11->Write();
    MinimalDataFile11->Close();
  }

  //___________________________________ LOAD DATA TO ROODATASET____________________________________
  
  RooRealVar BMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar EtaMass("eta_prime_MM","eta_prime_MM",870.0,1050.0);
  RooArgSet MassArgs(BMass,EtaMass);

  TFile* Data12File = new TFile("MinimalDataFile12.root");
  TTree* DataTree12=(TTree*)Data12File->Get("DecayTree");

  RooDataSet* Data12 = new RooDataSet("Data12","Data12",MassArgs,Import(*DataTree12));

  TFile* Data11File = new TFile("MinimalDataFile11.root");
  TTree* DataTree11=(TTree*)Data11File->Get("DecayTree");

  RooDataSet* Data11 = new RooDataSet("Data11","Data11",MassArgs,Import(*DataTree11));
  
  RooDataSet* AllData = new RooDataSet("AllData","AllData",MassArgs);
  AllData->append(*Data12);
  AllData->append(*Data11);
  TCanvas ImportC;
  RooPlot* ImportCheck = BMass.frame(Title("ImportCheck"),Bins(50));
  AllData->plotOn(ImportCheck);
  ImportCheck->Draw();
  ImportC.SaveAs("Alldataimport.pdf");

  std::cout<<" Data Loaded, Total Entries = "<<AllData->numEntries()<<std::endl;

  AllData->Print("v");

  RooDataSet* BData=(RooDataSet*)AllData->reduce(RooArgSet(BMass));
  BData->Print("v");

  RooDataSet* EtaData=(RooDataSet*)AllData->reduce(RooArgSet(EtaMass));
  EtaData->Print("v");

  //___________________________________Fit to Eta_Prime in BMass Sidebands______________________

  RooDataSet* BSidebands=(RooDataSet*)AllData->reduce(Cut("(Bu_DTF_MF>5000.0&&Bu_DTF_MF<5179.0)||(Bu_DTF_MF>5379.0&&Bu_DTF_MF<5800.0)"));

  TCanvas BSidebandCanvas;
  RooPlot* BSidebandPlot = EtaMass.frame(Title("B sidebands"),Bins(30));
  BSidebands->plotOn(BSidebandPlot);
  BSidebandPlot->Draw();
  BSidebandCanvas.SaveAs("BSidebandDataCheck.pdf");

  
  RooRealVar BsbMean(" Mean","BsbMean",958.0,900.0,1020.0);
  RooRealVar BsbSigma(" Sigma","BsbSigma",19.8,10.0,40.8);
  RooRealVar BsbLAlpha(" Alpha","BsbLAlpha",-1.63,-10.0,0.0);
  //  RooRealVar BsbRAlpha("BsbRAlpha","BsbRAlpha",1.47,0.0,10.0);
  RooRealVar BsbLN(" N","BsbLN",0.1,0.0,20.0);
  //  RooRealVar BsbRN("BsbRN","BsbRN",0.1,0.0,20.0);

  RooCBShape BsbCBLeft("BsbCBLeft","BsbCBLeft",EtaMass,BsbMean,BsbSigma,BsbLAlpha,BsbLN);
  
  //  RooCBShape BsbCBRight("BsbCBRight","BsbCBRight",EtaMass,BsbMean,BsbSigma,BsbRAlpha,BsbRN);

  //  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.5,0.0,1.0);
  //  RooAddPdf BsbDCB("BsbDCB","BsbDCB",RooArgList(BsbCBRight,BsbCBLeft),BsbFitFraction);
  RooRealVar Bsbslope("Bsbslope","Bsbslope",0.5,0.0,1.0);
  RooRealVar BsbP2("BsbP2","BsbP2",-0.5,-1.0,0.0);
  RooChebychev BsbLinear("BsbLinear","BsbLinear",EtaMass,RooArgSet(Bsbslope,BsbP2));

  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.2,0.0,1.0);

  RooAddPdf BsbBackground("BsbBackground","BsbBackground",RooArgList(BsbLinear,BsbCBLeft),BsbFitFraction);
  
  RooRealVar BsbYield(" Yield","BsbYield",500.0,0.0,1000.0);
  RooExtendPdf BsbExtDCB("BsbExtDCB","BsbExtDCB",BsbCBLeft,BsbYield);

  BsbExtDCB.fitTo(*BSidebands,Extended(kTRUE),Minos(kTRUE));
  TCanvas BSBFitCanvas;
  RooPlot* BSBFitPlot = EtaMass.frame(Title("Eta fit in B Sidebands"),Bins(30));
  BSidebands->plotOn(BSBFitPlot);
  BsbExtDCB.plotOn(BSBFitPlot);
  BsbExtDCB.paramOn(BSBFitPlot);
  BSBFitPlot->Draw();
  BSBFitCanvas.SaveAs("BSidebandFit.pdf");
  TFile * SidebandFitFile= new TFile("SidebandFit.root","RECREATE");
  BSBFitCanvas.Write();
  SidebandFitFile->Close();
  
  //___________________________________DO THE 2D FIT TO DATA___________________________________


  const double PDGBMass= 5279.26;
  BMass.setRange("SignalWindow",PDGBMass-(3*Sigma.getVal()),PDGBMass+(3*Sigma.getVal()));
  RooRealVar DSignalYield("DSignalYield","DSignalYield",4000.0,0.0,10000.0);

  //================================= B MASS SIGNAL PDF==============================
  RooRealVar DMean("Mean","DMean",5279.29,5270.0,5290.00);
  RooRealVar DSigma("Sigma","DSigma",19.8,10.0,40.8);
  RooRealVar DLAlpha("DLAlpha","DLAlpha",LAlpha.getVal());
  RooRealVar DRAlpha("DRAlpha","DRAlpha",RAlpha.getVal());
  RooRealVar DLN("DLN","DLN",LN.getVal());
  RooRealVar DRN("DRN","DRN",RN.getVal());

  RooCBShape DCBLeft("DCBLeft","DCBLeft",BMass,DMean,DSigma,DLAlpha,DLN);
  
  RooCBShape DCBRight("DCBRight","DCBRight",BMass,DMean,DSigma,DRAlpha,DRN);

  RooRealVar DFitFraction("FitFraction","DFitFraction",0.5,0.0,1.0);
  RooAddPdf DDCB("DDCB","DDCB",RooArgList(DCBRight,DCBLeft),DFitFraction);
  
  //==============================B MASS BKG PDF==============================
  RooRealVar slope("slope","slope",-0.5,-1.0,0.0);
  RooChebychev bkg("bkg","Background",BMass,RooArgSet(slope));
  
  //==============================Eta mass signal pdf================================
  RooRealVar DEtamean("Etamean","DEtamean",958.0,945.0,980.0) ;
  RooRealVar DEtasigma("Etasigma","DEtasigma",15.0,5.0,65.0) ;
  RooRealVar DEtaLAlpha("DEtaLAlpha","DEtaLAlpha",EtaLAlpha.getVal());
  RooRealVar DEtaRAlpha("DEtaRAlpha","DEtaRAlpha",EtaRAlpha.getVal());
  RooRealVar DEtaLN("DEtaLN","DEtaLN",EtaLN.getVal());
  RooRealVar DEtaRN("DEtaRN","DEtaRN",EtaRN.getVal());
  
  RooCBShape EtaDCBLeft("EtaDCBLeft","EtaDCBLeft",EtaMass,DEtamean,DEtasigma,DEtaLAlpha,DEtaLN);
  
  RooCBShape EtaDCBRight("EtaDCBRight","EtaDCBRight",EtaMass,DEtamean,DEtasigma,DEtaRAlpha,DEtaRN);
  
  RooRealVar DEtaFitFraction("EtaFitFraction","DEtaFitFraction",0.5,0.0,1.0);
  RooAddPdf EtaDDCB("EtaDDCB","EtaDDCB",RooArgList(EtaDCBRight,EtaDCBLeft),DEtaFitFraction);

  RooProdPdf DSignalPdf("DSignalPdf","DSignalPdf",RooArgList(EtaDDCB,DDCB));
  
  RooExtendPdf DExtSignalPdf("DExtSignalPdf","DExtSignalPdf",DSignalPdf,DSignalYield);

  //=============================== Eta mass bkg pdf==================================
  
  RooRealVar EtaBkgMean("EtaBkgMean","EtaBkgMean",958.0,900.0,1020.0);
  RooRealVar EtaBkgSigma("EtaBkgSigma","EtaBkgSigma",19.8,10.0,40.8);
  RooRealVar EtaBkgLAlpha("EtaBkgLAlpha","EtaBkgLAlpha",BsbLAlpha.getVal());
  //  RooRealVar EtaBkgRAlpha("EtaBkgRAlpha","EtaBkgRAlpha",BsbRAlpha.getVal());
  RooRealVar EtaBkgLN("EtaBkgLN","EtaBkgLN",BsbLN.getVal());
  //  RooRealVar EtaBkgRN("EtaBkgRN","EtaBkgRN",BsbRN.getVal());

  RooCBShape EtaBkgCBLeft("EtaBkgCBLeft","EtaBkgCBLeft",EtaMass,DEtamean,EtaBkgSigma,EtaBkgLAlpha,EtaBkgLN);
  
  //  RooCBShape EtaBkgCBRight("EtaBkgCBRight","EtaBkgCBRight",EtaMass,DEtamean,EtaBkgSigma,EtaBkgRAlpha,EtaBkgRN);
  
  //  RooRealVar EtaBkgFitFraction("EtaBkgFitFraction","EtaBkgFitFraction",0.5,0.0,1.0);
  //  RooAddPdf EtaBkgDCB("EtaBkgDCB","EtaBkgDCB",RooArgList(EtaBkgCBRight,EtaBkgCBLeft),EtaBkgFitFraction);
  
  RooProdPdf DataBackgroundPDF("DataBackgroundPDF","DataBackgroundPDF",RooArgList(EtaBkgCBLeft,bkg));
  
  RooRealVar DataBackgroundYield("BackgroundYield","DataBackgroundYield",500.0,0.0,10000.0);
  
  RooExtendPdf ExtDataBackgroundPDF("ExtDataBackgroundPDF","ExtDataBackgroundPDF",DataBackgroundPDF,DataBackgroundYield);

  RooAddPdf TotalPDF("TotalPDF","TotalPDF",RooArgList(ExtDataBackgroundPDF,DExtSignalPdf));
  std::cout<<"Dependents = "<<std::endl;
  RooArgSet* Dependents=TotalPDF.getDependents(AllData);
  Dependents->Print("v");
  std::cout<<"parameters= "<<std::endl;
  RooArgSet* parameters=TotalPDF.getParameters(AllData);
  parameters->Print("v");
  RooCategory MassType("MassType","MassType") ;
  MassType.defineType("B") ;
  MassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet combData("combData","combined data",MassArgs,Index(MassType),Import("B",*BData),Import("Eta",*EtaData));

  RooSimultaneous simPdf("simPdf","simultaneous pdf",MassType) ;

  // Associate model with the physics state and model_ctl with the control state
  //  simPdf.addPdf(WholeFit,"B");
  //  simPdf.addPdf(WholeEtaFit,"Eta"); 

  //  simPdf.fitTo(combData,Extended(kTRUE)/*,Minos(kTRUE)*/);
  
  TotalPDF.fitTo(*AllData,Extended(kTRUE),Minos(kTRUE));

  RooPlot* frame1 = BMass.frame(Bins(50),Title("B mass projection"));
  AllData->plotOn(frame1);
  TotalPDF.plotOn(frame1,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame1);
  TotalPDF.paramOn(frame1);
  
  // The same plot for the control sample slice
  RooPlot* frame2 = EtaMass.frame(Bins(50),Title("Eta mass projection")) ;
  AllData->plotOn(frame2);
  TotalPDF.plotOn(frame2,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame2);
  TotalPDF.paramOn(frame2);
  TCanvas* DecoratedCanvas =HandyFunctions::DecoratePlot(frame2);

  
  TCanvas* DataBC= new TCanvas("BCanvas","BCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
  TCanvas* EtaBC= new TCanvas("EtaCanvas","EtaCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;
  DataBC->SaveAs("DataBC.pdf");
  EtaBC->SaveAs("EtaBC.pdf");
  
  TFile * DataSimulFit = new TFile("DataSimulFit.root","RECREATE");
  DataBC->Write();
  EtaBC->Write();
  DecoratedCanvas->Write();

  
		 
		  

  
}
Ejemplo n.º 20
0
void fitM3()
{

	// LOAD HISTOGRAMS FROM FILES
	/////////////////////////////////
	TH1F *hTTjets;
	TH1F *hWjets;
	TH1F *hM3;
	TH1F *hZjets;
	TH1F *hQCD;
	TH1F *hST_s;
	TH1F *hST_t;
	TH1F *hST_tW;

	// histograms from nonimal sample
	///////////
	
	TFile *infile0 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_TTJets-madgraph_Fall08_all_all.root");
	//TFile *infile0 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_TauolaTTbar.root");
	hTTjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	TFile *infile1 = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_WJets_madgraph_Fall08_all.root");
	hWjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	TFile *infile1Fast = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Wjets_madgraph_Winter09_v2_all.root");
	hWjetsFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZ = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ZJets_madgraph_Fall08_all.root");
	hZjets = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	TFile *infileZFast = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Zjets_madgraph_Winter09_v2_all.root");
	hZjetsFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_s = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_s.root");
	hST_s = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_t = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_t.root");
	hST_t = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tW = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_ST_tW.root");
	hST_tW = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileQCD = TFile::Open("nominal_IPsig3_Iso95/TopAnalysis_InclusiveMuPt15_Summer08_all.root");
	hQCD = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	// histograms from systematic samples
	//////////
	TFile *infile0S = TFile::Open("nominal_JESUp/TopAnalysis_TTJets-madgraph_Fall08_all_all.root");
	hTTjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
		
	TFile *infile1S = TFile::Open("nominal_JESUp/TopAnalysis_WJets_madgraph_Fall08_all.root");// from FullSim
	hWjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	//TFile *infile1SF = TFile::Open("nominal_JESUp_Fast/TopAnalysis_WJets_madgraph_Fall08_all.root");// from FastSim
	//TFile *infile1SF = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_Wjets_ScaleUp_madgraph_Winter09_all.root");
	TFile *infile1SF = TFile::Open("nominal_IPsig3_Iso95_Fast/TopAnalysis_WJets_Threshold20GeV_madgraph_Winter09_all.root");
	hWjetsSFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZS = TFile::Open("nominal_JESUp/TopAnalysis_ZJets_madgraph_Fall08_all.root");// from FullSim
	hZjetsS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileZSF = TFile::Open("nominal_JESUp_Fast/TopAnalysis_ZJets_madgraph_Fall08_all.root");// from FullSim
	hZjetsSFast = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_sS = TFile::Open("nominal_JESUp/TopAnalysis_ST_s.root");
	hST_sS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tS = TFile::Open("nominal_JESUp/TopAnalysis_ST_t.root");
	hST_tS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileST_tWS = TFile::Open("nominal_JESUp/TopAnalysis_ST_tW.root");
	hST_tWS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	TFile *infileQCDS = TFile::Open("nominal_JESUp/TopAnalysis_InclusiveMuPt15_Summer08_all.root");//
	hQCDS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");
	
	//TFile *infileQCD_CS = TFile::Open("nominal_antiMuon/TopAnalysis_InclusiveMuPt15_Summer08_all.root");
	//hQCD_CS = (TH1F*) gDirectory->Get("Mass/HadronicTop_mass_cut1");

	// write templates to file
	//TFile *outfile = TFile::Open("templates.root","RECREATE");
	//hTTjets->Write("ttbar");
	//hWjets->Write("Wjets");
	//outfile->Close();

	// Add over/underflow bins if requested
	bool UseOverflow = true;
	bool UseUnderflow = true;
	
	if (UseOverflow) {
		int maxbin=hTTjets->GetNbinsX();
	
		hTTjets->SetBinContent(maxbin,    hTTjets->GetBinContent(maxbin+1)+hTTjets->GetBinContent(maxbin) );
		hWjets->SetBinContent(maxbin,     hWjets->GetBinContent(maxbin+1)+hWjets->GetBinContent(maxbin) );
		hWjetsFast->SetBinContent(maxbin, hWjetsFast->GetBinContent(maxbin+1)+hWjetsFast->GetBinContent(maxbin) );
		hZjets->SetBinContent(maxbin,     hZjets->GetBinContent(maxbin+1)+hZjets->GetBinContent(maxbin) );
		hZjetsFast->SetBinContent(maxbin, hZjetsFast->GetBinContent(maxbin+1)+hZjetsFast->GetBinContent(maxbin) );
		hQCD->SetBinContent(maxbin,       hQCD->GetBinContent(maxbin+1)+hQCD->GetBinContent(maxbin) );
		//hQCD_CS->SetBinContent(maxbin, hQCD_CS->GetBinContent(maxbin+1)+hQCD_CS->GetBinContent(maxbin) );
		hST_s->SetBinContent(maxbin,      hST_s->GetBinContent(maxbin+1)+hST_s->GetBinContent(maxbin) );
		hST_t->SetBinContent(maxbin,      hST_t->GetBinContent(maxbin+1)+hST_t->GetBinContent(maxbin) );
		hST_tW->SetBinContent(maxbin,     hST_tW->GetBinContent(maxbin+1)+hST_tW->GetBinContent(maxbin) );
	}
	//underflow bin
	if (UseUnderflow) {
		int maxbin=1;
		hTTjets->SetBinContent(maxbin,    hTTjets->GetBinContent(maxbin-1)+hTTjets->GetBinContent(maxbin) );
		hWjets->SetBinContent(maxbin,     hWjets->GetBinContent(maxbin-1)+hWjets->GetBinContent(maxbin) );
		hWjetsFast->SetBinContent(maxbin, hWjetsFast->GetBinContent(maxbin-1)+hWjetsFast->GetBinContent(maxbin) );
		hZjets->SetBinContent(maxbin,     hZjets->GetBinContent(maxbin-1)+hZjets->GetBinContent(maxbin) );
		hZjetsFast->SetBinContent(maxbin, hZjetsFast->GetBinContent(maxbin-1)+hZjetsFast->GetBinContent(maxbin) );
		hQCD->SetBinContent(maxbin,       hQCD->GetBinContent(maxbin-1)+hQCD->GetBinContent(maxbin) );
		//hQCD_CS->SetBinContent(maxbin, hQCD_CS->GetBinContent(maxbin-1)+hQCD_CS->GetBinContent(maxbin) );
		hST_s->SetBinContent(maxbin,      hST_s->GetBinContent(maxbin-1)+hST_s->GetBinContent(maxbin) );
		hST_t->SetBinContent(maxbin,      hST_t->GetBinContent(maxbin-1)+hST_t->GetBinContent(maxbin) );
		hST_tW->SetBinContent(maxbin,     hST_tW->GetBinContent(maxbin-1)+hST_tW->GetBinContent(maxbin) );
	}
	//syst.
	if (UseOverflow) {
		int maxbin=hTTjetsS->GetNbinsX();
		hTTjetsS->SetBinContent(maxbin,    hTTjetsS->GetBinContent(maxbin+1)+hTTjetsS->GetBinContent(maxbin) );
		hWjetsS->SetBinContent(maxbin,     hWjetsS->GetBinContent(maxbin+1)+hWjetsS->GetBinContent(maxbin) );
		hWjetsSFast->SetBinContent(maxbin, hWjetsSFast->GetBinContent(maxbin+1)+hWjetsSFast->GetBinContent(maxbin) );
		hZjetsS->SetBinContent(maxbin,     hZjetsS->GetBinContent(maxbin+1)+hZjetsS->GetBinContent(maxbin) );
		hZjetsSFast->SetBinContent(maxbin, hZjetsSFast->GetBinContent(maxbin+1)+hZjetsSFast->GetBinContent(maxbin) );
		hQCDS->SetBinContent(maxbin,       hQCDS->GetBinContent(maxbin+1)+hQCDS->GetBinContent(maxbin) );
		hST_sS->SetBinContent(maxbin,      hST_sS->GetBinContent(maxbin+1)+hST_sS->GetBinContent(maxbin) );
		hST_tS->SetBinContent(maxbin,      hST_tS->GetBinContent(maxbin+1)+hST_tS->GetBinContent(maxbin) );
		hST_tWS->SetBinContent(maxbin,     hST_tWS->GetBinContent(maxbin+1)+hST_tWS->GetBinContent(maxbin) );
	}
	if (UseUnderflow) {
		//underflow bin
		int maxbin=1;
		hTTjetsS->SetBinContent(maxbin,    hTTjetsS->GetBinContent(maxbin-1)+hTTjetsS->GetBinContent(maxbin) );
		hWjetsS->SetBinContent(maxbin,     hWjetsS->GetBinContent(maxbin-1)+hWjetsS->GetBinContent(maxbin) );
		hWjetsSFast->SetBinContent(maxbin, hWjetsSFast->GetBinContent(maxbin-1)+hWjetsSFast->GetBinContent(maxbin) );
		hZjetsS->SetBinContent(maxbin,     hZjetsS->GetBinContent(maxbin-1)+hZjetsS->GetBinContent(maxbin) );
		hZjetsSFast->SetBinContent(maxbin,     hZjetsSFast->GetBinContent(maxbin-1)+hZjetsSFast->GetBinContent(maxbin) );
		hQCDS->SetBinContent(maxbin,       hQCDS->GetBinContent(maxbin-1)+hQCDS->GetBinContent(maxbin) );
		hST_sS->SetBinContent(maxbin,      hST_sS->GetBinContent(maxbin-1)+hST_sS->GetBinContent(maxbin) );
		hST_tS->SetBinContent(maxbin,      hST_tS->GetBinContent(maxbin-1)+hST_tS->GetBinContent(maxbin) );
		hST_tWS->SetBinContent(maxbin,     hST_tWS->GetBinContent(maxbin-1)+hST_tWS->GetBinContent(maxbin) );
	}
	
	// scale histograms to 20/pb

	hTTjets->Scale(0.0081); // madgraph
	//hTTjets->Scale(0.0777);//Tauola
	hWjets->Scale(0.0883);
	//hWjetsFast->Scale(0.0091); //fastsim
	hWjetsFast->Scale(hWjets->Integral() / hWjetsFast->Integral()); // scale to FullSim
		
	hZjets->Scale(0.0731);
	hZjetsFast->Scale(hZjets->Integral()/hZjetsFast->Integral()); //scale to FullSim
	hQCD->Scale(0.4003);
	hQCD_WFast = (TH1F*) hWjetsFast->Clone("hQCD_WFast"); //take shape from Wjets
	hQCD_WFast->Scale(hQCD->Integral()/hQCD_WFast->Integral()); //scale to FullSim
	hST_t->Scale(0.003);
	hST_s->Scale(0.0027);
	hST_tW->Scale(0.0034);

	hTTjetsS->Scale(0.0081); // 
	//hTTjetsS->Scale(0.0008); // for fastsim
	hWjetsS->Scale(0.0883);
	//hWjetsS->Scale(0.0091);// from fastsim
	//hWjetsSFast->Scale(hWjetsS->Integral() / hWjetsSFast->Integral()); // scale to FullSim
	//hWjetsSFast->Scale(0.6642); // scaleUP
	//hWjetsSFast->Scale(0.8041); // scaleDown
	//hWjetsSFast->Scale(0.0605); // threshold 5gev
	hWjetsSFast->Scale(0.042); // threshold 20gev
	
	hZjetsS->Scale(0.0731);
	//hZjetsS->Scale(0.0085);// from fastsim
	hZjetsSFast->Scale(hZjetsS->Integral() / hZjetsSFast->Integral()); // scale to FullSim
	hQCDS->Scale(0.4003);
	//hQCDS_WFast = (TH1F*) hWjetsS->Clone("hQCDS_WFast");
	//hQCDS_WFast->Scale(hQCDS->Integral()/hQCDS_WFast->Integral());
	hST_tS->Scale(0.003);
	hST_sS->Scale(0.0027);
	hST_tWS->Scale(0.0034);
	
	cout << " N expected ttbar+jets events = " << hTTjets->Integral() << endl;
	cout << " N expected W+jets     events = " << hWjets->Integral()  << endl;
	cout << " N expected Z+jets     events = " << hZjets->Integral()  << endl;
	cout << " N expected ST s       events = " << hST_s->Integral()  << endl;
	cout << " N expected ST t       events = " << hST_t->Integral()  << endl;
	cout << " N expected ST tW      events = " << hST_tW->Integral()  << endl;
	cout << " N expected qcd        events = " << hQCD->Integral()  << endl;

	cout << endl;
	cout << " N expected W+jets fast = " << hWjetsFast->Integral() << endl;
	cout << " N expected z+jets fast = " << hZjetsFast->Integral() << endl;
	cout << " N expected qcd Wfast = " << hQCD_WFast->Integral() << endl;

	cout << "\n systematics: " << endl;
	cout << " N expected W+jets fast = " << hWjetsSFast->Integral() << endl;
	cout << " N expected z+jets fast = " << hZjetsS->Integral() << endl;
	cout << " N expected qcd Wfast = " << hQCDS->Integral() << endl;

	// add all three single top samples

	// for systematics
	//hST_t->Scale(2.);
	
	hST_t->Add(hST_s);
	hST_t->Add(hST_tW);
	cout << " number of ST = " << hST_t->Integral() << endl;
	// syst. uncertainty in single top
	//double tmpST = 0.6* hST_t->Integral();
	//hST_t->Scale(0.6);
	//cout << tmpST << endl;
	cout << " New number of ST = " << hST_t->Integral() << endl;
	
	hST_tS->Add(hST_sS);
	hST_tS->Add(hST_tWS);

	// dump scaled histograms in root file
	//TFile *output = TFile::Open("fitM3.root","RECREATE");
	//hTTjets->SetName("ttbar");hTTjets->Write();
	//hWjetsFast->SetName("WjetsFast");hWjetsFast->Write();
	//hST_t->SetName("ST");hST_t->Write();
	//output->Close();
	
		
	hM3 = (TH1F*) hTTjets->Clone("hM3");
	hM3->Add(hWjets);
	hM3->Add(hZjets);
	hM3->Add(hQCD);
	hM3->Add(hST_t);
	
	int Nbins = hM3->GetNbinsX();
	
	// --- Observable ---
        
	RooRealVar mass("mass","M3'(#chi^{2})",100,500,"GeV/c^{2}") ; 
	RooRealVar Ntt("Ntt","number of t#bar{t} events", hTTjets->Integral(), -100 , 1000);
    RooRealVar NW("NW","number of W+jets events", hWjetsFast->Integral(), -500 , 1000);
	RooRealVar NST("NST","number of single top events", hST_t->Integral(), -500,100);
	RooRealVar NZjets("NZjets","number of Z+jets events", hZjetsS->Integral(), -500,500);
	RooRealVar Nqcd("Nqcd","number of QCD events", hQCD_WFast->Integral(), -500,100);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral()+hST_t->Integral()+hZjetsFast->Integral()+hQCD_WFast->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of W+jets events", hWjets->Integral(), -500 , 1000); // 2 templates

	RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral()+hZjets->Integral()+hQCD_WFast->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsFast->Integral(), -500 , 1000);
	
	// for systematics
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsSFast->Integral()+hZjetsS->Integral()+hQCDS->Integral(), -500 , 1000);
	//RooRealVar Nbkg("Nbkg","number of bkg events", hWjetsSFast->Integral(), -500 , 1000);
	
	mass.setBins(Nbins);

	// RooFit datasets
	RooDataHist hdata_ttbar("hdata_ttbar","ttbar", mass, hTTjets);       
	//RooDataHist hdata_wjets("hdata_wjets","wjets", mass, hWjets);
	RooDataHist hdata_wjetsFast("hdata_wjetsFast","wjets_Fast", mass, hWjetsFast);
	RooDataHist hdata_ST("hdata_ST","ST", mass, hST_t);
	RooDataHist hdata_zjets("hdata_zjets","zjets", mass, hZjets);
	//RooDataHist hdata_qcd("hdata_qcd","qcd", mass, hQCD);
	RooDataHist hdata_zjetsFast("hdata_zjetsFast","zjets_Fast", mass, hZjetsFast);
	RooDataHist hdata_qcdWFast("hdata_qcdWFast","qcd WFast", mass, hQCD_WFast);
	
	RooHistPdf hpdf_ttbar("hpdf_ttbar","signal pdf", mass, hdata_ttbar, 0 );
	//RooHistPdf hpdf_wjets("hpdf_wjets","W+jets pdf", mass, hdata_wjets, 0 );
	RooHistPdf hpdf_wjetsFast("hpdf_wjetsFast","W+jets pdf", mass, hdata_wjetsFast, 0 );
	RooHistPdf hpdf_ST("hpdf_ST","ST pdf", mass, hdata_ST, 0 );
	//RooHistPdf hpdf_zjets("hpdf_zjets","Z+jets pdf", mass, hdata_zjets, 0 );
	//RooHistPdf hpdf_qcd("hpdf_qcd","qcd pdf", mass, hdata_qcd, 0 );
	RooHistPdf hpdf_zjetsFast("hpdf_zjetsFast","Z+jets pdf", mass, hdata_zjetsFast, 0 );
	RooHistPdf hpdf_qcdWFast("hpdf_qcdWFast","qcd WFast pdf", mass, hdata_qcdWFast, 0 );
	
	// for systematics
	RooDataHist hdata_ttbarS("hdata_ttbarS","ttbar", mass, hTTjetsS);       
	RooDataHist hdata_wjetsS("hdata_wjetsS","wjets", mass, hWjetsSFast);
	RooDataHist hdata_STS("hdata_STS","ST", mass, hST_tS);
	RooDataHist hdata_zjetsS("hdata_zjetsS","zjets", mass, hZjetsSFast);
	RooDataHist hdata_qcdS("hdata_qcdS","qcd", mass, hQCDS);
	//RooDataHist hdata_qcdSWFast("hdata_qcdSWFast","qcd WFast", mass, hQCDS_WFast);
		
	RooHistPdf hpdf_ttbarS("hpdf_ttbarS","signal pdf", mass, hdata_ttbarS, 0 );
	RooHistPdf hpdf_wjetsS("hpdf_wjetsS","W+jets pdf", mass, hdata_wjetsS, 0 );
	RooHistPdf hpdf_STS("hpdf_STS","ST pdf", mass, hdata_STS, 0 );
	RooHistPdf hpdf_zjetsS("hpdf_zjetsS","Z+jets pdf", mass, hdata_zjetsS, 0 );
	RooHistPdf hpdf_qcdS("hpdf_qcdS","qcd pdf", mass, hdata_qcdS, 0 );
	//RooHistPdf hpdf_qcdSWFast("hpdf_qcdSWFast","qcd WFast pdf", mass, hdata_qcdSWFast, 0 );

	//RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsFast,hpdf_ST,hpdf_qcdWFast),
	//				   RooArgList(NW,NST,Nqcd) );
					   
	//RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsFast,hpdf_ST,hpdf_zjetsFast,hpdf_qcdWFast),
					   //RooAddPdf hpdf_bkg("hpdf_bkg","bkg", RooArgList(hpdf_wjetsS,hpdf_STS,hpdf_zjetsS,hpdf_qcdSWFast),
					   //RooArgList(NW,NST,NZjets,Nqcd) );
// only two pdfs: ttbar + Wjets
//RooHistPdf hpdf_bkg = hpdf_wjetsFast;
	
	//RooAddPdf model_M3("modelM3","all", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST,hpdf_zjetsFast,hpdf_qcdWFast),
	//			   RooArgList(Ntt,Nbkg,NST,NZjets,Nqcd));
	// for systematics
	RooAddPdf model_M3("modelM3","all", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),//RooArgList(hpdf_ttbar,hpdf_wjetsS,hpdf_ST),
					   RooArgList(Ntt,Nbkg,NST) );
	
	//RooAddPdf model_M3("modelM3","all",RooArgList(hpdf_ttbar,hpdf_bkg),
	//		   RooArgList(Ntt,Nbkg) );
	//RooArgList(Ntt,Nbkg,NST,Nqcd) );
	
	RooAddPdf model_histpdf("model", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),
							RooArgList(Ntt, Nbkg, NST) ) ;

	// Construct another Gaussian constraint p.d.f on parameter f at n with resolution of sqrt(n)
	RooGaussian STgaussConstraint("STgaussConstraint","STgaussConstraint",NST,RooConst(hST_t->Integral()),RooConst(sqrt(hST_t->Integral() + (0.3*hST_t->Integral())*(0.3*hST_t->Integral()))) );
	//RooGaussian fconstext2("fconstext2","fconstext2",NZjets,RooConst(hZjets->Integral()),RooConst(sqrt(hZjets->Integral())) );
	
	// --- Generate a toyMC sample 
	//RooMCStudy *mcstudyM3 = new RooMCStudy(model_M3, mass, Binned(kTRUE),Silence(),Extended(),
	//								   FitOptions(Save(kTRUE),Minos(kTRUE),Extended(), ExternalConstraints(fconstext)) );

	// generate PEs
	int Nsamples = 1000;
	// PEs for ttbar
/*
	RooExtendPdf ext_hpdf_ttbar("ext_hpdf_ttbar","ext_hpdf_ttbar",hpdf_ttbar,Ntt);
	RooExtendPdf ext_hpdf_wjets("ext_hpdf_wjets","ext_hpdf_wjets",hpdf_wjetsFast,NW);
	RooExtendPdf ext_hpdf_zjets("ext_hpdf_zjets","ext_hpdf_zjets",hpdf_zjetsFast,NZjets);
	RooExtendPdf ext_hpdf_qcd("ext_hpdf_qcd","ext_hpdf_qcd",hpdf_qcdWFast,Nqcd);
	RooExtendPdf ext_hpdf_ST("ext_hpdf_ST","ext_hpdf_ST",hpdf_ST,NST);
	
	RooMCStudy *mc_ttbar = new RooMCStudy(ext_hpdf_ttbar,mass,Binned(kTRUE),Silence(kTRUE));
	mc_ttbar->generate(Nsamples,0,kFALSE,"data/toymc_ttbar_%04d.dat");
	RooMCStudy *mc_wjets = new RooMCStudy(ext_hpdf_wjets,mass,Binned(kTRUE),Silence(kTRUE));
	mc_wjets->generate(Nsamples,0,kFALSE,"data/toymc_wjets_%04d.dat");
	RooMCStudy *mc_zjets = new RooMCStudy(ext_hpdf_zjets,mass,Binned(kTRUE),Silence(kTRUE));
	mc_zjets->generate(Nsamples,0,kFALSE,"data/toymc_zjets_%04d.dat");
	RooMCStudy *mc_qcd = new RooMCStudy(ext_hpdf_qcd,mass,Binned(kTRUE),Silence(kTRUE));
	mc_qcd->generate(Nsamples,0,kFALSE,"data/toymc_qcd_%04d.dat");
	RooMCStudy *mc_ST = new RooMCStudy(ext_hpdf_ST,mass,Binned(kTRUE),Silence(kTRUE),FitOptions(ExternalConstraints(STgaussConstraint)));
	mc_ST->generate(Nsamples,0,kFALSE,"data/toymc_ST_%04d.dat");

	return;
*/	
	RooMCStudy *mcstudy = new RooMCStudy(model_M3, mass, FitModel(model_histpdf),Binned(kTRUE),Silence(kTRUE), Extended() , 
										 //FitOptions(Save(kTRUE),Minos(kTRUE),Extended()) );
										 FitOptions(Save(kTRUE),Minos(kTRUE),Extended(),ExternalConstraints(STgaussConstraint)));//RooArgList(fconstext,fconstext2)) )); //gaussian constraint
	
		
	//mcstudyM3->generate(Nsamples,0,kFALSE,"toymc.dat");
	//mcstudyM3->generateAndFit(Nsamples,0,kFALSE,"toymc.dat");
	
	//TList dataList;
	//for (int isample=0; isample<Nsamples; ++isample) dataList.Add( mcstudyM3->genData(isample));

	
	// Fit
	mcstudy->generateAndFit(Nsamples,0,kTRUE);
	//mcstudy->fit(Nsamples, "data/toymc_%04d.dat");

		
	gDirectory->Add(mcstudy) ;	
	// E x p l o r e   r e s u l t s   o f   s t u d y 
	// ------------------------------------------------

	// Make plots of the distributions of mean, the error on mean and the pull of mean
	RooPlot* frame1 = mcstudy->plotParam(Ntt,Bins(40));
	RooPlot* frame2 = mcstudy->plotError(Ntt,Bins(40)) ;
	RooPlot* frame3 = mcstudy->plotPull(Ntt,Bins(40),FitGauss(kTRUE)) ;
	RooPlot* frame1w = mcstudy->plotParam(Nbkg,Bins(40)) ;
	RooPlot* frame2w = mcstudy->plotError(Nbkg,Bins(40)) ;
	RooPlot* frame3w = mcstudy->plotPull(Nbkg,Bins(40),FitGauss(kTRUE)) ;
	RooPlot* frame1st = mcstudy->plotParam(NST,Bins(40)) ;
	RooPlot* frame2st = mcstudy->plotError(NST,Bins(40)) ;
	//RooPlot* frame3st = mcstudy->plotPull(NST,Bins(40),FitGauss(kTRUE)) ;
	
	// Plot distribution of minimized likelihood
	RooPlot* frame4 = mcstudy->plotNLL(Bins(40)) ;

	// Make some histograms from the parameter dataset
	TH1* hh_cor_ttbar_w = mcstudy->fitParDataSet().createHistogram("hh",Ntt,YVar(Nbkg)) ;

	// Access some of the saved fit results from individual toys
	//TH2* corrHist000 = mcstudy->fitResult(0)->correlationHist("c000") ;
	//TH2* corrHist127 = mcstudy->fitResult(127)->correlationHist("c127") ;
	//TH2* corrHist953 = mcstudy->fitResult(953)->correlationHist("c953") ;

	
	// Draw all plots on a canvas
	gStyle->SetPalette(1) ;
	gStyle->SetOptStat(0) ;

	TCanvas* cv = new TCanvas("cv","cv",600,600) ;
	hM3->SetFillColor(kRed);
	hWjets->SetFillColor(kGreen);
	hM3->Draw();
	hWjets->Draw("same");
	gPad->RedrawAxis();
	
	TCanvas* cva = new TCanvas("cva","cva",1800,600) ;
	cva->Divide(3);
	cva->cd(1) ;
	RooPlot *initialframe = mass.frame();
	//initial->SetMaximum(10);
	hpdf_ttbar.plotOn(initialframe,LineColor(kRed));
	hpdf_wjetsFast.plotOn(initialframe,LineColor(kGreen));
	hpdf_ST.plotOn(initialframe,LineColor(kYellow));
	initialframe->Draw();
	//initialframe->SetTitle();
	cva->cd(2);
	//retrieve data for only one PE
	
	int Npe = 10;
	RooPlot *genframe = mass.frame(Nbins);
	RooDataSet *gendata = mcstudy->genData(Npe);
	cout << " N events = " << gendata->numEntries() << endl;
	gendata->plotOn(genframe);
	//mcstudy->fitResult(Npe)->plotOn(genframe, model_histpdf);
	genframe->Draw();
	cva->cd(3);
	RooPlot *genframe2 = mass.frame(Nbins);
	mcstudy->fitResult(Npe)->Print("v");
	gendata->plotOn(genframe2);
	RooArgList arglist = mcstudy->fitResult(Npe)->floatParsFinal();

	
	//cout << "name of argument:" << arglist[2].GetName() << endl;
	//cout << "name of argument:" << arglist[1].GetName() << endl;
	//cout << "name of argument:" << arglist[0].GetName() << endl;
	
	RooAddPdf model_histpdf_fitted("modelfitted", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjetsFast,hpdf_ST),
							   RooArgList(arglist[2],arglist[1],arglist[0]) ) ;
	
	model_histpdf_fitted.plotOn(genframe2,LineColor(kRed));
	model_histpdf_fitted.plotOn(genframe2,Components(hpdf_wjetsFast),LineColor(kGreen));
	model_histpdf_fitted.plotOn(genframe2,Components(hpdf_ST),LineColor(kYellow));
	genframe2->Draw();

	TCanvas* cvb = new TCanvas("cvb","cvb",1800,600) ;
	cvb->Divide(3);
	cvb->cd(1) ; frame1->Draw();
	cvb->cd(2) ; frame2->Draw();
	cvb->cd(3) ; frame3->Draw();
	TCanvas* cvbb = new TCanvas("cvbb","cvbb",1800,600) ;
	cvbb->Divide(3);
	cvbb->cd(1) ; frame1w->Draw();
	cvbb->cd(2) ; frame2w->Draw();
	cvbb->cd(3) ; frame3w->Draw();

	TCanvas* cvbbb = new TCanvas("cvbbb","cvbbb",1200,600) ;
	cvbbb->Divide(2);
	cvbbb->cd(1) ; frame1st->Draw();
	cvbbb->cd(2) ; frame2st->Draw();
	//cvbbb->cd(3) ; frame3st->Draw();
	
	TCanvas* cvbc = new TCanvas("cvbc","cvbc",600,600) ;
	TH2 *h2 = Ntt.createHistogram("Nttbar vs NWjets",Nbkg);
	mcstudy->fitParDataSet().fillHistogram(h2,RooArgList(Ntt,Nbkg));
	h2->Draw("box");

	
	TCanvas* cvc = new TCanvas("cvc","cvc",600,600) ;	
	// Plot distribution of minimized likelihood
	RooPlot* frame4 = mcstudy->plotNLL(Bins(40)) ;
	frame4->Draw();

	//return;//debuging

	
	TCanvas* cvd = new TCanvas("cvd","cvd",600,600) ;
	TCanvas* cve = new TCanvas("cve","cve",1200,600) ;
	TCanvas* cvf = new TCanvas("cvf","cvf",600,600) ;

	TH1F *hNgen = new TH1F("hNgen","Number of observed events",30,350,650);
	hNgen->SetXTitle("Number of observed events");

	TH1F *hNttresults = new TH1F("hNttresults","number of ttbar events",50,20,600);
	TH1F *hNWresults = new TH1F("hNWresults","number of W events",50,-150,400);
	TH1F *hNSTresults = new TH1F("hNSTresults","number of ttbar events",50,5,25);
									 
	bool gotone = false;
	int Nfailed = 0;
	for ( int i=0; i< Nsamples; i++)
	{
		
		RooFitResult *r = mcstudy->fitResult(i);
		RooArgList list = r->floatParsFinal();
		RooRealVar *rrv_nt = (RooRealVar*)list.at(2);
		double nt = rrv_nt->getVal();
		//double nte= rrv_nt->getError();
		RooRealVar *rrv_nw = (RooRealVar*)list.at(1);
		double nw = rrv_nw->getVal();
		//double nwe= rrv_nw->getError();
		RooRealVar *rrv_nst = (RooRealVar*)list.at(0);
		double nst = rrv_nst->getVal();

				
		hNttresults->Fill(nt);
		hNWresults->Fill(nw);
		hNSTresults->Fill(nst);
		
		
		RooDataSet *adata = mcstudy->genData(i);
		hNgen->Fill(adata->numEntries());
		
		if ( r->numInvalidNLL() > 0 ) Nfailed++;
		
		
		/*
		if ( false ) {
			cout << " sample # " << i << endl;
			gotone = true;
			r->Print("v");
			cout << " invalidNLL = "<< r->numInvalidNLL() << endl;
			cout << " N events = " << adata->numEntries() << endl;

			
			RooAddPdf amodel("amodel", "TTjets+Wjets", RooArgList(hpdf_ttbar,hpdf_wjets,hpdf_ST),
							 RooArgList(list[2],list[1],list[0])) ;
			RooPlot *d2 = new RooPlot(Ntt,NW,0,500,-200,200);
			r->plotOn(d2,Ntt,NW,"ME12ABHV");
			cvd->cd();
			d2->Draw();
			
			RooNLLVar nll("nll","nll", amodel, *adata, Extended() );//, Extended(), PrintEvalErrors(-1) );
			RooMinuit myminuit(nll)
			myminuit.migrad();
			myminuit.hesse();
			myminuit.minos();
			//myminuit.Save()->Print("v");

			cve->Divide(2);
			RooPlot *nllframett = Ntt.frame(Bins(50),Range(100,600));//,Range(10,2000));
			nll.plotOn(nllframett);//,ShiftToZero());
						
			RooProfileLL pll_ntt("pll_ntt","pll_ntt",nll,Ntt);
			pll_ntt.plotOn(nllframett,LineColor(kRed));

			RooPlot *nllframeW = NW.frame(Bins(50),Range(0,250));//,Range(10,2000));
			nll.plotOn(nllframeW);//,ShiftToZero());
						
			RooProfileLL pll_nW("pll_nW","pll_nW",nll,NW);
			pll_nW.plotOn(nllframeW,LineColor(kRed));

			cve->cd(1);
			nllframett->SetMaximum(2);
			nllframett->Draw();
			cve->cd(2);
			nllframeW->SetMaximum(2);
			nllframeW->Draw();
			
		}
		*/
	}

	TCanvas *tmpcv = new TCanvas("tmpcv","tmpcv",700,700);
	cout << "\n ==================================" << endl;
	cout << "gaussian fit of Nttbar fitted values: " << endl;
	//hNttresults->Print("all");
	hNttresults->Fit("gaus");

	cout << "\n ==================================" << endl;
	cout << "gaussian fit of NW fitted values: " << endl;
	//hNWresults->Print("all");
	hNWresults->Fit("gaus");

	cout << "\n ==================================" << endl;
	cout << "gaussian fit of NST fitted values: " << endl;
	//hNSTresults->Print("all");
	hNSTresults->Fit("gaus");

	
	cout << "N failed fits = " << Nfailed << endl;
	
	cvf->cd();
	hNgen->Draw();
	
	// Make RooMCStudy object available on command line after
	// macro finishes
	//gDirectory->Add(mcstudy) ;
}
Ejemplo n.º 21
0
void crossfeeds_nondiag(TString title, 
			TString bkgfile,
			TString epsfile,
			TString txtfile,
			Double_t alpha_,
			Double_t mass_,
			Double_t n_,
			Double_t sigma_
			)
{

  RooRealVar mbc("mbc", "m_{BC}", 1.83, 1.89, "GeV");
  RooRealVar ebeam("ebeam", "Ebeam", 0., 100., "GeV");
  RooRealVar chg("chg", "Charge", -2, 2);
  RooCategory passed("passed", "Event should be used for plot");

  passed.defineType("yes", 1);
  passed.defineType("no", 0);

  RooRealVar arg_cutoff ("arg_cutoff", "Argus cutoff", 1.8865, 1.885, 1.8875,"GeV"); 
  RooRealVar arg_slope ("arg_slope", "Argus slope", -13, -100, 40);

  RooRealVar mbc_float ("mbc_float", "Floating D mass", mass_, "GeV"); 
  RooRealVar sigma ("sigma", "CB width", sigma_, "GeV"); 
  RooRealVar alpha("alpha", "CB shape cutoff", alpha_);
  RooRealVar n("n", "CB tail parameter", n_);

  RooCBShape cb_float ("cb_float", "Floating Crystal Barrel", mbc, mbc_float, sigma, alpha, n); 
  RooArgusBG argus("argus", "Argus BG", mbc, arg_cutoff, arg_slope);

  RooRealVar yld("yield", "D yield", 0, -30, 100000); 
  RooRealVar bkg("bkg", "Background", 20, 0, 40000);

  // Build pdf
  RooAddPdf sumpdf_float("sumpdf_float", "Generic D sum pdf", RooArgList(cb_float, argus),
			   RooArgList(yld, bkg));
  
  RooDataSet* dset = RooDataSet::read(bkgfile, RooArgList(mbc, ebeam, passed), "", "");

  RooPlot* xframe  = mbc.frame();

  RooDataSet* dset2 = dset->reduce("passed==1");

  dset2->plotOn(xframe);
  
  // RooFitResult* rv = sumpdf_float.fitTo(*dset2, Extended(kTRUE), Save(kTRUE),
  // 					Hesse(kTRUE), Verbose(kTRUE));
  RooFitResult* rv = sumpdf_float.fitTo(*dset2, "ermh");

  sumpdf_float.paramOn(xframe, dset2);

  if ((yld.getVal() < 0) && (-yld.getVal()/bkg.getVal() > 0.5)){
    yld.setVal(0);
    bkg.setVal(1);
  }
  
  sumpdf_float.plotOn(xframe);
  sumpdf_float.plotOn(xframe, Components(RooArgSet(argus)),
                      LineColor(kRed), LineStyle(kDashed));

  TCanvas* c1 = new TCanvas("c1","Canvas", 2);
  
  xframe->SetTitleOffset(2.2, "Y");
  xframe->SetTitleOffset(1.1, "X");
  xframe->SetTitle(title);

  c1->SetLeftMargin(0.17);
  xframe->Draw();
  
  if ( rv && rv->covQual() != 3){
    // fit has failed
    TText *txt = new TText();
    txt->SetTextSize(.08);
    txt->SetTextAlign(22);
    txt->SetTextAngle(30);
    txt->DrawTextNDC(0.5, 0.5, "FAILED");
  }
  

  c1->Update();
  c1->Print(epsfile);
  c1->Clear();

  FILE* table = fopen(txtfile.Data(), "w+");
  fprintf(table, "Name\t|| Value\t|| Error\n");
  //  fprintf(table, "yldsigma\t| %.10f\t| \n", yld.getVal()/yld.getError());
  fprintf(table, "entries\t| %.10f\t| \n", dset->numEntries());
  fprintf(table, "yld\t| %.10f\t| %.10f\n",  yld.getVal(), yld.getError());
  //  fprintf(table, "ratio\t| %.10f\t| \n",  yld.getVal()/dset->numEntries());
  //  fprintf(table, "ratioerr\t| %.10f\t| \n",  yld.getError()/dset->numEntries());
  fclose(table);

  cout << "Saved output as: " << txtfile << endl;

  rv->Delete();
}
int main(int argc, char *argv[]){

	OptionParser(argc,argv);
	

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


  
	system(Form("mkdir -p %s",outdir_.c_str()));

	vector<string> procs;
	split(infilenames_,infilenamesStr_,boost::is_any_of(","));
  
   TPython::Exec("import os,imp,re");
    const char * env = gSystem->Getenv("CMSSW_BASE") ; 
      std::string globeRt = env;
      TPython::Exec(Form("buildSMHiggsSignalXSBR = imp.load_source('*', '%s/src/flashggFinalFit/Signal/python/buildSMHiggsSignalXSBR.py')",globeRt.c_str()));
      TPython::Eval(Form("buildSMHiggsSignalXSBR.Init%dTeV()", 13));
   for (unsigned int i =0 ; i<infilenames_.size() ; i++){
	    int mH  =(int) TPython::Eval(Form("int(re.search('_M(.+?)_','%s').group(1))",infilenames_[i].c_str())); 
	   double WH_XS  =  (double)TPython::Eval(Form("buildSMHiggsSignalXSBR.getXS(%d,'%s')",mH,"WH"));
	   double ZH_XS  =  (double)TPython::Eval(Form("buildSMHiggsSignalXSBR.getXS(%d,'%s')",mH,"ZH"));
     float tot_XS = WH_XS + ZH_XS;
     float wFrac=  WH_XS /tot_XS ;
     float zFrac=  ZH_XS /tot_XS ;
      std::cout << "mass "<< mH << " wh fraction "<< WH_XS /tot_XS << ", zh fraction "<< ZH_XS /tot_XS <<std::endl; 
     TFile *infile =  TFile::Open(infilenames_[i].c_str());
	   string outname  =(string) TPython::Eval(Form("'%s'.split(\"/\")[-1].replace(\"VH\",\"WH_VH\")",infilenames_[i].c_str())); 
     TFile *outfile = TFile::Open(outname.c_str(),"RECREATE") ;
    TDirectory* saveDir = outfile->mkdir("tagsDumper");
    saveDir->cd();

    RooWorkspace *inWS = (RooWorkspace*) infile->Get("tagsDumper/cms_hgg_13TeV");
    RooRealVar *intLumi = (RooRealVar*)inWS->var("IntLumi");
    RooWorkspace *outWS = new RooWorkspace("cms_hgg_13TeV");
    outWS->import(*intLumi);
    std::list<RooAbsData*> data =  (inWS->allData()) ;
    std::cout <<" [INFO] Reading WS dataset contents: "<< std::endl;
        for (std::list<RooAbsData*>::const_iterator iterator = data.begin(), end = data.end(); iterator != end; ++iterator )  {
              RooDataSet *dataset = dynamic_cast<RooDataSet *>( *iterator );
              if (dataset) {
	            string zhname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"zh\")",dataset->GetName())); 
	            string whname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"wh\")",dataset->GetName())); 
              RooDataSet *datasetZH = (RooDataSet*) dataset->emptyClone(zhname.c_str(),zhname.c_str());
              RooDataSet *datasetWH = (RooDataSet*) dataset->emptyClone(whname.c_str(),whname.c_str());
                TRandom3 r;
                r.Rndm();
                double x[dataset->numEntries()];
                r.RndmArray(dataset->numEntries(),x);
                for (int j =0; j < dataset->numEntries() ; j++){
                    
                    if( x[j] < wFrac){
                    dataset->get(j);
                    datasetWH->add(*(dataset->get(j)),dataset->weight());
                    } else{
                    dataset->get(j);
                    datasetZH->add(*(dataset->get(j)),dataset->weight());
                    }
                }
              float w =datasetWH->sumEntries();
              float z =datasetZH->sumEntries();
           if(verbose_){
              std::cout << "Original dataset " << *dataset <<std::endl;
              std::cout << "WH       dataset " << *datasetWH <<std::endl;
              std::cout << "ZH       dataset " << *datasetZH <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : WH " << w/(w+z) <<",   ZH "<< z/(w+z) << std::endl;
              std::cout << "WH fraction (exp) : WH " << wFrac <<",   ZH "<< zFrac << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datasetWH);
               outWS->import(*datasetZH);
                }
             RooDataHist *datahist = dynamic_cast<RooDataHist *>( *iterator );

              if (datahist) {
	            string zhname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"zh\")",datahist->GetName())); 
	            string whname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"wh\")",datahist->GetName())); 
              RooDataHist *datahistZH = (RooDataHist*) datahist->emptyClone(zhname.c_str(),zhname.c_str());
              RooDataHist *datahistWH = (RooDataHist*) datahist->emptyClone(whname.c_str(),whname.c_str());
                TRandom3 r;
                r.Rndm();
                double x[datahist->numEntries()];
                r.RndmArray(datahist->numEntries(),x);
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistWH->add(*(datahist->get(j)),datahist->weight()*wFrac);
                    datahistZH->add(*(datahist->get(j)),datahist->weight()*zFrac);
                }
              float w =datahistWH->sumEntries();
              float z =datahistZH->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "WH       datahist " << *datahistWH <<std::endl;
              std::cout << "ZH       datahist " << *datahistZH <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : WH " << w/(w+z) <<",   ZH "<< z/(w+z) << std::endl;
              std::cout << "WH fraction (exp) : WH " << wFrac <<",   ZH "<< zFrac << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistWH);
               outWS->import(*datahistZH);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
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;

}
void embeddedToysWithBackgDetEffects_1DKD(int nEvts=600, int nToys=3000,
					  sample mySample = kScalar_fa3p5, 
					  bool bkg, bool sigFloating, int counter){
  
  RooRealVar* kd = new RooRealVar("psMELA","psMELA",0,1);
  kd->setBins(1000);
  RooPlot* kdframe1 = kd->frame();
  
  // 0- template
  TFile f1("KDdistribution_ps_analytical_detEff.root", "READ"); 
  TH1F *h_KD_ps = (TH1F*)f1.Get("h_KD");
  h_KD_ps->SetName("h_KD_ps");
  RooDataHist rdh_KD_ps("rdh_KD_ps","rdh_KD_ps",RooArgList(*kd),h_KD_ps);
  RooHistPdf pdf_KD_ps("pdf_KD_ps","pdf_KD_ps",RooArgList(*kd),rdh_KD_ps); 

  // 0+ template
  TFile f2("KDdistribution_sm_analytical_detEff.root", "READ"); 
  TH1F *h_KD_sm = (TH1F*)f2.Get("h_KD");
  h_KD_sm->SetName("h_KD_sm");
  RooDataHist rdh_KD_sm("rdh_KD_sm","rdh_KD_sm",RooArgList(*kd),h_KD_sm);
  RooHistPdf pdf_KD_sm("pdf_KD_sm","pdf_KD_sm",RooArgList(*kd),rdh_KD_sm); 

  // backg template
  TFile f3("KDdistribution_bkg_analytical_detEff.root", "READ"); 
  TH1F *h_KD_bkg = (TH1F*)f3.Get("h_KD");
  h_KD_bkg->SetName("h_KD_bkg");
  RooDataHist rdh_KD_bkg("rdh_KD_bkg","rdh_KD_bkg",RooArgList(*kd),h_KD_bkg);
  RooHistPdf pdf_KD_bkg("pdf_KD_bkg","pdf_KD_bkg",RooArgList(*kd),rdh_KD_bkg); 

  //Define signal model with 0+, 0- mixture
  RooRealVar rrv_fa3("fa3","fa3",0.5,0.,1.);  //free parameter of the model
  RooFormulaVar rfv_fa3Obs("fa3obs","1/ (1 + (1/@0 - 1)*0.99433)",RooArgList(rrv_fa3));
  RooAddPdf modelSignal("modelSignal","ps+sm",pdf_KD_ps,pdf_KD_sm,rfv_fa3Obs);  
  rrv_fa3.setConstant(kFALSE);
  
  //Define signal+bakground model
  RooRealVar rrv_BoverTOT("BoverTOT","BoverTOT",1/(3.75+1),0.,10.);  
  RooAddPdf model("model","background+modelSignal",pdf_KD_bkg,modelSignal,rrv_BoverTOT);  
  if(sigFloating)
    rrv_BoverTOT.setConstant(kFALSE);
  else
    rrv_BoverTOT.setConstant(kTRUE);

  //Set the values of free parameters to compute pulls
  double fa3Val=-99;
  if (mySample == kScalar_fa3p0)
    fa3Val=0.;
  else if (mySample == kScalar_fa3p1)
    fa3Val=0.1;
  else if (mySample == kScalar_fa3p5 || mySample == kScalar_fa3p5phia390)
    fa3Val=0.5;
  else if (mySample == kScalar_fa3p25)
    fa3Val=0.25;
  else{
    cout<<"fa3Val not correct!"<<endl;
      return 0;
  }
  double sigFracVal=1 - 1/(3.75+1);

  //Plot the models
  TCanvas* c = new TCanvas("modelPlot_detBkg","modelPlot_detBkg",400,400);
  rdh_KD_ps.plotOn(kdframe1,LineColor(kBlack),MarkerColor(kBlack));
  pdf_KD_ps.plotOn(kdframe1,LineColor(kBlack),RooFit::Name("pseudo"));
  //rdh_KD_sm.plotOn(kdframe1,LineColor(kBlue),MarkColor(kBlue));
  pdf_KD_sm.plotOn(kdframe1,LineColor(kBlue),RooFit::Name("SM"));
  //rdh_KD_bkg.plotOn(kdframe1,LineColor(kGreen),LineColor(kGreen));
  pdf_KD_bkg.plotOn(kdframe1,LineColor(kGreen),RooFit::Name("bkg"));
  modelSignal.plotOn(kdframe1,LineColor(kRed),RooFit::Name("signal_fa3p5"));
  model.plotOn(kdframe1,LineColor(kOrange),RooFit::Name("signal+background"));
  TLegend *leg = new TLegend (0.7,0.6,0.95,0.8);
  leg->AddEntry(kdframe1->findObject("pseudo"),"0-","L");
  leg->AddEntry(kdframe1->findObject("SM"),"0+","L");
  leg->AddEntry(kdframe1->findObject("bkg"),"bkg","L");
  leg->AddEntry(kdframe1->findObject("signal_fa3p5"),"signal fa3=0.5","L");
  leg->AddEntry(kdframe1->findObject("signal+background"),"signal + bkg","L");
  kdframe1->Draw();
  leg->SetFillColor(kWhite);
  leg->Draw("same");
  c->SaveAs("modelPlot_detBkg.eps");
  c->SaveAs("modelPlot_detBkg.png");

  
  //Load the trees into the datasets
  TChain* myChain = new TChain("SelectedTree");
  myChain->Add(inputFileNames[mySample]);
  if(!myChain || myChain->GetEntries()<=0) {
    cout<<"error in the tree"<<endl;
    return 0;
  }
  RooDataSet* data = new RooDataSet("data","data",myChain,RooArgSet(*kd),"");

  TChain* myChain_bkg = new TChain("SelectedTree");
  myChain_bkg->Add("samples/analyticalpsMELA/withResolution/pwgevents_mllCut10_smeared_withDiscriminants_2e2mu_cutDetector.root");
  myChain_bkg->Add("samples/analyticalpsMELA/withResolution/pwgevents_mllCut4_wResolution_withDiscriminants_cutDetector.root");
  if(!myChain_bkg || myChain_bkg->GetEntries()<=0) {
    cout<<"error in the tree"<<endl;
    return 0;
  }
  RooDataSet* data_bkg = new RooDataSet("data_bkg","data_bkg",myChain_bkg,RooArgSet(*kd),"");

  cout << "Number of events in data sig: " << data->numEntries() << endl;
  cout << "Number of events in data bkg: " << data_bkg->numEntries() << endl;
  
  // Initialize tree to save toys to 
  TTree* results = new TTree("results","toy results");
  
  double fa3,fa3Error, fa3Pull;
  double sigFrac,sigFracError, sigFracPull;
  double significance;

  results->Branch("fa3",&fa3,"fa3/D");
  results->Branch("fa3Error",&fa3Error,"fa3Error/D");
  results->Branch("fa3Pull",&fa3Pull,"fa3Pull/D");
  results->Branch("sigFrac",&sigFrac,"sigFrac/D");
  results->Branch("sigFracError",&sigFracError,"sigFracError/D");
  results->Branch("sigFracPull",&sigFracPull,"sigFracPull/D");
  results->Branch("significance",&significance,"significance/D");

  //---------------------------------

  RooDataSet* toyData;
  RooDataSet* toyData_bkgOnly;
  int embedTracker=nEvts*counter;
  int embedTracker_bkg=TMath::Ceil(nEvts/3.75*counter);
  RooArgSet *tempEvent;

  RooFitResult *toyfitresults;
  RooFitResult *toyfitresults_sigBkg;
  RooFitResult *toyfitresults_bkgOnly;
  RooRealVar *r_fa3;
  RooRealVar *r_sigFrac;

  for(int i = 0 ; i<nToys ; i++){
    cout <<i<<"<-----------------------------"<<endl;
    //if(toyData) delete toyData;
    toyData = new RooDataSet("toyData","toyData",RooArgSet(*kd));
    toyData_bkgOnly = new RooDataSet("toyData_bkgOnly","toyData_bkgOnly",RooArgSet(*kd));

    if(nEvts+embedTracker > data->sumEntries()){
      cout << "Playground::generate() - ERROR!!! Playground::data does not have enough events to fill toy!!!!  bye :) " << endl;
      toyData = NULL;
      abort();
      return 0;
    }
    if(nEvts+embedTracker_bkg > data_bkg->sumEntries()){
      cout << "Playground::generate() - ERROR!!! Playground::data does not have enough events to fill toy!!!!  bye :) " << endl;
      toyData = NULL;
      abort();
      return 0;
    }

    for(int iEvent=0; iEvent<nEvts; iEvent++){
      if(iEvent==1)
	cout << "generating event: " << iEvent << " embedTracker: " << embedTracker << endl;
      tempEvent = (RooArgSet*) data->get(embedTracker);
      toyData->add(*tempEvent);
      embedTracker++;
    }
    if(bkg){
      for(int iEvent=0; iEvent<nEvts/3.75; iEvent++){
	if(iEvent==1)
	  cout << "generating bkg event: " << iEvent << " embedTracker bkg: " << embedTracker_bkg << endl;
	tempEvent = (RooArgSet*) data_bkg->get(embedTracker_bkg);
	toyData->add(*tempEvent);
	toyData_bkgOnly->add(*tempEvent);
	embedTracker_bkg++;
      }
    }

    if(bkg)
      toyfitresults =model.fitTo(*toyData,Save());
    else
      toyfitresults =modelSignal.fitTo(*toyData,Save());

    //cout<<toyfitresults<<endl;
    r_fa3 = (RooRealVar *) toyfitresults->floatParsFinal().find("fa3");

    fa3 = r_fa3->getVal();
    fa3Error = r_fa3->getError();
    fa3Pull = (r_fa3->getVal() - fa3Val) / r_fa3->getError();
    if(sigFloating){
      r_sigFrac = (RooRealVar *) toyfitresults->floatParsFinal().find("BoverTOT");
      sigFrac = 1-r_sigFrac->getVal();
      sigFracError = r_sigFrac->getError();
      sigFracPull = (1-r_sigFrac->getVal() - sigFracVal) / r_sigFrac->getError();
    }
    // fill TTree
    results->Fill();
  }

  char nEvtsString[100];
  sprintf(nEvtsString,"_%iEvts_%iiter",nEvts, counter);

  // write tree to output file (ouputFileName set at top)
  TFile *outputFile = new TFile("embeddedToys1DKD_fa3Corr_WithBackgDetEffects_"+sampleName[mySample]+nEvtsString+".root","RECREATE");
  results->Write();
  outputFile->Close();

}
Ejemplo n.º 25
0
void StandardFeldmanCousinsDemo(const char* infile = "",
                                const char* workspaceName = "combined",
                                const char* modelConfigName = "ModelConfig",
                                const char* dataName = "obsData"){

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


   // -------------------------------------------------------
   // Tutorial starts here
   // -------------------------------------------------------

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

   // -------------------------------------------------------
   // 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
   FeldmanCousins fc(*data,*mc);
   fc.SetConfidenceLevel(0.95); // 95% interval
   //fc.AdditionalNToysFactor(0.1); // to speed up the result
   fc.UseAdaptiveSampling(true); // speed it up a bit
   fc.SetNBins(10); // set how many points per parameter of interest to scan
   fc.CreateConfBelt(true); // save the information in the belt for plotting

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

   // We can use PROOF to speed things along in parallel
   //  ProofConfig pc(*w, 1, "workers=4", kFALSE);
   //  ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   //  toymcsampler->SetProofConfig(&pc); // enable proof


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

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

   // ---------------------------------------------
   // No nice plots yet, so plot the belt by hand

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

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

}
void makejpsifit(string inputFilename, string outFilename, 
		 Int_t ptBin, Int_t etaBin,
		 double minMass, double maxMass, 
		 double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, 
		 const char* plotOpt, const int nbins, Int_t isMC) {

  TStyle *mystyle = RooHZZStyle("ZZ");
  mystyle->cd();

  //Create Data Set
  RooRealVar mass("zmass","m(e^{+}e^{-})",minMass,maxMass,"GeV/c^{2}");

  // Reading everything from root tree instead
  TFile *tfile = TFile::Open(inputFilename.c_str());
  TTree *ttree = (TTree*)tfile->Get("zeetree/probe_tree");
  hzztree *zeeTree = new hzztree(ttree);

  RooArgSet zMassArgSet(mass);
  RooDataSet* data = new RooDataSet("data", "ntuple parameters", zMassArgSet);

  for (int i = 0; i < zeeTree->fChain->GetEntries(); i++) {
    if(i%100000==0) cout << "Processing Event " << i << endl;
    zeeTree->fChain->GetEntry(i);

    //*************************************************************************
    //Electron Selection
    //*************************************************************************
    // already passed for this tree

    //*************************************************************************
    //Compute electron four vector;
    //*************************************************************************
    double ele1pt = zeeTree->l1pt;
    double ele2pt = zeeTree->l2pt;

    double ELECTRONMASS = 0.51e-3;
    TLorentzVector ele1FourVector;
    ele1FourVector.SetPtEtaPhiM(zeeTree->l1pt, zeeTree->l1eta, zeeTree->l1phi, ELECTRONMASS);
    TLorentzVector ele2FourVector;
    ele2FourVector.SetPtEtaPhiM(zeeTree->l2pt, zeeTree->l2eta, zeeTree->l2phi, ELECTRONMASS);

    
    //*************************************************************************
    //pt and eta cuts on electron
    //*************************************************************************
    if (! (ele1pt > 7 && ele2pt > 7
           && fabs( zeeTree->l1eta) < 2.5 
           && fabs( zeeTree->l2eta) < 2.5 )) continue;

    //*************************************************************************
    //pt bins and eta bins
    //*************************************************************************
    Int_t Ele1PtBin = -1;
    Int_t Ele1EtaBin = -1;
    Int_t Ele2PtBin = -1;
    Int_t Ele2EtaBin = -1;
    if (ele1pt > 7 && ele1pt < 10) Ele1PtBin = 0;
    else if (ele1pt < 20) Ele1PtBin = 1;
    else Ele1PtBin = 2;
    if (ele2pt > 7 && ele2pt < 10) Ele2PtBin = 0;
    else if (ele2pt < 20) Ele2PtBin = 1;
    else Ele2PtBin = 2;
    if (fabs(zeeTree->l1sceta) < 1.479) Ele1EtaBin = 0;
    else Ele1EtaBin = 1;
    if (fabs(zeeTree->l2sceta) < 1.479) Ele2EtaBin = 0;
    else Ele2EtaBin = 1;

    if (!(Ele1PtBin == ptBin || Ele2PtBin == ptBin)) continue; 
    if (!(Ele1EtaBin == etaBin && Ele2EtaBin == etaBin)) continue; 
    
    //*************************************************************************
    // restrict range of mass
    //*************************************************************************
    double zMass = (ele1FourVector+ele2FourVector).M();
    if (zMass < minMass || zMass > maxMass) continue;

    //*************************************************************************
    //set mass variable
    //*************************************************************************
    zMassArgSet.setRealValue("zmass", zMass);    

    data->add(zMassArgSet);
  }

  // do binned fit to gain time...
  mass.setBins(nbins);
  RooDataHist *bdata = new RooDataHist("data_binned","data_binned", zMassArgSet, *data);

  cout << "dataset size: " << data->numEntries() << endl;

//   // Closing file
//   treeFile->Close();
  //====================== Parameters===========================

  //Crystal Ball parameters
//   RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
//   RooRealVar cbSigma("sigma_{CB}", "CB Width", 1.7, 0.8, 5.0, "GeV/c^{2}");
//   RooRealVar cbCut  ("a_{CB}","CB Cut", 1.05, 1.0, 3.0);
//   RooRealVar cbPower("n_{CB}","CB Order", 2.45, 0.1, 20.0);
  RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
  RooRealVar cbSigma("#sigma_{CB}", "CB Width", 1.5, 0.01, 5.0, "GeV/c^{2}");
  RooRealVar cbCut  ("a_{CB}","CB Cut", 1.0, 1.0, 3.0);
  RooRealVar cbPower("n_{CB}","CB Order", 2.5, 0.1, 20.0);
  cbCut.setVal(cutoff_cb);
  cbPower.setVal(power_cb);

  // Just checking
  //cbCut.Print();
  //cbPower.Print();

  //Breit_Wigner parameters
  RooRealVar bwMean("m_{JPsi}","BW Mean", 3.096916, "GeV/c^{2}");
  bwMean.setVal(mean_bw);
  RooRealVar bwWidth("#Gamma_{JPsi}", "BW Width", 92.9e-6, "GeV/c^{2}");
  bwWidth.setVal(gamma_bw);

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

  // Exponential Background parameters
  RooRealVar expRate("#lambda_{exp}", "Exponential Rate", -0.064, -1, 1);
  RooRealVar c0("c_{0}", "c0", 1., 0., 50.);

  //Number of Signal and Background events
  RooRealVar nsig("N_{S}", "# signal events", 524, 0.1, 10000000000.);
  RooRealVar nbkg("N_{B}", "# background events", 43, 1., 10000000.);

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

  // Mass signal for two decay electrons p.d.f.
  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);

  // Mass background p.d.f.
  RooExponential bg("bg", "exp. background", mass, expRate);

  // Mass model for signal electrons p.d.f.
  RooAddPdf model("model", "signal", RooArgList(BWxCB), RooArgList(nsig));

  TStopwatch t ;
  t.Start() ;
  double fitmin, fitmax;
  if(isMC) {
    fitmin = (etaBin==0) ? 3.00 : 2.7;
    fitmax = (etaBin==0) ? 3.20 : 3.4;
  } else {
    fitmin = (etaBin==0) ? ( (ptBin>=2) ? 3.01 : 3.02 ) : 2.7;
    fitmax = (etaBin==0) ? ( (ptBin==3) ? 3.23 : 3.22 ) : 3.4;
  }
  RooFitResult *fitres = model.fitTo(*bdata,Range(fitmin,fitmax),Hesse(1),Minos(1),Timer(1),Save(1));
  fitres->SetName("fitres");
  t.Print() ;

  TCanvas* c = new TCanvas("c","Unbinned Invariant Mass Fit", 0,0,800,600);

  //========================== Plotting  ============================
  //Create a frame
  RooPlot* plot = mass.frame(Range(minMass,maxMass),Bins(nbins));
  // Add data and model to canvas
  int col = (isMC ? kAzure+4 : kGreen+1);
  data->plotOn(plot);
  model.plotOn(plot,LineColor(col));
  data->plotOn(plot);
  model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(cbBias, cbSigma, cbCut, cbPower, bwMean, bwWidth, expRate, nsig, nbkg)), Layout(0.15,0.45,0.80));
  plot->getAttText()->SetTextSize(.03);
  plot->SetTitle("");
  plot->Draw();

  // Print Fit Values
  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(.1);
  tex->SetTextFont(132);
  //  tex->Draw();
  tex->SetTextSize(0.057);
  if(isMC) tex->DrawLatex(0.65, 0.75, "J/#psi #rightarrow e^{+}e^{-} MC");
  else tex->DrawLatex(0.65, 0.75, "J/#psi #rightarrow e^{+}e^{-} data");
  tex->SetTextSize(0.030);
  tex->DrawLatex(0.645, 0.65, Form("BW Mean = %.2f GeV/c^{2}", bwMean.getVal()));
  tex->DrawLatex(0.645, 0.60, Form("BW #sigma = %.2f GeV/c^{2}", bwWidth.getVal()));
  c->Update();
  c->SaveAs((outFilename + ".pdf").c_str());
  c->SaveAs((outFilename + ".png").c_str());

  // tablefile << Form(Outfile + "& $ %f $ & $ %f $ & $ %f $\\ \hline",cbBias.getVal(), cbSigma.getVal(), cbCut.getVal());
  // Output workspace with model and data

  RooWorkspace *w = new RooWorkspace("JPsieeMassScaleAndResolutionFit");
  w->import(model);
  w->import(*bdata);
  w->writeToFile((outFilename + ".root").c_str());  

  TFile *tfileo = TFile::Open((outFilename + ".root").c_str(),"update");
  fitres->Write();
  tfileo->Close();

}
Ejemplo n.º 27
0
void trig_eta_P()
{
  TCanvas *myCan=new TCanvas("myCan","myCan");
  myCan->SetGrid();
  /************************
  TFile *f_RD= new TFile("TnP_Z_Trigger_RDpt.root","read");
  RooDataSet *dataset = (RooDataSet*)f_RD->Get("tpTree/Track_To_TightCombRelIso_Mu15_eta2p1_pt/fit_eff");
  cout<<"ntry: "<<dataset->numEntries()<<endl;
  double X[11],XerrL[11],XerrH[11],Y[11],YerrLo[11],YerrHi[11];
  for(int i(0); i<dataset->numEntries();i++)
  {
    const RooArgSet &point=*dataset->get(i);
    RooRealVar &pt=point["pt"],&eff = point["efficiency"];
    X[i]=pt.getVal();
    XerrL[i]=-pt.getAsymErrorLo();
    XerrH[i]=pt.getAsymErrorHi();
    Y[i]=eff.getVal();
    YerrLo[i]=-eff.getAsymErrorLo();
    YerrHi[i]=eff.getAsymErrorHi();
  }
  gr=new TGraphAsymmErrors(11,X,Y,XerrL,XerrH,YerrLo,YerrHi);
  gr->Draw("AP");
***************************/

///*
  TFile *f_MC= new TFile("../efficiency-mc-WptCutToHLT_eta_P.root","read");
  RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("WptCutToHLT/efficiency/cnt_eff");
  //RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTree/Track_with_TightCombRelIso_to_Mu15_eta2p1_pt/fit_eff");
  cout<<"ntry: "<<datasetMC->numEntries()<<endl;

  double XMC[binSize],XMCerrL[binSize],XMCerrH[binSize],YMC[binSize],YMCerrLo[binSize],YMCerrHi[binSize];
  for(int i(0); i<datasetMC->numEntries();i++)
  {
    const RooArgSet &pointMC=*datasetMC->get(i);
    RooRealVar &ptMC=pointMC["probe_sc_eta"],&effMC = pointMC["efficiency"];
    XMC[i]=ptMC.getVal();
    XMCerrL[i]=-ptMC.getAsymErrorLo();
    XMCerrH[i]=ptMC.getAsymErrorHi();
    YMC[i]=effMC.getVal();
    YMCerrLo[i]=-effMC.getAsymErrorLo();
    YMCerrHi[i]=effMC.getAsymErrorHi();
  }
  grMC=new TGraphAsymmErrors(binSize,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);

cout << "MC efficiency:  " << endl;
cout << "YMC:  " << effMC.getVal()<< " +/- " << - effMC.getAsymErrorLo() << endl;
cout << "YMCerrLo:  " <<- effMC.getAsymErrorLo() << endl;
cout << "YMCerrHi:  " << effMC.getAsymErrorHi() << endl;


  grMC->SetLineColor(kRed);
  grMC->SetMarkerColor(kRed);

///**///

//*

  TFile *f_RD= new TFile("../efficiency-data-WptCutToHLT_eta_P.root","read");
  RooDataSet *datasetRD = (RooDataSet*)f_RD->Get("WptCutToHLT/efficiency/cnt_eff");
  //RooDataSet *datasetMC = (RooDataSet*)f_MC->Get("tpTree/Track_with_TightCombRelIso_to_Mu15_eta2p1_pt/fit_eff");
  cout<<"ntry: "<<datasetRD->numEntries()<<endl;

  double XMC[binSize],XMCerrL[binSize],XMCerrH[binSize],YMC[binSize],YMCerrLo[binSize],YMCerrHi[binSize];
  for(int i(0); i<datasetRD->numEntries();i++)
  {
    const RooArgSet &pointRD=*datasetRD->get(i);
    RooRealVar &ptRD=pointRD["probe_sc_eta"],&effRD = pointRD["efficiency"];
    XMC[i]=ptRD.getVal();
    XMCerrL[i]=-ptRD.getAsymErrorLo();
    XMCerrH[i]=ptRD.getAsymErrorHi();
    YMC[i]=effRD.getVal();
    YMCerrLo[i]=-effRD.getAsymErrorLo();
    YMCerrHi[i]=effRD.getAsymErrorHi();
  }
  grRD=new TGraphAsymmErrors(binSize,XMC,YMC,XMCerrL,XMCerrH,YMCerrLo,YMCerrHi);

cout << "RD efficiency:  " << endl;
cout << "YMC:  " << effRD.getVal()<< " +/- " <<- effRD.getAsymErrorLo() << endl;
cout << "YMCerrLo:  " <<- effRD.getAsymErrorLo() << endl;
cout << "YMCerrHi:  " << effRD.getAsymErrorHi() << endl;




cout << "Scale factor  " << effRD.getVal()/effMC.getVal() << endl;
cout<<"Lo:"<<effRD.getVal()/effMC.getVal()*sqrt(effRD.getAsymErrorLo()*effRD.getAsymErrorLo()/effRD.getVal()/effRD.getVal() + effMC.getAsymErrorLo()*effMC.getAsymErrorLo()/effMC.getVal()/effMC.getVal() ) <<  endl;


cout<<"High:"<<effRD.getVal()/effMC.getVal()*sqrt(effRD.getAsymErrorHi()*effRD.getAsymErrorHi()/effRD.getVal()/effRD.getVal() + effMC.getAsymErrorHi()*effMC.getAsymErrorHi()/effMC.getVal()/effMC.getVal() ) <<  endl;


  grRD->SetLineColor(kBlue);
  grRD->SetMarkerColor(kBlue);

///***///

  //myCan->SetLogx();
// grMC->Draw("AP");

  grRD->Draw("AP");
  grRD->SetMinimum(0.8);
  grRD->SetMaximum(1.04);
  grRD->GetXaxis()->SetNdivisions(505);
  grMC->Draw("psame");

//TLegend *Lgd = new TLegend(.70, .30,.80,.40);
TLegend *Lgd = new TLegend(.70, .30,.80,.40);
Lgd->AddEntry(grMC,"MC","lep");
Lgd->AddEntry(grRD,"RD","lep");
Lgd->SetFillColor(0);
Lgd->Draw();

 //grRD->Draw("AP");
 //grMC->Draw("psame");
  myCan->SaveAs("trig_eta_P.png");
  myCan->SaveAs("trig_eta_P.eps");

}
Ejemplo n.º 28
0
void makeWorkspace(double mh, TH1* data, std::map<std::string, double> sparams, std::map<std::string, double> bparams, std::string cat, bool maketoy=true, bool useSignalInterpol=true) {

    RooMsgService::instance().setSilentMode(kTRUE);
    RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;

    stringstream mh_ss;
    mh_ss << mh;
    
    std::cout << "Creating datacard for " << mh_ss.str() << " GeV mass point, category " << cat << " ... " << std::endl;
   
    std::stringstream card_name_ss;
    card_name_ss << "card_";
    card_name_ss << "m" << mh_ss.str() << "_";
    card_name_ss << cat;
    std::string card_name = card_name_ss.str();

    std::string workspace = card_name+"_workspace.root";

    /* Dark photon mass and dimuon mass variables */

    const char* massvarstr  = "CMS_darkphoton_mass";
    const char* scalevarstr = "CMS_darkphoton_scale";
    const char* resvarstr   = "CMS_darkphoton_res";

    int    fitbins  = data->GetNbinsX();
    double massLow  = data->GetXaxis()->GetXmin();
    double massHigh = data->GetXaxis()->GetXmax();

    std::cout << "Will perform a binned fit with " << fitbins << " bins in the mass range " << massLow << " to " << massHigh << std::endl; 

    RooRealVar rmh  ("MH"       , "MH"         , mh);
    RooRealVar m2mu (massvarstr , "Dimuon mass", mh  , massLow, massHigh, "GeV/c^{2}");
    RooRealVar scale(scalevarstr, "Scale unc. ", 0.0 , 0.0    , 1.0     , "GeV/c^{2}");
    RooRealVar res  (resvarstr  , "RFes. unc. ", 0.0 , 0.0    , 1.0);
    m2mu.setBins(data->GetNbinsX());   

    /* Extract shape parameters */

    std::string spdf = "sig_mass_";
    std::string bpdf = "bkg_mass_";

    spdf += cat;
    bpdf += cat;

    RooRealVar sig_norm((spdf+"_pdf_norm").c_str(), "", sparams["yield"]);
    RooRealVar bkg_norm((bpdf+"_pdf_norm").c_str(), "", bparams["yield"]);

    std::cout << "Expected signal     yield : " << sig_norm.getVal() << std::endl;
    std::cout << "Expected background yield : " << bkg_norm.getVal() << std::endl;

    sig_norm.setConstant(kTRUE);
    bkg_norm.setConstant(kTRUE);

    /* Define PDFs */

    // Background
    int bkgorder = bparams.size() - 3;
    RooArgList argl;
    std::vector<RooRealVar*> bargs;
    for (std::size_t i = 1; i <= bkgorder; i++) {
        std::stringstream argname_ss;
        argname_ss << "c" << i;
        double argval = bparams[argname_ss.str().c_str()];
        bargs.push_back(new RooRealVar(argname_ss.str().c_str(), "", argval, argval-500., argval+500.));
        argl.add(*bargs.back());
    }
    RooBernstein bkg_mass_pdf(("bkg_mass_"+cat+"_pdf" ).c_str(), "", m2mu, argl);
   
    // Signal
    std::stringstream meanss;
    std::stringstream sigmass;
    double aLval = 0.0;
    double aRval = 0.0;
    double nLval = 0.0;
    double nRval = 0.0;

    if (!useSignalInterpol) {
        meanss  << "@0 - " << sparams["m0"]  << " + " << "@0*@1";
        sigmass << sparams["si"]   << " * " << "(1+@0)";
        aLval = sparams["aL"];
        aRval = sparams["aR"];
        nLval = sparams["nL"];
        nRval = sparams["nR"];
    }
    else {
        meanss  << "35 + 0.99785*(@0-35)"        << " + " << "@0*@1";
        sigmass << "(0.3762 + 0.012223*(@0-35))" << " * " << "(1+@1)";
        aLval = 1.26833918722;
        aRval = 1.2945031338;
        nLval = 2.76027985241;
        nRval = 9.59850913168;
    }

    RooFormulaVar fmean ((spdf+"_fmean" ).c_str(), "", meanss .str().c_str(), RooArgList(rmh, scale));
    RooFormulaVar fsigma((spdf+"_fsigma").c_str(), "", sigmass.str().c_str(), RooArgList(rmh, res  ));
    RooRealVar    raL   ((spdf+"_aL"    ).c_str(), "", aLval);
    RooRealVar    rnL   ((spdf+"_nL"    ).c_str(), "", nLval);
    RooRealVar    raR   ((spdf+"_aR"    ).c_str(), "", aRval);
    RooRealVar    rnR   ((spdf+"_nR"    ).c_str(), "", nRval);

    RooDoubleCB sig_mass_pdf(("sig_mass_"+cat+"_pdf" ).c_str(), "", m2mu, fmean, fsigma, raL, rnL, raR, rnR);

    /* RooDataSet of the observed data */

    std::cout << "Generating toy data with " << int(bparams["yield"]) << " events\n";
    RooDataSet* dset = bkg_mass_pdf.generate(m2mu, int(bparams["yield"]));

    TH1F dhist("dhist", "", fitbins, massLow, massHigh);
    for (int i = 0; i < dset->numEntries(); i++) {
        const RooArgSet* aset = dset->get(i);
        double mass = aset->getRealValue(massvarstr);
        dhist.Fill(mass);
    }

    RooDataHist data_obs("data_obs", "", RooArgList(m2mu), (maketoy ? &dhist : data));

    RooWorkspace w("w", "");

    w.import(data_obs);
    w.import(sig_norm);
    w.import(bkg_norm);
    w.import(sig_mass_pdf);
    w.import(bkg_mass_pdf);

    w.writeToFile(workspace.c_str());

    /* Create the data card text file */

    std::string card = createCardTemplate(mh, cat, workspace);
    std::ofstream ofile;
    ofile.open ((card_name +".txt").c_str());
    ofile << card;
    ofile.close();

    for (std::size_t i = 0; i < bargs.size(); i++) {
        if (bargs[i]) delete bargs[i];        
    }
}
void OneSidedFrequentistUpperLimitWithBands_intermediate(const char* infile = "",
					    const char* workspaceName = "combined",
					    const char* modelConfigName = "ModelConfig",
					    const char* dataName = "obsData"){


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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


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

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

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

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

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


  double CLb=0;
  double CLbinclusive=0;

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

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

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

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


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

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

    histOfUL->Fill(thisUL);

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

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

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

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

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

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

  delete profile;
  delete nll;

}
Ejemplo n.º 30
0
//____________________________________
void AddModel(RooWorkspace* ws){

  // Variables
  RooRealVar* run = new RooRealVar("run","run number",100000,300000);
  RooRealVar* event = new RooRealVar("event","event number",0.,1e10);
  //  RooRealVar* FourMu_Mass = new RooRealVar("FourMu_Mass","FourMu_Mass",6.,100.);
  RooRealVar* FourMu_Mass = new RooRealVar("FourMu_Mass","FourMu_Mass",0.,999.);
  //  RooRealVar* FourMu_Mass = new RooRealVar("FourMu_Mass","FourMu_Mass",6.,20.);
  RooRealVar* Psi1_Mass = new RooRealVar("Psi1_Mass","Psi1_Mass",2.85,3.35);
  RooRealVar* Psi2_Mass = new RooRealVar("Psi2_Mass","Psi2_Mass",2.85,3.35);
  RooRealVar* Psi1_CTxy = new RooRealVar("Psi1_CTxy","Psi1_CTxy",-0.05,0.1);
  RooRealVar* Psi2_CTxy = new RooRealVar("Psi2_CTxy","Psi2_CTxy",-0.05,0.1);
  RooRealVar* Psi1To2_dY = new RooRealVar("Psi1To2_dY","Psi1To2_dY",0.,4.8);
  RooRealVar* Psi1To2Significance = new RooRealVar("Psi1To2Significance","Psi1To2Significance",0.,8);

  RooArgSet dataVars;
  dataVars.add(RooArgSet(*run,*event,*FourMu_Mass,*Psi1_Mass,*Psi2_Mass,*Psi1_CTxy,*Psi2_CTxy,*Psi1To2_dY,*Psi1To2Significance));
  RooDataSet *data;
  //TFile* f= (TFile*)gROOT->FindObject("./data.root"); if (f) f->Close();
  //f = new TFile ("./data.root","UPDATE");
  //TFile* f= (TFile*)gROOT->FindObject("./Input_To_Fit_pT_Sort.root"); if (f) f->Close();
  //TFile* f = new TFile ("./Input_To_Fit_pT_Sort_iter_7_Data_Good_Eff.root","READ");
  TFile* f = new TFile ("./Input_To_Fit_pT_Sort_2012_Data_04_tight_mass.root","READ");
  //TFile* f = new TFile ("./Input_To_Fit_pT_Sort_iter_7_Data.root","READ");
  TTree *myTree = (TTree*)f->Get("PATEventTree");
  data = new RooDataSet("data","data",myTree,dataVars);

  /////////////////////////
  // Signal PDFs parameters
  /////////////////////////

  RooRealVar*  jpsi1_mass_1 = new RooRealVar("jpsi1_mass_1","",3.08988e+00);
  RooRealVar*  jpsi1_mass_2 = new RooRealVar("jpsi1_mass_2","",3.09553e+00);
  RooRealVar*  jpsi1_width_1 = new RooRealVar("jpsi1_width_1","",7.00000e-02);
  RooRealVar*  jpsi1_width_2 = new RooRealVar("jpsi1_width_2","",4.30143e-01);
  RooFormulaVar*  jpsi1_width_a = new RooFormulaVar("jpsi1_width_a","","@0*@1",RooArgList(*jpsi1_width_1,*jpsi1_width_2));
  RooRealVar*  frac_1 = new RooRealVar("frac_1","",3.76426e-01);

  RooRealVar*  jpsi2_mass_1 = new RooRealVar("jpsi2_mass_1","",3.08680e+00);
  RooRealVar*  jpsi2_mass_2 = new RooRealVar("jpsi2_mass_2","",3.09285e+00);
  RooRealVar*  jpsi2_width_1 = new RooRealVar("jpsi2_width_1","",7.00000e-02);
  RooRealVar*  jpsi2_width_2 = new RooRealVar("jpsi2_width_2","",4.79895e-01);
  RooFormulaVar*  jpsi2_width_a = new RooFormulaVar("jpsi2_width_a","","@0*@1",RooArgList(*jpsi2_width_1,*jpsi2_width_2));
  RooRealVar*  frac_2 = new RooRealVar("frac_2","",5.00000e-01);  

  RooRealVar*  R_mean_coreCT1 = new RooRealVar("R_mean_coreCT1","",2.63860e-05);
  RooRealVar*  R_mean_tailCT1 = new RooRealVar("R_mean_tailCT1","",1.19874e-03);
  RooRealVar*  R_sigma_coreCT1 = new RooRealVar("R_sigma_coreCT1","",2.72201e-03);
  RooRealVar*  R_sigma_tailCT1 = new RooRealVar("R_sigma_tailCT1","",2.72258e+00);
  RooFormulaVar*  R_sigma_totCT1 = new RooFormulaVar("R_sigma_totCT1","","@0*@1",RooArgList(*R_sigma_coreCT1,*R_sigma_tailCT1));
  RooRealVar*  R_fracCT1 = new RooRealVar("R_fracCT1","",8.47797e-01);

  RooRealVar*  R_mean_core = new RooRealVar("R_mean_core","",4.08278e-01);
  RooRealVar*  R_sigma_core = new RooRealVar("R_sigma_core","",2.17748e-01);
  RooRealVar*  etab_lambda = new RooRealVar("etab_lambda","",6.76288e-01);

  RooGaussian jpsi1mass_1("jpsi1mass_1","jpsi mass distribution",*Psi1_Mass,*jpsi1_mass_1,*jpsi1_width_1);
  RooGaussian jpsi1mass_2("jpsi1mass_2","jpsi mass distribution",*Psi1_Mass,*jpsi1_mass_1,*jpsi1_width_a);
  RooAddPdf jpsi1mass("jpsi1mass","jpsi1 mass distribution",RooArgList(jpsi1mass_1,jpsi1mass_2),RooArgList(*frac_1));

  RooGaussian jpsi2mass_1("jpsi2mass_1","jpsi mass distribution",*Psi2_Mass,*jpsi2_mass_1,*jpsi2_width_1);
  RooGaussian jpsi2mass_2("jpsi2mass_2","jpsi mass distribution",*Psi2_Mass,*jpsi2_mass_1,*jpsi2_width_a);
  RooAddPdf jpsi2mass("jpsi2mass","jpsi2 mass distribution",RooArgList(jpsi2mass_1,jpsi2mass_2),RooArgList(*frac_2));

  RooGaussian ct_1a("ct_1a","ct distribution",*Psi1_CTxy,*R_mean_coreCT1,*R_sigma_coreCT1);
  RooGaussian ct_1b("ct_1b","ct distribution",*Psi1_CTxy,*R_mean_tailCT1,*R_sigma_totCT1);
  RooAddPdf ct_1("ct_1","ct distribution",RooArgList(ct_1a,ct_1b),RooArgList(*R_fracCT1));

  RooGaussModel resolution_core("resolution_core","",*Psi1To2Significance,*R_mean_core,*R_sigma_core);
  RooDecay sig_distT("sig_distT","",*Psi1To2Significance,*etab_lambda,resolution_core,RooDecay::SingleSided);

  RooProdPdf sig_model("sig_model","",RooArgList(jpsi1mass,jpsi2mass,ct_1,sig_distT));

  /////////////////////////
  // B bkg PDF 
  /////////////////////////

  RooRealVar*   Bbkg_jpsi1_mass_1 = new RooRealVar("Bbkg_jpsi1_mass_1","",3.08988e+00);
  RooRealVar*   Bbkg_jpsi1_mass_2 = new RooRealVar("Bbkg_jpsi1_mass_2","",3.09553e+00);
  RooRealVar*   Bbkg_jpsi1_width_1 = new RooRealVar("Bbkg_jpsi1_width_1","",7.00000e-02);
  RooRealVar*   Bbkg_jpsi1_width_2 = new RooRealVar("Bbkg_jpsi1_width_2","",4.30143e-01);
  RooFormulaVar*   Bbkg_jpsi1_width_a = new RooFormulaVar("Bbkg_jpsi1_width_a","","@0*@1",RooArgList(*Bbkg_jpsi1_width_1,*Bbkg_jpsi1_width_2));
  RooRealVar*   Bbkg_frac_1 = new RooRealVar("Bbkg_frac_1","",3.76426e-01);

  RooRealVar*   Bbkg_jpsi2_mass_1 = new RooRealVar("Bbkg_jpsi2_mass_1","",3.08680e+00);
  RooRealVar*   Bbkg_jpsi2_mass_2 = new RooRealVar("Bbkg_jpsi2_mass_2","",3.09285e+00);
  RooRealVar*   Bbkg_jpsi2_width_1 = new RooRealVar("Bbkg_jpsi2_width_1","",7.00000e-02);
  RooRealVar*   Bbkg_jpsi2_width_2 = new RooRealVar("Bbkg_jpsi2_width_2","",4.79895e-01);
  RooFormulaVar*   Bbkg_jpsi2_width_a = new RooFormulaVar("Bbkg_jpsi2_width_a","","@0*@1",RooArgList(*Bbkg_jpsi2_width_1,*Bbkg_jpsi2_width_2));
  RooRealVar*   Bbkg_frac_2 = new RooRealVar("Bbkg_frac_2","",5.00000e-01);

  RooRealVar*   Bbkg_mean_CT1 = new RooRealVar("Bbkg_mean_CT1","",6.51060e-04);
  RooRealVar*   Bbkg_width_CT1 = new RooRealVar("Bbkg_width_CT1","",3.77146e-03);
  //RooRealVar*   Bbkg_lambda_CT1 = new RooRealVar("Bbkg_lambda_CT1","Bbkg_lambda_CT1",1.59424e-02); // for eff_cut dataset
  //RooRealVar*   Bbkg_lambda_CT1 = new RooRealVar("Bbkg_lambda_CT1","Bbkg_lambda_CT1",1.60933e-02); // for eff_cut dataset
  RooRealVar*   Bbkg_lambda_CT1 = new RooRealVar("Bbkg_lambda_CT1","Bbkg_lambda_CT1",1.86124e-02); // for all dataset

  RooRealVar*   Bbkg_p3_distT = new RooRealVar("Bbkg_p3_distT","",1.18073e+00);
  RooRealVar*   Bbkg_p4_distT = new RooRealVar("Bbkg_p4_distT","",5.15922e-01);
  RooRealVar*   Bbkg_lambda1 = new RooRealVar("Bbkg_lambda1","",9.99999e+01);

  RooGaussian Bbkg_jpsi1mass_1("Bbkg_jpsi1mass_1","jpsi mass distribution",*Psi1_Mass,*Bbkg_jpsi1_mass_1,*Bbkg_jpsi1_width_1);
  RooGaussian Bbkg_jpsi1mass_2("Bbkg_jpsi1mass_2","jpsi mass distribution",*Psi1_Mass,*Bbkg_jpsi1_mass_1,*Bbkg_jpsi1_width_a);
  RooAddPdf Bbkg_jpsi1mass("Bbkg_jpsi1mass","jpsi1 mass distribution",RooArgList(Bbkg_jpsi1mass_1,Bbkg_jpsi1mass_2),RooArgList(*Bbkg_frac_1));

  RooGaussian Bbkg_jpsi2mass_1("Bbkg_jpsi2mass_1","jpsi mass distribution",*Psi2_Mass,*Bbkg_jpsi2_mass_1,*Bbkg_jpsi2_width_1);
  RooGaussian Bbkg_jpsi2mass_2("Bbkg_jpsi2mass_2","jpsi mass distribution",*Psi2_Mass,*Bbkg_jpsi2_mass_1,*Bbkg_jpsi2_width_a);
  RooAddPdf Bbkg_jpsi2mass("Bbkg_jpsi2mass","jpsi1 mass distribution",RooArgList(Bbkg_jpsi2mass_1,Bbkg_jpsi2mass_2),RooArgList(*Bbkg_frac_2));

  RooGaussModel resolution_R1("resolution_R1","",*Psi1_CTxy,*Bbkg_mean_CT1,*Bbkg_width_CT1);
  RooDecay Bbkg_CT1("Bbkg_CT1","",*Psi1_CTxy,*Bbkg_lambda_CT1,resolution_R1,RooDecay::SingleSided);

  RooGaussModel resolution_core2("resolution_core2","",*Psi1To2Significance,*Bbkg_p3_distT,*Bbkg_p4_distT);
  RooDecay Bbkg_distT("Bbkg_distT","",*Psi1To2Significance,*Bbkg_lambda1,resolution_core2,RooDecay::SingleSided);

  RooProdPdf Bbkg_model("Bbkg_model","",RooArgList(Bbkg_jpsi1mass,Bbkg_jpsi2mass,Bbkg_CT1,Bbkg_distT));

  /////////////////////////
  // bkg PDF 
  /////////////////////////

  // jpsi-sideband case
  RooRealVar*    bkg_jpsi1_mass_1 = new RooRealVar("bkg_jpsi1_mass_1","",3.08988e+00);
  //RooRealVar*    bkg_jpsi1_mass_2 = new RooRealVar("bkg_jpsi1_mass_2","",3.08988e+00);
  RooRealVar*    bkg_jpsi1_width_1 = new RooRealVar("bkg_jpsi1_width_1","",7.00000e-02);
  RooRealVar*    bkg_jpsi1_width_2 = new RooRealVar("bkg_jpsi1_width_2","",4.30143e-01);
  RooFormulaVar* bkg_jpsi1_width_a = new RooFormulaVar("bkg_jpsi1_width_a","","@0*@1",RooArgList(*bkg_jpsi1_width_1,*bkg_jpsi1_width_2));
  RooRealVar*    bkg_frac_6 = new RooRealVar("bkg_frac_6","",3.76426e-01);

  RooRealVar*    bkg_p3 = new RooRealVar("bkg_p3","",-2.10268e-01);
  RooRealVar*    bkg_p4 = new RooRealVar("bkg_p4","",-1.95504e-01);
  RooRealVar*    bkg_p5 = new RooRealVar("bkg_p5","",5.00755e-02);

  RooRealVar*    bkg1_R_mean_core = new RooRealVar("bkg1_R_mean_core","",1.04093e-02);
  RooRealVar*    bkg1_R_mean_tail = new RooRealVar("bkg1_R_mean_tail","",-2.51869e-04);
  RooRealVar*    bkg1_R_sigma_core = new RooRealVar("bkg1_R_sigma_core","",1.24609e-02);
  RooRealVar*    bkg1_R_sigma_tail = new RooRealVar("bkg1_R_sigma_tail","",2.63519e-01);
  RooRealVar*    bkg_frac_1 = new RooRealVar("bkg_frac_1","",7.07283e-01);
  //RooRealVar*    bkg1_R_mean_core = new RooRealVar("bkg1_R_mean_core","",2.63860e-05);
  //RooRealVar*    bkg1_R_mean_tail = new RooRealVar("bkg1_R_mean_tail","",1.19874e-03);
  //RooRealVar*    bkg1_R_sigma_core = new RooRealVar("bkg1_R_sigma_core","",2.72201e-03);
  //RooRealVar*    bkg1_R_sigma_tail = new RooRealVar("bkg1_R_sigma_tail","",2.72258e+00);
  //RooRealVar*    bkg_frac_1 = new RooRealVar("bkg_frac_1","",8.47797e-01);

  RooFormulaVar* bkg1_R_sigma_tot = new RooFormulaVar("bkg1_R_sigma_tot","","@0*@1",RooArgList(*bkg1_R_sigma_tail,*bkg1_R_sigma_core));
  //RooGaussian bkg_jpsi1mass("bkg_jpsi1mass","jpsi mass distribution",*Psi1_Mass,*bkg_jpsi1_mass_1,*bkg_jpsi1_width_1);
  RooGaussian bkg_jpsi1mass_1("bkg_jpsi1mass_1","jpsi mass distribution",*Psi1_Mass,*bkg_jpsi1_mass_1,*bkg_jpsi1_width_1);
  RooGaussian bkg_jpsi1mass_2("bkg_jpsi1mass_2","jpsi mass distribution",*Psi1_Mass,*bkg_jpsi1_mass_1,*bkg_jpsi1_width_a);
  RooAddPdf bkg_jpsi1mass("bkg_jpsi1mass","jpsi1 mass distribution",RooArgList(bkg_jpsi1mass_1,bkg_jpsi1mass_2),RooArgList(*bkg_frac_6));
  RooChebychev bkg_jpsi1mass_Pol("bkg_jpsi1mass_Pol","",*Psi2_Mass,RooArgList(*bkg_p3,*bkg_p4,*bkg_p5));

  RooGaussian bkg_ctSB1_1a("bkg_ctSB1_1a","ct distribution",*Psi1_CTxy,*bkg1_R_mean_core,*bkg1_R_sigma_core);
  RooGaussian bkg_ctSB1_1b("bkg_ctSB1_1b","ct distribution",*Psi1_CTxy,*bkg1_R_mean_tail,*bkg1_R_sigma_tot);
  RooAddPdf bkg_CT1_SB1("bkg_CT1_SB1","ct distribution",RooArgList(bkg_ctSB1_1a,bkg_ctSB1_1b),RooArgList(*bkg_frac_1));

  //RooRealVar*    bkg_p3_distT = new RooRealVar("bkg_p3_distT","",2.87578e-01);
  //RooRealVar*    bkg_p4_distT = new RooRealVar("bkg_p4_distT","",1.26380e-01);
  //RooRealVar*    bkg_lambda1 = new RooRealVar("bkg_lambda1","",3.65276e+00);
  //RooGaussModel resolution_core3("resolution_core3","",*Psi1To2Significance,*bkg_p3_distT,*bkg_p4_distT);
  //RooDecay bkg_distT("bkg_distT","",*Psi1To2Significance,*bkg_lambda1,resolution_core3,RooDecay::SingleSided);

  RooRealVar* bkg_co0 =  new RooRealVar("bkg_co0","",9.99840e-01);
  RooRealVar* bkg_co1 =  new RooRealVar("bkg_co1","",2.00471e-06);
  RooRealVar* bkg_flau = new RooRealVar("bkg_flau","",6.48517e-01);
  RooRealVar* bkg_meanlandau = new RooRealVar("bkg_meanlandau","",1.00181e+00);
  RooRealVar* bkg_sigmalandau = new RooRealVar("bkg_sigmalandau","",4.35740e-01);
  RooLandau bkg_landau("bkg_landau", "bkg_landau", *Psi1To2Significance, *bkg_meanlandau, *bkg_sigmalandau);
  RooChebychev bkg_polyshape("bkg_polyshape","",*Psi1To2Significance,RooArgList(*bkg_co0,*bkg_co1));
  RooAddPdf bkg_distT("bkg_distT","", RooArgList(bkg_landau,bkg_polyshape),*bkg_flau);

  RooProdPdf bkg_mass1("bkg_mass1","",RooArgList(bkg_jpsi1mass,bkg_jpsi1mass_Pol,bkg_CT1_SB1,bkg_distT));

  // sideband-jpsi case
  RooRealVar*    bkg_jpsi2_mass_1 = new RooRealVar("bkg_jpsi2_mass_1","",3.08680e+00);
  //RooRealVar*    bkg_jpsi2_mass_2 = new RooRealVar("bkg_jpsi2_mass_2","",3.08680e+00);
  RooRealVar*    bkg_jpsi2_width_1 = new RooRealVar("bkg_jpsi2_width_1","",7.00000e-02);
  RooRealVar*    bkg_jpsi2_width_2 = new RooRealVar("bkg_jpsi2_width_2","",4.79895e-01);
  RooFormulaVar* bkg_jpsi2_width_a = new RooFormulaVar("bkg_jpsi1_width_a","","@0*@1",RooArgList(*bkg_jpsi2_width_1,*bkg_jpsi2_width_2));
  RooRealVar*    bkg_frac_7 = new RooRealVar("bkg_frac_7","",5.00000e-01);

  RooRealVar*  bkg_p0 = new RooRealVar("bkg_p0","",-2.93132e-01);
  RooRealVar*  bkg_p1 = new RooRealVar("bkg_p1","",-3.89092e-01);
  RooRealVar*  bkg_p2 = new RooRealVar("bkg_p2","",1.94808e-01);
  
  RooRealVar*  bkg3_R_mean_core = new RooRealVar("bkg3_R_mean_core","",3.60489e-02);
  RooRealVar*  bkg3_R_mean_tail = new RooRealVar("bkg3_R_mean_tail","",4.32342e-03);
  RooRealVar*  bkg3_R_sigma_core = new RooRealVar("bkg3_R_sigma_core","",2.89854e-02);
  RooRealVar*  bkg3_R_sigma_tail = new RooRealVar("bkg3_R_sigma_tail","",3.60637e-01);
  RooRealVar*  bkg_frac_3 = new RooRealVar("bkg_frac_3","",6.27677e-02);
  RooFormulaVar*  bkg3_R_sigma_tot = new RooFormulaVar("bkg3_R_sigma_tot","","@0*@1",RooArgList(*bkg3_R_sigma_tail,*bkg3_R_sigma_core));

  //RooGaussian bkg_jpsi2mass("bkg_jpsi2mass","jpsi mass distribution",*Psi2_Mass,*bkg_jpsi2_mass_1,*bkg_jpsi2_width_1);
  RooGaussian bkg_jpsi2mass_1("bkg_jpsi2mass_1","jpsi mass distribution",*Psi2_Mass,*bkg_jpsi2_mass_1,*bkg_jpsi2_width_1);
  RooGaussian bkg_jpsi2mass_2("bkg_jpsi2mass_2","jpsi mass distribution",*Psi2_Mass,*bkg_jpsi2_mass_1,*bkg_jpsi2_width_a);
  RooAddPdf bkg_jpsi2mass("bkg_jpsi2mass","jpsi2 mass distribution",RooArgList(bkg_jpsi2mass_1,bkg_jpsi2mass_2),RooArgList(*bkg_frac_7));
  RooChebychev bkg_jpsi2mass_Pol("bkg_jpsi2mass_Pol","",*Psi1_Mass,RooArgList(*bkg_p0,*bkg_p1,*bkg_p2));

  RooGaussian bkg_ctSB2_1a("bkg_ctSB2_1a","ct distribution",*Psi1_CTxy,*bkg3_R_mean_core,*bkg3_R_sigma_core);
  RooGaussian bkg_ctSB2_1b("bkg_ctSB2_1b","ct distribution",*Psi1_CTxy,*bkg3_R_mean_tail,*bkg3_R_sigma_tot);
  RooAddPdf bkg_CT1_SB2("bkg_CT1_SB2","ct distribution",RooArgList(bkg_ctSB2_1a,bkg_ctSB2_1b),RooArgList(*bkg_frac_3));

  //RooRealVar*  bkg_p5_distT = new RooRealVar("bkg_p5_distT","",2.41297e-01);
  //RooRealVar*  bkg_p6_distT = new RooRealVar("bkg_p6_distT","",7.29316e-02);
  //RooRealVar*  bkg_lambda2 = new RooRealVar("bkg_lambda2","",4.66802e+00);
  //RooGaussModel resolution_core4("resolution_core4","",*Psi1To2Significance,*bkg_p5_distT,*bkg_p6_distT);
  //RooDecay bkg_distT2("bkg_distT2","",*Psi1To2Significance,*bkg_lambda2,resolution_core4,RooDecay::SingleSided);

  RooRealVar* bkg_co02 =  new RooRealVar("bkg_co02","", 6.58858e-01);
  RooRealVar* bkg_co12 =  new RooRealVar("bkg_co12","", 2.48596e-05);
  RooRealVar* bkg_flau2 = new RooRealVar("bkg_flau2","",5.33780e-01);
  RooRealVar* bkg_meanlandau2 = new RooRealVar("bkg_meanlandau2","",1.09999e+00);
  RooRealVar* bkg_sigmalandau2 = new RooRealVar("bkg_sigmalandau2","",4.64046e-01);
  RooChebychev bkg_polyshape2("bkg_polyshape2","",*Psi1To2Significance,RooArgList(*bkg_co02,*bkg_co12));
  RooLandau bkg_landau2("bkg_landau2", "bkg_landau2", *Psi1To2Significance, *bkg_meanlandau2, *bkg_sigmalandau2);
  RooAddPdf bkg_distT2("bkg_distT2","", RooArgList(bkg_landau2,bkg_polyshape2),*bkg_flau2);

  RooProdPdf bkg_mass2("bkg_mass2","",RooArgList(bkg_jpsi2mass,bkg_jpsi2mass_Pol,bkg_CT1_SB2,bkg_distT2));

  // fraction for the J/psi-flat flat-J/psi ratio (Andrew: I think this is defined as (# J/psi-flat)/(# J/psi-flat + # flat-J/psi))
  //RooRealVar*  bkg_frac_5 = new RooRealVar("bkg_frac_5","",);
  //RooRealVar*  bkg_frac_5 = new RooRealVar("bkg_frac_5","",5.95167e-01); // for eff_cut dataset
  RooRealVar*  bkg_frac_5 = new RooRealVar("bkg_frac_5","",8.92796e-01); // for all dataset
  RooAddPdf bkg_model("bkg_model","",RooArgList(bkg_mass1,bkg_mass2),RooArgList(*bkg_frac_5));

  /////////////////////////
  // bkg flat flat
  /////////////////////////
  RooRealVar*  bkg7_R_mean_core = new RooRealVar("bkg7_R_mean_core","",3.45913e-03);
  RooRealVar*  bkg7_R_sigma_core = new RooRealVar("bkg7_R_sigma_core","",1.10565e-02);
  RooGaussian bkg2_CT1("bkg2_CT1","ct distribution",*Psi1_CTxy,*bkg7_R_mean_core,*bkg7_R_sigma_core);

  //RooRealVar*  bkg_p7_distT = new RooRealVar("bkg_p7_distT","",5.13453e-01);
  //RooRealVar*  bkg_p8_distT = new RooRealVar("bkg_p8_distT","",2.85147e-01);
  //RooRealVar*  bkg_lambda3 = new RooRealVar("bkg_lambda3","",3.54163e+00);
  //RooGaussModel resolution_core5("resolution_core5","",*Psi1To2Significance,*bkg_p7_distT,*bkg_p8_distT);
  //RooDecay bkg2_distT("bkg2_distT","",*Psi1To2Significance,*bkg_lambda3,resolution_core5,RooDecay::SingleSided);

  RooRealVar* bkg2_co0 =  new RooRealVar("bkg2_co0","", 3.86180e-01);
  RooRealVar* bkg2_co1 =  new RooRealVar("bkg2_co1","", 9.49975e-01);
  RooRealVar* bkg2_flau = new RooRealVar("bkg2_flau","",7.28332e-01);
  RooRealVar* bkg2_meanlandau = new RooRealVar("bkg2_meanlandau","",1.56581e+00);
  RooRealVar* bkg2_sigmalandau = new RooRealVar("bkg2_sigmalandau","",5.51089e-01);
  RooLandau bkg2_landau("bkg2_landau", "bkg2_landau", *Psi1To2Significance, *bkg2_meanlandau, *bkg2_sigmalandau);
  RooChebychev bkg2_polyshape("bkg2_polyshape","",*Psi1To2Significance,RooArgList(*bkg2_co0,*bkg2_co1));
  RooAddPdf bkg2_distT("bkg2_distT","", RooArgList(bkg2_landau,bkg2_polyshape),*bkg2_flau);

  RooProdPdf bkg2_model("bkg2_model","",RooArgList(bkg_jpsi2mass_Pol,bkg_jpsi1mass_Pol,bkg2_CT1,bkg2_distT));

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

  RooRealVar nsig("nsig","number of signal events",700,1,5000);
  RooRealVar nBbkg("nBbkg","number of B background events",1000,1,5000);
  RooRealVar nbkg("nbkg","number of background events",200,1,5000);
  RooRealVar nbkg2("nbkg2","number of background events",200,1,5000);

  RooAddPdf model("model","model",RooArgList(sig_model,Bbkg_model,bkg_model,bkg2_model),RooArgList(nsig,nBbkg,nbkg,nbkg2));

  std::cout << "import model" << std::endl;
  ws->import(model);
  std::cout << "import data" << std::endl;
  ws->import(*data);

  cout << "data entries: " << data->numEntries() << endl;

  // fitting dY with SPS and DPS

  RooRealVar*   m_dY = new RooRealVar("m_dY","",3.11781e+00);
  RooRealVar*   w_dY = new RooRealVar("w_dY","",4.99424e-01);
  /*
  RooRealVar*   p0_dY = new RooRealVar("p0_dY","",-8.06009e-01,-1.,1.);
  RooRealVar*   p1_dY = new RooRealVar("p1_dY","",3.19965e-01,-1.,1.);
  RooRealVar*   p2_dY = new RooRealVar("p2_dY","",-4.41787e-02,-1.,1.);
  */
  RooRealVar*   p0_dY = new RooRealVar("p0_dY","",-82.9767/3182.94);
  RooRealVar*   p1_dY = new RooRealVar("p1_dY","",-61.3831/3182.94);
  RooRealVar*   frac_dY = new RooRealVar("frac_dY","",1.61012e-01);
  RooGaussian g_dY("g_dY"," ",*Psi1To2_dY,*m_dY,*w_dY);
  //  RooPolynomial pol_dY("pol_dY"," ",*Psi1To2_dY,RooArgList(*p0_dY,*p1_dY,*p2_dY));
  //  RooAddPdf model_DPS("model_DPS"," ",RooArgList(g_dY,pol_dY),*frac_dY);
  //  RooPolynomial model_DPS("model_DPS"," ",*Psi1To2_dY,RooArgList(*p0_dY,*p1_dY,*p2_dY));
  RooPolynomial model_DPS("model_DPS"," ",*Psi1To2_dY,RooArgList(*p0_dY,*p1_dY));
  //  RooPolynomial model_DPS("model_DPS"," ",*Psi1To2_dY,RooArgList(*p0_dY));

  RooRealVar*  Rm_dY = new RooRealVar("Rm_dY"," " , -5.82342e-01);
  RooRealVar*  Rw_dY = new RooRealVar("Rw_dY"," " , 7.35732e-01);
  RooRealVar*  lambda_dY = new RooRealVar("lambda_dY"," " , 3.26722e-01);
  RooGaussModel res_dY("res_dY","",*Psi1To2_dY,*Rm_dY,*Rw_dY);
  RooDecay model_SPS("model_SPS","",*Psi1To2_dY,*lambda_dY,res_dY,RooDecay::SingleSided);

  RooRealVar nsigDPS("nsigDPS","number of signal events",300,1,500);
  RooRealVar nsigSPS("nsigSPS","number of signal events",200,1,500);

  RooAddPdf model_dY("model_dY","model_dY",RooArgList(model_DPS,model_SPS),RooArgList(nsigDPS,nsigSPS));
  std::cout << "import model for dY fitting" << std::endl;
  ws->import(model_dY);

}