pair<double,double> datEvents(RooWorkspace *work, int m_hyp, int cat, bool spin=false){
  
  vector<double> result;
  RooDataSet *data = (RooDataSet*)work->data(Form("data_mass_cat%d",cat));
  double evs = data->numEntries();
  double evsPerGev;
  if (!spin) evsPerGev = data->sumEntries(Form("CMS_hgg_mass>=%4.1f && CMS_hgg_mass<%4.1f",double(m_hyp)-0.5,double(m_hyp)+0.5));
  else evsPerGev = data->sumEntries(Form("mass>=%4.1f && mass<%4.1f",double(m_hyp)-0.5,double(m_hyp)+0.5));
  return pair<double,double>(evs,evsPerGev);
}
예제 #2
0
void FitterUtils::PlotShape2D(RooDataSet& originDataSet, RooDataSet& genDataSet, RooAbsPdf& shape, string plotsfile, string canvName, RooRealVar& B_plus_M, RooRealVar& misPT)
{
   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");

   //**************Plot Signal Zero Gamma

   TH2F* th2fKey = (TH2F*)shape.createHistogram("th2Shape", B_plus_M, Binning(20), YVar(misPT, Binning(20)));
   cout<<genDataSet.sumEntries()<<endl;
   TH2F* th2fGen = (TH2F*)genDataSet.createHistogram("th2fGen", B_plus_M, Binning(20), YVar(misPT, Binning(20)));

   RooPlot* plotM = B_plus_M.frame();
   originDataSet.plotOn(plotM);
   shape.plotOn(plotM);

   RooPlot* plotMisPT = misPT.frame();
   originDataSet.plotOn(plotMisPT);
   shape.plotOn(plotMisPT);

   TCanvas canv(canvName.c_str(), canvName.c_str(), 800, 800);
   canv.Divide(2,2);
   canv.cd(1); th2fGen->Draw("lego");
   canv.cd(2); th2fKey->Draw("surf");
   canv.cd(3); plotM->Draw();
   canv.cd(4); plotMisPT->Draw();

   canv.Write();

   f2.Close();
}
예제 #3
0
void reweight_eta_1d(TH1F* weight_eta,TH1F* weight_etao,TH2F*weight_etan,TH2F* weight_eta2o,TH2F* weight_etanr,TH2F*weight_eta2,RooDataSet **dset, RooDataSet *dsetdestination, int numvar){

  if (!(*dset)) return;

  TH1F *hnum = new TH1F("hnum","hnum",n_etabins_forreweighting,etabins_forreweighting);
 TH1F *hden = new TH1F("hden","hden",n_etabins_forreweighting,etabins_forreweighting);
//  TH1F *hnum = new TH1F("hnum","hnum",25,0.,2.5);
//  TH1F *hden = new TH1F("hden","hden",25,0.,2.5);
  hnum->Sumw2();
  hden->Sumw2();

  const char* etaname=Form("rooeta%d",numvar);

  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue(etaname)),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue(etaname)),dsetdestination->store()->weight(i));
  }
  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());

  hnum->Divide(hden);
  TH1F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_etarew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float eta = args.getRealValue(etaname);
    float neww = oldw*h->GetBinContent(h->FindBin(fabs(eta)));
    if(debug){ 
		weight_eta->Fill(neww);	
		weight_etao->Fill(oldw);
		weight_etan->Fill(h->FindBin(fabs(eta)),neww);	
		weight_eta2o->Fill(h->FindBin(fabs(eta)),oldw);
		if(oldw!=0 && neww!=0)weight_etanr->Fill(h->FindBin(fabs(eta)),oldw/neww);
		else {weight_etanr->Fill(-10,1);}
	   // weight_pt2->Fill(pt,neww/oldw);
	   if(oldw!=0 && neww!=0)weight_eta2->Fill(fabs(eta),oldw/neww);
	   else {weight_eta2->Fill(-10,1);}
	}  
	  newdset->add(args,neww);
	  
	  }


  newdset->SetName((*dset)->GetName());
  newdset->SetTitle((*dset)->GetTitle());
  delete hnum; delete hden;

  RooDataSet *old_dset = *dset;
  *dset=newdset;
  std::cout << "Eta 1d rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;

  delete old_dset;

};
예제 #4
0
void MakeSpinPlots::DrawSpinBackground(TString tag, TString mcName,bool signal){
  bool drawSM = (smName!="" && smName!=mcName);

  TCanvas cv;
  double thisN  = ws->data(mcName+"_Combined")->reduce(TString("evtcat==evtcat::")+tag)->sumEntries();
  float norm = thisN; //607*lumi/12.*thisN/(totEB+totEE);
  cout << norm <<endl;
  if(signal) norm = ws->data(Form("Data_%s_%s_sigWeight",tag.Data(),mcName.Data()))->sumEntries();
  RooPlot *frame = ws->var("cosT")->frame(0,1,5);

  RooDataSet* bkgWeight = (RooDataSet*)ws->data(Form("Data_%s_%s_bkgWeight",tag.Data(),mcName.Data()));
  RooDataSet* tmp = (RooDataSet*)ws->data("Data_Combined")->reduce(TString("((mass>115 && mass<120) || (mass>130 && mass<135)) && evtcat==evtcat::")+tag);
  tmp->plotOn(frame,RooFit::Rescale(norm/tmp->sumEntries()));
  cout << "b" <<endl;
  ws->pdf(Form("%s_FIT_%s_cosTpdf",mcName.Data(),tag.Data()))->plotOn(frame,RooFit::LineColor(kGreen),RooFit::Normalization(norm/tmp->sumEntries()));
  if(drawSM) ws->pdf(Form("%s_FIT_%s_cosTpdf",smName.Data(),tag.Data()))->plotOn(frame,RooFit::LineColor(kRed),RooFit::Normalization(norm/tmp->sumEntries()));
  cout << "c   " <<bkgWeight <<endl;

  bkgWeight->plotOn(frame,RooFit::Rescale(norm/bkgWeight->sumEntries()),RooFit::MarkerColor(kBlue) );  
  if(signal){
    cout << "d" <<endl;
      
    ws->data(Form("Data_%s_%s_sigWeight",tag.Data(),mcName.Data()))->plotOn(frame,RooFit::MarkerStyle(4));
  }
  cout << "d" <<endl;
  
  frame->SetMaximum(frame->GetMaximum()*(signal?0.8:0.4)*norm/tmp->sumEntries());
  frame->SetMinimum(-1*frame->GetMaximum());
  TLegend l(0.6,0.2,0.95,0.45);
  l.SetFillColor(0);
  l.SetBorderSize(0);
  l.SetHeader(tag);
  l.AddEntry(frame->getObject(0),"Data m#in [115,120]#cup[130,135]","p");
  l.AddEntry(frame->getObject(1),mcName,"l");
  if(drawSM) l.AddEntry(frame->getObject(2),"SM Higgs","l");
  l.AddEntry(frame->getObject(2+drawSM),"background weighted Data","p");
  if(signal) l.AddEntry(frame->getObject(3+drawSM),"signal weighted Data","p");

  cout << "e" <<endl;

  frame->Draw();
  l.Draw("SAME");
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_%s%s_%s_%s.png",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data(),tag.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/C/CosThetaDist_%s%s_%s_%s.C",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data(),tag.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_%s%s_%s_%s.pdf",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data(),tag.Data()) );
}
예제 #5
0
void reweight_pt_1d(TH1F* weight_pt, TH1F* weight_pto,TH2F*weight_ptn,TH2F*weight_pt2o,TH2F* weight_ptnr, TH2F* weight_pt2,RooDataSet **dset, RooDataSet *dsetdestination, int numvar){

  if (!(*dset)) return;
///numerator and denominator
  TH1F *hnum = new TH1F("hnum","hnum",n_ptbins_forreweighting,ptbins_forreweighting);
  TH1F *hden = new TH1F("hden","hden",n_ptbins_forreweighting,ptbins_forreweighting);
  hnum->Sumw2();
  hden->Sumw2();

  const char* ptname=Form("roopt%d",numvar);
// RooAbsData->get*() Load a given row of data
 //getRealValue Get value of a RooAbsReal stored in set with given name. If none is found, value of defVal is returned.
  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue(ptname)),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue(ptname)),dsetdestination->store()->weight(i));
  }
  
 //normalize to one 
  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());
  hnum->Divide(hden);
  TH1F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_ptrew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float pt = args.getRealValue(ptname);
    float neww = oldw*h->GetBinContent(h->FindBin(fabs(pt)));
    if(debug){
		weight_pt->Fill(neww);	
		weight_pto->Fill(oldw);
		weight_pt2o->Fill(h->FindBin(fabs(pt)),oldw);
		weight_ptn->Fill(h->FindBin(fabs(pt)),neww);	
		if(oldw!=0 && neww!=0)weight_ptnr->Fill(h->FindBin(fabs(pt)),oldw/neww);
		else {weight_ptnr->Fill(-10,1);}
		if(oldw!=0 && neww!=0)weight_pt2->Fill(pt,oldw/neww);
		else {weight_pt2->Fill(-10,1);}
     }
	 newdset->add(args,neww);
  }

  newdset->SetName((*dset)->GetName());
  newdset->SetTitle((*dset)->GetTitle());
  delete hnum; delete hden;

  RooDataSet *old_dset = *dset;
  *dset=newdset;
  std::cout << "Pt 1d rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;
  delete old_dset;
};
예제 #6
0
//2d reweighting of rho and its sigma
void reweight_rhosigma(TH1F* weight_rho, TH1F* weight_rhoo,TH2F*weight_rhon,TH2F*weight_rho2o,TH2F* weight_rhonr, TH2F* weight_rho2,TH2F*weight_sigman,TH2F*weight_sigma2o,TH2F* weight_sigmanr, TH2F* weight_sigma2,RooDataSet **dset, RooDataSet *dsetdestination, bool deleteold){
  if (!(*dset)) return;
//  TH2F *hnum = new TH2F("hnum","hnum",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
//  TH2F *hden = new TH2F("hden","hden",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
  TH2F *hnum = new TH2F("hnum","hnum",100,0,100,20,0,20);
  TH2F *hden = new TH2F("hden","hden",100,0,100,20,0,20);
  hnum->Sumw2();
  hden->Sumw2();
  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue("roorho")),fabs((*dset)->get(i)->getRealValue("roosigma")),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue("roorho")),fabs(dsetdestination->get(i)->getRealValue("roosigma")),dsetdestination->store()->weight(i));
  }

  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());
//data/MC
  hnum->Divide(hden);
  TH2F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_rhosigmarew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float rho = args.getRealValue("roorho");
    float sigma = args.getRealValue("roosigma");
    float neww = oldw*h->GetBinContent(h->FindBin(rho,sigma));
	if(debug){
		weight_rho->Fill(neww);
		weight_rhoo->Fill(oldw);
		weight_rho2o->Fill(h->GetXaxis()->FindBin(rho),oldw);	
		weight_rhon->Fill(h->GetXaxis()->FindBin(rho),neww);	
		if(oldw!=0)weight_rhonr->Fill(h->GetXaxis()->FindBin(rho),oldw/neww);
		else {weight_rhonr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_rho2->Fill(rho,oldw/neww);
		weight_sigma2o->Fill(h->GetYaxis()->FindBin(sigma),oldw);	
		weight_sigman->Fill(h->GetYaxis()->FindBin(sigma),neww);	
		if(oldw!=0)weight_sigmanr->Fill(h->GetYaxis()->FindBin(sigma),oldw/neww);
		else {weight_sigmanr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_sigma2->Fill(sigma,oldw/neww);
	}
		newdset->add(args,neww);
	  }
	  newdset->SetName((*dset)->GetName());
	  newdset->SetTitle((*dset)->GetTitle());
	  delete hnum; delete hden;
	  RooDataSet *old_dset = *dset;
	  *dset=newdset;
	  std::cout << "RhoSigma2D rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;
	  if (deleteold) delete old_dset;
	};
예제 #7
0
void MakeSpinPlots::DrawSpinSubTotBackground(TString mcName,bool signal){
  bool drawSM = (smName!="" && smName!=mcName);

  TCanvas cv;
  double thisN  = ws->data(mcName+"_Combined")->sumEntries();
  float norm = thisN;


  if(signal) norm = ws->var(Form("Data_%s_FULLFIT_Nsig",mcName.Data()))->getVal();
  RooPlot *frame = ws->var("cosT")->frame(0,1,10);

  RooDataSet* tmp = (RooDataSet*)ws->data(Form("Data_Combined"))->reduce("(mass>115 && mass<120) || (mass>130 && mass<135)");
  tmp->plotOn(frame,RooFit::Rescale(norm/tmp->sumEntries()));

  ws->pdf(Form("%s_FIT_cosTpdf",mcName.Data()))->plotOn(frame,RooFit::LineColor(kGreen),RooFit::Normalization(norm/tmp->sumEntries()));
  if(drawSM)  ws->pdf(Form("%s_FIT_cosTpdf",smName.Data()))->plotOn(frame,RooFit::LineColor(kRed),RooFit::Normalization(norm/tmp->sumEntries()));
  if(signal){
    RooDataHist *h = (RooDataHist*)ws->data( Form("Data_%s_Combined_bkgSub_cosT",mcName.Data()) );
    h->plotOn(frame,RooFit::MarkerStyle(4));
    std::cout << "Nsig: " << h->sumEntries() << std::endl;
  }

  
  frame->SetMaximum(frame->GetMaximum()*(signal?2.:1.2)*norm/tmp->sumEntries());
  frame->SetMinimum(-1*frame->GetMaximum());
  TLegend l(0.6,0.2,0.95,0.45);
  l.SetFillColor(0);
  l.SetBorderSize(0);
  l.SetHeader("Combined");
  l.AddEntry(frame->getObject(0),"Data m#in [115,120]#cup[130,135]","p");
  l.AddEntry(frame->getObject(1),mcName,"l");
  if(drawSM) l.AddEntry(frame->getObject(2),"SM Higgs","l");
  if(signal) l.AddEntry(frame->getObject(2+drawSM),"bkg-subtracted Data","p");
  
  frame->Draw();
  l.Draw("SAME");
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_SimpleSub_%s%s_%s.png",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/C/CosThetaDist_SimpleSub_%s%s_%s.C",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data()) );
  cv.SaveAs( basePath+Form("/cosThetaPlots/CosThetaDist_SimpleSub_%s%s_%s.pdf",outputTag.Data(),(signal ? "":"_BLIND"),mcName.Data()) );
}
vector<double> sigEvents(RooWorkspace *work, int m_hyp, int cat, string altSigFileName, int spin=false){

  RooWorkspace *tempWork;
  if (altSigFileName!=""){
    TFile *temp = TFile::Open(altSigFileName.c_str());
    tempWork = (RooWorkspace*)temp->Get("cms_hgg_workspace");
  }
  else {
    tempWork = work;
  }
  vector<double> result;
  RooDataSet *ggh = (RooDataSet*)tempWork->data(Form("sig_ggh_mass_m%d_cat%d",m_hyp,cat));
  RooDataSet *vbf = (RooDataSet*)tempWork->data(Form("sig_vbf_mass_m%d_cat%d",m_hyp,cat));
  RooDataSet *wzh = (RooDataSet*)tempWork->data(Form("sig_wzh_mass_m%d_cat%d",m_hyp,cat));
  RooDataSet *tth = (RooDataSet*)tempWork->data(Form("sig_tth_mass_m%d_cat%d",m_hyp,cat));
  
  double total;
  if (!spin) {
    total = ggh->sumEntries()+vbf->sumEntries()+wzh->sumEntries()+tth->sumEntries();
    result.push_back(total);
    result.push_back(100*ggh->sumEntries()/total);
    result.push_back(100*vbf->sumEntries()/total);
    result.push_back(100*wzh->sumEntries()/total);
    result.push_back(100*tth->sumEntries()/total);
  }
  else {
    ggh = (RooDataSet*)tempWork->data(Form("sig_mass_m%d_cat%d",m_hyp,cat));
    total = ggh->sumEntries();
    result.push_back(total);
    result.push_back(100.);
    result.push_back(0.);
    result.push_back(0.);
    result.push_back(0.);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	OptionParser(argc,argv);
	

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


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

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

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

              if (datahist) {
	            string zhname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"zh\")",datahist->GetName())); 
	            string whname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"wh\")",datahist->GetName())); 
              RooDataHist *datahistZH = (RooDataHist*) datahist->emptyClone(zhname.c_str(),zhname.c_str());
              RooDataHist *datahistWH = (RooDataHist*) datahist->emptyClone(whname.c_str(),whname.c_str());
                TRandom3 r;
                r.Rndm();
                double x[datahist->numEntries()];
                r.RndmArray(datahist->numEntries(),x);
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistWH->add(*(datahist->get(j)),datahist->weight()*wFrac);
                    datahistZH->add(*(datahist->get(j)),datahist->weight()*zFrac);
                }
              float w =datahistWH->sumEntries();
              float z =datahistZH->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "WH       datahist " << *datahistWH <<std::endl;
              std::cout << "ZH       datahist " << *datahistZH <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : WH " << w/(w+z) <<",   ZH "<< z/(w+z) << std::endl;
              std::cout << "WH fraction (exp) : WH " << wFrac <<",   ZH "<< zFrac << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistWH);
               outWS->import(*datahistZH);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
예제 #11
0
void FitterUtils::prepare_PDFs(string trigStr, string BDTVar, double BDTcut,
      string signalfile, string partrecofile, string combfile, string JpsiLeakfile,
      double minBMass, double maxBMass,
      string signaltree, string partrecotree, string combtree, string JpsiLeaktree)
{


   //***********Get the datasets
   TFile* fSignal = new TFile(signalfile.c_str());
   TTree* tSignal = (TTree*)fSignal->Get(signaltree.c_str());
   TFile* fPartReco = new TFile(partrecofile.c_str());
   TTree* tPartReco = (TTree*)fPartReco->Get(partrecotree.c_str());
   TFile* fComb = new TFile(combfile.c_str());
   TTree* tComb = (TTree*)fComb->Get(combtree.c_str()); 
   TFile* fJpsiLeak = new TFile(JpsiLeakfile.c_str());
   TTree* tJpsiLeak = (TTree*)fJpsiLeak->Get(JpsiLeaktree.c_str()); 


   //**********Define variables
   RooRealVar trigVar(trigStr.c_str(), trigStr.c_str(), -10, 10);
   RooRealVar BDTRooRealVar(BDTVar.c_str(), BDTVar.c_str(), -1,1);
   RooRealVar B_plus_M("B_plus_M", "M_{visible}", minBMass, maxBMass, "MeV");
   RooRealVar misPT("misPT", "p_{#perp}", 0, 5000, "MeV");
   RooRealVar B_plus_DTFM_M_zero("B_plus_DTFM_M_zero", "M_{constr}", 0, 20000, "MeV"); 
   RooRealVar e_plus_BremMultiplicity("e_plus_BremMultiplicity","e_plus_BremMultiplicity", -1,2);
   RooRealVar e_minus_BremMultiplicity("e_minus_BremMultiplicity","e_minus_BremMultiplicity", -1,2);

   RooRealVar weightPartReco("weightPartReco", "weightPartReco", 0, 10);
   RooRealVar weightLeakage("weightLeakage", "weightLeakage", 0, 10);
   RooRealVar dataMCWeightee("DataMCWeightee", "DataMCWeightee",0, 30);


   //***********Set only variables needed

   tSignal->SetBranchStatus("*", 0); tSignal->SetBranchStatus("B_plus_M", 1); tSignal->SetBranchStatus("misPT", 1); tSignal->SetBranchStatus("B_plus_DTFM_M_zero", 1); tSignal->SetBranchStatus(BDTVar.c_str(),1);
   tSignal->SetBranchStatus("e_plus_BremMultiplicity", 1); tSignal->SetBranchStatus("e_minus_BremMultiplicity", 1); tSignal->SetBranchStatus(trigStr.c_str()); tSignal->SetBranchStatus("DataMCWeightee",1);

   tPartReco->SetBranchStatus("*", 0); tPartReco->SetBranchStatus("B_plus_M", 1); tPartReco->SetBranchStatus("misPT", 1); tPartReco->SetBranchStatus("B_plus_DTFM_M_zero", 1);tPartReco->SetBranchStatus(BDTVar.c_str(),1);
   tPartReco->SetBranchStatus("e_plus_BremMultiplicity", 1); tPartReco->SetBranchStatus("e_minus_BremMultiplicity", 1); tPartReco->SetBranchStatus(trigStr.c_str()); tPartReco->SetBranchStatus("weightPartReco",1);

   tComb->SetBranchStatus("*", 0); tComb->SetBranchStatus("B_plus_M", 1); tComb->SetBranchStatus("misPT", 1); tComb->SetBranchStatus("B_plus_DTFM_M_zero", 1);tComb->SetBranchStatus(BDTVar.c_str(),1);
   tComb->SetBranchStatus("e_plus_BremMultiplicity", 1); tComb->SetBranchStatus("e_minus_BremMultiplicity", 1); tComb->SetBranchStatus(trigStr.c_str());

   tJpsiLeak->SetBranchStatus("*", 0); tJpsiLeak->SetBranchStatus("B_plus_M", 1); tJpsiLeak->SetBranchStatus("misPT", 1); 
   tJpsiLeak->SetBranchStatus("B_plus_DTFM_M_zero", 1);tJpsiLeak->SetBranchStatus(BDTVar.c_str(),1);
   tJpsiLeak->SetBranchStatus("e_plus_BremMultiplicity", 1); tJpsiLeak->SetBranchStatus("e_minus_BremMultiplicity", 1); tJpsiLeak->SetBranchStatus(trigStr.c_str()); 
   tJpsiLeak->SetBranchStatus("weightLeakage",1);


   //***********Set Binning


   RooBinning defaultMBins(floor((maxBMass-minBMass)/(40.)), B_plus_M.getMin(), B_plus_M.getMax() ); 
   RooBinning defaultMisPTBins(floor(40), misPT.getMin(), misPT.getMax()); 
   RooBinning broaderMBins(floor((maxBMass-minBMass)/(80.)), B_plus_M.getMin(), B_plus_M.getMax()); 
   RooBinning broaderMisPTBins(floor(40), misPT.getMin(), misPT.getMax()); 

   B_plus_M.setBinning( defaultMBins);
   misPT.setBinning( defaultMisPTBins );
   B_plus_M.setBinning( broaderMBins, "broaderBins");
   misPT.setBinning( broaderMisPTBins, "broaderBins" );

   B_plus_DTFM_M_zero.setBins(100);

   RooArgSet argset(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity);
   RooArgSet argsetPartReco(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, weightPartReco);
   RooArgSet argsetLeakage(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, weightLeakage);
   RooArgSet argsetSignal(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, dataMCWeightee);

   cout<<"getting the datasets:"<<endl;

   RooDataSet* dataSetSignalZeroGamma;
   RooDataSet* dataSetSignalOneGamma;
   RooDataSet* dataSetSignalTwoGamma;
   RooDataSet* dataSetPartReco;
   RooDataSet* dataSetJpsiLeak;
   RooDataSet* dataSetComb;

   TFile* fw(NULL);

   string BDTCutString( ("("+BDTVar+">"+d2s(BDTcut)+")").c_str()  );

   dataSetSignalZeroGamma = new RooDataSet("dataSetSignalZeroGamma", "dataSetSignalZeroGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > -0.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 0.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );

   dataSetSignalOneGamma = new RooDataSet("dataSetSignalOneGamma", "dataSetSignalOneGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > 0.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 1.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );

   dataSetSignalTwoGamma = new RooDataSet("dataSetSignalTwoGamma", "dataSetSignalTwoGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > 1.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 2.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );


   dataSetPartReco = new RooDataSet("dataSetPartReco", "dataSetPartReco",  argsetPartReco, Import(*tPartReco),Cut(("("+trigStr+"  > 0.9) && "+BDTCutString+ " && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("weightPartReco"));

   dataSetJpsiLeak = new RooDataSet("dataSetJpsiLeak", "dataSetJpsiLeak",  argsetLeakage, Import(*tJpsiLeak),Cut(("B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("weightLeakage"));

    // dataSetComb = new RooDataSet("dataSetComb", "dataSetComb", tComb, argset, ("("+trigStr+"  > 0.9) && (UBDT3R > "+d2s(BDTcut-0.03)+")  && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());
   dataSetComb = new RooDataSet("dataSetComb", "dataSetComb", tComb, argset, ("("+trigStr+"  > 0.9) && "+BDTCutString+"  && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());

   cout<<"Number of zero: "<< dataSetSignalZeroGamma->sumEntries()<<endl;
   cout<<"Number of one: "<< dataSetSignalOneGamma->sumEntries()<<endl;
   cout<<"Number of two: "<< dataSetSignalTwoGamma->sumEntries()<<endl;
   cout<<"Number of PartReco: "<< dataSetPartReco->sumEntries()<<endl;
   cout<<"Number of Jpsi leaking:"<< dataSetJpsiLeak->sumEntries()<<endl;
   cout<<"Number of combinatorial events:"<< dataSetComb->sumEntries()<<endl;


   cout<<"binning the datasets:"<<endl;

   RooArgSet argset2(B_plus_M);
   if (fit2D) argset2.add(misPT);

   RooDataHist dataHistSignalZeroGamma("dataHistSignalZeroGamma", "dataHistSignalZeroGamma", argset2, *dataSetSignalZeroGamma); 
   RooDataHist dataHistSignalOneGamma("dataHistSignalOneGamma", "dataHistSignalOneGamma", argset2, *dataSetSignalOneGamma); 
   RooDataHist dataHistSignalTwoGamma("dataHistSignalTwoGamma", "dataHistSignalTwoGamma", argset2, *dataSetSignalTwoGamma); 
   RooDataHist dataHistComb("dataHistComb", "dataHistComb", argset2, *dataSetComb); 
   RooDataHist dataHistPartReco("dataHistPartReco", "dataHistPartReco", argset2, *dataSetPartReco); 
   RooDataHist dataHistJpsiLeak("dataHistJpsiLeak", "dataHistJpsiLeak", argset2, "broaderBins");
   dataHistJpsiLeak.add(*dataSetJpsiLeak); 

   //*************** Compute Error on J/psi leak

   double ErrorJpsi(0);
   if(dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()) > 0) ErrorJpsi = 1./sqrt(dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()));
   RooRealVar fractionalErrorJpsiLeak("fractionalErrorJpsiLeak", "fractionalErrorJpsiLeak", ErrorJpsi);
   cout<<"JPSI LEAK: "<<dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());
   cout<<"JPSI LEAK fractional Error: "<<ErrorJpsi<<endl;


   //***************Create 2D histogram estimates from data


   cout<<"Preparing the 3 2D histPdf: 1";
   //   RooArgSet argset2(B_plus_M);
   RooHistPdf histPdfSignalZeroGamma("histPdfSignalZeroGamma", "histPdfSignalZeroGamma", argset2, dataHistSignalZeroGamma,2); cout<<" 2";
   RooHistPdf histPdfSignalOneGamma("histPdfSignalOneGamma", "histPdfSignalOneGamma", argset2, dataHistSignalOneGamma,2); cout<<" 3";
   RooHistPdf histPdfSignalTwoGamma("histPdfSignalTwoGamma", "histPdfSignalTwoGamma", argset2, dataHistSignalTwoGamma,2); cout<<" 4";
   RooHistPdf histPdfPartReco("histPdfPartReco", "histPdfPartReco", argset2, dataHistPartReco,2); cout<<" 5";
   RooHistPdf histPdfJpsiLeak("histPdfJpsiLeak", "histPdfJpsiLeak", argset2, dataHistJpsiLeak,2); cout<<" 6";


   //***************Create combinatorial from fit to data

   RooRealVar expoConst("expoConst", "expoConst", -1e-3, -1, 1);
   RooRealVar T("T", "T", 97, 0, 200);
   RooRealVar n("n", "n", 3.5, 1., 5.5);
   RooAbsPdf *combPDF;

   if (fit2D)
   {  
      combPDF =  new RooPTMVis("PTMVis", "PTMVis", misPT, B_plus_M, T, n, expoConst);
   }
   else
   {
      combPDF =  new RooExponential("histPdfComb", "histPdfComb", B_plus_M, expoConst);
   }



   combPDF->fitTo(*dataSetComb); // 


   if (fit2D)
   {
      T.setConstant(true);
      n.setConstant(true);
      std::cout<<"T generated is: "<<T.getVal()<<std::endl;
   }

   RooRealVar trueExp("trueExp","trueExp", expoConst.getVal(), -1000, 1000);
   trueExp.setError(expoConst.getError());

   RooRealVar trueT("trueT","trueT", T.getVal(), -1000, 1000);
   trueT.setError(T.getError());
   RooRealVar trueN("trueN","trueN", n.getVal(), -1000, 1000);
   trueN.setError(n.getError());


   //***************Save everything on a workspace
   RooWorkspace workspace("workspace", "workspace");
   workspace.import(B_plus_DTFM_M_zero);
   workspace.import(B_plus_M);
   workspace.import(misPT);
   workspace.import(expoConst);
   workspace.import(trueExp);
   workspace.import(T);
   workspace.import(n);
   workspace.import(*dataSetSignalZeroGamma);
   workspace.import(*dataSetSignalOneGamma);
   workspace.import(*dataSetSignalTwoGamma);
   workspace.import(*dataSetPartReco);
   workspace.import(*dataSetComb);
   workspace.import(*dataSetJpsiLeak);
   workspace.import(histPdfSignalZeroGamma);
   workspace.import(histPdfSignalOneGamma);
   workspace.import(histPdfSignalTwoGamma);
   workspace.import(histPdfPartReco);
   workspace.import(histPdfJpsiLeak);
   workspace.import(fractionalErrorJpsiLeak);
   workspace.import(trueT);
   workspace.import(trueN);
   workspace.writeToFile(workspacename.c_str());



   delete fComb;
   delete fSignal;
   delete fPartReco;
   if(fw!=0 && fw != NULL) delete fw;
   delete combPDF;

   delete dataSetSignalZeroGamma; 
   delete dataSetSignalOneGamma;
   delete dataSetSignalTwoGamma;
   delete dataSetPartReco;
   delete dataSetJpsiLeak;
   delete dataSetComb;
}
void angularDistributions_spin0(int plotIndex=0, int binning=80){

  gROOT->ProcessLine(".L  ../PDFs/RooXZsZs_5D.cxx+");
  gROOT->ProcessLine(".L  ../PDFs/RooSpinOne_7D.cxx+");  
  gROOT->ProcessLine(".L  ../PDFs/RooSpinTwo_7D.cxx+");  
  gROOT->ProcessLine(".L  ../src/AngularPdfFactory.cc+");
  gROOT->ProcessLine(".L  ../src/ScalarPdfFactory.cc+");
  gROOT->ProcessLine(".L  ../src/VectorPdfFactory.cc+");
  gROOT->ProcessLine(".L  ../src/TensorPdfFactory.cc+");

  gROOT->ProcessLine(".L  ~/tdrstyle.C");
  setTDRStyle();

  // observables
  RooRealVar* z1mass = new RooRealVar("z1mass","m_{1} [GeV]",40,110);
  RooRealVar* z2mass = new RooRealVar("z2mass","m_{2} [GeV]",1e-09,65);
  RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
  RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
  RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
  RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
  RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());

  vector<RooRealVar*> measureables;
  measureables.push_back(z1mass);
  measureables.push_back(z2mass);
  measureables.push_back(hs);
  measureables.push_back(h1);
  measureables.push_back(h2);
  measureables.push_back(Phi);
  measureables.push_back(Phi1);

  RooRealVar* mzz = new RooRealVar("mzz","mzz",125,100,1000);

  ScalarPdfFactory* SMHiggs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  SMHiggs->makeSMHiggs();
  SMHiggs->makeParamsConst(true);

  ScalarPdfFactory* PSHiggs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  PSHiggs->makePSHiggs();
  PSHiggs->makeParamsConst(true);

  ScalarPdfFactory* LGHiggs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  LGHiggs->makeLGHiggs();
  LGHiggs->makeParamsConst(true);

  ScalarPdfFactory* A2Higgs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  A2Higgs->makeCustom(0.0,1.0,0.0,0.0,0.0,0.0);
  A2Higgs->makeParamsConst(true);

  TChain* treeSM = new TChain("angles");
  treeSM->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/SMHiggs_store/SMHiggs_125GeV.root");
  RooDataSet* dataSM = new RooDataSet("dataSM","dataSM",treeSM,RooArgSet(*z1mass,*z2mass,*hs,*h1,*h2,*Phi,*Phi1));

  TChain* treePS = new TChain("angles");
  treePS->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/psScalar_store/psScalar_125GeV.root");
  RooDataSet* data = new RooDataSet("dataPS","dataPS",treePS,RooArgSet(*z1mass,*z2mass,*hs,*h1,*h2,*Phi,*Phi1));

  TChain* treeLG = new TChain("angles");
  treeLG->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/0hPlus_store/0hPlus_125GeV.root");
  RooDataSet* dataLG = new RooDataSet("dataLG","dataLG",treeLG,RooArgSet(*z1mass,*z2mass,*hs,*h1,*h2,*Phi,*Phi1));

  double normFix;
  if( ! strcmp( measureables[plotIndex]->GetName() , "phistar1" ) ) normFix=.001/(2.*3.1415);
  else if( ! strcmp( measureables[plotIndex]->GetName() , "costhetastar" ) ) normFix=.001/2.0;
  else normFix=.001;
  
  RooPlot* plot = measureables[plotIndex]->frame(binning);
  plot->GetXaxis()->CenterTitle();
  plot->GetYaxis()->CenterTitle();
  plot->GetYaxis()->SetTitle(" ");
  plot->GetXaxis()->SetNdivisions(-505);

  cout << 1./dataSM->sumEntries() << endl;
  double rescale=(double)(1./dataSM->sumEntries());
  dataSM->plotOn(plot,MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0),Rescale(.001),DataError(RooAbsData::None));
  SMHiggs.PDF->plotOn(plot,LineColor(kRed),LineWidth(2),Normalization( normFix ));
  cout << 1./dataPS->sumEntries() << endl;
  rescale=(double)(1./dataPS->sumEntries());
  dataPS->plotOn(plot,MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0),Rescale(.001),DataError(RooAbsData::None));
  PSHiggs.PDF->plotOn(plot,LineColor(kBlue),LineWidth(2),Normalization( normFix ));
  cout << 1./dataLG->sumEntries() << endl;
  rescale=(double)(1./dataLG->sumEntries());
  dataLG->plotOn(plot,MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0),Rescale(.001),DataError(RooAbsData::None));
  LGHiggs.PDF->plotOn(plot,LineColor(kGreen+3),LineWidth(2),Normalization( normFix ));

  TGaxis::SetMaxDigits(3);

  TCanvas* can =new TCanvas("can","can",600,600);

  gStyle->SetPadLeftMargin(0.05);

  char temp[150];
  sprintf(temp,"%s>>SM_histo(%i,%i,%i)",measureables[plotIndex]->GetName(),binning,(int)measureables[plotIndex]->getMin(),(int)measureables[plotIndex]->getMin());
  treeSM->Draw(temp);
  TH1F* SM_histo = (TH1F*) gDirectory->Get("SM_histo");
  sprintf(temp,"%s>>PS_histo(%i,%i,%i)",measureables[plotIndex]->GetName(),binning,(int)measureables[plotIndex]->getMin(),(int)measureables[plotIndex]->getMin());
  treePS->Draw(temp);
  TH1F* PS_histo = (TH1F*) gDirectory->Get("PS_histo");
  sprintf(temp,"%s>>LG_histo(%i,%i,%i)",measureables[plotIndex]->GetName(),binning,(int)measureables[plotIndex]->getMin(),(int)measureables[plotIndex]->getMin());
  treeLG->Draw(temp);
  TH1F* LG_histo = (TH1F*) gDirectory->Get("LG_histo");

  if(!strcmp(measureables[plotIndex]->GetName(),"z1mass"))
    plot->GetYaxis()->SetRangeUser(0,max(max(LG_histo->GetMaximum(),PS_histo->GetMaximum()),SM_histo->GetMaximum())*.8/1000.);
  else
    plot->GetYaxis()->SetRangeUser(0,max(max(LG_histo->GetMaximum(),PS_histo->GetMaximum()),SM_histo->GetMaximum())*1.3/1000.);

  //cout << "max range: " << max(max(LG_histo->GetMaximum(),PS_histo->GetMaximum()),SM_histo->GetMaximum())*.8/1000. << endl;

  plot->Draw();

  char temp[150];
  sprintf(temp,"epsfiles/%s_125GeV_spin0_3in1.eps",measureables[plotIndex]->GetName());
  can->SaveAs(temp);
  sprintf(temp,"pngfiles/%s_125GeV_spin0_3in1.png",measureables[plotIndex]->GetName());
  can->SaveAs(temp);

  delete SMHiggs;
  delete PSHiggs;
  delete LGHiggs;

}
예제 #13
0
void forData(string channel, string catcut, bool removeMinor=true){

  // Suppress all the INFO message

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

  // Input files and sum all backgrounds

  TChain* treeData  = new TChain("tree");
  TChain* treeZjets = new TChain("tree");

  if( channel == "ele" ){

    treeData->Add(Form("%s/data/SingleElectron-Run2015D-05Oct2015-v1_toyMCnew.root",  channel.data()));
    treeData->Add(Form("%s/data/SingleElectron-Run2015D-PromptReco-V4_toyMCnew.root", channel.data()));

  }

  else if( channel == "mu" ){

    treeData->Add(Form("%s/data/SingleMuon-Run2015D-05Oct2015-v1_toyMCnew.root",  channel.data()));
    treeData->Add(Form("%s/data/SingleMuon-Run2015D-PromptReco-V4_toyMCnew.root", channel.data()));

  }

  else return;

  treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-100to200_13TeV_toyMCnew.root", channel.data()));
  treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-200to400_13TeV_toyMCnew.root", channel.data()));
  treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-400to600_13TeV_toyMCnew.root", channel.data()));
  treeZjets->Add(Form("%s/Zjets/DYJetsToLL_M-50_HT-600toInf_13TeV_toyMCnew.root", channel.data()));

  // To remove minor background contribution in data set (weight is -1)

  if( removeMinor ){

    treeData->Add(Form("%s/VV/WW_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data()));
    treeData->Add(Form("%s/VV/WZ_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data()));
    treeData->Add(Form("%s/VV/ZZ_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data()));
    treeData->Add(Form("%s/TT/TT_TuneCUETP8M1_13TeV_toyMCnew.root", channel.data()));

  }

  // Define all the variables from the trees

  RooRealVar cat ("cat", "", 0, 2);
  RooRealVar mJet("prmass", "M_{jet}",  30.,  300., "GeV");
  RooRealVar mZH ("mllbb",   "M_{ZH}", 900., 3000., "GeV");
  RooRealVar evWeight("evweight", "", -1.e3, 1.e3);

  // Set the range in jet mass

  mJet.setRange("allRange", 30., 300.);
  mJet.setRange("lowSB",    30.,  65.);
  mJet.setRange("highSB",  135., 300.);
  mJet.setRange("signal",  105., 135.);

  RooBinning binsmJet(54, 30, 300);

  RooArgSet variables(cat, mJet, mZH, evWeight);

  TCut catCut = Form("cat==%s", catcut.c_str());
  TCut sbCut  = "prmass>30 && !(prmass>65 && prmass<135) && prmass<300";
  TCut sigCut = "prmass>105 && prmass<135";

  // Create a dataset from a tree -> to process an unbinned likelihood fitting

  RooDataSet dataSetData   ("dataSetData",    "dataSetData",    variables, Cut(catCut),           WeightVar(evWeight), Import(*treeData));
  RooDataSet dataSetDataSB ("dataSetDataSB",  "dataSetDataSB",  variables, Cut(catCut && sbCut),  WeightVar(evWeight), Import(*treeData));
  RooDataSet dataSetZjets  ("dataSetZjets",   "dataSetZjets",   variables, Cut(catCut),           WeightVar(evWeight), Import(*treeZjets));
  RooDataSet dataSetZjetsSB("dataSetZjetsSB", "dataSetZjetsSB", variables, Cut(catCut && sbCut),  WeightVar(evWeight), Import(*treeZjets));  
  RooDataSet dataSetZjetsSG("dataSetZjetsSG", "dataSetZjetsSG", variables, Cut(catCut && sigCut), WeightVar(evWeight), Import(*treeZjets));
  
  // Total events number

  float totalMcEv   = dataSetZjetsSB.sumEntries() + dataSetZjetsSG.sumEntries();
  float totalDataEv = dataSetData.sumEntries();

  RooRealVar nMcEvents("nMcEvents", "nMcEvents", 0., 99999.);
  RooRealVar nDataEvents("nDataEvents", "nDataEvents", 0., 99999.);

  nMcEvents.setVal(totalMcEv);
  nMcEvents.setConstant(true);

  nDataEvents.setVal(totalDataEv);
  nDataEvents.setConstant(true);

  // Signal region jet mass

  RooRealVar constant("constant", "constant", -0.02,  -1.,   0.);
  RooRealVar offset  ("offset",   "offset",     30., -50., 200.);
  RooRealVar width   ("width",    "width",     100.,   0., 200.);

  if( catcut == "1" ) offset.setConstant(true);
  
  RooErfExpPdf model_mJet("model_mJet", "model_mJet", mJet, constant, offset, width);
  RooExtendPdf ext_model_mJet("ext_model_mJet", "ext_model_mJet", model_mJet, nMcEvents);

  RooFitResult* mJet_result = ext_model_mJet.fitTo(dataSetZjets, SumW2Error(true), Extended(true), Range("allRange"), Strategy(2), Minimizer("Minuit2"), Save(1));

  // Side band jet mass

  RooRealVar constantSB("constantSB", "constantSB", constant.getVal(),  -1.,   0.);
  RooRealVar offsetSB  ("offsetSB",   "offsetSB",   offset.getVal(),   -50., 200.);
  RooRealVar widthSB   ("widthSB",    "widthSB",    width.getVal(),      0., 200.);

  offsetSB.setConstant(true);

  RooErfExpPdf model_mJetSB("model_mJetSB", "model_mJetSB", mJet, constantSB, offsetSB, widthSB);
  RooExtendPdf ext_model_mJetSB("ext_model_mJetSB", "ext_model_mJetSB", model_mJetSB, nMcEvents);

  RooFitResult* mJetSB_result = ext_model_mJetSB.fitTo(dataSetZjetsSB, SumW2Error(true), Extended(true), Range("lowSB,highSB"), Strategy(2), Minimizer("Minuit2"), Save(1));

  RooAbsReal* nSIGFit = ext_model_mJetSB.createIntegral(RooArgSet(mJet), NormSet(mJet), Range("signal"));

  float normFactor = nSIGFit->getVal() * totalMcEv;
  
  // Plot the results on a frame

  RooPlot* mJetFrame = mJet.frame();

  dataSetZjetsSB.  plotOn(mJetFrame, Binning(binsmJet));  
  ext_model_mJetSB.plotOn(mJetFrame, Range("allRange"), VisualizeError(*mJetSB_result), FillColor(kYellow));
  dataSetZjetsSB.  plotOn(mJetFrame, Binning(binsmJet));  
  ext_model_mJetSB.plotOn(mJetFrame, Range("allRange"));
  mJetFrame->SetTitle("M_{jet} distribution in Z+jets MC");

  // Alpha ratio part

  mZH.setRange("fullRange", 900., 3000.);

  RooBinning binsmZH(21, 900, 3000);

  RooRealVar a("a", "a",  0., -1.,    1.);
  RooRealVar b("b", "b", 1000,  0., 4000.);
  
  RooGenericPdf model_ZHSB("model_ZHSB", "model_ZHSB", "TMath::Exp(@1*@0+@2/@0)", RooArgSet(mZH,a,b));
  RooGenericPdf model_ZHSG("model_ZHSG", "model_ZHSG", "TMath::Exp(@1*@0+@2/@0)", RooArgSet(mZH,a,b));
  RooGenericPdf model_ZH  ("model_ZH",   "model_ZH",   "TMath::Exp(@1*@0+@2/@0)", RooArgSet(mZH,a,b));

  RooExtendPdf ext_model_ZHSB("ext_model_ZHSB", "ext_model_ZHSB", model_ZHSB, nMcEvents);
  RooExtendPdf ext_model_ZHSG("ext_model_ZHSG", "ext_model_ZHSG", model_ZHSG, nMcEvents);
  RooExtendPdf ext_model_ZH  ("ext_model_ZH",   "ext_model_ZH",   model_ZH,   nDataEvents);

  // Fit ZH mass in side band  

  RooFitResult* mZHSB_result = ext_model_ZHSB.fitTo(dataSetZjetsSB, SumW2Error(true), Extended(true), Range("fullRange"), Strategy(2), Minimizer("Minuit2"), Save(1));

  float p0 = a.getVal();
  float p1 = b.getVal();

  // Fit ZH mass in signal region

  RooFitResult* mZHSG_result = ext_model_ZHSG.fitTo(dataSetZjetsSG, SumW2Error(true), Extended(true), Range("fullRange"), Strategy(2), Minimizer("Minuit2"), Save(1));

  float p2 = a.getVal();
  float p3 = b.getVal();

  // Fit ZH mass in side band region (data)

  RooFitResult* mZH_result = ext_model_ZH.fitTo(dataSetDataSB, SumW2Error(true), Extended(true), Range("fullRange"), Strategy(2), Minimizer("Minuit2"), Save(1));

  // Draw the model of alpha ratio
  // Multiply the model of background in data side band with the model of alpha ratio to the a model of background in data signal region

  RooGenericPdf model_alpha("model_alpha", "model_alpha", Form("TMath::Exp(%f*@0+%f/@0)/TMath::Exp(%f*@0+%f/@0)", p2,p3,p0,p1), RooArgSet(mZH));
  RooProdPdf    model_sigData("model_sigData", "ext_model_ZH*model_alpha", RooArgList(ext_model_ZH,model_alpha));

  // Plot the results to a frame 

  RooPlot* mZHFrameMC = mZH.frame();

  dataSetZjetsSB.plotOn(mZHFrameMC, Binning(binsmZH));
  ext_model_ZHSB.plotOn(mZHFrameMC, VisualizeError(*mZHSB_result), FillColor(kYellow));
  dataSetZjetsSB.plotOn(mZHFrameMC, Binning(binsmZH));
  ext_model_ZHSB.plotOn(mZHFrameMC, LineStyle(7), LineColor(kBlue));

  dataSetZjetsSG.plotOn(mZHFrameMC, Binning(binsmZH));
  ext_model_ZHSG.plotOn(mZHFrameMC, VisualizeError(*mZHSG_result), FillColor(kYellow));
  dataSetZjetsSG.plotOn(mZHFrameMC, Binning(binsmZH));
  ext_model_ZHSG.plotOn(mZHFrameMC, LineStyle(7), LineColor(kRed));

  TLegend* leg = new TLegend(0.65,0.77,0.85,0.85);

  leg->AddEntry(mZHFrameMC->findObject(mZHFrameMC->nameOf(3)), "side band",     "l");
  leg->AddEntry(mZHFrameMC->findObject(mZHFrameMC->nameOf(7)), "signal region", "l");
  leg->Draw();

  mZHFrameMC->addObject(leg);
  mZHFrameMC->SetTitle("M_{ZH} distribution in MC");

  RooPlot* mZHFrame = mZH.frame();

  dataSetDataSB.plotOn(mZHFrame, Binning(binsmZH));
  ext_model_ZH .plotOn(mZHFrame, VisualizeError(*mZH_result), FillColor(kYellow));
  dataSetDataSB.plotOn(mZHFrame, Binning(binsmZH));
  ext_model_ZH .plotOn(mZHFrame, LineStyle(7), LineColor(kBlue));
  model_sigData.plotOn(mZHFrame, Normalization(normFactor, RooAbsReal::NumEvent), LineStyle(7), LineColor(kRed));

  TLegend* leg1 = new TLegend(0.65,0.77,0.85,0.85);

  leg1->AddEntry(mZHFrame->findObject(mZHFrame->nameOf(3)), "side band",     "l");
  leg1->AddEntry(mZHFrame->findObject(mZHFrame->nameOf(4)), "signal region", "l");
  leg1->Draw();
  
  mZHFrame->addObject(leg1);
  mZHFrame->SetTitle("M_{ZH} distribution in Data");

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

  c->cd();
  mZHFrameMC->Draw();
  c->Print(Form("rooFit_forData_%s_cat%s.pdf(", channel.data(), catcut.data()));

  c->cd();
  mZHFrame->Draw();
  c->Print(Form("rooFit_forData_%s_cat%s.pdf", channel.data(), catcut.data()));

  c->cd();
  mJetFrame->Draw();
  c->Print(Form("rooFit_forData_%s_cat%s.pdf)", channel.data(), catcut.data()));

}
예제 #14
0
int main(int argc, char *argv[]){

	OptionParser(argc,argv);
	

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


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

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

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

              if (datahist) {
              RooDataHist *datahistOUT = (RooDataHist*) datahist->emptyClone(datahist->GetName(),datahist->GetName());
                TRandom3 r;
                r.Rndm();
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistOUT->add(*(datahist->get(j)),datahist->weight());
                }
              float w =datahistOUT->sumEntries();
              float z =datahist->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "Reduced  datahist " << *datahistOUT<<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : " << w/(z) <<std::endl;
              std::cout << "WH fraction (exp) : " << fraction_ << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistOUT);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
예제 #15
0
void Fit3D::plotFitAccuracy(
    const RooDataSet& mc_data,
    const RooFitResult& fit)
{
  fit.Print("v");

  double n_true_bs = mc_data.sumEntries("component == component::bs");
  double n_true_bd = mc_data.sumEntries("component == component::bd");
  double n_true_cw = mc_data.sumEntries("component == component::cw");
  double n_true_ww = mc_data.sumEntries("component == component::ww");
  double n_true_cn = mc_data.sumEntries("component == component::cn");

  RooRealVar* bs_fit = (RooRealVar*) fit.floatParsFinal().find("n_bs_pp");
  RooRealVar* bd_fit = (RooRealVar*) fit.floatParsFinal().find("n_bd_pp");
  RooRealVar* cw_fit = (RooRealVar*) fit.floatParsFinal().find("n_cw_pp");
  RooRealVar* ww_fit = (RooRealVar*) fit.floatParsFinal().find("n_ww_pp");
  RooRealVar* cn_fit = (RooRealVar*) fit.floatParsFinal().find("n_cn_pp");
  
  TString title("Fit Accuracy (N^{++}_{fit}-N^{++}_{true})");
  TString filename(output_path_ + "fit_accuracy_pp");
  if (!bs_fit) {
    bs_fit = (RooRealVar*) fit.floatParsFinal().find("n_bs_nn");
    bd_fit = (RooRealVar*) fit.floatParsFinal().find("n_bd_nn");
    cw_fit = (RooRealVar*) fit.floatParsFinal().find("n_cw_nn");
    ww_fit = (RooRealVar*) fit.floatParsFinal().find("n_ww_nn");
    cn_fit = (RooRealVar*) fit.floatParsFinal().find("n_cn_nn");
    title = TString("Fit Accuracy (N^{--}_{fit}-N^{--}_{true})");
    filename = TString(output_path_ + "fit_accuracy_nn");
  }
  if (!bs_fit) {
    // Error. Quit while ahead.
    cout << "Error in plotFitAccuracy(): "
         << "Cannot find fit variables. Check names are valid."
         << endl;
    return;
  }

  std::cout << n_true_bd << std::endl;
  std::cout << n_true_bs << std::endl;
  std::cout << n_true_cn << std::endl;
  std::cout << n_true_cw << std::endl;
  std::cout << n_true_ww << std::endl;
  
  TCanvas c1("c1", title, 200, 10, 700, 500);
  c1.SetGrid();
  double x[5] = {1, 2, 3, 4, 5};
  double y[5] = {
      bs_fit->getVal() - n_true_bs,
      bd_fit->getVal() - n_true_bd,
      cw_fit->getVal() - n_true_cw,
      ww_fit->getVal() - n_true_ww,
      cn_fit->getVal() - n_true_cn};
  double exl[5] = {0, 0, 0, 0, 0};
  double exh[5] = {0, 0, 0, 0, 0};
  double eyl[5] = {
      -bs_fit->getErrorLo(),
      -bd_fit->getErrorLo(),
      -cw_fit->getErrorLo(),
      -ww_fit->getErrorLo(),
      -cn_fit->getErrorLo()};
  double eyh[5] = {
      bs_fit->getErrorHi(),
      bd_fit->getErrorHi(),
      cw_fit->getErrorHi(),
      ww_fit->getErrorHi(),
      cn_fit->getErrorHi()};
  TGraphAsymmErrors* gr = new TGraphAsymmErrors(5, x, y, exl, exh, eyl, eyh);
  
  TLatex* cc_bs_label = new TLatex(gr->GetX()[0], gr->GetY()[0], " CC (B_{s})");
  TLatex* cc_bd_label = new TLatex(gr->GetX()[1], gr->GetY()[1], " CC (B_{d})");
  TLatex* cw_label = new TLatex(gr->GetX()[2], gr->GetY()[2], " CW");
  TLatex* ww_label = new TLatex(gr->GetX()[3], gr->GetY()[3], " WW");
  TLatex* cn_label = new TLatex(gr->GetX()[4], gr->GetY()[4], " CN");
  
  gr->GetListOfFunctions()->Add(cc_bs_label);
  gr->GetListOfFunctions()->Add(cc_bd_label);
  gr->GetListOfFunctions()->Add(cw_label);
  gr->GetListOfFunctions()->Add(ww_label);
  gr->GetListOfFunctions()->Add(cn_label);
  
  gr->SetTitle(title);
  gr->SetMarkerStyle(kOpenCircle);
  gr->SetMarkerColor(4);
  gr->Draw("AP");

  c1.Print(filename + ".eps");
  
  TFile accuracy_plot_file(filename + ".root", "RECREATE");
  gr->Write();
  accuracy_plot_file.Close();
  
  return;
}
예제 #16
0
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();
}
예제 #17
0
void higgsMassFit(const int& mH, const std::string& mode = "exclusion", const bool& drawPlots = false, const int& nToys = 10000)
{
  using namespace RooFit;
  RooMsgService::instance().deleteStream(0);
  RooMsgService::instance().deleteStream(1);
  
  
  
  std::string varName = "lepNuW_m";
  
  int step = 16;
  char treeName[50];
  sprintf(treeName, "ntu_%d", step);
  
  float lumi = 1000.;
  
  int nBins = 50;
  double xMin = 0.;
  double xMax = 1000.;
  double xMin_signal = 0.;
  double xMax_signal = 0.;
  SetXSignal(xMin_signal,xMax_signal,mH);
  
  RooRealVar x("x",varName.c_str(),xMin,xMax);
  x.setRange("low",   xMin,       xMin_signal);
  x.setRange("signal",xMin_signal,xMax_signal);
  x.setRange("high",  xMax_signal,xMax);
  
  RooRealVar w("w","weight",0.,1000000000.);
  
  char signalCut[50];
  sprintf(signalCut,"x > %f && x < %f",xMin_signal,xMax_signal);
  
  
  
  //-------------------
  // define the outfile
  char outFileName[50];
  sprintf(outFileName,"higgsMassFit_H%d_%s.root",mH,mode.c_str());
  TFile* outFile = new TFile(outFileName,"RECREATE");
  outFile -> cd();
  
  
  
  //-------------------
  // define the infiles
  char higgsMass[50];
  sprintf(higgsMass,"%d",mH);
  
  std::string BKGPath = "/grid_mnt/vol__vol1__u/llr/cms/abenagli/COLLISIONS7TeV/Fall10/VBFAnalysisPackage/data/VBFAnalysis_AK5PF_H" + 
                        std::string(higgsMass) + 
                        "_ET30_maxDeta_minDeta_Spring11_EGMu_noHiggsMassCut/";
  
  std::string WJetsFolder = "WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_Spring11-PU_S1_START311_V1G1-v1/";
  std::string TTJetsFolder = "TTJets_TuneZ2_7TeV-madgraph-tauola_Spring11-PU_S1_START311_V1G1-v1/";
  //std::string ZJetsFolder = 
  //std::string GJets_HT40To100Folder 
  //std::string GJets_HT100To200Folder 
  //std::string GJets_HT200Folder 
  //std::string WWFolder 
  //std::string WZFolder 
  //std::string TJets_schannelFolder 
  //std::string TJets_tchannelFolder 
  //std::string TJets_tWchannelFolder 
  
  std::string GluGluHToLNuQQFolder   = "GluGluToHToWWToLNuQQ_M-"   + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  std::string GluGluHToTauNuQQFolder = "GluGluToHToWWToTauNuQQ_M-" + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  std::string VBFHToLNuQQFolder      = "VBF_HToWWToLNuQQ_M-"       + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  std::string VBFHToTauNuQQFolder    = "VBF_HToWWToTauNuQQ_M-"     + std::string(higgsMass) + "_7TeV-powheg-pythia6_Spring11-PU_S1_START311_V1G1-v1/";
  
  
  
  //---------------------------------------
  // define the background shape histograms
  int nBKG = 2;
  
  TH1F** BKGShapeHisto = new TH1F*[nBKG];
  TH1F* BKGTotShapeHisto = new TH1F("BKGTotShapeHisto","",nBins,xMin,xMax);
  THStack* BKGShapeStack = new THStack();
  RooDataSet** rooBKGDataSet = new RooDataSet*[nBKG];
  
  std::string* BKGNames = new std::string[nBKG];
  BKGNames[1]  = BKGPath+WJetsFolder+"VBFAnalysis_AK5PF.root";
  BKGNames[0]  = BKGPath+TTJetsFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[1]  = BKGPath+ZJetsFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[2]  = BKGPath+GJets_HT40To100Folder+"VBFAnalysis_AK5PF.root";
  //BKGNames[3]  = BKGPath+GJets_HT100To200Folder+"VBFAnalysis_AK5PF.root";
  //BKGNames[4]  = BKGPath+GJets_HT200Folder+"VBFAnalysis_AK5PF.root";
  //BKGNames[6]  = BKGPath+WWFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[7]  = BKGPath+WZFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[8]  = BKGPath+TJets_schannelFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[9]  = BKGPath+TJets_tchannelFolder+"VBFAnalysis_AK5PF.root";
  //BKGNames[10] = BKGPath+TJets_tWchannelFolder+"VBFAnalysis_AK5PF.root";
  
  std::string* BKGShortNames = new std::string[nBKG];
  BKGShortNames[1]  = "WJets";
  BKGShortNames[0]  = "TTJets";
  //BKGShortNames[1]  = "ZJets";
  //BKGShortNames[2]  = "GJets_HT40To100";
  //BKGShortNames[3]  = "GJets_HT100To200";
  //BKGShortNames[4]  = "GJets_HT200";
  //BKGShortNames[6]  = "WW";
  //BKGShortNames[7]  = "WZ";
  //BKGShortNames[8]  = "TJets_schannel";
  //BKGShortNames[9]  = "TJets_tchannel";
  //BKGShortNames[10] = "TJets_tWchannel";
  
  Color_t* BKGColors = new Color_t[nBKG];
  BKGColors[1]  = kOrange-708;
  BKGColors[0]  = kAzure-795;
  
  
  
  //-----------------------------------
  // define the signal shape histograms
  int nSIG = 2;
  
  TH1F* SIGShapeHisto = new TH1F("SIGShapeHisto","",4*nBins,xMin,xMax);
  SIGShapeHisto -> Sumw2();
  SIGShapeHisto -> SetLineWidth(1);
  SIGShapeHisto -> SetLineStyle(1);
  RooDataSet* rooSIGDataSet = new RooDataSet("rooSIGDataSet","",RooArgSet(x,w),WeightVar(w));
  
  std::string* SIGNames = new std::string[nSIG];
  SIGNames[0]  = BKGPath+GluGluHToLNuQQFolder+"VBFAnalysis_AK5PF.root";
  SIGNames[1]  = BKGPath+VBFHToLNuQQFolder+"VBFAnalysis_AK5PF.root";
  
  std::string* SIGShortNames = new std::string[nSIG];
  SIGShortNames[1]  = "ggH";
  SIGShortNames[0]  = "qqH";
  
  
  
  
  
  
  //----------------------
  // loop over backgrounds
  std::cout << "***********************************************************************" << std::endl;
  std::cout << ">>> Fill the background shapes" << std::endl;
    
  for(int i = 0; i < nBKG; ++i)
  {
    TFile* inFile_BKGShape = TFile::Open((BKGNames[i]).c_str());
    inFile_BKGShape -> cd();
    
    TTree* BKGShapeTree = (TTree*)(inFile_BKGShape -> Get(treeName));
    
    BKGShapeHisto[i] = new TH1F(("BKGShapeHisto_"+BKGShortNames[i]).c_str(),"",nBins,xMin,xMax);
    enum EColor color = (enum EColor)(BKGColors[i]);
    BKGShapeHisto[i] -> SetFillColor(color);
    BKGShapeHisto[i] -> Sumw2();
    
    rooBKGDataSet[i] = new RooDataSet(("rooBKGDataSet_"+BKGShortNames[i]).c_str(),"",RooArgSet(x,w),WeightVar(w)); 
    
    TH1F* eventsHisto;
    inFile_BKGShape -> GetObject("events", eventsHisto);
    float totEvents = eventsHisto -> GetBinContent(1);
    
    
    // set branch addresses
    float crossSection;
    float var;
    BKGShapeTree -> SetBranchAddress("crossSection", &crossSection);
    BKGShapeTree -> SetBranchAddress(varName.c_str(),&var);
    
    
    // loop over the entries
    for(int entry = 0; entry < BKGShapeTree->GetEntries(); ++entry)
    {
      BKGShapeTree -> GetEntry(entry);
      
      x = var;
      w = 1./totEvents*crossSection*lumi;
      
      BKGShapeHisto[i] -> Fill(var, 1./totEvents*crossSection*lumi);
      BKGTotShapeHisto    -> Fill(var, 1./totEvents*crossSection*lumi);
      rooBKGDataSet[i] -> add(RooArgSet(x,w));
    }
    
    BKGShapeStack -> Add(BKGShapeHisto[i]);
  }
  
  
  
  
  
  
  //------------------
  // loop over signals
  std::cout << ">>> Fill the signal shapes" << std::endl;
    
  for(int i = 0; i < nSIG; ++i)
  {
    TFile* inFile_SIGShape = TFile::Open((SIGNames[i]).c_str());
    inFile_SIGShape -> cd();
    
    TTree* SIGShapeTree = (TTree*)(inFile_SIGShape -> Get(treeName));
    
    TH1F* eventsHisto = (TH1F*)(inFile_SIGShape -> Get("events"));
    float totEvents = eventsHisto -> GetBinContent(1);
    
    
    // set branch addresses
    float crossSection;
    float var;
    SIGShapeTree -> SetBranchAddress("crossSection", &crossSection);
    SIGShapeTree -> SetBranchAddress(varName.c_str(),&var);
    
    
    // loop over the entries
    for(int entry = 0; entry < SIGShapeTree->GetEntries(); ++entry)
    {
      SIGShapeTree -> GetEntry(entry);
      
      x = var;
      w= 1./totEvents*crossSection*lumi;
      
      SIGShapeHisto -> Fill(var, 1./totEvents*crossSection*lumi);
      rooSIGDataSet -> add(RooArgSet(x,w));
    }
  }
  
  
  
  //-----------------------------------
  // draw the background + signal stack
  if( drawPlots )
  {
    TCanvas* c1 = new TCanvas("BKGShapeStack","BKGShapeStack");
    c1 -> SetGridx();
    c1 -> SetGridy();
    BKGShapeStack -> Draw("HIST");
    SIGShapeHisto -> Draw("HIST,same");  
    char pngFileName[50];
    sprintf(pngFileName,"BKGShapeStack_H%d_%s.png",mH,mode.c_str());
    c1 -> Print(pngFileName,"png");
  }  
  
  
  
  
  
  
  //---------------------------------
  // define the bkg shape with roofit
  std::cout << ">>> Define the background pdf" << std::endl;
    
  RooKeysPdf** rooBKGPdf = new RooKeysPdf*[nBKG];
  RooRealVar** rooNBKG = new RooRealVar*[nBKG];
  RooRealVar* rooNBKGTot = new RooRealVar("rooNBKGTot","",BKGTotShapeHisto->Integral(),0.,1000000.);
  
  for(int i = 0; i < nBKG; ++i)
  {  
    rooBKGPdf[i] = new RooKeysPdf(("rooBKGPdf_"+BKGShortNames[i]).c_str(),"",x,*rooBKGDataSet[i]);
    rooNBKG[i] = new RooRealVar(("rooNBKG_"+BKGShortNames[i]).c_str(),"",BKGShapeHisto[i]->Integral(),BKGShapeHisto[i]->Integral()),BKGShapeHisto[i]->Integral();
  }
  
  RooAddPdf* rooBKGTotPdf = new RooAddPdf("rooBKGTotPdf","",RooArgList(*rooBKGPdf[0],*rooBKGPdf[1]),RooArgList(*rooNBKG[0],*rooNBKG[1]));
  
  
  
  //---------------------------------
  // define the sig shape with roofit
  std::cout << ">>> Define the signal pdf" << std::endl;
    
  RooKeysPdf* rooSIGPdf = new RooKeysPdf("rooSIGPdf","",x,*rooSIGDataSet);
  RooRealVar* rooNSIG = new RooRealVar("rooNSIG","",1.,-1000000.,1000000.);
  
  
  
  //---------------------------------
  // define the tot shape with roofit
  std::cout << ">>> Define the total pdf" << std::endl;
  
  RooAddPdf* rooTotPdf = NULL;
  if( mode == "exclusion") rooTotPdf = new RooAddPdf("rooTotPdf","",RooArgList(*rooBKGTotPdf),RooArgList(*rooNBKGTot));
  if( mode == "discovery") rooTotPdf = new RooAddPdf("rooTotPdf","",RooArgList(*rooBKGTotPdf,*rooSIGPdf),RooArgList(*rooNBKGTot,*rooNSIG));
  
  
  
  
  
  
  //----
  // plot 
  if( drawPlots )
  {
    TCanvas* c2 = new TCanvas("rooTotPdf","rooTotPdf");
    c2 -> SetGridx();
    c2 -> SetGridy();
    
    RooPlot* rooBKGPlot = x.frame();
    rooBKGTotPdf -> plotOn(rooBKGPlot,LineColor(kBlack));
    enum EColor color = (enum EColor)(BKGColors[0]);
    rooBKGTotPdf -> plotOn(rooBKGPlot,Components(("rooBKGPdf_"+BKGShortNames[0]).c_str()),LineColor(color));
    color = (enum EColor)(BKGColors[1]);
    rooBKGTotPdf -> plotOn(rooBKGPlot,Components(("rooBKGPdf_"+BKGShortNames[1]).c_str()),LineColor(color));
    
    rooSIGPdf -> plotOn(rooBKGPlot,LineColor(kBlack),LineStyle(1),LineWidth(1));
    
    rooBKGPlot->Draw();
    
    TH1F* BKGShapeHistoNorm = (TH1F*) BKGTotShapeHisto -> Clone();
    BKGShapeHistoNorm -> Scale(1./BKGTotShapeHisto->Integral()/nBKG);
    BKGShapeHistoNorm -> Draw("HIST,same");

    char pngFileName[50];
    sprintf(pngFileName,"BKGShapeNorm_H%d_%s.png",mH,mode.c_str());
    c2 -> Print(pngFileName,"png");
  }
  
  
  
  
  
  
  //------------------------
  // generate toy experiment
  std::cout << "***********************************************************************" << std::endl;
  std::cout << ">>> 1st toy experiment - " << mode << " mode" << std::endl;  
  
  int NBKGToy = int(BKGTotShapeHisto->Integral());
  int NSIGToy = 0;
  if( mode == "discovery" ) NSIGToy = int(SIGShapeHisto->Integral());
  
  RooDataSet* rooBKGToyDataSet = rooBKGTotPdf->generate(RooArgSet(x),NBKGToy);
  RooDataSet* rooSIGToyDataSet = rooSIGPdf->generate(RooArgSet(x),NSIGToy);
  rooBKGToyDataSet -> append(*rooSIGToyDataSet);
  
  float NBKGToy_signal = rooBKGToyDataSet->sumEntries(signalCut);
  float NBKGToy_signal_fit = 0.;
  
  
  
  // fit
  if( mode == "exclusion" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1),Range("low,high"));
  if( mode == "discovery" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1));
  
  
  
  // count events
  if( mode == "exclusion" )
  {
    RooAbsReal* rooTotIntegral = rooTotPdf -> createIntegral(x,NormSet(x),Range("signal"));
    NBKGToy_signal_fit = rooTotIntegral->getVal() * rooNBKGTot->getVal();
    
    std::cout << ">>>>>> BKG toy events (true) in signal region in " << lumi << "/pb: " << NBKGToy_signal << std::endl;  
    std::cout << ">>>>>> BKG toy events (fit)  in signal region in " << lumi << "/pb: " << NBKGToy_signal_fit << std::endl;      
  }
  
  if( mode == "discovery" )
  {
    std::cout << ">>>>>> BKG toy events (true) in " << lumi << "/pb: " << NBKGToy << std::endl;  
    std::cout << ">>>>>> BKG toy events (fit)  in " << lumi << "/pb: " << rooNBKGTot->getVal() << std::endl;  
    std::cout << ">>>>>> SIG toy events (true) in " << lumi << "/pb: " << NSIGToy << std::endl;  
    std::cout << ">>>>>> SIG toy events (fit)  in " << lumi << "/pb: " << rooNSIG->getVal() << std::endl;  
  }
  
  if( drawPlots )
  {
    TCanvas* c3 = new TCanvas("TOY","TOY");
    c3 -> SetGridx();
    c3 -> SetGridy();
    
    RooPlot* rooTOYPlot = x.frame();
    rooBKGToyDataSet -> plotOn(rooTOYPlot,MarkerSize(0.7));
    rooTotPdf -> plotOn(rooTOYPlot, LineColor(kRed));
    rooTotPdf -> plotOn(rooTOYPlot, Components("rooSIGPdf"), LineColor(kRed));
    rooTOYPlot->Draw();
    
    char pngFileName[50];
    sprintf(pngFileName,"BKGToyFit_H%d_%s.png",mH,mode.c_str());
    c3 -> Print(pngFileName,"png");
  }
  
  
  
  
  
  
  //-------------------------
  // generate toy experiments
  
  TH1F* h_BKGRes = new TH1F("h_BKGRes","",200,-400,400);
  TH1F* h_SIGRes = new TH1F("h_SIGRes","",200,-400,400);
  
  TRandom3 B;
  TRandom3 S;
  for(int j = 0; j < nToys; ++j)
  {
    if( j%100 == 0 )
      std::cout << ">>>>>> generating toy experiment " << j << std::endl;
    
    NBKGToy = B.Poisson(BKGTotShapeHisto->Integral());
    NSIGToy = 0;
    if( mode == "discovery" ) NSIGToy = S.Poisson(SIGShapeHisto->Integral());
    
    rooBKGToyDataSet = rooBKGTotPdf->generate(RooArgSet(x),NBKGToy);
    rooSIGToyDataSet = rooSIGPdf->generate(RooArgSet(x),NSIGToy);
    rooBKGToyDataSet -> append(*rooSIGToyDataSet);
    
    NBKGToy_signal = rooBKGToyDataSet->sumEntries(signalCut);
    NBKGToy_signal_fit = 0.;
    
    
    
    // fit
    if( mode == "exclusion" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1),Range("low,high"));
    if( mode == "discovery" ) rooTotPdf -> fitTo(*rooBKGToyDataSet,Extended(kTRUE),PrintLevel(-1));    
    
    
    
    // count events
    if( mode == "exclusion" )
    {
      RooAbsReal* rooTotIntegral = rooTotPdf -> createIntegral(x,NormSet(x),Range("signal"));
      NBKGToy_signal_fit = rooTotIntegral->getVal() * rooNBKGTot->getVal();
      
      h_BKGRes -> Fill(NBKGToy_signal_fit - NBKGToy_signal);
      h_SIGRes -> Fill(0.);
    }
    
    if( mode == "discovery" )
    {
      h_BKGRes -> Fill(rooNBKGTot->getVal() - NBKGToy);
      h_SIGRes -> Fill(rooNSIG->getVal() - NSIGToy);
    }
    
  }
  
  
  
  outFile -> cd();
  
  h_BKGRes -> Write();
  h_SIGRes -> Write();
  
  outFile -> Close();
}
예제 #18
0
void embeddedToysVBF_1DKD(int nEvts=50, int nToys=100,
		  sample mySample = kScalar_fa3_0){
  

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

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

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

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

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

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

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

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

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

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

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

  RooFitResult *toyfitresults;
  RooRealVar *r_fa3;

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

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

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

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

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

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

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

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

}
예제 #19
0
void MakeSpinPlots::DrawBlindFit(TString tag, TString mcName,TString cosThetaBin){
  TString fitTag="FULLFIT";
  TString cat = "evtcat";
  if(cosThetaBin!=""){
    tag+="_"+cosThetaBin;
    fitTag="FULLCOSTFIT";
    cat = "evtcat_cosT";
  }
  TString dataTag = "_Combined";
  if(cosThetaBin!="") dataTag+="_CosTBin";

  TCanvas *cv = new TCanvas(Form("%s_%s",mcName.Data(),tag.Data()));

  
  RooRealVar* mass = ws->var("mass");
  mass->setBins( (mass->getMax() - mass->getMin())/1.5 ); //enfore 1.5GeV bin width
  RooPlot* frame  = mass->frame();
  double Nb = ws->var(Form("Data_BKGFIT_%s_Nbkg",tag.Data()))->getVal();
  cout << Nb << endl;
  RooDataSet *blind = (RooDataSet*)ws->data("Data"+dataTag)->reduce(TString("((mass<119) || (mass>135.5)) && ")+cat+"=="+cat+"::"+tag);
  blind->plotOn(frame);

  tPair lbl(mcName,tag);
  double nBkg = ws->data("Data"+dataTag)->sumEntries(cat+"=="+cat+"::"+tag);

  ws->pdf( Form("Data_BKGFIT_%s_bkgModel",tag.Data()) )->plotOn(frame,RooFit::Range("all"),RooFit::Normalization(nBkg/blind->sumEntries()),
									       RooFit::LineColor(kRed));

  //TLatex *prelim = new TLatex(250,x->GetXmax()-40.,"CMS Preliminary");
  TLatex *prelim = new TLatex(0.12,0.96,"CMS Preliminary");
  TLatex *lum = new TLatex(0.7,0.96,Form("#sqrt{s}=8 TeV  L = %0.1f fb^{-1}",lumi));
  prelim->SetNDC();
  lum->SetNDC();
  prelim->SetTextSize(0.045);
  prelim->SetTextColor(kBlack);
  lum->SetTextSize(0.045);
  lum->SetTextColor(kBlack);

  TLatex *owner = new TLatex(0.6,0.88,"Caltech-CMS Preliminary");
  owner->SetNDC();
  owner->SetTextSize(0.045);
  owner->SetTextColor(kBlack);

  TLatex *Nbkg = new TLatex(0.7,0.8,Form("N_{bkg}= %0.1f #pm %0.1f",nBackground[lbl].first,nBackground[lbl].second));
  Nbkg->SetNDC();
  Nbkg->SetTextSize(0.045);

  TLatex *sig = new TLatex(0.7,0.72,Form("#sigma_{eff} = %0.1f #pm %0.2f",fitSigEff[lbl].first,fitSigEff[lbl].second));
  sig->SetNDC();
  sig->SetTextSize(0.045);

  TLatex *expBkg = new TLatex(0.7,0.64,Form("B @ 125 = %0.1f",fitBkg1Sigma[lbl].first));
  expBkg->SetNDC();
  expBkg->SetTextSize(0.045);


  frame->addObject(prelim);
  frame->addObject(lum);
  //frame->addObject(owner);
  frame->addObject(Nbkg);
  frame->addObject(sig);
  frame->addObject(expBkg);
  frame->Draw();
  cv->SaveAs( basePath+Form("/mgg-%s-%s-%s_BLIND.png",outputTag.Data(),mcName.Data(),tag.Data()) );
  cv->SaveAs( basePath+Form("/C/mgg-%s-%s-%s_BLIND.C",outputTag.Data(),mcName.Data(),tag.Data()) );
  cv->SaveAs( basePath+Form("/mgg-%s-%s-%s_BLIND.pdf",outputTag.Data(),mcName.Data(),tag.Data()) );
  delete cv;
}
예제 #20
0
int main(int argc, char* argv[]){
 
  string fileName;
  string fileNameZee;  
  string fileNameout;
  string outDir;
  int ncats;
  int jcats;
  int bins; 
  string outfilename;
  string logfile;
  bool verbose=false;
  int mhLow;
  int mhHigh;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h",                                                                                  "Show help")
    ("infilename,i", po::value<string>(&fileName)->default_value("CMS-HGG.root"),                                             "In file name")
    ("infilenameZee,I", po::value<string>(&fileNameZee)->default_value("CMS-HGG_DY_fit.root"),                                  "In file name Zee")   
    ("Outfilename,o", po::value<string>(&fileNameout)->default_value("CMS-HGG_finalBkg.root"),                                              "Out file name")
    ("outDir,D", po::value<string>(&outDir)->default_value("plots/FinalBackground"),                      "Out directory for plots")
    ("logfile,l", po::value<string>(&logfile)->default_value("BackgroundFit.log"),                  "log file of fit results")
    ("ncats,c", po::value<int>(&ncats)->default_value(4),                                       "Number of categories")
    ("jcats,j", po::value<int>(&jcats)->default_value(0),                                       "Start number of categories")
    ("mhLow,L", po::value<int>(&mhLow)->default_value(75),                                                                                                                 "Starting point for scan") 
    ("mhHigh,H", po::value<int>(&mhHigh)->default_value(120),                                                                                                               "End point for scan") 
    ("bins,B", po::value<int>(&bins)->default_value(45),                                                                                                                 "Bins for the dataset") 
    ("verbose,v",                                                                               "Run with more output")
  ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc,argv,desc),vm);
  po::notify(vm);
  if (vm.count("help")) { cout << desc << endl; exit(1); }  
  if (vm.count("verbose")) verbose=true;

  if (!verbose) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
    RooMsgService::instance().setSilentMode(true);
  }


  TFile *outputfile;
  outputfile = new TFile(fileNameout.c_str(),"RECREATE");
  RooWorkspace *outputws;  

  ofstream logfile_stream(logfile.c_str());    

  TFile *inFile = TFile::Open(fileName.c_str());
  RooWorkspace *inWS = (RooWorkspace*)inFile->Get("cms_hgg_workspace");
  outputws = (RooWorkspace*)inWS->Clone("cms_hgg_workspace");   

  std::string ext = "8TeV";

  vector<pair<string,int> > funChoice;   // <functionType,order>

  funChoice.push_back(pair<string,int>("Bernstein",4)); //cat0 
  funChoice.push_back(pair<string,int>("Bernstein",5)); //cat1
  funChoice.push_back(pair<string,int>("Bernstein",5)); //cat2
  funChoice.push_back(pair<string,int>("Bernstein",5)); //cat3


  PdfModelBuilder pdfsModel;
  RooRealVar *mass = (RooRealVar*)inWS->var("CMS_hgg_mass");
  pdfsModel.setObsVar(mass);
  //mass->setBins(bins); 
  //mass->setRange(85,110);


  for (int cat=jcats; cat<ncats; cat++){ 

    RooDataSet *data = (RooDataSet*)inWS->data(Form("data_mass_cat%d",cat));
    //RooDataHist thisdataBinned(Form("roohist_data_mass_cat%d",cat),"data",*mass,*dataFull); //FAN Procedure (from an official script)
    //RooDataSet *data = (RooDataSet*)&thisdataBinned; 

    RooAbsPdf *pdfZee;

    TFile *inFileZee = TFile::Open(fileNameZee.c_str()); 
    RooWorkspace *inWS_Zee = (RooWorkspace*)inFileZee->Get("Zpeak");
    
    cout<<endl<<"///////////////////////////////////"<<endl;
    inWS_Zee->Print();
    cout<<"///////////////////////////////////"<<endl<<endl;
   
    pdfZee = inWS_Zee->pdf(Form("hgg_bkg_%s_cat%d_DCB",ext.c_str(),cat));

    cout<<endl<<"///////////////////////////////////"<<endl;
    pdfZee->Print();
    cout<<"///////////////////////////////////"<<endl<<endl;

    //RooAbsPdf *pdfZeeFixed=pdfsModel.floatDoubleCB(pdfZee,data,Form("hgg_bkg_%s_cat%d_DCB",ext.c_str(),cat));
    RooAbsPdf *pdfZeeFixed=pdfsModel.fixDoubleCB(pdfZee,data,Form("hgg_bkg_%s_cat%d_DCB",ext.c_str(),cat));

    RooAbsPdf  *bkgPdf;
    RooAbsPdf  *berComponent;
    RooAbsPdf  *dcbComponent;


    string funcType = funChoice[cat].first;
    int orderOff = funChoice[cat].second; 
    
    bkgPdf = pdfsModel.getFixedDoubleCBplusContinuum(funcType,Form("hgg_bkg_%s_cat%d",ext.c_str(),cat),orderOff,pdfZeeFixed,false).first;
    berComponent = pdfsModel.getFixedDoubleCBplusContinuum(funcType,Form("hgg_bkg_%s_cat%d",ext.c_str(),cat),orderOff,pdfZeeFixed,false).second.first;
    dcbComponent = pdfsModel.getFixedDoubleCBplusContinuum(funcType,Form("hgg_bkg_%s_cat%d",ext.c_str(),cat),orderOff,pdfZeeFixed,false).second.second;

    cout<<endl<<"///////////////////////////////////"<<endl;
    bkgPdf->Print();
    cout<<"///////////////////////////////////"<<endl<<endl;

    cout<<endl<<"///////////////////////////////////"<<endl;
    bkgPdf->getParameters(data)->Print();
    cout<<"///////////////////////////////////"<<endl<<endl;


    int fitStatus = 0; 
    double thisNll=0.;
    runFit(bkgPdf,data,&thisNll,&fitStatus,3,mhLow,mhHigh);
    //RooFitResult *fitRes = bkgPdf->fitTo(*data,Save(true),Range(mhLow,mhHigh));
    //plot(mass,bkgPdf,data,Form("%s/hgg_bkg_%s_cat%d",outDir.c_str(),ext.c_str(),cat),bins,mhLow,mhHigh);

    //print results in log file


    RooArgSet *params = bkgPdf->getParameters(*data);
          float Mean = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_mean",ext.c_str(),cat)))->getValV();
          float MeanErrorL = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_mean",ext.c_str(),cat)))->getErrorLo();
          float MeanErrorH = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_mean",ext.c_str(),cat)))->getErrorHi(); 
          float Sigma = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_sigma",ext.c_str(),cat)))->getValV();
          float SigmaErrorL = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_sigma",ext.c_str(),cat)))->getErrorLo();
          float SigmaErrorH = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_sigma",ext.c_str(),cat)))->getErrorHi();
          float nCB1 = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB1",ext.c_str(),cat)))->getValV();
          float nCB1ErrorL = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB1",ext.c_str(),cat)))->getErrorLo();
          float nCB1ErrorH = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB1",ext.c_str(),cat)))->getErrorHi();
          float nCB2 = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB2",ext.c_str(),cat)))->getValV();
          float nCB2ErrorL = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB2",ext.c_str(),cat)))->getErrorLo();
          float nCB2ErrorH = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB2",ext.c_str(),cat)))->getErrorHi();
          float alphaCB1 = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_alphaCB1",ext.c_str(),cat)))->getValV();
          float alphaCB2 = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_alphaCB2",ext.c_str(),cat)))->getValV();

	   logfile_stream << Form("**************** cat: %d    ***************",cat) <<endl<<"    nEntries     "<<data->sumEntries() << endl << "    Mean:  " << Mean << "   MeanErrorL:  " << MeanErrorL << " MeanErrorH:  "<< MeanErrorH << "  Sigma:  " << Sigma << "  SigmaErrorL:  " << SigmaErrorL << " SigmaErrorH:  " << SigmaErrorH << "    nCB1:  " << nCB1 << "    nCB1ErrorL:   " << nCB1ErrorL << "   nCB1ErrorH:  " << nCB1ErrorH << "   nCB2:  " << nCB2 << "   nCB2ErrorL:  " << nCB2ErrorL << "    nCB2ErrorH:   " << nCB2ErrorH << "    alphaCB1:   " << alphaCB1 << "    alphaCB2:   " << alphaCB2 << endl;

          float frac = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_frac_sum1",ext.c_str(),cat)))->getValV();
          float fracErrorL = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_frac_sum1",ext.c_str(),cat)))->getErrorLo();
          float fracErrorH = ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_frac_sum1",ext.c_str(),cat)))->getErrorHi();

	   logfile_stream <<"    Frac    "<<frac<<"    FracErrorL    "<<fracErrorL<<"    FracErrorH    "<<fracErrorH<<endl;


      for(int i=0;i<orderOff;i++){
          RooRealVar *coeff=(RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_%s_p%i",ext.c_str(),cat,abbr(funcType).c_str(),i));
	  logfile_stream <<Form("     %s_%i:     ",funcType.c_str(),i)<<coeff->getValV()<<Form("     %s_%i ErrorL:     ",funcType.c_str(),i)<<coeff->getErrorLo()<<Form("     %s_%i ErrorH:     ",funcType.c_str(),i)<<coeff->getErrorHi();
	}
       logfile_stream<<endl;

    plot2(mass,bkgPdf,berComponent,dcbComponent,frac,data,Form("%s/hgg_bkg_%s_cat%d",outDir.c_str(),ext.c_str(),cat),bins,mhLow,mhHigh);

    //Let the DCB parameter float within their uncertaincy range in combine ?
  
    ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_mean",ext.c_str(),cat)))->setConstant(false);
    ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_sigma",ext.c_str(),cat)))->setConstant(false);
    ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB1",ext.c_str(),cat)))->setConstant(false);
    ((RooRealVar*)params->find(Form("hgg_bkg_%s_cat%d_DCB_nCB2",ext.c_str(),cat)))->setConstant(false);

    outputws->var(Form("pdf_data_pol_model_8TeV_cat%d_norm",cat))->SetName(Form("hgg_bkg_8TeV_cat%d_DCBplusBernstein_norm",cat));

    outputws->import(*bkgPdf);

    }

    outputfile->cd();
    outputws->Write();
  
    cout<<endl<<"///////////////////////////////////"<<endl;
    //outputws->Print();
    cout<<"///////////////////////////////////"<<endl<<endl;
    
    outputfile->Close();


}
예제 #21
0
int main(int argc, char* argv[]){
 
  string fileName;
  string fileNameZee;  
  string functionName;
  string fileNameout;
  int ncats;
  int jcats;
  int bins; 
  string outfilename;
  bool is2011=false;
  bool useDoubleCB=false;  
  bool verbose=false;
  int mhLow;
  int mhHigh;



  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h",                                                                                  "Show help")
    ("infilename,i", po::value<string>(&fileName),                                              "In file name")
    ("infilenameZee,I", po::value<string>(&fileNameZee),                                              "In file name Zee")   
    ("function,f", po::value<string>(&functionName),                                              "Function to use")
    ("Outfilename,o", po::value<string>(&fileNameout),                                              "Out file name")
    ("ncats,c", po::value<int>(&ncats)->default_value(5),                                       "Number of categories")
    ("jcats,j", po::value<int>(&jcats)->default_value(0),                                       "Start number of categories")
    ("mhLow,L", po::value<int>(&mhLow)->default_value(75),                                                                                                                 "Starting point for scan") 
    ("mhHigh,H", po::value<int>(&mhHigh)->default_value(120),                                                                                                               "End point for scan") 
    ("bins,B", po::value<int>(&bins)->default_value(180),                                                                                                                 "Bins for the dataset") 
    ("is2011",                                                                                  "Run 2011 config")
    ("useDoubleCB",                                                                                  "use double crystal ball function")   
    ("verbose,v",                                                                               "Run with more output")
  ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc,argv,desc),vm);
  po::notify(vm);
  if (vm.count("help")) { cout << desc << endl; exit(1); }
  if (vm.count("is2011")) is2011=true;
  if (vm.count("useDoubleCB"))  useDoubleCB=true;   
  if (vm.count("verbose")) verbose=true;

  if (!verbose) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
    RooMsgService::instance().setSilentMode(true);
  }


  TFile *outputfile;
  //RooWorkspace *outputws = new RooWorkspace("cms_hgg_workspace");  
  RooWorkspace *outputws;  
  outputfile = new TFile(fileNameout.c_str(),"RECREATE");

  
  
  TFile *inFile = TFile::Open(fileName.c_str());
  RooWorkspace *inWS = (RooWorkspace*)inFile->Get("cms_hgg_workspace");
  outputws = (RooWorkspace*)inWS->Clone("cms_hgg_workspace");   
  



  vector<string> functionClasses;
  functionClasses.push_back("Chebychev");
  functionClasses.push_back("Bernstein");
  functionClasses.push_back("Exponential");
  functionClasses.push_back("PowerLaw");
  functionClasses.push_back("Laurent");
  
  map<string,string> namingMap;
  namingMap.insert(pair<string,string>("Bernstein","pol"));  
  namingMap.insert(pair<string,string>("Exponential","exp"));
  namingMap.insert(pair<string,string>("PowerLaw","pow"));
  namingMap.insert(pair<string,string>("Laurent","lau"));
  
  vector<pair<pair<string,int> ,pair<pair<int,int>, pair<float,float> > > >  fabChoice;
  int sqrts; string ext;
  if (is2011) {
    sqrts = 7;
    ext = "7TeV";
  }
  else {
    sqrts = 8;
    ext = "8TeV";
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Bernstein",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //0 
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Bernstein",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //1
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Chebychev",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //2
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Bernstein",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //3
  }

  // store results here

  PdfModelBuilderFAN pdfsModel;
  RooRealVar *mass = (RooRealVar*)inWS->var("CMS_hgg_mass");
  mass->setRange(mhLow,mhHigh); 
  pdfsModel.setObsVar(mass);
  mass->setBins(bins); 
  ofstream outfile("Zee_Yield.log");  

cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Initialization Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

  for (int cat=jcats; cat<ncats; cat++){ 
   
     
      
    RooDataSet *dataFull = (RooDataSet*)inWS->data(Form("data_mass_cat%d",cat));
    RooDataHist thisdataBinned(Form("roohist_data_mass_cat%d",cat),"data",*mass,*dataFull);
    RooDataSet *data = (RooDataSet*)&thisdataBinned; 
         

    string funcType = fabChoice[cat].first.first;
    float LaurentConstant = fabChoice[cat].first.second; 
    int orderOff = fabChoice[cat].second.first.first; 
    int orderBre = fabChoice[cat].second.first.second;
    float bernDownBound = fabChoice[cat].second.second.first;
    float bernUpBound = fabChoice[cat].second.second.second; 

    RooAbsPdf *pdfVoiFix; float voiMean=0.; float voiMeanErrorL=0.; float voiMeanErrorH=0.; float voiSigma=0.; float voiSigmaErrorL=0.; float voiSigmaErrorH=0.; float voiWidth=0;  float voiWidthErrorL=0.; float voiWidthErrorH=0.; float voinCB1=0.; float voinCB1ErrorL=0.; float voinCB1ErrorH=0.; float voinCB2=0.; float voinCB2ErrorL=0.; float voinCB2ErrorH=0.; float voialphaCB1=0.; float voialphaCB2=0.; float ErrorRange=1.0;
    if(orderBre != 0){
         TFile *inFileZee = TFile::Open(fileNameZee.c_str()); 
         RooWorkspace *inWS_Zee = (RooWorkspace*)inFileZee->Get("fTestVoi_Zee");
         if(!useDoubleCB)  pdfVoiFix = inWS_Zee->pdf(Form("ftest_Zee_Voi_%s_cat%d",ext.c_str(),cat));
         else pdfVoiFix = inWS_Zee->pdf(Form("ftest_Zee_DCB_%s_cat%d",ext.c_str(),cat));

cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Get Zee Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

         if(pdfVoiFix!=NULL){
              if(!useDoubleCB){
                   ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->setConstant(true);
                   voiMean = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->getValV();
                   voiMeanErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorLo();
                   voiMeanErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorHi();

                   ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->setConstant(true);
                   voiSigma = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getValV();    
                   voiSigmaErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorLo();    
                   voiSigmaErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorHi();    

                   ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->setConstant(true);
                   voiWidth = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->getValV();
                   voiWidthErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->getErrorLo();
                   voiWidthErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->getErrorHi();
              }else{
                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->setConstant(true);
                  voiMean = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->getValV();
                  voiMeanErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorLo();
                  voiMeanErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->setConstant(true);
                  voiSigma = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getValV();
                  voiSigmaErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorLo();
                  voiSigmaErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->setConstant(true);
                  voinCB1 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->getValV();
                  voinCB1ErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->getErrorLo();
                  voinCB1ErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->setConstant(true);
                  voinCB2 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->getValV();
                  voinCB2ErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->getErrorLo();
                  voinCB2ErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB1_p0",ext.c_str(),cat)))->setConstant(true);
                  voialphaCB1 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB1_p0",ext.c_str(),cat)))->getValV();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB2_p0",ext.c_str(),cat)))->setConstant(true);
                  voialphaCB2 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB2_p0",ext.c_str(),cat)))->getValV();
              }
         }
    }
    else{
         pdfVoiFix = 0;
    }
 
cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Get Zee Params Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

    RooAbsPdf *bkgPdf;
    if(orderBre == 0){
        bkgPdf = getPdf(pdfsModel, funcType, orderOff, Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat), LaurentConstant); 
        bkgPdf->SetName(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat));
    }
    else{ 
        if(functionName == "Voi"){
            if(!useDoubleCB){
                  bkgPdf = getPdfSumVoigtianFixNew(pdfsModel, funcType, orderOff, voiMean, voiMeanErrorL, voiMeanErrorH, voiSigma, voiSigmaErrorL, voiSigmaErrorH, voiWidth, voiWidthErrorL, voiWidthErrorH, ErrorRange, Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat), LaurentConstant, bernDownBound, bernUpBound).first;   
            }else{
                  bkgPdf = getPdfSumVoigtianFixNewDouleCB(pdfsModel, funcType, orderOff, voiMean, voiMeanErrorL, voiMeanErrorH, voiSigma, voiSigmaErrorL, voiSigmaErrorH, voinCB1, voinCB1ErrorL, voinCB1ErrorH, voinCB2, voinCB2ErrorL, voinCB2ErrorH, voialphaCB1, voialphaCB2, ErrorRange, Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat), LaurentConstant, bernDownBound, bernUpBound).first;     
            }
        }
        bkgPdf->SetName(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat));
    }

    RooArgSet *params = bkgPdf->getParameters(*data);
    params->Print("v");

cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Prepare Final Pdf Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

    RooFitResult *fitRes = bkgPdf->fitTo(*data,Save(true),Range(mhLow,mhHigh));
   
    fitRes->floatParsInit().Print("v"); 
    fitRes->floatParsFinal().Print("v"); 
    


    if(voiMean != 0){
         if(!useDoubleCB){
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fvoimean",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fvoisigma",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fvoiwidth",cat)))->setConstant(false);
         }else{
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fdcbmean",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fdcbsigma",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_FdcbnCB1",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_FdcbnCB2",cat)))->setConstant(false);
         }

         params->Print("v");

         
         float BernFrac = ((RooRealVar*)fitRes->floatParsFinal().find(Form("pdf_data_pol_model_8TeV_cat%d_frac_sum1",cat)))->getValV();
         if(!useDoubleCB){
              outfile << Form("cat %d   ",cat) << data->sumEntries()*(1.0-BernFrac) << "   Mean " << voiMean << "   voiMeanErrorL  " << voiMeanErrorL << " voiMeanErrorH  "<< voiMeanErrorH << "  voiSigma  " << voiSigma << "  voiSigmaErrorL  " << voiSigmaErrorL << " voiSigmaErrorH  " << voiSigmaErrorH << "  voiWidth  " << voiWidth << "  voiWidthErrorL  " << voiWidthErrorL << " voiWidthErrorH  " << voiWidthErrorH << endl;
              outfile << endl;
         }else{
              outfile << Form("cat %d    ",cat) << data->sumEntries()*(1.0-BernFrac) << "    Mean " << voiMean << "   voiMeanErrorL  " << voiMeanErrorL << " voiMeanErrorH  "<< voiMeanErrorH << "  voiSigma  " << voiSigma << "  voiSigmaErrorL  " << voiSigmaErrorL << " voiSigmaErrorH  " << voiSigmaErrorH << "    nCB1  " << voinCB1 << "    nCB1ErrorL   " << voinCB1ErrorL << "   nCB1ErrorH  " << voinCB1ErrorH << "   nCB2  " << voinCB2 << "   nCB2ErrorL  " << voinCB2ErrorL << "    nCB2ErrorH   " << voinCB2ErrorH << "bernfrac "<<BernFrac<< endl;

         }
         

    }

    outputws->pdf(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat))->SetName(Form("pdf_data_pol_model_%dTeV_cat%d_OLD",sqrts,cat));
    outputws->import(*bkgPdf);
    //outputws->import(*data);

    outputws->pdf(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat))->Print();



    outputws->data(Form("data_mass_cat%d",cat))->Print("v");
   

    outputws->data(Form("roohist_data_mass_cat%d",cat))->Print("v");




 

    
  }




  
  outputfile->cd();
  outputws->Write();
  outputfile->Close();   


}