Beispiel #1
0
void MakeSpinPlots::DrawSpinSubTotBackground(TString mcName,bool signal){
  bool drawSM = (smName!="" && smName!=mcName);

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return 0;
}
Beispiel #3
0
void plotContsSingle(TFile *fOUT, std::string dirname, std::string fin, float X, int keepMDM=10){

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	OptionParser(argc,argv);
	

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


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

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

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

              if (datahist) {
	            string zhname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"zh\")",datahist->GetName())); 
	            string whname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"wh\")",datahist->GetName())); 
              RooDataHist *datahistZH = (RooDataHist*) datahist->emptyClone(zhname.c_str(),zhname.c_str());
              RooDataHist *datahistWH = (RooDataHist*) datahist->emptyClone(whname.c_str(),whname.c_str());
                TRandom3 r;
                r.Rndm();
                double x[datahist->numEntries()];
                r.RndmArray(datahist->numEntries(),x);
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistWH->add(*(datahist->get(j)),datahist->weight()*wFrac);
                    datahistZH->add(*(datahist->get(j)),datahist->weight()*zFrac);
                }
              float w =datahistWH->sumEntries();
              float z =datahistZH->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "WH       datahist " << *datahistWH <<std::endl;
              std::cout << "ZH       datahist " << *datahistZH <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : WH " << w/(w+z) <<",   ZH "<< z/(w+z) << std::endl;
              std::cout << "WH fraction (exp) : WH " << wFrac <<",   ZH "<< zFrac << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistWH);
               outWS->import(*datahistZH);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
int main(int argc, char *argv[]){

	OptionParser(argc,argv);
	

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


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

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

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

              if (datahist) {
              RooDataHist *datahistOUT = (RooDataHist*) datahist->emptyClone(datahist->GetName(),datahist->GetName());
                TRandom3 r;
                r.Rndm();
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistOUT->add(*(datahist->get(j)),datahist->weight());
                }
              float w =datahistOUT->sumEntries();
              float z =datahist->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "Reduced  datahist " << *datahistOUT<<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : " << w/(z) <<std::endl;
              std::cout << "WH fraction (exp) : " << fraction_ << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistOUT);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
Beispiel #6
0
void fitPtOverMCJLST(int mass = 125, int LHCsqrts = 7, int whichtype = 1, 
		     bool correctErrors = false, /* string changeParName = "", */
		     bool showErrorPDFs = false, string systString = "Default")

// whichtype
// 0 - gg Signal
// 1 - VBF Signal
// 2 - ZZ
// 3 - ZX
// 4 - ggZZ
// 5 - WH
// 6 - ZH
// 7 - ttH

{

  string changeParName = "";
  if (systString == "Default") changeParName = "up";

  string nameSample[8] = {"gg","vbf","zz","zx","ggzz","wh","zh","tth"};
  float maxType[8] = {2.4,3.2,1.6,1.6,1.6,3.2,3.2,3.2};   
  float rebinType[8] = {1,2,1,1,4,10,10,40};
  
  for (int t = 0; t < 8; t++) {
    if (mass > 150) maxType[t] = int(117.90*maxType[t]/sqrt(mass-10.91))/10.;
  }

  char fileToOpen[200];
  sprintf(fileToOpen,"selRootFiles/PToverM_%s%d_SEL_%dTeV.root",nameSample[whichtype].c_str(),mass,LHCsqrts);
  // if (whichtype == 3) sprintf(fileToOpen,"PTOVERM_%s_SEL_allTeV.root",nameSample[whichtype].c_str());

  RooRealVar* ptoverm = new RooRealVar("ptoverm","p_{T}/M^{4l}",0.,maxType[whichtype],"GeV/c");
 
  TFile input(fileToOpen);
  // if (systString == "Mass" || systString == "Mela") {
  //  sprintf(fileToOpen,"ptovermH_%sUp",systString.c_str());
  // } else {
  sprintf(fileToOpen,"ptovermH_%s",systString.c_str());
  //}
  TH1F* ptovermH = (TH1F*)input.Get(fileToOpen);
  
  if (rebinType[whichtype] > 1) ptovermH->Rebin(rebinType[whichtype]);
  if (maxType[whichtype] < ptovermH->GetBinLowEdge(ptovermH->GetNbinsX() + 1) - ptovermH->GetBinWidth(1)) {
    int theBin = ptovermH->FindBin(maxType[whichtype]);
    ptovermH->GetXaxis()->SetRange(1,theBin-1);
  }

  gROOT->ProcessLine(".L mytdrstyle.C");
  gROOT->ProcessLine("setTDRStyle()");
  
  // cout << endl << "Signal " << endl;   
  ptoverm->setBins(ptovermH->GetNbinsX());

  RooDataHist* rdh = new RooDataHist("rdh","Some dataset",RooArgList(*ptoverm),Import(*ptovermH,kFALSE));
 
  // fit definitions
  // RooWorkspace *ws = new RooWorkspace("ws");

  RooRealVar m("m","emme", 1.,0.01, 40.);
  RooRealVar n("n","enne", 0.93, 0.05, 15.);
  RooRealVar n2("n2","enne2", 0.75, 0.5, 15.);
  RooRealVar bb("bb","bibi",0.02, 0.000005, 20.0);
  RooRealVar T("T","tti",0.2,0.00000005,1.);
  RooRealVar bb2("bb2","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexp("fexp","f_exp",0.02, 0.0, 1.0);
  if (whichtype == 0) {
    if (LHCsqrts == 8) {
      m.setVal(3.319);   // m.setConstant(kTRUE);
      n.setVal(0.7606);    if (systString != "Default" || mass != 125) n.setConstant(kTRUE); 
      n2.setVal(0.8061);   n2.setConstant(kTRUE);
      bb.setVal(3.728);   // bb.setConstant(kTRUE);
      T.setVal(0.00333);   // T.setConstant(kTRUE);
      bb2.setVal(1.7172);    // bb2.setConstant(kTRUE);
      fexp.setVal(0.002144);   if (systString != "Default" || mass != 125) fexp.setConstant(kTRUE);
    } else {
      m.setVal(0.061);   // m.setConstant(kTRUE);
      n.setVal(1.6141);   if (systString == "Resummation" || systString == "TopMass")  n.setConstant(kTRUE);
      n2.setVal(1.3294);   n2.setConstant(kTRUE);
      bb.setVal(4.2761);   // bb.setConstant(kTRUE);
      T.setVal(0.0361);   // T.setConstant(kTRUE);
      bb2.setVal(1.6643);   bb2.setConstant(kTRUE);
      fexp.setVal(0.0004);   // fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 1) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);   n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.02048);   bb.setConstant(kTRUE);
    T.setVal(0.16115);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE); // T.setConstant(kTRUE);
    bb2.setVal(1.0024);   bb2.setConstant(kTRUE);
    fexp.setVal(0.005);   fexp.setConstant(kTRUE);
    if (mass > 300) {
      fexp.setVal(0.0);   fexp.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb2.setVal(5.0);  //  bb2.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb.setVal(15.0);  //  bb.setConstant(kFALSE);
    }
  } else if (whichtype == 2) {
    if (LHCsqrts == 8) {
      m.setVal(1.0476);   // m.setConstant(kTRUE);    
      bb.setVal(3.3088);  // if (mass != 140) bb.setConstant(kTRUE);
      n2.setVal(0.7146);   n2.setConstant(kTRUE);
      n.setVal(0.9518);      n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.0021889);    if (systString.find("Mela") != string::npos || mass != 140) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    } else {
      m.setVal(1.028);   // m.setConstant(kTRUE);    
      bb.setVal(2.91); // bb.setConstant(kTRUE);
      n2.setVal(0.7146);  n2.setConstant(kTRUE);
      n.setVal(0.9518);     n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.002248);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 3) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(3.4523);     n.setConstant(kTRUE);
    n2.setVal(0.6910);    n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 4) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(5.756);    // n.setConstant(kTRUE);
    n2.setVal(0.8738);   // n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 5 && LHCsqrts == 8) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(3.897);   bb.setConstant(kTRUE);
    T.setVal(0.1009);  // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  } else {
    // cout << "Entro qui" << endl;
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.0129);  bb.setConstant(kTRUE);
    T.setVal(0.1009);    // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  }
 
  
  RooModifTsallis* rt3 = new RooModifTsallis("rt3","rt3",*ptoverm,m,n,n2,bb,bb2,T,fexp);
  // ws->import(*rt3);

  // fit
  RooFitResult* fit = rt3->fitTo(*rdh,Minos(0),Save(1),SumW2Error(kTRUE),NumCPU(1));  

  float mVal = m.getVal();   
  float nVal = n.getVal();
  float n2Val = n2.getVal();
  float bbVal = bb.getVal();
  float bb2Val = bb2.getVal();
  float fexpVal = fexp.getVal();
  float TVal = T.getVal();

  if (correctErrors) {
    // Tsallis errors not reliable, use toy MC

    TH1F* mHist = new TH1F("mHist","m",21,-0.5*mVal,0.5*mVal);
    TH1F* nHist = new TH1F("nHist","n",21,-0.2*nVal,0.2*nVal);
    TH1F* n2Hist = new TH1F("n2Hist","n2",21,-0.2*n2Val,0.2*n2Val);
    TH1F* bbHist = new TH1F("bbHist","bb",21,-0.2*bbVal,0.2*bbVal);
    TH1F* bb2Hist = new TH1F("bb2Hist","bb2",21,-0.2*bb2Val,0.2*bb2Val);
    TH1F* fexpHist = new TH1F("fexpHist","fexp",21,-0.2*fexpVal-0.000001,0.2*fexpVal+0.000001);
    TH1F* THist = new TH1F("THist","T",21,-0.5*TVal,0.5*TVal);
    mHist->GetXaxis()->SetTitle("m-m_{gen}");
    nHist->GetXaxis()->SetTitle("n-n_{gen}");
    n2Hist->GetXaxis()->SetTitle("n2-n2_{gen}");
    bbHist->GetXaxis()->SetTitle("bb-bb_{gen}");
    bb2Hist->GetXaxis()->SetTitle("bb2-bb2_{gen}");
    THist->GetXaxis()->SetTitle("T-T_{gen}");
    fexpHist->GetXaxis()->SetTitle("fexp-fexp_{gen}");

    for (unsigned int iToy = 0; iToy < 200; iToy++) {

      cout << endl << "####" << endl;
      cout << "Generating toy experiment n. " << iToy+1 << endl;

      m.setVal(mVal);
      n.setVal(nVal);
      n2.setVal(n2Val);
      bb.setVal(bbVal);
      bb2.setVal(bb2Val);
      fexp.setVal(fexpVal);
      T.setVal(TVal);

      TDatime *now = new TDatime();
      Int_t seed = now->GetDate() + now->GetTime();
      cout << "RooFit Generation Seed = " << seed+iToy << endl;
      RooRandom::randomGenerator()->SetSeed(seed+iToy);
      cout << "####" << endl << endl;

      RooDataSet *dataToy = rt3->generate(RooArgSet(*ptoverm),ptovermH->GetEntries());
      RooDataHist *dataToyH = new RooDataHist("dataToyH","toy",RooArgSet(*ptoverm),*dataToy);
      
      rt3->fitTo(*dataToyH,Minos(0),SumW2Error(kTRUE),NumCPU(1));  
  
      if (fit->floatParsFinal().find("m")) mHist->Fill(m.getVal()-mVal);
      if (fit->floatParsFinal().find("n")) nHist->Fill(n.getVal()-nVal);
      if (fit->floatParsFinal().find("n2")) n2Hist->Fill(n2.getVal()-n2Val);
      if (fit->floatParsFinal().find("bb")) bbHist->Fill(bb.getVal()-bbVal);
      if (fit->floatParsFinal().find("bb2")) bb2Hist->Fill(bb2.getVal()-bb2Val);
      if (fit->floatParsFinal().find("fexp")) fexpHist->Fill(fexp.getVal()-fexpVal);
      if (fit->floatParsFinal().find("T")) THist->Fill(T.getVal()-TVal);
    }

    TCanvas cant("cant","Test canvas",5.,5.,900.,500.);
    cant.Divide(4,2);
    cant.cd(1);   mHist->Draw();
    cant.cd(2);   nHist->Draw();
    cant.cd(3);   n2Hist->Draw();
    cant.cd(4);   bbHist->Draw();
    cant.cd(5);   bb2Hist->Draw();
    cant.cd(6);   fexpHist->Draw();
    cant.cd(7);   THist->Draw();
    // cant.SaveAs("figs/testToys.pdf");
    cant.SaveAs("newfigs/testToys.pdf");

    if (fit->floatParsFinal().find("m")) m.setError(mHist->GetRMS());
    if (fit->floatParsFinal().find("n")) n.setError(nHist->GetRMS());
    if (fit->floatParsFinal().find("n2")) n2.setError(n2Hist->GetRMS());
    if (fit->floatParsFinal().find("bb")) bb.setError(bbHist->GetRMS());
    if (fit->floatParsFinal().find("bb2")) bb2.setError(bb2Hist->GetRMS());
    if (fit->floatParsFinal().find("fexp")) fexp.setError(fexpHist->GetRMS());
    if (fit->floatParsFinal().find("T")) T.setError(THist->GetRMS());
  }

  m.setVal(mVal);
  n.setVal(nVal);
  n2.setVal(n2Val);
  bb.setVal(bbVal);
  bb2.setVal(bb2Val);
  fexp.setVal(fexpVal);
  T.setVal(TVal);

  char fileToSave[200];
  // if (changeParName != "") 
  //  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s_%dTeV_%s_%s.txt",nameSample[whichtype].c_str(),LHCsqrts,systString.c_str(),changeParName.c_str()); 
  // else 
  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_%s.txt",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  ofstream os1(fileToSave);
  if (changeParName != "") {
    sprintf(fileToSave,"m%s",changeParName.c_str());  m.SetName(fileToSave);
    sprintf(fileToSave,"n%s",changeParName.c_str());  n.SetName(fileToSave);
    sprintf(fileToSave,"n2%s",changeParName.c_str());  n2.SetName(fileToSave);
    sprintf(fileToSave,"bb%s",changeParName.c_str());  bb.SetName(fileToSave);
    sprintf(fileToSave,"bb2%s",changeParName.c_str());  bb2.SetName(fileToSave);
    sprintf(fileToSave,"fexp%s",changeParName.c_str());  fexp.SetName(fileToSave);
    sprintf(fileToSave,"T%s",changeParName.c_str());  T.SetName(fileToSave);
  }
  (RooArgSet(m,n,n2,bb,bb2,fexp,T)).writeToStream(os1,false);
  os1.close();

  RooRealVar mup("mup","emme", 1.,0.01, 30.);
  RooRealVar nup("nup","enne", 0.93, 0.5, 15.);
  RooRealVar n2up("n2up","enne2", 0.75, 0.5, 15.);
  RooRealVar bbup("bbup","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tup("Tup","tti",0.2,0.00000005,1.);
  RooRealVar bb2up("bb2up","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpup("fexpup","f_exp",0.02, 0.0, 1.0);
 
  RooModifTsallis* rt3up = new RooModifTsallis("rt3up","rt3up",*ptoverm,mup,nup,n2up,bbup,bb2up,Tup,fexpup);
  // ws->import(*rt3up);
 
  RooRealVar mdown("mdown","emme", 1.,0.01, 30.);
  RooRealVar ndown("ndown","enne", 0.93, 0.5, 15.);
  RooRealVar n2down("n2down","enne2", 0.75, 0.5, 15.);
  RooRealVar bbdown("bbdown","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tdown("Tdown","tti",0.2,0.00000005,1.);
  RooRealVar bb2down("bb2down","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpdown("fexpdown","f_exp",0.02, 0.0, 1.0);

  RooModifTsallis* rt3down = new RooModifTsallis("rt3down","rt3down",*ptoverm,mdown,ndown,n2down,bbdown,bb2down,Tdown,fexpdown);
  // ws->import(*rt3down);

  RooPlot *frame = ptoverm->frame();

  char reducestr[300];
  sprintf(reducestr,"ptoverm > %f && ptoverm < %f",ptoverm->getMin(),ptoverm->getMax());
  
  rdh->plotOn(frame,DataError(RooAbsData::SumW2),Cut(reducestr));
  static RooHist *hpull;
  float chi2 = 0.;

  if (changeParName == "") {
    sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_Default.txt",nameSample[whichtype].c_str(),mass,LHCsqrts);
    ifstream is1(fileToSave);
    (RooArgSet(mup,nup,n2up,bbup,bb2up,fexpup,Tup)).readFromStream(is1,false);

    mdown.setVal(fabs(3*mup.getVal() - 2*m.getVal()));
    ndown.setVal(fabs(3*nup.getVal() - 2*n.getVal()));
    n2down.setVal(fabs(3*n2up.getVal() - 2*n2.getVal()));
    bbdown.setVal(fabs(3*bbup.getVal() - 2*bb.getVal()));
    Tdown.setVal(fabs(3*Tup.getVal() - 2*T.getVal()));
    bb2down.setVal(fabs(3*bb2up.getVal() - 2*bb2.getVal()));
    fexpdown.setVal(fabs(3*fexpup.getVal() - 2*fexp.getVal()));

    if (showErrorPDFs) {
      rt3->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
      rt3up->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      if (systString.find("Mela") == string::npos) rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    } else {
      rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
    }
  } else {
    mup.setVal(m.getVal() + m.getError());   cout << "mup = " << mup.getVal() << endl;
    nup.setVal(n.getVal() + n.getError());
    n2up.setVal(n2.getVal() + n2.getError());
    bbup.setVal(bb.getVal() + bb.getError());
    Tup.setVal(T.getVal() + T.getError());
    bb2up.setVal(bb2.getVal() + bb2.getError());
    fexpup.setVal(fexp.getVal() + fexp.getError());

    mdown.setVal(m.getVal() - m.getError());  cout << "mdown = " << mdown.getVal() << endl;
    ndown.setVal(n.getVal() - n.getError());
    n2down.setVal(n2.getVal() - n2.getError());
    bbdown.setVal(bb.getVal() - bb.getError());
    Tdown.setVal(T.getVal() - T.getError());
    bb2down.setVal(bb2.getVal() - bb2.getError());
    fexpdown.setVal(fexp.getVal() - fexp.getError());

    rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    hpull = frame->pullHist();
    if (showErrorPDFs) {
      rt3up->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    }
  }

  double *ypulls = hpull->GetY();
  unsigned int nBins = rdh->numEntries();
  unsigned int nFullBins = 0;
  for (unsigned int i = 0; i < nBins; i++) {
    cout << "Pull of bin " << i << " = " << ypulls[i] << endl;
    if (fabs(ypulls[i]) < 5.0) chi2 += ypulls[i]*ypulls[i]; 
    cout << "Partial chi2 = " << chi2 << endl;
    if (fabs(ypulls[i]) > 0.0001 && fabs(ypulls[i]) < 5.0) nFullBins++;
  }
  for (unsigned int i = 0; i < nBins; i++) {
    if (fabs(ypulls[i]) < 0.0001) ypulls[i] = 999.; 
    hpull->SetPointError(i,0.,0.,0.,0.);
  } 
  int nFitPar = fit->floatParsFinal().getSize() - 1;

  TCanvas can("can","The canvas",5.,5.,500.,900.); 
  can.Divide(1,3);

  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextAlign(22);
  t->SetTextSize(0.06);

  can.cd(1);
  gPad->SetBottomMargin(0.0);
  frame->Draw();
  // gPad->SetLogy(); 
  // Htest->Draw();
  sprintf(fileToSave,"%s %d GeV at %d TeV",nameSample[whichtype].c_str(),mass,LHCsqrts);
  t->DrawLatex(0.6,0.8,fileToSave); 

  can.cd(2);
  gPad->SetLogy(); 
  gPad->SetTopMargin(0.0);
  frame->Draw();
 
  RooPlot* pull = ptoverm->frame(Title("Pull Distribution")) ;
  pull->GetYaxis()->SetTitle("Pull");
  /* pull->SetLabelSize(0.08,"XYZ");
  pull->SetTitleSize(0.08,"XYZ");
  pull->SetTitleOffset(0.6,"Y");
  pull->SetTitleOffset(1.0,"X"); */
  pull->addPlotable(hpull,"P") ; 
  pull->SetMinimum(-6.); 
  pull->SetMaximum(6.); 

  can.cd(3);
  gPad->SetGridy();
  pull->Draw();
  sprintf(fileToSave,"#chi^{2}/n_{DoF} = %4.1f/%d",chi2,nFullBins - nFitPar);
  if (chi2 < 1000.) t->DrawLatex(0.80,0.86,fileToSave);

  // sprintf(fileToSave,"figs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  sprintf(fileToSave,"newfigs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  can.SaveAs(fileToSave);

}
int main(){
  
  system("mkdir -p plots");
  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  TFile *bkgFile = TFile::Open("comb_svn/hgg.inputbkgdata_8TeV_MVA.root");
  TFile *sigFile = TFile::Open("comb_svn/hgg.inputsig_8TeV_nosplitVH_MVA.root");
  RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get("cms_hgg_workspace");
  RooWorkspace *sigWS = (RooWorkspace*)sigFile->Get("wsig_8TeV");

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

  mass->setBins(320);
  cout << mass->getBins() << endl;
  RooDataSet *dataAll;
  
  int firstCat=1;
  int lastCat=1;
  float mu_low=-1.;
  float mu_high=3.;
  float mu_step=0.01;

  vector<pair<double,TGraph*> > minNlltrack;

  for (int cat=firstCat; cat<=lastCat; cat++){
    RooDataSet *data = (RooDataSet*)bkgWS->data(Form("data_mass_cat%d",cat));
    if (cat==firstCat) dataAll = (RooDataSet*)data->Clone("data_mass_all");
    else dataAll->append(*data);
    RooDataHist *dataBinned = new RooDataHist(Form("roohist_data_mass_cat%d",cat),Form("roohist_data_mass_cat%d",cat),RooArgSet(*mass),*data);
    RooDataSet *sigMC = (RooDataSet*)sigWS->data(Form("sig_mass_m125_cat%d",cat));

    if (!dataBinned || !sigMC){
      cerr << "ERROR -- one of data or signal is NULL" << endl;
      exit(1);
    }
    
    // Construct PDFs for this category using PdfModelBuilder
    PdfModelBuilder modelBuilder;
    modelBuilder.setObsVar(mass);
    modelBuilder.setSignalModifier(mu);
    // For Standard Analysis
    //if (cat>=0 && cat<=3) modelBuilder.addBkgPdf("Bernstein",5,Form("pol5_cat%d",cat));
    //if (cat>=4 && cat<=5) modelBuilder.addBkgPdf("Bernstein",4,Form("pol4_cat%d",cat));
    //if (cat>=6 && cat<=8) modelBuilder.addBkgPdf("Bernstein",3,Form("pol3_cat%d",cat));
    // To Profile Multiple PDFs
    if (cat==0 || cat==1 || cat==2 || cat==3){
      modelBuilder.addBkgPdf("Bernstein",4,Form("pol4_cat%d",cat));
      modelBuilder.addBkgPdf("Bernstein",5,Form("pol5_cat%d",cat));
      modelBuilder.addBkgPdf("Bernstein",6,Form("pol6_cat%d",cat));
      /*
      modelBuilder.addBkgPdf("PowerLaw",1,Form("pow1_cat%d",cat));
      modelBuilder.addBkgPdf("PowerLaw",3,Form("pow3_cat%d",cat));
      modelBuilder.addBkgPdf("PowerLaw",5,Form("pow5_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",1,Form("exp1_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",3,Form("exp3_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",5,Form("exp5_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",1,Form("lau1_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",3,Form("lau3_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",5,Form("lau5_cat%d",cat));
      */
    }
    if (cat==4 || cat==5 || cat==6 || cat==7 || cat==8) {
      modelBuilder.addBkgPdf("Bernstein",3,Form("pol3_cat%d",cat));
      modelBuilder.addBkgPdf("Bernstein",4,Form("pol4_cat%d",cat));
      /*
      modelBuilder.addBkgPdf("PowerLaw",1,Form("pow1_cat%d",cat));
      modelBuilder.addBkgPdf("PowerLaw",3,Form("pow3_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",1,Form("exp1_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",3,Form("exp3_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",1,Form("lau1_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",3,Form("lau3_cat%d",cat));
      */
    }
    map<string,RooAbsPdf*> bkgPdfs = modelBuilder.getBkgPdfs();
    modelBuilder.setSignalPdfFromMC(sigMC);
    modelBuilder.makeSBPdfs();
    map<string,RooAbsPdf*> sbPdfs = modelBuilder.getSBPdfs();

    modelBuilder.fitToData(dataBinned,true,true);
    modelBuilder.fitToData(dataBinned,false,true);

    modelBuilder.throwToy(Form("cat%d_toy0",cat),dataBinned->sumEntries(),true,true);

    // Profile this category using ProfileMultiplePdfs
    ProfileMultiplePdfs profiler;
    for (map<string,RooAbsPdf*>::iterator pdf=sbPdfs.begin(); pdf!=sbPdfs.end(); pdf++) {
      string bkgOnlyName = pdf->first.substr(pdf->first.find("sb_")+3,string::npos);
      if (bkgPdfs.find(bkgOnlyName)==bkgPdfs.end()){
        cerr << "ERROR -- couldn't find bkg only pdf " << bkgOnlyName << " for SB pdf " << pdf->first << endl;
        pdf->second->fitTo(*dataBinned);
        exit(1);
      }
      int nParams = bkgPdfs[bkgOnlyName]->getVariables()->getSize()-1;
      profiler.addPdf(pdf->second,2*nParams);
      //profiler.addPdf(pdf->second);
      cout << pdf->second->GetName() << " nParams=" << pdf->second->getVariables()->getSize() << " nBkgParams=" << nParams << endl;
    }
    profiler.printPdfs();
    //cout << "Continue?" << endl;
    //string bus; cin >> bus;
    profiler.plotNominalFits(dataBinned,mass,80,Form("cat%d",cat));
    pair<double,map<string,TGraph*> > minNlls = profiler.profileLikelihood(dataBinned,mass,mu,mu_low,mu_high,mu_step);
    pair<double,map<string,TGraph*> > correctedNlls = profiler.computeEnvelope(minNlls,Form("cat%d",cat),2.);
    minNlltrack.push_back(make_pair(correctedNlls.first,correctedNlls.second["envelope"]));
    //minNlls.second.insert(pair<string,TGraph*>("envelope",envelopeNll.second));
    //map<string,TGraph*> minNLLs = profiler.profileLikelihoodEnvelope(dataBinned,mu,mu_low,mu_high,mu_step);
    profiler.plot(correctedNlls.second,Form("cat%d_nlls",cat));
    //profiler.print(minNLLs,mu_low,mu_high,mu_step);
    /*
    if (minNLLs.find("envelope")==minNLLs.end()){
      cerr << "ERROR -- envelope TGraph not found in minNLLs" << endl;
      exit(1);
    }
    */
    //minNlltrack.push_back(make_pair(profiler.getGlobalMinNLL(),minNLLs["envelope"]));
  }
  //exit(1);
  TGraph *comb = new TGraph();
  for (vector<pair<double,TGraph*> >::iterator it=minNlltrack.begin(); it!=minNlltrack.end(); it++){
    if (it->second->GetN()!=minNlltrack.begin()->second->GetN()){
      cerr << "ERROR -- unequal number of points for TGraphs " << it->second->GetName() << " and " << minNlltrack.begin()->second->GetName() << endl;
      exit(1);
    }
  }
  for (int p=0; p<minNlltrack.begin()->second->GetN(); p++){
    double x,y,sumy=0;
    for (vector<pair<double,TGraph*> >::iterator it=minNlltrack.begin(); it!=minNlltrack.end(); it++){
      it->second->GetPoint(p,x,y);
      sumy += (y+it->first);
    }
    comb->SetPoint(p,x,sumy);
  }
  pair<double,double> globalMin = getGraphMin(comb);
  for (int p=0; p<comb->GetN(); p++){
    double x,y;
    comb->GetPoint(p,x,y);
    comb->SetPoint(p,x,y-globalMin.second);
  }
  vector<double> fitVal = getValsFromLikelihood(comb);

  cout << "Best fit.." << endl;
  cout << "\t mu = " << Form("%4.3f",fitVal[0]) << " +/- (1sig) = " << fitVal[2]-fitVal[0] << " / " << fitVal[0]-fitVal[1] << endl;
  cout << "\t      " << "    " << " +/- (2sig) = " << fitVal[4]-fitVal[0] << " / " << fitVal[0]-fitVal[3] << endl;

  cout << comb->Eval(fitVal[0]) << " " << comb->Eval(fitVal[1]) << " " << comb->Eval(fitVal[2]) << " " << comb->Eval(fitVal[3]) << " " << comb->Eval(fitVal[4]) << endl;

  double quadInterpVal = ProfileMultiplePdfs::quadInterpMinimum(comb);
  cout << "quadInterp: mu = " << quadInterpVal << endl;
  cout << "\t " << comb->Eval(quadInterpVal) << " " << comb->Eval(quadInterpVal-0.005) << " " << comb->Eval(quadInterpVal-0.01) << " " << comb->Eval(quadInterpVal+0.005) << " " << comb->Eval(quadInterpVal+0.01) << endl;
  
  comb->SetLineWidth(2);
  TCanvas *canv = new TCanvas();
  comb->Draw("ALP");
  canv->Print("plots/comb.pdf");
  TFile *tempOut = new TFile("tempOut.root","RECREATE");
  tempOut->cd();
  comb->SetName("comb");
  comb->Write();
  tempOut->Close();
  return 0;
}