示例#1
0
Roo2DKeysPdf *SmoothKeys(TH2F *h)
{
  RooDataSet *dataset = th22dataset(h);
  RooRealVar *v1 = (RooRealVar *) dataset->get()->find("constTerm");
  RooRealVar *v2 =  (RooRealVar *) dataset->get()->find("alpha");


  Roo2DKeysPdf *myPdf = new Roo2DKeysPdf("mypdf","", *v1, *v2, *dataset);
  return myPdf;

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

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

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

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

      mass->setVal(toyData->get(i)->getRealValue("mass"));
      cosT->setVal(toyData->get(i)->getRealValue("cosT"));
      extractedData->add(event,weight_double);
   }
   delete toyData;
}
示例#3
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");

}
示例#4
0
文件: trig_pt.C 项目: d4space/KoSMP
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");

}
示例#5
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");

}
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);
	//*/
	
}
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;
	
	
	
	
	
}
void LeptonPreselectionCMG( PreselType type, RooWorkspace * w ) {
	const Options & opt = Options::getInstance(); 
	if (type == ELE)
		cout << "Running Electron Preselection :" << endl;
	else if (type == MU)
		cout << "Running Muon Preselection :" << endl;
	else if (type == EMU)
		cout << "Running Electron-Muon Preselection() ..." << endl;
	else if (type == PHOT)
		cout << "Running Photon Preselection :" << endl;

	string systVar;
	try {
		systVar = opt.checkStringOption("SYSTEMATIC_VAR");
	} catch (const std::string & exc) {
		cout << exc << endl;
	}
	if (systVar == "NONE")
		systVar.clear();

#ifdef CMSSWENV
	JetCorrectionUncertainty jecUnc("Summer13_V4_MC_Uncertainty_AK5PFchs.txt");
#endif

	string inputDir = opt.checkStringOption("INPUT_DIR");
	string outputDir = opt.checkStringOption("OUTPUT_DIR");
	string sampleName = opt.checkStringOption("SAMPLE_NAME");
	string inputFile = inputDir + '/' + sampleName + ".root";
	cout << "\tInput file: " << inputFile << endl;

	bool isSignal = opt.checkBoolOption("SIGNAL");
	TGraph * higgsW = 0;
	TGraph * higgsI = 0;
	if (isSignal) {
		double higgsM = opt.checkDoubleOption("HIGGS_MASS");
		if (higgsM >= 400) {
			string dirName = "H" + double2string(higgsM);
			bool isVBF = opt.checkBoolOption("VBF");
			string lshapeHistName = "cps";
			string intHistName = "nominal";
			
			if (systVar == "LSHAPE_UP") {
				intHistName = "up";
			} else if (systVar == "LSHAPE_DOWN") {
				intHistName = "down";
			}

			if (isVBF) {
				TFile weightFile("VBF_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();

			} else {
				TFile weightFile("GG_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();
				TFile interfFile("newwgts_interf.root");
				higgsI = (TGraph *) ( (TDirectory *) interfFile.Get(dirName.c_str()))->Get( intHistName.c_str() )->Clone();
			}
		}
	}

	TFile * file = new TFile( inputFile.c_str() );
	if (!file->IsOpen())
		throw string("ERROR: Can't open the file: " + inputFile + "!");
	TDirectory * dir = (TDirectory *) file->Get("dataAnalyzer");
	TH1D * nEvHisto = (TH1D *) dir->Get("cutflow");
	TH1D * puHisto = (TH1D *) dir->Get("pileup");
	TTree * tree = ( TTree * ) dir->Get( "data" );
	Event ev( tree );
	const int * runP = ev.getSVA<int>("run"); 
	const int * lumiP = ev.getSVA<int>("lumi"); 
	const int * eventP = ev.getSVA<int>("event"); 
	const bool * trigBits = ev.getAVA<bool>("t_bits");
	const int * trigPres = ev.getAVA<int>("t_prescale");
	const float * metPtA = ev.getAVA<float>("met_pt");
	const float * metPhiA = ev.getAVA<float>("met_phi");
	const float * rhoP = ev.getSVA<float>("rho");
	const float * rho25P = ev.getSVA<float>("rho25");
	const int * nvtxP = ev.getSVA<int>("nvtx"); 
	const int * niP = ev.getSVA<int>("ngenITpu"); 
	
#ifdef PRINTEVENTS
	string eventFileName;
	if (type == ELE)
		eventFileName = "events_ele.txt";
	else if (type == MU)
		eventFileName = "events_mu.txt";
	else if (type == EMU)
		eventFileName = "events_emu.txt";

	EventPrinter evPrint(ev, type, eventFileName);
	evPrint.readInEvents("diff.txt");
	evPrint.printElectrons();
	evPrint.printMuons();
	evPrint.printZboson();
	evPrint.printJets();
	evPrint.printHeader();
#endif

	string outputFile = outputDir + '/' + sampleName;

	if (systVar.size())
		outputFile += ('_' + systVar);

	if (type == ELE)
		outputFile += "_elePresel.root";
	else if (type == MU)
		outputFile += "_muPresel.root";
	else if (type == EMU)
		outputFile += "_emuPresel.root";
	else if (type == PHOT)
		outputFile += "_phPresel.root";
	cout << "\tOutput file: " << outputFile << endl;

	TFile * out = new TFile( outputFile.c_str(), "recreate" );
	TH1D * outNEvHisto = new TH1D("nevt", "nevt", 1, 0, 1);
	outNEvHisto->SetBinContent(1, nEvHisto->GetBinContent(1));
	outNEvHisto->Write("nevt");

	TH1D * outPuHisto = new TH1D( *puHisto );
	outPuHisto->Write("pileup");

	std::vector< std::tuple<std::string, std::string> > eleVars;
	eleVars.push_back( std::make_tuple("ln_px", "F") );
	eleVars.push_back( std::make_tuple("ln_py", "F") );
	eleVars.push_back( std::make_tuple("ln_pz", "F") );
	eleVars.push_back( std::make_tuple("ln_en", "F") );
	eleVars.push_back( std::make_tuple("ln_idbits", "I") );
	eleVars.push_back( std::make_tuple("ln_d0", "F") );
	eleVars.push_back( std::make_tuple("ln_dZ", "F") );
	eleVars.push_back( std::make_tuple("ln_nhIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_gIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_chIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_trkLostInnerHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addEleVars;
	addEleVars.push_back( std::make_tuple("egn_sceta", "F") );
	addEleVars.push_back( std::make_tuple("egn_detain", "F") );
	addEleVars.push_back( std::make_tuple("egn_dphiin", "F") );
	addEleVars.push_back( std::make_tuple("egn_sihih", "F") );
	addEleVars.push_back( std::make_tuple("egn_hoe", "F") );
	addEleVars.push_back( std::make_tuple("egn_ooemoop", "F") );
	addEleVars.push_back( std::make_tuple("egn_isConv", "B") );

	std::vector< std::tuple<std::string, std::string> > muVars;
	muVars.push_back( std::make_tuple("ln_px", "F") );
	muVars.push_back( std::make_tuple("ln_py", "F") );
	muVars.push_back( std::make_tuple("ln_pz", "F") );
	muVars.push_back( std::make_tuple("ln_en", "F") );
	muVars.push_back( std::make_tuple("ln_idbits", "I") );
	muVars.push_back( std::make_tuple("ln_d0", "F") );
	muVars.push_back( std::make_tuple("ln_dZ", "F") );
	muVars.push_back( std::make_tuple("ln_nhIso04", "F") );
	muVars.push_back( std::make_tuple("ln_gIso04", "F") );
	muVars.push_back( std::make_tuple("ln_chIso04", "F") );
	muVars.push_back( std::make_tuple("ln_puchIso04", "F") );
	muVars.push_back( std::make_tuple("ln_trkchi2", "F") );
	muVars.push_back( std::make_tuple("ln_trkValidPixelHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addMuVars;
	addMuVars.push_back( std::make_tuple("mn_trkLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_pixelLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_innerTrackChi2", "F") );
	addMuVars.push_back( std::make_tuple("mn_validMuonHits", "F") );
	addMuVars.push_back( std::make_tuple("mn_nMatchedStations", "F") );

	unsigned run;
	unsigned lumi;
	unsigned event;
	double pfmet;
	int nele;
	int nmu;
	int nsoftmu;
	double l1pt;
	double l1eta;
	double l1phi;
	double l2pt;
	double l2eta;
	double l2phi;
	double zmass;
	double zpt;
	double zeta;
	double mt;
	int nsoftjet;
	int nhardjet;
	double maxJetBTag;
	double minDeltaPhiJetMet;
	double detajj;
	double mjj;
	int nvtx;
	int ni;
	int category;
	double weight;
	double hmass;
	double hweight;

	TTree * smallTree = new TTree("HZZ2l2nuAnalysis", "HZZ2l2nu Analysis Tree");
	smallTree->Branch( "Run", &run, "Run/i" );
	smallTree->Branch( "Lumi", &lumi, "Lumi/i" );
	smallTree->Branch( "Event", &event, "Event/i" );
	smallTree->Branch( "PFMET", &pfmet, "PFMET/D" );
	smallTree->Branch( "NELE", &nele, "NELE/I" );
	smallTree->Branch( "NMU", &nmu, "NMU/I" );
	smallTree->Branch( "NSOFTMU", &nsoftmu, "NSOFTMU/I" );
	smallTree->Branch( "L1PT", &l1pt, "L1PT/D" );
	smallTree->Branch( "L1ETA", &l1eta, "L1ETA/D" );
	smallTree->Branch( "L1PHI", &l1phi, "L1PHI/D" );
	smallTree->Branch( "L2PT", &l2pt, "L2PT/D" );
	smallTree->Branch( "L2ETA", &l2eta, "L2ETA/D" );
	smallTree->Branch( "L2PHI", &l2phi, "L2PHI/D" );
	smallTree->Branch( "ZMASS", &zmass, "ZMASS/D" );
	smallTree->Branch( "ZPT", &zpt, "ZPT/D" );
	smallTree->Branch( "ZETA", &zeta, "ZETA/D" );
	smallTree->Branch( "MT", &mt, "MT/D" );
	smallTree->Branch( "NSOFTJET", &nsoftjet, "NSOFTJET/I" );
	smallTree->Branch( "NHARDJET", &nhardjet, "NHARDJET/I" );
	smallTree->Branch( "MAXJETBTAG", &maxJetBTag, "MAXJETBTAG/D" );
	smallTree->Branch( "MINDPJETMET", &minDeltaPhiJetMet, "MINDPJETMET/D" );
	smallTree->Branch( "DETAJJ", &detajj, "DETAJJ/D" );
	smallTree->Branch( "MJJ", &mjj, "MJJ/D" );
	smallTree->Branch( "NVTX", &nvtx, "NVTX/I" );
	smallTree->Branch( "nInter" , &ni, "nInter/I" );
	smallTree->Branch( "CATEGORY", &category, "CATEGORY/I" );
	smallTree->Branch( "Weight" , &weight, "Weight/D" );
	smallTree->Branch( "HMASS", &hmass, "HMASS/D" );
	smallTree->Branch( "HWEIGHT", &hweight, "HWEIGHT/D" );

	bool isData = opt.checkBoolOption("DATA");

	unsigned long nentries = tree->GetEntries();

	RooDataSet * events = nullptr;

	PhotonPrescale photonPrescales;

	vector<int> thresholds;
	if (type == PHOT) {
		if (w == nullptr)
			throw string("ERROR: No mass peak pdf!");
		RooRealVar * zmass = w->var("mass");
		zmass->setRange(76.0, 106.0);
		RooAbsPdf * pdf = w->pdf("massPDF");
		events = pdf->generate(*zmass, nentries);

		photonPrescales.addTrigger("HLT_Photon36_R9Id90_HE10_Iso40_EBOnly", 36, 3, 7);
		photonPrescales.addTrigger("HLT_Photon50_R9Id90_HE10_Iso40_EBOnly", 50, 5, 8);
		photonPrescales.addTrigger("HLT_Photon75_R9Id90_HE10_Iso40_EBOnly", 75, 7, 9);
		photonPrescales.addTrigger("HLT_Photon90_R9Id90_HE10_Iso40_EBOnly", 90, 10, 10);
	}

	TH1D ptSpectrum("ptSpectrum", "ptSpectrum", 200, 55, 755);
	ptSpectrum.Sumw2();

	unordered_set<EventAdr> eventsSet;
	for ( unsigned long iEvent = 0; iEvent < nentries; iEvent++ ) {
//		if (iEvent < 6060000)
//			continue;

		if ( iEvent % 10000 == 0) {
			cout << string(40, '\b');
			cout << setw(10) << iEvent << " / " << setw(10) << nentries << " done ..." << std::flush;
		}

		tree->GetEntry( iEvent );

		run = -999;
		lumi = -999;
		event = -999;
		pfmet = -999;
		nele = -999;
		nmu = -999;
		nsoftmu = -999;
		l1pt = -999;
		l1eta = -999;
		l1phi = -999;
		l2pt = -999;
		l2eta = -999;
		l2phi = -999;
		zmass = -999;
		zpt = -999;
		zeta = -999;
		mt = -999;
		nsoftjet = -999;
		nhardjet = -999;
		maxJetBTag = -999;
		minDeltaPhiJetMet = -999;
		detajj = -999;
		mjj = -999;
		nvtx = -999;
		ni = -999;
		weight = -999;
		category = -1;
		hmass = -999;
		hweight = -999;

		run = *runP;
		lumi = *lumiP;
		event = *eventP;

		EventAdr tmp(run, lumi, event);
		if (eventsSet.find( tmp ) != eventsSet.end()) {
			continue;
		}
		eventsSet.insert( tmp );

		if (type == ELE && isData) {
			if (trigBits[0] != 1 || trigPres[0] != 1)
				continue;
		}

		if (type == MU && isData) {
			if ( (trigBits[2] != 1 || trigPres[2] != 1)
				&& (trigBits[3] != 1 || trigPres[3] != 1)
				&& (trigBits[6] != 1 || trigPres[6] != 1)
			   )
				continue;
		}

		if (type == EMU && isData) {
			if ( (trigBits[4] != 1 || trigPres[4] != 1)
				&& (trigBits[5] != 1 || trigPres[5] != 1)
			   )
				continue;
		}

		vector<Electron> electrons = buildLeptonCollection<Electron, 11>(ev, eleVars, addEleVars);
		vector<Muon> muons = buildLeptonCollection<Muon, 13>(ev, muVars, addMuVars);

		float rho = *rhoP;
		float rho25 = *rho25P;

		vector<Electron> looseElectrons;
		vector<Electron> selectedElectrons;
		for (unsigned j = 0; j < electrons.size(); ++j) {
			try {
			TLorentzVector lv = electrons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesVetoID() &&
					electrons[j].isPFIsolatedLoose(rho25)
				) {
				looseElectrons.push_back(electrons[j]);
			}

			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesMediumID() &&
					electrons[j].isPFIsolatedMedium(rho25)
				) {
				selectedElectrons.push_back(electrons[j]);
			}
			} catch (const string & exc) {
				cout << exc << endl;
				cout << "run = " << run << endl;
				cout << "lumi = " << lumi << endl;
				cout << "event = " << event << endl;
			}
		}

		vector<Muon> looseMuons;
		vector<Muon> softMuons;
		vector<Muon> selectedMuons;
		for (unsigned j = 0; j < muons.size(); ++j) {
			TLorentzVector lv = muons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isLooseMuon() &&
					muons[j].isPFIsolatedLoose()
				) {
				looseMuons.push_back(muons[j]);
			} else if (
					lv.Pt() > 3 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isSoftMuon()
				) {
				softMuons.push_back(muons[j]);
			}
			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isTightMuon() &&
					muons[j].isPFIsolatedTight()
				) {
				selectedMuons.push_back(muons[j]);
			}
		}

		vector<Lepton> looseLeptons;
		for (unsigned i = 0; i < looseElectrons.size(); ++i)
			looseLeptons.push_back(looseElectrons[i]);
		for (unsigned i = 0; i < looseMuons.size(); ++i)
			looseLeptons.push_back(looseMuons[i]);
		for (unsigned i = 0; i < softMuons.size(); ++i)
			looseLeptons.push_back(softMuons[i]);

#ifdef PRINTEVENTS
		evPrint.setElectronCollection(selectedElectrons);
		evPrint.setMuonCollection(selectedMuons);
#endif

		vector<Photon> photons = selectPhotonsCMG( ev );
		vector<Photon> selectedPhotons;
		for (unsigned i = 0; i < photons.size(); ++i) {
			if (photons[i].isSelected(rho) && photons[i].lorentzVector().Pt() > 55)
				selectedPhotons.push_back( photons[i] );
		}

		if (type == PHOT) {
			vector<Electron> tmpElectrons;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < looseElectrons.size(); ++j) {
					TLorentzVector elVec = looseElectrons[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), elVec.Eta(), elVec.Phi());
					if ( dR > 0.05 )
						tmpElectrons.push_back( looseElectrons[j] );
				}
			}
			looseElectrons = tmpElectrons;
		}

		string leptonsType;
		Lepton * selectedLeptons[2] = {0};
		if (type == ELE) {
			if (selectedElectrons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedElectrons[1];
			}
		} else if (type == MU) {
			if (selectedMuons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedMuons[0];
				selectedLeptons[1] = &selectedMuons[1];
			}
		} else if (type == EMU) {
			if (selectedElectrons.size() < 1 || selectedMuons.size() < 1) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedMuons[0];
			}
		} else if (type == PHOT) {
			if (selectedPhotons.size() != 1) {
				continue;
			}
		}

		nele = looseElectrons.size();
		nmu = looseMuons.size();
		nsoftmu = softMuons.size();

		TLorentzVector Zcand;

		if (type == ELE || type == MU || type == EMU) {
			TLorentzVector lep1 = selectedLeptons[0]->lorentzVector();
			TLorentzVector lep2 = selectedLeptons[1]->lorentzVector();

			if (lep2.Pt() > lep1.Pt() && type != EMU) {
				TLorentzVector temp = lep1;
				lep1 = lep2;
				lep2 = temp;
			}

			l1pt = lep1.Pt();
			l1eta = lep1.Eta();
			l1phi = lep1.Phi();

			l2pt = lep2.Pt();
			l2eta = lep2.Eta();
			l2phi = lep2.Phi();

			Zcand = lep1 + lep2;
			zmass = Zcand.M();
		} else if (type == PHOT) {
			Zcand = selectedPhotons[0].lorentzVector();
			zmass = events->get(iEvent)->getRealValue("mass");
		}

		zpt = Zcand.Pt();
		zeta = Zcand.Eta();

		if (type == PHOT) {
			unsigned idx = photonPrescales.getIndex(zpt);
			if (trigBits[idx])
				weight = trigPres[idx];
			else
				continue;
			ptSpectrum.Fill(zpt, weight);
		}

		TLorentzVector met;
		met.SetPtEtaPhiM(metPtA[0], 0.0, metPhiA[0], 0.0);
		TLorentzVector clusteredFlux;

		unsigned mode = 0;
		if (systVar == "JES_UP")
			mode = 1;
		else if (systVar == "JES_DOWN")
			mode = 2;
		TLorentzVector jecCorr;

#ifdef CMSSWENV
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, jecUnc, &jecCorr, mode );
#else
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, &jecCorr, mode );
#endif

		met -= jecCorr;

		mode = 0;
		if (systVar == "JER_UP")
			mode = 1;
		else if (systVar == "JER_DOWN")
			mode = 2;
		TLorentzVector smearCorr = smearJets( jetsAll, mode );
		if (isData && smearCorr != TLorentzVector())
			throw std::string("Jet smearing corrections different from zero in DATA!");
		met -= smearCorr;

		vector<Jet> selectedJets;
		for (unsigned i = 0; i < jetsAll.size(); ++i) {
			if (
					jetsAll[i].lorentzVector().Pt() > 10
					&& fabs(jetsAll[i].lorentzVector().Eta()) < 4.7
					&& jetsAll[i].passesPUID() &&
					jetsAll[i].passesPFLooseID()
				)
				selectedJets.push_back( jetsAll[i] );
		}
		if (type == PHOT) {
			vector<Jet> tmpJets;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < selectedJets.size(); ++j) {
					TLorentzVector jVec = selectedJets[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), jVec.Eta(), jVec.Phi());
					if ( dR > 0.4 )
						tmpJets.push_back( selectedJets[j] );
				}
			}
			selectedJets = tmpJets;
		}

		if (systVar == "UMET_UP" || systVar == "UMET_DOWN") {
			for (unsigned i = 0; i < jetsAll.size(); ++i)
				clusteredFlux += jetsAll[i].lorentzVector();
			for (unsigned i = 0; i < looseElectrons.size(); ++i)
				clusteredFlux += looseElectrons[i].lorentzVector();
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				clusteredFlux += looseMuons[i].lorentzVector();

			TLorentzVector unclusteredFlux = -(met + clusteredFlux);
			if (systVar == "UMET_UP")
				unclusteredFlux *= 1.1;
			else
				unclusteredFlux *= 0.9;
			met = -(clusteredFlux + unclusteredFlux);
		}

		if (systVar == "LES_UP" || systVar == "LES_DOWN") {
			TLorentzVector diff;
			double sign = 1.0;
			if (systVar == "LES_DOWN")
				sign = -1.0;
			for (unsigned i = 0; i < looseElectrons.size(); ++i) {
				TLorentzVector tempEle = looseElectrons[i].lorentzVector();
				if (looseElectrons[i].isEB())
					diff += sign * 0.02 * tempEle;
				else
					diff += sign * 0.05 * tempEle;
			}
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				diff += sign * 0.01 * looseMuons[i].lorentzVector();

			met -= diff;
		}

		pfmet = met.Pt();

		double px = met.Px() + Zcand.Px();
		double py = met.Py() + Zcand.Py();
		double pt2 = px * px + py * py;
		double e = sqrt(zpt * zpt + zmass * zmass) + sqrt(pfmet * pfmet + zmass * zmass);
		double mt2 = e * e - pt2;
		mt = (mt2 > 0) ? sqrt(mt2) : 0;

		vector<Jet> hardjets;
		vector<Jet> softjets;
		maxJetBTag = -999;
		minDeltaPhiJetMet = 999;
		for ( unsigned j = 0; j < selectedJets.size(); ++j ) {
			TLorentzVector jet = selectedJets[j].lorentzVector();

			if ( jet.Pt() > 30 ) {
				hardjets.push_back( selectedJets[j] );
			}
			if ( jet.Pt() > 15 )
				softjets.push_back( selectedJets[j] );
		}
		nhardjet = hardjets.size();
		nsoftjet = softjets.size();
//		if ( type == PHOT && nsoftjet == 0 )
//			continue;

		if (nhardjet > 1) {
			sort(hardjets.begin(), hardjets.end(), [](const Jet & a, const Jet & b) {
					return a.lorentzVector().Pt() > b.lorentzVector().Pt();
				});
			TLorentzVector jet1 = hardjets[0].lorentzVector();
			TLorentzVector jet2 = hardjets[1].lorentzVector();
			const double maxEta = max( jet1.Eta(), jet2.Eta() );
			const double minEta = min( jet1.Eta(), jet2.Eta() );
			bool passCJV = true;
			for (unsigned j = 2; j < hardjets.size(); ++j) {
				double tmpEta = hardjets[j].lorentzVector().Eta();
				if ( tmpEta > minEta && tmpEta < maxEta )
					passCJV = false;
			}
			const double tmpDelEta = std::fabs(jet2.Eta() - jet1.Eta());
			TLorentzVector diJetSystem = jet1 + jet2;
			const double tmpMass = diJetSystem.M();
			if ( type == PHOT) {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && zeta > minEta && maxEta > zeta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			} else {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && l1eta > minEta && l2eta > minEta && maxEta > l1eta && maxEta > l2eta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			}
		}

		category = evCategory(nhardjet, nsoftjet, detajj, mjj, type == PHOT);

		minDeltaPhiJetMet = 10;
		for ( unsigned j = 0; j < hardjets.size(); ++j ) {
			TLorentzVector jet = hardjets[j].lorentzVector();
			if ( hardjets[j].getVarF("jn_jp") > maxJetBTag && fabs(jet.Eta()) < 2.5 )
				maxJetBTag = hardjets[j].getVarF("jn_jp");
			double tempDelPhiJetMet = deltaPhi(met.Phi(), jet.Phi());
			if ( tempDelPhiJetMet < minDeltaPhiJetMet )
				minDeltaPhiJetMet = tempDelPhiJetMet;
		}

		nvtx = *nvtxP;

		if (isData)
			ni = -1;
		else
			ni = *niP;

		if (isSignal) {
			const int nMC = ev.getSVV<int>("mcn");
			const int * mcID = ev.getAVA<int>("mc_id");
			int hIdx = 0;
			for (; hIdx < nMC; ++hIdx)
				if (fabs(mcID[hIdx]) == 25)
					break;
			if (hIdx == nMC)
				throw string("ERROR: Higgs not found in signal sample!");

			float Hpx = ev.getAVV<float>("mc_px", hIdx);
			float Hpy = ev.getAVV<float>("mc_py", hIdx);
			float Hpz = ev.getAVV<float>("mc_pz", hIdx);
			float Hen = ev.getAVV<float>("mc_en", hIdx);
			TLorentzVector higgs;
			higgs.SetPxPyPzE( Hpx, Hpy, Hpz, Hen );
			hmass = higgs.M();

			if (higgsW) {
				hweight = higgsW->Eval(hmass);
				if (higgsI)
					hweight *= higgsI->Eval(hmass);
			} else
				hweight = 1;
		}

		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == ELE || type == MU || type == EMU) && ((nele + nmu + nsoftmu) > 2) )
			continue;
		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == PHOT) && ((nele + nmu + nsoftmu) > 0) )
			continue;
		if ( opt.checkBoolOption("ZPT_CUT") && zpt < 55 )
			continue;
		// for different background estimation methods different window should be applied:
		// * sample for photons should have 76.0 < zmass < 106.0
		// * sample for non-resonant background should not have this cut applied
		if ( opt.checkBoolOption("TIGHT_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("WIDE_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("BTAG_CUT") && ( maxJetBTag > 0.264) )
			continue;
		if ( opt.checkBoolOption("DPHI_CUT") && ( minDeltaPhiJetMet < 0.5) )
			continue;


#ifdef PRINTEVENTS
		evPrint.setJetCollection(hardjets);
		evPrint.setMET(met);
		evPrint.setMT(mt);
		string channelType;
		if (type == ELE)
			channelType = "ee";
		else if (type == MU)
			channelType = "mumu";
		else if (type == EMU)
			channelType = "emu";
		if (category == 1)
			channelType += "eq0jets";
		else if (category == 2)
			channelType += "geq1jets";
		else
			channelType += "vbf";
		evPrint.setChannel(channelType);
		unsigned bits = 0;
		bits |= (0x7);
		bits |= ((zmass > 76.0 && zmass < 106.0) << 3);
		bits |= ((zpt > 55) << 4);
		bits |= (((nele + nmu + nsoftmu) == 2) << 5);
		bits |= ((maxJetBTag < 0.275) << 6);
		bits |= ((minDeltaPhiJetMet > 0.5) << 7);
		evPrint.setBits(bits);
		evPrint.print();
#endif
		
		smallTree->Fill();
	}
	cout << endl;
	
	TCanvas canv("canv", "canv", 800, 600);
	//effNum.Sumw2();
	//effDen.Sumw2();
	//effNum.Divide(&effDen);
	//effNum.Draw();
	canv.SetGridy();
	canv.SetGridx();
	//canv.SaveAs("triggEff.ps");
	//canv.Clear();
	ptSpectrum.SetMarkerStyle(20);
	ptSpectrum.SetMarkerSize(0.5);
	ptSpectrum.Draw("P0E");
	//ptSpectrum.Draw("COLZ");
	canv.SetLogy();
	canv.SaveAs("ptSpectrum.ps");

	delete file;
	smallTree->Write("", TObject::kOverwrite);
	delete smallTree;
	delete out;
}
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;

}
// 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;
}
示例#11
0
void MakePlots(RooWorkspace* ws){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  RooDataSet *Data = (RooDataSet*)w->data("Data2011")->Clone("Data");
  Data->append( *((RooDataSet*)w->data("Data2012")) );

  RooDataSet *Bs2Kst0Kst0_MC = (RooDataSet*)w->data("Bs2Kst0Kst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2Kst0Kst0_MC->append( *((RooDataSet*)w->data("Bs2Kst0Kst0_MC2012")) );

  RooDataSet *Bs2Kst0Kst01430_MC = (RooDataSet*)w->data("Bs2Kst0Kst01430_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2Kst0Kst01430_MC->append( *((RooDataSet*)w->data("Bs2Kst0Kst01430_MC2012")) );

  RooDataSet *Bs2Kst01430Kst01430_MC = (RooDataSet*)w->data("Bs2Kst01430Kst01430_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2Kst01430Kst01430_MC->append( *((RooDataSet*)w->data("Bs2Kst01430Kst01430_MC2012")) );

  RooDataSet *Bd2Kst0Kst0_MC = (RooDataSet*)w->data("Bd2Kst0Kst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bd2Kst0Kst0_MC->append( *((RooDataSet*)w->data("Bd2Kst0Kst0_MC2012")) );

  RooDataSet *Bd2PhiKst0_MC = (RooDataSet*)w->data("Bd2PhiKst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bd2PhiKst0_MC->append( *((RooDataSet*)w->data("Bd2PhiKst0_MC2012")) );

  RooDataSet *Bs2PhiKst0_MC = (RooDataSet*)w->data("Bs2PhiKst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2PhiKst0_MC->append( *((RooDataSet*)w->data("Bs2PhiKst0_MC2012")) );

  RooDataSet *Bd2RhoKst0_MC = (RooDataSet*)w->data("Bd2RhoKst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bd2RhoKst0_MC->append( *((RooDataSet*)w->data("Bd2RhoKst0_MC2012")) );

  RooDataSet *Lb2ppipipi_MC = (RooDataSet*)w->data("Lb2ppipipi_MC2011")->Clone("Bs2KstKst0_MC");
  Lb2ppipipi_MC->append( *((RooDataSet*)w->data("Lb2ppipipi_MC2012")) );

  RooDataSet *Lb2pKpipi_MC = (RooDataSet*)w->data("Lb2pKpipi_MC2011")->Clone("Bs2KstKst0_MC");
  Lb2pKpipi_MC->append( *((RooDataSet*)w->data("Lb2pKpipi_MC2012")) );


  w->import(*Data);
  w->import(*Bs2Kst0Kst0_MC);
  w->import(*Bs2Kst0Kst01430_MC);
  w->import(*Bs2Kst01430Kst01430_MC);
  w->import(*Bd2Kst0Kst0_MC);
  w->import(*Bd2PhiKst0_MC);
  w->import(*Bs2PhiKst0_MC);
  w->import(*Bd2RhoKst0_MC);
  w->import(*Lb2ppipipi_MC);
  w->import(*Lb2pKpipi_MC);

  RooRealVar *mass = (RooRealVar*)w->var("B_s0_DTF_B_s0_M");

  fitIpatia( w, "bs2kstkst_mc", "Bs2KstKst0_MC");

  // Make the PDF here
  RooRealVar *p1 = new RooRealVar("p1","p1",-0.002,-0.004,0.);
  RooExponential *exp = new RooExponential("exp","exp",*mass,*p1);
  //RooRealVar *m1 = new RooRealVar("m1","m1",5320,5380);
  //RooRealVar *s1 = new RooRealVar("s1","s1",1,20);
  //RooGaussian *sig = new RooGaussian("sig","sig",*mass,*m1,*s1);
  RooRealVar *m2 = new RooRealVar("m2","m2",5320,5380);
  RooRealVar *s2 = new RooRealVar("s2","s2",1,20);
  RooGaussian *sig_bd = new RooGaussian("sig_bd","sig_bd",*mass,*m2,*s2);

  //
  RooRealVar *bs2kstkst_l       = new RooRealVar( "bs2kstkst_l"    ,"", -5, -20, -1.);
  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   ,20 );
  RooRealVar *bs2kstkst_mu      = new RooRealVar( "bs2kstkst_mu"   ,"",5350  ,5380     );
  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","sig",*mass,*bs2kstkst_l,*bs2kstkst_zeta,*bs2kstkst_fb,*bs2kstkst_sigma,*bs2kstkst_mu,*bs2kstkst_a,*bs2kstkst_n,*bs2kstkst_a2,*bs2kstkst_n2);

  RooRealVar *bkg_y = new RooRealVar("bkg_y","bkg_y",10e3,10e5);
  RooRealVar *sig_y = new RooRealVar("sig_y","sig_y",0,20e3);
  RooRealVar *sig_bd_y = new RooRealVar("sig_bd_y","sig_bd_y",0,3000);

  RooArgList *pdfs = new RooArgList();
  RooArgList *yields = new RooArgList();

  pdfs->add( *exp );
  pdfs->add( *sig );
  pdfs->add( *sig_bd );

  yields->add( *bkg_y );
  yields->add( *sig_y );
  yields->add( *sig_bd_y );

  RooAddPdf *pdf = new RooAddPdf("pdf","pdf",*pdfs,*yields);

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

  RooPlot *plot = mass->frame();
  Data->plotOn(plot);
    // set fit params constant;
  pdf->plotOn(plot);

  TCanvas *c = new TCanvas();
  plot->Draw();
  c->Print("tmp/mass.pdf");

  // Plots Kst Ms with no sweights
  TCanvas *c1 = new TCanvas("c1","c1",800,1200);
  c1->Divide(1,2);
  c1->cd(1);
  RooPlot *c1p1 = w->var("B_s0_DTF_KST1_M")->frame();
  Data->plotOn(c1p1);
  c1p1->Draw();
  c1->cd(2);
  RooPlot *c1p2 = w->var("B_s0_DTF_KST2_M")->frame();
  Data->plotOn(c1p2);
  c1p2->Draw();
  c1->Print("tmp/nosw.pdf");

  // set fit params constant
  p1->setConstant(true);
  //m1->setConstant(true);
  //s1->setConstant(true);
  bs2kstkst_l->setConstant(true);
  //bs2kstkst_zeta->setConstant(true);
  //bs2kstkst_fb->setConstant(true);
  bs2kstkst_sigma->setConstant(true);
  bs2kstkst_mu->setConstant(true);
  bs2kstkst_a->setConstant(true);
  bs2kstkst_n->setConstant(true);
  bs2kstkst_a2->setConstant(true);
  bs2kstkst_n2->setConstant(true);
  m2->setConstant(true);
  s2->setConstant(true);

  RooStats::SPlot *sData = new RooStats::SPlot("sData","sData", *Data, pdf, *yields);

  w->import(*sData);
  w->import(*Data,Rename("Data_wsweights"));

  RooDataSet *swdata = new RooDataSet("Data_wsweights", "Data", Data, *Data->get(), 0 , "sig_y_sw");
  // Plots Kst Ms with no sweights
  TCanvas *c2 = new TCanvas("c2","c2",800,1200);
  c2->Divide(1,2);
  c2->cd(1);
  RooPlot *c2p1 = w->var("B_s0_DTF_KST1_M")->frame();
  swdata->plotOn(c2p1);
  c2p1->Draw();
  c2->cd(2);
  RooPlot *c2p2 = w->var("B_s0_DTF_KST2_M")->frame();
  swdata->plotOn(c2p2);
  c2p2->Draw();
  c2->Print("tmp/withsw.pdf");


  tf->Close();
  return 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;
} 
示例#14
0
文件: makeEffToys.C 项目: dcraik/lhcb
void makeEffToys(Int_t seed, TString veto="D") {
//	r.SetSeed(seed);
	r = RooRandom::randomGenerator();
	r->SetSeed(seed);

	TFile* fin = TFile::Open(veto+"veto_200.root");

	TString fName("toys/"); fName+=seed; fName+="/"+veto+"veto_200.root";

	TFile* fout = new TFile(fName,"RECREATE");

	for(Int_t j=0; j<21; ++j) {
		TString hName  = "efficiency_"; hName+=j;
		TString hName2 = "efficiencyHist_"; hName2+=j;
		TEfficiency* hin = dynamic_cast<TEfficiency*>(fin->Get(hName));

		TH1* hout = dynamic_cast<TH1*>(hin->GetTotalHistogram()->Clone(hName2));

		std::vector<Int_t> corrBins;

		Int_t n = hout->GetNbinsX();
		for(Int_t i=0; i<n; ++i) {
			Double_t eff = hin->GetEfficiency(i+1);
			Double_t erm = hin->GetEfficiencyErrorLow(i+1);
			Double_t erp = hin->GetEfficiencyErrorUp(i+1);

			Bool_t fluctuate = kTRUE;

			// don't fluctuate if the veto hasn't affected this bin
			// also ignore the odd missing entry - not sure what causes these but they don't seem reasonable
			if((eff > 0.99 && eff + erp > 0.999) //efficiency close to 1 and not significantly different
			|| ((i<1 || hin->GetEfficiency(i) == 1) && (i>n-1 || hin->GetEfficiency(i+2) == 1))) { //single bin dip (careful with this one)
				eff = 1;
				fluctuate = kFALSE;
			}
			if(eff < 0.01 && eff - erm < 0.001) {//efficiency close to 0 and not significantly different
				eff = 0;
				fluctuate = kFALSE;
			}

			//otherwise we're fluctuating the bin
			if(fluctuate) {
				//if the errors are roughly symmetric then we can symmetrise them and introduce some correlation between neighbouring bins
				//this is difficult to do with asymmetric errors so if asymmetry > 10% lets just ignore correlations
				//note that a large asymmetry in neighbouring bins will also lead to same-sign fluctuations anyway
				if((erm - erp) / (erm + erp) < 0.1) {
					//correlation is more important than asymmetry

					//add bin to the list to be fluctuated later
					corrBins.push_back(i+1);

				} else {
					//asymmetry is more important than correlation

					//first catch any cases on a limit (the previous checks for eff > 0.99 and eff < 0.01 should catch these but play it safe)
					if(erm <= 0) {
						//vary with a half Gaussian
						eff += TMath::Abs(r->Gaus(0.,erp));
					} else if(erp <= 0) {
						//vary with a half Gaussian
						eff -= TMath::Abs(r->Gaus(0.,erm));
					} else {
						//vary with a bifurcated Gaussian
						RooRealVar effVar( "effVar", "",-1.,2.);
						RooRealVar muVar(  "muVar",  "",eff);
						RooRealVar sigmVar("sigmVar","",erm);
						RooRealVar sigpVar("sigpVar","",erp);

						RooBifurGauss pdf("pdf","",effVar,muVar,sigmVar,sigpVar);
						RooDataSet* ds = pdf.generate(RooArgSet(effVar),1);
						eff = ds->get(0)->getRealValue("effVar");
						delete ds;
					}
				}
			}
			if(eff > 1.0) eff = 1.0; //std::cout << i << "\t" << eff << "\t" << erp << "\t" << erm << std::endl;
//			std::cout << hin->GetEfficiency(i+1) << "\t" << eff << std::endl;

			hout->SetBinContent(i+1, eff);
		}

		//now deal with the correlated efficiencies
		Double_t corrFactor(0.01);

		while(!doCorrelatedBinFluctuation(hin,hout,corrBins,corrFactor)) {
			corrFactor /= 2.;
		}

//		std::cout << std::endl;

		TCanvas c;
		hin->Draw();
		hout->SetMarkerColor(kRed);
		hout->SetMarkerStyle(4);
		hout->Draw("Psame");
		TString pName = "plots/toys/"; pName+=seed; pName+="/"+veto+"veto_Q"; pName+=j; pName+=".pdf";
		c.SaveAs(pName);
	}

	hout->Write();
	fout->Close();
}
///
/// Perform the 1d Prob scan.
/// Saves chi2 values and the prob-Scan p-values in a root tree
/// For the datasets stuff, we do not yet have a MethodDatasetsProbScan class, so we do it all in
/// MethodDatasetsProbScan
/// \param nRun Part of the root tree file name to facilitate parallel production.
///
int MethodDatasetsProbScan::scan1d(bool fast, bool reverse)
{
	if (fast) return 0; // tmp

	if ( arg->debug ) cout << "MethodDatasetsProbScan::scan1d() : starting ... " << endl;

    // Set limit to all parameters.
    this->loadParameterLimits(); /// Default is "free", if not changed by cmd-line parameter


    // Define scan parameter and scan range.
    RooRealVar *parameterToScan = w->var(scanVar1);
    float parameterToScan_min = hCL->GetXaxis()->GetXmin();
    float parameterToScan_max = hCL->GetXaxis()->GetXmax();

		// do a free fit
		RooFitResult *result = this->loadAndFit(this->pdf); // fit on data
		assert(result);
    RooSlimFitResult *slimresult = new RooSlimFitResult(result,true);
		slimresult->setConfirmed(true);
		solutions.push_back(slimresult);
		double freeDataFitValue = w->var(scanVar1)->getVal();

    // Define outputfile
    system("mkdir -p root");
    TString probResName = Form("root/scan1dDatasetsProb_" + this->pdf->getName() + "_%ip" + "_" + scanVar1 + ".root", arg->npoints1d);
    TFile* outputFile = new TFile(probResName, "RECREATE");

    // Set up toy root tree
    this->probScanTree = new ToyTree(this->pdf, arg);
    this->probScanTree->init();
    this->probScanTree->nrun = -999; //\todo: why does this branch even exist in the output tree of the prob scan?

    // Save parameter values that were active at function
    // call. We'll reset them at the end to be transparent
    // to the outside.
    RooDataSet* parsFunctionCall = new RooDataSet("parsFunctionCall", "parsFunctionCall", *w->set(pdf->getParName()));
    parsFunctionCall->add(*w->set(pdf->getParName()));

    // start scan
    cout << "MethodDatasetsProbScan::scan1d_prob() : starting ... with " << nPoints1d << " scanpoints..." << endl;
    ProgressBar progressBar(arg, nPoints1d);
    for ( int i = 0; i < nPoints1d; i++ )
    {
        progressBar.progress();
        // scanpoint is calculated using min, max, which are the hCL x-Axis limits set in this->initScan()
        // this uses the "scan" range, as expected
        // don't add half the bin size. try to solve this within plotting method

        float scanpoint = parameterToScan_min + (parameterToScan_max - parameterToScan_min) * (double)i / ((double)nPoints1d - 1);
				if (arg->debug) cout << "DEBUG in MethodDatasetsProbScan::scan1d_prob() " << scanpoint << " " << parameterToScan_min << " " << parameterToScan_max << endl;

        this->probScanTree->scanpoint = scanpoint;

        if (arg->debug) cout << "DEBUG in MethodDatasetsProbScan::scan1d_prob() - scanpoint in step " << i << " : " << scanpoint << endl;

        // don't scan in unphysical region
        // by default this means checking against "free" range
        if ( scanpoint < parameterToScan->getMin() || scanpoint > parameterToScan->getMax() + 2e-13 ) {
            cout << "it seems we are scanning in an unphysical region: " << scanpoint << " < " << parameterToScan->getMin() << " or " << scanpoint << " > " << parameterToScan->getMax() + 2e-13 << endl;
            exit(EXIT_FAILURE);
        }

        // FIT TO REAL DATA WITH FIXED HYPOTHESIS(=SCANPOINT).
        // THIS GIVES THE NUMERATOR FOR THE PROFILE LIKELIHOOD AT THE GIVEN HYPOTHESIS
        // THE RESULTING NUISANCE PARAMETERS TOGETHER WITH THE GIVEN HYPOTHESIS ARE ALSO
        // USED WHEN SIMULATING THE TOY DATA FOR THE FELDMAN-COUSINS METHOD FOR THIS HYPOTHESIS(=SCANPOINT)
        // Here the scanvar has to be fixed -> this is done once per scanpoint
        // and provides the scanner with the DeltaChi2 for the data as reference
        // additionally the nuisances are set to the resulting fit values

        parameterToScan->setVal(scanpoint);
        parameterToScan->setConstant(true);

        RooFitResult *result = this->loadAndFit(this->pdf); // fit on data
        assert(result);

        if (arg->debug) {
            cout << "DEBUG in MethodDatasetsProbScan::scan1d_prob() - minNll data scan at scan point " << scanpoint << " : " << 2 * result->minNll() << ": "<< 2 * pdf->getMinNll() << endl;
        }
        this->probScanTree->statusScanData = result->status();

        // set chi2 of fixed fit: scan fit on data
        // CAVEAT: chi2min from fitresult gives incompatible results to chi2min from pdf
        // this->probScanTree->chi2min           = 2 * result->minNll();
        this->probScanTree->chi2min           = 2 * pdf->getMinNll();
        this->probScanTree->covQualScanData   = result->covQual();
        this->probScanTree->scanbest  = freeDataFitValue;

        // After doing the fit with the parameter of interest constrained to the scanpoint,
        // we are now saving the fit values of the nuisance parameters. These values will be
        // used to generate toys according to the PLUGIN method.
        this->probScanTree->storeParsScan(); // \todo : figure out which one of these is semantically the right one

        this->pdf->deleteNLL();

        // also save the chi2 of the free data fit to the tree:
        this->probScanTree->chi2minGlobal = this->getChi2minGlobal();
        this->probScanTree->chi2minBkg = this->getChi2minBkg();

        this->probScanTree->genericProbPValue = this->getPValueTTestStatistic(this->probScanTree->chi2min - this->probScanTree->chi2minGlobal);
        this->probScanTree->fill();

        if(arg->debug && pdf->getBkgPdf())
        {
            float pval_cls = this->getPValueTTestStatistic(this->probScanTree->chi2min - this->probScanTree->chi2minBkg, true);
            cout << "DEBUG in MethodDatasetsProbScan::scan1d() - p value CLs: " << pval_cls << endl;
        }


        // reset
        setParameters(w, pdf->getParName(), parsFunctionCall->get(0));
        //setParameters(w, pdf->getObsName(), obsDataset->get(0));
    } // End of npoints loop
    probScanTree->writeToFile();
    if (bkgOnlyFitResult) bkgOnlyFitResult->Write();
    if (dataFreeFitResult) dataFreeFitResult->Write();
    outputFile->Close();
    std::cout << "Wrote ToyTree to file" << std::endl;
    delete parsFunctionCall;

    // This is kind of a hack. The effect is supposed to be the same as callincg
    // this->sethCLFromProbScanTree(); here, but the latter gives a segfault somehow....
    // \todo: use this->sethCLFromProbScanTree() directly after figuring out the cause of the segfault.
    this->loadScanFromFile();

    return 0;
}
示例#16
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();

}
示例#17
0
文件: track_pt.C 项目: d4space/KoSMP
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();
}
示例#18
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();
}
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")));
}
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;

}
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();
   }
}
示例#23
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();

}
示例#24
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"));

}
示例#25
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");

}
示例#26
0
///
/// Find the global minimum in a more thorough way.
/// First fit with external start parameters, then
/// for each parameter that starts with "d" or "r" (typically angles and ratios):
///   - at upper scan range, rest at start parameters
///   - at lower scan range, rest at start parameters
/// This amounts to a maximum of 1+2^n fits, where n is the number
/// of parameters to be varied.
///
/// \param w Workspace holding the pdf.
/// \param name Name of the pdf without leading "pdf_".
/// \param forceVariables Apply the force method for these variables only. Format
/// "var1,var2,var3," (list must end with comma). Default is to apply for all angles,
/// all ratios except rD_k3pi and rD_kpi, and the k3pi coherence factor.
///
RooFitResult* Utils::fitToMinForce(RooWorkspace *w, TString name, TString forceVariables)
{
	bool debug = true;

	TString parsName = "par_"+name;
	TString obsName  = "obs_"+name;
	TString pdfName  = "pdf_"+name;
	RooFitResult *r = 0;
	int printlevel = -1;
	RooMsgService::instance().setGlobalKillBelow(ERROR);

	// save start parameters
	if ( !w->set(parsName) ){
		cout << "MethodProbScan::scan2d() : ERROR : parsName not found: " << parsName << endl;
		exit(1);
	}
	RooDataSet *startPars = new RooDataSet("startParsForce", "startParsForce", *w->set(parsName));
	startPars->add(*w->set(parsName));

	// set up parameters and ranges
	RooArgList *varyPars = new RooArgList();
	TIterator* it = w->set(parsName)->createIterator();
	while ( RooRealVar* p = (RooRealVar*)it->Next() )
	{
		if ( p->isConstant() ) continue;
		if ( forceVariables=="" && ( false
					|| TString(p->GetName()).BeginsWith("d") ///< use these variables
					// || TString(p->GetName()).BeginsWith("r")
					|| TString(p->GetName()).BeginsWith("k")
					|| TString(p->GetName()) == "g"
					) && ! (
						TString(p->GetName()) == "rD_k3pi"  ///< don't use these
						|| TString(p->GetName()) == "rD_kpi"
						// || TString(p->GetName()) == "dD_kpi"
						|| TString(p->GetName()) == "d_dk"
						|| TString(p->GetName()) == "d_dsk"
						))
		{
			varyPars->add(*p);
		}
		else if ( forceVariables.Contains(TString(p->GetName())+",") )
		{
			varyPars->add(*p);
		}
	}
	delete it;
	int nPars = varyPars->getSize();
	if ( debug ) cout << "Utils::fitToMinForce() : nPars = " << nPars << " => " << pow(2.,nPars) << " fits" << endl;
	if ( debug ) cout << "Utils::fitToMinForce() : varying ";
	if ( debug ) varyPars->Print();

	//////////

	r = fitToMinBringBackAngles(w->pdf(pdfName), false, printlevel);

	//////////

	int nErrors = 0;

	// We define a binary mask where each bit corresponds
	// to parameter at max or at min.
	for ( int i=0; i<pow(2.,nPars); i++ )
	{
		if ( debug ) cout << "Utils::fitToMinForce() : fit " << i << "        \r" << flush;
		setParameters(w, parsName, startPars->get(0));

		for ( int ip=0; ip<nPars; ip++ )
		{
			RooRealVar *p = (RooRealVar*)varyPars->at(ip);
			float oldMin = p->getMin();
			float oldMax = p->getMax();
			setLimit(w, p->GetName(), "force");
			if ( i/(int)pow(2.,ip) % 2==0 ) { p->setVal(p->getMin()); }
			if ( i/(int)pow(2.,ip) % 2==1 ) { p->setVal(p->getMax()); }
			p->setRange(oldMin, oldMax);
		}

		// check if start parameters are sensible, skip if they're not
		double startParChi2 = getChi2(w->pdf(pdfName));
		if ( startParChi2>2000 ){
			nErrors += 1;
			continue;
		}

		// refit
		RooFitResult *r2 = fitToMinBringBackAngles(w->pdf(pdfName), false, printlevel);

		// In case the initial fit failed, accept the second one.
		// If both failed, still select the second one and hope the
		// next fit succeeds.
		if ( !(r->edm()<1 && r->covQual()==3) ){
			delete r;
			r = r2;
		}
		else if ( r2->edm()<1 && r2->covQual()==3 && r2->minNll()<r->minNll() ){
			// better minimum found!
			delete r;
			r = r2;
		}
		else{
			delete r2;
		}
	}

	if ( debug ) cout << endl;
	if ( debug ) cout << "Utils::fitToMinForce() : nErrors = " << nErrors << endl;

	RooMsgService::instance().setGlobalKillBelow(INFO);

	// (re)set to best parameters
	setParameters(w, parsName, r);

	delete startPars;
	return r;
}
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();

}
示例#28
0
   void fitqual_plots( const char* wsfile = "outputfiles/ws.root", const char* plottitle="" ) {

      TText* tt_title = new TText() ;
      tt_title -> SetTextAlign(33) ;

      gStyle -> SetOptStat(0) ;
      gStyle -> SetLabelSize( 0.06, "y" ) ;
      gStyle -> SetLabelSize( 0.08, "x" ) ;
      gStyle -> SetLabelOffset( 0.010, "y" ) ;
      gStyle -> SetLabelOffset( 0.010, "x" ) ;
      gStyle -> SetTitleSize( 0.07, "y" ) ;
      gStyle -> SetTitleSize( 0.05, "x" ) ;
      gStyle -> SetTitleOffset( 1.50, "x" ) ;
      gStyle -> SetTitleH( 0.07 ) ;
      gStyle -> SetPadLeftMargin( 0.15 ) ;
      gStyle -> SetPadBottomMargin( 0.15 ) ;
      gStyle -> SetTitleX( 0.10 ) ;

      gDirectory->Delete("h*") ;

      TFile* wstf = new TFile( wsfile ) ;

      RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
      ws->Print() ;

      int bins_of_met = TMath::Nint( ws->var("bins_of_met")->getVal()  ) ;
      printf("\n\n Bins of MET : %d\n\n", bins_of_met ) ;

      int bins_of_nb = TMath::Nint( ws->var("bins_of_nb")->getVal()  ) ;
      printf("\n\n Bins of nb : %d\n\n", bins_of_nb ) ;

      int nb_lookup[10] ;
      if ( bins_of_nb == 2 ) {
         nb_lookup[0] = 2 ;
         nb_lookup[1] = 4 ;
      } else if ( bins_of_nb == 3 ) {
         nb_lookup[0] = 2 ;
         nb_lookup[1] = 3 ;
         nb_lookup[2] = 4 ;
      }

      TCanvas* cfq1 = (TCanvas*) gDirectory->FindObject("cfq1") ;
      if ( cfq1 == 0x0 ) {
         if ( bins_of_nb == 3 ) {
            cfq1 = new TCanvas("cfq1","hbb fit", 700, 1000 ) ;
         } else if ( bins_of_nb == 2 ) {
            cfq1 = new TCanvas("cfq1","hbb fit", 700, 750 ) ;
         } else {
            return ;
         }
      }

      RooRealVar* rv_sig_strength = ws->var("sig_strength") ;
      if ( rv_sig_strength == 0x0 ) { printf("\n\n *** can't find sig_strength in workspace.\n\n" ) ; return ; }

      ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;

      RooDataSet* rds = (RooDataSet*) ws->obj( "hbb_observed_rds" ) ;

      rds->Print() ;
      rds->printMultiline(cout, 1, kTRUE, "") ;

      RooAbsPdf* likelihood = modelConfig->GetPdf() ;

      ///RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
      RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(3) ) ;
      fitResult->Print() ;


      char hname[1000] ;
      char htitle[1000] ;
      char pname[1000] ;




     //-- unpack observables.

      int obs_N_msig[10][50] ; // first index is n btags, second is met bin.
      int obs_N_msb[10][50]  ; // first index is n btags, second is met bin.

      const RooArgSet* dsras = rds->get() ;
      TIterator* obsIter = dsras->createIterator() ;
      while ( RooRealVar* obs = (RooRealVar*) obsIter->Next() ) {
         for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {
            for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
               sprintf( pname, "N_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
               if ( strcmp( obs->GetName(), pname ) == 0 ) { obs_N_msig[nbi][mbi] = TMath::Nint( obs -> getVal() ) ; }
               sprintf( pname, "N_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
               if ( strcmp( obs->GetName(), pname ) == 0 ) { obs_N_msb[nbi][mbi] = TMath::Nint( obs -> getVal() ) ; }
            } // mbi.
         } // nbi.
      } // obs iterator.


      printf("\n\n") ;
      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {
         printf(" nb=%d :  ", nb_lookup[nbi] ) ;
         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
            printf("  sig=%3d, sb=%3d  |", obs_N_msig[nbi][mbi], obs_N_msb[nbi][mbi] ) ;
         } // mbi.
         printf("\n") ;
      } // nbi.
      printf("\n\n") ;




      int pad(1) ;

      cfq1->Clear() ;
      cfq1->Divide( 2, bins_of_nb+1 ) ;

      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {


         sprintf( hname, "h_bg_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_bg_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_bg_msig -> SetFillColor( kBlue-9 ) ;
         labelBins( hist_bg_msig ) ;

         sprintf( hname, "h_bg_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_bg_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_bg_msb -> SetFillColor( kBlue-9 ) ;
         labelBins( hist_bg_msb ) ;

         sprintf( hname, "h_sig_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_sig_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_sig_msig -> SetFillColor( kMagenta+2 ) ;
         labelBins( hist_sig_msig ) ;

         sprintf( hname, "h_sig_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_sig_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_sig_msb -> SetFillColor( kMagenta+2 ) ;
         labelBins( hist_sig_msb ) ;

         sprintf( hname, "h_all_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_all_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;

         sprintf( hname, "h_all_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_all_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;

         sprintf( hname, "h_data_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_data_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_data_msig -> SetLineWidth(2) ;
         hist_data_msig -> SetMarkerStyle(20) ;
         labelBins( hist_data_msig ) ;

         sprintf( hname, "h_data_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_data_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_data_msb -> SetLineWidth(2) ;
         hist_data_msb -> SetMarkerStyle(20) ;
         labelBins( hist_data_msb ) ;

         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {



            sprintf( pname, "mu_bg_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_bg_msig = ws->function( pname ) ;
            if ( mu_bg_msig == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_bg_msig -> SetBinContent( mbi+1, mu_bg_msig->getVal() ) ;

            sprintf( pname, "mu_sig_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_sig_msig = ws->function( pname ) ;
            if ( mu_sig_msig == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_sig_msig -> SetBinContent( mbi+1, mu_sig_msig->getVal() ) ;

            hist_all_msig -> SetBinContent( mbi+1, mu_bg_msig->getVal() + mu_sig_msig->getVal() ) ;

            hist_data_msig -> SetBinContent( mbi+1, obs_N_msig[nbi][mbi] ) ;



            sprintf( pname, "mu_bg_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_bg_msb = ws->function( pname ) ;
            if ( mu_bg_msb == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_bg_msb -> SetBinContent( mbi+1, mu_bg_msb->getVal() ) ;

            sprintf( pname, "mu_sig_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_sig_msb = ws->function( pname ) ;
            if ( mu_sig_msb == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_sig_msb -> SetBinContent( mbi+1, mu_sig_msb->getVal() ) ;

            hist_all_msb -> SetBinContent( mbi+1, mu_bg_msb->getVal() + mu_sig_msb->getVal() ) ;

            hist_data_msb -> SetBinContent( mbi+1, obs_N_msb[nbi][mbi] ) ;



         } // mbi.

         cfq1->cd( pad ) ;

         sprintf( hname, "h_stack_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         THStack* hstack_msig = new THStack( hname, htitle ) ;
         hstack_msig -> Add( hist_bg_msig ) ;
         hstack_msig -> Add( hist_sig_msig ) ;

         hist_data_msig -> Draw("e") ;
         hstack_msig -> Draw("same") ;
         hist_data_msig -> Draw("same e") ;
         hist_data_msig -> Draw("same axis") ;

         tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

         pad++ ;



         cfq1->cd( pad ) ;

         sprintf( hname, "h_stack_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         THStack* hstack_msb = new THStack( hname, htitle ) ;
         hstack_msb -> Add( hist_bg_msb ) ;
         hstack_msb -> Add( hist_sig_msb ) ;

         hist_data_msb -> Draw("e") ;
         hstack_msb -> Draw("same") ;
         hist_data_msb -> Draw("same e") ;
         hist_data_msb -> Draw("same axis") ;

         tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

         pad++ ;



      } // nbi.




      TH1F* hist_R_msigmsb = new TH1F( "h_R_msigmsb", "R msig/msb vs met bin", bins_of_met, 0.5, 0.5+bins_of_met ) ;
      hist_R_msigmsb -> SetLineWidth(2) ;
      hist_R_msigmsb -> SetMarkerStyle(20) ;
      hist_R_msigmsb -> SetYTitle("R msig/msb") ;
      labelBins( hist_R_msigmsb ) ;


      for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
         sprintf( pname, "R_msigmsb_met%d", mbi+1 ) ;
         RooRealVar* rrv_R = ws->var( pname ) ;
         if ( rrv_R == 0x0 ) { printf("\n\n *** Can't find %s in ws.\n\n", pname ) ; return ; }
         hist_R_msigmsb -> SetBinContent( mbi+1, rrv_R -> getVal() ) ;
         hist_R_msigmsb -> SetBinError( mbi+1, rrv_R -> getError() ) ;
      } // mbi.

      cfq1->cd( pad ) ;

      gPad->SetGridy(1) ;

      hist_R_msigmsb -> SetMaximum(0.35) ;
      hist_R_msigmsb -> Draw("e") ;

      tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

      pad++ ;



      cfq1->cd( pad ) ;

      scan_sigstrength( wsfile ) ;

      tt_title -> DrawTextNDC( 0.85, 0.25, plottitle ) ;



      TString pdffile( wsfile ) ;
      pdffile.ReplaceAll("ws-","fitqual-") ;
      pdffile.ReplaceAll("root","pdf") ;


      cfq1->SaveAs( pdffile ) ;



      TString histfile( wsfile ) ;
      histfile.ReplaceAll("ws-","fitqual-") ;

      saveHist( histfile, "h*" ) ;



   } // fitqual_plots
示例#29
0
void rf403_weightedevts()
{
  // C r e a t e   o b s e r v a b l e   a n d   u n w e i g h t e d   d a t a s e t 
  // -------------------------------------------------------------------------------

  // Declare observable
  RooRealVar x("x","x",-10,10) ;
  x.setBins(40) ;

  // Construction a uniform pdf
  RooPolynomial p0("px","px",x) ;

  // Sample 1000 events from pdf
  RooDataSet* data = p0.generate(x,1000) ;

 

  // C a l c u l a t e   w e i g h t   a n d   m a k e   d a t a s e t   w e i g h t e d 
  // -----------------------------------------------------------------------------------

  // Construct formula to calculate (fake) weight for events
  RooFormulaVar wFunc("w","event weight","(x*x+10)",x) ;

  // Add column with variable w to previously generated dataset
  RooRealVar* w = (RooRealVar*) data->addColumn(wFunc) ;

  // Dataset d is now a dataset with two observable (x,w) with 1000 entries
  data->Print() ;

  // Instruct dataset wdata in interpret w as event weight rather than as observable
  RooDataSet wdata(data->GetName(),data->GetTitle(),data,*data->get(),0,w->GetName()) ;

  // Dataset d is now a dataset with one observable (x) with 1000 entries and a sum of weights of ~430K
  wdata.Print() ;



  // U n b i n n e d   M L   f i t   t o   w e i g h t e d   d a t a 
  // ---------------------------------------------------------------

  // Construction quadratic polynomial pdf for fitting
  RooRealVar a0("a0","a0",1) ;
  RooRealVar a1("a1","a1",0,-1,1) ;
  RooRealVar a2("a2","a2",1,0,10) ;
  RooPolynomial p2("p2","p2",x,RooArgList(a0,a1,a2),0) ;

  // Fit quadratic polynomial to weighted data

  // NOTE: A plain Maximum likelihood fit to weighted data does in general 
  //       NOT result in correct error estimates, unless individual
  //       event weights represent Poisson statistics themselves.
  //       
  // Fit with 'wrong' errors
  RooFitResult* r_ml_wgt = p2.fitTo(wdata,Save()) ;
  
  // A first order correction to estimated parameter errors in an 
  // (unbinned) ML fit can be obtained by calculating the
  // covariance matrix as
  //
  //    V' = V C-1 V
  //
  // where V is the covariance matrix calculated from a fit
  // to -logL = - sum [ w_i log f(x_i) ] and C is the covariance
  // matrix calculated from -logL' = -sum [ w_i^2 log f(x_i) ] 
  // (i.e. the weights are applied squared)
  //
  // A fit in this mode can be performed as follows:

  RooFitResult* r_ml_wgt_corr = p2.fitTo(wdata,Save(),SumW2Error(kTRUE)) ;



  // P l o t   w e i g h e d   d a t a   a n d   f i t   r e s u l t 
  // ---------------------------------------------------------------

  // Construct plot frame
  RooPlot* frame = x.frame(Title("Unbinned ML fit, binned chi^2 fit to weighted data")) ;

  // Plot data using sum-of-weights-squared error rather than Poisson errors
  wdata.plotOn(frame,DataError(RooAbsData::SumW2)) ;

  // Overlay result of 2nd order polynomial fit to weighted data
  p2.plotOn(frame) ;



  // M L  F i t   o f   p d f   t o   e q u i v a l e n t  u n w e i g h t e d   d a t a s e t
  // -----------------------------------------------------------------------------------------
  
  // Construct a pdf with the same shape as p0 after weighting
  RooGenericPdf genPdf("genPdf","x*x+10",x) ;

  // Sample a dataset with the same number of events as data
  RooDataSet* data2 = genPdf.generate(x,1000) ;

  // Sample a dataset with the same number of weights as data
  RooDataSet* data3 = genPdf.generate(x,43000) ;

  // Fit the 2nd order polynomial to both unweighted datasets and save the results for comparison
  RooFitResult* r_ml_unw10 = p2.fitTo(*data2,Save()) ;
  RooFitResult* r_ml_unw43 = p2.fitTo(*data3,Save()) ;


  // C h i 2   f i t   o f   p d f   t o   b i n n e d   w e i g h t e d   d a t a s e t
  // ------------------------------------------------------------------------------------

  // Construct binned clone of unbinned weighted dataset
  RooDataHist* binnedData = wdata.binnedClone() ;
  binnedData->Print("v") ;

  // Perform chi2 fit to binned weighted dataset using sum-of-weights errors
  // 
  // NB: Within the usual approximations of a chi2 fit, a chi2 fit to weighted
  // data using sum-of-weights-squared errors does give correct error
  // estimates
  RooChi2Var chi2("chi2","chi2",p2,*binnedData,DataError(RooAbsData::SumW2)) ;
  RooMinuit m(chi2) ;
  m.migrad() ;
  m.hesse() ;

  // Plot chi^2 fit result on frame as well
  RooFitResult* r_chi2_wgt = m.save() ;
  p2.plotOn(frame,LineStyle(kDashed),LineColor(kRed)) ;



  // C o m p a r e   f i t   r e s u l t s   o f   c h i 2 , M L   f i t s   t o   ( u n ) w e i g h t e d   d a t a 
  // ---------------------------------------------------------------------------------------------------------------

  // Note that ML fit on 1Kevt of weighted data is closer to result of ML fit on 43Kevt of unweighted data 
  // than to 1Kevt of unweighted data, whereas the reference chi^2 fit with SumW2 error gives a result closer to
  // that of an unbinned ML fit to 1Kevt of unweighted data. 

  cout << "==> ML Fit results on 1K unweighted events" << endl ;
  r_ml_unw10->Print() ;
  cout << "==> ML Fit results on 43K unweighted events" << endl ;
  r_ml_unw43->Print() ;
  cout << "==> ML Fit results on 1K weighted events with a summed weight of 43K" << endl ;
  r_ml_wgt->Print() ;
  cout << "==> Corrected ML Fit results on 1K weighted events with a summed weight of 43K" << endl ;
  r_ml_wgt_corr->Print() ;
  cout << "==> Chi2 Fit results on 1K weighted events with a summed weight of 43K" << endl ;
  r_chi2_wgt->Print() ;


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


}
示例#30
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];        
    }
}