hpstr
The Heavy Photon Search Toolkit for Reconstruction (hpstr) provides an interface to physics data from the HPS experiment saved in the LCIO format and converts it into an ROOT based format.
Loading...
Searching...
No Matches
ApOptimizationProcessor.cxx
Go to the documentation of this file.
2
3#include <cstdlib>
4#include <fstream>
5#include <iostream>
6#include <string>
7
10
12
14 std::cout << "ApOptimizationProcessor::configure" << std::endl;
15 try {
16 // Basic config
17 debug_ = parameters.getInteger("debug", debug_);
18 year_ = parameters.getInteger("year", year_);
19 cuts_cfgFile_ = parameters.getString("cuts_cfgFile", cuts_cfgFile_);
20 outFileName_ = parameters.getString("outFileName", outFileName_);
21 cutVariables_ = parameters.getVString("cutVariables", cutVariables_);
22
23 // Background
24 bkgVtxAnaFilename_ = parameters.getString("bkgVtxAnaFilename", bkgVtxAnaFilename_);
25 bkgVtxAnaTreename_ = parameters.getString("bkgVtxAnaTreename", bkgVtxAnaTreename_);
26 background_sf_ = parameters.getDouble("background_sf", background_sf_);
27
28 // MC Signal
29 variableHistCfgFilename_ = parameters.getString("variableHistCfgFilename", variableHistCfgFilename_);
30 signalVtxAnaFilename_ = parameters.getString("signalVtxAnaFilename", signalVtxAnaFilename_);
31 // signalVtxSubsetAnaFilename_ = parameters.getString("signalVtxSubsetAnaFilename", signalVtxSubsetAnaFilename_);
32 signalVtxAnaTreename_ = parameters.getString("signalVtxAnaTreename", signalVtxAnaTreename_);
33 signalMCAnaFilename_ = parameters.getString("signalMCAnaFilename", signalMCAnaFilename_);
34 signalMCAnaTreename_ = parameters.getString("signalMCAnaTreename", signalMCAnaTreename_);
35 signal_pdgid_ = parameters.getString("signal_pdgid", signal_pdgid_);
36 signal_sf_ = parameters.getDouble("signal_sf", signal_sf_);
37 signal_mass_ = parameters.getDouble("signal_mass", signal_mass_);
38 mass_window_nsigma_ = parameters.getDouble("mass_window_nsigma", mass_window_nsigma_);
39 signalVtxMCSelection_ = parameters.getString("signalVtxMCSelection", signalVtxMCSelection_);
40 eps_ = pow(10, parameters.getInteger("eps", eps_)); // get logeps and convert to eps
41
42 // Optimization config
43 max_iteration_ = parameters.getInteger("max_iteration", max_iteration_);
44 step_size_ = parameters.getDouble("step_size", step_size_);
45 min_ztail_events_ = parameters.getDouble("min_ztail_events", min_ztail_events_);
46 scan_zcut_ = parameters.getInteger("scan_zcut", scan_zcut_);
47 fixed_zcut_ = parameters.getDouble("fixed_zcut", fixed_zcut_);
48
49 // Expected Signal Calculation
50 radFrac_ = parameters.getDouble("radFrac", radFrac_);
51 hit_category_ = parameters.getString("hit_category", hit_category_);
52 ztarget_ = parameters.getDouble("ztarget", ztarget_);
53 psum_cut_ = parameters.getDouble("psum_cut", psum_cut_);
54 } catch (std::runtime_error& error) {
55 std::cout << error.what() << std::endl;
56 }
57}
58
59void ApOptimizationProcessor::initialize(std::string inFilename, std::string outFilename) {
60 std::cout << "ApOptimizationProcessor::initialize with output file " << outFilename << std::endl;
61
62 outFileName_ = outFilename;
63
64 // TODO: write equation to find mass resolution at signal mass
66
67 // Define Mass window
71 "(vertex.invM_ > " + std::to_string(lowMass_) + " && vertex.invM_ < " + std::to_string(highMass_) + ")";
72
73 // Read signal ana vertex tuple, and convert to mutable tuple
74 std::cout << "ApOptimizationProcessor::initialize: Reading Signal AnaVertex Tuple from file "
75 << signalVtxAnaFilename_.c_str() << std::endl;
76 signalVtxAnaFile_ = new TFile(signalVtxAnaFilename_.c_str(), "READ");
78
79 // TFile* signalVtxSubsetAnaFile = new TFile(signalVtxSubsetAnaFilename_.c_str(), "READ");
80 // TTree* signal_subset_tree = (TTree*)signalVtxSubsetAnaFile->Get(signalVtxAnaTreename_.c_str());
81
82 std::cout << "ApOptimizationProcessor::initialize: Reading Signal MC Tuple from file "
83 << signalMCAnaFilename_.c_str() << std::endl;
84 signalMCAnaFile_ = new TFile(signalMCAnaFilename_.c_str(), "READ");
86
87 // Read background ana vertex tuple, and convert to mutable tuple
88 std::cout << "ApOptimizationProcessor::initialize: Reading Background AnaVertex Tuple from file "
89 << bkgVtxAnaFilename_.c_str() << std::endl;
90 bkgVtxAnaFile_ = new TFile(bkgVtxAnaFilename_.c_str(), "READ");
91 bkg_tree_ = (TTree*)bkgVtxAnaFile_->Get(bkgVtxAnaTreename_.c_str());
92
93 // Initialize Persistent Cut Selector. These cuts are applied to all events.
94 std::cout << "ApOptimizationProcessor::initialize: Initializing Set of Persistent Cuts" << std::endl;
96 persistentCutsSelector_->LoadSelection();
97 persistentCutsPtr_ = persistentCutsSelector_->getPointerToCuts();
98
99 // initalize Test Cuts
100 std::cout << "ApOptimizationProcessor::initialize: Initializing Set of Test Cuts" << std::endl;
102 testCutsSelector_->LoadSelection();
103 testCutsPtr_ = testCutsSelector_->getPointerToCuts();
104 testCutsSelector_->filterCuts(cutVariables_);
105
106 // Initialize signal histograms
107 signalHistos_ = std::make_shared<ZBiHistos>("signal");
108 signalHistos_->debugMode(debug_);
109 signalHistos_->loadHistoConfig(variableHistCfgFilename_);
110
111 // Initialize background histograms
112 bkgHistos_ = std::make_shared<ZBiHistos>("background");
113 bkgHistos_->debugMode(debug_);
114 bkgHistos_->loadHistoConfig(variableHistCfgFilename_);
115
116 // Initialize Test Cut histograms
117 testCutHistos_ = std::make_shared<ZBiHistos>("testCutHistos");
118 testCutHistos_->debugMode(debug_);
119
120 // Initialize processor histograms that summarize iterative results
121 processorHistos_ = std::make_shared<ZBiHistos>("zbi_processor");
122
123 initialCuts_ = "(psum > " + std::to_string(psum_cut_) + ") && " + massWindow_;
124
125 std::cout << "ApOptimizationProcessor::initialize: Setting up Test Cut PDFs and Quantiles" << std::endl;
126 json cut_cfg = signalHistos_->getConfig();
127 // Add Test Cut Analysis Histograms necessary for calculating background and signal
128 for (cut_iter_ it = testCutsPtr_->begin(); it != testCutsPtr_->end(); it++) {
129 std::string cut_name = it->first;
130 std::string cut_var = testCutsSelector_->getCutVar(cut_name, true);
131
132 persistentCutStrings_[cut_name] = initialCuts_ + " && " + getHitCategoryCut() + " && " +
133 persistentCutsSelector_->getFullCutString({cut_name}, true);
134
135 // Initialize graphs to store iterative results for each Test Cut variable
136 initializeGraphs(cut_name);
137
138 // Determine pdf and cdf for test cut variable (not meaningful for z0 and y0 variables)
139 initializeTestCutPDF(cut_name, cut_var, persistentCutStrings_[cut_name].c_str());
140
141 // Get cutvalue that corresponds to cutting n% of signal distribution in cutvar
142 if (cut_name == "pos_z0" || cut_name == "ele_z0" || cut_name == "min_y0") {
143 std::cout << "ApOptimizationProcessor::initialize: Setting up z0/y0 cut quantiles for cut " << cut_name
144 << std::endl;
145
146 json cut_cfg = signalHistos_->getConfig();
147 double* bins_and_limits_cut_var = getBinsAndLimits(cut_cfg, cut_name);
148 std::string bin_str = "(" + std::to_string((int)zbins_[0]) + "," + std::to_string(zbins_[1]) + "," +
149 std::to_string(zbins_[2]) + "," + std::to_string((int)bins_and_limits_cut_var[0]) + "," +
150 std::to_string(bins_and_limits_cut_var[1]) + "," + std::to_string(bins_and_limits_cut_var[2]) + ")";
151 signal_tree_->Draw(
152 (cut_var + ":vertex.getZ() >> h_pdf2d_signal_cut_" + cut_name + bin_str).c_str(),
153 persistentCutStrings_[cut_name].c_str());
154 TH2F* pdf_signal_cut = (TH2F*)gDirectory->Get(("h_pdf2d_signal_cut_" + cut_name).c_str());
155
157
158 testVarQuantiles_[cut_name] = new double[max_iteration_];
159 for (int i = 0; i < max_iteration_; i++) {
160 testVarQuantiles_[cut_name][i] = i * step_size_;
161 }
162
163 delete[] bins_and_limits_cut_var;
164 } else {
165 // find initial cut fraction to vary quantile calculation around
166 double initial_cut_value;
167 if (persistentCutsSelector_->getCutRange(cut_name).first < -999.) {
168 initial_cut_value = persistentCutsSelector_->getCutRange(cut_name).second;
169 } else if (persistentCutsSelector_->getCutRange(cut_name).second > 999.) {
170 initial_cut_value = persistentCutsSelector_->getCutRange(cut_name).first;
171 }
172 double initial_cut_frac =
173 testVarCDFs_[cut_name]->GetBinContent(testVarCDFs_[cut_name]->FindBin(initial_cut_value));
174
175 // quantiles of cut distribution
176 double* quantile_pos = new double[max_iteration_];
177 double* quantiles =
178 getQuantileArray(testCutsSelector_->getCutRange(cut_name), max_iteration_, initial_cut_frac);
179
180 testVarPDFs_[cut_name]->GetQuantiles(max_iteration_, quantile_pos, quantiles);
181 testVarQuantiles_[cut_name] = quantiles;
182 testVarQuantilePos_[cut_name] = quantile_pos;
183 }
184 }
185
186 // Calculate signal vertex efficiency vs vertex z using subset of signal MC with truth information
188
189 // Save data mass distribution after initial cuts for signal estimation
190 std::string mass_bin_str = "(" + std::to_string((int)massbins_[0]) + "," + std::to_string(massbins_[1]) + "," +
191 std::to_string(massbins_[2]) + ")";
192 bkg_tree_->Draw(("vertex.invM_ >> h_data_mass" + mass_bin_str).c_str(), initialCuts_.c_str());
193 h_data_mass_rad_ = (TH1D*)gDirectory->Get("h_data_mass");
194 h_data_mass_rad_->SetTitle((";m_{inv} [GeV];Events/" + std::to_string(mass_bin_width_) + "GeV").c_str());
195
196 bkgHistos_->addHisto1d(h_data_mass_rad_);
197
198 // apply initial cuts to background and keep for record
199 bkg_tree_->Draw(("vertex.getZ() >> h_data_vtxz_rad" + zbin_str_).c_str(), initialCuts_.c_str());
200 auto h_data_vtxz_rad_ = (TH1D*)gDirectory->Get("h_data_vtxz_rad");
201 h_data_vtxz_rad_->SetTitle((";z_{vtx} [mm];Events/" + std::to_string(z_bin_width_) + "mm").c_str());
202
203 bkgHistos_->addHisto1d(h_data_vtxz_rad_);
204}
205
207 std::cout << "ApOptimizationProcessor::process: Start of processing events" << std::endl;
208
209 auto t1 = std::chrono::high_resolution_clock::now();
210
211 for (cut_iter_ it = testCutsPtr_->begin(); it != testCutsPtr_->end(); it++) {
212 std::string cutname = it->first;
213 std::string cutvar = testCutsSelector_->getCutVar(cutname, true);
214
215 // iteratively cut n% of the signal distribution for a given Test Cut variable
216 for (int iteration = 0; iteration < max_iteration_; iteration++) {
217 double cutvalue;
218 double cutfraction = testVarQuantiles_[cutname][iteration];
219 std::string filter = "";
220 if (cutname == "pos_z0" || cutname == "ele_z0" || cutname == "min_y0") {
221 double zoffset = testZoffsetAlpha_[cutname][iteration].first; // mm
222 double alpha = testZoffsetAlpha_[cutname][iteration].second; // rad
223 filter = "vertex.getZ() * " + std::to_string(alpha) + " - abs(" + cutvar + ") < " +
224 std::to_string(alpha) + " * " + std::to_string(zoffset);
225 } else {
226 cutvalue = testVarQuantilePos_[cutname][iteration];
227 if (testCutsSelector_->getCutRange(cutname).first < -999.) {
228 filter = cutvar + " < " + std::to_string(cutvalue);
229 } else if (testCutsSelector_->getCutRange(cutname).second > 999.) {
230 filter = cutvar + " > " + std::to_string(cutvalue);
231 }
232 }
233
234 if (debug_) std::cout << "Applying Test Cut " << filter << " at iteration " << iteration << std::endl;
235
236 std::string tight_cuts = persistentCutStrings_[cutname] + " && " + filter;
237
238 bkg_tree_->Draw(
239 ("vertex.getZ() >> h_bkg_vtxz_cut_" + cutname + "_" + std::to_string(iteration) + zbin_str_).c_str(),
240 tight_cuts.c_str());
241 auto h_bkg_vtxz_cut =
242 (TH1D*)gDirectory->Get(("h_bkg_vtxz_cut_" + cutname + "_" + std::to_string(iteration)).c_str());
243 h_bkg_vtxz_cut->SetTitle(
244 (";z_{vtx} [mm];Background Events/" + std::to_string(z_bin_width_) + "mm").c_str());
245 h_bkg_vtxz_cut->Sumw2();
246 bkgHistos_->addHisto1d(h_bkg_vtxz_cut);
247
248 std::vector<double> zcuts;
249 if (fixed_zcut_ > -99.0) {
250 // use fixed zcut from config
251 zcuts.push_back(fixed_zcut_);
252 } else {
253 // find zcuts corresponding to different expected background levels
254 zcuts = findZcut(h_bkg_vtxz_cut, true, iteration);
255 }
256
257 double Nsig_for_best_zcut = 0.0;
258 double Nbkg_for_best_zcut = 0.0;
259 double best_z_cut = 0.0;
260 double ZBi_for_best_zcut = -99.0;
261
262 for (double zcut : zcuts) {
263 if (debug_) std::cout << "Using zcut = " << zcut << " mm" << std::endl;
264
265 // Apply zcut to signal and background and store vertex z histograms after cut
266 std::string zcut_filter = tight_cuts + " && (vertex.getZ() > " + std::to_string(zcut) + ")";
267
268 signal_tree_->Draw(
269 ("vertex.getZ() >> h_signal_vtxz_cut_" + cutname + "_" + std::to_string(iteration) + zbin_str_)
270 .c_str(),
271 zcut_filter.c_str());
272 auto h_signal_vtxz_cut =
273 (TH1D*)gDirectory->Get(("h_signal_vtxz_cut_" + cutname + "_" + std::to_string(iteration)).c_str());
274 h_signal_vtxz_cut->SetTitle(
275 (";z_{vtx} [mm];Signal Events/" + std::to_string(z_bin_width_) + "mm").c_str());
276 h_signal_vtxz_cut->Sumw2();
277 signalHistos_->addHisto1d(h_signal_vtxz_cut);
278
279 TH1F* h_chi =
280 (TH1F*)h_signal_vtxz_cut->Clone(("h_chi_" + cutname + "_" + std::to_string(iteration)).c_str());
281 h_chi->Divide(h_signal_vtxz_rad_);
282 processorHistos_->addHisto1d(h_chi);
283
284 double Nbkg = h_bkg_vtxz_cut->Integral(h_bkg_vtxz_cut->FindBin(zcut), h_bkg_vtxz_cut->GetNbinsX());
285 double Nsig = computeDisplacedYield(h_chi, 0.9 * 3.74);
286 double zbi = calculateZBi((Nsig + Nbkg), Nbkg, 1.0);
287
288 if (debug_)
289 std::cout << "Expected Signal: " << Nsig << ", Expected Background: " << Nbkg << ", ZBi: " << zbi
290 << std::endl;
291
292 if (zbi > ZBi_for_best_zcut) {
293 ZBi_for_best_zcut = zbi;
294 best_z_cut = zcut;
295 Nsig_for_best_zcut = Nsig;
296 Nbkg_for_best_zcut = Nbkg;
297 }
298 }
299
300 if (cutname == "pos_z0" || cutname == "ele_z0" || cutname == "min_y0") {
301 double zoffset = testZoffsetAlpha_[cutname][iteration].first; // mm
302 double alpha = testZoffsetAlpha_[cutname][iteration].second; // rad
303
304 processorHistos_->getGraph("g_nsig_vs_" + cutname)->AddPoint(iteration, Nsig_for_best_zcut);
305 processorHistos_->getGraph("g_nbkg_vs_" + cutname)->AddPoint(iteration, Nbkg_for_best_zcut);
306 processorHistos_->getGraph("g_zcut_vs_" + cutname)->AddPoint(iteration, best_z_cut);
307 processorHistos_->getGraph("g_zbi_vs_" + cutname)->AddPoint(iteration, ZBi_for_best_zcut);
308 processorHistos_->getGraph("g_cut_frac_vs_" + cutname)->AddPoint(iteration, cutfraction);
309 processorHistos_->getGraph("g_zoffset_vs_" + cutname)->AddPoint(iteration, zoffset);
310 processorHistos_->getGraph("g_alpha_vs_" + cutname)->AddPoint(iteration, alpha);
311 } else {
312 processorHistos_->getGraph("g_nsig_vs_" + cutname)->AddPoint(cutvalue, Nsig_for_best_zcut);
313 processorHistos_->getGraph("g_nbkg_vs_" + cutname)->AddPoint(cutvalue, Nbkg_for_best_zcut);
314 processorHistos_->getGraph("g_zcut_vs_" + cutname)->AddPoint(cutvalue, best_z_cut);
315 processorHistos_->getGraph("g_zbi_vs_" + cutname)->AddPoint(cutvalue, ZBi_for_best_zcut);
316 processorHistos_->getGraph("g_cut_frac_vs_" + cutname)->AddPoint(cutvalue, cutfraction);
317 }
318 }
319 }
320
321 auto t2 = std::chrono::high_resolution_clock::now();
322
323 /* Getting number of milliseconds as an integer. */
324 auto time_in_sec = std::chrono::duration_cast<std::chrono::seconds>(t2 - t1);
325
326 std::cout << "ApOptimizationProcessor::process: End of processing events. Time taken: " << time_in_sec.count()
327 << " s" << std::endl;
328 return true;
329}
330
332 std::cout << "ApOptimizationProcessor::finalize" << std::endl;
333
334 // Initialize output file
335 outFile_ = new TFile(outFileName_.c_str(), "RECREATE");
336
337 processorHistos_->saveHistos(outFile_, "processorHistos");
338 processorHistos_->writeGraphs(outFile_, "processorGraphs");
339 testCutHistos_->saveHistos(outFile_, "testCutHistos");
340 signalHistos_->saveHistos(outFile_, "signal");
341 bkgHistos_->saveHistos(outFile_, "background");
342
343 outFile_->Close();
344}
345
347 // EAp in GeV, mass in GeV
348 // z, ztarget in mm
349 double gamma = EAp / signal_mass_;
350 double ctau = 0.08 * pow(1e-4 / eps_, 2) * 0.1 / signal_mass_; // mm
351 return exp(-(z - ztarget_) / (gamma * ctau)) / (gamma * ctau);
352}
353
355 // double Nbin = h_data_mass_rad_->GetBinContent(h_data_mass_rad_->FindBin(signal_mass_)); // content at signal mass
356 double Nbin = h_data_mass_rad_->Integral(h_data_mass_rad_->FindBin(lowMass_), h_data_mass_rad_->FindBin(highMass_)); // content in mass window
357 double alpha = 1 / 137.0;
358 double factors = 3 * TMath::Pi() * pow(eps_, 2) / (2 * alpha);
359
360 return radFrac_ * factors * Nbin * signal_mass_ / mass_bin_width_;
361}
362
363double ApOptimizationProcessor::computeDisplacedYield(TH1* h_chi_eff, double EAp) {
364 double expected_signal = 0.0;
365 for (int i = 1; i <= h_chi_eff->GetNbinsX(); i++) {
366 double z = h_chi_eff->GetBinCenter(i);
367 double Ntruth = computeTruthSignalShape(z, EAp);
368 double eff = h_chi_eff->GetBinContent(i) * f_xi_eff_->Eval(z);
369 expected_signal += eff * Ntruth;
370 }
371 expected_signal *= computePromptYield();
372
373 if (debug_) std::cout << "Expected Displaced Signal Yield: " << expected_signal << std::endl;
374 return expected_signal;
375}
376
377std::vector<double> ApOptimizationProcessor::fitZBkgTail(TH1* h_bkg, std::string fitname) {
378 std::vector<double> fit_params;
379 TF1* bkg_tail_fit = new TF1(fitname.c_str(), "[0]*exp([2]*(x-[1]))", 0.0, 10.0);
380 bkg_tail_fit->SetParameters(1000.0, 30.0, -0.1);
381 h_bkg->Fit(bkg_tail_fit, "RQ");
382 fit_params.push_back(bkg_tail_fit->GetParameter(0)); // A
383 fit_params.push_back(bkg_tail_fit->GetParameter(1)); // z0
384 fit_params.push_back(bkg_tail_fit->GetParameter(2)); // slope
385 return fit_params;
386}
387
388std::vector<double> ApOptimizationProcessor::findZcut(TH1* h_bkg_vtxz_cut, bool fromTailFit, int iteration) {
389 std::vector<double> zcuts;
390 double A = 0.0;
391 double z0 = 0.0;
392 double slope = 0.0;
393
394 if (fromTailFit) {
395 // fit z tail to find zcut corresponding to ztail_events
396 std::vector<double> fit_params = fitZBkgTail((TH1*)h_bkg_vtxz_cut, "bkg_tail_fit" + std::to_string(iteration));
397 A = fit_params[0];
398 z0 = fit_params[1];
399 slope = fit_params[2];
400 }
401
402 for (double ztail_events = min_ztail_events_; ztail_events <= 20; ztail_events += 0.5) {
403 if (fromTailFit) {
404 // fit z tail to find zcut corresponding to ztail_events
405 double zcut = z0 - (log(ztail_events) - log(A)) / slope;
406 zcuts.push_back(zcut);
407 } else {
408 double cumulative_bkg = 0.0;
409 for (int bin = h_bkg_vtxz_cut->GetNbinsX(); bin >= min_ztail_events_; bin--) {
410 cumulative_bkg += h_bkg_vtxz_cut->GetBinContent(bin);
411 if (cumulative_bkg >= 1.0) {
412 double zcut = h_bkg_vtxz_cut->GetBinLowEdge(bin);
413 zcuts.push_back(zcut);
414 break;
415 }
416 }
417 }
418 if (!scan_zcut_) {
419 break; // only need one zcut if not scanning
420 }
421 }
422
423 return zcuts;
424}
425
426// Get mass resolution in GeV
428 mass *= 1000.; // convert to MeV
429 if (hit_category_ == "l1l1") {
430 return (0.4840 + 0.0421 * mass) / 1000.;
431 } else if (hit_category_ == "l1l2") {
432 return (0.8124 + 0.0422 * mass) / 1000.;
433 } else {
434 return 0.005; // default 5 MeV
435 }
436}
437
439 if (hit_category_ == "l1l1") {
440 return "(eleL1 && eleL2 && posL1 && posL2)";
441 } else if (hit_category_ == "l1l2") {
442 return "((eleL1 && eleL2 && posL2 && !posL1) || (posL1 && posL2 && eleL2 && !eleL1))";
443 } else if (hit_category_ == "l2l2") {
444 return "(eleL2 && !eleL1 && posL2 && !posL1)";
445 } else {
446 return "(1)"; // no cut
447 }
448}
449
450double* ApOptimizationProcessor::getBinsAndLimits(json histo_cfg, std::string varname) {
451 for (auto& hist_config : histo_cfg.items()) {
452 // check if key contains varname
453 if (hist_config.key().find(varname) != std::string::npos) {
454 double bins = hist_config.value().at("bins");
455 double minX = hist_config.value().at("minX");
456 double maxX = hist_config.value().at("maxX");
457 return new double[3]{bins, minX, maxX};
458 }
459 }
460 return new double[3]{100, 0, 100};
461}
462
463void ApOptimizationProcessor::initializeTestCutPDF(std::string cut_name, std::string cut_var,
464 std::string persistent_cuts) {
465 json cut_cfg = signalHistos_->getConfig();
466 double* bins_and_limits = getBinsAndLimits(cut_cfg, cut_name);
467 std::string drawstring = cut_var + ">>" + cut_name + "_pdf_h(" + std::to_string((int)bins_and_limits[0]) + "," +
468 std::to_string(bins_and_limits[1]) + "," + std::to_string(bins_and_limits[2]) + ")";
469
470 signal_tree_->Draw(drawstring.c_str(), persistent_cuts.c_str());
471 // sig_h is used to determine pdf for test cut 'cut_name'
472 TH1F* sig_h = (TH1F*)gDirectory->Get((cut_name + "_pdf_h").c_str());
473 sig_h->Sumw2();
474 sig_h->Scale(1. / sig_h->Integral());
475 sig_h->SetTitle(("; " + cut_var + "; normalized units").c_str());
476 testCutHistos_->addHisto1d(sig_h);
477
478 delete[] bins_and_limits;
479
480 // actual definition of pdf and cdf
481 testVarPDFs_[cut_name] = (TH1F*)testCutHistos_->getPDF(cut_name + "_pdf_h");
482
483 bool forward = testCutsSelector_->getCutRange(cut_name).first < -999 ? false : true;
484 testVarCDFs_[cut_name] = (TH1F*)testVarPDFs_[cut_name]->GetCumulative(forward);
485 testCutHistos_->addHisto1d(testVarCDFs_[cut_name]);
486}
487
489 TGraphErrors* g_zbi = processorHistos_->configureGraph(("g_zbi_vs_" + cut_name).c_str(), "", "Z_{Bi}");
490 processorHistos_->addGraph(g_zbi);
491
492 TGraphErrors* g_nsig = processorHistos_->configureGraph(("g_nsig_vs_" + cut_name).c_str(), "", "N_{sig}");
493 processorHistos_->addGraph(g_nsig);
494
495 TGraphErrors* g_nbkg = processorHistos_->configureGraph(("g_nbkg_vs_" + cut_name).c_str(), "", "N_{bkg}");
496 processorHistos_->addGraph(g_nbkg);
497
498 TGraphErrors* g_zcut = processorHistos_->configureGraph(("g_zcut_vs_" + cut_name).c_str(), "", "z_{cut}/mm");
499 processorHistos_->addGraph(g_zcut);
500
501 TGraphErrors* g_cut_frac =
502 processorHistos_->configureGraph(("g_cut_frac_vs_" + cut_name).c_str(), "", "N_{sig}^{cut}/N_{sig}^{original}");
503 processorHistos_->addGraph(g_cut_frac);
504
505 // Additional graphs for zoffset and alpha if test cut variable is related to track z0 or y0
506 if (cut_name == "pos_z0" || cut_name == "ele_z0" || cut_name == "min_y0") {
507 TGraphErrors* g_zoffset =
508 processorHistos_->configureGraph(("g_zoffset_vs_" + cut_name).c_str(), "", "z_{offset}/mm");
509 processorHistos_->addGraph(g_zoffset);
510
511 TGraphErrors* g_alpha = processorHistos_->configureGraph(("g_alpha_vs_" + cut_name).c_str(), "", "#alpha");
512 processorHistos_->addGraph(g_alpha);
513 }
514}
515
517 // vertex z distribution from generated A' sample
518 signal_pretrig_sim_tree_->Draw(("vtx.z >> h_pretrig_signal_vtxz" + zbin_str_).c_str());
519 h_pretrig_signal_vtxz_ = (TH1D*)gDirectory->Get("h_pretrig_signal_vtxz");
520 h_pretrig_signal_vtxz_->Sumw2();
521
522 // vertex z distribution from reconstructed A' (corresponding to generated sample)
523 // apply psum and mass window cuts == initial cuts
524 signal_tree_->Draw(("true_ap.vtx_z_ >> h_signal_vtxz_rad" + zbin_str_).c_str(), initialCuts_.c_str());
525 h_signal_vtxz_rad_ = (TH1D*)gDirectory->Get("h_signal_vtxz_rad");
526 h_signal_vtxz_rad_->SetTitle((";z_{truth} [mm];Events/" + std::to_string(z_bin_width_) + "mm").c_str());
527 h_signal_vtxz_rad_->Sumw2();
528
529 TH1D* h_xi_eff = (TH1D*)h_signal_vtxz_rad_->Clone("h_xi_eff");
530 h_xi_eff->Divide(h_pretrig_signal_vtxz_);
531
532 f_xi_eff_ = new TF1("f_xi_eff_", "exp([0] + [1]*x + [2]*x*x)", -1, 150);
533 h_xi_eff->Fit(f_xi_eff_, "SRQ", "", -1, 150);
534
535 double xi_eff_0 = f_xi_eff_->Eval(ztarget_);
536 f_xi_eff_->SetParameters(f_xi_eff_->GetParameter(0) - log(xi_eff_0), f_xi_eff_->GetParameter(1),
537 f_xi_eff_->GetParameter(2));
538
541 signalHistos_->addHisto1d(h_xi_eff);
542
543 // // determine h_signal_vtxz_rad_ for full signal sample
544 // signal_tree_->Draw(("vertex.getZ() >> h_signal_vtxz_rad" + zbin_str_).c_str(), initialCuts_.c_str());
545 // h_signal_vtxz_rad_ = (TH1D*)gDirectory->Get("h_signal_vtxz_rad");
546 // h_signal_vtxz_rad_->SetTitle((";z_{vtx} [mm];Events/" + std::to_string(z_bin_width_) + "mm").c_str());
547 // h_signal_vtxz_rad_->Sumw2();
548
549 // signalHistos_->addHisto1d(h_signal_vtxz_rad_);
550}
551
552double* ApOptimizationProcessor::getQuantileArray(std::pair<double, double> range, int n_quantiles,
553 double initial_cut_frac) {
554 double* quantiles = new double[n_quantiles];
555 double start_frac = 1.0;
556
557 if (debug_)
558 std::cout << "ApOptimizationProcessor::getQuantileArray: Initial cut fraction = " << initial_cut_frac
559 << std::endl;
560 if (initial_cut_frac > -999.) {
561 // recenter quantiles around initial cut fraction
562 start_frac = initial_cut_frac - (n_quantiles / 2) * step_size_;
563 if (debug_)
564 std::cout << "ApOptimizationProcessor::getQuantileArray: Start at fraction = " << start_frac << std::endl;
565 for (int i = 0; i < n_quantiles; i++) {
566 if (start_frac + step_size_ * i < 0.)
567 quantiles[i] = 0.;
568 else if (start_frac + step_size_ * i > 1.)
569 quantiles[i] = 1.;
570 else
571 quantiles[i] = start_frac + step_size_ * i;
572 }
573 if (range.first < -999.) {
574 for (int i = 0; i < n_quantiles; i++) {
575 quantiles[i] = 1 - quantiles[i];
576 }
577 }
578 } else {
579 if (range.first < -999.) {
580 for (int i = 0; i < n_quantiles; i++) {
581 quantiles[i] = 1 - step_size_ * i;
582 }
583 } else if (range.second > 999.) {
584 for (int i = 0; i < n_quantiles; i++) {
585 quantiles[i] = step_size_ * i;
586 }
587 }
588 }
589 return quantiles;
590}
591
592std::vector<std::pair<double, double>> ApOptimizationProcessor::getZoffsetAlpha(TH2F* h_y0_vs_z, int n_quantiles,
593 int nbins) {
594 double* quantiles = getQuantileArray(std::make_pair(0, 9999.9), n_quantiles);
595 std::vector<std::pair<double, double>> zoffset_alpha;
596 processorHistos_->addHisto2d(h_y0_vs_z);
597 for (int q = 0; q < n_quantiles; q++) {
598 TGraphErrors* g_y0_vs_z =
599 processorHistos_->configureGraph(("g_y0_vs_z_q" + std::to_string(q)).c_str(), "z_{vtx} [mm]", "y_{0} [mm]");
600 processorHistos_->addGraph(g_y0_vs_z);
601 }
602 if (debug_)
603 std::cout << "ApOptimizationProcessor::getZoffsetAlpha: Number of z bins = "
604 << int(h_y0_vs_z->GetNbinsX() / nbins) << std::endl;
605
606 for (int i = 0; i < int(h_y0_vs_z->GetNbinsX() / nbins); i++) {
607 auto h_proj = h_y0_vs_z->ProjectionY(("h_y0_vs_z_py_" + std::to_string(i)).c_str(), nbins * i + 1, nbins * (i + 1));
608
609 if (h_proj->GetEntries() < 50) {
610 if (debug_) {
611 std::cout << "ApOptimizationProcessor::getZoffsetAlpha: Skipping z slice " << i
612 << " with entries = " << h_proj->GetEntries() << std::endl;
613 }
614 continue;
615 }
616 processorHistos_->addHisto1d(h_proj);
617 double zval = ((TAxis*)h_y0_vs_z->GetXaxis())->GetBinCenter(nbins * (i + 0.5));
618
619 double* quantile_pos = new double[n_quantiles];
620 h_proj->GetQuantiles(n_quantiles, quantile_pos, quantiles);
621 for (int q = 0; q < n_quantiles; q++) {
622 //processorHistos_->getGraph(("g_y0_vs_z_q" + std::to_string(q)).c_str())->AddPointError(zval, quantile_pos[q], 0.0, 0.0);
623 TGraphErrors* g = processorHistos_->getGraph(("g_y0_vs_z_q" + std::to_string(q)).c_str());
624 int n = g->GetN();
625 g->SetPoint(n, zval, quantile_pos[q]);
626 g->SetPointError(n, 0.0, 0.0);
627 // double error = 0.;
628
629 // processorHistos_->getGraph(("g_y0_vs_z_q" + std::to_string(q)).c_str())->SetPointError(i, 0.0, error);
630 }
631 }
632 for (int q = 0; q < n_quantiles; q++) {
633 if (q == 0) {
634 zoffset_alpha.push_back(std::make_pair(0.0, 0.0));
635 continue;
636 }
637 TF1* f1 = new TF1(("f1_y0_vs_z_q" + std::to_string(q)).c_str(), "[0] + [1]*x", -0.5, 15);
638 processorHistos_->getGraph(("g_y0_vs_z_q" + std::to_string(q)).c_str())->Fit(f1, "QRS");
639
640 double zoffset = -f1->GetParameter(0) / f1->GetParameter(1);
641 zoffset_alpha.push_back(std::make_pair(zoffset, f1->GetParameter(1)));
642 if (debug_)
643 std::cout << "Quantile " << q << " : zoffset = " << zoffset << " alpha = " << f1->GetParameter(1)
644 << std::endl;
645 }
646 return zoffset_alpha;
647}
648
nlohmann::json json
#define DECLARE_PROCESSOR(CLASS)
Macro which allows the framework to construct a producer given its name during configuration.
Definition Processor.h:139
Cutflow optimization tool for A'.
TreeCutSelector * persistentCutsSelector_
std::map< std::string, TH1F * > testVarPDFs_
virtual void configure(const ParameterSet &parameters)
description
virtual void initialize(TTree *tree)
description
double * getBinsAndLimits(json histo_cfg, std::string varname)
virtual void finalize()
description
std::map< std::string, std::vector< std::pair< double, double > > > testZoffsetAlpha_
std::map< std::string, std::string > persistentCutStrings_
std::map< std::string, std::pair< std::pair< double, double >, int > >::iterator cut_iter_
std::map< std::string, TH1F * > testVarCDFs_
std::vector< double > fitZBkgTail(TH1 *h_bkg_vtxz, std::string fitname)
void initializeGraphs(std::string cut_name)
std::map< std::string, std::pair< std::pair< double, double >, int > > * persistentCutsPtr_
std::vector< double > findZcut(TH1 *h_bkg_vtxz_cut, bool fromTailFit, int iteration=0)
std::vector< std::pair< double, double > > getZoffsetAlpha(TH2F *h_y0_vs_z, int n_quantiles, int nbins)
std::map< std::string, std::pair< std::pair< double, double >, int > > * testCutsPtr_
double computeDisplacedYield(TH1 *h_chi_eff, double EAp)
double computeTruthSignalShape(double z, double EAp)
ApOptimizationProcessor(const std::string &name, Process &process)
std::map< std::string, double * > testVarQuantiles_
std::map< std::string, double * > testVarQuantilePos_
virtual bool process(IEvent *event)
description
double * getQuantileArray(std::pair< double, double > range, int n_quantiles, double initial_cut_frac=-999.9)
virtual bool process()
description
void initializeTestCutPDF(std::string cut_name, std::string cut_var, std::string persistent_cuts)
double calculateZBi(double n_on, double n_off, double tau)
description
std::shared_ptr< ZBiHistos > bkgHistos_
std::vector< std::string > cutVariables_
OptimizationProcessor(const std::string &name, Process &process)
std::shared_ptr< ZBiHistos > processorHistos_
std::shared_ptr< ZBiHistos > signalHistos_
std::shared_ptr< ZBiHistos > testCutHistos_
description