forked from iLCSoft/ConformalTracking
/
ConformalTracking.cc
3097 lines (2621 loc) · 148 KB
/
ConformalTracking.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "ConformalTracking.h"
#include "Cell.h"
#include "KDTree.h"
#include "KalmanTrack.h"
#include <MarlinTrk/Factory.h>
#include <MarlinTrk/IMarlinTrack.h>
#include <MarlinTrk/IMarlinTrkSystem.h>
#include <MarlinTrk/MarlinTrkUtils.h>
#include <EVENT/LCCollection.h>
#include <EVENT/MCParticle.h>
#include <IMPL/LCCollectionVec.h>
#include <IMPL/TrackImpl.h>
#include <IMPL/TrackerHitPlaneImpl.h>
#include <UTIL/ILDConf.h>
#include <UTIL/LCRelationNavigator.h>
#include <UTIL/LCTrackerConf.h>
#include <marlinutil/GeometryUtil.h>
#include <marlin/AIDAProcessor.h>
#include <marlin/Exceptions.h>
#include <marlin/Global.h>
#include <marlin/ProcessorEventSeeder.h>
#include <AIDA/IAnalysisFactory.h>
#include <TCanvas.h>
#include <TLine.h>
#include <TLorentzVector.h>
#include <TStopwatch.h>
#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <iostream>
#include <map>
#include <sstream>
#include <utility>
using namespace lcio;
using namespace marlin;
using namespace std;
using namespace AIDA;
// Static instantiation of the processor
ConformalTracking aConformalTracking;
/*
Pattern recognition code for the CLIC detector, using conformal mapping and cellular automaton
*/
class TooManyTracksException : public marlin::SkipEventException {
public:
TooManyTracksException(Processor* proc) : marlin::SkipEventException(proc) {}
};
ConformalTracking::ConformalTracking(std::string const& procName) : Processor(procName) {}
ConformalTracking::ConformalTracking() : Processor("ConformalTracking") {
// Processor description
_description = "ConformalTracking constructs tracks using a combined conformal mapping and cellular automaton approach.";
// Input collections and parameters
registerParameters();
registerInputCollections(LCIO::TRACKERHITPLANE, "MainTrackerHitCollectionNames",
"Name of the TrackerHit input collections from the Main Tracker",
m_inputMainTrackerHitCollections,
{"ITrackerHits", "OTrackerHits", "ITrackerEndcapHits", "OTrackerEndcapHits"});
registerInputCollections(LCIO::TRACKERHITPLANE, "VertexBarrelHitCollectionNames",
"Name of the TrackerHit input collections from the Vertex Barrel", m_inputVertexBarrelCollections,
{"VXDTrackerHits"});
registerInputCollections(LCIO::TRACKERHITPLANE, "VertexEndcapHitCollectionNames",
"Name of the TrackerHit input collections from the Vertex Endcap", m_inputVertexEndcapCollections,
{"VXDEndcapTrackerHits"});
// Parameters for tracking
registerProcessorParameter("MaxCellAngle", "Cut on angle between two cells for cell to be valid", m_maxCellAngle,
double(0.035));
registerProcessorParameter("MaxCellAngleRZ", "Cut on angle between two cells in RZ for cell to be valid", m_maxCellAngleRZ,
double(0.035));
registerProcessorParameter("MaxDistance", "Maximum length of a cell (max. distance between two hits)", m_maxDistance,
double(0.015));
registerProcessorParameter("HighPTCut", "pT threshold (in GeV) for enabling extendHighPT in extendTracks", m_highPTcut,
double(10.0));
registerProcessorParameter("MaxChi2", "Maximum chi2/ndof for linear conformal tracks", m_chi2cut, double(300.));
registerProcessorParameter("MinClustersOnTrack", "Minimum number of clusters to create a track in pattern recognition",
m_minClustersOnTrack, int(6));
registerProcessorParameter("EnableTightCutsVertexCombined",
"Enabled tight cuts as first step of reconstruction in vertex b+e [TMP!!]", m_enableTCVC,
bool(true));
}
void ConformalTracking::registerParameters() {
std::vector<std::string> inputTrackerHitCollections = {"VXDTrackerHits", "VXDEndcapTrackerHits", "ITrackerHits",
"OTrackerHits", "ITrackerEndcapHits", "OTrackerEndcapHits"};
registerInputCollections(LCIO::TRACKERHITPLANE, "TrackerHitCollectionNames", "Name of the TrackerHit input collections",
m_inputTrackerHitCollections, inputTrackerHitCollections);
// Debugging collections - MC particles and relation collections
registerInputCollection(LCIO::MCPARTICLE, "MCParticleCollectionName", "Name of the MCParticle input collection",
m_inputParticleCollection, std::string(""));
std::vector<std::string> inputRelationCollections = {"VXDTrackerHitRelations", "VXDEndcapTrackerHitRelations",
"InnerTrackerBarrelHitsRelations", "OuterTrackerBarrelHitsRelations",
"InnerTrackerEndcapHitsRelations", "OuterTrackerEndcapHitsRelations"};
registerInputCollections(LCIO::LCRELATION, "RelationsNames", "Name of the TrackerHit relation collections",
m_inputRelationCollections, inputRelationCollections);
// Output collections - tracks
registerOutputCollection(LCIO::TRACK, "SiTrackCollectionName", "Silicon track Collection Name", m_outputTrackCollection,
std::string("CATracks"));
registerOutputCollection(LCIO::TRACKERHITPLANE, "DebugHits", "DebugHits", m_outputDebugHits, std::string("DebugHits"));
registerProcessorParameter("DebugPlots", "Plots for debugging the tracking", m_debugPlots, bool(false));
registerProcessorParameter("DebugTiming", "Print out time profile", m_debugTime, bool(false));
// Parameters for tracking
registerProcessorParameter("RetryTooManyTracks", "retry with tightened parameters, when too many tracks are being created",
m_retryTooManyTracks, m_retryTooManyTracks);
registerProcessorParameter("TooManyTracks", "Number of tracks that is considered too many", m_tooManyTracks,
m_tooManyTracks);
registerProcessorParameter("SortTreeResults", "sort results from kdtree search", m_sortTreeResults, m_sortTreeResults);
registerProcessorParameter("trackPurity", "Purity value used for checking if tracks are real or not", m_purity,
double(0.75));
registerProcessorParameter("ThetaRange", "Angular range for initial cell seeding", m_thetaRange, double(0.1));
registerProcessorParameter("MinClustersOnTrackAfterFit", "Final minimum number of track clusters",
m_minClustersOnTrackAfterFit, int(4));
registerProcessorParameter("MaxHitInvertedFit", "Maximum number of track hits to try the inverted fit", m_maxHitsInvFit,
int(0));
}
void ConformalTracking::init() {
// Print the initial parameters
printParameters();
parseStepParameters();
// Reset counters
m_runNumber = 0;
m_eventNumber = 0;
// Set up the track fit factory
trackFactory = MarlinTrk::Factory::createMarlinTrkSystem("DDKalTest", nullptr, "");
trackFactory->setOption(MarlinTrk::IMarlinTrkSystem::CFG::useQMS, true);
trackFactory->setOption(MarlinTrk::IMarlinTrkSystem::CFG::usedEdx, true);
trackFactory->setOption(MarlinTrk::IMarlinTrkSystem::CFG::useSmoothing, false);
trackFactory->init();
// Put default values for track fitting
m_initialTrackError_d0 = 1.e6;
m_initialTrackError_phi0 = 1.e2;
m_initialTrackError_omega = 1.e-4;
m_initialTrackError_z0 = 1.e6;
m_initialTrackError_tanL = 1.e2;
m_maxChi2perHit = 1.e2;
// Get the magnetic field
m_magneticField = MarlinUtil::getBzAtOrigin(); // z component at (0,0,0)
// Seed hit for debug printouts. If not set later, isn't used
debugSeed = nullptr;
// Initialise histograms (if debug plotting on)
if (m_debugPlots) {
// Automatically add histograms to output root file
AIDAProcessor::histogramFactory(this);
// Histogram initailisation
m_szDistribution = new TH2F("m_szDistribution", "m_szDistribution", 20000, -100, 100, 200, -10, 10);
m_uvDistribution = new TH2F("m_uvDistribution", "m_uvDistribution", 1000, -0.05, 0.05, 1000, -0.05, 0.05);
m_xyDistribution = new TH2F("m_xyDistribution", "m_xyDistribution", 500, -1500, 1500, 500, -1500, 1500);
m_xyzDistribution = new TH3F("m_xyzDistribution", "m_xyzDistribution", 50, 0, 100, 50, 0, 100, 100, 0, 25);
// Histograms for neighbors parameters
m_X = new TH1F("m_X", "m_X", 500, -1500, 1500);
m_Y = new TH1F("m_Y", "m_Y", 500, -1500, 1500);
m_Z = new TH1F("m_Z", "m_Z", 500, -2500, 2500);
m_neighX = new TH1F("m_neighX", "m_neighX", 500, -1500, 1500);
m_neighY = new TH1F("m_neighY", "m_neighY", 500, -1500, 1500);
m_neighZ = new TH1F("m_neighZ", "m_neighZ", 500, -2500, 2500);
m_slopeZ = new TH1F("m_slopeZ", "m_slopeZ", 1000, -100, 100);
m_slopeZ_true = new TH1F("m_slopeZ_true", "m_slopeZ_true", 1000, -100, 100);
m_slopeZ_true_first = new TH1F("m_slopeZ_true_first", "m_slopeZ_true_first", 1000, -100, 100);
m_slopeZ_vs_pt_true = new TH2F("m_diffZ_pt_true_first", "m_diffZ_pt_true_first", 2000, -500, 500, 400, 0, 100);
// Histograms for tuning parameters (cell angle cut, cell length cut)
m_cellAngle = new TH1F("cellAngle", "cellAngle", 1250, 0, 0.05);
m_cellDOCA = new TH1F("cellDOCA", "cellDOCA", 100., 0, 0.1);
m_cellAngleRadius = new TH2F("cellAngleRadius", "cellAngleRadius", 400, 0, 0.04, 1000, 0, 0.04);
m_cellLengthRadius = new TH2F("cellLengthRadius", "cellLengthRadius", 300, 0, 0.03, 1000, 0, 0.04);
m_cellAngleLength = new TH2F("cellAngleLength", "cellAngleLength", 400, 0, 0.04, 300, 0, 0.03);
m_conformalChi2 = new TH1F("conformalChi2", "conformalChi2", 100, 0, 100);
m_conformalChi2real = new TH1F("conformalChi2real", "conformalChi2real", 1000, 0, 1000);
m_conformalChi2fake = new TH1F("conformalChi2fake", "conformalChi2fake", 1000, 0, 1000);
m_conformalChi2Purity = new TH2F("conformalChi2Purity", "conformalChi2Purity", 150, 0, 1.5, 1000, 0, 1000);
m_conformalChi2MC = new TH1F("conformalChi2MC", "conformalChi2MC", 1000, 0, 1000);
m_conformalChi2PtMC = new TH2F("conformalChi2PtMC", "conformalChi2PtMC", 1000, 0, 1000, 1000, 0, 100);
m_conformalChi2VertexRMC = new TH2F("conformalChi2VertexRMC", "conformalChi2VertexRMC", 1000, 0, 1000, 100, 0, 100);
m_conformalChi2SzMC = new TH1F("conformalChi2SzMC", "conformalChi2SzMC", 1000, 0, 1000);
m_conformalChi2SzPtMC = new TH2F("conformalChi2SzPtMC", "conformalChi2SzPtMC", 1000, 0, 1000, 1000, 0, 100);
m_conformalChi2SzVertexRMC =
new TH2F("conformalChi2SzVertexRMC", "conformalChi2SzVertexRMC", 1000, 0, 1000, 100, 0, 100);
m_cellAngleMC = new TH1F("cellAngleMC", "cellAngleMC", 1250, 0, 0.05);
m_cellDOCAMC = new TH1F("cellDOCAMC", "cellDOCAMC", 100., 0, 0.1);
m_cellAngleRadiusMC = new TH2F("cellAngleRadiusMC", "cellAngleRadiusMC", 400, 0, 0.04, 1000, 0, 0.04);
m_cellLengthRadiusMC = new TH2F("cellLengthRadiusMC", "cellLengthRadiusMC", 300, 0, 0.03, 1000, 0, 0.04);
m_cellAngleLengthMC = new TH2F("cellAngleLengthMC", "cellAngleLengthMC", 400, 0, 0.04, 300, 0, 0.03);
m_cellAngleRZMC = new TH1F("cellAngleRZMC", "cellAngleRZMC", 1250, 0, 0.05);
// Histograms for "event display"
m_conformalEvents = new TH2F("conformalEvents", "conformalEvents", 1000, -0.05, 0.05, 1000, -0.05, 0.05);
m_nonconformalEvents = new TH2F("nonconformalEvents", "nonconformalEvents", 500, -1500, 1500, 500, -1500, 1500);
m_conformalEventsRTheta = new TH2F("conformalEventsRTheta", "conformalEventsRTheta", 200, 0, 0.05, 632, -0.02, 6.30);
m_conformalEventsMC = new TH2F("conformalEventsMC", "conformalEventsMC", 1000, -0.05, 0.05, 1000, -0.05, 0.05);
m_canvConformalEventDisplay = new TCanvas("canvConformalEventDisplay", "canvConformalEventDisplay");
m_canvConformalEventDisplayAllCells =
new TCanvas("canvConformalEventDisplayAllCells", "canvConformalEventDisplayAllCells");
m_canvConformalEventDisplayAcceptedCells =
new TCanvas("canvConformalEventDisplayAcceptedCells", "canvConformalEventDisplayAcceptedCells");
m_canvConformalEventDisplayMC = new TCanvas("canvConformalEventDisplayMC", "canvConformalEventDisplayMC");
m_canvConformalEventDisplayMCunreconstructed =
new TCanvas("canvConformalEventDisplayMCunreconstructed", "canvConformalEventDisplayMCunreconstructed");
}
// Initialize timing monitoring histograms
if (m_debugTime) {
for (auto const& parameters : _stepParameters) {
char axes[100];
sprintf(axes, ";Time [ms];Step %d iterations", parameters._step);
char hname[100];
sprintf(hname, "timing_buildNewTracks_%d", parameters._step);
m_timing_buildNewTracks.push_back(new TH1F(hname, axes, 1e4, 0, 1e7));
sprintf(hname, "timing_buildNewTracks_neighbourSearch_%d", parameters._step);
m_timing_buildNewTracks_neighbourSearch.push_back(new TH1F(hname, axes, 1e4, 0, 1e4));
sprintf(hname, "timing_buildNewTracks_seeding_%d", parameters._step);
m_timing_buildNewTracks_seeding.push_back(new TH1F(hname, axes, 1e4, 0, 10));
sprintf(hname, "timing_buildNewTracks_extending_%d", parameters._step);
m_timing_buildNewTracks_extending.push_back(new TH1F(hname, axes, 1e4, 0, 5e3));
sprintf(hname, "timing_buildNewTracks_fitting_%d", parameters._step);
m_timing_buildNewTracks_fitting.push_back(new TH1F(hname, axes, 1e4, 0, 1e2));
sprintf(hname, "timing_buildNewTracks_seed_sort_%d", parameters._step);
m_timing_buildNewTracks_seed_sort.push_back(new TH1F(hname, axes, 1e4, 0, 10));
sprintf(hname, "timing_buildNewTracks_seed_total_%d", parameters._step);
m_timing_buildNewTracks_seed_total.push_back(new TH1F(hname, axes, 1e4, 0, 5e3));
sprintf(hname, "timing_extendTracks_%d", parameters._step);
m_timing_extendTracks.push_back(new TH1F(hname, axes, 1e4, 0, 1e7));
sprintf(hname, "timing_extendTracks_extendTracksPerLayer_%d", parameters._step);
m_timing_extendTracks_extendTracksPerLayer.push_back(new TH1F(hname, axes, 1e4, 0, 1e2));
sprintf(hname, "timing_extendTracks_extendTrack_%d", parameters._step);
m_timing_extendTracks_extendTrack.push_back(new TH1F(hname, axes, 1e4, 0, 1e2));
}
}
// Register this process
Global::EVENTSEEDER->registerProcessor(this);
}
void ConformalTracking::parseStepParameters() {
fillCollectionIndexVectors();
int step = 0;
// Build tracks in the vertex barrel
Parameters initialParameters(m_vertexBarrelHits, m_maxCellAngle, m_maxCellAngleRZ, m_chi2cut, m_minClustersOnTrack,
m_maxDistance, m_slopeZRange, m_highPTcut, /*highPT*/ true, /*OnlyZS*/ false,
/*rSearch*/ false,
/*vtt*/ true, /*kalmanFitForward*/ true, step++,
/*combine*/ true, /*build*/ true, /*extend*/ false, /*sort*/ false);
// Extend through the endcap
Parameters parameters2(m_vertexEndcapHits, m_maxCellAngle, m_maxCellAngleRZ, m_chi2cut, m_minClustersOnTrack,
m_maxDistance, m_slopeZRange, m_highPTcut, /*highPT*/ true, /*OnlyZS*/ false,
/*rSearch*/ false, /*vtt*/ true,
/*kalmanFitForward*/ true, step++,
/*combine*/ true, /*build*/ false, /*extend*/ true, /*sort*/ false);
// Make combined vertex tracks
Parameters parametersTCVC(m_vertexCombinedHits, m_maxCellAngle, m_maxCellAngleRZ, m_chi2cut, m_minClustersOnTrack,
m_maxDistance, m_slopeZRange, m_highPTcut, /*highPT*/ true, /*OnlyZS*/ false,
/*rSearch*/ false, /*vtt*/ true,
/*kalmanFitForward*/ true, step++,
/*combine*/ true, /*build*/ true, /*extend*/ false, /*sort*/ false);
// Make leftover tracks in the vertex with lower requirements
// 1. open the cell angles
Parameters lowerCellAngleParameters(m_vertexCombinedHits, m_maxCellAngle * 5.0, m_maxCellAngleRZ * 5.0, m_chi2cut,
m_minClustersOnTrack, m_maxDistance, m_slopeZRange, m_highPTcut,
/*highPT*/ true, /*OnlyZS*/ false,
/*rSearch*/ true, /*vtt*/ true, /*kalmanFitForward*/ true, step++,
/*combine*/ not m_enableTCVC, /*build*/ true, /*extend*/ false, /*sort*/ false);
// 2. open further the cell angles and increase the chi2cut
Parameters lowerCellAngleParameters2({}, m_maxCellAngle * 10.0, m_maxCellAngleRZ * 10.0, m_chi2cut * 20.0,
m_minClustersOnTrack, m_maxDistance, m_slopeZRange, m_highPTcut,
/*highPT*/ true, /*OnlyZS*/ false,
/*rSearch*/ true, /*vtt*/ true, /*kalmanFitForward*/ true, step++,
/*combine*/ false, /*build*/ true, /*extend*/ false, /*sort*/ false);
// 3. min number of hits on the track = 4
Parameters lowNumberHitsParameters({}, m_maxCellAngle * 10.0, m_maxCellAngleRZ * 10.0, m_chi2cut * 20.0,
/*m_minClustersOnTrack*/ 4, m_maxDistance, m_slopeZRange, m_highPTcut,
/*highPT*/ true,
/*OnlyZS*/ false,
/*rSearch*/ true, /*vtt*/ true, /*kalmanFitForward*/ true, step++,
/*combine*/ false, /*build*/ true, /*extend*/ false, /*sort*/ true);
// Extend through inner and outer trackers
Parameters trackerParameters(m_trackerHits, m_maxCellAngle * 10.0, m_maxCellAngleRZ * 10.0, m_chi2cut * 20.0,
/*m_minClustersOnTrack*/ 4, m_maxDistance, m_slopeZRange, /*highPTcut*/ 1.0,
/*highPT*/ true,
/*OnlyZS*/ false,
/*rSearch*/ true, /*vtt*/ true, /*kalmanFitForward*/ true, step++,
/*combine*/ true, /*build*/ false, /*extend*/ true, /*sort*/ false);
// Finally reconstruct displaced tracks
Parameters displacedParameters(m_allHits, m_maxCellAngle * 10.0, m_maxCellAngleRZ * 10.0, m_chi2cut * 10.0,
/*m_minClustersOnTrack*/ 5, 0.015, m_slopeZRange, m_highPTcut,
/*highPT*/ false, /*OnlyZS*/ true,
/*rSearch*/ true,
/*vtt*/ false, /*kalmanFitForward*/ true, step++,
/*combine*/ true, /*build*/ true, /*extend*/ false, /*sort*/ false);
_stepParameters.push_back(initialParameters);
_stepParameters.push_back(parameters2);
if (m_enableTCVC) {
_stepParameters.push_back(parametersTCVC);
}
_stepParameters.push_back(lowerCellAngleParameters);
_stepParameters.push_back(lowerCellAngleParameters2);
_stepParameters.push_back(lowNumberHitsParameters);
_stepParameters.push_back(trackerParameters);
_stepParameters.push_back(displacedParameters);
}
// The main code, run over each event
void ConformalTracking::processEvent(LCEvent* evt) {
//------------------------------------------------------------------------------------------------------------------
// This pattern recognition algorithm is based on two concepts: conformal mapping and cellular automaton. Broadly
// speaking, the 2D xy projection of all hits is transformed such that circles (helix projections) become straight
// lines. The tracking is then considered as a 2D straight line search, using the z information to reduce
// combinatorics.
//
// The hits from each input collection are transformed into conformal hit positions, with some binary trees created
// to allow fast nearest neighbour calculations. All hits are then considered as seeds (starting from outer radius)
// and an attempt to make cells leading back to this seed is carried out. If a long enough chain of cells can be
// produced, this is defined as a track and the hits contained are all removed from further consideration. Once all
// hits in a collection have been considered, the next collection of hits is added to the unused hits and the search
// for new tracks begin again (first an attempt to extend existing tracks is performed, followed by a new search
// using all unused hits as seeding points).
//
// Where several paths are possible back to the seed position, the candidate with lowest chi2/ndof is chosen.
//------------------------------------------------------------------------------------------------------------------
streamlog_out(DEBUG9) << "Event number: " << m_eventNumber << std::endl;
// Set up ID decoder
UTIL::BitField64 m_encoder(lcio::LCTrackerCellID::encoding_string());
// Object to store all of the track hit collections passed to the pattern recognition
std::vector<LCCollection*> trackerHitCollections;
std::vector<SLCRelationNavigator> relations;
LCCollection* particleCollection;
// Loop over each input collection and get the hits
for (unsigned int collection = 0; collection < m_inputTrackerHitCollections.size(); collection++) {
// Get the collection of tracker hits
LCCollection* trackerHitCollection = 0;
getCollection(trackerHitCollection, m_inputTrackerHitCollections[collection], evt);
if (trackerHitCollection == 0)
continue;
streamlog_out(DEBUG9) << "Collection " << m_inputTrackerHitCollections[collection] << " contains "
<< trackerHitCollection->getNumberOfElements() << " hits" << std::endl;
trackerHitCollections.push_back(trackerHitCollection);
// If debugging, get the relations between tracker hits and MC particle
if (m_debugPlots) {
// Get the collection of tracker hit relations
LCCollection* trackerHitRelationCollection = 0;
getCollection(trackerHitRelationCollection, m_inputRelationCollections[collection], evt);
if (trackerHitRelationCollection == 0)
continue;
// Create the relations navigator
auto relation = std::make_shared<LCRelationNavigator>(trackerHitRelationCollection);
relations.push_back(std::move(relation));
}
}
// Get the MC particle collection
getCollection(particleCollection, m_inputParticleCollection, evt);
// Make the output track collection
auto trackCollection = std::unique_ptr<LCCollectionVec>(new LCCollectionVec(LCIO::TRACK));
auto debugHitCollection = std::unique_ptr<LCCollectionVec>(new LCCollectionVec(LCIO::TRACKERHITPLANE));
debugHitCollection->setSubset(true);
// Enable the track collection to point back to hits
LCFlagImpl trkFlag(0);
trkFlag.setBit(LCIO::TRBIT_HITS);
trackCollection->setFlag(trkFlag.getFlag());
//------------------------------------------------------------------------------
// Make the collection of conformal hits that will be used, with a link back to
// the corresponding tracker hit.
//------------------------------------------------------------------------------
// Collections to be stored throughout the tracking
std::map<int, SharedKDClusters> collectionClusters; // Conformal hits
std::map<SKDCluster, TrackerHitPlane*> kdClusterMap; // Their link to "real" hits
std::map<TrackerHitPlane*, SKDCluster> conformalHits; // The reverse link
// Debug collections (not filled if debug off)
std::map<MCParticle*, SharedKDClusters> particleHits; // List of conformal hits on each MC particle
std::map<MCParticle*, bool> reconstructed; // Check for MC particles
SharedKDClusters debugHits; // Debug hits for plotting
if (m_debugPlots) {
m_debugger.clear();
m_debugger.setRelations(relations);
}
// Create the conformal hit collections for each tracker hit collection (and save the link)
for (unsigned int collection = 0; collection < trackerHitCollections.size(); collection++) {
// Loop over tracker hits and make conformal hit collection
SharedKDClusters tempClusters;
int nHits = trackerHitCollections[collection]->getNumberOfElements();
for (int itHit = 0; itHit < nHits; itHit++) {
// Get the hit
TrackerHitPlane* hit = dynamic_cast<TrackerHitPlane*>(trackerHitCollections[collection]->getElementAt(itHit));
// Get subdetector information and check if the hit is in the barrel or endcaps
const int celId = hit->getCellID0();
m_encoder.setValue(celId);
int subdet = m_encoder[lcio::LCTrackerCellID::subdet()];
int side = m_encoder[lcio::LCTrackerCellID::side()];
int layer = m_encoder[lcio::LCTrackerCellID::layer()];
int module = m_encoder[lcio::LCTrackerCellID::module()];
int sensor = m_encoder[lcio::LCTrackerCellID::sensor()];
bool isEndcap = false;
bool forward = false;
if (side != ILDDetID::barrel) {
isEndcap = true;
if (side == ILDDetID::fwd)
forward = true;
}
// Make a new kd cluster
auto kdhit = std::make_shared<KDCluster>(hit, isEndcap, forward);
// Set the subdetector information
kdhit->setDetectorInfo(subdet, side, layer, module, sensor);
// Store the link between the two
kdClusterMap[kdhit] = hit;
conformalHits[hit] = kdhit;
tempClusters.push_back(kdhit);
// Store the MC link if in debug mode
if (m_debugPlots) {
// Get the related simulated hit(s)
const LCObjectVec& simHitVector = relations[collection]->getRelatedToObjects(hit);
// Take the first hit only (TODO: this should be changed? Loop over all related simHits and add an entry for each mcparticle so that this hit is in each fit?)
SimTrackerHit* simHit = dynamic_cast<SimTrackerHit*>(simHitVector.at(0));
// Get the particle belonging to that hit
MCParticle* particle = simHit->getMCParticle();
// Store the information (not for secondaries)
kdParticles[kdhit] = particle;
kdSimHits[kdhit] = simHit;
if (!simHit->isProducedBySecondary()) {
particleHits[particle].push_back(kdhit);
}
m_debugger.registerHit(collection, kdhit, hit);
// Draw plots for event 0
if (m_eventNumber == 0) {
m_conformalEvents->Fill(kdhit->getU(), kdhit->getV());
m_nonconformalEvents->Fill(hit->getPosition()[0], hit->getPosition()[1]);
m_conformalEventsRTheta->Fill(kdhit->getR(), kdhit->getTheta());
}
// Set debug hit if required
// if (kdhit->getX() < (-537.4) && kdhit->getX() > (-537.5) && kdhit->getY() < (-144.5) && kdhit->getY() > (-144.6))
// debugSeed = kdhit;
}
}
collectionClusters[collection] = tempClusters;
}
// WHAT TO DO ABOUT THIS?? POSSIBLY MOVE DEPENDING ON MC RECONSTRUCTION (and in fact, would fit better into the check reconstruction code at present)
// Now loop over all MC particles and make the cells connecting hits
if (m_debugPlots) {
int nParticles = particleCollection->getNumberOfElements();
for (int itP = 0; itP < nParticles; itP++) {
// Get the particle
MCParticle* mcParticle = dynamic_cast<MCParticle*>(particleCollection->getElementAt(itP));
// Get the vector of hits from the container
if (particleHits.count(mcParticle) == 0)
continue;
SharedKDClusters trackHits = m_debugger.getAssociatedHits(mcParticle); //particleHits[mcParticle];
// Only make tracks with n or more hits
if (trackHits.size() < (unsigned int)m_minClustersOnTrack)
continue;
// Discard low momentum particles
double particlePt = sqrt(mcParticle->getMomentum()[0] * mcParticle->getMomentum()[0] +
mcParticle->getMomentum()[1] * mcParticle->getMomentum()[1]);
// Cut on stable particles
if (mcParticle->getGeneratorStatus() != 1)
continue;
// Sort the hits from larger to smaller radius
std::sort(trackHits.begin(), trackHits.end(), sort_by_radiusKD);
// Make a track
auto pars = _stepParameters[0];
auto mcTrack = std::unique_ptr<KDTrack>(new KDTrack(pars));
// Loop over all hits for debugging
for (auto const& cluster : trackHits) {
// Get the conformal clusters
mcTrack->add(cluster);
}
// Fit the track and plot the chi2
mcTrack->linearRegression();
mcTrack->linearRegressionConformal();
m_conformalChi2MC->Fill(mcTrack->chi2ndof());
m_conformalChi2PtMC->Fill(mcTrack->chi2ndof(), particlePt);
m_conformalChi2SzMC->Fill(mcTrack->chi2ndofZS());
m_conformalChi2SzPtMC->Fill(mcTrack->chi2ndofZS(), particlePt);
double mcVertexX = mcParticle->getVertex()[0];
double mcVertexY = mcParticle->getVertex()[1];
double mcVertexR = sqrt(pow(mcVertexX, 2) + pow(mcVertexY, 2));
m_conformalChi2VertexRMC->Fill(mcTrack->chi2ndof(), mcVertexR);
m_conformalChi2SzVertexRMC->Fill(mcTrack->chi2ndofZS(), mcVertexR);
// Now loop over the hits and make cells - filling histograms along the way
int nHits = trackHits.size();
for (int itHit = 0; itHit < (nHits - 2); itHit++) {
// Get the conformal clusters
SKDCluster cluster0 = trackHits[itHit];
SKDCluster cluster1 = trackHits[itHit + 1];
SKDCluster cluster2 = trackHits[itHit + 2];
// Make the two cells connecting these three hits
auto cell = std::make_shared<Cell>(cluster0, cluster1);
cell->setWeight(itHit);
auto cell1 = std::make_shared<Cell>(cluster1, cluster2);
cell1->setWeight(itHit + 1);
if (itHit == 0)
m_cellDOCAMC->Fill(cell->doca());
// Fill the debug/tuning plots
double angleBetweenCells = cell->getAngle(cell1);
double angleRZBetweenCells = cell->getAngleRZ(cell1);
double cell0Length = sqrt(pow(cluster0->getU() - cluster1->getU(), 2) + pow(cluster0->getV() - cluster1->getV(), 2));
double cell1Length = sqrt(pow(cluster1->getU() - cluster2->getU(), 2) + pow(cluster1->getV() - cluster2->getV(), 2));
m_cellAngleMC->Fill(angleBetweenCells);
m_cellAngleRadiusMC->Fill(cluster2->getR(), angleBetweenCells);
m_cellLengthRadiusMC->Fill(cluster0->getR(), cell0Length);
m_cellAngleLengthMC->Fill(cell1Length, angleBetweenCells);
m_cellAngleRZMC->Fill(angleRZBetweenCells);
// Draw cells on the first event
if (m_eventNumber == 0) {
// Fill the event display (hit positions)
m_conformalEventsMC->Fill(cluster0->getU(), cluster0->getV());
m_conformalEventsMC->Fill(cluster1->getU(), cluster1->getV());
m_conformalEventsMC->Fill(cluster2->getU(), cluster2->getV());
// Draw the cell lines on the event display. Use the line style to show
// if the cells would have been cut by some of the search criteria
m_canvConformalEventDisplayMC->cd();
if (itHit == 0) {
drawline(cluster0, cluster1, itHit + 1);
}
// Draw line style differently if the cell angle was too large
if (angleBetweenCells > (m_maxCellAngle)) {
drawline(cluster1, cluster2, itHit + 2, 3);
} else {
drawline(cluster1, cluster2, itHit + 2);
}
}
}
}
}
// Draw the final set of conformal hits (on top of the cell lines)
if (m_eventNumber == 0 && m_debugPlots) {
m_canvConformalEventDisplayMC->cd();
m_conformalEventsMC->DrawCopy("same");
// Draw the non-MC event display
m_canvConformalEventDisplay->cd();
m_conformalEvents->DrawCopy("");
m_canvConformalEventDisplayAllCells->cd();
m_conformalEvents->DrawCopy("");
m_canvConformalEventDisplayAcceptedCells->cd();
m_conformalEvents->DrawCopy("");
m_canvConformalEventDisplayMC->cd();
m_conformalEvents->DrawCopy("");
m_canvConformalEventDisplayMCunreconstructed->cd();
m_conformalEvents->DrawCopy("");
}
// END OF "WHAT TO DO ABOUT THIS??"
//------------------------------------------------------------------------------
// Now the track reconstruction strategy. Perform a sequential search, with hits
// removed from the seeding collections once tracks have been built
//------------------------------------------------------------------------------
// The final vector of conformal tracks
UniqueKDTracks conformalTracks;
SharedKDClusters kdClusters;
UKDTree nearestNeighbours = nullptr;
for (auto const& parameters : _stepParameters) {
runStep(kdClusters, nearestNeighbours, conformalTracks, collectionClusters, parameters);
streamlog_out(DEBUG9) << "STEP " << parameters._step << ": nr tracks = " << conformalTracks.size() << std::endl;
if (streamlog_level(DEBUG9)) {
for (auto const& confTrack : conformalTracks) {
streamlog_out(DEBUG9) << "- Track " << &confTrack << " has " << confTrack->m_clusters.size() << " hits" << std::endl;
for (unsigned int ht = 0; ht < confTrack->m_clusters.size(); ht++) {
SKDCluster const& kdhit = confTrack->m_clusters.at(ht);
streamlog_out(DEBUG9) << "-- Hit " << ht << ": [x,y,z] = [" << kdhit->getX() << ", " << kdhit->getY() << ", "
<< kdhit->getZ() << "]" << std::endl;
}
}
}
}
// Clean up
nearestNeighbours.reset(nullptr);
// Now in principle have all conformal tracks, but due to how the check for clones is performed (ish) there is a possibility
// that clones/fakes are still present. Try to remove them by looking at overlapping hits. Turned off at the moment
// if the conformalTracks objects needs to be used, this needs to be changed a lot
UniqueKDTracks conformalTracksFinal = std::move(conformalTracks);
// Sort the tracks by length, so that the longest are kept
/*std::sort(conformalTracks.begin(),conformalTracks.end(),sort_by_length);
for(int existingTrack=0;existingTrack<conformalTracks.size();existingTrack++){
bool clone = false; bool saved = false;
for(int savedTrack=0;savedTrack<conformalTracksFinal.size();savedTrack++){
const int nOverlappingHits = overlappingHits(conformalTracks[existingTrack],conformalTracksFinal[savedTrack]);
if( nOverlappingHits >= 2) {
clone = true;
// Calculate the new and existing chi2 values
double newchi2 = (conformalTracks[existingTrack]->chi2ndofZS()*conformalTracks[existingTrack]->chi2ndofZS() + conformalTracks[existingTrack]->chi2ndof()*conformalTracks[existingTrack]->chi2ndof());
double oldchi2 = (conformalTracksFinal[savedTrack]->chi2ndofZS()*conformalTracksFinal[savedTrack]->chi2ndofZS() + conformalTracksFinal[savedTrack]->chi2ndof()*conformalTracksFinal[savedTrack]->chi2ndof());
double deltachi2ZS = (conformalTracks[existingTrack]->chi2ndofZS()-conformalTracksFinal[savedTrack]->chi2ndofZS());
double deltachi2 = (conformalTracks[existingTrack]->chi2ndof()-conformalTracksFinal[savedTrack]->chi2ndof());
// If the new track is a subtrack of an existing track, don't consider it further (already try removing bad hits from tracks
if(nOverlappingHits == conformalTracks[existingTrack]->m_clusters.size()) break;
// Otherwise take the longest if the delta chi2 is not too much
else if(conformalTracks[existingTrack]->m_clusters.size() >= conformalTracksFinal[savedTrack]->m_clusters.size()){ // New track longer/equal in length
// Increase in chi2 is too much (double)
if( (newchi2 - oldchi2) > oldchi2) break;
// Otherwise take it
delete conformalTracksFinal[savedTrack];
conformalTracksFinal[savedTrack] = conformalTracks[existingTrack]; saved = true;
}
else if(conformalTracks[existingTrack]->m_clusters.size() < conformalTracksFinal[savedTrack]->m_clusters.size()){ // Old track longer
// Must improve chi2 by factor two
if( (newchi2 - 0.5*oldchi2) > 0.) break;
// Otherwise take it
delete conformalTracksFinal[savedTrack];
conformalTracksFinal[savedTrack] = conformalTracks[existingTrack]; saved = true;
}
break;
}
}
if(!clone){
conformalTracksFinal.push_back(conformalTracks[existingTrack]);
}else{
if(!saved) delete conformalTracks[existingTrack];
}
}
//*/
// Now make "real" tracks from all of the conformal tracks
streamlog_out(DEBUG9) << "*** CA has made " << conformalTracksFinal.size()
<< (conformalTracksFinal.size() == 1 ? " track ***" : " tracks ***") << std::endl;
// Loop over all track candidates
for (auto& conformalTrack : conformalTracksFinal) {
streamlog_out(DEBUG9) << "- Fitting track " << &conformalTrack << std::endl;
// Make the LCIO track hit vector
EVENT::TrackerHitVec trackHits;
for (auto const& cluster : conformalTrack->m_clusters) {
trackHits.push_back(kdClusterMap[cluster]);
}
// Add kalman filtered hits
if (conformalTrack->kalmanTrack() != nullptr) {
KalmanTrack* kalmanTrack = conformalTrack->kalmanTrack();
for (size_t i = 1; i < kalmanTrack->m_kalmanClusters.size(); i++) {
SKDCluster cluster = kalmanTrack->m_kalmanClusters[i];
trackHits.push_back(kdClusterMap[cluster]);
}
}
// Sort the hits from smaller to larger radius
std::sort(trackHits.begin(), trackHits.end(), sort_by_radius);
// Now we can make the track object and relations object, and fit the track
auto track = std::unique_ptr<TrackImpl>(new TrackImpl);
// First, for some reason there are 2 track objects, one which gets saved and one which is used for fitting. Don't ask...
shared_ptr<MarlinTrk::IMarlinTrack> marlinTrack(trackFactory->createTrack());
// Make an initial covariance matrix with very broad default values
EVENT::FloatVec covMatrix(15, 0); // Size 15, filled with 0s
covMatrix[0] = (m_initialTrackError_d0); //sigma_d0^2
covMatrix[2] = (m_initialTrackError_phi0); //sigma_phi0^2
covMatrix[5] = (m_initialTrackError_omega); //sigma_omega^2
covMatrix[9] = (m_initialTrackError_z0); //sigma_z0^2
covMatrix[14] = (m_initialTrackError_tanL); //sigma_tanl^2
streamlog_out(DEBUG9) << " Track hits before fit = " << trackHits.size() << std::endl;
// Try to fit
int fitError =
MarlinTrk::createFinalisedLCIOTrack(marlinTrack.get(), trackHits, track.get(), conformalTrack->m_kalmanFitForward,
covMatrix, m_magneticField, m_maxChi2perHit);
streamlog_out(DEBUG9) << " Fit direction " << ((conformalTrack->m_kalmanFitForward) ? "forward" : "backward")
<< std::endl;
streamlog_out(DEBUG9) << " Track hits after fit = " << track->getTrackerHits().size() << std::endl;
// If the track is too short (usually less than 7 hits correspond to a vertex track)
// the fit is tried using the inverted direction
if (int(track->getTrackerHits().size()) < m_maxHitsInvFit || fitError != MarlinTrk::IMarlinTrack::success) {
shared_ptr<MarlinTrk::IMarlinTrack> marlinTrack_inv(trackFactory->createTrack());
auto track_inv = std::unique_ptr<TrackImpl>(new TrackImpl);
// Try to fit on the other way
int fitError_inv = MarlinTrk::createFinalisedLCIOTrack(marlinTrack_inv.get(), trackHits, track_inv.get(),
!conformalTrack->m_kalmanFitForward, covMatrix, m_magneticField,
m_maxChi2perHit);
streamlog_out(DEBUG9) << " Fit direction " << ((!conformalTrack->m_kalmanFitForward) ? "forward" : "backward")
<< std::endl;
streamlog_out(DEBUG9) << " Track hits after inverse fit = " << track_inv->getTrackerHits().size() << std::endl;
if (track_inv->getTrackerHits().size() > track->getTrackerHits().size()) {
streamlog_out(DEBUG9) << " Track is replaced. " << std::endl;
track.swap(track_inv);
marlinTrack.swap(marlinTrack_inv);
fitError = fitError_inv;
} else {
streamlog_out(DEBUG9) << " Track is not replaced. " << std::endl;
}
}
// Check track quality - if fit fails chi2 will be 0. For the moment add hits by hand to any track that fails the track fit, and store it as if it were ok...
if (fitError != MarlinTrk::IMarlinTrack::success) {
//streamlog_out(DEBUG7) << "- Fit failed. Track has " << track->getTrackerHits().size() << " hits" << std::endl;
streamlog_out(DEBUG9) << "- Fit fail error " << fitError << std::endl;
continue;
} //*/
// Check if track has minimum number of hits
if (int(track->getTrackerHits().size()) < m_minClustersOnTrackAfterFit) {
streamlog_out(DEBUG9) << "- Track has " << track->getTrackerHits().size() << " hits. The minimum required is "
<< m_minClustersOnTrackAfterFit << std::endl;
continue;
}
/*for (unsigned int p = 0; p < trackHits.size(); p++) {
track->addHit(trackHits[p]);
} //*/
// Add hit information TODO: this is just a fudge for the moment, since we only use vertex hits. Should do for each subdetector once enabled
track->subdetectorHitNumbers().resize(2 * lcio::ILDDetID::ETD);
track->subdetectorHitNumbers()[2 * lcio::ILDDetID::VXD - 2] = trackHits.size();
// calculate purities and check if track has been reconstructed
if (m_debugPlots) {
m_conformalChi2->Fill(conformalTrack->chi2ndof());
streamlog_out(DEBUG9) << "-------------------- New TRACK --------------------" << std::endl;
//streamlog_out(DEBUG7) << " LCIO track fit chi2 is "<<track->getChi2()<<std::endl;
double purity = checkReal(conformalTrack, reconstructed, particleHits);
if (purity >= m_purity) {
m_conformalChi2real->Fill(conformalTrack->chi2ndof());
}
if (purity < m_purity) {
m_conformalChi2fake->Fill(conformalTrack->chi2ndof());
}
m_conformalChi2Purity->Fill(purity, conformalTrack->chi2ndof());
}
// Push back to the output container
trackCollection->addElement(track.release());
}
// Draw the cells for all produced tracks
if (m_debugPlots && m_eventNumber == 0) {
m_canvConformalEventDisplay->cd();
for (auto& debugTrack : conformalTracksFinal) {
SharedKDClusters clusters = debugTrack->m_clusters;
std::sort(clusters.begin(), clusters.end(), sort_by_lower_radiusKD);
for (size_t itCluster = 1; itCluster < clusters.size(); itCluster++)
drawline(clusters[itCluster - 1], clusters[itCluster], clusters.size() - itCluster);
}
}
// Draw the conformal event display hits for debugging
if (m_debugPlots && m_eventNumber == 0) {
m_canvConformalEventDisplay->cd();
m_conformalEvents->DrawCopy("same");
m_canvConformalEventDisplayAllCells->cd();
m_conformalEvents->DrawCopy("same");
m_canvConformalEventDisplayAcceptedCells->cd();
m_conformalEvents->DrawCopy("same");
m_canvConformalEventDisplayMCunreconstructed->cd();
m_conformalEvents->DrawCopy("same");
}
if (m_debugPlots) {
int nReconstructed(0), nUnreconstructed(0);
// Additionally draw all tracks that were not reconstructed
m_canvConformalEventDisplayMCunreconstructed->cd();
int nParticles = particleCollection->getNumberOfElements();
// Make the nearest neighbour tree to debug particle reconstruction issues
SharedKDClusters kdClusters_debug;
for (size_t i = 0; i < trackerHitCollections.size(); i++)
kdClusters_debug.insert(kdClusters_debug.begin(), collectionClusters[i].begin(), collectionClusters[i].end());
auto nearestNeighbours_debug = UKDTree(new KDTree(kdClusters_debug, m_thetaRange, m_sortTreeResults));
for (int itP = 0; itP < nParticles; itP++) {
// Get the particle
MCParticle* mcParticle = dynamic_cast<MCParticle*>(particleCollection->getElementAt(itP));
// Get the conformal hits
if (particleHits.count(mcParticle) == 0)
continue;
SharedKDClusters mcHits = particleHits[mcParticle];
// Cut on the number of hits
int uniqueHits = getUniqueHits(mcHits);
if (uniqueHits < m_minClustersOnTrack)
continue;
// Check if it was stable
if (mcParticle->getGeneratorStatus() != 1)
continue;
// Check if it was reconstructed
streamlog_out(DEBUG9) << "-------------------- New PARTICLE --------------------" << std::endl;
// List the pt
double particlePt = sqrt(mcParticle->getMomentum()[0] * mcParticle->getMomentum()[0] +
mcParticle->getMomentum()[1] * mcParticle->getMomentum()[1]);
streamlog_out(DEBUG9) << "Particle pt: " << particlePt << std::endl;
//checkReconstructionFailure(mcParticle, particleHits, nearestNeighbours_debug, _stepParameters[0]);
if (reconstructed.count(mcParticle)) {
nReconstructed++;
continue;
}
// Draw the cells connecting the hits
std::sort(mcHits.begin(), mcHits.end(), sort_by_radiusKD);
for (size_t iHit = 0; iHit < (mcHits.size() - 1); iHit++) {
drawline(mcHits[iHit], mcHits[iHit + 1], iHit + 1);
}
streamlog_out(DEBUG7) << "Unreconstructed particle pt: " << particlePt << std::endl;
nUnreconstructed++;
// Check why particles were not reconstructed
// checkReconstructionFailure(mcParticle, particleHits, used, nearestNeighbours);
}
streamlog_out(DEBUG9) << "Reconstructed " << nReconstructed << " particles out of " << nReconstructed + nUnreconstructed
<< ". Gives efficiency "
<< 100. * (double)nReconstructed / (double)(nReconstructed + nUnreconstructed) << "%" << std::endl;
nearestNeighbours_debug.reset(nullptr);
}
// Save the output track collection
evt->addCollection(trackCollection.release(), m_outputTrackCollection);
evt->addCollection(debugHitCollection.release(), m_outputDebugHits);
// Increment the event number
m_eventNumber++;
}
void ConformalTracking::end() {
streamlog_out(MESSAGE) << " end() " << name() << " processed " << m_eventNumber << " events in " << m_runNumber
<< " runs " << std::endl;
// Write debug canvases to output file
if (m_debugPlots) {
m_canvConformalEventDisplay->Write();
m_canvConformalEventDisplayAllCells->Write();
m_canvConformalEventDisplayAcceptedCells->Write();
m_canvConformalEventDisplayMC->Write();
m_canvConformalEventDisplayMCunreconstructed->Write();
}
kdParticles.clear();
kdSimHits.clear();
//FIXME trackFactory is leaking Memory, but probably a MarlinTRK issue
}
//===================================
// Tracking strategies
//===================================
// Combine collections
void ConformalTracking::combineCollections(SharedKDClusters& kdClusters, UKDTree& nearestNeighbours,
std::vector<int> const& combination,
std::map<int, SharedKDClusters> const& collectionClusters) {
// Clear the input objects
kdClusters.clear();
nearestNeighbours.reset(nullptr);
// Loop over all given collections
for (unsigned int i = 0; i < combination.size(); i++) {
// Copy the clusters to the output vector
const SharedKDClusters& clusters = collectionClusters.at(combination[i]);
kdClusters.insert(kdClusters.end(), clusters.begin(), clusters.end());
}
streamlog_out(DEBUG9) << "*** combineCollections: Collection has " << kdClusters.size() << " hits" << std::endl;
// Sort the KDClusters from larger to smaller radius
std::sort(kdClusters.begin(), kdClusters.end(), sort_by_radiusKD);
// Make the binary search tree. This tree class contains two binary trees - one sorted by u-v and the other by theta
nearestNeighbours = UKDTree(new KDTree(kdClusters, m_thetaRange, m_sortTreeResults));
}
// Take a collection of hits and try to produce tracks out of them
void ConformalTracking::buildNewTracks(UniqueKDTracks& conformalTracks, SharedKDClusters& collection,
UKDTree& nearestNeighbours, Parameters const& parameters, bool radialSearch,
bool vertexToTracker) {
streamlog_out(DEBUG9) << "*** buildNewTracks" << std::endl;
// Sort the input collection by radius - higher to lower if starting with the vertex detector (high R in conformal space)
std::sort(collection.begin(), collection.end(), (vertexToTracker ? sort_by_radiusKD : sort_by_lower_radiusKD));
auto stopwatch_hit = TStopwatch();
auto stopwatch_hit_total = TStopwatch();
// Loop over all hits, using each as a seed to produce a new track
unsigned int nKDHits = collection.size();
for (unsigned int nKDHit = 0; nKDHit < nKDHits; nKDHit++) {
stopwatch_hit.Start(true);
stopwatch_hit_total.Start(true);
// Get the kdHit and check if it has already been used (assigned to a track)
SKDCluster kdhit = collection[nKDHit];
streamlog_out(DEBUG9) << "Seed hit " << nKDHit << ": [x,y,z] = [" << kdhit->getX() << ", " << kdhit->getY() << ", "
<< kdhit->getZ() << "]" << std::endl;
if (m_debugPlots) {
m_X->Fill(kdhit->getX());
m_Y->Fill(kdhit->getY());
m_Z->Fill(kdhit->getZ());
}
if (debugSeed && kdhit == debugSeed)
streamlog_out(DEBUG7) << "Starting to seed with debug cluster" << std::endl;
if (kdhit->used()) {
streamlog_out(DEBUG9) << "hit already used" << std::endl;
continue;
}
// Debug: Plot residuals between hit and associated SimTrackerHit
if (m_debugPlots) {
streamlog_out(DEBUG7) << "SimHit : [x,y,z] = [" << kdSimHits[kdhit]->getPosition()[0] << ", "
<< kdSimHits[kdhit]->getPosition()[1] << ", " << kdSimHits[kdhit]->getPosition()[2] << "] "
<< std::endl;
}
// if(kdhit->getR() < 0.003) break; // new cut - once we get to inner radius we will never make tracks. temp? TODO: make parameter? FCC (0.005 to 0.003)
// The tracking differentiates between the first and all subsequent hits on a chain.
// First, take the seed hit and look for sensible hits nearby to make an initial set
// of cells. Once these are found, extrapolate the cells and look for additional hits
// to produce a new cell along the chain. This is done mainly for speed: you ignore
// all combinations which would be excluded when compared with the seed cell. In the
// end we will try to produce a track starting from this seed, then begin again for
// the next seed hit.