LDMX Software
GSFProcessor.cxx
1#include "Tracking/Reco/GSFProcessor.h"
2
3#include <algorithm>
4
5#include "Acts/EventData/SourceLink.hpp"
6#include "Tracking/Event/Track.h"
7
8namespace tracking {
9namespace reco {
10
11GSFProcessor::GSFProcessor(const std::string& name, framework::Process& process)
12 : TrackingGeometryUser(name, process) {}
13
15 beam_origin_surface_ = tracking::sim::utils::unboundSurface(-700);
16 target_surface_ = tracking::sim::utils::unboundSurface(0.);
17 ecal_surface_ = tracking::sim::utils::unboundSurface(240.5);
18
19 // Setup a interpolated bfield map
20 if (field_map_.empty())
21 loadBField();
22 else
24 const auto map =
25 std::static_pointer_cast<InterpolatedMagneticField3>(bField());
26
27 auto acts_logging_level = Acts::Logging::FATAL;
28
29 if (debug_) acts_logging_level = Acts::Logging::VERBOSE;
30
31 // Setup the GSF Fitter
32
33 // Stepper
34 // Acts::MixtureReductionMethod finalReductionMethod;
35 // const auto multi_stepper = Acts::MultiEigenStepperLoop{map};
36
37 // Acts::ComponentMergeMethod reductionMethod =
38 // Acts::ComponentMergeMethod::eMaxWeight;
39 // Acts::MultiEigenStepperLoop multi_stepper(
40 // map, reductionMethod,
41 // Acts::getDefaultLogger("GSF_STEP", acts_loggingLevel));
42
43 Acts::MultiEigenStepperLoop multi_stepper(map);
44 // Detailed Stepper
45
46 // Acts::MultiEigenStepperLoop multi_stepper(map, finalReductionMethod);
47
48 // Navigator
49 Acts::Navigator::Config nav_cfg{geometry().getTG()};
50 nav_cfg.resolveMaterial = true;
51 nav_cfg.resolvePassive = false;
52 nav_cfg.resolveSensitive = true;
53 const Acts::Navigator navigator(nav_cfg);
54
55 auto gsf_propagator =
56 GsfPropagator(std::move(multi_stepper), std::move(navigator),
57 Acts::getDefaultLogger("GSF_PROP", acts_logging_level));
58
59 BetheHeitlerApprox bethe_heitler = Acts::makeDefaultBetheHeitlerApprox();
60
61 gsf_ = std::make_unique<std::decay_t<decltype(*gsf_)>>(
62 std::move(gsf_propagator), std::move(bethe_heitler),
63 Acts::getDefaultLogger("GSF", acts_logging_level));
64
65 const auto stepper = Acts::EigenStepper<>{map};
66 propagator_ = std::make_unique<Propagator>(
67 stepper, navigator,
68 Acts::getDefaultLogger("GSF_EXTRAP", acts_logging_level));
69
70 trk_extrap_ = std::make_shared<std::decay_t<decltype(*trk_extrap_)>>(
71 *propagator_, geometryContext(), magneticFieldContext());
72}
73
76 parameters.get<std::string>("out_trk_collection", "GSFTracks");
77
79 parameters.get<std::string>("track_collection", "TaggerTracks");
81 parameters.get<std::string>("meas_collection", "DigiTaggerSimHits");
82
83 track_passname_ = parameters.get<std::string>("track_passname");
84 meas_passname_ = parameters.get<std::string>("meas_passname");
86 parameters.get<std::string>("track_collection_event_passname");
88 parameters.get<std::string>("meas_collection_event_passname");
89
90 max_components_ = parameters.get<int>("max_components", 4);
91 abort_on_error_ = parameters.get<bool>("abort_on_error", false);
93 parameters.get<bool>("disable_all_material_handling", false);
94 weight_cutoff_ = parameters.get<double>("weight_cutoff_", 1.0e-4);
95
96 propagator_max_steps_ = parameters.get<int>("propagator_max_steps", 10000);
97 propagator_step_size_ = parameters.get<double>("propagator_step_size", 200.);
98 field_map_ = parameters.get<std::string>("field_map");
99 use_perigee_ = parameters.get<bool>("usePerigee", false);
100
101 debug_ = parameters.get<bool>("debug", false);
102 tagger_tracking_ = parameters.get<bool>("tagger_tracking", true);
103
104 // final_reduction_method_ =
105 // parameters.get<double>("finalReductionMethod",);
106} // end of configure()
107
109 // General Setup
110
111 auto tg{geometry()};
112
113 // Retrieve the tracks
115 return;
116 const auto& tracks =
117 event.getCollection<ldmx::Track>(track_collection_, track_passname_);
118
119 // Retrieve the measurements
121 const auto& measurements =
123
124 tracking::sim::LdmxMeasurementCalibrator calibrator{measurements};
125
126 // GSF Setup
127 Acts::GainMatrixUpdater updater;
128 Acts::GsfExtensions<Acts::VectorMultiTrajectory> gsf_extensions;
129 gsf_extensions.updater.connect<
130 &Acts::GainMatrixUpdater::operator()<Acts::VectorMultiTrajectory>>(
131 &updater);
132 gsf_extensions.calibrator
134 Acts::VectorMultiTrajectory>>(&calibrator);
135
136 // Surface Accessor
137 struct SurfaceAccessor {
138 const Acts::TrackingGeometry* tracking_geometry_;
139
140 const Acts::Surface* operator()(const Acts::SourceLink& sourceLink) const {
141 const auto& index_source_link =
142 sourceLink.get<acts_examples::IndexSourceLink>();
143 return tracking_geometry_->findSurface(index_source_link.geometryId());
144 }
145 };
146
147 SurfaceAccessor m_sl_surface_accessor{tg.getTG().get()};
148 // m_slSurfaceAccessor.trackingGeometry = tg.getTG();
149 gsf_extensions.surfaceAccessor.connect<&SurfaceAccessor::operator()>(
150 &m_sl_surface_accessor);
151 gsf_extensions.mixtureReducer.connect<&Acts::reduceMixtureLargestWeights>();
152
153 // Propagator Options
154
155 // Move this at the start of the producer
156 Acts::PropagatorOptions<Acts::StepperPlainOptions,
157 Acts::NavigatorPlainOptions, ActionList, AbortList>
158 propagator_options(geometryContext(), magneticFieldContext());
159
160 propagator_options.pathLimit = std::numeric_limits<double>::max();
161
162 // Activate loop protection at some pt value
163 propagator_options.loopProtection = false;
164 //(startParameters.transverseMomentum() < cfg.ptLoopers);
165
166 // Switch the material interaction on/off & eventually into logging mode
167 auto& m_interactor =
168 propagator_options.actionList.get<Acts::MaterialInteractor>();
169 m_interactor.multipleScattering = true;
170 m_interactor.energyLoss = true;
171 m_interactor.recordInteractions = false;
172
173 // The logger can be switched to sterile, e.g. for timing logging
174 auto& s_logger =
175 propagator_options.actionList.get<Acts::detail::SteppingLogger>();
176 s_logger.sterile = true;
177 // Set a maximum step size
178 propagator_options.stepping.maxStepSize =
179 propagator_step_size_ * Acts::UnitConstants::mm;
180 propagator_options.maxSteps = propagator_max_steps_;
181
182 // Electron hypothesis
183 // propagator_options.mass = 0.511 * Acts::UnitConstants::MeV;
184
185 // GSF options will be configured per-track
186 std::shared_ptr<const Acts::Surface> gsf_ref_surface;
187 Acts::GsfOptions<Acts::VectorMultiTrajectory> gsf_options{
188 geometryContext(), magneticFieldContext(), calibrationContext()};
189 gsf_options.extensions = gsf_extensions;
190 gsf_options.propagatorPlainOptions = propagator_options;
191 gsf_options.maxComponents = max_components_;
192 gsf_options.weightCutoff = weight_cutoff_;
193 gsf_options.abortOnError = abort_on_error_;
194 gsf_options.disableAllMaterialHandling = disable_all_material_handling_;
195
196 // Output track container
197 std::vector<ldmx::Track> out_tracks;
198
199 Acts::VectorTrackContainer vtc;
200 Acts::VectorMultiTrajectory mtj;
201 Acts::TrackContainer tc{vtc, mtj};
202
203 // Loop on tracks
204 unsigned int itrk = 0;
205 ldmx_log(debug) << "Starting GSF processing of " << tracks.size()
206 << " tracks";
207
208 for (auto& track : tracks) {
209 ldmx_log(debug) << "Processing track " << itrk << " with "
210 << track.getMeasurementsIdxs().size() << " measurements";
211 // Retrieve measurements on track
212 std::vector<ldmx::Measurement> meas_on_track;
213
214 // std::vector<ActsExamples::IndexSourceLink> fit_trackSourceLinks;
215 std::vector<Acts::SourceLink> fit_track_source_links;
216
217 for (auto imeas : track.getMeasurementsIdxs()) {
218 auto meas = measurements.at(imeas);
219 meas_on_track.push_back(meas);
220
221 // Retrieve the surface
222
223 const Acts::Surface* hit_surface =
224 tg.geo::TrackingGeometry::getSurface(meas.getLayerID());
225
226 // Store the index_ source link
227 acts_examples::IndexSourceLink idx_sl(hit_surface->geometryId(), imeas);
228 fit_track_source_links.push_back(Acts::SourceLink(idx_sl));
229 }
230
231 // Reverse the order of the vectors
232 std::reverse(meas_on_track.begin(), meas_on_track.end());
233 std::reverse(fit_track_source_links.begin(), fit_track_source_links.end());
234
235 for (auto m : meas_on_track) {
236 ldmx_log(trace) << " Measurement:\n" << m << "\n";
237 }
238
239 ldmx_log(debug) << " Track bound track parameters preparation:";
240
241 // Reconstruct BoundTrackParameters at perigee (target) from stored params.
242 // perigee_ is stored in LDMX frame; rotate to ACTS frame for surface
243 // creation.
244 Acts::Vector3 perigee_acts = tracking::sim::utils::ldmx2Acts(Acts::Vector3(
245 track.getPerigeeX(), track.getPerigeeY(), track.getPerigeeZ()));
246 std::shared_ptr<Acts::PerigeeSurface> perigee =
247 Acts::Surface::makeShared<Acts::PerigeeSurface>(perigee_acts);
248
249 Acts::BoundTrackParameters trk_btp =
250 tracking::sim::utils::boundTrackParameters(track, perigee);
251
252 // GSF starting parameters: for tagger, extrapolate back to beam origin;
253 // for recoil, use target parameters directly.
254 Acts::BoundTrackParameters trk_btp_fit_start = trk_btp;
255
256 if (tagger_tracking_) {
257 auto opt_beam_origin =
258 trk_extrap_->extrapolate(trk_btp, beam_origin_surface_);
259 if (!opt_beam_origin) {
260 ldmx_log(warn) << "Failed extrapolating to beam origin for GSF start. "
261 "Skipping..";
262 continue;
263 }
264 trk_btp_fit_start = *opt_beam_origin;
265 }
266
267 ldmx_log(debug) << " Perigee surface (acts): (" << track.getPerigeeX()
268 << ", " << track.getPerigeeY() << ", "
269 << track.getPerigeeZ() << ")";
270
271 const Acts::BoundVector& trkpars = trk_btp.parameters();
272 ldmx_log(debug) << " Perigee parameters (d0, z0, phi, theta, q/p)= ("
273 << trkpars[Acts::eBoundLoc0] << ", "
274 << trkpars[Acts::eBoundLoc1] << ", "
275 << trkpars[Acts::eBoundPhi] << ", "
276 << trkpars[Acts::eBoundTheta] << ", "
277 << trkpars[Acts::eBoundQOverP] << ")";
278
279 const Acts::BoundVector& fit_start_pars = trk_btp_fit_start.parameters();
280 ldmx_log(debug) << " GSF start parameters (d0, z0, phi, theta, q/p)= ("
281 << fit_start_pars[Acts::eBoundLoc0] << ", "
282 << fit_start_pars[Acts::eBoundLoc1] << ", "
283 << fit_start_pars[Acts::eBoundPhi] << ", "
284 << fit_start_pars[Acts::eBoundTheta] << ", "
285 << fit_start_pars[Acts::eBoundQOverP] << ")";
286
287 ldmx_log(debug) << " About to run GSF fit with "
288 << fit_track_source_links.size() << " source links";
289
290 // Update GSF reference surface for this track
291 if (tagger_tracking_) {
292 gsf_ref_surface = beam_origin_surface_;
293 } else {
294 gsf_ref_surface = target_surface_;
295 }
296 gsf_options.referenceSurface = &(*gsf_ref_surface);
297
298 auto gsf_refit_result =
299 gsf_->fit(fit_track_source_links.begin(), fit_track_source_links.end(),
300 trk_btp_fit_start, gsf_options, tc);
301
302 if (!gsf_refit_result.ok()) {
303 ldmx_log(warn) << "GSF re-fit failed: "
304 << gsf_refit_result.error().message();
305 continue;
306 }
307
308 ldmx_log(debug) << " GSF fit succeeded, tc.size() = " << tc.size();
309
310 if (tc.size() < 1) continue;
311
312 auto gsftrk = tc.getTrack(0);
313 // calculateTrackQuantities(gsftrk);
314
315 const Acts::BoundVector& perigee_pars = gsftrk.parameters();
316 const Acts::BoundMatrix& trk_cov = gsftrk.covariance();
317 const Acts::Surface& perigee_surface = gsftrk.referenceSurface();
318
319 ldmx_log(debug)
320 << " Reference Surface (acts-x, acts-y, acts-z) = ("
321 << perigee_surface.transform(geometryContext()).translation()(0) << ", "
322 << perigee_surface.transform(geometryContext()).translation()(1) << ", "
323 << perigee_surface.transform(geometryContext()).translation()(2) << ")";
324
325 ldmx_log(debug) << " Found track has " << gsftrk.nTrackStates()
326 << " track states";
327
328 ldmx_log(debug) << " Track parameters (d0, z0, phi, theta, q/p)= ("
329 << perigee_pars[Acts::eBoundLoc0] << ", "
330 << perigee_pars[Acts::eBoundLoc1] << ", "
331 << perigee_pars[Acts::eBoundPhi] << ", "
332 << perigee_pars[Acts::eBoundTheta] << ", "
333 << perigee_pars[Acts::eBoundQOverP] << ") ";
334
335 ldmx::Track trk;
336
337 // Extrapolate GSF track to target surface to get perigee parameters
338 auto opt_target = trk_extrap_->extrapolate(gsftrk, target_surface_);
339
340 if (opt_target) {
341 ldmx_log(debug) << " GSF target extrapolation succeeded";
342 auto ts_at_target = tracking::sim::utils::makeTrackState(
343 geometryContext(), *opt_target, ldmx::AtTarget);
344 trk.addTrackState(ts_at_target);
345
346 trk.setPerigeeParameters(tracking::sim::utils::convertActsToLdmxPars(
347 opt_target->parameters()));
348 if (opt_target->covariance()) {
349 std::vector<double> cov_vec;
350 tracking::sim::utils::flatCov(*(opt_target->covariance()), cov_vec);
351 trk.setPerigeeCov(cov_vec);
352 }
353 Acts::Vector3 target_loc_ldmx = tracking::sim::utils::acts2Ldmx(
354 target_surface_->transform(geometryContext()).translation());
355 trk.setPerigeeLocation(target_loc_ldmx[0], target_loc_ldmx[1],
356 target_loc_ldmx[2]);
357
358 ldmx_log(debug)
359 << " GSF target parameters (d0, z0, phi, theta, q/p)= ("
360 << opt_target->parameters()[Acts::eBoundLoc0] << ", "
361 << opt_target->parameters()[Acts::eBoundLoc1] << ", "
362 << opt_target->parameters()[Acts::eBoundPhi] << ", "
363 << opt_target->parameters()[Acts::eBoundTheta] << ", "
364 << opt_target->parameters()[Acts::eBoundQOverP] << ")";
365 } else {
366 ldmx_log(debug) << " GSF target extrapolation failed, using GSF fit "
367 "parameters at reference surface";
368 trk.setPerigeeParameters(
369 tracking::sim::utils::convertActsToLdmxPars(perigee_pars));
370 std::vector<double> v_trk_cov;
371 tracking::sim::utils::flatCov(trk_cov, v_trk_cov);
372 trk.setPerigeeCov(v_trk_cov);
373 }
374
375 // Tagger: also add beam-origin state; Recoil: add ECAL state
376 if (tagger_tracking_) {
377 auto opt_beam_origin =
378 trk_extrap_->extrapolate(gsftrk, beam_origin_surface_);
379 if (opt_beam_origin)
380 trk.addTrackState(tracking::sim::utils::makeTrackState(
381 geometryContext(), *opt_beam_origin, ldmx::AtBeamOrigin));
382 } else {
383 ldmx_log(debug) << " ECAL extrapolation";
384 auto opt_ecal = trk_extrap_->extrapolate(gsftrk, ecal_surface_);
385 if (opt_ecal)
386 trk.addTrackState(tracking::sim::utils::makeTrackState(
387 geometryContext(), *opt_ecal, ldmx::AtECAL));
388 }
389
390 trk.setChi2(gsftrk.chi2());
391 trk.setNhits(gsftrk.nMeasurements());
392 trk.setNdf(gsftrk.nMeasurements() - 5);
393 trk.setCharge(perigee_pars[Acts::eBoundQOverP] > 0 ? 1 : -1);
394
395 // Truth information carried over from input track
396 trk.setTrackID(track.getTrackID());
397 trk.setPdgID(track.getPdgID());
398 trk.setTruthProb(track.getTruthProb());
399
400 itrk++;
401
402 ldmx_log(debug) << " Added track to output, total tracks = "
403 << (out_tracks.size() + 1);
404
405 out_tracks.push_back(trk);
406
407 } // loop on tracks
408
409 event.add(out_trk_collection_, out_tracks);
410} // end of produce()
411
414
415} // namespace reco
416} // namespace tracking
417
#define DECLARE_PRODUCER(CLASS)
Macro which allows the framework to construct a producer given its name during configuration.
Implements an event buffer system for storing event data.
Definition Event.h:42
bool exists(const std::string &name, const std::string &passName, bool unique=true) const
Check for the existence of an object or collection with the given name and pass name in the event.
Definition Event.cxx:105
Class which represents the process under execution.
Definition Process.h:37
Class encapsulating parameters for configuring a processor.
Definition Parameters.h:29
const T & get(const std::string &name) const
Retrieve the parameter of the given name.
Definition Parameters.h:78
Run-specific configuration and data stored in its own output TTree alongside the event TTree in the o...
Definition RunHeader.h:57
Implementation of a track object.
Definition Track.h:53
bool disable_all_material_handling_
Disable all material interactions during propagation.
std::unique_ptr< const Acts::GaussianSumFitter< GsfPropagator, BetheHeitlerApprox, Acts::VectorMultiTrajectory > > gsf_
Gaussian Sum Fitter instance for track refitting.
std::shared_ptr< Acts::Surface > target_surface_
Target surface at z=0 mm (recoil track initialization, perigee output)
void produce(framework::Event &event) override
Run the processor.
bool debug_
Enable verbose debug output logging.
std::string track_collection_
Collection name for input tracks to be refit.
size_t max_components_
Maximum number of mixture components in GSF fit.
std::string meas_collection_
Collection name for measurements associated with tracks.
bool abort_on_error_
Abort fit if any error occurs (strict error handling)
std::string meas_passname_
Pass name for measurement collection in event.
void onProcessEnd() override
Callback for the EventProcessor to take any necessary action when the processing of events finishes,...
double weight_cutoff_
Weight threshold below which mixture components are dropped.
std::string field_map_
Path to magnetic field map file.
void configure(framework::config::Parameters &parameters) override
Configure the processor using the given user specified parameters.
int propagator_max_steps_
Maximum number of propagation steps before aborting.
bool use_perigee_
Use perigee parameterization for tracks.
GSFProcessor(const std::string &name, framework::Process &process)
Constructor.
void onProcessStart() override
Callback for the EventProcessor to take any necessary action when the processing of events starts,...
void onNewRun(const ldmx::RunHeader &rh) override
onNewRun is the first function called for each processor after the conditions are fully configured an...
std::string track_collection_event_passname_
Pass name qualifier for track collection event key.
std::unique_ptr< const Propagator > propagator_
Propagator for track extrapolation using eigen stepper.
double propagator_step_size_
Step size for track propagation in mm.
std::shared_ptr< Acts::Surface > beam_origin_surface_
Beam origin surface at z=-700 mm (tagger track initialization)
std::string track_passname_
Pass name for track collection in event.
std::shared_ptr< Acts::Surface > ecal_surface_
ECAL surface at z=240.5 mm (ECAL scoring plane for recoil tracking)
std::string meas_collection_event_passname_
Pass name qualifier for measurement collection event key.
std::string out_trk_collection_
Collection name for output GSF-refitted tracks.
a helper base class providing some methods to shorten access to common conditions used within the tra...
std::shared_ptr< Acts::MagneticFieldProvider > bField() const
Return the loaded B-field provider.
void loadBField(const std::string &path, const std::vector< double > &map_offset={0., 0., 0.})
Load the interpolated B-field map from path and cache it.
void calibrate1d(const Acts::GeometryContext &, const Acts::CalibrationContext &, const Acts::SourceLink &genericSourceLink, typename traj_t::TrackStateProxy trackState) const
Find the measurement corresponding to the source link.
The measurement calibrator can be a function or a class/struct able to retrieve the sim hits containe...