All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CandHitDerivative_tool.cc
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////
2 /// \file CandHitDerivative.cc
3 /// \author T. Usher
4 //note for MT: this implementation is not thread-safe
5 ////////////////////////////////////////////////////////////////////////
6 
10 
11 #include "art/Framework/Services/Registry/ServiceHandle.h"
12 #include "art/Utilities/ToolMacros.h"
13 #include "art/Utilities/make_tool.h"
14 #include "art_root_io/TFileService.h"
15 #include "cetlib_except/exception.h"
17 
18 #include "TProfile.h"
19 
20 #include <cmath>
21 
22 namespace reco_tool {
23 
25  public:
26  explicit CandHitDerivative(const fhicl::ParameterSet& pset);
27 
28  void findHitCandidates(const recob::Wire::RegionsOfInterest_t::datarange_t&,
29  const size_t,
30  const size_t,
31  const size_t,
32  HitCandidateVec&) const override;
33 
34  void MergeHitCandidates(const recob::Wire::RegionsOfInterest_t::datarange_t&,
35  const HitCandidateVec&,
36  MergeHitCandidateVec&) const override;
37 
38  private:
39  // Internal functions
40  void findHitCandidates(Waveform::const_iterator,
41  Waveform::const_iterator,
42  const size_t,
43  int,
44  float,
45  HitCandidateVec&) const;
46 
47  // Finding the nearest maximum/minimum from current point
48  Waveform::const_iterator findNearestMax(Waveform::const_iterator,
49  Waveform::const_iterator) const;
50  Waveform::const_iterator findNearestMin(Waveform::const_iterator,
51  Waveform::const_iterator) const;
52 
53  // handle finding the "start" and "stop" of a candidate hit
54  Waveform::const_iterator findStartTick(Waveform::const_iterator,
55  Waveform::const_iterator) const;
56  Waveform::const_iterator findStopTick(Waveform::const_iterator, Waveform::const_iterator) const;
57 
58  // some control variables
59  size_t fPlane; //< Identifies the plane this tool is meant to operate on
60  int fMinDeltaTicks; //< minimum ticks from max to min to consider
61  int fMaxDeltaTicks; //< maximum ticks from max to min to consider
62  float fMinDeltaPeaks; //< minimum maximum to minimum peak distance
63  float fMinHitHeight; //< Drop candidate hits with height less than this
64  size_t fNumInterveningTicks; //< Number ticks between candidate hits to merge
65  bool fOutputHistograms; //< If true will generate a very large file of hists!
66 
67  art::TFileDirectory* fHistDirectory;
68 
69  // Global histograms
73 
74  mutable std::map<size_t, int> fChannelCntMap;
75 
76  // Member variables from the fhicl file
77  std::unique_ptr<reco_tool::IWaveformTool> fWaveformTool;
78 
79  const geo::GeometryCore* fGeometry = lar::providerFrom<geo::Geometry>();
80  };
81 
82  //----------------------------------------------------------------------
83  // Constructor.
84  CandHitDerivative::CandHitDerivative(const fhicl::ParameterSet& pset)
85  {
86  fPlane = pset.get<size_t>("Plane", 0);
87  fMinDeltaTicks = pset.get<int>("MinDeltaTicks", 0);
88  fMaxDeltaTicks = pset.get<int>("MaxDeltaTicks", 30);
89  fMinDeltaPeaks = pset.get<float>("MinDeltaPeaks", 0.025);
90  fMinHitHeight = pset.get<float>("MinHitHeight", 2.0);
91  fNumInterveningTicks = pset.get<size_t>("NumInterveningTicks", 6);
92  fOutputHistograms = pset.get<bool>("OutputHistograms", false);
93 
94  // Recover the baseline tool
96  art::make_tool<reco_tool::IWaveformTool>(pset.get<fhicl::ParameterSet>("WaveformAlgs"));
97 
98  // If asked, define the global histograms
99  if (fOutputHistograms) {
100  // Access ART's TFileService, which will handle creating and writing
101  // histograms and n-tuples for us.
102  art::ServiceHandle<art::TFileService> tfs;
103 
104  fHistDirectory = tfs.get();
105 
106  // Make a directory for these histograms
107  art::TFileDirectory dir = fHistDirectory->mkdir(Form("HitPlane_%1zu", fPlane));
108 
110  dir.make<TH1F>(Form("DStopStart_%1zu", fPlane), ";Delta Stop/Start;", 200, 0., 200.);
112  dir.make<TH1F>(Form("DMaxTMinT_%1zu", fPlane), ";Delta Max/Min Tick;", 200, 0., 200.);
114  dir.make<TH1F>(Form("DMaxDMinD_%1zu", fPlane), ";Delta Max/Min Deriv;", 200, 0., 200.);
115  }
116 
117  return;
118  }
119 
120  void
122  const recob::Wire::RegionsOfInterest_t::datarange_t& dataRange,
123  const size_t roiStartTick,
124  const size_t channel,
125  const size_t eventCount,
126  HitCandidateVec& hitCandidateVec) const
127  {
128  // In this case we want to find hit candidates based on the derivative of of the input waveform
129  // We get this from our waveform algs too...
130  Waveform rawDerivativeVec;
131  Waveform derivativeVec;
132 
133  // Recover the actual waveform
134  const Waveform& waveform = dataRange.data();
135 
136  fWaveformTool->firstDerivative(waveform, rawDerivativeVec);
137  fWaveformTool->triangleSmooth(rawDerivativeVec, derivativeVec);
138 
139  std::vector<geo::WireID> wids = fGeometry->ChannelToWire(channel);
140  size_t plane = wids[0].Plane;
141  size_t cryo = wids[0].Cryostat;
142  size_t tpc = wids[0].TPC;
143  size_t wire = wids[0].Wire;
144 
145  // Just make sure the input candidate hit vector has been cleared
146  hitCandidateVec.clear();
147 
148  // Now find the hits
149  findHitCandidates(derivativeVec.begin(),
150  derivativeVec.end(),
151  roiStartTick,
154  hitCandidateVec);
155 
156  if (hitCandidateVec.empty()) {
157  if (plane == 0) {
158  std::cout << "** C/T/P: " << cryo << "/" << tpc << "/" << plane << ", wire: " << wire
159  << " has not hits with input size: " << waveform.size() << std::endl;
160  }
161  }
162 
163  // Reset the hit height from the input waveform
164  for (auto& hitCandidate : hitCandidateVec) {
165  size_t centerIdx = hitCandidate.hitCenter;
166 
167  hitCandidate.hitHeight = waveform.at(centerIdx);
168  }
169 
170  // Keep track of histograms if requested
171  if (fOutputHistograms) {
172  // Recover the details...
173  // std::vector<geo::WireID> wids = fGeometry->ChannelToWire(channel);
174  // size_t plane = wids[0].Plane;
175  // size_t cryo = wids[0].Cryostat;
176  // size_t tpc = wids[0].TPC;
177  // size_t wire = wids[0].Wire;
178 
179  size_t channelCnt = fChannelCntMap[channel]++;
180 
181  // Make a directory for these histograms
182  art::TFileDirectory dir = fHistDirectory->mkdir(
183  Form("HitPlane_%1zu/ev%04zu/c%1zut%1zuwire_%05zu", plane, eventCount, cryo, tpc, wire));
184 
185  size_t waveformSize = waveform.size();
186  int waveStart = roiStartTick;
187  int waveStop = waveStart + waveformSize;
188 
189  TProfile* waveHist = dir.make<TProfile>(
190  Form("HWfm_%03zu_ctw%01zu-%01zu-%01zu-%05zu", channelCnt, cryo, tpc, plane, wire),
191  "Waveform",
192  waveformSize,
193  waveStart,
194  waveStop,
195  -500.,
196  500.);
197  TProfile* derivHist = dir.make<TProfile>(
198  Form("HDer_%03zu_ctw%01zu-%01zu-%01zu-%05zu", channelCnt, cryo, tpc, plane, wire),
199  "Derivative",
200  waveformSize,
201  waveStart,
202  waveStop,
203  -500.,
204  500.);
205  TProfile* candHitHist = dir.make<TProfile>(
206  Form("HCan_%03zu_ctw%01zu-%01zu-%01zu-%05zu", channelCnt, cryo, tpc, plane, wire),
207  "Cand Hits",
208  waveformSize,
209  waveStart,
210  waveStop,
211  -500.,
212  500.);
213  TProfile* maxDerivHist = dir.make<TProfile>(
214  Form("HMax_%03zu_ctw%01zu-%01zu-%01zu-%05zu", channelCnt, cryo, tpc, plane, wire),
215  "Maxima",
216  waveformSize,
217  waveStart,
218  waveStop,
219  -500.,
220  500.);
221 
222  // Fill wave/derivative
223  for (size_t idx = 0; idx < waveform.size(); idx++) {
224  waveHist->Fill(roiStartTick + idx, waveform.at(idx));
225  derivHist->Fill(roiStartTick + idx, derivativeVec.at(idx));
226  }
227 
228  // Fill hits
229  for (const auto& hitCandidate : hitCandidateVec) {
230  candHitHist->Fill(hitCandidate.hitCenter, hitCandidate.hitHeight);
231  maxDerivHist->Fill(hitCandidate.maxTick, hitCandidate.maxDerivative);
232  maxDerivHist->Fill(hitCandidate.minTick, hitCandidate.minDerivative);
233 
234  fDStopStartHist->Fill(hitCandidate.stopTick - hitCandidate.startTick, 1.);
235  fDMaxTickMinTickHist->Fill(hitCandidate.minTick - hitCandidate.maxTick, 1.);
236  fDMaxDerivMinDerivHist->Fill(hitCandidate.maxDerivative - hitCandidate.minDerivative, 1.);
237  }
238  }
239 
240  return;
241  }
242 
243  void
244  CandHitDerivative::findHitCandidates(Waveform::const_iterator startItr,
245  Waveform::const_iterator stopItr,
246  const size_t roiStartTick,
247  int dTicksThreshold,
248  float dPeakThreshold,
249  HitCandidateVec& hitCandidateVec) const
250  {
251  // Search for candidate hits...
252  // The idea will be to find the largest deviation in the input derivative waveform as the starting point. Depending
253  // on if a maximum or minimum, we search forward or backward to find the minimum or maximum that our extremum
254  // corresponds to.
255  std::pair<Waveform::const_iterator, Waveform::const_iterator> minMaxPair =
256  std::minmax_element(startItr, stopItr);
257 
258  Waveform::const_iterator maxItr = minMaxPair.second;
259  Waveform::const_iterator minItr = minMaxPair.first;
260 
261  // Use the larger of the two as the starting point and recover the nearest max or min
262  if (std::fabs(*maxItr) > std::fabs(*minItr))
263  minItr = findNearestMin(maxItr, stopItr);
264  else
265  maxItr = findNearestMax(minItr, startItr);
266 
267  int deltaTicks = std::distance(maxItr, minItr);
268  float range = *maxItr - *minItr;
269 
270  // At some point small rolling oscillations on the waveform need to be ignored...
271  if (deltaTicks >= dTicksThreshold && range > dPeakThreshold) {
272  // Need to back up to find zero crossing, this will be the starting point of our
273  // candidate hit but also the endpoint of the pre sub-waveform we'll search next
274  Waveform::const_iterator newEndItr = findStartTick(maxItr, startItr);
275 
276  int startTick = std::distance(startItr, newEndItr);
277 
278  // Now need to go forward to again get close to zero, this will then be the end point
279  // of our candidate hit and the starting point for the post sub-waveform to search
280  Waveform::const_iterator newStartItr = findStopTick(minItr, stopItr);
281 
282  int stopTick = std::distance(startItr, newStartItr);
283 
284  // Find hits in the section of the waveform leading up to this candidate hit
285  if (startTick > dTicksThreshold) {
286  // Special handling for merged hits
287  if (*(newEndItr - 1) > 0.) {
288  dTicksThreshold = 2;
289  dPeakThreshold = 0.;
290  }
291  else {
292  dTicksThreshold = fMinDeltaTicks;
293  dPeakThreshold = fMinDeltaPeaks;
294  }
295 
297  startItr, newEndItr + 1, roiStartTick, dTicksThreshold, dPeakThreshold, hitCandidateVec);
298  }
299 
300  // Create a new hit candidate and store away
301  HitCandidate hitCandidate;
302 
303  Waveform::const_iterator peakItr =
304  std::min_element(maxItr, minItr, [](const auto& left, const auto& right) {
305  return std::fabs(left) < std::fabs(right);
306  });
307 
308  // Check balance
309  if (2 * std::distance(peakItr, minItr) < std::distance(maxItr, peakItr))
310  peakItr--;
311  else if (2 * std::distance(maxItr, peakItr) < std::distance(peakItr, minItr))
312  peakItr++;
313 
314  hitCandidate.startTick = roiStartTick + startTick;
315  hitCandidate.stopTick = roiStartTick + stopTick;
316  hitCandidate.maxTick = roiStartTick + std::distance(startItr, maxItr);
317  hitCandidate.minTick = roiStartTick + std::distance(startItr, minItr);
318  hitCandidate.maxDerivative = maxItr != stopItr ? *maxItr : 0.;
319  hitCandidate.minDerivative = minItr != stopItr ? *minItr : 0.;
320  hitCandidate.hitCenter = roiStartTick + std::distance(startItr, peakItr) + 0.5;
321  hitCandidate.hitSigma = 0.5 * float(hitCandidate.minTick - hitCandidate.maxTick);
322  hitCandidate.hitHeight =
323  hitCandidate.hitSigma * (hitCandidate.maxDerivative - hitCandidate.minDerivative) / 1.2130;
324 
325  hitCandidateVec.push_back(hitCandidate);
326 
327  // Finally, search the section of the waveform following this candidate for more hits
328  if (std::distance(newStartItr, stopItr) > dTicksThreshold) {
329  // Special handling for merged hits
330  if (*(newStartItr + 1) < 0.) {
331  dTicksThreshold = 2;
332  dPeakThreshold = 0.;
333  }
334  else {
335  dTicksThreshold = fMinDeltaTicks;
336  dPeakThreshold = fMinDeltaPeaks;
337  }
338 
339  findHitCandidates(newStartItr,
340  stopItr,
341  roiStartTick + stopTick,
342  dTicksThreshold,
343  dPeakThreshold,
344  hitCandidateVec);
345  }
346  }
347 
348  return;
349  }
350 
351  void
353  const recob::Wire::RegionsOfInterest_t::datarange_t& rangeData,
354  const HitCandidateVec& hitCandidateVec,
355  MergeHitCandidateVec& mergedHitsVec) const
356  {
357  // If nothing on the input end then nothing to do
358  if (hitCandidateVec.empty()) return;
359 
360  // The idea is to group hits that "touch" so they can be part of common fit, those that
361  // don't "touch" are fit independently. So here we build the output vector to achieve that
362  // Get a container for the hits...
363  HitCandidateVec groupedHitVec;
364 
365  // Initialize the end of the last hit which we'll set to the first input hit's stop
366  size_t lastStopTick = hitCandidateVec.front().stopTick;
367 
368  // Step through the input hit candidates and group them by proximity
369  for (const auto& hitCandidate : hitCandidateVec) {
370  // Small pulse height hits should not be considered?
371  if (hitCandidate.hitHeight > fMinHitHeight) {
372  // Check condition that we have a new grouping
373  if (hitCandidate.startTick > lastStopTick + fNumInterveningTicks &&
374  !groupedHitVec.empty()) {
375  mergedHitsVec.emplace_back(groupedHitVec);
376 
377  groupedHitVec.clear();
378  }
379 
380  // Add the current hit to the current group
381  groupedHitVec.emplace_back(hitCandidate);
382 
383  lastStopTick = hitCandidate.stopTick;
384  }
385  }
386 
387  // Check end condition
388  if (!groupedHitVec.empty()) mergedHitsVec.emplace_back(groupedHitVec);
389 
390  return;
391  }
392 
393  ICandidateHitFinder::Waveform::const_iterator
394  CandHitDerivative::findNearestMin(Waveform::const_iterator maxItr,
395  Waveform::const_iterator stopItr) const
396  {
397  // reset the min iterator and search forward to find the nearest minimum
398  Waveform::const_iterator lastItr = maxItr;
399 
400  // The strategy is simple...
401  // We are at a maximum so we search forward until we find the lowest negative point
402  while ((lastItr + 1) != stopItr) {
403  if (*(lastItr + 1) > *lastItr) break;
404 
405  lastItr++;
406  }
407 
408  // The minimum will be the last iterator value...
409  return lastItr;
410  }
411 
412  ICandidateHitFinder::Waveform::const_iterator
413  CandHitDerivative::findNearestMax(Waveform::const_iterator minItr,
414  Waveform::const_iterator startItr) const
415  {
416  // Set the internal loop variable...
417  Waveform::const_iterator lastItr = minItr;
418 
419  // One extra condition to watch for here, make sure we can actually back up!
420  if (std::distance(startItr, minItr) > 0) {
421  // Similar to searching for a maximum, we loop backward over ticks looking for the waveform to start decreasing
422  while ((lastItr - 1) != startItr) {
423  if (*(lastItr - 1) < *lastItr) break;
424 
425  lastItr--;
426  }
427  }
428 
429  return lastItr;
430  }
431 
432  ICandidateHitFinder::Waveform::const_iterator
433  CandHitDerivative::findStartTick(Waveform::const_iterator maxItr,
434  Waveform::const_iterator startItr) const
435  {
436  Waveform::const_iterator lastItr = maxItr;
437 
438  // If we can't back up then there is nothing to do
439  if (std::distance(startItr, lastItr) > 0) {
440  // In theory, we are starting at a maximum and want to find the "start" of the candidate peak
441  // Ideally we would look to search backward to the point where the (derivative) waveform crosses zero again.
442  // However, the complication is that we need to watch for the case where two peaks are merged together and
443  // we might run through another peak before crossing zero...
444  // So... loop until we hit the startItr...
445  Waveform::const_iterator loopItr = lastItr - 1;
446 
447  while (loopItr != startItr) {
448  // Ideal world case, we cross zero... but we might encounter a minimum... or an inflection point
449  if (*loopItr < 0. || !(*loopItr < *lastItr)) break;
450 
451  lastItr = loopItr--;
452  }
453  }
454  else
455  lastItr = startItr;
456 
457  return lastItr;
458  }
459 
460  ICandidateHitFinder::Waveform::const_iterator
461  CandHitDerivative::findStopTick(Waveform::const_iterator minItr,
462  Waveform::const_iterator stopItr) const
463  {
464  Waveform::const_iterator lastItr = minItr;
465 
466  // If we can't go forward then there is really nothing to do
467  if (std::distance(minItr, stopItr) > 1) {
468  // Pretty much the same strategy as for finding the start tick...
469  Waveform::const_iterator loopItr = lastItr + 1;
470 
471  while (loopItr != stopItr) {
472  // Ideal case that we have crossed zero coming from a minimum... but watch for a maximum as well
473  if (*loopItr > 0. || !(*loopItr > *lastItr)) break;
474 
475  lastItr = loopItr++;
476  }
477  }
478 
479  return lastItr;
480  }
481 
482  DEFINE_ART_CLASS_TOOL(CandHitDerivative)
483 }
void findHitCandidates(const recob::Wire::RegionsOfInterest_t::datarange_t &, const size_t, const size_t, const size_t, HitCandidateVec &) const override
Utilities related to art service access.
This is the interface class for tools/algorithms that perform various operations on waveforms...
walls no right
Definition: selectors.fcl:105
Waveform::const_iterator findNearestMax(Waveform::const_iterator, Waveform::const_iterator) const
const geo::GeometryCore * fGeometry
std::vector< geo::WireID > ChannelToWire(raw::ChannelID_t const channel) const
Returns a list of wires connected to the specified TPC channel.
double distance(geo::Point_t const &point, CathodeDesc_t const &cathode)
Returns the distance of a point from the cathode.
std::unique_ptr< reco_tool::IWaveformTool > fWaveformTool
walls no left
Definition: selectors.fcl:105
Description of geometry of one entire detector.
std::map< size_t, int > fChannelCntMap
tuple dir
Definition: dropbox.py:28
Waveform::const_iterator findStopTick(Waveform::const_iterator, Waveform::const_iterator) const
CandHitDerivative(const fhicl::ParameterSet &pset)
This provides an interface for tools which are tasked with finding candidate hits on input waveforms...
Waveform::const_iterator findStartTick(Waveform::const_iterator, Waveform::const_iterator) const
art::TFileDirectory * fHistDirectory
art::ServiceHandle< art::TFileService > tfs
std::vector< HitCandidateVec > MergeHitCandidateVec
art framework interface to geometry description
BEGIN_PROLOG could also be cout
Waveform::const_iterator findNearestMin(Waveform::const_iterator, Waveform::const_iterator) const
std::vector< HitCandidate > HitCandidateVec
void MergeHitCandidates(const recob::Wire::RegionsOfInterest_t::datarange_t &, const HitCandidateVec &, MergeHitCandidateVec &) const override