コード例 #1
0
void Process(TString fname, TString myRooWS, int toMass, int fromMass, int Bin)
{

  gROOT->SetStyle("Plain");
  TFile * file = new TFile(fname.Data(), "READ");
  std::cout << "reading " << fname.Data() << std::endl;
  TString outname("newcards/");
  outname.Append(massS[toMass]);
  outname.Append("/");
  fname.ReplaceAll("110","");
  fname.ReplaceAll("115","");
  fname.ReplaceAll("120","");
  fname.ReplaceAll("125","");
  fname.ReplaceAll("130","");
  fname.ReplaceAll("135","");
  fname.ReplaceAll("140","");
  fname.ReplaceAll("145","");
  fname.ReplaceAll("150","");
  fname.ReplaceAll("/","");

  if(fname.Contains("Zn") && (Bin == 0)) fname.ReplaceAll(".root","Low.root");
  if(fname.Contains("Zn") && (Bin == 1)) fname.ReplaceAll(".root","Med.root");
  if(fname.Contains("Zn") && (Bin == 2)) fname.ReplaceAll(".root","High.root");
  
  outname.Append(fname.Data());
  outname.ReplaceAll("Wtn_BDT_newBinning_","vhbb_Wtn_8TeV");
  outname.ReplaceAll("WS_BDT_H_","");
  outname.ReplaceAll("WS_BDT_M_","");
  std::cout << "FILENAME: " << outname.Data() <<std::endl;

  TFile * outfile = new TFile(outname.Data(), "RECREATE");

  using namespace RooFit;
  RooWorkspace *myWS = new RooWorkspace(myRooWS.Data(),myRooWS.Data());

  if(fname.Contains ("Zmm") | fname.Contains ("Zee") )  {myWS->factory("CMS_vhbb_BDT_Zll_8TeV[-1.,1.]"); bins = 15;}
  else if(fname.Contains ("Zn") && (Bin == 0))  {myWS->factory("CMS_vhbb_BDT_ZnunuLowPt_8TeV[-1.,1.]"); bins = 24;}
  else if(fname.Contains ("Zn") && (Bin == 1))  {myWS->factory("CMS_vhbb_BDT_ZnunuMedPt_8TeV[-1.,1.]"); bins = 32;}
  else if(fname.Contains ("Zn") && (Bin == 2))  {myWS->factory("CMS_vhbb_BDT_ZnunuHighPt_8TeV[-1.,1.]"); bins = 40;}
  else if(fname.Contains("We") | fname.Contains("Wm")) {myWS->factory("CMS_vhbb_BDT_Wln_8TeV[-1.,1.]"); bins = 48;}
  else if(fname.Contains("Wt")) {myWS->factory("BDT[-1.,1.]"); bins = 18;}


  RooWorkspace *tempWS =  (RooWorkspace*) file->Get(myRooWS.Data());
  
  for(int s=0; s<NS; s++ ){
      makeSystPlot(tempWS, myWS,  systs[s], Bin, toMass, fromMass );
    }
  


  myWS->writeToFile(outname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << outname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;
  outfile->Write();
  outfile->Close();


}
コード例 #2
0
ファイル: gen1.C プロジェクト: CMS-HIN-dilepton/DimuonCADIs
void gen1(const char* output, const char* suffix) {
  // S e t u p   m o d e l 
  // ---------------------

   gRandom = new TRandom();
   gRandom->SetSeed(0);
   RooWorkspace *ws = new RooWorkspace("workspace");
  // Declare variables x,mean,sigma with associated name, title, initial value and allowed range
  ws->factory("invMass[2,5]");
  RooRealVar *invMass = ws->var("invMass");
  RooRealVar *weight = new RooRealVar("weight","weight",1,0,1e6);
  ws->factory(Form("Gaussian::siga_nonorm_%s(invMass,m_%s[3,2.5,3.5],sigmaa_%s[0.02,0.,0.5])",suffix,suffix,suffix));
  ws->factory(Form("Gaussian::sigb_nonorm_%s(invMass,m_%s,sigmab_%s[0.1,0.,0.5])",suffix,suffix,suffix));
  ws->factory(Form("SUM::sig_nonorm_%s(f_%s[0.8,0,1]*siga_nonorm_%s,sigb_nonorm_%s)",suffix,suffix,suffix,suffix));
  ws->factory(Form("RooExtendPdf::sig_%s(sig_nonorm_%s,Nsig_%s[1e4,-1e5,1e5])",suffix,suffix,suffix));
  ws->factory(Form("Gaussian::sig2_nonorm_%s(invMass,m2_%s[3.5,3.,4.],sigma2_%s[0.1,0.,0.5])",suffix,suffix,suffix));
  ws->factory(Form("RooFormulaVar::Nsig2_%s('@0*@1',{Nsig_%s,frac_%s[0.5,-10,10]})",suffix,suffix,suffix));
  ws->factory(Form("RooExtendPdf::sig2_%s(sig2_nonorm_%s,Nsig2_%s)",suffix,suffix,suffix));
  ws->factory(Form("Chebychev::bkg_nonorm_%s(invMass,{lambda0_%s[0.1,-1.5,1.5],lambda1_%s[0.1,-1.5,1.5]})",suffix,suffix,suffix));
  ws->factory(Form("RooExtendPdf::bkg_%s(bkg_nonorm_%s,Nbkg_%s[1e4,-1e5,1e5])",suffix,suffix,suffix));
  // ws->factory(Form("SUM::tot_%s( sig_%s,  bkg_%s)",suffix,suffix,suffix));
  // RooAbsPdf *thepdf = ws->pdf(Form("tot_%s",suffix));
  RooAbsPdf *thepdf = new RooAddPdf(Form("tot_%s",suffix), Form("tot_%s",suffix), 
        RooArgList(*ws->pdf(Form("sig_%s",suffix)), *ws->pdf(Form("sig2_%s",suffix)), *ws->pdf(Form("bkg_%s",suffix))));
  ws->import(*thepdf);

  // G e n e r a t e   e v e n t s 
  // -----------------------------

  // Generate a dataset of 1000 events in x from gauss
  RooDataSet* data = thepdf->generate(*invMass,2e4,Name(Form("data_%s",suffix))) ;  
  ws->import(*data);

  ws->writeToFile(output);
}
コード例 #3
0
ファイル: fitZraw.C プロジェクト: janveverka/FWLite
void fitZraw() {

    // Choose the File Name, Title and Output File for Fit
    string file;
    cout << "Enter File Name:"<<endl;
    getline(cin, file);
    string Title;
    cout << "Enter Fit Title"<<endl;
    getline(cin, Title);
    string output;
    cout << "Enter Output File Name"<<endl;
    getline(cin, output);

    // Define Fit Inputs and Call Fit
    char* filename = file.c_str();
    char* FitTitle = Title.c_str();
    char* Outfile = output.c_str();
    double minMass = 60;
    double maxMass = 120;
    double mean_bw = 91.1876;
    double gamma_bw = 2.4952;
    double cutoff_cb = 1.0;
    const char *plotOpt = "NEU";
    const int nbins = 40;
    RooWorkspace *w = makefit(filename, FitTitle, Outfile, minMass,  maxMass,  mean_bw,  gamma_bw,  cutoff_cb,  plotOpt, nbins);
    cout << "Saving file..." << endl << flush;
    w->writeToFile(Form("%s.root", Outfile));
    delete w;
}
コード例 #4
0
void makeDataset( TString fname, TString tname, TString outfname ) {

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

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

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

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

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

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

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

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

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

    tree->GetEntry(ev);

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

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

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

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

  }
  tf->Close();

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

  w->writeToFile(outfname);

}
コード例 #5
0
void Process(TString fname, TString oldFolder, int toMass, int fromMass)
{




  std::string channels[] = {"data_obs", "VH", "TT",  "WjLF", "WjHF", "ZjLF", "ZjHF" , "VV" , "s_Top", "QCD"};
  std::string systs[] = {"eff_b", "fake_b", "res_j", "scale_j" , "stat" };

  kount = 0;  

  gROOT->SetStyle("Plain");
  setTDRStyle();

  TFile * file = new TFile(fname.Data(), "READ");
  std::cout << "reading " << fname.Data() << std::endl;
  TString outname(massS[toMass]);
  outname.Append(".root");
  fname.ReplaceAll(".root",outname.Data());
  TFile * outfile = new TFile(fname.Data(), "RECREATE");

  using namespace RooFit;
  RooWorkspace *myWS = new RooWorkspace(oldFolder.Data(),oldFolder.Data());
  myWS->factory("CMS_vhbb_BDT_Zll[-1.,1.]"); ///NEW VARIABLE NAME HERE 

  
  
  for (int c =0; c<10; c++)
  {
    kount2 = 0;  
    for (int s =0; s<5 ; s++ ){
      makeSystPlot( file, oldFolder, myWS,  channels[c], systs[s], toMass, fromMass );
    }
  }


  



  myWS->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


  outfile->Write();
  outfile->Close();


}
コード例 #6
0
void makeFit( TString inf, TString outf ) {

  TFile *tf = TFile::Open( inf );
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");

  //w->factory( "Gaussian::dst_mass1( Dst_M, dst_mean[2005,2015], dst_sigma1[1,20] )" );
  //w->factory( "Gaussian::dst_mass2( Dst_M, dst_mean, dst_sigma2[3,50] )" );
  //w->factory( "Gaussian::dst_mass3( Dst_M, dst_mean, dst_sigma3[5,200] )" );
  //w->factory( "SUM::dst_mass( dst_f[0.1,1.]*dst_mass1, dst_f2[0.1,1.]*dst_mass2, dst_mass3 )" );
  //w->factory( "SUM::dst_mass_sig( dst_f[0.1,1.]*dst_mass1, dst_f2[0.1,1.]*dst_mass2, dst_mass3 )" );
  w->factory( "Gaussian::dst_mass1( Dst_M, dst_mean[2005,2015], dst_sigma1[1,20] )" );
  w->factory( "CBShape::dst_mass2( Dst_M, dst_mean, dst_sigma2[1,20], dst_alpha[0.1,10.], dst_n1[0.1,10.] )" );
  w->factory( "SUM::dst_mass_sig( dst_f[0.1,1.]*dst_mass1, dst_mass2 )" );
  w->factory( "Bernstein::dst_mass_bkg( Dst_M, {1.,dst_p0[0.,1.]} )" );
  w->factory( "SUM::dst_mass( dst_mass_sy[0,10e8]*dst_mass_sig, dst_mass_by[0,10e2]*dst_mass_bkg )" );

  //w->factory( "Gaussian::d0_mass1( D0_M, d0_mean[1862,1868], d0_sigma1[1,20] )" );
  //w->factory( "Gaussian::d0_mass2( D0_M, d0_mean, d0_sigma2[3,50] )" );
  //w->factory( "Gaussian::d0_mass3( D0_M, d0_mean, d0_sigma3[5,200] )" );
  //w->factory( "SUM::d0_mass( d0_f[0.1,1.]*d0_mass1, d0_f2[0.1,1.]*d0_mass2, d0_mass3 )" );
  //w->factory( "SUM::d0_mass( d0_f[0.1,1.]*d0_mass1, d0_f2[0.1,1.]*d0_mass2, d0_mass3 )" );
  w->factory( "Gaussian::d0_mass1( D0_M, d0_mean[1862,1868], d0_sigma1[1,20] )" );
  w->factory( "CBShape::d0_mass2( D0_M, d0_mean, d0_sigma2[1,20], d0_alpha[0.1,10.], d0_n1[0.1,10.] )" );
  w->factory( "SUM::d0_mass_sig( d0_f[0.1,1.]*d0_mass1, d0_mass2 )" );
  w->factory( "Bernstein::d0_mass_bkg( D0_M, {1.,d0_p0[0.,1.]} )" );
  w->factory( "SUM::d0_mass( d0_mass_sy[0,10e8]*d0_mass_sig, d0_mass_by[0,10e1]*d0_mass_bkg )" );

  w->factory( "d0_tau[0,1000.]" );
  w->factory( "expr::d0_e( '-1/@0', d0_tau)" );
  w->factory( "Exponential::d0_t( D0_LTIME_ps, d0_e )" );

  w->pdf("dst_mass")->fitTo( *w->data("Data") , Range(1960,2060) );
  w->pdf("d0_mass") ->fitTo( *w->data("Data") , Range(1820,1910) );
  w->pdf("d0_t")    ->fitTo( *w->data("Data") , Range(0.25,5.) );

  tf->Close();

  w->writeToFile(outf);


}
コード例 #7
0
void createWorkspace(const std::string &infilename, int nState, bool correctCtau, bool drawRapPt2D, bool drawPtCPM2D){
	gROOT->SetStyle("Plain");
	gStyle->SetTitleBorderSize(0);

	// Set some strings
	const std::string workspacename = "ws_masslifetime",
				treename = "selectedData";

	// Get the tree from the data file
	TFile *f = TFile::Open(infilename.c_str());
	TTree *tree = (TTree*)f->Get(treename.c_str());

	// Set branch addresses in tree to be able to import tree to roofit
	TLorentzVector* jpsi = new TLorentzVector;
	tree->SetBranchAddress("JpsiP",&jpsi);
	double CPMval = 0;
	tree->SetBranchAddress("CPM",&CPMval);
	double massErr = 0;
	tree->SetBranchAddress("JpsiMassErr",&massErr);
	double Vprob = 0;
	tree->SetBranchAddress("JpsiVprob",&Vprob);
	double lifetime = 0;
	tree->SetBranchAddress("Jpsict",&lifetime);
	double lifetimeErr = 0;
	tree->SetBranchAddress("JpsictErr",&lifetimeErr);

	// define variables necessary for J/Psi(Psi(2S)) mass,lifetime fit
	RooRealVar* JpsiMass =
		new RooRealVar("JpsiMass", "M [GeV]", onia::massMin, onia::massMax);
	RooRealVar* JpsiMassErr =
		new RooRealVar("JpsiMassErr", "#delta M [GeV]", 0, 5);
	RooRealVar* JpsiRap =
		new RooRealVar("JpsiRap", "y", -onia::rap, onia::rap);
	RooRealVar* JpsiPt =
		new RooRealVar("JpsiPt", "p_{T} [GeV]", 0. ,100.);
	RooRealVar* JpsiCPM =
		new RooRealVar("JpsiCPM", "N_{ch}", 0. ,100.);		
	RooRealVar* Jpsict =
		new RooRealVar("Jpsict", "lifetime [mm]", -1., 2.5);
	RooRealVar* JpsictErr =
		new RooRealVar("JpsictErr", "Error on lifetime [mm]", 0.0001, 1);
	RooRealVar* JpsiVprob =
		new RooRealVar("JpsiVprob", "", 0.01, 1.);

	// Set bins
	Jpsict->setBins(10000,"cache");
	Jpsict->setBins(100);
	JpsiMass->setBins(100);
	JpsictErr->setBins(100);

	// The list of data variables    
	RooArgList dataVars(*JpsiMass,*JpsiMassErr,*JpsiRap,*JpsiPt,*JpsiCPM,*Jpsict,*JpsictErr,*JpsiVprob);

	// construct dataset to contain events
	RooDataSet* fullData = new RooDataSet("fullData","The Full Data From the Input ROOT Trees",dataVars);

	int entries = tree->GetEntries();
	cout << "entries " << entries << endl;

	// loop through events in tree and save them to dataset
	for (int ientries = 0; ientries < entries; ientries++) {
	
		if (ientries%100000==0) std::cout << "event " << ientries << " of " << entries <<  std::endl;

		tree->GetEntry(ientries);

		double M =jpsi->M();
		double y=jpsi->Rapidity();
		double pt=jpsi->Pt();
		double cpm=CPMval;


		if (M > JpsiMass->getMin() && M < JpsiMass->getMax()
				&& massErr > JpsiMassErr->getMin() && massErr < JpsiMassErr->getMax()
				&& pt > JpsiPt->getMin() && pt < JpsiPt->getMax()
				&& cpm > JpsiCPM->getMin() && cpm < JpsiCPM->getMax()
				&& y > JpsiRap->getMin() && y < JpsiRap->getMax()
				&& lifetime > Jpsict->getMin() && lifetime < Jpsict->getMax()
				&& lifetimeErr > JpsictErr->getMin() && lifetimeErr < JpsictErr->getMax()
				&& Vprob > JpsiVprob->getMin() && Vprob < JpsiVprob->getMax()
			 ){

			JpsiPt      ->setVal(pt); 
			JpsiCPM		->setVal(cpm);
			JpsiRap     ->setVal(y); 
			JpsiMass    ->setVal(M);
			JpsiMassErr ->setVal(massErr);
			JpsiVprob   ->setVal(Vprob);

			//cout<<"before lifetime correction \n"
			//	<<"Jpsict: "<<lifetime<<" JpsictErr: "<<lifetimeErr<<endl;

			if(correctCtau){
				lifetime    = lifetime    * onia::MpsiPDG / M ;
				lifetimeErr = lifetimeErr * onia::MpsiPDG / M ;
				Jpsict    ->setVal(lifetime);
				JpsictErr ->setVal(lifetimeErr);
				//cout<<"MpsiPDG: "<<onia::MpsiPDG<<endl;
				//cout<<"after lifetime correction \n"
				//	<<"Jpsict: "<<lifetime<<" JpsictErr: "<<lifetimeErr<<endl;
			}
			else{
				Jpsict    ->setVal(lifetime);
				JpsictErr ->setVal(lifetimeErr);
			}

			fullData->add(dataVars);
		}
	}//ientries


	//------------------------------------------------------------------------------------------------------------------
	// Define workspace and import datasets

	////Get datasets binned in pT, cpm, and y

		for(int iRap = 1; iRap <= onia::kNbRapForPTBins; iRap++){ 

		Double_t yMin;
		Double_t yMax;
		if(iRap==0){
			yMin = onia::rapForPTRange[0];
			yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		} else{
			yMin = onia::rapForPTRange[iRap-1];
			yMax = onia::rapForPTRange[iRap];
		}

		for(int iPT = 1; iPT <= onia::kNbPTBins[iRap]; iPT++){
			//for(int iPT = 0; iPT <= 0; iPT++)

			Double_t ptMin;
			Double_t ptMax;
			if(iPT==0){
				ptMin = onia::pTRange[iRap][0];
				ptMax = onia::pTRange[iRap][onia::kNbPTBins[0]];
			} else{
				ptMin = onia::pTRange[iRap][iPT-1];
				ptMax = onia::pTRange[iRap][iPT];
			}
			
		  for(int iCPM = 1; iCPM <= onia::NchBins; iCPM++){
		  
		  
	  	    Double_t cpmMin;
			Double_t cpmMax;
			if(iCPM==0){
				cpmMin = onia::cpmRange[0];
				cpmMax = onia::cpmRange[onia::NchBins];
			} else{
				cpmMin = onia::cpmRange[iCPM-1];
				cpmMax = onia::cpmRange[iCPM];
			}

			// output file name and workspace
			std::stringstream outfilename;
			outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap" << iRap << "_pt" << iPT << "_cpm" << iCPM << ".root";
//			outfilename << "tmpFiles/fit_Psi" << nState-3 << "S_rap" << iRap << "_pt" << iPT << ".root";			
			RooWorkspace* ws = new RooWorkspace(workspacename.c_str());

			// define pt and y cuts on dataset
			std::stringstream cutString;
			cutString << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && " << "(JpsiPt >= " << ptMin << " && JpsiPt < "<< ptMax << ") && "
				<< "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";

			cout << "cutString: " << cutString.str().c_str() << endl;

			// get the dataset for the fit
			RooDataSet* binData = (RooDataSet*)fullData->reduce(cutString.str().c_str());
			std::stringstream name;
			name << "data_rap" << iRap << "_pt" << iPT << "_cpm" << iCPM;;
			binData->SetNameTitle(name.str().c_str(), "Data For Fitting");    

			// Import variables to workspace
			ws->import(*binData);
			ws->writeToFile(outfilename.str().c_str());
			
		  }//iCPM
		}//iPT
	}//iRap

	////---------------------------------------------------------------
	////--Integrating rapidity and pt bins, in +/- 3*sigma mass window
	////---------------------------------------------------------------
	if(drawRapPt2D){
		double yMin = onia::rapForPTRange[0];
		double yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		double ptMin =  onia::pTRange[0][0];
		double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];
		double cpmMin =  onia::cpmRange[0];
		double cpmMax =  onia::cpmRange[onia::NchBins];		

		std::stringstream cutRapPt;
		cutRapPt << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && "
			<< "(JpsiPt > " << ptMin << " && JpsiPt < "<< ptMax << ") && "
			<< "(TMath::Abs(JpsiRap) > " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
		cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

		RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
		std::stringstream nameRapPt;
		nameRapPt << "data_rap0_pt0_cpm0";
		rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

		// output file name and workspace
		std::stringstream outfilename;
		outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap0_pt0_cpm0.root";
		RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
		//Import variables to workspace
		ws_RapPt->import(*rapPtData);
		ws_RapPt->writeToFile(outfilename.str().c_str());

		TH2D* rapPt;
		TH1D* rap1p2;
		double MassMin;
		double MassMax;

		rap1p2 = new TH1D("rap1p2","rap1p2",30,0, 1.8); 
		if(nState==4){
			rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72);
			MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
			MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
			// sigma  27.2 MeV
			// mean 3.093 GeV
		}
		if(nState==5){
			rapPt = new TH2D( "rapPt", "rapPt", 64,-1.6,1.6,144,0,72); //  rap<1.5
			//rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
			MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
			MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
			// sigma 34.9 MeV // pT > 7
			// sigma 34.3 MeV // pT > 10
			// mean 3.681 GeV
		}

		cout<<"Plotting rap-Pt for Psi"<<nState-3<<"S"<<endl;
		cout<<"MassMin for rap-Pt plot = "<<MassMin<<endl;
		cout<<"MassMax for rap-Pt plot = "<<MassMax<<endl;

		TTree *rapPtTree = (TTree*)rapPtData->tree();
		std::stringstream cutMass;
		cutMass<<"(JpsiMass > " << MassMin << " && JpsiMass < "<< MassMax << ")";
		//following two methods can only be used in root_v30, 34 does not work
		rapPtTree->Draw("JpsiPt:JpsiRap>>rapPt",cutMass.str().c_str(),"colz");
		cout<<"debug"<<endl;
		rapPtTree->Draw("TMath::Abs(JpsiRap)>>rap1p2",cutMass.str().c_str());

		TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
		rapPt->SetYTitle("p_{T}(#mu#mu) [GeV]");
		rapPt->SetXTitle("y(#mu#mu)");
		gStyle->SetPalette(1);
		gPad->SetFillColor(kWhite);
		rapPt->SetTitle(0);
		rapPt->SetStats(0);
		gPad->SetLeftMargin(0.15);
		gPad->SetRightMargin(0.17);
		rapPt->GetYaxis()->SetTitleOffset(1.5);
		rapPt->Draw("colz");

		TLine* rapPtLine;

		for(int iRap=0;iRap<onia::kNbRapForPTBins+1;iRap++){
			rapPtLine= new TLine( -onia::rapForPTRange[iRap], onia::pTRange[0][0], -onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
			rapPtLine->SetLineWidth( 2 );
			rapPtLine->SetLineStyle( 1 );
			rapPtLine->SetLineColor( kWhite );
			rapPtLine->Draw();
			rapPtLine= new TLine( onia::rapForPTRange[iRap], onia::pTRange[0][0], onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
			rapPtLine->SetLineWidth( 2 );
			rapPtLine->SetLineStyle( 1 );
			rapPtLine->SetLineColor( kWhite );
			rapPtLine->Draw();
			int pTBegin = 0;
			if(nState==5) pTBegin = 1;
			for(int iPt=pTBegin;iPt<onia::kNbPTBins[iRap]+1;iPt++){
				rapPtLine= new TLine( -onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt], onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt] );
				rapPtLine->SetLineWidth( 2 );
				rapPtLine->SetLineStyle( 1 );
				rapPtLine->SetLineColor( kWhite );
				rapPtLine->Draw();
			}
		}

		char savename[200];
		sprintf(savename,"Fit/rapPt_Psi%dS.pdf",nState-3);
		c2->SaveAs(savename);
		TCanvas* c3 = new TCanvas("c3","c3",1500,1200);
		rap1p2->SetYTitle("Events");
		rap1p2->SetXTitle("y(#mu#mu)");
		rap1p2->SetTitle(0);
		rap1p2->SetStats(0);
		rap1p2->GetYaxis()->SetTitleOffset(1.2);
		rap1p2->Draw();
		sprintf(savename,"Fit/rapDimuon_1p2_Psi%dS.pdf",nState-3);
		c3->SaveAs(savename);
	}
	
	if(drawPtCPM2D){
		double yMin = onia::rapForPTRange[0];
		double yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		double ptMin =  onia::pTRange[0][0];
		double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];
		double cpmMin =  onia::cpmRange[0];
		double cpmMax =  onia::cpmRange[onia::NchBins];		

		std::stringstream cutRapPt;
		cutRapPt << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && "
			<< "(JpsiPt > " << ptMin << " && JpsiPt < "<< ptMax << ") && "
			<< "(TMath::Abs(JpsiRap) > " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
		cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

		RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
		std::stringstream nameRapPt;
		nameRapPt << "data_rap0_pt0_cpm0";
		rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

		// output file name and workspace
		std::stringstream outfilename;
		outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap0_pt0_cpm0.root";
		RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
		//Import variables to workspace
		ws_RapPt->import(*rapPtData);
		ws_RapPt->writeToFile(outfilename.str().c_str());

		TH2D* PtCPM;
		double MassMin;
		double MassMax;

		if(nState==4){
			PtCPM = new TH2D( "PtCPM", "PtCPM", 100,0,50,200,0,100);
			MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
			MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
			// sigma  27.2 MeV
			// mean 3.093 GeV
		}
		if(nState==5){
			PtCPM = new TH2D( "PtCPM", "PtCPM", 100,0,50,200,0,100); //  rap<1.5
			//rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
			MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
			MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
			// sigma 34.9 MeV // pT > 7
			// sigma 34.3 MeV // pT > 10
			// mean 3.681 GeV
		}

		cout<<"Plotting Pt-CPM for Psi"<<nState-3<<"S"<<endl;
		cout<<"MassMin for Pt-CPM plot = "<<MassMin<<endl;
		cout<<"MassMax for Pt-CPM plot = "<<MassMax<<endl;

		TTree *rapPtTree = (TTree*)rapPtData->tree();
		std::stringstream cutMass;
		cutMass<<"(JpsiMass > " << MassMin << " && JpsiMass < "<< MassMax << ")";
		//following two methods can only be used in root_v30, 34 does not work
		rapPtTree->Draw("JpsiCPM:JpsiPt>>PtCPM",cutMass.str().c_str(),"colz");
		cout<<"debug"<<endl;

		TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
		PtCPM->SetYTitle("N_{ch}");
		PtCPM->SetXTitle("p_{T}(#mu#mu) [GeV]");
		gStyle->SetPalette(1);
		gPad->SetFillColor(kWhite);
		PtCPM->SetTitle(0);
		PtCPM->SetStats(0);
		gPad->SetLeftMargin(0.15);
		gPad->SetRightMargin(0.17);
		PtCPM->GetYaxis()->SetTitleOffset(1.5);
		PtCPM->Draw("colz");

		TLine* PtCPMLine;

		int iRap=0;
		for(int iPt=0;iPt<onia::kNbPTMaxBins+1;iPt++){
		int cpmBegin = 0;
			if(nState==5) cpmBegin = 1;
			for(int icpm=cpmBegin;icpm<onia::NchBins+1;icpm++){
			
			PtCPMLine= new TLine( onia::pTRange[iRap][0], onia::cpmRange[icpm], onia::pTRange[iRap][onia::kNbPTMaxBins], onia::cpmRange[icpm] );
			PtCPMLine->SetLineWidth( 2 );
			PtCPMLine->SetLineStyle( 1 );
			PtCPMLine->SetLineColor( kWhite );
			PtCPMLine->Draw();
			PtCPMLine= new TLine( onia::pTRange[iRap][iPt], onia::cpmRange[0], onia::pTRange[iRap][iPt], onia::cpmRange[onia::NchBins] );
			PtCPMLine->SetLineWidth( 2 );
			PtCPMLine->SetLineStyle( 1 );
			PtCPMLine->SetLineColor( kWhite );
			PtCPMLine->Draw();

			
//				PtCPMLine= new TLine( onia::pTRange[0][onia::kNbPTMaxBins], onia::cpmRange[icpm], onia::pTRange[0][onia::kNbPTMaxBins], onia::cpmRange[icpm] );
//				PtCPMLine->SetLineWidth( 2 );
//				PtCPMLine->SetLineStyle( 1 );
//				PtCPMLine->SetLineColor( kWhite );
//				PtCPMLine->Draw();
			}
		}

		char savename[200];
		sprintf(savename,"Fit/PtCPM_Psi%dS.pdf",nState-3);
		c2->SaveAs(savename);
	}

	f->Close();
}
コード例 #8
0
void hggfitmceerr(double nommass=123., double tgtr=1., int ijob=0) {
    
  //gSystem->cd("/scratch/bendavid/root/bare/fitplotsJun10test/");
  
  int seed = 65539+ijob+1; 
  
  TString dirname = "/scratch/bendavid/root/bare/hggfiteerrtestall_large2/";
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);
  
  
  //nommass=150.;
 // gSystem->cd("/scratch/bendavid/root/bare/fitplotsJun8_150_2x/");
  
  gRandom->SetSeed(seed);
  RooRandom::randomGenerator()->SetSeed(seed);    
  
//   TFile *fin = TFile::Open("/home/mingyang/cms/hist_approval/hgg-2013Moriond/merged/hgg-2013Moriond_s12-h150gg-gf-v7a_noskim.root");
//   TDirectory *hdir = (TDirectory*)fin->FindObjectAny("PhotonTreeWriterPresel");
//   TTree *htree = (TTree*)hdir->Get("hPhotonTree");

//   TFile *fdin = TFile::Open("/home/mingyang/cms/hist/hgg-2013Moriond/merged/hgg-2013Moriond_r12_ABCD.root");
//   TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPresel");
//   TTree *dtree = (TTree*)ddir->Get("hPhotonTree");  
  
  //TCut selcut = "(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)";
  TCut selcut = "(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)";
  //TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut selweight = "xsecweight(procidx)*mcweight*kfact(procidx,ph1.ispromptgen,ph2.ispromptgen)";
  
  TCut sigFcut = "(procidx==0 || procidx==3)";
  TCut sigVcut = "(procidx==1 || procidx==2)";
  
  TCut bkgPPcut = "(procidx==4)";
  TCut bkgPFcut = "(procidx==5 || procidx==6)";
  TCut bkgFFcut = "(procidx==7 || procidx==8)";
  
  
  
  TCut bkgcut = "(procidx>3)";
  TCut bkgcutnoq = "(procidx>3 && procidx<7)";
  
  TCut prescalenone = "(1==1)";
  TCut evenevents = "(evt%2==0)";
  TCut oddevents =  "(evt%2==1)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale50 = "(evt%50==0)";
  TCut prescale100 = "(evt%100==0)";
  
  
  
  TCut fcut = prescale50;  
  
  
  float xsecs[50];

  
  //TCut selcutsingle = "ph.pt>25. && ph.isbarrel && ph.ispromptgen";
  //TCut selcutsingle = "ph.pt>25.&& ph.ispromptgen";
  TCut selcutsingle = "ph.genpt>16.&& ph.ispromptgen";
  TCut selweightsingle = "xsecweight(procidx)";
  
  
//   TChain *tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonMvaMod/JetPub/JetCorrectionMod/SeparatePileUpMod/ElectronIDMod/MuonIDMod/PhotonPairSelectorPresel/PhotonTreeWriterPresel/hPhotonTreeSingle");
//   tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV/merged/hgg-2013Final8TeV_s12-diphoj-v7n_noskim.root");

  TChain *tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonMvaMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle");
  tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV_reg_trans/merged/hgg-2013Final8TeV_reg_trans_s12-pj20_40-2em-v7n_noskim.root");
  tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV_reg_trans/merged/hgg-2013Final8TeV_reg_trans_s12-pj40-2em-v7n_noskim.root");
  
  xsecs[0] = 0.001835*81930.0;
  xsecs[1] = 0.05387*8884.0;
  initweights(tree,xsecs,1.);
  
  double weightscale = xsecweights[1];
  xsecweights[0] /= weightscale;
  xsecweights[1] /= weightscale;  
 
  
  
  tree->SetCacheSize(64*1024*1024);
  
  

  RooRealVar energy("energy","ph.e",0);
  RooRealVar sceta("sceta","ph.sceta",0.);
  RooRealVar idmva("idmva","ph.idmva",0.,-1.,1.);  
  RooRealVar eerr("eerr","(ph.isbarrel + 0.5*!ph.isbarrel)*ph.eerr/ph.e",0.);
  RooRealVar evt("evt","evt",0.);
  
  
  RooArgList vars;
  vars.add(energy);
  vars.add(sceta);
  //vars.add(idmva);
  
  
  RooArgList condvars(vars);
  
  vars.add(eerr);  
  
  RooArgList condvarsid(vars);
  
  vars.add(idmva);
  vars.add(evt);
  

//   RooPowerLaw("testpow","",pt1,pt2);
//   return;
  

//    new TCanvas;
//    tree->Draw("mass>>htmpall(80,100.,180.)",bkgcut*selcut*selweight,"HIST");
// 
//    new TCanvas;
//    tree->Draw("mass>>htmpallid(80,100.,180.)",idcut*bkgcut*selcut*selweight,"HIST");   
//    
//    new TCanvas;
//    tree->Draw("mass>>htmp(80,100.,180.)",bkgcutnoq*selcut*selweight,"HIST");   
// //   
//    return;
    
  
  
  //RooRealVar weightvar("weightvar","(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2 && evt%100!=0)",1.);
  RooRealVar weightvar("weightvar","",1.);
  //RooRealVar weightvar("weightvar","(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)",1.);
  
  weightvar.SetTitle(selcutsingle*selweightsingle);
  RooDataSet *hdataSingle = RooTreeConvert::CreateDataSet("hdataSingle",tree,vars,weightvar);    
  
  int ngauseerr = 4;
  //int nparmseerr = 3*ngauseerr + 2;
  //int nparmseerr = 3*ngauseerr + 2;
  int nparmseerr = 5*ngauseerr;
  
  RooArgList tgtseerr;
  RooGBRFunction funceerr("funceerr","",condvars,nparmseerr);
 
  int iparmeerr = 0;  
  
  
  RooArgList eerrgauspdfs;
  RooArgList eerrgauscoeffs;
  
  double stepeerr = 0.07/double(std::max(1,ngauseerr-1));
  
//    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_eerr_%i",0),"",0.007+stepeerr*0);
//    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_eerr_%i",0),"",0.01);
// //   //RooRealVar *gsigmaRvar = new RooRealVar(TString::Format("gsigmaRvar_eerr_%i",0),"",0.02);
// //   
// //   //if (0==0) gmeanvar->setVal(0.007);
// //   
//    gmeanvar->setConstant(false);
//    gsigmavar->setConstant(false);
// //   //gsigmaRvar->setConstant(false);
// //   
// //   
//    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_eerr_%i",0),"",funceerr,iparmeerr++,*gmeanvar);
//    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_eerr_%i",0),"",funceerr,iparmeerr++,*gsigmavar);
// //   //RooGBRTarget *gsigmaR = new RooGBRTarget(TString::Format("gsigmaR_eerr_%i",0),"",funceerr,iparmeerr++,*gsigmaRvar);
// // 
//    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_eerr_%i",0),"",*gmean,0.,0.5);   
//    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_eerr_%i",0),"",*gsigma,1e-7,0.5);
//   //RooRealConstraint *gsigmaRlim = new RooRealConstraint(TString::Format("gsigmaRlim_eerr_%i",0),"",*gsigmaR,1e-7,0.2);  
//   
//   tgtseerr.add(*gmean);
//   tgtseerr.add(*gsigma);
  
  for (int igaus=0; igaus<ngauseerr; ++igaus) {
    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_eerr_%i",igaus),"",0.007+stepeerr*igaus);
    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_eerr_%i",igaus),"",0.01);
    RooRealVar *galphavar = new RooRealVar(TString::Format("galphavar_eerr_%i",igaus),"",1.0);
    RooRealVar *gnvar = new RooRealVar(TString::Format("gnvar_eerr_%i",igaus),"",2.);    
    RooRealVar *gfracvar = new RooRealVar(TString::Format("gfracvar_eerr_%i",igaus),"",1.0);  
    
    //if (igaus==0) gmeanvar->setVal(0.007);
    
    gmeanvar->setConstant(false);
    gsigmavar->setConstant(false);
    galphavar->setConstant(false);
    gnvar->setConstant(false);    
    gfracvar->setConstant(false);
    
    
    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_eerr_%i",igaus),"",funceerr,iparmeerr++,*gmeanvar);
    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_eerr_%i",igaus),"",funceerr,iparmeerr++,*gsigmavar);
    RooGBRTarget *galpha = new RooGBRTarget(TString::Format("galpha_eerr_%i",igaus),"",funceerr,iparmeerr++,*galphavar);
    RooGBRTarget *gn = new RooGBRTarget(TString::Format("gn_eerr_%i",igaus),"",funceerr,iparmeerr++,*gnvar);    
    RooGBRTarget *gfrac = new RooGBRTarget(TString::Format("gfrac_eerr_%i",igaus),"",funceerr,iparmeerr++,*gfracvar);

    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_eerr_%i",igaus),"",*gmean,0.,0.5);   
    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_eerr_%i",igaus),"",*gsigma,1e-5,0.1);
    RooRealConstraint *galphalim = new RooRealConstraint(TString::Format("galphalim_eerr_%i",igaus),"",*galpha,0.05,8.);
    RooRealConstraint *gnlim = new RooRealConstraint(TString::Format("gnlim_eerr_%i",igaus),"",*gn,1.01,5000.);
    //RooRealConstraint *gfraclim = new RooRealConstraint(TString::Format("gfraclim_eerr_%i",igaus),"",*gfrac,0.,1.);
    RooAbsReal *gfraclim = new RooProduct(TString::Format("gfraclim_eerr_%i",igaus),"",RooArgList(*gfrac,*gfrac));
 
    
    if (igaus==0) {
      gfraclim = new RooConstVar(TString::Format("gfraclimconst_eerr_%i",igaus),"",1.);
    }
    else {
      tgtseerr.add(*gfrac);   
    }
    
    //RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim);
    //RooBifurGauss *gpdf = new RooBifurGauss(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim,*galphalim);
    
    
    if (igaus==0) {
      RooRevCBFast *gpdf = new RooRevCBFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim,*galphalim, *gnlim);
    
      tgtseerr.add(*gmean);
      tgtseerr.add(*gsigma);
      tgtseerr.add(*galpha);
      tgtseerr.add(*gn);
      
      eerrgauspdfs.add(*gpdf);      
    
    }
    else {
      RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim);
    
      tgtseerr.add(*gmean);
      tgtseerr.add(*gsigma);
      
      eerrgauspdfs.add(*gpdf);

    }      
      
    
    eerrgauscoeffs.add(*gfraclim);    
    
  }
  RooCondAddPdf eerrpdf("eerrpdf","",eerrgauspdfs,eerrgauscoeffs);  
  
  
  RooAbsPdf *pdf0 = static_cast<RooAbsPdf*>(eerrgauspdfs.at(0));
  
  
  int ngaus = 6;
  int nparms = 4*ngaus;
  
  RooArgList tgtsid;
  RooGBRFunction funcid("funcid","",condvarsid,nparms);  
  
  RooArgList gauspdfs;
  RooArgList gauscoeffs;
  
  double step = 0.5/double(std::max(1,ngaus-1));
  
  int iparm = 0;
  for (int igaus=0; igaus<ngaus; ++igaus) {
    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_%i",igaus),"",-0.2+step*igaus);
    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_%i",igaus),"",0.1);
    RooRealVar *gsigmaRvar = new RooRealVar(TString::Format("gsigmaRvar_%i",igaus),"",0.1);
    RooRealVar *gfracvar = new RooRealVar(TString::Format("gfracvar_%i",igaus),"",1.0);  
    
    gmeanvar->setConstant(false);
    gsigmavar->setConstant(false);
    gsigmaRvar->setConstant(false);
    gfracvar->setConstant(false);
    
    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_%i",igaus),"",funcid,iparm++,*gmeanvar);
    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_%i",igaus),"",funcid,iparm++,*gsigmavar);
    RooGBRTarget *gsigmaR = new RooGBRTarget(TString::Format("gsigmaR_%i",igaus),"",funcid,iparm++,*gsigmaRvar);
    RooGBRTarget *gfrac = new RooGBRTarget(TString::Format("gfrac_%i",igaus),"",funcid,iparm++,*gfracvar);

    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_%i",igaus),"",*gmean,-1.,1.);   
    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_%i",igaus),"",*gsigma,1e-4,2.);
    RooRealConstraint *gsigmaRlim = new RooRealConstraint(TString::Format("gsigmaRlim_%i",igaus),"",*gsigmaR,1e-4,2.);
    //RooRealConstraint *gfraclim = new RooRealConstraint(TString::Format("gfraclim_%i",igaus),"",*gfrac,0.,1.);
    
    RooAbsReal *gfraclim = new RooProduct(TString::Format("gfraclim_%i",igaus),"",RooArgList(*gfrac,*gfrac));
 
    
    if (igaus==0) {
      gfraclim = new RooConstVar(TString::Format("gfraclimconst_%i",igaus),"",1.);
    }
    else {
      tgtsid.add(*gfrac);   
    }    
    
    
    RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_%i",igaus),"",idmva,*gmeanlim,*gsigmalim);
    //RooBifurGauss *gpdf = new RooBifurGauss(TString::Format("gdf_%i",igaus),"",idmva,*gmeanlim,*gsigmalim,*gsigmaRlim);
    
    gauspdfs.add(*gpdf);
    gauscoeffs.add(*gfraclim);
    
    tgtsid.add(*gmean);
    tgtsid.add(*gsigma);
    //tgtsid.add(*gsigmaR);
    //tgtsid.add(*gfrac);    
  }
  RooCondAddPdf idpdf("idpdf","",gauspdfs,gauscoeffs);
  
  RooConstVar etermconst("etermconst","",0.);  
  RooAbsReal &eterm = etermconst;
  RooRealVar dummy("dummy","",1.0);
   

  std::vector<RooAbsData*> vdata;
  vdata.push_back(hdataSingle);

  
  std::vector<RooAbsReal*> vpdf;
  vpdf.push_back(&eerrpdf);
  //vpdf.push_back(pdf0);

  std::vector<RooAbsReal*> vpdfid;
  vpdfid.push_back(&idpdf);  
 
  
  RooHybridBDTAutoPdf bdtpdf("bdtpdf","",funceerr,tgtseerr,eterm,dummy,vdata,vpdf);
  bdtpdf.SetPrescaleInit(100);
  bdtpdf.SetMinCutSignificance(5.0);
  bdtpdf.SetShrinkage(0.1);
  bdtpdf.SetMinWeightTotal(200.);
  bdtpdf.SetMaxNodes(200);
  bdtpdf.TrainForest(1e6);   
  
  RooHybridBDTAutoPdf bdtpdfid("bdtpdfid","",funcid,tgtsid,eterm,dummy,vdata,vpdfid);
  bdtpdfid.SetPrescaleInit(100);
  bdtpdfid.SetMinCutSignificance(5.0);
  bdtpdfid.SetShrinkage(0.1);
  bdtpdfid.SetMinWeightTotal(200.);
  bdtpdfid.SetMaxNodes(200);
  bdtpdfid.TrainForest(1e6);    
  
  
  RooAbsReal *finalcdferr = eerrpdf.createCDF(eerr);
  
  RooFormulaVar transerr("transerr","","sqrt(2.)*TMath::ErfInverse(2.*@0-1.)",*finalcdferr);
  


  RooAbsReal *finalcdfid = idpdf.createCDF(idmva);
  
  RooFormulaVar transid("transid","","sqrt(2.)*TMath::ErfInverse(2.*@0-1.)",*finalcdfid);
  
  
  RooWorkspace *wsout = new RooWorkspace("wsfiteerr");
  wsout->import(*hdataSingle);
  
  wsout->import(eerrpdf,RecycleConflictNodes());
  wsout->import(idpdf,RecycleConflictNodes());
//   wsout->import(transerr,RecycleConflictNodes());
//   wsout->import(transid,RecycleConflictNodes());
  
  wsout->defineSet("datavars",vars,true);
    
  wsout->writeToFile("hggfiteerr.root");  
  
  
    
  
  RooRealVar *cdfidvar = (RooRealVar*)hdataSingle->addColumn(*finalcdfid);    
  RooRealVar *transidvar = (RooRealVar*)hdataSingle->addColumn(transid);
    
  RooGaussianFast unormpdfid("unormpdfid","",*transidvar,RooConst(0.),RooConst(1.));    

  RooRealVar *cdferrvar = (RooRealVar*)hdataSingle->addColumn(*finalcdferr);    
  RooRealVar *transerrvar = (RooRealVar*)hdataSingle->addColumn(transerr);
    
  RooGaussianFast unormpdferr("unormpdferr","",*transerrvar,RooConst(0.),RooConst(1.));    
  
  
  //RooDataSet *testdata = (RooDataSet*)hdataSingle->reduce("abs(sceta)>1.3 && abs(sceta)<1.4");
  RooDataSet *testdata = hdataSingle;
    
  
  new TCanvas;
  RooPlot *eerrplot = eerr.frame(0.,0.1,200);
  testdata->plotOn(eerrplot);
  eerrpdf.plotOn(eerrplot,ProjWData(*testdata));
  eerrplot->Draw();    
  

  
  new TCanvas;
  RooPlot *transplot = transerrvar->frame(-5.,5.,100);
  hdataSingle->plotOn(transplot);
  unormpdferr.plotOn(transplot);
  transplot->Draw();
  //return;
  
  new TCanvas;
  RooPlot *cdfploterr = cdferrvar->frame(0.,1.,100);
  hdataSingle->plotOn(cdfploterr);
  //unormpdf.plotOn(transplot);
  cdfploterr->Draw();
  //return;    
  
  
  
  new TCanvas;
  RooPlot *idplot = idmva.frame(-1.,1.,200);
  testdata->plotOn(idplot);
  idpdf.plotOn(idplot,ProjWData(*testdata));
  idplot->Draw();  
  

  
  new TCanvas;
  RooPlot *transplotid = transidvar->frame(-5.,5.,100);
  testdata->plotOn(transplotid);
  unormpdfid.plotOn(transplotid);
  transplotid->Draw();
  //return;
  
  new TCanvas;
  RooPlot *cdfplotid = cdfidvar->frame(0.,1.,100);
  testdata->plotOn(cdfplotid);
  //unormpdf.plotOn(transplot);
  cdfplotid->Draw();
  //return;        
  

  TH1 *herrid = testdata->createHistogram("herrid",eerr,Binning(30,0.,0.1), YVar(idmva,Binning(30,-0.5,0.6)));
  TH1 *herre = testdata->createHistogram("herre",energy,Binning(30,0.,200.), YVar(eerr,Binning(30,0.,0.1)));
  TH1 *hideta = testdata->createHistogram("hideta",sceta,Binning(40,-2.5,2.5), YVar(idmva,Binning(30,-0.5,0.6)));

  TH1 *herridtrans = testdata->createHistogram("herridtrans",*transerrvar,Binning(30,-5.,5.), YVar(*transidvar,Binning(30,-5.,5.)));
  TH1 *herrtranse = testdata->createHistogram("herrtranse",energy,Binning(30,0.,200.), YVar(*transerrvar,Binning(30,-5.,5.)));
  TH1 *hidtranseta = testdata->createHistogram("hidtranseta",sceta,Binning(40,-2.5,2.5), YVar(*transidvar,Binning(30,-5.,5.)));  

  new TCanvas;
  herrid->Draw("COLZ");

  new TCanvas;
  herre->Draw("COLZ");
  
  new TCanvas;
  hideta->Draw("COLZ");    
  
  
  new TCanvas;
  herridtrans->Draw("COLZ");

  new TCanvas;
  herrtranse->Draw("COLZ");
  
  new TCanvas;
  hidtranseta->Draw("COLZ");  
  

  
//   new TCanvas;
//   RooRealVar *meanvar = (RooRealVar*)hdataSingle->addColumn(eerrmeanlim);
//   RooPlot *meanplot = meanvar->frame(0.,0.1,200);
//   hdataSingle->plotOn(meanplot);
//   meanplot->Draw();
  

  return;
  
}
コード例 #9
0
ファイル: createWorkspace.C プロジェクト: knuenz/ChicPol
void createWorkspace(const std::string &infilename, int nState, bool correctCtau, bool drawRapPt2D) {
    gROOT->SetStyle("Plain");
    gStyle->SetTitleBorderSize(0);

    delete gRandom;
    gRandom = new TRandom3(23101987);

    // Set some strings
    const std::string workspacename = "ws_masslifetime",
                      treename = "selectedData";

    // Get the tree from the data file
    TFile *f = TFile::Open(infilename.c_str());
    TTree *tree = (TTree*)f->Get(treename.c_str());

    // Set branch addresses in tree to be able to import tree to roofit
    TLorentzVector* chic = new TLorentzVector;
    tree->SetBranchAddress("chic",&chic);
    TLorentzVector* chic_rf = new TLorentzVector;
    tree->SetBranchAddress("chic_rf",&chic_rf);
    TLorentzVector* jpsi = new TLorentzVector;
    tree->SetBranchAddress("jpsi",&jpsi);
    double lifetime = 0;
    tree->SetBranchAddress("Jpsict",&lifetime);
    double lifetimeErr = 0;
    tree->SetBranchAddress("JpsictErr",&lifetimeErr);

    char lifetimeTitle[200];

    sprintf(lifetimeTitle,"l^{#psi} [mm]");
    if(correctCtau) sprintf(lifetimeTitle,"l^{#chi} [mm]");

    // define variables necessary for J/Psi(Psi(2S)) mass,lifetime fit
    RooRealVar* JpsiMass =
        new RooRealVar("JpsiMass", "M^{#psi} [GeV]", onia::massMin, onia::massMax);
    RooRealVar* JpsiPt =
        new RooRealVar("JpsiPt", "p^{#psi}_{T} [GeV]", 0. ,1000.);
    RooRealVar* JpsiRap =
        new RooRealVar("JpsiRap", "y^{#psi}", -2., 2.);
    RooRealVar* chicMass =
        new RooRealVar("chicMass", "M^{#chi} [GeV]", onia::chimassMin, onia::chimassMax);
    RooRealVar* chicRap =
        new RooRealVar("chicRap", "y^{#chi}", -onia::chirap, onia::chirap);
    RooRealVar* chicPt =
        new RooRealVar("chicPt", "p^{#chi}_{T} [GeV]", 0. ,100.);
    RooRealVar* Jpsict =
        new RooRealVar("Jpsict", lifetimeTitle, onia::ctVarMin, onia::ctVarMax);
    RooRealVar* JpsictErr =
        new RooRealVar("JpsictErr", Form("Error on %s",lifetimeTitle), 0.0001, 1.);

    // Set bins
    Jpsict->setBins(10000,"cache");
    JpsiMass->setBins(10000,"cache");
    JpsiPt->setBins(100);
    JpsiRap->setBins(10000,"cache");
    chicMass->setBins(10000,"cache");
    //JpsictErr->setBins(100);
    JpsictErr->setBins(10000,"cache");

    // The list of data variables
    RooArgList dataVars(*JpsiMass,*JpsiPt,*JpsiRap,*chicMass,*chicRap,*chicPt,*Jpsict,*JpsictErr);

    // construct dataset to contain events
    RooDataSet* fullData = new RooDataSet("fullData","The Full Data From the Input ROOT Trees",dataVars);

    int entries = tree->GetEntries();
    cout << "entries " << entries << endl;

    int numEntriesTotal=0;
    int numEntriesInAnalysis=0;
    int numEntriesNotInAnalysis=0;



    /*
    	/// Read in 2011 data ctauErr-histos

    	char saveDir[200];
    	char PlotID[200];
    	char savename[200];
    	sprintf(saveDir,"/afs/hephy.at/scratch/k/knuenz/ChicPol/macros/polFit/Figures/CtauErrModel");
    	gSystem->mkdir(saveDir);
    	sprintf(PlotID,"2014May26_MoreLbins");
    	sprintf(saveDir,"%s/%s",saveDir,PlotID);
    	gSystem->mkdir(saveDir);
    	sprintf(savename,"%s/CtauErrModel_histograms.root",saveDir);

    	TFile *infile = new TFile(savename,"READ");
    	cout<<"opened file"<<endl;

    	const int nPT=5;
    	const int nRAP=2;
    	const int nL=15;

    	const double bordersPT[nPT+1] = {0., 12., 16., 20., 30., 100.};
    	const double bordersRAP[nRAP+1] = {0., 0.6, 2.};
    	const double bordersL[nL+1] = {onia::ctVarMin, -0.05, -0.03, -0.02, -0.015, -0.01, -0.005,  0., 0.005, 0.01, 0.015, 0.02, 0.03, 0.05, 0.1, onia::ctVarMax};

    	TH1D* h_ctauerr_2011[nRAP+1][nPT+1][nL+1];
    	TH1D* h_ctauerr_2012[nRAP+1][nPT+1][nL+1];

    	for(int iRAP = 0; iRAP < nRAP+1; iRAP++){
    		for(int iPT = 0; iPT < nPT+1; iPT++){
    			for(int iL = 0; iL < nL+1; iL++){

    				h_ctauerr_2011[iRAP][iPT][iL] = (TH1D*)infile->Get(Form("h_ctauerr_2011_rap%d_pt%d_l%d",iRAP, iPT, iL));
    				h_ctauerr_2012[iRAP][iPT][iL] = (TH1D*)infile->Get(Form("h_ctauerr_2012_rap%d_pt%d_l%d",iRAP, iPT, iL));

    			}
    		}
    	}
    	cout<<"opened hists"<<endl;

    	/// Finished reading in 2011 data ctauErr-histos
    */


    // loop through events in tree and save them to dataset
    for (int ientries = 0; ientries < entries; ientries++) {
        numEntriesTotal++;
        if (ientries%10000==0) std::cout << "event " << ientries << " of " << entries <<  std::endl;

        tree->GetEntry(ientries);

        double M_jpsi =jpsi->M();
        double pt_jpsi =jpsi->Pt();
        double y_jpsi =jpsi->Rapidity();
        double M =chic_rf->M();
        //double M =chic->M()-jpsi->M()+onia::MpsiPDG;
        double y=chic->Rapidity();
        double pt=chic->Pt();

        //if (ientries%3==0){
        //	M_jpsi = gRandom->Uniform(JpsiMass->getMin(), JpsiMass->getMax());
        //}


        //double JpsictErrRand = h_JpsictErr->GetRandom();
        //double JpsictErrRand2 = h_JpsictErr->GetRandom();
        //double JpsictMeanRand=0.;
        ////double pTcorrection=(pt-20.)*0.002;
        //
        ////JpsictErrRand-=pTcorrection;
        //if(JpsictErrRand<0) JpsictErrRand=0.001;
        ////JpsictErrRand2-=pTcorrection;
        //if(JpsictErrRand2<0) JpsictErrRand2=0.001;
        //
        //if (ientries%1000000==0){
        //	double exponent=0.4;
        //	JpsictMeanRand=gRandom->Exp(exponent);
        //}
        //
        //
        //lifetime = gRandom->Gaus(JpsictMeanRand,0.8*JpsictErrRand);
        //lifetimeErr = JpsictErrRand2;
        //if (ientries%3==0){
        //	lifetime = gRandom->Gaus(JpsictMeanRand,1.5*JpsictErrRand);
        //}
        //

        //double resCorrFactor=1.08;
        //if(lifetime<0)
        //	lifetimeErr/=resCorrFactor;


        /*
        		int iRAPindex=0;
        		int iPTindex=0;
        		int iLindex=0;

        		for(int iRAP = 1; iRAP < nRAP+1; iRAP++){
        			for(int iPT = 1; iPT < nPT+1; iPT++){
        				for(int iL = 1; iL < nL+1; iL++){

        					Double_t ptMin = bordersPT[iPT-1];;
        					Double_t ptMax = bordersPT[iPT];;
        					Double_t rapMin = bordersRAP[iRAP-1];;
        					Double_t rapMax = bordersRAP[iRAP];  ;
        					Double_t lMin = bordersL[iL-1];;
        					Double_t lMax = bordersL[iL];  ;

        					if(pt_jpsi>ptMin && pt_jpsi<ptMax && TMath::Abs(y_jpsi)>rapMin && TMath::Abs(y_jpsi)<rapMax && lifetime>lMin && lifetime<lMax){
        						iRAPindex=iRAP;
        						iPTindex=iPT;
        						iLindex=iL;
        					}

        				}

        			}
        		}

        		double lifetimeErrRand = h_ctauerr_2011[iRAPindex][iPTindex][iLindex]->GetRandom();

        		lifetimeErr = lifetimeErrRand;
        		if (ientries%10000==0){
        			std::cout << "Test output: lifetimeErr " << lifetimeErr << " randomly drawn from from " << h_ctauerr_2011[iRAPindex][iPTindex][iLindex]->GetName() <<  std::endl;
        		}

        */

        if (
            M > chicMass->getMin() && M < chicMass->getMax()
            && pt > chicPt->getMin() && pt < chicPt->getMax()
            && y > chicRap->getMin() && y < chicRap->getMax()
            && M_jpsi > JpsiMass->getMin() && M_jpsi < JpsiMass->getMax()
            && pt_jpsi > JpsiPt->getMin() && pt_jpsi < JpsiPt->getMax()
            && y_jpsi > JpsiRap->getMin() && y_jpsi < JpsiRap->getMax()
            && lifetime > Jpsict->getMin() && lifetime < Jpsict->getMax()
            && lifetimeErr > JpsictErr->getMin() && lifetimeErr < JpsictErr->getMax()
        ) {

            chicPt      ->setVal(pt);
            chicRap     ->setVal(y);
            chicMass    ->setVal(M);
            JpsiMass    ->setVal(M_jpsi);
            JpsiPt    	->setVal(pt_jpsi);
            JpsiRap     ->setVal(y_jpsi);
            Jpsict      ->setVal(lifetime);
            JpsictErr   ->setVal(lifetimeErr);

            //cout<<"JpsiRap->getVal() "<<JpsiRap->getVal()<<endl;

            fullData->add(dataVars);
            numEntriesInAnalysis++;
        }
        else {
            numEntriesNotInAnalysis++;
            //if (M < chicMass->getMin() || M > chicMass->getMax()) cout << "M " << M << endl;
            //if (pt < chicPt->getMin() || pt > chicPt->getMax()) cout << "pt " << pt << endl;
            //if (y < chicRap->getMin() || y > chicRap->getMax()) cout << "y " << y << endl;
            //if (lifetime < Jpsict->getMin() || lifetime > Jpsict->getMax()) cout << "lifetime " << lifetime << endl;
            //if (lifetimeErr < JpsictErr->getMin() || lifetimeErr > JpsictErr->getMax()) cout << "lifetimeErr " << lifetimeErr << endl;
            //cout << "M " << M << endl;
            //cout << "pt " << pt << endl;
            //cout << "y " << y << endl;
            //cout << "lifetime " << lifetime << endl;
            //cout << "lifetimeErr " << lifetimeErr << endl;
            //cout << " " << endl;

        }

    }//ientries

    //infile->Close();

    cout << "entries entering all bins " << fullData->sumEntries() << endl;
    cout << "numEntriesTotal " << numEntriesTotal << endl;
    cout << "numEntriesInAnalysis " << numEntriesInAnalysis << endl;
    cout << "numEntriesNotInAnalysis " << numEntriesNotInAnalysis << endl;

    //------------------------------------------------------------------------------------------------------------------
    // Define workspace and import datasets

    ////Get datasets binned in pT an y

    for(int iRap = 0; iRap <= onia::kNbRapForPTBins; iRap++) {

        Double_t yMin;
        Double_t yMax;
        if(iRap==0) {
            yMin = onia::rapForPTRange[0];
            yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
        } else {
            yMin = onia::rapForPTRange[iRap-1];
            yMax = onia::rapForPTRange[iRap];
        }

        for(int iPT = 0; iPT <= onia::kNbPTBins[iRap]; iPT++) {
            //for(int iPT = 0; iPT <= 0; iPT++)

            Double_t ptMin;
            Double_t ptMax;
            if(iPT==0) {
                ptMin = onia::pTRange[iRap][0];
                ptMax = onia::pTRange[iRap][onia::kNbPTBins[0]];
            } else {
                ptMin = onia::pTRange[iRap][iPT-1];
                ptMax = onia::pTRange[iRap][iPT];
            }

            // output file name and workspace
            std::stringstream outfilename;
            outfilename << "tmpFiles/backupWorkSpace/ws_createWorkspace_Chi_rap" << iRap << "_pt" << iPT << ".root";
            RooWorkspace* ws = new RooWorkspace(workspacename.c_str());

            // define pt and y cuts on dataset
            std::stringstream cutString;

            if(onia::KinParticleChi && !onia::KinParticleChiButJpsiRap) {
                cutString << "(chicPt >= " << ptMin << " && chicPt < "<< ptMax << ") && "
                          << "(TMath::Abs(chicRap) >= " << yMin << " && TMath::Abs(chicRap) < " << yMax << ")";
            }
            if(!onia::KinParticleChi) {
                cutString << "(JpsiPt >= " << ptMin << " && JpsiPt < "<< ptMax << ") && "
                          << "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
            }
            if(onia::KinParticleChi && onia::KinParticleChiButJpsiRap) {
                cutString << "(chicPt >= " << ptMin << " && chicPt < "<< ptMax << ") && "
                          << "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
            }


            cout << "cutString: " << cutString.str().c_str() << endl;

            // get the dataset for the fit
            RooDataSet* binData = (RooDataSet*)fullData->reduce(cutString.str().c_str());
            std::stringstream name;
            name << "jpsi_data_rap" << iRap << "_pt" << iPT;
            binData->SetNameTitle(name.str().c_str(), "Data For Fitting");

            cout << "numEvents = " << binData->sumEntries() << endl;

            double chicMeanPt = binData->mean(*chicPt);
            RooRealVar var_chicMeanPt("var_chicMeanPt","var_chicMeanPt",chicMeanPt);
            if(!ws->var("var_chicMeanPt")) ws->import(var_chicMeanPt);
            else ws->var("var_chicMeanPt")->setVal(chicMeanPt);
            cout << "chicMeanPt = " << chicMeanPt << endl;

            double jpsiMeanPt = binData->mean(*JpsiPt);
            RooRealVar var_jpsiMeanPt("var_jpsiMeanPt","var_jpsiMeanPt",jpsiMeanPt);
            if(!ws->var("var_jpsiMeanPt")) ws->import(var_jpsiMeanPt);
            else ws->var("var_jpsiMeanPt")->setVal(jpsiMeanPt);
            cout << "jpsiMeanPt = " << jpsiMeanPt << endl;

            std::stringstream cutStringPosRapChic;
            cutStringPosRapChic << "chicRap > 0";
            RooDataSet* binDataPosRapChic = (RooDataSet*)binData->reduce(cutStringPosRapChic.str().c_str());
            double chicMeanAbsRap = binDataPosRapChic->mean(*chicRap);
            cout << "chicMeanAbsRap = " << chicMeanAbsRap << endl;
            RooRealVar var_chicMeanAbsRap("var_chicMeanAbsRap","var_chicMeanAbsRap",chicMeanAbsRap);
            if(!ws->var("var_chicMeanAbsRap")) ws->import(var_chicMeanAbsRap);
            else ws->var("var_chicMeanAbsRap")->setVal(chicMeanAbsRap);

            std::stringstream cutStringPosRapJpsi;
            cutStringPosRapJpsi << "JpsiRap > 0";
            RooDataSet* binDataPosRapJpsi = (RooDataSet*)binData->reduce(cutStringPosRapJpsi.str().c_str());
            double jpsiMeanAbsRap = binDataPosRapJpsi->mean(*JpsiRap);
            cout << "jpsiMeanAbsRap = " << jpsiMeanAbsRap << endl;
            RooRealVar var_jpsiMeanAbsRap("var_jpsiMeanAbsRap","var_jpsiMeanAbsRap",jpsiMeanAbsRap);
            if(!ws->var("var_jpsiMeanAbsRap")) ws->import(var_jpsiMeanAbsRap);
            else ws->var("var_jpsiMeanAbsRap")->setVal(jpsiMeanAbsRap);

            // Import variables to workspace
            ws->import(*binData);
            ws->writeToFile(outfilename.str().c_str());
        }//iPT
    }//iRap

    ////---------------------------------------------------------------
    ////--Integrating rapidity and pt bins, in +/- 3*sigma mass window
    ////---------------------------------------------------------------
    if(drawRapPt2D) {
        double yMin = onia::rapForPTRange[0];
        double yMax = 1.6;//onia::rapForPTRange[onia::kNbRapForPTBins];
        double ptMin =  onia::pTRange[0][0];
        double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];

        std::stringstream cutRapPt;
        cutRapPt << "(chicPt > " << ptMin << " && chicPt < "<< ptMax << ") && "
                 << "(TMath::Abs(chicRap) > " << yMin << " && TMath::Abs(chicRap) < " << yMax << ")";
        cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

        RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
        std::stringstream nameRapPt;
        nameRapPt << "data_rap0_pt0";
        rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

        // output file name and workspace
        std::stringstream outfilename;
        outfilename << "tmpFiles/backupWorkSpace/ws_createWorkspace_Chi_rap0_pt0.root";
        RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
        //Import variables to workspace
        ws_RapPt->import(*rapPtData);
        ws_RapPt->writeToFile(outfilename.str().c_str());

        TH2D* rapPt;
        TH1D* rap1p2;
        double MassMin;
        double MassMax;

        rap1p2 = new TH1D("rap1p2","rap1p2",30,1.2, 1.8);
        if(nState==4) {
            rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72);
            MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
            MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
            // sigma  27.2 MeV
            // mean 3.093 GeV
        }
        if(nState==5) {
            rapPt = new TH2D( "rapPt", "rapPt", 64,-1.6,1.6,144,0,72); //  rap<1.5
            //rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
            MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
            MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
            // sigma 34.9 MeV // pT > 7
            // sigma 34.3 MeV // pT > 10
            // mean 3.681 GeV
        }

        cout<<"Plotting rap-Pt for Psi"<<nState-3<<"S"<<endl;
        cout<<"MassMin for rap-Pt plot = "<<MassMin<<endl;
        cout<<"MassMax for rap-Pt plot = "<<MassMax<<endl;

        TTree *rapPtTree = (TTree*)rapPtData->tree();
        std::stringstream cutMass;
        cutMass<<"(chicMass > " << MassMin << " && chicMass < "<< MassMax << ")";
        //following two methods can only be used in root_v30, 34 does not work
        rapPtTree->Draw("chicPt:chicRap>>rapPt",cutMass.str().c_str(),"colz");
        cout<<"debug"<<endl;
        rapPtTree->Draw("TMath::Abs(chicRap)>>rap1p2",cutMass.str().c_str());

        TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
        rapPt->SetYTitle("p_{T}(#mu#mu) [GeV]");
        rapPt->SetXTitle("y(#mu#mu)");
        gStyle->SetPalette(1);
        gPad->SetFillColor(kWhite);
        rapPt->SetTitle(0);
        rapPt->SetStats(0);
        gPad->SetLeftMargin(0.15);
        gPad->SetRightMargin(0.17);
        rapPt->GetYaxis()->SetTitleOffset(1.5);

        rapPt->Draw("colz");

        TLine* rapPtLine;

        for(int iRap=0; iRap<onia::kNbRapForPTBins+1; iRap++) {
            rapPtLine= new TLine( -onia::rapForPTRange[iRap], onia::pTRange[0][0], -onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
            rapPtLine->SetLineWidth( 2 );
            rapPtLine->SetLineStyle( 1 );
            rapPtLine->SetLineColor( kWhite );
            rapPtLine->Draw();
            rapPtLine= new TLine( onia::rapForPTRange[iRap], onia::pTRange[0][0], onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
            rapPtLine->SetLineWidth( 2 );
            rapPtLine->SetLineStyle( 1 );
            rapPtLine->SetLineColor( kWhite );
            rapPtLine->Draw();

            int pTBegin = 0;
            if(nState==5) pTBegin = 1;
            for(int iPt=pTBegin; iPt<onia::kNbPTBins[iRap+1]+1; iPt++) {
                rapPtLine= new TLine( -onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt], onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt] );
                rapPtLine->SetLineWidth( 2 );
                rapPtLine->SetLineStyle( 1 );
                rapPtLine->SetLineColor( kWhite );
                rapPtLine->Draw();
            }
        }

        char savename[200];
        sprintf(savename,"Figures/rapPt_Chi.pdf");
        c2->SaveAs(savename);

        TCanvas* c3 = new TCanvas("c3","c3",1500,1200);
        rap1p2->SetYTitle("Events");
        rap1p2->SetXTitle("y(#mu#mu)");
        rap1p2->SetTitle(0);
        rap1p2->SetStats(0);
        rap1p2->GetYaxis()->SetTitleOffset(1.2);
        rap1p2->Draw();
        sprintf(savename,"Figures/rap_Chi_1p2.pdf");
        c3->SaveAs(savename);
    }

    f->Close();
}
コード例 #10
0
ファイル: create_tight.C プロジェクト: pbgeff/UserCode
void new_RA4(){
  
  // let's time this challenging example
  TStopwatch t;
  t.Start();

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

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

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

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

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

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

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

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

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


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

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


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


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

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


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


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


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


  // inspect workspace
  wspace->Print();

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


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

}
コード例 #11
0
void eregmerge(bool doele) {
  
  TString dirname = "/afs/cern.ch/user/b/bendavid/CMSSWhgg/CMSSW_5_3_11_patch5/src/HiggsAnalysis/GBRLikelihoodEGTools/data/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  TString fnameeb;
  TString fnameee;
  if (doele) { 
    fnameeb = "wereg_ele_eb.root";
    fnameee = "wereg_ele_ee.root";
  }
  else if (!doele) {
    fnameeb = "wereg_ph_eb.root";
    fnameee = "wereg_ph_ee.root";
  }    
    
   
  TString infileeb = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/%s",fnameeb.Data());
  TString infileee = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/%s",fnameee.Data());
  
  TFile *fwseb = TFile::Open(infileeb); 
  TFile *fwsee = TFile::Open(infileee); 
  
  RooWorkspace *wseb = (RooWorkspace*)fwseb->Get("wereg");
  RooWorkspace *wsee = (RooWorkspace*)fwsee->Get("wereg");
  
  RooAbsPdf *sigpdfeborig = wseb->pdf("sigpdf");
  RooAbsPdf *sigpdfeeorig = wsee->pdf("sigpdf");
  
  RooAbsPdf *sigpdfeb = static_cast<RooAbsPdf*>(cloneRecursiveRename(sigpdfeborig,"EB"));
  RooAbsPdf *sigpdfee = static_cast<RooAbsPdf*>(cloneRecursiveRename(sigpdfeeorig,"EE"));
    
  RooWorkspace *wsout = new RooWorkspace("EGRegressionWorkspace");
  wsout->import(*sigpdfeb);
  wsout->import(*sigpdfee);
  
  TString outname;
  if (doele) outname = "regweights_v4_ele.root";
  else outname = "regweights_v4_ph.root";
  
  wsout->writeToFile(outname);
  
  RooArgList pdfeblist;
  RooArgSet *pdfebcomps = sigpdfeb->getComponents();
  RooArgSet *pdfebvars = sigpdfeb->getVariables();
  pdfeblist.add(*pdfebcomps);
  pdfeblist.add(*pdfebvars);
  delete pdfebcomps;
  delete pdfebvars;
  
  
  RooArgList pdfeelist;
  RooArgSet *pdfeecomps = sigpdfee->getComponents();
  RooArgSet *pdfeevars = sigpdfee->getVariables();
  pdfeelist.add(*pdfeecomps);
  pdfeelist.add(*pdfeevars);
  delete pdfeecomps;
  delete pdfeevars;  
  
  
//   RooArgList components(ws->components());
//   for (int iarg=0; iarg<components.getSize(); ++iarg) {
//     components.at(iarg)->SetName(TString::Format("%s_1",components.at(iarg)->GetName()));
//   }
  
  RooGBRFunction *funceb = static_cast<RooGBRFunction*>(pdfeblist.find("func_EB"));
  RooGBRFunction *funcee = static_cast<RooGBRFunction*>(pdfeelist.find("func_EE"));
  
//   funceb->Vars().Print("V");
//   funcee->Vars().Print("V");

  for (int ivar=0; ivar<funceb->Vars().getSize(); ++ivar) {
    printf("%i: %s, %s\n",ivar,funceb->Vars().at(ivar)->GetName(),funceb->Vars().at(ivar)->GetTitle());
  }
  
  for (int ivar=0; ivar<funcee->Vars().getSize(); ++ivar) {
    printf("%i: %s, %s\n",ivar,funcee->Vars().at(ivar)->GetName(),funcee->Vars().at(ivar)->GetTitle());
  }
  
  TString outnameforest;
  if (doele) outnameforest = "regweights_v4_forest_ele.root";
  else outnameforest = "regweights_v4_forest_ph.root";  
  
  TFile *fforest = new TFile(outnameforest,"RECREATE");
  fforest->WriteObject(funceb->Forest(),"EGRegressionForest_EB");
  fforest->WriteObject(funcee->Forest(),"EGRegressionForest_EE");
  fforest->Close();
  
}
コード例 #12
0
ファイル: mytest.C プロジェクト: nadjieh/Haamumu
void mytest(int seed = 37) {
    using namespace RooFit;
    using namespace std;
	int nbin = 50;
    bool binned = true;
    stringstream nSig;
    stringstream nBkg;
    stringstream bwRatio;
    stringstream bRatio;
    stringstream mass = "60";
    double bL = 20.;//std::atof(mass.str().c_str()) - 10;
    double bH = 70.;//std::atof(mass.str().c_str()) + 10;
    TString pf = "4_4";
    nSig << 3.84;
    nBkg << 552;
    double bkgUnc = 1;//(510-424.)/424.; //50%
    bwRatio << 0.2;
    bRatio << 0.8;
    stringstream range;
    range << bL << "," << bH;
    cout << "Mass: " << mass.str() << endl;
    cout << "Range: " << range.str() << endl;
    TString Range = range.str().c_str();
    TString Mass = mass.str().c_str();
    ///	Data-fit ////////////////
    TString fname = ""; 
    if(!binned)
	    fname = "hamb-shapes-UnbinnedParam-m" + Mass + "-Data-fit.root";
	else
	    fname = "hamb-shapes-BinnedParam-m" + Mass + "-Data-fit.root";		
	
	if(!binned){
		TString name = "test";
    	RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH);
    	TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ");
    	TTree* hbkg = (TTree*) fbkg->Get("rds_zbb");
	    RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, "");
    	RooRandom::randomGenerator()->SetSeed(seed);
    	RooWorkspace *w = new RooWorkspace("w", "w");
    	w->factory("eventSelectionamassMu[" + Range + "]"/*,Range(SM, 50,70)"*/);
    	w->import(bkgData);
    	w->factory("KeysPdf::"+name+"_bkg_dimu(eventSelectionamassMu,bkgData)");

    	TFile* f = new TFile("DoubleMu2012_Summer12_final_" + pf + ".root", "READ");
    	TTree* hh = (TTree*) f->Get("rds_zbb");
    	RooDataSet data("data_dimu", "data", hh, eventSelectionamassMu, "");
    	w->import(data);
    	TH1D * hData = data.createHistogram("data_obs",eventSelectionamassMu,Binning(nbin));
    	double frac = (double)hData->Integral()/(double)nbin;
    	nBkg.str("");
    	nBkg << hData->Integral() - (5 * frac);

    	TFile * fsig = new TFile("H2ToH1H1_H1To2Mu2B_mH2-125_mH1-" + Mass + "_Summer12_final_" + pf + ".root", "read");
    	TTree* hsig = (TTree*) fsig->Get("rds_zbb");
    	RooDataSet sigData("sigData_dimu", "sigData", hsig, eventSelectionamassMu, "");
    	w->import(sigData);
    	w->factory("KeysPdf::" + name + "_sigPdf_dimu(eventSelectionamassMu,sigData_dimu)");
    	   
    	w->factory(name + "_bkg_dimu_norm[" + nBkg.str().c_str() + "]");
    	w->factory(name + "_sigPdf_dimu_norm[" + nSig.str().c_str() + "]");
   	
    	w->writeToFile(fname);
    	//w->var("eventSelectionamassMu")->setBins(55);
    	cardMaker(Mass, bkgUnc, binned);
		
	} else {
        RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH);
    	TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ");
    	TTree* hbkg = (TTree*) fbkg->Get("rds_zbb");
    	RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, "");
    	TH1D * hbkgData = bkgData.createHistogram("bkg",eventSelectionamassMu,Binning(nbin));
    	hbkgData->SetName("bkg");
	    TFile* f = new TFile("DoubleMu2012_Summer12_final_" + pf + ".root", "READ");
    	TTree* hh = (TTree*) f->Get("rds_zbb");
    	RooDataSet data("data_dimu", "data", hh, eventSelectionamassMu, "");
    	TH1D * hData = data.createHistogram("data_obs",eventSelectionamassMu,Binning(nbin));
    	int nData = hData->Integral();
    	double frac = (double)hData->Integral()/(double)nbin;
    	nBkg.str("");
    	nBkg << hData->Integral() - (5 * frac);
    	hData->SetName("data_obs");
   		TFile * fsig = new TFile("H2ToH1H1_H1To2Mu2B_mH2-125_mH1-" + Mass + "_Summer12_final_" + pf + ".root", "read");
    	TTree* hsig = (TTree*) fsig->Get("rds_zbb");
    	RooDataSet sigData("sigData_dimu", "sigData", hsig, eventSelectionamassMu, "");
	    TH1D * hsigData = sigData.createHistogram("signal",eventSelectionamassMu,Binning(nbin));
	    hsigData->SetName("signal");
	    
	    hbkgData->Scale(std::atof(nBkg.str().c_str())/hbkgData->Integral());
	    hsigData->Scale(std::atof(nSig.str().c_str())/hsigData->Integral());
	    	    
		TFile * fOut = new TFile(fname,"recreate");
		fOut->mkdir("dimu")->cd();
		hData->Write();
		hbkgData->Write();
		hsigData->Write();
		fOut->cd();
		fOut->Close();
	    cardMaker(Mass, bkgUnc, binned, std::atof(nSig.str().c_str()), std::atof(nBkg.str().c_str()), nData);
	}
}
コード例 #13
0
ファイル: fitbkgdataCard.C プロジェクト: janveverka/MitHgg
void fitbkgdataCard(TString configCard="template.config", 
		    bool dobands  = true,  // create baerror bands for BG models
		    bool dosignal = false, // plot the signal model (needs to be present)
		    bool blinded  = true,  // blind the data in the plots?
		    bool verbose  = true  ) {
  
  gROOT->Macro("MitStyle.C");
  gStyle->SetErrorX(0); 
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();  
  
  TString projectDir;

  std::vector<TString> catdesc;
  std::vector<TString> catnames;  
  std::vector<int>     polorder;

  double massmin = -1.;
  double massmax = -1.;

  double theCMenergy = -1.;

  bool readStatus = readFromConfigCard( configCard,
					projectDir,
					catnames,
					catdesc,
					polorder,
					massmin,
					massmax,
					theCMenergy
					);
  
  if( !readStatus ) {
    std::cerr<<" ERROR: Could not read from card > "<<configCard.Data()<<" <."<<std::endl;
    return;
  }
  
  TFile *fdata = new TFile(TString::Format("%s/CMS-HGG-data.root",projectDir.Data()),"READ");
  if( !fdata ) {
    std::cerr<<" ERROR: Could not open file "<<projectDir.Data()<<"/CMS-HGG-data.root."<<std::endl;
    return;
  }
  
  if( !gSystem->cd(TString::Format("%s/databkg/",projectDir.Data())) ) {
    std::cerr<<" ERROR: Could not change directory to "<<TString::Format("%s/databkg/",projectDir.Data()).Data()<<"."<<std::endl;
    return;
  }
  
  // ----------------------------------------------------------------------
  // load the input workspace....
  RooWorkspace* win = (RooWorkspace*)fdata->Get("cms_hgg_workspace_data");
  if( !win ) {
    std::cerr<<" ERROR: Could not load workspace > cms_hgg_workspace_data < from file > "<<TString::Format("%s/CMS-HGG-data.root",projectDir.Data()).Data()<<" <."<<std::endl;
    return;
  }

  RooRealVar *intLumi = win->var("IntLumi");
  RooRealVar *hmass   = win->var("CMS_hgg_mass");
  if( !intLumi || !hmass ) {
    std::cerr<<" ERROR: Could not load needed variables > IntLumi < or > CMS_hgg_mass < forom input workspace."<<std::endl;
    return;
  }

  //win->Print();

  hmass->setRange(massmin,massmax);
  hmass->setBins(4*(int)(massmax-massmin));
  hmass->SetTitle("m_{#gamma#gamma}");
  hmass->setUnit("GeV");
  hmass->setRange("fitrange",massmin,massmax);

  hmass->setRange("blind1",100.,110.);
  hmass->setRange("blind2",150.,180.);
  
  // ----------------------------------------------------------------------
  // some auxiliray vectro (don't know the meaning of all of them ... yet...
  std::vector<RooAbsData*> data_vec;
  std::vector<RooAbsPdf*>  pdfShape_vec;   // vector to store the NOT-EXTENDED PDFs (aka pdfshape)
  std::vector<RooAbsPdf*>  pdf_vec;        // vector to store the EXTENDED PDFs
  
  std::vector<RooAbsReal*> normu_vec;      // this holds the normalization vars for each Cat (needed in bands for combined cat)

  RooArgList               normList;       // list of range-limityed normalizations (needed for error bands on combined category)

  //std::vector<RooRealVar*> coeffv;
  //std::vector<RooAbsReal*> normu_vecv; // ???

  // ----------------------------------------------------------------------
  // define output works
  RooWorkspace *wOut = new RooWorkspace("wbkg","wbkg") ;
  
  // util;ities for the combined fit
  RooCategory     finalcat  ("finalcat",  "finalcat") ;  
  RooSimultaneous fullbkgpdf("fullbkgpdf","fullbkgpdf",finalcat);
  RooDataSet      datacomb  ("datacomb",  "datacomb",  RooArgList(*hmass,finalcat)) ;

  RooDataSet *datacombcat = new RooDataSet("data_combcat","",RooArgList(*hmass)) ;
  
  // add the 'combcat' to the list...if more than one cat
  if( catnames.size() > 1 ) {
    catnames.push_back("combcat");    
    catdesc.push_back("Combined");
  }
  
  for (UInt_t icat=0; icat<catnames.size(); ++icat) {
    TString catname = catnames.at(icat);
    finalcat.defineType(catname);
    
    // check if we're in a sub-cat or the comb-cat
    RooDataSet *data   = NULL;
    RooDataSet *inData = NULL;
    if( icat < (catnames.size() - 1) || catnames.size() == 1) { // this is NOT the last cat (which is by construction the combination)
      inData = (RooDataSet*)win->data(TString("data_mass_")+catname);
      if( !inData ) {
	std::cerr<<" ERROR: Could not find dataset > data_mass_"<<catname.Data()<<" < in input workspace."<<std::endl;
	return;
      }
      data = new RooDataSet(TString("data_")+catname,"",*hmass,Import(*inData));  // copy the dataset (why?)
      
      // append the data to the combined data...
      RooDataSet *datacat = new RooDataSet(TString("datacat")+catname,"",*hmass,Index(finalcat),Import(catname,*data)) ;
      datacomb.append(*datacat);
      datacombcat->append(*data);
      
      // normalization for this category
      RooRealVar *nbkg = new RooRealVar(TString::Format("CMS_hgg_%s_bkgshape_norm",catname.Data()),"",800.0,0.0,25e3);
      
      // we keep track of the normalizario vars only for N-1 cats, naming convetnions hystoric...
      if( catnames.size() > 2 && icat < (catnames.size() - 2) ) {
	RooRealVar* cbkg = new RooRealVar(TString::Format("cbkg%s",catname.Data()),"",0.0,0.0,1e3);
	cbkg->removeRange();
	normu_vec.push_back(cbkg);
	normList.add(*cbkg);
      }
      
      /// generate the Bernstrin polynomial (FIX-ME: add possibility ro create other models...)
      fstBernModel* theBGmodel = new fstBernModel(hmass, polorder[icat], icat, catname);            // using my dedicated class...
      
      std::cout<<" model name is "<<theBGmodel->getPdf()->GetName()<<std::endl;

      RooAbsPdf*    bkgshape   = theBGmodel->getPdf();                                              // the BG shape
      RooAbsPdf*    bkgpdf     = new RooExtendPdf(TString("bkgpdf")+catname,"",*bkgshape,*nbkg);    // the extended PDF
      
      // add the extedned PDF to the RooSimultaneous holding all models...
      fullbkgpdf.addPdf(*bkgpdf,catname);
      // store the NON-EXTENDED PDF for usgae to compute the error bands later..
      pdfShape_vec.push_back(bkgshape);
      pdf_vec     .push_back(bkgpdf);
      data_vec    .push_back(data);
      
    } else {
      data = datacombcat;   // we're looking at the last cat (by construction the combination)
      data_vec.push_back(data);
      
      // sum up all the cts PDFs for combined PDF
      RooArgList subpdfs;
      for (int ipdf=0; ipdf<pdf_vec.size(); ++ipdf) {
	subpdfs.add(*pdf_vec.at(ipdf));
      }
      RooAddPdf* bkgpdf = new RooAddPdf(TString("bkgpdf")+catname,"",subpdfs);
      pdfShape_vec.push_back(bkgpdf);      
      pdf_vec     .push_back(bkgpdf);  // I don't think this is really needed though....
    }
    
    // generate the binned dataset (to be put into the workspace... just in case...)
    RooDataHist *databinned = new RooDataHist(TString("databinned_")+catname,"",*hmass,*data);
    
    wOut->import(*data);
    wOut->import(*databinned);

  }
  
  std::cout<<" ***************** "<<std::endl;

  // fit the RooSimultaneous to the combined dataset -> (we could also fit each cat separately)
  fullbkgpdf.fitTo(datacomb,Strategy(1),Minos(kFALSE),Save(kTRUE));
  RooFitResult *fullbkgfitres = fullbkgpdf.fitTo(datacomb,Strategy(2),Minos(kFALSE),Save(kTRUE));
  
  // in principle we're done now, so store the results in the output workspace
  wOut->import(datacomb);  
  wOut->import(fullbkgpdf);
  wOut->import(*fullbkgfitres);

  std::cout<<" ***************** "<<std::endl;
  

  if( verbose ) wOut->Print();

  
  std::cout<<" ***************** "<<std::endl;

  wOut->writeToFile("bkgdatawithfit.root") ;  
  
  if( verbose ) {
    printf("IntLumi = %5f\n",intLumi->getVal());
    printf("ndata:\n");
    for (UInt_t icat=0; icat<catnames.size(); ++icat) {    
      printf("%i ",data_vec.at(icat)->numEntries());      
    }   
    printf("\n");
  } 
  
  // --------------------------------------------------------------------------------------------
  // Now comesd the plotting
  // chage the Statistics style...
  gStyle->SetOptStat(1110);
  
  // we want to plot in 1GeV bins (apparently...)
  UInt_t nbins = (UInt_t) (massmax-massmin);
  
  // here we'll store the curves for the bands...
  std::vector<RooCurve*> fitcurves;
  
  // loop again over the cats
  TCanvas **canbkg = new TCanvas*[catnames.size()];
  RooPlot** plot   = new RooPlot*[catnames.size()];

  TLatex** lat  = new TLatex*[catnames.size()];
  TLatex** lat2 = new TLatex*[catnames.size()];

  std::cout<<"  beofre plotting..."<<std::endl;
  

  for (UInt_t icat=0; icat<catnames.size(); ++icat) {
    TString catname = catnames.at(icat);
    

    std::cout<<" trying to plot #"<<icat<<std::endl;

    // plot the data and the fit 
    canbkg[icat] = new TCanvas;
    plot  [icat] = hmass->frame(Bins(nbins),Range("fitrange"));
    
    std::cout<<" trying to plot #"<<icat<<std::endl;

    // first plot the data invisibly... and put the fitted BG model on top...
    data_vec    .at(icat)->plotOn(plot[icat],RooFit::LineColor(kWhite),MarkerColor(kWhite),Invisible());
    pdfShape_vec.at(icat)->plotOn(plot[icat],RooFit::LineColor(kRed),Range("fitrange"),NormRange("fitrange"));
    
    std::cout<<" trying to plot #"<<icat<<std::endl;


    // if toggled on, plot also the Data visibly
    if( !blinded ) {
      data_vec.at(icat)->plotOn(plot[icat]);
    }
   
    std::cout<<" trying to plot #"<<icat<<std::endl;

    // some cosmetics...
    plot[icat]->SetTitle("");      
    plot[icat]->SetMinimum(0.0);
    plot[icat]->SetMaximum(1.40*plot[icat]->GetMaximum());
    plot[icat]->GetXaxis()->SetTitle("m_{#gamma#gamma} (GeV/c^{2})");
    plot[icat]->Draw();       
            

    std::cout<<" trying to plot #"<<icat<<std::endl;

    // legend....
    TLegend *legmc = new TLegend(0.68,0.70,0.97,0.90);
    legmc->AddEntry(plot[icat]->getObject(2),"Data","LPE");
    legmc->AddEntry(plot[icat]->getObject(1),"Bkg Model","L");
    
    // this part computes the 1/2-sigma bands.    
    TGraphAsymmErrors *onesigma = NULL;
    TGraphAsymmErrors *twosigma = NULL;
    
    std::cout<<" trying ***  to plot #"<<icat<<std::endl;

    RooAddition* sumcatsnm1 = NULL;

    if ( dobands ) { //&& icat == (catnames.size() - 1) ) {

      onesigma = new TGraphAsymmErrors();
      twosigma = new TGraphAsymmErrors();

      // get the PDF for this cat from the vector
      RooAbsPdf *thisPdf = pdfShape_vec.at(icat); 

      // get the nominal fir curve
      RooCurve *nomcurve = dynamic_cast<RooCurve*>(plot[icat]->getObject(1));
      fitcurves.push_back(nomcurve);

      bool iscombcat       = ( icat == (catnames.size() - 1) && catnames.size() > 1);
      RooAbsData *datanorm = ( iscombcat ? &datacomb : data_vec.at(icat) );

      // this si the nornmalization in the 'sliding-window' (i.e. per 'test-bin')
      RooRealVar *nlim = new RooRealVar(TString::Format("nlim%s",catnames.at(icat).Data()),"",0.0,0.0,10.0);
      nlim->removeRange();

      if( iscombcat ) {
	// ----------- HISTORIC NAMING  ----------------------------------------
	sumcatsnm1 = new RooAddition("sumcatsnm1","",normList);   // summing all normalizations epect the last Cat
	// this is the normlization of the last Cat
	RooFormulaVar *nlast = new RooFormulaVar("nlast","","TMath::Max(0.1,@0-@1)",RooArgList(*nlim,*sumcatsnm1));
	// ... and adding it ot the list of norms
	normu_vec.push_back(nlast);
      }

      //if (icat == 1 && catnames.size() == 2) continue; // only 1 cat, so don't need combination

      for (int i=1; i<(plot[icat]->GetXaxis()->GetNbins()+1); ++i) {
	
	// this defines the 'binning' we use for the error bands
        double lowedge = plot[icat]->GetXaxis()->GetBinLowEdge(i);
        double upedge = plot[icat]->GetXaxis()->GetBinUpEdge(i);
        double center = plot[icat]->GetXaxis()->GetBinCenter(i);
        
	// get the nominal value at the center of the bin
        double nombkg = nomcurve->interpolate(center);
        nlim->setVal(nombkg);
        hmass->setRange("errRange",lowedge,upedge);

	// this is the new extended PDF whith the normalization restricted to the bin-area
        RooAbsPdf *extLimPdf = NULL;
	if( iscombcat ) {
	  extLimPdf = new RooSimultaneous("epdf","",finalcat);
	  // loop over the cats and generate temporary extended PDFs
	  for (int jcat=0; jcat<(catnames.size()-1); ++jcat) {
            RooRealVar *rvar = dynamic_cast<RooRealVar*>(normu_vec.at(jcat));
            if (rvar) rvar->setVal(fitcurves.at(jcat)->interpolate(center));
            RooExtendPdf *ecpdf = new RooExtendPdf(TString::Format("ecpdf%s",catnames.at(jcat).Data()),"",*pdfShape_vec.at(jcat),*normu_vec.at(jcat),"errRange");
            static_cast<RooSimultaneous*>(extLimPdf)->addPdf(*ecpdf,catnames.at(jcat));
          }
	} else
	  extLimPdf = new RooExtendPdf("extLimPdf","",*thisPdf,*nlim,"errRange");

        RooAbsReal *nll = extLimPdf->createNLL(*datanorm,Extended(),NumCPU(1));
        RooMinimizer minim(*nll);
        minim.setStrategy(0);
        double clone = 1.0 - 2.0*RooStats::SignificanceToPValue(1.0);
        double cltwo = 1.0 - 2.0*RooStats::SignificanceToPValue(2.0);
	
        if (iscombcat) minim.setStrategy(2);
        
        minim.migrad();
	
        if (!iscombcat) { 
          minim.minos(*nlim);
        }
        else {
          minim.hesse();
          nlim->removeAsymError();
        }

	if( verbose ) 
	  printf("errlo = %5f, errhi = %5f\n",nlim->getErrorLo(),nlim->getErrorHi());
        
        onesigma->SetPoint(i-1,center,nombkg);
        onesigma->SetPointError(i-1,0.,0.,-nlim->getErrorLo(),nlim->getErrorHi());
        
	// to get the 2-sigma bands...
        minim.setErrorLevel(0.5*pow(ROOT::Math::normal_quantile(1-0.5*(1-cltwo),1.0), 2)); // the 0.5 is because qmu is -2*NLL
                          // eventually if cl = 0.95 this is the usual 1.92!      
        
        if (!iscombcat) { 
          minim.migrad();
          minim.minos(*nlim);
        }
        else {
          nlim->setError(2.0*nlim->getError());
          nlim->removeAsymError();          
        }
	
        twosigma->SetPoint(i-1,center,nombkg);
        twosigma->SetPointError(i-1,0.,0.,-nlim->getErrorLo(),nlim->getErrorHi());      
        
        // for memory clean-up
        delete nll;
        delete extLimPdf;
      }
      
      hmass->setRange("errRange",massmin,massmax);

      if( verbose )
	onesigma->Print("V");
      
      // plot[icat] the error bands
      twosigma->SetLineColor(kGreen);
      twosigma->SetFillColor(kGreen);
      twosigma->SetMarkerColor(kGreen);
      twosigma->Draw("L3 SAME");     
      
      onesigma->SetLineColor(kYellow);
      onesigma->SetFillColor(kYellow);
      onesigma->SetMarkerColor(kYellow);
      onesigma->Draw("L3 SAME");
      
      plot[icat]->Draw("SAME");
    
      // and add the error bands to the legend
      legmc->AddEntry(onesigma,"#pm1 #sigma","F");  
      legmc->AddEntry(twosigma,"#pm2 #sigma","F");  
    }
    
    std::cout<<" trying ***2  to plot #"<<icat<<std::endl;

    // rest of the legend ....
    legmc->SetBorderSize(0);
    legmc->SetFillStyle(0);
    legmc->Draw();   

    lat[icat]  = new TLatex(103.0,0.9*plot[icat]->GetMaximum(),TString::Format("#scale[0.7]{#splitline{CMS preliminary}{#sqrt{s} = %.1f TeV L = %.2f fb^{-1}}}",theCMenergy,intLumi->getVal()));
    lat2[icat] = new TLatex(103.0,0.75*plot[icat]->GetMaximum(),catdesc.at(icat));

    lat[icat] ->Draw();
    lat2[icat]->Draw();
    
    // -------------------------------------------------------    
    // save canvas in different formats
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".pdf"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".eps"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".root"));              
  }
  
  return;
  
}
コード例 #14
0
void fastEfficiencyNadir(unsigned int iEG, int iECAL1, int iColl1, int iECAL2, int iColl2,
			 TString dirIn="/home/llr/cms/ndaci/SKWork/macro/skEfficiency/tagAndProbe/EfficiencyStudy/SingEle-May10ReReco/UPDATE2/Tag80Probe95/", 
			 TString lumi="200 pb", int nCPU=4, 
			 int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
			 TString probe="WP80", TString tag="WP80", TString fileIn="tree_effi_TagProbe.root")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // EG THRESHOLDS //
  const int nEG = 71;
  double thres[nEG];
  for(int i=0 ; i<nEG ; i++) thres[i]=i;

  TString names[nEG];
  ostringstream ossi;
  for(int i=0;i<(int)nEG;i++) {
    ossi.str("");
    ossi << thres[i] ;
    names[i] = ossi.str();
  }

  // NAMES //
  const int nECAL=2;
  const int nColl=2;

  TString name_leg_ecal[nECAL] = {"Barrel","Endcaps"};
  TString name_leg_coll[nColl] = {"Online","Emulation"};  

  TString name_ecal[nECAL] = {"_EB","_EE"};
  TString name_coll[nColl] = {"_N","_M"};

  TString dirResults = dirIn + "/turnons/EG"+names[iEG]+"/" ;
  TString name_image = 
    dirResults + "eff_EG"+names[iEG]+"_tag"+tag+"_probe"+probe+name_ecal[iECAL1]+name_coll[iColl1]+"_vs"+name_ecal[iECAL2]+name_coll[iColl2] ;

  // Output log //
  ofstream fichier(name_image+".txt", ios::out);


  // BINNING //
  const int nbins[nEG] = {29,29,29,29,21,21,21,22,22,21,22,21,22,18,19,18,18,18,18,20,20,20,20,19,20,20,20,20,21,21,
			  21,21,21,21,21,21,21,21,21,21, //EG30
			  22,22,22,22,22,22,22,22,22,22, //EG40
			  29,29,29,29,29,29,29,29,29,29, //EG50
			  29,29,29,29,29,29,29,29,29,29};//EG60

  Double_t bins_0[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG0
  Double_t bins_1[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG1
  Double_t bins_2[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG2 
  Double_t bins_3[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG3

  Double_t bins_4[21] = {1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 27, 32, 41, 50, 60, 70, 150}; // EG4
  Double_t bins_5[21] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 31, 40, 50, 60, 70, 150}; // EG5
  Double_t bins_6[21] = {3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19, 21, 23, 27, 32, 41, 50, 60, 70, 150}; // EG6

  Double_t bins_7[22] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG7
  Double_t bins_8[22] = {3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 32, 41, 50, 60, 70, 150}; // EG8
  Double_t bins_9[21] = {4, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG9

  Double_t bins_10[22] = {5, 7, 8, 9, 10, 11, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG10
  Double_t bins_11[21] = {6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 26, 28, 31, 40, 50, 60, 70, 150}; // EG11
  Double_t bins_12[22] = {5, 7, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG12

  Double_t bins_13[18] = {5, 7, 9, 11, 12, 13, 14, 15, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG13
  Double_t bins_14[19] = {6, 8, 10, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG14
  Double_t bins_15[18] = {5, 7, 9, 11, 13, 14, 15, 16, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG15

  Double_t bins_16[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG16
  Double_t bins_17[18] = {9, 11, 13, 15, 16, 17, 18, 19, 21, 23, 25, 30, 35, 40, 50, 60, 70, 150}; // EG17
  Double_t bins_18[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG18

  Double_t bins_19[20] = {9, 11, 13, 15, 17, 18, 19, 20, 21, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG19
  Double_t bins_20[20] = {8, 10, 12, 14, 16, 18, 19, 20, 21, 22, 24, 26, 30, 35, 40, 45, 50, 60, 70, 100}; // EG20
  Double_t bins_21[20] = {9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG21

  Double_t bins_22[20] = {10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG22
  Double_t bins_23[19] = {11, 13, 15, 17, 19, 21, 22, 23, 24, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG23
  Double_t bins_24[20] = {10, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG24

  Double_t bins_25[20] = {11, 13, 15, 17, 19, 21, 23, 24, 25, 26, 27, 29, 30, 35, 40, 45, 50, 60, 70, 150}; // EG25
  Double_t bins_26[20] = {10, 12, 14, 16, 18, 20, 22, 24, 25, 26, 27, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG26
  Double_t bins_27[20] = {11, 13, 15, 17, 19, 21, 23, 25, 26, 27, 28, 29, 33, 35, 40, 45, 50, 60, 70, 150}; // EG27

  Double_t bins_28[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 29, 30, 32, 35, 40, 45, 50, 60, 70, 150}; // EG28
  Double_t bins_29[21] = {11, 13, 15, 17, 19, 21, 23, 25, 27, 28, 29, 30, 31, 33, 35, 40, 45, 50, 60, 70, 150}; // EG29
  Double_t bins_30[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 29, 30, 31, 32, 35, 40, 45, 50, 60, 70, 150}; // EG30

  Double_t bins_40[22] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 38, 39, 40, 42, 45, 50, 60, 70, 150}; // EG40
  Double_t bins_50[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG50
  Double_t bins_60[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG60

  vector< Double_t* > bins;
  bins.push_back( bins_0 ); bins.push_back( bins_1 ); bins.push_back( bins_2 ); bins.push_back( bins_3 ); bins.push_back( bins_4 ); 
  bins.push_back( bins_5 ); bins.push_back( bins_6 ); bins.push_back( bins_7 ); bins.push_back( bins_8 ); bins.push_back( bins_9 ); 
  bins.push_back( bins_10 ); bins.push_back( bins_11 ); bins.push_back( bins_12 ); bins.push_back( bins_13 ); bins.push_back( bins_14 ); 
  bins.push_back( bins_15 ); bins.push_back( bins_16 ); bins.push_back( bins_17 ); bins.push_back( bins_18 ); bins.push_back( bins_19 ); 
  bins.push_back( bins_20 ); bins.push_back( bins_21 ); bins.push_back( bins_22 ); bins.push_back( bins_23 ); bins.push_back( bins_24 ); 
  bins.push_back( bins_25 ); bins.push_back( bins_26 ); bins.push_back( bins_27 ); bins.push_back( bins_28 ); bins.push_back( bins_29 ); 

  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_30 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_40 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_50 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_60 );

  RooBinning binning = RooBinning(nbins[iEG]-1, bins[iEG], "binning");


  // INPUT DATA //
  TFile* f1 = TFile::Open(dirIn+"/"+fileIn);

  TTree* treenew;
  TTree* treenew_2;

  treenew = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL1]+name_coll[iColl1] ) ;
  treenew_2 = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL2]+name_coll[iColl2] ) ;

  TString name_scet[2], name_scdr[2], name_l1bin[2];
  name_scet[0] = "sc_et"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scet[1] = "sc_et"+name_ecal[iECAL2]+name_coll[iColl2];
  name_scdr[0] = "sc_dr"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scdr[1] = "sc_dr"+name_ecal[iECAL2]+name_coll[iColl2];
  
  name_l1bin[0] = "l1_"+names[iEG]+name_ecal[iECAL1]+name_coll[iColl1];
  name_l1bin[1] = "l1_"+names[iEG]+name_ecal[iECAL2]+name_coll[iColl2];

  RooRealVar et_plot(name_scet[0],name_scet[0],0,150) ;
  RooRealVar dr(name_scdr[0],name_scdr[0],0.5,1.5) ; 
  RooRealVar et_plot2(name_scet[1],name_scet[1],0,150) ;
  RooRealVar dr2(name_scdr[1],name_scdr[1],0.5,1.5) ;

  // Acceptance state cut (1 or 0)
  RooCategory cut(name_l1bin[0],name_l1bin[0]) ;
  cut.defineType("accept",1) ;
  cut.defineType("reject",0) ;
  RooCategory cut2(name_l1bin[1],name_l1bin[1]) ;
  cut2.defineType("accept",1) ;
  cut2.defineType("reject",0) ;
  
  // PARAMETRES ROOFIT CRYSTAL BALL
  RooRealVar norm("norm","N",1,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.671034,0.01,8);
  RooRealVar n("n","n",4.07846,1.1,35);
  RooRealVar mean("mean","mean",20.8,0,100);
  //mean.setVal(thres[iEG]);
  RooRealVar sigma("sigma","#sigma",0.972825,0.01,5);
  //RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  RooRealVar norm2("norm2","N",0.999069,0.6,1);
  RooRealVar alpha2("alpha2","#alpha",0.492303,0.01,8);
  RooRealVar n2("n2","n",11.6694,1.1,35);
  RooRealVar mean2("mean2","mean",21.4582,0,100);
  //mean2.setVal(thres[iEG]);
  RooRealVar sigma2("sigma2","#sigma",1.19,0.01,5);
  //RooRealVar pedestal2("pedestal2","pedestal",0.01,0,0.4);

  FuncCB cb("cb","Crystal Ball Integree",et_plot,mean,sigma,alpha,n,norm) ;
  FuncCB cb2("cb2","Crystal Ball Integree",et_plot2,mean2,sigma2,alpha2,n2,norm2) ;
  
  // EFFICIENCY //
  RooEfficiency eff("eff","efficiency",cb,cut,"accept");
  RooEfficiency eff2("eff2","efficiency",cb2,cut2,"accept");

  // DATASETS //
  RooDataSet dataSet("data","data",RooArgSet(et_plot, cut,dr),Import(*treenew)); 
  RooDataSet dataSet2("data2","data2",RooArgSet(et_plot2, cut2,dr2),Import(*treenew_2));

  dataSet.Print();
  dataSet2.Print();
  
  // PLOT //
  RooPlot* frame = et_plot.frame(Bins(18000),Title("Fitted efficiency")) ;
  RooPlot* frame2 = et_plot2.frame(Bins(18000),Title("Fitted efficiency")) ;

  dataSet.plotOn(frame, Binning(binning), Efficiency(cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSet2.plotOn(frame2, Binning(binning), Efficiency(cut2), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );


  /////////////////////// FITTING /////////////////////////////

  double fit_cuts_min = thres[iEG]-1.5 ;
  double fit_cuts_max = 150;

  et_plot.setRange("interesting",fit_cuts_min,fit_cuts_max);
  et_plot2.setRange("interesting",fit_cuts_min,fit_cuts_max);

  RooFitResult* roofitres1 = new RooFitResult("roofitres1","roofitres1");
  RooFitResult* roofitres2 = new RooFitResult("roofitres2","roofitres2");

  fichier << "Fit characteristics :"   << endl ;
  fichier << "EG "     << names[iEG] << endl ;
  fichier << "Fit Range , EB Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "Fit Range , EE Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "----------------------"  << endl ;

  // Fit #1 //
  roofitres1 = eff.fitTo(dataSet,ConditionalObservables(et_plot),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
  
  cb.plotOn(frame,LineColor(color1),LineWidth(2));

  double res_norm1  = norm.getVal();
  double err_norm1  = norm.getErrorLo();
  double res_mean1  = mean.getVal();
  double err_mean1  = mean.getError();
  double res_sigma1 = sigma.getVal();
  double err_sigma1 = sigma.getError();
  double res_n1     = n.getVal();
  double err_n1     = n.getError();
  double res_alpha1 = alpha.getVal();
  double err_alpha1 = alpha.getError();

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << res_mean1  << "; "
	  << "double res_sigma=" << res_sigma1 << "; "
          << "double res_alpha=" << res_alpha1 << "; "
          << "double res_n="     << res_n1     << "; "
          << "double res_norm="  << res_norm1  << "; "
	  << endl
	  << "double err_mean="  << err_mean1  << "; "
	  << "double err_sigma=" << err_sigma1 << "; "
          << "double err_alpha=" << err_alpha1 << "; "
          << "double err_n="     << err_n1     << "; "
          << "double err_norm="  << err_norm1  << "; "
	  << endl;

  // Fit #2 //
  roofitres2 = eff2.fitTo(dataSet2,ConditionalObservables(et_plot2),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
 
  cb2.plotOn(frame2,LineColor(color2),LineWidth(2));

  double res_norm2  = norm2.getVal();
  double err_norm2  = norm2.getErrorLo();
  double res_mean2  = mean2.getVal();
  double err_mean2  = mean2.getError();
  double res_sigma2 = sigma2.getVal();
  double err_sigma2 = sigma2.getError();
  double res_n2     = n2.getVal();
  double err_n2     = n2.getError();
  double res_alpha2 = alpha2.getVal();
  double err_alpha2 = alpha2.getError();

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << res_mean2  << "; "
	  << "double res_sigma=" << res_sigma2 << "; "
	  << "double res_alpha=" << res_alpha2 << "; "
	  << "double res_n="     << res_n2     << "; "
	  << "double res_norm="  << res_norm2  << "; "
	  << endl
	  << "double err_mean="  << err_mean2  << "; "
	  << "double err_sigma=" << err_sigma2 << "; "
	  << "double err_alpha=" << err_alpha2 << "; "
	  << "double err_n="     << err_n2     << "; "
	  << "double err_norm="  << err_norm2  << "; "
	  << endl;
    

  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,100.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  frame2->GetYaxis()->SetRangeUser(0,1.05);
  frame2->GetXaxis()->SetRangeUser(1,100.);
  frame2->GetYaxis()->SetTitle("Efficiency");
  frame2->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame2->Draw("same") ;

  TH1F *SCeta1 = new TH1F("SCeta1","SCeta1",50,-2.5,2.5);
  TH1F *SCeta2 = new TH1F("SCeta2","SCeta2",50,-2.5,2.5);

  SCeta1->SetLineColor(color1) ;
  SCeta1->SetMarkerColor(color1);
  SCeta1->SetMarkerStyle(style1);

  SCeta2->SetLineColor(color2) ;
  SCeta2->SetMarkerColor(color2);
  SCeta2->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.246,0.435,0.461,0.560,NULL,"brNDC"); // mid : x=353.5
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);
  leg->SetMargin(0.25);
  TLegendEntry *entry=leg->AddEntry("NULL","L1_SingleEG"+names[iEG],"h");
//   leg->AddEntry(SCeta1,name_leg_ecal[iECAL1]+" "+name_leg_coll[iColl1],"p");
//   leg->AddEntry(SCeta2,name_leg_ecal[iECAL2]+" "+name_leg_coll[iColl2],"p");
  leg->AddEntry(SCeta1,name_leg_ecal[iECAL1],"p");
  leg->AddEntry(SCeta2,name_leg_ecal[iECAL2],"p");
  leg->Draw();

  leg = new TLegend(0.16,0.725,0.58,0.905,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.03);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+names[iEG]+" GeV","h");
  leg->Draw();

  TPaveText *pt2 = new TPaveText(0.220,0.605,0.487,0.685,"brNDC"); // mid : x=353.5                                          
  pt2->SetLineColor(1);
  pt2->SetTextColor(1);
  pt2->SetTextFont(42);
  pt2->SetTextSize(0.03);
  pt2->SetFillColor(kWhite);
  pt2->SetShadowColor(kWhite);
  pt2->AddText("L1 E/Gamma Trigger");
  pt2->AddText("Electrons from Z");
  pt2->Draw();
  
  //TString name_image="eff_EG20_2012_12fb";

  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");
  ca->Print(name_image+".eps","eps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

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

  w->import(dataSet);
  w->import(dataSet2);
  
  w->import(*roofitres1,"roofitres1");
  w->import(*roofitres2,"roofitres2");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  //f1->Close();
}
コード例 #15
0
ファイル: CreateBkgTemplates.C プロジェクト: UAEDF/vbfHbb
void CreateBkgTemplates(float XMIN, float XMAX, TString OUTPATH, bool MERGE)
{
  gROOT->ProcessLineSync(".x ../common/styleCMSTDR.C");
  gROOT->ForceStyle();
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  const int NSEL(2);
  if (!MERGE) {const int NCAT[NSEL] = {4,3};}
  else {const int NCAT[NSEL] = {4,2};}
  if (!MERGE) {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,0.8,1}};}
  else {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,1}};}
  float LUMI[2] = {19784,18281};
  TString SELECTION[2] = {"NOM","VBF"};
  TString SELNAME[2] = {"NOM","PRK"};
  TString MASS_VAR[2] = {"mbbReg[1]","mbbReg[2]"};
  TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
  TString PATH("flat/");
  TFile *inf[9];
  TTree *tr;
  TH1F *hMbb[9],*hMbbYield[9],*hPass;
  TH1F *hZ,*hW,*hTT,*hST,*hTop;
  TH1F *hZYield,*hWYield,*hTTYield,*hSTYield,*hTopYield;
  char name[1000];
  float LUMI;
  float XSEC[9] = {56.4,11.1,3.79,30.7,11.1,1.76,245.8,650,1.2*1205};
  RooDataHist *roohist_Z[5],*roohist_T[5];
  RooRealVar *kJES[10],*kJER[10];
  RooWorkspace *w = new RooWorkspace("w","workspace");
  
  TString tMERGE = MERGE ? "_CATmerge56" : "";
  
  //RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
  int counter(0);
  for(int isel=0;isel<NSEL;isel++) {
    inf[0] = TFile::Open(PATH+"Fit_T_t-channel_sel"+SELECTION[isel]+".root");
    inf[1] = TFile::Open(PATH+"Fit_T_tW-channel_sel"+SELECTION[isel]+".root");
    inf[2] = TFile::Open(PATH+"Fit_T_s-channel_sel"+SELECTION[isel]+".root");
    inf[3] = TFile::Open(PATH+"Fit_Tbar_t-channel_sel"+SELECTION[isel]+".root");
    inf[4] = TFile::Open(PATH+"Fit_Tbar_tW-channel_sel"+SELECTION[isel]+".root");
    inf[5] = TFile::Open(PATH+"Fit_Tbar_s-channel_sel"+SELECTION[isel]+".root");
    inf[6] = TFile::Open(PATH+"Fit_TTJets_sel"+SELECTION[isel]+".root");
    inf[7] = TFile::Open(PATH+"Fit_ZJets_sel"+SELECTION[isel]+".root");
    inf[8] = TFile::Open(PATH+"Fit_WJets_sel"+SELECTION[isel]+".root");
     
    TCanvas *canZ = new TCanvas("canZ_"+SELECTION[isel],"canZ_"+SELECTION[isel],900,600); 
    TCanvas *canT = new TCanvas("canT_"+SELECTION[isel],"canT_"+SELECTION[isel],900,600);  
    canZ->Divide(2,2);
    canT->Divide(2,2);
    TCanvas *can = new TCanvas(); 
    
    sprintf(name,"CMS_vbfbb_scale_mbb_sel%s",SELECTION[isel].Data()); 
    kJES[isel] = new RooRealVar(name,name,1.0);
    sprintf(name,"CMS_vbfbb_res_mbb_sel%s",SELECTION[isel].Data()); 
    kJER[isel] = new RooRealVar(name,name,1.0);
    kJES[isel]->setConstant(kTRUE);
    kJER[isel]->setConstant(kTRUE);
  
    for(int icat=0;icat<NCAT[isel];icat++) {
		if (MERGE && SELECTION[isel]=="VBF" && icat==1) counter = 56;
      /*
      sprintf(name,"CMS_vbfbb_scale_mbb_CAT%d",counter); 
      kJES[counter] = new RooRealVar(name,name,1.0);
      sprintf(name,"CMS_vbbb_res_mbb_CAT%d",counter); 
      kJER[counter] = new RooRealVar(name,name,1.0);
      kJES[counter]->setConstant(kTRUE);
      kJER[counter]->setConstant(kTRUE);
      */ 
      for(int i=0;i<9;i++) {
        hPass = (TH1F*)inf[i]->Get("TriggerPass");
        sprintf(name,"Hbb/events",icat);
        tr = (TTree*)inf[i]->Get(name); 
        sprintf(name,"puWt[0]*%s*(mva%s>%1.2f && mva%s<=%1.2f)",TRIG_WT[isel].Data(),SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1]);
        TCut cut(name); 
        int NBINS(20);
        //if (icat > 1 && icat<=2) NBINS = 20; 
        if (icat > 2) NBINS = 12;
        sprintf(name,"hMbb%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbb[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbb[i]->Sumw2();
        can->cd();        
        tr->Draw(MASS_VAR[isel]+">>"+hMbb[i]->GetName(),cut);
        sprintf(name,"hMbbYield%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbbYield[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbbYield[i]->Sumw2();
        tr->Draw(MASS_VAR[isel]+">>"+hMbbYield[i]->GetName(),cut);
        hMbbYield[i]->Scale(LUMI[isel]*XSEC[i]/hPass->GetBinContent(1)); 
      }
      hZ  = (TH1F*)hMbb[7]->Clone("Z");
      hW  = (TH1F*)hMbb[8]->Clone("W");
      hTT = (TH1F*)hMbb[6]->Clone("TT");
      hST = (TH1F*)hMbb[0]->Clone("ST");
      hST->Add(hMbb[1]);
      hST->Add(hMbb[2]);
      hST->Add(hMbb[3]);
      hST->Add(hMbb[4]);
      hST->Add(hMbb[5]);
      hTop = (TH1F*)hTT->Clone("Top");
      hTop->Add(hST);
      //hZ->Add(hW);
      hZYield  = (TH1F*)hMbbYield[7]->Clone("ZYield");
      hWYield  = (TH1F*)hMbbYield[8]->Clone("WYield");
      hTTYield = (TH1F*)hMbbYield[6]->Clone("TTYield");
      hSTYield = (TH1F*)hMbbYield[0]->Clone("STYield");
      hSTYield->Add(hMbbYield[1]);
      hSTYield->Add(hMbbYield[2]);
      hSTYield->Add(hMbbYield[3]);
      hSTYield->Add(hMbbYield[4]);
      hSTYield->Add(hMbbYield[5]);
      hTopYield = (TH1F*)hTTYield->Clone("TopYield");
      hTopYield->Add(hSTYield);
      hZYield->Add(hWYield); 

      RooRealVar x("mbbReg_"+TString::Format("CAT%d",counter),"mbbReg_"+TString::Format("CAT%d",counter),XMIN,XMAX);

      sprintf(name,"yield_ZJets_CAT%d",counter);
      RooRealVar *YieldZ = new RooRealVar(name,name,hZYield->Integral());
      sprintf(name,"yield_WJets_CAT%d",counter);
      RooRealVar *YieldW = new RooRealVar(name,name,hWYield->Integral());
      sprintf(name,"yield_Top_CAT%d",counter);
      RooRealVar *YieldT = new RooRealVar(name,name,hTopYield->Integral());
      sprintf(name,"yield_TT_CAT%d",counter);
      RooRealVar *YieldTT = new RooRealVar(name,name,hTTYield->Integral());
      sprintf(name,"yield_ST_CAT%d",counter);
      RooRealVar *YieldST = new RooRealVar(name,name,hSTYield->Integral());

      sprintf(name,"roohist_Z_CAT%d",counter);
      roohist_Z[icat] = new RooDataHist(name,name,x,hZ);

      sprintf(name,"Z_mean_CAT%d",counter);
      RooRealVar mZ(name,name,95,80,110);
      sprintf(name,"Z_sigma_CAT%d",counter);
      RooRealVar sZ(name,name,12,9,20);

      sprintf(name,"Z_mean_shifted_CAT%d",counter);
      RooFormulaVar mZShift(name,"@0*@1",RooArgList(mZ,*(kJES[isel])));
      sprintf(name,"Z_sigma_shifted_CAT%d",counter);
      RooFormulaVar sZShift(name,"@0*@1",RooArgList(sZ,*(kJER[isel])));

      sprintf(name,"Z_a_CAT%d",counter);
      RooRealVar aZ(name,name,-1,-10,10);
      sprintf(name,"Z_n_CAT%d",counter);
      RooRealVar nZ(name,name,1,0,10);

      RooRealVar Zb0("Z_b0_CAT"+TString::Format("%d",counter),"Z_b0_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb1("Z_b1_CAT"+TString::Format("%d",counter),"Z_b1_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb2("Z_b2_CAT"+TString::Format("%d",counter),"Z_b2_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooBernstein Zbkg("Z_bkg_CAT"+TString::Format("%d",counter),"Z_bkg_CAT"+TString::Format("%d",counter),x,RooArgSet(Zb0,Zb1,Zb2));
      
      RooRealVar fZsig("fZsig_CAT"+TString::Format("%d",counter),"fZsig_CAT"+TString::Format("%d",counter),0.7,0.,1.);
      RooCBShape Zcore("Zcore_CAT"+TString::Format("%d",counter),"Zcore_CAT"+TString::Format("%d",counter),x,mZShift,sZShift,aZ,nZ);
    
      RooAddPdf modelZ("Z_model_CAT"+TString::Format("%d",counter),"Z_model_CAT"+TString::Format("%d",counter),RooArgList(Zcore,Zbkg),fZsig);
    
      RooFitResult *resZ = modelZ.fitTo(*roohist_Z[icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q"); 
  
      canZ->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_Z[icat]->plotOn(frame);
      modelZ.plotOn(frame,RooFit::LineWidth(2));
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      TPaveText *pave = new TPaveText(0.7,0.76,0.9,0.9,"NDC");
		pave->SetTextAlign(11);
      pave->SetFillColor(0);
      pave->SetBorderSize(0);
      pave->SetTextFont(62);
      pave->SetTextSize(0.045);
      pave->AddText(TString::Format("%s selection",SELNAME[isel].Data()));
		pave->AddText(TString::Format("CAT%d",counter));
		TText *lastline = pave->AddText("Z template");
		pave->SetY1NDC(pave->GetY2NDC()-0.055*3);
		TPaveText *paveorig = (TPaveText*)pave->Clone();
      paveorig->Draw();
    
      sprintf(name,"roohist_T_CAT%d",counter);
      if (icat < 3) { 
        roohist_T[icat] = new RooDataHist(name,name,x,hTopYield);
      }
      else {
        roohist_T[icat] = new RooDataHist(name,name,x,hSTYield);
      }

      sprintf(name,"Top_mean_CAT%d",counter);
      RooRealVar mT(name,name,130,0,200);
      sprintf(name,"Top_sigma_CAT%d",counter);
      RooRealVar sT(name,name,50,0,200);

      sprintf(name,"Top_mean_shifted_CAT%d",counter);
      RooFormulaVar mTShift(name,"@0*@1",RooArgList(mT,*(kJES[isel])));
      sprintf(name,"Top_sigma_shifted_CAT%d",counter);
      RooFormulaVar sTShift(name,"@0*@1",RooArgList(sT,*(kJER[isel])));

      sprintf(name,"Top_model_CAT%d",counter);

      RooGaussian *modelT = new RooGaussian(name,name,x,mTShift,sTShift); 
    
      RooFitResult *resT = modelT->fitTo(*roohist_T[icat],Save(),SumW2Error(kTRUE),"q");
      /*
      TF1 *tmp_func = new TF1("tmpFunc","gaus",XMIN,XMAX);
      tmp_func->SetParameters(1,a0.getVal(),a1.getVal());
      if (icat < 3) {
        float norm = tmp_func->Integral(XMIN,XMAX)/hTopYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hTopYield->Integral()/norm);
      }
      else {
        float norm = tmp_func->Integral(XMIN,XMAX)/hSTYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hSTYield->Integral()/norm);
      }  
      */
      canT->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_T[icat]->plotOn(frame);
      modelT->plotOn(frame,RooFit::LineWidth(2));
      //modelT->plotOn(frame,VisualizeError(*resT,1,kTRUE),FillColor(kGray),MoveToBack());
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      //tmp_func->Draw("sameL");
		lastline->SetTitle("Top template");
		pave->Draw();

      mZ.setConstant(kTRUE);
      sZ.setConstant(kTRUE);
      aZ.setConstant(kTRUE);
      nZ.setConstant(kTRUE);
      Zb0.setConstant(kTRUE);
      Zb1.setConstant(kTRUE);
      Zb2.setConstant(kTRUE);
      fZsig.setConstant(kTRUE);
      
      mT.setConstant(kTRUE);
      sT.setConstant(kTRUE);

      w->import(modelZ);
      w->import(*modelT);
      w->import(*YieldZ);
      w->import(*YieldT);
      w->import(*YieldTT);
      w->import(*YieldST);
      YieldZ->Print();
      YieldW->Print();
      YieldT->Print();
      YieldTT->Print();
      YieldST->Print();
      counter++;
    }// category loop
	 system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots ] && mkdir %s/plots",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots/bkgTemplates ] && mkdir %s/plots/bkgTemplates",OUTPATH.Data(),OUTPATH.Data()).Data());
	 TString FULLPATH(OUTPATH+"/plots/bkgTemplates");
	 canT->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canZ->GetName()));
	 canT->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canZ->GetName()));
	 delete can;
  }// selection loop
  system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
  system(TString::Format("[ ! -d %s/output ] && mkdir %s/output",OUTPATH.Data(),OUTPATH.Data()).Data());
  w->Print();
  w->writeToFile(TString::Format("%s/output/bkg_shapes_workspace%s.root",OUTPATH.Data(),tMERGE.Data()).Data());
}
コード例 #16
0
//-------------------------------------------------------------
//Main macro for generating data and fitting
//=============================================================  
void PrelimFits_DiphotonMassInBJetWindow(const string inputfilePho = "/afs/cern.ch/user/s/sixie/work/public/Phase2Upgrade/HHToBBGG/MassFit/InputMassHistograms/noPU/HHToBBGG_SignalBkgd_AfterCuts_diphotonMassBJetWin.root", Int_t plotOption = 1, Int_t constBkg = 0) {

  RooWorkspace *ws = new RooWorkspace("MassFitWorkspace");
  AddModels(ws, inputfilePho, plotOption, constBkg);
  ws->writeToFile("CMSAna/HHToBBGG/data/FitWorkspace_DiphotonMassInBJetWindow.root",kTRUE);
}
コード例 #17
0
void makejpsifit(string inputFilename, string outFilename, 
		 Int_t ptBin, Int_t etaBin,
		 double minMass, double maxMass, 
		 double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, 
		 const char* plotOpt, const int nbins, Int_t isMC) {

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

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

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

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

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

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

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

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

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

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

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

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

    data->add(zMassArgSet);
  }

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

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

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

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

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

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

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

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

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

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

  // Mass signal for two decay electrons p.d.f.
  RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth);
  RooCBShape  cball("cball", "Crystal Ball", mass, cbBias, cbSigma, cbCut, cbPower);
  RooFFTConvPdf BWxCB("BWxCB", "bw X crystal ball", mass, bw, cball);

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

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

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

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

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

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

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

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

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

}
コード例 #18
0
void Process(TString fname, TString oldFolder, int toMass, int fromMass)
{




  std::string channels[] = {"data_obs", "WH", "TT",  "WjLF", "WjHF", "ZjLF", "ZjHF" , "VV" , "s_Top"};
  std::string systs[] = {"eff_b", "fake_b", "res_j", "scale_j" , "stat" };

  kount = 0;  

  gROOT->SetStyle("Plain");
  setTDRStyle();

  TFile * file = new TFile(fname.Data(), "READ");
  std::cout << "reading " << fname.Data() << std::endl;
  TString outname(massS[toMass]);
  outname.Append("_June8.root");
  fname.ReplaceAll(".root",outname.Data());
 
///BEGIN CHECK RBIN
  int addRightBin = 0, addRightBinm1 = 0 , rightBinNo = 0;
  float a,overflow;
  RooWorkspace *mytempWS =  (RooWorkspace*) file->Get(oldFolder.Data());
  RooRealVar BDT("CMS_vhbb_BDT_Wln", "BDT", -1, 1);

  float Signal = 0;
  float Background = 0;
  float Backgroundm1 = 0;
  float Data = 0;

  RooDataHist* tempRooDataHistNomS = (RooDataHist*)  mytempWS->data(channels[1].c_str());
  TH1 *tempHistNomS = tempRooDataHistNomS->createHistogram(channels[1].c_str(),BDT,RooFit::Binning(bins));
  tempHistNomS->Rebin(rebin);


  TH1 *tempHistNomD = tempRooDataHistNomS->createHistogram(channels[0].c_str(),BDT,RooFit::Binning(bins));
  tempHistNomD->Rebin(rebin);



  for(int i = 1; i <= tempHistNomS->GetNbinsX(); i++)
  { 
    if(tempHistNomS->GetBinContent(i) > 0)
      { rightBinNo = i; Signal = tempHistNomS->GetBinContent(i); Data = tempHistNomS->GetBinError(i); }
  }

  for(int i = 2; i < 9; i++)
  {
   RooDataHist* tempRooDataHistNom = (RooDataHist*)  mytempWS->data(channels[i].c_str());
   TH1 *tempHistNom = tempRooDataHistNom->createHistogram(channels[i].c_str(),BDT,RooFit::Binning(bins));
   tempHistNom->Rebin(rebin);
   Background += tempHistNom->GetBinContent(rightBinNo);
   

   //   if(tempHistNom->GetBinContent(rightBinNo-1) == 0)
   // {
   // Backgroundm1 = 0;  
   //std::cout << "ARGHGHGHGHGH bkg is 0 still at left" << std::endl;
   //   std::cin >> ;
   // }

   Backgroundm1+=  tempHistNom->GetBinContent(rightBinNo-1); 

   overflow = tempHistNom->GetBinContent(rightBinNo+1) ;
   
   if(tempHistNom->GetBinContent(rightBinNo+1) > 0)
   {
   std::cout << "ARGHGHGHGHGH overflow at right" << std::endl;
   //   std::cin >> ;
   }
   a+= overflow;
  }

  if( (Background ==0) ) addRightBin = 1;
else  addRightBin = 0;


std::cout << "################# folder" << oldFolder << std::endl;
 std::cout<< "################# CHECK RBIN:: right bin n  " << rightBinNo << " signal: " << Signal << " bkg: " << Background << " bkgm1: " <<  Backgroundm1  << " Data:  " << Data <<  " at right there is an overflow of: "<< a << std::endl;
std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin << std::endl;  
 if ( (Backgroundm1 == 0)  ) 
   { addRightBinm1 =1 ;
     std::cout << "ARGHGHGHGHGH " << Backgroundm1 << " at left" << std::endl;
    
   }

std::cout << "########################### need to rebin further? " << addRightBinm1  << std::endl;  
///END CHECK RBIN



  TFile * outfile = new TFile(fname.Data(), "RECREATE");
  using namespace RooFit;
  RooWorkspace *myWS = new RooWorkspace(oldFolder.Data(),oldFolder.Data());
  myWS->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE 

  TString oldFolder2(oldFolder.Data());
  oldFolder2.Append("2");
  RooWorkspace *myWS2 = new RooWorkspace(oldFolder2.Data(),oldFolder2.Data());
  myWS2->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE 

///BEGIN CHECK RBIN
  int addRightBin2=0, rightBinNo2=0, addRightBin2m1=0;
  float a2,overflow2;
  RooWorkspace *mytempWS2 =  (RooWorkspace*) file->Get(oldFolder2.Data());
   RooRealVar BDT2("CMS_vhbb_BDT_Wln", "BDT", -1, 1);

  float Signal2 = 0;
  float Background2 = 0;
  float Background2m1 = 0;
  float Data2 = 0;
  RooDataHist* tempRooDataHistNomS2 = (RooDataHist*)  mytempWS2->data(channels[1].c_str());
  RooDataHist* tempRooDataHistNomD2 = (RooDataHist*)  mytempWS2->data(channels[0].c_str());

  TH1 *tempHistNomS2 = tempRooDataHistNomS2->createHistogram(channels[1].c_str(),BDT2,RooFit::Binning(bins));
  tempHistNomS2->Rebin(rebin);

  TH1 *tempHistNomD2 = tempRooDataHistNomD2->createHistogram(channels[0].c_str(),BDT2,RooFit::Binning(bins));
  tempHistNomD2->Rebin(rebin);


  for(int i = 1; i <= tempHistNomS2->GetNbinsX(); i++)
  { 
    //    std::cout << "############    signal in bin " << i << " is " << tempHistNomS2->GetBinContent(i) << std::endl;
    // std::cout << "############    data in bin " << i << " is " << tempHistNomD2->GetBinContent(i) << std::endl;
    if(tempHistNomS2->GetBinContent(i) > 0)
      { rightBinNo2 = i; Signal2 = tempHistNomS2->GetBinContent(i); Data2 = tempHistNomD2->GetBinContent(i) ;}

  }


  

  for(int i = 2; i < 9; i++)
  {
   RooDataHist* tempRooDataHistNom2 = (RooDataHist*)  mytempWS2->data(channels[i].c_str());
   TH1 *tempHistNom2 = tempRooDataHistNom2->createHistogram(channels[i].c_str(),BDT2,RooFit::Binning(bins));
   tempHistNom2->Rebin(rebin);
   Background2 += tempHistNom2->GetBinContent(rightBinNo2);
   
   overflow2 = tempHistNom2->GetBinContent(rightBinNo2+1) ;

    Background2m1+=  tempHistNom2->GetBinContent(rightBinNo2-1); 


 
   if(tempHistNom2->GetBinContent(rightBinNo2+1) > 0)
   {
   std::cout << "ARGHGHGHGHGH" << std::endl;
   //   std::cin >> ;
   }
   a2+= overflow2;
  }

  if( (Background2 ==0) ) addRightBin2 = 1;
else  addRightBin2 = 0;
    if( (Background2m1 ==0) ) addRightBin2m1 = 1;
std::cout << "################# folder" << oldFolder2 << std::endl;
 std::cout << "################# CHECK RBIN:: right bin n  " << rightBinNo2 << " signal: " << Signal2 << " bkg: " << Background2 <<   " bkgm1: " <<  Background2m1  << " Data:  " << Data2 <<   " at right there is an overflow of: "<< a2 << std::endl;
std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin2 << std::endl;  
std::cout << "########################### need to rebin further? " << addRightBin2m1 << std::endl;  
///END CHECK RBIN

  
  
  for (int c =0; c<9; c++)
  {
     kount2 = 0;  
    for (int s =0; s<5 ; s++ ){
      makeSystPlot( file, oldFolder, myWS,  channels[c], systs[s], toMass, fromMass,  rightBinNo, addRightBin, addRightBinm1  );
      makeSystPlot( file, oldFolder2, myWS2,  channels[c], systs[s] , toMass, fromMass,  rightBinNo2, addRightBin2, addRightBin2m1 );
    }
  }


  if(!(IFILE.Contains("8TeV")))
  {
    makeSystPlot(file, oldFolder, myWS, "WjLF", "WModel",toMass, fromMass, rightBinNo, addRightBin ,addRightBinm1 );
    makeSystPlot(file, oldFolder, myWS, "WjHF", "WModel",toMass, fromMass, rightBinNo, addRightBin, addRightBinm1  );


    makeSystPlot(file, oldFolder2, myWS2, "WjLF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2 , addRightBin2m1);
    makeSystPlot(file, oldFolder2, myWS2, "WjHF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2, addRightBin2m1 );
  }

  myWS->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


  outfile->Write();
  outfile->Close();
  fname.ReplaceAll("June8","June82");
  TFile * outfile2 = new TFile(fname.Data(), "RECREATE");
  myWS2->writeToFile(fname.Data());  
  std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl;
  std::cout << fname.Data() << " written" << std::endl;
  std::cout << "///////////////////////////" << std::endl << std::endl << std::endl;


}
コード例 #19
0
void fillDatasets( TString fname, TString tname, TString outfname ) {

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

  ULong64_t eventNumber;
  TString   *year = 0;
  double    B_s0_DTF_B_s0_M;
  int       itype;
  bool      pass_bdt;
  bool      pass_pid;
  bool      pass_rhokst;
  bool      pass_massveto;
  bool      pass_multcand;
  bool      B_s0_L0HadronDecision_TOS;
  bool      B_s0_L0Global_TIS;
  double    B_s0_DTF_KST1_M;
  double    B_s0_DTF_KST2_M;

  tree->SetBranchAddress(  "eventNumber"                 , &eventNumber                 );
  tree->SetBranchAddress(  "year"                        , &year                        );
  tree->SetBranchAddress(  "B_s0_DTF_B_s0_M"             , &B_s0_DTF_B_s0_M             );
  tree->SetBranchAddress(  "itype"                       , &itype                       );
  tree->SetBranchAddress(  "pass_bdt"                    , &pass_bdt                    );
  tree->SetBranchAddress(  "pass_pid"                    , &pass_pid                    );
  tree->SetBranchAddress(  "pass_rhokst"                 , &pass_rhokst                 );
  tree->SetBranchAddress(  "pass_massveto"               , &pass_massveto               );
  tree->SetBranchAddress(  "pass_multcand"               , &pass_multcand               );
  tree->SetBranchAddress(  "B_s0_L0HadronDecision_TOS"   , &B_s0_L0HadronDecision_TOS   );
  tree->SetBranchAddress(  "B_s0_L0Global_TIS"           , &B_s0_L0Global_TIS           );
  tree->SetBranchAddress(  "B_s0_DTF_KST1_M"             , &B_s0_DTF_KST1_M             );
  tree->SetBranchAddress(  "B_s0_DTF_KST2_M"             , &B_s0_DTF_KST2_M             );

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

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

    tree->GetEntry(ev);

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

    // cut events outside the mass window
    if ( B_s0_DTF_B_s0_M < 5000 || B_s0_DTF_B_s0_M > 5800 ) continue;
    if ( B_s0_DTF_KST1_M < 750  || B_s0_DTF_KST1_M > 1600 ) continue;
    if ( B_s0_DTF_KST2_M < 750  || B_s0_DTF_KST2_M > 1600 ) continue;

    // set workspace values
    w->var("B_s0_DTF_B_s0_M")->setVal( B_s0_DTF_B_s0_M );
    w->var("eventNumber")->setVal( eventNumber );
    if ( *year==TString("2011") ) {
      if ( B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("HadronTOS2011");
      else if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("GlobalTIS2011");
      else continue;
    }
    else if ( *year==TString("2012") ) {
      if ( B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("HadronTOS2012");
      else if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("GlobalTIS2012");
      else continue;
    }
    else continue;

    // for the most case we put the bdt and pid requirement in
    // for low stats MC samples we don't use it
    //
    // NO REQUIREMENT:
    // Lb2pKpipi MC
    if ( itype == -78 || itype == -88 ) {
      w->data("Lb2pKpipi")->add( *w->set("observables") );
    }
    // Lb2ppipipi MC
    else if ( itype == -79 || itype == -89 ) {
        w->data("Lb2ppipipi")->add( *w->set("observables") );
    }
    // Bd2PhiKst MC
    else if ( itype == -75 || itype == -85 ) {
      w->data("Bd2PhiKst")->add( *w->set("observables") );
    }
    // Bs2PhiKst MC
    else if ( itype == -76 || itype == -86 ) {
      w->data("Bs2PhiKst")->add( *w->set("observables") );
    }
    // Bd2RhoKst MC
    else if ( itype == -77 || itype == -87 ) {
      w->data("Bd2RhoKst")->add( *w->set("observables") );
    }

    // FROM HERE BDT, PID AND MASS VETO REQUIREMENTS
    //if ( pass_bdt && pass_pid && pass_multcand && !pass_rhokst && !pass_massveto) {
    if ( pass_bdt && pass_pid && pass_multcand && !pass_massveto) {
      // Data 2011
      if ( itype == 71 ) {
        w->data("Data")->add( *w->set("observables") );
        w->data("Data2011")->add( *w->set("observables") );
        if ( B_s0_L0HadronDecision_TOS ) {
          w->data("Data2011HadronTOS")->add( *w->set("observables") );
        }
        if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) {
          w->data("Data2011GlobalTIS")->add( *w->set("observables") );
        }
      }
      // Data 2012
      else if ( itype == 81 ) {
        w->data("Data")->add( *w->set("observables") );
        w->data("Data2012")->add( *w->set("observables") );
        if ( B_s0_L0HadronDecision_TOS ) {
          w->data("Data2012HadronTOS")->add( *w->set("observables") );
        }
        if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) {
          w->data("Data2012GlobalTIS")->add( *w->set("observables") );
        }
      }
      // Bs2KstKst MC
      else if ( itype == -70 || itype == -80 ) {
        w->data("Bs2KstKst")->add( *w->set("observables") );
      }
      // Bs2KstKst1430 MC
      else if ( itype == -71 || itype == -81 ) {
        w->data("Bs2KstKst1430")->add( *w->set("observables") );
      }
      // Bs2Kst1430Kst1430 MC
      else if ( itype == -72 || itype == -82 ) {
        w->data("Bs2Kst1430Kst1430")->add( *w->set("observables") );
      }
      // Bs2KPiKPi PhaseSpace
      else if ( itype == -73 || itype == -83 ) {
        w->data("Bs2KpiKpiPhaseSpace")->add( *w->set("observables") );
      }
      // Bd2KstKst MC
      else if ( itype == -74 || itype == -84 ) {
        w->data("Bd2KstKst")->add( *w->set("observables") );
      }
    }
  }

  // combined data
  map<string,RooDataSet*> dsetMap;
  dsetMap[ "HadronTOS2011" ] = (RooDataSet*)w->data("Data2011HadronTOS") ;
  dsetMap[ "GlobalTIS2011" ] = (RooDataSet*)w->data("Data2011GlobalTIS") ;
  dsetMap[ "HadronTOS2012" ] = (RooDataSet*)w->data("Data2012HadronTOS") ;
  dsetMap[ "GlobalTIS2012" ] = (RooDataSet*)w->data("Data2012GlobalTIS") ;

  RooDataSet *DataComb = new RooDataSet( "DataCombined", "DataCombined", *w->set("observables"), Index(*w->cat("DataCat")), Import(dsetMap) );
  w->import(*DataComb);
  delete DataComb;

  inFile->Close();
  delete inFile;
  delete year;

  w->writeToFile( outfname );

}
コード例 #20
0
ファイル: sig.C プロジェクト: cms-analysis/ZprimeDiLeptons
void makeModel(RooWorkspace& w) {

   TFile *_file0 = TFile::Open("plots/htotal_root_ZprimeRecomass.root");
   TH1F *Histo = (TH1F*)_file0->Get("htotaldata");
   RooRealVar invm("invm","invm",200.,4000.);    
   RooDataHist* data = new RooDataHist("data","data",invm,Import(*Histo)) ;
   

//   TTree* tree = new TTree("simple","data from ascii file");
//   Long64_t nlines = tree->ReadFile("list_mll_200_2016.txt","x1:x2:x3:invm:x5:x6");
//   Long64_t nlines = tree->ReadFile("a.txt","x1:x2:x3:invm:x5:x6");
//   printf(" found %lld pointsn",nlines);
//   tree->Write();
//   tree->GetEntries();

   RooRealVar mass("mass","mass", 300., 200., 1600.);
   RooRealVar nsig("nsig","Number of signal events", 0., 5000.);
   RooRealVar nbkg("nbkg","Number of background events", 0., 300000.);
   w.import(mass);
   w.import(nsig);
   w.import(nbkg);

//   RooRealVar invm("invm","Invariant mass", 200., 4000.);
//   RooDataSet* data = new RooDataSet("data", "Data", invm, RooFit::Import(*tree));

   data->Print("v");
   w.import(invm);
   w.import(*data);
 
   w.factory("expr::sigma('invm*(0.01292 + 0.00001835 * invm - 0.0000000002733 * invm*invm)',invm)");
   w.factory("expr::width('0.03*invm',invm)");
 
   w.factory("CEXPR::bkgpdf('exp(24.9327 - 2.39287e-03*invm + 3.19926e-07*invm*invm - 3.38799e-11*invm*invm*invm)*pow(invm,-3.3634)',invm)");
   w.factory("Voigtian::sigpdf(invm,mass,width,sigma)");

   w.factory("SUM::model(nbkg*bkgpdf, nsig*sigpdf)");

   RooAbsPdf* sigpdf = w.pdf("sigpdf");
   RooAbsPdf* bkgpdf = w.pdf("bkgpdf");
   RooAbsPdf* model  = w.pdf("model");

   RooStats::ModelConfig* mc = new ModelConfig("mc",&w);
   mc->SetPdf(*w.pdf("model"));
   mc->SetParametersOfInterest(*w.var("nsig"));
   mc->SetObservables(*w.var("invm"));
   w.defineSet("nuisParams","nbkg");

   mc->SetNuisanceParameters(*w.set("nuisParams"));
   w.var("mass")->setConstant(true);

   w.import(*mc);

   w.Print("tree");

   w.writeToFile("MyModel_workspace.root");
  
   TCanvas* c1 = new TCanvas("c1","Control Plots", 900, 700);
   RooPlot* plot = w.var("invm")->frame();
   w.data("data")->plotOn(plot);
   w.pdf("model")->plotOn(plot);
   w.pdf("model")->plotOn(plot, Components("bkgpdf"),LineStyle(kDashed));
   w.pdf("model")->plotOn(plot, Components("sigpdf"),LineColor(kRed));
   plot->Draw();

   return;

}
コード例 #21
0
void CreateDataTemplates(double dX,int BRN_ORDER)
{
  gROOT->ForceStyle();
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  double XMIN = 80;
  double XMAX = 200;
  const int NSEL(2);
  const int NCAT[NSEL] = {4,3};
  const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,0.8,1}};
  char name[1000];
  TString SELECTION[NSEL] = {"NOM","VBF"};
  TString SELTAG[NSEL]    = {"NOM","PRK"};
  TString MASS_VAR[NSEL]  = {"mbbReg[1]","mbbReg[2]"};

  TFile *fBKG  = TFile::Open("limit_BRN5+4_dX0p1_80-200_CAT0-6/output/bkg_shapes_workspace.root");
  RooWorkspace *wBkg = (RooWorkspace*)fBKG->Get("w");
  RooWorkspace *w = new RooWorkspace("w","workspace");
  //RooRealVar x(*(RooRealVar*)wBkg->var("mbbReg"));
  TTree *tr;
  TH1F *h,*hBlind;
  TCanvas *canFit[5]; 
  RooDataHist *roohist[5],*roohist_blind[5];

  TFile *fTransfer = TFile::Open("limit_BRN5+4_dX0p1_80-200_CAT0-6/output/transferFunctions.root");
  TF1 *transFunc;

  int counter(0);
  int NPAR = BRN_ORDER;

  for(int isel=0;isel<NSEL;isel++) {
    TFile *fDATA = TFile::Open("flat/Fit_data_sel"+SELECTION[isel]+".root");
    RooRealVar *brn[8];
    RooArgSet brn_params;
    if (isel == 1) {
      NPAR = 4;
    } 
    for(int ib=0;ib<=NPAR;ib++) {
      brn[ib] = new RooRealVar("b"+TString::Format("%d",ib)+"_sel"+SELECTION[isel],"b"+TString::Format("%d",ib)+"_sel"+SELECTION[isel],0.5,0,10.);
      brn_params.add(*brn[ib]);
    }
    for(int icat=0;icat<NCAT[isel];icat++) {
      RooRealVar x("mbbReg_"+TString::Format("CAT%d",counter),"mbbReg_"+TString::Format("CAT%d",counter),XMIN,XMAX);

      sprintf(name,"fitRatio_sel%s_CAT%d",SELTAG[isel].Data(),counter);
      transFunc = (TF1*)fTransfer->Get(name);
		transFunc->Print();
      // --- The error on the tranfer function parameters is shrinked because the correlations are ingored. 
      // --- Must be consistent with TransferFunctions.C
      float p0 = transFunc->GetParameter(0);
      float e0 = transFunc->GetParError(0);
      float p1 = transFunc->GetParameter(1);
      float e1 = transFunc->GetParError(1);
      float p2 = transFunc->GetParameter(2);
      float e2 = transFunc->GetParError(2);
      RooRealVar trans_p2(TString::Format("trans_p2_CAT%d",counter),TString::Format("trans_p2_CAT%d",counter),p2);
      RooRealVar trans_p1(TString::Format("trans_p1_CAT%d",counter),TString::Format("trans_p1_CAT%d",counter),p1);
      RooRealVar trans_p0(TString::Format("trans_p0_CAT%d",counter),TString::Format("trans_p0_CAT%d",counter),p0);
		printf("%.2f %.2f %.2f\n",p0,p1,p2);
      RooGenericPdf *transfer;
      if (isel == 0) {
        trans_p2.setError(0.5*e2);
        trans_p1.setError(0.5*e1);
        trans_p0.setError(0.5*e0);
        transfer = new RooGenericPdf(TString::Format("transfer_CAT%d",counter),"@2*@0+@1",RooArgList(x,trans_p0,trans_p1)); 
      }
      else {
        trans_p2.setError(0.05*e2);
        trans_p1.setError(0.05*e1);
        trans_p0.setError(0.05*e0);
        transfer = new RooGenericPdf(TString::Format("transfer_CAT%d",counter),"@3*@0*@0+@2*@0+@1",RooArgList(x,trans_p0,trans_p1,trans_p2));
      }
      trans_p2.setConstant(kTRUE);
      trans_p1.setConstant(kTRUE);
      trans_p0.setConstant(kTRUE);

		transfer->Print();
            
      sprintf(name,"FitData_sel%s_CAT%d",SELECTION[isel].Data(),icat);
      canFit[icat] = new TCanvas(name,name,900,600);
      canFit[icat]->cd(1)->SetBottomMargin(0.4);
      sprintf(name,"Hbb/events");
      tr = (TTree*)fDATA->Get(name); 
      sprintf(name,"hMbb_%s_CAT%d",SELECTION[isel].Data(),icat);
      int NBINS = (XMAX[isel][icat]-XMIN[isel][icat])/dX;
      
      h = new TH1F(name,name,NBINS,XMIN[isel][icat],XMAX[isel][icat]);

      sprintf(name,"hMbb_blind_%s_CAT%d",SELECTION[isel].Data(),icat);
      hBlind = new TH1F(name,name,NBINS,XMIN[isel][icat],XMAX[isel][icat]);

      sprintf(name,"mva%s>%1.2f && mva%s<=%1.2f",SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1]);
      TCut cut(name);
      sprintf(name,"mva%s>%1.2f && mva%s<=%1.2f && %s>100 && %s<150",SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1],MASS_VAR[isel].Data(),MASS_VAR[isel].Data());
      TCut cutBlind(name);
      tr->Draw(MASS_VAR[isel]+">>"+h->GetName(),cut); 
      tr->Draw(MASS_VAR[isel]+">>"+hBlind->GetName(),cutBlind); 
      sprintf(name,"yield_data_CAT%d",counter);
      RooRealVar *Yield = new RooRealVar(name,name,h->Integral());
      
      sprintf(name,"data_hist_CAT%d",counter);
      roohist[icat] = new RooDataHist(name,name,x,h);

      sprintf(name,"data_hist_blind_CAT%d",counter);
      roohist_blind[icat] = new RooDataHist(name,name,x,hBlind);
        
      RooAbsPdf *qcd_pdf;
      if (icat == 0) {
        for(int ib=0;ib<=NPAR;ib++) {
          brn[ib]->setConstant(kFALSE);
        }
        sprintf(name,"qcd_model_CAT%d",counter);
        RooBernstein *qcd_pdf_aux = new RooBernstein(name,name,x,brn_params);
        qcd_pdf = dynamic_cast<RooAbsPdf*> (qcd_pdf_aux);
      }
      else {
        for(int ib=0;ib<=NPAR;ib++) {
          brn[ib]->setConstant(kTRUE);
        }
        sprintf(name,"qcd_model_aux1_CAT%d",counter);
        RooBernstein *qcd_pdf_aux1 = new RooBernstein(name,name,x,brn_params);
        sprintf(name,"qcd_model_CAT%d",counter);
        RooProdPdf *qcd_pdf_aux2 = new RooProdPdf(name,name,RooArgSet(*transfer,*qcd_pdf_aux1));
        qcd_pdf = dynamic_cast<RooAbsPdf*> (qcd_pdf_aux2);
      } 

      sprintf(name,"Z_model_CAT%d",counter);
      RooAbsPdf *z_pdf = (RooAbsPdf*)wBkg->pdf(name);
      sprintf(name,"Top_model_CAT%d",counter);
      RooAbsPdf *top_pdf = (RooAbsPdf*)wBkg->pdf(name);

      sprintf(name,"yield_ZJets_CAT%d",counter);
      RooRealVar *nZ = (RooRealVar*)wBkg->var(name);
      sprintf(name,"yield_Top_CAT%d",counter);
      RooRealVar *nT = (RooRealVar*)wBkg->var(name);
      sprintf(name,"yield_QCD_CAT%d",counter);
      RooRealVar nQCD(name,name,1000,0,1e+10);
      nZ->setConstant(kTRUE);
      nT->setConstant(kTRUE);
    
      sprintf(name,"bkg_model_CAT%d",counter);
      RooAddPdf model(name,name,RooArgList(*z_pdf,*top_pdf,*qcd_pdf),RooArgList(*nZ,*nT,nQCD));
      
      RooFitResult *res = model.fitTo(*roohist[icat],RooFit::Save());
      res->Print();
      
      RooPlot* frame = x.frame();
      RooPlot* frame1 = x.frame();
      roohist[icat]->plotOn(frame);
      model.plotOn(frame,LineWidth(2));
      cout<<"chi2/ndof = "<<frame->chiSquare()<<endl;
      RooHist *hresid = frame->residHist(); 
      //model.plotOn(frame,RooFit::VisualizeError(*res,1,kFALSE),FillColor(kGray)MoveToBack());
      model.plotOn(frame,Components(*qcd_pdf),LineWidth(2),LineColor(kBlack),LineStyle(kDashed));
      model.plotOn(frame,Components(*z_pdf),LineWidth(2),LineColor(kBlue));
      model.plotOn(frame,Components(*top_pdf),LineWidth(2),LineColor(kGreen+1));
      frame->Draw(); 
      gPad->Update();
      TPad* pad = new TPad("pad", "pad", 0., 0., 1., 1.);
      pad->SetTopMargin(0.6);
      pad->SetFillColor(0);
      pad->SetFillStyle(0);
      pad->Draw();
      pad->cd(0);
      frame1->addPlotable(hresid,"p");
      frame1->Draw();

      for(int ib=0;ib<=NPAR;ib++) {
        brn[ib]->setConstant(kFALSE);
      }
      
      if (icat > 0) {
        trans_p2.setConstant(kFALSE);
        trans_p1.setConstant(kFALSE);
        trans_p0.setConstant(kFALSE);
      }
      if (isel == 0) {
        w->import(trans_p1);
        w->import(trans_p0);
      }
      else {
        w->import(trans_p2);
        w->import(trans_p1);
        w->import(trans_p0);
      }
      w->import(*roohist[icat]);
      w->import(*roohist_blind[icat]);
      w->import(model);
      w->import(*Yield);
      counter++; 
    }// category loop
  }// selection loop
  w->Print();
  w->writeToFile("data_shapes_workspace_"+TString::Format("BRN%d",BRN_ORDER)+".root");
}
コード例 #22
0
ファイル: templatesSig.C プロジェクト: UAEDF/vbfHbb
void templatesSig(double XMIN,double XMAX,double dX,TString cutstring) {
	gROOT->ForceStyle();
	RooMsgService::instance().setSilentMode(kTRUE);
	for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE);

	const int NMASS(1);
	char name[1000];

	TFile *fVBF[NMASS];//,*fGF[NMASS];
	TH1F  *hVBF[NMASS][5],*hPassVBF;
	int H_MASS[1] = {125};
	TString SELECTION[1] = {"jetPt[0]>80 && jetPt[1]>70"};
	int NCAT[1] = {4};
	int LUMI[1] = {19281};
	int XSEC_VBF[1] = {0.911};

//	TH1F  *hGF[NMASS][5],*hVBF[NMASS][5],*hTOT[NMASS][5],*hPassGF,*hPassVBF;
	RooDataHist *RooHistFit[NMASS][5],*RooHistScaled[NMASS][5];
	RooAddPdf *model[NMASS][5];

	TCanvas *can[NMASS];
	TString PATH("rootfiles/");

	RooWorkspace *w = new RooWorkspace("w","workspace");
	int NBINS   = (XMAX-XMIN)/dX;

	RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
	RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1);
	RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2);
	kJES.setConstant(kTRUE);
	kJER.setConstant(kTRUE);

	TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
	for(int iMass=0;iMass<NMASS;iMass++) {
		cout<<"Mass = "<<H_MASS[iMass]<<" GeV"<<endl;
		int counter(0);
		for(int iSEL=0;iSEL<2;iSEL++) {
//			sprintf(name,"Fit_VBFPowheg%d_sel%s.root",H_MASS[iMass],SELECTION[iSEL].Data());
			sprintf(name,"vbfHbb_uncertainties_JEx.root");
			cout << name << endl;
			fVBF[iMass]  = TFile::Open(PATH+TString(name));
//			hPassVBF = (TH1F*)fVBF[iMass]->Get("TriggerPass");

//			sprintf(name,"Fit_GFPowheg%d_sel%s.root",H_MASS[iMass],SELECTION[iSEL].Data());
//			fGF[iMass]  = TFile::Open(PATH+TString(name)); 
//			hPassGF = (TH1F*)fGF[iMass]->Get("TriggerPass");

			sprintf(name,"HMassTemplate_%d_sel%s",H_MASS[iMass],SELECTION[iSEL].Data());

			can[iMass] = new TCanvas(name,name,1200,800);
			can[iMass]->Divide(2,2);

			for(int icat=0;icat<NCAT[iSEL];icat++) { 
				sprintf(name,"Hbb%d/events",icat);
//				trVBF = (TTree*)fVBF[iMass]->Get(name);
//				trGF  = (TTree*)fGF[iMass]->Get(name);
				can[iMass]->cd(icat+1);
				sprintf(name,"mass_VBF%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				
				hVBF[iMass][icat] = (TH1F*)fVBF[iMass]->Get("histos/VBF125/h_NOM_VBF125_Hbb_mbbReg1;1");//new TH1F(name,name,NBINS,XMIN,XMAX);
//				hVBF[iMass][icat]->Sumw2();
//				TCut cut("puWt[0]*"+TRIG_WT[iSEL]+"*(mva"+SELECTION[iSEL]+">-1)");
//				TCut cut(cutstring.Data());
//				trVBF->Draw(MASS_VAR[iSEL]+">>"+TString(name),cut);

//				sprintf(name,"mass_GF%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
//				hGF[iMass][icat] = new TH1F(name,name,NBINS,XMIN,XMAX);
//				hGF[iMass][icat]->Sumw2();
//				trGF->Draw(MASS_VAR[iSEL]+">>"+TString(name),cut);
//
		//		delete trVBF;
//				delete trGF;
				
				sprintf(name,"roohist_fit_mass%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				RooHistFit[iMass][icat] = new RooDataHist(name,name,x,hVBF[iMass][icat]);
				
//				hGF[iMass][icat]->Scale(LUMI[iSEL]*XSEC_GF[iMass]/hPassGF->GetBinContent(1));
				hVBF[iMass][icat]->Scale(LUMI[iSEL]*XSEC_VBF[iMass]/4794398.);//hPassVBF->GetBinContent(1));

//				sprintf(name,"mass_Total%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				hTOT[iMass][icat] = (TH1F*)hVBF[iMass][icat]->Clone(name);
//				hTOT[iMass][icat]->Add(hGF[iMass][icat]);
				
				sprintf(name,"yield_signalVBF_mass%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar *YieldVBF = new RooRealVar(name,name,hVBF[iMass][icat]->Integral());
        		
				sprintf(name,"roohist_demo_mass%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
		        RooHistScaled[iMass][icat] = new RooDataHist(name,name,x,hTOT[iMass][icat]);

      			sprintf(name,"mean_m%d_CAT%d",H_MASS[iMass],counter);
	        	RooRealVar m(name,name,125,100,150);
	        	sprintf(name,"sigma_m%d_CAT%d",H_MASS[iMass],counter);
	        	RooRealVar s(name,name,12,3,30);

				sprintf(name,"mean_shifted_m%d_CAT%d",H_MASS[iMass],counter);
				RooFormulaVar mShift(name,"@0*@1",RooArgList(m,kJES));
				sprintf(name,"sigma_shifted_m%d_CAT%d",H_MASS[iMass],counter);
				RooFormulaVar sShift(name,"@0*@1",RooArgList(s,kJER)); 
				
				sprintf(name,"alpha_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar a(name,name,1,-10,10);
				sprintf(name,"exp_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar n(name,name,1,0,100);
				
				sprintf(name,"b0_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b0(name,name,0.5,0.,1.);
				sprintf(name,"b1_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b1(name,name,0.5,0.,1.);
				sprintf(name,"b2_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b2(name,name,0.5,0.,1.);
				sprintf(name,"b3_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b3(name,name,0.5,0.,1.);
				
				sprintf(name,"signal_bkg_m%d_CAT%d",H_MASS[iMass],counter);
				RooBernstein bkg(name,name,x,RooArgSet(b0,b1,b2));
				
				sprintf(name,"fsig_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar fsig(name,name,0.7,0.,1.);
				
				sprintf(name,"signal_gauss_m%d_CAT%d",H_MASS[iMass],counter);
				RooCBShape sig(name,name,x,mShift,sShift,a,n);
				
				
				// model(x) = fsig*sig(x) + (1-fsig)*bkg(x)
				sprintf(name,"signal_model_m%d_CAT%d",H_MASS[iMass],counter);
				model[iMass][icat] = new RooAddPdf(name,name,RooArgList(sig,bkg),fsig);
				
				RooFitResult *res = model[iMass][icat]->fitTo(*RooHistFit[iMass][icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");
				//res->Print();
				
				RooPlot* frame = x.frame();
				RooHistScaled[iMass][icat]->plotOn(frame);
				//model[iMass][icat]->plotOn(frame,RooFit::VisualizeError(*res,1,kFALSE),RooFit::FillColor(kGray));
				//RooHist[iMass][icat]->plotOn(frame);
				model[iMass][icat]->plotOn(frame);
				double chi2 = frame->chiSquare(); 
				//model[iMass][icat]->plotOn(frame,RooFit::LineWidth(2));
				model[iMass][icat]->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(2),RooFit::LineStyle(kDashed)); 
				frame->GetXaxis()->SetNdivisions(505); 
				frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
				frame->GetYaxis()->SetTitle("Events");
				frame->Draw();
//				hGF[iMass][icat]->SetFillColor(kGreen-8); 
				hVBF[iMass][icat]->SetFillColor(kRed-10); 
				THStack *hs = new THStack("hs","hs");
//				hs->Add(hGF[iMass][icat]);
				hs->Add(hVBF[iMass][icat]);
				hs->Draw("same hist");
				frame->Draw("same");
				gPad->RedrawAxis();
				
				TF1 *tmp_func = model[iMass][icat]->asTF(x,fsig,x);
				double y0 = tmp_func->GetMaximum();
				double x0 = tmp_func->GetMaximumX();
				double x1 = tmp_func->GetX(y0/2,XMIN,x0);
				double x2 = tmp_func->GetX(y0/2,x0,XMAX);
				double FWHM = x2-x1;
				//cout<<"Int = "<<tmp_func->Integral(XMIN,XMAX)<<", Yield = "<<Yield->getVal()<<", y0 = "<<y0<<", x0 = "<<x0<<", x1 = "<<x1<<", x2 = "<<x2<<", FWHM = "<<FWHM<<endl;
				//delete tmp_func;
				double y1 = dX*0.5*y0*(YieldVBF->getVal()+YieldGF->getVal())/tmp_func->Integral(XMIN,XMAX); 
				TLine *ln = new TLine(x1,y1,x2,y1);
				ln->SetLineColor(kMagenta+3);
				ln->SetLineStyle(7);
				ln->SetLineWidth(2);
				ln->Draw(); 
				
				TLegend *leg = new TLegend(0.65,0.35,0.9,0.45);  
				leg->AddEntry(hVBF[iMass][icat],"VBF","F");
//				leg->AddEntry(hGF[iMass][icat],"GF","F");
				leg->SetFillColor(0);
				leg->SetBorderSize(0);
				leg->SetTextFont(42);
				leg->SetTextSize(0.05);
				leg->Draw("same");
				
				TPaveText *pave = new TPaveText(0.65,0.55,0.9,0.92,"NDC");
				sprintf(name,"M_{H} = %d GeV",H_MASS[iMass]);
				TLegend *leg = new TLegend(0.65,0.35,0.9,0.45);  
				leg->AddEntry(hVBF[iMass][icat],"VBF","F");
//				leg->AddEntry(hGF[iMass][icat],"GF","F");
				leg->SetFillColor(0);
				leg->SetBorderSize(0);
				leg->SetTextFont(42);
				leg->SetTextSize(0.05);
				leg->Draw("same");
				
				TPaveText *pave = new TPaveText(0.65,0.55,0.9,0.92,"NDC");
				sprintf(name,"M_{H} = %d GeV",H_MASS[iMass]);
				pave->AddText(name);
				sprintf(name,"%s selection",SELECTION[iSEL].Data());
				pave->AddText(name);
				sprintf(name,"CAT%d",icat);
				pave->AddText(name);
				sprintf(name,"m = %1.1f #pm %1.1f",m.getVal(),m.getError());
				pave->AddText(name);
				sprintf(name,"#sigma = %1.1f #pm %1.1f",s.getVal(),s.getError());
				pave->AddText(name);
				sprintf(name,"FWHM = %1.2f",FWHM);
				pave->AddText(name);
				/*
				sprintf(name,"a = %1.2f #pm %1.2f",a.getVal(),a.getError());
				pave->AddText(name);
				sprintf(name,"n = %1.2f #pm %1.2f",n.getVal(),n.getError());
				pave->AddText(name);
				sprintf(name,"f = %1.2f #pm %1.2f",fsig.getVal(),fsig.getError());
				pave->AddText(name);
				*/
				pave->SetFillColor(0);
				pave->SetBorderSize(0);
				pave->SetTextFont(42);
				pave->SetTextSize(0.05);
				pave->SetTextColor(kBlue);
				pave->Draw();
				
				b0.setConstant(kTRUE);
				b1.setConstant(kTRUE);
				b2.setConstant(kTRUE);
				b3.setConstant(kTRUE);
				
				//m2.setConstant(kTRUE);
				//s2.setConstant(kTRUE); 
				m.setConstant(kTRUE);
				s.setConstant(kTRUE); 
				a.setConstant(kTRUE);
				n.setConstant(kTRUE);
				fsig.setConstant(kTRUE);
				
				w->import(*model[iMass][icat]);
				w->import(*RooHistScaled[iMass][icat]);
				w->import(*res); 
				w->import(*YieldVBF);   
				w->import(*YieldGF);  
				
				counter++;
			}// categories loop
		}// selection loop 
	}// mass loop
	w->Print();
	//x.Print();
	TString selName = "_";
	selName += XMIN;    
	selName += "-";
	selName += XMAX;
	w->writeToFile("signal_shapes_workspace"+selName+".root");
}
コード例 #23
0
void CreateTemplatesForW(TString CAT, TString CUT)
{
  gROOT->ForceStyle();
  
  RooMsgService::instance().setSilentMode(kTRUE);
  RooMsgService::instance().setStreamStatus(0,kFALSE);
  RooMsgService::instance().setStreamStatus(1,kFALSE);

  TFile *infMC   = TFile::Open("Histo_TT_TuneCUETP8M1_13TeV-powheg-pythia8.root");
  TFile *infData = TFile::Open("Histo_JetHT.root");
    
  TH1F *hMC,*hData;
  RooDataHist *roohMC,*roohData;
  RooAddPdf *signal,*qcd;
  
  TString VAR,TAG;
  float XMIN,XMAX;

  VAR = "mW";
  TAG = CUT+"_"+CAT;
  XMIN = 20.;
  XMAX = 160.;

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

  //---- define observable ------------------------
  RooRealVar *x = new RooRealVar("mW","mW",XMIN,XMAX);
  w->import(*x);
  //---- first do the data template ---------------
  
  hData = (TH1F*)infData->Get("boosted/h_mW_"+CUT+"_0btag");
  hData->Rebin(5);
  roohData = new RooDataHist("roohistData","roohistData",RooArgList(*x),hData);  

  //---- QCD -----------------------------------
  RooRealVar bBkg0("qcd_b0","qcd_b0",0.5,0,1);
  RooRealVar bBkg1("qcd_b1","qcd_b1",0.5,0,1);
  RooRealVar bBkg2("qcd_b2","qcd_b2",0.5,0,1);
  RooRealVar bBkg3("qcd_b3","qcd_b3",0.5,0,1);

  RooBernstein qcd1("qcd_brn","qcd_brn",*x,RooArgList(bBkg0,bBkg1,bBkg2,bBkg3));

  RooRealVar mQCD("qcd_mean2" ,"qcd_mean2",40,0,100);
  RooRealVar sQCD("qcd_sigma2","qcd_sigma2",20,0,50);
  RooGaussian qcd2("qcd_gaus" ,"qcd_gaus",*x,mQCD,sQCD);

  RooRealVar fqcd("qcd_f1","qcd_f1",0.5,0,1);

  qcd = new RooAddPdf("qcd_pdf","qcd_pdf",qcd1,qcd2,fqcd);

  //---- plots ---------------------------------------------------
  TCanvas *canB = new TCanvas("Template_W_QCD_"+CUT+"_"+CAT,"Template_W_QCD_"+CUT+"_"+CAT,900,600);

  RooFitResult *res = qcd->fitTo(*roohData,RooFit::Save());
  res->Print();
  RooPlot *frameB = x->frame();
  roohData->plotOn(frameB);
  qcd->plotOn(frameB);
  qcd->plotOn(frameB,RooFit::Components("qcd_brn"),RooFit::LineColor(kRed),RooFit::LineWidth(2),RooFit::LineStyle(2));
  qcd->plotOn(frameB,RooFit::Components("qcd_gaus"),RooFit::LineColor(kGreen+1),RooFit::LineWidth(2),RooFit::LineStyle(2));
  frameB->GetXaxis()->SetTitle("m_{W} (GeV)");
  frameB->Draw();
  gPad->Update();
  canB->Print("plots/"+TString(canB->GetName())+".pdf");

  RooArgSet *parsQCD = (RooArgSet*)qcd->getParameters(roohData);
  parsQCD->setAttribAll("Constant",true);

  w->import(*qcd);

  //---- then do the signal templates -------------
  hMC = (TH1F*)infMC->Get("boosted/hWt_"+VAR+"_"+TAG);
  roohMC = new RooDataHist("roohistTT","roohistTT",RooArgList(*x),hMC);
  normMC = ((TH1F*)infMC->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();
  hMC->Rebin(2);
      
  RooRealVar m("ttbar_mean","ttbar_mean",90,70,100);
  RooRealVar s("ttbar_sigma","ttbar_sigma",20,0,50);
    
  RooGaussian sig_core("ttbar_core","ttbar_core",*x,m,s);
  
  RooRealVar bSig0("ttbar_b0","ttbar_b0",0.5,0,1);
  RooRealVar bSig1("ttbar_b1","ttbar_b1",0.5,0,1);
  RooRealVar bSig2("ttbar_b2","ttbar_b2",0.5,0,1); 
  RooRealVar bSig3("ttbar_b3","ttbar_b3",0.5,0,1);
  RooRealVar bSig4("ttbar_b4","ttbar_b4",0.5,0,1);
  RooRealVar bSig5("ttbar_b5","ttbar_b5",0.5,0,1); 
  RooRealVar bSig6("ttbar_b6","ttbar_b6",0.5,0,1);
  RooRealVar bSig7("ttbar_b7","ttbar_b7",0.5,0,1);
  RooRealVar bSig8("ttbar_b8","ttbar_b8",0.5,0,1);

  RooBernstein sig_tail("ttbar_tail","ttbar_tail",*x,RooArgList(bSig0,bSig1,bSig2,bSig3,bSig4,bSig5,bSig6,bSig7,bSig8)); 

  RooRealVar fcore("ttbar_fcore","ttbar_fcore",0.5,0,1);

  signal = new RooAddPdf("ttbar_pdf","ttbar_pdf",RooArgList(sig_core,sig_tail),RooArgList(fcore));

  TCanvas *canS = new TCanvas("Template_W_TT_"+CAT+"_"+CUT,"Template_W_TT_"+CAT+"_"+CUT,900,600);

  res = signal->fitTo(*roohMC,RooFit::Save());

  cout<<"mean = "<<m.getVal()<<" +/ "<<m.getError()<<", sigma = "<<s.getVal()<<" +/- "<<s.getError()<<endl;

  //res->Print();
  RooPlot *frameS = x->frame();
  roohMC->plotOn(frameS);
  signal->plotOn(frameS);
  signal->plotOn(frameS,RooFit::Components("ttbar_core"),RooFit::LineColor(kRed),RooFit::LineWidth(2),RooFit::LineStyle(2));
  signal->plotOn(frameS,RooFit::Components("ttbar_tail"),RooFit::LineColor(kGreen+1),RooFit::LineWidth(2),RooFit::LineStyle(2));
  frameS->GetXaxis()->SetTitle("m_{W} (GeV)");
  frameS->Draw();
  gPad->Update();
  canS->Print("plots/"+TString(canS->GetName())+".pdf");

  RooArgSet *parsSig = (RooArgSet*)signal->getParameters(roohMC);
  parsSig->setAttribAll("Constant",true);

  w->import(*signal);
  
  //w->Print();
  w->writeToFile("templates_W_"+CUT+"_"+CAT+"_workspace.root");
}                            
コード例 #24
0
ファイル: buildPdf.C プロジェクト: carlpan/HZZResearch
void buildPdf()
{
    
    Double_t lorange = 100.;
    Double_t hirange = 140.;
    
    // Import data
    TFile *file = new TFile("/atlas/data18a/yupan/HZZ4l2012/MiniTree/data12.root");
    TTree *tree = (TTree*)file->Get("tree_incl_4mu");
    // should include all channels, for now just testing...
    
    // Define variables
    Float_t m4l = 0;
    Float_t m4lerr = 0;
   // Float_t wgt = 0;
    
    // Get number of entries and setbranchaddress
    Int_t nevents = tree->GetEntries();
    
    tree->SetBranchStatus("*",0);
    tree->SetBranchStatus("m4l_unconstrained",1);
    tree->SetBranchStatus("m4lerr_unconstrained",1);
    //tree->SetBranchStatus("weight",1);
    
    tree->SetBranchAddress("m4l_unconstrained",&m4l);
    tree->SetBranchAddress("m4lerr_unconstrained",&m4lerr);
    //tree->SetBranchAddress("weight",&wgt);
    
    ///////////////
    // Build pdfs
    //////////////
    RooRealVar* mass = new RooRealVar("m4l","mass",lorange,hirange,"GeV");
    RooRealVar merr("m4lerr","mass err",0.1,4.0,"GeV");
    //RooRealVar weight("weight","weight",0,10);
    
    RooRealVar scale("scale","per-event error scale factor",1.0,0.2,4.0);
    RooProduct sigmaErr("sigmaErr","sigmaErr",RooArgSet(scale,merr));
   
    /*
    float totalwgt(0);
    for (Int_t i=0; i<nevents; i++) {
        tree->GetEntry(i);
        totalwgt+=wgt;
    }
    std::cout<<"total weight = "<<totalwgt<<std::endl;
   */ 
    /// Make DataSet
    RooDataSet signal("signal","signal",RooArgSet(*mass,merr));
    
    std::cout<<"Reading in events from signal minitree"<<std::endl;
    for (Int_t i=0; i<nevents; i++) {
        tree->GetEntry(i);
        mass->setVal(m4l);
        merr.setVal(m4lerr);
        //weight.setVal(wgt/totalwgt);
        signal.add(RooArgSet(*mass,merr));
    }
    
    // Create 1D kernel estimation for signal mass
    std::cout<<"Building mass keys"<<std::endl;
    RooKeysPdf kestsig("kestsig","kestsig",*mass,signal);
    TH1F* hm = (TH1F*)kestsig.createHistogram("hm",*mass);
    kestsig.fillHistogram(hm,RooArgList(*mass));
    std::cout<<"Building mass pdf"<<std::endl;
    RooDataHist* dmass = new RooDataHist("dmass","binned dataset",*mass,hm);
    RooHistPdf* masspdf = new RooHistPdf("masspdf","pdf(dm)",*mass,*dmass,2);
    
    // Create 1D kernel estimation for mass err
    std::cout<<"Building error keys"<<std::endl;
    RooKeysPdf kestsigerr("kestsigerr","kestsigerr",merr,signal,RooKeysPdf::MirrorBoth,2);
    TH1F* herr = (TH1F*)kestsigerr.createHistogram("herr",merr);
    kestsigerr.fillHistogram(herr,RooArgList(merr));
    std::cout<<"Integral "<<herr->Integral()<<std::endl;
    std::cout<<"Building error pdf"<<std::endl;
    RooDataHist* derr = new RooDataHist("derr","binned dataset",merr,herr);
    RooHistPdf* errpdf = new RooHistPdf("errpdf","pdf(de)",merr,*derr,2);
    
    
    //Make the crystal ball resolution model with CB sigma = mass error
    RooRealVar 	meanCB 	("meanCB",  "mean CB", hmass, hmass-10., hmass+5.);
    RooRealVar 	alphaCB	("alphaCB", "alpha CB", 7, 0., 10.);
    RooRealVar 	nnCB   	("nnCB", "nn CB", 1.5, 0., 15.);
    RooCBShape* shapeCB = new RooCBShape("shapeCB", "crystal ball pdf", *mass, meanCB, sigmaErr, alphaCB, nnCB);

    // Make conditional pdf
    RooProdPdf* sigmodel = new RooProdPdf("sigmodel","sigmodel", *errpdf, Conditional(*shapeCB, *mass));

    
    
    // Make a workspace to store the fit model
    RooWorkspace* pdfWsp = new RooWorkspace("pdfWspCB");
    pdfWsp->import(*sigmodel,RecycleConflictNodes());
    pdfWsp->import(*masspdf);
    pdfWsp->import(*errpdf,RecycleConflictNodes());
    pdfWsp->import(signal);
    pdfWsp->Print();
    pdfWsp->writeToFile("pdfWspCB.root");
    
    
    // Make some plots
    TCanvas *c = new TCanvas("c","c",500,500);
    c->Divide(2);
    RooPlot* frame = merr.frame(Title("keys signal error"));
    signal.plotOn(frame);
    kestsigerr.plotOn(frame,LineColor(kRed));
    errpdf->plotOn(frame);
    
    RooPlot* frame2 = mass->frame(Title("keys signal"));
    signal.plotOn(frame2);
    kestsig.plotOn(frame2,LineColor(kRed));
    masspdf->plotOn(frame2);
    
    c->cd(2);
    frame->Draw();
    c->cd(1);
    grame2->Draw();
    
    c->Print("testPdf.png");
    
    
}
コード例 #25
0
void eregtraining_fixalpha(bool dobarrel, bool doele) {
   
//   gSystem->Setenv("OMP_WAIT_POLICY","PASSIVE");
  
  //candidate to set fixed alpha values (0.9,3.8)
  //TString dirname = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregtesteleJul30_sig5_01_alphafloat5_%i/",int(minevents)); 
  
  TString dirname = "/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);  
  
  std::vector<std::string> *varsf = new std::vector<std::string>;
  varsf->push_back("ph.scrawe");
  varsf->push_back("ph.sceta");
  varsf->push_back("ph.scphi");
  varsf->push_back("ph.r9");  
  varsf->push_back("ph.scetawidth");
  varsf->push_back("ph.scphiwidth");  
  varsf->push_back("ph.scnclusters");
  varsf->push_back("ph.hoveretower");
  varsf->push_back("rho");
  varsf->push_back("nVtx");  
 
  varsf->push_back("ph.etaseed-ph.sceta");
  varsf->push_back("atan2(sin(ph.phiseed-ph.scphi),cos(ph.phiseed-ph.scphi))");
  varsf->push_back("ph.eseed/ph.scrawe");
  
  varsf->push_back("ph.e3x3seed/ph.e5x5seed");
  varsf->push_back("ph.sigietaietaseed");   
  varsf->push_back("ph.sigiphiphiseed");   
  varsf->push_back("ph.covietaiphiseed");
  varsf->push_back("ph.emaxseed/ph.e5x5seed");
  varsf->push_back("ph.e2ndseed/ph.e5x5seed");
  varsf->push_back("ph.etopseed/ph.e5x5seed");
  varsf->push_back("ph.ebottomseed/ph.e5x5seed");
  varsf->push_back("ph.eleftseed/ph.e5x5seed");
  varsf->push_back("ph.erightseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5maxseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5topseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5bottomseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5leftseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5rightseed/ph.e5x5seed");
  
  std::vector<std::string> *varseb = new std::vector<std::string>(*varsf);
  std::vector<std::string> *varsee = new std::vector<std::string>(*varsf);
  
  varseb->push_back("ph.e5x5seed/ph.eseed");
  
  varseb->push_back("ph.ietaseed");
  varseb->push_back("ph.iphiseed");
  varseb->push_back("ph.ietaseed%5");
  varseb->push_back("ph.iphiseed%2");       
  varseb->push_back("(abs(ph.ietaseed)<=25)*(ph.ietaseed%25) + (abs(ph.ietaseed)>25)*((ph.ietaseed-25*abs(ph.ietaseed)/ph.ietaseed)%20)");
  varseb->push_back("ph.iphiseed%20"); 
  varseb->push_back("ph.etacryseed");
  varseb->push_back("ph.phicryseed");

  varsee->push_back("ph.scpse/ph.scrawe");
    
  std::vector<std::string> *varslist;
  if (dobarrel) varslist = varseb;
  else varslist = varsee;
  
  RooArgList vars;
  for (unsigned int ivar=0; ivar<varslist->size(); ++ivar) {
    RooRealVar *var = new RooRealVar(TString::Format("var_%i",ivar),varslist->at(ivar).c_str(),0.);
    vars.addOwned(*var);
  }
  
  RooArgList condvars(vars);
  
//   RooRealVar *tgtvar = new RooRealVar("tgtvar","ph.scrawe/ph.gene",1.);
//   if (!dobarrel) tgtvar->SetTitle("(ph.scrawe + ph.scpse)/ph.gene");
  
  RooRealVar *tgtvar = new RooRealVar("tgtvar","ph.gene/ph.scrawe",1.);
  if (!dobarrel) tgtvar->SetTitle("ph.gene/(ph.scrawe + ph.scpse)");  
  
  //tgtvar->setRange(0.,5.);
  
  vars.addOwned(*tgtvar);


  
  //varstest.add(*tgtvar);
    
  RooRealVar weightvar("weightvar","",1.);

  //TFile *fdin = TFile::Open("/home/mingyang/cms/hist/hgg-2013Moriond/merged/hgg-2013Moriond_s12-diphoj-3-v7a_noskim.root");
//   TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/trainingtreesJul1/hgg-2013Final8TeV_s12-zllm50-v7n_noskim.root");
//   TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
//   TTree *dtree = (TTree*)ddir->Get("hPhotonTreeSingle");    
  
/*  TFile *fdinsig = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/trainingtreesJul1/hgg-2013Moriond_s12-h125gg-gf-v7a_noskim.root");
  TDirectory *ddirsig = (TDirectory*)fdinsig->FindObjectAny("PhotonTreeWriterPreselNoSmear");
  TTree *dtreesig = (TTree*)ddirsig->Get("hPhotonTreeSingle");     */ 
  
  TString treeloc;
  if (doele) {
    treeloc = "RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPreselInvert/PhotonTreeWriterSingleInvert/hPhotonTreeSingle";
  }
  else {
    treeloc = "RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle";
  }

  TChain *tree;
  float xsecs[50];

      
  if (doele) {
    tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPreselInvert/PhotonTreeWriterSingleInvert/hPhotonTreeSingle");
    tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    
    xsecs[0] = 1.;
    initweights(tree,xsecs,1.);      
    
    xsecweights[0] = 1.0;
    
  }
  else {
    tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle");
    tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj20_40-2em-v7n_noskim.root");
    tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj40-2em-v7n_noskim.root");
    
    xsecs[0] = 0.001835*81930.0;
    xsecs[1] = 0.05387*8884.0;    
    initweights(tree,xsecs,1.);  
    
    double weightscale = xsecweights[1];
    xsecweights[0] /= weightscale;
    xsecweights[1] /= weightscale;
  }
  
  
  TCut selcut;
  if (dobarrel) {
    selcut = "ph.genpt>16. && ph.isbarrel && ph.ispromptgen"; 
  }
  else {
    selcut = "ph.genpt>16. && !ph.isbarrel && ph.ispromptgen";     
  }
  

  
  TCut selweight = "xsecweight(procidx)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale50 = "(evt%50==0)";
  TCut prescale100 = "(evt%100==0)";  
  TCut prescale1000 = "(evt%1000==0)";  
  TCut evenevents = "(evt%2==0)";
  TCut oddevents = "(evt%2==1)";
  //TCut oddevents = prescale100; 
  
  //weightvar.SetTitle(prescale10*selcut);
  
/*  new TCanvas;
  tree->Draw("ph.genpt>>hpt(200,0.,100.)",selweight*selcut);

  return;*/  
  
  if (doele) {
    weightvar.SetTitle(evenevents*selcut);
  }
  else {
    weightvar.SetTitle(selweight*selcut);
  }
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",tree,vars,weightvar);   
  
//   weightvar.SetTitle(prescale1000*selcut);
//   RooDataSet *hdatasig = RooTreeConvert::CreateDataSet("hdatasig",dtree,vars,weightvar);   
//   RooDataSet *hdatasigtest = RooTreeConvert::CreateDataSet("hdatasigtest",dtree,varstest,weightvar); 
  
  RooDataSet *hdatasig = 0;
  RooDataSet *hdatasigtest = 0;
  
//   weightvar.SetTitle(prescale10*selcut);
//   RooDataSet *hdatasigsmall = RooTreeConvert::CreateDataSet("hdatasigsmall",dtreesig,vars,weightvar);   
  
  RooRealVar sigwidthtvar("sigwidthtvar","",0.01);
  sigwidthtvar.setConstant(false);
  
  RooRealVar sigmeantvar("sigmeantvar","",1.);
  sigmeantvar.setConstant(false); 

  RooRealVar sigalphavar("sigalphavar","",1.);
  sigalphavar.setConstant(false);   
  
  RooRealVar signvar("signvar","",2.);
  signvar.setConstant(false);     

  RooRealVar sigalpha2var("sigalpha2var","",1.);
  sigalpha2var.setConstant(false);   
  
  RooRealVar sign2var("sign2var","",2.);
  sign2var.setConstant(false);     
  
  
   
  RooArgList tgts;
  RooGBRFunction func("func","",condvars,4);
  RooGBRTarget sigwidtht("sigwidtht","",func,0,sigwidthtvar);
  RooGBRTarget sigmeant("sigmeant","",func,1,sigmeantvar);
  RooGBRTarget signt("signt","",func,2,signvar);
  RooGBRTarget sign2t("sign2t","",func,3,sign2var);
  
  tgts.add(sigwidtht);
  tgts.add(sigmeant);
  tgts.add(signt);
  tgts.add(sign2t);
  
  RooRealConstraint sigwidthlim("sigwidthlim","",sigwidtht,0.0002,0.5);
  RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,0.2,2.0);
  //RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,-2.0,-0.2); 
  
  RooRealConstraint signlim("signlim","",signt,1.01,110.); 

  RooRealConstraint sign2lim("sign2lim","",sign2t,1.01,110.); 
  
  RooLinearVar tgtscaled("tgtscaled","",*tgtvar,sigmeanlim,RooConst(0.));
  
  RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.0),signlim,RooConst(1.0),sign2lim);
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.0),signlim,RooConst(1.0),sign2lim);
  
  //RooCBExp sigpdf("sigpdf","",tgtscaled,RooConst(-1.),sigwidthlim,sigalpha2lim,sign2lim,sigalphalim);
  
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(100.),RooConst(100.),sigalpha2lim,sign2lim);
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim,RooConst(3.),sign2lim);
  //RooCBShape sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim);
  
  RooConstVar etermconst("etermconst","",0.);  
  //RooFormulaVar etermconst("etermconst","","1000.*(@0-1.)*(@0-1.)",RooArgList(tgtscaled));
   
  RooRealVar r("r","",1.);
  r.setConstant();

  std::vector<RooAbsReal*> vpdf;
  vpdf.push_back(&sigpdf);  

  double minweight = 200.;

  std::vector<double> minweights;
  minweights.push_back(minweight);
  
  //ntot.setConstant();

  TFile *fres = new TFile("fres.root","RECREATE");

  if (1) {  
    std::vector<RooAbsData*> vdata;
    vdata.push_back(hdata);    
    
    RooHybridBDTAutoPdf bdtpdfdiff("bdtpdfdiff","",func,tgts,etermconst,r,vdata,vpdf);
    bdtpdfdiff.SetMinCutSignificance(5.);
    bdtpdfdiff.SetPrescaleInit(100);
   // bdtpdfdiff.SetPrescaleInit(10);
    //bdtpdfdiff.SetMaxNSpurious(300.);
    //bdtpdfdiff.SetMaxNSpurious(2400.);
    bdtpdfdiff.SetShrinkage(0.1);
    bdtpdfdiff.SetMinWeights(minweights);
    //bdtpdfdiff.SetMaxNodes(270);
    //bdtpdfdiff.SetMaxNodes(750);
    bdtpdfdiff.SetMaxNodes(500);
    //bdtpdfdiff.SetMaxDepth(8);
    bdtpdfdiff.TrainForest(1e6);  
    
  }   
     
  
  RooWorkspace *wereg = new RooWorkspace("wereg");
  wereg->import(sigpdf);
  
  if (doele && dobarrel)
    wereg->writeToFile("wereg_ele_eb.root");    
  else if (doele && !dobarrel) 
    wereg->writeToFile("wereg_ele_ee.root");    
  else if (!doele && dobarrel)
    wereg->writeToFile("wereg_ph_eb.root");    
  else if (!doele && !dobarrel)
    wereg->writeToFile("wereg_ph_ee.root");    
  
  
  return;
  
  
}
コード例 #26
0
ファイル: fitZee_BWxCB.C プロジェクト: vlambert/ZeeScripts
void fitZee_BWxCB() {
   cout <<  "// ======================================================= //" << endl;
   cout <<  "//                  Setting Program Mode                   //" << endl;
   cout <<  "//                                                         //" << endl;
   cout <<  "//     Auto:  Runs preset text files with file names       //" << endl;
   cout <<  "//            title, output and table  file names          //" << endl;
   cout <<  "//                                                         //" << endl;
   cout <<  "//     User:  Allows user input of individual file,        //" << endl;
   cout <<  "//            title, output, and table file names          //" << endl;
   cout <<  "// ======================================================= //" << endl;
 
  string mode;
  // Prompt User for mode setting
  cout << "Choose Mode (Auto/User):"<<endl;
  getline(cin, mode);
  
  
  // For Auto Mode
  if (mode == "Auto") {
    // Prompt User to choose data set type to select which set of data files to access
    string set;
    cout<< "Choose Data Set Type (tight, mva, mvat, empty): "<<endl;
    getline(cin, set);

    // Line Counters
    Int_t nfile = 0;
    Int_t ntitle = 0;
    Int_t noutput = 0;

    // Lines
    string fline;
    string tline;
    string oline;
    string table;

    // Arrays of Lines
    string files[200];
    string titles[200];
    string outputs[200];

    // Open Files
    string datafiles = "fitfiles/"+ set +"datafiles.txt";
    string titlefiles = "fitfiles/"+ set+"titlefiles.txt";
    string outputfiles = "fitfiles/"+ set+"outputfiles.txt";
    string tablefiles = "fitfiles/"+ set+ "tablefiles.txt";
    ifstream dfiles(datafiles.c_str());
    ifstream tfiles(titlefiles.c_str());
    ifstream ofiles(outputfiles.c_str());
    ifstream Tfiles(tablefiles.c_str());

    // Check that files are open
    if (!dfiles.is_open()){
      cout<<"ERROR: Given data file could not be opened. File does not exist"<<endl;
      exit(1);
    };
    if (!tfiles.is_open()){
      cout<<"ERROR: Given title file could not be opened. File does not exist"<<endl;
      exit(1);
    };
    if (!ofiles.is_open()){
      cout<<"ERROR: Given output file could not be opened. File does not exist"<<endl;
      exit(1);
    };
    if (!Tfiles.is_open()){
      cout<<"ERROR: Given Table file could not be opened. File does not exist"<<endl;
      exit(1);
    };

    // Read Files to Arrays and count number of lines
    while (true){
      getline(dfiles, fline);
      if (dfiles.eof()) {
	break;
      }
      files[nfile] = fline;
      nfile++;
    };
    while (true){
      getline(tfiles, tline);
      if (tfiles.eof()) {
	break;
      }
      titles[ntitle] = tline;
      ntitle++;
    };
    while (true){
      getline(ofiles, oline);
      if (ofiles.eof()) {
	break;
      }
      outputs[noutput] = oline;
      noutput++;
    };
    getline(Tfiles, table);

    // Require all files to have same length
    if (nfile == ntitle && ntitle == noutput) {
      // Define Fit Inputs
      double minMass = 60;
      double maxMass = 120;
      double mean_bw = 91.1876;
      double gamma_bw = 2.4952;
      double cutoff_cb = 1.0;
      const char *plotOpt = "NEU";
      const int nbins = 40;
      string autofile;
      string autoTitle;
      string autooutput;
      char* filename;
      char* FitTitle;
      char* Outfile;

      // Open table file to which LaTeX table formatted lines will be output with fit parameters
      ofstream tablefile(table.c_str());

      //Loop through each of the files and call the fitting program
      for (Int_t j=0; j<nfile;j++) {
	autofile = files[j];
	autoTitle = titles[j];
	autooutput = outputs[j];
	filename = autofile.c_str();
	FitTitle = autoTitle.c_str();
	Outfile = autooutput.c_str();

	// Call the fitting program and output a workspace with a root file of the model and data as well as a pdf of the fit
	RooWorkspace *w = makefit(filename, FitTitle, Outfile, tablefile,  minMass,  maxMass,  mean_bw,  gamma_bw,  cutoff_cb,  plotOpt, nbins);
	w->writeToFile(Form("%s.root", Outfile));
	delete w;
      };

      // Close table file
      tablefile.close();
    };

    // If the files are not the same size call error
    else {
コード例 #27
0
// implementation
void TwoBinInstructional( void ){
  
  // let's time this example
  TStopwatch t;
  t.Start();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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

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

  // inspect workspace
  pWs->Print();

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

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

} // ----- end of tutorial ----------------------------------------
コード例 #28
0
void combinedWorkspace_4WS(const char* name_pbpb_pass="******", const char* name_pbpb_fail="fitresult_pbpb_fail.root", const char* name_pp_pass="******", const char* name_pp_fail="fitresult_pp_fail.root", const char* name_out="fitresult_combo.root", const float systval = 0., const char* subDirName ="wsTest", int nCPU=2){
   // subdir: Directory to save workspaces under currentPATH/CombinedWorkspaces/subDir/

   // set things silent
   gErrorIgnoreLevel=kError;
   RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  
   bool dosyst = (systval > 0.);

   TString nameOut(name_out);
  
   RooWorkspace * ws = test_combine_4WS(name_pbpb_pass, name_pp_pass, name_pbpb_fail, name_pp_fail, false, nCPU);
   RooAbsData * data = ws->data("dOS_DATA");

   RooRealVar* RFrac2Svs1S_PbPbvsPP_P = ws->var("RFrac2Svs1S_PbPbvsPP_P");
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",-10);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",10);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*RFrac2Svs1S_PbPbvsPP_P, *leftEdge, *rightEdge));
   ws->import(step);
   ws->factory( "Uniform::flat(RFrac2Svs1S_PbPbvsPP_P)" );

   // systematics
   if (dosyst) {
     ws->factory( Form("kappa_syst[%f]",systval) );
     ws->factory( "expr::alpha_syst('kappa_syst*beta_syst',kappa_syst,beta_syst[0,-5,5])" );
     ws->factory( "Gaussian::constr_syst(beta_syst,glob_syst[0,-5,5],1)" );
     
     // add systematics into the double ratio
     ws->factory( "expr::RFrac2Svs1S_PbPbvsPP_P_syst('@0+@1',RFrac2Svs1S_PbPbvsPP_P,alpha_syst)" );
     
     // build the pbpb pdf
     RooRealVar* effjpsi_pp_P = (RooRealVar*)ws->var("effjpsi_pp_P");
     RooRealVar* effpsip_pp_P = (RooRealVar*)ws->var("effpsip_pp_P");
     RooRealVar* effjpsi_pp_NP = (RooRealVar*)ws->var("effjpsi_pp_NP");
     Double_t Npsi2SPbPbPass = npsip_pbpb_pass_from_doubleratio_prompt(ws, RooArgList(*effjpsi_pp_P,*effpsip_pp_P,*effjpsi_pp_NP),true); // Create and import N_Psi2S_PbPb_pass_syst
     
     ws->factory( "SUM::pdfMASS_Tot_PbPb_pass_syst(N_Jpsi_PbPb_pass * pdfMASS_Jpsi_PbPb_pass, N_Psi2S_PbPb_pass_syst * pdfMASS_Psi2S_PbPb_pass, N_Bkg_PbPb_pass * pdfMASS_Bkg_PbPb_pass)" );
     ws->factory( "PROD::pdfMASS_Tot_PbPb_pass_constr(pdfMASS_Tot_PbPb_pass_syst,constr_syst)" );
     
     // build the combined pdf
     ws->factory("SIMUL::simPdf_syst_noconstr(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass_syst,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)");
     RooSimultaneous *simPdf = (RooSimultaneous*) ws->pdf("simPdf_syst_noconstr");
     RooGaussian *constr_syst = (RooGaussian*) ws->pdf("constr_syst");
     RooProdPdf *simPdf_constr = new RooProdPdf("simPdf_syst","simPdf_syst",RooArgSet(*simPdf,*constr_syst));
     ws->import(*simPdf_constr);
     
   } else {
      ws->factory("SIMUL::simPdf_syst(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)");
   }

   ws->Print();

   if (dosyst) ws->var("beta_syst")->setConstant(kFALSE);


   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws->var("invMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws->cat("sample"));    
   //  /////////////////////////////////////////////////////////////////////

   if (dosyst) ws->var("glob_syst")->setConstant(true);
   RooArgSet globalObs("global_obs");
   if (dosyst) globalObs.add( *ws->var("glob_syst") );

   // ws->Print();

   RooArgSet poi("poi");
   poi.add( *ws->var("RFrac2Svs1S_PbPbvsPP_P") );



   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   if (dosyst) nuis.add( *ws->var("beta_syst") );

   // set parameters constant
   RooArgSet allVars = ws->allVars();
   TIterator* it = allVars.createIterator();
   RooRealVar *theVar = (RooRealVar*) it->Next();
   while (theVar) {
      TString varname(theVar->GetName());
//      if (varname != "RFrac2Svs1S_PbPbvsPP"
//            && varname != "invMass"
//            && varname != "sample"
//            )
//         theVar->setConstant();
     if ( varname.Contains("f_Jpsi_PP") || varname.Contains("f_Jpsi_PbPb") ||
           varname.Contains("rSigma21_Jpsi_PP") || 
           varname.Contains("m_Jpsi_PP") || varname.Contains("m_Jpsi_PbPb") || 
           varname.Contains("sigma1_Jpsi_PP") || varname.Contains("sigma1_Jpsi_PbPb") || 
           (varname.Contains("lambda")) ||
           (varname.Contains("_fail") && !varname.Contains("RFrac2Svs1S")))
         {
           theVar->setConstant();
         }
      if (varname=="glob_syst"
            || varname=="beta_syst"
         ) {
         cout << varname << endl;
         theVar->setConstant(!dosyst);
      }
      theVar = (RooRealVar*) it->Next();
   }

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


   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) );
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
  
   if (controlPlots)
   {
     RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,1),Title("LL and profileLL in RFrac2Svs1S_PbPbvsPP_P"));
     pNll->plotOn(framepoi,ShiftToZero());
     framepoi->SetMinimum(0);
     framepoi->SetMaximum(10);
     TCanvas *cpoi = new TCanvas();
     cpoi->cd(); framepoi->Draw();
     cpoi->SaveAs("cpoi.pdf");
   }
  
   ((RooRealVar *)poi.first())->setMin(0.);
   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);
  
   if (controlPlots)
   {
     RooPlot* xframeSB_PP_pass = pObs->frame(Title("SBhypo_PP_pass"));
     data->plotOn(xframeSB_PP_pass,Cut("sample==sample::PP_pass"));
     RooAbsPdf *pdfSB_PP_pass = sbHypo.GetPdf();
     RooCategory *sample = ws->cat("sample");
     pdfSB_PP_pass->plotOn(xframeSB_PP_pass,Slice(*sample,"PP_pass"),ProjWData(*sample,*data));
     TCanvas *c1 = new TCanvas();
     c1->cd(); xframeSB_PP_pass->Draw();
     c1->SaveAs("c1.pdf");
    
     RooPlot* xframeSB_PP_fail = pObs->frame(Title("SBhypo_PP_fail"));
     data->plotOn(xframeSB_PP_fail,Cut("sample==sample::PP_fail"));
     RooAbsPdf *pdfSB_PP_fail = sbHypo.GetPdf();
     pdfSB_PP_fail->plotOn(xframeSB_PP_fail,Slice(*sample,"PP_fail"),ProjWData(*sample,*data));
     TCanvas *c2 = new TCanvas();
     c2->cd(); xframeSB_PP_fail->Draw();
     c2->SaveAs("c1.pdf");
    
     RooPlot* xframeB_PbPb_pass = pObs->frame(Title("SBhypo_PbPb_pass"));
     data->plotOn(xframeB_PbPb_pass,Cut("sample==sample::PbPb_pass"));
     RooAbsPdf *pdfB_PbPb_pass = sbHypo.GetPdf();
     pdfB_PbPb_pass->plotOn(xframeB_PbPb_pass,Slice(*sample,"PbPb_pass"),ProjWData(*sample,*data));
     TCanvas *c3 = new TCanvas();
     c3->cd(); xframeB_PbPb_pass->Draw();
     c3->SetLogy();
     c3->SaveAs("c2.pdf");
    
     RooPlot* xframeB_PbPb_fail = pObs->frame(Title("SBhypo_PbPb_fail"));
     data->plotOn(xframeB_PbPb_fail,Cut("sample==sample::PbPb_fail"));
     RooAbsPdf *pdfB_PbPb_fail = sbHypo.GetPdf();
     pdfB_PbPb_fail->plotOn(xframeB_PbPb_fail,Slice(*sample,"PbPb_fail"),ProjWData(*sample,*data));
     TCanvas *c4 = new TCanvas();
     c4->cd(); xframeB_PbPb_fail->Draw();
     c4->SetLogy();
     c4->SaveAs("c2.pdf");
   }
  
   delete pNll;
   delete pPoiAndNuisance;
   ws->import( sbHypo );
  
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) );
   // RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   RooAbsReal * pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   ((RooRealVar *)poi.first())->setVal( 0 );  // set RFrac2Svs1S_PbPbvsPP=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);


   delete pNll;
   delete pPoiAndNuisance;

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

   // save workspace to file
   string mainDIR = gSystem->ExpandPathName(gSystem->pwd());
   string wsDIR = mainDIR + "/CombinedWorkspaces/";
   string ssubDirName="";
   if (subDirName) ssubDirName.append(subDirName);
   string subDIR = wsDIR + ssubDirName;
  
   void * dirp = gSystem->OpenDirectory(wsDIR.c_str());
   if (dirp) gSystem->FreeDirectory(dirp);
   else gSystem->mkdir(wsDIR.c_str(), kTRUE);

   void * dirq = gSystem->OpenDirectory(subDIR.c_str());
   if (dirq) gSystem->FreeDirectory(dirq);
   else gSystem->mkdir(subDIR.c_str(), kTRUE);
  
   const char* saveName = Form("%s/%s",subDIR.c_str(),nameOut.Data());
   ws->writeToFile(saveName);
}
コード例 #29
0
/*
 * Prepares the workspace to be used by the hypothesis test calculator
 */
void workspace_preparer(char *signal_file_name, char *signal_hist_name_in_file, char *background_file_name, char *background_hist_name_in_file, char *data_file_name, char *data_hist_name_in_file, char *config_file) {

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

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

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

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

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

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



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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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


    //Set Nuisnaces

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

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


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

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


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

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


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

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

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


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

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

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


} // ----- end of tutorial ----------------------------------------
コード例 #30
0
ファイル: fitZraw.C プロジェクト: sixie/CITHZZ
void fitZraw() {
  // ======================================================= //
  //                  Setting Program Mode                   //
  //                                                         //
  //     Auto:  Runs preset text files with file names       //
  //            title and output file names                  //
  //                                                         //
  //     User:  Allows user input of individual file,        //
  //            title and output file names                  //
  // ======================================================= //
  string mode;
  cout << "Choose Mode (Auto/User):"<<endl;
  getline(cin, mode);

  // Declaring tablefile
  ofstream tablefile;

  // For Auto Mode
  if (mode == "Auto") {
    // Line Counters
    string set;
    cout<< "Choose Data Set (tight, mva, mvat, NULL)"<<endl;
    getline(cin, set);
    Int_t nfile = 0;
    Int_t ntitle = 0;
    Int_t noutput = 0;
    // Lines
    string fline;
    string tline;
    string oline;
    string table;
    // Arrays of Lines
    string files[200];
    string titles[200];
    string outputs[200];
    // Open Files
    string datafiles = "fitfiles/"+ set +"datafiles.txt";
    string titlefiles = "fitfiles/"+ set+"titlefiles.txt";
    string outputfiles = "fitfiles/"+ set+"outputfiles.txt";
    string tablefiles = "fitfiles/"+ set+ "tablefiles.txt";
    ifstream dfiles(datafiles.c_str());
    ifstream tfiles(titlefiles.c_str());
    ifstream ofiles(outputfiles.c_str());
    ifstream Tfiles(tablefiles.c_str());

    // Check that files are open
    if (!dfiles.is_open()){
      cout<<"ERROR: Given data file could not be opened. File does not exist"<<endl;
      exit(1);
    }
    if (!tfiles.is_open()){
      cout<<"ERROR: Given title file could not be opened. File does not exist"<<endl;
      exit(1);
    }
    if (!ofiles.is_open()){
      cout<<"ERROR: Given output file could not be opened. File does not exist"<<endl;
      exit(1);
    }
    if (!Tfiles.is_open()){
      cout<<"ERROR: Given Table file could not be opened. File does not exist"<<endl;
      exit(1);
    }

    // Read Files to Arrays and count number of lines
    while (true){
      getline(dfiles, fline);
      if (dfiles.eof()) {
	break;
      }
      files[nfile] = fline;
      nfile++;
    }
    while (true){
      getline(tfiles, tline);
      if (tfiles.eof()) {
	break;
      }
      titles[ntitle] = tline;
      ntitle++;
    }
    while (true){
      getline(ofiles, oline);
      if (ofiles.eof()) {
	break;
      }
      outputs[noutput] = oline;
      noutput++;
    }
    getline(Tfiles, table);
    cout<<ntitle<<endl;
    cout<<nfile<<endl;
    cout<<noutput<<endl;
    // Require all files to have same length
    if (nfile == ntitle && ntitle == noutput) {
      // Define Fit Inputs
      double minMass = 60;
      double maxMass = 120;
      double mean_bw = 91.1876;
      double gamma_bw = 2.4952;
      double cutoff_cb = 1.0;
      const char *plotOpt = "NEU";
      const int nbins = 40;
      string autofile;
      string autoTitle;
      string autooutput;
      char* filename;
      char* FitTitle;
      char* Outfile;
      tablefile.open(table.c_str());
      //Loop through each of the files and call the fitting program
      for (Int_t j=0; j<nfile;j++) {
	autofile = files[j];
	autoTitle = titles[j];
	autooutput = outputs[j];
	filename = (char*) autofile.c_str();
	FitTitle = (char*) autoTitle.c_str();
	Outfile = (char*) autooutput.c_str();
	// Call the fitting program and output a workspace with a root file
	// of the model and data as well as a pdf of the fit
	RooWorkspace *w = makefit(filename, FitTitle, Outfile, minMass,  maxMass,  mean_bw,  gamma_bw,  cutoff_cb,  plotOpt, nbins);
	w->writeToFile(Form("%s.root", Outfile));
	delete w;
      }
      tablefile.close();
    } else {
      cout<<"ERROR: File Sizes Disagree"<<endl;
    }
  }

  // For Interactive User mode:
  if (mode == "User") { 
    // Choose the File Name, Title and Output File for Fit
    string file;
    cout << "Enter File Name:"<<endl;
    getline(cin, file);
    string Title;
    cout << "Enter Fit Title"<<endl;
    getline(cin, Title);
    string output;
    cout << "Enter Output File Name"<<endl;
    getline(cin, output);
    string table;
    cout << "Enter Table File Name"<<endl;
    getline(cin, table);
    char* filename = (char*) file.c_str();
    char* FitTitle = (char*) Title.c_str();
    char* Outfile = (char*) output.c_str();
    tablefile.open(table.c_str());
    // Define Fit Inputs and Call Fit
    double minMass = 60;
    double maxMass = 120;
    double mean_bw = 91.1876;
    double gamma_bw = 2.4952;
    double cutoff_cb = 1.0;
    const char *plotOpt = "NEU";
    const int nbins = 40;
    // Call the fitting program and output a workspace with a root file
    // of the model and data as well as a pdf of the fit
    RooWorkspace *w =  makefit(filename, FitTitle, Outfile, minMass,  maxMass,  mean_bw,  gamma_bw,  cutoff_cb,  plotOpt, nbins);
    w->writeToFile(Form("%s.root", Outfile));
    delete w;
  }  
  tablefile.close();
}