LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
KalmanFilterTrajectoryFitter_module.cc
Go to the documentation of this file.
1 
12 
15 #include "fhiclcpp/types/Atom.h"
17 #include "fhiclcpp/types/Table.h"
18 
29 
30 #include <memory>
31 
32 namespace trkf {
33 
35  public:
36  struct Inputs {
37  using Name = fhicl::Name;
40  Name("inputTrajectoryLabel"),
41  Comment("Label of recob::Trajectory or recob::TrackTrajectory Collection to be fit")};
43  Name("isTrackTrajectory"),
44  Comment("If true, we assume the input collection is made of recob::TrackTrajectory "
45  "objects, otherwise of recob::Trajectory objects.")};
47  Name("inputMCLabel"),
48  Comment("Label of sim::MCTrack Collection to be used for initial momentum estimate. Used "
49  "only if momFromMC is set to true.")};
50  };
51 
52  struct Options {
53  using Name = fhicl::Name;
55  fhicl::Atom<bool> pFromLength{Name("momFromLength"),
56  Comment("Flag used to get initial momentum estimate from "
57  "trkf::TrackMomentumCalculator::GetTrackMomentum().")};
59  Name("momFromMC"),
60  Comment("Flag used to get initial momentum estimate from inputMCLabel collection.")};
62  Name("momentumInGeV"),
63  Comment("Fixed momentum estimate value, to be used when momFromCalo, momFromLength and "
64  "momFromMC are all false, or if the estimate is not available.") //momFromMSChi2,
65  };
67  Name("pdgId"),
68  Comment("Default particle id hypothesis in case no valid id is provided either via "
69  "PFParticle or in the ParticleId collection.")};
70  fhicl::Atom<bool> dirFromMC{Name("dirFromMC"), Comment("Assume track direction from MC.")};
71  fhicl::Atom<bool> dirFromVec{Name("dirFromVec"),
72  Comment("Assume track direction from as the one giving positive "
73  "dot product with vector specified by dirVec.")};
74  fhicl::Sequence<float, 3u> dirVec{Name("dirVec"),
75  Comment("Fhicl sequence defining the vector used when "
76  "dirFromVec=true. It must have 3 elements.")};
77  fhicl::Atom<bool> alwaysInvertDir{
78  Name("alwaysInvertDir"),
79  Comment("If true, fit all tracks from end to vertex assuming inverted direction.")};
80  fhicl::Atom<bool> produceTrackFitHitInfo{
81  Name("produceTrackFitHitInfo"),
82  Comment("Option to produce (or not) the detailed TrackFitHitInfo.")};
83  fhicl::Atom<bool> produceSpacePoints{
84  Name("produceSpacePoints"),
85  Comment("Option to produce (or not) the associated SpacePoints.")};
86  fhicl::Atom<bool> keepInputTrajectoryPoints{
87  Name("keepInputTrajectoryPoints"),
88  Comment("Option to keep positions and directions from input trajectory. The fit will "
89  "provide only covariance matrices, chi2, ndof, particle Id and absolute momentum. "
90  "It may also modify the trajectory point flags. In order to avoid inconsistencies, "
91  "it has to be used with the following fitter options all set to false: "
92  "sortHitsByPlane, sortOutputHitsMinLength, skipNegProp.")};
93  };
94 
95  struct Config {
96  using Name = fhicl::Name;
98  Name("inputs"),
99  };
103  };
105 
106  explicit KalmanFilterTrajectoryFitter(Parameters const& p);
107 
108  // Plugins should not be copied or assigned.
113 
114  private:
115  void produce(art::Event& e) override;
116 
121 
124 
125  bool isTT;
126 
127  double setMomValue(const recob::TrackTrajectory* ptraj, const double pMC, const int pId) const;
128  int setPId() const;
129  bool setDirFlip(const recob::TrackTrajectory* ptraj, TVector3& mcdir) const;
130 
132  const std::vector<art::Ptr<recob::Hit>>& inHits,
133  recob::Track& outTrack,
134  std::vector<art::Ptr<recob::Hit>>& outHits) const;
135  };
136 }
137 
140  : EDProducer{p}
141  , p_(p)
142  , prop{p_().propagator}
143  , kalmanFitter{&prop, p_().fitter}
144  , trajectoryInputTag{p_().inputs().inputTrajectoryLabel()}
145 {
146  if (p_().options().pFromMC() || p_().options().dirFromMC())
147  simTrackInputTag = art::InputTag{p_().inputs().inputMCLabel()};
148 
149  isTT = p_().inputs().isTrackTrajectory();
150 
151  produces<std::vector<recob::Track>>();
152  produces<art::Assns<recob::Track, recob::Hit>>();
153  produces<art::Assns<recob::Track, recob::Hit, recob::TrackHitMeta>>();
154  if (isTT) { produces<art::Assns<recob::TrackTrajectory, recob::Track>>(); }
155  else {
156  produces<art::Assns<recob::Trajectory, recob::Track>>();
157  }
158  if (p_().options().produceTrackFitHitInfo()) {
159  produces<std::vector<std::vector<recob::TrackFitHitInfo>>>();
160  }
161  if (p_().options().produceSpacePoints()) {
162  produces<std::vector<recob::SpacePoint>>();
163  produces<art::Assns<recob::Hit, recob::SpacePoint>>();
164  }
165 
166  //throw expections to avoid possible silent failures due to incompatible configuration options
167 
168  unsigned int nDirs = 0;
169  if (p_().options().dirFromMC()) nDirs++;
170  if (p_().options().dirFromVec()) nDirs++;
171  if (p_().options().alwaysInvertDir()) nDirs++;
172  if (nDirs > 1) {
173  throw cet::exception("KalmanFilterTrajectoryFitter")
174  << "Incompatible configuration parameters: only at most one can be set to true among "
175  "dirFromMC, dirFromVec, and alwaysInvertDir."
176  << "\n";
177  }
178 
179  unsigned int nPFroms = 0;
180  if (p_().options().pFromLength()) nPFroms++;
181  if (p_().options().pFromMC()) nPFroms++;
182  if (nPFroms > 1) {
183  throw cet::exception("KalmanFilterTrajectoryFitter")
184  << "Incompatible configuration parameters: only at most one can be set to true among "
185  "pFromLength, and pFromMC."
186  << "\n"; //pFromMSChi2,
187  }
188 
189  if (p_().options().keepInputTrajectoryPoints()) {
190  if (p_().fitter().sortHitsByPlane() || p_().fitter().sortOutputHitsMinLength() ||
191  p_().fitter().skipNegProp()) {
192  throw cet::exception("KalmanFilterTrajectoryFitter")
193  << "Incompatible configuration parameters: keepInputTrajectoryPoints needs the following "
194  "fitter options all set to false: sortHitsByPlane, sortOutputHitsMinLength, skipNegProp."
195  << "\n";
196  }
197  }
198 }
199 
201 {
202 
203  auto outputTracks = std::make_unique<std::vector<recob::Track>>();
204  auto outputHitsMeta =
205  std::make_unique<art::Assns<recob::Track, recob::Hit, recob::TrackHitMeta>>();
206  auto outputHits = std::make_unique<art::Assns<recob::Track, recob::Hit>>();
207  auto outputHitInfo = std::make_unique<std::vector<std::vector<recob::TrackFitHitInfo>>>();
208 
209  //only one will be filled and pushed into the event:
210  auto outputTTjTAssn = std::make_unique<art::Assns<recob::TrackTrajectory, recob::Track>>();
211  auto outputTjTAssn = std::make_unique<art::Assns<recob::Trajectory, recob::Track>>();
212 
213  auto const tid = e.getProductID<std::vector<recob::Track>>();
214  auto const tidgetter = e.productGetter(tid);
215 
216  auto outputSpacePoints = std::make_unique<std::vector<recob::SpacePoint>>();
217  auto outputHitSpacePointAssn = std::make_unique<art::Assns<recob::Hit, recob::SpacePoint>>();
218  auto const spid = e.getProductID<std::vector<recob::SpacePoint>>();
219  auto const spidgetter = e.productGetter(spid);
220 
221  //FIXME, eventually remove this (ok only for single particle MC)
222  double pMC = -1.;
223  TVector3 mcdir;
224  if (p_().options().pFromMC() || p_().options().dirFromMC()) {
226  e.getValidHandle<std::vector<sim::MCTrack>>(simTrackInputTag);
227  for (unsigned int iMC = 0; iMC < simTracks->size(); ++iMC) {
228  const sim::MCTrack& mctrack = simTracks->at(iMC);
229  //fiducial cuts on MC tracks
230  if (mctrack.PdgCode() != 13) continue;
231  if (mctrack.Process() != "primary") continue;
232  pMC = mctrack.Start().Momentum().P() * 0.001;
233  mcdir = TVector3(mctrack.Start().Momentum().X() * 0.001 / pMC,
234  mctrack.Start().Momentum().Y() * 0.001 / pMC,
235  mctrack.Start().Momentum().Z() * 0.001 / pMC);
236  break;
237  }
238  //std::cout << "mc momentum value = " << pval << " GeV" << std::endl;
239  }
240 
241  unsigned int nTrajs = 0;
242 
245  const std::vector<recob::TrackTrajectory>* trackTrajectoryVec = nullptr;
246  const std::vector<recob::Trajectory>* trajectoryVec = nullptr;
247  const art::Assns<recob::TrackTrajectory, recob::Hit>* trackTrajectoryHitsAssn = nullptr;
248  const art::Assns<recob::Trajectory, recob::Hit>* trajectoryHitsAssn = nullptr;
249  if (isTT) {
250  bool ok = e.getByLabel(trajectoryInputTag, inputTrackTrajectoryH);
251  if (!ok)
252  throw cet::exception("KalmanFilterTrajectoryFitter")
253  << "Cannot find recob::TrackTrajectory art::Handle with inputTag " << trajectoryInputTag;
254  trackTrajectoryVec = inputTrackTrajectoryH.product();
255  trackTrajectoryHitsAssn =
257  .product();
258  nTrajs = trackTrajectoryVec->size();
259  }
260  else {
261  bool ok = e.getByLabel(trajectoryInputTag, inputTrajectoryH);
262  if (!ok)
263  throw cet::exception("KalmanFilterTrajectoryFitter")
264  << "Cannot find recob::Trajectory art::Handle with inputTag " << trajectoryInputTag;
265  trajectoryVec = inputTrajectoryH.product();
266  trajectoryHitsAssn =
268  nTrajs = trajectoryVec->size();
269  }
270 
271  auto const detProp = art::ServiceHandle<detinfo::DetectorPropertiesService const>()->DataFor(e);
272 
273  for (unsigned int iTraj = 0; iTraj < nTrajs; ++iTraj) {
274 
275  const recob::TrackTrajectory& inTraj =
276  (isTT ? trackTrajectoryVec->at(iTraj) :
277  recob::TrackTrajectory(trajectoryVec->at(iTraj),
278  std::vector<recob::TrajectoryPointFlags>()));
279  // this is not computationally optimal, but at least preserves the order
280  // unlike FindManyP
281  std::vector<art::Ptr<recob::Hit>> inHits;
282  if (isTT) {
283  for (auto it = trackTrajectoryHitsAssn->begin(); it != trackTrajectoryHitsAssn->end(); ++it) {
284  if (it->first.key() == iTraj)
285  inHits.push_back(it->second);
286  else if (inHits.size() > 0)
287  break;
288  }
289  }
290  else {
291  for (auto it = trajectoryHitsAssn->begin(); it != trajectoryHitsAssn->end(); ++it) {
292  if (it->first.key() == iTraj)
293  inHits.push_back(it->second);
294  else if (inHits.size() > 0)
295  break;
296  }
297  }
298  const int pId = setPId();
299  const double mom = setMomValue(&inTraj, pMC, pId);
300  const bool flipDir = setDirFlip(&inTraj, mcdir);
301 
302  recob::Track outTrack;
303  std::vector<art::Ptr<recob::Hit>> outHits;
304  trkmkr::OptionalOutputs optionals;
305  if (p_().options().produceTrackFitHitInfo()) optionals.initTrackFitInfos();
306  bool fitok = kalmanFitter.fitTrack(detProp,
307  inTraj,
308  iTraj,
309  SMatrixSym55(),
310  SMatrixSym55(),
311  inHits, // inFlags,
312  mom,
313  pId,
314  flipDir,
315  outTrack,
316  outHits,
317  optionals);
318  if (!fitok) continue;
319 
320  if (p_().options().keepInputTrajectoryPoints()) {
321  restoreInputPoints(inTraj, inHits, outTrack, outHits);
322  }
323 
324  outputTracks->emplace_back(std::move(outTrack));
325  art::Ptr<recob::Track> aptr(tid, outputTracks->size() - 1, tidgetter);
326  unsigned int ip = 0;
327  for (auto const& trhit : outHits) {
328  //the fitter produces collections with 1-1 match between hits and point
329  recob::TrackHitMeta metadata(ip, -1);
330  outputHitsMeta->addSingle(aptr, trhit, metadata);
331  outputHits->addSingle(aptr, trhit);
332  if (p_().options().produceSpacePoints() && outputTracks->back().HasValidPoint(ip)) {
333  auto& tp = outputTracks->back().Trajectory().LocationAtPoint(ip);
334  double fXYZ[3] = {tp.X(), tp.Y(), tp.Z()};
335  double fErrXYZ[6] = {0};
336  recob::SpacePoint sp(fXYZ, fErrXYZ, -1.);
337  outputSpacePoints->emplace_back(std::move(sp));
338  art::Ptr<recob::SpacePoint> apsp(spid, outputSpacePoints->size() - 1, spidgetter);
339  outputHitSpacePointAssn->addSingle(trhit, apsp);
340  }
341  ip++;
342  }
343  outputHitInfo->emplace_back(optionals.trackFitHitInfos());
344  if (isTT) {
345  outputTTjTAssn->addSingle(art::Ptr<recob::TrackTrajectory>(inputTrackTrajectoryH, iTraj),
346  aptr);
347  }
348  else {
349  outputTjTAssn->addSingle(art::Ptr<recob::Trajectory>(inputTrajectoryH, iTraj), aptr);
350  }
351  }
352  e.put(std::move(outputTracks));
353  e.put(std::move(outputHitsMeta));
354  e.put(std::move(outputHits));
355  if (p_().options().produceTrackFitHitInfo()) { e.put(std::move(outputHitInfo)); }
356  if (p_().options().produceSpacePoints()) {
357  e.put(std::move(outputSpacePoints));
358  e.put(std::move(outputHitSpacePointAssn));
359  }
360  if (isTT)
361  e.put(std::move(outputTTjTAssn));
362  else
363  e.put(std::move(outputTjTAssn));
364 }
365 
368  const std::vector<art::Ptr<recob::Hit>>& inHits,
369  recob::Track& outTrack,
370  std::vector<art::Ptr<recob::Hit>>& outHits) const
371 {
372  const auto np = outTrack.NumberTrajectoryPoints();
373  std::vector<Point_t> positions(np);
374  std::vector<Vector_t> momenta(np);
375  std::vector<recob::TrajectoryPointFlags> outFlags(np);
376  //
377  for (unsigned int p = 0; p < np; ++p) {
378  auto flag = outTrack.FlagsAtPoint(p);
379  auto mom = outTrack.VertexMomentum();
380  auto op = flag.fromHit();
381  positions[op] = track.LocationAtPoint(op);
382  momenta[op] = mom * track.DirectionAtPoint(op);
383  auto mask = flag.mask();
386  outFlags[op] = recob::TrajectoryPointFlags(op, mask);
387  }
388  auto covs = outTrack.Covariances();
389  outTrack = recob::Track(
390  recob::TrackTrajectory(std::move(positions), std::move(momenta), std::move(outFlags), true),
391  outTrack.ParticleId(),
392  outTrack.Chi2(),
393  outTrack.Ndof(),
394  std::move(covs.first),
395  std::move(covs.second),
396  outTrack.ID());
397  //
398  outHits.clear();
399  for (auto h : inHits)
400  outHits.push_back(h);
401 }
402 
404  const double pMC,
405  const int pId) const
406 {
407  double result = p_().options().pval();
408  if (p_().options().pFromLength()) { result = tmc.GetTrackMomentum(ptraj->Length(), pId); }
409  else if (p_().options().pFromMC() && pMC > 0.) {
410  result = pMC;
411  }
412  return result;
413 }
414 
416 {
417  int result = p_().options().pdgId();
418  return result;
419 }
420 
422  TVector3& mcdir) const
423 {
424  bool result = false;
425  if (p_().options().alwaysInvertDir()) { return true; }
426  else if (p_().options().dirFromMC()) {
427  auto tdir = ptraj->VertexDirection();
428  if ((mcdir.X() * tdir.X() + mcdir.Y() * tdir.Y() + mcdir.Z() * tdir.Z()) < 0.) result = true;
429  }
430  else if (p_().options().dirFromVec()) {
431  std::array<float, 3> dir = p_().options().dirVec();
432  auto tdir = ptraj->VertexDirection();
433  if ((dir[0] * tdir.X() + dir[1] * tdir.Y() + dir[2] * tdir.Z()) < 0.) result = true;
434  }
435  return result;
436 }
437 
void restoreInputPoints(const recob::TrackTrajectory &track, const std::vector< art::Ptr< recob::Hit >> &inHits, recob::Track &outTrack, std::vector< art::Ptr< recob::Hit >> &outHits) const
double VertexMomentum() const
Definition: Track.h:176
Fit tracks using Kalman Filter fit+smooth.
void initTrackFitInfos()
initialize the output vector of TrackFitHitInfos
Definition: TrackMaker.h:140
static constexpr Flag_t NoPoint
The trajectory point is not defined.
T DirectionAtPoint(unsigned int p) const
Direction at point p. Use e.g. as:
int ParticleId() const
Access to various track properties.
Definition: Track.h:211
ProductID getProductID(std::string const &instance_name="") const
Declaration of signal hit object.
EDProducer(fhicl::ParameterSet const &pset)
Definition: EDProducer.cc:6
recob::tracking::SMatrixSym55 SMatrixSym55
Definition: TrackState.h:15
float Chi2() const
Access to various track properties.
Definition: Track.h:208
size_t NumberTrajectoryPoints() const
Various functions related to the presence and the number of (valid) points.
Definition: Track.h:136
Class to keep data related to recob::Hit associated with recob::Track.
bool fitTrack(detinfo::DetectorPropertiesData const &detProp, const recob::TrackTrajectory &traj, int tkID, const SMatrixSym55 &covVtx, const SMatrixSym55 &covEnd, const std::vector< art::Ptr< recob::Hit >> &hits, const double pval, const int pdgid, const bool flipDirection, recob::Track &outTrack, std::vector< art::Ptr< recob::Hit >> &outHits, trkmkr::OptionalOutputs &optionals) const
Fit track starting from TrackTrajectory.
Class for propagation of a trkf::TrackState to a recob::tracking::Plane.
Data related to recob::Hit associated with recob::Track.The purpose is to collect several variables t...
Definition: TrackHitMeta.h:43
std::pair< SMatrixSym55, SMatrixSym55 > Covariances() const
Access to position, momentum or covariance at the start and end of the track.
Definition: Track.h:199
const_iterator begin() const
Definition: Assns.h:507
PutHandle< PROD > put(std::unique_ptr< PROD > &&edp, std::string const &instance={})
Definition: Event.h:77
auto vector(Vector const &v)
Returns a manipulator which will print the specified array.
Definition: DumpUtils.h:289
Vector_t VertexDirection() const
Returns the direction of the trajectory at the first point.
double Length(size_t startAt=0) const
Returns the approximate length of the trajectory.
EDProductGetter const * productGetter(ProductID const pid) const
T const * product() const
Definition: Handle.h:174
#define DEFINE_ART_MODULE(klass)
Definition: ModuleMacros.h:65
A trajectory in space reconstructed from hits.
T LocationAtPoint(unsigned int p) const
Position at point p. Use e.g. as:
Provides recob::Track data product.
double setMomValue(const recob::TrackTrajectory *ptraj, const double pMC, const int pId) const
Class def header for mctrack data container.
int Ndof() const
Access to various track properties.
Definition: Track.h:210
int PdgCode() const
Definition: MCTrack.h:39
const TLorentzVector & Momentum() const
Definition: MCStep.h:34
const_iterator end() const
Definition: Assns.h:514
int ID() const
Definition: Track.h:244
ValidHandle< PROD > getValidHandle(InputTag const &tag) const
bool getByLabel(std::string const &label, std::string const &instance, Handle< PROD > &result) const
std::vector< recob::TrackFitHitInfo > trackFitHitInfos()
get the output vector of TrackFitHitInfos by releasing and moving
Definition: TrackMaker.h:151
TDirectory * dir
Definition: macro.C:5
const std::string & Process() const
Definition: MCTrack.h:41
PointFlags_t const & FlagsAtPoint(size_t i) const
Access to i-th TrajectoryPoint or its Flags.
Definition: Track.h:152
const MCStep & Start() const
Definition: MCTrack.h:42
bool setDirFlip(const recob::TrackTrajectory *ptraj, TVector3 &mcdir) const
TrackCollectionProxyElement< TrackCollProxy > Track
Proxy to an element of a proxy collection of recob::Track objects.
Definition: Track.h:992
Float_t e
Definition: plot.C:35
Float_t track
Definition: plot.C:35
KalmanFilterTrajectoryFitter & operator=(KalmanFilterTrajectoryFitter const &)=delete
Struct holding optional TrackMaker outputs.
Definition: TrackMaker.h:108
Set of flags pertaining a point of the track.
Track from a non-cascading particle.A recob::Track consists of a recob::TrackTrajectory, plus additional members relevant for a "fitted" track:
Definition: Track.h:49
double GetTrackMomentum(double trkrange, int pdg) const
cet::coded_exception< error, detail::translate > exception
Definition: exception.h:33