Ejemplo n.º 1
0
// based on rf801_mcstudy
void rooFitValid()
{
  // C r e a t e   m o d e l
  // -----------------------

    // some config
    
	const double valLo(5.22), valHi(6.045);


  // Declare observable x
        RooRealVar mass("mlb", "J/#psi #Lambda mass [GeV/c^{2}]", valLo, valHi);
	//	mass.setBins(33);

        //   mass fit
        double m=5.62354;
	double m_sig=0.00360244;
        double sg=0.0215277;
	double sg_sig=0.0031824;
	double ns=71.2533;
	double ns_sig=10.8354;
	double nb=255.756;
        double nb_sig=17.3733;
        double cc=-0.335304;
        double cc_sig=0.109179;
	double n_std = 3.0;
        RooRealVar mean("mean","mean",m,5.60,5.64);
        RooRealVar sigma("sigma","sigma",sg,0.01,0.03);
        RooGaussian sig("sig","signal p.d.f.",mass,mean,sigma) ;

        RooRealVar c0("c0","coefficient #0", cc,cc-n_std*cc_sig,cc+n_std*cc_sig) ;
        RooChebychev bkg("bkg","background p.d.f.",mass,RooArgSet(c0)) ;

        RooRealVar nsig("nsig","n_{sig}", ns, ns-n_std*ns_sig, ns+n_std*ns_sig);
        RooRealVar nbkg("nbkg","n_{bg}", nb, nb-n_std*nb_sig, nb+n_std*nb_sig);

        RooAddPdf model("model","model",RooArgList(sig,bkg),RooArgList(nsig,nbkg)) ;



  // C r e a t e   m a n a g e r
  // ---------------------------

  // Instantiate RooMCStudy manager on model with x as observable and given choice of fit options
  //
  // The Silence() option kills all messages below the PROGRESS level, leaving only a single message
  // per sample executed, and any error message that occur during fitting
  //
  // The Extended() option has two effects: 
  //    1) The extended ML term is included in the likelihood and 
  //    2) A poisson fluctuation is introduced on the number of generated events 
  //
  // The FitOptions() given here are passed to the fitting stage of each toy experiment.
  // If Save() is specified, the fit result of each experiment is saved by the manager  
  //
  // A Binned() option is added in this example to bin the data between generation and fitting
  // to speed up the study at the expemse of some precision

  RooMCStudy* mcstudy = new RooMCStudy(model,mass,Binned(kFALSE),Silence(), Extended(),
				       FitOptions(Save(kTRUE),PrintEvalErrors(0))) ;
  

  // G e n e r a t e   a n d   f i t   e v e n t s
  // ---------------------------------------------

  // Generate and fit 1000 samples of Poisson(nExpected) events
  mcstudy->generateAndFit(1000) ;


  // E x p l o r e   r e s u l t s   o f   s t u d y 
  // ------------------------------------------------

  setTDRStyle();
  // Make plots of the distributions of mean, the error on mean and the pull of mean
  RooPlot* frame1 = mcstudy->plotPull(nsig, FrameRange(-3.0,3.0),Bins(40),FitGauss(kTRUE)) ;
  RooPlot* frame2 = mcstudy->plotPull(nbkg, FrameRange(-3.0,3.0),Bins(40),FitGauss(kTRUE)) ;
  RooPlot* frame3 = mcstudy->plotPull(mean, FrameRange(-3.0,3.0),Bins(40),FitGauss(kTRUE)) ;
  RooPlot* frame4 = mcstudy->plotPull(sigma, FrameRange(-3.0,3.0),Bins(40),FitGauss(kTRUE)) ;

  RooPlot* frame5 = mcstudy->plotParam(nsig,Bins(40)) ;
  RooPlot* frame6 = mcstudy->plotParam(nbkg,Bins(40)) ;
  RooPlot* frame7 = mcstudy->plotParam(mean,Bins(40));
  RooPlot* frame8 = mcstudy->plotParam(sigma,Bins(40));
  RooPlot* frame9 = mcstudy->plotParam(c0,Bins(40));

  // Plot distribution of minimized likelihood
  RooPlot* frame10 = mcstudy->plotNLL(Bins(40)) ;



  // Draw all plots on a canvas
  gStyle->SetPalette(1) ;
  gStyle->SetOptStat(0) ;
  TCanvas* c = new TCanvas("rooFitPulls","rooFitPulls",900,900) ;
  c->Divide(2,2) ;
  c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->SetTitle(""); frame1->Draw() ;
  c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->SetTitle(""); frame2->Draw() ;
  c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->GetYaxis()->SetTitleOffset(1.4) ; frame3->SetTitle(""); frame3->Draw() ;
  c->cd(4) ; gPad->SetLeftMargin(0.15) ; frame4->GetYaxis()->SetTitleOffset(1.4) ; frame4->SetTitle(""); frame4->Draw() ;

  TCanvas* c2 = new TCanvas("rooFitValid","rooFitValid",900,900) ;
  c2->Divide(3,2) ;
  c2->cd(1) ; gPad->SetLeftMargin(0.15) ; frame5->GetYaxis()->SetTitleOffset(1.4) ;frame5->SetTitle(""); frame5->Draw() ;
  c2->cd(2) ; gPad->SetLeftMargin(0.15) ; frame6->GetYaxis()->SetTitleOffset(1.4) ;frame6->SetTitle(""); frame6->Draw() ;
  c2->cd(3) ; gPad->SetLeftMargin(0.15) ; frame7->GetYaxis()->SetTitleOffset(1.4) ;frame7->SetTitle(""); frame7->Draw() ;
  c2->cd(4) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ;frame8->SetTitle(""); frame8->Draw() ;
  c2->cd(5) ; gPad->SetLeftMargin(0.15) ; frame9->GetYaxis()->SetTitleOffset(1.4) ;frame9->SetTitle(""); frame9->Draw() ;
  c2->cd(6) ; gPad->SetLeftMargin(0.15) ; frame10->GetYaxis()->SetTitleOffset(1.4) ;frame10->SetTitle(""); frame10->Draw() ;



  // Make RooMCStudy object available on command line after
  // macro finishes
  gDirectory->Add(mcstudy) ;
}
Ejemplo n.º 2
0
void rf803_mcstudy_addons2()
{
   // C r e a t e   m o d e l 
   // -----------------------

   // Simulation of signal and background of top quark decaying into
   // 3 jets with background

   // Observable
   RooRealVar mjjj("mjjj","m(3jet) (GeV)",100,85.,350.) ;

   // Signal component (Gaussian)
   RooRealVar mtop("mtop","m(top)",162) ;
   RooRealVar wtop("wtop","m(top) resolution",15.2) ;
   RooGaussian sig("sig","top signal",mjjj,mtop,wtop) ;

   // Background component (Chebychev)
   RooRealVar c0("c0","Chebychev coefficient 0",-0.846,-1.,1.) ;
   RooRealVar c1("c1","Chebychev coefficient 1", 0.112,-1.,1.) ;
   RooRealVar c2("c2","Chebychev coefficient 2", 0.076,-1.,1.) ;
   RooChebychev bkg("bkg","combinatorial background",mjjj,RooArgList(c0,c1,c2)) ;

   // Composite model
   RooRealVar nsig("nsig","number of signal events",53,0,1e3) ;
   RooRealVar nbkg("nbkg","number of background events",103,0,5e3) ;
   RooAddPdf model("model","model",RooArgList(sig,bkg),RooArgList(nsig,nbkg)) ;



   // C r e a t e   m a n a g e r
   // ---------------------------

   // Configure manager to perform binned extended likelihood fits (Binned(),Extended()) on data generated
   // with a Poisson fluctuation on Nobs (Extended())
   RooMCStudy* mcs = new RooMCStudy(model,mjjj,Binned(),Silence(),Extended(kTRUE),
                  FitOptions(Extended(kTRUE),PrintEvalErrors(-1))) ;



   // C u s t o m i z e   m a n a g e r
   // ---------------------------------

   // Add module that randomizes the summed value of nsig+nbkg 
   // sampling from a uniform distribution between 0 and 1000
   //
   // In general one can randomize a single parameter, or a 
   // sum of N parameters, using either a uniform or a Gaussian
   // distribution. Multiple randomization can be executed
   // by a single randomizer module
   
   RooRandomizeParamMCSModule randModule ;
   randModule.sampleSumUniform(RooArgSet(nsig,nbkg),50,500) ;
   mcs->addModule(randModule) ;  


   // Add profile likelihood calculation of significance. Redo each
   // fit while keeping parameter nsig fixed to zero. For each toy,
   // the difference in -log(L) of both fits is stored, as well
   // a simple significance interpretation of the delta(-logL)
   // using Dnll = 0.5 sigma^2

   RooDLLSignificanceMCSModule sigModule(nsig,0) ;
   mcs->addModule(sigModule) ;



   // R u n   m a n a g e r ,   m a k e   p l o t s
   // ---------------------------------------------

   // Run 1000 experiments. This configuration will generate a fair number
   // of (harmless) MINUIT warnings due to the instability of the Chebychev polynomial fit
   // at low statistics.
   mcs->generateAndFit(500) ;

   // Make some plots
   TH1* dll_vs_ngen = mcs->fitParDataSet().createHistogram("ngen,dll_nullhypo_nsig",-40,-40) ;
   TH1* z_vs_ngen = mcs->fitParDataSet().createHistogram("ngen,significance_nullhypo_nsig",-40,-40) ;
   TH1* errnsig_vs_ngen = mcs->fitParDataSet().createHistogram("ngen,nsigerr",-40,-40) ;
   TH1* errnsig_vs_nsig = mcs->fitParDataSet().createHistogram("nsig,nsigerr",-40,-40) ;


   // Draw plots on canvas
   TCanvas* c = new TCanvas("rf803_mcstudy_addons2","rf802_mcstudy_addons2",800,800) ;
   c->Divide(2,2) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; dll_vs_ngen->GetYaxis()->SetTitleOffset(1.6) ; dll_vs_ngen->Draw("box") ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; z_vs_ngen->GetYaxis()->SetTitleOffset(1.6) ; z_vs_ngen->Draw("box") ;
   c->cd(3) ; gPad->SetLeftMargin(0.15) ; errnsig_vs_ngen->GetYaxis()->SetTitleOffset(1.6) ; errnsig_vs_ngen->Draw("box") ;
   c->cd(4) ; gPad->SetLeftMargin(0.15) ; errnsig_vs_nsig->GetYaxis()->SetTitleOffset(1.6) ; errnsig_vs_nsig->Draw("box") ;

   
   // Make RooMCStudy object available on command line after
   // macro finishes
   gDirectory->Add(mcs) ;

}
Ejemplo n.º 3
0
void rf802_mcstudy_addons()
{

   // C r e a t e   m o d e l 
   // -----------------------

   // Observables, parameters
   RooRealVar x("x","x",-10,10) ;
   x.setBins(10) ;
   RooRealVar mean("mean","mean of gaussian",0) ;
   RooRealVar sigma("sigma","width of gaussian",5,1,10) ;

   // Create Gaussian pdf
   RooGaussian gauss("gauss","gaussian PDF",x,mean,sigma) ;  



   // C r e a t e   m a n a g e r  w i t h   c h i ^ 2   a d d - o n   m o d u l e
   // ----------------------------------------------------------------------------

   // Create study manager for binned likelihood fits of a Gaussian pdf in 10 bins
   RooMCStudy* mcs = new RooMCStudy(gauss,x,Silence(),Binned()) ;

   // Add chi^2 calculator module to mcs
   RooChi2MCSModule chi2mod ;
   mcs->addModule(chi2mod) ;

   // Generate 1000 samples of 1000 events
   mcs->generateAndFit(2000,1000) ;
   
   // Fill histograms with distributions chi2 and prob(chi2,ndf) that
   // are calculated by RooChiMCSModule
   TH1* hist_chi2 = mcs->fitParDataSet().createHistogram("chi2") ; 
   TH1* hist_prob = mcs->fitParDataSet().createHistogram("prob") ;   



   // C r e a t e   m a n a g e r  w i t h   s e p a r a t e   f i t   m o d e l 
   // ----------------------------------------------------------------------------

   // Create alternate pdf with shifted mean
   RooRealVar mean2("mean2","mean of gaussian 2",0.5) ;
   RooGaussian gauss2("gauss2","gaussian PDF2",x,mean2,sigma) ;  

   // Create study manager with separate generation and fit model. This configuration
   // is set up to generate bad fits as the fit and generator model have different means
   // and the mean parameter is not floating in the fit
   RooMCStudy* mcs2 = new RooMCStudy(gauss2,x,FitModel(gauss),Silence(),Binned()) ;

   // Add chi^2 calculator module to mcs
   RooChi2MCSModule chi2mod2 ;
   mcs2->addModule(chi2mod2) ;

   // Generate 1000 samples of 1000 events
   mcs2->generateAndFit(2000,1000) ;
   
   // Fill histograms with distributions chi2 and prob(chi2,ndf) that
   // are calculated by RooChiMCSModule
   TH1* hist2_chi2 = mcs2->fitParDataSet().createHistogram("chi2") ; 
   TH1* hist2_prob = mcs2->fitParDataSet().createHistogram("prob") ;   
   hist2_chi2->SetLineColor(kRed) ;
   hist2_prob->SetLineColor(kRed) ;

   

   TCanvas* c = new TCanvas("rf802_mcstudy_addons","rf802_mcstudy_addons",800,400) ;
   c->Divide(2) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; hist_chi2->GetYaxis()->SetTitleOffset(1.4) ; hist_chi2->Draw() ; hist2_chi2->Draw("esame") ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; hist_prob->GetYaxis()->SetTitleOffset(1.4) ; hist_prob->Draw() ; hist2_prob->Draw("esame") ;


   
   // Make RooMCStudy object available on command line after
   // macro finishes
   gDirectory->Add(mcs) ;
}
Ejemplo n.º 4
0
void fitM3()
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// add all three single top samples

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	//return;//debuging

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

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

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

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

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

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

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

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

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

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

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

	
	cout << "N failed fits = " << Nfailed << endl;
	
	cvf->cd();
	hNgen->Draw();
	
	// Make RooMCStudy object available on command line after
	// macro finishes
	//gDirectory->Add(mcstudy) ;
}
void addNuisanceWithToys(std::string iFileName,std::string iChannel,std::string iBkg,std::string iEnergy,std::string iName,std::string iDir,bool iRebin=true,bool iVarBin=false,int iFitModel=1,int iFitModel1=1,double iFirst=150,double iLast=1500,std::string iSigMass="800",double iSigScale=0.1,int iNToys=1000) { 
  std::cout << "======> " << iDir << "/" << iBkg << " -- " << iFileName << std::endl;  
  if(iVarBin) std::cout << "option not implemented yet!";
  if(iVarBin) return;
  //double lFirst = 200;
  //double lLast  = 1500;
  double lFirst = iFirst;
  double lLast  = iLast;

  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "Using Initial fit model: " << iFitModel << ", fitting range: " << iFirst << "-" << iLast << " , using alternative fit model: " << iFitModel1 << std::endl; 
  std::cout << "===================================================================================================================================================" <<std::endl;

  TFile *lFile = new TFile(iFileName.c_str());
  TH1F  *lH0   = (TH1F*) lFile->Get((iDir+"/"+iBkg).c_str());
  TH1F  *lData = (TH1F*) lFile->Get((iDir+"/data_obs").c_str());
  TH1F  *lSig = 0;

  // for now, use bbH signal for testing in b-tag and ggH in no-btag
  if(iDir.find("_btag") != std::string::npos) lSig = (TH1F*)lFile->Get((iDir+"/bbH"+iSigMass+"_fine_binning").c_str());
  else lSig = (TH1F*)lFile->Get((iDir+"/ggH"+iSigMass+"_fine_binning").c_str());

  TH1F *lH0Clone = (TH1F*)lH0->Clone("lH0Clone");     // binning too fine as of now? start by rebinning
  TH1F *lDataClone = (TH1F*)lData->Clone("lDataClone");   
  TH1F *lSigClone = (TH1F*)lSig->Clone("lSigClone");  
 // lH0Clone->Rebin(2);
 // lDataClone->Rebin(2);
 // lSigClone->Rebin(2);

  lSig->Rebin(10);  

  //Define the fit function
  RooRealVar lM("m","m" ,0,5000);
  lM.setRange(lFirst,lLast);
  RooRealVar lA("a","a" ,50,  0.1,200);
  RooRealVar lB("b","b" ,0.0 , -10.5,10.5);
  RooRealVar lA1("a1","a1" ,50,  0.1,1000);
  RooRealVar lB1("b1","b1" ,0.0 , -10.5,10.5);

  RooDataHist *pH0  =  new RooDataHist("Data","Data" ,RooArgList(lM),lH0);
  double lNB0 = lH0->Integral(lH0->FindBin(lFirst),lH0->FindBin(lLast));
  double lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast));
 //lNB0=500;
// lNSig0=500;
 lSig->Scale(iSigScale*lNB0/lNSig0);                                         // scale signal to iSigScale*(Background yield), could try other options
 lNSig0 = lSig->Integral(lSig->FindBin(lFirst),lSig->FindBin(lLast));        // readjust norm of signal hist   
  
  //Generate the "default" fit model 

  RooGenericPdf *lFit  = 0; lFit = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFit = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) {lA.setVal(0.3); lB.setVal(0.5);}
  if(iFitModel == 2) lFit = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 2) {lA.setVal(0.01); lA.setRange(0,10); }
  if(iFitModel == 3) lFit = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));
 
  // Generate the alternative model
  
  RooGenericPdf *lFit1  = 0; lFit1 = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) lFit1 = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) {lA1.setVal(0.3); lB1.setVal(0.5);}
  if(iFitModel1 == 2) lFit1 = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 2) {lA1.setVal(0.01); lA1.setRange(0,10); }
  if(iFitModel1 == 3) lFit1 = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1));
  
  //=============================================================================================================================================
  //Perform the tail fit and generate the shift up and down histograms
  //=============================================================================================================================================

  RooFitResult  *lRFit = 0;
  lRFit = lFit->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(lFirst,lLast),RooFit::Strategy(0)); 
  TMatrixDSym lCovMatrix   = lRFit->covarianceMatrix(); 
  TMatrixD  lEigVecs(2,2);    lEigVecs = TMatrixDSymEigen(lCovMatrix).GetEigenVectors();
  TVectorD  lEigVals(2);      lEigVals = TMatrixDSymEigen(lCovMatrix).GetEigenValues();
  cout << " Ve---> " << lEigVecs(0,0) << " -- " << lEigVecs(1,0) << " -- " << lEigVecs(0,1) << " -- " << lEigVecs(1,1) << endl;
  cout << " Co---> " << lCovMatrix(0,0) << " -- " << lCovMatrix(1,0) << " -- " << lCovMatrix(0,1) << " -- " << lCovMatrix(1,1) << endl;
  double lACentral = lA.getVal();
  double lBCentral = lB.getVal();
  lEigVals(0) = sqrt(lEigVals(0));
  lEigVals(1) = sqrt(lEigVals(1));
  cout << "===> " << lEigVals(0) << " -- " << lEigVals(1) << endl;
  
  TH1F* lH     = (TH1F*) lFit->createHistogram("fit" ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral + lEigVals(0)*lEigVecs(1,0));
  TH1F* lHUp   = (TH1F*) lFit->createHistogram("Up"  ,lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral - lEigVals(0)*lEigVecs(0,0));
  lB.setVal(lBCentral - lEigVals(0)*lEigVecs(1,0));
  TH1F* lHDown = (TH1F*) lFit->createHistogram("Down",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral + lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral + lEigVals(1)*lEigVecs(1,1));
  TH1F* lHUp1   = (TH1F*) lFit->createHistogram("Up1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  lA.setVal(lACentral - lEigVals(1)*lEigVecs(0,1));
  lB.setVal(lBCentral - lEigVals(1)*lEigVecs(1,1));
  TH1F* lHDown1 = (TH1F*) lFit->createHistogram("Down1",lM,RooFit::Binning(lH0->GetNbinsX(),lH0->GetXaxis()->GetXmin(),lH0->GetXaxis()->GetXmax()));

  std::string lNuisance1 =  iBkg+"_"+"CMS_"+iName+"1_" + iChannel + "_" + iEnergy;
  std::string lNuisance2 =  iBkg+"_"+"CMS_"+iName+"2_" + iChannel + "_" + iEnergy;
  lHUp    = merge(lNuisance1 + "Up"   ,lFirst,lH0,lHUp);
  lHDown  = merge(lNuisance1 + "Down" ,lFirst,lH0,lHDown);
  lHUp1   = merge(lNuisance2 + "Up"   ,lFirst,lH0,lHUp1);
  lHDown1 = merge(lNuisance2 + "Down" ,lFirst,lH0,lHDown1);
  lH      = merge(lH0->GetName()      ,lFirst,lH0,lH);

  //=============================================================================================================================================
  //=============================================================================================================================================
  
  //Set the variables A and B to the final central values from the tail fit

  lA.setVal(lACentral);
  lB.setVal(lBCentral);
 // lA.removeRange();
 // lB.removeRange();
 
  //Generate the background pdf corresponding to the final result of the tail fit
 
 RooGenericPdf *lFitFinal  = 0; lFitFinal = new RooGenericPdf("genPdf","exp(-m/(a+b*m))",RooArgList(lM,lA,lB));
  if(iFitModel == 1) lFitFinal = new RooGenericPdf("genPdf","exp(-a*pow(m,b))",RooArgList(lM,lA,lB));
  if(iFitModel == 2) lFitFinal = new RooGenericPdf("genPdf","a*exp(b*m)",RooArgList(lM,lA,lB));
  if(iFitModel == 3) lFitFinal = new RooGenericPdf("genPdf","a/pow(m,b)",RooArgList(lM,lA,lB));



  //=============================================================================================================================================
  //Perform the tail fit with the alternative fit function (once initially, before allowing tail fit to float in toy fit).
  //=============================================================================================================================================

  RooFitResult  *lRFit1 = 0;
 //lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(iFirst,iLast),RooFit::Strategy(0));  
 lRFit1=lFit1->fitTo(*pH0,RooFit::Save(kTRUE),RooFit::Range(200,1500),RooFit::Strategy(0));  
  
  //Generate the background pdf corresponding to the result of the alternative tail fit

  RooGenericPdf *lFit1Final  = 0; lFit1Final = new RooGenericPdf("genPdf","exp(-m/(a1+b1*m))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 1) lFit1Final = new RooGenericPdf("genPdf","exp(-a1*pow(m,b1))",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 2) lFit1Final = new RooGenericPdf("genPdf","a1*exp(b1*m)",RooArgList(lM,lA1,lB1));
  if(iFitModel1 == 3) lFit1Final = new RooGenericPdf("genPdf","a1/pow(m,b1)",RooArgList(lM,lA1,lB1));

 // lA1.removeRange();
 // lB1.removeRange();
  
  //=============================================================================================================================================

  //Define RooRealVar for the normalization of the signal and background, starting from the initial integral of the input histograms

  lM.setRange(300,1500);  

  RooRealVar lNB("nb","nb",lNB0,0,10000);
  RooRealVar lNSig("nsig","nsig",lNSig0,-1000,1000);

  //Define a PDF for the signal histogram lSig
  
  RooDataHist  *pS      = new RooDataHist("sigH","sigH",RooArgList(lM),lSig);
  RooHistPdf   *lSPdf   = new RooHistPdf ("sigPdf","sigPdf",lM,*pS);
 
  //Define generator and fit functions for the RooMCStudy

  RooAddPdf    *lGenMod = new RooAddPdf  ("genmod","genmod",RooArgList(*lFitFinal ,*lSPdf),RooArgList(lNB,lNSig));
  RooAddPdf    *lFitMod = new RooAddPdf  ("fitmod","fitmod",RooArgList(*lFit1Final,*lSPdf),RooArgList(lNB,lNSig));

  //Generate plot of the signal and background models going into the toy generation   

  RooPlot* plot=lM.frame();
  lGenMod->plotOn(plot);
  lGenMod->plotOn(plot,RooFit::Components(*lSPdf),RooFit::LineColor(2));
  TCanvas* lC11 = new TCanvas("pdf","pdf",600,600) ;
  lC11->cd();
  plot->Draw();
  lC11->SaveAs(("SBModel_"+iBkg+"_" + iDir + "_" + iEnergy+".pdf").c_str());

  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "FIT PARAMETERS BEFORE ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl;  
  std::cout << "===================================================================================================================================================" <<std::endl;


  RooMCStudy   *lToy    = new RooMCStudy(*lGenMod,lM,RooFit::FitModel(*lFitMod),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(kTRUE),RooFit::Verbose(kTRUE),RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::Strategy(0)));

  // Generate and fit iNToys toy samples
  
  std::cout << "Number of background events: " << lNB0 << " Number of signal events: " << lNSig0 << " Sum: " << lNB0+lNSig0 << std::endl;
  
  //=============================================================================================================================================
  // Generate and fit toys
  //============================================================================================================================================= 
    
  lToy->generateAndFit(iNToys,lNB0+lNSig0,kTRUE);
 
  std::cout << "===================================================================================================================================================" <<std::endl;
  std::cout << "FIT PARAMETERS AFTER ROOMCSTUDY: lA: " << lA.getVal() << " lB: " << lB.getVal() << " lA1: " << lA1.getVal() << " lB1: " << lB1.getVal() << std::endl;  
  std::cout << "===================================================================================================================================================" <<std::endl;
  

  //=============================================================================================================================================
  // Generate plots relevant to the toy fit
  //=============================================================================================================================================

  RooPlot* lFrame1 = lToy->plotPull(lNSig,-5,5,100,kTRUE);
  lFrame1->SetTitle("distribution of pulls on signal yield from toys");
  lFrame1->SetXTitle("N_{sig} pull");
  
  TCanvas* lC00 = new TCanvas("pulls","pulls",600,600) ;
  lC00->cd();
  lFrame1->GetYaxis()->SetTitleOffset(1.2); 
  lFrame1->GetXaxis()->SetTitleOffset(1.0); 
  lFrame1->Draw() ;
  lC00->SaveAs(("sig_pulls_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame2 = lToy->plotParam(lA1);
  lFrame2->SetTitle("distribution of values of parameter 1 (a) after toy fit");
  lFrame2->SetXTitle("Parameter 1 (a)");
  TCanvas* lC01 = new TCanvas("valA","valA",600,600) ;
  lFrame2->Draw() ;
  lC01->SaveAs(("valA_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame3 = lToy->plotParam(lB1);
  lFrame3->SetTitle("distribution of values of parameter 2 (b) after toy fit");
  lFrame3->SetXTitle("Parameter 2 (b)");
  TCanvas* lC02 = new TCanvas("valB","valB",600,600) ;
  lFrame3->Draw() ;
  lC02->SaveAs(("valB_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
  
  RooPlot* lFrame6 = lToy->plotNLL(0,1000,100);
  lFrame6->SetTitle("-log(L)");
  lFrame6->SetXTitle("-log(L)");
  TCanvas* lC05 = new TCanvas("logl","logl",600,600) ;
  lFrame6->Draw() ;
  lC05->SaveAs(("logL_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());

  RooPlot* lFrame7 = lToy->plotParam(lNSig);
  lFrame7->SetTitle("distribution of values of N_{sig} after toy fit");
  lFrame7->SetXTitle("N_{sig}");
  TCanvas* lC06 = new TCanvas("Nsig","Nsig",600,600) ;
  lFrame7->Draw() ;
  lC06->SaveAs(("NSig_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
  
  RooPlot* lFrame8 = lToy->plotParam(lNB);
  lFrame8->SetTitle("distribution of values of N_{bkg} after toy fit");
  lFrame8->SetXTitle("N_{bkg}");
  TCanvas* lC07 = new TCanvas("Nbkg","Nbkg",600,600) ;
  lFrame8->Draw() ;
  lC07->SaveAs(("Nbkg_toyfits_"+iBkg+"_" + iDir + "_" + iEnergy+".png").c_str());
 

  if(iRebin) { 
    const int lNBins = lData->GetNbinsX();
    double *lAxis    = getAxis(lData);
    lH0     = rebin(lH0    ,lNBins,lAxis);
    lH      = rebin(lH     ,lNBins,lAxis);
    lHUp    = rebin(lHUp   ,lNBins,lAxis);
    lHDown  = rebin(lHDown ,lNBins,lAxis);
    lHUp1   = rebin(lHUp1  ,lNBins,lAxis);
    lHDown1 = rebin(lHDown1,lNBins,lAxis);
  }

  // we dont need this bin errors since we do not use them (fit tails replaces bin-by-bin error!), therefore i set all errors to 0, this also saves us from modifying the add_bbb_error.py script in which I otherwise would have to include a option for adding bbb only in specific ranges
  int lMergeBin = lH->GetXaxis()->FindBin(iFirst);
  for(int i0 = lMergeBin; i0 < lH->GetNbinsX()+1; i0++){
    lH->SetBinError  (i0,0);
    lHUp->SetBinError  (i0,0);
    lHDown->SetBinError  (i0,0);
    lHUp1->SetBinError  (i0,0);
    lHDown1->SetBinError  (i0,0);
  }


  TFile *lOutFile =new TFile("Output.root","RECREATE");
  cloneFile(lOutFile,lFile,iDir+"/"+iBkg);
  lOutFile->cd(iDir.c_str());
  lH     ->Write();
  lHUp   ->Write(); 
  lHDown ->Write(); 
  lHUp1  ->Write(); 
  lHDown1->Write(); 

  // Debug Plots
  lH0->SetStats(0);
  lH->SetStats(0);
  lHUp->SetStats(0);
  lHDown->SetStats(0);
  lHUp1->SetStats(0);
  lHDown1->SetStats(0);
  lH0    ->SetLineWidth(1); lH0->SetMarkerStyle(kFullCircle);
  lH     ->SetLineColor(kGreen);
  lHUp   ->SetLineColor(kRed);
  lHDown ->SetLineColor(kRed);
  lHUp1  ->SetLineColor(kBlue);
  lHDown1->SetLineColor(kBlue);
  TCanvas *lC0 = new TCanvas("Can","Can",800,600);
  lC0->Divide(1,2); lC0->cd();  lC0->cd(1)->SetPad(0,0.2,1.0,1.0); gPad->SetLeftMargin(0.2) ; 
  lH0->Draw();
  lH     ->Draw("hist sames");
  lHUp   ->Draw("hist sames");
  lHDown ->Draw("hist sames");
  lHUp1  ->Draw("hist sames");
  lHDown1->Draw("hist sames");
  gPad->SetLogy();
  
  TLegend* leg1;
  /// setup the CMS Preliminary
  leg1 = new TLegend(0.7, 0.80, 1, 1); 
  leg1->SetBorderSize( 0 );
  leg1->SetFillStyle ( 1001 );
  leg1->SetFillColor (kWhite);
  leg1->AddEntry( lH0 , "orignal",  "PL" );
  leg1->AddEntry( lH , "cental fit",  "L" );
  leg1->AddEntry( lHUp , "shift1 up",  "L" );
  leg1->AddEntry( lHDown , "shift1 down",  "L" );
  leg1->AddEntry( lHUp1 , "shift2 up",  "L" );
  leg1->AddEntry( lHDown1 , "shift2 down",  "L" );
  leg1->Draw("same");


  lC0->cd(2)->SetPad(0,0,1.0,0.2); gPad->SetLeftMargin(0.2) ;
  drawDifference(lH0,lH,lHUp,lHDown,lHUp1,lHDown1);
  lH0->SetStats(0);
  lC0->Update();
  lC0->SaveAs((iBkg+"_"+"CMS_"+iName+"1_" + iDir + "_" + iEnergy+".png").c_str());
  //lFile->Close();
  return;
}