コード例 #1
0
/*
 * Prepares the workspace to be used by the hypothesis test calculator
 */
void workspace_preparer(char *signal_file_name, char *signal_hist_name_in_file, char *background_file_name, char *background_hist_name_in_file, char *data_file_name, char *data_hist_name_in_file, char *config_file, char *workspace_name){

  // Include the config_reader class.
  TString path = gSystem->GetIncludePath();
  path.Append(" -I/home/max/cern/cls/mario");//why does this work?
  gSystem->SetIncludePath(path);
  gROOT->LoadMacro("config_reader.cxx");

  // RooWorkspace used to store values.
  RooWorkspace * pWs = new RooWorkspace("ws");

  // Create a config_reader (see source for details) to read the config
  // file.
  config_reader reader(config_file, pWs);

  // Read MR and RR bounds from the config file.
  double MR_lower = reader.find_double("MR_lower");
  double MR_upper = reader.find_double("MR_upper");
  double RR_lower = reader.find_double("RR_lower");
  double RR_upper = reader.find_double("RR_upper");
  double MR_initial = (MR_lower + MR_upper)/2;
  double RR_initial = (RR_lower + RR_upper)/2;

  // Define the Razor Variables 
  RooRealVar MR = RooRealVar("MR", "MR", MR_initial, MR_lower, MR_upper);
  RooRealVar RR = RooRealVar("RSQ", "RSQ", RR_initial, RR_lower, RR_upper);

  // Argument lists 
  RooArgList pdf_arg_list(MR, RR, "input_args_list");
  RooArgSet pdf_arg_set(MR, RR, "input_pdf_args_set");



  /***********************************************************************/
  /* PART 1: IMPORTING SIGNAL AND BACKGROUND HISTOGRAMS                  */
  /***********************************************************************/

  /*
   * Get the signal's unextended pdf by converting the TH2D in the file
   * into a RooHistPdf
   */
  TFile *signal_file = new TFile(signal_file_name);
  TH2D *signal_hist = (TH2D *)signal_file->Get(signal_hist_name_in_file);
  RooDataHist *signal_RooDataHist = new RooDataHist("signal_roodatahist",
                                                    "signal_roodatahist", 
                                                    pdf_arg_list, 
                                                    signal_hist);

  RooHistPdf *unextended_sig_pdf = new RooHistPdf("unextended_sig_pdf", 
                                                  "unextended_sig_pdf", 
                                                  pdf_arg_set, 
                                                  *signal_RooDataHist);

  /* 
   * Repeat this process for the background.
   */
  TFile *background_file = new TFile(background_file_name);
  TH2D *background_hist = 
    (TH2D *)background_file->Get(background_hist_name_in_file);
  RooDataHist *background_RooDataHist = 
    new RooDataHist("background_roodatahist", "background_roodatahist", 
                    pdf_arg_list, background_hist);
  RooHistPdf *unextended_bkg_pdf = new RooHistPdf("unextended_bkg_pdf", 
                                                  "unextended_bkg_pdf", 
                                                  pdf_arg_set, 
                                                  *background_RooDataHist);

  /*
   * Now, we want to create the bprime variable, which represents the
   * integral over the background-only sample.  We will perform the
   * integral automatically (that's why this is the only nuisance
   * parameter declared in this file - its value can be determined from
   * the input histograms).
   */
  ostringstream bprime_string;

  double integral = background_hist->Integral();
  double low_tolerance = .8 * integral;//1.3 * integral;
  double high_tolerance = 1.2 * integral;//.7 * integral;

  double nom_val = integral + 1;
  double low_nom = ((low_tolerance / integral) * nom_val);
  double high_nom = ((high_tolerance / integral) * nom_val);

  // Make a poisson in prime_bprime and nom_bprime
  //bprime_string << "Poisson::bprime_pdf(nom_bprime[" <<  integral << "," << (integral - 1) << "," << (integral + 1) << "], prime_bprime[" << integral << "," << (low_tolerance)  << "," << (high_tolerance)  << "])";
  bprime_string << "Gamma::bprime_pdf(prime_bprime[" << integral << "," << low_tolerance << "," << high_tolerance << "], nom_bprime[" << nom_val << "," << low_nom << "," << high_nom << "], 1, 0)";

  cout << endl << endl << endl << endl << bprime_string.str() << endl << endl;

  pWs->factory(bprime_string.str().c_str());


  /* 
   * This simple command will create all values from the config file
   * with 'make:' at the beginning and a delimiter at the end (see config
   * _reader if you don't know what a delimiter is).  In other
   * words, the luminosity, efficiency, transfer factors, and their pdfs
   * are created from this command.  The declarations are contained in the
   * config file to be changed easily without having to modify this code.
   */
  reader.factory_all();


  /* 
   * Now, we want to create the extended pdfs from the unextended pdfs, as
   * well as from the S and B values we manufactured in the config file.
   * S and B are the values by which the signal and background pdfs,
   * respectively, are extended.  Recall that they were put in the
   * workspace in the reader.facotry_all() command.
   */
  RooAbsReal *S = pWs->function("S");
  RooAbsReal *B = pWs->function("B");
  
  RooExtendPdf *signalpart = new RooExtendPdf("signalpart", "signalpart",
                                              *unextended_sig_pdf, *S);
  RooExtendPdf *backgroundpart = 
    new RooExtendPdf("backgroundpart", "backgroundpart", 
                     *unextended_bkg_pdf, *B);

  RooArgList *pdf_list = new RooArgList(*signalpart, *backgroundpart, 
                                        "list");
  // Add the signal and background pdfs to make a TotalPdf
  RooAddPdf *TotalPdf = new RooAddPdf("TotalPdf", "TotalPdf", *pdf_list);
  
  RooArgList *pdf_prod_list = new RooArgList(*TotalPdf, 
                                             *pWs->pdf("lumi_pdf"),
                                             *pWs->pdf("eff_pdf"),
                                             *pWs->pdf("rho_pdf"),
                                             *pWs->pdf("bprime_pdf"));
  // This creates the final model pdf.
  RooProdPdf *model = new RooProdPdf("model", "model", *pdf_prod_list);

  /*
   * Up until now, we have been using the workspace pWs to contain all of
   * our values.  Now, all of our values that we require are in use in the
   * RooProdPdf called "model".  So, we need to import "model" into a 
   * RooWorkspace.  To avoid recopying values into the rooworkspace, when
   * the values may already be present (which can cause problems), we will
   * simply create a new RooWorkspace to avoid confusion and problems.  The
   * new RooWorkspace is created here.
   */
  RooWorkspace *newworkspace = new RooWorkspace("newws");
  newworkspace->import(*model);

  // Immediately delete pWs, so we don't accidentally use it again.
  delete pWs;

  // Show off the newworkspace
  newworkspace->Print();

  // observables
  RooArgSet obs(*newworkspace->var("MR"), *newworkspace->var("RSQ"), "obs");

  // global observables
  //RooArgSet globalObs(*newworkspace->var("nom_lumi"), *newworkspace->var("nom_eff"), *newworkspace->var("nom_rho"), *newworkspace->var("nom_bprime"));
  RooArgSet globalObs(*newworkspace->var("nom_lumi"), *newworkspace->var("nom_eff"), *newworkspace->var("nom_rho"), *newworkspace->var("nom_bprime"), "global_obs");

  //fix global observables to their nominal values
  newworkspace->var("nom_lumi")->setConstant();
  newworkspace->var("nom_eff")->setConstant();
  newworkspace->var("nom_rho")->setConstant();
  newworkspace->var("nom_bprime")->setConstant();//Do this?  probs fine.

  //Set Parameters of interest
  RooArgSet poi(*newworkspace->var("sigma"), "poi");  


  //Set Nuisances

  RooArgSet nuis(*newworkspace->var("prime_lumi"), *newworkspace->var("prime_eff"), *newworkspace->var("prime_rho"), *newworkspace->var("prime_bprime"));

  // priors (for Bayesian calculation)
  //newworkspace->factory("Uniform::prior_signal(sigma)"); // for parameter of interest
  //newworkspace->factory("Uniform::prior_bg_b(prime_bprime)"); // for data driven nuisance parameter
  //newworkspace->factory("PROD::prior(prior_signal,prior_bg_b)"); // total prior


  //Observed data is pulled from histogram.
  /*TFile *data_file = new TFile(data_file_name);
  TH2D *data_hist = (TH2D *)data_file->Get(data_hist_name_in_file);
  RooDataHist *pData = new RooDataHist("data", "data", obs, data_hist);
  newworkspace->import(*pData);*/

  // Now, we will draw our data from a RooDataHist.
  TFile *data_file = new TFile(data_file_name);
  //TTree *data_tree = (TTree *) data_file->Get(data_hist_name_in_file);
  RooDataSet *pData = (RooDataSet *)data_file->Get(data_hist_name_in_file);
  newworkspace->import(*pData);
  

  // Craft the signal+background model
  ModelConfig * pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*newworkspace);
  pSbModel->SetPdf(*newworkspace->pdf("model"));
  //pSbModel->SetPriorPdf(*newworkspace->pdf("prior"));//[][]
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);

  // set all but obs, poi and nuisance to const
  SetConstants(newworkspace, pSbModel);
  newworkspace->import(*pSbModel);


  // background-only model
  // use the same PDF as s+b, with sig=0
  // POI value under the background hypothesis
  // (We will set the value to 0 later)

  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)newworkspace->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*newworkspace);
  newworkspace->import(*pBModel);

  // find global maximum with the signal+background model
  // with conditional MLEs for nuisance parameters
  // and save the parameter point snapshot in the Workspace
  //  - safer to keep a default name because some RooStats calculators
  //    will anticipate it
  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  if(pSbModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  // Find a parameter point for generating pseudo-data
  // with the background-only data.
  // Save the parameter point snapshot in the Workspace
  pNll = pBModel->GetPdf()->createNLL(*pData);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  if(pBModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // save workspace to file
  newworkspace->writeToFile(workspace_name);

  // clean up
  delete newworkspace;
  delete pData;
  delete pSbModel;
  delete pBModel;


} // ----- end of tutorial ----------------------------------------
コード例 #2
0
void addTemplate(string procname, RooArgList& varlist, RooWorkspace& ws, TH1F* hist) {
    RooDataHist rhist(procname.c_str(), "", varlist, hist);
    ws.import(rhist);
}
コード例 #3
0
void StandardBayesianNumericalDemo(const char* infile = "",
                                   const char* workspaceName = "combined",
                                   const char* modelConfigName = "ModelConfig",
                                   const char* dataName = "obsData") {

   // option definitions
   double confLevel = optBayes.confLevel;
   TString integrationType = optBayes.integrationType;
   int nToys = optBayes.nToys;
   bool scanPosterior = optBayes.scanPosterior;
   int nScanPoints = optBayes.nScanPoints;
   int intervalType = optBayes.intervalType;
   int  maxPOI =  optBayes.maxPOI;
   double  nSigmaNuisance = optBayes.nSigmaNuisance;



   // -------------------------------------------------------
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist

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

   }
   else
      filename = infile;

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

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


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

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

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

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

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

   // ------------------------------------------
   // create and use the BayesianCalculator
   // to find and plot the 95% credible interval
   // on the parameter of interest as specified
   // in the model config

   // before we do that, we must specify our prior
   // it belongs in the model config, but it may not have
   // been specified
   RooUniform prior("prior","",*mc->GetParametersOfInterest());
   w->import(prior);
   mc->SetPriorPdf(*w->pdf("prior"));

   // do without systematics
   //mc->SetNuisanceParameters(RooArgSet() );
   if (nSigmaNuisance > 0) {
      RooAbsPdf * pdf = mc->GetPdf();
      assert(pdf);
      RooFitResult * res = pdf->fitTo(*data, Save(true), Minimizer(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str()), Hesse(true),
                                       PrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1) );

      res->Print();
      RooArgList nuisPar(*mc->GetNuisanceParameters());
      for (int i = 0; i < nuisPar.getSize(); ++i) {
         RooRealVar * v = dynamic_cast<RooRealVar*> (&nuisPar[i] );
         assert( v);
         v->setMin( TMath::Max( v->getMin(), v->getVal() - nSigmaNuisance * v->getError() ) );
         v->setMax( TMath::Min( v->getMax(), v->getVal() + nSigmaNuisance * v->getError() ) );
         std::cout << "setting interval for nuisance  " << v->GetName() << " : [ " << v->getMin() << " , " << v->getMax() << " ]" << std::endl;
      }
   }


   BayesianCalculator bayesianCalc(*data,*mc);
   bayesianCalc.SetConfidenceLevel(confLevel); // 95% interval

   // default of the calculator is central interval.  here use shortest , central or upper limit depending on input
   // doing a shortest interval might require a longer time since it requires a scan of the posterior function
   if (intervalType == 0)  bayesianCalc.SetShortestInterval(); // for shortest interval
   if (intervalType == 1)  bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
   if (intervalType == 2)  bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit

   if (!integrationType.IsNull() ) {
      bayesianCalc.SetIntegrationType(integrationType); // set integrationType
      bayesianCalc.SetNumIters(nToys); // set number of iterations (i.e. number of toys for MC integrations)
   }

   // in case of toyMC make a nuisance pdf
   if (integrationType.Contains("TOYMC") ) {
      RooAbsPdf * nuisPdf = RooStats::MakeNuisancePdf(*mc, "nuisance_pdf");
      cout << "using TOYMC integration: make nuisance pdf from the model " << std::endl;
      nuisPdf->Print();
      bayesianCalc.ForceNuisancePdf(*nuisPdf);
      scanPosterior = true; // for ToyMC the posterior is scanned anyway so used given points
   }

   // compute interval by scanning the posterior function
   if (scanPosterior)
      bayesianCalc.SetScanOfPosterior(nScanPoints);

   RooRealVar* poi = (RooRealVar*) mc->GetParametersOfInterest()->first();
   if (maxPOI != -999 &&  maxPOI > poi->getMin())
      poi->setMax(maxPOI);


   SimpleInterval* interval = bayesianCalc.GetInterval();

   // print out the interval on the first Parameter of Interest
   cout << "\n>>>> RESULT : " << confLevel*100 << "% interval on " << poi->GetName()<<" is : ["<<
      interval->LowerLimit() << ", "<<
      interval->UpperLimit() <<"] "<<endl;


   // make a plot
   // since plotting may take a long time (it requires evaluating
   // the posterior in many points) this command will speed up
   // by reducing the number of points to plot - do 50

   // ignore errors of PDF if is zero
   RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::Ignore) ;


   cout << "\nDrawing plot of posterior function....." << endl;

   // always plot using numer of scan points
   bayesianCalc.SetScanOfPosterior(nScanPoints);

   RooPlot * plot = bayesianCalc.GetPosteriorPlot();
   plot->Draw();

}
コード例 #4
0
void PDF_GGSZ_ExpNLL::buildPdfParametric()
{
  RooMsgService::instance().setGlobalKillBelow(ERROR);
  RooWorkspace *wExpNll = new RooWorkspace("wExpNll");

  //
  // for B-
  //
  RooHistPdfVar *xm_pdf = new RooHistPdfVar("xm_pdf", "xm_pdf", *xm_obs, *xm_th, RooConst( 0.000+2.62345e-03));
  RooHistPdfVar *ym_pdf = new RooHistPdfVar("ym_pdf", "ym_pdf", *ym_obs, *ym_th, RooConst( 0.027+1.88547e-03));

  double xmp0wl                        =    0.0541675;
  double xmp1wl                        =     0.018955;
  double xmp2wl                        =       0.3075;
  double xmp3wl                        =     -0.89035;
  double xmp4wl                        =     -3.44858;

  RooPoly4Var *ymwidthl = new RooPoly4Var("ymwidthl", "ymwidthl", *xm_pdf,
    xmp0wl, xmp1wl, xmp2wl, xmp3wl, xmp4wl);

  double xmp0wr                        =    0.0494967; 
  double xmp1wr                        =    0.0130424; 
  double xmp2wr                        =     0.110901; 
  double xmp3wr                        =   -0.0796312; 
  double xmp4wr                        =     0.204101;

  RooPoly4Var *ymwidthr = new RooPoly4Var("ymwidthr", "ymwidthr", *xm_pdf, 
    xmp0wr, xmp1wr, xmp2wr, xmp3wr, xmp4wr);
  
  double xmp0m                        =    0.0292742;
  double xmp1m                        =    -0.123769;
  double xmp2m                        =     -0.39777;
  double xmp3m                        =     0.825458;
    
  RooPoly3Var *ymmean = new RooPoly3Var("ymmean", "ymmean", *xm_pdf, 
    xmp0m, xmp1m, xmp2m, xmp3m);  
  RooBifurGauss *ympdf = new RooBifurGauss("ympdf", "ympdf", *ym_pdf, *ymmean, *ymwidthl, *ymwidthr);
  wExpNll->import(*ympdf);
  wExpNll->factory("RooBifurGauss::xmpdf(xm_pdf, xmmean[2.58584e-03], xmwidthl[4.37123e-02], xmwidthr[4.37101e-02])");
  wExpNll->factory("PROD::pdf_ggszexpnll_neg(xmpdf,ympdf)");
  
  //
  // for B+
  //
  RooHistPdfVar *xp_pdf = new RooHistPdfVar("xp_pdf", "xp_pdf", *xp_obs, *xp_th, RooConst(-0.103-5.74430e-03));    
  RooHistPdfVar *yp_pdf = new RooHistPdfVar("yp_pdf", "yp_pdf", *yp_obs, *yp_th, RooConst(-0.009-4.54284e-03));
    
  double xpp0wl                        =     0.0292561;
  double xpp1wl                        =     0.0703944;
  double xpp2wl                        =    -0.0922186;
  double xpp3wl                        =      -11.8135;
  double xpp4wl                        =      -34.8594;
  
  RooPoly4Var *ypwidthl = new RooPoly4Var("ypwidthl", "ypwidthl", *xp_pdf, 
    xpp0wl, xpp1wl, xpp2wl, xpp3wl, xpp4wl);

  double xpp0wr                        =   0.0403016; 
  double xpp1wr                        =   0.0367049; 
  double xpp2wr                        =    0.535281; 
  double xpp3wr                        =     2.29804; 
  double xpp4wr                        =     5.37199;

  RooPoly4Var *ypwidthr = new RooPoly4Var("ypwidthr", "ypwidthr", *xp_pdf, 
    xpp0wr, xpp1wr, xpp2wr, xpp3wr, xpp4wr);
  
  double xpp0m                        =    -0.0133043;
  double xpp1m                        =     -0.139777;
  double xpp2m                        =      -1.38657;
  double xpp3m                        =     -0.727225;
  
  RooPoly3Var *ypmean = new RooPoly3Var("ypmean", "ypmean", *xp_pdf, 
    xpp0m, xpp1m, xpp2m, xpp3m);  
  RooBifurGauss *yppdf = new RooBifurGauss("yppdf", "yppdf", *yp_pdf, *ypmean, *ypwidthl, *ypwidthr);
  wExpNll->import(*yppdf);
  wExpNll->factory("RooBifurGauss::xppdf(xp_pdf, xpmean[-1.08775e-01], xpwidthl[4.32573e-02], xpwidthr[4.93588e-02])");
  wExpNll->factory("PROD::pdf_ggszexpnll_pos(xppdf,yppdf)");

  // multiply both
  wExpNll->factory("PROD::pdf_"+name+"(pdf_ggszexpnll_neg,pdf_ggszexpnll_pos)");
  pdf = wExpNll->pdf("pdf_"+name);
  RooMsgService::instance().setGlobalKillBelow(INFO);
}
コード例 #5
0
ファイル: fitbkgdataCard.C プロジェクト: janveverka/MitHgg
void fitbkgdataCard(TString configCard="template.config", 
		    bool dobands  = true,  // create baerror bands for BG models
		    bool dosignal = false, // plot the signal model (needs to be present)
		    bool blinded  = true,  // blind the data in the plots?
		    bool verbose  = true  ) {
  
  gROOT->Macro("MitStyle.C");
  gStyle->SetErrorX(0); 
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();  
  
  TString projectDir;

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

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

  double theCMenergy = -1.;

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

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

  //win->Print();

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

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

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

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

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

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

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

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

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

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

  if( verbose ) wOut->Print();

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

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

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

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

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

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

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

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


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

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

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

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

    RooAddition* sumcatsnm1 = NULL;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    lat[icat] ->Draw();
    lat2[icat]->Draw();
    
    // -------------------------------------------------------    
    // save canvas in different formats
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".pdf"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".eps"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".root"));              
  }
  
  return;
  
}
コード例 #6
0
void eregtraining_flextest(bool dobarrel, bool doele) {
   
//   gSystem->Setenv("OMP_WAIT_POLICY","PASSIVE");
  
  //candidate to set fixed alpha values (0.9,3.8)
  //TString dirname = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregtesteleJul30_sig5_01_alphafloat5_%i/",int(minevents)); 
  
  //TString dirname = "/afs/cern.ch/work/b/bendavid/bare/eregAug23test/";
  TString dirname = "/data/bendavid/regflextesting/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);  
  
  std::vector<std::string> *varsf = new std::vector<std::string>;
  varsf->push_back("ph.scrawe");
  varsf->push_back("ph.sceta");
  varsf->push_back("ph.scphi");
  varsf->push_back("ph.r9");  
  varsf->push_back("ph.scetawidth");
  varsf->push_back("ph.scphiwidth");  
  varsf->push_back("ph.scnclusters");
  varsf->push_back("ph.hoveretower");
  varsf->push_back("rho");
  varsf->push_back("nVtx");  
 
  varsf->push_back("ph.etaseed-ph.sceta");
  varsf->push_back("atan2(sin(ph.phiseed-ph.scphi),cos(ph.phiseed-ph.scphi))");
  varsf->push_back("ph.eseed/ph.scrawe");
  
  varsf->push_back("ph.e3x3seed/ph.e5x5seed");
  varsf->push_back("ph.sigietaietaseed");   
  varsf->push_back("ph.sigiphiphiseed");   
  varsf->push_back("ph.covietaiphiseed");
  varsf->push_back("ph.emaxseed/ph.e5x5seed");
  varsf->push_back("ph.e2ndseed/ph.e5x5seed");
  varsf->push_back("ph.etopseed/ph.e5x5seed");
  varsf->push_back("ph.ebottomseed/ph.e5x5seed");
  varsf->push_back("ph.eleftseed/ph.e5x5seed");
  varsf->push_back("ph.erightseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5maxseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5topseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5bottomseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5leftseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5rightseed/ph.e5x5seed");
  
  std::vector<std::string> *varseb = new std::vector<std::string>(*varsf);
  std::vector<std::string> *varsee = new std::vector<std::string>(*varsf);
  
  varseb->push_back("ph.e5x5seed/ph.eseed");
  
  varseb->push_back("ph.ietaseed");
  varseb->push_back("ph.iphiseed");
  varseb->push_back("(ph.ietaseed-1*abs(ph.ietaseed)/ph.ietaseed)%5");
  varseb->push_back("(ph.iphiseed-1)%2");       
  varseb->push_back("(abs(ph.ietaseed)<=25)*((ph.ietaseed-1*abs(ph.ietaseed)/ph.ietaseed)%25) + (abs(ph.ietaseed)>25)*((ph.ietaseed-26*abs(ph.ietaseed)/ph.ietaseed)%20)");
  varseb->push_back("(ph.iphiseed-1)%20"); 
  varseb->push_back("ph.etacryseed");
  varseb->push_back("ph.phicryseed");

  varsee->push_back("ph.scpse/ph.scrawe");
    
  std::vector<std::string> *varslist;
  if (dobarrel) varslist = varseb;
  else varslist = varsee;
  
  RooArgList vars;
  for (unsigned int ivar=0; ivar<varslist->size(); ++ivar) {
    RooRealVar *var = new RooRealVar(TString::Format("var_%i",ivar),varslist->at(ivar).c_str(),0.);
    vars.addOwned(*var);
  }
  
  RooArgList condvars(vars);
  
  RooArgList condvarsred;
  condvarsred.add(*condvars.at(0));
  condvarsred.add(*condvars.at(1));
  condvarsred.add(*condvars.at(2));
  condvarsred.add(*condvars.at(3));
  
  
//   RooRealVar *tgtvar = new RooRealVar("tgtvar","ph.scrawe/ph.gene",1.);
//   if (!dobarrel) tgtvar->SetTitle("(ph.scrawe + ph.scpse)/ph.gene");
  
  RooRealVar *tgtvar = new RooRealVar("tgtvar","ph.gene/ph.scrawe",1.);
  if (!dobarrel) tgtvar->SetTitle("ph.gene/(ph.scrawe + ph.scpse)");  
  
/*  RooRealVar *tgtvar = new RooRealVar("tgtvar","log(ph.gene/ph.scrawe)",1.);
  if (!dobarrel) tgtvar->SetTitle("log(ph.gene/(ph.scrawe + ph.scpse))");  */  
  
  //tgtvar->setRange(0.8,2.);
  
  vars.addOwned(*tgtvar);


  
  //varstest.add(*tgtvar);
    
  RooRealVar weightvar("weightvar","",1.);

  //TFile *fdin = TFile::Open("/home/mingyang/cms/hist/hgg-2013Moriond/merged/hgg-2013Moriond_s12-diphoj-3-v7a_noskim.root");
//   TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/trainingtreesJul1/hgg-2013Final8TeV_s12-zllm50-v7n_noskim.root");
//   TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
//   TTree *dtree = (TTree*)ddir->Get("hPhotonTreeSingle");    
  
/*  TFile *fdinsig = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/trainingtreesJul1/hgg-2013Moriond_s12-h125gg-gf-v7a_noskim.root");
  TDirectory *ddirsig = (TDirectory*)fdinsig->FindObjectAny("PhotonTreeWriterPreselNoSmear");
  TTree *dtreesig = (TTree*)ddirsig->Get("hPhotonTreeSingle");     */ 
  
  TString treeloc;
  if (doele) {
    treeloc = "RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPreselInvert/PhotonTreeWriterSingleInvert/hPhotonTreeSingle";
  }
  else {
    treeloc = "RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle";
  }

  TChain *tree;
  float xsecs[50];

      
  if (doele) {
    tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPreselInvert/PhotonTreeWriterSingleInvert/hPhotonTreeSingle");
    //tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    tree->Add("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    
    xsecs[0] = 1.;
    initweights(tree,xsecs,1.);      
    
    xsecweights[0] = 1.0;
    
  }
  else {
    tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle");
//     tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj20_40-2em-v7n_noskim.root");
//     tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj40-2em-v7n_noskim.root");
    tree->Add("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj20_40-2em-v7n_noskim.root");
    tree->Add("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj40-2em-v7n_noskim.root");    
    
    xsecs[0] = 0.001835*81930.0;
    xsecs[1] = 0.05387*8884.0;    
    initweights(tree,xsecs,1.);  
    
    double weightscale = xsecweights[1];
    xsecweights[0] /= weightscale;
    xsecweights[1] /= weightscale;
  }
  
  
  TCut selcut;
  if (dobarrel) {
    selcut = "ph.genpt>16. && ph.isbarrel && ph.ispromptgen && evt%100==0"; 
  }
  else {
    selcut = "ph.genpt>16. && !ph.isbarrel && ph.ispromptgen";     
  }
  

  
  TCut selweight = "xsecweight(procidx)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale20 = "(evt%20==0)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale50 = "(evt%50==0)";
  TCut prescale100 = "(evt%100==0)";  
  TCut prescale1000 = "(evt%1000==0)";  
  TCut evenevents = "(evt%2==0)";
  TCut oddevents = "(evt%2==1)";
  //TCut oddevents = prescale100; 
  
  //weightvar.SetTitle(prescale10*selcut);
  
/*  new TCanvas;
  tree->Draw("ph.genpt>>hpt(200,0.,100.)",selweight*selcut);

  return;*/  
  
  if (doele) {
    weightvar.SetTitle(evenevents*selcut);
  }
  else {
    weightvar.SetTitle(selweight*selcut);
  }
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",tree,vars,weightvar);   
  
//   weightvar.SetTitle(prescale1000*selcut);
//   RooDataSet *hdatasig = RooTreeConvert::CreateDataSet("hdatasig",dtree,vars,weightvar);   
//   RooDataSet *hdatasigtest = RooTreeConvert::CreateDataSet("hdatasigtest",dtree,varstest,weightvar); 
  
  RooDataSet *hdatasig = 0;
  RooDataSet *hdatasigtest = 0;
  
//   weightvar.SetTitle(prescale10*selcut);
//   RooDataSet *hdatasigsmall = RooTreeConvert::CreateDataSet("hdatasigsmall",dtreesig,vars,weightvar);   
  
  RooRealVar sigwidthtvar("sigwidthtvar","",0.01);
  sigwidthtvar.setConstant(false);
  
  RooRealVar sigmeantvar("sigmeantvar","",1.);
  sigmeantvar.setConstant(false); 

  RooRealVar sigalphavar("sigalphavar","",1.);
  sigalphavar.setConstant(false);   
  
  RooRealVar signvar("signvar","",3.);
  signvar.setConstant(false);     

  RooRealVar sigalpha2var("sigalpha2var","",1.);
  sigalpha2var.setConstant(false);   
  
  RooRealVar sign2var("sign2var","",3.);
  sign2var.setConstant(false);     
  
  RooRealVar sigwidth2var("sigwidth2var","",0.5);
  sigwidth2var.setConstant(false);
  
  RooRealVar sigmean2var("sigmean2var","",1.);
  sigmean2var.setConstant(false);   
  
  RooRealVar sigfracvar("sigfracvar","",0.9);
  sigfracvar.setConstant(false);       
  
  
   
  RooArgList tgts;
  //RooGBRFunction func("func","",condvars,4);
  RooGBRFunctionFlex sigwidthfunc("sigwidthfunc","");
  RooGBRFunctionFlex sigmeanfunc("sigmeanfunc","");
  RooGBRFunctionFlex signfunc("signfunc","");
  RooGBRFunctionFlex sign2func("sign2func","");
  
  RooGBRTargetFlex sigwidtht("sigwidtht","",sigwidthfunc,sigwidthtvar,condvarsred);
  RooGBRTargetFlex sigmeant("sigmeant","",sigmeanfunc,sigmeantvar,condvars);
  RooGBRTargetFlex signt("signt","",signfunc,signvar,condvarsred);
  RooGBRTargetFlex sign2t("sign2t","",sign2func,sign2var,condvarsred);
  
    
  tgts.add(sigwidtht);
  tgts.add(sigmeant);
   //tgts.add(sigalpha);
  tgts.add(signt);
   //tgts.add(sigalpha2);
  tgts.add(sign2t);
//   tgts.add(sigmean2);
//   tgts.add(sigwidth2);
//   tgts.add(sigfrac);

  double lowboundalpha = 1e-2;
//   if (dobarrel) lowboundalpha = 0.05;
//   else lowboundalpha = 0.05;
  
  RooRealConstraint sigwidthlim("sigwidthlim","",sigwidtht,0.0002,0.5);
  RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,0.2,2.0);
  //RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,-2.0,2.0);
  //RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,-2.0,-0.2); 
  
  RooRealConstraint signlim("signlim","",signt,1.01,5000.); 
  //RooRealConstraint sigalphalim("sigalphalim","",sigalpha,lowboundalpha,8.0);

  RooRealConstraint sign2lim("sign2lim","",sign2t,1.01,5000.); 
  //RooRealConstraint sigalpha2lim("sigalpha2lim","",sigalpha2,lowboundalpha,8.0);  
  
  
/*  RooRealConstraint signlim("signlim","",signvar,1.01,500.); 
  RooRealConstraint sigalphalim("sigalphalim","",sigalphavar,lowboundalpha,8.0);

  RooRealConstraint sign2lim("sign2lim","",sign2var,1.01,500.); 
  RooRealConstraint sigalpha2lim("sigalpha2lim","",sigalpha2var,lowboundalpha,8.0);  */  
  
  
//   RooRealConstraint sigwidth2lim("sigwidth2lim","",sigwidth2,0.0002,10.);
//   RooRealConstraint sigmean2lim("sigmean2lim","",sigmean2,0.,10.0);  
//   
//   RooRealConstraint sigfraclim("sigfraclim","",sigfrac,0.,1.0);  
  
  
  //RooLinearVar tgtscaled("tgtscaled","",*tgtvar,sigmeanlim,RooConst(0.));
  
  //printf("tgtvar: min = %5e, max = %5e\n",tgtvar->getMin(),tgtvar->getMax());
  //printf("tgtscaled: min = %5e, max = %5e\n",tgtscaled.getMin(),tgtscaled.getMax());
  
 // RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim,sigalpha2lim,sign2lim);
  
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.),signlim,sigalpha2lim,sign2lim);
 
  
  RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,RooConst(2.),signlim,RooConst(1.),sign2lim);
  //RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,sigalphalim,signlim,sigalpha2lim,sign2lim);
  
  

  //RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,sigalphalim,signlim,sigalpha2lim,sign2lim);
  //RooCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,sigalpha2lim,sign2lim);
  
 // RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,RooConst(5.),RooConst(2.),sigalpha2lim,sign2lim);
  
 // RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,RooConst(5.),RooConst(2.),RooConst(5.),RooConst(2.));
  
   //RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,sigalphalim,RooConst(2.),sigalpha2lim,RooConst(2.));

//   RooDoubleCBFast sigg1("sigg1","",*tgtvar,sigmeanlim,sigwidthlim,RooConst(5.),RooConst(2.),RooConst(5.),RooConst(2.));
//   //RooGaussian sigg1("sigg1","",*tgtvar,sigmeanlim,sigwidthlim);
//   RooGaussianFast sigg2("sigg2","",*tgtvar,sigmean2lim,sigwidth2lim);
//   RooCondAddPdf sigpdf("sigpdf","",RooArgList(sigg1,sigg2),sigfraclim);
  
  
//   RooProduct sigwidthscaled("sigwidthscaled","",RooArgList(sigmeanlim,sigwidthlim));
//   RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthscaled,sigalphalim,signlim,sigalpha2lim,sign2lim);
  
  
  
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.),signlim,RooConst(1.),sign2lim);
  
  //RooDoubleCBFast sigpdf("sigpdf","",*tgtvar,sigmeanlim,sigwidthlim,sigalphalim,signlim,sigalpha2lim,sign2lim);
  
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.0),signlim,RooConst(1.0),sign2lim);
  
  //RooCBExp sigpdf("sigpdf","",tgtscaled,RooConst(-1.),sigwidthlim,sigalpha2lim,sign2lim,sigalphalim);
  
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(100.),RooConst(100.),sigalpha2lim,sign2lim);
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim,RooConst(3.),sign2lim);
  //RooCBShape sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim);
  
  RooConstVar etermconst("etermconst","",0.);  
  //RooFormulaVar etermconst("etermconst","","1000.*(@0-1.)*(@0-1.)",RooArgList(tgtscaled));
   
  RooRealVar r("r","",1.);
  r.setConstant();

  std::vector<RooAbsReal*> vpdf;
  vpdf.push_back(&sigpdf);  

  double minweight = 200;

  std::vector<double> minweights;
  minweights.push_back(minweight);
  
  //ntot.setConstant();

  TFile *fres = new TFile("fres.root","RECREATE");

  if (1) {  
    std::vector<RooAbsData*> vdata;
    vdata.push_back(hdata);    
    
    RooHybridBDTAutoPdf bdtpdfdiff("bdtpdfdiff","",tgts,etermconst,r,vdata,vpdf);
    bdtpdfdiff.SetMinCutSignificance(5.);
    //bdtpdfdiff.SetPrescaleInit(5);
    //bdtpdfdiff.SetPrescaleInit(100);
   // bdtpdfdiff.SetPrescaleInit(10);
    //bdtpdfdiff.SetMaxNSpurious(300.);
    //bdtpdfdiff.SetMaxNSpurious(2400.);
    //bdtpdfdiff.SetShrinkage(0.1);
    //bdtpdfdiff.SetShrinkage(0.1);
    bdtpdfdiff.SetShrinkage(0.1);
    bdtpdfdiff.SetMinWeights(minweights);
    //bdtpdfdiff.SetMaxNodes(270);
    bdtpdfdiff.SetMaxNodes(750);
    //bdtpdfdiff.SetMaxNodes(600);
    //bdtpdfdiff.SetMaxNodes(500);
    //bdtpdfdiff.SetMaxDepth(8);
    //bdtpdfdiff.TrainForest(1e6);
    bdtpdfdiff.TrainForest(1e6);  
    
  }   
     
  
  RooWorkspace *wereg = new RooWorkspace("wereg");
  wereg->import(sigpdf);
  
  if (doele && dobarrel)
    wereg->writeToFile("wereg_ele_eb.root");    
  else if (doele && !dobarrel) 
    wereg->writeToFile("wereg_ele_ee.root");    
  else if (!doele && dobarrel)
    wereg->writeToFile("wereg_ph_eb.root");    
  else if (!doele && !dobarrel)
    wereg->writeToFile("wereg_ph_ee.root");    
  
  
  return;
  
  
}
コード例 #7
0
void createWorkspace(const std::string &infilename, int nState, bool correctCtau, bool drawRapPt2D, bool drawPtCPM2D){
	gROOT->SetStyle("Plain");
	gStyle->SetTitleBorderSize(0);

	// Set some strings
	const std::string workspacename = "ws_masslifetime",
				treename = "selectedData";

	// Get the tree from the data file
	TFile *f = TFile::Open(infilename.c_str());
	TTree *tree = (TTree*)f->Get(treename.c_str());

	// Set branch addresses in tree to be able to import tree to roofit
	TLorentzVector* jpsi = new TLorentzVector;
	tree->SetBranchAddress("JpsiP",&jpsi);
	double CPMval = 0;
	tree->SetBranchAddress("CPM",&CPMval);
	double massErr = 0;
	tree->SetBranchAddress("JpsiMassErr",&massErr);
	double Vprob = 0;
	tree->SetBranchAddress("JpsiVprob",&Vprob);
	double lifetime = 0;
	tree->SetBranchAddress("Jpsict",&lifetime);
	double lifetimeErr = 0;
	tree->SetBranchAddress("JpsictErr",&lifetimeErr);

	// define variables necessary for J/Psi(Psi(2S)) mass,lifetime fit
	RooRealVar* JpsiMass =
		new RooRealVar("JpsiMass", "M [GeV]", onia::massMin, onia::massMax);
	RooRealVar* JpsiMassErr =
		new RooRealVar("JpsiMassErr", "#delta M [GeV]", 0, 5);
	RooRealVar* JpsiRap =
		new RooRealVar("JpsiRap", "y", -onia::rap, onia::rap);
	RooRealVar* JpsiPt =
		new RooRealVar("JpsiPt", "p_{T} [GeV]", 0. ,100.);
	RooRealVar* JpsiCPM =
		new RooRealVar("JpsiCPM", "N_{ch}", 0. ,100.);		
	RooRealVar* Jpsict =
		new RooRealVar("Jpsict", "lifetime [mm]", -1., 2.5);
	RooRealVar* JpsictErr =
		new RooRealVar("JpsictErr", "Error on lifetime [mm]", 0.0001, 1);
	RooRealVar* JpsiVprob =
		new RooRealVar("JpsiVprob", "", 0.01, 1.);

	// Set bins
	Jpsict->setBins(10000,"cache");
	Jpsict->setBins(100);
	JpsiMass->setBins(100);
	JpsictErr->setBins(100);

	// The list of data variables    
	RooArgList dataVars(*JpsiMass,*JpsiMassErr,*JpsiRap,*JpsiPt,*JpsiCPM,*Jpsict,*JpsictErr,*JpsiVprob);

	// construct dataset to contain events
	RooDataSet* fullData = new RooDataSet("fullData","The Full Data From the Input ROOT Trees",dataVars);

	int entries = tree->GetEntries();
	cout << "entries " << entries << endl;

	// loop through events in tree and save them to dataset
	for (int ientries = 0; ientries < entries; ientries++) {
	
		if (ientries%100000==0) std::cout << "event " << ientries << " of " << entries <<  std::endl;

		tree->GetEntry(ientries);

		double M =jpsi->M();
		double y=jpsi->Rapidity();
		double pt=jpsi->Pt();
		double cpm=CPMval;


		if (M > JpsiMass->getMin() && M < JpsiMass->getMax()
				&& massErr > JpsiMassErr->getMin() && massErr < JpsiMassErr->getMax()
				&& pt > JpsiPt->getMin() && pt < JpsiPt->getMax()
				&& cpm > JpsiCPM->getMin() && cpm < JpsiCPM->getMax()
				&& y > JpsiRap->getMin() && y < JpsiRap->getMax()
				&& lifetime > Jpsict->getMin() && lifetime < Jpsict->getMax()
				&& lifetimeErr > JpsictErr->getMin() && lifetimeErr < JpsictErr->getMax()
				&& Vprob > JpsiVprob->getMin() && Vprob < JpsiVprob->getMax()
			 ){

			JpsiPt      ->setVal(pt); 
			JpsiCPM		->setVal(cpm);
			JpsiRap     ->setVal(y); 
			JpsiMass    ->setVal(M);
			JpsiMassErr ->setVal(massErr);
			JpsiVprob   ->setVal(Vprob);

			//cout<<"before lifetime correction \n"
			//	<<"Jpsict: "<<lifetime<<" JpsictErr: "<<lifetimeErr<<endl;

			if(correctCtau){
				lifetime    = lifetime    * onia::MpsiPDG / M ;
				lifetimeErr = lifetimeErr * onia::MpsiPDG / M ;
				Jpsict    ->setVal(lifetime);
				JpsictErr ->setVal(lifetimeErr);
				//cout<<"MpsiPDG: "<<onia::MpsiPDG<<endl;
				//cout<<"after lifetime correction \n"
				//	<<"Jpsict: "<<lifetime<<" JpsictErr: "<<lifetimeErr<<endl;
			}
			else{
				Jpsict    ->setVal(lifetime);
				JpsictErr ->setVal(lifetimeErr);
			}

			fullData->add(dataVars);
		}
	}//ientries


	//------------------------------------------------------------------------------------------------------------------
	// Define workspace and import datasets

	////Get datasets binned in pT, cpm, and y

		for(int iRap = 1; iRap <= onia::kNbRapForPTBins; iRap++){ 

		Double_t yMin;
		Double_t yMax;
		if(iRap==0){
			yMin = onia::rapForPTRange[0];
			yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		} else{
			yMin = onia::rapForPTRange[iRap-1];
			yMax = onia::rapForPTRange[iRap];
		}

		for(int iPT = 1; iPT <= onia::kNbPTBins[iRap]; iPT++){
			//for(int iPT = 0; iPT <= 0; iPT++)

			Double_t ptMin;
			Double_t ptMax;
			if(iPT==0){
				ptMin = onia::pTRange[iRap][0];
				ptMax = onia::pTRange[iRap][onia::kNbPTBins[0]];
			} else{
				ptMin = onia::pTRange[iRap][iPT-1];
				ptMax = onia::pTRange[iRap][iPT];
			}
			
		  for(int iCPM = 1; iCPM <= onia::NchBins; iCPM++){
		  
		  
	  	    Double_t cpmMin;
			Double_t cpmMax;
			if(iCPM==0){
				cpmMin = onia::cpmRange[0];
				cpmMax = onia::cpmRange[onia::NchBins];
			} else{
				cpmMin = onia::cpmRange[iCPM-1];
				cpmMax = onia::cpmRange[iCPM];
			}

			// output file name and workspace
			std::stringstream outfilename;
			outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap" << iRap << "_pt" << iPT << "_cpm" << iCPM << ".root";
//			outfilename << "tmpFiles/fit_Psi" << nState-3 << "S_rap" << iRap << "_pt" << iPT << ".root";			
			RooWorkspace* ws = new RooWorkspace(workspacename.c_str());

			// define pt and y cuts on dataset
			std::stringstream cutString;
			cutString << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && " << "(JpsiPt >= " << ptMin << " && JpsiPt < "<< ptMax << ") && "
				<< "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";

			cout << "cutString: " << cutString.str().c_str() << endl;

			// get the dataset for the fit
			RooDataSet* binData = (RooDataSet*)fullData->reduce(cutString.str().c_str());
			std::stringstream name;
			name << "data_rap" << iRap << "_pt" << iPT << "_cpm" << iCPM;;
			binData->SetNameTitle(name.str().c_str(), "Data For Fitting");    

			// Import variables to workspace
			ws->import(*binData);
			ws->writeToFile(outfilename.str().c_str());
			
		  }//iCPM
		}//iPT
	}//iRap

	////---------------------------------------------------------------
	////--Integrating rapidity and pt bins, in +/- 3*sigma mass window
	////---------------------------------------------------------------
	if(drawRapPt2D){
		double yMin = onia::rapForPTRange[0];
		double yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		double ptMin =  onia::pTRange[0][0];
		double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];
		double cpmMin =  onia::cpmRange[0];
		double cpmMax =  onia::cpmRange[onia::NchBins];		

		std::stringstream cutRapPt;
		cutRapPt << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && "
			<< "(JpsiPt > " << ptMin << " && JpsiPt < "<< ptMax << ") && "
			<< "(TMath::Abs(JpsiRap) > " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
		cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

		RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
		std::stringstream nameRapPt;
		nameRapPt << "data_rap0_pt0_cpm0";
		rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

		// output file name and workspace
		std::stringstream outfilename;
		outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap0_pt0_cpm0.root";
		RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
		//Import variables to workspace
		ws_RapPt->import(*rapPtData);
		ws_RapPt->writeToFile(outfilename.str().c_str());

		TH2D* rapPt;
		TH1D* rap1p2;
		double MassMin;
		double MassMax;

		rap1p2 = new TH1D("rap1p2","rap1p2",30,0, 1.8); 
		if(nState==4){
			rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72);
			MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
			MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
			// sigma  27.2 MeV
			// mean 3.093 GeV
		}
		if(nState==5){
			rapPt = new TH2D( "rapPt", "rapPt", 64,-1.6,1.6,144,0,72); //  rap<1.5
			//rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
			MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
			MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
			// sigma 34.9 MeV // pT > 7
			// sigma 34.3 MeV // pT > 10
			// mean 3.681 GeV
		}

		cout<<"Plotting rap-Pt for Psi"<<nState-3<<"S"<<endl;
		cout<<"MassMin for rap-Pt plot = "<<MassMin<<endl;
		cout<<"MassMax for rap-Pt plot = "<<MassMax<<endl;

		TTree *rapPtTree = (TTree*)rapPtData->tree();
		std::stringstream cutMass;
		cutMass<<"(JpsiMass > " << MassMin << " && JpsiMass < "<< MassMax << ")";
		//following two methods can only be used in root_v30, 34 does not work
		rapPtTree->Draw("JpsiPt:JpsiRap>>rapPt",cutMass.str().c_str(),"colz");
		cout<<"debug"<<endl;
		rapPtTree->Draw("TMath::Abs(JpsiRap)>>rap1p2",cutMass.str().c_str());

		TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
		rapPt->SetYTitle("p_{T}(#mu#mu) [GeV]");
		rapPt->SetXTitle("y(#mu#mu)");
		gStyle->SetPalette(1);
		gPad->SetFillColor(kWhite);
		rapPt->SetTitle(0);
		rapPt->SetStats(0);
		gPad->SetLeftMargin(0.15);
		gPad->SetRightMargin(0.17);
		rapPt->GetYaxis()->SetTitleOffset(1.5);
		rapPt->Draw("colz");

		TLine* rapPtLine;

		for(int iRap=0;iRap<onia::kNbRapForPTBins+1;iRap++){
			rapPtLine= new TLine( -onia::rapForPTRange[iRap], onia::pTRange[0][0], -onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
			rapPtLine->SetLineWidth( 2 );
			rapPtLine->SetLineStyle( 1 );
			rapPtLine->SetLineColor( kWhite );
			rapPtLine->Draw();
			rapPtLine= new TLine( onia::rapForPTRange[iRap], onia::pTRange[0][0], onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
			rapPtLine->SetLineWidth( 2 );
			rapPtLine->SetLineStyle( 1 );
			rapPtLine->SetLineColor( kWhite );
			rapPtLine->Draw();
			int pTBegin = 0;
			if(nState==5) pTBegin = 1;
			for(int iPt=pTBegin;iPt<onia::kNbPTBins[iRap]+1;iPt++){
				rapPtLine= new TLine( -onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt], onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt] );
				rapPtLine->SetLineWidth( 2 );
				rapPtLine->SetLineStyle( 1 );
				rapPtLine->SetLineColor( kWhite );
				rapPtLine->Draw();
			}
		}

		char savename[200];
		sprintf(savename,"Fit/rapPt_Psi%dS.pdf",nState-3);
		c2->SaveAs(savename);
		TCanvas* c3 = new TCanvas("c3","c3",1500,1200);
		rap1p2->SetYTitle("Events");
		rap1p2->SetXTitle("y(#mu#mu)");
		rap1p2->SetTitle(0);
		rap1p2->SetStats(0);
		rap1p2->GetYaxis()->SetTitleOffset(1.2);
		rap1p2->Draw();
		sprintf(savename,"Fit/rapDimuon_1p2_Psi%dS.pdf",nState-3);
		c3->SaveAs(savename);
	}
	
	if(drawPtCPM2D){
		double yMin = onia::rapForPTRange[0];
		double yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		double ptMin =  onia::pTRange[0][0];
		double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];
		double cpmMin =  onia::cpmRange[0];
		double cpmMax =  onia::cpmRange[onia::NchBins];		

		std::stringstream cutRapPt;
		cutRapPt << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && "
			<< "(JpsiPt > " << ptMin << " && JpsiPt < "<< ptMax << ") && "
			<< "(TMath::Abs(JpsiRap) > " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
		cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

		RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
		std::stringstream nameRapPt;
		nameRapPt << "data_rap0_pt0_cpm0";
		rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

		// output file name and workspace
		std::stringstream outfilename;
		outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap0_pt0_cpm0.root";
		RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
		//Import variables to workspace
		ws_RapPt->import(*rapPtData);
		ws_RapPt->writeToFile(outfilename.str().c_str());

		TH2D* PtCPM;
		double MassMin;
		double MassMax;

		if(nState==4){
			PtCPM = new TH2D( "PtCPM", "PtCPM", 100,0,50,200,0,100);
			MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
			MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
			// sigma  27.2 MeV
			// mean 3.093 GeV
		}
		if(nState==5){
			PtCPM = new TH2D( "PtCPM", "PtCPM", 100,0,50,200,0,100); //  rap<1.5
			//rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
			MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
			MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
			// sigma 34.9 MeV // pT > 7
			// sigma 34.3 MeV // pT > 10
			// mean 3.681 GeV
		}

		cout<<"Plotting Pt-CPM for Psi"<<nState-3<<"S"<<endl;
		cout<<"MassMin for Pt-CPM plot = "<<MassMin<<endl;
		cout<<"MassMax for Pt-CPM plot = "<<MassMax<<endl;

		TTree *rapPtTree = (TTree*)rapPtData->tree();
		std::stringstream cutMass;
		cutMass<<"(JpsiMass > " << MassMin << " && JpsiMass < "<< MassMax << ")";
		//following two methods can only be used in root_v30, 34 does not work
		rapPtTree->Draw("JpsiCPM:JpsiPt>>PtCPM",cutMass.str().c_str(),"colz");
		cout<<"debug"<<endl;

		TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
		PtCPM->SetYTitle("N_{ch}");
		PtCPM->SetXTitle("p_{T}(#mu#mu) [GeV]");
		gStyle->SetPalette(1);
		gPad->SetFillColor(kWhite);
		PtCPM->SetTitle(0);
		PtCPM->SetStats(0);
		gPad->SetLeftMargin(0.15);
		gPad->SetRightMargin(0.17);
		PtCPM->GetYaxis()->SetTitleOffset(1.5);
		PtCPM->Draw("colz");

		TLine* PtCPMLine;

		int iRap=0;
		for(int iPt=0;iPt<onia::kNbPTMaxBins+1;iPt++){
		int cpmBegin = 0;
			if(nState==5) cpmBegin = 1;
			for(int icpm=cpmBegin;icpm<onia::NchBins+1;icpm++){
			
			PtCPMLine= new TLine( onia::pTRange[iRap][0], onia::cpmRange[icpm], onia::pTRange[iRap][onia::kNbPTMaxBins], onia::cpmRange[icpm] );
			PtCPMLine->SetLineWidth( 2 );
			PtCPMLine->SetLineStyle( 1 );
			PtCPMLine->SetLineColor( kWhite );
			PtCPMLine->Draw();
			PtCPMLine= new TLine( onia::pTRange[iRap][iPt], onia::cpmRange[0], onia::pTRange[iRap][iPt], onia::cpmRange[onia::NchBins] );
			PtCPMLine->SetLineWidth( 2 );
			PtCPMLine->SetLineStyle( 1 );
			PtCPMLine->SetLineColor( kWhite );
			PtCPMLine->Draw();

			
//				PtCPMLine= new TLine( onia::pTRange[0][onia::kNbPTMaxBins], onia::cpmRange[icpm], onia::pTRange[0][onia::kNbPTMaxBins], onia::cpmRange[icpm] );
//				PtCPMLine->SetLineWidth( 2 );
//				PtCPMLine->SetLineStyle( 1 );
//				PtCPMLine->SetLineColor( kWhite );
//				PtCPMLine->Draw();
			}
		}

		char savename[200];
		sprintf(savename,"Fit/PtCPM_Psi%dS.pdf",nState-3);
		c2->SaveAs(savename);
	}

	f->Close();
}
コード例 #8
0
ファイル: buildModel.C プロジェクト: echapon/fitting_utils
void buildModel(RooWorkspace& w,int chooseFitParams, int chooseSample,int whatBin, int signalModel, int bkgdModel, int doRap, int doPt,int doCent,int useRef,float muonPtMin, int fixFSR){
// C r e a t e   m o d e l  
  int nt=100000;
  // cout << "you're building a model for the quarkonium resonance of mass = "<< M1S <<" GeV/c^{2},"endl;
  RooRealVar *nsig1f   = new RooRealVar("N_{ #varUpsilon(1S)}","nsig1S",0,nt*10);
  RooRealVar* mass       = new RooRealVar("invariantMass","#mu#mu mass",mass_l,mass_h,"GeV/c^{2}");

  RooRealVar *nsig2f = NULL;
  RooRealVar *nsig3f = NULL;

 switch (chooseFitParams)
    {
    case 0://use the YIELDs of 2S and 3S as free parameters
      //minor modif here: 3S forced positive.
      nsig2f  = new RooRealVar("N_{ #varUpsilon(2S)}","nsig2S",   nt*0.25,-200,10*nt);
      nsig3f  = new RooRealVar("N_{ #varUpsilon(3S)}","nsig3S",   nt*0.25,-200,10*nt);
      cout << "you're fitting to extract yields, "<< endl;
      break;
    default:
      cout<<"Make a pick from chooseFitParams!!!"<<endl;
      break;
    }  

      RooRealVar  *mean = new RooRealVar("m_{ #varUpsilon(1S)}","#Upsilon mean",M1S,M1S-0.2,M1S+0.2);
      RooConstVar *rat2 = new RooConstVar("rat2", "rat2", M2S/M1S);
      RooConstVar *rat3 = new RooConstVar("rat3", "rat3", M3S/M1S);
      // scale mean and resolution by mass ratio
      RooFormulaVar *mean1S = new RooFormulaVar("mean1S","@0",RooArgList(*mean));
      RooFormulaVar *mean2S = new RooFormulaVar("mean2S","@0*@1", RooArgList(*mean,*rat2));
      RooFormulaVar *mean3S = new RooFormulaVar("mean3S","@0*@1", RooArgList(*mean,*rat3));

      // //detector resolution ?? where is this coming from?
      RooRealVar    *sigma1  = new RooRealVar("#sigma_{CB1}","#sigma_{CB1}",sigma_min[whatBin],sigma_max[whatBin]); // 
      RooFormulaVar *sigma1S = new RooFormulaVar("sigma1S","@0"   ,RooArgList(*sigma1));
      RooFormulaVar *sigma2S = new RooFormulaVar("sigma2S","@0*@1",RooArgList(*sigma1,*rat2));
      RooFormulaVar *sigma3S = new RooFormulaVar("sigma3S","@0*@1",RooArgList(*sigma1,*rat3));
      RooRealVar *alpha  = new RooRealVar("#alpha_{CB}","tail shift",alpha_min[whatBin],alpha_max[whatBin]);    // MC 5tev 1S pol2 
      RooRealVar *npow   = new RooRealVar("n_{CB}","power order",npow_min[whatBin],npow_max[whatBin]);    // MC 5tev 1S pol2 
      RooRealVar *sigmaFraction = new RooRealVar("sigmaFraction","Sigma Fraction",0.,1.);
      // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.
      RooRealVar    *scaleWidth = new RooRealVar("#sigma_{CB2}/#sigma_{CB1}","scaleWidth",1.,2.5);
      RooFormulaVar *sigmaGaus = new RooFormulaVar("sigmaGaus","@0*@1", RooArgList(*sigma1,*scaleWidth));
      RooFormulaVar *sigmaGaus2 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat2));
      RooFormulaVar *sigmaGaus3 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat3));
      RooGaussian* gauss1 = new RooGaussian("gaus1s","gaus1s",
      					    *nsig1f,
      					    *mass,    //mean
      					    *sigmaGaus); //sigma
      // RooGaussian* gauss1b = new RooGaussian("gaus1sb","gaus1sb",
      // 					     *nsig1f,
      // 					     *m,    //mean
      // 					     *sigma1); //sigma
      switch(signalModel){    
      case 1: //crystal boule
	RooCBShape  *sig1S   = new RooCBShape ("cb1S_1", "FSR cb 1s",
					       *mass,*mean1S,*sigma1,*alpha,*npow);

	RooCBShape  *sig2S   = new RooCBShape ("cb2S_1", "FSR cb 1s",
					       *mass,*mean2S,*sigma2S,*alpha,*npow);
	RooCBShape  *sig3S   = new RooCBShape ("cb3S_1", "FSR cb 1s",
					       *mass,*mean3S,*sigma3S,*alpha,*npow);
	cout << "you're fitting each signal peak with a Crystal Ball function"<< endl;
	break;
      case 2: //Gaussein
	RooAbsPdf      *sig1S  = new RooGaussian ("g1", "gaus 1s",
						  *mass,*mean1S,*sigma1);
	cout << "you're fitting 1 signal peak with a Gaussian function"<< endl;
	break;
      case 3: //Gaussein + crystal boule
	RooCBShape  *cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
						 *mass,*mean1S,*sigma1,*alpha,*npow);
	RooAddPdf      *sig1S  = new RooAddPdf ("cbg", "cbgaus 1s",
						RooArgList(*gauss1,*cb1S_1),*sigmaFraction);
	cout << "you're fitting 1 signal peak with a sum of a Gaussian and a Crystal Ball function"<< endl;
	break;
      case 4: //crystal boules
	RooCBShape  *cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
						 *mass,*mean1S,*sigma1,*alpha,*npow);
       
	RooCBShape  *cb1S_2    = new RooCBShape ("cb1S_2", "FSR cb 1s",
						 *mass,*mean1S,*sigmaGaus,*alpha,*npow);
	RooAddPdf      *sig1S  = new RooAddPdf  ("cbcb","1S mass pdf",
						 RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);
	// /// Upsilon 2S
	RooCBShape  *cb2S_1    = new RooCBShape ("cb2S_1", "FSR cb 2s", 
						 *mass,*mean2S,*sigma2S,*alpha,*npow); 
	RooCBShape  *cb2S_2    = new RooCBShape ("cb2S_2", "FSR cb 2s", 
						 *mass,*mean2S,*sigmaGaus2,*alpha,*npow); 
	RooAddPdf      *sig2S  = new RooAddPdf  ("sig2S","2S mass pdf",
						 RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);
      
	// /// Upsilon 3S
	RooCBShape  *cb3S_1    = new RooCBShape ("cb3S_1", "FSR cb 3s", 
						 *mass,*mean3S,*sigma3S,*alpha,*npow); 
	RooCBShape  *cb3S_2    = new RooCBShape ("cb3S_2", "FSR cb 3s", 
						 *mass,*mean3S,*sigmaGaus3,*alpha,*npow); 
	RooAddPdf      *sig3S  = new RooAddPdf  ("sig3S","3S mass pdf",
						 RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction); // = cb3S1*sigmaFrac + cb3S2*(1-sigmaFrac)
	cout << "you're fitting each signal peak with a Double Crystal Ball function"<< endl;
	break;
      
      case 5: //deux Gausseins
	RooAddPdf      *sig1S  = new RooAddPdf ("cb1S_1", "cbgaus 1s",
						RooArgList(*gauss1,*gauss1b),*sigmaFraction);
	cout << "you're fitting each signal peak with a Double Gaussian function"<< endl;
	break;
      }
      // bkg Chebychev
      RooRealVar *nbkgd   = new RooRealVar("n_{Bkgd}","nbkgd",0,nt);
      RooRealVar *bkg_a1  = new RooRealVar("a1_bkg", "bkg_{a1}", 0, -5, 5);
      RooRealVar *bkg_a2  = new RooRealVar("a2_Bkg", "bkg_{a2}", 0, -2, 2);
      RooRealVar *bkg_a3  = new RooRealVar("a3_Bkg", "bkg_{a3}", 0, -0.9, 2);

      //  likesign
      RooRealVar *nLikesignbkgd = new RooRealVar("NLikesignBkg","nlikesignbkgd",nt*0.75,0,10*nt);
      // *************************************************** bkgModel
      
      RooRealVar turnOn("turnOn","turnOn", turnOn_minCent[whatBin],turnOn_maxCent[whatBin]);
      RooRealVar width("width","width",width_minCent[whatBin],width_maxCent[whatBin]);// MB 2.63
      RooRealVar decay("decay","decay",decay_minCent[whatBin],decay_maxCent[whatBin]);// MB: 3.39
      if (doRap && !doPt)
	{
	  RooRealVar turnOn("turnOn","turnOn", turnOn_minRap[whatBin],turnOn_maxRap[whatBin]);
	  RooRealVar width("width","width",width_minRap[whatBin],width_maxRap[whatBin]);// MB 2.63
	  RooRealVar decay("decay","decay",decay_minRap[whatBin],decay_maxRap[whatBin]);// MB: 3.39
	}
      if (doPt && !doRap)
	{
	  RooRealVar turnOn("turnOn","turnOn", turnOn_minPt[whatBin],turnOn_maxPt[whatBin]);
	  RooRealVar width("width","width",width_minPt[whatBin],width_maxPt[whatBin]);// MB 2.63
	  RooRealVar decay("decay","decay",decay_minPt[whatBin],decay_maxPt[whatBin]);// MB: 3.39
	}
      
  
      width.setConstant(false);
      decay.setConstant(false);
      turnOn.setConstant(false);
 
  switch (useRef)// no reference
    {
    case 0: // forcing sigma and fsr to be left free.
      fixSigma1 = 0;
      fixFSR    = 0;
      break;
    case 1:
      //using data-driven estimates
      int dataRef=1;
      cout<<"You're using the debug mode based on data parameters. So you must not take this result as the central one."<<endl;
      break;
    case 2:
      
      cout << "doCent="<<doCent << endl;
      //using MC-driven estimates
      int dataRef=2;
      if(doCent)   //MB values, assumed to be the same with all centralities...
     	{
	  if(muonPtMin <4){
	    gROOT->LoadMacro("dataTable_loose.h");
	  }else if(muonPtMin > 3.5){
	    gROOT->LoadMacro("dataTable_tight.h");
	  }
	  npow->setVal(npow_rapBins[8]);
	  alpha->setVal(alpha_rapBins[8]);
	  sigma1->setVal(sigma1_rapBins[8]);
	  scaleWidth->setVal(scale_rapBins[8]);
	  sigmaFraction->setVal(pdFrac_rapBins[8]);
	  cout<< whatBin << endl;
	}
      if(doRap && !doPt)
	{
	  if(muonPtMin <4){
	    gROOT->LoadMacro("dataTable_loose.h");
	  }else if(muonPtMin > 3.5){
	    gROOT->LoadMacro("dataTable_tight.h");
	  }
	  npow->setVal(npow_rapBins[whatBin]);
	  alpha->setVal(alpha_rapBins[whatBin]);
	  sigma1->setVal(sigma1_rapBins[whatBin]);
	  scaleWidth->setVal(scale_rapBins[whatBin]);
	  sigmaFraction->setVal(pdFrac_rapBins[whatBin]);
	  cout<< whatBin << endl;
	}
      if(doPt && !doRap)
	{
	  // cout << "we're here" << endl;
	  if(muonPtMin <4){
	    gROOT->LoadMacro("dataTable_loose.h");
	  }else if(muonPtMin > 3.5){
	    gROOT->LoadMacro("dataTable_tight.h");
	  }
	  cout << " ok ... " <<endl;
	  npow->setVal(npow_ptBins[whatBin]);
	  alpha->setVal(alpha_ptBins[whatBin]);
	  sigma1->setVal(sigma1_ptBins[whatBin]);
	  scaleWidth->setVal(scale_ptBins[whatBin]);
	  sigmaFraction->setVal(pdFrac_ptBins[whatBin]);
	}
     
      cout<<"You're using MC parameters. So you may use this result as the central one, according to the LLR test outcome."<<endl;
      break;
    default: break;
    }

  //
  cout << "npow tried=" << npow->getVal(); 
  if(fixFSR==3 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "alpha tried=" << alpha->getVal(); 
  if(fixFSR==2 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "sigma1 tried=" << sigma1->getVal(); 
  if(fixFSR==4 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "scale tried=" << scaleWidth->getVal(); 
  if(fixFSR==4 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  cout << "normalisation tried=" << sigmaFraction->getVal();
  if(fixFSR==5 || fixFSR==1) cout << "   constant!" << endl;   else cout << "   floating!" << endl;
  
  switch (fixFSR) // 0: free;  1: both fixed 2: alpha fixed 3: npow fixed
    {      
    case 0:// all free
      alpha->setConstant(false);
      npow->setConstant(false);
      sigma1->setConstant(false);
      scaleWidth->setConstant(false);
      sigmaFraction->setConstant(false);
      break;
    case 1:// all fixed
      alpha->setConstant(true);
      npow ->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 2: // release alpha
      alpha->setConstant(false);
      npow ->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 3:// npow released
      alpha->setConstant(true);
      npow->setConstant(false);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 4:// width+ sF +scale released
      alpha->setConstant(true);
      npow->setConstant(true);
      sigma1->setConstant(false);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(true);
      break;
    case 5:// scale +sF
      alpha->setConstant(true);
      npow->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(false);
      sigmaFraction->setConstant(true);
      break;
   case 6:// scale +sF
      alpha->setConstant(true);
      npow->setConstant(true);
      sigma1->setConstant(true);
      scaleWidth->setConstant(true);
      sigmaFraction->setConstant(false);
      break;
    default:
      cout<<"Donno this choice! Pick somehting for FSR parameters that I know"<<endl;
      break;
    }
   //thisPdf: form of the bkg pdf
  //pdf_combinedbkgd; // total bkg pdf. usually form*normalization  (so that you can do extended ML fits)
  switch (bkgdModel) 
    {
    case 1 :  //(erf*exp ) to fit the SS, then fix the shape and fit OS, in case of constrain option
      bkg_a3->setConstant(true);
      RooGenericPdf *ErrPdf = new  RooGenericPdf("ErrPdf","ErrPdf",
						 "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
					       RooArgList(*mass,turnOn,width,decay));
      RooFitResult* fit_1st  = ErrPdf->fitTo(*likesignData,Save(),NumCPU(4)) ; // likesign data
      if (doTrkRot) fit_1st  = thisPdf->fitTo(*TrkRotData,Save(),NumCPU(4)) ;
      
      if (doConstrainFit) 
	{ // allow parameters to vary within cenral value from above fit + their sigma
	  turnOn_constr = new RooGaussian("turnOn_constr","turnOn_constr",
					  turnOn,
					  RooConst(turnOn.getVal()),
					  RooConst(turnOn.getError()));
	  width_constr   = new RooGaussian("width_constr","width_constr",
					   width,					   RooConst(width.getVal()),
					   RooConst(width.getError()));
	  decay_constr    = new RooGaussian("decay_constr","decay_constr",
					    decay,
					    RooConst(decay.getVal()),
					    RooConst(decay.getError()));
	}
      else 
	{
	  turnOn.setConstant(kTRUE);
	  width.setConstant(kTRUE);
	  decay.setConstant(kTRUE);
	}
      RooRealVar *fLS =new RooRealVar("R_{SS/OS}","Empiric LS/SS ratio",0.,1.);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ErrPdf,*ChebPdf),
						      RooArgList(*fLS));
      
      break;
    case 2 : //us eRooKeysPdf to smooth the SS, then fit OS with pol+keys
      bkg_a3->setConstant(true);
      RooRealVar *fLS =new RooRealVar("R_{SS/OS}","Empiric LS/SS ratio",0.,1.);
      RooKeysPdf *KeysPdf        = new RooKeysPdf("KeysPdf","KeysPdf",*mass,*likesignData,
						  RooKeysPdf::MirrorBoth, 1.4);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      if (doTrkRot) thisPdf     = new RooKeysPdf("thisPdf","thisPdf",*mass,*TrkRotData,
						 RooKeysPdf::MirrorBoth, 1.4);
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*KeysPdf,*ChebPdf),
						      RooArgList(*fLS));
      break;
    case 3 : //use error function to fit the OS directly
      bkg_a3->setConstant(true);
      RooAbsPdf *pdf_combinedbkgd            = new  RooGenericPdf("bkgPdf","bkgPdf",
								  "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
								  RooArgList(*mass,turnOn,width,decay));
      break;
      
    case 4 : //use pol 2+ErfExp to fit the OS directly

      RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      RooGenericPdf *ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
						     "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
						     RooArgList(*mass,turnOn,width,decay));
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ChebPdf,*ErrPdf),
						      RooArgList(*fPol));

      break;
    case 5 : //use ( error function + polynomial 1) to fit the OS directly
      
      bkg_a3->setConstant(true);
      bkg_a2->setConstant(true);
      RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2,*bkg_a3));
      RooGenericPdf *ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
						     "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
						   RooArgList(*mass,turnOn,width,decay));
      RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ChebPdf,*ErrPdf),
						      RooArgList(*fPol));
      break;
    case 6: // NOT WORKING
      RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
      RooAbsPdf  *ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
					      *mass, RooArgList(*bkg_a1,*bkg_a2));
      RooGenericPdf *ExpPdf     = new  RooGenericPdf("ExpPdf","ExpPdf",
						     "exp(-@0/decay)",
						     RooArgList(*mass,decay));
      RooAbsPdf  *pdf_combinedbkgd  =  new RooAddPdf ("bkgPdf","total combined background pdf",
						      RooArgList(*ChebPdf,*ExpPdf),
						      RooArgList(*fPol));
      break;
    default :
      cout<<"Donno what you are talking about! Pick another fit option!"<<endl;
      break;
    }
  
  //###### the nominal fit with default pdf 
 
  // RooAbsPdf  *pdf; // nominal PDF
  if(chooseSample==8)
   {     
     // bkg_a1->setVal(0);// can be turned on at convenience
     // bkg_a1->setConstant();
     // bkg_a2->setVal(0);
     // bkg_a2->setConstant();
     // bkg_a3->setVal(0);
     // bkg_a3->setConstant();
     // RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",
     // 						  RooArgList(*sig1S,*pdf_combinedbkgd),
     // 						  RooArgList(*nsig1f,*nbkgd));
        RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",*sig1S,*nsig1f);
   } else if(chooseSample!=8)
    {
      // can remove the double crystal ball in pbpb: just commenting out and copying an appropriate version
      RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",
						   RooArgList(*sig1S,*sig2S,*sig3S,*pdf_combinedbkgd),
						   RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
      //  nsig3f->setVal(0); nsig3f->setConstant();
      
    }
  w.import(*pdf);
  w.Print();
}
コード例 #9
0
ファイル: templatesSig.C プロジェクト: UAEDF/vbfHbb
void templatesSig(double XMIN,double XMAX,double dX,TString cutstring) {
	gROOT->ForceStyle();
	RooMsgService::instance().setSilentMode(kTRUE);
	for(int i=0;i<2;i++) RooMsgService::instance().setStreamStatus(i,kFALSE);

	const int NMASS(1);
	char name[1000];

	TFile *fVBF[NMASS];//,*fGF[NMASS];
	TH1F  *hVBF[NMASS][5],*hPassVBF;
	int H_MASS[1] = {125};
	TString SELECTION[1] = {"jetPt[0]>80 && jetPt[1]>70"};
	int NCAT[1] = {4};
	int LUMI[1] = {19281};
	int XSEC_VBF[1] = {0.911};

//	TH1F  *hGF[NMASS][5],*hVBF[NMASS][5],*hTOT[NMASS][5],*hPassGF,*hPassVBF;
	RooDataHist *RooHistFit[NMASS][5],*RooHistScaled[NMASS][5];
	RooAddPdf *model[NMASS][5];

	TCanvas *can[NMASS];
	TString PATH("rootfiles/");

	RooWorkspace *w = new RooWorkspace("w","workspace");
	int NBINS   = (XMAX-XMIN)/dX;

	RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
	RooRealVar kJES("CMS_scale_j","CMS_scale_j",1,0.9,1.1);
	RooRealVar kJER("CMS_res_j","CMS_res_j",1,0.8,1.2);
	kJES.setConstant(kTRUE);
	kJER.setConstant(kTRUE);

	TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
	for(int iMass=0;iMass<NMASS;iMass++) {
		cout<<"Mass = "<<H_MASS[iMass]<<" GeV"<<endl;
		int counter(0);
		for(int iSEL=0;iSEL<2;iSEL++) {
//			sprintf(name,"Fit_VBFPowheg%d_sel%s.root",H_MASS[iMass],SELECTION[iSEL].Data());
			sprintf(name,"vbfHbb_uncertainties_JEx.root");
			cout << name << endl;
			fVBF[iMass]  = TFile::Open(PATH+TString(name));
//			hPassVBF = (TH1F*)fVBF[iMass]->Get("TriggerPass");

//			sprintf(name,"Fit_GFPowheg%d_sel%s.root",H_MASS[iMass],SELECTION[iSEL].Data());
//			fGF[iMass]  = TFile::Open(PATH+TString(name)); 
//			hPassGF = (TH1F*)fGF[iMass]->Get("TriggerPass");

			sprintf(name,"HMassTemplate_%d_sel%s",H_MASS[iMass],SELECTION[iSEL].Data());

			can[iMass] = new TCanvas(name,name,1200,800);
			can[iMass]->Divide(2,2);

			for(int icat=0;icat<NCAT[iSEL];icat++) { 
				sprintf(name,"Hbb%d/events",icat);
//				trVBF = (TTree*)fVBF[iMass]->Get(name);
//				trGF  = (TTree*)fGF[iMass]->Get(name);
				can[iMass]->cd(icat+1);
				sprintf(name,"mass_VBF%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				
				hVBF[iMass][icat] = (TH1F*)fVBF[iMass]->Get("histos/VBF125/h_NOM_VBF125_Hbb_mbbReg1;1");//new TH1F(name,name,NBINS,XMIN,XMAX);
//				hVBF[iMass][icat]->Sumw2();
//				TCut cut("puWt[0]*"+TRIG_WT[iSEL]+"*(mva"+SELECTION[iSEL]+">-1)");
//				TCut cut(cutstring.Data());
//				trVBF->Draw(MASS_VAR[iSEL]+">>"+TString(name),cut);

//				sprintf(name,"mass_GF%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
//				hGF[iMass][icat] = new TH1F(name,name,NBINS,XMIN,XMAX);
//				hGF[iMass][icat]->Sumw2();
//				trGF->Draw(MASS_VAR[iSEL]+">>"+TString(name),cut);
//
		//		delete trVBF;
//				delete trGF;
				
				sprintf(name,"roohist_fit_mass%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				RooHistFit[iMass][icat] = new RooDataHist(name,name,x,hVBF[iMass][icat]);
				
//				hGF[iMass][icat]->Scale(LUMI[iSEL]*XSEC_GF[iMass]/hPassGF->GetBinContent(1));
				hVBF[iMass][icat]->Scale(LUMI[iSEL]*XSEC_VBF[iMass]/4794398.);//hPassVBF->GetBinContent(1));

//				sprintf(name,"mass_Total%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
				hTOT[iMass][icat] = (TH1F*)hVBF[iMass][icat]->Clone(name);
//				hTOT[iMass][icat]->Add(hGF[iMass][icat]);
				
				sprintf(name,"yield_signalVBF_mass%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar *YieldVBF = new RooRealVar(name,name,hVBF[iMass][icat]->Integral());
        		
				sprintf(name,"roohist_demo_mass%d_sel%s_CAT%d",H_MASS[iMass],SELECTION[iSEL].Data(),icat);
		        RooHistScaled[iMass][icat] = new RooDataHist(name,name,x,hTOT[iMass][icat]);

      			sprintf(name,"mean_m%d_CAT%d",H_MASS[iMass],counter);
	        	RooRealVar m(name,name,125,100,150);
	        	sprintf(name,"sigma_m%d_CAT%d",H_MASS[iMass],counter);
	        	RooRealVar s(name,name,12,3,30);

				sprintf(name,"mean_shifted_m%d_CAT%d",H_MASS[iMass],counter);
				RooFormulaVar mShift(name,"@0*@1",RooArgList(m,kJES));
				sprintf(name,"sigma_shifted_m%d_CAT%d",H_MASS[iMass],counter);
				RooFormulaVar sShift(name,"@0*@1",RooArgList(s,kJER)); 
				
				sprintf(name,"alpha_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar a(name,name,1,-10,10);
				sprintf(name,"exp_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar n(name,name,1,0,100);
				
				sprintf(name,"b0_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b0(name,name,0.5,0.,1.);
				sprintf(name,"b1_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b1(name,name,0.5,0.,1.);
				sprintf(name,"b2_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b2(name,name,0.5,0.,1.);
				sprintf(name,"b3_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar b3(name,name,0.5,0.,1.);
				
				sprintf(name,"signal_bkg_m%d_CAT%d",H_MASS[iMass],counter);
				RooBernstein bkg(name,name,x,RooArgSet(b0,b1,b2));
				
				sprintf(name,"fsig_m%d_CAT%d",H_MASS[iMass],counter);
				RooRealVar fsig(name,name,0.7,0.,1.);
				
				sprintf(name,"signal_gauss_m%d_CAT%d",H_MASS[iMass],counter);
				RooCBShape sig(name,name,x,mShift,sShift,a,n);
				
				
				// model(x) = fsig*sig(x) + (1-fsig)*bkg(x)
				sprintf(name,"signal_model_m%d_CAT%d",H_MASS[iMass],counter);
				model[iMass][icat] = new RooAddPdf(name,name,RooArgList(sig,bkg),fsig);
				
				RooFitResult *res = model[iMass][icat]->fitTo(*RooHistFit[iMass][icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q");
				//res->Print();
				
				RooPlot* frame = x.frame();
				RooHistScaled[iMass][icat]->plotOn(frame);
				//model[iMass][icat]->plotOn(frame,RooFit::VisualizeError(*res,1,kFALSE),RooFit::FillColor(kGray));
				//RooHist[iMass][icat]->plotOn(frame);
				model[iMass][icat]->plotOn(frame);
				double chi2 = frame->chiSquare(); 
				//model[iMass][icat]->plotOn(frame,RooFit::LineWidth(2));
				model[iMass][icat]->plotOn(frame,RooFit::Components(bkg),RooFit::LineColor(kBlue),RooFit::LineWidth(2),RooFit::LineStyle(kDashed)); 
				frame->GetXaxis()->SetNdivisions(505); 
				frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
				frame->GetYaxis()->SetTitle("Events");
				frame->Draw();
//				hGF[iMass][icat]->SetFillColor(kGreen-8); 
				hVBF[iMass][icat]->SetFillColor(kRed-10); 
				THStack *hs = new THStack("hs","hs");
//				hs->Add(hGF[iMass][icat]);
				hs->Add(hVBF[iMass][icat]);
				hs->Draw("same hist");
				frame->Draw("same");
				gPad->RedrawAxis();
				
				TF1 *tmp_func = model[iMass][icat]->asTF(x,fsig,x);
				double y0 = tmp_func->GetMaximum();
				double x0 = tmp_func->GetMaximumX();
				double x1 = tmp_func->GetX(y0/2,XMIN,x0);
				double x2 = tmp_func->GetX(y0/2,x0,XMAX);
				double FWHM = x2-x1;
				//cout<<"Int = "<<tmp_func->Integral(XMIN,XMAX)<<", Yield = "<<Yield->getVal()<<", y0 = "<<y0<<", x0 = "<<x0<<", x1 = "<<x1<<", x2 = "<<x2<<", FWHM = "<<FWHM<<endl;
				//delete tmp_func;
				double y1 = dX*0.5*y0*(YieldVBF->getVal()+YieldGF->getVal())/tmp_func->Integral(XMIN,XMAX); 
				TLine *ln = new TLine(x1,y1,x2,y1);
				ln->SetLineColor(kMagenta+3);
				ln->SetLineStyle(7);
				ln->SetLineWidth(2);
				ln->Draw(); 
				
				TLegend *leg = new TLegend(0.65,0.35,0.9,0.45);  
				leg->AddEntry(hVBF[iMass][icat],"VBF","F");
//				leg->AddEntry(hGF[iMass][icat],"GF","F");
				leg->SetFillColor(0);
				leg->SetBorderSize(0);
				leg->SetTextFont(42);
				leg->SetTextSize(0.05);
				leg->Draw("same");
				
				TPaveText *pave = new TPaveText(0.65,0.55,0.9,0.92,"NDC");
				sprintf(name,"M_{H} = %d GeV",H_MASS[iMass]);
				TLegend *leg = new TLegend(0.65,0.35,0.9,0.45);  
				leg->AddEntry(hVBF[iMass][icat],"VBF","F");
//				leg->AddEntry(hGF[iMass][icat],"GF","F");
				leg->SetFillColor(0);
				leg->SetBorderSize(0);
				leg->SetTextFont(42);
				leg->SetTextSize(0.05);
				leg->Draw("same");
				
				TPaveText *pave = new TPaveText(0.65,0.55,0.9,0.92,"NDC");
				sprintf(name,"M_{H} = %d GeV",H_MASS[iMass]);
				pave->AddText(name);
				sprintf(name,"%s selection",SELECTION[iSEL].Data());
				pave->AddText(name);
				sprintf(name,"CAT%d",icat);
				pave->AddText(name);
				sprintf(name,"m = %1.1f #pm %1.1f",m.getVal(),m.getError());
				pave->AddText(name);
				sprintf(name,"#sigma = %1.1f #pm %1.1f",s.getVal(),s.getError());
				pave->AddText(name);
				sprintf(name,"FWHM = %1.2f",FWHM);
				pave->AddText(name);
				/*
				sprintf(name,"a = %1.2f #pm %1.2f",a.getVal(),a.getError());
				pave->AddText(name);
				sprintf(name,"n = %1.2f #pm %1.2f",n.getVal(),n.getError());
				pave->AddText(name);
				sprintf(name,"f = %1.2f #pm %1.2f",fsig.getVal(),fsig.getError());
				pave->AddText(name);
				*/
				pave->SetFillColor(0);
				pave->SetBorderSize(0);
				pave->SetTextFont(42);
				pave->SetTextSize(0.05);
				pave->SetTextColor(kBlue);
				pave->Draw();
				
				b0.setConstant(kTRUE);
				b1.setConstant(kTRUE);
				b2.setConstant(kTRUE);
				b3.setConstant(kTRUE);
				
				//m2.setConstant(kTRUE);
				//s2.setConstant(kTRUE); 
				m.setConstant(kTRUE);
				s.setConstant(kTRUE); 
				a.setConstant(kTRUE);
				n.setConstant(kTRUE);
				fsig.setConstant(kTRUE);
				
				w->import(*model[iMass][icat]);
				w->import(*RooHistScaled[iMass][icat]);
				w->import(*res); 
				w->import(*YieldVBF);   
				w->import(*YieldGF);  
				
				counter++;
			}// categories loop
		}// selection loop 
	}// mass loop
	w->Print();
	//x.Print();
	TString selName = "_";
	selName += XMIN;    
	selName += "-";
	selName += XMAX;
	w->writeToFile("signal_shapes_workspace"+selName+".root");
}
コード例 #10
0
int main (int argc, char **argv) {

  TFile *tf = TFile::Open("root/AnalysisOut.root");
  TTree *tree = (TTree*)tf->Get("AnalysisTree");

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

  // tree variables
  Double_t  t_mass;
  Double_t  t_KST1_m;
  Double_t  t_KST2_m;
  int       t_itype;
  ULong64_t t_eventNumber;
  Bool_t    t_pass_bdt;
  Bool_t    t_pass_pid;
  TString   *t_evname = 0;

  // tree branches
  tree->SetBranchAddress("B_s0_DTF_B_s0_M",      &t_mass        );
  tree->SetBranchAddress("B_s0_DTF_KST1_M",      &t_KST1_m   );
  tree->SetBranchAddress("B_s0_DTF_KST2_M",      &t_KST2_m   );
  tree->SetBranchAddress("itype",                &t_itype       );
  tree->SetBranchAddress("eventNumber",          &t_eventNumber );
  tree->SetBranchAddress("pass_bdt",             &t_pass_bdt    );
  tree->SetBranchAddress("pass_pid",             &t_pass_pid    );
  tree->SetBranchAddress("evname",               &t_evname      );

  // observables
  RooRealVar *mass        = new RooRealVar("B_s0_DTF_B_s0_M", "m(K#piK#pi)", 5000., 5800.);
  RooRealVar *KST1_mass   = new RooRealVar("B_s0_DTF_KST1_M", "m(K#pi)"    , 750, 1700 );
  RooRealVar *KST2_mass   = new RooRealVar("B_s0_DTF_KST2_M", "m(K#pi)"    , 750, 1700 );
  RooRealVar *itype       = new RooRealVar("itype","itype",-10,10); itype->removeRange();
  RooRealVar *eventNumber = new RooRealVar("eventNumber","eventNumber",0,10e10);


  // map to store datasets
  map<int, RooDataSet*> dsets;

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

    if ( t_itype >= 0 && !t_pass_bdt ) continue;
    if ( t_itype >= 0 && !t_pass_pid ) continue;

    // if entry not in map then add it
    if ( dsets.find( t_itype ) == dsets.end() ) {
      dsets[t_itype] = new RooDataSet( *t_evname, *t_evname, RooArgSet(*mass,*KST1_mass,*KST2_mass,*itype,*eventNumber) );
    }

    // add to dataset
    mass->setVal( t_mass );
    KST1_mass->setVal( t_KST1_m );
    KST2_mass->setVal( t_KST2_m );
    itype->setVal( t_itype );
    eventNumber->setVal( t_eventNumber );
    dsets[t_itype]->add( RooArgSet(*mass,*KST1_mass,*KST2_mass,*itype,*eventNumber) );

    if ( ev%10000==0 ) {
      cout << ev << "/" << tree->GetEntries() << endl;
      cout << "\t" << t_itype << " " << *t_evname << " " << t_eventNumber << " " << t_mass << endl;
    }
  }

  for ( map<int, RooDataSet*>::iterator it = dsets.begin(); it != dsets.end(); it++ ) {

    cout << "\t" << it->first << " " << it->second->GetName() << " " << it->second->numEntries() << endl;
    w->import(*it->second);

  }

  tf->Close();

  delete t_evname;

  w->writeToFile("tmp/DataSets.root");
  return 0;
}
コード例 #11
0
void MakeWorkspace(const TString& channel, const TString& strategy)
{
    TString dcname       = g_dcname;
    TString wsname       = g_wsname;
    TString realvarname  = g_realvarname;
    TString rootname     = g_rootname;
    TString pdfname      = g_pdfname;
    dcname      .ReplaceAll("$CHANNEL", channel);
    wsname      .ReplaceAll("$CHANNEL", channel);
    realvarname .ReplaceAll("$CHANNEL", channel);
    rootname    .ReplaceAll("$CHANNEL", channel);
    pdfname     .ReplaceAll("$CHANNEL", channel);
    
    RooWorkspace * ws = new RooWorkspace(channel + "_8TeV", channel + "_8TeV");
    ws->factory(Form("%s[%.2f,%.2f]", realvarname.Data(), g_xlow, g_xup));
    RooRealVar * realvar = ws->var(realvarname.Data());
    RooArgList * obs = new RooArgList(*realvar);
    
    TFile * input = TFile::Open(rootname, "READ");
    TH1F * h(0);

    if (strategy == "blind") {
        h = (TH1F *) input->Get(channel + "/" + "mc_exp");
    } else if (strategy == "injectsignal") {
        h = (TH1F *) input->Get(channel + "/" + "mc_exp");
        TH1F * hZH = (TH1F *) input->Get(channel + "/" + "ZH_SM");
        h->Add(hZH);
        TH1F * hWH = (TH1F *) input->Get(channel + "/" + "WH_SM");
        h->Add(hWH);
        delete hZH;
        delete hWH;
    } else if (strategy == "real") {
        h = (TH1F *) input->Get(channel + "/" + "data_obs");
    } else {
        std::cerr << "Unknown strategy: " << strategy << std::endl;
    }

    if (strategy != "real")  gSystem->Exec(Form("sed -i 's/observation.*/observation %.3f/' %s ", h->Integral(), dcname.Data()));

    // data_obs
    RooDataHist * dh = new RooDataHist("data_obs", "", *obs, h);
    ws->import(*dh);
    delete dh;
    delete h;

    // no systematics
    for (Int_t p=0; p < jmax+1; p++) {
        const TString& process = g_processes[p];
        h = (TH1F *) input->Get(channel + "/" + process);
        dh = new RooDataHist(process, "", *obs, h);
        ws->import(*dh);
        delete dh;
        delete h;
    }

    // with systematics up/down
    TCanvas * c1 = new TCanvas("c1", "c1", 700, 700);
    c1->SetLogy();
    c1->Print(pdfname+"[");
    for (Int_t p=0; p < jmax+1; p++) {
        for (Int_t s=1; s < nsyst; s+=2) {
            MakeSystPlot(channel, input, ws, obs, p, s, s+1);
        }
    }
    c1->Print(pdfname+"]");
    delete c1;
    
    ws->writeToFile(wsname, kTRUE);
    delete input;
    delete ws;
    
    return;
}
コード例 #12
0
void testBackground(char* fileName="../dataFiles/forMatthew/summer11_data_lowmass.root",double lowMassCut=120, double highMassCut=170, int mH=150){

  gROOT->ProcessLine(".L ../PDFs/Roo2l2jMasses2D_Bkg.cc+");

  //================== measurables

  cout << "initializing measurables..." <<endl;

  RooRealVar mLL("mLL","mZ*",20,80);
  RooRealVar mZZ("mZZ","m_{ZZ}",lowMassCut,highMassCut);
  RooRealVar mJJ("mJJ","m_{jj}",50,150);
  RooRealVar nBTags("nBTags","nBTags",-1,3);
  RooRealVar met("met","met",0,1000);

  //================== P_1(m'Z*,mZZ) ==================
	//=============================

  cout << "initializing parameters... " << endl;

  RooRealVar mZ("mZ","m_{Z}",60,120);
  RooRealVar Gamma("Gamma","#Gamma",0,100);
  
  mZ.setVal(91.2);   mZ.setConstant(kTRUE);
  Gamma.setVal(0.); Gamma.setConstant(kTRUE);

  RooRealVar p1("p1","p1",1.54516e+01.,0,1000);
  //p1.setConstant(kTRUE);
  RooRealVar p2("p2","p2",1.54516e+01.,0,1000);
  //p2.setConstant(kTRUE);

  RooPolynomial P1("P1","P1",mLL,RooArgList(p1),0);
  RooPolynomial P2("P2","P2",mZZ,RooArgList(p2),0);

  RooProdPdf totalPDF_bkg("totalPDF_bkg","totalPDF_bkg",P1,P2);

  //============== load data ========================
	//============================
  
  cout << "loading data..." << endl;

  TFile *file = new TFile(fileName);
  char cutString_SB[100], cutString_0btag[100],cutString_1btag[100],cutString_2btag[100];
  char cutString_SB_0btag[100],cutString_SB_1btag[100],cutString_SB_2btag[100];

  sprintf(cutString_SB_0btag,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&(mJJ<75||mJJ>105)&&nBTags==0",highMassCut,lowMassCut);
  sprintf(cutString_SB_1btag,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&(mJJ<75||mJJ>105)&&nBTags==1",highMassCut,lowMassCut);
  sprintf(cutString_SB_2btag,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&(mJJ<75||mJJ>105)&&nBTags==2&&met<50",highMassCut,lowMassCut);
  sprintf(cutString_SB,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&((mJJ>60&&mJJ<75)||(mJJ<130&&mJJ>105))",highMassCut,lowMassCut);  
  sprintf(cutString_0btag,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&mJJ>75&&mJJ<105&&nBTags==0",highMassCut,lowMassCut);
  sprintf(cutString_1btag,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&mJJ>75&&mJJ<105&&nBTags==1",highMassCut,lowMassCut);
  sprintf(cutString_2btag,"mZZ<%f&&mZZ>%f&&mLL>20&&mLL<80&&mJJ>75&&mJJ<105&&nBTags==2&&met<50",highMassCut,lowMassCut);

  cout << "check1" << endl;

  RooDataSet data_SB_0btag("data_SB_0btag","data_SB_0btag",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags),cutString_SB_0btag);
  RooDataSet data_SB_1btag("data_SB_1btag","data_SB_1btag",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags),cutString_SB_1btag);
  RooDataSet data_SB_2btag("data_SB_2btag","data_SB_2btag",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags,met),cutString_SB_2btag);
  RooDataSet data_SB("data_SB","data_SB",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags),cutString_SB);
  RooDataSet data_0btag("data_0btag","data_0btag",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags),cutString_0btag);
  RooDataSet data_0b=(RooDataSet)data_0btag.reduce(RooArgSet(mZZ,mLL));
  RooDataSet data_1btag("data_1btag","data_1btag",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags),cutString_1btag);
  RooDataSet data_1b=(RooDataSet)data_1btag.reduce(RooArgSet(mZZ,mLL));
  RooDataSet data_2btag("data_2btag","data_2btag",(TTree*)file->Get("AngularInfo"),RooArgSet(mZZ,mLL,mJJ,nBTags,met),cutString_2btag);
  RooDataSet data_2b=(RooDataSet)data_2btag.reduce(RooArgSet(mZZ,mLL));
      
  
  cout << "fitting data..." << endl;

  totalPDF_bkg.fitTo(data_SB);
  
  p1.setConstant(kTRUE);
  p2.setConstant(kTRUE);

  cout << "plotting data/fits..." << endl;

  RooPlot *plot=mLL.frame(20,80,40);
  RooPlot *plot2=mZZ.frame(lowMassCut,highMassCut,40);
  data_SB.plotOn(plot2);
  totalPDF_bkg.plotOn(plot2);//DrawOption("F"),FillColor(3));
  data_SB.plotOn(plot);
  totalPDF_bkg.plotOn(plot);//,DrawOption("F"),FillColor(3));

  cout << "drawing..." << endl;

  TCanvas*c = new TCanvas("c","c",800,400);
  c->Divide(2,1);
  c->cd(1);
  plot->Draw();
  c->cd(2);  
  plot2->Draw();	

  for (int i=0; i<plot2->numItems(); i++) {
    TString obj_name=plot2->nameOf(i); if (obj_name=="") continue;
    cout << Form("%d. '%s'\n",i,obj_name.Data());
  }

  TLegend *leg = new TLegend(.2,.8,.6,.6);
  leg->SetTextSize(0.036);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->AddEntry("totalPDF_bkg_Int[mLL]_Norm[mLL,mZZ]","Background Fit","l");
  leg->AddEntry("h_data_SB","Inclusive Sideband","p");
  leg->Draw();

  char inWorkspace[100];
  sprintf(inWorkspace,"2DWorkspace_%i.root",mH);
  char outWorkspace[100];
  sprintf(outWorkspace,"Final2DWorkspace_%i.root",mH);

  TFile *workspaceFile = new TFile(inWorkspace);
  RooWorkspace* w = (RooWorkspace*) workspaceFile->Get("w");

  w->import(totalPDF_bkg);
  w->import(data_0b);
  w->import(data_1b);
  w->import(data_2b);
  
  TFile *newFile = new TFile(outWorkspace,"RECREATE");
  w->Write("w");

}
コード例 #13
0
void fastEfficiencyNadir(unsigned int iEG, int iECAL1, int iColl1, int iECAL2, int iColl2,
			 TString dirIn, 
			 TString lumi, int nCPU, 
			 int color1, int style1, int color2, int style2,
			 TString probe, TString tag, TString fileIn)
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // EG THRESHOLDS //
  const int nEG = 71;
  double thres[nEG];
  for(int i=0 ; i<nEG ; i++) thres[i]=i;

  TString names[nEG];
  ostringstream ossi;
  for(int i=0;i<(int)nEG;i++) {
    ossi.str("");
    ossi << thres[i] ;
    names[i] = ossi.str();
  }

  // NAMES //
  const int nECAL=2;
  const int nColl=2;

  TString name_leg_ecal[nECAL] = {"Barrel","Endcaps"};
  TString name_leg_coll[nColl] = {"Online","Emulation"};  

  TString name_ecal[nECAL] = {"_EB","_EE"};
  TString name_coll[nColl] = {"_N","_M"};

  TString dirResults = dirIn + "/turnons/EG"+names[iEG]+"/" ;
  TString name_image = 
    dirResults + "eff_EG"+names[iEG]+"_tag"+tag+"_probe"+probe+name_ecal[iECAL1]+name_coll[iColl1]+"_vs"+name_ecal[iECAL2]+name_coll[iColl2] ;

  // Output log //
  ofstream fichier(name_image+".txt", ios::out);


  // BINNING //
  const int nbins[nEG] = {29,29,29,29,21,21,21,22,22,21,22,21,22,18,19,18,18,18,18,20,20,20,20,19,20,20,20,20,21,21,
			  21,21,21,21,21,21,21,21,21,21, //EG30
			  22,22,22,22,22,22,22,22,22,22, //EG40
			  29,29,29,29,29,29,29,29,29,29, //EG50
			  29,29,29,29,29,29,29,29,29,29};//EG60

  Double_t bins_0[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG0
  Double_t bins_1[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG1
  Double_t bins_2[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG2 
  Double_t bins_3[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG3

  Double_t bins_4[21] = {1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 27, 32, 41, 50, 60, 70, 150}; // EG4
  Double_t bins_5[21] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 31, 40, 50, 60, 70, 150}; // EG5
  Double_t bins_6[21] = {3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19, 21, 23, 27, 32, 41, 50, 60, 70, 150}; // EG6

  Double_t bins_7[22] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG7
  Double_t bins_8[22] = {3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 32, 41, 50, 60, 70, 150}; // EG8
  Double_t bins_9[21] = {4, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG9

  Double_t bins_10[22] = {5, 7, 8, 9, 10, 11, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG10
  Double_t bins_11[21] = {6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 26, 28, 31, 40, 50, 60, 70, 150}; // EG11
  Double_t bins_12[22] = {5, 7, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG12

  Double_t bins_13[18] = {5, 7, 9, 11, 12, 13, 14, 15, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG13
  Double_t bins_14[19] = {6, 8, 10, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG14
  Double_t bins_15[18] = {5, 7, 9, 11, 13, 14, 15, 16, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG15

  Double_t bins_16[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG16
  Double_t bins_17[18] = {9, 11, 13, 15, 16, 17, 18, 19, 21, 23, 25, 30, 35, 40, 50, 60, 70, 150}; // EG17
  Double_t bins_18[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG18

  Double_t bins_19[20] = {9, 11, 13, 15, 17, 18, 19, 20, 21, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG19
  Double_t bins_20[20] = {8, 10, 12, 14, 16, 18, 19, 20, 21, 22, 24, 26, 30, 35, 40, 45, 50, 60, 70, 100}; // EG20
  Double_t bins_21[20] = {9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG21

  Double_t bins_22[20] = {10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG22
  Double_t bins_23[19] = {11, 13, 15, 17, 19, 21, 22, 23, 24, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG23
  Double_t bins_24[20] = {10, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG24

  Double_t bins_25[20] = {11, 13, 15, 17, 19, 21, 23, 24, 25, 26, 27, 29, 30, 35, 40, 45, 50, 60, 70, 150}; // EG25
  Double_t bins_26[20] = {10, 12, 14, 16, 18, 20, 22, 24, 25, 26, 27, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG26
  Double_t bins_27[20] = {11, 13, 15, 17, 19, 21, 23, 25, 26, 27, 28, 29, 33, 35, 40, 45, 50, 60, 70, 150}; // EG27

  Double_t bins_28[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 29, 30, 32, 35, 40, 45, 50, 60, 70, 150}; // EG28
  Double_t bins_29[21] = {11, 13, 15, 17, 19, 21, 23, 25, 27, 28, 29, 30, 31, 33, 35, 40, 45, 50, 60, 70, 150}; // EG29
  Double_t bins_30[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 29, 30, 31, 32, 35, 40, 45, 50, 60, 70, 150}; // EG30

  Double_t bins_40[22] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 38, 39, 40, 42, 45, 50, 60, 70, 150}; // EG40
  Double_t bins_50[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG50
  Double_t bins_60[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG60

  vector< Double_t* > bins;
  bins.push_back( bins_0 ); bins.push_back( bins_1 ); bins.push_back( bins_2 ); bins.push_back( bins_3 ); bins.push_back( bins_4 ); 
  bins.push_back( bins_5 ); bins.push_back( bins_6 ); bins.push_back( bins_7 ); bins.push_back( bins_8 ); bins.push_back( bins_9 ); 
  bins.push_back( bins_10 ); bins.push_back( bins_11 ); bins.push_back( bins_12 ); bins.push_back( bins_13 ); bins.push_back( bins_14 ); 
  bins.push_back( bins_15 ); bins.push_back( bins_16 ); bins.push_back( bins_17 ); bins.push_back( bins_18 ); bins.push_back( bins_19 ); 
  bins.push_back( bins_20 ); bins.push_back( bins_21 ); bins.push_back( bins_22 ); bins.push_back( bins_23 ); bins.push_back( bins_24 ); 
  bins.push_back( bins_25 ); bins.push_back( bins_26 ); bins.push_back( bins_27 ); bins.push_back( bins_28 ); bins.push_back( bins_29 ); 

  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_30 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_40 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_50 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_60 );

  RooBinning binning = RooBinning(nbins[iEG]-1, bins[iEG], "binning");


  // INPUT DATA //
  TFile* f1 = TFile::Open(dirIn+"/"+fileIn);

  TTree* treenew;
  TTree* treenew_2;

  treenew = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL1]+name_coll[iColl1] ) ;
  treenew_2 = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL2]+name_coll[iColl2] ) ;

  TString name_scet[2], name_scdr[2], name_l1bin[2];
  name_scet[0] = "sc_et"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scet[1] = "sc_et"+name_ecal[iECAL2]+name_coll[iColl2];
  name_scdr[0] = "sc_dr"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scdr[1] = "sc_dr"+name_ecal[iECAL2]+name_coll[iColl2];
  
  name_l1bin[0] = "l1_"+names[iEG]+name_ecal[iECAL1]+name_coll[iColl1];
  name_l1bin[1] = "l1_"+names[iEG]+name_ecal[iECAL2]+name_coll[iColl2];

  RooRealVar et_plot(name_scet[0],name_scet[0],0,150) ;
  RooRealVar dr(name_scdr[0],name_scdr[0],0.5,1.5) ; 
  RooRealVar et_plot2(name_scet[1],name_scet[1],0,150) ;
  RooRealVar dr2(name_scdr[1],name_scdr[1],0.5,1.5) ;

  // Acceptance state cut (1 or 0)
  RooCategory cut(name_l1bin[0],name_l1bin[0]) ;
  cut.defineType("accept",1) ;
  cut.defineType("reject",0) ;
  RooCategory cut2(name_l1bin[1],name_l1bin[1]) ;
  cut2.defineType("accept",1) ;
  cut2.defineType("reject",0) ;
  
  // PARAMETRES ROOFIT CRYSTAL BALL
  RooRealVar norm("norm","N",1,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.671034,0.01,8);
  RooRealVar n("n","n",4.07846,1.1,35);
  RooRealVar mean("mean","mean",20.8,0,100);
  //mean.setVal(thres[iEG]);
  RooRealVar sigma("sigma","#sigma",0.972825,0.01,5);
  //RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  RooRealVar norm2("norm2","N",0.999069,0.6,1);
  RooRealVar alpha2("alpha2","#alpha",0.492303,0.01,8);
  RooRealVar n2("n2","n",11.6694,1.1,35);
  RooRealVar mean2("mean2","mean",21.4582,0,100);
  //mean2.setVal(thres[iEG]);
  RooRealVar sigma2("sigma2","#sigma",1.19,0.01,5);
  //RooRealVar pedestal2("pedestal2","pedestal",0.01,0,0.4);

  FuncCB cb("cb","Crystal Ball Integree",et_plot,mean,sigma,alpha,n,norm) ;
  FuncCB cb2("cb2","Crystal Ball Integree",et_plot2,mean2,sigma2,alpha2,n2,norm2) ;
  
  // EFFICIENCY //
  RooEfficiency eff("eff","efficiency",cb,cut,"accept");
  RooEfficiency eff2("eff2","efficiency",cb2,cut2,"accept");

  // DATASETS //
  RooDataSet dataSet("data","data",RooArgSet(et_plot, cut,dr),Import(*treenew)); 
  RooDataSet dataSet2("data2","data2",RooArgSet(et_plot2, cut2,dr2),Import(*treenew_2));

  dataSet.Print();
  dataSet2.Print();
  
  // PLOT //
  RooPlot* frame = et_plot.frame(Bins(18000),Title("Fitted efficiency")) ;
  RooPlot* frame2 = et_plot2.frame(Bins(18000),Title("Fitted efficiency")) ;

  dataSet.plotOn(frame, Binning(binning), Efficiency(cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSet2.plotOn(frame2, Binning(binning), Efficiency(cut2), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );


  /////////////////////// FITTING /////////////////////////////

  double fit_cuts_min = thres[iEG]-1.5 ;
  double fit_cuts_max = 150;

  et_plot.setRange("interesting",fit_cuts_min,fit_cuts_max);
  et_plot2.setRange("interesting",fit_cuts_min,fit_cuts_max);

  RooFitResult* roofitres1 = new RooFitResult("roofitres1","roofitres1");
  RooFitResult* roofitres2 = new RooFitResult("roofitres2","roofitres2");

  fichier << "Fit characteristics :"   << endl ;
  fichier << "EG "     << names[iEG] << endl ;
  fichier << "Fit Range , EB Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "Fit Range , EE Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "----------------------"  << endl ;

  // Fit #1 //
  roofitres1 = eff.fitTo(dataSet,ConditionalObservables(et_plot),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
  
  cb.plotOn(frame,LineColor(color1),LineWidth(2));

  double res_norm1  = norm.getVal();
  double err_norm1  = norm.getErrorLo();
  double res_mean1  = mean.getVal();
  double err_mean1  = mean.getError();
  double res_sigma1 = sigma.getVal();
  double err_sigma1 = sigma.getError();
  double res_n1     = n.getVal();
  double err_n1     = n.getError();
  double res_alpha1 = alpha.getVal();
  double err_alpha1 = alpha.getError();

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << res_mean1  << "; "
	  << "double res_sigma=" << res_sigma1 << "; "
          << "double res_alpha=" << res_alpha1 << "; "
          << "double res_n="     << res_n1     << "; "
          << "double res_norm="  << res_norm1  << "; "
	  << endl
	  << "double err_mean="  << err_mean1  << "; "
	  << "double err_sigma=" << err_sigma1 << "; "
          << "double err_alpha=" << err_alpha1 << "; "
          << "double err_n="     << err_n1     << "; "
          << "double err_norm="  << err_norm1  << "; "
	  << endl;

  // Fit #2 //
  roofitres2 = eff2.fitTo(dataSet2,ConditionalObservables(et_plot2),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
 
  cb2.plotOn(frame2,LineColor(color2),LineWidth(2));

  double res_norm2  = norm2.getVal();
  double err_norm2  = norm2.getErrorLo();
  double res_mean2  = mean2.getVal();
  double err_mean2  = mean2.getError();
  double res_sigma2 = sigma2.getVal();
  double err_sigma2 = sigma2.getError();
  double res_n2     = n2.getVal();
  double err_n2     = n2.getError();
  double res_alpha2 = alpha2.getVal();
  double err_alpha2 = alpha2.getError();

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << res_mean2  << "; "
	  << "double res_sigma=" << res_sigma2 << "; "
	  << "double res_alpha=" << res_alpha2 << "; "
	  << "double res_n="     << res_n2     << "; "
	  << "double res_norm="  << res_norm2  << "; "
	  << endl
	  << "double err_mean="  << err_mean2  << "; "
	  << "double err_sigma=" << err_sigma2 << "; "
	  << "double err_alpha=" << err_alpha2 << "; "
	  << "double err_n="     << err_n2     << "; "
	  << "double err_norm="  << err_norm2  << "; "
	  << endl;
    

  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,100.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  frame2->GetYaxis()->SetRangeUser(0,1.05);
  frame2->GetXaxis()->SetRangeUser(1,100.);
  frame2->GetYaxis()->SetTitle("Efficiency");
  frame2->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame2->Draw("same") ;

  TH1F *SCeta1 = new TH1F("SCeta1","SCeta1",50,-2.5,2.5);
  TH1F *SCeta2 = new TH1F("SCeta2","SCeta2",50,-2.5,2.5);

  SCeta1->SetLineColor(color1) ;
  SCeta1->SetMarkerColor(color1);
  SCeta1->SetMarkerStyle(style1);

  SCeta2->SetLineColor(color2) ;
  SCeta2->SetMarkerColor(color2);
  SCeta2->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.246,0.435,0.461,0.560,NULL,"brNDC"); // mid : x=353.5
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);
  leg->SetMargin(0.25);
  TLegendEntry *entry=leg->AddEntry("NULL","L1_SingleEG"+names[iEG],"h");
//   leg->AddEntry(SCeta1,name_leg_ecal[iECAL1]+" "+name_leg_coll[iColl1],"p");
//   leg->AddEntry(SCeta2,name_leg_ecal[iECAL2]+" "+name_leg_coll[iColl2],"p");
  leg->AddEntry(SCeta1,name_leg_ecal[iECAL1],"p");
  leg->AddEntry(SCeta2,name_leg_ecal[iECAL2],"p");
  leg->Draw();

  leg = new TLegend(0.16,0.725,0.58,0.905,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.03);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+names[iEG]+" GeV","h");
  leg->Draw();

  TPaveText *pt2 = new TPaveText(0.220,0.605,0.487,0.685,"brNDC"); // mid : x=353.5                                          
  pt2->SetLineColor(1);
  pt2->SetTextColor(1);
  pt2->SetTextFont(42);
  pt2->SetTextSize(0.03);
  pt2->SetFillColor(kWhite);
  pt2->SetShadowColor(kWhite);
  pt2->AddText("L1 E/Gamma Trigger");
  pt2->AddText("Electrons from Z");
  pt2->Draw();
  
  //TString name_image="eff_EG20_2012_12fb";

  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");
  ca->Print(name_image+".eps","eps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

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

  w->import(dataSet);
  w->import(dataSet2);
  
  w->import(*roofitres1,"roofitres1");
  w->import(*roofitres2,"roofitres2");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  //f1->Close();
}
コード例 #14
0
string runQuickRejig(string oldfilename, int ncats){
  
  string newfilename="TestWS.root";
  TFile *oldFile = TFile::Open(oldfilename.c_str());
  TFile *newFile = new TFile(newfilename.c_str(),"RECREATE");

  RooWorkspace *oldWS = (RooWorkspace*)oldFile->Get("cms_hgg_workspace");
  RooWorkspace *newWS = new RooWorkspace("wsig_8TeV");
  
  RooRealVar *mass = (RooRealVar*)oldWS->var("CMS_hgg_mass");

  RooDataSet *tot;

  RooRealVar *normT1 = new RooRealVar("nT1","nT1",500,0,550);
  RooRealVar *meanT1 = new RooRealVar("mT1","mT1",125,122,128);
  RooRealVar *sigmaT1 = new RooRealVar("sT1","sT1",3.1,1.,10.);
  RooGaussian *gausT1 = new RooGaussian("gT1","gT1",*mass,*meanT1,*sigmaT1);
  RooRealVar *normT2 = new RooRealVar("nT2","nT2",2,0,500);
  RooRealVar *meanT2 = new RooRealVar("mT2","mT2",125,122,128);
  RooRealVar *sigmaT2 = new RooRealVar("sT2","sT2",1.7,0.,10.);
  RooGaussian *gausT2 = new RooGaussian("gT2","gT2",*mass,*meanT2,*sigmaT2);
  RooRealVar *normT3 = new RooRealVar("nT3","nT3",2,0,500);
  RooRealVar *meanT3 = new RooRealVar("mT3","mT3",125,122,128);
  RooRealVar *sigmaT3 = new RooRealVar("sT3","sT3",1.7,0.,10.);
  RooGaussian *gausT3 = new RooGaussian("gT3","gT3",*mass,*meanT3,*sigmaT3);
  RooAddPdf *gausT = new RooAddPdf("gT","gT",RooArgList(*gausT1,*gausT2,*gausT3),RooArgList(*normT1,*normT2,*normT3));

  for (int cat=0; cat<ncats; cat++){
    RooDataSet *thisData = (RooDataSet*)oldWS->data(Form("sig_ggh_mass_m125_cat%d",cat));
    newWS->import(*thisData);
    RooRealVar *norm1 = new RooRealVar(Form("n1%d",cat),Form("n1%d",cat),500,0,550);
    RooRealVar *mean1 = new RooRealVar(Form("m1%d",cat),Form("m1%d",cat),125,122,128);
    RooRealVar *sigma1 = new RooRealVar(Form("s1%d",cat),Form("s1%d",cat),3.1,1.,10.);
    RooGaussian *gaus1 = new RooGaussian(Form("g1%d",cat),Form("g1%d",cat),*mass,*mean1,*sigma1);
    RooRealVar *norm2 = new RooRealVar(Form("n2%d",cat),Form("n2%d",cat),2,0,500);
    RooRealVar *mean2 = new RooRealVar(Form("m2%d",cat),Form("m2%d",cat),125,122,128);
    RooRealVar *sigma2 = new RooRealVar(Form("s2%d",cat),Form("s2%d",cat),1.7,0.,10.);
    RooGaussian *gaus2 = new RooGaussian(Form("g2%d",cat),Form("g2%d",cat),*mass,*mean2,*sigma2);
    RooRealVar *norm3 = new RooRealVar(Form("n3%d",cat),Form("n3%d",cat),2,0,500);
    RooRealVar *mean3 = new RooRealVar(Form("m3%d",cat),Form("m3%d",cat),125,122,128);
    RooRealVar *sigma3 = new RooRealVar(Form("s3%d",cat),Form("s3%d",cat),1.7,0.,10.);
    RooGaussian *gaus3 = new RooGaussian(Form("g3%d",cat),Form("g3%d",cat),*mass,*mean3,*sigma3);
    RooAddPdf *gaus = new RooAddPdf(Form("g%d",cat),"g",RooArgList(*gaus1,*gaus2,*gaus3),RooArgList(*norm1,*norm2,*norm3));
    gaus->fitTo(*thisData,SumW2Error(kTRUE));
    newWS->import(*gaus);
    if (cat==0) {
      tot = thisData;
      tot->SetName("sig_ggh_m125");
    }
    else tot->append(*thisData);
  }
  newWS->import(*tot);
  gausT->fitTo(*tot,SumW2Error(kTRUE));
  newWS->import(*gausT);
  newWS->Write();
  oldFile->Close();
  newFile->Close();
  delete newFile;
  delete newWS;

  return newfilename;

}
コード例 #15
0
void buildModel(int sel_i, TFile *fin, TDirectory *fout){

   // Define outputs
   RooWorkspace *wout = new RooWorkspace();
   wout->SetName(Form("normalization_cat%d",sel_i));
   fout->cd();

   // Input to this is TTrees 
   // Setup the "x" variable and weights 
   RooRealVar mvamet("metRaw","metRaw",200,1200);
   //RooRealVar mvamet("jet1mprune","jet1mprune",0,200);
   //RooRealVar mvamet("jet1tau2o1","jet1tau2o1",0,1);
   wout->import(mvamet);
   
   // TH1F Base Style
   std::string lName = "basehist";
   //const int numberofBins = 18;
   //double myBins[numberofBins+1] = {200,210,220,230,240,250,260,270,280,290,300,310,320,330,350,380,430,500,1200};
   //TH1F *lMet = new TH1F(lName.c_str(),lName.c_str(),numberofBins,myBins);
   TH1F *lMet = new TH1F(lName.c_str(),lName.c_str(),20,200,1200);
   //TH1F *lMet = new TH1F(lName.c_str(),lName.c_str(),20,0,1);

   // Make Datasets 
   makeAndImportDataSets(fin,wout,mvamet);

   // ==========================================================================================================
   const int nProcs = 27; 
   std::string procnames[nProcs];
   procnames[0]  = "DY";
   procnames[1]  = "RDY";
   procnames[2]  = "W";
   procnames[3]  = "WHT";
   procnames[4]  = "TT";
   procnames[5]  = "T";
   procnames[6]  = "ZZ";
   procnames[7]  = "WW";
   procnames[8]  = "WZ";
   procnames[9]  = "WH0";
   procnames[10]  = "ZH0";
   procnames[11] = "GGH0";
   procnames[12] = "VBFH0";
   //procnames[12] = "DY_control_bkg_mc";
   procnames[13] = "Zvv_control_mc";   
   procnames[14] = "T_control_bkg_mc"; 
   procnames[15] = "TT_control_bkg_mc";
   procnames[16] = "WW_control_bkg_mc";
   procnames[17] = "WZ_control_bkg_mc";
   procnames[18] = "ZZ_control_bkg_mc";

   procnames[19] = "Wlv_control_mc_1";   
   procnames[20] = "Wlv_control_mc_2";   
   procnames[21] = "T_sl_control_bkg_mc"; 
   procnames[22] = "TT_sl_control_bkg_mc";
   procnames[23] = "WW_sl_control_bkg_mc";
   procnames[24] = "WZ_sl_control_bkg_mc";
   procnames[25] = "ZZ_sl_control_bkg_mc";
   procnames[26] = "DY_sl_control_bkg_mc";


   
   // Fill TF1s which do not need corrections
   for (int p0=0;p0<nProcs;p0++){
     std::cout << "Filling hist for " << procnames[p0] << std::endl;;
     TH1F *hist_  = (TH1F*)generateTemplate(lMet, (TTree*)fin->Get(procnames[p0].c_str()), mvamet.GetName(), "weight",cutstring);  // standard processes are TTrees
     hist_->Write();
   }
   std::cout << "Filling hist for " << "data_obs" << std::endl;;
   TH1F *hist_  = (TH1F*)generateTemplate(lMet, (TTree*)fin->Get("data_obs"), mvamet.GetName(), "",cutstring);  // standard processes are TTrees
   hist_->Write();
   std::cout << "Filling hist for " << "Zvv_control" << std::endl;;
   hist_  = (TH1F*)generateTemplate(lMet, (TTree*)fin->Get("Zvv_control"), mvamet.GetName(), "",cutstring);  // standard processes are TTrees
   hist_->Write();
   std::cout << "Filling hist for " << "Wlv_control" << std::endl;;
   hist_  = (TH1F*)generateTemplate(lMet, (TTree*)fin->Get("Wlv_control"), mvamet.GetName(), "",cutstring);  // standard processes are TTrees
   hist_->Write();
   // ==========================================================================================================

   // Fit backgrounds to produce fit model
#ifdef RUN_CORRECTION 
   buildAndFitModels(fout,wout,mvamet,"Zvv");
   buildAndFitModels(fout,wout,mvamet,"Wlv");

   double mcyield   = wout->data("DY")->sumEntries();
   double datayield = wout->var("num_Zvv")->getVal();  // post fit number of data Z->mumu in control
   std::cout << "sfactor" << brscaleFactorZvv*datayield/mcyield << std::endl; 
   TH1F *hist_zvv = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("ratio_Zvv") , *(wout->var(mvamet.GetName())), (RooDataSet*) wout->data("DY")
   //TH1F *hist_zvv = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("") , *(wout->var(mvamet.GetName())), (RooDataSet*) wout->data("DY")
   		, 1 /*run correction*/
		, 1 /*brscaleFactorZvv*datayield/mcyield*/ /*additional weight*/);
   hist_zvv->Write();
   std::cout << " DataCardInfo ---------------- " << std::endl;
   std::cout << Form("  Zvv_norm gmN  %d  %g ",(int)datayield,hist_zvv->Integral()/datayield) << std::endl;
   std::cout << " ----------------------------- " << std::endl;

   // Also correct normalization data why not?
   hist_zvv = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("ratio_Zvv") , *(wout->var(mvamet.GetName())), (RooDataSet*) wout->data("Zvv_control_mc")
   		, 1 /*run correction*/
		, 1. /*additional weight*/);
   hist_zvv->Write();

   // Single muon
   mcyield   = wout->data("W")->sumEntries();
   datayield = wout->var("num_Wlv")->getVal();  // post fit number of data W->munu in control
   std::cout << "sfactor" << brscaleFactorWlv*datayield/mcyield << std::endl; 
   TH1F *hist_wlv = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("ratio_Wlv") , *(wout->var(mvamet.GetName())), (RooDataSet*) wout->data("W")
   		, 1 /*run correction*/
		, 1./*brscaleFactorWlv*datayield/mcyield*/ /*additional weight*/);
   hist_wlv->Write();
   std::cout << " DataCardInfo ---------------- " << std::endl;
   std::cout << Form("  Wlv_norm gmN  %d  %g ",(int)datayield,hist_wlv->Integral()/datayield) << std::endl;
   std::cout << " ----------------------------- " << std::endl;

   // Also correct normalization data why not?
   hist_wlv = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("ratio_Wlv") , *(wout->var(mvamet.GetName())), (RooDataSet*) wout->data("Wlv_control_mc")
   		, 1 /*run correction*/
		, 1. /*additional weight*/);
   hist_wlv->Write();
   //buildAndFitModels(fout,wout,mvamet,"Wlv");   
   //TH1F *hist_wlv = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("ratio_Wlv"), &mvamet, (RooDataSet*) wout->data(""));
   //hist_wlv->Write();
#endif
   // Since the W came in 2 parts, we can make the histogram based on the dataset (called uncorrected)
   TH1F *hist_wlv_uc = (TH1F*)generateTemplate(lMet, (RooFormulaVar*)wout->function("") , *(wout->var(mvamet.GetName())), (RooDataSet*) wout->data("W")
   		, 1 /*run correction forwards*/
		, 1./*brscaleFactorWlv*datayield/mcyield*/ /*additional weight*/);
   hist_wlv_uc->Write();


#ifdef RUN_BKGSYS
   // Load and run systematics from fit model
   std::vector<TH1F> v_th1f_Z;
   generateVariations(lMet,(RooFitResult*)fout->Get("fitResult_Zvv_control"),(RooFormulaVar*)wout->function("ratio_Zvv"),wout->var(mvamet.GetName()),v_th1f_Z,wout,"DY");
   std::vector<TH1F> v_th1f_W;
   generateVariations(lMet,(RooFitResult*)fout->Get("fitResult_Wlv_control"),(RooFormulaVar*)wout->function("ratio_Wlv"),wout->var(mvamet.GetName()),v_th1f_W,wout,"W");

   // Nice plots
   hist_zvv = (TH1F*)fout->Get("th1f_corrected_DY");
   hist_wlv = (TH1F*)fout->Get("th1f_corrected_W");
   
   double norm = hist_zvv->Integral();
   int colit=2, styleit=1;
   TCanvas *can_zvv_systs = new TCanvas("can_zvv_systs","can_zvv_systs",800,600);
   TLegend *leg = new TLegend(0.6,0.4,0.89,0.89); leg->SetFillColor(0); leg->SetTextFont(42);
   hist_zvv->SetLineColor(1);hist_zvv->SetLineWidth(3); hist_zvv->Draw();
   for (std::vector<TH1F>::iterator hit=v_th1f_Z.begin();hit!=v_th1f_Z.end();hit++){
     hit->SetLineColor(colit);
     hit->SetLineWidth(3);
     hit->SetLineStyle(styleit%2+1);
     leg->AddEntry(&(*hit),hit->GetName(),"L");
     hit->Scale(norm/hit->Integral());
     hit->Draw("same"); 
     hit->Write();
     styleit++;
     if (styleit%2==1) colit++;
   }
   leg->Draw();
   can_zvv_systs->Write();

   norm = hist_wlv->Integral();
   styleit=1; colit=2; 
   TCanvas *can_wlv_systs = new TCanvas("can_wlv_systs","can_wlv_systs",800,600);
   TLegend *leg_2 = new TLegend(0.6,0.4,0.89,0.89); leg_2->SetFillColor(0); leg_2->SetTextFont(42);
   hist_wlv->SetLineColor(1);hist_wlv->SetLineWidth(3); hist_wlv->Draw();
   for (std::vector<TH1F>::iterator hit=v_th1f_W.begin();hit!=v_th1f_W.end();hit++){
     hit->SetLineColor(colit);
     hit->SetLineWidth(3);
     hit->SetLineStyle(styleit%2+1);
     leg_2->AddEntry(&(*hit),hit->GetName(),"L");
     hit->Scale(norm/hit->Integral());
     hit->Draw("same"); 
     hit->Write();
     styleit++;
     if (styleit%2==1) colit++;
   }
   leg_2->Draw();
   can_wlv_systs->Write();

#endif 

   // Save the work
   fout->cd();
   wout->Write();
   // Done!
}
コード例 #16
0
ファイル: mytest.C プロジェクト: nadjieh/Haamumu
void mytest(int seed = 37) {
    using namespace RooFit;
    using namespace std;
	int nbin = 50;
    bool binned = true;
    stringstream nSig;
    stringstream nBkg;
    stringstream bwRatio;
    stringstream bRatio;
    stringstream mass = "60";
    double bL = 20.;//std::atof(mass.str().c_str()) - 10;
    double bH = 70.;//std::atof(mass.str().c_str()) + 10;
    TString pf = "4_4";
    nSig << 3.84;
    nBkg << 552;
    double bkgUnc = 1;//(510-424.)/424.; //50%
    bwRatio << 0.2;
    bRatio << 0.8;
    stringstream range;
    range << bL << "," << bH;
    cout << "Mass: " << mass.str() << endl;
    cout << "Range: " << range.str() << endl;
    TString Range = range.str().c_str();
    TString Mass = mass.str().c_str();
    ///	Data-fit ////////////////
    TString fname = ""; 
    if(!binned)
	    fname = "hamb-shapes-UnbinnedParam-m" + Mass + "-Data-fit.root";
	else
	    fname = "hamb-shapes-BinnedParam-m" + Mass + "-Data-fit.root";		
	
	if(!binned){
		TString name = "test";
    	RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH);
    	TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ");
    	TTree* hbkg = (TTree*) fbkg->Get("rds_zbb");
	    RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, "");
    	RooRandom::randomGenerator()->SetSeed(seed);
    	RooWorkspace *w = new RooWorkspace("w", "w");
    	w->factory("eventSelectionamassMu[" + Range + "]"/*,Range(SM, 50,70)"*/);
    	w->import(bkgData);
    	w->factory("KeysPdf::"+name+"_bkg_dimu(eventSelectionamassMu,bkgData)");

    	TFile* f = new TFile("DoubleMu2012_Summer12_final_" + pf + ".root", "READ");
    	TTree* hh = (TTree*) f->Get("rds_zbb");
    	RooDataSet data("data_dimu", "data", hh, eventSelectionamassMu, "");
    	w->import(data);
    	TH1D * hData = data.createHistogram("data_obs",eventSelectionamassMu,Binning(nbin));
    	double frac = (double)hData->Integral()/(double)nbin;
    	nBkg.str("");
    	nBkg << hData->Integral() - (5 * frac);

    	TFile * fsig = new TFile("H2ToH1H1_H1To2Mu2B_mH2-125_mH1-" + Mass + "_Summer12_final_" + pf + ".root", "read");
    	TTree* hsig = (TTree*) fsig->Get("rds_zbb");
    	RooDataSet sigData("sigData_dimu", "sigData", hsig, eventSelectionamassMu, "");
    	w->import(sigData);
    	w->factory("KeysPdf::" + name + "_sigPdf_dimu(eventSelectionamassMu,sigData_dimu)");
    	   
    	w->factory(name + "_bkg_dimu_norm[" + nBkg.str().c_str() + "]");
    	w->factory(name + "_sigPdf_dimu_norm[" + nSig.str().c_str() + "]");
   	
    	w->writeToFile(fname);
    	//w->var("eventSelectionamassMu")->setBins(55);
    	cardMaker(Mass, bkgUnc, binned);
		
	} else {
        RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH);
    	TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ");
    	TTree* hbkg = (TTree*) fbkg->Get("rds_zbb");
    	RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, "");
    	TH1D * hbkgData = bkgData.createHistogram("bkg",eventSelectionamassMu,Binning(nbin));
    	hbkgData->SetName("bkg");
	    TFile* f = new TFile("DoubleMu2012_Summer12_final_" + pf + ".root", "READ");
    	TTree* hh = (TTree*) f->Get("rds_zbb");
    	RooDataSet data("data_dimu", "data", hh, eventSelectionamassMu, "");
    	TH1D * hData = data.createHistogram("data_obs",eventSelectionamassMu,Binning(nbin));
    	int nData = hData->Integral();
    	double frac = (double)hData->Integral()/(double)nbin;
    	nBkg.str("");
    	nBkg << hData->Integral() - (5 * frac);
    	hData->SetName("data_obs");
   		TFile * fsig = new TFile("H2ToH1H1_H1To2Mu2B_mH2-125_mH1-" + Mass + "_Summer12_final_" + pf + ".root", "read");
    	TTree* hsig = (TTree*) fsig->Get("rds_zbb");
    	RooDataSet sigData("sigData_dimu", "sigData", hsig, eventSelectionamassMu, "");
	    TH1D * hsigData = sigData.createHistogram("signal",eventSelectionamassMu,Binning(nbin));
	    hsigData->SetName("signal");
	    
	    hbkgData->Scale(std::atof(nBkg.str().c_str())/hbkgData->Integral());
	    hsigData->Scale(std::atof(nSig.str().c_str())/hsigData->Integral());
	    	    
		TFile * fOut = new TFile(fname,"recreate");
		fOut->mkdir("dimu")->cd();
		hData->Write();
		hbkgData->Write();
		hsigData->Write();
		fOut->cd();
		fOut->Close();
	    cardMaker(Mass, bkgUnc, binned, std::atof(nSig.str().c_str()), std::atof(nBkg.str().c_str()), nData);
	}
}
コード例 #17
0
bool fitCharmoniaMassModel( RooWorkspace& myws,            // Local Workspace
                            const RooWorkspace& inputWorkspace,  // Workspace with all the input RooDatasets
                            struct KinCuts& cut,           // Variable containing all kinematic cuts
                            map<string, string>&  parIni,  // Variable containing all initial parameters
                            struct InputOpt& opt,          // Variable with run information (kept for legacy purpose)
                            string outputDir,              // Path to output directory
                            // Select the type of datasets to fit
                            string DSTAG,                  // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                            bool isPbPb      = false,      // isPbPb = false for pp, true for PbPb
                            bool importDS    = true,       // Select if the dataset is imported in the local workspace
                            // Select the type of object to fit
                            bool incJpsi     = true,       // Includes Jpsi model
                            bool incPsi2S    = true,       // Includes Psi(2S) model
                            bool incBkg      = true,       // Includes Background model
                            // Select the fitting options
                            bool doFit       = true,       // Flag to indicate if we want to perform the fit
                            bool cutCtau     = false,      // Apply prompt ctau cuts
                            bool doConstrFit   = false,    // Do constrained fit
                            bool doSimulFit  = false,      // Do simultaneous fit
                            bool wantPureSMC = false,      // Flag to indicate if we want to fit pure signal MC
                            const char* applyCorr ="",     // Flag to indicate if we want corrected dataset and which correction
                            uint loadFitResult = false,    // Load previous fit results
                            string inputFitDir = "",       // Location of the fit results
                            int  numCores    = 2,          // Number of cores used for fitting
                            // Select the drawing options
                            bool setLogScale = true,       // Draw plot with log scale
                            bool incSS       = false,      // Include Same Sign data
                            bool zoomPsi     = false,      // Zoom Psi(2S) peak on extra pad
                            double  binWidth = 0.05,       // Bin width used for plotting
                            bool getMeanPT   = false       // Compute the mean PT (NEED TO FIX)
                            )  
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return true;
};
コード例 #18
0
int main(int argc, char* argv[]) {

 doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

    

 epdf->Var("sig_yield");
 epdf->Var("sig_yield").setVal(153000);
 epdf->Var("sig_yield").setConstant(false);
 //decay time
 epdf->Var("obsTime");
 epdf->Var("obsTime").SetTitle("t_{#kern[-0.2]{B}_{#kern[-0.1]{ d}}^{#kern[-0.1]{ 0}}}");
 epdf->Var("obsTime").setUnit("ps");
 epdf->Var("obsTime").setRange(0.,16.);

 // tag, respectively the initial state of the produced B meson
 epdf->Cat("obsTag");
 epdf->Cat("obsTag").defineType("B_S",1);
 epdf->Cat("obsTag").defineType("Bbar_S",-1);

  //finalstate
  epdf->Cat("catFinalState");
  epdf->Cat("catFinalState").defineType("f",1);
  epdf->Cat("catFinalState").defineType("fbar",-1);

  epdf->Var("obsEtaOS");
  epdf->Var("obsEtaOS").setRange(0.0,0.5);


  std::vector<double> knots;
    knots.push_back(0.07);
    knots.push_back(0.10);
    knots.push_back(0.138);
    knots.push_back(0.16);
    knots.push_back(0.23);
    knots.push_back(0.28);
    knots.push_back(0.35);
    knots.push_back(0.42);
    knots.push_back(0.44);
    knots.push_back(0.48);
    knots.push_back(0.5);

  // empty arg list for coefficients
  RooArgList* list = new RooArgList();

  // create first coefficient
  RooRealVar* coeff_first = &(epdf->Var("parCSpline1"));
  coeff_first->setRange(0,10000);
  coeff_first->setVal(1);
  coeff_first->setConstant(false);
  list->add( *coeff_first );

  for (unsigned int i=1; i <= knots.size(); ++i){
    std::string number = boost::lexical_cast<std::string>(i);
    RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
    coeff->setRange(0,10000);
    coeff->setVal(1);
    coeff->setConstant(false);
    list->add( *coeff );
    }
  
  // create last coefficient
  RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
  coeff_last->setRange(0,10000);
  coeff_last->setVal(1);
  coeff_last->setConstant(false);
  list->add( *coeff_last );
  list->Print();
  // define Eta PDF
  doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
  
  //Berechne die Tagging Assymetrie
  epdf->Var("p0");
  epdf->Var("p0").setVal(0.369);
  epdf->Var("p0").setConstant(true);

  epdf->Var("p1");
  epdf->Var("p1").setVal(0.952);
  epdf->Var("p1").setConstant(true);

  epdf->Var("delta_p0");
  epdf->Var("delta_p0").setVal(0.019);
  epdf->Var("delta_p0").setConstant(true);

  epdf->Var("delta_p1");
  epdf->Var("delta_p1").setVal(-0.012);
  epdf->Var("delta_p1").setConstant(true);

  epdf->Var("etamean");
  epdf->Var("etamean").setVal(0.365);
  epdf->Var("etamean").setConstant(true);

  epdf->Formula("omega","@0 +@1/2 +(@2+@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
  epdf->Formula("omegabar","@0 -@1/2 +(@2-@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));


  //Koeffizienten
  DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_ch);
  epdf->AddRealToStore(coeff_sh);
  epdf->AddRealToStore(coeff_c);
  epdf->AddRealToStore(coeff_s);

  ///////////////////Generiere PDF's/////////////////////
  //Zeit
  epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
  epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));

  //Zusammenfassen der Parameter in einem RooArgSet
  RooArgSet Observables;
  Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));

  epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"),epdf->Real("sig_yield"));

  RooWorkspace ws;
    ws.import(epdf->Pdf("pdfExtend"));
    ws.defineSet("Observables",Observables, true);
    ws.Print();

    doofit::config::CommonConfig cfg_com("common");
    cfg_com.InitializeOptions(argc, argv);
    doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
    cfg_tfac.InitializeOptions(cfg_com);
    doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
    cfg_tstudy.InitializeOptions(cfg_tfac);

    // set a previously defined workspace to get PDF from (not mandatory, but convenient)
    cfg_tfac.set_workspace(&ws);
    cfg_com.CheckHelpFlagAndPrintHelp();

    // Initialize the toy factory module with the config objects and start
    // generating toy samples.
    doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
    doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);

  //Generate data
  RooDataSet* data = tfac.Generate();
  data->Print();
  epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt");
  epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt.new");

 
  //RooRealVar eta("eta","eta", 0, 0.5);
  //eta = data->mean(epdf->Var("obsEtaOS"));w

  
  epdf->Var("p0Fit");
  epdf->Var("p0Fit").setVal(0.369);
  epdf->Var("p0Fit").setConstant(true);

  epdf->Var("p1Fit");
  epdf->Var("p1Fit").setVal(0.952);
  epdf->Var("p1Fit").setConstant(true);

  epdf->Var("etameanFit");
  epdf->Var("etameanFit").setVal(0.365);
  epdf->Var("etameanFit").setConstant(true);

  epdf->Formula("omegaFit","@0+@1*(@2-@3)", RooArgList(epdf->Var("p0Fit"),epdf->Var("p1Fit"),epdf->Var("obsEtaOS"),epdf->Var("etameanFit")));
  /*epdf->Var("omegaFit");
  epdf->Var("omegaFit").setVal(0.369);
  epdf->Var("omegaFit").setConstant(true);*/
  //Koeffizienten
  DecRateCoeff *coeff_cFit  = new DecRateCoeff("coef_cosFit","coef_cosFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("tageff"),epdf->Real("omegaFit"),epdf->Real("omegaFit"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sFit  = new DecRateCoeff("coef_sinFit","coef_sinFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("tageff"),epdf->Real("omegaFit"),epdf->Real("omegaFit"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_shFit = new DecRateCoeff("coef_sinhFit","coef_sinhFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("tageff"),epdf->Real("omegaFit"),epdf->Real("omegaFit"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_chFit = new DecRateCoeff("coef_coshFit","coef_coshFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("tageff"),epdf->Real("omegaFit"),epdf->Real("omegaFit"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_chFit);
  epdf->AddRealToStore(coeff_shFit);
  epdf->AddRealToStore(coeff_cFit);
  epdf->AddRealToStore(coeff_sFit);

  //Fit PDF
  

  epdf->BDecay("pdfSigTimeFit",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_coshFit"),epdf->Real("coef_sinhFit"),epdf->Real("coef_cosFit"),epdf->Real("coef_sinFit"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));
     
	//Zusammenfassen der Parameter in einem RooArgSet
	RooArgSet ObservablesFit;
	ObservablesFit.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));

  epdf->Extend("pdfExtendFit", epdf->Pdf("pdfSigTimeFit"),epdf->Real("sig_yield"));
  epdf->Pdf("pdfExtendFit").fitTo(*data);
  //epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-fit-result.txt");
       
  //phido
  RooFitResult* fit_result = epdf->Pdf("pdfExtendFit").fitTo(*data, RooFit::Save(true));
  tstudy.StoreFitResult(fit_result);
  epdf->Pdf("pdfExtendFit").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt");
  epdf->Pdf("pdfExtendFit").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt.new");

  //Plotten auf lhcb
  /*using namespace doofit::plotting;

  PlotConfig cfg_plot("cfg_plot");
  cfg_plot.InitializeOptions();
  cfg_plot.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_omega-dgfloat-lhcb/time/");
  // plot PDF and directly specify components
  Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtendFit")));
  myplot.PlotItLogNoLogY();

  PlotConfig cfg_plotEta("cfg_plotEta");
  cfg_plotEta.InitializeOptions();
  cfg_plotEta.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_omega-dgfloat-lhcb/eta/");
  // plot PDF and directly specify components
  Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
  myplotEta.PlotIt();*/

 }
コード例 #19
0
int main(int argc, char* argv[]) {

     doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();
     
     //Mass 
     //epdf->Var("obsMass").setVal(5280);
     //epdf->Var("obsMass").setRange(5200.,5500.);
     //epdf->Var("obsMass").SetTitle("Masse");


	//decay time
	epdf->Var("obsTime");
	epdf->Var("obsTime").SetTitle("t_{#kern[-0.3]{B}^{#kern[-0.3]{0}}}");
	epdf->Var("obsTime").setUnit("ps");
	epdf->Var("obsTime").setRange(0.,16.);

	// tag, respectively the initial state of the produced B meson
	epdf->Cat("obsTag");
	epdf->Cat("obsTag").defineType("B",1);
	epdf->Cat("obsTag").defineType("Bbar",-1);

	//finalstate
	epdf->Cat("catFinalState");
	epdf->Cat("catFinalState").defineType("f",1);
	epdf->Cat("catFinalState").defineType("fbar",-1);

     epdf->Var("sig_Yield");
     epdf->Var("sig_Yield").setVal(490000);

	//Zusammenfassen der Parameter in einem RooArgSet
     //RooArgSet Observables;
     //Observables.add(RooArgSet(epdf->Var("obsMass"), epdf->Var("obsTime"), epdf->Cat("catFinalState"), epdf->Cat("obsTag") ));

     /*std::vector<double> knots;
     knots.push_back(0.07);
     knots.push_back(0.10);
     knots.push_back(0.138);
     knots.push_back(0.16);
     knots.push_back(0.23);
     knots.push_back(0.28);
     knots.push_back(0.35);
     knots.push_back(0.42);
     knots.push_back(0.44);
     knots.push_back(0.48);
     knots.push_back(0.5);

   // empty arg list for coefficients
     RooArgList* list = new RooArgList();
  
   // create first coefficient
     RooRealVar* coeff_first = &(epdf.Var("parCSpline1"));
     coeff_first->setRange(0,10000);
     coeff_first->setVal(1);
     coeff_first->setConstant(false);
     list->add( *coeff_first );

   for (unsigned int i=1; i <= knots.size(); ++i){
      std::string number = boost::lexical_cast<std::string>(i);
      RooRealVar* coeff = &(epdf.Var("parCSpline"+number));
      coeff->setRange(0,10000);
      coeff->setVal(1);
      coeff->setConstant(false);
      list->add( *coeff );
   }

   // create last coefficient
   RooRealVar* coeff_last = &(epdf.Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
   coeff_last->setRange(0,10000);
   coeff_last->setVal(1);
   coeff_last->setConstant(false);
   list->add( *coeff_last );

   list->Print();*/

     //Koeffizienten
	DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("tageff"),epdf->Var("eta"),epdf->Var("etabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
	DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("tageff"),epdf->Var("eta"),epdf->Var("etabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
	DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("tageff"),epdf->Var("eta"),epdf->Var("etabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
	DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("tageff"),epdf->Var("eta"),epdf->Var("etabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

	epdf->AddRealToStore(coeff_ch);
	epdf->AddRealToStore(coeff_sh);
	epdf->AddRealToStore(coeff_c);
	epdf->AddRealToStore(coeff_s);


	///////////////////Generiere PDF's/////////////////////
	//Zeit
	epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
	epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));
	//doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf.Var("obsEtaOS"),knots,*list,0,0.5);


     //Zeit Untergrund
	//epdf->Exponential("pdf_bkg_mass_time", epdf->Var("obsTime"), epdf->Var("tau_bkg"));
     epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"), epdf->Real("sig_Yield"));

	
	//PDF für SIgnal und UNtergrund der Massedoo
	/*epdf->Gaussian("pdf_sig_mass_gauss", epdf->Var("obsMass"), epdf->Var("pdf_sig_mass_mean"),epdf->Var("pdf_sig_mass_width"));
	epdf->Exponential("pdf_bkg_mass_expo", epdf->Var("obsMass"),epdf->Var("pdf_bkg_mass_lambda"));*/




     
     
     //Zusammenfassen der Parameter in einem RooArgSet
     RooArgSet Observables;
     Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag")));

     
     
  
     

     //Multipliziere Signal und Untergrund PDF mit ihrer jeweiligen Zerfalls PDF//
     //Untergrund * Zerfall
     /*epdf->Product("pdf_bkg", RooArgSet(epdf->Pdf("pdf_bkg_mass_expo"), epdf->Pdf("pdf_bkg_mass_time")));
     //Signal * Zerfall
     epdf->Product("pdf_sig", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss"),epdf->Pdf("pdfSigTime")));
	//Addiere PDF's
     epdf->Add("pdf_total", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss*pdf_sig_time_decay"), epdf->Pdf("pdf_bkg_mass*pdf_bkg_time_decay")), RooArgSet(epdf->Var("bkg_Yield"),epdf->Var("sig_Yield")));*/


    	    


     
     
     RooWorkspace ws;
     ws.import(epdf->Pdf("pdfExtend"));
     ws.defineSet("Observables",Observables, true);

     ws.Print();

     doofit::config::CommonConfig cfg_com("common");
     cfg_com.InitializeOptions(argc, argv);
     doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
     cfg_tfac.InitializeOptions(cfg_com);
     doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
     cfg_tstudy.InitializeOptions(cfg_tfac);

     // set a previously defined workspace to get PDF from (not mandatory, but convenient)
     cfg_tfac.set_workspace(&ws);

     // Check for a set --help flag and if so, print help and exit gracefully
     // (recommended).
     cfg_com.CheckHelpFlagAndPrintHelp();

     // More custom code, e.g. to set options internally.
     // Not required as configuration via command line/config file is enough.


     // Print overview of all options (optional)
     // cfg_com.PrintAll();

     // Initialize the toy factory module with the config objects and start
     // generating toy samples.
     doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
     doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);


     //for(int i=0;i<100;i++)
     //{
     RooDataSet* data = tfac.Generate();
     epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt");
     epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt.new");

     // fitting on the generated dataset is your responsibility
     RooFitResult* fit_result = epdf->Pdf("pdfExtend").fitTo(*data, RooFit::Save(true));
  
    /*epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/fit-result.txt");

  	 using namespace doofit::plotting;

     PlotConfig cfg_plot("cfg_plot");
     cfg_plot.InitializeOptions();

     // plot PDF and directly specify component
     Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
     myplot.PlotItLogNoLogY();*/

     //Speichern der Ergebnisse
     tstudy.StoreFitResult(fit_result);
     //}
     /*tstudy.FinishFitResultSaving();
     tstudy.ReadFitResults();
     tstudy.EvaluateFitResults();
     tstudy.PlotEvaluatedParameters();*/
    


 }
コード例 #20
0
ファイル: Raa3S_Workspace.C プロジェクト: echapon/upsilonPbPb
void Raa3S_Workspace(const char* filename="fitresult_combo_nofixed.root"){

   TFile File(filename);

   RooWorkspace * ws;
   File.GetObject("wcombo", ws);
   // ws->Print();
   RooAbsData * data = ws->data("data");

   // RooDataSet * US_data = (RooDataSet*) data->reduce( "QQsign == QQsign::PlusMinus");
   // US_data->SetName("US_data");
   // ws->import(* US_data);
   // RooDataSet * hi_data = (RooDataSet*) US_data->reduce("dataCat == dataCat::hi");
   // hi_data->SetName("hi_data");
   // ws->import(* hi_data);
   // hi_data->Print();

   RooRealVar* raa3 = new RooRealVar("raa3","R_{AA}(#Upsilon (3S))",0.5,0,1);
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",0);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",1);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*raa3, *leftEdge, *rightEdge));
   ws->import(step);
   ws->factory( "Uniform::flat(raa3)" );

   //pp Luminosities, Taa and efficiency ratios Systematics

   ws->factory( "Taa_hi[5.662e-9]" );
   ws->factory( "Taa_kappa[1.057]" );
   ws->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" );
   ws->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" );
   ws->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" );

   ws->factory( "lumipp_hi[5.4]" );
   ws->factory( "lumipp_kappa[1.06]" );
   ws->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" );
   ws->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" );
   ws->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" );

   // ws->factory( "effRat1[1]" );
   // ws->factory( "effRat2[1]" );
   ws->factory( "effRat3_hi[0.95]" );
   ws->factory( "effRat_kappa[1.054]" );
   ws->factory( "expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])" );
   // ws->factory( "prod::effRat1_nom(effRat1_hi,alpha_effRat)" );
   ws->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" );
   // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" );
   ws->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" );
   //  
   ws->factory("Nmb_hi[1.161e9]");
   ws->factory("prod::denominator(Taa_nom,Nmb_hi)");
   ws->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)");
   RooFormulaVar *lumiOverTaaNmbmodified = ws->function("lumiOverTaaNmbmodified");
   //  
   //  RooRealVar *raa1 = ws->var("raa1");
   //  RooRealVar* nsig1_pp = ws->var("nsig1_pp");
   //  RooRealVar* effRat1 = ws->function("effRat1_nom");
   //  RooRealVar *raa2 = ws->var("raa2");
   //  RooRealVar* nsig2_pp = ws->var("nsig2_pp");
   //  RooRealVar* effRat2 = ws->function("effRat2_nom");
   RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   cout << nsig3_pp << endl;
   RooRealVar* effRat3 = ws->function("effRat3_nom");
   //  
   //  RooFormulaVar nsig1_hi_modified("nsig1_hi_modified", "@0*@1*@3/@2", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1));
   //  ws->import(nsig1_hi_modified);
   //  RooFormulaVar nsig2_hi_modified("nsig2_hi_modified", "@0*@1*@3/@2", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2));
   //  ws->import(nsig2_hi_modified);
   RooFormulaVar nsig3_hi_modified("nsig3_hi_modified", "@0*@1*@3/@2", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3));
   ws->import(nsig3_hi_modified);

   //  // background yield with systematics
   ws->factory( "nbkg_hi_kappa[1.10]" );
   ws->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" );
   ws->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" );
   ws->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" );
   RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi");
   RooAbsPdf* sig2S_hi = ws->pdf("sig2S_hi");
   RooAbsPdf* sig3S_hi = ws->pdf("sig3S_hi");
   RooAbsPdf* LSBackground_hi = ws->pdf("nbkg_hi_nom");
   RooRealVar* nsig1_hi = ws->var("N_{#Upsilon(1S)}_hi");
   RooRealVar* nsig2_hi = ws->var("N_{#Upsilon(2S)}_hi");
   cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl;
   RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified");
   RooRealVar* norm_nbkg_hi = ws->var("n_{Bkgd}_hi");

   RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi);
   RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi);

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

   ws->factory( "nbkg_pp_kappa[1.03]" );
   ws->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" );
   ws->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" );
   ws->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" );
   RooAbsPdf* sig1S_pp = ws->pdf("cbcb_pp");
   RooAbsPdf* sig2S_pp = ws->pdf("sig2S_pp");
   RooAbsPdf* sig3S_pp = ws->pdf("sig3S_pp");
   RooAbsPdf* LSBackground_pp = ws->pdf("nbkg_pp_nom");
   RooRealVar* nsig1_pp = ws->var("N_{#Upsilon(1S)}_pp");
   RooRealVar* nsig2_pp = ws->var("N_{#Upsilon(2S)}_pp");
   RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   RooRealVar* norm_nbkg_pp = ws->var("n_{Bkgd}_pp");

   RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp);
   RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp);

   RooAddPdf model_num("model_num", "model_num", pdfs_hi,norms_hi); 
   ws->import(model_num);
   ws->factory("PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)");

   RooAddPdf model_den("model_den", "model_den", pdfs_pp,norms_pp); 
   ws->import(model_den);
   ws->factory("PROD::model_pp(model_den, constr_nbkg_pp)");

   ws->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)");



   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws->var("invariantMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws->cat("dataCat"));    
   //  /////////////////////////////////////////////////////////////////////
   ws->var("glob_lumipp")->setConstant(true);
   ws->var("glob_Taa")->setConstant(true);
   ws->var("glob_effRat")->setConstant(true);
   ws->var("glob_nbkg_pp")->setConstant(true);
   ws->var("glob_nbkg_hi")->setConstant(true);
   RooArgSet globalObs("global_obs");
   globalObs.add( *ws->var("glob_lumipp") );
   globalObs.add( *ws->var("glob_Taa") );
   globalObs.add( *ws->var("glob_effRat") );
   globalObs.add( *ws->var("glob_nbkg_hi") );
   globalObs.add( *ws->var("glob_nbkg_pp") );

   // ws->Print();

   RooArgSet poi("poi");
   poi.add( *ws->var("raa3") );



   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   nuis.add( *ws->var("beta_lumipp") );
   nuis.add( *ws->var("beta_nbkg_hi") );
   nuis.add( *ws->var("beta_nbkg_pp") );
   nuis.add( *ws->var("beta_Taa") );
   nuis.add( *ws->var("beta_effRat") );

   ws->var("#alpha_{CB}_hi")->setConstant(true);
   ws->var("#alpha_{CB}_pp")->setConstant(true);
   ws->var("#sigma_{CB1}_hi")->setConstant(true);
   ws->var("#sigma_{CB1}_pp")->setConstant(true);
   ws->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true);
   ws->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true);
   ws->var("Centrality")->setConstant(true);
   ws->var("N_{#Upsilon(1S)}_hi")->setConstant(true);
   ws->var("N_{#Upsilon(1S)}_pp")->setConstant(true);
   ws->var("N_{#Upsilon(2S)}_hi")->setConstant(true);
   ws->var("N_{#Upsilon(2S)}_pp")->setConstant(true);
   ws->var("N_{#Upsilon(3S)}_pp")->setConstant(true);
   ws->var("Nmb_hi")->setConstant(true);
   // ws->var("QQsign")->setConstant(true);
   ws->var("Taa_hi")->setConstant(true);
   ws->var("Taa_kappa")->setConstant(true);
   // ws->var("beta_Taa")->setConstant(true);
   // ws->var("beta_effRat")->setConstant(true);
   // ws->var("beta_lumipp")->setConstant(true);
   // ws->var("beta_nbkg_hi")->setConstant(true);
   // ws->var("beta_nbkg_pp")->setConstant(true);
   // ws->var("dataCat")->setConstant(true);
   ws->var("decay_hi")->setConstant(true);
   ws->var("decay_pp")->setConstant(true);
   ws->var("effRat3_hi")->setConstant(true);
   ws->var("effRat_kappa")->setConstant(true);
   // ws->var("glob_Taa")->setConstant(true);
   // ws->var("glob_effRat")->setConstant(true);
   // ws->var("glob_lumipp")->setConstant(true);
   // ws->var("glob_nbkg_hi")->setConstant(true);
   // ws->var("glob_nbkg_pp")->setConstant(true);
   // ws->var("invariantMass")->setConstant(true);
   ws->var("leftEdge")->setConstant(true);
   ws->var("lumipp_hi")->setConstant(true);
   ws->var("lumipp_kappa")->setConstant(true);
   ws->var("mass1S_hi")->setConstant(true);
   ws->var("mass1S_pp")->setConstant(true);
   ws->var("muMinusPt")->setConstant(true);
   ws->var("muPlusPt")->setConstant(true);
   ws->var("n_{Bkgd}_hi")->setConstant(true);
   ws->var("n_{Bkgd}_pp")->setConstant(true);
   ws->var("nbkg_hi_kappa")->setConstant(true);
   ws->var("nbkg_pp_kappa")->setConstant(true);
   ws->var("npow")->setConstant(true);
   ws->var("N_{#Upsilon(3S)}_pp")->setConstant(true);
   // ws->var("raa3")->setConstant(true);
   ws->var("rightEdge")->setConstant(true);
   ws->var("sigmaFraction_hi")->setConstant(true);
   ws->var("sigmaFraction_pp")->setConstant(true);
   ws->var("turnOn_hi")->setConstant(true);
   ws->var("turnOn_pp")->setConstant(true);
   ws->var("upsPt")->setConstant(true);
   ws->var("upsRapidity")->setConstant(true);
   ws->var("vProb")->setConstant(true);
   ws->var("width_hi")->setConstant(true);
   ws->var("width_pp")->setConstant(true);
   ws->var("x3raw")->setConstant(true);
   //  RooArgSet fixed_again("fixed_again");
   //  fixed_again.add( *ws->var("leftEdge") );
   //  fixed_again.add( *ws->var("rightEdge") );
   //  fixed_again.add( *ws->var("Taa_hi") );
   //  fixed_again.add( *ws->var("Nmb_hi") );
   //  fixed_again.add( *ws->var("lumipp_hi") );
   //  fixed_again.add( *ws->var("effRat1_hi") );
   //  fixed_again.add( *ws->var("effRat2_hi") );
   //  fixed_again.add( *ws->var("effRat3_hi") );
   //  fixed_again.add( *ws->var("nsig3_pp") );
   //  fixed_again.add( *ws->var("nsig1_pp") );
   //  fixed_again.add( *ws->var("nbkg_hi") );
   //  fixed_again.add( *ws->var("alpha") );
   //  fixed_again.add( *ws->var("nbkg_kappa") );
   //  fixed_again.add( *ws->var("Taa_kappa") );
   //  fixed_again.add( *ws->var("lumipp_kappa") );
   // fixed_again.add( *ws->var("mean_hi") );
   // fixed_again.add( *ws->var("mean_pp") );
   // fixed_again.add( *ws->var("width_hi") );
   // fixed_again.add( *ws->var("turnOn_hi") );
   // fixed_again.add( *ws->var("bkg_a1_pp") );
   // fixed_again.add( *ws->var("bkg_a2_pp") );
   // fixed_again.add( *ws->var("decay_hi") );
   // fixed_again.add( *ws->var("raa1") );
   // fixed_again.add( *ws->var("raa2") );
   //  fixed_again.add( *ws->var("nsig2_pp") );
   // fixed_again.add( *ws->var("sigma1") );
   //  fixed_again.add( *ws->var("nbkg_pp") );
   // fixed_again.add( *ws->var("npow") );
   // fixed_again.add( *ws->var("muPlusPt") );
   // fixed_again.add( *ws->var("muMinusPt") );
   // fixed_again.add( *ws->var("mscale_hi") );
   // fixed_again.add( *ws->var("mscale_pp") );
   //  
   // ws->Print();

   // create signal+background Model Config
   RooStats::ModelConfig sbHypo("SbHypo");
   sbHypo.SetWorkspace( *ws );
   sbHypo.SetPdf( *ws->pdf("joint") );
   sbHypo.SetObservables( obs );
   sbHypo.SetGlobalObservables( globalObs );
   sbHypo.SetParametersOfInterest( poi );
   sbHypo.SetNuisanceParameters( nuis );
   sbHypo.SetPriorPdf( *ws->pdf("step") ); // this is optional

   // ws->Print();
   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3"));
   pNll->plotOn(framepoi,ShiftToZero());
   
   RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
   pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
   pProfile->plotOn(framepoi,LineColor(kRed));
   framepoi->SetMinimum(0);
   framepoi->SetMaximum(3);
   TCanvas *cpoi = new TCanvas();
   cpoi->cd(); framepoi->Draw();
   cpoi->SaveAs("cpoi.pdf");

   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
   // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeSB = pObs->frame(Title("SBhypo"));
   data->plotOn(xframeSB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfSB = sbHypo.GetPdf();
   RooCategory *dataCat = ws->cat("dataCat");
   pdfSB->plotOn(xframeSB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c1 = new TCanvas();
   c1->cd(); xframeSB->Draw();
   c1->SaveAs("c1.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;
   ws->import( sbHypo );
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   double oldval = ((RooRealVar *)poi.first())->getVal( ); 
   ((RooRealVar *)poi.first())->setVal( 0 );  // set raa3=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeB = pObs->frame(Title("Bhypo"));
   data->plotOn(xframeB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfB = bHypo.GetPdf();
   pdfB->plotOn(xframeB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c2 = new TCanvas();
   c2->cd(); xframeB->Draw();
   c2->SaveAs("c2.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;

   // import model config into workspace
   bHypo.SetWorkspace(*ws);
   ws->import( bHypo );
   /////////////////////////////////////////////////////////////////////
   ws->Print();
   bHypo.Print();
   sbHypo.Print();

   ((RooRealVar *)poi.first())->setVal( oldval );  // set raa3=oldval here
   // save workspace to file
   ws -> SaveAs("TRIAL.root");

   return;
}
コード例 #21
0
void check_fit_bias_sim(const int N=1, string infname="20140409_SimFits_M1850_DblMu0_AllCent/fracLogCBG_PbPbpol3_HI020_pol2_HI2040_pol2_HI40100_pppol2_rap16-24_pT3-30_centMult_Workspace.root")
{
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING);

  TFile *inf = new TFile(infname.c_str(),"READ");
  RooWorkspace *ws = (RooWorkspace*) inf->Get("workspace");
  // ws->var("doubleRatio_HI020")->setConstant(true);
  // ws->var("doubleRatio_HI2040")->setConstant(true);
  // ws->var("doubleRatio_HI40100")->setConstant(true);

  RooRealVar *Jpsi_Mass = ws->var("Jpsi_Mass");
  RooCategory *sample = ws->cat("sample");

  // TIter types(ws->cat("sample")->typeIterator());
  // RooCatType * type;
  // types.Reset();
  RooDataSet * protoData = (RooDataSet*) ws->data("redDataSim");
  RooDataSet * protoData_pp = (RooDataSet*) ws->data("data4");
  RooDataSet * protoData_HI020 = (RooDataSet*) ws->data("data1");
  RooDataSet * protoData_HI2040 = (RooDataSet*) ws->data("data2");
  RooDataSet * protoData_HI40100 = (RooDataSet*) ws->data("data3");

  //  RooSimultaneous *model = (RooSimultaneous*) ws->pdf("sigMassPDFSim");
  RooAbsPdf *model_pp = (RooAbsPdf*) ws->pdf("sigMassPDF_pp");
  RooAbsPdf *model_HI020 = (RooAbsPdf*) ws->pdf("pdf_HI020");
  RooAbsPdf *model_HI2040 = (RooAbsPdf*) ws->pdf("pdf_HI2040");
  RooAbsPdf *model_HI40100 = (RooAbsPdf*) ws->pdf("pdf_HI40100");

  // ws->var("sigma_pol")->setVal(0.0);
  // ws->var("sigma_b")->setVal(0.0);
  // ws->var("sigma_pol")->setConstant(true);
  // ws->var("sigma_b")->setConstant(true);

  // ws->var("sigma_fit_HI020")->setVal(0.0);
  // ws->var("sigma_eff_HI020")->setVal(0.0);
  // ws->var("sigma_fit_HI020")->setConstant(true);
  // ws->var("sigma_eff_HI020")->setConstant(true);

  // ws->var("sigma_fit_HI2040")->setVal(0.0);
  // ws->var("sigma_eff_HI2040")->setVal(0.0);
  // ws->var("sigma_fit_HI2040")->setConstant(true);
  // ws->var("sigma_eff_HI2040")->setConstant(true);

  // ws->var("sigma_fit_HI40100")->setVal(0.0);
  // ws->var("sigma_eff_HI40100")->setVal(0.0);
  // ws->var("sigma_fit_HI40100")->setConstant(true);
  // ws->var("sigma_eff_HI40100")->setConstant(true);

  RooPlot *frame = Jpsi_Mass->frame(Range("M2242"));
  protoData->plotOn(frame, Cut("sample==sample::pp"));
  protoData->plotOn(frame, Cut("sample==sample::HI020"), MarkerColor(kRed));
  protoData->plotOn(frame, Cut("sample==sample::HI2040"), MarkerStyle(25), MarkerColor(kBlue));
  protoData->plotOn(frame, Cut("sample==sample::HI40100"), MarkerStyle(24), MarkerColor(kGreen+2));

  //  model->plotOn(frame, Slice(*sample,"pp"), ProjWData(*sample,*protoData));
  TCanvas *c0 = new TCanvas("c0","c0");
  c0->cd();
  frame->Draw();
  //  return;
  //  ws->pdf("sigMassPDF_M2242")->plotOn(frame,Range("M2242"));
  //  redData->plotOn(frame,MarkerStyle(24),MarkerColor(kRed),Range("M2242"));


  // while ((type=(RooCatType*)types.Next())) {
  //   protoData = 
  //     (RooDataSet*)ws->data(TString::Format("data_%s", type->GetName()));
  //   bkg = ws.pdf(TString::Format("expFunct_%s", type->GetName()));
  //   if ((*type) == "HI")
  //     N = Nhi;
  //   else
  //     N = Npp;
  //   RooDataSet * tmpData = bkg->generate(RooArgSet(*Jpsi_mass), N,
  // 					 RooFit::ProtoData(*protoData));
  //   osBkgData->append(*tmpData);
  //   delete tmpData;
  // }



  //  double Nevents =  ws->var("NJpsi_pp")->getVal()+ws->function("NPsiP_pp")->getVal()+ws->var("NBkg_pp")->getVal();

  TH1F *h0_pp = new TH1F("h0_pp","h0_pp;R_{#psi}^{pp};Events",1200,-0.3,0.3);
  TH1F *h1_pp = new TH1F("h1_pp","h1_pp;R_{#psi}^{pp};Events",1200,-0.3,0.3);
  TH2F *h2_pp = new TH2F("h2_pp","h2_pp;R_{#psi}^{pp} (M1850);R_{#psi}^{pp} (M2242)",600,-0.3,0.3,600,-0.3,0.3);
  h0_pp->Sumw2();
  h1_pp->Sumw2();
  h2_pp->Sumw2();
  h1_pp->SetMarkerColor(2);
  h1_pp->SetLineColor(2);
  h0_pp->GetXaxis()->CenterTitle(true);
  h1_pp->GetXaxis()->CenterTitle(true);
  h2_pp->GetXaxis()->CenterTitle(true);

  TH1F *h0_HI020 = new TH1F("h0_HI020","h0_HI020;#chi_{#psi}^{HI020};Events",5000,-1.0,4.0);
  TH1F *h1_HI020 = new TH1F("h1_HI020","h1_HI020;#chi_{#psi}^{HI020};Events",5000,-1.0,4.0);
  TH2F *h2_HI020 = new TH2F("h2_HI020","h2_HI020;#chi_{#psi}^{HI020} (M1850);#chi_{#psi}^{HI020} (M2242)",500,-1,4,500,-1,4);
  h0_HI020->Sumw2();
  h1_HI020->Sumw2();
  h2_HI020->Sumw2();
  h1_HI020->SetMarkerColor(2);
  h1_HI020->SetLineColor(2);
  h0_HI020->GetXaxis()->CenterTitle(true);
  h1_HI020->GetXaxis()->CenterTitle(true);
  h2_HI020->GetXaxis()->CenterTitle(true);

  TH1F *h0_HI2040 = new TH1F("h0_HI2040","h0_HI2040;#chi_{#psi}^{HI2040};Events",5000,-1.0,4.0);
  TH1F *h1_HI2040 = new TH1F("h1_HI2040","h1_HI2040;#chi_{#psi}^{HI2040};Events",5000,-1.0,4.0);
  TH2F *h2_HI2040 = new TH2F("h2_HI2040","h2_HI2040;#chi_{#psi}^{HI2040} (M1850);#chi_{#psi}^{HI2040} (M2242)",500,-1,4,500,-1,4);
  h0_HI2040->Sumw2();
  h1_HI2040->Sumw2();
  h2_HI2040->Sumw2();
  h1_HI2040->SetMarkerColor(2);
  h1_HI2040->SetLineColor(2);
  h0_HI2040->GetXaxis()->CenterTitle(true);
  h1_HI2040->GetXaxis()->CenterTitle(true);
  h2_HI2040->GetXaxis()->CenterTitle(true);

  TH1F *h0_HI40100 = new TH1F("h0_HI40100","h0_HI40100;#chi_{#psi}^{HI40100};Events",5000,-1.0,4.0);
  TH1F *h1_HI40100 = new TH1F("h1_HI40100","h1_HI40100;#chi_{#psi}^{HI40100};Events",5000,-1.0,4.0);
  TH2F *h2_HI40100 = new TH2F("h2_HI40100","h2_HI40100;#chi_{#psi}^{HI40100} (M1850);#chi_{#psi}^{HI40100} (M2242)",500,-1,4,500,-1,4);
  h0_HI40100->Sumw2();
  h1_HI40100->Sumw2();
  h2_HI40100->Sumw2();
  h1_HI40100->SetMarkerColor(2);
  h1_HI40100->SetLineColor(2);
  h0_HI40100->GetXaxis()->CenterTitle(true);
  h1_HI40100->GetXaxis()->CenterTitle(true);
  h2_HI40100->GetXaxis()->CenterTitle(true);

  TH1F *h0_HI0100 = new TH1F("h0_HI0100","h0_HI0100;#chi_{#psi}^{HI0100};Events",5000,-1.0,4.0);
  TH1F *h1_HI0100 = new TH1F("h1_HI0100","h1_HI0100;#chi_{#psi}^{HI0100};Events",5000,-1.0,4.0);
  TH2F *h2_HI0100 = new TH2F("h2_HI0100","h2_HI0100;#chi_{#psi}^{HI0100} (M1850);#chi_{#psi}^{HI0100} (M2242)",500,-1,4,500,-1,4);
  h0_HI0100->Sumw2();
  h1_HI0100->Sumw2();
  h2_HI0100->Sumw2();
  h1_HI0100->SetMarkerColor(2);
  h1_HI0100->SetLineColor(2);
  h0_HI0100->GetXaxis()->CenterTitle(true);
  h1_HI0100->GetXaxis()->CenterTitle(true);
  h2_HI0100->GetXaxis()->CenterTitle(true);


  Jpsi_Mass->setRange("signal",3.6,3.76);
  Jpsi_Mass->setRange("M2045",2.0,4.5);
  Jpsi_Mass->setRange("M2242",2.2,4.2);

  RooFitResult *fitMall;
  RooFitResult *fitM;

  // RooFit cannot normalize Chebychev polynomials to a subrange (no analytic integral?)
  // using normal polynomials instead
  RooRealVar a("a","a",0.0);a.setConstant(false);
  RooRealVar b("b","b",0.01);b.setConstant(false);
  RooRealVar c("c","c",-0.005);c.setConstant(false);
  // mid
  //  RooPolynomial bkg_pp("bkg_pp","bkg_pp",*Jpsi_Mass,RooArgSet(a,b,c));
  // fwd
  RooPolynomial bkg_pp("bkg_pp","bkg_pp",*Jpsi_Mass,RooArgSet(a));//,b,c));

  RooRealVar a_HI020("a_HI020","a_HI020",0.0);a_HI020.setConstant(false);
  RooRealVar b_HI020("b_HI020","b_HI020",0.01);b_HI020.setConstant(false);
  RooRealVar c_HI020("c_HI020","c_HI020",-0.005);c_HI020.setConstant(false);
  // mid
  //  RooPolynomial bkg_HI020("bkg_HI020","bkg_HI020",*Jpsi_Mass,RooArgSet(a_HI020));//,b_HI020,c_HI020));
  // fwd
  RooPolynomial bkg_HI020("bkg_HI020","bkg_HI020",*Jpsi_Mass,RooArgSet(a_HI020,b_HI020,c_HI020));

  RooRealVar a_HI2040("a_HI2040","a_HI2040",0.0);a_HI2040.setConstant(false);
  RooRealVar b_HI2040("b_HI2040","b_HI2040",0.01);b_HI2040.setConstant(false);
  RooRealVar c_HI2040("c_HI2040","c_HI2040",-0.005);c_HI2040.setConstant(false);
  // mid
  //  RooPolynomial bkg_HI2040("bkg_HI2040","bkg_HI2040",*Jpsi_Mass,RooArgSet(a_HI2040));//,b_HI2040,c_HI2040));
  // fwd
  RooPolynomial bkg_HI2040("bkg_HI2040","bkg_HI2040",*Jpsi_Mass,RooArgSet(a_HI2040,b_HI2040));//,c_HI2040));

  RooRealVar a_HI40100("a_HI40100","a_HI40100",0.0);a_HI40100.setConstant(false);
  RooRealVar b_HI40100("b_HI40100","b_HI40100",0.01);b_HI40100.setConstant(false);
  RooRealVar c_HI40100("c_HI40100","c_HI40100",-0.005);c_HI40100.setConstant(false);
  // mid
  // a_HI40100.setConstant(true);
  // RooPolynomial bkg_HI40100("bkg_HI40100","bkg_HI40100",*Jpsi_Mass,RooArgSet(a_HI40100));//,b_HI40100,c_HI40100));
  // fwd
  RooPolynomial bkg_HI40100("bkg_HI40100","bkg_HI40100",*Jpsi_Mass,RooArgSet(a_HI40100));//,b_HI40100,c_HI40100));

  ws->import(bkg_pp);
  ws->import(bkg_HI020);
  ws->import(bkg_HI2040);
  ws->import(bkg_HI40100);

  ws->factory("SUM::sigMassPDF_pp_M2242(NJpsi_pp*sigCB1G2_HI,NPsiP_pp*sigCB1G2P_HI,NBkg_pp*bkg_pp)");
  ws->factory("SUM::sigMassPDF_HI020_M2242(NJpsi_HI020*sigCB1G2_HI,NPsiP_HI020*sigCB1G2P_HI,NBkg_HI020*bkg_HI020)");
  ws->factory("SUM::sigMassPDF_HI2040_M2242(NJpsi_HI2040*sigCB1G2_HI,NPsiP_HI2040*sigCB1G2P_HI,NBkg_HI2040*bkg_HI2040)");
  ws->factory("SUM::sigMassPDF_HI40100_M2242(NJpsi_HI40100*sigCB1G2_HI,NPsiP_HI40100*sigCB1G2P_HI,NBkg_HI40100*bkg_HI40100)");

  ws->factory("SIMUL::sigMassPDFSim_M2242(sample,HI020=sigMassPDF_HI020_M2242,HI2040=sigMassPDF_HI2040_M2242,HI40100=sigMassPDF_HI40100_M2242,pp=sigMassPDF_pp_M2242)");
    
  RooDataSet *data[N];
  RooDataSet *data_pp[N];
  RooDataSet *data_HI020[N];
  RooDataSet *data_HI2040[N];
  RooDataSet *data_HI40100[N];
  RooDataSet *redData;

  for (int i=0;i<N;++i) {
    cout << "Generating event " << i << "/" << N << endl;
    // cout << "Generate N = " << Nevents << " events with R_{psi} = " << ws->var("fracP_pp")->getVal() << endl;
    //    data[i] = model->generateSimGlobal(*Jpsi_Mass,ProtoData(*protoData), Verbose(1));
    data_pp[i] = model_pp->generate(*Jpsi_Mass, ProtoData(*protoData_pp),Verbose(0));
    data_HI020[i] = model_HI020->generate(*Jpsi_Mass, ProtoData(*protoData_HI020),Verbose(0));
    data_HI2040[i] = model_HI2040->generate(*Jpsi_Mass, ProtoData(*protoData_HI2040),Verbose(0));
    data_HI40100[i] = model_HI40100->generate(*Jpsi_Mass, ProtoData(*protoData_HI40100),Verbose(0));

    data[i] = new RooDataSet("data","data",RooArgSet(*Jpsi_Mass),Index(*sample),Import("HI020",*data_HI020[i]),Import("HI2040",*data_HI2040[i]),Import("HI40100",*data_HI40100[i]),Import("pp",*data_pp[i]));
  }
    
  RooPlot *frame2 = Jpsi_Mass->frame();
  data_pp[0]->plotOn(frame2);
  data[N-1]->plotOn(frame2, Cut("sample==sample::pp"),MarkerColor(kRed), MarkerStyle(24));
  data[N-1]->plotOn(frame2, Cut("sample==sample::HI020"), MarkerColor(kRed));
  data[N-1]->plotOn(frame2, Cut("sample==sample::HI2040"), MarkerStyle(25), MarkerColor(kBlue));
  data[N-1]->plotOn(frame2, Cut("sample==sample::HI40100"), MarkerStyle(24), MarkerColor(kGreen+2));
  // data[N-1]->plotOn(frame2, Cut("sample!=sample::pp"), MarkerColor(kRed));
  //  model->plotOn(frame, Slice(*sample,"pp"), ProjWData(*sample,*protoData));
  TCanvas *c0a = new TCanvas("c0a","c0a");
  c0a->cd();
  frame2->Draw();
  //  return;
  // cout << data->sumEntries() << endl;

  for (int i=0;i<N;++i) {
    cout << "Fitting event " << i << "/" << N << endl;
    fitMall = ws->pdf("sigMassPDFSim")->fitTo(*data[i],Extended(1),Hesse(1),Save(1),NumCPU(8),PrintEvalErrors(-1),Verbose(0),PrintLevel(-1));
    if (fitMall->statusCodeHistory(fitMall->numStatusHistory()-1) != 0) {i--; continue;}
    //    fitMall->Print("v");

    //    cout << "Fitted R_{psi} = " << ws->var("fracP_pp")->getVal() << " +/- " << ws->var("fracP_pp")->getPropagatedError(*fitMall) << endl;
    double R1850_pp = ws->var("fracP_pp")->getVal();
    double R1850_HI020 = ws->var("doubleRatio_HI020")->getVal();
    double R1850_HI2040 = ws->var("doubleRatio_HI2040")->getVal();
    double R1850_HI40100 = ws->var("doubleRatio_HI40100")->getVal();
    double R1850_HI0100 = ws->function("doubleRatio_HI0100")->getVal();
    h0_pp->Fill(R1850_pp);
    h0_HI020->Fill(R1850_HI020);
    h0_HI2040->Fill(R1850_HI2040);
    h0_HI40100->Fill(R1850_HI40100);
    h0_HI0100->Fill(R1850_HI0100);


    redData = (RooDataSet*)data[i]->reduce("Jpsi_Mass>2.2&&Jpsi_Mass<4.2");
    //  cout << redData->sumEntries() << endl;

    fitM = ws->pdf("sigMassPDFSim_M2242")->fitTo(*redData,Extended(1),Hesse(1),Save(1),NumCPU(8),PrintEvalErrors(-1),Verbose(0),PrintLevel(-1),Range("M2242"));
    if (fitM->statusCodeHistory(fitM->numStatusHistory()-1) != 0) {i--; continue;}

    //    fitM->Print("v");
    // cout << "Fit over M2242: R_{psi} = " << ws->var("fracP_pp")->getVal() << " +/- " << ws->var("fracP_pp")->getPropagatedError(*fitM) << endl;

    // RooPlot *frame = Jpsi_Mass->frame(Range("M2242"));
    // redData->plotOn(frame);
    // ws->pdf("sigMassPDF_M2242")->plotOn(frame,Range("M2242"));
    //  redData->plotOn(frame,MarkerStyle(24),MarkerColor(kRed),Range("M2242"));

    double R2242_pp = ws->var("fracP_pp")->getVal();
    double R2242_HI020 = ws->var("doubleRatio_HI020")->getVal();
    double R2242_HI2040 = ws->var("doubleRatio_HI2040")->getVal();
    double R2242_HI40100 = ws->var("doubleRatio_HI40100")->getVal();
    double R2242_HI0100 = ws->function("doubleRatio_HI0100")->getVal();
    h1_pp->Fill(R2242_pp);
    h1_HI020->Fill(R2242_HI020);
    h1_HI2040->Fill(R2242_HI2040);
    h1_HI40100->Fill(R2242_HI40100);
    h1_HI0100->Fill(R2242_HI0100);

    h2_pp->Fill(R1850_pp,R2242_pp);
    h2_HI020->Fill(R1850_HI020,R2242_HI020);
    h2_HI2040->Fill(R1850_HI2040,R2242_HI2040);
    h2_HI40100->Fill(R1850_HI40100,R2242_HI40100);
    h2_HI0100->Fill(R1850_HI0100,R2242_HI0100);
  }
  TCanvas *c1 = new TCanvas("c1","c1");
  c1->Divide(2,2);
  c1->cd(1);
  h0_pp->Draw();
  h1_pp->Draw("same");
  c1->cd(2);
  h0_HI020->Draw();
  h1_HI020->Draw("same");
  c1->cd(3);
  h0_HI2040->Draw();
  h1_HI2040->Draw("same");
  c1->cd(4);
  h0_HI40100->Draw();
  h1_HI40100->Draw("same");
  //  frame->Draw();
  cout << "pp" << endl;
  cout << h0_pp->GetMean() << "\t" << h0_pp->GetRMS() << endl;
  cout << h1_pp->GetMean() << "\t" << h1_pp->GetRMS() << endl;
  cout << 1-(h0_pp->GetMean()/h1_pp->GetMean()) << endl;

  cout << "HI020" << endl;
  cout << h0_HI020->GetMean() << "\t" << h0_HI020->GetRMS() << endl;
  cout << h1_HI020->GetMean() << "\t" << h1_HI020->GetRMS() << endl;
  cout << 1-(h0_HI020->GetMean()/h1_HI020->GetMean()) << endl;

  cout << "HI2040" << endl;
  cout << h0_HI2040->GetMean() << "\t" << h0_HI2040->GetRMS() << endl;
  cout << h1_HI2040->GetMean() << "\t" << h1_HI2040->GetRMS() << endl;
  cout << 1-(h0_HI2040->GetMean()/h1_HI2040->GetMean()) << endl;

  cout << "HI40100" << endl;
  cout << h0_HI40100->GetMean() << "\t" << h0_HI40100->GetRMS() << endl;
  cout << h1_HI40100->GetMean() << "\t" << h1_HI40100->GetRMS() << endl;
  cout << 1-(h0_HI40100->GetMean()/h1_HI40100->GetMean()) << endl;

  cout << "HI0100" << endl;
  cout << h0_HI0100->GetMean() << "\t" << h0_HI0100->GetRMS() << endl;
  cout << h1_HI0100->GetMean() << "\t" << h1_HI0100->GetRMS() << endl;
  cout << 1-(h0_HI0100->GetMean()/h1_HI0100->GetMean()) << endl;

  c1->SaveAs(Form("toy_fits_dblRatio_fwd_M1850_N%i.pdf",N));

  TF1 *f3 = new TF1("f3","x",-0.5,3.0);
  f3->SetLineWidth(1);
  TCanvas *c2 = new TCanvas("c2","c2");
  c2->Divide(2,2);
  c2->cd(1);
  h2_pp->Draw("colz");
  f3->Draw("same");
  c2->cd(2);
  h2_HI020->Draw("colz");
  f3->Draw("same");
  c2->cd(3);
  h2_HI2040->Draw("colz");
  f3->Draw("same");
  c2->cd(4);
  h2_HI40100->Draw("colz");
  f3->Draw("same");

  TCanvas *c3 = new TCanvas("c3","c3");
  c3->Divide(2,1);
  c3->cd(1);
  h0_HI0100->Draw();
  h1_HI0100->Draw("same");
  c3->cd(2);
  h2_HI0100->Draw("colz");
  f3->Draw("same");

  TFile *outf = new TFile(Form("toy_fits_dblRatio_fwd_M1850_N%i.root",N),"RECREATE");
  h0_pp->Write();
  h1_pp->Write();
  h2_pp->Write();
  h0_HI020->Write();
  h1_HI020->Write();
  h2_HI020->Write();
  h0_HI2040->Write();
  h1_HI2040->Write();
  h2_HI2040->Write();
  h0_HI40100->Write();
  h1_HI40100->Write();
  h2_HI40100->Write();
  h0_HI0100->Write();
  h1_HI0100->Write();
  h2_HI0100->Write();
  outf->Close();


  return;
}
コード例 #22
0
ファイル: exercise_0.C プロジェクト: pellicci/UserCode
void exercise_0()
{

  //First, define the observable for the analysis
  RooRealVar mass("mass","mass",100.,150.);

  //Construct the signal P.D.F., a gaussian function
  RooRealVar mean("mean","mean of gaussian",125.,110.,140.);
  RooRealVar sigma("sigma","width of gaussian",6.,0.01,10.);
  RooGaussian gauss("gauss","Signal PDF",mass,mean,sigma);  

  //Now define the background P.D.F, a simple exponential
  RooRealVar tau("tau","exponential function parameter",-0.05,-10.,-0.001);
  RooExponential exponential("exponential","Background PDF",mass,tau);

  //Now construct the total PDF. We need to define the number of signal and background events in the model
  //
  //for UL calculation use Nsig = 5, Nbkg = 100
  //for mH calculation use Nsig = 50, Nbkg = 450
  //for systematics inclusion use Nsig = 20, Nbkg = 100, also, with the width set to 5 GeV!!
  RooRealVar Nsig("Nsig","Number of signal events",20.,0.,200.);
  RooRealVar Nbkg("Nbkg","Number of background events",100.,0.,1000.);

  RooAddPdf PDFtot("PDFtot","PDFtot",RooArgList(gauss,exponential),RooArgList(Nsig,Nbkg));

  //Now generate a sample with the total PDF
  RooDataSet *data = PDFtot.generate(RooArgSet(mass),NumEvents(Nsig.getVal()+Nbkg.getVal()),Extended(1));

  //Now fit the PDF to the data
  //For low statistics, fix the mean and the width
  mean.setConstant(kTRUE);
  sigma.setConstant(kTRUE);
  PDFtot.fitTo(*data);

  // Print values of mean and sigma (that now reflect fitted values and errors, unless you fixed them)
  mean.Print();
  sigma.Print();

  //Now plot the data and the fitted PDF
  RooPlot *massframe = mass.frame(50);
  data->plotOn(massframe);
  PDFtot.plotOn(massframe);

  //One can also plot the single components of the total PDF, like the background component
  PDFtot.plotOn(massframe,Components(exponential),LineStyle(kDashed),LineColor(kRed));

  //Actually plot the result
  TCanvas c1;
  c1.cd();
  massframe->Draw();
  c1.SaveAs("exercise_0.gif");

  //Now save the data and the PDF into a Workspace, for later use for statistical analysis
  //and save the workspace into a ROOT file
  RooWorkspace* w = new RooWorkspace("w") ;
  w->import(*data);
  w->import(PDFtot);

  TFile fOut("exercise_0.root","RECREATE");
  fOut.cd();
  w->Write();
  fOut.Close();

}
コード例 #23
0
ファイル: fitZraw.C プロジェクト: janveverka/FWLite
RooWorkspace* makefit(char* filename, char* FitTitle, char* Outfile, double minMass, double maxMass, double mean_bw, double gamma_bw, double cutoff_cb, const char* plotOpt, const int nbins) {
    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    gStyle->SetPadRightMargin(0.05);

    //Create Data Set
    RooRealVar mass("mass","m(EE)",minMass,maxMass,"GeV/c^{2}");
    RooDataSet *data = RooDataSet::read(filename,RooArgSet(mass));

    //====================== Parameters===========================

    //Crystal Ball parameters
    RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
    RooRealVar cbSigma("sigma_{CB}", "CB Width", 1.7, 0.02, 5.0, "GeV/c^{2}");
    RooRealVar cbCut  ("a_{CB}","CB Cut", 1.05, 0.1, 3.0);
    RooRealVar cbPower("n_{CB}","CB Order", 2.45, 0.1, 20.0);
    cbCut.setVal(cutoff_cb);

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

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

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

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

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

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

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

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


    TStopwatch t ;
    t.Start() ;
    model.fitTo(*data,FitOptions("mh"),Optimize(0),Timer(1));
    t.Print() ;

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

    //========================== Plotting  ============================
    //Create a frame
    RooPlot* plot = mass.frame(Range(minMass,maxMass),Bins(nbins));

    data->plotOn(plot);
    model.plotOn(plot);
    model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(cbBias, cbSigma, cbCut, cbPower, bwMean, bwWidth, expRate, nsig, nbkg)), Layout(0.66,0.63));
    plot->getAttText()->SetTextSize(.03);
    plot->Draw();

    // Print Fit Values
    TLatex *tex = new TLatex();
    tex->SetNDC();
    tex->SetTextSize(.04);
    tex->SetTextFont(2);
    tex->DrawLatex(0.195,0.875, "CMS ECAL, 2012");
    tex->Draw();
    tex->SetTextSize(0.022);
    tex->DrawLatex(0.195, 0.81, FitTitle);
    tex->DrawLatex(0.195, 0.75, "Z #rightarrow ee^{+}");
    tex->SetTextSize(0.024);
    tex->DrawLatex(0.645, 0.59, Form("BW Mean = %.2f GeV/c^{2}", bwMean.getVal()));
    tex->DrawLatex(0.645, 0.54, Form("BW #sigma = %.2f GeV/c^{2}", bwWidth.getVal()));
    c->Update();
    c->Print(Outfile);
    RooWorkspace *w = new RooWorkspace("zfit");
    w->import(model);
    w->import(*data);
    return w;
}
コード例 #24
0
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();
   }
}
コード例 #25
0
ファイル: sig.C プロジェクト: cms-analysis/ZprimeDiLeptons
void makeModel(RooWorkspace& w) {

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

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

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

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

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

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

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

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

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

   w.import(*mc);

   w.Print("tree");

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

   return;

}
コード例 #26
0
void makeAllCtauPlots(const char* workDirName, const char* DSTag, bool paperStyle, bool incSS) {
   // list of files
   vector<TString> theFiles = fileList(workDirName,"",DSTag);

   for (vector<TString>::const_iterator it=theFiles.begin(); it!=theFiles.end(); it++) {
      // if this is not a MB bin, skip it
      anabin thebin = binFromFile(*it);
      // if (!(thebin==anabin(0,1.6,6.5,30,0,200) || thebin==anabin(1.6,2.4,3,30,0,200))) continue;
      if (!(thebin==anabin(0,1.6,9,12,0,200) || 
               thebin==anabin(1.6,2.4,20,30,0,200) ||
               thebin==anabin(1.6,2.4,3,30,40,80) ||
               thebin==anabin(0,1.6,6.5,30,0,200) || thebin==anabin(1.6,2.4,3,30,0,200)
           )) continue;

      TFile *f = TFile::Open(*it);
      TString t; Int_t from = 0;
      bool catchjpsi=false, catchpsip=false, catchbkg=false;
      Char_t jpsiName[128], psipName[128], bkgName[128];
      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;
      }

      bool isPbPb = (it->Index("PbPb")>0);
      struct KinCuts cut;
      cut.dMuon.M.Min = 3;
      cut.dMuon.M.Max = 3.2;
      
      cut.Centrality.Start = thebin.centbin().low();
      cut.Centrality.End = thebin.centbin().high();
      cut.dMuon.Pt.Min = thebin.ptbin().low();
      cut.dMuon.Pt.Max = thebin.ptbin().high();
      cut.dMuon.AbsRap.Min = thebin.rapbin().low();
      cut.dMuon.AbsRap.Max = thebin.rapbin().high();

      string indMuonMass    = Form("(%.6f < invMass && invMass < %.6f)",       cut.dMuon.M.Min,       cut.dMuon.M.Max);
      // if (fitSB) indMuonMass = indMuonMass + "&&" + "((2.0 < invMass && invMass < 2.7) || (3.3 < invMass && invMass < 3.45) || (3.9 < invMass && invMass < 5.0))";
      string indMuonRap     = Form("(%.6f <= abs(rap) && abs(rap) < %.6f)",    cut.dMuon.AbsRap.Min,  cut.dMuon.AbsRap.Max);
      string indMuonPt      = Form("(%.6f <= pt && pt < %.6f)",                cut.dMuon.Pt.Min,      cut.dMuon.Pt.Max);
      // string indMuonCtau    = Form("(%.6f < ctau && ctau < %.6f)",             cut.dMuon.ctau.Min,    cut.dMuon.ctau.Max); 
      // if(cut.dMuon.ctauCut!=""){ indMuonCtau = cut.dMuon.ctauCut; }
      // string indMuonCtauErr = Form("(%.6f < ctauErr && ctauErr < %.6f)",       cut.dMuon.ctauErr.Min, cut.dMuon.ctauErr.Max);
      string inCentrality   = Form("(%d <= cent && cent < %d)",                cut.Centrality.Start,  cut.Centrality.End);

      string strCut         = indMuonMass +"&&"+ indMuonRap +"&&"+ indMuonPt;// +"&&"+ indMuonCtau +"&&"+ indMuonCtauErr;
      if (isPbPb){ strCut = strCut +"&&"+ inCentrality; } 

      // RooWorkspace *myws = (RooWorkspace*) f->Get("workspace");
      TFile *fmaster = NULL;
      if (isPbPb) fmaster = TFile::Open("DataSet/DATASET_DATA_PbPb.root");
      else fmaster = TFile::Open("DataSet/DATASET_DATA_PP.root");
      if (!fmaster || !fmaster->IsOpen()) continue;
      RooDataSet *dOS = (RooDataSet*) fmaster->Get(Form("dOS_DATA_%s",isPbPb ? "PbPb" : "PP"));
      RooDataSet *dSS = (RooDataSet*) fmaster->Get(Form("dSS_DATA_%s",isPbPb ? "PbPb" : "PP"));
      RooWorkspace *myws = new RooWorkspace("workspace");
      cout << strCut << endl;
      if (dOS) {
         RooDataSet *dOS2 = (RooDataSet*) dOS->reduce(strCut.c_str());
         myws->import(*dOS2);
         cout << dOS2->sumEntries() << endl;
      }
      if (dSS) {
         RooDataSet *dSS2 = (RooDataSet*) dSS->reduce(strCut.c_str());
         myws->import(*dSS2);
         cout << dSS2->sumEntries() << endl;
      }


      string outputDir = string("Output/") + string(workDirName) + string("/");
      struct InputOpt opt;
      opt.pp.RunNb.Start   = 262157; opt.PbPb.RunNb.Start = 262620;
      opt.pp.RunNb.End     = 262328; opt.PbPb.RunNb.End   = 263757;
      opt.pp.TriggerBit    = (int) PP::HLT_HIL1DoubleMu0_v1; 
      opt.PbPb.TriggerBit  = (int) HI::HLT_HIL1DoubleMu0_v1; 
      string plotLabel = "";
      bool cutCtau = true;
      bool doSimulFit = false;
      cout << *it << " " << it->Index("PbPb") << endl;
      bool setLogScale = true; //!paperStyle;
      bool zoomPsi = paperStyle;
      int nBins = 80;

      drawCtauPlot(*myws, outputDir, opt, cut, plotLabel, DSTag, isPbPb, setLogScale, incSS, nBins, paperStyle, false);

      delete myws;
      delete f;
      delete fmaster;
   }
}
コード例 #27
0
ファイル: toyMC_new.C プロジェクト: pjwinnetou/quarkonia
void toyMC(
	   int collId = kAADATA,
	   float ptLow=0, float ptHigh=5,
	   float yLow=0, float yHigh=2.4,
	   int cLow=0, int cHigh=200,
	   float muPtCut=4.0,
	   int inputOption=kChPol4, //kChPol3,
	   int nGen = 10000,
	   int useCentIntBkgShape = 1,
     int nToys = 1000
	    ) 
{
  using namespace RooFit;
  RooRandom::randomGenerator()->SetSeed(111);
  gStyle->SetEndErrorSize(0);
  float Val_2S_1S_nom = 0;
  float Val_2S_1S_alt = 0;
  float Dev_2S_1S = 0;
  

  TString fcoll;
  TString finput;
  if(collId == kAADATA) fcoll = "AA";
  else if(collId == kPPDATA) fcoll = "PP";
  if(inputOption == 3) finput = "4th poly";
  else if(inputOption == 4) finput = "Nominal+Exp";
  
  TFile *wf = new TFile(Form("%s_fit_pt%.1f-%.1f_rap%.1f-%.1f_cent%d-%d_Gen%d_input%d_useCentBkg%d_nToys%d.root",fcoll.Data(),ptLow,ptHigh,yLow,yHigh,cLow,cHigh,nGen,inputOption,useCentIntBkgShape,nToys),"recreate");
  
  TH1D *h1 = new TH1D("h1",Form("SR Nominal, %d toys, %d events, cent %d-%d;2S/1S nom;Counts",nToys,nGen,cLow,cHigh),100,0,1);
  TH1D *h2 = new TH1D("h2",Form("SR %s, %d toys, %d events, cent %d-%d;2S/1S nom;Counts",finput.Data(),nToys,nGen,cLow,cHigh),100,0,1);
  TH1D *h3 = new TH1D("h3","Deviation;2S/1S dev;Counts",1000,0,100);

  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  
  for(int i=0;i<nToys;i++){
  
  float massLow = 8. ;
  float massHigh = 14.;
  int   nMassBin  = (massHigh-massLow)*10;
  
  RooWorkspace *ws = new RooWorkspace("ws");
  RooWorkspace *wsinp = new RooWorkspace("wsinp");

  RooRealVar mass("mass","mass", massLow, massHigh);
  ws->import(mass);
  wsinp->import(mass);
  mass.Print();
  

  RooRealVar mRatio21("mRatio21","mRatio21",pdgMass.Y2S / pdgMass.Y1S );
  RooRealVar mRatio31("mRatio31","mRatio31",pdgMass.Y3S / pdgMass.Y1S );
  RooRealVar mean1s("m_{#Upsilon(1S)}","mean of the signal gaussian mass PDF",pdgMass.Y1S, pdgMass.Y1S -0.1, pdgMass.Y1S + 0.1 ) ;
  
  PSet3SingleCB InitialSetUpsilons = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh, muPtCut) ; 
  RooRealVar sigma1s_1("sigma1s_1","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);
  RooRealVar sigma2s_1("sigma2s_1","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);
  RooRealVar sigma1s_2("sigma1s_2","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);
  RooRealVar sigma2s_2("sigma2s_2","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);

  RooRealVar alpha1s_1("alpha1s_1","tail shift", 5. , 1.0, 9.8);
  RooRealVar alpha2s_1("alpha2s_1","tail shift", 5. , 1.15, 9.2);
  RooRealVar alpha1s_2("alpha1s_2","tail shift", 5. , 1.0, 9.2);
  RooRealVar alpha2s_2("alpha2s_2","tail shift", 2.5, 1.10, 10.);

  RooRealVar n1s_1("n1s_1","power order", 5. , 1.4, 10.);
  RooRealVar n2s_1("n2s_1","power order", 6. , 1.1, 9.5);
  RooRealVar n1s_2("n1s_2","power order", 5. , 1.4, 10.);
  RooRealVar n2s_2("n2s_2","power order", 6. , 1.1, 9.5);
    
  RooRealVar *f1S = new RooRealVar("f1S","1S CB fraction", InitialSetUpsilons.MCf, InitialSetUpsilons.MCf*0.9, InitialSetUpsilons.MCf*1.1);
  f1S->setVal(InitialSetUpsilons.MCf);  f1S->setConstant();
  RooRealVar X1S("X1S","sigma fraction 1S 2nd CB", InitialSetUpsilons.MCX, InitialSetUpsilons.MCX*0.9, InitialSetUpsilons.MCX*1.1);
  
  // Fix the parameters 
  n1s_1.setVal(InitialSetUpsilons.MCN);  n1s_1.setConstant();  
  n1s_2.setVal(InitialSetUpsilons.MCN);  n1s_2.setConstant();  
  n2s_1.setVal(InitialSetUpsilons.MCN);  n2s_1.setConstant();  
  n2s_2.setVal(InitialSetUpsilons.MCN);  n2s_2.setConstant(); 
  alpha1s_1.setVal(InitialSetUpsilons.MCAlpha);  alpha1s_1.setConstant(); 
  alpha1s_2.setVal(InitialSetUpsilons.MCAlpha);  alpha1s_2.setConstant();
  alpha2s_1.setVal(InitialSetUpsilons.MCAlpha);  alpha2s_1.setConstant();
  alpha2s_2.setVal(InitialSetUpsilons.MCAlpha);  alpha2s_2.setConstant();  
  sigma1s_1.setVal(InitialSetUpsilons.MCSigma1S);  sigma1s_1.setConstant();  
  sigma1s_2.setVal(InitialSetUpsilons.MCSigma1S);  sigma1s_2.setConstant();  
  sigma2s_1.setVal(InitialSetUpsilons.MCSigma1S * InitialSetUpsilons.MCX );  sigma2s_1.setConstant();  
  sigma2s_2.setVal(InitialSetUpsilons.MCSigma1S * InitialSetUpsilons.MCX );  sigma2s_2.setConstant();  
  mean1s.setVal(InitialSetUpsilons.bkg_mass_res); mean1s.setConstant();
  
  RooFormulaVar mean2s("mean2s","m_{#Upsilon(1S)}*mRatio21", RooArgSet(mean1s,mRatio21) );
  RooFormulaVar mean3s("mean3s","m_{#Upsilon(1S)}*mRatio31", RooArgSet(mean1s,mRatio31) );
  
  RooCBShape* cb1s_1 = new RooCBShape("cball1s_1", "cystal Ball", mass, mean1s, sigma1s_1, alpha1s_1, n1s_1);
  RooCBShape* cb2s_1 = new RooCBShape("cball2s_1", "cystal Ball", mass, mean2s, sigma2s_1, alpha2s_1, n2s_1);
  
  RooCBShape* cb1s_2 = new RooCBShape("cball1s_2", "cystal Ball", mass, mean1s, sigma1s_2, alpha1s_2, n1s_2);
  RooCBShape* cb2s_2 = new RooCBShape("cball2s_2", "cystal Ball", mass, mean2s, sigma2s_2, alpha2s_2, n2s_2);
 
  RooAddPdf*  cb1s = new RooAddPdf();
  RooAddPdf*  cb2s = new RooAddPdf();
  cb1s = new RooAddPdf("cb1s","Signal 1S",RooArgList(*cb1s_1,*cb1s_2), RooArgList(*f1S) );
  cb2s = new RooAddPdf("cb2s","Signal 2S",RooArgList(*cb2s_1,*cb2s_2), RooArgList(*f1S) );


  // Input model 
  PSet3SingleCB bkgParm = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh, muPtCut) ; 
  PSet3SingleCB bkgParmCentInt;
  if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA)   ) {
    bkgParmCentInt      = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh,    0,   200, muPtCut) ; 
    cout << " ok done " << endl;
  }

  // if ( inputOption == kErrExp ) 
  RooRealVar err_mu1("#mu1","err_mu1",  bkgParm.bkg_mu1 ) ;
  RooRealVar err_sigma1("#sigma1","err_sigma1", bkgParm.bkg_sigma1);
  RooRealVar m_decay1("#lambda1","m_decay1", bkgParm.bkg_lambda1);
  RooRealVar err_mu2("#mu2","err_mu2",  bkgParm.bkg_mu2 ) ;
  RooRealVar err_sigma2("#sigma2","err_sigma2", bkgParm.bkg_sigma2);
  RooRealVar m_decay2("#lambda2","m_decay2", bkgParm.bkg_lambda2);
  
  
  float the_ch3_k1 = bkgParm.ch3_k1 ;   float the_ch3_k2 = bkgParm.ch3_k2 ;  float the_ch3_k3 = bkgParm.ch3_k3 ;
  float the_ch4_k1 = bkgParm.ch4_k1 ;   float the_ch4_k2 = bkgParm.ch4_k2 ;  float the_ch4_k3 = bkgParm.ch4_k3 ; float the_ch4_k4 = bkgParm.ch4_k4 ;
  float the_bkg4_mu = bkgParm.bkg4_mu ;           float the_bkg4_sigma = bkgParm.bkg4_sigma; 
  float the_bkg4_lambda = bkgParm.bkg4_lambda ;   float the_bkg4_lambda2 = bkgParm.bkg4_lambda2 ;
  if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) && useCentIntBkgShape  ) {
    the_ch3_k1 = bkgParmCentInt.ch3_k1 ;    the_ch3_k2 = bkgParmCentInt.ch3_k2 ;   the_ch3_k3 = bkgParmCentInt.ch3_k3 ;
    the_ch4_k1 = bkgParmCentInt.ch4_k1 ;    the_ch4_k2 = bkgParmCentInt.ch4_k2 ;   the_ch4_k3 = bkgParmCentInt.ch4_k3 ; the_ch4_k4 = bkgParmCentInt.ch4_k4 ;
    the_bkg4_mu = bkgParmCentInt.bkg4_mu ;            bkgParmCentInt.bkg4_sigma =bkgParmCentInt.bkg4_sigma;
    the_bkg4_lambda = bkgParmCentInt.bkg4_lambda ;    the_bkg4_lambda2 = bkgParmCentInt.bkg4_lambda2 ;
  }
  // if ( inputOption == kChPol3 ) 
  RooRealVar ch3_k1("pol3_k1","pol3_k1", the_ch3_k1 ) ;
  RooRealVar ch3_k2("pol3_k2","pol3_k2", the_ch3_k2 ) ;
  RooRealVar ch3_k3("pol3_k3","pol3_k3", the_ch3_k3 ) ;
  // if ( inputOption == kChPol4 ) 
  RooRealVar ch4_k1("pol4_k1","pol4_k1", the_ch4_k1 , the_ch4_k1*0.3, the_ch4_k1*1.6) ;
  RooRealVar ch4_k2("pol4_k2","pol4_k2", the_ch4_k2 , the_ch4_k2*0.3, the_ch4_k2*1.6) ;
  RooRealVar ch4_k3("pol4_k3","pol4_k3", the_ch4_k3 , the_ch4_k3*0.3, the_ch4_k3*1.6) ;
  RooRealVar ch4_k4("pol4_k4","pol4_k4", the_ch4_k4 , the_ch4_k4*0.3, the_ch4_k4*1.6) ;


  // if (inputOption == kErrExpExp ) 
  RooRealVar err4_mu("err4_mu","err4_mu",  the_bkg4_mu , the_bkg4_mu*0.4,the_bkg4_mu*1.4) ;
  RooRealVar err4_sigma("err4_sigma","err4_sigma", the_bkg4_sigma, the_bkg4_sigma*0.4, the_bkg4_sigma*1.4);
  RooRealVar m4_decay("err4_lambda","m4_decay", the_bkg4_lambda, the_bkg4_lambda*0.4, the_bkg4_lambda*1.4);
  RooRealVar m4_decay2("err4_lambda2","m4_decay2", the_bkg4_lambda2, the_bkg4_lambda2*0.4, the_bkg4_lambda2*1.4);

  RooGenericPdf *bkgErrExp1;
  RooGenericPdf *bkgErrExp2;

  RooGenericPdf *bkg4ErrExp ; // kErrExpExp
  RooGenericPdf *bkg4Exp = new RooGenericPdf("bkg4Exp","bkg4Exp","TMath::Exp(-@0/@1)",RooArgList(mass,m4_decay2));


 
 if ( ptLow == 0)  { 
   bkg4ErrExp = new RooGenericPdf("bkg4ErrExp","bkg4ErrExp","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err4_mu,err4_sigma,m4_decay));
   bkgErrExp1 = new RooGenericPdf("bkgErrExp1","Background1","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu1,err_sigma1,m_decay1));
   bkgErrExp2 = new RooGenericPdf("bkgErrExp2","Background2","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu2,err_sigma2,m_decay2));
 }
  else  { // if ptLow >= 5 
    bkg4ErrExp = new RooGenericPdf("bkg4ErrExp","bkg4ErrExp", "TMath::Exp(-@0/@1)",RooArgList(mass,m4_decay));
    bkgErrExp1 = new RooGenericPdf("bkgErrExp1","Background1","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay1));
    bkgErrExp2 = new RooGenericPdf("bkgErrExp2","Background2","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay2));
  }




  RooRealVar* rBkg2nd = new RooRealVar("rBkg2over1","rBkg2over1", bkgParm.rBkg42over1); // bkgParm.rBkgErr2over1
  RooAddPdf* bkgDblErr = new RooAddPdf("bkgDblErrExp","Bkg Only",RooArgList(*bkgErrExp2, *bkgErrExp1),RooArgList(*rBkg2nd));   // if ( inputOption == kErrExp )
  RooAddPdf* bkgComp4 = new RooAddPdf("bkgComp4","bkgComp4",RooArgList(*bkg4Exp, *bkg4ErrExp),RooArgList(*rBkg2nd));   // if ( inputOption == kErrExp )

  RooChebychev * bkgChPol3 = new RooChebychev("cPolBkg","Background1",mass,RooArgSet(ch3_k1,ch3_k2,ch3_k3));  // if ( inputOption == kChPol3 )
  RooChebychev * bkgChPol4 = new RooChebychev("cPol4Bkg","Background4",mass,RooArgSet(ch4_k1,ch4_k2,ch4_k3,ch4_k4));  // if ( inputOption == kChPol3 )

  float r1S_overTot = bkgParm.nSignal1s / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; // Numbers obtained from the real data
  float r2S_overTot = bkgParm.nSignal2s / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; 
  float rBkg_overTot = bkgParm.nBkg / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; 
  
  RooRealVar *nSig1sInp  = new RooRealVar("nSig1sInp","nSig1sInp", nGen * r1S_overTot,  0,   nGen);
  RooRealVar *nSig2sInp  = new RooRealVar("nSig2sInp","nSig2sInp", nGen * r2S_overTot, 0,   nGen);
  RooRealVar *nBkgInp  = new RooRealVar("nBkgInp","n_bkgInp",      nGen * rBkg_overTot,  0,   nGen);
  

  //----------------------------------------------------------------------------------------
  //Generating function from nominal fit
  
  RooRealVar err_mu_gen("err_mu_gen","err_mu_gen",  bkgParm.bkg_mu_res) ;
  RooRealVar err_sigma_gen("err_sigma_gen","err_sigma_gen", bkgParm.bkg_sigma_res);
  RooRealVar m_decay_gen("err_lambda_gen","m_decay_gen", bkgParm.bkg_lambda_res);

  err_mu_gen.setVal(bkgParm.bkg_mu_res); err_mu_gen.setConstant();
  err_sigma_gen.setVal(bkgParm.bkg_sigma_res); err_sigma_gen.setConstant();
  m_decay_gen.setVal(bkgParm.bkg_lambda_res); m_decay_gen.setConstant();
  
  RooGenericPdf* bkgInp_gen;
  RooGenericPdf *bkgInp_in;
  if ( ptLow == 0)  { 
    bkgInp_in = new RooGenericPdf("bkgInp_gen","Background Gen","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu_gen,err_sigma_gen,m_decay_gen));
  }
  else {
    bkgInp_in = new RooGenericPdf("bkgInp_gen","Background Gen","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay_gen));
  }
  
  bkgInp_gen = bkgInp_in;
  
  
  RooAddPdf* modelInput_gen; 
  modelInput_gen = new RooAddPdf("modelInput_gen","1S+2S + Bkg",RooArgList(*cb1s, *cb2s, *bkgInp_gen),RooArgList(*nSig1sInp,*nSig2sInp,*nBkgInp));
  
  //----------------------------------------------------------------------------------------
  //----------------------------------------------------------------------------------------
  
  RooAddPdf* modelInput; 
  RooGenericPdf* bkgInp;
  if ( inputOption == kErrExp ) { 
    bkgInp = (RooGenericPdf*) bkgDblErr;
  }
  else if ( inputOption == kChPol3 ) { 
    bkgInp = (RooGenericPdf*) bkgChPol3;
  }
  else if ( inputOption == kChPol4 ) { 
    bkgInp = (RooGenericPdf*) bkgChPol4;
  }
  else if ( inputOption == kErrExpExp ) { 
    bkgInp = (RooGenericPdf*) bkgComp4;
  }

  modelInput = new RooAddPdf("modelInput","1S+2S + Bkg",RooArgList(*cb1s, *cb2s, *bkgInp),RooArgList(*nSig1sInp,*nSig2sInp,*nBkgInp));
  wsinp->import(*modelInput);

  Val_2S_1S_nom=0;
  Val_2S_1S_alt=0;
  Dev_2S_1S=0;


  RooDataSet *data = modelInput_gen->generate(mass,nGen) ;

  RooPlot* xframe  = ws->var("mass")->frame(nMassBin); // bins
  xframe->SetXTitle("mass (Gev/c^{2})");
  xframe->GetXaxis()->CenterTitle();
  xframe->GetYaxis()->CenterTitle();
  RooPlot* xframe2 = (RooPlot*)xframe->Clone("xframe2");
  
  RooFitResult* fitResInput = wsinp->pdf("modelInput")->fitTo(*data,Save(), Hesse(kTRUE),Range(massLow, massHigh),Minos(0), SumW2Error(kTRUE));
  data->plotOn(xframe,Name("dataHist"),MarkerSize(0.7)) ;
  wsinp->pdf("modelInput")->plotOn(xframe, Name("inputModelHist"));
  wsinp->pdf("modelInput")->plotOn(xframe, Components(RooArgSet(*bkgInp)),LineColor(kBlack),LineStyle(kDashed));
  if ( inputOption == kErrExp ) 
    {  
      modelInput->plotOn(xframe,Components(RooArgSet(*bkgDblErr)),LineColor(kRed),LineStyle(kDashed));
      modelInput->plotOn(xframe,Components(RooArgSet(*bkgErrExp1)),LineColor(kBlack),LineStyle(kDashed));
      modelInput->plotOn(xframe,Components(RooArgSet(*bkgErrExp2)),LineColor(kBlack),LineStyle(kDashed));
    }
  else if  ( inputOption == kChPol3 )
    modelInput->plotOn(xframe,Components(RooArgSet(*bkgChPol3)),LineColor(kBlack),LineStyle(kDashed));
  else if  ( inputOption == kChPol4 )
    modelInput->plotOn(xframe,Components(RooArgSet(*bkgChPol4)),LineColor(kBlack),LineStyle(kDashed));
  else if (inputOption == kErrExpExp ) {
    modelInput->plotOn(xframe,Components(RooArgSet(*bkgComp4)),LineColor(kBlack),LineStyle(kDashed));
    modelInput->plotOn(xframe,Components(RooArgSet(*bkg4ErrExp)),LineColor(kBlack),LineStyle(kDashed));
    modelInput->plotOn(xframe,Components(RooArgSet(*bkg4Exp)),LineColor(kBlack),LineStyle(kDashed));
  }


  // New fit 
  
  float the_bkg_mu = bkgParm.bkg_mu ;
  float the_bkg_sigma = bkgParm.bkg_sigma ;
  float the_bkg_lambda = bkgParm.bkg_lambda ;
  if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) && useCentIntBkgShape  ) {
    the_bkg_mu = bkgParmCentInt.bkg_mu ;
    the_bkg_sigma = bkgParmCentInt.bkg_sigma ;
    the_bkg_lambda = bkgParmCentInt.bkg_lambda ;
  }

  //RooRealVar err_mu("err_mu","err_mu", the_bkg_mu, 0.0, 40);
  RooRealVar err_mu("err_mu","err_mu", the_bkg_mu, the_bkg_mu*0.4, the_bkg_mu*1.4);
  //RooRealVar err_mu("err_mu","err_mu", 1., 0.0, 30);
  //RooRealVar err_sigma("err_sigma","err_sigma", 1.2, 1.1,55);
  //RooRealVar err_sigma("err_sigma","err_sigma", 10.,0,20);
  RooRealVar err_sigma("err_sigma","err_sigma", the_bkg_sigma, the_bkg_sigma*0.4, the_bkg_sigma*1.4);
  //RooRealVar m_decay("m_decay","m_decay", 10., 6.5, 30);
  RooRealVar m_decay("m_decay","m_decay",the_bkg_lambda, the_bkg_lambda*0.4, the_bkg_lambda*1.4);
  
  if( ( ptLow == (float)0 ) && (ptHigh == (float)30 ) && (yLow == (float)0 ) && (yHigh == (float)2.4) && collId==kPPDATA) 
  {
    err_sigma.setVal(1.055); 
    err_sigma.setConstant();
  }
  if( ( ptLow == (float)0 ) && (ptHigh == (float)30 ) && (yLow == (float)0 ) && (yHigh == (float)2.4) && collId==kAADATA) 
  {
    err_sigma.setVal(1.103); 
    err_sigma.setConstant();
  }

  RooGenericPdf *bkgFitOut;
  if ( ptLow == 0)  { 
    bkgFitOut = new RooGenericPdf("bkgFitOut","BackgroundOut","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu,err_sigma,m_decay));
  }
  else {
    bkgFitOut = new RooGenericPdf("bkgFitOut","BackgroundOut","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay));
  }

  

  RooRealVar *nSig1sOut  = new RooRealVar("nSig1sOut","nSig1sOut", r1S_overTot*nGen, 0,  r1S_overTot*2.*nGen);
  RooRealVar *nSig2sOut  = new RooRealVar("nSig2sOut","nSig2sOut", r2S_overTot*nGen, 0, r2S_overTot*2.*nGen);
  RooRealVar *nBkgOut  = new RooRealVar("nBkgOut","n_bkgOut",nGen * rBkg_overTot, 0, nGen);

  RooAddPdf*  cb1sOut = (RooAddPdf*)cb1s->Clone("cb1sOutput");
  RooAddPdf*  cb2sOut = (RooAddPdf*)cb2s->Clone("cb2sOutput");
  RooAddPdf* modelOutput = new RooAddPdf("modelOutput","1S+2S + Bkg",RooArgList(*cb1sOut, *cb2sOut, *bkgFitOut),RooArgList(*nSig1sOut,*nSig2sOut,*nBkgOut));
  ws->import(*modelOutput);
  
  RooFitResult* fitRes = ws->pdf("modelOutput")->fitTo(*data,Save(), Hesse(kTRUE),Range(massLow, massHigh),Minos(0), SumW2Error(kTRUE));
  data->plotOn(xframe2,Name("dataHist2"),MarkerSize(0.7)) ;
  ws->pdf("modelOutput")->plotOn(xframe2, Name("outputModelHist"));
  ws->pdf("modelOutput")->plotOn(xframe2, Components(RooArgSet(*bkgFitOut)),LineColor(kBlack),LineStyle(kDashed));
  
  Val_2S_1S_nom = (float)(ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal());
  Val_2S_1S_alt = (float)(wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal());
  Dev_2S_1S = (Val_2S_1S_alt/Val_2S_1S_nom - 1) * 100;
  h1->Fill(Val_2S_1S_nom);
  h2->Fill(Val_2S_1S_alt);
  h3->Fill(Dev_2S_1S);

  // DRAW! 
  if(i == 0){
  TCanvas* c1 =  new TCanvas("canvas2","My plots",4,45,800,400);
  c1->cd();
  TPad *pad1 = new TPad("pad1", "pad1", 0, 0.25, 0.49, 1.0);
  pad1->SetTicks(1,1);
  pad1->Draw(); pad1->cd();
  pad1->SetBottomMargin(0); // Upper and lower plot are joined

  xframe->GetYaxis()->SetTitleOffset(1.4) ; xframe->Draw() ;
  drawText(Form("#Upsilon(2S)/#Upsilon(1S) = %.5f",(float)(wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal())),0.2,0.54,1,16) ;
  
  if (inputOption==kChPol4 ) 
    drawText("4th order poly. Bkg.",0.2,0.62,2,15) ;
  if (inputOption==kErrExpExp ) 
    drawText("Erf*exp + exp Bkg.",0.2,0.62,2,15) ;
  
  if(collId == kAADATA)
    drawText("PbPb",0.4,0.45,1,15);
  if(collId == kPPDATA)
    drawText("pp", 0.4,0.45,1,15);

  drawText(Form("%.1f < p_{T}^{#mu#mu} < %.1f GeV",ptLow,ptHigh ),0.5,0.60,1,12);
  drawText(Form("%.1f < y^{#mu#mu} < %.1f",yLow,yHigh ), 0.5,0.55,1,12);
  TString perc = "%";
  if(collId == kAADATA)
    drawText(Form("Cent %d-%d%s",cLow/2,cHigh/2,perc.Data()),0.5,0.5,4,12);
  
  TLatex *tex = new TLatex(0.4,0.88,"Toy MC generated");
  tex->SetTextFont(43);
  tex->SetTextSize(15);
  tex->SetNDC();
  //  tex->SetTextAngle(180);
  tex->Draw();

  RooArgList paramListinp = fitResInput->floatParsFinal();
  paramListinp.Print("v");
  RooPlot* legFrameinp = wsinp->var("mass")->frame(Name("Fit Results"), Title("Fit Results"));
  wsinp->pdf("modelInput")->paramOn(legFrameinp,Layout(.6,.9, .5),Parameters(paramListinp));
  legFrameinp->getAttText()->SetTextAlign(11);
  legFrameinp->getAttText()->SetTextSize(0.028);
  TPaveText* hhinp = (TPaveText*)legFrameinp->findObject(Form("%s_paramBox",wsinp->pdf("modelInput")->GetName()));
  hhinp->SetY1(0.35); hhinp->SetY2(0.83);
  hhinp->Draw();
  // PULL

  TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 0.49, 0.25);
  c1->cd();
  pad2->Draw();
  pad2->cd();
  RooHist* hpull = xframe->pullHist("dataHist","inputModelHist");
  RooPlot* pullFrame = wsinp->var("mass")->frame(Title("Pull Distribution")) ;
  pullFrame->addPlotable(hpull,"P") ;
  pullFrame->SetTitleSize(2.57);
  pullFrame->GetYaxis()->SetTitleOffset(1.8) ;
  pullFrame->GetYaxis()->SetLabelSize(0.16) ;
  pullFrame->GetYaxis()->SetRange(-10,10) ;
  pullFrame->GetXaxis()->SetTitleOffset(0.7) ;
  pullFrame->GetXaxis()->SetLabelSize(0.1) ;
  pullFrame->GetXaxis()->SetTitleSize(0.13) ;
  pullFrame->Draw() ;


  TPad *pad3 = new TPad("pad3", "pad3", 0.51, 0.25, 0.99, 1);
  pad3->SetTicks(1,1);
  pad3->SetBottomMargin(0); // Upper and lower plot are joined
  c1->cd();
  pad3->Draw(); pad3->cd();

  xframe2->GetYaxis()->SetTitleOffset(1.4) ; xframe2->Draw() ;
  TLatex *tex2 = new TLatex(0.4,0.9,"Fitted by Nominal function");
  tex2->SetTextFont(43);
  tex2->SetTextSize(15);
  tex2->SetTextColor(2);
  tex2->SetNDC();
  tex2->Draw();
  drawText(Form("#Upsilon(2S)/#Upsilon(1S) = %.5f",(float)(ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal())), 0.4,0.85,1,16 );

  // *~*~*~*~*~*~*~* Draw the parameters in the plot  *~*~*~*~*~*~*~* //
  RooArgList paramList = fitRes->floatParsFinal();
  paramList.Print("v");
  RooPlot* legFrame = ws->var("mass")->frame(Name("Fit Results"), Title("Fit Results"));
  ws->pdf("modelOutput")->paramOn(legFrame,Layout(.6,.9, .5),Parameters(paramList));
  legFrame->getAttText()->SetTextAlign(11);
  legFrame->getAttText()->SetTextSize(0.028);
  TPaveText* hh = (TPaveText*)legFrame->findObject(Form("%s_paramBox",ws->pdf("modelOutput")->GetName()));
  hh->SetY1(0.35); hh->SetY2(0.83);
  hh->Draw();

  TPad *pad4 = new TPad("pad4", "pad4", 0.51, 0.05, 0.99, 0.25);
  // pad4->SetBottomMargin(0); // Upper and lower plot are joined
  c1->cd();
  pad4->Draw();
  pad4->cd();
  RooHist* hpullOut = xframe2->pullHist("dataHist2","outputModelHist");
  RooPlot* pullOutFrm = ws->var("mass")->frame(Title("Pull Distribution")) ;
  pullOutFrm->addPlotable(hpullOut,"P") ;
  pullOutFrm->SetTitleSize(2.57);
  pullOutFrm->GetYaxis()->SetTitleOffset(1.8) ;
  pullOutFrm->GetYaxis()->SetLabelSize(0.16) ;
  pullOutFrm->GetYaxis()->SetRange(-10,10) ;
  pullOutFrm->GetXaxis()->SetTitleOffset(0.7) ;
  pullOutFrm->GetXaxis()->SetLabelSize(0.1) ;
  pullOutFrm->GetXaxis()->SetTitleSize(0.13) ;
  pullOutFrm->Draw() ;



  // *~*~*~*~*~*~*~* Print the results *~*~*~*~*~*~*~* //

  //cout << "nSig2sInp/nSig1sInp = " << nSig2sInp->getVal() / nSig1sInp->getVal() << endl;
  cout << "input fit ratio = " << wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal() << endl;
  cout << "output fit ratio = " << ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal() << endl;
  c1->SaveAs(Form( "toyMCFit_collId%d_pt%.0f-%.0fGeV_y%.0f-%.0f_cBin%d-%d_muPtCut%.0fGeV_BkgPDFOpt%d_nGen%d_useCentIntBkgShape%d.png",
		   collId, ptLow, ptHigh, yLow*10, yHigh*10, cLow, cHigh, muPtCut, inputOption, nGen,useCentIntBkgShape) );
  
  float r1 =  wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal() ; 
  float r2 =  ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal() ; 
  cout << Form( "collId: %d,    pt: %.0f - %.0fGeV,   y: %.1f - %.1f,  cBin: %d - %d", collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh ) << endl;
  cout << "Uncertainty = "  << (r2 - r1 ) / r1 << endl;
  }  
  
  }

  wf->cd();
  h1->Write();
  h2->Write();
  h3->Write();

   
} 
コード例 #28
0
int main(int argc, char* argv[]) {

     doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

     //Observable
     epdf->Var("obsMass").setVal(5280);
     epdf->Var("obsMass").setRange(5200.,5500.);
     epdf->Var("obsTime").setVal(1.3);
     epdf->Var("obsTime").setRange(0.3, 18.3);
  
     //Zusammenfassen der Parameter in einem RooArgSet
     RooArgSet Observables;
     Observables.add(RooArgSet(epdf->Var("obsMass"), epdf->Var("obsTime")));

     //Anlegen der Parameter
     /*epdf->Var("pdf_sig_mass_mean").setRange(5230, 5330);
     epdf->Var("pdf_sig_mass_mean").setVal(5280);
     epdf->Var("pdf_sig_mass_width").setRange(1.0, 15);
     epdf->Var("pdf_sig_mass_width").setVal(10);
     epdf->Var("pdf_bkg_mass_lambda").setRange(-0.0074, 0.0);
     epdf->Var("pdf_bkg_mass_lambda").setVal(-0.001);
     epdf->Var("sig_Yield").setRange(0.0, 10000);
     epdf->Var("sig_Yield").setVal(5000);
     epdf->Var("bkg_Yield").setRange(0.0, 10000);
     epdf->Var("bkg_Yield").setVal(5000);*/
  
     ///////////////////Generiere PDF's/////////////////////
  
     //Signal PDF's//
     epdf->DoubleGaussianScaled("pdf_sig_mass_gauss", epdf->Var("obsMass"),  epdf->Var("pdf_sig_mass_mean"), epdf-> Var("pdf_sig_mass_width"), epdf->Var("scale"), epdf->Var("fraction"), "Sigma");
     //Untergrund PDF
     epdf->Exponential("pdf_bkg_mass_expo", epdf->Var("obsMass"),epdf->Var("pdf_bkg_mass_lambda"));
  

     //Zerfalls PDF's//
     //Resolution Model
     epdf->GaussModel("pdf_resolution", epdf->Var("obsTime"), epdf->Var("pdf_res_mean"), epdf->Var("obsTimeErr"));
     //Zerfalls PDF des Untergrunds
     epdf->Decay("pdf_bkg_time_decay", epdf->Var("obsTime"),epdf->Var("pdf_bkg_time_tau"), epdf->Model("pdf_resolution"));
     //Zerfall PDF des Signals
     epdf->Decay("pdf_sig_time_decay", epdf->Var("obsTime"),epdf->Var("pdf_sig_time_tau"), epdf->Model("pdf_resolution"));


     //Multipliziere Signal und Untergrund PDF mit ihrer jeweiligen Zerfalls PDF//
     //Untergrund * Zerfall
     epdf->Product("pdf_bkg_mass*pdf_bkg_time_decay", RooArgSet(epdf->Pdf("pdf_bkg_mass_expo"), epdf->Pdf("pdf_bkg_time_decay")));
     //Signal * Zerfall
     epdf->Product("pdf_sig_mass_gauss*pdf_sig_time_decay", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss"),epdf->Pdf("pdf_sig_time_decay")));




     //Addiere PDF's
     epdf->Add("pdf_total", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss*pdf_sig_time_decay"), epdf->Pdf("pdf_bkg_mass*pdf_bkg_time_decay")), RooArgSet(epdf->Var("bkg_Yield"),epdf->Var("sig_Yield")));


    	    


     

     RooWorkspace ws;
     ws.import(epdf->Pdf("pdf_total"));
     ws.defineSet("Observables",Observables, true);

     ws.Print();

     doofit::config::CommonConfig cfg_com("common");
     cfg_com.InitializeOptions(argc, argv);
     doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
     cfg_tfac.InitializeOptions(cfg_com);
     doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
     cfg_tstudy.InitializeOptions(cfg_tfac);

     // set a previously defined workspace to get PDF from (not mandatory, but convenient)
     cfg_tfac.set_workspace(&ws);

     // Check for a set --help flag and if so, print help and exit gracefully
     // (recommended).
     cfg_com.CheckHelpFlagAndPrintHelp();

     // More custom code, e.g. to set options internally.
     // Not required as configuration via command line/config file is enough.


     // Print overview of all options (optional)
     // cfg_com.PrintAll();

     // Initialize the toy factory module with the config objects and start
     // generating toy samples.
     doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
     doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);


     //for(int i=0;i<100;i++)
     //{
     RooDataSet* data = tfac.Generate();
     epdf->Pdf("pdf_total").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/parameters_generate2.txt");
     epdf->Pdf("pdf_total").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/parameters_generate2.txt.new");

     // fitting on the generated dataset is your responsibility
     RooFitResult* fit_result = epdf->Pdf("pdf_total").fitTo(*data, RooFit::Save(true));
  
     /*using namespace doofit::plotting;

     PlotConfig cfg_plot("cfg_plot");
     cfg_plot.InitializeOptions();

     // plot PDF and directly specify component
     //Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdf_total")));
     Plot myplot(cfg_plot, epdf->Var("obsMass"), *data, RooArgList(epdf->Pdf("pdf_total")));
     myplot.PlotIt();*/

     //Speichern der Ergebnisse
     tstudy.StoreFitResult(fit_result);
     //}
     /*tstudy.FinishFitResultSaving();
     tstudy.ReadFitResults();
     tstudy.EvaluateFitResults();
     tstudy.PlotEvaluatedParameters();*/
    


 }
コード例 #29
0
int main (int argc, char **argv) {

  TFile *tf = TFile::Open("tmp/DataSets.root");
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");

  RooDataSet *Data = (RooDataSet*)w->data("Data2011")->Clone("Data");
  Data->append( *((RooDataSet*)w->data("Data2012")) );

  RooDataSet *Bs2Kst0Kst0_MC = (RooDataSet*)w->data("Bs2Kst0Kst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2Kst0Kst0_MC->append( *((RooDataSet*)w->data("Bs2Kst0Kst0_MC2012")) );

  RooDataSet *Bs2Kst0Kst01430_MC = (RooDataSet*)w->data("Bs2Kst0Kst01430_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2Kst0Kst01430_MC->append( *((RooDataSet*)w->data("Bs2Kst0Kst01430_MC2012")) );

  RooDataSet *Bs2Kst01430Kst01430_MC = (RooDataSet*)w->data("Bs2Kst01430Kst01430_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2Kst01430Kst01430_MC->append( *((RooDataSet*)w->data("Bs2Kst01430Kst01430_MC2012")) );

  RooDataSet *Bd2Kst0Kst0_MC = (RooDataSet*)w->data("Bd2Kst0Kst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bd2Kst0Kst0_MC->append( *((RooDataSet*)w->data("Bd2Kst0Kst0_MC2012")) );

  RooDataSet *Bd2PhiKst0_MC = (RooDataSet*)w->data("Bd2PhiKst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bd2PhiKst0_MC->append( *((RooDataSet*)w->data("Bd2PhiKst0_MC2012")) );

  RooDataSet *Bs2PhiKst0_MC = (RooDataSet*)w->data("Bs2PhiKst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bs2PhiKst0_MC->append( *((RooDataSet*)w->data("Bs2PhiKst0_MC2012")) );

  RooDataSet *Bd2RhoKst0_MC = (RooDataSet*)w->data("Bd2RhoKst0_MC2011")->Clone("Bs2KstKst0_MC");
  Bd2RhoKst0_MC->append( *((RooDataSet*)w->data("Bd2RhoKst0_MC2012")) );

  RooDataSet *Lb2ppipipi_MC = (RooDataSet*)w->data("Lb2ppipipi_MC2011")->Clone("Bs2KstKst0_MC");
  Lb2ppipipi_MC->append( *((RooDataSet*)w->data("Lb2ppipipi_MC2012")) );

  RooDataSet *Lb2pKpipi_MC = (RooDataSet*)w->data("Lb2pKpipi_MC2011")->Clone("Bs2KstKst0_MC");
  Lb2pKpipi_MC->append( *((RooDataSet*)w->data("Lb2pKpipi_MC2012")) );


  w->import(*Data);
  w->import(*Bs2Kst0Kst0_MC);
  w->import(*Bs2Kst0Kst01430_MC);
  w->import(*Bs2Kst01430Kst01430_MC);
  w->import(*Bd2Kst0Kst0_MC);
  w->import(*Bd2PhiKst0_MC);
  w->import(*Bs2PhiKst0_MC);
  w->import(*Bd2RhoKst0_MC);
  w->import(*Lb2ppipipi_MC);
  w->import(*Lb2pKpipi_MC);

  RooRealVar *mass = (RooRealVar*)w->var("B_s0_DTF_B_s0_M");

  fitIpatia( w, "bs2kstkst_mc", "Bs2KstKst0_MC");

  // Make the PDF here
  RooRealVar *p1 = new RooRealVar("p1","p1",-0.002,-0.004,0.);
  RooExponential *exp = new RooExponential("exp","exp",*mass,*p1);
  //RooRealVar *m1 = new RooRealVar("m1","m1",5320,5380);
  //RooRealVar *s1 = new RooRealVar("s1","s1",1,20);
  //RooGaussian *sig = new RooGaussian("sig","sig",*mass,*m1,*s1);
  RooRealVar *m2 = new RooRealVar("m2","m2",5320,5380);
  RooRealVar *s2 = new RooRealVar("s2","s2",1,20);
  RooGaussian *sig_bd = new RooGaussian("sig_bd","sig_bd",*mass,*m2,*s2);

  //
  RooRealVar *bs2kstkst_l       = new RooRealVar( "bs2kstkst_l"    ,"", -5, -20, -1.);
  RooConstVar *bs2kstkst_zeta   = new RooConstVar( "bs2kstkst_zeta","",0.              );
  RooConstVar *bs2kstkst_fb     = new RooConstVar( "bs2kstkst_fb"  ,"",0.              );
  RooRealVar *bs2kstkst_sigma   = new RooRealVar( "bs2kstkst_sigma","",15    ,10   ,20 );
  RooRealVar *bs2kstkst_mu      = new RooRealVar( "bs2kstkst_mu"   ,"",5350  ,5380     );
  RooRealVar *bs2kstkst_a       = new RooRealVar( "bs2kstkst_a"    ,"",2.5  , 0    ,10 );
  RooRealVar *bs2kstkst_n       = new RooRealVar( "bs2kstkst_n"    ,"",2.5  , 0    ,10 );
  RooRealVar *bs2kstkst_a2      = new RooRealVar( "bs2kstkst_a2"   ,"",2.5  , 0    ,10 );
  RooRealVar *bs2kstkst_n2      = new RooRealVar( "bs2kstkst_n2"   ,"",2.5  , 0    ,10 );

  RooIpatia2 *sig = new RooIpatia2("sig","sig",*mass,*bs2kstkst_l,*bs2kstkst_zeta,*bs2kstkst_fb,*bs2kstkst_sigma,*bs2kstkst_mu,*bs2kstkst_a,*bs2kstkst_n,*bs2kstkst_a2,*bs2kstkst_n2);

  RooRealVar *bkg_y = new RooRealVar("bkg_y","bkg_y",10e3,10e5);
  RooRealVar *sig_y = new RooRealVar("sig_y","sig_y",0,20e3);
  RooRealVar *sig_bd_y = new RooRealVar("sig_bd_y","sig_bd_y",0,3000);

  RooArgList *pdfs = new RooArgList();
  RooArgList *yields = new RooArgList();

  pdfs->add( *exp );
  pdfs->add( *sig );
  pdfs->add( *sig_bd );

  yields->add( *bkg_y );
  yields->add( *sig_y );
  yields->add( *sig_bd_y );

  RooAddPdf *pdf = new RooAddPdf("pdf","pdf",*pdfs,*yields);

  pdf->fitTo(*Data, Extended() );

  RooPlot *plot = mass->frame();
  Data->plotOn(plot);
    // set fit params constant;
  pdf->plotOn(plot);

  TCanvas *c = new TCanvas();
  plot->Draw();
  c->Print("tmp/mass.pdf");

  // Plots Kst Ms with no sweights
  TCanvas *c1 = new TCanvas("c1","c1",800,1200);
  c1->Divide(1,2);
  c1->cd(1);
  RooPlot *c1p1 = w->var("B_s0_DTF_KST1_M")->frame();
  Data->plotOn(c1p1);
  c1p1->Draw();
  c1->cd(2);
  RooPlot *c1p2 = w->var("B_s0_DTF_KST2_M")->frame();
  Data->plotOn(c1p2);
  c1p2->Draw();
  c1->Print("tmp/nosw.pdf");

  // set fit params constant
  p1->setConstant(true);
  //m1->setConstant(true);
  //s1->setConstant(true);
  bs2kstkst_l->setConstant(true);
  //bs2kstkst_zeta->setConstant(true);
  //bs2kstkst_fb->setConstant(true);
  bs2kstkst_sigma->setConstant(true);
  bs2kstkst_mu->setConstant(true);
  bs2kstkst_a->setConstant(true);
  bs2kstkst_n->setConstant(true);
  bs2kstkst_a2->setConstant(true);
  bs2kstkst_n2->setConstant(true);
  m2->setConstant(true);
  s2->setConstant(true);

  RooStats::SPlot *sData = new RooStats::SPlot("sData","sData", *Data, pdf, *yields);

  w->import(*sData);
  w->import(*Data,Rename("Data_wsweights"));

  RooDataSet *swdata = new RooDataSet("Data_wsweights", "Data", Data, *Data->get(), 0 , "sig_y_sw");
  // Plots Kst Ms with no sweights
  TCanvas *c2 = new TCanvas("c2","c2",800,1200);
  c2->Divide(1,2);
  c2->cd(1);
  RooPlot *c2p1 = w->var("B_s0_DTF_KST1_M")->frame();
  swdata->plotOn(c2p1);
  c2p1->Draw();
  c2->cd(2);
  RooPlot *c2p2 = w->var("B_s0_DTF_KST2_M")->frame();
  swdata->plotOn(c2p2);
  c2p2->Draw();
  c2->Print("tmp/withsw.pdf");


  tf->Close();
  return 0;
}
コード例 #30
0
void testSelectionZee(char *test_datasetname, int test_evtRange){
  
  
  rgen_ = new TRandom3(0);
  cout<< rgen_->Gaus(0,0.01) <<endl; 
  
  
  dataversion = "v3";
  datasetname = test_datasetname;
  evtRange = test_evtRange; 
  
  
  egammaMVACorrection_LoadWeights();
    
  fChain  =new TChain("Analysis");
  TString filename ; 

  /// those files are preselected with two electron Et > 25GeV
  filename = TString( Form("/castor/cern.ch/user/y/yangyong/data/Run2011A/HiggsAnalysis/dielectronSkimmed/testAnalysisZee.%s.%s.allconv1.vtxmethod2.presel5.vtxtmva0.r%d.root",dataversion.c_str(),datasetname.c_str(),evtRange));
  cout<<filename<<endl;
  fChain->Add(filename);
  
  
  TChain *fevtInfo = new TChain("evtInfo");
  fevtInfo->Add(filename);
  fevtInfo->SetBranchAddress("totalNumberofEvents", &totalNumberofEvents);
  fevtInfo->SetBranchAddress("preselectedNumberofEvents", &preselectedNumberofEvents);
  fevtInfo->SetBranchAddress("datasettag", &datasettag);
  
  fevtInfo->GetEntry(0);
  string dname = datasettag->at(0);
  string dv = datasettag->at(1);
  int ntotal = totalNumberofEvents; 
  int nskimmed = preselectedNumberofEvents; 
  for(int n=1; n< fevtInfo->GetEntries(); n++){
    fevtInfo->GetEntry(n);
    ntotal += totalNumberofEvents; 
    nskimmed += preselectedNumberofEvents; 
  }
  
  
  setBranchAddress_ele();
  
  totalEntries = fChain->GetEntries();
  
  cout<<"totalEntries " << totalEntries <<endl; 
  
  ///get json file good lumis for each run 
  vector<string> certFile; 
  certFile.push_back("JsonFile/Cert_160404-163869_7TeV_May10ReReco_Collisions11_CMSSWConfig_v2.txtv1");
  certFile.push_back("JsonFile/Cert_160404-167913_7TeV_PromptReco_Collisions11_CMSSWConfig.txt.afterMay10");
  certFile.push_back("JsonFile/Cert_170249-172619_7TeV_ReReco5Aug_Collisions11_CMSSWConfig.txtv1");
  certFile.push_back("JsonFile/Cert_160404-173692_7TeV_PromptReco_Collisions11_CMSSWConfig.txtv1.run172620up");
  getLSrangeofEachRuns(certFile);

  
  TH1D *hh_pileupmc = new TH1D("hh_pileupmc","hh_npileup mc",51,-0.5,50.5);
  vector<double> weights_pileup;
  if( datasetname.find("SIM") != string::npos){
    /////for PU reweighting (added root files together)
    filename = TString( Form("PileUPDistrubtion/testAnalysis.%s.%s.puHist.root",dataversion.c_str(),datasetname.c_str()));
    TFile *fpumc = new TFile(filename,"read");
    TH1D *hh_npileupbx0 = (TH1D*)fpumc->Get("hh_npileupbx0");
    TH1D *hh_npileupbx1 = (TH1D*)fpumc->Get("hh_npileupbx1");
    TH1D *hh_npileupbxm1 = (TH1D*)fpumc->Get("hh_npileupbxm1");
    TH1D *hh_npileupbxav = (TH1D*)fpumc->Get("hh_npileupbxav"); //right now using averaged
    TFile *fpudata = new TFile("PileUPDistrubtion/Pileup_2011_EPS_8_jul.root","read");
    
    TH1D *hh_npileupdata = (TH1D*)fpudata->Get("pileup");
    weights_pileup = LumiReWeighting_getWeights(hh_npileupdata, hh_npileupbxav);
    fpumc->Close();
    fpudata->Close();
  }
  
  
  filename = TString (Form("selres/testSelectionZee.%s.%s.r%d.root",dataversion.c_str(), datasetname.c_str(),evtRange));
  cout<<filename<<endl; 
  TFile *fnew = new TFile(filename,"recreate");
  
  TH1I *hh_nevents = new TH1I("hh_nevents","total and skimm events",2,0,2);
  hh_nevents->SetBinContent(1,ntotal);
  hh_nevents->SetBinContent(2,nskimmed);
  
  
  vector<string> mpair_var;
  mpair_var.push_back("mpair_ebeb");
  mpair_var.push_back("mpair_ebeb_highr9");
  mpair_var.push_back("mpair_ebeb_lowr9");
  mpair_var.push_back("mpair_eeee");
  mpair_var.push_back("mpair_eeee_highr9");
  mpair_var.push_back("mpair_eeee_lowr9");
  mpair_var.push_back("mpair_eeee_highr9_loweps"); //eps_escraw < 0.05
  mpair_var.push_back("mpair_eeee_highr9_higheps");//eps_escraw > 0.05
  mpair_var.push_back("mpair_eeee_lowr9_loweps"); //eps_escraw < 0.05
  mpair_var.push_back("mpair_eeee_lowr9_higheps");//eps_escraw > 0.05
  
  
  
  RooRealVar *rv_mass = new RooRealVar("rv_mass","mass",100,0,1000);
  RooRealVar *rv_weight = new RooRealVar("rv_weight","weight",1.0,0,1E6);
  map<string,RooDataSet*> rhs_map_mpair;
  map<string,RooDataSet*> rhs_map_mpair_corr;
  for(int j=0; j< int( mpair_var.size()); j++){
    string mpairname = mpair_var[j];
    TString rname = TString( Form("rhs_%s",mpairname.c_str()) );
    rhs_map_mpair[mpairname] = new RooDataSet(rname,rname,RooArgList(*rv_mass,*rv_weight),rv_weight->GetName());
    mpairname = string (Form("%s_corr",mpair_var[j].c_str()));
    rname = TString( Form("rhs_%s",mpairname.c_str()) );
    rhs_map_mpair_corr[mpairname] = new RooDataSet(rname,rname,RooArgList(*rv_mass,*rv_weight),rv_weight->GetName());
  }
  map<string,TH1F*> hh_map_mpair; 
  map<string,TH1F*> hh_map_mpaircorr; 
  for(int j=0; j< int( mpair_var.size()); j++){
    string mpairname = mpair_var[j];
    filename = TString(Form("hh_%s",mpairname.c_str()));
    TH1F *hhtmp = new TH1F(filename,filename,2000,0,200);
    hh_map_mpair[mpairname] = hhtmp;
    hh_map_mpair[mpairname] ->Sumw2();
    
    mpairname = string (Form("%s_corr",mpair_var[j].c_str()));
    filename = TString(Form("hh_%s",mpairname.c_str())); 
    TH1F *hhtmp2 = new TH1F(filename,filename,2000,0,200);
    hh_map_mpaircorr[mpairname] = hhtmp2;
    hh_map_mpaircorr[mpairname] ->Sumw2();
  }
  
  
  
  bool goodCurLumiBlock = false; 
  int curLumiBlock = -1; 
  int curRun = -1; 
  vector<int> runNotUsed; 
  
  
  
  float en[2];
  float encorr[2];
  float pt[2];
  float eta[2];
  float phi[2];
  float res[20];
  float scr9[2];
  float scrps[2];
  
  float mpaircorr; 
  
  
  int nsel = 0; 
  
  bool firstEvent = true; 

  ////loop over all events ( di-photon skimmed)
  for(entry = 0; entry < totalEntries; entry ++){
    fChain->GetEntry(entry);
    if(entry % 1000 ==0 ) cout<<" entry " <<entry<<endl; 
    
    if( firstEvent){
      loadecalGapCoordinates();
      firstEvent = false; 
    }

    ///JSON file good run and LS
    if( isRealData ){
      vector<int>::iterator it = find(goodRunList.begin(),goodRunList.end(),runNumber); 
      if( it == goodRunList.end()){
	vector<int>::iterator it2 = find(runNotUsed.begin(),runNotUsed.end(),runNumber); 
	if( it2 == runNotUsed.end()){
	  runNotUsed.push_back(runNumber); 
	}
	continue; 
      }
      if( curLumiBlock != lumiBlock || curRun != runNumber){ /// a new lumiBlock  or starting of a new Run
	curLumiBlock = lumiBlock; 
	curRun =  runNumber; 
	goodCurLumiBlock = checkLumiBlockofRun();  //check this lumiBlock
      }
      if( ! goodCurLumiBlock) continue; 
      
    }
    
    for(int j=0; j< nElectron; j++){
      electronecalEnergy[j] = electronscenergy[j];  //right now ecalEnerg = scEnergy  
      float corr = getElectronCorrection(j); ///correction from regression 
      electronecalEnergyCorr[j] = (electronscrawEnergy[j] + electronscpreshowerEnergy[j]) * corr;
    }
    
    
    vector<int> indsel; 
    for(int j=0; j< nElectron; j++){
      if( electronecalDrivenSeed[j] ==0) continue; 
      float et = electronscenergy[j] * sin(2*atan(exp(-electroneta[j])));
      if( et < 30 ) continue;  ///ET > 30 
      if(! passElectronID(j,3)) continue; ///right now WP80 
      indsel.push_back(j);
    }
    if( int(indsel.size()) <2) continue; 
    
    nsel ++; 
    
    
    for(int j=0; j<2;j++){
      int k = indsel[j];
      en[j] = electronecalEnergy[k];
      encorr[j] = electronecalEnergyCorr[k];
      eta[j] = electrongsfTracketa[k];
      phi[j] = electrongsfTrackphi[k];
      scr9[j] = electrone3x3[k]/electronscrawEnergy[k];
      scrps[j] = electronscpreshowerEnergy[k] / electronscrawEnergy[k];
    }
    
    calcPairObjects(11,11,en,eta,phi,res);
    mpair = res[0];
    calcPairObjects(11,11,encorr,eta,phi,res);
    mpaircorr = res[0];
    
    
    double evtweight =1; 


    ///get pile up weghit 
    if( ! isRealData){
      int npubxav = 0; 
      for(unsigned int j =0; j < pileupBunchX->size(); j++){
	int BX = pileupBunchX->at(j);
	int npv = pileupNInteraction->at(j);
	if( BX >=-1 && BX <= 1){
	  npubxav += npv; 
	}
      }
      npvbxav = npubxav*1.0/3;
      int bin_weight = hh_pileupmc->FindFixBin(npvbxav) -1;
      double puwt = LumiReWeighting_weightINT_v2(bin_weight, weights_pileup);
      
      evtweight = puwt; 
      
    }
    
    
    int ind1 = indsel[0];
    int ind2 = indsel[1];
    int bothEB =  fabs(electronsceta[ind1]) < 1.482 && fabs(electronsceta[ind2]) < 1.482;
    int bothEE =  fabs(electronsceta[ind1]) > 1.482 && fabs(electronsceta[ind2]) > 1.482;
    int bothHighR9 = scr9[0] > 0.94 && scr9[1] > 0.94; 
    int bothLowR9 = scr9[0] < 0.94 && scr9[1] < 0.94; 
    int bothLowEPS = scrps[0] < 0.05 && scrps[1] < 0.05; 
    int bothHighEPS = scrps[0] > 0.05 && scrps[1] > 0.05; 
    
    
    
    bool fillflag[20] = {bothEB,
			 bothEB && bothHighR9,
			 bothEB && bothLowR9, 
			 bothEE, 
			 bothEE && bothHighR9, 
			 bothEE && bothLowR9,
			 bothEE && bothHighR9 && bothLowEPS, 
			 bothEE && bothHighR9 && bothHighEPS,
			 bothEE && bothLowR9 && bothLowEPS, 
			 bothEE && bothLowR9 && bothHighEPS};
    
    for(int j=0; j< int( mpair_var.size()); j++){
      if( fillflag[j]==false) continue;
      string mpairname = mpair_var[j];
      rv_mass->setVal(mpair);
      hh_map_mpair[mpairname]->Fill(mpair,evtweight);
      rhs_map_mpair[mpairname]->add(*rv_mass,evtweight);
      rv_mass->setVal(mpaircorr);
      mpairname = TString( Form("%s_corr",mpair_var[j].c_str()));
      hh_map_mpaircorr[mpairname]->Fill(mpaircorr,evtweight);
      rhs_map_mpair_corr[mpairname]->add(*rv_mass,evtweight);
    }
    
  }

  cout <<" nsel" << nsel <<endl; 
  
  
  fnew->cd();
  //RooContainer_Save();
  RooWorkspace *w = new RooWorkspace("zeeShape","workspace") ;
  for (std::map<string,RooDataSet*>::iterator it_data = rhs_map_mpair.begin()
	 ;it_data != rhs_map_mpair.end();it_data++)	{
    w->import(*it_data->second);
  }
  for (std::map<string,RooDataSet*>::iterator it_data = rhs_map_mpair_corr.begin()
	 ;it_data != rhs_map_mpair_corr.end();it_data++)	{
    w->import(*it_data->second);
  }
  w->Write();
  
  fnew->Write();
  fnew->Close();
}