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
TrackSmearingTool.cxx
Go to the documentation of this file.
1#include "TrackSmearingTool.h"
3#include "TFile.h"
4#include "TH1D.h"
5
6#include <stdexcept>
7#include <cstdlib>
8#include <iomanip>
9#include <map>
10
11// Helper function to check file extension
12static bool endsWith(const std::string& str, const std::string& suffix) {
13 if (suffix.size() > str.size()) return false;
14 return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
15}
16
17TrackSmearingTool::TrackSmearingTool(const std::string& smearingfile,
18 const bool relSmearingP,
19 const bool relSmearingZ0,
20 const int seed,
21 const std::string& tracks,
22 const double smearingFactor){
23
24 smearingFactor_ = smearingFactor;
25
26 // Auto-detect file type based on extension
27 if (endsWith(smearingfile, ".json")) {
28 // JSON config file with top/bot smearing values
29 std::ifstream cfgFile(smearingfile);
30 if (!cfgFile)
31 throw std::invalid_argument("Smearing JSON config file not found: " + smearingfile);
32
33 json cfg;
34 cfgFile >> cfg;
35
36 if (cfg.contains("pSmearing")) {
37 const auto& ps = cfg["pSmearing"];
38 pSmearingValueTop_ = ps["top"].get<double>() * smearingFactor_;
39 pSmearingValueBot_ = ps["bot"].get<double>() * smearingFactor_;
40 if (ps.contains("mu_data") && ps.contains("mu_mc")) {
41 pMeanDataTop_ = ps["mu_data"]["top"].get<double>();
42 pMeanDataBot_ = ps["mu_data"]["bot"].get<double>();
43 pMeanMcTop_ = ps["mu_mc"]["top"].get<double>();
44 pMeanMcBot_ = ps["mu_mc"]["bot"].get<double>();
45 hasMeanCorrP_ = true;
46 }
47 }
48 if (cfg.contains("z0Smearing")) {
49 const auto& zs = cfg["z0Smearing"];
50 z0SmearingValueTop_ = zs["top"].get<double>() * smearingFactor_;
51 z0SmearingValueBot_ = zs["bot"].get<double>() * smearingFactor_;
52 if (zs.contains("mu_data") && zs.contains("mu_mc")) {
53 z0MeanDataTop_ = zs["mu_data"]["top"].get<double>();
54 z0MeanDataBot_ = zs["mu_data"]["bot"].get<double>();
55 z0MeanMcTop_ = zs["mu_mc"]["top"].get<double>();
56 z0MeanMcBot_ = zs["mu_mc"]["bot"].get<double>();
57 hasMeanCorrZ0_ = true;
58 }
59 }
60
61 // Support separate relSmearing for p and z0, with backwards compatibility
62 // If relSmearingP/relSmearingZ0 are present, use them; otherwise fall back to relSmearing
63 if (cfg.contains("relSmearingP")) {
64 relSmearingP_ = cfg["relSmearingP"].get<bool>();
65 } else if (cfg.contains("relSmearing")) {
66 relSmearingP_ = cfg["relSmearing"].get<bool>();
67 } else {
68 relSmearingP_ = false;
69 }
70
71 if (cfg.contains("relSmearingZ0")) {
72 relSmearingZ0_ = cfg["relSmearingZ0"].get<bool>();
73 } else if (cfg.contains("relSmearing")) {
74 relSmearingZ0_ = cfg["relSmearing"].get<bool>();
75 } else {
76 relSmearingZ0_ = false;
77 }
78
79 // Parse omega smearing parameters (optional)
80 if (cfg.contains("omegaSmearing")) {
81 const auto& os = cfg["omegaSmearing"];
82 omegaSmearingValueTop_ = os["top"].get<double>() * smearingFactor_;
83 omegaSmearingValueBot_ = os["bot"].get<double>() * smearingFactor_;
84 if (os.contains("mu_data") && os.contains("mu_mc")) {
85 omegaMeanDataTop_ = os["mu_data"]["top"].get<double>();
86 omegaMeanDataBot_ = os["mu_data"]["bot"].get<double>();
87 omegaMeanMcTop_ = os["mu_mc"]["top"].get<double>();
88 omegaMeanMcBot_ = os["mu_mc"]["bot"].get<double>();
89 hasMeanCorrOmega_ = true;
90 }
91 }
92
93 // Parse smearOmega flag (optional, default false)
94 if (cfg.contains("smearOmega")) {
95 smearOmega_ = cfg["smearOmega"].get<bool>();
96 }
97
98 // Parse all {section}_binned_{varname} entries from hpsplot tool JSON.
99 // Each entry key encodes both the section and the lookup variable name.
100 auto parseBinnedSection = [&](const std::string& prefix,
101 std::map<std::string, BinnedParam>& binMap,
102 bool applyFactor) {
103 for (auto& [k, v] : cfg.items()) {
104 if (k.rfind(prefix, 0) != 0) continue;
105 std::string var = k.substr(prefix.size());
106 if (var.empty() || !v.contains("top") || !v.contains("bot")) continue;
107 BinnedParam& bp = binMap[var];
108 bp.edgesTop = v["top"]["bin_edges"].get<std::vector<double>>();
109 bp.edgesBot = v["bot"]["bin_edges"].get<std::vector<double>>();
110 if (v["top"].contains("values")) {
111 bp.valTop = v["top"]["values"].get<std::vector<double>>();
112 bp.valBot = v["bot"]["values"].get<std::vector<double>>();
113 if (applyFactor) {
114 for (auto& x : bp.valTop) x *= smearingFactor_;
115 for (auto& x : bp.valBot) x *= smearingFactor_;
116 }
117 }
118 if (v["top"].contains("mu_data") && v["top"].contains("mu_mc")) {
119 bp.muDatTop = v["top"]["mu_data"].get<std::vector<double>>();
120 bp.muMcTop = v["top"]["mu_mc"].get<std::vector<double>>();
121 bp.muDatBot = v["bot"]["mu_data"].get<std::vector<double>>();
122 bp.muMcBot = v["bot"]["mu_mc"].get<std::vector<double>>();
123 }
124 }
125 };
126 parseBinnedSection("pSmearing_binned_", pBinned_, true);
127 parseBinnedSection("omegaSmearing_binned_", omegaBinned_, true);
128 parseBinnedSection("z0Smearing_binned_", z0Binned_, false);
129
130 // Set hasMeanCorr flags if any binned entry (or scalar) has means
131 for (const auto& [v, bp] : pBinned_)
132 if (!bp.muDatTop.empty()) { hasMeanCorrP_ = true; break; }
133 for (const auto& [v, bp] : omegaBinned_)
134 if (!bp.muDatTop.empty()) { hasMeanCorrOmega_ = true; break; }
135 for (const auto& [v, bp] : z0Binned_)
136 if (!bp.muDatTop.empty()) { hasMeanCorrZ0_ = true; break; }
137
138 useFixedSmearing_ = true;
139 useSeparateTopBot_ = true;
140 smearingFile_ = smearingfile;
141
142 } else {
143 // ROOT file with smearing histograms
144 relSmearingP_ = relSmearingP;
145 relSmearingZ0_ = relSmearingZ0;
146 std::string hsuffix = relSmearingP_ ? "_rel" : "";
147 smearingfile_ = std::make_shared<TFile>(smearingfile.c_str());
148
149 if (!smearingfile_)
150 throw std::invalid_argument("Provided input smearing file does not exist");
151
152 //cache the smearing histograms
153 smearing_histo_top_ = (TH1D*) smearingfile_->Get((tracks+"_p_vs_nHits_top_hh_smearing"+hsuffix).c_str());
154 smearing_histo_bot_ = (TH1D*) smearingfile_->Get((tracks+"_p_vs_nHits_bot_hh_smearing"+hsuffix).c_str());
155
157 throw std::invalid_argument("Top and Bottom smearing histograms not found in smearing file");
158
159 }
160
161 //setup random engine
162 if (debug_)
163 std::cout<<"Setting up random engine with seed "<<seed<<std::endl;
164 generator_ = std::make_shared<std::default_random_engine>(seed);
165
166 normal_ = std::make_shared<std::normal_distribution<double>>(0.,1.);
167
168}
169
170TrackSmearingTool::TrackSmearingTool(const double pSmearingValue,
171 const double z0SmearingValue,
172 const bool relSmearingP,
173 const bool relSmearingZ0,
174 const int seed,
175 const double smearingFactor) {
176
177 smearingFactor_ = smearingFactor;
178 relSmearingP_ = relSmearingP;
179 relSmearingZ0_ = relSmearingZ0;
180 pSmearingValue_ = pSmearingValue * smearingFactor_;
181 z0SmearingValue_ = z0SmearingValue * smearingFactor_;
182 useFixedSmearing_ = true;
183
184 //setup random engine
185 if (debug_)
186 std::cout<<"Setting up random engine with seed "<<seed<<std::endl;
187 generator_ = std::make_shared<std::default_random_engine>(seed);
188
189 normal_ = std::make_shared<std::normal_distribution<double>>(0.,1.);
190
191 if (debug_) {
192 std::cout<<"Using smearing factor: "<<smearingFactor_<<std::endl;
193 std::cout<<"Using fixed p smearing value: "<<pSmearingValue_<<std::endl;
194 std::cout<<"Using fixed z0 smearing value: "<<z0SmearingValue_<<std::endl;
195 std::cout<<"Using relSmearingP: "<<relSmearingP_<<" relSmearingZ0: "<<relSmearingZ0_<<std::endl;
196 }
197
198}
199
200double TrackSmearingTool::lookupBinnedValue(const std::vector<double>& edges,
201 const std::vector<double>& values,
202 double x) const {
203 if (edges.size() < 2 || values.empty()) return 0.;
204 if (x <= edges.front()) return values.front();
205 if (x >= edges.back()) return values.back();
206 auto it = std::upper_bound(edges.begin(), edges.end(), x);
207 int bin = static_cast<int>(std::distance(edges.begin(), it)) - 1;
208 if (bin < 0) bin = 0;
209 if (bin >= static_cast<int>(values.size())) bin = static_cast<int>(values.size()) - 1;
210 return values[bin];
211}
212
213double TrackSmearingTool::getLookupValue(const Track& track) const {
214 if (binnedLookupVariable_ == "phi0" || binnedLookupVariable_ == "phi")
215 return track.getPhi();
216 if (binnedLookupVariable_ == "nHits" || binnedLookupVariable_ == "nhits")
217 return static_cast<double>(track.getTrackerHitCount());
218 return track.getTanLambda(); // default: tanLambda
219}
220
221void TrackSmearingTool::setForcedVariable(const std::string& var) {
222 if (var.empty()) return; // leave JSON defaults in place
223
224 if (var == "flat") {
225 // Force scalar mode — clear all binned maps so lookups fall back to flat values
226 pBinned_.clear();
227 omegaBinned_.clear();
228 z0Binned_.clear();
229 std::cout << "TrackSmearingTool: forced to flat (scalar) smearing." << std::endl;
230 return;
231 }
232
233 // Validate that at least one section has a binned entry for the requested variable
234 bool found = pBinned_.count(var) || omegaBinned_.count(var) || z0Binned_.count(var);
235 if (!found)
236 throw std::invalid_argument(
237 "TrackSmearingTool: smearingVariable='" + var +
238 "' requested but no binned smearing data was found for this variable in the JSON.");
239
241 std::cout << "TrackSmearingTool: using binned smearing, variable='" << var << "'." << std::endl;
242}
243
244void TrackSmearingTool::setScaleCorrVariable(const std::string& var) {
245 if (var.empty()) {
247 std::cout << "TrackSmearingTool: scaleCorrVariable cleared — "
248 << "omega data-mode scale correction uses omegaSmearing_binned_"
249 << binnedLookupVariable_ << " means (default)." << std::endl;
250 return;
251 }
252 if (!pBinned_.count(var))
253 throw std::invalid_argument(
254 "TrackSmearingTool: scaleCorrVariable='" + var +
255 "' not found in pSmearing_binned tables. Check JSON contains pSmearing_binned_" + var);
256 scaleCorrVariable_ = var;
257 std::cout << "TrackSmearingTool: *** scale correction override active ***\n"
258 << " resolution sigma : omegaSmearing_binned_" << binnedLookupVariable_ << "\n"
259 << " scale correction : pSmearing_binned_" << scaleCorrVariable_
260 << " (p-space, mu_mc/mu_data)" << std::endl;
261}
262
263static void printBinTable(const std::string& varName,
264 const std::vector<double>& edgesT,
265 const std::vector<double>& sigT,
266 const std::vector<double>& edgesB,
267 const std::vector<double>& sigB,
268 const std::vector<double>& muDatT,
269 const std::vector<double>& muMcT,
270 const std::vector<double>& muDatB,
271 const std::vector<double>& muMcB) {
272 int n = static_cast<int>(edgesT.size()) - 1;
273 bool hasSig = !sigT.empty();
274 bool hasMean = !muDatT.empty();
275 std::cout << " binned (" << varName << ", " << n << " bins):\n";
276 std::cout << std::scientific << std::setprecision(3);
277 std::cout << " bin lo hi ";
278 if (hasSig) std::cout << " top_sigma bot_sigma ";
279 if (hasMean) std::cout << " top_mu_dat bot_mu_dat top_mu_mc bot_mu_mc";
280 std::cout << "\n";
281 for (int i = 0; i < n; ++i) {
282 std::cout << " [" << std::setw(2) << i << "] "
283 << std::setw(11) << edgesT[i] << " "
284 << std::setw(11) << edgesT[i+1];
285 if (hasSig)
286 std::cout << " " << std::setw(11) << (i < (int)sigT.size() ? sigT[i] : 0.)
287 << " " << std::setw(11) << (i < (int)sigB.size() ? sigB[i] : 0.);
288 if (hasMean)
289 std::cout << " " << std::setw(11) << (i < (int)muDatT.size() ? muDatT[i] : 0.)
290 << " " << std::setw(11) << (i < (int)muDatB.size() ? muDatB[i] : 0.)
291 << " " << std::setw(11) << (i < (int)muMcT.size() ? muMcT[i] : 0.)
292 << " " << std::setw(11) << (i < (int)muMcB.size() ? muMcB[i] : 0.);
293 std::cout << "\n";
294 }
295}
296
298 const std::string sep(72, '=');
299 std::cout << "\n" << sep << "\n";
300 std::cout << " TrackSmearingTool\n" << sep << "\n";
301 std::cout << " JSON: " << smearingFile_ << "\n";
302 std::cout << " Mode: "
303 << (isData_ ? "Data (mean correction only, no Gaussian smearing)"
304 : "MC (Gaussian smearing applied)") << "\n";
305 std::cout << std::fixed << std::setprecision(4);
306 std::cout << " smearingFactor: " << smearingFactor_ << "\n";
307 std::cout << " relSmearingP: " << (relSmearingP_ ? "relative" : "absolute")
308 << " relSmearingZ0: " << (relSmearingZ0_ ? "relative" : "absolute") << "\n";
309 std::cout << " smearOmega: " << (smearOmega_ ? "true" : "false") << "\n";
310 std::cout << " binnedLookupVar:" << binnedLookupVariable_ << "\n";
311 if (!scaleCorrVariable_.empty()) {
312 std::cout << " *** scaleCorrVariable: pSmearing_binned_" << scaleCorrVariable_
313 << " (p-space means for omega scale correction in data mode) ***\n";
314 } else {
315 std::cout << " scaleCorrVariable: (none — omega-space means from omegaSmearing_binned_"
316 << binnedLookupVariable_ << ")\n";
317 }
318
319 // p smearing
320 std::cout << "\n [p smearing] (" << (relSmearingP_ ? "relative" : "absolute") << ")\n";
321 std::cout << std::scientific << std::setprecision(4);
322 std::cout << " flat: top = " << pSmearingValueTop_
323 << " bot = " << pSmearingValueBot_ << "\n";
324 if (hasMeanCorrP_ && pBinned_.empty()) {
325 std::cout << " mu_data: top = " << pMeanDataTop_ << " bot = " << pMeanDataBot_ << "\n";
326 std::cout << " mu_mc: top = " << pMeanMcTop_ << " bot = " << pMeanMcBot_ << "\n";
327 }
328 if (!pBinned_.empty()) {
329 for (const auto& [var, bp] : pBinned_)
330 printBinTable(var, bp.edgesTop, bp.valTop, bp.edgesBot, bp.valBot,
331 bp.muDatTop, bp.muMcTop, bp.muDatBot, bp.muMcBot);
332 } else {
333 std::cout << " (no binned p smearing loaded)\n";
334 }
335
336 // omega smearing
337 std::cout << "\n [omega smearing] (absolute)\n";
338 std::cout << " flat: top = " << omegaSmearingValueTop_
339 << " bot = " << omegaSmearingValueBot_ << "\n";
340 if (hasMeanCorrOmega_ && omegaBinned_.empty()) {
341 std::cout << " mu_data: top = " << omegaMeanDataTop_ << " bot = " << omegaMeanDataBot_ << "\n";
342 std::cout << " mu_mc: top = " << omegaMeanMcTop_ << " bot = " << omegaMeanMcBot_ << "\n";
343 }
344 if (!omegaBinned_.empty()) {
345 for (const auto& [var, bp] : omegaBinned_)
346 printBinTable(var, bp.edgesTop, bp.valTop, bp.edgesBot, bp.valBot,
347 bp.muDatTop, bp.muMcTop, bp.muDatBot, bp.muMcBot);
348 } else {
349 std::cout << " (no binned omega smearing loaded)\n";
350 }
351
352 // z0 smearing
353 std::cout << "\n [z0 smearing] (" << (relSmearingZ0_ ? "relative" : "absolute") << ")\n";
354 std::cout << " flat: top = " << z0SmearingValueTop_
355 << " bot = " << z0SmearingValueBot_ << "\n";
356 if (hasMeanCorrZ0_ && z0Binned_.empty()) {
357 std::cout << " mu_data: top = " << z0MeanDataTop_ << " bot = " << z0MeanDataBot_ << "\n";
358 std::cout << " mu_mc: top = " << z0MeanMcTop_ << " bot = " << z0MeanMcBot_ << "\n";
359 }
360 if (!z0Binned_.empty()) {
361 for (const auto& [var, bp] : z0Binned_)
362 printBinTable(var, bp.edgesTop, bp.valTop, bp.edgesBot, bp.valBot,
363 bp.muDatTop, bp.muMcTop, bp.muDatBot, bp.muMcBot);
364 } else {
365 std::cout << " (no binned z0 smearing loaded)\n";
366 }
367
368 std::cout << sep << "\n\n";
369}
370
371double TrackSmearingTool::smearTrackP(const double p) {
372
373 double rel_smear = (*normal_)(*generator_);
374 double sp = rel_smear * pSmearingValue_;
375
376 double psmear = 0.;
377
378 if (relSmearingP_)
379 psmear = p + sp*p;
380 else
381 psmear = p + sp;
382
383 if (debug_) {
384 std::cout<<"p: "<<p<<" deltaP="<<sp<<" p'="<<psmear<<std::endl;
385 }
386
387 return psmear;
388
389}
390
392
393 double p = track.getP();
394
395 // If using fixed smearing with separate top/bot values
397 bool isTop = track.getTanLambda() > 0.;
398
399 // --- Data mode: apply mean correction only, no Gaussian smearing ---
400 if (isData_) {
401 if (!applyMeanCorr_) return p;
402 double mu_data = 0., mu_mc = 0.;
403 bool hasMu = false;
404 if (pBinned_.count(binnedLookupVariable_)) {
405 const auto& bp = pBinned_.at(binnedLookupVariable_);
406 if (!bp.muDatTop.empty()) {
407 double lv = getLookupValue(track);
408 mu_data = isTop ? lookupBinnedValue(bp.edgesTop, bp.muDatTop, lv)
409 : lookupBinnedValue(bp.edgesBot, bp.muDatBot, lv);
410 mu_mc = isTop ? lookupBinnedValue(bp.edgesTop, bp.muMcTop, lv)
411 : lookupBinnedValue(bp.edgesBot, bp.muMcBot, lv);
412 hasMu = true;
413 }
414 }
415 if (!hasMu) {
416 if (!hasMeanCorrP_) return p;
417 mu_data = isTop ? pMeanDataTop_ : pMeanDataBot_;
418 mu_mc = isTop ? pMeanMcTop_ : pMeanMcBot_;
419 }
420 double pcorr = relSmearingP_ ? ((mu_data > 0.) ? p * (mu_mc / mu_data) : p)
421 : p + (mu_mc - mu_data);
422 if (debug_)
423 std::cout<<"Data p corr: isTop="<<isTop<<" p="<<p<<" mu_data="<<mu_data<<" mu_mc="<<mu_mc<<" p'="<<pcorr<<std::endl;
424 return pcorr;
425 }
426
427 // --- MC mode: Gaussian smearing only ---
428 double smearingValue;
429 if (pBinned_.count(binnedLookupVariable_)) {
430 const auto& bp = pBinned_.at(binnedLookupVariable_);
431 double lv = getLookupValue(track);
432 smearingValue = isTop ? lookupBinnedValue(bp.edgesTop, bp.valTop, lv)
433 : lookupBinnedValue(bp.edgesBot, bp.valBot, lv);
434 } else {
435 smearingValue = isTop ? pSmearingValueTop_ : pSmearingValueBot_;
436 }
437
438 double rel_smear = (*normal_)(*generator_);
439 double sp = rel_smear * smearingValue;
440
441 double psmear = relSmearingP_ ? p + sp * p : p + sp;
442
443 if (debug_)
444 std::cout<<"Track isTop: "<<isTop<<" p: "<<p<<" deltaP="<<sp<<" p'="<<psmear<<std::endl;
445
446 return psmear;
447 }
448
449 // If using fixed smearing (single value), delegate to the simpler function
450 if (useFixedSmearing_) {
451 return smearTrackP(p);
452 }
453
454 double nhits = track.getTrackerHitCount();
455 bool isTop = track.getTanLambda() > 0. ? true : false;
456 int binN = smearing_histo_top_->FindBin(nhits);
457
458 if (debug_)
459 std::cout<<"Track nhits="<<nhits<<" bin="<<binN<<std::endl;
460
461 if (binN < 1) {
462 if (debug_)
463 std::cout<<"Track nhits="<<nhits<<" bin="<<binN<<" rounding to bin=1"<< std::endl;
464 binN=1;
465 } else if (binN > smearing_histo_top_->GetXaxis()->GetNbins()) {
466 throw std::invalid_argument("Bin not found in smearing histogram");
467 }
468
469 double rel_smear = (*normal_)(*generator_);
470 double sp = 0.;
471
472 if (isTop)
473 sp = rel_smear * smearing_histo_top_->GetBinContent(binN) * smearingFactor_;
474 else
475 sp = rel_smear * smearing_histo_bot_->GetBinContent(binN) * smearingFactor_;
476
477 double psmear = 0.;
478
479 if (relSmearingP_)
480 psmear = p + sp*p;
481 else
482 psmear = p + sp;
483
484
485 if (debug_) {
486 std::cout<<"Track isTop: "<<isTop<<" nHits: "<<nhits<<" p: "<<p<<" deltaP=" << sp<<" p'="<<psmear<<std::endl;
487 }
488
489 return psmear;
490
491}
492
494 // Truth matching only applies to MC — on data there are no MC particles to match against
495 if (!isData_ && requireTruthMatch_ && !hasTruthMatch(trk)) {
496 if (debug_) {
497 std::cout << "TrackSmearingTool: Skipping momentum smearing - no truth match" << std::endl;
498 }
499 return 1.0; // No smearing applied
500 }
501
502 double smeared_magnitude = smearTrackP(trk);
503 // updated momentum by scaling each coordinate by smeared/unsmeared
504 // this takes the direction of the unsmeared momentum and applies
505 // the smeared magnitude
506 std::vector<double> momentum = trk.getMomentum();
507 double unsmeared_magnitude = trk.getP();
508 for (double& coordinate : momentum)
509 coordinate *= (smeared_magnitude/unsmeared_magnitude);
510 trk.setMomentum(momentum);
511 return (smeared_magnitude/unsmeared_magnitude);
512}
513
514void TrackSmearingTool::updateVertexWithSmearP(Vertex* vtx, double p1_smear_factor, double p2_smear_factor) {
515 TVector3 p1_corr, p2_corr;
516
517 if (debug_) {
518 double p1_px = vtx->getP1X(), p1_py = vtx->getP1Y(), p1_pz = vtx->getP1Z();
519 double p2_px = vtx->getP2X(), p2_py = vtx->getP2Y(), p2_pz = vtx->getP2Z();
520 double p1_p = sqrt(p1_px*p1_px + p1_py*p1_py + p1_pz*p1_pz);
521 double p2_p = sqrt(p2_px*p2_px + p2_py*p2_py + p2_pz*p2_pz);
522 double psum_px = p1_px + p2_px, psum_py = p1_py + p2_py, psum_pz = p1_pz + p2_pz;
523 double psum = sqrt(psum_px*psum_px + psum_py*psum_py + psum_pz*psum_pz);
524 std::cout << "Before smearing:" << std::endl;
525 std::cout << " P1: px=" << p1_px << " py=" << p1_py << " pz=" << p1_pz << " |p|=" << p1_p << std::endl;
526 std::cout << " P2: px=" << p2_px << " py=" << p2_py << " pz=" << p2_pz << " |p|=" << p2_p << std::endl;
527 std::cout << " Psum: px=" << psum_px << " py=" << psum_py << " pz=" << psum_pz << " |psum|=" << psum << std::endl;
528 }
529
530
531 // We don't know whether p1 or p2 is the electron
532 // TODO: Introduce matching between the electron Track (not in this function), and p1/p2 to determine which is which
533 // This is most easily done by comparing the py values of p1/2_corr and the track, since they should be in different regions of the detector (top/bottom)
534 p1_corr.SetX(vtx->getP1X()*p1_smear_factor);
535 p1_corr.SetY(vtx->getP1Y()*p1_smear_factor);
536 p1_corr.SetZ(vtx->getP1Z()*p1_smear_factor);
537
538 p2_corr.SetX(vtx->getP2X()*p2_smear_factor);
539 p2_corr.SetY(vtx->getP2Y()*p2_smear_factor);
540 p2_corr.SetZ(vtx->getP2Z()*p2_smear_factor);
541
542 if (debug_) {
543 double p1_p_corr = p1_corr.Mag();
544 double p2_p_corr = p2_corr.Mag();
545 TVector3 psum_corr = p1_corr + p2_corr;
546 std::cout << "After smearing (p1_factor=" << p1_smear_factor << ", p2_factor=" << p2_smear_factor << "):" << std::endl;
547 std::cout << " P1: px=" << p1_corr.X() << " py=" << p1_corr.Y() << " pz=" << p1_corr.Z() << " |p|=" << p1_p_corr << std::endl;
548 std::cout << " P2: px=" << p2_corr.X() << " py=" << p2_corr.Y() << " pz=" << p2_corr.Z() << " |p|=" << p2_p_corr << std::endl;
549 std::cout << " Psum: px=" << psum_corr.X() << " py=" << psum_corr.Y() << " pz=" << psum_corr.Z() << " |psum|=" << psum_corr.Mag() << std::endl;
550 }
551
552 // smear invariant mass by sqrt(p1_smear*p2_smear)
553 double m_corr = vtx->getInvMass() * sqrt(p1_smear_factor * p2_smear_factor);
554 vtx->setVtxParameters(p1_corr, p2_corr, m_corr);
555}
556
557double TrackSmearingTool::smearTrackZ0(const double z0) {
558
559 double rel_smear = (*normal_)(*generator_);
560 double sz0 = rel_smear * z0SmearingValue_;
561
562 double z0smear = 0.;
563
564 if (relSmearingZ0_)
565 z0smear = z0 + sz0*z0;
566 else
567 z0smear = z0 + sz0;
568
569 if (debug_) {
570 std::cout<<"z0: "<<z0<<" deltaZ0="<<sz0<<" z0'="<<z0smear<<std::endl;
571 }
572
573 return z0smear;
574
575}
576
578
579 double z0 = track.getZ0();
580
581 // If using fixed smearing with separate top/bot values
583 bool isTop = track.getTanLambda() > 0.;
584
585 // --- Data mode: apply mean correction only, no Gaussian smearing ---
586 if (isData_) {
587 if (!applyMeanCorr_) return z0;
588 double mu_data = 0., mu_mc = 0.;
589 bool hasMu = false;
590 if (z0Binned_.count(binnedLookupVariable_)) {
591 const auto& bp = z0Binned_.at(binnedLookupVariable_);
592 if (!bp.muDatTop.empty()) {
593 double lv = getLookupValue(track);
594 mu_data = isTop ? lookupBinnedValue(bp.edgesTop, bp.muDatTop, lv)
595 : lookupBinnedValue(bp.edgesBot, bp.muDatBot, lv);
596 mu_mc = isTop ? lookupBinnedValue(bp.edgesTop, bp.muMcTop, lv)
597 : lookupBinnedValue(bp.edgesBot, bp.muMcBot, lv);
598 hasMu = true;
599 }
600 }
601 if (!hasMu) {
602 if (!hasMeanCorrZ0_) return z0;
603 mu_data = isTop ? z0MeanDataTop_ : z0MeanDataBot_;
604 mu_mc = isTop ? z0MeanMcTop_ : z0MeanMcBot_;
605 }
606 double z0corr = z0 + (mu_mc - mu_data);
607 if (debug_) {
608 std::cout << "z0 smear (data): isTop=" << isTop
609 << " source=" << (hasMu ? "binned[" + binnedLookupVariable_ + "]" : "flat")
610 << " mu_data=" << mu_data << " mu_mc=" << mu_mc
611 << " z0=" << z0 << " shift=" << (mu_mc - mu_data) << " z0'=" << z0corr << std::endl;
612 }
613 return z0corr;
614 }
615
616 // --- MC mode: Gaussian smearing only ---
617 double smearingValue;
618 bool usedBinned = false;
619 double lookupVal = 0.;
620 if (z0Binned_.count(binnedLookupVariable_) &&
621 !z0Binned_.at(binnedLookupVariable_).valTop.empty()) {
622 const auto& bp = z0Binned_.at(binnedLookupVariable_);
623 lookupVal = getLookupValue(track);
624 smearingValue = isTop ? lookupBinnedValue(bp.edgesTop, bp.valTop, lookupVal)
625 : lookupBinnedValue(bp.edgesBot, bp.valBot, lookupVal);
626 usedBinned = true;
627 } else {
628 smearingValue = isTop ? z0SmearingValueTop_ : z0SmearingValueBot_;
629 }
630
631 double rel_smear = (*normal_)(*generator_);
632 double sz0 = rel_smear * smearingValue;
633
634 double z0smear = relSmearingZ0_ ? z0 + sz0 * z0 : z0 + sz0;
635
636 if (debug_) {
637 std::cout << "z0 smear (MC): isTop=" << isTop
638 << " source=" << (usedBinned ? "binned[" + binnedLookupVariable_ + "=" + std::to_string(lookupVal) + "]" : "flat")
639 << " sigma=" << smearingValue
640 << " z0=" << z0 << " deltaZ0=" << sz0 << " z0'=" << z0smear << std::endl;
641 }
642
643 return z0smear;
644 }
645
646 return smearTrackZ0(z0);
647
648}
649
651 // Truth matching only applies to MC — on data there are no MC particles to match against
652 if (!isData_ && requireTruthMatch_ && !hasTruthMatch(trk)) {
653 if (debug_) {
654 std::cout << "TrackSmearingTool: Skipping z0 smearing - no truth match" << std::endl;
655 }
656 return;
657 }
658
659 double smeared_z0 = smearTrackZ0(trk);
660 trk.setZ0(smeared_z0);
661}
662
663double TrackSmearingTool::updateWithSmearOmega(Track& trk, double /*bfield*/) {
664 // Truth matching only applies to MC — on data there are no MC particles to match against
665 if (!isData_ && requireTruthMatch_ && !hasTruthMatch(trk)) {
666 if (debug_) {
667 std::cout << "TrackSmearingTool: Skipping omega smearing - no truth match" << std::endl;
668 }
669 return 1.0; // No smearing applied
670 }
671
672 // Get current omega (curvature)
673 double omega = trk.getOmega();
674
675 // Determine smearing value based on top/bottom (with optional binned lookup)
676 bool isTop = trk.getTanLambda() > 0.;
677 double smearingValue;
679 const auto& bp = omegaBinned_.at(binnedLookupVariable_);
680 double lv = getLookupValue(trk);
681 smearingValue = isTop ? lookupBinnedValue(bp.edgesTop, bp.valTop, lv)
682 : lookupBinnedValue(bp.edgesBot, bp.valBot, lv);
683 } else {
684 smearingValue = isTop ? omegaSmearingValueTop_ : omegaSmearingValueBot_;
685 }
686
687 // --- Data mode: apply mean correction only, no Gaussian smearing ---
688 if (isData_) {
689 double lv = getLookupValue(trk);
690
691 // --- Path A: p-space scale correction from pSmearing_binned_{scaleCorrVariable_} ---
692 if (!scaleCorrVariable_.empty() && pBinned_.count(scaleCorrVariable_)) {
693 const auto& bp = pBinned_.at(scaleCorrVariable_);
694 if (!bp.muDatTop.empty()) {
695 double mu_data_p = isTop ? lookupBinnedValue(bp.edgesTop, bp.muDatTop, lv)
696 : lookupBinnedValue(bp.edgesBot, bp.muDatBot, lv);
697 double mu_mc_p = isTop ? lookupBinnedValue(bp.edgesTop, bp.muMcTop, lv)
698 : lookupBinnedValue(bp.edgesBot, bp.muMcBot, lv);
699 if (mu_data_p > 0. && mu_mc_p > 0.) {
700 // p_corr = p * (mu_mc_p / mu_data_p) [p-space scale]
701 // omega ~ 1/p => omega_corr = omega * (mu_data_p / mu_mc_p)
702 double p_scale = mu_mc_p / mu_data_p;
703 double omega_corr = omega / p_scale;
704 double p_before = trk.getP();
705 std::vector<double> momentum = trk.getMomentum();
706 for (double& coord : momentum) coord *= p_scale;
707 trk.setMomentum(momentum);
708 trk.setOmega(omega_corr);
709 double p_after = trk.getP();
710 if (debug_)
711 std::cout << "[TrackSmearingTool] Data omega scale (PATH A — p-space): "
712 << "paramVar=pSmearing_binned_" << scaleCorrVariable_
713 << " isTop=" << isTop << " lv(tanL)=" << lv
714 << " mu_data_p=" << mu_data_p << " mu_mc_p=" << mu_mc_p
715 << " p_scale=" << p_scale
716 << " |p|: " << p_before << " -> " << p_after
717 << " omega: " << omega << " -> " << omega_corr << std::endl;
718 return std::fabs(p_scale);
719 }
720 // Bin has zero means — no correction available for this track
721 if (debug_)
722 std::cout << "[TrackSmearingTool] Data omega scale (PATH A): "
723 << "pSmearing_binned_" << scaleCorrVariable_
724 << " has zero means at lv=" << lv << " isTop=" << isTop
725 << " — skipping scale correction for this track." << std::endl;
726 return 1.0;
727 }
728 }
729
730 // --- Path B (default): omega-space mean correction from omegaSmearing_binned_{binnedLookupVariable_} ---
731 if (!applyMeanCorr_) {
732 if (debug_)
733 std::cout << "[TrackSmearingTool] Data omega scale (PATH B — omega-space): "
734 << "applyMeanCorr=false — no correction applied." << std::endl;
735 return 1.0;
736 }
737 double mu_data = 0., mu_mc = 0.;
738 bool hasMu = false;
740 const auto& bp = omegaBinned_.at(binnedLookupVariable_);
741 if (!bp.muDatTop.empty()) {
742 mu_data = isTop ? lookupBinnedValue(bp.edgesTop, bp.muDatTop, lv)
743 : lookupBinnedValue(bp.edgesBot, bp.muDatBot, lv);
744 mu_mc = isTop ? lookupBinnedValue(bp.edgesTop, bp.muMcTop, lv)
745 : lookupBinnedValue(bp.edgesBot, bp.muMcBot, lv);
746 hasMu = true;
747 }
748 }
749 if (!hasMu) {
750 if (!hasMeanCorrOmega_) return 1.0;
751 mu_data = isTop ? omegaMeanDataTop_ : omegaMeanDataBot_;
752 mu_mc = isTop ? omegaMeanMcTop_ : omegaMeanMcBot_;
753 }
754 double omega_corr = omega + (mu_mc - mu_data);
755 double scale = (omega_corr != 0.) ? omega / omega_corr : 1.0;
756 std::vector<double> momentum = trk.getMomentum();
757 for (double& coord : momentum) coord *= scale;
758 trk.setMomentum(momentum);
759 trk.setOmega(omega_corr);
760 if (debug_)
761 std::cout << "[TrackSmearingTool] Data omega scale (PATH B — omega-space): "
762 << "paramVar=omegaSmearing_binned_" << binnedLookupVariable_
763 << " isTop=" << isTop << " lv=" << lv
764 << " mu_data=" << mu_data << " mu_mc=" << mu_mc
765 << " omega=" << omega << " omega'=" << omega_corr << std::endl;
766 return std::fabs(scale);
767 }
768
769 // --- MC mode: Gaussian smearing only ---
770 // Generate Gaussian random and apply absolute smearing to omega
771 double smear = (*normal_)(*generator_);
772 double omega_smeared = omega + smear * smearingValue;
773
774 // Scale momentum by omega / omega_smeared (since p ~ 1/|omega|).
775 // This avoids reconstructing from helix parameters with a B-field value
776 // that may not match the one used when the track was originally created
777 // (bLocal from LCIO is not persisted into the ROOT ntuples).
778 double scale = omega / omega_smeared;
779 std::vector<double> momentum = trk.getMomentum();
780 for (double& coord : momentum)
781 coord *= scale;
782 trk.setMomentum(momentum);
783 trk.setOmega(omega_smeared);
784
785 if (debug_) {
786 double original_p = trk.getP() / fabs(scale);
787 std::cout << "TrackSmearingTool::updateWithSmearOmega:" << std::endl;
788 std::cout << " isTop: " << isTop << " smearingValue: " << smearingValue << std::endl;
789 std::cout << " omega: " << omega << " smear: " << smear << " omega': " << omega_smeared << std::endl;
790 std::cout << " original_p: " << original_p << " smeared_p: " << trk.getP() << std::endl;
791 }
792
793 return fabs(scale);
794}
795
796void TrackSmearingTool::setMCParticles(const std::vector<MCParticle*>* mc_particles) {
797 mcParticles_ = mc_particles;
798}
799
803
nlohmann::json json
static void printBinTable(const std::string &varName, const std::vector< double > &edgesT, const std::vector< double > &sigT, const std::vector< double > &edgesB, const std::vector< double > &sigB, const std::vector< double > &muDatT, const std::vector< double > &muMcT, const std::vector< double > &muDatB, const std::vector< double > &muMcB)
static bool endsWith(const std::string &str, const std::string &suffix)
double smearTrackP(const Track &trk)
double smearTrackZ0(const Track &trk)
bool hasTruthMatch(Track &trk)
double lookupBinnedValue(const std::vector< double > &edges, const std::vector< double > &values, double x) const
TrackSmearingTool(const std::string &smearingfile, const bool relSmearingP=true, const bool relSmearingZ0=false, const int seed=42, const std::string &tracks="KalmanFullTracks", const double smearingFactor=1.0)
std::map< std::string, BinnedParam > z0Binned_
void updateWithSmearZ0(Track &trk)
void updateVertexWithSmearP(Vertex *vtx, double p1_smear_factor, double p2_smear_factor)
std::string scaleCorrVariable_
int getTruthPDG(Track &trk)
void setForcedVariable(const std::string &var)
std::shared_ptr< std::default_random_engine > generator_
std::shared_ptr< TFile > smearingfile_
void setMCParticles(const std::vector< MCParticle * > *mc_particles)
std::shared_ptr< std::normal_distribution< double > > normal_
std::string binnedLookupVariable_
const std::vector< MCParticle * > * mcParticles_
std::map< std::string, BinnedParam > pBinned_
double updateWithSmearOmega(Track &trk, double bfield=0.52)
double updateWithSmearP(Track &trk)
double getLookupValue(const Track &track) const
void setScaleCorrVariable(const std::string &var)
std::map< std::string, BinnedParam > omegaBinned_
Definition Track.h:32
double getOmega() const
Definition Track.h:90
void setOmega(const double omega)
Definition Track.h:91
double getTanLambda() const
Definition Track.h:92
std::vector< double > getMomentum()
Definition Track.h:287
void setZ0(const double z0)
Definition Track.h:94
double getP() const
Definition Track.h:293
void setMomentum(double bfield=0.52)
Definition Track.cxx:63
bool hasTruthMatch(Track &trk, const std::vector< MCParticle * > *mcParticles, bool debug=false)
Check if a track has a truth-matched electron/positron.
int getTruthPDG(Track &trk, const std::vector< MCParticle * > *mcParticles, bool debug=false)
Get the PDG code of the truth particle best matching this track.