CMS 3D CMS Logo

Zmumumerge.cc
Go to the documentation of this file.
1 #include <cmath>
2 #include <fstream>
3 #include <iomanip>
4 #include <iostream>
5 #include <string>
6 
7 #include "toolbox.h"
8 #include "Options.h"
9 
10 #include "TAxis.h"
11 #include "TBranch.h"
12 #include "TCanvas.h"
13 #include "TChain.h"
14 #include "TCut.h"
15 #include "TF1.h"
16 #include "TFile.h"
17 #include "TFrame.h"
18 #include "TH1.h"
19 #include "TH1D.h"
20 #include "TH1F.h"
21 #include "TH2.h"
22 #include "TH2F.h"
23 #include "THStack.h"
24 #include "TLatex.h"
25 #include "TLegend.h"
26 #include "TMath.h"
27 #include "TPad.h"
28 #include "TPaveText.h"
29 #include "TRandom.h"
30 #include "TString.h"
31 #include "TStyle.h"
32 #include "TSystem.h"
33 #include "TTree.h"
34 //#include "RooGlobalFunc.h"
35 
36 #include <boost/filesystem.hpp>
37 #include <boost/property_tree/ptree.hpp>
38 #include <boost/property_tree/json_parser.hpp>
39 #include <boost/range/adaptor/indexed.hpp>
40 
43 
44 using namespace RooFit;
45 using namespace std;
46 using namespace AllInOneConfig;
47 namespace pt = boost::property_tree;
48 /*--------------------------------------------------------------------*/
49 void makeNicePlotStyle(RooPlot* plot) {
50  plot->GetXaxis()->CenterTitle(true);
51  plot->GetYaxis()->CenterTitle(true);
52  plot->GetXaxis()->SetTitleFont(42);
53  plot->GetYaxis()->SetTitleFont(42);
54  plot->GetXaxis()->SetTitleSize(0.05);
55  plot->GetYaxis()->SetTitleSize(0.05);
56  plot->GetXaxis()->SetTitleOffset(0.9);
57  plot->GetYaxis()->SetTitleOffset(1.3);
58  plot->GetXaxis()->SetLabelFont(42);
59  plot->GetYaxis()->SetLabelFont(42);
60  plot->GetYaxis()->SetLabelSize(.05);
61  plot->GetXaxis()->SetLabelSize(.05);
62 }
63 /*--------------------------------------------------------------------*/
64 
65 RooRealVar MuMu_mass("MuMu_mass", "MuMu_mass", 70, 110);
66 static TString GT = "";
67 TLatex* tlxg = new TLatex();
68 class FitOut {
69 public:
70  double mean;
71  double mean_err;
72  double sigma;
73  double sigma_err;
74  double chi2;
75  FitOut(double a, double b, double c, double d) : mean(a), mean_err(b), sigma(c), sigma_err(d) {}
76 };
77 
78 FitOut ZMassBinFit_OldTool(TH1D* th1d_input, TString s_name = "zmumu_fitting", TString output_path = "./") {
79  // silence messages
80  RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
81 
82  double xMean = 91.1876;
83  double xMin = th1d_input->GetXaxis()->GetXmin();
84  double xMax = th1d_input->GetXaxis()->GetXmax();
85 
86  double sigma(2.);
87  double sigmaMin(0.1);
88  double sigmaMax(10.);
89 
90  double sigma2(0.1);
91  double sigma2Min(0.);
92  double sigma2Max(10.);
93 
94  std::unique_ptr<FitWithRooFit> fitter = std::make_unique<FitWithRooFit>();
95 
96  bool useChi2(false);
97 
98  fitter->useChi2_ = useChi2;
99  fitter->initMean(xMean, xMin, xMax);
100  fitter->initSigma(sigma, sigmaMin, sigmaMax);
101  fitter->initSigma2(sigma2, sigma2Min, sigma2Max);
102  fitter->initAlpha(1.5, 0.05, 10.);
103  fitter->initN(1, 0.01, 100.);
104  fitter->initFGCB(0.4, 0., 1.);
105  fitter->initGamma(2.4952, 0., 10.);
106  fitter->gamma()->setConstant(kTRUE);
107  fitter->initMean2(0., -20., 20.);
108  fitter->mean2()->setConstant(kTRUE);
109  fitter->initSigma(1.2, 0., 5.);
110  fitter->initAlpha(1.5, 0.05, 10.);
111  fitter->initN(1, 0.01, 100.);
112  fitter->initExpCoeffA0(-1., -10., 10.);
113  fitter->initExpCoeffA1(0., -10., 10.);
114  fitter->initExpCoeffA2(0., -2., 2.);
115  fitter->initFsig(0.9, 0., 1.);
116  fitter->initA0(0., -10., 10.);
117  fitter->initA1(0., -10., 10.);
118  fitter->initA2(0., -10., 10.);
119  fitter->initA3(0., -10., 10.);
120  fitter->initA4(0., -10., 10.);
121  fitter->initA5(0., -10., 10.);
122  fitter->initA6(0., -10., 10.);
123 
124  TCanvas* c1 = new TCanvas();
125  c1->Clear();
126  c1->SetLeftMargin(0.15);
127  c1->SetRightMargin(0.10);
128 
129  fitter->fit(th1d_input, "breitWignerTimesCB", "exponential", xMin, xMax, false);
130 
131  c1->Print(Form("%s/fitResultPlot/%s_oldtool.pdf", output_path.Data(), s_name.Data()));
132  c1->Print(Form("%s/fitResultPlot/%s_oldtool.root", output_path.Data(), s_name.Data()));
133 
134  FitOut fitRes(
135  fitter->mean()->getValV(), fitter->mean()->getError(), fitter->sigma()->getValV(), fitter->sigma()->getError());
136 
137  return fitRes;
138 }
139 void Draw_th1d(TH1D* th1d_input, TString variable_name, TString output_path) {
140  TCanvas* c = new TCanvas();
141  c->cd();
142  gStyle->SetOptStat(0);
143  th1d_input->SetMarkerStyle(kFullCircle);
144  th1d_input->SetMarkerColor(kRed);
145  th1d_input->SetLineColor(kRed);
146  th1d_input->SetMaximum(91.4);
147  th1d_input->SetMinimum(90.85);
148  th1d_input->GetXaxis()->SetTitle(variable_name.Data());
149  th1d_input->GetXaxis()->SetTitleOffset(1.2);
150  th1d_input->GetYaxis()->SetTitle("Mass mean (GeV)");
151  th1d_input->Draw();
152  tlxg->DrawLatexNDC(0.2, 0.8, Form("%s", GT.Data()));
153  c->Print(Form("%s/fitResultPlot/mass_VS_%s.pdf", output_path.Data(), variable_name.Data()));
154 }
155 
156 const static int variables_number = 8;
158  "CosThetaCS", "DeltaEta", "EtaMinus", "EtaPlus", "PhiCS", "PhiMinus", "PhiPlus", "Pt"};
159 const TString tstring_variables_name_label[variables_number] = {"cos #theta_{CS}",
160  "#Delta #eta",
161  "#eta_{#mu^{-}}",
162  "#eta_{#mu^{+}}",
163  "#phi_{CS}",
164  "#phi_{#mu^{-}}",
165  "#phi_{#mu^{+}}",
166  "p_{T}"};
167 
168 void Fitting_GetMassmeanVSvariables(TString inputfile_name, TString output_path) {
169  TH2D* th2d_mass_variables[variables_number];
170  TFile* inputfile = TFile::Open(inputfile_name.Data());
171  TDirectoryFile* tdirectory = (TDirectoryFile*)inputfile->Get("DiMuonMassValidation");
172  for (int i = 0; i < variables_number; i++) {
173  TString th2d_name = Form("th2d_mass_%s", tstring_variables_name[i].Data());
174  th2d_mass_variables[i] = (TH2D*)tdirectory->Get(th2d_name);
175  }
176 
177  gSystem->Exec(Form("mkdir -p %s", output_path.Data()));
178  gSystem->Exec(Form("mkdir -p %s/fitResultPlot", output_path.Data()));
179  TFile* outputfile = TFile::Open(Form("%s/fitting_output.root", output_path.Data()), "RECREATE");
180  TH1D* th1d_variables_meanmass[variables_number];
181  TH1D* th1d_variables_entries[variables_number];
182  const int variables_rebin[variables_number] = {1, 1, 1, 1, 1, 1, 1, 1};
183  const double xaxis_range[variables_number][2] = {
184  {-1, 1}, {-4.8, 4.8}, {-2.4, 2.4}, {-2.4, 2.4}, {-1, 1}, {-M_PI, M_PI}, {-M_PI, M_PI}, {0, 100}};
185  for (int i = 0; i < variables_number; i++) {
186  TString th1d_name = Form("th1d_meanmass_%s", tstring_variables_name[i].Data());
187 
188  th2d_mass_variables[i]->RebinY(variables_rebin[i]);
189  th1d_variables_meanmass[i] = th2d_mass_variables[i]->ProjectionY(th1d_name, 1, 1, "d");
190  for (int j = 0; j < th1d_variables_meanmass[i]->GetNbinsX(); j++) {
191  if (i == 7 and j > 25) {
192  continue;
193  }
194  std::cout << __PRETTY_FUNCTION__
195  << " th1d_variables_meanmass[i]->GetNbinsX()=" << th1d_variables_meanmass[i]->GetNbinsX() << endl;
196  std::cout << __PRETTY_FUNCTION__ << " th2d_mass_variables[i]->GetNbinsY()=" << th2d_mass_variables[i]->GetNbinsY()
197  << endl;
198  th1d_variables_meanmass[i]->SetBinContent(j, 0);
199  th1d_variables_meanmass[i]->SetBinError(j, 0);
200 
201  TString th1d_mass_temp_name = Form("th1d_mass_%s_%d", tstring_variables_name[i].Data(), j);
202  TH1D* th1d_i = th2d_mass_variables[i]->ProjectionX(th1d_mass_temp_name, j, j, "d");
203  th1d_i->Write(th1d_mass_temp_name);
204  TString s_cut = Form("nocut");
205  TString s_name = Form("%s_%d", tstring_variables_name[i].Data(), j);
206 
207  FitOut fitR = ZMassBinFit_OldTool(th1d_i, s_name, output_path);
208 
209  th1d_variables_meanmass[i]->SetBinContent(j, fitR.mean);
210  th1d_variables_meanmass[i]->SetBinError(j, fitR.mean_err);
211  }
212 
213  th1d_variables_meanmass[i]->GetXaxis()->SetRangeUser(xaxis_range[i][0], xaxis_range[i][1]);
214  Draw_th1d(th1d_variables_meanmass[i], tstring_variables_name[i], output_path);
215  outputfile->cd();
216  th1d_variables_meanmass[i]->Write(th1d_name);
217 
218  TString th1d_name_entries = Form("th1d_entries_%s", tstring_variables_name[i].Data());
219  th1d_variables_entries[i] = th2d_mass_variables[i]->ProjectionY(th1d_name_entries, 0, -1, "d");
220  th1d_variables_entries[i]->GetXaxis()->SetTitle(tstring_variables_name[i].Data());
221  th1d_variables_entries[i]->GetYaxis()->SetTitle("Entry");
222  outputfile->cd();
223  th1d_variables_entries[i]->Write(th1d_name_entries);
224  }
225 
226  if (outputfile->IsOpen()) {
227  // Get the path (current working directory) in which the file is going to be written
228  const char* path = outputfile->GetPath();
229 
230  if (path) {
231  std::cout << "File is going to be written in the directory: " << path << " for input file: " << inputfile_name
232  << std::endl;
233  } else {
234  std::cerr << "Error: Unable to determine the path." << std::endl;
235  }
236  outputfile->Close();
237  delete outputfile;
238  }
239 }
240 
241 const static int max_file_number = 10;
242 void Draw_TH1D_forMultiRootFiles(const vector<TString>& file_names,
243  const vector<TString>& label_names,
244  const vector<int>& colors,
245  const vector<int>& styles,
246  const TString& Rlabel,
247  const TString& th1d_name,
248  const TString& xlabel,
249  const TString& ylabel,
250  const TString& output_name) {
251  if (file_names.empty() || label_names.empty()) {
252  std::cout << "Provided an empty list of file and label names" << std::endl;
253  return;
254  }
255 
256  // do not allow the list of files and labels names to differ
257  assert(file_names.size() == label_names.size());
258 
259  TH1D* th1d_input[max_file_number];
260  TFile* file_input[max_file_number];
261  for (auto const& filename : file_names | boost::adaptors::indexed(0)) {
262  file_input[filename.index()] = TFile::Open(filename.value());
263  th1d_input[filename.index()] = (TH1D*)file_input[filename.index()]->Get(th1d_name);
264  th1d_input[filename.index()]->SetTitle("");
265  }
266 
267  int W = 800;
268  int H = 800;
269  // references for T, B, L, R
270  float T = 0.08 * H;
271  float B = 0.12 * H;
272  float L = 0.12 * W;
273  float R = 0.04 * W;
274 
275  // Form the canvas name by appending th1d_name
276  TString canvasName;
277  canvasName.Form("canv_%s", th1d_name.Data());
278 
279  // Create a new canvas with the formed name
280  TCanvas* canv = new TCanvas(canvasName, canvasName, W, H);
281  canv->SetFillColor(0);
282  canv->SetBorderMode(0);
283  canv->SetFrameFillStyle(0);
284  canv->SetFrameBorderMode(0);
285  canv->SetLeftMargin(L / W + 0.05);
286  canv->SetRightMargin(R / W);
287  canv->SetTopMargin(T / H);
288  canv->SetBottomMargin(B / H);
289  canv->SetTickx(0);
290  canv->SetTicky(0);
291  canv->SetGrid();
292  canv->cd();
293 
294  gStyle->SetOptStat(0);
295 
296  TLegend* lg = new TLegend(0.3, 0.7, 0.7, 0.9);
297  lg->SetFillStyle(0);
298  lg->SetLineColor(0);
299  lg->SetEntrySeparation(0.05);
300 
301  double ymin;
302  double ymax;
303 
304  for (auto const& labelname : label_names | boost::adaptors::indexed(0)) {
305  double temp_ymin = th1d_input[labelname.index()]->GetMinimum();
306  double temp_ymax = th1d_input[labelname.index()]->GetMaximum();
307  if (labelname.index() == 0) {
308  ymin = temp_ymin;
309  ymax = temp_ymax;
310  }
311  if (temp_ymin <= ymin) {
312  ymin = temp_ymin;
313  }
314  if (temp_ymax >= ymax) {
315  ymax = temp_ymax;
316  }
317  }
318 
319  for (auto const& labelname : label_names | boost::adaptors::indexed(0)) {
320  th1d_input[labelname.index()]->SetMarkerColor(colors[labelname.index()]);
321  th1d_input[labelname.index()]->SetLineColor(colors[labelname.index()]);
322  th1d_input[labelname.index()]->SetMarkerStyle(styles[labelname.index()]);
323  th1d_input[labelname.index()]->GetXaxis()->SetTitle(xlabel);
324  th1d_input[labelname.index()]->GetYaxis()->SetTitle(ylabel);
325  th1d_input[labelname.index()]->GetYaxis()->SetTitleOffset(2.0);
326  lg->AddEntry(th1d_input[labelname.index()], labelname.value());
327 
328  TString label_meanmass_plot = "Mean M_{#mu#mu} (GeV)";
329  if (ylabel.EqualTo(label_meanmass_plot)) {
330  double ycenter = (ymax + ymin) / 2.0;
331  double yrange = (ymax - ymin) * 2;
332  double Ymin = ycenter - yrange;
333  double Ymax = ycenter + yrange * 1.10;
334  th1d_input[labelname.index()]->SetAxisRange(Ymin, Ymax, "Y");
335  th1d_input[labelname.index()]->Draw("PEX0same");
336  } else {
337  double Ymin = ymin - ymin * 0.07;
338  double Ymax = ymax + ymax * 0.35;
339  th1d_input[labelname.index()]->SetAxisRange(Ymin, Ymax, "Y");
340  th1d_input[labelname.index()]->Draw("HIST E1 same");
341  }
342  }
343 
344  CMS_lumi(canv, 0, 3, Rlabel);
345 
346  lg->Draw("same");
347 
348  canv->Update();
349  canv->RedrawAxis();
350  canv->GetFrame()->Draw();
351  canv->SaveAs(output_name);
352 
353  if (output_name.Contains(".pdf")) {
354  TString output_name_png(output_name); // output_name is const, copy to modify
355  output_name_png.Replace(output_name_png.Index(".pdf"), 4, ".png");
356  canv->SaveAs(output_name_png);
357  }
358 }
359 
360 int Zmumumerge(int argc, char* argv[]) {
361  vector<TString> vec_single_file_path;
362  vector<TString> vec_single_file_name;
363  vector<TString> vec_global_tag;
364  vector<TString> vec_title;
365  vector<int> vec_color;
366  vector<int> vec_style;
367  vector<TString> vec_right_title;
368 
370  options.helper(argc, argv);
371  options.parser(argc, argv);
372  pt::ptree main_tree;
373  pt::read_json(options.config, main_tree);
374  pt::ptree alignments = main_tree.get_child("alignments");
375  pt::ptree validation = main_tree.get_child("validation");
376 
377  for (const auto& childTree : alignments) {
378  // do not consider the nodes with a "file" to merge
379  if (childTree.second.find("file") == childTree.second.not_found()) {
380  std::cerr << "Ignoring alignment: " << childTree.second.get<std::string>("title") << ".\nNo file to merged found!"
381  << std::endl;
382  continue;
383  } else {
384  std::cout << "Storing alignment: " << childTree.second.get<std::string>("title") << std::endl;
385  }
386  vec_single_file_path.push_back(childTree.second.get<std::string>("file"));
387  vec_single_file_name.push_back(childTree.second.get<std::string>("file") + "/Zmumu.root");
388  vec_color.push_back(childTree.second.get<int>("color"));
389  vec_style.push_back(childTree.second.get<int>("style"));
390  if (childTree.second.find("customrighttitle") == childTree.second.not_found()) {
391  vec_right_title.push_back("");
392  } else {
393  vec_right_title.push_back(childTree.second.get<std::string>("customrighttitle"));
394  }
395  vec_global_tag.push_back(childTree.second.get<std::string>("globaltag"));
396  vec_title.push_back(childTree.second.get<std::string>("title"));
397 
398  //Fitting_GetMassmeanVSvariables(childTree.second.get<std::string>("file") + "/Zmumu.root", childTree.second.get<std::string>("file"));
399  }
400 
401  TString merge_output = main_tree.get<std::string>("output");
402  //=============================================
403  vector<TString> vec_single_fittingoutput;
404  vec_single_fittingoutput.clear();
405  for (unsigned i = 0; i < vec_single_file_path.size(); i++) {
406  Fitting_GetMassmeanVSvariables(vec_single_file_name[i], vec_single_file_path[i]);
407  vec_single_fittingoutput.push_back(vec_single_file_path[i] + "/fitting_output.root");
408  }
409 
410  int files_number = vec_single_file_path.size();
411  cout << "files_number=" << files_number << endl;
412  for (int idx_variable = 0; idx_variable < variables_number; idx_variable++) {
413  TString th1d_name = Form("th1d_meanmass_%s", tstring_variables_name[idx_variable].Data());
414 
416  vec_single_fittingoutput,
417  vec_title,
418  vec_color,
419  vec_style,
420  vec_right_title[0],
421  th1d_name,
422  tstring_variables_name_label[idx_variable].Data(),
423  "Mean M_{#mu#mu} (GeV)",
424  merge_output + Form("/meanmass_%s_GTs.pdf", tstring_variables_name[idx_variable].Data()));
425 
426  TString th1d_name_entries = Form("th1d_entries_%s", tstring_variables_name[idx_variable].Data());
427 
429  vec_single_fittingoutput,
430  vec_title,
431  vec_color,
432  vec_style,
433  vec_right_title[0],
434  th1d_name_entries,
435  tstring_variables_name_label[idx_variable].Data(),
436  "Events",
437  merge_output + Form("/entries_%s_GTs.pdf", tstring_variables_name[idx_variable].Data()));
438  }
439 
440  //=============================================
441  return EXIT_SUCCESS;
442 }
443 #ifndef DOXYGEN_SHOULD_SKIP_THIS
444 int main(int argc, char* argv[]) { return Zmumumerge(argc, argv); }
445 #endif
int Zmumumerge(int argc, char *argv[])
Definition: Zmumumerge.cc:360
static TString GT
Definition: Zmumumerge.cc:66
void makeNicePlotStyle(RooPlot *plot)
Definition: Zmumumerge.cc:49
Definition: APVGainStruct.h:7
static const int variables_number
Definition: Zmumumerge.cc:156
static PFTauRenderPlugin instance
static const int max_file_number
Definition: Zmumumerge.cc:241
FitOut ZMassBinFit_OldTool(TH1D *th1d_input, TString s_name="zmumu_fitting", TString output_path="./")
Definition: Zmumumerge.cc:78
FitOut(double a, double b, double c, double d)
Definition: Zmumumerge.cc:75
assert(be >=bs)
int main(int argc, char *argv[])
Definition: Zmumumerge.cc:444
const TString tstring_variables_name_label[variables_number]
Definition: Zmumumerge.cc:159
void Draw_TH1D_forMultiRootFiles(const vector< TString > &file_names, const vector< TString > &label_names, const vector< int > &colors, const vector< int > &styles, const TString &Rlabel, const TString &th1d_name, const TString &xlabel, const TString &ylabel, const TString &output_name)
Definition: Zmumumerge.cc:242
RooRealVar MuMu_mass("MuMu_mass", "MuMu_mass", 70, 110)
d
Definition: ztail.py:151
#define M_PI
double sigma_err
Definition: Zmumumerge.cc:73
const TString tstring_variables_name[variables_number]
Definition: Zmumumerge.cc:157
void Draw_th1d(TH1D *th1d_input, TString variable_name, TString output_path)
Definition: Zmumumerge.cc:139
std::vector< Style_t > styles
double b
Definition: hdecay.h:120
Definition: colors.py:1
double a
Definition: hdecay.h:121
double mean
Definition: Zmumumerge.cc:70
void Fitting_GetMassmeanVSvariables(TString inputfile_name, TString output_path)
Definition: Zmumumerge.cc:168
double chi2
Definition: Zmumumerge.cc:74
TLatex * tlxg
Definition: Zmumumerge.cc:67
double mean_err
Definition: Zmumumerge.cc:71
double sigma
Definition: Zmumumerge.cc:72
long double T
void CMS_lumi(TPad *pad, int iPeriod=3, int iPosX=10, TString RLabel="")
Definition: CMS_lumi.h:46