KalmanFilterTrajectoryFitter_module.cc
Go to the documentation of this file.
1 /// \class KalmanFilterTrajectoryFitter
2 ///
3 /// \brief Producer for fitting Trajectories and TrackTrajectories using TrackKalmanFitter.
4 ///
5 /// \author G. Cerati
6 ///
7 
12 
14 #include "fhiclcpp/types/Atom.h"
16 #include "fhiclcpp/types/Table.h"
17 
28 
29 #include <memory>
30 
31 namespace trkf {
32 
34  public:
35  struct Inputs {
36  using Name = fhicl::Name;
39  Name("inputTrajectoryLabel"),
40  Comment("Label of recob::Trajectory or recob::TrackTrajectory Collection to be fit")};
42  Name("isTrackTrajectory"),
43  Comment("If true, we assume the input collection is made of recob::TrackTrajectory "
44  "objects, otherwise of recob::Trajectory objects.")};
46  Name("inputMCLabel"),
47  Comment("Label of sim::MCTrack Collection to be used for initial momentum estimate. Used "
48  "only if momFromMC is set to true.")};
49  };
50 
51  struct Options {
52  using Name = fhicl::Name;
54  fhicl::Atom<bool> pFromLength{Name("momFromLength"),
55  Comment("Flag used to get initial momentum estimate from "
56  "trkf::TrackMomentumCalculator::GetTrackMomentum().")};
58  Name("momFromMC"),
59  Comment("Flag used to get initial momentum estimate from inputMCLabel collection.")};
61  Name("momentumInGeV"),
62  Comment("Fixed momentum estimate value, to be used when momFromCalo, momFromLength and "
63  "momFromMC are all false, or if the estimate is not available.") //momFromMSChi2,
64  };
66  Name("pdgId"),
67  Comment("Default particle id hypothesis in case no valid id is provided either via "
68  "PFParticle or in the ParticleId collection.")};
69  fhicl::Atom<bool> dirFromMC{Name("dirFromMC"), Comment("Assume track direction from MC.")};
70  fhicl::Atom<bool> dirFromVec{Name("dirFromVec"),
71  Comment("Assume track direction from as the one giving positive "
72  "dot product with vector specified by dirVec.")};
73  fhicl::Sequence<float, 3u> dirVec{Name("dirVec"),
74  Comment("Fhicl sequence defining the vector used when "
75  "dirFromVec=true. It must have 3 elements.")};
76  fhicl::Atom<bool> alwaysInvertDir{
77  Name("alwaysInvertDir"),
78  Comment("If true, fit all tracks from end to vertex assuming inverted direction.")};
79  fhicl::Atom<bool> produceTrackFitHitInfo{
80  Name("produceTrackFitHitInfo"),
81  Comment("Option to produce (or not) the detailed TrackFitHitInfo.")};
82  fhicl::Atom<bool> produceSpacePoints{
83  Name("produceSpacePoints"),
84  Comment("Option to produce (or not) the associated SpacePoints.")};
85  fhicl::Atom<bool> keepInputTrajectoryPoints{
86  Name("keepInputTrajectoryPoints"),
87  Comment("Option to keep positions and directions from input trajectory. The fit will "
88  "provide only covariance matrices, chi2, ndof, particle Id and absolute momentum. "
89  "It may also modify the trajectory point flags. In order to avoid inconsistencies, "
90  "it has to be used with the following fitter options all set to false: "
91  "sortHitsByPlane, sortOutputHitsMinLength, skipNegProp.")};
92  };
93 
94  struct Config {
95  using Name = fhicl::Name;
97  Name("inputs"),
98  };
102  };
104 
105  explicit KalmanFilterTrajectoryFitter(Parameters const& p);
106 
107  // Plugins should not be copied or assigned.
112 
113  private:
114  void produce(art::Event& e) override;
115 
120 
123 
124  bool isTT;
125 
126  double setMomValue(const recob::TrackTrajectory* ptraj, const double pMC, const int pId) const;
127  int setPId() const;
128  bool setDirFlip(const recob::TrackTrajectory* ptraj, TVector3& mcdir) const;
129 
130  void restoreInputPoints(const recob::TrackTrajectory& track,
131  const std::vector<art::Ptr<recob::Hit>>& inHits,
132  recob::Track& outTrack,
133  std::vector<art::Ptr<recob::Hit>>& outHits) const;
134  };
135 }
136 
139  : EDProducer{p}
140  , p_(p)
141  , prop{p_().propagator}
142  , kalmanFitter{&prop, p_().fitter}
143  , trajectoryInputTag{p_().inputs().inputTrajectoryLabel()}
144 {
145  if (p_().options().pFromMC() || p_().options().dirFromMC())
146  simTrackInputTag = art::InputTag{p_().inputs().inputMCLabel()};
147 
148  isTT = p_().inputs().isTrackTrajectory();
149 
150  produces<std::vector<recob::Track>>();
151  produces<art::Assns<recob::Track, recob::Hit>>();
152  produces<art::Assns<recob::Track, recob::Hit, recob::TrackHitMeta>>();
153  if (isTT) { produces<art::Assns<recob::TrackTrajectory, recob::Track>>(); }
154  else {
155  produces<art::Assns<recob::Trajectory, recob::Track>>();
156  }
157  if (p_().options().produceTrackFitHitInfo()) {
158  produces<std::vector<std::vector<recob::TrackFitHitInfo>>>();
159  }
160  if (p_().options().produceSpacePoints()) {
161  produces<std::vector<recob::SpacePoint>>();
162  produces<art::Assns<recob::Hit, recob::SpacePoint>>();
163  }
164 
165  //throw expections to avoid possible silent failures due to incompatible configuration options
166 
167  unsigned int nDirs = 0;
168  if (p_().options().dirFromMC()) nDirs++;
169  if (p_().options().dirFromVec()) nDirs++;
170  if (p_().options().alwaysInvertDir()) nDirs++;
171  if (nDirs > 1) {
172  throw cet::exception("KalmanFilterTrajectoryFitter")
173  << "Incompatible configuration parameters: only at most one can be set to true among "
174  "dirFromMC, dirFromVec, and alwaysInvertDir."
175  << "\n";
176  }
177 
178  unsigned int nPFroms = 0;
179  if (p_().options().pFromLength()) nPFroms++;
180  if (p_().options().pFromMC()) nPFroms++;
181  if (nPFroms > 1) {
182  throw cet::exception("KalmanFilterTrajectoryFitter")
183  << "Incompatible configuration parameters: only at most one can be set to true among "
184  "pFromLength, and pFromMC."
185  << "\n"; //pFromMSChi2,
186  }
187 
188  if (p_().options().keepInputTrajectoryPoints()) {
189  if (p_().fitter().sortHitsByPlane() || p_().fitter().sortOutputHitsMinLength() ||
190  p_().fitter().skipNegProp()) {
191  throw cet::exception("KalmanFilterTrajectoryFitter")
192  << "Incompatible configuration parameters: keepInputTrajectoryPoints needs the following "
193  "fitter options all set to false: sortHitsByPlane, sortOutputHitsMinLength, skipNegProp."
194  << "\n";
195  }
196  }
197 }
198 
199 void
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
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 
366 void
368  const recob::TrackTrajectory& track,
369  const std::vector<art::Ptr<recob::Hit>>& inHits,
370  recob::Track& outTrack,
371  std::vector<art::Ptr<recob::Hit>>& outHits) const
372 {
373  const auto np = outTrack.NumberTrajectoryPoints();
374  std::vector<Point_t> positions(np);
375  std::vector<Vector_t> momenta(np);
376  std::vector<recob::TrajectoryPointFlags> outFlags(np);
377  //
378  for (unsigned int p = 0; p < np; ++p) {
379  auto flag = outTrack.FlagsAtPoint(p);
380  auto mom = outTrack.VertexMomentum();
381  auto op = flag.fromHit();
382  positions[op] = track.LocationAtPoint(op);
383  momenta[op] = mom * track.DirectionAtPoint(op);
384  auto mask = flag.mask();
387  outFlags[op] = recob::TrajectoryPointFlags(op, mask);
388  }
389  auto covs = outTrack.Covariances();
390  outTrack = recob::Track(
391  recob::TrackTrajectory(std::move(positions), std::move(momenta), std::move(outFlags), true),
392  outTrack.ParticleId(),
393  outTrack.Chi2(),
394  outTrack.Ndof(),
395  std::move(covs.first),
396  std::move(covs.second),
397  outTrack.ID());
398  //
399  outHits.clear();
400  for (auto h : inHits)
401  outHits.push_back(h);
402 }
403 
404 double
406  const double pMC,
407  const int pId) const
408 {
409  double result = p_().options().pval();
410  if (p_().options().pFromLength()) { result = tmc.GetTrackMomentum(ptraj->Length(), pId); }
411  else if (p_().options().pFromMC() && pMC > 0.) {
412  result = pMC;
413  }
414  return result;
415 }
416 
417 int
419 {
420  int result = p_().options().pdgId();
421  return result;
422 }
423 
424 bool
426  TVector3& mcdir) const
427 {
428  bool result = false;
429  if (p_().options().alwaysInvertDir()) { return true; }
430  else if (p_().options().dirFromMC()) {
431  auto tdir = ptraj->VertexDirection();
432  if ((mcdir.X() * tdir.X() + mcdir.Y() * tdir.Y() + mcdir.Z() * tdir.Z()) < 0.) result = true;
433  }
434  else if (p_().options().dirFromVec()) {
435  std::array<float, 3> dir = p_().options().dirVec();
436  auto tdir = ptraj->VertexDirection();
437  if ((dir[0] * tdir.X() + dir[1] * tdir.Y() + dir[2] * tdir.Z()) < 0.) result = true;
438  }
439  return result;
440 }
441 
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:142
Fit tracks using Kalman Filter fit+smooth.
void initTrackFitInfos()
initialize the output vector of TrackFitHitInfos
Definition: TrackMaker.h:150
static QCString result
ProductID getProductID(std::string const &instance_name="") const
Definition: DataViewImpl.h:338
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
Definition: Track.h:171
EDProducer(fhicl::ParameterSet const &pset)
Definition: EDProducer.h:20
recob::tracking::SMatrixSym55 SMatrixSym55
Definition: TrackState.h:15
struct vector vector
ChannelGroupService::Name Name
float Chi2() const
Definition: Track.h:168
size_t NumberTrajectoryPoints() const
Various functions related to the presence and the number of (valid) points.
Definition: Track.h:102
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
string dir
std::pair< SMatrixSym55, SMatrixSym55 > Covariances() const
Definition: Track.h:162
const_iterator begin() const
Definition: Assns.h:504
Vector_t VertexDirection() const
Returns the direction of the trajectory at the first point.
bool getByLabel(std::string const &label, std::string const &instance, Handle< PROD > &result) const
Definition: DataViewImpl.h:633
double Length(size_t startAt=0) const
Returns the approximate length of the trajectory.
const double e
T const * product() const
Definition: Handle.h:163
#define DEFINE_ART_MODULE(klass)
Definition: ModuleMacros.h:67
A trajectory in space reconstructed from hits.
T LocationAtPoint(unsigned int p) const
Position at point p. Use e.g. as:
def move(depos, offset)
Definition: depos.py:107
EDProductGetter const * productGetter(ProductID const pid) const
ValidHandle< PROD > getValidHandle(InputTag const &tag) const
Definition: DataViewImpl.h:441
p
Definition: test.py:223
ProductID put(std::unique_ptr< PROD > &&edp, std::string const &instance={})
Definition: DataViewImpl.h:686
double setMomValue(const recob::TrackTrajectory *ptraj, const double pMC, const int pId) const
Class def header for mctrack data container.
int Ndof() const
Definition: Track.h:170
int PdgCode() const
Definition: MCTrack.h:41
const TLorentzVector & Momentum() const
Definition: MCStep.h:38
const_iterator end() const
Definition: Assns.h:511
pval
Definition: tracks.py:168
int ID() const
Definition: Track.h:198
Declaration of signal hit object.
#define Comment
std::vector< recob::TrackFitHitInfo > trackFitHitInfos()
get the output vector of TrackFitHitInfos by releasing and moving
Definition: TrackMaker.h:174
const std::string & Process() const
Definition: MCTrack.h:43
Provides recob::Track data product.
PointFlags_t const & FlagsAtPoint(size_t i) const
Definition: Track.h:118
const MCStep & Start() const
Definition: MCTrack.h:44
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:1036
KalmanFilterTrajectoryFitter & operator=(KalmanFilterTrajectoryFitter const &)=delete
Struct holding optional TrackMaker outputs.
Definition: TrackMaker.h:114
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