Beispiel #1
0
void chi2(int xmin = 0, int xmax = 200, TString filename="../DsubMC/met2j0bIso2ewkScale_0_200.root", int nparam = 2){
RooAbsData::ErrorType errorType = RooAbsData::SumW2;

file = new TFile(filename);
RooRealVar* h = new RooRealVar("h","h",xmin,xmax); 

//Get Data
TH1D* hData = file->Get("dataih");
hData->SetName("hData");
//hData->Draw();
RooDataHist* data = new RooDataHist("data","data",*h,hData);

//Get Summed MC
TH1D* hMC = file->Get("hh");
hMC->SetName("hMC");
hMC->Draw();
RooDataHist rdhMC("MC","MC",*h,hMC);
RooHistPdf pdfMC("MCpdf","MCpdf",*h,rdhMC);

//make (plot) the curves
RooPlot* hFrame = h->frame(Name("hFrame"));
data->plotOn(hFrame,RooFit::DataError(errorType));
pdfMC.plotOn(hFrame,ProjWData(*data),Components(pdfMC),Name("h_total"));

//Determine Chi^2
double chi2fit = hFrame->chiSquare("h_total", "h_data", nparam);
cout<<"Chi 2 / dof: "<<chi2fit<<endl;

//Determine K-S
double ks = hMC->KolmogorovTest(hData);
cout<<"Kolmogorov-Smirnov: "<<ks<<endl;
}
void makeDataset( TString fname, TString tname, TString outfname ) {

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

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

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

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

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

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

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

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

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

    tree->GetEntry(ev);

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

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

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

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

  }
  tf->Close();

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

  w->writeToFile(outfname);

}
Beispiel #3
0
void rf903_numintcache(Int_t mode=0)
{
   // Mode = 0 : Run plain fit (slow)
   // Mode = 1 : Generate workspace with pre-calculated integral and store it on file (prepare for accelerated running)
   // Mode = 2 : Run fit from previously stored workspace including cached integrals (fast, requires run in mode=1 first)

   // C r e a t e ,   s a v e   o r   l o a d   w o r k s p a c e   w i t h   p . d . f .
   // -----------------------------------------------------------------------------------

   // Make/load workspace, exit here in mode 1
   RooWorkspace* w1 = getWorkspace(mode) ;
   if (mode==1) {

      // Show workspace that was created
      w1->Print() ;

      // Show plot of cached integral values
      RooDataHist* hhcache = (RooDataHist*) w1->expensiveObjectCache().getObj(1) ;
      if (hhcache) {

         new TCanvas("rf903_numintcache","rf903_numintcache",600,600) ;
         hhcache->createHistogram("a")->Draw() ;

      }
      else {
         Error("rf903_numintcache","Cached histogram is not existing in workspace");
      }
         return ;
   }

   // U s e   p . d . f .   f r o m   w o r k s p a c e   f o r   g e n e r a t i o n   a n d   f i t t i n g
   // -----------------------------------------------------------------------------------

   // This is always slow (need to find maximum function value empirically in 3D space)
   RooDataSet* d = w1->pdf("model")->generate(RooArgSet(*w1->var("x"),*w1->var("y"),*w1->var("z")),1000) ;

   // This is slow in mode 0, but fast in mode 1
   w1->pdf("model")->fitTo(*d,Verbose(kTRUE),Timer(kTRUE)) ;

   // Projection on x (always slow as 2D integral over Y,Z at fitted value of a is not cached)
   RooPlot* framex = w1->var("x")->frame(Title("Projection of 3D model on X")) ;
   d->plotOn(framex) ;
   w1->pdf("model")->plotOn(framex) ;

   // Draw x projection on canvas
   new TCanvas("rf903_numintcache","rf903_numintcache",600,600) ;
   framex->Draw() ;

   // Make workspace available on command line after macro finishes
   gDirectory->Add(w1) ;

   return ;

}
Beispiel #4
0
//_________________________________________________
void TestJeffreysGaussSigma(){
  // this one is VERY sensitive
  // if the Gaussian is narrow ~ range(x)/nbins(x) then the peak isn't resolved
  //   and you get really bizzare shapes
  // if the Gaussian is too wide range(x) ~ sigma then PDF gets renormalized
  //   and the PDF falls off too fast at high sigma
  RooWorkspace w("w");
  w.factory("Gaussian::g(x[0,-20,20],mu[0,-5,5],sigma[1,1,5])");
  w.factory("n[100,.1,2000]");
  w.factory("ExtendPdf::p(g,n)");
  //  w.var("sigma")->setConstant();
  w.var("mu")->setConstant();
  w.var("n")->setConstant();
  w.var("x")->setBins(301);

  RooDataHist* asimov = w.pdf("p")->generateBinned(*w.var("x"),ExpectedData());

  RooFitResult* res = w.pdf("p")->fitTo(*asimov,Save(),SumW2Error(kTRUE));

  asimov->Print();
  res->Print();
  TMatrixDSym cov = res->covarianceMatrix();
  cout << "variance = " << (cov.Determinant()) << endl;
  cout << "stdev = " << sqrt(cov.Determinant()) << endl;
  cov.Invert();
  cout << "jeffreys = " << sqrt(cov.Determinant()) << endl;


  //  w.defineSet("poi","mu,sigma");
  //w.defineSet("poi","mu,sigma,n");
  w.defineSet("poi","sigma");
  w.defineSet("obs","x");

  RooJeffreysPrior pi("jeffreys","jeffreys",*w.pdf("p"),*w.set("poi"),*w.set("obs"));
  //  pi.specialIntegratorConfig(kTRUE)->method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D")  ;
  pi.specialIntegratorConfig(kTRUE)->getConfigSection("RooIntegrator1D").setRealValue("maxSteps",3);

  const RooArgSet* temp = w.set("poi");
  pi.getParameters(*temp)->Print();
  //  return;

  //  return;
  RooGenericPdf* test = new RooGenericPdf("test","test","sqrt(2.)/sigma",*w.set("poi"));

  TCanvas* c1 = new TCanvas;
  RooPlot* plot = w.var("sigma")->frame();
  pi.plotOn(plot);
  test->plotOn(plot,LineColor(kRed),LineStyle(kDotted));
  plot->Draw();


}
Beispiel #5
0
void JeffreysPriorDemo(){
  RooWorkspace w("w");
  w.factory("Uniform::u(x[0,1])");
  w.factory("mu[100,1,200]");
  w.factory("ExtendPdf::p(u,mu)");

  //  w.factory("Poisson::pois(n[0,inf],mu)");

  RooDataHist* asimov = w.pdf("p")->generateBinned(*w.var("x"),ExpectedData());
  //  RooDataHist* asimov2 = w.pdf("pois")->generateBinned(*w.var("n"),ExpectedData());

  RooFitResult* res = w.pdf("p")->fitTo(*asimov,Save(),SumW2Error(kTRUE));

  asimov->Print();
  res->Print();
  TMatrixDSym cov = res->covarianceMatrix();
  cout << "variance = " << (cov.Determinant()) << endl;
  cout << "stdev = " << sqrt(cov.Determinant()) << endl;
  cov.Invert();
  cout << "jeffreys = " << sqrt(cov.Determinant()) << endl;

  w.defineSet("poi","mu");
  w.defineSet("obs","x");
  //  w.defineSet("obs2","n");

  RooJeffreysPrior pi("jeffreys","jeffreys",*w.pdf("p"),*w.set("poi"),*w.set("obs"));
  //  pi.specialIntegratorConfig(kTRUE)->method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D")  ;
  //  pi.specialIntegratorConfig(kTRUE)->getConfigSection("RooIntegrator1D").setRealValue("maxSteps",10);

  //  JeffreysPrior pi2("jeffreys2","jeffreys",*w.pdf("pois"),*w.set("poi"),*w.set("obs2"));

  //  return;
  RooGenericPdf* test = new RooGenericPdf("test","test","1./sqrt(mu)",*w.set("poi"));

  TCanvas* c1 = new TCanvas;
  RooPlot* plot = w.var("mu")->frame();
  //  pi.plotOn(plot, Normalization(1,RooAbsReal::Raw),Precision(.1));
  pi.plotOn(plot);
  //  pi2.plotOn(plot,LineColor(kGreen),LineStyle(kDotted));
  test->plotOn(plot,LineColor(kRed));
  plot->Draw();

}
Beispiel #6
0
void MCStudy()
{
    
    string fileName = "h4l_Template_2012_lowmass_unconstrained_new_v00.root";
    
    const char * wsName      = "combined";    //"w";
    const char * modelSBName = "ModelConfig"; //"modelConfig";
    const char * dataName    = dataname.c_str();
    
    TFile* file = TFile::Open(fileName);

    // get the workspace out of file
    RooWorkspace* w = (RooWorkspace*) file->Get(wsName);
    if (!wsName) {
        cout << "workspace not found" << endl;
        return -1.0;
    }
    
    // get the modelConfig out of the file
    ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
    
    // get the data out of file
    //RooAbsData* data = w->data(dataName);
    
    // get toy MC data
    TFile *fhist = new TFile("../ToyMC/toyMC_ggF125.root");
    TH1F *hsum = (TH1F*) fhist->Get("sumtoy1");
    
    RooRealVar m4l("m4l","m4l",120,130);
    RooDataHist* data = new RooDataHist("data","data",x,hsum);
    
    // get pdf
    RooAbsPdf* model = sbModel->GetPdf();
    
    RooPlot* xframe = m4l.frame();
    data->plotOn(xframe);
    model->fitTo(*data);
    model->plotOn(xframe,LineColor(kRed));
    
    TCanvas *c = new TCanvas("c","c");
    xframe->Draw();
    
}
Beispiel #7
0
//_________________________________________________
void TestJeffreysGaussMean(){
  RooWorkspace w("w");
  w.factory("Gaussian::g(x[0,-20,20],mu[0,-5,5],sigma[1,0,10])");
  w.factory("n[10,.1,200]");
  w.factory("ExtendPdf::p(g,n)");
  w.var("sigma")->setConstant();
  w.var("n")->setConstant();

  RooDataHist* asimov = w.pdf("p")->generateBinned(*w.var("x"),ExpectedData());

  RooFitResult* res = w.pdf("p")->fitTo(*asimov,Save(),SumW2Error(kTRUE));

  asimov->Print();
  res->Print();
  TMatrixDSym cov = res->covarianceMatrix();
  cout << "variance = " << (cov.Determinant()) << endl;
  cout << "stdev = " << sqrt(cov.Determinant()) << endl;
  cov.Invert();
  cout << "jeffreys = " << sqrt(cov.Determinant()) << endl;

  //  w.defineSet("poi","mu,sigma");
  w.defineSet("poi","mu");
  w.defineSet("obs","x");

  RooJeffreysPrior pi("jeffreys","jeffreys",*w.pdf("p"),*w.set("poi"),*w.set("obs"));
  //  pi.specialIntegratorConfig(kTRUE)->method1D().setLabel("RooAdaptiveGaussKronrodIntegrator1D")  ;
  //  pi.specialIntegratorConfig(kTRUE)->getConfigSection("RooIntegrator1D").setRealValue("maxSteps",3);

  const RooArgSet* temp = w.set("poi");
  pi.getParameters(*temp)->Print();

  //  return;
  RooGenericPdf* test = new RooGenericPdf("test","test","1",*w.set("poi"));

  TCanvas* c1 = new TCanvas;
  RooPlot* plot = w.var("mu")->frame();
  pi.plotOn(plot);
  test->plotOn(plot,LineColor(kRed),LineStyle(kDotted));
  plot->Draw();


}
Beispiel #8
0
void simul(){

	TFile* in = new TFile( "../bin/Kdata.root", "READ" );

	TH1D* h = in->Get("tof_8");

	RooRealVar * x = new RooRealVar( "x", "x", -10, 10 );

	RooDataHist * rdh = new RooDataHist( "data", "data", RooArgSet( *x ), h);

	RooRealVar m( "mean", "mean", 0, -1, 1 );
	RooRealVar s( "sigma", "sigma", .5, 0, 1 );
	RooGaussian g( "gauss", "gauss", )

	RooPlot * frame = x->frame();
	rdh->plotOn( frame );
	frame->Draw();
	

}
Beispiel #9
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()) );
}
Beispiel #10
0
RooFitResult* fitter_Zee(TH1D *hist){

  RooRealVar  Zmassvar("Zmassvar","Zmassvar", 82, 100);
  RooDataHist *datahist = new RooDataHist("data","Z Mass",Zmassvar,hist);
  RooPlot *Zmassvarframe = Zmassvar.frame(Name("Zmassvarframe"),Title(hist->GetTitle())) ;
  datahist->plotOn(Zmassvarframe);
  
  RooRealVar alpha  ("alpha"  ,        "alpha" , 0.005,0.001,0.1); 
  RooRealVar n      ("n"      ,            "n" , 1,0.001,10); 
  RooRealVar cbmean ("cbmean" ,       "cbmean" , 1, 0.8, 1.2);
  RooRealVar cbsigma("cbsigma",      "cbsigma" , 0.01, 0.001, 0.2);

  RooRealVar bwmean("bwmean","bwmean",91,85,95);
  RooRealVar bwsigma("bwsigma","bwsigma",3,2,4);
  RooRealVar expoconst("expoconst","expoconst",-0.1,-0.5,0);

  RooCBShape cball  ("cball"  , "crystal ball" , Zmassvar, cbmean, cbsigma, alpha, n);
  RooBreitWigner bw("bw","breit wigner",Zmassvar,bwmean,bwsigma);

  RooFFTConvPdf cballXbw("cballXbw","cball (X) bw",Zmassvar,bw,cball);
  RooExponential expo("expo", "exponential", Zmassvar, expoconst);

  RooRealVar frac("frac","frac",0.1,0.001,0.2);

  RooAddPdf Zshapemodel("Zshapemodel","expo + cball (X) bw",RooArgList(expo,cballXbw),frac);


  RooFitResult *fitres =Zshapemodel.fitTo(*datahist,Range(82,100),Save());   
  Zshapemodel.plotOn(Zmassvarframe,LineColor(kBlue));

  Zmassvarframe->Draw();

  fitres->Print();

  return fitres;

};
Beispiel #11
0
int scaleSmearFit(TString RDFile, TString MCFile, char BaseName[30])
{
  cout<<"Processing "<<BaseName<<endl;
  gStyle->SetPalette(1);
  //Data and histograms
  TFile *f_RD = new TFile(RDFile);
  TFile *f_MC = new TFile(MCFile);
  TH1D *h1_ZmassDaughEtaRD = (TH1D*)f_RD->Get("h1_ZmassDaughEtaRD")->Clone();
  TH1D *h1_ZmassDaughEtaMC[ScaleBins][ScaleBins];
  //Variables
  char histName[30];
  RooRealVar zMass("zMass","zMass",60,120);
  RooRealVar *nMC;
  RooRealVar nBRD("nBRD","nBRD",5,2000);
  RooRealVar nSRD("nSRD","nSRD",1000,0,20000);
  RooRealVar nBMC("nBMC","nBMC",5,2000);
  RooRealVar nSMC("nSMC","nSMC",1000,0,20000);
  RooPlot *zmassframe;
  RooPlot *zmassframeMC;
  CPlot *plotFit;
  CPlot *plotFitMC;
  //zMass.setBins(50);
  RooFitResult* fitRes;
  RooFitResult* fitResMC;
  TCanvas *myCan = MakeCanvas("myCan","myCan",800,600);
  RooDataHist *ZmassMC;
  //RooHistPdf *pdfMC;
  RooAddPdf *pdfMC;
  RooAddPdf* pdfRD;
  //RD fitting
  RooDataHist *ZmassRD =
    new RooDataHist("ZmassRD","ZmassRD", RooArgSet(zMass),h1_ZmassDaughEtaRD);
  //CBreitWignerConvCrystalBall ZsignalPdf("ZsigPdf",zMass);
  //pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsignalPdf.model)),RooArgList(nRD));
  CVoigtian     ZsigRD("ZsigRD",zMass);
  CErfExpo ZbgRD("ZbgRD",zMass);
  //CQuadraticExp ZbgRD("ZbgRD",zMass);
  pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD));
  pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD));
  fitRes=pdfRD->fitTo(*ZmassRD,Extended(),Minos(kTRUE),Save(kTRUE));
  //fitRes=ZsignalPdf.model->fitTo(*ZmassRD,Minos(kTRUE),Save(kTRUE));
  zmassframe=zMass.frame(Bins(60));
  ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp"));
  //ZsignalPdf.model->plotOn(zmassframe,LineColor(kBlue),DrawOption("l"));
  pdfRD->plotOn(zmassframe,LineColor(kBlack),DrawOption("l"));
  pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZsigRD.model))),LineColor(kBlue),DrawOption("l"));
  pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZbgRD.model))),LineColor(kRed),DrawOption("l"));
  sprintf(histName,"ZmassRD_%s",BaseName);
  plotFit = new CPlot(histName,zmassframe,"","","Z mass");
  plotFit->setOutDir("Plot");
  plotFit->Draw(myCan,kTRUE,"png");

  //CErfExpo *pdfZbg;
  //double nLL[41][41];

  //                                 90 0.004
  double ScaleWidth = (ScaleH-ScaleL)/(ScaleBins-1);
  double SmearWidth = (SmearH-SmearL)/(ScaleBins-1);
  sprintf(histName,"h2_NLL_%s",BaseName);
  TH2D *h2_NLL = new TH2D(histName,histName,
      ScaleBins,ScaleL-ScaleWidth/2,ScaleH+ScaleWidth/2,
      ScaleBins,SmearL-SmearWidth/2,SmearH+SmearWidth/2);
  //TH2D *h2_NLL = new TH2D("h2_NLL","NLL",41,0.97,1.05,41,0.5,1.5);
  double x,prob;
  //RooAbsReal *nll;
  double nll;
  double binContent;
  //***
  CVoigtian ZsigMC("ZsigMC",zMass);
  RooArgSet allArgset(zMass);
  RooArgSet anaVar;
  //for(int i(0);i<=0;i++)for(int j(0);j<=0;j++)
  for(int i(0);i<=ScaleBins-1;i++)for(int j(0);j<=ScaleBins-1;j++)
  {
    sprintf(histName,"h1_ZmassDaughEta_%d_%d",i,j);
    h1_ZmassDaughEtaMC[i][j] = (TH1D*)f_MC->Get(histName)->Clone(histName);
    ZmassMC =
      new RooDataHist("ZmassMC","ZmassMC",RooArgSet(zMass),h1_ZmassDaughEtaMC[i][j]);
    //                                               interpolation order
    //pdfMC =new RooHistPdf ("pdfMC", "pdfMC", zMass,*ZmassMC, 1);
    //Using fitting MC
    nSMC.setVal(285);
    ZsigMC.mass->setVal(91.37);
    ZsigMC.sigma->setVal(0.42);
    ZsigMC.width->setVal(4.4);
    pdfMC = new RooAddPdf("pdfMC","pdfMC",RooArgList(*(ZsigMC.model)),RooArgList(nSMC));
    fitResMC = pdfMC->fitTo(*ZmassMC,Extended(),Minos(kTRUE),Save(kTRUE),SumW2Error(kTRUE));//SumW2Error(kTRUE) default

    nll=0;
    //nll= h1_ZmassDaughEtaMC[i][j]->Chi2Test(h1_ZmassDaughEtaRD,"CHI2/NDF");
    // code 1000 dataHist sum
    int intCode = pdfMC->getAnalyticalIntegral(allArgset,anaVar);
    double norm = pdfMC->analyticalIntegral(intCode);
    cout<<"norm: code "<<norm<<" : "<<intCode<<"======================"<<endl;
    //double totalProb(0);
    //****
    for(int k(1);k<=60;k++)
    {
      x=h1_ZmassDaughEtaMC[i][j]->GetBinCenter(k);
    //  binContent = h1_ZmassDaughEtaRD->GetBinContent(k);
      //binContent = h1_ZmassDaughEtaMC[i][j]->GetBinContent(k);
      zMass=x;
      //prob = ZsignalPdf.model->evaluate();
      binContent = ZsigRD.model->evaluate()*(120-60)/60.*nSRD.getVal();
      prob = pdfMC->evaluate()*(120-60)/60.;
      //cout<<"binCont, prob "<<binContent<<" "<<prob<<endl;
      //totalProb +=prob;
      nll+=-binContent*log(prob);
      //cout<<" x: prob "<<x<<"  "<<prob<<endl;
    }
    h2_NLL->SetBinContent(i+1,j+1,nll);
    /***/
    //
    //
    if( j==0 || j==int(ScaleBins/2)|| j==(ScaleBins-1) )
    {
      //RD MCpdf RDpdf Plot
      zmassframe =zMass.frame(Bins(60));
      ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp"));
      pdfRD->plotOn(zmassframe,LineColor(kBlack));
      pdfMC->plotOn(zmassframe,LineColor(kBlue));
      //pdfRD->plotOn(zmassframe,Components(RooArgSet(*(pdfZbg->model))),LineColor(kRed));
      sprintf(histName,"Zmass_%s_%d_%d",BaseName,i,j);
      plotFit = new CPlot(histName,zmassframe,"","","Z mass");
      plotFit->SetLegend(0.68,0.57,0.93,0.8);
      plotFit->GetLegend()->AddEntry(pdfRD,"RD","f");
      plotFit->GetLegend()->AddEntry(pdfMC,"MC","f");
      plotFit->setOutDir("Plot");
      plotFit->Draw(myCan,kTRUE,"png");
      //MC MCPdf Plot
      zmassframeMC = zMass.frame(Bins(60));
      ZmassMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("p"));
      pdfMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("l"));
      sprintf(histName,"ZmassMC_%s_%d_%d",BaseName,i,j);
      plotFitMC = new CPlot(histName,zmassframeMC,"","","Z mass MC");
      plotFitMC->setOutDir("Plot");
      plotFitMC->Draw(myCan,kTRUE,"png");
    }
  }
  //====
  //Plot
  //====
  //Zmass----------
  //CPlot *plotZmassRD=new CPlot("plotZmassRD","","zMass","Event");
  //plotZmassRD->setOutDir("Plot");
  //plotZmassRD->AddHist1D(h1_ZmassDaughEtaRD,"",kBlack);
  //plotZmassRD->SetLegend(0.68,0.57,0.93,0.8);
  //plotZmassRD->GetLegend()->AddEntry(h1_ZmassDaughEtaRD,"RD Ele","l");
  //plotZmassRD->AddTextBox("both lepton at the |Eta|<0.4",0.65,0.80,0.99,0.86,0);
  //plotZmassRD->Draw(myCan,kTRUE,"png");
  //NLL------------
  sprintf(histName,"plotNLL_%s",BaseName);
  CPlot *plotNll=new CPlot(histName,"","Scale","Smear");
  plotNll->setOutDir("Plot");
  //plotNll->AddHist2D(h2_NLL,"COLZ",kWhite,kBlack);
  plotNll->AddHist2D(h2_NLL,"SURF3",kWhite,kBlack);
  plotNll->Draw(myCan,kTRUE,"png");
  //****/
  return 0;
}
Beispiel #12
0
RooAddPdf fitScaledMuMuGammaMass(
  const char *histoname = "scaledMmgMass_00",
  const char *filename = "scaledMmgHistos.root",
  const char* plotOpt = "NEU",
  const int nbins = 20)
{
  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  gStyle->SetPadRightMargin(0.05);

  double minMass = 60;
  double maxMass = 120;
  RooRealVar  mass("mass","m(#mu#mu#gamma)", minMass, maxMass,"GeV/c^{2}");

  // Read data set

  TFile * file = new TFile(filename);
  TH1F * hh = (TH1F*) file->Get(histoname);
  if (!hh) {
    cout << "Didn't find " << histoname << " in " << filename << endl;
    return;
  }
  RooDataHist *data = new RooDataHist("data", "data", RooArgSet(mass), hh);
//   RooDataSet *data = RooDataSet::read(filename,RooArgSet(mass));
//   RooDataSet *dataB = RooDataSet::read(filenameB,RooArgSet(mass));

// Build p.d.f.

////////////////////////////////////////////////
//             Parameters                     //
////////////////////////////////////////////////

//  Signal p.d.f. parameters
//  Parameters for a Gaussian and a Crystal Ball Lineshape
  RooRealVar  cbBias ("#Deltam_{CB}", "CB Bias", 0.05, -10, 10,"GeV/c^{2}");
  RooRealVar  cbSigma("#sigma_{CB}","CB Width", 1.6, 0.001, 10.0,"GeV/c^{2}");
  RooRealVar  cbCut  ("a_{CB}","CB Cut", 1.5, 0.1, 2.0);
  RooRealVar  cbPower("n_{CB}","CB Power", 1.3, 0.1, 20.0);

//   cbSigma.setConstant(kTRUE);
//   cbCut.setConstant(kTRUE);
//   cbPower.setConstant(kTRUE);

//  Parameters for Breit-Wigner
  RooRealVar bwMean("m_{Z}","BW Mean", 91.1876, "GeV/c^{2}");
  RooRealVar bwWidth("#Gamma_{Z}", "BW Width", 2.4952, "GeV/c^{2}");

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


//  Background p.d.f. parameters
// Parameters for exponential
  RooRealVar expRate("#lambda_{exp}", "Exponential Rate", -0.119, -10, 1);

//   expRate.setConstant(kTRUE);



// fraction of signal
//  RooRealVar  frac("frac", "Signal Fraction", 0.1,0.,0.3.);
/*  RooRealVar  nsig("N_{S}", "#signal events", 9000, 0.,10000.);
  RooRealVar  nbkg("N_{B}", "#background events", 1000,2,10000.);*/
  RooRealVar  nsig("N_{S}", "#signal events", 29300, 0.1, 100000.);
  RooRealVar  nbkg("N_{B}", "#background events", 0, 0., 10000.);

//   nbkg.setConstant(kTRUE);



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

// Di-photon mass signal p.d.f.
  RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth);
//   RooGaussian    signal("signal", "A  Gaussian Lineshape", mass, m0, sigma);
  RooCBShape     cball("cball", "A  Crystal Ball Lineshape", mass, cbBias, cbSigma, cbCut, cbPower);

  mass.setBins(100000, "fft");
  RooFFTConvPdf BWxCB("BWxCB","bw (X) crystall ball", mass, bw, cball);


// Di-photon mass background  p.d.f.
  RooExponential bg("bg","bkgd exp", mass, expRate);

// Di-photon mass model p.d.f.
  RooAddPdf      model("model", "signal + background mass model", RooArgList(BWxCB, bg), RooArgList(nsig, nbkg));


  TStopwatch t ;
  t.Start() ;
  model.fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));
//   signal->fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));

  t.Print() ;

  TCanvas *c = new TCanvas("c","Unbinned Invariant Mass Fit", 0,0,800,600);
// Plot the fit results
  RooPlot* plot = mass.frame(Range(minMass,maxMass)/*,Bins(nbins)*/);

// Plot 1
//   dataB->plotOn(plot, MarkerColor(kRed), LineColor(kRed));
  data->plotOn(plot);
//   model.plotOn(plot);
  model.plotOn(plot);
  //model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(nsig, nbkg, m0, sigma)));
  model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(cbBias, cbSigma, cbCut, cbPower, bwMean, bwWidth, expRate, nsig, nbkg)));

//   model.plotOn(plot, Components("signal"), LineStyle(kDashed), LineColor(kRed));
  model.plotOn(plot, Components("bg"), LineStyle(kDashed), LineColor(kRed));


  plot->Draw();

//   TLatex *   tex = new TLatex(0.2,0.8,"CMS preliminary");
//   tex->SetNDC();
//   tex->SetTextFont(42);
//   tex->SetLineWidth(2);
//   tex->Draw();
//   tex->DrawLatex(0.2, 0.725, "7 TeV Data, L = 258 pb^{-1}");
//
//   float fsig_peak = NormalizedIntegral(model,
//                       mass,
//                       cbBias.getVal() - 2.5*cbSigma.getVal(),
//                       cbBias.getVal() + 2.5*cbSigma.getVal()
//                     );

//   float fbkg_peak = NormalizedIntegral(bg,
//                       mass,
//                       m0.getVal() - 2.5*sigma.getVal(),
//                       m0.getVal() + 2.5*sigma.getVal()
//                     );

/*  double nsigVal = fsig_peak * nsig.getVal();
  double nsigErr = fsig_peak * nsig.getError();
  double nsigErrRel = nsigErr / nsigVal;*/
//   double nbkgVal = fbkg_peak * nbkg.getVal();
//   double nbkgErr = fbkg_peak * nbkg.getError();
//   double nbkgErrRel = nbkgErr / nbkgVal;

//   cout << "nsig " << nsigVal << " +/- " << nsigErr << endl;
//   cout << "S/B_{#pm2.5#sigma} " << nsigVal/nbkgVal << " +/- "
//     << (nsigVal/nbkgVal)*sqrt(nsigErrRel*nsigErrRel + nbkgErrRel*nbkgErrRel)
//     << endl;

//   tex->DrawLatex(0.2, 0.6, Form("N_{S} = %.0f#pm%.0f", nsigVal, nsigErr) );
//   tex->DrawLatex(0.2, 0.525, Form("S/B_{#pm2.5#sigma} = %.1f", nsigVal/nbkgVal) );
//   tex->DrawLatex(0.2, 0.45, Form("#frac{S}{#sqrt{B}}_{#pm2.5#sigma} = %.1f", nsigVal/sqrt(nbkgVal)));

//   leg = new TLegend(0.65,0.6,0.9,0.75);
//   leg->SetFillColor(kWhite);
//   leg->SetLineColor(kWhite);
//   leg->SetShadowColor(kWhite);
//   leg->SetTextFont(42);

//   TLegendEntry * ldata  = leg->AddEntry(data, "Opposite Sign");
//   TLegendEntry * ldataB = leg->AddEntry(dataB, "Same Sign");
//   ldata->SetMarkerStyle(20);
//   ldataB->SetMarkerStyle(20);
//   ldataB->SetMarkerColor(kRed);

//   leg->Draw();

  cout << "histogram name, cbMean, cbMeanErr, cbWidth, cbWidthErr\n"
    << histoname << "\t"
    << cbBias.getVal() << "\t"
    << cbBias.getError() << "\t"
    << cbSigma.getVal() << "\t"
    << cbSigma.getError() << "\t"
    << std::endl << std::flush;

  return model;



}
Beispiel #13
0
void Back_2dFit(void){
  TFile *ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/fil_b2dh_gen.root");
  TTree *tree = (TTree*)ifile->Get("TEvent");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("comb",-1);

  RooArgSet argset;
  
  const double mbcMin = 5.20;
  const double mbcMax = 5.29;
  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbcMin,mbcMax,"GeV"); argset.add(mbc);
  mbc.setRange("Signal",mbc_min,mbc_max);
  mbc.setRange("mbcSignal",mbc_min,mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset);
  RooDataSet* ds0 = ds.reduce(RooArgSet(de,mbc));
  RooDataHist* dh = ds0->binnedClone();
  ds.Print();
  dh->Print();

  ////////////
  // de pdf //
  ////////////
//  RooRealVar c1("c1","c1",mc_c1,-1.,0.); if(cComb) c1.setConstant(kTRUE);
//  RooRealVar c2("c2","c2",mc_c2,0.,0.1); if(cComb) c2.setConstant(kTRUE);
  RooRealVar c3("c3","c3",mc_c1,-1.,0.); if(cComb) c3.setConstant(kTRUE);
  RooRealVar c4("c4","c4",mc_c2,0.,0.1); if(cComb) c4.setConstant(kTRUE);
  RooChebychev pdf_de("pdf_de","pdf_de",de,RooArgSet(c3,c4));

  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argpar("argpar","argus shape parameter",mc_argpar,-100.,-1.); if(cComb)
  argpar.setConstant(kTRUE);
  RooRealVar argedge("argedge","argedge",mc_argedge,5.285,5.292); if(cComb) argedge.setConstant(kTRUE);
  RooArgusBG pdf_mbc("pdf_mbc","Argus PDF",mbc,argedge,argpar);

  /////////
  // pdf //
  /////////
  RooProdPdf pdf("pdf","pdf",RooArgList(pdf_de,pdf_mbc));

  pdf.fitTo(*dh,Verbose(),Timer(true));

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(deFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E, Signal","#Delta E, Signal",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out;
  out.str("");
  out << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  TPaveText *pt = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  pt->AddText(out.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,200);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,200);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(mbcFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}, Signal","M_{bc}, Signal",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  out.str("");
  out << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  TPaveText *ptmbc = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  ptmbc->AddText(out.str().c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT = new TLine(mbc_max,0,mbc_max,150);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT = new TLine(mbc_min,0,mbc_min,150);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();
  
  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();
  
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,-0.15,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  cmmbc->Update();
}
void makeSystPlot( TFile * f, TString oldFolder, RooWorkspace *WS,  string channel, string syst, int toMassNo, int fromMassNo, int rightBinNo, int addRightBin,  int addRightBinm1) //massNo 0-51, see xSec7TeV.h 
{


  std::cout << "oldFolder,  channel , addRightBin, addRightBinm1: " << oldFolder << " , " <<channel << " , " << addRightBin  << " , "<< addRightBinm1 << std::endl;

  RooArgList  * hobs = new RooArgList("hobs");
  //  RooRealVar BDT("BDT", "BDT", -1, 1);///OLD VARIABLE NAME HERE
  RooRealVar BDT("CMS_vhbb_BDT_Wln", "CMS_vhbb_BDT_Wln", -1, 1);///OLD VARIABLE NAME HERE
  hobs->add(*WS->var("CMS_vhbb_BDT_Wln"));  ///NEW VARIABLE NAME HERE
  RooWorkspace *tempWS =  (RooWorkspace*) f->Get(oldFolder.Data());
  TString systT(syst);
  TString chanT(channel);

  if((kount < 3) && (channel=="data_obs"))
  {
    kount++;
    std::string namen  = channel;
    
    std::cout << oldFolder.Data() << std::endl;
    std::cout << namen << std::endl;
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,RooFit::Binning(bins));

   tempHistNom->Rebin(rebin);

 if(addRightBin == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo);
     float  con0 = tempHistNom->GetBinContent(rightBinNo);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-1);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-1);
       
     tempHistNom->SetBinContent(rightBinNo,0);
     tempHistNom->SetBinError(rightBinNo,0);
     tempHistNom->SetBinContent(rightBinNo-1,con0+con1);
     tempHistNom->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));
    }


 if(addRightBinm1 == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo-1);
     float  con0 = tempHistNom->GetBinContent(rightBinNo-1);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-2);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-2);
       
     tempHistNom->SetBinContent(rightBinNo-1,0);
     tempHistNom->SetBinError(rightBinNo-1,0);
     tempHistNom->SetBinContent(rightBinNo-2,con0+con1);
     tempHistNom->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));
    }





    RooDataHist *DHnom = new RooDataHist(channel.c_str(),"",*hobs,tempHistNom);  
    WS->import(*(new RooHistPdf(channel.c_str(),"",*hobs,*DHnom)));
 
 }

 if (channel!="data_obs")
{
  std::string nameUp; 
  std::string namen; 
  std::string nameDown;


  if(syst == "stat")
  {
   if(oldFolder.Contains("Wenu"))
   { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_WenuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_WenuDown";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_WenuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_WenuDown";
     }

   }
   else
   {
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_WmunuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_WmunuDown";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_WmunuUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_WmunuDown";
     }


   }
  }
  else
  {
  nameUp  = channel + "_CMS_" + syst + "Up";
  namen  = channel;
  nameDown = channel + "_CMS_" + syst + "Down";
  }
 
  if((syst == "stat") && (oldFolder.Contains("2")))
  {
   if(oldFolder.Contains("Wenu"))
   { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2Down";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu2Down";
     }

   }
   else
   {
     nameUp  = channel + "_CMS_vhbb_stat" + channel +  "_Wmunu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmunu2Down";

     if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmunu2Up";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmunu2Down";
     }


   }
  }

  if(systT.Contains("Model"))
  {
     nameUp  = channel + "_CMS_vhbb_WModelUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_WModelDown";
  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wenu")) && IFILE.Contains("8TeV") && !(oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu_8TeVDown";
     }


  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wmunu")) && IFILE.Contains("8TeV") && !(oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmnu_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmnu_8TeVDown";
     }


  }


  if( systT.Contains("stat") && (oldFolder.Contains("Wenu")) && IFILE.Contains("8TeV") && (oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wenu2_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wenu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wenu2_8TeVDown";
     }


  }

  if( systT.Contains("stat") && (oldFolder.Contains("Wmunu")) && IFILE.Contains("8TeV") && (oldFolder.Contains("2")))
  { 
     nameUp  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_stat" + channel + "_Wmnu2_8TeVDown";

   if(channel == "s_Top")
     {
     nameUp  = channel + "_CMS_vhbb_statsTop_Wmnu2_8TeVUp";
     namen  = channel;
     nameDown  = channel + "_CMS_vhbb_statsTop_Wmnu2_8TeVDown";
     }


  }







  RooDataHist* tempRooDataHistUp = (RooDataHist*)  tempWS->data(nameUp.c_str());
  RooDataHist* tempRooDataHistDown = (RooDataHist*)  tempWS->data(nameDown.c_str());
  RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());


  std::cout << oldFolder.Data() << std::endl; 
  std::cout << nameUp.c_str() << std::endl; 
  

  


  TH1 *tempHistUp = tempRooDataHistUp->createHistogram(nameUp.c_str(),BDT,RooFit::Binning(bins));
  TH1 *tempHistDown = tempRooDataHistDown->createHistogram(nameDown.c_str(),BDT,RooFit::Binning(bins));
  TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,RooFit::Binning(bins));
  
  if(chanT.Contains("WH") && IFILE.Contains("7TeV"))
  {
     tempHistUp->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
     tempHistDown->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
     tempHistNom->Scale(xSec7WH[toMassNo]/xSec7WH[fromMassNo]);
  }  
 
  if(chanT.Contains("WH") && IFILE.Contains("8TeV"))
  {
     tempHistUp->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
     tempHistDown->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
     tempHistNom->Scale(xSec8WH[toMassNo]/xSec8WH[fromMassNo]);
  }  
  
  std::cout<< "channel--> " << channel << std::endl;


    
  tempHistUp->SetLineColor(kRed);
  tempHistUp->SetLineWidth(3);
  tempHistUp->SetFillColor(0);
  
  tempHistDown->SetLineColor(kBlue);
  tempHistDown->SetFillColor(0);
  tempHistDown->SetLineWidth(3);
  
  tempHistNom->SetFillColor(0);
  tempHistNom->SetMarkerStyle(20);
    
  tempHistUp->SetTitle((channel + syst).c_str());
 
  tempHistNom->Rebin(rebin);
  tempHistUp->Rebin(rebin);
  tempHistDown->Rebin(rebin);


 if(addRightBin == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo);
     float  con0 = tempHistNom->GetBinContent(rightBinNo);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-1);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-1);
       
     tempHistNom->SetBinContent(rightBinNo,0);
     tempHistNom->SetBinError(rightBinNo,0);
     tempHistNom->SetBinContent(rightBinNo-1,con0+con1);
     tempHistNom->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));


     err0 = tempHistUp->GetBinError(rightBinNo);
     con0 = tempHistUp->GetBinContent(rightBinNo);
 
     err1 = tempHistUp->GetBinError(rightBinNo-1);
     con1 = tempHistUp->GetBinContent(rightBinNo-1);
       
     tempHistUp->SetBinContent(rightBinNo,0);
     tempHistUp->SetBinError(rightBinNo,0);
     tempHistUp->SetBinContent(rightBinNo-1,con0+con1);
     tempHistUp->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));



     err0 = tempHistDown->GetBinError(rightBinNo);
     con0 = tempHistDown->GetBinContent(rightBinNo);
 
     err1 = tempHistDown->GetBinError(rightBinNo-1);
     con1 = tempHistDown->GetBinContent(rightBinNo-1);
       
     tempHistDown->SetBinContent(rightBinNo,0);
     tempHistDown->SetBinError(rightBinNo,0);
     tempHistDown->SetBinContent(rightBinNo-1,con0+con1);
     tempHistDown->SetBinError(rightBinNo-1,sqrt(err0*err0+err1*err1));

    }



 if(addRightBinm1 == 1)
    {
     float  err0 = tempHistNom->GetBinError(rightBinNo-1);
     float  con0 = tempHistNom->GetBinContent(rightBinNo-1);
 
     float  err1 = tempHistNom->GetBinError(rightBinNo-2);
     float  con1 = tempHistNom->GetBinContent(rightBinNo-2);
       
     tempHistNom->SetBinContent(rightBinNo-1,0);
     tempHistNom->SetBinError(rightBinNo-1,0);
     tempHistNom->SetBinContent(rightBinNo-2,con0+con1);
     tempHistNom->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));


     err0 = tempHistUp->GetBinError(rightBinNo-1);
     con0 = tempHistUp->GetBinContent(rightBinNo-1);
 
     err1 = tempHistUp->GetBinError(rightBinNo-2);
     con1 = tempHistUp->GetBinContent(rightBinNo-2);
       
     tempHistUp->SetBinContent(rightBinNo-1,0);
     tempHistUp->SetBinError(rightBinNo-1,0);
     tempHistUp->SetBinContent(rightBinNo-2,con0+con1);
     tempHistUp->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));



     err0 = tempHistDown->GetBinError(rightBinNo-1);
     con0 = tempHistDown->GetBinContent(rightBinNo-1);
 
     err1 = tempHistDown->GetBinError(rightBinNo-2);
     con1 = tempHistDown->GetBinContent(rightBinNo-2);
       
     tempHistDown->SetBinContent(rightBinNo-1,0);
     tempHistDown->SetBinError(rightBinNo-1,0);
     tempHistDown->SetBinContent(rightBinNo-2,con0+con1);
     tempHistDown->SetBinError(rightBinNo-2,sqrt(err0*err0+err1*err1));

    }




  RooDataHist *DHnom;
  RooDataHist *DHup = new RooDataHist(nameUp.c_str(),"",*hobs,tempHistUp);  
  if(kount2 < 3) DHnom = new RooDataHist(namen.c_str(),"",*hobs,tempHistNom);
  RooDataHist *DHdown = new RooDataHist(nameDown.c_str(),"",*hobs,tempHistDown);  

  WS->import(*(new RooHistPdf(nameUp.c_str(),"",*hobs,*DHup)));
  WS->import(*(new RooHistPdf(nameDown.c_str(),"",*hobs,*DHdown)));
  if(kount2 < 3){ WS->import(*(new RooHistPdf(namen.c_str(),"",*hobs,*DHnom))); kount2++;}

 }


}
Beispiel #15
0
void FitBias(TString CAT,TString CUT,float SIG,float BKG,int NTOYS)
{
  gROOT->ForceStyle();
  
  RooMsgService::instance().setSilentMode(kTRUE);
  RooMsgService::instance().setStreamStatus(0,kFALSE);
  RooMsgService::instance().setStreamStatus(1,kFALSE);
  
  // -----------------------------------------
  TFile *fTemplates = TFile::Open("templates_"+CUT+"_"+CAT+"_workspace.root");
  RooWorkspace *wTemplates = (RooWorkspace*)fTemplates->Get("w");
  RooRealVar *x            = (RooRealVar*)wTemplates->var("mTop");
  RooAbsPdf *pdf_signal    = (RooAbsPdf*)wTemplates->pdf("ttbar_pdf_Nominal");
  RooAbsPdf *pdf_bkg       = (RooAbsPdf*)wTemplates->pdf("qcdCor_pdf"); 
  TRandom *rnd = new TRandom();
  rnd->SetSeed(0);
  x->setBins(250);   
  RooPlot *frame;

  TFile *outf;

  if (NTOYS > 1) { 
    outf = TFile::Open("FitBiasToys_"+CUT+"_"+CAT+".root","RECREATE");
  }

  float nSigInj,nBkgInj,nSigFit,nBkgFit,eSigFit,eBkgFit,nll;

  TTree *tr = new TTree("toys","toys");
  
  tr->Branch("nSigInj",&nSigInj,"nSigInj/F");
  tr->Branch("nSigFit",&nSigFit,"nSigFit/F");
  tr->Branch("nBkgInj",&nBkgInj,"nBkgInj/F");
  tr->Branch("nBkgFit",&nBkgFit,"nBkgFit/F");
  tr->Branch("eSigFit",&eSigFit,"eSigFit/F");
  tr->Branch("eBkgFit",&eBkgFit,"eBkgFit/F");
  tr->Branch("nll"    ,&nll    ,"nll/F");

  for(int itoy=0;itoy<NTOYS;itoy++) {
    // generate pseudodataset
    nSigInj = rnd->Poisson(SIG);
    nBkgInj = rnd->Poisson(BKG);
    RooRealVar *nSig = new RooRealVar("nSig","nSig",nSigInj);
    RooRealVar *nBkg = new RooRealVar("nBkg","nBkg",nBkgInj);
    RooAddPdf *model = new RooAddPdf("model","model",RooArgList(*pdf_signal,*pdf_bkg),RooArgList(*nSig,*nBkg)); 
    RooDataSet *data = model->generate(*x,nSigInj+nBkgInj);
    
    RooDataHist *roohist = new RooDataHist("roohist","roohist",RooArgList(*x),*data);
    // build fit model
    RooRealVar *nFitSig = new RooRealVar("nFitSig","nFitSig",SIG,0,10*SIG);
    RooRealVar *nFitBkg = new RooRealVar("nFitBkg","nFitBkg",BKG,0,10*BKG);
    RooAddPdf *modelFit = new RooAddPdf("modelFit","modelFit",RooArgList(*pdf_signal,*pdf_bkg),RooArgList(*nFitSig,*nFitBkg)); 
    // fit the pseudo dataset
    RooFitResult *res = modelFit->fitTo(*roohist,RooFit::Save(),RooFit::Extended(kTRUE));
    //res->Print();
    nSigFit = nFitSig->getVal();
    nBkgFit = nFitBkg->getVal();
    eSigFit = nFitSig->getError();
    eBkgFit = nFitBkg->getError();
    nll     = res->minNll();
    tr->Fill();
    if (itoy % 100 == 0) {
      cout<<"Toy #"<<itoy<<": injected = "<<nSigInj<<", fitted = "<<nSigFit<<", error = "<<eSigFit<<endl;
    }
    if (NTOYS == 1) {
      frame = x->frame();
      roohist->plotOn(frame); 
      model->plotOn(frame);
    }
  }
  if (NTOYS == 1) {
    TCanvas *can = new TCanvas("Toy","Toy",900,600);
    frame->Draw();
  }  
  else {
    outf->cd();
    tr->Write();
    outf->Close();
    fTemplates->Close();
  }  
}
void TwoCategorySimZFitter( TH1& h_TT, TH1& h_TF, 
                            double intLumi, int removeEE )
{
  // The fit variable - lepton invariant mass
  rooMass_ = new RooRealVar("Mass","m_{ee}",60.0, 120.0, "GeV/c^{2}");
  rooMass_->setBins(20.0);
  RooRealVar Mass = *rooMass_;

  // Make the category variable that defines the two fits,
  // namely whether the probe passes or fails the eff criteria.
  RooCategory sample("sample","") ;
  sample.defineType("TT", 1) ;
  sample.defineType("TF", 2) ; 

  gROOT->cd();

  ///////// convert Histograms into RooDataHists
  RooDataHist* data_TT = new RooDataHist("data_TT","data_TT",
					  RooArgList(Mass), &h_TT);
  RooDataHist* data_TF = new RooDataHist("data_TF","data_TF",
					  RooArgList(Mass), &h_TF);

  RooDataHist* data = new RooDataHist( "fitData","fitData",
				       RooArgList(Mass),Index(sample),
				       Import("TT",*data_TT), Import("TF",*data_TF) ); 

  data->get()->Print();
  cout << "Made datahist" << endl;


  // ********** Construct signal & bkg shape PDF ********** //
  makeSignalPdf();
  cout << "Made signal pdf" << endl;
  makeBkgPdf();
  cout << "Made bkg pdf" << endl;

  // Now supply integrated luminosity in inverse picobarn
  // -->  we get this number from the CMS lumi group
  // https://twiki.cern.ch/twiki/bin/view/CMS/LumiWiki2010Data
  RooRealVar lumi("lumi","lumi", intLumi);


  // Now define Z production cross section variable (in pb) 
  RooRealVar xsec("xsec","xsec", 1300., 400.0, 2000.0);


  // Define efficiency variables  
  RooRealVar eff("eff","eff", 0.9, 0.5, 1.0);

  // Now define acceptance variables --> we get these numbers from MC   
//   RooRealVar acc_BB("acc_BB","acc_BB", 0.2253);
//   RooRealVar acc_EB("acc_EB","acc_EB", 0.1625);
//   RooRealVar acc_EE("acc_EE","acc_EE", 0.0479);

  double ACCEPTANCE=0.4357;
  if(removeEE==1) ACCEPTANCE= 0.3878;
  if(removeEE==2) ACCEPTANCE= 0.2253;
  RooRealVar acc("acc","acc", ACCEPTANCE);

  // Define background yield variables: they are not related to each other  
  RooRealVar nBkgTF("nBkgTF","nBkgTF",10.,-10.,100000.);
 
  ////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////
 //  Define signal yield variables.  
  // They are linked together by the total cross section:  e.g. 
  //          Nbb = sigma*L*Abb*effB

  char* formula;
  RooArgList* args;
  formula = "lumi*xsec*acc*eff*eff";
  args = new RooArgList(lumi,xsec,acc,eff);
  RooFormulaVar nSigTT("nSigTT", formula, *args);
  delete args;

  formula = "lumi*xsec*acc*eff*(1.0-eff)";
  args = new RooArgList(lumi,xsec,acc,eff);
  RooFormulaVar nSigTF("nSigTF",formula, *args);
  delete args;

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

   RooArgList componentsTF(*signalShapePdfTF_,*bkgShapePdfTF_);
   RooArgList yieldsTF(nSigTF, nBkgTF );	  

   RooExtendPdf pdfTT("pdfTT","extended sum pdf", *signalShapePdfTT_, nSigTT);
   RooAddPdf pdfTF("pdfTF","extended sum pdf",componentsTF, yieldsTF);


   // The total simultaneous fit ...
   RooSimultaneous totalPdf("totalPdf","totalPdf", sample);
   totalPdf.addPdf(pdfTT,"TT");
   totalPdf.Print();
   totalPdf.addPdf(pdfTF,"TF");
   totalPdf.Print();


  // ********* Do the Actual Fit ********** //  
   RooFitResult *fitResult = totalPdf.fitTo(*data, Save(true), 
					    Extended(), Minos(),
                        PrintEvalErrors(-1),Warnings(false) );
  fitResult->Print("v");


  // ********** Make and save Canvas for the plots ********** //
  gROOT->ProcessLine(".L ~/tdrstyle.C");
  setTDRStyle();
  tdrStyle->SetErrorX(0.5);
  tdrStyle->SetPadLeftMargin(0.19);
  tdrStyle->SetPadRightMargin(0.10);
  tdrStyle->SetPadBottomMargin(0.15);
  tdrStyle->SetLegendBorderSize(0);
  tdrStyle->SetTitleYOffset(1.5);
  RooAbsData::ErrorType errorType = RooAbsData::SumW2;


  TString cname = Form("Zmass_TT_%dnb", (int)(1000*intLumi) );
  c = new TCanvas(cname,cname,500,500);
  RooPlot* frame1 = Mass.frame();
  data_TT->plotOn(frame1,RooFit::DataError(errorType));
  pdfTT.plotOn(frame1,ProjWData(*data_TT));
  frame1->SetMinimum(0);
  frame1->Draw("e0");
  TPaveText *plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
  TPaveText *plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  TPaveText *plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
  char temp[100];
  sprintf(temp, "%.1f", intLumi);
  plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
  temp + string(" pb^{ -1}")).c_str());
  TPaveText *plotlabel4 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   double nsig = eff.getVal()*xsec.getVal()*acc.getVal()*lumi.getVal();
   double xsecFrErr = xsec.getError()/xsec.getVal();
   double effFrErr = eff.getError()/eff.getVal();
   double effxsecCorr = fitResult->correlation(eff, xsec);
   double nsigerr = sqrt(effFrErr**2 +xsecFrErr**2 + 
   2.0*effxsecCorr*xsecFrErr*effFrErr)*nsig;
   sprintf(temp, "Signal = %.2f #pm %.2f", nsig, nsigerr);
   plotlabel4->AddText(temp);
  TPaveText *plotlabel5 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "#epsilon = %.4f #pm %.4f", eff.getVal(), eff.getError());
   plotlabel5->AddText(temp);
  TPaveText *plotlabel6 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   sprintf(temp, "#sigma = %.1f #pm %.1f pb", xsec.getVal(), xsec.getError());
   plotlabel6->AddText(temp);

  plotlabel->Draw();
  plotlabel2->Draw();
  plotlabel3->Draw();
  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  c->SaveAs( cname + TString(".eps"));
  c->SaveAs( cname + TString(".gif"));
  c->SaveAs( cname + TString(".root"));
  c->SaveAs( cname + TString(".png"));
  c->SaveAs( cname + TString(".C"));


  TString cname = Form("Zmass_TF_%dnb", (int)(1000*intLumi) );
  c = new TCanvas(cname,cname,500,500);
  RooPlot* frame2 = Mass.frame();
  data_TF->plotOn(frame2,RooFit::DataError(errorType));
  pdfTF.plotOn(frame2,ProjWData(*data_TF),
  Components(*bkgShapePdfTF_),LineColor(kRed));
  pdfTF.plotOn(frame2,ProjWData(*data_TF));
  frame2->SetMinimum(0);
  frame2->Draw("e0");
  frame2->GetYaxis()->SetNdivisions(505);
  TPaveText *plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
  TPaveText *plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  TPaveText *plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
  char temp[100];
  sprintf(temp, "%.1f", intLumi);
  plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
  temp + string(" pb^{ -1}")).c_str());
  TPaveText *plotlabel4 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   double nsig = (1.0-eff.getVal())*xsec.getVal()*acc.getVal()*lumi.getVal();
   double xsecFrErr = xsec.getError()/xsec.getVal();
   double effFrErr = eff.getError()/(1.0-eff.getVal());
   double effxsecCorr = fitResult->correlation(eff, xsec);
   double nsigerr = sqrt(effFrErr**2 +xsecFrErr**2 + 
   2.0*effxsecCorr*xsecFrErr*effFrErr)*nsig;
   sprintf(temp, "Signal = %.2f #pm %.2f", nsig, nsigerr);
   plotlabel4->AddText(temp);
  TPaveText *plotlabel5 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", nBkgTF.getVal(), nBkgTF.getError());
   plotlabel5->AddText(temp);
  TPaveText *plotlabel6 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   sprintf(temp, "#epsilon = %.4f #pm %.4f", eff.getVal(), eff.getError());
   plotlabel6->AddText(temp);

  plotlabel->Draw();
  plotlabel2->Draw();
  plotlabel3->Draw();
  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();

  c->SaveAs( cname + TString(".eps"));
  c->SaveAs( cname + TString(".gif"));
  c->SaveAs( cname + TString(".root"));
  c->SaveAs( cname + TString(".png"));
  c->SaveAs( cname + TString(".C"));

/*
  RooMCStudy toymc( totalPdf, RooArgSet(Mass, sample), Binned(kTRUE), 
  FitModel(totalPdf), Extended(),FitOptions(Extended(), Minos()));
  int numEventsToGenerate = (int)(h_TT.Integral()+h_TF.Integral());
  toymc.generateAndFit(1000,numEventsToGenerate);

  RooPlot* plot1 = toymc.plotPull( xsec, -4., 4., 24);
  plot1->SetTitle("");
  plot1->GetXaxis()->SetTitle("cross section pull");
  TString cname = Form("pull_crosssection_%dnb", (int)(1000*intLumi));
  TCanvas *c2 = new TCanvas(cname,"Pull distribution of cross section",500,500);
  plot1->Draw();
  c2->SaveAs( cname + TString(".eps"));
  c2->SaveAs( cname + TString(".gif"));
  c2->SaveAs( cname + TString(".root"));




  RooPlot* plot2 = toymc.plotError( eff, 0., 0.2, 20);
  plot2->SetTitle("");
  plot2->GetXaxis()->SetTitle("Uncertainty in efficiency");
  TString cname = Form("error_efficiency_%dnb", (int)(1000*intLumi));
  TCanvas *c3 = new TCanvas(cname,"Uncertainty in efficiency",500,500);
  plot2->Draw();
  c3->SaveAs( cname + TString(".eps"));
  c3->SaveAs( cname + TString(".gif"));
  c3->SaveAs( cname + TString(".root"));



  RooPlot* plot3 = toymc.plotError( xsec, 0., 650., 65);
  plot3->SetTitle("");
  plot3->GetXaxis()->SetTitle("Uncertainty in cross section (pb)");
  TString cname = Form("error_crosssection_%dnb", (int)(1000*intLumi));
  TCanvas *c4 = new TCanvas(cname,"Uncertainty in cross section",500,500);
  plot3->Draw();
  c4->SaveAs( cname + TString(".eps"));
  c4->SaveAs( cname + TString(".gif"));
  c4->SaveAs( cname + TString(".root"));

*/

  //    if(data) delete data;
  //    if(c) delete c;
}
void generateSigHist_for_combineMaker(Float_t lum =10, Int_t cc1 = 0, Int_t cc2 = 9) {

    const Int_t NCAT(4); // 4 categories in the source file
    TString myCut[NCAT] = {"EBHighR9","EBLowR9","EEHighR9","EELowR9"};
    //Float_t lum =10;
    TString lum_string = TString::Format("%g", lum);
    TFile *file=TFile::Open("workspaces/HighMassGG_m1500_01_mgg_lum_"+lum_string+".root");
    RooWorkspace *w_all = (RooWorkspace*)file->Get("w_all");

    RooRealVar *mgg = (RooRealVar*)w_all->var("mgg");
    RooRealVar *MH = (RooRealVar*)w_all->var("MH");
    RooRealVar *kpl = (RooRealVar*)w_all->var("kpl");

    RooNumConvPdf* numConv[NCAT];
    RooFormulaVar* norm[NCAT];

    // necessary to set a window as it is not saved when RooNumConvPdf is saved
    RooRealVar* W = new RooRealVar("W","W",500);
    W->setConstant();
    RooRealVar* C = new RooRealVar("C","C",0);
    C->setConstant();

    cout << "READ PDFs FROM WORKSPACE : SIGNAL FROM 4 CATEGORIES" << endl;
    cout << "READ ROOFORMULAs FROM WORKSPACE : NORMALIZATION OF 4 CATEGORIES" << endl;
    cout << "SET WINDOW FOR THE 4 CONVOLUTIONS (PDFs)" << endl;
    cout << "..." << endl;
    for(Int_t c = 0; c<NCAT; c++) {

        numConv[c] = (RooNumConvPdf*)w_all->pdf("mggSig_cat"+myCut[c]);
        norm[c] = (RooFormulaVar*)w_all->function("mggSig_cat"+myCut[c]+"_norm");
        numConv[c]->setConvolutionWindow(*C,*W);
    }
    cout << endl;
    cout << "ADD PDFs TO FORM THE TWO CATEGORIES EBEB AND EBEE" << endl;
    RooFormulaVar *mggSig_catEBEB_norm = new RooFormulaVar("mggSig_catEBEB_norm","mggSig_catEBEB_norm","@0+@1",RooArgList(*norm[0],*norm[1]));
    RooFormulaVar *mggSig_catEBEE_norm = new RooFormulaVar("mggSig_catEBEE_norm","mggSig_catEBEE_norm","@0+@1",RooArgList(*norm[2],*norm[3]));

    RooFormulaVar *frac1EBEB = new RooFormulaVar("frac1EBEB","frac1EBEB","@0/@1",RooArgList(*norm[0],*mggSig_catEBEB_norm));
    RooFormulaVar *frac2EBEB = new RooFormulaVar("frac2EBEB","frac2EBEB","@0/@1",RooArgList(*norm[1],*mggSig_catEBEB_norm));
    RooFormulaVar *frac1EBEE = new RooFormulaVar("frac1EBEE","frac1EBE","@0/@1",RooArgList(*norm[2],*mggSig_catEBEE_norm));
    RooFormulaVar *frac2EBEE = new RooFormulaVar("frac2EBEE","frac2EBEE","@0/@1",RooArgList(*norm[3],*mggSig_catEBEE_norm));

    RooAddPdf* mggSig_catEBEB = new RooAddPdf("mggSig_catEBEB","mggSig_catEBEB",RooArgList(*numConv[0],*numConv[1]),RooArgList(*frac1EBEB,*frac2EBEB));
    RooAddPdf* mggSig_catEBEE = new RooAddPdf("mggSig_catEBEE","mggSig_catEBEE",RooArgList(*numConv[2],*numConv[3]),RooArgList(*frac1EBEE,*frac2EBEE));

    cout << endl << endl ;
    cout << "READ CFG FROM BACKGROUND_FINAL TO BE USED IN COMBINE_MAKER.PY" << endl;
    TFile *fcfg = TFile::Open("../../Analysis/macros/workspace_cic2_dijet_lum_10/full_analysis_anv1_v18_bkg_ws_300.root");
    TObjString *cfg = (TObjString*)fcfg->Get("cfg");

    const Int_t nCouplings(9);
    Double_t couplings[nCouplings] = {0.01, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.175, 0.2};

    cout << endl << endl ;
    cout << "SCAN OVER MH AND KAPPA VALUES TO GET DIFFERENT PDFs FOR EACH SET OF PARAMETERS..." << endl;

    for(Int_t icoupling = cc1; icoupling < cc2; icoupling++) {

        //CREATE FOLDER FOR THE COUPLING
        TString coupling_string = TString::Format("%g",couplings[icoupling]);
        coupling_string.ReplaceAll(".","");
        TString inDir("../../Analysis/macros/workspace_cic2_signalDataHist_lum_"+lum_string+"/");
        gSystem->mkdir(inDir);

        for(Int_t mass = 1000; mass < 5100 ; mass+=100) {

            TString mass_string = TString::Format("%d",mass);
            TString signame("grav_"+coupling_string+"_"+mass_string);
            cout << endl;
            cout << "********************************************" << endl;
            cout << "SET MH and KAPPA values" << endl << "kappa: " << couplings[icoupling] << endl << "mass: " << mass << endl;
            cout << "********************************************" << endl;
            MH->setVal(mass);
            kpl->setVal(couplings[icoupling]);

            cout << "CREATE ROODATAHIST WITH NORM..." << endl;
            RooDataHist* dhEBEB = mggSig_catEBEB->generateBinned(RooArgSet(*mgg),mggSig_catEBEB_norm->getVal(), RooFit::ExpectedData());
            RooDataHist* dhEBEE = mggSig_catEBEE->generateBinned(RooArgSet(*mgg),mggSig_catEBEE_norm->getVal(), RooFit::ExpectedData());

            dhEBEB->SetName("signal_"+signame+"_EBEB");
            dhEBEB->SetTitle("signal_"+signame+"_EBEB");
            dhEBEE->SetName("signal_"+signame+"_EBEE");
            dhEBEE->SetTitle("signal_"+signame+"_EBEE");

            //CREATE ROOHISTPDF
            //RooHistPdf *fhEBEB = new RooHistPdf("mggHistPdf_catEBEB","mggHistPdf_catEBEB",RooArgSet(*mgg),*dhEBEB);
            //RooHistPdf *fhEBEE = new RooHistPdf("mggHistPdf_catEBEE","mggHistPdf_catEBEE",RooArgSet(*mgg),*dhEBEE);

            //SAVE ALL IN A WORKSPACE WITH FILE NAME corresponding to MASS AND COUPLING VALUE
            RooWorkspace *wtemplates = new RooWorkspace("wtemplates","wtemplates");

            //wtemplates->import(*fhEBEB);
            //wtemplates->import(*fhEBEE);
            //wtemplates->import(*mggSig_catEBEB_norm,RecycleConflictNodes());
            //wtemplates->import(*mggSig_catEBEE_norm,RecycleConflictNodes());
            wtemplates->import(*dhEBEB);
            wtemplates->import(*dhEBEE);
            //wtemplates->import(*numConv[0],RecycleConflictNodes());

            cout << "******************************************" << endl;
            cout << "WORKSPACE CONTENT FOR COUPLING " << couplings[icoupling] << " AND MASS " << mass << endl;
            wtemplates->Print("V");

            //WRITE IN FILE
            TString filename = inDir+"300_"+signame+".root";
            TFile *fileOutput = TFile::Open(filename,"recreate");
            cfg->Write("cfg");
            wtemplates->Write("wtemplates");
            cout << "workspace imported to " << filename << endl;

        }
    }
}
Beispiel #18
0
void makeModel(RooWorkspace& w) {

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

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

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

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

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

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

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

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

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

   w.import(*mc);

   w.Print("tree");

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

   return;

}
Beispiel #19
0
int main(int argc, char* argv[]){

  string bkgFileName;
  string sigFileName;
  string sigWSName;
  string bkgWSName;
  string outFileName;
  string datFileName;
  string outDir;
  int cat;
  int ntoys;
  int jobn;
  int seed;
  float mu_low;
  float mu_high;
  float mu_step;
  float expectSignal;
  int expectSignalMass;
  bool skipPlots=false;
  int verbosity;
  bool throwHybridToys=false;
  vector<float> switchMass;
  vector<string> switchFunc;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h",                                                                                  "Show help")
    ("sigfilename,s", po::value<string>(&sigFileName),                                          "Signal file name")
    ("bkgfilename,b", po::value<string>(&bkgFileName),                                          "Background file name")
    ("sigwsname", po::value<string>(&sigWSName)->default_value("cms_hgg_workspace"),            "Signal workspace name")
    ("bkgwsname", po::value<string>(&bkgWSName)->default_value("cms_hgg_workspace"),            "Background workspace name")
    ("outfilename,o", po::value<string>(&outFileName)->default_value("BiasStudyOut.root"),      "Output file name")
    ("datfile,d", po::value<string>(&datFileName)->default_value("config.dat"),                 "Name of datfile containing pdf info")
    ("outDir,D", po::value<string>(&outDir)->default_value("./"),                               "Name of out directory for plots")
    ("cat,c", po::value<int>(&cat),                                                             "Category")
    ("ntoys,t", po::value<int>(&ntoys)->default_value(0),                                       "Number of toys to run")
    ("jobn,j", po::value<int>(&jobn)->default_value(0),                                         "Job number")
    ("seed,r", po::value<int>(&seed)->default_value(0),                                         "Set random seed")
    ("mulow,L", po::value<float>(&mu_low)->default_value(-3.),                                  "Value of mu to start scan")
    ("muhigh,H", po::value<float>(&mu_high)->default_value(3.),                                 "Value of mu to end scan")
    ("mustep,S", po::value<float>(&mu_step)->default_value(0.01),                               "Value of mu step size")
    ("expectSignal", po::value<float>(&expectSignal)->default_value(0.),                        "Inject signal into toy")
    ("expectSignalMass", po::value<int>(&expectSignalMass)->default_value(125),                 "Inject signal at this mass")
    ("skipPlots",                                                                               "Skip full profile and toy plots")                        
    ("verbosity,v", po::value<int>(&verbosity)->default_value(0),                               "Verbosity level")
  ;    
  
  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("skipPlots")) skipPlots=true;
  if (expectSignalMass!=110 && expectSignalMass!=115 && expectSignalMass!=120 && expectSignalMass!=125 && expectSignalMass!=130 && expectSignalMass!=135 && expectSignalMass!=140 && expectSignalMass!=145 && expectSignalMass!=150){
    cerr << "ERROR - expectSignalMass has to be integer in range (110,150,5)" << endl;
    exit(1);
  }

  vector<pair<int,pair<string,string> > > toysMap;
  vector<pair<int,pair<string,string> > > fabianMap;
  vector<pair<int,pair<string,string> > > paulMap;
  readDatFile(datFileName,cat,toysMap,fabianMap,paulMap);
  
  cout << "Toy vector.." << endl;
  printOptionsMap(toysMap);
  cout << "Fabian vector.." << endl;
  printOptionsMap(fabianMap);
  cout << "Paul vector.." << endl;
  printOptionsMap(paulMap);
  
  TStopwatch sw;
  sw.Start();
 
  if (verbosity<1) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
    RooMsgService::instance().setSilentMode(true);
  }
  
  TFile *bkgFile = TFile::Open(bkgFileName.c_str());
  TFile *sigFile = TFile::Open(sigFileName.c_str());

  //RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get("cms_hgg_workspace");
  RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get(bkgWSName.c_str());
  RooWorkspace *sigWS = (RooWorkspace*)sigFile->Get(sigWSName.c_str());

  if (!bkgWS || !sigWS){
    cerr << "ERROR - one of signal or background workspace is NULL" << endl;
    exit(1);
  }

  RooRealVar *mass = (RooRealVar*)bkgWS->var("CMS_hgg_mass");
  RooRealVar *mu = new RooRealVar("mu","mu",0.,mu_low,mu_high);

  TFile *outFile = new TFile(outFileName.c_str(),"RECREATE");
  TTree *muTree = new TTree("muTree","muTree");
  int toyn;
  vector<string> truthModel;
  vector<double> muFab;
  vector<double> muPaul;
  vector<double> muChi2;
  vector<double> muAIC;
  vector<double> muFabErrLow;
  vector<double> muPaulErrLow;
  vector<double> muChi2ErrLow;
  vector<double> muAICErrLow;
  vector<double> muFabErrHigh;
  vector<double> muPaulErrHigh;
  vector<double> muChi2ErrHigh;
  vector<double> muAICErrHigh;
  muTree->Branch("jobn",&jobn);
  muTree->Branch("toyn",&toyn);
  muTree->Branch("truthModel",&truthModel);
  muTree->Branch("muFab",&muFab);
  muTree->Branch("muPaul",&muPaul);
  muTree->Branch("muChi2",&muChi2);
  muTree->Branch("muAIC",&muAIC);
  muTree->Branch("muFabErrLow",&muFabErrLow);
  muTree->Branch("muPaulErrLow",&muPaulErrLow);
  muTree->Branch("muChi2ErrLow",&muChi2ErrLow);
  muTree->Branch("muAICErrLow",&muAICErrLow);
  muTree->Branch("muFabErrHigh",&muFabErrHigh);
  muTree->Branch("muPaulErrHigh",&muPaulErrHigh);
  muTree->Branch("muChi2ErrHigh",&muChi2ErrHigh);
  muTree->Branch("muAICErrHigh",&muAICErrHigh);
  
  //TH1F *muDistFab = new TH1F("muDistFab","muDistFab",int(20*(mu_high-mu_low)),mu_low,mu_high);
  //TH1F *muDistPaul = new TH1F("muDistPaul","muDistPaul",int(20*(mu_high-mu_low)),mu_low,mu_high);
  //TH1F *muDistChi2 = new TH1F("muDistChi2","muDistChi2",int(20*(mu_high-mu_low)),mu_low,mu_high);
  //TH1F *muDistAIC = new TH1F("muDistAIC","muDistAIC",int(20*(mu_high-mu_low)),mu_low,mu_high);
  
  mass->setBins(320);
  RooDataSet *data = (RooDataSet*)bkgWS->data(Form("data_mass_cat%d",cat));
  //RooDataSet *data = (RooDataSet*)bkgWS->data(Form("data_cat%d_7TeV",cat));
  RooDataHist *dataBinned = new RooDataHist(Form("roohist_data_mass_cat%d",cat),Form("roohist_data_mass_cat%d",cat),RooArgSet(*mass),*data);
  RooDataSet *sigMC = (RooDataSet*)sigWS->data(Form("sig_ggh_mass_m%d_cat%d",expectSignalMass,cat));
  RooDataSet *sigMC_vbf = (RooDataSet*)sigWS->data(Form("sig_wzh_mass_m%d_cat%d",expectSignalMass,cat));
  RooDataSet *sigMC_wzh = (RooDataSet*)sigWS->data(Form("sig_vbf_mass_m%d_cat%d",expectSignalMass,cat));
  RooDataSet *sigMC_tth = (RooDataSet*)sigWS->data(Form("sig_tth_mass_m%d_cat%d",expectSignalMass,cat));
  sigMC->append(*sigMC_vbf);
  sigMC->append(*sigMC_wzh);
  sigMC->append(*sigMC_tth);
  //RooExtendPdf *ggh_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_ggh",cat));
  //RooExtendPdf *vbf_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_vbf",cat));
  //RooExtendPdf *wzh_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_wzh",cat));
  //RooExtendPdf *tth_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_tth",cat));
  //RooAbsPdf *sigPdf = new RooAddPdf(Form("sigpdfsmrel_cat%d_7TeV",cat),Form("sigpdfsmrel_cat%d_7TeV",cat),RooArgList(*ggh_pdf,*vbf_pdf,*wzh_pdf,*tth_pdf));
  
  if (!dataBinned || !sigMC){
    cerr << "ERROR -- one of data or signal is NULL" << endl;
    exit(1);
  }
  
  // set of truth models to throw toys from
  PdfModelBuilder toysModel;
  toysModel.setObsVar(mass);
  toysModel.setSignalModifier(mu);
  // add truth pdfs from config datfile these need to be cached
  // to throw a toy from the SB fit make sure that the cache happens at makeSBPdfs
  for (vector<pair<int,pair<string,string> > >::iterator it=toysMap.begin(); it!=toysMap.end(); it++){
    if (it->first==-1) { // this is a hyrbid toy
      throwHybridToys=true;
      vector<string> temp;
      split(temp,it->second.first,boost::is_any_of(","));
      split(switchFunc,it->second.second,boost::is_any_of(","));
      for (unsigned int i=0; i<temp.size(); i++){
        switchMass.push_back(atof(temp[i].c_str()));
      }
      continue; 
    }
    if (it->first==-2) { // this is a keys pdf toy
      double rho = lexical_cast<double>(it->second.first);
      toysModel.setKeysPdfAttributes(data,rho);
      toysModel.addBkgPdf("KeysPdf",0,Form("truth_%s_cat%d",it->second.second.c_str(),cat),false);
      continue;
    }
    if (it->first==-3) { // this is read pdf from file
      toysModel.addBkgPdf(it->second.second,it->first,it->second.first,false);
      continue;
    }
    toysModel.addBkgPdf(it->second.second,it->first,Form("truth_%s_cat%d",it->second.first.c_str(),cat),false); 
  }
  toysModel.setSignalPdfFromMC(sigMC);
  //toysModel.setSignalPdf(sigPdf);
  toysModel.makeSBPdfs(true);
  map<string,RooAbsPdf*> toyBkgPdfs = toysModel.getBkgPdfs();
  map<string,RooAbsPdf*> toySBPdfs = toysModel.getSBPdfs();
  toysModel.setSeed(seed);

  // fabians chosen model
  PdfModelBuilder fabianModel;
  fabianModel.setObsVar(mass);
  fabianModel.setSignalModifier(mu);
  // add pdfs from config datfile - should be no need to cache these
  for (vector<pair<int,pair<string,string> > >::iterator it=fabianMap.begin(); it!=fabianMap.end(); it++){
    fabianModel.addBkgPdf(it->second.second,it->first,Form("fabian_%s_cat%d",it->second.first.c_str(),cat),false); 
  }
  fabianModel.setSignalPdfFromMC(sigMC);
  //fabianModel.setSignalPdf(sigPdf);
  fabianModel.makeSBPdfs(false);
  map<string,RooAbsPdf*> fabianBkgPdfs = fabianModel.getBkgPdfs();
  map<string,RooAbsPdf*> fabianSBPdfs = fabianModel.getSBPdfs();

  // set of models to profile 
  PdfModelBuilder paulModel;
  paulModel.setObsVar(mass);
  paulModel.setSignalModifier(mu);
  // add pdfs from config datfile - should be no need to cache these
  for (vector<pair<int,pair<string,string> > >::iterator it=paulMap.begin(); it!=paulMap.end(); it++){
    paulModel.addBkgPdf(it->second.second,it->first,Form("paul_%s_cat%d",it->second.first.c_str(),cat),false); 
  }
  paulModel.setSignalPdfFromMC(sigMC);
  //paulModel.setSignalPdf(sigPdf);
  paulModel.makeSBPdfs(false);
  map<string,RooAbsPdf*> paulBkgPdfs = paulModel.getBkgPdfs();
  map<string,RooAbsPdf*> paulSBPdfs = paulModel.getSBPdfs();

  // set up profile for Fabians models
  ProfileMultiplePdfs fabianProfiler;
  for (map<string,RooAbsPdf*>::iterator pdf=fabianSBPdfs.begin(); pdf!=fabianSBPdfs.end(); pdf++){
    fabianProfiler.addPdf(pdf->second);
  }
  cout << "Fabian profiler pdfs:" << endl;
  fabianProfiler.printPdfs();

  // set up profile for Pauls models
  ProfileMultiplePdfs paulProfiler;
  for (map<string,RooAbsPdf*>::iterator pdf=paulSBPdfs.begin(); pdf!=paulSBPdfs.end(); pdf++){
    paulProfiler.addPdf(pdf->second);
  }
  cout << "Paul profiler pdfs:" << endl;
  paulProfiler.printPdfs();

  if (!skipPlots) {
    system(Form("mkdir -p %s/plots/truthToData",outDir.c_str()));
    system(Form("mkdir -p %s/plots/envelopeNlls",outDir.c_str()));
    system(Form("mkdir -p %s/plots/toys",outDir.c_str()));
  }
  
  // throw toys - only need to fit data once as result will be cached
  cout << "------ FITTING TRUTH TO DATA ------" << endl;
  // sometimes useful to do best fit first to get reasonable starting value
  toysModel.setSignalModifierConstant(false);
  toysModel.fitToData(dataBinned,false,false,true);
  // -----
  toysModel.setSignalModifierVal(expectSignal);
  toysModel.setSignalModifierConstant(true);
  toysModel.fitToData(dataBinned,false,true,true);
  if (!skipPlots) toysModel.plotPdfsToData(dataBinned,80,Form("%s/plots/truthToData/datafit_mu%3.1f",outDir.c_str(),expectSignal),false);
  toysModel.setSignalModifierConstant(false);
  toysModel.saveWorkspace(outFile);
  
  for (int toy=0; toy<ntoys; toy++){
    cout << "---------------------------" << endl;
    cout << "--- RUNNING TOY " << toy << " / " << ntoys << " ----" << endl;
    cout << "---------------------------" << endl;
    // wipe stuff for tree
    truthModel.clear();
    muFab.clear();
    muPaul.clear();
    muChi2.clear();
    muAIC.clear();
    muFabErrLow.clear();
    muPaulErrLow.clear();
    muChi2ErrLow.clear();
    muAICErrLow.clear();
    muFabErrHigh.clear();
    muPaulErrHigh.clear();
    muChi2ErrHigh.clear();
    muAICErrHigh.clear();
    // throw toy
    map<string,RooAbsData*> toys; 
    if (throwHybridToys) {
      toysModel.throwHybridToy(Form("truth_job%d_toy%d",jobn,toy),dataBinned->sumEntries(),switchMass,switchFunc,false,true,true,true);
      toys = toysModel.getHybridToyData();
      if (!skipPlots) toysModel.plotToysWithPdfs(Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),80,false);
      if (!skipPlots) toysModel.plotHybridToy(Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),80,switchMass,switchFunc,false);
    }
    else {
      toysModel.throwToy(Form("truth_job%d_toy%d",jobn,toy),dataBinned->sumEntries(),false,true,true,true);
      toys = toysModel.getToyData();
      if (!skipPlots) toysModel.plotToysWithPdfs(Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),80,false);
    }
    for (map<string,RooAbsData*>::iterator it=toys.begin(); it!=toys.end(); it++){
      // ----- USEFUL DEBUG -----------
      //  --- this can be a useful check that the truth model values are being cached properly ---
      //toysModel.fitToData(it->second,true,false,true);
      //toysModel.plotPdfsToData(it->second,80,Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),true,"NONE");
      if (!skipPlots) fabianProfiler.plotNominalFits(it->second,mass,80,Form("%s/plots/toys/job%d_toy%d_fit_fab",outDir.c_str(),jobn,toy));
      if (!skipPlots) paulProfiler.plotNominalFits(it->second,mass,80,Form("%s/plots/toys/job%d_toy%d_fit_paul",outDir.c_str(),jobn,toy));
      //continue;
      // --------------------------------
      cout << "Fitting toy for truth model " << distance(toys.begin(),it) << "/" << toys.size() << " (" << it->first << ") " << endl;
      // get Fabian envelope
      pair<double,map<string,TGraph*> > fabianMinNlls = fabianProfiler.profileLikelihood(it->second,mass,mu,mu_low,mu_high,mu_step);
      pair<double,map<string,TGraph*> > fabianEnvelope = fabianProfiler.computeEnvelope(fabianMinNlls,Form("fabEnvelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),0.);
      if (!skipPlots) fabianProfiler.plot(fabianEnvelope.second,Form("%s/plots/envelopeNlls/nlls_fab_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
     
      // get Paul envelopes
      pair<double,map<string,TGraph*> > paulMinNlls = paulProfiler.profileLikelihood(it->second,mass,mu,mu_low,mu_high,mu_step);
      pair<double,map<string,TGraph*> > paulEnvelope = paulProfiler.computeEnvelope(paulMinNlls,Form("paulEnvelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),0.);
      if (!skipPlots) paulProfiler.plot(paulEnvelope.second,Form("%s/plots/envelopeNlls/nlls_paul_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
      pair<double,map<string,TGraph*> > chi2Envelope = paulProfiler.computeEnvelope(paulMinNlls,Form("chi2Envelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),1.);
      if (!skipPlots) paulProfiler.plot(chi2Envelope.second,Form("%s/plots/envelopeNlls/nlls_chi2_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
      pair<double,map<string,TGraph*> > aicEnvelope = paulProfiler.computeEnvelope(paulMinNlls,Form("aicEnvelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),2.);
      if (!skipPlots) paulProfiler.plot(aicEnvelope.second,Form("%s/plots/envelopeNlls/nlls_aic_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
     
      pair<double,pair<double,double> > muFabInfo = ProfileMultiplePdfs::getMinAndErrorAsymm(fabianEnvelope.second["envelope"],1.);
      pair<double,pair<double,double> > muPaulInfo = ProfileMultiplePdfs::getMinAndErrorAsymm(paulEnvelope.second["envelope"],1.);
      pair<double,pair<double,double> > muChi2Info = ProfileMultiplePdfs::getMinAndErrorAsymm(chi2Envelope.second["envelope"],1.);
      pair<double,pair<double,double> > muAICInfo = ProfileMultiplePdfs::getMinAndErrorAsymm(aicEnvelope.second["envelope"],1.);

      truthModel.push_back(it->first);
      muFab.push_back(muFabInfo.first);
      muPaul.push_back(muPaulInfo.first);
      muChi2.push_back(muChi2Info.first);
      muAIC.push_back(muAICInfo.first);
      muFabErrLow.push_back(muFabInfo.second.first);
      muPaulErrLow.push_back(muPaulInfo.second.first);
      muChi2ErrLow.push_back(muChi2Info.second.first);
      muAICErrLow.push_back(muAICInfo.second.first);
      muFabErrHigh.push_back(muFabInfo.second.second);
      muPaulErrHigh.push_back(muPaulInfo.second.second);
      muChi2ErrHigh.push_back(muChi2Info.second.second);
      muAICErrHigh.push_back(muAICInfo.second.second);

      cout << "Fab mu = " << muFabInfo.first << " - " << muFabInfo.second.first << " + " << muFabInfo.second.second << endl;
      cout << "Paul mu = " << muPaulInfo.first << " - " << muPaulInfo.second.first << " + " << muPaulInfo.second.second << endl;
      cout << "Chi2 mu = " << muChi2Info.first << " - " << muChi2Info.second.first << " + " << muChi2Info.second.second << endl;
      cout << "AIC mu = " << muAICInfo.first << " - " << muAICInfo.second.first << " + " << muAICInfo.second.second << endl;

      outFile->cd();
      fabianEnvelope.second["envelope"]->Write();
      paulEnvelope.second["envelope"]->Write();
      chi2Envelope.second["envelope"]->Write();
      aicEnvelope.second["envelope"]->Write();
    }
    toyn=toy;
    muTree->Fill();
  }

  outFile->cd();
  muTree->Write();
  cout << "Done." << endl;
  cout << "Whole process took..." << endl;
  cout << "\t "; sw.Print();
 
  outFile->Close();

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

//   gROOT->ProcessLine(".L tdrstyle.C");
//   setTDRStyle();
//   gStyle->SetPadRightMargin(0.05);

  //Create Data Set
  RooRealVar mass("zmass","m(e^{+}e^{-})",minMass,maxMass,"GeV/c^{2}");
  RooRealVar puw("puW","pileup weight",0.,2.);
  //  mass.setRange(80,100);

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

  TString nF(inputFilename.c_str());
  nF.ReplaceAll(".root","_friend.root");
  ttree->AddFriend("puweights=zeetree/probe_tree",nF.Data());
  float puW;
  ttree->SetBranchAddress("puW",&puW);
  
  RooArgSet zMassArgSet(mass,puw);
  RooDataSet* data = new RooDataSet("data", "ntuple parameters", zMassArgSet, RooFit::WeightVar("puW"));

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

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

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

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

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

    //*************************************************************************
    //pt bins and eta bins
    //*************************************************************************
    Int_t Ele1PtBin = -1;
    Int_t Ele1EtaBin = -1;
    Int_t Ele2PtBin = -1;
    Int_t Ele2EtaBin = -1;
    Int_t Ele1R9Bin = -1;
    Int_t Ele2R9Bin = -1;
    if (ele1pt > 20 && ele1pt < 30) Ele1PtBin = 0;
    else if (ele1pt < 40) Ele1PtBin = 1;
    else if (ele1pt < 50) Ele1PtBin = 2;
    else Ele1PtBin = 3;
    if (ele2pt > 20 && ele2pt < 30) Ele2PtBin = 0;
    else if (ele2pt < 40) Ele2PtBin = 1;
    else if (ele2pt < 50) Ele2PtBin = 2;
    else Ele2PtBin = 3;
    if (fabs(zeeTree->l1sceta) < 1.479) Ele1EtaBin = 0;
    else Ele1EtaBin = 1;
    if (fabs(zeeTree->l2sceta) < 1.479) Ele2EtaBin = 0;
    else Ele2EtaBin = 1;
    if (zeeTree->l1r9 > 0.94) Ele1R9Bin = 0;
    else Ele1R9Bin = 1;
    if (zeeTree->l2r9 > 0.94) Ele2R9Bin = 0;
    else Ele2R9Bin = 1;

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

    //*************************************************************************
    //set mass variable
    //*************************************************************************
    zMassArgSet.setRealValue("zmass", zMass);    
    
    data->add(zMassArgSet,puW);
  }
  cout << "data->isWeighted() = " << data->isWeighted() << endl;

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

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

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

  //Crystal Ball parameters
//   RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
//   RooRealVar cbSigma("sigma_{CB}", "CB Width", 1.7, 0.8, 5.0, "GeV/c^{2}");
//   RooRealVar cbCut  ("a_{CB}","CB Cut", 1.05, 1.0, 3.0);
//   RooRealVar cbPower("n_{CB}","CB Order", 2.45, 0.1, 20.0);
  RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
  RooRealVar cbSigma("#sigma_{CB}", "CB Width", 1.5, 0.8, 5.0, "GeV/c^{2}");
  RooRealVar cbCut  ("a_{CB}","CB Cut", 1.0, 1.0, 3.0);
  RooRealVar cbPower("n_{CB}","CB Order", 2.5, 0.1, 20.0);
  cbCut.setVal(cutoff_cb);
  cbPower.setVal(power_cb);
  //  if(!isMC && !(ptBin==0 && etaBin==1 && R9Bin==0)) {
  //    cbCut.setConstant(kTRUE);
  //    cbPower.setConstant(kTRUE);
  //  }

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

  //Breit_Wigner parameters
  RooRealVar bwMean("m_{Z}","BW Mean", 91.1876, "GeV/c^{2}");
  bwMean.setVal(mean_bw);
  RooRealVar bwWidth("#Gamma_{Z}", "BW Width", 2.4952, "GeV/c^{2}");
  bwWidth.setVal(gamma_bw);

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

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

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

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

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

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

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

  TStopwatch t ;
  t.Start() ;
  RooFitResult *fitres = model.fitTo(*bdata,Hesse(1),Minos(1),Timer(1),Save(1));
  fitres->SetName("fitres");
  t.Print() ;

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

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

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

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

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

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

}
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();
   }
}
Beispiel #22
0
void plotContsSingle(TFile *fOUT, std::string dirname, std::string fin, float X, int keepMDM=10){

   //gSystem->Load("libHiggsAnalysisCombinedLimit.so");
   gROOT->SetBatch(1);

   TFile *fiSignals = TFile::Open("signalsVA.root");
   RooWorkspace *workspace = (RooWorkspace*)fiSignals->Get("combinedws");
   TFile *fiSignalsPS = TFile::Open("signalsPS.root");
   RooWorkspace *workspacePS = (RooWorkspace*)fiSignalsPS->Get("combinedws");

   //TFile *fi = TFile::Open("limits-output.root");
   //TFile *fi = TFile::Open("signal-scans.root");
   TFile *fi = TFile::Open(fin.c_str());
   TTree *tree = (TTree*)fi->Get("limit");

   double mh;
   double limit;
   float quantile;
   tree->SetBranchAddress("mh",&mh);
   tree->SetBranchAddress("limit",&limit);
   tree->SetBranchAddress("quantileExpected",&quantile);

   int nvt = tree->GetEntries();
   
   TGraph2D *grV = new TGraph2D(); grV->SetName("vector");
   TGraph2D *grA = new TGraph2D(); grA->SetName("axial");
   TGraph2D *grS = new TGraph2D(); grS->SetName("scalar");
   TGraph2D *grP = new TGraph2D(); grP->SetName("pseudoscalar");


   TGraph2D *grVs = new TGraph2D(); grVs->SetName("vector_signal");
   TGraph2D *grAs = new TGraph2D(); grAs->SetName("axial_signal");
   TGraph2D *grSs = new TGraph2D(); grSs->SetName("scalar_signal");
   TGraph2D *grPs = new TGraph2D(); grPs->SetName("pseudoscalar_signal");

   int ptV=0;
   int ptA=0;
   int ptS=0;
   int ptP=0;

   TGraph *grV_mMED = new TGraph(); grV_mMED->SetName(Form("vector_mMED_mDM%d",keepMDM));
   TGraph *grA_mMED = new TGraph(); grA_mMED->SetName(Form("axial_mMED_mDM%d",keepMDM));
   TGraph *grS_mMED = new TGraph(); grS_mMED->SetName(Form("scalar_mMED_mDM%d",keepMDM));
   TGraph *grP_mMED = new TGraph(); grP_mMED->SetName(Form("pseudoscalar_mMED_mDM%d",keepMDM));
   int ptVm=0;
   int ptAm=0;
   int ptSm=0;
   int ptPm=0;

   grV_mMED->SetLineWidth(2); grV_mMED->SetMarkerSize(1.0);
   grA_mMED->SetLineWidth(2); grA_mMED->SetMarkerSize(1.0);
   grS_mMED->SetLineWidth(2); grS_mMED->SetMarkerSize(1.0);
   grP_mMED->SetLineWidth(2); grP_mMED->SetMarkerSize(1.0);

   for (int i=0; i<nvt;i++){
     //if ( ! ( i%6==X ) ) continue; // 2 or 5
     tree->GetEntry(i);
     if (quantile!=X) continue;
      
     int cd = code(mh);

     float mmed = MMED(mh,cd);
     float mdm  = MDM(mh,cd);

     // onshell crazyness?
     if ((int)mmed==2*( (int)mdm) ) continue;
     //
     //std::cout << " int X = " << i << std::endl;
     //std::cout << mh << ", " << cd << ", " << mmed << ", " << mdm <<  ", " << limit << std::endl;  
     //std::cout << mh << ", " << Form("monojet_signal_signal_%3d%04d%04d",cd,(int)mmed,(int)mdm) << std::endl; 
     //exit();
     
     //std::vector<std::pair<double,double>> pointsV_mMED;
     //std::vector<std::pair<double,double>> pointsA_mMED;
     //std::vector<std::pair<double,double>> pointsS_mMED;
     //std::vector<std::pair<double,double>> pointsP_mMED;

     RooDataHist *dh; 
     if      (cd==801 || cd==800) dh = (RooDataHist*) workspace->data(Form("monojet_signal_signal_%3d%04d%04d",cd,(int)mmed,(int)mdm));
     else if (cd==805 || cd==806) dh = (RooDataHist*) workspacePS->data(Form("monojet_signal_signal_%3d%04d%04d",cd,(int)mmed,(int)mdm));
     double nsignal = 0;
     if (dh) {
     	nsignal = dh->sumEntries();
     }
     if (cd==800) {
	grVs->SetPoint(ptV,mmed,mdm,nsignal);
     	grV->SetPoint(ptV,mmed,mdm,limit);
	ptV++;
	if ( (int)mdm == keepMDM ) { 
		grV_mMED->SetPoint(ptVm,mmed,limit);
		//pointsV_mMED.push_back(std::mk_pair<double,double>(mmed,limit));
		ptVm++;
	}
     } else if (cd==801){
	grAs->SetPoint(ptA,mmed,mdm,nsignal);
     	grA->SetPoint(ptA,mmed,mdm,limit);
	ptA++;
	if ( (int)mdm == keepMDM ) { 
		grA_mMED->SetPoint(ptAm,mmed,limit);
		ptAm++;
	}
     } else if (cd==805){
	grSs->SetPoint(ptS,mmed,mdm,nsignal);
     	grS->SetPoint(ptS,mmed,mdm,limit);
	ptS++;
	if ( (int)mdm == keepMDM ) { 
		grS_mMED->SetPoint(ptSm,mmed,limit);
		ptSm++;
	}
     } else if (cd==806){
	grPs->SetPoint(ptP,mmed,mdm,nsignal);
     	grP->SetPoint(ptP,mmed,mdm,limit);
	ptP++;
	if ( (int)mdm == keepMDM ) { 
     		//std::cout << mh << ", " << cd << ", " << mmed << ", " << mdm <<  ", " << limit <<std::endl;  
		grP_mMED->SetPoint(ptPm,mmed,limit);
		ptPm++;
	}
     }
   }

   // Add a strip of points to the edges of the graphs as contours suck?
   //
   /*
   dress2d(grV);
   dress2d(grA);
   dress2d(grS);
   dress2d(grP);
   */

   TDirectory *fout = fOUT->mkdir(dirname.c_str());
   //TFile *fout = new TDirectory(); 
   // TFile(Form("fout-%s.root",fin.c_str()),"RECREATE");
   fout->WriteTObject(grV);
   fout->WriteTObject(grA);
   fout->WriteTObject(grS);
   fout->WriteTObject(grP);

   reorderFuckingUselessGraph(grV_mMED);
   reorderFuckingUselessGraph(grA_mMED);
   reorderFuckingUselessGraph(grS_mMED);
   reorderFuckingUselessGraph(grP_mMED);

   fout->WriteTObject(grV_mMED);
   fout->WriteTObject(grA_mMED);
   fout->WriteTObject(grS_mMED);
   fout->WriteTObject(grP_mMED);

   fout->WriteTObject(grVs);
   fout->WriteTObject(grAs);
   fout->WriteTObject(grSs);
   fout->WriteTObject(grPs);
   
   //TGraph2D *grVf = (TGraph2D*) supergraph(grV);
   //TGraph2D *grAf = (TGraph2D*) supergraph(grA);
//   TGraph2D *grSf = (TGraph2D*) supergraph(grS);
//   TGraph2D *grPf = (TGraph2D*) supergraph(grP);

   //fout->WriteTObject(grVf);
   //fout->WriteTObject(grAf);
//   fout->WriteTObject(grSf);
//   fout->WriteTObject(grPf);

 //  limit->Draw("limit: ((Int_t)(mh-80100000000))/10000 : (mh-80100000000)  - ( ((Int_t)(mh-80100000000))/10000 )*10000 ","Entry$%6==2")

}
Beispiel #23
0
void DrawMass(int iSEL)
{
  gROOT->ForceStyle();
  TString SET[2] = {"A","B"};
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  TString SELECTION[2] = {"NOM","VBF"};
  TString MASS_RAW[2]  = {"mbb[1]","mbb[2]"};
  TString MASS_REG[2]  = {"mbbReg[1]","mbbReg[2]"};

 // TFile *inf = TFile::Open("Fit_VBFPowheg125_sel"+SELECTION[iSEL]+".root");
  TFile *inf = TFile::Open("/usb/data2/UAData/2015/flatTree_VBFPowheg125.root");
  TTree *tr  = (TTree*)inf->Get("Hbb/events");

  TH1F *hRaw = new TH1F("hRawMass","hRawMass",150,0,300);
  TH1F *hReg = new TH1F("hRegMass","hRegMass",150,0,300);

  RooRealVar x("mbb","mbb",60,170);

  TCanvas *can = new TCanvas("Mbb_sel"+SELECTION[iSEL],"Mbb_sel"+SELECTION[iSEL],900,750);
  
  TCut ct1 = TCut("triggerResult[0]==1||triggerResult[1]==1");
  TCut cs1 = TCut("jetBtag[b1[1]]>0.244 && jetBtag[b2[1]]>0.244 && jetPt[3]>40. && jetPt[2]>50. && jetPt[1]>70. && jetPt[0]>80. && dEtaqq[1]>2.5 && mqq[1]>250 && dPhibb[1]<2.0 && nLeptons==0");
  tr->Draw(MASS_RAW[iSEL]+">>hRawMass",ct1&&cs1);
  tr->Draw(MASS_REG[iSEL]+">>hRegMass",ct1&&cs1);

  hRaw->Sumw2();
  hReg->Sumw2();
  hRaw->Scale(1./(hRaw->Integral()*hRaw->GetBinWidth(1)));
  hReg->Scale(1./(hReg->Integral()*hReg->GetBinWidth(1)));

  RooDataHist *rRaw = new RooDataHist("rRaw","rRaw",x,hRaw);
  RooDataHist *rReg = new RooDataHist("rReg","rReg",x,hReg);

  RooRealVar m1("m1","m1",125,110,140); 
  RooRealVar m2("m2","m2",125,110,140);
  RooRealVar sL1("sL1","sL1",12,3,30); 
  RooRealVar sL2("sL2","sL2",12,3,30);
  RooRealVar sR1("sR1","sR1",12,3,30); 
  RooRealVar sR2("sR2","sR2",12,3,30);
  RooRealVar a1("a1","a1",1,-10,10); 
  RooRealVar a2("a2","a2",1,-10,10); 
  RooRealVar n1("n1","n1",1,0,100); 
  RooRealVar n2("n2","n2",1,0,100);        
  RooRealVar b10("b10","b10",0.5,0.,1.);
  RooRealVar b11("b11","b11",0.5,0.,1.);
  RooRealVar b12("b12","b12",0.5,0.,1.);
  RooRealVar b13("b13","b13",0.5,0.,1.);
  RooRealVar b20("b20","b20",0.5,0.,1.);
  RooRealVar b21("b21","b21",0.5,0.,1.);
  RooRealVar b22("b22","b22",0.5,0.,1.); 
  RooRealVar b23("b23","b23",0.5,0.,1.);     
        
  RooBernstein bkg1("bkg1","bkg1",x,RooArgSet(b10,b11,b12,b13));
  RooBernstein bkg2("bkg2","bkg2",x,RooArgSet(b20,b21,b22,b23));
  RooRealVar fsig1("fsig1","fsig1",0.7,0.,1.); 
  RooRealVar fsig2("fsig2","fsig2",0.7,0.,1.);     
  RooBifurGauss sig1("sig1","sig1",x,m1,sL1,sR1);
  RooBifurGauss sig2("sig2","sig2",x,m2,sL2,sR2);
  //RooCBShape sig1("sig1","sig1",x,m1,s1,a1,n1);
  //RooCBShape sig2("sig2","sig2",x,m2,s2,a2,n2);
        
  RooAddPdf *model1 = new RooAddPdf("model1","model1",RooArgList(sig1,bkg1),fsig1);
  RooAddPdf *model2 = new RooAddPdf("model2","model2",RooArgList(sig2,bkg2),fsig2);

  model1->fitTo(*rRaw,SumW2Error(kFALSE),"q");
  model2->fitTo(*rReg,SumW2Error(kFALSE),"q");

  hRaw->SetLineWidth(2);
  hReg->SetLineWidth(2);
  hRaw->SetLineColor(kBlack);
  hReg->SetLineColor(kRed+1); 
  hReg->SetFillColor(kRed-10);
  hRaw->SetMarkerStyle(21);
  hReg->SetMarkerStyle(20);
  hRaw->SetMarkerSize(1.5);
  hReg->SetMarkerSize(1.5);
  hRaw->SetMarkerColor(kBlack);
  hReg->SetMarkerColor(kRed+1);
  
  RooPlot* frame = x.frame();
  rRaw->plotOn(frame,LineColor(kBlack),LineWidth(1),MarkerColor(kBlack),MarkerStyle(21));
  model1->plotOn(frame,LineColor(kBlack),LineWidth(2));
  rReg->plotOn(frame,LineColor(kRed+1),LineWidth(1),MarkerColor(kRed+1),MarkerStyle(20));
  model2->plotOn(frame,LineColor(kRed+1),LineWidth(2));

  
  TF1 *tmp_func1 = model1->asTF(x,fsig1,x);
  TF1 *tmp_func2 = model2->asTF(x,fsig2,x);
  double y01 = tmp_func1->GetMaximum();
  double x01 = tmp_func1->GetMaximumX();
  double x11 = tmp_func1->GetX(y01/2,60,x01);
  double x21 = tmp_func1->GetX(y01/2,x01,200);
  double FWHM1 = x21-x11;
  
  double y02 = tmp_func2->GetMaximum();
  double x02 = tmp_func2->GetMaximumX();
  double x12 = tmp_func2->GetX(y02/2,60,x02);
  double x22 = tmp_func2->GetX(y02/2,x02,200);
  double FWHM2 = x22-x12;
  
  hReg->GetXaxis()->SetRangeUser(60,170);
  hReg->GetXaxis()->SetTitle("m_{bb} (GeV)");
  hReg->GetYaxis()->SetTitle("1/N #times dN/dm_{bb} (GeV^{-1})");
  hReg->GetYaxis()->SetNdivisions(505);
  hReg->SetMaximum(0.035);
  hReg->Draw("HIST");
  hRaw->Draw("HIST SAME");
  frame->Draw("same");

  TLegend *leg = new TLegend(0.18,0.7,0.43,0.91);
  leg->SetTextFont(42);
  leg->SetTextSize(0.05);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetHeader("m_{H} = 125 GeV (set "+SET[iSEL]+")");
  leg->AddEntry(hReg,"Regressed","LP");
  leg->AddEntry(hRaw,"Raw","LP");
  leg->Draw();

  TPaveText *pave1 = new TPaveText(0.18,0.56,0.43,0.7,"NDC");
  pave1->AddText(TString::Format("PEAK = %1.1f GeV",x02));
  pave1->AddText(TString::Format("FWHM = %1.1f GeV",FWHM2));
  pave1->SetTextFont(42);
  pave1->SetTextSize(0.04);
  pave1->SetTextColor(kRed+1);
  pave1->SetBorderSize(0);
  pave1->SetFillColor(0);
  pave1->Draw();

  TPaveText *pave2 = new TPaveText(0.18,0.42,0.43,0.56,"NDC");
  pave2->AddText(TString::Format("PEAK = %1.1f GeV",x01));
  pave2->AddText(TString::Format("FWHM = %1.1f GeV",FWHM1));
  pave2->SetTextFont(42);
  pave2->SetTextSize(0.04);
  pave2->SetTextColor(kBlack);
  pave2->SetBorderSize(0);
  pave2->SetFillColor(0);
  pave2->Draw();


  can->SaveAs("regressionKost.pdf");
//  CMS_lumi(can,0,0); 
}
Beispiel #24
0
double* fitHist(TCanvas *iC, bool iDoMu,int iPlot, std::string iName,TH1D *iData,TH1D *iW,TH1D *iEWK,TH1D *iAntiData,TH1D *iAntiW,TH1D *iAntiEWK,const Double_t METMAX,const Int_t NBINS,const Double_t lumi,const Int_t Ecm,int iAltQCD) {
    //
    // Declare fit parameters for signal and background yields
    // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
    //
    RooRealVar nSig(("nSig"+iName).c_str(),("nSig"+iName).c_str(),0.7*(iData->Integral()),0,iData->Integral());
    RooRealVar nQCD(("nQCD"+iName).c_str(),("nQCD"+iName).c_str(),0.3*(iData->Integral()),0,iData->Integral());
    RooRealVar cewk(("cewk"+iName).c_str(),("cewk"+iName).c_str(),0.1,0,5) ;
    cewk.setVal(iEWK->Integral()/iW->Integral());
    cewk.setConstant(kTRUE);
    RooFormulaVar nEWK(("nEWK"+iName).c_str(),("nEWK"+iName).c_str(),("cewk"+iName+"*nSig"+iName).c_str(),RooArgList(nSig,cewk));

    RooRealVar nAntiSig(("nAntiSig"+iName).c_str(),("nAntiSig"+iName).c_str(),0.05*(iAntiData->Integral()),0,iAntiData->Integral());
    RooRealVar nAntiQCD(("nAntiQCD"+iName).c_str(),("nAntiQCD"+iName).c_str(),0.9 *(iAntiData->Integral()),0,iAntiData->Integral());
    RooRealVar dewk    (("dewk"    +iName).c_str(),("dewk"    +iName).c_str(),0.1,0,5) ;
    dewk.setVal(iAntiEWK->Integral()/iAntiW->Integral());
    dewk.setConstant(kTRUE);
    RooFormulaVar nAntiEWK(("nAntiEWK"+iName).c_str(),("nAntiEWK"+iName).c_str(),("dewk"+iName+"*nAntiSig"+iName).c_str(),RooArgList(nAntiSig,dewk));

    //
    // Construct PDFs for fitting
    //
    RooRealVar pfmet(("pfmet"+iName).c_str(),("pfmet"+iName).c_str(),0,METMAX);
    pfmet.setBins(NBINS);

    // Signal PDFs
    RooDataHist wMet  (("wMET" +iName).c_str(), ("wMET" +iName).c_str(),     RooArgSet(pfmet),iW);
    RooHistPdf  pdfW(( "w"+iName).c_str(), ( "w"+iName).c_str(), pfmet, wMet, 1);
    RooDataHist awMet (("awMET"+iName).c_str(), ("awMET"+iName).c_str(),     RooArgSet(pfmet),iAntiW);
    RooHistPdf apdfW(("aw"+iName).c_str(), ("aw"+iName).c_str(), pfmet,awMet, 1);

    // EWK+top PDFs
    RooDataHist ewkMet (("ewkMET" +iName).c_str(),( "ewkMET"+iName).c_str(), RooArgSet(pfmet),iEWK);
    RooHistPdf  pdfEWK (( "ewk"+iName).c_str(),( "ewk"+iName).c_str(), pfmet,ewkMet, 1);
    RooDataHist aewkMet(("aewkMET"+iName).c_str(),("aewkMET"+iName).c_str(), RooArgSet(pfmet),iAntiEWK);
    RooHistPdf apdfEWK (("aewk"+iName).c_str(),("aewk"+iName).c_str(), pfmet,aewkMet, 1);

    // QCD Pdfs
    CPepeModel0 qcd0 (("qcd0" +iName).c_str(),pfmet);
    CPepeModel1 qcd1 (("qcd1" +iName).c_str(),pfmet);
    CPepeModel2 qcd2 (("qcd2" +iName).c_str(),pfmet);
    CPepeModel0 aqcd0(("aqcd0"+iName).c_str(),pfmet);
    CPepeModel1 aqcd1(("aqcd1"+iName).c_str(),pfmet,qcd1.sigma);
    CPepeModel2 aqcd2(("aqcd2"+iName).c_str(),pfmet);
    RooGenericPdf *lQCD  =  qcd0.model;
    RooGenericPdf *lAQCD = aqcd0.model;
    if(iDoMu) lQCD  = qcd1.model;
    if(iDoMu) lAQCD = aqcd1.model;
    if(iAltQCD == 0) lQCD = qcd0.model;
    if(iAltQCD == 1) lQCD = qcd1.model;
    if(iAltQCD == 2) lQCD = qcd2.model;
    if(iAltQCD == 0) lAQCD = aqcd0.model;
    if(iAltQCD == 1) lAQCD = aqcd1.model;
    if(iAltQCD == 2) lAQCD = aqcd2.model;

    // Signal + Background PDFs
    RooAddPdf pdfMet (("pdfMet"+iName).c_str(), ("pdfMet" +iName).c_str(), RooArgList(pdfW ,pdfEWK ,*lQCD), RooArgList(nSig,nEWK,nQCD));
    RooAddPdf apdfMet(("apdfMet"+iName).c_str(),("apdfMet"+iName).c_str(), RooArgList(apdfW,apdfEWK,*lAQCD), RooArgList(nAntiSig,nAntiEWK,nAntiQCD));

    // PDF for simultaneous fit
    RooCategory rooCat("rooCat","rooCat");
    rooCat.defineType("Select");
    rooCat.defineType("Anti");

    RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat);
    pdfTotal.addPdf(pdfMet, "Select");
    if(iDoMu) pdfTotal.addPdf(apdfMet,"Anti");

    // Perform fits
    RooDataHist dataMet  (("dataMet"+iName).c_str(),("dataMet"+iName).c_str(), RooArgSet(pfmet),iData);
    RooDataHist antiMet  (("antiMet"+iName).c_str(),("antiMet"+iName).c_str(), RooArgSet(pfmet),iAntiData);
    RooDataHist dataTotal(("data"   +iName).c_str(),("data"   +iName).c_str(), RooArgList(pfmet), Index(rooCat),
                          Import("Select", dataMet),
                          Import("Anti",   antiMet));

    RooFitResult *fitRes = 0;
    bool runMinos = kTRUE;
    if(iPlot == 0 || iPlot == 3) runMinos = kFALSE; //Remove Minos when running toys (too damn slow)
    if(!iDoMu) fitRes = pdfMet  .fitTo(dataMet  ,Extended(),Minos(runMinos),Save(kTRUE));
    if( iDoMu) fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(runMinos),Save(kTRUE));

    double *lResults = new double[16];
    lResults[0]  = nSig.getVal();
    lResults[1]  = nEWK.getVal();
    lResults[2]  = nQCD.getVal();
    lResults[3]  = nAntiSig.getVal();
    lResults[4]  = nAntiEWK.getVal();
    lResults[5]  = nAntiQCD.getVal();
    if(!iDoMu) lResults[6]  = double(qcd0.sigma->getVal());
    if( iDoMu) lResults[6]  = double(qcd1.sigma->getVal());

    lResults[7]  = 0.;
    if(!iDoMu) lResults[7]  = qcd1.a1->getVal();
    lResults[8]   = nSig    .getPropagatedError(*fitRes);
    lResults[9]   = nEWK    .getPropagatedError(*fitRes);
    lResults[10]  = nQCD    .getPropagatedError(*fitRes);
    lResults[11]  = nAntiSig.getPropagatedError(*fitRes);
    lResults[12]  = nAntiEWK.getPropagatedError(*fitRes);
    lResults[13]  = nAntiQCD.getPropagatedError(*fitRes);
    if( iDoMu) lResults[14]  = qcd0.sigma->getError();
    if(!iDoMu) lResults[14]  = qcd1.sigma->getError();
    if( iDoMu) lResults[15]  = 0;
    if(!iDoMu) lResults[15]  = qcd1.a1   ->getError();
    if(iPlot == 0 ) return lResults;
    //
    // Use histogram version of fitted PDFs to make ratio plots
    // (Will also use PDF histograms later for Chi^2 and KS tests)
    //
    TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram(("hPdfMet"+iName).c_str(), pfmet));
    hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
    TH1D *hMetDiff = makeDiffHist(iData,hPdfMet,"hMetDiff"+iName);
    hMetDiff->SetMarkerStyle(kFullCircle);
    hMetDiff->SetMarkerSize(0.9);

    TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram(("hPdfAntiMet"+iName).c_str(), pfmet));
    hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
    TH1D *hAntiMetDiff = makeDiffHist(iAntiData,hPdfAntiMet,"hAntiMetDiff"+iName);
    hAntiMetDiff->SetMarkerStyle(kFullCircle);
    hAntiMetDiff->SetMarkerSize(0.9);
    if(iPlot == 3 ) {
        //Build best fit QCD with default W and EWK Shap
        TH1D *hPdfMetQCD  = (TH1D*)(lQCD ->createHistogram(("hPdfMetQCD"    +iName).c_str(), pfmet));
        TH1D *hPdfAMetQCD = (TH1D*)(lAQCD->createHistogram(("hPdfAntiMetQCD"+iName).c_str(), pfmet));
        hPdfMetQCD ->Scale(nQCD    .getVal()/hPdfMetQCD ->Integral());
        hPdfAMetQCD->Scale(nAntiQCD.getVal()/hPdfAMetQCD->Integral());

        TH1D *pW    = (TH1D*) iW      ->Clone("WForToys");
        pW   ->Scale(nSig    .getVal()/pW   ->Integral());
        TH1D *pEWK  = (TH1D*) iEWK    ->Clone("EWKForToys");
        pEWK ->Scale(nEWK    .getVal()/pEWK ->Integral());
        TH1D *pAW   = (TH1D*) iAntiW  ->Clone("AWForToys");
        pAW  ->Scale(nAntiSig.getVal()/pAW  ->Integral());
        TH1D *pAEWK = (TH1D*) iAntiEWK->Clone("AEWKForToys");
        pAEWK->Scale(nAntiEWK.getVal()/pAEWK->Integral());
        hPdfMetQCD ->Add(pW);
        hPdfMetQCD ->Add(pEWK);
        hPdfAMetQCD->Add(pAW);
        hPdfAMetQCD->Add(pAEWK);
        fBestFit     = hPdfMetQCD;
        fAntiBestFit = hPdfAMetQCD;
        return lResults;
    }

    //--------------------------------------------------------------------------------------------------------------
    // Make plots
    //==============================================================================================================
    char ylabel[100];  // string buffer for y-axis label

    // file format for output plots
    const TString format("png");

    // label for lumi
    char lumitext[100];
    if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = %i TeV",lumi*1000.,Ecm);
    else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = %i TeV",lumi      ,Ecm);

    // plot colors
    Int_t linecolorW   = kOrange-3;
    Int_t fillcolorW   = kOrange-2;
    Int_t linecolorEWK = kOrange+10;
    Int_t fillcolorEWK = kOrange+7;
    Int_t linecolorQCD = kViolet+2;
    Int_t fillcolorQCD = kViolet-5;
    Int_t ratioColor   = kGray+2;

    //
    // Dummy histograms for TLegend
    // (Nobody can figure out how to properly pass RooFit objects...)
    //
    TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
    hDummyData->SetMarkerStyle(kFullCircle);
    hDummyData->SetMarkerSize(0.9);

    TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
    hDummyW->SetLineColor(linecolorW);
    hDummyW->SetFillColor(fillcolorW);
    hDummyW->SetFillStyle(1001);

    TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
    hDummyEWK->SetLineColor(linecolorEWK);
    hDummyEWK->SetFillColor(fillcolorEWK);
    hDummyEWK->SetFillStyle(1001);

    TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
    hDummyQCD->SetLineColor(linecolorQCD);
    hDummyQCD->SetFillColor(fillcolorQCD);
    hDummyQCD->SetFillStyle(1001);

    //
    // W MET plot
    //
    RooPlot *wmframe = pfmet.frame(Bins(NBINS));
    dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
    pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
    pdfMet.plotOn(wmframe,LineColor(linecolorW));
    pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*lQCD)),FillColor(fillcolorEWK),DrawOption("F"));
    pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*lQCD)),LineColor(linecolorEWK));
    pdfMet.plotOn(wmframe,Components(RooArgSet(*lQCD)),FillColor(fillcolorQCD),DrawOption("F"));
    pdfMet.plotOn(wmframe,Components(RooArgSet(*lQCD)),LineColor(linecolorQCD));
    pdfMet.plotOn(wmframe,Components(RooArgSet(pdfW)),LineColor(linecolorW),LineStyle(2));
    dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));

    sprintf(ylabel,"Events / %.1f GeV",iData->GetBinWidth(1));
    CPlot plotMet(("fitmet"+iName).c_str(),wmframe,"","",ylabel);
    plotMet.SetLegend(0.68,0.57,0.93,0.77);
    plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
    plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
    plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
    plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
    plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
    plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
    plotMet.SetYRange(0.1,1.1*(iData->GetMaximum()));
    plotMet.Draw(iC,kFALSE,format,1);

    CPlot plotMetDiff(("fitmet"+iName).c_str(),"","#slash{E}_{T} [GeV]","#chi");
    plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
    plotMetDiff.SetYRange(-8,8);
    plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
    plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
    plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
    plotMetDiff.Draw(iC,kTRUE,format,2);
    plotMet.Draw(iC,kTRUE,format,1);

    plotMet.SetName(("fitmetlog"+iName).c_str());
    plotMet.SetLogy();
    plotMet.SetYRange(1e-3*(iData->GetMaximum()),10*(iData->GetMaximum()));
    plotMet.Draw(iC,kTRUE,format,1);

    if(iDoMu) {
        RooPlot *awmframe = pfmet.frame(Bins(NBINS));
        antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
        apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
        apdfMet.plotOn(awmframe,LineColor(linecolorW));
        apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*lQCD)),FillColor(fillcolorEWK),DrawOption("F"));
        apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*lQCD)),LineColor(linecolorEWK));
        apdfMet.plotOn(awmframe,Components(RooArgSet(*lQCD)),FillColor(fillcolorQCD),DrawOption("F"));
        apdfMet.plotOn(awmframe,Components(RooArgSet(*lQCD)),LineColor(linecolorQCD));
        apdfMet.plotOn(awmframe,Components(RooArgSet(apdfW)),LineColor(linecolorW),LineStyle(2));
        antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));

        sprintf(ylabel,"Events / %.1f GeV",iAntiData->GetBinWidth(1));
        CPlot plotAntiMet(("fitantimet"+iName).c_str(),awmframe,"","",ylabel);
        plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
        plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
        plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
        plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
        plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
        plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
        plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
        plotAntiMet.SetYRange(0.1,1.1*(iAntiData->GetMaximum()));
        plotAntiMet.Draw(iC,kFALSE,format,1);

        CPlot plotAntiMetDiff(("fitantimet"+iName).c_str(),"","#slash{E}_{T} [GeV]","#chi");
        plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
        plotAntiMetDiff.SetYRange(-8,8);
        plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
        plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
        plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
        plotAntiMetDiff.Draw(iC,kTRUE,format,2);

        plotAntiMet.SetName(("fitantimetlog"+iName).c_str());
        plotAntiMet.SetLogy();
        plotAntiMet.SetYRange(1e-3*(iAntiData->GetMaximum()),10*(iAntiData->GetMaximum()));
        plotAntiMet.Draw(iC,kTRUE,format,1);
    }
    if(iPlot == 1) return lResults;

    ofstream txtfile;
    std::string txtfName = "fitres"+iName;
    if( iDoMu) txtfName + "Mu.txt";
    if(!iDoMu) txtfName + "Mu.txt";
    ios_base::fmtflags flags;
    cout << " --- test " << iData->Integral() << " -- " << hPdfMet->Integral() << endl;
    Double_t chi2prob = iData->Chi2Test(hPdfMet,"PUW");
    Double_t chi2ndf  = iData->Chi2Test(hPdfMet,"CHI2/NDFUW");
    Double_t ksprob   = iData->KolmogorovTest(hPdfMet);
    Double_t ksprobpe = 1;//iData->KolmogorovTest(hPdfMet,"DX");
    txtfile.open(txtfName.c_str());
    assert(txtfile.is_open());

    flags = txtfile.flags();
    txtfile << setprecision(10);
    txtfile << " *** Yields *** " << endl;
    txtfile << "Selected: " << iData->Integral() << endl;
    txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
    txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
    txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
    txtfile << endl;
    txtfile.flags(flags);

    fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
    txtfile << endl;
    printCorrelations(txtfile, fitRes);
    txtfile << endl;
    printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
    txtfile.close();
    return lResults;
}
void rf401_importttreethx()
{
    // I m p o r t  m u l t i p l e   T H 1   i n t o   a   R o o D a t a H i s t
    // --------------------------------------------------------------------------

    // Create thee ROOT TH1 histograms
    TH1* hh_1 = makeTH1("hh1",0,3) ;
    TH1* hh_2 = makeTH1("hh2",-3,1) ;
    TH1* hh_3 = makeTH1("hh3",+3,4) ;

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

    // Create category observable c that serves as index for the ROOT histograms
    RooCategory c("c","c") ;
    c.defineType("SampleA") ;
    c.defineType("SampleB") ;
    c.defineType("SampleC") ;

    // Create a binned dataset that imports contents of all TH1 mapped by index category c
    RooDataHist* dh = new RooDataHist("dh","dh",x,Index(c),Import("SampleA",*hh_1),Import("SampleB",*hh_2),Import("SampleC",*hh_3)) ;
    dh->Print() ;

    // Alternative constructor form for importing multiple histograms
    map<string,TH1*> hmap ;
    hmap["SampleA"] = hh_1 ;
    hmap["SampleB"] = hh_2 ;
    hmap["SampleC"] = hh_3 ;
    RooDataHist* dh2 = new RooDataHist("dh","dh",x,c,hmap) ;
    dh2->Print() ;



    // I m p o r t i n g   a   T T r e e   i n t o   a   R o o D a t a S e t   w i t h   c u t s
    // -----------------------------------------------------------------------------------------

    TTree* tree = makeTTree() ;

    // Define observables y,z
    RooRealVar y("y","y",-10,10) ;
    RooRealVar z("z","z",-10,10) ;

    // Import only observables (y,z)
    RooDataSet ds("ds","ds",RooArgSet(x,y),Import(*tree)) ;
    ds.Print() ;

    // Import observables (x,y,z) but only event for which (y+z<0) is true
    RooDataSet ds2("ds2","ds2",RooArgSet(x,y,z),Import(*tree),Cut("y+z<0")) ;
    ds2.Print() ;



    // I m p o r t i n g   i n t e g e r   T T r e e   b r a n c h e s
    // ---------------------------------------------------------------

    // Import integer tree branch as RooRealVar
    RooRealVar i("i","i",0,5) ;
    RooDataSet ds3("ds3","ds3",RooArgSet(i,x),Import(*tree)) ;
    ds3.Print() ;

    // Define category i
    RooCategory icat("i","i") ;
    icat.defineType("State0",0) ;
    icat.defineType("State1",1) ;

    // Import integer tree branch as RooCategory (only events with i==0 and i==1
    // will be imported as those are the only defined states)
    RooDataSet ds4("ds4","ds4",RooArgSet(icat,x),Import(*tree)) ;
    ds4.Print() ;



    // I m p o r t  m u l t i p l e   R o o D a t a S e t s   i n t o   a   R o o D a t a S e t
    // ----------------------------------------------------------------------------------------

    // Create three RooDataSets in (y,z)
    RooDataSet* dsA = (RooDataSet*) ds2.reduce(RooArgSet(x,y),"z<-5") ;
    RooDataSet* dsB = (RooDataSet*) ds2.reduce(RooArgSet(x,y),"abs(z)<5") ;
    RooDataSet* dsC = (RooDataSet*) ds2.reduce(RooArgSet(x,y),"z>5") ;

    // Create a dataset that imports contents of all the above datasets mapped by index category c
    RooDataSet* dsABC = new RooDataSet("dsABC","dsABC",RooArgSet(x,y),Index(c),Import("SampleA",*dsA),Import("SampleB",*dsB),Import("SampleC",*dsC)) ;

    dsABC->Print() ;

}
void makeSystPlot( TFile * f, TString oldFolder, RooWorkspace *WS,  string channel, string syst, int toMassNo, int fromMassNo) //massNo 0-51, see xSec7TeV.h 
{

  RooArgList  * hobs = new RooArgList("hobs");
  RooRealVar BDT("CMS_vhbb_BDT_Zll", "CMS_vhbb_BDT_Zll", -1, 1);///OLD VARIABLE NAME HERE
  hobs->add(*WS->var("CMS_vhbb_BDT_Zll"));  ///NEW VARIABLE NAME HERE
  RooWorkspace *tempWS =  (RooWorkspace*) f->Get(oldFolder.Data());
  TString systT(syst);
  TString chanT(channel);
  bool writeIt = 1;
 
  if(chanT.Contains("QCD") || chanT.Contains("Wj"))
  if(!(systT.Contains("stat"))) writeIt = 0;
 

  if((kount < 3) && (channel=="data_obs"))
  {
    kount++;
    std::string namen  = channel;
    
    std::cout << "reading WS "<< oldFolder.Data() << std::endl;
    std::cout << namen << std::endl;
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,Binning(bins));
    std::cout << namen << std::endl;

    RooDataHist *DHnom = new RooDataHist(channel.c_str(),"",*hobs,tempHistNom);  
    WS->import(*(new RooHistPdf(channel.c_str(),"",*hobs,*DHnom)));
 
 }

 if (channel!="data_obs")
 {
  std::string nameUp; 
  std::string namen; 
  std::string nameDown;


  if((syst == "stat"))
  {
    if(IFILE.Contains("7TeV"))
    {
      nameUp  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Up";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Down";
    }
    if(IFILE.Contains("8TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Up";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Down";
    }

  }
  else
  {
  nameUp  = channel + "CMS_" + syst + "Up";
  namen  = channel;
  nameDown = channel + "CMS_" + syst + "Down";
  }
  if((syst == "ZJModel"))
  {
    if(IFILE.Contains("7TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_7TeVUp";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_7TeVDown";
    }
    if(IFILE.Contains("8TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_8TeVUp";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_8TeVDown";
    }

  }
  
  if(writeIt)
   {
    RooDataHist* tempRooDataHistUp = (RooDataHist*)  tempWS->data(nameUp.c_str());
    RooDataHist* tempRooDataHistDown = (RooDataHist*)  tempWS->data(nameDown.c_str());
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());


   
    std::cout << oldFolder.Data() << std::endl; 
    std::cout << nameUp.c_str() << std::endl; 
 	 
    TH1 *tempHistUp = tempRooDataHistUp->createHistogram(nameUp.c_str(),BDT,Binning(bins));
    TH1 *tempHistDown = tempRooDataHistDown->createHistogram(nameDown.c_str(),BDT,Binning(bins));
    std::cout << namen.c_str() << std::endl;
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,Binning(bins));

    if(chanT.Contains("VH") && IFILE.Contains("7TeV"))
    {
     tempHistUp->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
     tempHistDown->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
     tempHistNom->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
    }  
 
   if(chanT.Contains("VH") && IFILE.Contains("8TeV"))
   {
     tempHistUp->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
     tempHistDown->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
     tempHistNom->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
   }  
   
   std::cout<< "channel--> " << channel << std::endl;


   tempHistUp->SetLineColor(kRed);
   tempHistUp->SetLineWidth(3);
   tempHistUp->SetFillColor(0);
  
   tempHistDown->SetLineColor(kBlue);
   tempHistDown->SetFillColor(0);
   tempHistDown->SetLineWidth(3);
  
   tempHistNom->SetFillColor(0);
   tempHistNom->SetMarkerStyle(20);
   tempHistUp->SetTitle((channel + syst).c_str());
 
 
   RooDataHist *DHnom;
   RooDataHist *DHup = new RooDataHist(nameUp.c_str(),"",*hobs,tempHistUp);  
   if(kount2 < 3) DHnom = new RooDataHist(namen.c_str(),"",*hobs,tempHistNom);
   RooDataHist *DHdown = new RooDataHist(nameDown.c_str(),"",*hobs,tempHistDown);  

   WS->import(*(new RooHistPdf(nameUp.c_str(),"",*hobs,*DHup)));
   WS->import(*(new RooHistPdf(nameDown.c_str(),"",*hobs,*DHdown)));
   if(kount2 < 3){ WS->import(*(new RooHistPdf(namen.c_str(),"",*hobs,*DHnom))); kount2++;}
   }
 }


}
Beispiel #27
0
void fitWWa_el() {

    TFile* fin     = new TFile("../RunII_WVA_ControlPlots.root");


    TH1D* data_obs = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/data_obs");
    TH1D* th1fkdata = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1FakePhotons");
    TH1D* th1wwa = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1wwa");
    TH1D* th1wza = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1wza");
    TH1D* th1wajets = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1wajets");
    TH1D* th1zajets = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1zajets");
    TH1D* th1Top = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1ttajets");
    TH1D* th1tajets = (TH1D*) fin->Get("Electron/vbf_maxpt_jj_m/th1tajets");

    int NbinsX = data_obs->GetNbinsX();
    double xmin = data_obs->GetXaxis()->GetBinLowEdge(1);
    double xmax = data_obs->GetXaxis()->GetBinLowEdge(NbinsX+1);

    data_obs->GetXaxis()->SetRangeUser(xmin, xmax);
    th1fkdata->GetXaxis()->SetRangeUser(xmin, xmax);
    th1wwa->GetXaxis()->SetRangeUser(xmin, xmax);
    th1wza->GetXaxis()->SetRangeUser(xmin, xmax);
    th1wajets->GetXaxis()->SetRangeUser(xmin, xmax);
    th1zajets->GetXaxis()->SetRangeUser(xmin, xmax);
    th1Top->GetXaxis()->SetRangeUser(xmin, xmax);
    th1tajets->GetXaxis()->SetRangeUser(xmin, xmax);

    th1wwa->Add(th1wza);
    th1Top->Add(th1tajets);

    mjj_ = new RooRealVar( "Mjj", "m_{jj}", xmin, xmax, "GeV");
    RooRealVar Mass = *mjj_;
    RooDataHist* data = new RooDataHist("data","data", *mjj_, data_obs);

    RooHistPdf* pdffk = makePdf(th1fkdata, "pdffk");
    RooHistPdf* pdfwwa = makePdf(th1wwa, "pdfwwa");
    RooHistPdf* pdfwajets = makePdf(th1wajets, "pdfwajets");
    RooHistPdf* pdfzajets = makePdf(th1zajets, "pdfzajets");
    RooHistPdf* pdfTop = makePdf(th1Top, "pdfTop");

    double fkNorm = th1fkdata->Integral();
    double wwaNorm = th1wwa->Integral();
    double wajetsNorm = th1wajets->Integral();
    double zajetsNorm = th1zajets->Integral();
    double TopNorm = th1Top->Integral();


    RooRealVar nfk("nfk","nfk",                 fkNorm,     0.0,   1000.);
    RooRealVar nwwa("nwwa","nwwa",              wwaNorm);
    RooRealVar nwajets("nwajets","nwajets",     400.0,     0.0,   10000.);
    RooRealVar nzajets("nzajets","nzajets",     zajetsNorm);
    RooRealVar nTop("nTop","nTop",              TopNorm);


    RooArgList* components
        = new RooArgList(*pdffk, *pdfwwa, *pdfwajets, *pdfzajets, *pdfTop);
    RooArgList* yields = new RooArgList(nfk, nwwa, nwajets, nzajets, nTop);


    RooAddPdf totalPdf("totalPdf","extended sum pdf", *components, *yields);

    RooGaussian consNfk("consNfk","", nfk, RooConst(fkNorm),RooConst(0.146*fkNorm)) ;
    RooGaussian consNwwa("consNwwa","", nwwa, RooConst(wwaNorm),RooConst(0.28*wwaNorm)) ;
    RooGaussian consNzajets("consNzajets","", nzajets, RooConst(zajetsNorm),RooConst(0.22*zajetsNorm)) ;
    RooGaussian consNTop("consNTop","", nTop, RooConst(TopNorm),RooConst(0.21*TopNorm)) ;


    RooFitResult *fitResult
        = totalPdf.fitTo(*data, Save(true),
                         ExternalConstraints(consNfk),
                         //ExternalConstraints(consNwwa),
                         //ExternalConstraints(consNzajets),
                         //ExternalConstraints(consNTop),
                         RooFit::Extended(true),
                         //RooFit::Minos(true),
                         //RooFit::Hesse(false),
                         //PrintEvalErrors(-1),
                         // RooFit::Range(rangeString),
                         Warnings(false)
                        );

    fitResult->Print("v");


    std::cout << "===================== Wa+jets k-factor = " <<
              nwajets.getVal() / wajetsNorm << "  +- "  << nwajets.getError() / wajetsNorm << std::endl;


    // ********** Make and save Canvas for the plots ********** //
    gROOT->ProcessLine(".L ~kalanand/tdrstyle.C");
    setTDRStyle();
    tdrStyle->SetErrorX(0.5);
    tdrStyle->SetPadLeftMargin(0.19);
    tdrStyle->SetPadRightMargin(0.10);
    tdrStyle->SetPadBottomMargin(0.15);
    tdrStyle->SetLegendBorderSize(0);
    tdrStyle->SetTitleYOffset(1.5);
    RooAbsData::ErrorType errorType = RooAbsData::SumW2;



    TCanvas* c = new TCanvas("fit","",500,500);
    RooPlot* frame1 = Mass.frame();
    data->plotOn(frame1,RooFit::DataError(errorType), Name("h_data"));
    totalPdf.plotOn(frame1,ProjWData(*data), Name("h_total"));
    totalPdf.plotOn(frame1,ProjWData(*data),Components("pdfwajets"),
                    LineColor(kRed), LineStyle(2), Name("h_wajets"));

    totalPdf.plotOn(frame1,ProjWData(*data),Components("pdffk,pdfwwa,pdfzajets,pdfTop"),
                    LineColor(kBlack), LineStyle(2), Name("h_others"));
    totalPdf.plotOn(frame1,ProjWData(*data));

    frame1->SetMinimum(0);
    frame1->SetMaximum(1.35* frame1->GetMaximum());
    frame1->Draw("e0");


    std::cout << "===================== chi2/ dof = " << frame1->chiSquare() << std::endl;

    TPaveText *plotlabel4 = new TPaveText(0.25,0.66,0.5,0.81,"NDC");
    plotlabel4->SetTextColor(kBlack);
    plotlabel4->SetFillColor(kWhite);
    plotlabel4->SetBorderSize(0);
    plotlabel4->SetTextAlign(12);
    plotlabel4->SetTextSize(0.04);
    char temp[50];
    sprintf(temp, "#chi^{2} / dof = %.2f", frame1->chiSquare());
    plotlabel4->AddText(temp);
    plotlabel4->Draw();

    cmsPrelim2();

    TLegend* legend = new TLegend(0.55,0.72,0.88,0.91);
    RooHist* datahist = frame1->getHist("h_data");
    RooCurve* totalhist = frame1->getCurve("h_total");
    RooCurve* wjetshist = frame1->getCurve("h_wajets");
    RooCurve* otherhist = frame1->getCurve("h_others");

    legend->AddEntry( datahist, "Data", "PE");
    legend->AddEntry( totalhist, "Fit", "L");
    legend->AddEntry( wjetshist, "W#gamma+jets", "L");
    legend->AddEntry( otherhist, "Other processes", "L");
    legend->SetFillColor(0);
    legend->Draw();
    c->SaveAs( "el_WVa_WjetsKfactorFit.png");
    c->SaveAs( "el_WVa_WjetsKfactorFit.pdf");

}
Beispiel #28
0
void fitTopMass(const char * inFileName)
{

  gROOT->SetBatch(true);
  gSystem->Load("libRooFit");
  TFile* inFile = TFile::Open(inFileName);

  RooRealVar x("mass","M_{top}",100,200);
  using namespace std;
  vector<TH1F*> hists;
  vector<int> nTotal;
  std::vector<std::pair<float, float> >  range;

  const char* types[] = { "top1","top2","top"};
  for( auto type : types ) {
    hists.push_back (  (TH1F*)inFile->Get(TString::Format("%s_mass_GenJet",type)) ) ;
    hists.push_back (  (TH1F*)inFile->Get(TString::Format("%s_mass_Jet",type)) ) ;
    hists.push_back (  (TH1F*)inFile->Get(TString::Format("%s_mass_btagged_Jet",type)) ) ;
    hists.push_back (  (TH1F*)inFile->Get(TString::Format("%s_mass_charged_Jet",type)) ) ;
    hists.push_back (  (TH1F*)inFile->Get(TString::Format("%s_mass_btagged_charged_Jet",type)) ) ;
  }
  for( int i= 0 ; i<hists.size() ; i++) {
    if ( hists[i] == nullptr) std::cout<<"Error! Hist is nullptr."<<std::endl;
  }


  for( int i = 0 ; i < hists.size() ; i++) {
    nTotal.push_back(hists[i]->Integral());
  } 

  // For top1,
  for(int i= 0 ; i < 5 ; i++) {
    range.push_back( make_pair(150,180) ); 
  }
  // For top2,
  for(int i= 0 ; i < 5 ; i++) {
    range.push_back( make_pair(150,180) ); 
  }
  // For all top,
  for(int i= 0 ; i < 5 ; i++) {
    range.push_back( make_pair(150,180) ); 
  }
 
  for( int i= 0 ; i< hists.size() ; i++) {
    std::cout<<"hist["<<i<<"]"<<std::endl;
    RooDataHist* dh = new RooDataHist("dh","data histogram",x,hists[i]);

    auto gaus_mean = RooRealVar("gaus_mean","gaus_mean",172.5, 100,200);
    auto gaus_sigma = RooRealVar("gaus_sigma","gaus_sigma",1, 0,100);
    auto nGaus = RooRealVar("nGaus","nGaus",nTotal[i]*0.2, 0., nTotal[i]);
    auto gaus_pdf = RooGaussian("gaus_pdf","Gaussian p.d.f",x,gaus_mean, gaus_sigma);

    
    auto expo_tau = RooRealVar("exp_const","exp_const",0,-10000,10000);
    auto nExp = RooRealVar("nExp","nExp",1,0,nTotal[i]);
    auto expo_pdf = RooExponential("bkg","bkg p.d.f",x,expo_tau);

    auto CB_mean  = RooRealVar("CB_mean","CB_mean",172.5,100,200);
    auto CB_sigma = RooRealVar("CB_sigma","CB_sigma",5,0,100);
    auto CB_alpha = RooRealVar("CB_alpha","CB_alpha",1,0,100);
    auto CB_n     = RooRealVar("CB_n","CB_n",1,0,100);
    auto nCB = RooRealVar("nCB","nCB",nTotal[i]*0.8,0.,nTotal[i]);
    auto CB_pdf = RooCBShape("sig","signal p.d.f",x,CB_mean, CB_sigma, CB_alpha, CB_n );

    auto BW_mean  = RooRealVar("BW_mean","BW_mean",172.5,100,200);
    auto BW_sigma = RooRealVar("BW_sigma","BW_sigma",10,0,100);
    auto nBW = RooRealVar("nBW","nBW",nTotal[i]*0.7, 0, nTotal[i]);
    auto BW_pdf = RooBreitWigner("sig","signal p.d.f",x,BW_mean, BW_sigma );
  
    RooFormulaVar mirrorX("neg_x","-mass", RooArgSet(x)); 
    //RooRealVar landau_mean("lan_mean","Landau_mean",150.5,100,200);
    RooRealVar landau_mean("lan_mean","Landau_mean",-160,-200,-100);
    RooRealVar landau_sigma("lan_sigma","Landau_sigma",2.5, 0,100);
    RooRealVar nLandau("nLan","nlan",nTotal[i]*0.3, 0, nTotal[i]);
    RooLandau  landau_pdf("lx","lx",mirrorX,landau_mean, landau_sigma);
  
    //TF1* f1 = new TF1("landau","nLan*ROOT::Math::landau_pdf(-x,lan_sigma,-lan_mean)",100,300);
    //RooAbsPdf* invlandau_pdf = RooFit::bindPdf(f1,x,nLandau, landau_mean,landau_sigma);
    //RooGenericPdf invlandau_pdf("invLandau","ROOT::Math::landau_pdf(-x,lan_sigma,-lan_mean)",RooArgSet(x,landau_sigma,landau_mean)); 
 
    //sig_pdf = cb_pdf;
    //bkg_pdf = bw_pdf;
    
    //nsig = nCB;
    //nbkg = nBW;

    //RooFFTConvPdf model("lxg","CB (x) gauss",x,CB_pdf,gaus_pdf);
    //RooFFTConvPdf model("lxg","CB (x) BW",x,CB_pdf,BW_pdf);
    //auto model = RooAddPdf("model","model",RooArgList(landau),RooArgList(nlandau));

    //auto model = RooAddPdf("model","model",RooArgList(sig_pdf,  bkg_pdf),RooArgList(nsig, nbkg));
    //auto model = RooAddPdf("model","model",RooArgList(CB_pdf,  gaus_pdf),RooArgList(nCB, nGaus));
    RooAddPdf* model;
    RooFitResult * fitResult;
    TPaveText* t1 = new TPaveText(0.15,0.5,0.45,0.8,"brNDC");
    //auto model = RooAddPdf("model","model",RooArgList(CB_pdf,  expo_pdf),RooArgList(nCB, nExp));
    //auto model = RooAddPdf("model","model",RooArgList(CB_pdf,  BW_pdf),RooArgList(nCB, nBW));
    //auto model = RooAddPdf("model","model",RooArgList(CB_pdf),RooArgList(nCB));
    //auto model = RooAddPdf("model","model",RooArgList(cb_pdf,  gaus_pdf),RooArgList(nCB, nGaus));
    //auto model = sig_pdf;
    std::cout<<"Hello"<<std::endl;

    if ( i< 5 ) {
      /*
      model = new RooAddPdf("model","model",RooArgList(BW_pdf),RooArgList(nBW));
      fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second ));
      t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError()));
      */
      model = new RooAddPdf("model","model",RooArgList(BW_pdf, landau_pdf),RooArgList(nBW, nLandau));
      fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second ));
      t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError()));
      t1->AddText(TString::Format("Landau ) Mean : %3.3f(+-%3.3f)", landau_mean.getVal(), landau_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", landau_sigma.getVal(), landau_sigma.getError()));

    }
    if ( i>=5 && i<10 ) {
      model = new RooAddPdf("model","model",RooArgList(BW_pdf, landau_pdf),RooArgList(nBW, nLandau));
      fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second ));
      t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError()));
      t1->AddText(TString::Format("Landau ) Mean : %3.3f(+-%3.3f)", landau_mean.getVal(), landau_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", landau_sigma.getVal(), landau_sigma.getError()));

    }
    if ( i>=10 ) {
      model = new RooAddPdf("model","model",RooArgList(BW_pdf, landau_pdf),RooArgList(nBW, nLandau));
      fitResult = model->fitTo(*dh, RooFit::Extended(true), RooFit::Save(), RooFit::Range( range[i].first, range[i].second ));
      t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError()));
      t1->AddText(TString::Format("Landau ) Mean : %3.3f(+-%3.3f)", landau_mean.getVal(), landau_mean.getError()));
      t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", landau_sigma.getVal(), landau_sigma.getError()));
    }

    //t1->AddText(TString::Format("Breit-Wigner ) Mean : %3.3f(+-%3.3f)", BW_mean.getVal(), BW_mean.getError()));
    //t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)", BW_sigma.getVal(), BW_sigma.getError()));
    //t1->AddText(TString::Format("CrystalBall ) Mean : %3.3f(+-%3.3f)", CB_mean.getVal(), CB_mean.getError()));
    //t1->AddText(TString::Format("#sigma : %0.3f(+-%0.3f)  #alpha : %0.2f ", CB_sigma.getVal(), CB_sigma.getError(), CB_alpha.getVal()));
    t1->Draw();

    RooPlot* top_mass_frame = x.frame();
    dh->plotOn(top_mass_frame);

    model->plotOn(top_mass_frame);
    model->plotOn(top_mass_frame, RooFit::Components(BW_pdf),RooFit::LineStyle(kDashed));
    //model.plotOn(top_mass_frame, RooFit::Components(CB_pdf),RooFit::LineStyle(kDashed));
    //model.plotOn(top_mass_frame, RooFit::Components(gaus_pdf),RooFit::LineColor(kRed), RooFit::LineStyle(kDashed));
    model->plotOn(top_mass_frame, RooFit::Components(landau_pdf),RooFit::LineColor(kRed), RooFit::LineStyle(kDashed));

    TString canvas_name = TString::Format("FitResult_%s",hists[i]->GetName());
    TCanvas* c1 = new TCanvas(canvas_name.Data(),canvas_name.Data(),800,600);
    top_mass_frame->addObject(t1);
    top_mass_frame->Draw();
    top_mass_frame->SetTitle(canvas_name.Data());


    c1->SaveAs( (TString(c1->GetName())+".png").Data());
    c1->SaveAs( (TString("plotCode/")+TString(c1->GetName()).Strip()+".C").Data());
    delete c1;
    delete dh;
  }
}
Beispiel #29
0
void rf403_weightedevts()
{
  // C r e a t e   o b s e r v a b l e   a n d   u n w e i g h t e d   d a t a s e t 
  // -------------------------------------------------------------------------------

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

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

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

 

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

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

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

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

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

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



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

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

  // Fit quadratic polynomial to weighted data

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

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



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

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

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

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



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

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

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

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


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

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

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

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



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

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

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


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


}
void Process(TString fname, TString oldFolder, int toMass, int fromMass)
{




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

  kount = 0;  

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

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

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

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


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



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

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

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

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

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

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


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

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



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

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

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

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

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

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


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

  }


  

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

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


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

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

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


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


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

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


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


}