Jpp 21.0.0
the software that should make you happy
Loading...
Searching...
No Matches
JMuonPrefit.hh
Go to the documentation of this file.
1#ifndef __JRECONSTRUCTION__JMUONPREFIT__
2#define __JRECONSTRUCTION__JMUONPREFIT__
3
4#include <iostream>
5#include <iomanip>
6#include <vector>
7#include <deque>
8#include <queue>
9#include <algorithm>
10
14
15#include "JTrigger/JHitR1.hh"
16#include "JTrigger/JBuildL0.hh"
17#include "JTrigger/JBuildL2.hh"
19#include "JTrigger/JMatch1D.hh"
20#include "JTrigger/JMatch3B.hh"
21
22#include "JFit/JLine1Z.hh"
24#include "JFit/JMatrixNZ.hh"
25#include "JFit/JVectorNZ.hh"
26#include "JFit/JFitToolkit.hh"
27
31
32#include "JMath/JConstants.hh"
33#include "JMath/JWatershed.hh"
35
36#include "JLang/JPredicate.hh"
37
40
42
45
46#include "Jeep/JMessage.hh"
47
48
49/**
50 * \author mdejong, gmaggi, azegarelli
51 */
52
53namespace JRECONSTRUCTION {}
54namespace JPP { using namespace JRECONSTRUCTION; }
55
56namespace JRECONSTRUCTION {
57
60 using JFIT::JLine1Z;
61 using JFIT::JEstimator;
62 using JFIT::JMatrixNZ;
63 using JFIT::JVectorNZ;
69
70
71 /**
72 * Wrapper class to make pre-fit of muon trajectory.
73 *
74 * The JMuonPrefit fit is used to generate start values for subsequent fits (usually JMuonSimplex and JMuonGandalf).\n
75 * To this end, a scan of directions is made and the time and transverse positions of the track are fitted for each direction (JFIT::JEstimator<JLine1Z>).\n
76 * The directions are spaced by the parameters JMuonPrefitParameters_t::gridAngle_deg.\n
77 * This angle corresponds to the envisaged angular accuracy of the result.\n
78 * The probability that one of the results is less than this angle away from the correct value,
79 * multiple start values should be considered (JMuonPrefitParameters_t::numberOfPrefits).\n
80 * Note that the CPU time scales with the inverse of the square of this angle.\n
81 * The directions are grouped according a course grid of directions.\n
82 * For each group, an alternative solution is maintained which can be used later to resolve possible ambiguities in the event data.\n
83 * The number of groups is approximately equal to JMuonPrefitParameters_t::numberOfPostfits.\n
84 * The chi-squared is based on the time residuals.\n
85 */
86 struct JMuonPrefit :
88 public JEstimator<JLine1Z>
89 {
93
94 using JEstimator_t::operator();
95
96 /**
97 * Input data type.
98 */
99 struct input_type :
100 public JDAQEventHeader
101 {
102 /**
103 * Default constructor.
104 */
106 {}
107
108
109 /**
110 * Constructor.
111 *
112 * \param header header
113 * \param coverage coverage
114 */
116 const coverage_type& coverage) :
117 JDAQEventHeader(header),
119 {}
120
124 };
125
126
127 /**
128 * Constructor
129 *
130 * \param parameters parameters
131 * \param debug debug
132 */
134 const int debug = 0) :
135 JMuonPrefitParameters_t(parameters),
136 omega (parameters.gridAngle_deg * JMATH::PI / 180.0,
137 parameters.numberOfPostfits),
138 debug (debug)
139 {}
140
141
142 /**
143 * Constructor
144 *
145 * \param parameters parameters
146 * \param omega directions
147 * \param debug debug
148 */
150 const JOmega3D& omega,
151 const int debug = 0) :
152 JMuonPrefitParameters_t(parameters),
153 omega (omega, parameters.numberOfPostfits),
154 debug (debug)
155 {}
156
157
158 /**
159 * Get input data.
160 *
161 * \param router module router
162 * \param event event
163 * \param coverage coverage
164 * \return input data
165 */
167 const JDAQEvent& event,
168 const coverage_type& coverage) const
169
170 {
171 using namespace std;
172 using namespace JTRIGGER;
173 using namespace KM3NETDAQ;
174
175 const JBuildL0<hit_type> buildL0;
177
178 input_type input(event.getDAQEventHeader(), coverage);
179
180 buffer_type& dataL0 = input.dataL0;
181 buffer_type& dataL1 = input.dataL1;
182
183 buildL2(event, router, !useL0, back_inserter(dataL1));
184
185 // 3D cluster of unique optical modules
186
188
189 sort(dataL1.begin(), dataL1.end(), hit_type::compare);
190
191 buffer_type::iterator __end = dataL1.end();
192
193 __end = unique(dataL1.begin(), __end, equal_to<JDAQModuleIdentifier>());
194
195 __end = clusterizeWeight(dataL1.begin(), __end, match3B);
196
197 dataL1.erase(__end, dataL1.end());
198
199
200 if (useL0) {
201
202 buildL0(event, router, true, back_inserter(dataL0));
203
204 __end = dataL0.end();
205
206 for (buffer_type::iterator i = dataL0.begin(); i != __end; ) {
207
208 if (match3B.count(*i, dataL1.begin(), dataL1.end()) != 0)
209 ++i;
210 else
211 swap(*i, *--__end);
212 }
213
214 dataL0.erase(__end, dataL0.end());
215 }
216
217 return input;
218 }
219
220
221 /**
222 * Fit function.
223 *
224 * \param input input data
225 * \return fit results
226 */
228 {
229 using namespace std;
230 using namespace JPP;
231
232 const double HIT_OFF = 1.0e3 * sigma_ns * sigma_ns; // [ns^2]
233
235
236 const buffer_type& dataL0 = input.dataL0;
237 const buffer_type& dataL1 = input.dataL1;
238
239 data.reserve(dataL0.size() +
240 dataL1.size());
241
242 JEvent event(JMUONPREFIT);
243
244 vector< deque<JFit> > buffer(omega.size());
245
246 for (size_t index = 0; index != omega.size(); ++index) {
247
248 for (const auto& dir : omega[index]) {
249
250 const JRotation3D R(dir);
251
252
253 buffer_type::iterator __end = copy(dataL1.begin(), dataL1.end(), data.begin());
254
255 for (buffer_type::iterator i = data.begin(); i != __end; ++i) {
256 i->rotate(R);
257 }
258
259 // reduce data
260
261 if (distance(data.begin(), __end) > NMaxHits) {
262
263 buffer_type::iterator __p = data.begin();
264
265 advance(__p, NMaxHits);
266
267 partial_sort(data.begin(), __p, __end, cmz);
268
269 __end = __p;
270 }
271
272 // 1D cluster
273
274 __end = clusterizeWeight(data.begin(), __end, match1D);
275
276 if (useL0 &&
277 distance(data.begin(), __end) < useL0 &&
278 distance(data.begin(), __end) < NMaxHits) {
279
280 buffer_type::iterator p = __end; // begin L0 data
281 buffer_type::iterator q = copy(dataL0.begin(), dataL0.end(), p); // end L0 data
282
283 for (buffer_type::iterator i = p; i != q; ++i) {
284
285 if (find_if(data.begin(), __end, make_predicate(&hit_type::getModuleID, i->getModuleID())) == __end) {
286
287 i->rotate(R);
288
289 if (match1D.count(*i, data.begin(), __end) != 0) {
290 *p = *i;
291 ++p;
292 }
293 }
294 }
295
296 __end = clusterize(__end, p, match1D);
297 }
298
299
300 if (distance(data.begin(), __end) <= NUMBER_OF_PARAMETERS) {
301 continue;
302 }
303
304 // 1D fit
305
306 JLine1Z tz;
307 double chi2 = numeric_limits<double>::max();
308 int NDF = distance(data.begin(), __end) - NUMBER_OF_PARAMETERS;
309 int N = getCount(data.begin(), __end);
310
311 try {
312
313 sort(data.begin(), __end, hit_type::compare);
314
315 (*this)(data.begin(), __end);
316
317 V.set(*this, data.begin(), __end, gridAngle_deg, sigma_ns);
318 Y.set(*this, data.begin(), __end);
319
320 V.invert();
321
322 tz = *this;
323 chi2 = getChi2(Y, V);
324 }
325 catch(const exception& error) {
326 continue;
327 }
328
329 // outlier removal
330
331 if (distance(data.begin(), __end) <= factoryLimit) {
332
333 const int number_of_outliers = min(numberOfOutliers, NDF - 1);
334
335 double ymin = chi2 - STANDARD_DEVIATIONS * STANDARD_DEVIATIONS;
336
337 for (int n = 1; n <= number_of_outliers; ++n) {
338
339 sort(data.begin(), __end, hit_type::compare);
340
341 buffer_type::iterator __end1 = prev(__end, n);
342
343 do {
344
345 try {
346
347 (*this)(data.begin(), __end1);
348
349 V.set(*this, data.begin(), __end1, gridAngle_deg, sigma_ns);
350 Y.set(*this, data.begin(), __end1);
351
352 V.invert();
353
354 double y = getChi2(Y, V);
355
357
358 WARNING(endl << "JMuonPrefit: invalid chi2 " << y << endl);
359
360 } else {
361
362 if (y < 0.0) {
363 y = 0.0;
364 }
365
366 if (y < ymin) {
367 ymin = y;
368 tz = *this;
369 chi2 = ymin;
370 NDF = distance(data.begin(), __end1) - NUMBER_OF_PARAMETERS;
371 N = getCount(data.begin(), __end1);
372 }
373 }
374 }
375 catch(const exception& error) {}
376
377 } while (next_permutation(data.begin(), __end1, __end, hit_type::compare));
378
380 }
381
382 } else {
383
384 const int number_of_outliers = NDF - 1;
385
386 for (int n = 1; n <= number_of_outliers; ++n) {
387
388 double ymax = 0.0;
389 int k = -1;
390
391 for (size_t i = 0; i != Y.size(); ++i) {
392
393 double y = getChi2(Y, V, i);
394
395 if (y > ymax) {
396 ymax = y;
397 k = i;
398 }
399 }
400
402 break;
403 }
404
405 try {
406
407 V.update(k, +HIT_OFF);
408
409 this->update(data.begin(), __end, V);
410
411 Y.set(*this, data.begin(), __end);
412
413 tz = *this;
414 chi2 = getChi2(Y, V);
415 NDF -= 1;
416 N -= getCount(data[k]);
417 }
418 catch(const exception& error) {
419 break;
420 }
421 }
422 }
423
424 tz.rotate_back(R);
425
426 buffer[index].push_back(getFit(event(), tz, dir, getQuality(chi2, N, NDF), NDF));
427
428 // set additional values
429
430 buffer[index].rbegin()->setW(JPP_COVERAGE_ORIENTATION, input.coverage.orientation);
431 buffer[index].rbegin()->setW(JPP_COVERAGE_POSITION, input.coverage.position);
432 }
433 }
434
435
436 JEvt out;
437
438 if (numberOfPrefits > 0) {
439
440 struct element_type { // auxiliary data structure for priority queue
441
442 size_t index;
443 JFit fit;
444
445 struct compare { // priority queue uses reverted comparison
446
447 inline bool operator()(const element_type& first, const element_type& second) const
448 {
449 return qualitySorter(second.fit, first.fit);
450 }
451 };
452 };
453
454 for (auto& i : buffer) {
455
456 auto ws = i.begin();
457
458 if (Qwatershed > 0.0) {
459
460 ws = watershed(i.begin(),
461 i.end(),
462 [](const JFit& fit) { return fit.getQ(); },
463 [](const JFit& first, const JFit& second) { return getAngle(first, second); },
464 Qwatershed);
465 }
466
467 sort(ws, i.end(), qualitySorter);
468 }
469
470 priority_queue<element_type, deque<element_type>, element_type::compare> queue;
471
472 auto move = [&buffer,&queue](size_t i) { // move first element from buffer at given index to output queue
473
474 if (!buffer[i].empty()) {
475
476 queue.push({i, buffer[i].front()});
477
478 buffer[i].pop_front();
479 }
480 };
481
482 for (size_t i = 0; i != buffer.size(); ++i) { // initialise queue
483 move(i);
484 }
485
486 while (!queue.empty() && out.size() < numberOfPrefits) {
487
488 const element_type top = queue.top(); // copy
489
490 queue.pop(); // remove
491
492 out.push_back(top.fit);
493
494 move(top.index); // refill queue
495 }
496
497 if (numberOfPostfits > 0) {
498
499 set<size_t> flag;
500
501 while (!queue.empty()) { // flush queue
502
503 const element_type top = queue.top(); // copy
504
505 queue.pop(); // remove
506
507 out.push_back(top.fit); // store
508
509 flag.insert(top.index);
510 }
511
512 for (size_t i = 0; i != omega.size(); ++i) { // recover missing principle directions
513
514 if (flag.count(i) == 0) {
515
516 const JPointing pointing(omega[i]);
517
518 typedef deque<JFit>::iterator iterator;
519
520 struct { // closest fit
521 double dot;
522 size_t i;
523 iterator p;
524 } xs = { -1.0, 0, buffer[0].end() };
525
526 for (size_t i = 0; i != buffer.size(); ++i) {
527
528 for (iterator p = buffer[i].begin(); p != buffer[i].end(); ++p) {
529
530 const double dot = pointing.getDot(*p);
531
532 if (dot > xs.dot) {
533 xs = { dot, i, p };
534 }
535 }
536 }
537
538 if (xs.p != buffer[xs.i].end()) {
539
540 out.push_back(*xs.p);
541
542 buffer[xs.i].erase(xs.p);
543 }
544 }
545 }
546 }
547
548 } else {
549
550 for (const auto& i : buffer) {
551 for (const auto& fit : i) {
552 out.push_back(fit);
553 }
554 }
555
556 sort(out.begin(), out.end(), qualitySorter);
557 }
558
559 return out;
560 }
561
562
563 /**
564 * Auxiliary data structure for sorting of hits.
565 */
566 static const struct cmz {
567 /**
568 * Sort hits according times corrected for position along z-axis.
569 *
570 * \param first first hit
571 * \param second second hit
572 * \return true if first hit earlier than second hit; else false
573 */
574 template<class T>
575 inline bool operator()(const T& first, const T& second) const
576 {
577 using namespace JPP;
578
579 return (first .getT() * getSpeedOfLight() - first .getZ() <
580 second.getT() * getSpeedOfLight() - second.getZ());
581 }
583
584
586 int debug;
587
588 static constexpr double STANDARD_DEVIATIONS = 3.0; //!< number of standard deviations for outlier removal [unit]
589
590 private:
594 };
595}
596
597#endif
Algorithms for hit clustering and sorting.
Coverage of dynamical detector calibration.
Auxiliary methods to evaluate Poisson probabilities and chi2.
Reduced data structure for L1 hit.
Linear fit of JFIT::JLine1Z.
Match operator for Cherenkov light from muon with given direction.
Match operator for Cherenkov light from muon in any direction.
Mathematical constants.
General purpose messaging.
#define WARNING(A)
Definition JMessage.hh:65
Direct access to module in detector data structure.
std::vector< T >::difference_type distance(typename std::vector< T >::const_iterator first, typename PhysicsEvent::const_iterator< T > second)
Specialisation of STL distance.
Router for direct addressing of module data in detector data structure.
Template definition of linear fit.
Definition JEstimator.hh:25
Data structure for set of track fit results.
Data structure for track fit results with history and optional associated values.
Data structure for fit of straight line paralel to z-axis.
Definition JLine1Z.hh:29
Determination of the co-variance matrix of hits for a track along z-axis (JFIT::JLine1Z).
Definition JMatrixNZ.hh:30
void set(const JVector3D &pos, T __begin, T __end, const double alpha, const double sigma)
Set co-variance matrix.
Definition JMatrixNZ.hh:85
Determination of the time residual vector of hits for a track along z-axis (JFIT::JLine1Z).
Definition JVectorNZ.hh:23
void set(const JLine1Z &track, T __begin, T __end)
Set time residual vector.
Definition JVectorNZ.hh:68
Direction set covering (part of) solid angle.
Definition JOmega3D.hh:68
JPosition3D & rotate_back(const JRotation3D &R)
Rotate back.
Auxiliary class to compare fit results with respect to a reference direction (e.g....
double getDot(const JFit &fit) const
Get dot product.
Template L0 hit builder.
Definition JBuildL0.hh:38
Template L2 builder.
Definition JBuildL2.hh:49
Reduced data structure for L1 hit.
Definition JHitR1.hh:38
1D match criterion.
Definition JMatch1D.hh:33
3D match criterion with road width.
Definition JMatch3B.hh:36
const JDAQEventHeader & getDAQEventHeader() const
Get DAQ event header.
int getModuleID() const
Get module identifier.
static const int JPP_COVERAGE_POSITION
coverage of dynamic position calibration of this event
static const int JPP_COVERAGE_ORIENTATION
coverage of dynamic orientation calibration of this event
double getChi2(const double P)
Get chi2 corresponding to given probability.
size_t getCount(const array_type< T > &buffer, const JCompare_t &compare)
Count number of unique values.
T watershed(T __begin, T __end, const JFunction_t &getValue, const JDistance_t &getDistance, double Y, int N=std::numeric_limits< int >::max())
Watershed algorithm.
Definition JWatershed.hh:29
const double getSpeedOfLight()
Get speed of light.
This name space includes all other name spaces (except KM3NETDAQ, KM3NET and ANTARES).
double getQuality(const double chi2, const int N, const int NDF)
Get quality of fit.
void copy(const JFIT::JEvt::const_iterator __begin, const JFIT::JEvt::const_iterator __end, Evt &out)
Copy tracks.
bool qualitySorter(const JFit &first, const JFit &second)
Comparison of fit results.
JFit getFit(const JHistory &history, const JTrack3D &track, const double Q, const int NDF, const double energy=0.0, const int status=SINGLE_STAGE)
Get fit.
counter_type advance(counter_type &counter, const counter_type value, const counter_type limit=std::numeric_limits< counter_type >::max())
Advance counter.
const int n
Definition JPolint.hh:791
bool next_permutation(T __begin, T __last, T __end, JComparator_t compare, std::bidirectional_iterator_tag)
Implementation of method next_permutation for bidirectional iterators.
Auxiliary classes and methods for triggering.
JHitIterator_t clusterize(JHitIterator_t __begin, JHitIterator_t __end, const JMatch_t &match, const int Nmin=1)
Partition data according given binary match operator.
Definition JAlgorithm.hh:38
JHitIterator_t clusterizeWeight(JHitIterator_t __begin, JHitIterator_t __end, const JMatch_t &match)
Partition data according given binary match operator.
KM3NeT DAQ data structures and auxiliaries.
Definition DataQueue.cc:39
Data structure for coverage of detector by dynamical calibrations.
Definition JCoverage.hh:19
double position
coverage of detector by available position calibration [0,1]
Definition JCoverage.hh:42
double orientation
coverage of detector by available orientation calibration [0,1]
Definition JCoverage.hh:41
Auxiliary class for historical event.
Definition JHistory.hh:40
Group of direction sets.
Definition JOmega3D.hh:197
void update(const size_t k, const double value)
Update inverted matrix at given diagonal element.
Definition JMatrixNS.hh:446
void invert()
Invert matrix according LDU decomposition.
Definition JMatrixNS.hh:75
double ctMin
minimal cosine space angle between PMT axes
int factoryLimit
factory limit for combinatorics
double TMaxLocal_ns
time window for local coincidences [ns]
double gridAngle_deg
grid angle for directions [deg]
Auxiliary data structure for sorting of hits.
bool operator()(const T &first, const T &second) const
Sort hits according times corrected for position along z-axis.
input_type(const JDAQEventHeader &header, const coverage_type &coverage)
Constructor.
Wrapper class to make pre-fit of muon trajectory.
static constexpr double STANDARD_DEVIATIONS
number of standard deviations for outlier removal [unit]
static const struct JRECONSTRUCTION::JMuonPrefit::cmz cmz
input_type getInput(const JModuleRouter &router, const JDAQEvent &event, const coverage_type &coverage) const
Get input data.
JMuonPrefit(const JMuonPrefitParameters_t &parameters, const int debug=0)
Constructor.
JEstimator< JLine1Z > JEstimator_t
JEvt operator()(const input_type &input)
Fit function.
std::vector< hit_type > buffer_type
JMuonPrefit(const JMuonPrefitParameters_t &parameters, const JOmega3D &omega, const int debug=0)
Constructor.
Auxiliary data structure for sorting of hits.
Definition JHitR1.hh:206
Data structure for L2 parameters.