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
TrackCorrector.cxx
Go to the documentation of this file.
1#include "TrackCorrector.h"
2
3#include <cmath>
4#include <cstdlib>
5#include <fstream>
6#include <iostream>
7#include <stdexcept>
8
9#include "TVector3.h"
10
11using json = nlohmann::json;
12
13namespace {
14json readJson(const std::string& file) {
15 std::ifstream ifs(file);
16 if (!ifs.good()) throw std::runtime_error("[TrackCorrector] cannot open " + file);
17 json cfg;
18 ifs >> cfg;
19 return cfg;
20}
21} // namespace
22
23std::string TrackCorrector::resolvePath(const std::string& path) const {
24 if (path.empty() || path.front() == '/') return path;
25 const char* base = std::getenv("HPSTR_BASE");
26 if (!base) throw std::runtime_error("[TrackCorrector] relative path " + path + " but HPSTR_BASE is not set");
27 return std::string(base) + "/" + path;
28}
29
30std::string TrackCorrector::dataOrMc(const json& block) const {
31 const char* key = opts_.isData ? "data" : "mc";
32 if (!block.is_object() || !block.contains(key)) return "";
33 return resolvePath(block[key].get<std::string>());
34}
35
36TrackCorrector::TrackCorrector(const std::string& cfgFile, const Options& opts)
37 : cfgFile_(resolvePath(cfgFile)), opts_(opts) {
38 json cfg = readJson(cfgFile_);
39
40 // Constant track offsets. Track::applyCorrection silently ignores unknown names,
41 // so check the spelling here.
42 std::string offsets = resolvePath(cfg.value("trackOffsets", ""));
43 if (!offsets.empty()) {
44 for (const auto& [name, corr] : readJson(offsets).items()) {
45 if (name != "track_z0" && name != "track_time")
46 throw std::runtime_error("[TrackCorrector] unrecognized track offset '" + name + "' in " + offsets);
47 trackOffsets_[name] = corr.get<double>();
48 }
49 }
50
51 if (cfg.contains("z0Offset")) {
52 z0OffsetFile_ = dataOrMc(cfg["z0Offset"]);
53 if (!z0OffsetFile_.empty()) {
54 z0OffsetFits_ = readJson(z0OffsetFile_);
55 if (z0OffsetFits_.empty()) throw std::runtime_error("[TrackCorrector] no runs in " + z0OffsetFile_);
56 }
57 }
58
59 if (cfg.contains("z0Calib")) {
60 z0CalibFile_ = dataOrMc(cfg["z0Calib"]);
61 if (!z0CalibFile_.empty()) {
62 z0Calib_ = std::make_shared<TrackBiasingTool>("", "KalmanFullTracks");
63 z0Calib_->loadZ0Calibration(z0CalibFile_);
64 z0Calib_->setDebug(opts_.debug);
65 }
66 }
67
68 if (cfg.contains("momentumScale") && opts_.isData) {
69 const json& ms = cfg["momentumScale"];
70 std::string runScale = resolvePath(ms.value("runScale", ""));
71 std::string meanCorr = resolvePath(ms.value("meanCorr", ""));
72 if (!runScale.empty() || !meanCorr.empty())
74 std::make_shared<RunScaleCorrectionTool>(runScale, meanCorr, ms.value("meanCorrVariable", ""));
75 }
76
77 if (cfg.contains("smearing")) {
78 const json& sm = cfg["smearing"];
79 std::string smearCfg = resolvePath(sm.value("cfg", ""));
80 if (!smearCfg.empty()) {
81 // relSmearingP=true (relative), relSmearingZ0=false (absolute); a JSON smearing
82 // file overrides these with its own values.
83 smearing_ = std::make_shared<TrackSmearingTool>(smearCfg, true, false, opts_.seed,
84 sm.value("trackCollection", "KalmanFullTracks"),
85 sm.value("smearingFactor", 1.0));
86 smearing_->setForcedVariable(sm.value("variable", ""));
87 bool truth = opts_.requireTruthMatch >= 0 ? opts_.requireTruthMatch != 0
88 : sm.value("requireTruthMatch", false);
89 smearing_->setRequireTruthMatch(truth);
90 smearing_->setDebug(opts_.debug);
91 smearing_->setIsData(opts_.isData);
92 // Data scale corrections come only from momentumScale, never from the smearing tool.
93 smearing_->setApplyMeanCorr(false);
94 smearOmega_ = sm.value("smearOmega", false);
95 smearZ0_ = sm.value("smearZ0", true);
96 }
97 }
98 applySmearing_ = smearing_ && !opts_.isData && opts_.doSmearing;
99
100 // Vertex momenta follow the tracks whenever a momentum step can run. With a smearing
101 // file on data the vertex is still refreshed (ratios of 1), as the preselection always did.
102 updatesVertex_ = (smearing_ && (opts_.isData || opts_.doSmearing)) || momentumScale_;
103}
104
105void TrackCorrector::beginEvent(int run, const std::vector<MCParticle*>* mcParticles) {
106 run_ = run;
107 if (z0Calib_) z0Calib_->setRun(run);
108 if (smearing_ && mcParticles) smearing_->setMCParticles(mcParticles);
109
110 if (!z0OffsetFile_.empty() && run != z0OffsetRun_) {
111 // Closest run at or below this one; runs before every entry use the earliest one.
112 int closest = -1;
113 for (const auto& entry : z0OffsetFits_.items()) {
114 int check = std::stoi(entry.key());
115 if (check > run) {
116 if (closest < 0) closest = check;
117 break;
118 }
119 closest = check;
120 }
121 const json& fit = z0OffsetFits_[std::to_string(closest)];
122 eleZ0Offset_ = fit["elez0_mean"].get<double>();
123 posZ0Offset_ = fit["posz0_mean"].get<double>();
124 z0OffsetRun_ = run;
125 }
126}
127
128std::vector<TrackCorrector::Result> TrackCorrector::correct(const std::vector<Track*>& tracks,
129 const std::vector<int>& charges) {
130 std::vector<Result> results(tracks.size());
131 if (!charges.empty() && charges.size() != tracks.size())
132 throw std::runtime_error("[TrackCorrector] charges and tracks differ in size");
133
134 for (Track* trk : tracks)
135 for (const auto& [name, corr] : trackOffsets_) trk->applyCorrection(name, corr);
136
137 if (!z0OffsetFile_.empty()) {
138 for (std::size_t i = 0; i < tracks.size(); ++i) {
139 int charge = charges.empty() ? tracks[i]->getCharge() : charges[i];
140 tracks[i]->applyCorrection("z0", charge < 0 ? eleZ0Offset_ : posZ0Offset_);
141 }
142 }
143
144 if (z0Calib_)
145 for (Track* trk : tracks) z0Calib_->updateWithCalibrateZ0(*trk);
146
147 if (momentumScale_)
148 for (std::size_t i = 0; i < tracks.size(); ++i) results[i].pScale = momentumScale_->apply(*tracks[i], run_);
149
150 if (applySmearing_) {
151 if (smearZ0_)
152 for (Track* trk : tracks) smearing_->updateWithSmearZ0(*trk);
153 for (std::size_t i = 0; i < tracks.size(); ++i)
154 results[i].pSmear = smearOmega_ ? smearing_->updateWithSmearOmega(*tracks[i])
155 : smearing_->updateWithSmearP(*tracks[i]);
156 }
157 return results;
158}
159
160void TrackCorrector::correctVertex(Vertex* vtx, double r1, double r2) {
161 TVector3 p1(vtx->getP1X() * r1, vtx->getP1Y() * r1, vtx->getP1Z() * r1);
162 TVector3 p2(vtx->getP2X() * r2, vtx->getP2Y() * r2, vtx->getP2Z() * r2);
163 vtx->setVtxParameters(p1, p2, vtx->getInvMass() * std::sqrt(r1 * r2));
164}
165
167 std::cout << "[TrackCorrector] " << cfgFile_ << " (" << (opts_.isData ? "data" : "MC") << ")" << std::endl;
168 std::cout << " trackOffsets : " << (trackOffsets_.empty() ? "off" : "") ;
169 for (const auto& [name, corr] : trackOffsets_) std::cout << name << "=" << corr << " ";
170 std::cout << std::endl;
171 std::cout << " z0Offset : " << (z0OffsetFile_.empty() ? "off" : z0OffsetFile_) << std::endl;
172 std::cout << " z0Calib : " << (z0CalibFile_.empty() ? "off" : z0CalibFile_) << std::endl;
173 std::cout << " momentumScale: " << (momentumScale_ ? "on (data)" : "off") << std::endl;
174 if (momentumScale_) momentumScale_->printConfig();
175 std::cout << " smearing : "
176 << (!smearing_ ? "off" : applySmearing_ ? (smearOmega_ ? "on (omega" : "on (p") : "configured, not applied (")
177 << (smearing_ ? std::string(smearZ0_ ? ", z0" : ", no z0") + ")" : "") << std::endl;
178 if (smearing_) smearing_->printConfig();
179}
nlohmann::json json
void beginEvent(int run, const std::vector< MCParticle * > *mcParticles=nullptr)
std::string z0OffsetFile_
std::vector< Result > correct(const std::vector< Track * > &tracks, const std::vector< int > &charges={})
std::shared_ptr< TrackSmearingTool > smearing_
std::shared_ptr< RunScaleCorrectionTool > momentumScale_
std::string dataOrMc(const nlohmann::json &block) const
std::string z0CalibFile_
std::string resolvePath(const std::string &path) const
nlohmann::json z0OffsetFits_
std::string cfgFile_
void printConfig() const
bool applySmearing_
smearing configured, MC, and Options::doSmearing
std::map< std::string, double > trackOffsets_
std::shared_ptr< TrackBiasingTool > z0Calib_
static void correctVertex(Vertex *vtx, double r1, double r2)
TrackCorrector(const std::string &cfgFile, const Options &opts)
Definition Track.h:32