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

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

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

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

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

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

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

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

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

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

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

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

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

      w->import(modelZ);
      w->import(*modelT);
      w->import(*YieldZ);
      w->import(*YieldT);
      w->import(*YieldTT);
      w->import(*YieldST);
      YieldZ->Print();
      YieldW->Print();
      YieldT->Print();
      YieldTT->Print();
      YieldST->Print();
      counter++;
    }// category loop
	 system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots ] && mkdir %s/plots",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots/bkgTemplates ] && mkdir %s/plots/bkgTemplates",OUTPATH.Data(),OUTPATH.Data()).Data());
	 TString FULLPATH(OUTPATH+"/plots/bkgTemplates");
	 canT->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canZ->GetName()));
	 canT->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canZ->GetName()));
	 delete can;
  }// selection loop
  system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
  system(TString::Format("[ ! -d %s/output ] && mkdir %s/output",OUTPATH.Data(),OUTPATH.Data()).Data());
  w->Print();
  w->writeToFile(TString::Format("%s/output/bkg_shapes_workspace%s.root",OUTPATH.Data(),tMERGE.Data()).Data());
}
示例#2
0
void FitterUtils::generate()
{
   //***************Get the PDFs from the workspace

   TFile fw(workspacename.c_str(), "UPDATE");   
   RooWorkspace* workspace = (RooWorkspace*)fw.Get("workspace");
   RooRealVar *B_plus_M = workspace->var("B_plus_M");
   RooRealVar *misPT = workspace->var("misPT");
   RooRealVar *T = workspace->var("T");
   RooRealVar *n = workspace->var("n");
   RooRealVar *expoConst = workspace->var("expoConst");
   RooRealVar *trueExp = workspace->var("trueExp");
   RooRealVar *fractionalErrorJpsiLeak = workspace->var("fractionalErrorJpsiLeak");

   cout<<"VALUE OF T IN GENERATE: "<<T->getVal()<<" +- "<<T->getError()<<endl;
   cout<<"VALUE OF n IN GENERATE: "<<n->getVal()<<" +- "<<n->getError()<<endl;

   RooHistPdf *histPdfSignalZeroGamma = (RooHistPdf *) workspace->pdf("histPdfSignalZeroGamma");
   RooHistPdf *histPdfSignalOneGamma = (RooHistPdf *) workspace->pdf("histPdfSignalOneGamma");
   RooHistPdf *histPdfSignalTwoGamma = (RooHistPdf *) workspace->pdf("histPdfSignalTwoGamma");
   RooHistPdf *histPdfPartReco = (RooHistPdf *) workspace->pdf("histPdfPartReco");
   RooHistPdf *histPdfJpsiLeak(0);
   if(nGenJpsiLeak>1) histPdfJpsiLeak = (RooHistPdf *) workspace->pdf("histPdfJpsiLeak");


   RooAbsPdf *combPDF;

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

   double trueExpConst(trueExp->getValV());
   expoConst->setVal(trueExpConst);


   //***************Prepare generation

   int nGenSignalZeroGamma(floor(nGenFracZeroGamma*nGenSignal));
   int nGenSignalOneGamma(floor(nGenFracOneGamma*nGenSignal));
   int nGenSignalTwoGamma(floor(nGenSignal-nGenSignalZeroGamma-nGenSignalOneGamma));


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

   cout<<"Preparing the generation of events 1";

   RooRandom::randomGenerator()->SetSeed();
   RooAbsPdf::GenSpec* GenSpecSignalZeroGamma = histPdfSignalZeroGamma->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenSignalZeroGamma)); cout<<" 2 ";
   RooAbsPdf::GenSpec* GenSpecSignalOneGamma = histPdfSignalOneGamma->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenSignalOneGamma)); cout<<" 3 ";
   RooAbsPdf::GenSpec* GenSpecSignalTwoGamma = histPdfSignalTwoGamma->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenSignalTwoGamma)); cout<<" 4 ";
   RooAbsPdf::GenSpec* GenSpecPartReco =  histPdfPartReco->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenPartReco)); cout<<" 5 "<<endl;
   RooAbsPdf::GenSpec* GenSpecComb = combPDF->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenComb));
   RooAbsPdf::GenSpec* GenSpecJpsiLeak(0);
   if(nGenJpsiLeak>1) GenSpecJpsiLeak = histPdfJpsiLeak->prepareMultiGen(argset2, RooFit::Extended(1), NumEvents(nGenJpsiLeak));


   cout<<"Variable loaded:"<<endl;
   B_plus_M->Print(); expoConst->Print(); //B_plus_DTFM_M_zero->Print();
   if (fit2D) misPT->Print(); 


   //***************Generate some datasets

   cout<<"Generating signal Zero Photon"<<endl;
   RooDataSet* dataGenSignalZeroGamma = histPdfSignalZeroGamma->generate(*GenSpecSignalZeroGamma);//(argset, 250, false, true, "", false, true);
   dataGenSignalZeroGamma->SetName("dataGenSignalZeroGamma"); dataGenSignalZeroGamma->SetTitle("dataGenSignalZeroGamma");
   cout<<"Generating signal One Photon"<<endl;
   RooDataSet* dataGenSignalOneGamma = histPdfSignalOneGamma->generate(*GenSpecSignalOneGamma);//(argset, 250, false, true, "", false, true);
   dataGenSignalOneGamma->SetName("dataGenSignalOneGamma"); dataGenSignalOneGamma->SetTitle("dataGenSignalOneGamma");
   cout<<"Generating signal two Photons"<<endl;
   RooDataSet* dataGenSignalTwoGamma = histPdfSignalTwoGamma->generate(*GenSpecSignalTwoGamma);//(argset, 250, false, true, "", false, true);
   dataGenSignalTwoGamma->SetName("dataGenSignalTwoGamma"); dataGenSignalTwoGamma->SetTitle("dataGenSignalTwoGamma");
   cout<<"Generating combinatorial"<<endl;
   RooDataSet* dataGenComb = combPDF->generate(*GenSpecComb);//(argset, 100, false, true, "", false, true);
   dataGenComb->SetName("dataGenComb"); dataGenComb->SetTitle("dataGenComb");
   cout<<"Generating PartReco"<<endl;
   RooDataSet* dataGenPartReco = histPdfPartReco->generate(*GenSpecPartReco);//argset, 160, false, true, "", false, true);
   dataGenPartReco->SetName("dataGenPartReco"); dataGenPartReco->SetTitle("dataGenPartReco");
   RooDataSet* dataGenJpsiLeak(0);
   if(nGenJpsiLeak>1)
   {
      cout<<"Generating Leaking JPsi"<<endl;
      dataGenJpsiLeak = histPdfJpsiLeak->generate(*GenSpecJpsiLeak);//argset, 160, false, true, "", false, true);
      dataGenJpsiLeak->SetName("dataGenJpsiLeak"); dataGenJpsiLeak->SetTitle("dataGenJpsiLeak");
   }

   //*************Saving the generated datasets in a workspace

   RooWorkspace workspaceGen("workspaceGen", "workspaceGen");

   workspaceGen.import(*dataGenSignalZeroGamma);
   workspaceGen.import(*dataGenSignalOneGamma);
   workspaceGen.import(*dataGenSignalTwoGamma);
   workspaceGen.import(*dataGenComb);
   workspaceGen.import(*dataGenPartReco);
   if(nGenJpsiLeak>1) workspaceGen.import(*dataGenJpsiLeak);
    
   
   workspaceGen.Write("", TObject::kOverwrite);


   //delete workspace;
   fw.Close();


   delete dataGenSignalZeroGamma;
   delete dataGenSignalOneGamma;
   delete dataGenSignalTwoGamma;
   delete dataGenComb;
   delete dataGenPartReco;
   if(nGenJpsiLeak>1) delete dataGenJpsiLeak;

   delete GenSpecSignalZeroGamma;
   delete GenSpecSignalOneGamma;
   delete GenSpecSignalTwoGamma;
   delete GenSpecComb;
   delete GenSpecPartReco;
   delete combPDF;
   if(nGenJpsiLeak>1) delete GenSpecJpsiLeak;

   delete histPdfSignalZeroGamma; 
   delete histPdfSignalOneGamma;
   delete histPdfSignalTwoGamma;
   delete histPdfPartReco;
   if(nGenJpsiLeak>1) delete histPdfJpsiLeak;


}
示例#3
0
文件: RA4abcd.C 项目: wa01/usercode
//
// scan over parameter space
//
void RA4Mult (const RA4WorkingPoint& muChannel,
	      const RA4WorkingPoint& eleChannel,
	      StatMethod method) {

  //
  // Prepare workspace
  //   no syst. parameters: efficiency / sig.cont. / kappa
  //
  bool noEffSyst(false);
  bool noSContSyst(false);
  bool noKappaSyst(false);
  RA4WorkSpace ra4WSpace("wspace",noEffSyst,noSContSyst,noKappaSyst);


  TFile* fYield[2];
  TFile* fKFactor[2];
  //
  // Muon channel
  //
  unsigned int nf(0);
  RA4WorkSpace::ChannelType channelTypes[2];
  const RA4WorkingPoint* workingPoints[2];
  addChannel(muChannel,RA4WorkSpace::MuChannel,ra4WSpace,fYield,fKFactor,
	     nf,channelTypes,workingPoints);
  addChannel(eleChannel,RA4WorkSpace::EleChannel,ra4WSpace,fYield,fKFactor,
	     nf,channelTypes,workingPoints);
  if ( nf==0 ) {
    std::cout << "No input file" << std::endl;
    return;
  }
  //
  // finish definition of model
  //
  ra4WSpace.finalize();
  RooWorkspace* wspace = ra4WSpace.workspace();
//   wspace->Print("v");
//   RooArgSet allVars = wspace->allVars();
//   // allVars.printLatex(std::cout,1);
//   TIterator* it = allVars.createIterator();
//   RooRealVar* var;
//   while ( var=(RooRealVar*)it->Next() ) {
//     var->Print("v");
//     var->printValue(std::cout);
//   }
  //
  // preparation of histograms with yields and k-factors
  //
  const char* cRegion = { "ABCD" };
  TH2* hYields[4][2];
  TH2* hYields05[4][2];
  TH2* hYields20[4][2];
  TH2* hYEntries[4][2];
  TH2* hYESmooth[4][2];
  for ( unsigned int j=0; j<nf; ++j ) {
    for ( unsigned int i=0; i<4; ++i ) {
      hYields[i][j] = 0;
      hYields05[i][j] = 0;
      hYields20[i][j] = 0;
      hYEntries[i][j] = 0;
      hYESmooth[i][j] = 0;
    }
  }
  TH2* hKF05[2];
  TH2* hKF10[2];
  TH2* hKF20[2];
  for ( unsigned int j=0; j<nf; ++j ) {
    hKF05[j] = 0;
    hKF10[j] = 0;
    hKF20[j] = 0;
  }
  //
  // Retrieval of histograms with k-factors
  //
  for ( unsigned int j=0; j<nf; ++j ) {
    hKF05[j] = (TH2*)fKFactor[j]->Get("hKF05D");
    hKF10[j] = (TH2*)fKFactor[j]->Get("hKF10D");
    hKF20[j] = (TH2*)fKFactor[j]->Get("hKF20D");
    if ( hKF05[j]==0 || hKF10==0 || hKF20==0 ) {
      std::cout << "Missing histogram for kfactor for channel " << j << std::endl;
      return;
    }
  }
  //
  // Retrieval of histograms with yields
  //
  std::string hName;
  for ( unsigned int j=0; j<nf; ++j ) {
    for ( unsigned int i=0; i<4; ++i ) {
      hName = "Events";
      hName += cRegion[i];

      hYields[i][j] = (TH2*)fYield[j]->Get(hName.c_str())->Clone();
      hYields05[i][j] = (TH2*)fYield[j]->Get(hName.c_str())->Clone();
      hYields20[i][j] = (TH2*)fYield[j]->Get(hName.c_str())->Clone();
      if ( hYields[i][j]==0 ) {
	std::cout << "Missing histogram for region " << cRegion[i] << std::endl;
	return;
      }
      hYields[i][j]->Multiply(hYields[i][j],hKF10[j]);
      hYields05[i][j]->Multiply(hYields05[i][j],hKF05[j]);
      hYields20[i][j]->Multiply(hYields20[i][j],hKF20[j]);

      hName = "Entries";
      hName += cRegion[i];
      hYEntries[i][j] = (TH2*)fYield[j]->Get(hName.c_str());
      if ( hYEntries[i][j]==0 ) {
	std::cout << "Missing histogram for region " << cRegion[i] << std::endl;
	return;
      }
      hName = "SmoothEntries";
      hName += cRegion[i];
      hYESmooth[i][j] = (TH2*)fYield[j]->Get(hName.c_str());
      if ( hYESmooth[i][j]==0 ) {
	std::cout << "Missing histogram for region " << cRegion[i] << std::endl;
	return;
      }
      // convert to efficiency (assume 10000 MC events/bin)
      hYEntries[i][j]->Scale(1/10000.);
      hYESmooth[i][j]->Scale(1/10000.);
      // convert yield to cross section
      hYields[i][j]->Divide(hYields[i][j],hYEntries[i][j]);
      hYields05[i][j]->Divide(hYields05[i][j],hYEntries[i][j]);
      hYields20[i][j]->Divide(hYields20[i][j],hYEntries[i][j]);
    }
  }
  //
  // histograms with exclusion and limits
  //
  gROOT->cd();
  TH2* hExclusion = (TH2*)hYields[0][0]->Clone("Exclusion");
  hExclusion->Reset();
  hExclusion->SetTitle("Exclusion");
  TH2* hLowerLimit = (TH2*)hYields[0][0]->Clone("LowerLimit");
  hLowerLimit->Reset();
  hLowerLimit->SetTitle("LowerLimit");
  TH2* hUpperLimit = (TH2*)hYields[0][0]->Clone("UpperLimit");
  hUpperLimit->Reset();
  hUpperLimit->SetTitle("UpperLimit");

  double yields[4][2];
  double yields05[4][2];
  double yields20[4][2];
  double entries[4][2];

//   double bkgs[4][2];

//   double kappa = (bkgs[0]*bkgs[3])/(bkgs[1]*bkgs[2]);
//   double sigma_kappa_base = 0.10;
//   double delta_kappa_abs = kappa - 1.;
//   double sigma_kappa = sqrt(sigma_kappa_base*sigma_kappa_base+delta_kappa_abs*delta_kappa_abs);
//   sigma_kappa = sqrt(0.129*0.129+0.1*0.1);

#ifndef DEBUG
  int nbx = hYields[0][0]->GetNbinsX();
  int nby = hYields[0][0]->GetNbinsY();
  for ( int ix=1; ix<=nbx; ++ix ) {
    for ( int iy=1; iy<=nby; ++iy ) {
#else
   { 
     int ix=40;
     {
       int iy=11;
#endif

      bool process(false);
      for ( unsigned int j=0; j<nf; ++j ) {
	ra4WSpace.setBackground(channelTypes[j],
				workingPoints[j]->bkg_[0],workingPoints[j]->bkg_[1],
				workingPoints[j]->bkg_[2],workingPoints[j]->bkg_[3]);
	ra4WSpace.setObserved(channelTypes[j],
			      workingPoints[j]->obs_[0],workingPoints[j]->obs_[1],
			      workingPoints[j]->obs_[2],workingPoints[j]->obs_[3]);
	for ( unsigned int i=0; i<4; ++i ) {
	  yields[i][j] = hYields[i][j]->GetBinContent(ix,iy);
	  yields05[i][j] = hYields05[i][j]->GetBinContent(ix,iy);
	  yields20[i][j] = hYields20[i][j]->GetBinContent(ix,iy);
	  entries[i][j] = hYESmooth[i][j]->GetBinContent(ix,iy);
	}
	if ( yields[3][j]>0.01 && yields[3][j]<10000 && entries[3][j]>0.0001 )  process = true;
	ra4WSpace.setSignal(channelTypes[j],
			    yields[0][j],yields[1][j],
			    yields[2][j],yields[3][j],
			    entries[0][j],entries[1][j],
			    entries[2][j],entries[3][j]);
#ifdef DEBUG
	std::cout << "yields for channel " << j << " =";
	for ( unsigned int i=0; i<4; ++i )
	  std::cout << " " << yields[i][j];
	std::cout << endl;
	std::cout << "effs for channel " << j << " =";
	for ( unsigned int i=0; i<4; ++i )
	  std::cout << " " << entries[i][j];
	std::cout << endl;
	std::cout << "backgrounds for channel " << j << " =";
	for ( unsigned int i=0; i<4; ++i )
	  std::cout << " " << workingPoints[j]->bkg_[i];
	std::cout << endl;
#endif
      }

      MyLimit limit(true,0.,999999999.);
      double sumD(0.);
      for ( unsigned int j=0; j<nf; ++j ) {
	sumD += (yields[3][j]*entries[3][j]);
      }
      if ( !process || sumD<0.01 ) {
	hExclusion->SetBinContent(ix,iy,limit.isInInterval);
	hLowerLimit->SetBinContent(ix,iy,limit.lowerLimit);
	hUpperLimit->SetBinContent(ix,iy,limit.upperLimit);
#ifndef DEBUG
	continue;
#endif
      }

      double sigK(0.);
      for ( unsigned int j=0; j<nf; ++j ) {
 	if ( workingPoints[j]->sigKappa_>sigK )
	  sigK = workingPoints[j]->sigKappa_;
// 	  sigK += workingPoints[j]->sigKappa_;
      }
//       sigK /= nf;
      double sigEffBase(0.15);
      double sigEffLept(0.05);
      double sigEffNLO(0.);
      for ( unsigned int j=0; j<nf; ++j ) {
	double sige = max(fabs(yields05[3][j]-yields[3][j]),
			  fabs(yields20[3][j]-yields[3][j]));
	sige /= yields[3][j];
	if ( sige>sigEffNLO )  sigEffNLO = sige;
      }
      double sigEff = sqrt(sigEffBase*sigEffBase+sigEffLept*sigEffLept+sigEffNLO*sigEffNLO);
      std::cout << "Systematics are " << sigK << " " << sigEff << std::endl;
      sigEff = 0.20;
      if ( !noKappaSyst ) 
	wspace->var("sigmaKappa")->setVal(sigK);
      if ( !noSContSyst )
	wspace->var("sigmaScont")->setVal(sigEff);
      if ( !noEffSyst )
	wspace->var("sigmaEff")->setVal(sigEff);
      
//       wspace->var("sigmaKappa")->setVal(sqrt(0.129*0.129+0.1*0.1)*0.967);
      // for the time being: work with yields
//       if ( muChannel.valid_ ) {
// 	wspace->var("effM")->setVal(1.);
//  	wspace->var("sadM")->setVal(0.);
//  	wspace->var("sbdM")->setVal(0.);
//  	wspace->var("scdM")->setVal(0.);
//       }
//       if ( eleChannel.valid_ ) {
// 	wspace->var("effE")->setVal(1.);
//  	wspace->var("sadE")->setVal(0.);
//  	wspace->var("sbdE")->setVal(0.);
//  	wspace->var("scdE")->setVal(0.);
//       }
#ifdef DEBUG
      wspace->Print("v");
      RooArgSet allVars = wspace->allVars();
      // allVars.printLatex(std::cout,1);
      TIterator* it = allVars.createIterator();
      RooRealVar* var;
      while ( var=(RooRealVar*)it->Next() ) {
	var->Print("v");
	var->printValue(std::cout);
	std::cout << std::endl;
      }
#endif
      std::cout << "Checked ( " << hExclusion->GetXaxis()->GetBinCenter(ix) << " , "
		<< hExclusion->GetYaxis()->GetBinCenter(iy) << " ) with signal " 
		<< yields[3][nf-1] << std::endl;
	

      RooDataSet data("data","data",*wspace->set("obs"));
      data.add(*wspace->set("obs"));
      data.Print("v");
      
      limit = computeLimit(wspace,&data,method);
      std::cout << "  Limit [ " << limit.lowerLimit << " , "
		<< limit.upperLimit << " ] ; isIn = " << limit.isInInterval << std::endl;
      

      double excl = limit.isInInterval;
      if ( limit.upperLimit<limit.lowerLimit )  excl = -1;
      hExclusion->SetBinContent(ix,iy,excl);
      hLowerLimit->SetBinContent(ix,iy,limit.lowerLimit);
      hUpperLimit->SetBinContent(ix,iy,limit.upperLimit);
//       return;
      
    }
  }
  
  TFile* out = new TFile("RA4abcd.root","RECREATE");
  hExclusion->SetDirectory(out);
  hExclusion->SetMinimum(); hExclusion->SetMaximum();
  hExclusion->SetContour(1); hExclusion->SetContourLevel(0,0.5);
  hLowerLimit->SetDirectory(out);
  hLowerLimit->SetMinimum(); hLowerLimit->SetMaximum();
  hUpperLimit->SetDirectory(out);
  hUpperLimit->SetMinimum(); hUpperLimit->SetMaximum();
  for ( unsigned int j=0; j<nf; ++j ) {
    hYields[3][j]->SetDirectory(out);
    hYields[3][j]->SetMinimum(); hYields[3][j]->SetMaximum();
  }
  out->Write();
  delete out;
}
void StandardHistFactoryPlotsWithCategories(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData"){


   double nSigmaToVary=5.;
   double muVal=0;
   bool doFit=false;

   // -------------------------------------------------------
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
                                                           // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }

   // -------------------------------------------------------
   // Tutorial starts here
   // -------------------------------------------------------

   // get the workspace out of the file
   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
   if(!w){
      cout <<"workspace not found" << endl;
      return;
   }

   // get the modelConfig out of the file
   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

   // get the modelConfig out of the file
   RooAbsData* data = w->data(dataName);

   // make sure ingredients are found
   if(!data || !mc){
      w->Print();
      cout << "data or ModelConfig was not found" <<endl;
      return;
   }

   // -------------------------------------------------------
   // now use the profile inspector

   RooRealVar* obs = (RooRealVar*)mc->GetObservables()->first();
   TList* list = new TList();


   RooRealVar * firstPOI = dynamic_cast<RooRealVar*>(mc->GetParametersOfInterest()->first());

   firstPOI->setVal(muVal);
   //  firstPOI->setConstant();
   if(doFit){
      mc->GetPdf()->fitTo(*data);
   }

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


   mc->GetNuisanceParameters()->Print("v");
   int  nPlotsMax = 1000;
   cout <<" check expectedData by category"<<endl;
   RooDataSet* simData=NULL;
   RooSimultaneous* simPdf = NULL;
   if(strcmp(mc->GetPdf()->ClassName(),"RooSimultaneous")==0){
      cout <<"Is a simultaneous PDF"<<endl;
      simPdf = (RooSimultaneous *)(mc->GetPdf());
   } else {
      cout <<"Is not a simultaneous PDF"<<endl;
   }



   if(doFit) {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      tt=(RooCatType*) iter->Next();
      RooAbsPdf* pdftmp = ((RooSimultaneous*)mc->GetPdf())->getPdf(tt->GetName()) ;
      RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
      obs = ((RooRealVar*)obstmp->first());
      RooPlot* frame = obs->frame();
      cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
      cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
      data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

      Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

      pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;
      frame->Draw();
      cout <<"expected events = " << mc->GetPdf()->expectedEvents(*data->get()) <<endl;
      return;
   }



   int nPlots=0;
   if(!simPdf){

      TIterator* it = mc->GetNuisanceParameters()->createIterator();
      RooRealVar* var = NULL;
      while( (var = (RooRealVar*) it->Next()) != NULL){
         RooPlot* frame = obs->frame();
         frame->SetYTitle(var->GetName());
         data->plotOn(frame,MarkerSize(1));
         var->setVal(0);
         mc->GetPdf()->plotOn(frame,LineWidth(1.));
         var->setVal(1);
         mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(1));
         var->setVal(-1);
         mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(1));
         list->Add(frame);
         var->setVal(0);
      }


   } else {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      //    TIterator* iter = simPdf->indexCat().typeIterator() ;
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      while(nPlots<nPlotsMax && (tt=(RooCatType*) iter->Next())) {

         cout << "on type " << tt->GetName() << " " << endl;
         // Get pdf associated with state from simpdf
         RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

         // Generate observables defined by the pdf associated with this state
         RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
         //      obstmp->Print();


         obs = ((RooRealVar*)obstmp->first());

         TIterator* it = mc->GetNuisanceParameters()->createIterator();
         RooRealVar* var = NULL;
         while(nPlots<nPlotsMax && (var = (RooRealVar*) it->Next())){
            TCanvas* c2 = new TCanvas("c2");
            RooPlot* frame = obs->frame();
            frame->SetName(Form("frame%d",nPlots));
            frame->SetYTitle(var->GetName());

            cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
            cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
            data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

            Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }
            // w->allVars().Print("v");
            // mc->GetNuisanceParameters()->Print("v");
            // pdftmp->plotOn(frame,LineWidth(2.));
            // mc->GetPdf()->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()+0.05);
               var->Print();
            } else{
               var->setVal(nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kRed),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()-0.05);
               var->Print();
            } else{
               var->setVal(-nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kGreen),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;



            // set them back to normal
            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }

            list->Add(frame);

            // quit making plots
            ++nPlots;

            frame->Draw();
            c2->SaveAs(Form("%s_%s_%s.pdf",tt->GetName(),obs->GetName(),var->GetName()));
            delete c2;
         }
      }
   }



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


   // now make plots
   TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
   if(list->GetSize()>4){
      double n = list->GetSize();
      int nx = (int)sqrt(n) ;
      int ny = TMath::CeilNint(n/nx);
      nx = TMath::CeilNint( sqrt(n) );
      c1->Divide(ny,nx);
   } else
      c1->Divide(list->GetSize());
   for(int i=0; i<list->GetSize(); ++i){
      c1->cd(i+1);
      list->At(i)->Draw();
   }





}