示例#1
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));
}
int main(int argc, char* argv[]){
 
  string fileName;
  string fileNameZee;  
  string fileNameout;
  string outDir;
  int ncats;
  int jcats;
  int bins; 
  string outfilename;
  string logfile;
  bool verbose=false;
  int mhLow;
  int mhHigh;

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

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


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

  ofstream logfile_stream(logfile.c_str());    

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

  std::string ext = "8TeV";

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

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


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


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

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

    RooAbsPdf *pdfZee;

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

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

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

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


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

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

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


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

    //print results in log file


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

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

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

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


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

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

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

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

    outputws->import(*bkgPdf);

    }

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


}
示例#3
0
void results2tree(
      const char* workDirName, 
      bool isMC=false,
      const char* thePoiNames="RFrac2Svs1S,N_Jpsi,f_Jpsi,m_Jpsi,sigma1_Jpsi,alpha_Jpsi,n_Jpsi,sigma2_Jpsi,MassRatio,rSigma21_Jpsi,lambda1_Bkg,lambda2_Bkg,lambda3_Bkg,lambda4_Bkg,lambda5__Bkg,N_Bkg"
      ) {
   // workDirName: usual tag where to look for files in Output
   // thePoiNames: comma-separated list of parameters to store ("par1,par2,par3"). Default: all

   TFile *f = new TFile(treeFileName(workDirName,isMC),"RECREATE");
   TTree *tr = new TTree("fitresults","fit results");


   // bin edges
   float ptmin, ptmax, ymin, ymax, centmin, centmax;
   // model names
   Char_t jpsiName[128], psipName[128], bkgName[128];
   // collision system
   Char_t collSystem[8];
   // goodness of fit
   float nll, chi2, normchi2; int npar, ndof;
   // parameters to store: make it a vector
   vector<poi> thePois;
   TString thePoiNamesStr(thePoiNames);
   TString t; Int_t from = 0;
   while (thePoiNamesStr.Tokenize(t, from , ",")) {
      poi p; strcpy(p.name, t.Data());
      cout << p.name << endl;
      thePois.push_back(p);
   }

   // create tree branches
   tr->Branch("ptmin",&ptmin,"ptmin/F");
   tr->Branch("ptmax",&ptmax,"ptmax/F");
   tr->Branch("ymin",&ymin,"ymin/F");
   tr->Branch("ymax",&ymax,"ymax/F");
   tr->Branch("centmin",&centmin,"centmin/F");
   tr->Branch("centmax",&centmax,"centmax/F");
   tr->Branch("jpsiName",jpsiName,"jpsiName/C");
   tr->Branch("psipName",psipName,"psipName/C");
   tr->Branch("bkgName",bkgName,"bkgName/C");
   tr->Branch("collSystem",collSystem,"collSystem/C");
   tr->Branch("nll",&nll,"nll/F");
   tr->Branch("chi2",&chi2,"chi2/F");
   tr->Branch("normchi2",&normchi2,"normchi2/F");
   tr->Branch("npar",&npar,"npar/I");
   tr->Branch("ndof",&ndof,"ndof/I");

   for (vector<poi>::iterator it=thePois.begin(); it!=thePois.end(); it++) {
      tr->Branch(Form("%s_val",it->name),&(it->val),Form("%s_val/F",it->name));
      tr->Branch(Form("%s_err",it->name),&(it->err),Form("%s_err/F",it->name));
   }

   // list of files
   vector<TString> theFiles = fileList(workDirName,"",isMC);

   int cnt=0;
   for (vector<TString>::const_iterator it=theFiles.begin(); it!=theFiles.end(); it++) {
      cout << "Parsing file " << cnt << " / " << theFiles.size() << ": " << *it << endl;

      // parse the file name to get info
      anabin thebin = binFromFile(*it);
      ptmin = thebin.ptbin().low();
      ptmax = thebin.ptbin().high();
      ymin = thebin.rapbin().low();
      ymax = thebin.rapbin().high();
      centmin = thebin.centbin().low();
      centmax = thebin.centbin().high();
      strcpy(collSystem, (it->Index("PbPb")>0) ? "PbPb" : "PP");

      // get the model names
      from = 0;
      bool catchjpsi=false, catchpsip=false, catchbkg=false;
      while (it->Tokenize(t, from, "_")) {
         if (catchjpsi) {strcpy(jpsiName, t.Data()); catchjpsi=false;}
         if (catchpsip) {strcpy(psipName, t.Data()); catchpsip=false;}
         if (catchbkg) {strcpy(bkgName, t.Data()); catchbkg=false;}
         if (t=="Jpsi") catchjpsi=true;
         if (t=="Psi2S") catchpsip=true;
         if (t=="Bkg") catchbkg=true;
      }

      TFile *f = new TFile(*it); RooWorkspace *ws = NULL;
      if (!f) {
         cout << "Error, file " << *it << " does not exist." << endl;
      } else {
         ws = (RooWorkspace*) f->Get("workspace");
         if (!ws) {
            cout << "Error, workspace not found in " << *it << "." << endl;
         }
      }

      nll=0; chi2=0; npar=0; ndof=0;
      if (f && ws) {
         // get the model for nll and npar
         RooAbsPdf *model = pdfFromWS(ws, Form("_%s",collSystem), "pdfMASS_Tot");
         if (model) {
            RooAbsData *dat = dataFromWS(ws, Form("_%s",collSystem), "dOS_DATA");
            if (dat) {
               RooAbsReal *NLL = model->createNLL(*dat);
               if (NLL) nll = NLL->getVal();
               npar = model->getParameters(dat)->selectByAttrib("Constant",kFALSE)->getSize();

               // compute the chi2 and the ndof
               RooPlot* frame = ws->var("invMass")->frame(Bins(nBins));
               dat->plotOn(frame);
               model->plotOn(frame);
               TH1 *hdatact = dat->createHistogram("hdatact", *(ws->var("invMass")), Binning(nBins));
               RooHist *hpull = frame->pullHist(0,0, true);
               double* ypulls = hpull->GetY();
               unsigned int nFullBins = 0;
               for (int i = 0; i < nBins; i++) {
                  if (hdatact->GetBinContent(i+1) > 0.0) {
                     chi2 += ypulls[i]*ypulls[i];
                     nFullBins++;
                  }
               }
               ndof = nFullBins - npar;
               normchi2 = chi2/ndof;
            }
         }

         // get the POIs
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            RooRealVar *thevar = poiFromWS(ws, Form("_%s",collSystem), itpoi->name);
            itpoi->val = thevar ? thevar->getVal() : 0;
            itpoi->err = thevar ? thevar->getError() : 0;
         }

         f->Close();
         delete f;
      } else {
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            itpoi->val = 0;
            itpoi->err = 0;
         }
      }

      // fill the tree
      tr->Fill();
      cnt++;
   } // loop on the files

   f->Write();
   f->Close();
}
int DiagnosisMacro(int Nbins = 10, int Nsigma = 10, int CPUused = 1, TString Filename = "FIT_DATA_Psi2SJpsi_PPPrompt_Bkg_SecondOrderChebychev_pt65300_rap016_cent0200_262620_263757.root", TString Outputdir = "./")
//Nbins: Number of points for which to calculate profile likelihood. Time required is about (1/CPU) minutes per point per parameter. 0 means do plain likelihood only
//Nsigma: The range in which the scan is performed (value-Nsigma*sigma, value+Nsigma*sigma)
//CPUused: anything larger than 1 causes weird fit results on my laptop, runs fine on lxplus with more (16)

{
    // R e a d   w o r k s p a c e   f r o m   f i l e
    // -----------------------------------------------
    // Open input file with workspace

    //Filename = "FIT_DATA_Psi2SJpsi_PP_Jpsi_DoubleCrystalBall_Psi2S_DoubleCrystalBall_Bkg_Chebychev2_pt6590_rap016_cent0200.root";
    //Filename = "FIT_DATA_Psi2SJpsi_PbPb_Jpsi_DoubleCrystalBall_Psi2S_DoubleCrystalBall_Bkg_Chebychev1_pt6590_rap016_cent0200.root";

    TFile *f = new TFile(Filename);
    // Retrieve workspace from file
    RooWorkspace* w = (RooWorkspace*)f->Get("workspace");

    // Retrieve x,model and data from workspace
    RooRealVar* x = w->var("invMass");
    RooAbsPdf* model = w->pdf("simPdf_syst");
    if (model == 0) {
        model = w->pdf("simPdf");
    }
    if (model == 0) {
        model = w->pdf("pdfMASS_Tot_PP");
    }
    if (model == 0) {
        model = w->pdf("pdfMASS_Tot_PbPb");
    }
    if (model == 0) {
        cout << "[ERROR] pdf failed to load from the workspace" << endl;
        return false;
    }

    RooAbsData* data = w->data("dOS_DATA");
    if (data == 0) {
        data = w->data("dOS_DATA_PP");
    }
    if (data == 0) {
        data = w->data("dOS_DATA_PbPb");
    }
    if (data == 0) {
        cout << "[ERROR] data failed to load from the workspace" << endl;
        return false;
    }

    // Print structure of composite p.d.f.
    model->Print("t");

    /*
    // P l o t   m o d e l
    // ---------------------------------------------------------
    // Plot data and PDF overlaid
    RooPlot* xframe = x->frame(Title("J/psi Model and Data"));
    data->plotOn(xframe);
    model->plotOn(xframe);

    // Draw the frame on the canvas
    TCanvas* c2 = new TCanvas("PlotModel", "PlotModel", 1000, 1000);
    gPad->SetLeftMargin(0.15);
    xframe->GetYaxis()->SetTitleOffset(2.0);
    xframe->Draw();//*/

    ///// Check parameters

    RooArgSet* paramSet1 = model->getDependents(data);
    paramSet1->Print("v");  // Just check
    RooArgSet* paramSet2 = model->getParameters(data);
    paramSet2->Print("v");
    int Nparams = paramSet2->getSize();
    cout << "Number of parameters: " << Nparams<<endl<<endl;


    // C o n s t r u c t   p l a i n   l i k e l i h o o d
    // ---------------------------------------------------
    // Construct unbinned likelihood
    RooAbsReal* nll = model->createNLL(*data, NumCPU(CPUused));
    // Minimize likelihood w.r.t all parameters before making plots
    RooMinuit(*nll).migrad();


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

    ///////////////////   L O O P   O V E R   P A R A M E T E R S

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

    /// Set up loop over parameters
    TString ParamName;
    double ParamValue;
    double ParamError;
    double ParamLimitLow;
    double ParamLimitHigh;
    double FitRangeLow;
    double FitRangeHigh;
    RooRealVar* vParam;
    int counter = 0;

    // Loop start
    TIterator* iter = paramSet2->createIterator();
    TObject* var = iter->Next();
    while (var != 0) {
        counter++;
        ParamName = var->GetName();
        vParam = w->var(ParamName);
        ParamValue = vParam->getVal();
        ParamError = vParam->getError();
        ParamLimitLow = vParam->getMin();
        ParamLimitHigh = vParam->getMax();
        cout << ParamName << " has value " << ParamValue << " with error: " << ParamError << " and limits: " << ParamLimitLow << " to " << ParamLimitHigh << endl << endl;

        if (ParamError == 0) {  //Skipping fixed parameters
            cout << "Parameter was fixed, skipping its fitting" << endl;
            cout << endl << "DONE WITH " << counter << " PARAMETER OUT OF " << Nparams << endl << endl;
            var = iter->Next();
            continue;
        }

        // determining fit range: Nsigma sigma on each side unless it would be outside of parameter limits
        if ((ParamValue - Nsigma * ParamError) > ParamLimitLow) {
            FitRangeLow = (ParamValue - Nsigma * ParamError);
        }
        else {
            FitRangeLow = ParamLimitLow;
        }

        if ((ParamValue + Nsigma * ParamError) < ParamLimitHigh) {
            FitRangeHigh = (ParamValue + Nsigma * ParamError);
        }
        else {
            FitRangeHigh = ParamLimitHigh;
        }


        // P l o t    p l a i n   l i k e l i h o o d   a n d   C o n s t r u c t   p r o f i l e   l i k e l i h o o d
        // ---------------------------------------------------
        RooPlot* frame1;
        RooAbsReal* pll=NULL;

        if (Nbins != 0) {
            frame1 = vParam->frame(Bins(Nbins), Range(FitRangeLow, FitRangeHigh), Title(TString::Format("LL and profileLL in %s", ParamName.Data())));
            nll->plotOn(frame1, ShiftToZero());

            pll = nll->createProfile(*vParam);
            // Plot the profile likelihood
            pll->plotOn(frame1, LineColor(kRed), RooFit::Precision(-1));
        }
        else { //Skip profile likelihood
            frame1 = vParam->frame(Bins(10), Range(FitRangeLow, FitRangeHigh), Title(TString::Format("LL and profileLL in %s", ParamName.Data())));
            nll->plotOn(frame1, ShiftToZero());
        }

        // D r a w   a n d   s a v e   p l o t s
        // -----------------------------------------------------------------------

        // Adjust frame maximum for visual clarity
        frame1->SetMinimum(0);
        frame1->SetMaximum(20);

        TCanvas* c = new TCanvas("CLikelihoodResult", "CLikelihoodResult", 800, 600);
        c->cd(1);
        gPad->SetLeftMargin(0.15);
        frame1->GetYaxis()->SetTitleOffset(1.4);
        frame1->Draw();
        TLegend* leg = new TLegend(0.70, 0.70, 0.95, 0.88, "");
        leg->SetFillColor(kWhite);
        leg->SetBorderSize(0);
        leg->SetTextSize(0.035);
        TLegendEntry *le1 = leg->AddEntry(nll, "Plain likelihood", "l");
        le1->SetLineColor(kBlue);
        le1->SetLineWidth(3);
        TLegendEntry *le2 = leg->AddEntry(pll, "Profile likelihood", "l");
        le2->SetLineColor(kRed);
        le2->SetLineWidth(3);
        leg->Draw("same");

        //Save plot
        TString StrippedName = TString(Filename(Filename.Last('/')+1,Filename.Length()));
        StrippedName = StrippedName.ReplaceAll(".root","");
        cout << StrippedName << endl;
        gSystem->mkdir(Form("%s/root/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/root/%s/Likelihood_scan_%s.root", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));
        gSystem->mkdir(Form("%s/pdf/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/pdf/%s/Likelihood_scan_%s.pdf", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));
        gSystem->mkdir(Form("%s/png/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/png/%s/Likelihood_scan_%s.png", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));


        delete c;
        delete frame1;
        if (pll) delete pll;

        cout << endl << "DONE WITH " << counter << " PARAMETER OUT OF " << Nparams << endl << endl;
        //if (counter == 2){ break; } //Exit - for testing
        var = iter->Next();
    }  // End of the loop

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



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

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


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

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



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

  // store results here

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

         params->Print("v");

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

         }
         

    }

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

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



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

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




 

    
  }




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


}