// Combinatorial PDFs
void makeCombinatorialPdf( RooWorkspace *w ) {
  // one in each cat
  RooCategory *cat = (RooCategory*)w->cat("DataCat");
  for ( int i=0; i < cat->numTypes(); i++ ) {
    cat->setIndex(i);
    w->factory( Form("Exponential::bkg_pdf_%s( B_s0_DTF_B_s0_M, bkg_exp_p1_%s[-0.002,-0.005,0.] )", cat->getLabel(), cat->getLabel() ) );
    defineParamSet( w, Form("bkg_pdf_%s",cat->getLabel()) );
  }
}
void rs602_HLFactoryCombinationexample() {

   using namespace RooStats;
   using namespace RooFit;

   // create a card
   TString card_name("HLFavtoryCombinationexample.rs");
   ofstream ofile(card_name);
   ofile << "// The simplest card for combination\n\n"
         << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n"
         << "flat1 = Polynomial(x,0);\n"
         << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n"
         << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n"
         << "flat2 = Polynomial(x,0);\n"
         << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n";

   ofile.close();

   HLFactory hlf("HLFavtoryCombinationexample",
               card_name,
               false);

   hlf.AddChannel("model1","sb_model1","flat1");
   hlf.AddChannel("model2","sb_model2","flat2");
   RooAbsPdf* pdf=hlf.GetTotSigBkgPdf();
   RooCategory* thecat = hlf.GetTotCategory();
   RooRealVar* x= static_cast<RooRealVar*>(hlf.GetWs()->arg("x"));

   RooDataSet* data = pdf->generate(RooArgSet(*x,*thecat),Extended());

   // --- Perform extended ML fit of composite PDF to toy data ---
   pdf->fitTo(*data) ;

   // --- Plot toy data and composite PDF overlaid ---
   RooPlot* xframe = x->frame() ;

   data->plotOn(xframe);
   thecat->setIndex(0);
   pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

   thecat->setIndex(1);
   pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

   gROOT->SetStyle("Plain");
   xframe->Draw();
}
Exemple #3
0
void splitws(string inFolderName, double mass, string channel) {
  cout << "Splitting workspace in " << channel << endl;

  int flatInterpCode = 4;
  int shapeInterpCode = 4;

  bool do2011 = 0;

  if (inFolderName.find("2011") != string::npos) do2011 = 1;

  bool conditionalAsimov = 0;
  bool doData = 1;
  //if (inFolderName.find("_blind_") != string::npos) {
    //conditionalAsimov = 0;
  //}
  //else {
    //conditionalAsimov = 1;
  //}

  set<string> channelNames;

  if (channel == "01j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "0j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "1j") {
    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF01j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF0j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF1j") {
    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF01j") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF0j") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF1j") {
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "2j") {
    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF2j") {
    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF2j") {
    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));

    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else {
    cout << "Channel " << channel << " not defined. Please check!" << endl;
    exit(1);
  }

  // bool fix = 1;
  stringstream inFileName;

  inFileName << "workspaces/" << inFolderName << "/" << mass << ".root";
  TFile f(inFileName.str().c_str());
  
  RooWorkspace* w = (RooWorkspace*)f.Get("combWS");
  if (!w) w = (RooWorkspace*)f.Get("combined");
  
  RooDataSet* data = (RooDataSet*)w->data("combData");
  if (!data) data = (RooDataSet*)w->data("obsData");
  
  ModelConfig* mc = (ModelConfig*)w->obj("ModelConfig");
  
  RooRealVar* weightVar = w->var("weightVar");
  
  RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();
  if (!mu) mu = w->var("SigXsecOverSM");

  const RooArgSet* mc_obs = mc->GetObservables();
  const RooArgSet* mc_nuis = mc->GetNuisanceParameters();
  const RooArgSet* mc_globs = mc->GetGlobalObservables();
  const RooArgSet* mc_poi = mc->GetParametersOfInterest();

  RooArgSet nuis = *mc_nuis;
  RooArgSet antiNuis = *mc_nuis;

  RooArgSet globs = *mc_globs;
  RooArgSet antiGlobs = *mc_globs;

  RooArgSet allParams;

  RooSimultaneous* simPdf = (RooSimultaneous*)mc->GetPdf();
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();

  RooArgSet nuis_tmp = nuis;
  RooArgSet fullConstraints = *simPdf->getAllConstraints(*mc_obs,nuis_tmp,false);

  vector<string> foundChannels;
  vector<string> skippedChannels;  

  cout << "Getting constraints" << endl;
  map<string, RooDataSet*> data_map;
  map<string, RooAbsPdf*> pdf_map;
  RooCategory* decCat = new RooCategory("dec_channel","dec_channel");
  // int i = 0;
  TIterator* catItr = cat->typeIterator();
  RooCatType* type;
  RooArgSet allConstraints;
  while ((type = (RooCatType*)catItr->Next())) {
    RooAbsPdf* pdf =  simPdf->getPdf(type->GetName());

    string typeName(type->GetName());
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end())  {
      skippedChannels.push_back(typeName);
      continue;
    }
    cout << "On channel " << type->GetName() << endl;
    foundChannels.push_back(typeName);

    decCat->defineType(type->GetName());
    // pdf->getParameters(*data)->Print("v");

    RooArgSet nuis_tmp1 = nuis;
    RooArgSet nuis_tmp2 = nuis;
    RooArgSet* constraints = pdf->getAllConstraints(*mc_obs, nuis_tmp1, true);
    constraints->Print();
    allConstraints.add(*constraints);
  }

  catItr->Reset();

  while ((type = (RooCatType*)catItr->Next())) {
    RooAbsPdf* pdf =  simPdf->getPdf(type->GetName());

    string typeName(type->GetName());
    cout << "Considering type " << typeName << endl;
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end()) continue;
    cout << "On channel " << type->GetName() << endl;

    RooArgSet nuis_tmp1 = nuis;
    RooArgSet nuis_tmp2 = nuis;
    RooArgSet* constraints = pdf->getAllConstraints(*mc_obs, nuis_tmp1, true);

    cout << "Adding pdf to map: " << typeName << " = " << pdf->GetName() << endl;
    pdf_map[typeName] = pdf;

    RooProdPdf prod("prod","prod",*constraints);

    RooArgSet* params = pdf->getParameters(*data);
    antiNuis.remove(*params);
    antiGlobs.remove(*params);

    allParams.add(*params);
    // cout << type->GetName() << endl;
  }
  // return;

  RooArgSet decNuis;
  TIterator* nuiItr = mc_nuis->createIterator();
  TIterator* parItr = allParams.createIterator();
  RooAbsArg* nui, *par;
  while ((par = (RooAbsArg*)parItr->Next())) {
    nuiItr->Reset();
    while ((nui = (RooAbsArg*)nuiItr->Next())) {
      if (par == nui) decNuis.add(*nui);
    }
  }

  RooArgSet decGlobs;
  TIterator* globItr = mc_globs->createIterator();
  parItr->Reset();
  RooAbsArg* glob;
  while ((par = (RooAbsArg*)parItr->Next())) {
    globItr->Reset();
    while ((glob = (RooAbsArg*)globItr->Next())) {
      if (par == glob) decGlobs.add(*glob);
    }
  }

  // antiNuis.Print();

  // nuis.Print();
  // globs.Print();

  // i = 0;
  TList* datalist = data->split(*cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  while ((ds = (RooAbsData*)dataItr->Next())) {
    string typeName(ds->GetName());
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end()) continue;

    cout << "Adding dataset to map: " << ds->GetName() << endl;
    data_map[string(ds->GetName())] = (RooDataSet*)ds;

    cout << ds->GetName() << endl;
  }

  RooSimultaneous* decPdf = new RooSimultaneous("decPdf","decPdf",pdf_map,*decCat); 
  RooArgSet decObs = *decPdf->getObservables(data);
  // decObs.add(*(RooAbsArg*)weightVar);
  decObs.add(*(RooAbsArg*)decCat);
  decObs.Print();

  nuis.remove(antiNuis);
  globs.remove(antiGlobs);
  // nuis.Print("v");

  RooDataSet* decData = new RooDataSet("obsData","obsData",RooArgSet(decObs,*(RooAbsArg*)weightVar),Index(*decCat),Import(data_map),WeightVar(*weightVar));

  decData->Print();

  RooArgSet poi(*(RooAbsArg*)mu);
  RooWorkspace decWS("combined");
  ModelConfig decMC("ModelConfig",&decWS);
  decMC.SetPdf(*decPdf);
  decMC.SetObservables(decObs);
  decMC.SetNuisanceParameters(decNuis);
  decMC.SetGlobalObservables(decGlobs);
  decMC.SetParametersOfInterest(poi);

  decMC.Print();
  decWS.import(*decPdf);
  decWS.import(decMC);
  decWS.import(*decData);
  // decWS.Print();

  ModelConfig* mcInWs = (ModelConfig*)decWS.obj("ModelConfig");
  decPdf = (RooSimultaneous*)mcInWs->GetPdf();

  // setup(mcInWs);
  // return;

  mcInWs->GetNuisanceParameters()->Print("v");
  mcInWs->GetGlobalObservables()->Print("v");
  // decData->tree()->Scan("*");

  // Make asimov data
  RooArgSet funcs = decWS.allFunctions();
  TIterator* it = funcs.createIterator();
  TObject* tempObj = 0;
  while((tempObj=it->Next()))
  {
    FlexibleInterpVar* flex = dynamic_cast<FlexibleInterpVar*>(tempObj);
    if(flex) {
      flex->setAllInterpCodes(flatInterpCode);
    }
    PiecewiseInterpolation* piece = dynamic_cast<PiecewiseInterpolation*>(tempObj);
    if(piece) {
      piece->setAllInterpCodes(shapeInterpCode);
    }
  }

  RooDataSet* dataInWs = (RooDataSet*)decWS.data("obsData");
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 0);
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 1);
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 2);

  system(("mkdir -vp workspaces/"+inFolderName+"_"+channel).c_str());
  stringstream outFileName;
  outFileName << "workspaces/" << inFolderName << "_" << channel << "/" << mass << ".root";
  cout << "Exporting" << endl;

  decWS.writeToFile(outFileName.str().c_str());

  cout << "\nIncluded the following channels: " << endl;
  for (int i=0;i<(int)foundChannels.size();i++) {
    cout << "-> " << foundChannels[i] << endl;
  }

  cout << "\nSkipping the following channels: " << endl;
  
  for (int i=0;i<(int)skippedChannels.size();i++) {
    cout << "-> " << skippedChannels[i] << endl;
  }

  cout << "Done" << endl;

  // decPdf->fitTo(*decData, Hesse(0), Minos(0), PrintLevel(0));
}
Exemple #4
0
int main(int argc, char **argv)
{
	bool printSw = true;
	//TString massModel = "Gauss-m[5622]";
	string massModel = "DCB-m[5622]";
	TString effbase = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/results/";
	bool printeff = false;
	TString dodata = "data";
	bool fitsingle = false;
	TString wstr = "physRate_polp006";
	TString decayToDo = "Lb2Lmumu";
	if(dodata=="genMC") wstr += "_noDecay";

	gROOT->ProcessLine(".x lhcbStyle.C");


	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * nsig_sw = new RooRealVar("nsig_sw","nsig_sw",1,-1.e6,1.e6);
	RooRealVar * MCweight = new RooRealVar(wstr,wstr,1.,-1.e10,1.e10);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5620.,5500.,5900.);
	TString datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb.root";
	if(dodata=="MC") datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb_MC.root";
	if(dodata=="genMC") datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/"+(string)decayToDo+"_geomMC_Pythia8_NBweighted.root";
	TreeReader * data;
	if(dodata!="genMC") data = new TreeReader("cand"+decayToDo);
	else data = new TreeReader("MCtree");
	data->AddFile(datafilename);

	TFile * histFile = new TFile("Afb_hist.root","recreate");

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

	int nbins = 1;//CutsDef::nq2bins;
	double q2min[] = {15.,11.0,15,16,18};//&CutsDef::q2min_highfirst[0];
	double q2max[] = {20.,12.5,16,18,20};//&CutsDef::q2max_highfirst[0];
	
	//int nbins = CutsDef::nq2bins
	//double *q2min = &CutsDef::q2min[0];
	//double *q2max = &CutsDef::q2max[0];


	TGraphErrors * Afb_vs_q2 = new TGraphErrors();
	TGraphErrors * AfbB_vs_q2 = new TGraphErrors();
	TGraphErrors * fL_vs_q2 = new TGraphErrors();
	TCanvas * ceff = new TCanvas();

	RooCategory * samples = new RooCategory("samples","samples");
	samples->defineType("DD");
	samples->defineType("LL");

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-100,100);
	RooRealVar * fL = new RooRealVar("fL","fL",0.7,-1.,10.);
	//RooRealVar * afb = new RooRealVar("afb","afb",0.,-1.,1.);
	//RooRealVar * fL = new RooRealVar("fL","fL",0.7,0.,1.);
	RooRealVar * origafb = new RooRealVar("afb","afb",0.,-1.,1.);
	RooRealVar * origfL = new RooRealVar("fL","fL",0.7,-1.,10.);
	TString afbLpdf = "((3./8.)*(1.-fL)*(1 + TMath::Power(cosThetaL,2)) + afb*cosThetaL + (3./4.)*fL*(1 - TMath::Power(cosThetaL,2)))";
	RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-100,100);
	//RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	RooRealVar * origafbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";

	vector< vector< double > > afb_errs, afbB_errs, fL_errs;
	TList * LLlist = new TList, * DDlist = new TList;

	TCanvas * cDD = new TCanvas();
	TCanvas * cLL = new TCanvas();
	TCanvas * cDDB = new TCanvas();
	TCanvas * cLLB = new TCanvas();

	for(int i = 0; i < nbins; i++)
	{
		//if(q2min[i] < 8) continue;
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e",q2min[i],q2max[i]);	
		//TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e && (Lb_MassConsLambda > 5680 || Lb_MassConsLambda < 5590)",q2min[i],q2max[i]); 
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		TFile * effFile = NULL;
		TH1F * effDD = NULL, * effLL = NULL, * effLLB = NULL, * effDDB = NULL;
		if(q2min[i] == 15 && q2max[i] == 20)
		{
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_DD.root");
			effDD  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_LL.root");
			effLL  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_DD.root");
			effDDB  = (TH1F *)effFile->Get("htot_nodet_eff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_LL.root");
			effLLB  = (TH1F *)effFile->Get("htot_nodet_eff");
		}
		else
		{

			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_DD.root");
			TH2F * effDD2D  = (TH2F *)effFile->Get("htot_eff");
			effDD = (TH1F*)GetSliceX(effDD2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_LL.root");
			TH2F * effLL2D  = (TH2F *)effFile->Get("htot_eff");
			effLL = (TH1F*)GetSliceX(effLL2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_DD.root");
			TH2F * effDDB2D  = (TH2F *)effFile->Get("hupper_eff");
			effDDB = (TH1F*)GetSliceX(effDDB2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_LL.root");
			TH2F * effLLB2D  = (TH2F *)effFile->Get("hupper_eff");
			effLLB = (TH1F*)GetSliceX(effLLB2D,(q2max[i]+q2min[i])/2.);
		}

		ceff->cd();

		/**                    FIT EFFICIENCY                  **/

		RooDataHist * hLL = new RooDataHist("hLL","hLL",*cosThetaL,effLL);
		RooDataHist * hDD = new RooDataHist("hDD","hDD",*cosThetaL,effDD);
		RooRealVar * c1LL = new RooRealVar("c1LL","",0.,-1.,1);
		RooRealVar * c1DD = new RooRealVar("c1DD","",0.,-1.,1);
		RooRealVar * c2LL = new RooRealVar("c2LL","",0.,-1.,1);
		RooRealVar * c2DD = new RooRealVar("c2DD","",0.,-1.,1);
		TString effLLstr = "(1 + c1LL*cosThetaL + c2LL*TMath::Power(cosThetaL,2))";
		TString effDDstr = "(1 + c1DD*cosThetaL + c2DD*TMath::Power(cosThetaL,2))";
		RooAbsPdf * effLLpdf = new RooGenericPdf("effLLpdf", "", effLLstr, RooArgSet(*cosThetaL, *c1LL, *c2LL));
		RooAbsPdf * effDDpdf = new RooGenericPdf("effDDpdf", "", effDDstr, RooArgSet(*cosThetaL, *c1DD, *c2DD));
		effLLpdf->fitTo(*hLL,PrintLevel(-1));
		effDDpdf->fitTo(*hDD,PrintLevel(-1));
		fixParams(effLLpdf,cosThetaL);
		fixParams(effDDpdf,cosThetaL);	

		RooDataHist * hLLB = new RooDataHist("hLLB","hLLB",*cosThetaB,effLLB);
		RooDataHist * hDDB = new RooDataHist("hDDB","hDDB",*cosThetaB,effDDB);
		RooRealVar * cB1LL = new RooRealVar("cB1LL","",0,-1.,1);
		RooRealVar * cB1DD = new RooRealVar("cB1DD","",0,-1.,1);
		RooRealVar * cB2LL = new RooRealVar("cB2LL","",0,-1.,1);
		RooRealVar * cB2DD = new RooRealVar("cB2DD","",0,-1.,1);
		TString effLLBstr = "(1 + cB1LL*cosThetaB + cB2LL*TMath::Power(cosThetaB,2))";
		TString effDDBstr = "(1 + cB1DD*cosThetaB + cB2DD*TMath::Power(cosThetaB,2))";
		RooAbsPdf * effLLpdfB = new RooGenericPdf("effLLpdfB", "", effLLBstr, RooArgSet(*cosThetaB, *cB1LL, *cB2LL));
		RooAbsPdf * effDDpdfB = new RooGenericPdf("effDDpdfB", "", effDDBstr, RooArgSet(*cosThetaB, *cB1DD, *cB2DD));
		effLLpdfB->fitTo(*hLLB,PrintLevel(-1));
		effDDpdfB->fitTo(*hDDB,PrintLevel(-1));
		fixParams(effLLpdfB,cosThetaB);
		fixParams(effDDpdfB,cosThetaB);

		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaL -> " << c1LL->getVal() << "  " << c2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaL -> " << c1DD->getVal() << "  " << c2DD->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaB -> " << cB1LL->getVal() << "  " << cB2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaB -> " << cB1DD->getVal() << "  " << cB2DD->getVal() << endl;


		if(printeff) {
			GetFrame(cosThetaL, hLL,effLLpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("DDeffFit"+q2name+".pdf");
			GetFrame(cosThetaL, hDD,effDDpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("LLeffFit"+q2name+".pdf");
			GetFrame(cosThetaB, hLLB,effLLpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("DDeffFitB"+q2name+".pdf");
			GetFrame(cosThetaB, hDDB,effDDpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("LLeffFitB"+q2name+".pdf"); }

			/**                    FIT AFB                  **/


			afb->setVal(0);
			afbB->setVal(0);
			fL->setVal(0.7);

			TString LLnorm = "1./( 1. + (2./3.)*afb*c1LL + (2./5.)*c2LL - (1./5.)*c2LL*fL )*"+effLLstr;
			TString DDnorm = "1./( 1. + (2./3.)*afb*c1DD + (2./5.)*c2DD - (1./5.)*c2DD*fL )*"+effDDstr;
			RooAbsPdf * corrPdfLL = new RooGenericPdf(Form("corrPdfLL_%i",i),LLnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
			RooAbsPdf * corrPdfDD = new RooGenericPdf(Form("corrPdfDD_%i",i),DDnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );

			TString LLnormB = "1./( (2./3.)*( 2*afbB*cB1LL + cB2LL + 3.) )*"+effLLBstr;
			TString DDnormB = "1./( (2./3.)*( 2*afbB*cB1DD + cB2DD + 3.) )*"+effDDBstr;
			RooAbsPdf * corrPdfLLB = new RooGenericPdf(Form("corrPdfLLB_%i",i),LLnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
			RooAbsPdf * corrPdfDDB = new RooGenericPdf(Form("corrPdfDDB_%i",i),DDnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );

			TCut cutLL = CutsDef::LLcut + (TCut)curq2cut;
			TCut cutDD = CutsDef::DDcut + (TCut)curq2cut;

			if(dodata=="genMC")
			{
				corrPdfLLB = new RooGenericPdf("corrPdfLL",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
				corrPdfDDB = new RooGenericPdf("corrPdfDD",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );
				corrPdfLL = new RooGenericPdf("corrPdfLL",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
				corrPdfDD = new RooGenericPdf("corrPdfDD",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );
				cutLL = (TCut)curq2cut;
				cutDD = (TCut)curq2cut;
			}

			Analysis * anaLL = new Analysis(Form("LL_mass_%i",i),"Lb",data,&cutLL,MM);
			anaLL->AddVariable(cosThetaL);
			anaLL->AddVariable(cosThetaB);
			anaLL->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaLL->SetWeight(wstr);
			RooDataSet * dataLL = anaLL->GetDataSet("-recalc-docuts");

			Analysis * anaDD = new Analysis(Form("DD_mass_%i",i),"Lb",data,&cutDD,MM);
			anaDD->AddVariable(cosThetaL);
			anaDD->AddVariable(cosThetaB);
			anaDD->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaDD->SetWeight(wstr);
			RooDataSet * dataDD = anaDD->GetDataSet("-recalc-docuts");

			RooDataSet * sdataDD, * sdataLL;

			if(dodata=="data")
			{
				sdataLL = anaLL->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataLL,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_"+q2name+".pdf");
				}

				sdataDD = anaDD->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataDD,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_"+q2name+".pdf");
				}
			}		
			else { sdataLL = dataLL; sdataDD = dataDD; }

			histFile->cd();
			TTree * LLTree = (TTree*)sdataLL->tree();
			LLTree->SetName(Form("treeLL_%i",i));
			LLlist->Add(LLTree);
			TTree * DDTree = (TTree*)sdataDD->tree();
			DDTree->SetName(Form("treeDD_%i",i));
			DDlist->Add(DDTree);


			// CREATE COMBINED DATASET
			RooDataSet * combData;
			if(dodata=="data") combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*nsig_sw),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar("nsig_sw"));
			else combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*MCweight),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar(wstr));


			// FIT COS LEPTON
			RooSimultaneous * combModel = new RooSimultaneous(Form("combModel_%i",i),"",*samples);
			combModel->addPdf(*corrPdfLL,"LL");
			combModel->addPdf(*corrPdfDD,"DD");

			combModel->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLL->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaL,corrPdfLL,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDD->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaL,corrPdfDD,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_DD_"+q2name+".pdf");

			Afb_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afb->getVal());
			Afb_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afb->getError());
			fL_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,fL->getVal());
			fL_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,fL->getError());
				
			// FIT COS HADRON
			RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
			combModelB->addPdf(*corrPdfLLB,"LL");
			combModelB->addPdf(*corrPdfDDB,"DD");

			combModelB->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLLB->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaB,corrPdfLLB,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDDB->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaB,corrPdfDDB,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_DD_"+q2name+".pdf");

			AfbB_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afbB->getVal());
			AfbB_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afbB->getError());
			
			cout << endl << fixed << setprecision(6) << "AfbB = " << afbB->getVal() << " +/- " << afbB->getError() << endl;
			cout << "Afb = " << afb->getVal() << " +/- " << afb->getError() << endl;
			cout << "fL = " << fL->getVal() << " +/- " << fL->getError() << endl;
			cout << endl;
			cout << "------------------------ FELDMAN AND COUSINS ------------------------" << endl;

			vector < RooDataSet * > datas;
			vector < RooAbsPdf * > pdfs, pdfsB;
			vector < TString > cat;
			cat.push_back("LL");
			cat.push_back("DD");
			datas.push_back(sdataLL);
			datas.push_back(sdataDD);

			RooArgSet * origPars = new RooArgSet();
			origPars->add(*origafb);
			origPars->add(*origfL);
			
			pdfs.push_back(corrPdfLL);
			pdfs.push_back(corrPdfDD);

			vector< double > afb_err, afbB_err, fL_err;
/*
			double fLval = fL->getVal(), fLerr = fL->getError();
			FeldmanCousins * FC = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,afb,"nsig_sw");
			//FC->SetNPointsToScan(20);
			//FC->SetNExp(1000);
			if(q2min[i]==18) afb_err = FC->ExtractLimits(origPars,-0.3,0.3);
			else if( (afb->getVal()-1.4*afb->getError()) > -1 && (afb->getVal()+1.4*afb->getError()) < 1 )
		       afb_err = FC->ExtractLimits(origPars,afb->getVal()-1.4*afb->getError(),afb->getVal()+1.4*afb->getError());
		    else afb_err = FC->ExtractLimits(origPars,-0.4,0.4);

			//FeldmanCousins * FCfL = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,fL,"nsig_sw");
			//if(q2min[i]==11) fL_err = FCfL->ExtractLimits(origPars,0.,0.6);
			//else if (q2min[i]==18) fL_err = FCfL->ExtractLimits(origPars,0.75,0.992);
			//( (fLval-1.3*fLerr) > 0 && (fLval+1.3*fLerr) <= 1 )
			//else fL_err = FCfL->ExtractLimits(origPars,fLval-1.3*fLerr,fLval+1.3*fLerr);

			afb_errs.push_back(afb_err);
			//fL_errs.push_back(fL_err);

 			RooArgSet * origParsB = new RooArgSet();
			origParsB->add(*origafbB);
			pdfsB.push_back(corrPdfLLB);
			pdfsB.push_back(corrPdfDDB);

			FeldmanCousins * FCB = new FeldmanCousins(q2name,cat,datas,pdfsB,cosThetaB,afbB,"nsig_sw");
			if( (afbB->getVal()-1.5*afbB->getError()) > -1 && (afbB->getVal()+1.5*afbB->getError()) < 1 )
			   afbB_err = FCB->ExtractLimits(origParsB,afbB->getVal()-1.5*afbB->getError(),afbB->getVal()+1.5*afbB->getError());
			else afbB_err = FCB->ExtractLimits(origParsB,-0.4,0.4);

			afbB_errs.push_back(afbB_err);
*/
			delete effDD;
			delete effLL;
			delete effLLB;
			delete effDDB;
	}

	cDD->Print("DDeff.pdf");
	cLL->Print("LLeff.pdf");
	cDDB->Print("DDBeff.pdf");
	cLLB->Print("LLBeff.pdf");


	Afb_vs_q2->GetXaxis()->SetTitle("q^{2}");
	Afb_vs_q2->GetYaxis()->SetTitle("Afb");
	Afb_vs_q2->SetMaximum(1);
	Afb_vs_q2->SetMinimum(-1);
	Afb_vs_q2->Draw("AP");
	ceff->Print("Afb_vs_q2.pdf");
	AfbB_vs_q2->GetXaxis()->SetTitle("q^{2}");
	AfbB_vs_q2->GetYaxis()->SetTitle("AfbB");
	AfbB_vs_q2->SetMaximum(1);
	AfbB_vs_q2->SetMinimum(-1);
	AfbB_vs_q2->Draw("AP");
	ceff->Print("AfbB_vs_q2.pdf");
	fL_vs_q2->GetXaxis()->SetTitle("q^{2}");
	fL_vs_q2->GetYaxis()->SetTitle("fL");
	fL_vs_q2->Draw("AP");
	ceff->Print("fL_vs_q2.pdf");

	for(int bb = 0; bb < Afb_vs_q2->GetN(); bb++)
	{
		double qq, qqerr, afbv, afbBv, fLv;
		Afb_vs_q2->GetPoint(bb,qq,afbv);
		qqerr = Afb_vs_q2->GetErrorX(bb);
		AfbB_vs_q2->GetPoint(bb,qq,afbBv);
		fL_vs_q2->GetPoint(bb,qq,fLv);
		cout << fixed << setprecision(1) << qq-qqerr << " - " << qq+qqerr;
		cout << fixed << setprecision(4); 
		//cout << " & $" << afbv << "_{-" << TMath::Abs(afb_errs[bb][0] - afbv) << "}^{+" << TMath::Abs(afb_errs[bb][1] - afbv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		//cout << " & $" << afbBv << "_{-" << TMath::Abs(afbB_errs[bb][0] - afbBv) << "}^{+" << TMath::Abs(afbB_errs[bb][1]-afbBv) << "} \\text{(stat)} \\pm \\text{(sys)}$ " ;
		//cout << " & $" << fLv << "_{-" << TMath::Abs(fL_errs[bb][0] - fLv) << "}^{+" << TMath::Abs(fL_errs[bb][1] - fLv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		cout << "  \\\\ " << endl;
	}

	histFile->cd();
	TTree * finalLLtree = (TTree*)TTree::MergeTrees(LLlist);
	TTree * finalDDtree = (TTree*)TTree::MergeTrees(DDlist);
	finalLLtree->SetName("LL_data");
	finalDDtree->SetName("DD_data");
	finalLLtree->Write();
	finalDDtree->Write();

	delete ceff;
	histFile->Write();
	delete histFile;

	}
Exemple #5
0
//put very small data entries in a binned dataset to avoid unphysical pdfs, specifically for H->ZZ->4l
RooDataSet* makeData(RooDataSet* orig, RooSimultaneous* simPdf, const RooArgSet* observables, RooRealVar* firstPOI, double mass, double& mu_min)
{

  double max_soverb = 0;

  mu_min = -10e9;

  map<string, RooDataSet*> data_map;
  firstPOI->setVal(0);
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();
  TList* datalist = orig->split(*(RooAbsCategory*)cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  RooRealVar* weightVar = new RooRealVar("weightVar","weightVar",1);
  while ((ds = (RooAbsData*)dataItr->Next()))
  {
    string typeName(ds->GetName());
    cat->setLabel(typeName.c_str());
    RooAbsPdf* pdf = simPdf->getPdf(typeName.c_str());
    cout << "pdf: " << pdf << endl;
    RooArgSet* obs = pdf->getObservables(observables);
    cout << "obs: " << obs << endl;

    RooArgSet obsAndWeight(*obs, *weightVar);
    obsAndWeight.add(*cat);
    stringstream datasetName;
    datasetName << "newData_" << typeName;
    RooDataSet* thisData = new RooDataSet(datasetName.str().c_str(),datasetName.str().c_str(), obsAndWeight, WeightVar(*weightVar));

    RooRealVar* firstObs = (RooRealVar*)obs->first();
    //int ibin = 0;
    int nrEntries = ds->numEntries();
    for (int ib=0;ib<nrEntries;ib++)
    {
      const RooArgSet* event = ds->get(ib);
      const RooRealVar* thisObs = (RooRealVar*)event->find(firstObs->GetName());
      firstObs->setVal(thisObs->getVal());

      firstPOI->setVal(0);
      double b = pdf->expectedEvents(*firstObs)*pdf->getVal(obs);
      firstPOI->setVal(1);
      double s = pdf->expectedEvents(*firstObs)*pdf->getVal(obs) - b;

      if (s > 0)
      {
	mu_min = max(mu_min, -b/s);
	double soverb = s/b;
	if (soverb > max_soverb)
	{
	  max_soverb = soverb;
	  cout << "Found new max s/b: " << soverb << " in pdf " << pdf->GetName() << " at m = " << thisObs->getVal() << endl;
	}
      }

      if (b == 0 && s != 0)
      {
	cout << "Expecting non-zero signal and zero bg at m=" << firstObs->getVal() << " in pdf " << pdf->GetName() << endl;
      }
      if (s+b <= 0) 
      {
	cout << "expecting zero" << endl;
	continue;
      }


      double weight = ds->weight();
      if ((typeName.find("ATLAS_H_4mu") != string::npos || 
	   typeName.find("ATLAS_H_4e") != string::npos ||
	   typeName.find("ATLAS_H_2mu2e") != string::npos ||
	   typeName.find("ATLAS_H_2e2mu") != string::npos) && fabs(firstObs->getVal() - mass) < 10 && weight == 0)
      {
	cout << "adding event: " << firstObs->getVal() << endl;
	thisData->add(*event, pow(10., -9.));
      }
      else
      {
	//weight = max(pow(10.0, -9), weight);
	thisData->add(*event, weight);
      }
    }



    data_map[string(ds->GetName())] = (RooDataSet*)thisData;
  }

  
  RooDataSet* newData = new RooDataSet("newData","newData",RooArgSet(*observables, *weightVar), 
				       Index(*cat), Import(data_map), WeightVar(*weightVar));

  orig->Print();
  newData->Print();
  //newData->tree()->Scan("*");
  return newData;

}
int main(int argc, char **argv)
{
	bool printeff = true;
	string fc = "none";
	
	gROOT->ProcessLine(".x lhcbStyle.C");

	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);

			if(arg.find("-E")!=string::npos) fc = str;
			if(arg=="-peff") printeff = true;
		}
	}
	
	int nexp = 100;
	int nbins = 6;
	double q2min[] = {8.,15.,11.0,15,16,18};
	double q2max[] = {11.,20.,12.5,16,18,20};

	TString datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/candLb.root";
	TreeReader * data = new TreeReader("candLb2Lmumu");
	data->AddFile(datafilename);
	TreeReader * datajpsi = new TreeReader("candLb2JpsiL");
	datajpsi->AddFile(datafilename);

	TFile * histFile = new TFile("Afb_bkgSys.root","recreate");

	string options = "-quiet-noPlot-lin-stdAxis-XM(#Lambda#mu#mu) (MeV/c^{2})-noCost-noParams";
	Analysis::SetPrintLevel("s");

	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5621.,5400.,6000.);
	MM->setRange("Signal",5600,5640);
	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);

	//TGraphAsymmErrors * fL_vs_q2 = new TGraphAsymmErrors();
	//TCanvas * ceff = new TCanvas();

	RooCategory * samples = new RooCategory("samples","samples");
	samples->defineType("DD");
	samples->defineType("LL");

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-0.75,0.75);
	RooRealVar * fL = new RooRealVar("fL","fL",0.6,0.,1.);
	TString afbLpdf = "((3./8.)*(1.-fL)*(1 + TMath::Power(cosThetaL,2)) + afb*cosThetaL + (3./4.)*fL*(1 - TMath::Power(cosThetaL,2)))";
	RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-0.5,0.5);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";
	RooAbsPdf * teoPdf = new RooGenericPdf("teoPdf",afbLpdf,RooArgSet(*cosThetaL,*afb,*fL));
	RooAbsPdf * teoPdfB = new RooGenericPdf("teoPdfB",afbBpdf,RooArgSet(*cosThetaB,*afbB));

	TreeReader * mydata = datajpsi;
	Str2VarMap jpsiParsLL = getJpsiPars("LL", CutsDef::LLcut, histFile);
	Str2VarMap jpsiParsDD = getJpsiPars("DD", CutsDef::DDcut, histFile);

	vector<TH1 *> fLsysh, afbsysh, afbBsysh, fLsysh_frac, afbsysh_frac, afbBsysh_frac;

	for(int i = 0; i < nbins; i++)
	{
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		if(i>0) { mydata = data; MM->setRange(5400,6000); }
		else { q2name = "jpsi"; MM->setRange(5500,5850); }
		TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e",q2min[i],q2max[i]);	
		
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		/**               GET AND FIT EFFICIENCIES                  **/

		RooAbsPdf * effDDpdf = NULL, * effLLpdf = NULL, * effLLBpdf = NULL, * effDDBpdf = NULL;	
		getEfficiencies(q2min[i],q2max[i],&effLLpdf,&effDDpdf,&effLLBpdf,&effDDBpdf,printeff);
		cout << "Efficiencies extracted" << endl;
		histFile->cd();


		/**                    FIT AFB                  **/


		afb->setVal(0);
		afbB->setVal(-0.37);
		fL->setVal(0.6);

		RooAbsPdf * corrPdfLL = new RooProdPdf("sigPdfLL"+q2name,"corrPdfLL",*teoPdf,*effLLpdf);
		RooAbsPdf * corrPdfDD = new RooProdPdf("sigPdfDD"+q2name,"corrPdfDD",*teoPdf,*effDDpdf);
		RooAbsPdf * corrPdfLLB = new RooProdPdf("sigPdfLLB"+q2name,"corrPdfLLB",*teoPdfB,*effLLBpdf);
		RooAbsPdf * corrPdfDDB = new RooProdPdf("sigPdfDDB"+q2name,"corrPdfDDB",*teoPdfB,*effDDBpdf);

		TCut baseCut = "";
		TCut cutLL = CutsDef::LLcut + (TCut)curq2cut + baseCut;
		TCut cutDD = CutsDef::DDcut + (TCut)curq2cut + baseCut;

		histFile->cd();
		double fracDDv[2], fracLLv[2];
		double nsigDD, nsigLL;
		RooDataSet * dataLL = getDataAndFrac("LL",q2name,mydata,cutLL,MM,&fracLLv[0],jpsiParsLL,&nsigLL);
		RooDataSet * dataDD = getDataAndFrac("DD",q2name,mydata,cutDD,MM,&fracDDv[0],jpsiParsDD,&nsigDD);
		double nevts = nsigDD+nsigLL;

		cout << fixed << setprecision(3) << fracDDv[0] << "   " << fracDDv[1] << endl;
		RooRealVar * fracLL = new RooRealVar("fracLL","fracLL",fracLLv[0]);
		RooRealVar * fracDD = new RooRealVar("fracDD","fracDD",fracDDv[0]);

		RooAbsPdf * bkgLL = NULL, * bkgLLB = NULL, * bkgDD = NULL, * bkgDDB = NULL;
		buildBkgPdfs(q2min[i],q2max[i],"LL",CutsDef::LLcut,&bkgLL,&bkgLLB);
		buildBkgPdfs(q2min[i],q2max[i],"DD",CutsDef::DDcut,&bkgDD,&bkgDDB);
	
		cout << "Backgrounds extracted" << endl;

		RooAbsPdf * modelLL = new RooAddPdf("modelLL","modelLL",RooArgSet(*corrPdfLL,*bkgLL),*fracLL);
		RooAbsPdf * modelDD = new RooAddPdf("modelDD","modelDD",RooArgSet(*corrPdfDD,*bkgDD),*fracDD);
		RooAbsPdf * modelLLB = new RooAddPdf("modelLLB","modelLLB",RooArgSet(*corrPdfLLB,*bkgLLB),*fracLL);
		RooAbsPdf * modelDDB = new RooAddPdf("modelDDB","modelDDB",RooArgSet(*corrPdfDDB,*bkgDDB),*fracDD);

		// CREATE COMBINED DATASET
		RooDataSet * combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*MM,*cosThetaL,*cosThetaB),Index(*samples),Import("DD",*dataDD),Import("LL",*dataLL));

		Str2VarMap params;
		params["fL"] = fL;
		params["afb"] = afb;	
		Str2VarMap paramsB;
		paramsB["afbB"] = afbB;

		// FIT COS LEPTON
		RooSimultaneous * combModel = new RooSimultaneous(Form("combModel_%i",i),"",*samples);
		combModel->addPdf(*modelLL,"LL");
		combModel->addPdf(*modelDD,"DD");

		RooFitResult * res = safeFit(combModel,combData,params,&isInAllowedArea);	
	
		// FIT COS HADRON
		RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
		combModelB->addPdf(*modelLLB,"LL");
		combModelB->addPdf(*modelDDB,"DD");

		RooFitResult * resB = safeFit(combModelB,combData,paramsB,&isInAllowedAreaB);

		cout << endl << fixed << setprecision(6) << "AfbB = " << afbB->getVal() << " +/- " << afbB->getError() << endl;
		cout << "Afb = " << afb->getVal() << " +/- " << afb->getError() << endl;
		cout << "fL = " << fL->getVal() << " +/- " << fL->getError() << endl;
		cout << endl;
		cout << "lepton:  " << res->edm() << "   "  << res->covQual() << endl;
		cout << "baryon:  " << resB->edm() << "   "  << resB->covQual() << endl;
		cout << endl;

		TH1F * fLsys = new TH1F(Form("fLsys_%i",i),"fLsys",40,-1,1);
		TH1F * afbsys = new TH1F(Form("afbsys_%i",i),"afbsys",40,-1,1);
		TH1F * afbBsys = new TH1F(Form("afbBsys_%i",i),"afbBsys",40,-1,1);
		TH1F * fLsys_frac = new TH1F(Form("fLsys_frac%i",i),"fLsys",40,-1,1);
		TH1F * afbsys_frac = new TH1F(Form("afbsys_frac%i",i),"afbsys",40,-1,1);
		TH1F * afbBsys_frac = new TH1F(Form("afbBsys_frac%i",i),"afbBsys",40,-1,1);


		RooAbsPdf * mybkgDD_2 = NULL, * mybkgDDB_2 = NULL;
		buildBkgPdfs(q2min[i],q2max[i],"DD",CutsDef::DDcut,&mybkgDD_2,&mybkgDDB_2,"RooKeyPdf");

		//cout << nevts << endl;
		//TRandom3 r(0);

		for(int e = 0; e < nexp; e++)
		{
			histFile->cd();
			RooAbsPdf * toypdf = (RooAbsPdf *)modelDD->Clone();
			Analysis * toy = new Analysis("toy",cosThetaL,modelDD,nevts);
			RooAbsPdf * toypdfB = (RooAbsPdf *)modelDDB->Clone();
			Analysis * toyB = new Analysis("toyB",cosThetaB,modelDDB,nevts);
			
			afb->setVal(0);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			safeFit(toypdf,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(toypdfB,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);
			double def_afb = afb->getVal();
			double def_fL = fL->getVal();
			double def_afbB = afbB->getVal();

			afb->setVal(0);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			RooAbsPdf * modelDD_2 = new RooAddPdf("modelDD_2","modelDD",RooArgSet(*corrPdfDD,*mybkgDD_2),*fracDD);
			RooAbsPdf * modelDDB_2 = new RooAddPdf("modelDDB_2","modelDDB",RooArgSet(*corrPdfDDB,*mybkgDDB_2),*fracDD);
			safeFit(modelDD_2,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(modelDDB_2,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);
			double oth_afb = afb->getVal();
			double oth_fL = fL->getVal();
			double oth_afbB = afbB->getVal();

			fLsys->Fill(oth_fL-def_fL);
			afbsys->Fill(oth_afb-def_afb);
			afbBsys->Fill(oth_afbB-def_afbB);
			

			afb->setVal(0.);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			//double rdm_frac = r.Gaus(fracDDv[0],fracDDv[1]);
			double rdm_frac = fracDDv[0] + fracDDv[1];
			RooRealVar * fracDD_2 = new RooRealVar("fracDD_2","fracDD_2",rdm_frac);	
			RooAbsPdf * modelDD_3 = new RooAddPdf("modelDD_3","modelDD",RooArgSet(*corrPdfDD,*bkgDD),*fracDD_2);
			RooAbsPdf * modelDDB_3 = new RooAddPdf("modelDDB_3","modelDDB",RooArgSet(*corrPdfDDB,*bkgDDB),*fracDD_2);
			safeFit(modelDD_3,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(modelDDB_3,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);

			double frc_afb = afb->getVal();
			double frc_fL = fL->getVal();
			double frc_afbB = afbB->getVal();

			fLsys_frac->Fill(frc_fL-def_fL);
			afbsys_frac->Fill(frc_afb-def_afb);
			afbBsys_frac->Fill(frc_afbB-def_afbB);
			
		}

		afbsysh.push_back(afbsys);
		afbBsysh.push_back(afbBsys);
		fLsysh.push_back(fLsys);
		afbsysh_frac.push_back(afbsys_frac);
		afbBsysh_frac.push_back(afbBsys_frac);
		fLsysh_frac.push_back(fLsys_frac);

	}

	
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << fLsysh[q]->GetMean() << " +/- " << fLsysh[q]->GetMeanError() << endl;
		cout << "Afb sys = " << afbsysh[q]->GetMean() << " +/- " << afbsysh[q]->GetMeanError() << endl;
		cout << "AfbB sys = " << afbBsysh[q]->GetMean() << " +/- " << afbBsysh[q]->GetMeanError() << endl;
	}

	cout << "#################################################################" << endl;
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << fLsysh_frac[q]->GetMean() << " +/- " << fLsysh_frac[q]->GetMeanError() << endl;
		cout << "Afb sys = " << afbsysh_frac[q]->GetMean() << " +/- " << afbsysh_frac[q]->GetMeanError() << endl;
		cout << "AfbB sys = " << afbBsysh_frac[q]->GetMean() << " +/- " << afbBsysh_frac[q]->GetMeanError() << endl;
	}

	cout << "#################################################################" << endl;
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << TMath::Sqrt(TMath::Power(fLsysh_frac[q]->GetMean(),2) + TMath::Power(fLsysh[q]->GetMean(),2) )  << endl;
		cout << "Afb sys = " << TMath::Sqrt(TMath::Power(afbsysh_frac[q]->GetMean(),2) + TMath::Power(afbsysh[q]->GetMean(),2) ) << endl;
		cout << "AfbB sys = " << TMath::Sqrt(TMath::Power(afbBsysh_frac[q]->GetMean(),2) + TMath::Power(afbBsysh[q]->GetMean(),2) ) << endl;
	}

}
void rs603_HLFactoryElaborateExample() {

  // --- Prepare the 2 needed datacards for this example ---

  TString card_name("rs603_card_WsMaker.rs");
  ofstream ofile(card_name);
  ofile << "// The simplest card for combination\n\n";
  ofile << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n";
  ofile << "flat1 = Polynomial(x,0);\n";
  ofile << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n\n";
  ofile << "echo In the middle!;\n\n";
  ofile << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n";
  ofile << "flat2 = Polynomial(x,0);\n";
  ofile << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n\n";
  ofile << "echo At the end!;\n";
  ofile.close();

  TString card_name2("rs603_card.rs");
  ofstream ofile2(card_name2);
  ofile2 << "// The simplest card for combination\n\n";
  ofile2 << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n";
  ofile2 << "flat1 = Polynomial(x,0);\n";
  ofile2 << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n\n";
  ofile2 << "echo In the middle!;\n\n";
  ofile2 << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n";
  ofile2 << "flat2 = Polynomial(x,0);\n";
  ofile2 << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n\n";
  ofile2 << "#include rs603_included_card.rs;\n\n";
  ofile2 << "echo At the end!;\n";
  ofile2.close();

  TString card_name3("rs603_included_card.rs");
  ofstream ofile3(card_name3);
  ofile3 << "echo Now reading the included file!;\n\n";
  ofile3 << "echo Including datasets in a Workspace in a Root file...;\n";
  ofile3 << "data1 = import(rs603_infile.root,\n";
  ofile3 << "               rs603_ws,\n";
  ofile3 << "               data1);\n\n";
  ofile3 << "data2 = import(rs603_infile.root,\n";
  ofile3 << "               rs603_ws,\n";
  ofile3 << "               data2);\n";
  ofile3.close();

// --- Produce the two separate datasets into a WorkSpace ---

HLFactory hlf("HLFactoryComplexExample",
              "rs603_card_WsMaker.rs",
              false);

RooRealVar* x = static_cast<RooRealVar*>(hlf.GetWs()->arg("x"));
RooAbsPdf* pdf1 = hlf.GetWs()->pdf("sb_model1");
RooAbsPdf* pdf2 = hlf.GetWs()->pdf("sb_model2");

RooWorkspace w("rs603_ws");

RooDataSet* data1 = pdf1->generate(RooArgSet(*x),Extended());
data1->SetName("data1");
w.import(*data1);

RooDataSet* data2 = pdf2->generate(RooArgSet(*x),Extended());
data2->SetName("data2");
w.import(*data2);

// --- Write the WorkSpace into a rootfile ---

TFile outfile("rs603_infile.root","RECREATE");
w.Write();
outfile.Close();

cout << "-------------------------------------------------------------------\n"
     << " Rootfile and Workspace prepared \n"
     << "-------------------------------------------------------------------\n";


HLFactory hlf_2("HLFactoryElaborateExample",
                "rs603_card.rs",
                false);

x = hlf_2.GetWs()->var("x");
pdf1 = hlf_2.GetWs()->pdf("sb_model1");
pdf2 = hlf_2.GetWs()->pdf("sb_model2");

hlf_2.AddChannel("model1","sb_model1","flat1","data1");
hlf_2.AddChannel("model2","sb_model2","flat2","data2");

RooDataSet* data = hlf_2.GetTotDataSet();
RooAbsPdf* pdf = hlf_2.GetTotSigBkgPdf();
RooCategory* thecat = hlf_2.GetTotCategory();

// --- Perform extended ML fit of composite PDF to toy data ---
pdf->fitTo(*data) ;

// --- Plot toy data and composite PDF overlaid ---
RooPlot* xframe = x->frame() ;

data->plotOn(xframe);
thecat->setIndex(0);
pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

thecat->setIndex(1);
pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

gROOT->SetStyle("Plain");

xframe->Draw();

}
Exemple #8
0
void Plot_BG(TString wsname)
{
	//get the stuff from the workspace:
	
	TFile* file=TFile::Open(wsname);
	RooWorkspace* ws = (RooWorkspace*)file->Get("combined");
	mc = (ModelConfig*)ws->obj("ModelConfig");
	data = ws->data("obsData");
	RooSimultaneous* simPdf=(RooSimultaneous*)(mc->GetPdf());
	RooAbsReal* nll=simPdf->createNLL(*data);
	
	//run on channels
	
	RooCategory* chanCat = (RooCategory*) (&simPdf->indexCat());
        TIterator* iterat = chanCat->typeIterator() ;
        RooCatType* ttype;
	bool stop = kFALSE;
	while ((ttype = (RooCatType*) iterat->Next())&&!stop)
	{
		// bool toggle to run on one channel or all	
		stop = kTRUE;
		RooAbsPdf  *pdf_state  = simPdf->getPdf(ttype->GetName()) ;
		RooArgSet  *obstmp  = pdf_state->getObservables( *mc->GetObservables() ) ;
        	RooAbsData *datatmp = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));
		RooRealVar *obs     = ((RooRealVar*) obstmp->first());
		TString chanName(ttype->GetName());

		// get data
		TH1* hdata = datatmp->createHistogram("Data "+chanName,*obs);
		// set errors to gaussian
        	for (int ib=0 ; ib<hdata->GetNbinsX()+1 ; ib++) hdata->SetBinError(ib, sqrt(hdata->GetBinContent(ib)));
		
		// get initial BG
		TH1* h_initial_BG = pdf_state->createHistogram("initial_BG_"+chanName,*obs);
	
		// get initial gammas
		int nbins = h_initial_BG->GetNbinsX();
        	double InitGamma[nbins];
        	for (int i=0; i<nbins; i++)
        	{
                	TString varname = "gamma_B0_0j_l1pt0_bin_"+NumberToString(i);
                	InitGamma[i] = ws->var(varname)->getVal();
                	cout << "initial gamma"+NumberToString(i)+" = " << InitGamma[i] << endl;
        	}
        	double InitFpt = ws->var("fl1pt_l1pt0")->getVal();
        	cout << "initial fpt_l1pt0 = " << InitFpt <<  endl;

		TCanvas* c1 = new TCanvas("BG and Data "+chanName,"BG and Data "+chanName,600,600);
		h_initial_BG->Draw();
		//hdata->DrawNormalized("sames E1");

		// DO THE GLOBAL FIT
		
		RooMinimizer minim(*nll);
        	//set some options:
        	minim.setPrintLevel(0);
        	minim.optimizeConst(1);
        	minim.setOffsetting(true);
        	minim.setMinimizerType("Minuit2");
        	minim.minimize("Minuit2");
        	minim.setStrategy(3); //0-3 where 0 is the fastest
        	minim.migrad();
        
		// get gammas after fit
		double FinalGamma[nbins];
		TH1* h_initBG_times_gamma = (TH1*)h_initial_BG->Clone("initBG_times_gamma");
		for (int i=0; i<nbins; i++)
        	{
                	TString varname = "gamma_B0_0j_l1pt0_bin_"+NumberToString(i);
                	FinalGamma[i] = ws->var(varname)->getVal();
                	cout << "Final gamma in bin "+NumberToString(i)+" = " << FinalGamma[i] << endl;
        		h_initBG_times_gamma->SetBinContent(i+1,h_initial_BG->GetBinContent(i+1)*FinalGamma[i]);
		}
		double FinalFpt = ws->var("fl1pt_l1pt0")->getVal();
		cout << "initial fpt_l1pt0 = " << InitFpt <<  endl;
		cout << "final fpt_l1pt0 = " << FinalFpt <<  endl;
	
		TH1* h_final_BG = pdf_state->createHistogram("final_BG_"+chanName,*obs);
        	//TCanvas* cf = new TCanvas("final BG","final BG",600,600);
		h_final_BG->Draw("sames");
		h_initBG_times_gamma->Draw("sames");
		TH1* h_ratio = (TH1*)h_initial_BG->Clone("h_ratio");
		h_ratio->Divide(h_final_BG);
		//h_ratio->Draw();
		cout << "channel name = " << chanName << endl;	
		for ( int j=1; j<=nbins; j++)
		{
			double init = h_initial_BG->GetBinContent(j);
			double fina = h_final_BG->GetBinContent(j);
			double r = (fina)/init;
			cout << "in bin " << j << ", initial B = " << init << ", final B = " << fina << ", ratio = " << r << ", Gamma = " << FinalGamma[j-1] << endl;
		}	
	}


}
Exemple #9
0
void PlotAll(TString wsname)
{
	char* binLabels[19] = {"60","70","80","90","100","110","120","130","140","150","160","170","180","190","200","250","300","400","1000"};	

	//get the stuff from the workspace:
	
	TFile* file=TFile::Open(wsname);
	RooWorkspace* ws = (RooWorkspace*)file->Get("combined");
	ModelConfig  *mc = (ModelConfig*)ws->obj("ModelConfig");
	RooAbsData   *data = ws->data("obsData");
	RooSimultaneous* simPdf=(RooSimultaneous*)(mc->GetPdf());
	RooAbsReal* nll=simPdf->createNLL(*data);

	// FPT 0 **************************************	
	// EM channel
	
	RooCategory* chanCat = (RooCategory*) (&simPdf->indexCat());
        TIterator* iterat = chanCat->typeIterator() ;
        RooCatType* ttype = (RooCatType*)iterat->Next();

	RooAbsPdf  *pdf_stateEM  = simPdf->getPdf(ttype->GetName()) ;
	RooArgSet  *obstmpEM  = pdf_stateEM->getObservables( *mc->GetObservables() ) ;
	
	// get EM data
       	RooAbsData *dataEM = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));
		
	RooRealVar *obsEM     = ((RooRealVar*) obstmpEM->first());
	TString chanName1(ttype->GetName());

	// create data histogram
	TH1* hdataEM = dataEM->createHistogram("Data "+chanName1,*obsEM);
	// set errors to gaussian
        for (int ib=0 ; ib<hdataEM->GetNbinsX()+1 ; ib++) hdataEM->SetBinError(ib, sqrt(hdataEM->GetBinContent(ib)));

	double EMnorm = pdf_stateEM->expectedEvents(*obsEM);
	
	//****************************
	// ME channel
	ttype = (RooCatType*)iterat->Next();
	RooAbsPdf* pdf_stateME  = simPdf->getPdf(ttype->GetName()) ;
        RooArgSet* obstmpME  = pdf_stateME->getObservables( *mc->GetObservables() ) ;

	// get ME data
	RooAbsData *dataME = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));	
	RooRealVar* obsME = ((RooRealVar*) obstmpME->first());
	TString chanName2(ttype->GetName());

        // create data histogram
        TH1* hdataME = dataME->createHistogram("Data "+chanName2,*obsME);
        // set errors to gaussian
        for (int ib=0 ; ib<hdataME->GetNbinsX()+1 ; ib++) hdataME->SetBinError(ib, sqrt(hdataME->GetBinContent(ib)));
        
	
	// get initial BG histogram
	//TH1* h_initial_BG_EM = pdf_stateEM->createHistogram("initial_BG_EM",*obsEM);
	//TH1* h_initial_BG_ME = pdf_stateME->createHistogram("initial_BG_ME",*obsME);
	
	double MEnorm = pdf_stateME->expectedEvents(*obsME);
	cout << "EM expected events = " << EMnorm << ", ME expected events = " << MEnorm << "." << endl;
	//h_initial_BG_EM->Scale(EMnorm);
	//h_initial_BG_ME->Scale(MEnorm);	

	// get initial gammas
	int nbins = hdataEM->GetNbinsX();
        double InitGamma[nbins];
        for (int i=0; i<nbins; i++)
        {
               	TString varname = "gamma_B0_l1pt0_bin_"+NumberToString(i);
               	InitGamma[i] = ws->var(varname)->getVal();
               	cout << "initial gamma"+NumberToString(i)+" = " << InitGamma[i] << endl;
        }
        double InitFpt = ws->var("fl1pt_l1pt0")->getVal();
        cout << "initial fpt_l1pt0 = " << InitFpt <<  endl;


	// DO THE GLOBAL FIT
	
	minimize(nll);	
       
	// get final BG histograms
	TH1* h_final_BG_EM = pdf_stateEM->createHistogram("final_BG_EM",*obsEM);
        TH1* h_final_BG_ME = pdf_stateME->createHistogram("final_BG_ME",*obsME); 
	h_final_BG_EM->Scale(EMnorm);
	h_final_BG_ME->Scale(MEnorm);
	
	// uncertainty bands
	TH1D* BuncertaintyEM = new TH1D("BuncertaintyEM","BuncertaintyEM",nbins,0,nbins);
	TH1D* BuncertaintyME = new TH1D("BuncertaintyME","BuncertaintyME",nbins,0,nbins);
	for (int i=1; i<=nbins; i++){
		double sigbEM = h_final_BG_EM->GetBinError(i);
		double bEM = h_final_BG_EM->GetBinContent(i);
		BuncertaintyEM->SetBinError(i,sigbEM); BuncertaintyEM->SetBinContent(i,bEM);
		double sigbME = h_final_BG_ME->GetBinError(i);
                double bME = h_final_BG_ME->GetBinContent(i);
                BuncertaintyME->SetBinError(i,sigbME); BuncertaintyME->SetBinContent(i,bME);
	}
	//BuncertaintyEM->SetFillStyle(3004); 
	BuncertaintyEM->SetFillColor(kGreen-9);
	BuncertaintyEM->SetLineColor(kBlack); BuncertaintyEM->SetLineStyle(2);
	//BuncertaintyME->SetFillStyle(3004); 
	BuncertaintyME->SetFillColor(kBlue-9);
        BuncertaintyME->SetLineColor(kBlack); BuncertaintyME->SetLineStyle(2);

	// get gammas after fit
	double FinalGamma[nbins];
	//TH1* h_initBG_times_gamma = (TH1*)h_initial_BG_EM->Clone("initBGEM_times_gamma");
	for (int i=0; i<nbins; i++)
       	{
               	TString varname = "gamma_B0_l1pt0_bin_"+NumberToString(i);
               	FinalGamma[i] = ws->var(varname)->getVal();
               	cout << "Final gamma in bin "+NumberToString(i)+" = " << FinalGamma[i] << endl;
       	//	h_initBG_times_gamma->SetBinContent(i+1,h_initial_BG_EM->GetBinContent(i+1)*FinalGamma[i]);
	}
	//double FinalFpt = ws->var("fl1pt_l1pt0")->getVal();
	
	// get final alpha (pull)
	RooRealVar* alphaVar = ws->var("alpha_l1ptsys_l1pt0");
	double alpha, alphaErr;
	if (alphaVar != NULL) {
		alpha = ws->var("alpha_l1ptsys_l1pt0")->getVal();
		alphaErr = ws->var("alpha_l1ptsys_l1pt0")->getError();
	}

	//FOR UNCONSTRAINED FPT - get final fpts
	double FinalFpt[5];
	double FinalFptErr[5];
	for (int k=0; k<5; k++){
		TString varname = "fl1pt_l1pt"+NumberToString(k);
		FinalFpt[k] = ws->var(varname)->getVal();
		FinalFptErr[k] =  ws->var(varname)->getError();
		cout << varname << " = "  << FinalFpt[k] << " +- " << FinalFptErr[k] << endl;
	}
	
	// get POI value
	double mu = ws->var("mu_BR_htm")->getVal();
	double muErr = ws->var("mu_BR_htm")->getError();
	
	// Draw
	TCanvas* c1 = new TCanvas("BG and Data "+chanName1+" "+chanName2,"BG and Data "+chanName1+" "+chanName2,600,600);
	BuncertaintyEM->Draw("E3 sames"); BuncertaintyME->Draw("E3 sames");
	//h_initial_BG_EM->SetLineColor(kGreen+2); h_initial_BG_EM->SetLineStyle(2); h_initial_BG_EM->Draw("sames");
	hdataEM->SetLineColor(kGreen+2); hdataEM->SetMarkerStyle(20); hdataEM->SetMarkerColor(kGreen+2);
	hdataEM->Draw("e1 sames");
	//h_initial_BG_ME->SetLineColor(kBlue); h_initial_BG_ME->SetLineStyle(2); h_initial_BG_ME->Draw("sames");
        hdataME->SetLineColor(kBlue); hdataME->SetMarkerStyle(20);  hdataME->SetMarkerColor(kBlue);
	hdataME->Draw("e1 sames");

	h_final_BG_EM->SetLineColor(kGreen+2); h_final_BG_EM->SetLineWidth(2); h_final_BG_EM->Draw("sames");
	h_final_BG_ME->SetLineColor(kBlue); h_final_BG_ME->SetLineWidth(2); h_final_BG_ME->Draw("sames");

	TLegend* leg = new TLegend(0.5,0.45,0.85,0.65);
        leg->SetFillColor(kWhite); leg->SetBorderSize(1); leg->SetLineColor(0); //leg->SetTextFont(14);
        leg->SetTextSize(.03);

	leg->AddEntry(hdataME,"DATA #mue","lep");
	leg->AddEntry(hdataEM,"DATA e#mu","lep");
	//leg->AddEntry(h_initial_BG_ME,"Initial #mue PDF","l");
	//leg->AddEntry(h_initial_BG_EM,"Initial e#mu PDF","l");
	leg->AddEntry(h_final_BG_ME,"#mue PDF = #gamma_{i}B_{i} + #muS_{i}","l");
	leg->AddEntry(h_final_BG_EM,"e#mu PDF = f(1+#alpha#sigma)(#gamma_{i}B_{i}+#muW_{i})","l");
	leg->Draw();

	cout << " ********************* Fit Values **************************** " <<  endl;
	if (alphaVar != NULL){cout << "alpha = " << alpha << " +- " << alphaErr << endl;}
	cout << "mu    = " << mu << " +- " << muErr << endl;

	TString WriteDownAlphaValue;
	TString WriteDownMuValue;
	WriteDownAlphaValue = "Fpt0 = ";
	WriteDownMuValue = "#mu = ";
	WriteDownAlphaValue += Form("%4.4f",FinalFpt[0]);
	WriteDownAlphaValue += "#pm";
	WriteDownAlphaValue += Form("%4.4f",FinalFptErr[0]);
	WriteDownMuValue += Form("%4.4f",mu);
        WriteDownMuValue += "#pm";
        WriteDownMuValue += Form("%4.4f",muErr);

	TLatex *texl = new TLatex(12,25,WriteDownAlphaValue);
   	texl->SetTextAlign(22); texl->SetTextSize(0.03); 
   	TLatex *texl2 = new TLatex(12,23,WriteDownMuValue);
        texl2->SetTextAlign(22); texl2->SetTextSize(0.03);
	texl->Draw(); 
	texl2->Draw();



	//FPT 1 ***********************************
	ttype = (RooCatType*)iterat->Next();

        RooAbsPdf  *pdf_stateEM1  = simPdf->getPdf(ttype->GetName()) ;
        RooArgSet  *obstmpEM1  = pdf_stateEM1->getObservables( *mc->GetObservables() ) ;
	RooAbsData *dataEM1 = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));

        RooRealVar *obsEM1     = ((RooRealVar*) obstmpEM1->first());
        TString chanName11(ttype->GetName());	
	TH1* hdataEM1 = dataEM1->createHistogram("Data "+chanName11,*obsEM1);
	for (int ib=0 ; ib<hdataEM1->GetNbinsX()+1 ; ib++) hdataEM1->SetBinError(ib, sqrt(hdataEM1->GetBinContent(ib)));

        double EMnorm1 = pdf_stateEM1->expectedEvents(*obsEM1);
	ttype = (RooCatType*)iterat->Next();
        RooAbsPdf* pdf_stateME1  = simPdf->getPdf(ttype->GetName()) ;
        RooArgSet* obstmpME1  = pdf_stateME1->getObservables( *mc->GetObservables() ) ;
	RooAbsData *dataME1 = data->reduce(Form("%s==%s::%s",chanCat->GetName(),chanCat->GetName(),ttype->GetName()));
        RooRealVar* obsME1 = ((RooRealVar*) obstmpME1->first());
        TString chanName21(ttype->GetName());
	TH1* hdataME1 = dataME1->createHistogram("Data "+chanName21,*obsME1);

	for (int ib=0 ; ib<hdataME1->GetNbinsX()+1 ; ib++) hdataME1->SetBinError(ib, sqrt(hdataME1->GetBinContent(ib)));
	double MEnorm1 = pdf_stateME1->expectedEvents(*obsME1);
	TH1* h_final_BG_EM1 = pdf_stateEM1->createHistogram("final_BG_EM1",*obsEM1);
        TH1* h_final_BG_ME1 = pdf_stateME1->createHistogram("final_BG_ME1",*obsME1);
        h_final_BG_EM1->Scale(EMnorm1);
        h_final_BG_ME1->Scale(MEnorm1);
	TH1D* BuncertaintyEM1 = new TH1D("BuncertaintyEM1","BuncertaintyEM1",nbins,0,nbins);
        TH1D* BuncertaintyME1 = new TH1D("BuncertaintyME1","BuncertaintyME1",nbins,0,nbins);
        for (int i=1; i<=nbins; i++){
                double sigbEM = h_final_BG_EM1->GetBinError(i);
                double bEM = h_final_BG_EM1->GetBinContent(i);
                BuncertaintyEM1->SetBinError(i,sigbEM); BuncertaintyEM1->SetBinContent(i,bEM);
                double sigbME = h_final_BG_ME1->GetBinError(i);
                double bME = h_final_BG_ME1->GetBinContent(i);
                BuncertaintyME1->SetBinError(i,sigbME); BuncertaintyME1->SetBinContent(i,bME);
        }
	BuncertaintyEM1->SetFillColor(kGreen-9);
        BuncertaintyEM1->SetLineColor(kBlack); BuncertaintyEM1->SetLineStyle(2);
	BuncertaintyME1->SetFillColor(kBlue-9);
        BuncertaintyME1->SetLineColor(kBlack); BuncertaintyME1->SetLineStyle(2);
	double FinalGamma1[nbins];
        for (int i=0; i<nbins; i++)
        {
                TString varname = "gamma_B0_l1pt1_bin_"+NumberToString(i);
                FinalGamma1[i] = ws->var(varname)->getVal();
                cout << "Final gamma in bin "+NumberToString(i)+" = " << FinalGamma1[i] << endl;
        }
	TCanvas* c2 = new TCanvas("BG and Data "+chanName11+" "+chanName21,"BG and Data "+chanName11+" "+chanName21,600,600);
        BuncertaintyEM1->Draw("E3 sames"); BuncertaintyME1->Draw("E3 sames");
        hdataEM1->SetLineColor(kGreen+2); hdataEM1->SetMarkerStyle(20); hdataEM1->SetMarkerColor(kGreen+2);
        hdataEM1->Draw("e1 sames");
        hdataME1->SetLineColor(kBlue); hdataME1->SetMarkerStyle(20);  hdataME1->SetMarkerColor(kBlue);
        hdataME1->Draw("e1 sames");

        h_final_BG_EM1->SetLineColor(kGreen+2); h_final_BG_EM1->SetLineWidth(2); h_final_BG_EM1->Draw("sames");
        h_final_BG_ME1->SetLineColor(kBlue); h_final_BG_ME1->SetLineWidth(2); h_final_BG_ME1->Draw("sames");

        leg->Draw();

        cout << " ********************* Fit Values **************************** " <<  endl;
        cout << "mu    = " << mu << " +- " << muErr << endl;
	TString WriteDownAlphaValue1;
        WriteDownAlphaValue1 = "Fpt1 = ";
        WriteDownAlphaValue1 += Form("%4.4f",FinalFpt[1]);
        WriteDownAlphaValue1 += "#pm";
        WriteDownAlphaValue1 += Form("%4.4f",FinalFptErr[1]);

        TLatex *texl11 = new TLatex(12,25,WriteDownAlphaValue1);
        texl11->SetTextAlign(22); texl11->SetTextSize(0.03);
        texl11->Draw(); 
        texl2->Draw();

}
// total PDF
void makeTotalPdf( RooWorkspace *w ) {

  // constrain the bs->phikst / bd->phikst ratio
  w->factory( "yield_ratio_bs2phikst_o_bd2phikst[0.,1.]" );
  w->factory( "Gaussian::yield_ratio_bs2phikst_o_bd2phikst_constraint( yield_ratio_bs2phikst_o_bd2phikst, 0.113, 0.0287 )" );
  // constrain the bd->rhokst / bd->phikst ratio
  w->factory("yield_ratio_bd2rhokst_o_bd2phikst[0.,1.]" );
  w->factory( "Gaussian::yield_ratio_bd2rhokst_o_bd2phikst_constraint( yield_ratio_bd2rhokst_o_bd2phikst, 0.390, 0.130 )" ); // PDG err is 0.130 (relax this for eff)

  // make a yield for each category
  RooCategory *cat = (RooCategory*)w->cat("DataCat");
  for ( int i=0; i < cat->numTypes(); i++ ) {
    cat->setIndex(i);
    w->factory( Form("bkg_y_%s[200,400e3]",       cat->getLabel()));
    w->factory( Form("part_reco_y_%s[100,200e3]", cat->getLabel()));
    w->factory( Form("bs2kstkst_y_%s[0,20e3]", cat->getLabel()));
    w->factory( Form("bd2kstkst_y_%s[0,3000]", cat->getLabel()));
    w->factory( Form("bd2phikst_y_%s[10,5000]", cat->getLabel()));
    // add bs2phikst yield as constrained ratio
    w->factory( Form("prod::bs2phikst_y_%s( yield_ratio_bs2phikst_o_bd2phikst, bd2phikst_y_%s )", cat->getLabel(), cat->getLabel()) );
    //w->factory( Form("bs2phikst_y_%s[10,5000]", cat->getLabel()));
    // add bd2rhokst yield as constrained ratio
    w->factory( Form("prod::bd2rhokst_y_%s( yield_ratio_bd2rhokst_o_bd2phikst, bd2phikst_y_%s )", cat->getLabel(), cat->getLabel()) );
    //w->factory( Form("bd2rhokst_y_%s[5,250]", cat->getLabel()));
    w->factory( Form("lb2pkpipi_y_%s[0,4000]", cat->getLabel()));
    w->factory( Form("lb2ppipipi_y_%s[0,4000]", cat->getLabel()));
  }

  // construct the pdf for each category
  for ( int i=0; i < cat->numTypes(); i++ ) {
    cat->setIndex(i);

    RooArgList *yields = new RooArgList();
    yields->add(*w->var( Form("bkg_y_%s"      , cat->getLabel()) ));
    yields->add(*w->var( Form("part_reco_y_%s", cat->getLabel()) ));
    yields->add(*w->var( Form("bs2kstkst_y_%s", cat->getLabel()) ));
    yields->add(*w->var( Form("bd2kstkst_y_%s", cat->getLabel()) ));
    yields->add(*w->var( Form("bd2phikst_y_%s", cat->getLabel()) ));
    yields->add(*w->function( Form("bs2phikst_y_%s", cat->getLabel()) ));
    //yields->add(*w->var( Form("bs2phikst_y_%s", cat->getLabel()) ));
    yields->add(*w->function( Form("bd2rhokst_y_%s", cat->getLabel()) ));
    //yields->add(*w->var( Form("bd2rhokst_y_%s", cat->getLabel()) ));
    yields->add(*w->var( Form("lb2pkpipi_y_%s", cat->getLabel()) ));
    //yields->add(*w->var( Form("lb2ppipipi_y_%s", cat->getLabel()) )); // this guy we scrap

    RooArgList *pdfs   = new RooArgList();
    pdfs->add(*w->pdf( Form("bkg_pdf_%s", cat->getLabel()) ));
    pdfs->add(*w->pdf("part_reco_pdf" ));
    pdfs->add(*w->pdf("bs2kstkst_mc_pdf"  ));
    pdfs->add(*w->pdf("bd2kstkst_mc_pdf" ));
    pdfs->add(*w->pdf("bd2phikst_mc_pdf" ));
    pdfs->add(*w->pdf("bs2phikst_mc_pdf" ));
    pdfs->add(*w->pdf("bd2rhokst_mc_pdf" ));
    pdfs->add(*w->pdf("lb2pkpipi_mc_pdf" ));
    //pdfs->add(*w->pdf("lb2ppipipi_mc_pdf")); // this guy we scrap

    RooAddPdf *pdf = new RooAddPdf( Form("pdf_%s",cat->getLabel()), "pdf" , *pdfs, *yields);
    w->import(*pdf);
    delete pdf;

    // then make the constrained pdf
    RooArgSet *prodpdfs = new RooArgSet();
    prodpdfs->add( *w->pdf(Form("pdf_%s",cat->getLabel())) );
    prodpdfs->add( *w->pdf("yield_ratio_bs2phikst_o_bd2phikst_constraint") );
    prodpdfs->add( *w->pdf("yield_ratio_bd2rhokst_o_bd2phikst_constraint") );
    RooProdPdf *cpdf = new RooProdPdf( Form("constrained_pdf_%s",cat->getLabel()), "constrained_pdf", *prodpdfs );
    w->import(*cpdf);
    delete cpdf;

    w->defineSet(Form("pdf_%s_yield_params",cat->getLabel()), *yields);
    w->defineSet(Form("constrained_pdf_%s_yield_params",cat->getLabel()), *yields);
  }

  // now make simultaneous pdf
  RooSimultaneous *cpdf = new RooSimultaneous( "constrained_pdf", "constrained_pdf", *w->cat("DataCat") );
  RooSimultaneous *pdf = new RooSimultaneous( "pdf", "pdf", *w->cat("DataCat") );
  for ( int i=0; i < cat->numTypes(); i++ ) {
    cat->setIndex(i);
    cpdf->addPdf( *w->pdf( Form("constrained_pdf_%s", cat->getLabel() )), cat->getLabel() );
    pdf->addPdf( *w->pdf( Form("pdf_%s", cat->getLabel() )), cat->getLabel() );
  }
  w->import(*cpdf);
  w->import(*pdf);

  delete pdf;
  delete cpdf;

}
Exemple #11
0
void fitbkgdataCard(TString configCard="template.config", 
		    bool dobands  = true,  // create baerror bands for BG models
		    bool dosignal = false, // plot the signal model (needs to be present)
		    bool blinded  = true,  // blind the data in the plots?
		    bool verbose  = true  ) {
  
  gROOT->Macro("MitStyle.C");
  gStyle->SetErrorX(0); 
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();  
  
  TString projectDir;

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

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

  double theCMenergy = -1.;

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

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

  //win->Print();

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

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

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

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

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

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

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

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

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

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

  if( verbose ) wOut->Print();

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

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

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

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

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

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

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

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


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

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

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

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

    RooAddition* sumcatsnm1 = NULL;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    lat[icat] ->Draw();
    lat2[icat]->Draw();
    
    // -------------------------------------------------------    
    // save canvas in different formats
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".pdf"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".eps"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".root"));              
  }
  
  return;
  
}
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();
   }





}
Exemple #13
0
void rf405_realtocatfuncs()
{

  // D e f i n e   p d f   i n   x ,   s a m p l e   d a t a s e t   i n   x 
  // ------------------------------------------------------------------------


  // Define a dummy PDF in x 
  RooRealVar x("x","x",0,10) ;
  RooArgusBG a("a","argus(x)",x,RooConst(10),RooConst(-1)) ;

  // Generate a dummy dataset 
  RooDataSet *data = a.generate(x,10000) ;



  // C r e a t e   a   t h r e s h o l d   r e a l - > c a t   f u n c t i o n
  // --------------------------------------------------------------------------

  // A RooThresholdCategory is a category function that maps regions in a real-valued 
  // input observable observables to state names. At construction time a 'default'
  // state name must be specified to which all values of x are mapped that are not
  // otherwise assigned
  RooThresholdCategory xRegion("xRegion","region of x",x,"Background") ;

  // Specify thresholds and state assignments one-by-one. 
  // Each statement specifies that all values _below_ the given value 
  // (and above any lower specified threshold) are mapped to the
  // category state with the given name
  //
  // Background | SideBand | Signal | SideBand | Background
  //           4.23       5.23     8.23       9.23 
  xRegion.addThreshold(4.23,"Background") ;
  xRegion.addThreshold(5.23,"SideBand") ;
  xRegion.addThreshold(8.23,"Signal") ;
  xRegion.addThreshold(9.23,"SideBand") ; 



  // U s e   t h r e s h o l d   f u n c t i o n   t o   p l o t   d a t a   r e g i o n s
  // -------------------------------------------------------------------------------------

  // Add values of threshold function to dataset so that it can be used as observable
  data->addColumn(xRegion) ;

  // Make plot of data in x
  RooPlot* xframe = x.frame(Title("Demo of threshold and binning mapping functions")) ;
  data->plotOn(xframe) ;

  // Use calculated category to select sideband data
  data->plotOn(xframe,Cut("xRegion==xRegion::SideBand"),MarkerColor(kRed),LineColor(kRed)) ;



  // C r e a t e   a   b i n n i n g    r e a l - > c a t   f u n c t i o n
  // ----------------------------------------------------------------------

  // A RooBinningCategory is a category function that maps bins of a (named) binning definition 
  // in a real-valued input observable observables to state names. The state names are automatically
  // constructed from the variable name, the binning name and the bin number. If no binning name
  // is specified the default binning is mapped

  x.setBins(10,"coarse") ;
  RooBinningCategory xBins("xBins","coarse bins in x",x,"coarse") ;



  // U s e   b i n n i n g   f u n c t i o n   f o r   t a b u l a t i o n   a n d   p l o t t i n g
  // -----------------------------------------------------------------------------------------------

  // Print table of xBins state multiplicity. Note that xBins does not need to be an observable in data
  // it can be a function of observables in data as well
  Roo1DTable* xbtable = data->table(xBins) ;
  xbtable->Print("v") ;

  // Add values of xBins function to dataset so that it can be used as observable
  RooCategory* xb = (RooCategory*) data->addColumn(xBins) ;

  // Define range "alt" as including bins 1,3,5,7,9 
  xb->setRange("alt","x_coarse_bin1,x_coarse_bin3,x_coarse_bin5,x_coarse_bin7,x_coarse_bin9") ;
  
  // Construct subset of data matching range "alt" but only for the first 5000 events and plot it on the frame
  RooDataSet* dataSel = (RooDataSet*) data->reduce(CutRange("alt"),EventRange(0,5000)) ;
  dataSel->plotOn(xframe,MarkerColor(kGreen),LineColor(kGreen)) ;



  new TCanvas("rf405_realtocatfuncs","rf405_realtocatfuncs",600,600) ;
  xframe->SetMinimum(0.01) ;
  gPad->SetLeftMargin(0.15) ; xframe->GetYaxis()->SetTitleOffset(1.4) ; xframe->Draw() ;


}
Exemple #14
0
bool fitCharmoniaMassModel( RooWorkspace& myws,            // Local Workspace
                            const RooWorkspace& inputWorkspace,  // Workspace with all the input RooDatasets
                            struct KinCuts& cut,           // Variable containing all kinematic cuts
                            map<string, string>&  parIni,  // Variable containing all initial parameters
                            struct InputOpt& opt,          // Variable with run information (kept for legacy purpose)
                            string outputDir,              // Path to output directory
                            // Select the type of datasets to fit
                            string DSTAG,                  // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                            bool isPbPb      = false,      // isPbPb = false for pp, true for PbPb
                            bool importDS    = true,       // Select if the dataset is imported in the local workspace
                            // Select the type of object to fit
                            bool incJpsi     = true,       // Includes Jpsi model
                            bool incPsi2S    = true,       // Includes Psi(2S) model
                            bool incBkg      = true,       // Includes Background model
                            // Select the fitting options
                            bool doFit       = true,       // Flag to indicate if we want to perform the fit
                            bool cutCtau     = false,      // Apply prompt ctau cuts
                            bool doConstrFit   = false,    // Do constrained fit
                            bool doSimulFit  = false,      // Do simultaneous fit
                            bool wantPureSMC = false,      // Flag to indicate if we want to fit pure signal MC
                            const char* applyCorr ="",     // Flag to indicate if we want corrected dataset and which correction
                            uint loadFitResult = false,    // Load previous fit results
                            string inputFitDir = "",       // Location of the fit results
                            int  numCores    = 2,          // Number of cores used for fitting
                            // Select the drawing options
                            bool setLogScale = true,       // Draw plot with log scale
                            bool incSS       = false,      // Include Same Sign data
                            bool zoomPsi     = false,      // Zoom Psi(2S) peak on extra pad
                            double  binWidth = 0.05,       // Bin width used for plotting
                            bool getMeanPT   = false       // Compute the mean PT (NEED TO FIX)
                            )  
{

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  // Check if input dataset is MC
  bool isMC = false;
  if (DSTAG.find("MC")!=std::string::npos) {
    if (incJpsi && incPsi2S) { 
      cout << "[ERROR] We can only fit one type of signal using MC" << endl; return false; 
    }
    isMC = true;
  }
  wantPureSMC = (isMC && wantPureSMC);
  bool cutSideBand = (incBkg && (!incPsi2S && !incJpsi));
  bool applyWeight_Corr = ( strcmp(applyCorr,"") );
  
  // Define the mass range
  setMassCutParameters(cut, incJpsi, incPsi2S, isMC);
  parIni["invMassNorm"] = Form("RooFormulaVar::%s('( -1.0 + 2.0*( @0 - @1 )/( @2 - @1) )', {%s, mMin[%.6f], mMax[%.6f]})", "invMassNorm", "invMass", cut.dMuon.M.Min, cut.dMuon.M.Max );
  // Apply the ctau cuts to reject non-prompt charmonia
  if (cutCtau) { setCtauCuts(cut, isPbPb); }
  
  string COLL = (isPbPb ? "PbPb" : "PP" );
  string plotLabelPbPb,  plotLabelPP;

  if (doSimulFit || !isPbPb) {
    // Set models based on initial parameters
    struct OniaModel model;
    if (!setMassModel(model, parIni, false, incJpsi, incPsi2S, incBkg)) { return false; }

    // Import the local datasets
    double numEntries = 1000000;
    string label = ((DSTAG.find("PP")!=std::string::npos) ? DSTAG.c_str() : Form("%s_%s", DSTAG.c_str(), "PP"));
    if (wantPureSMC) label += "_NoBkg";
    if (applyWeight_Corr) label += Form("_%s",applyCorr);
    string dsName = Form("dOS_%s", label.c_str());
    if (importDS) {
      if ( !(myws.data(dsName.c_str())) ) {
        int importID = importDataset(myws, inputWorkspace, cut, label, cutSideBand);
        if (importID<0) { return false; }
        else if (importID==0) { doFit = false; }
      }
      numEntries = myws.data(dsName.c_str())->sumEntries(); if (numEntries<=0) { doFit = false; }
    }
    else if (doFit && !(myws.data(dsName.c_str()))) { cout << "[ERROR] No local dataset was found to perform the fit!" << endl; return false; }
    if (myws.data(dsName.c_str())) numEntries = myws.data(dsName.c_str())->sumEntries();

    // Set global parameters
    setMassGlobalParameterRange(myws, parIni, cut, incJpsi, incPsi2S, incBkg, wantPureSMC);

    // Build the Fit Model
    if (!buildCharmoniaMassModel(myws, model.PP, parIni, false, doConstrFit, doSimulFit, incBkg, incJpsi, incPsi2S, numEntries))  { return false; }

    // Define plot names
    if (incJpsi)  { plotLabelPP += Form("_Jpsi_%s", parIni["Model_Jpsi_PP"].c_str());   } 
    if (incPsi2S) { plotLabelPP += Form("_Psi2S_%s", parIni["Model_Psi2S_PP"].c_str()); }
    if (incBkg)   { plotLabelPP += Form("_Bkg_%s", parIni["Model_Bkg_PP"].c_str());     }
    if (wantPureSMC) plotLabelPP +="_NoBkg";
    if (applyWeight_Corr) plotLabelPP +=Form("_%s",applyCorr);
  }

  if (doSimulFit || isPbPb) {
    // Set models based on initial parameters
    struct OniaModel model;
    if (!setMassModel(model, parIni, true, incJpsi, incPsi2S, incBkg)) { return false; }

    // Import the local datasets
    double numEntries = 1000000;
    string label = ((DSTAG.find("PbPb")!=std::string::npos) ? DSTAG.c_str() : Form("%s_%s", DSTAG.c_str(), "PbPb"));
    if (wantPureSMC) label += "_NoBkg";
    if (applyWeight_Corr) label += Form("_%s",applyCorr);
    string dsName = Form("dOS_%s", label.c_str());
    if (importDS) {
      if ( !(myws.data(dsName.c_str())) ) {
        int importID = importDataset(myws, inputWorkspace, cut, label, cutSideBand);
        if (importID<0) { return false; }
        else if (importID==0) { doFit = false; }
      }
      numEntries = myws.data(dsName.c_str())->sumEntries(); if (numEntries<=0) { doFit = false; }
    }
    else if (doFit && !(myws.data(dsName.c_str()))) { cout << "[ERROR] No local dataset was found to perform the fit!" << endl; return false; }
    if (myws.data(dsName.c_str())) numEntries = myws.data(dsName.c_str())->sumEntries();
      
    // Set global parameters
    setMassGlobalParameterRange(myws, parIni, cut, incJpsi, incPsi2S, incBkg, wantPureSMC);

    // Build the Fit Model
    if (!buildCharmoniaMassModel(myws, model.PbPb, parIni, true, doConstrFit, doSimulFit, incBkg, incJpsi, incPsi2S, numEntries))  { return false; }

    // Define plot names
    if (incJpsi)  { plotLabelPbPb += Form("_Jpsi_%s", parIni["Model_Jpsi_PbPb"].c_str());   } 
    if (incPsi2S) { plotLabelPbPb += Form("_Psi2S_%s", parIni["Model_Psi2S_PbPb"].c_str()); }
    if (incBkg)   { plotLabelPbPb += Form("_Bkg_%s", parIni["Model_Bkg_PbPb"].c_str());     }
    if (wantPureSMC) plotLabelPbPb += "_NoBkg";
    if (applyWeight_Corr) plotLabelPbPb += Form("_%s",applyCorr);
  }

  if (doSimulFit) {
    // Create the combided datasets
    RooCategory* sample = new RooCategory("sample","sample"); sample->defineType("PbPb"); sample->defineType("PP");
    RooDataSet*  combData = new RooDataSet("combData","combined data", *myws.var("invMass"), Index(*sample),
                                           Import("PbPb", *((RooDataSet*)myws.data("dOS_DATA_PbPb"))),
                                           Import("PP",   *((RooDataSet*)myws.data("dOS_DATA_PP")))
                                           );
    myws.import(*sample);

    // Create the combided models
    RooSimultaneous* simPdf = new RooSimultaneous("simPdf", "simultaneous pdf", *sample);
    simPdf->addPdf(*myws.pdf("pdfMASS_Tot_PbPb"), "PbPb"); simPdf->addPdf(*myws.pdf("pdfMASS_Tot_PP"), "PP");
    myws.import(*simPdf);

    // check if we have already done this fit. If yes, do nothing and return true.
    string FileName = "";
    setMassFileName(FileName, (inputFitDir=="" ? outputDir : inputFitDir), DSTAG, (plotLabelPP + plotLabelPbPb), cut, isPbPb, cutSideBand, doSimulFit);
    if (gSystem->AccessPathName(FileName.c_str()) && inputFitDir!="") {
      cout << "[WARNING] User Input File : " << FileName << " was not found!" << endl;
      if (loadFitResult) return false;
      setMassFileName(FileName, outputDir, DSTAG, (plotLabelPP + plotLabelPbPb), cut, isPbPb, cutSideBand, doSimulFit);
    }
    bool found =  true; bool skipFit = !doFit;
    RooArgSet *newpars = myws.pdf("simPdf")->getParameters(*(myws.var("invMass")));
    myws.saveSnapshot("simPdf_parIni", *newpars, kTRUE);
    found = found && isFitAlreadyFound(newpars, FileName, "simPdf");
    if (loadFitResult) {
      if ( loadPreviousFitResult(myws, FileName, DSTAG, false, (!isMC && !cutSideBand && loadFitResult==1), loadFitResult==1) ) { skipFit = true; } else { skipFit = false; }
      if ( loadPreviousFitResult(myws, FileName, DSTAG, true, (!isMC && !cutSideBand && loadFitResult==1), loadFitResult==1)  ) { skipFit = true; } else { skipFit = false; }
      if (skipFit) { cout << "[INFO] This simultaneous mass fit was already done, so I'll load the fit results." << endl; }
      myws.saveSnapshot("simPdf_parLoad", *newpars, kTRUE);
    } else if (found) {
      cout << "[INFO] This simultaneous mass fit was already done, so I'll just go to the next one." << endl;
      return true;
    }

    // Do the simultaneous fit
    if (skipFit==false) {
      RooFitResult* fitResult = simPdf->fitTo(*combData, Offset(kTRUE), Extended(kTRUE), NumCPU(numCores), Range("MassWindow"), Save()); //, Minimizer("Minuit2","Migrad")
      fitResult->Print("v");
      myws.import(*fitResult, "fitResult_simPdf"); 
      // Create the output files
      int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
      drawMassPlot(myws, outputDir, opt, cut, parIni, plotLabelPP, DSTAG, false, incJpsi, incPsi2S, incBkg, cutCtau, doSimulFit, false, setLogScale, incSS, zoomPsi, nBins, getMeanPT);
      drawMassPlot(myws, outputDir, opt, cut, parIni, plotLabelPbPb, DSTAG, true, incJpsi, incPsi2S, incBkg, cutCtau, doSimulFit, false, setLogScale, incSS, zoomPsi, nBins, getMeanPT);
      // Save the results
      string FileName = ""; setMassFileName(FileName, outputDir, DSTAG, (plotLabelPP + plotLabelPbPb), cut, isPbPb, cutSideBand, doSimulFit);
      myws.saveSnapshot("simPdf_parFit", *newpars, kTRUE);
      saveWorkSpace(myws, Form("%smass%s/%s/result", outputDir.c_str(), (cutSideBand?"SB":""), DSTAG.c_str()), FileName);
      // Delete the objects used during the simultaneous fit
      delete sample; delete combData; delete simPdf;
    }
  }
  else {
    // Define pdf and plot names
    string pdfName = Form("pdfMASS_Tot_%s", COLL.c_str());
    string plotLabel = (isPbPb ? plotLabelPbPb : plotLabelPP);

    // Import the local datasets
    string label = ((DSTAG.find(COLL.c_str())!=std::string::npos) ? DSTAG.c_str() : Form("%s_%s", DSTAG.c_str(), COLL.c_str()));
    if (wantPureSMC) label += "_NoBkg";
    if (applyWeight_Corr) label += Form("_%s",applyCorr);
    string dsName = Form("dOS_%s", label.c_str());
      
    // check if we have already done this fit. If yes, do nothing and return true.
    string FileName = "";
    setMassFileName(FileName, (inputFitDir=="" ? outputDir : inputFitDir), DSTAG, plotLabel, cut, isPbPb, cutSideBand);
    if (gSystem->AccessPathName(FileName.c_str()) && inputFitDir!="") {
      cout << "[WARNING] User Input File : " << FileName << " was not found!" << endl;
      if (loadFitResult) return false;
      setMassFileName(FileName, outputDir, DSTAG, plotLabel, cut, isPbPb, cutSideBand);
    }
    bool found =  true; bool skipFit = !doFit;
    RooArgSet *newpars = myws.pdf(pdfName.c_str())->getParameters(*(myws.var("invMass")));
    found = found && isFitAlreadyFound(newpars, FileName, pdfName.c_str());
    if (loadFitResult) {
      if ( loadPreviousFitResult(myws, FileName, DSTAG, isPbPb, (!isMC && !cutSideBand && loadFitResult==1), loadFitResult==1) ) { skipFit = true; } else { skipFit = false; } 
      if (skipFit) { cout << "[INFO] This mass fit was already done, so I'll load the fit results." << endl; }
      myws.saveSnapshot(Form("%s_parLoad", pdfName.c_str()), *newpars, kTRUE);
    } else if (found) {
      cout << "[INFO] This mass fit was already done, so I'll just go to the next one." << endl;
      return true;
    }

    // Fit the Datasets
    if (skipFit==false) {
      bool isWeighted = myws.data(dsName.c_str())->isWeighted();
      RooFitResult* fitResult(0x0);
      if (doConstrFit)
      {
        cout << "[INFO] Performing constrained fit" << endl;
        
        if (isPbPb) {
          cout << "[INFO] Constrained variables: alpha, n, ratio of sigmas" << endl;
          fitResult = myws.pdf(pdfName.c_str())->fitTo(*myws.data(dsName.c_str()), Extended(kTRUE), SumW2Error(isWeighted), Range(cutSideBand ? parIni["BkgMassRange_FULL_Label"].c_str() : "MassWindow"), ExternalConstraints(RooArgSet(*(myws.pdf("sigmaAlphaConstr")),*(myws.pdf("sigmaNConstr")),*(myws.pdf("sigmaRSigmaConstr")))), NumCPU(numCores), Save());
        }
        else {
          cout << "[INFO] Constrained variables: alpha, n, ratio of sigmas" << endl;
          fitResult = myws.pdf(pdfName.c_str())->fitTo(*myws.data(dsName.c_str()), Extended(kTRUE), SumW2Error(isWeighted), Range(cutSideBand ? parIni["BkgMassRange_FULL_Label"].c_str() : "MassWindow"), ExternalConstraints(RooArgSet(*(myws.pdf("sigmaAlphaConstr")),*(myws.pdf("sigmaNConstr")))), NumCPU(numCores), Save());
        }
      }
      else
      {
       fitResult = myws.pdf(pdfName.c_str())->fitTo(*myws.data(dsName.c_str()), Extended(kTRUE), SumW2Error(isWeighted), Range(cutSideBand ? parIni["BkgMassRange_FULL_Label"].c_str() : "MassWindow"), NumCPU(numCores), Save());
      }
      fitResult->Print("v"); 
      myws.import(*fitResult, Form("fitResult_%s", pdfName.c_str())); 
      // Create the output files
      int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
      drawMassPlot(myws, outputDir, opt, cut, parIni, plotLabel, DSTAG, isPbPb, incJpsi, incPsi2S, incBkg, cutCtau, doSimulFit, wantPureSMC, setLogScale, incSS, zoomPsi, nBins, getMeanPT);
      // Save the results
      string FileName = ""; setMassFileName(FileName, outputDir, DSTAG, plotLabel, cut, isPbPb, cutSideBand);
      myws.saveSnapshot(Form("%s_parFit", pdfName.c_str()), *newpars, kTRUE);
      saveWorkSpace(myws, Form("%smass%s/%s/result", outputDir.c_str(), (cutSideBand?"SB":""), DSTAG.c_str()), FileName);
    }
  }

  return true;
};