forked from marcelkunze/trackml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReconstruction.cxx
executable file
·1499 lines (1247 loc) · 47.8 KB
/
Reconstruction.cxx
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
// Neural Network based path reconstruction
// M.Kunze, Heidelberg University, 2018
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include "Parameters.h"
#include "Reconstruction.h"
#include "PolarModule.h"
#ifdef USETMVA
#ifdef TMVAREADER
#include "TMVA/Tools.h"
#include "TMVA/Reader.h"
#endif
#include "TMVAClassification_MLP1.h"
#include "TMVAClassification_MLP2.h"
#include "TMVAClassification_MLP3.h"
#else
#include "XMLP.h"
#endif
extern PolarModule *mod[LAYERS];
int Reconstruction::next_layer[LAYERS][LAYERS];
TFile *Reconstruction::file(NULL);
TNtuple *Reconstruction::ntuple1(NULL);
TNtuple *Reconstruction::ntuple2(NULL);
TNtuple *Reconstruction::ntuple3(NULL);
int Reconstruction::phires(PHIRESOLUTION);
int Reconstruction::theres(THETARESOLUTION);
using namespace std;
long long Reconstruction::hitHash(int hitid) {
long l=metai[hitid];
long m=meta[hitid].z;
auto h = graphHash(hitid);
long long index = (((long)h.first)<<32) | (((long)h.second)<<24) | (l<<16) | m;
//long long index = (l<<16) | m;
//long long index = l*MODULES + m;
return index;
}
Reconstruction::Reconstruction(int event,const char *workpath,std::map<std::pair<int,int>, Graph<long long> > &t,vector<point> &h,std::vector<point> &p,vector<point> &m,std::vector<int> &mi,std::vector<int> &mz,Layer (&l)[LAYERS],double (&dz)[LAYERS][4],vector<pair<pair<int, int>, double> > (&hc)[MAXDIM],point (&hd)[MAXDIM][2]) : eventnum(event), workPath(workpath), tgraph(t), hits(h), polar(p), meta(m), metai(mi), metaz(mz), layer(l), disc_z(dz), hit_cells(hc), hit_dir(hd)
{
static bool initialized(false);
if (!initialized) {
string filename = workPath + "/adjacency";
loadAdjacent(filename.c_str());
initialized = true;
}
initDensity3();
threshold1 = 0.1;
threshold2 = 0.1;
threshold3 = 0.3;
}
Reconstruction::~Reconstruction()
{
}
std::pair<int,int> Reconstruction::graphHash(int hitid) {
point pol = polar[hitid];
double rt = pol.x;
double ph = pol.y;
double z0 = pol.z;
double th = asinh(z0/rt); // slope (-4...+4)
int i1 = (int) (phires*0.15*(M_PI+ph));
int i2 = (int) (theres*0.1*(5-th));
return make_pair(i1,i2);
}
// Calculate a vertex for two points
double Reconstruction::xyVertex(int ai, int bi)
{
point &a = hits[ai];
point &b = hits[bi];
point d = a - b;
double ppxy = a.x*a.x+a.y*a.y;
double pdxy = a.x*d.x+a.y*d.y;
double ddxy = d.x*d.x+d.y*d.y;
if (ddxy==0) return 1.E3;
return sqrt(ppxy-pdxy*pdxy/ddxy);
}
double Reconstruction::zVertex(int ai, int bi)
{
point &a = hits[ai];
point &b = hits[bi];
point d = a - b;
double pp = a.x*a.x+a.y*a.y+a.z*a.z;
double pd = a.x*d.x+a.y*d.y+a.z*d.z;
double dd = d.x*d.x+d.y*d.y+d.z*d.z;
if (dd==0) return 1.E3;
return sqrt(pp-pd*pd/dd);
}
pair<double,double> Reconstruction::zVertexScore(int ai, int bi)
{
double z(0);
double dz = 10.0;
double minscore = 1.E3;
hits[0] = point(0,0,0);
if (hits[ai].z<0) dz = -dz; // negative direction
for (int i=0;i<16;i++) {
hits[0].z = i*dz;
double score = scoreTriple(0,ai,bi);
if (score < minscore) {
z = hits[0].z;
minscore = score;
}
}
return make_pair(z,minscore);
}
// Look for the point of closest approach to the origin
point Reconstruction::getVertex(int ai, int bi)
{
point origin(0,0,0);
point linePnt = hits[ai];
point line = hits[ai] - hits[bi];
double factor = 1./point::norm(line);
point lineDir = line*factor;
point v = origin - linePnt;
double d = point::dot(v,lineDir);
return linePnt + lineDir * d;
}
// Look for seeding pair/triple candidates by hit pair/triple combinations in consecutive layers
vector<triple> Reconstruction::findCandidatesGraph(Graph<long long> &g)
{
static const int n(STARTLAYERS); // number of seeding layers
static const int startlayer[48] = {0,11,4,18,1,5,12,13,6,2,3,19,20,7,14,21,24,36,15,8,22,9,16,38,40,42,26,28,30,25,37,10,17,23,32,34,44,46,27,39,29,41,31,43,33,45,35,47}; // seeding layers
static const double vertexscore[48] = {470,590,430,430,140,100,80,210,100,160,260,430,560,110,110,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE,VERTEXSCORE}; // max helix score
static const double offset[48] = {0.0,0.0,0.0,0.2,0.1,0.0,0.0,0.0,0.0,0.2,0.3,0.2,0.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; // adaptation wrt. recall distribution per layer
vector<triple> candidates;
for (int i = 0; i < n; i++)
{
int layer1 = startlayer[i];
for (auto start : g.hash(layer1)) { // all modules in first layer
const auto &edgelist = g.edges(start);
if (edgelist.size() == 0) continue;
for (auto &edge : edgelist) {
long nextindex = edge.first;
double vz = 0.0;
#ifdef VERTEXCUT
vz = edge.second; // get z vertex from graph
if (abs(vz) > VERTEXCUT) continue;
#endif
for (auto ai : g.data(start)) { // all hits in module
auto &p = g.data(nextindex); // all hits in following modules
if (p.size() == 0) continue;
for (auto bi:p)
{
int l1 = metai[ai];
int l2 = metai[bi];
if (l1 == l2) continue; // Same layer (Double hits)
double xy0 = xyVertex(ai,bi); // check the radial distance from origin
if (i<3 && xy0 > VERTEXCUTXY) continue;
double z0 = zVertex(ai,bi); // check the z distance from origin
if (z0 > VERTEXCUTZ) continue;
//double zdist = zdist2(hits[ai],hits[bi]);
//if (zdist > VERTEXCUTZ) continue;
hits[0] = point(0,0,vz); // origin
double score = scoreTriple(0,ai,bi); // helix score wrt. origin
if (score > vertexscore[i]) continue;
double dir1 = dir_miss(ai,bi);
double dir2 = dir_miss(bi,ai);
double recall(1.0);
bool tube = (l1<4) || (l1>=18 && l1<=23);
if (!tube) {
recall = recall1(g,ai,bi,dir1,dir2,vz); // Search for hit pairs using coordinates and hit direction
if (recall < threshold1+offset[i]) continue;
}
else {
recall = recall2(g,ai,bi,dir1,dir2,score,vz); // Search for hit pairs using coordinates, hit direction, and helix score
if (recall < threshold2+offset[i]) continue;
}
candidates.push_back(triple(ai,bi,0,recall,vz)); // Note the good pair candidates
}
}
}
}
}
return candidates;
}
// Generate tracklets of 3 points wrt. the first point in seed
std::vector<triple> Reconstruction::findTriplesGraph(Graph<long long> &g,vector<triple> &pairs) {
static const int target(2);
vector<triple> triples;
int n = (int) pairs.size();
for (int i=0;i<n;i++)
{
vector<triple> batchtriples;
auto &pa = pairs[i];
int ai = get<0>(pa);
int bi = get<1>(pa);
#ifdef COMBINEDMETHOD
pair<int,int> index = graphHash(bi);
auto *gg = &tgraph[index];
#else
Graph<long long> *gg = &g;
#endif
// Search for triples
long indexg = hitHash(bi);
const auto &edgelist = gg->edges(indexg);
if (edgelist.size() == 0) continue;
for (auto &edge : edgelist) {
long nextindex = edge.first;
double vz = 0.0; //edge.second;
auto &p = g.data(nextindex); // all hits in following modules
if (p.size() == 0) continue;
vector<triple> v;
for (auto ci:p)
{
if (ci==ai || ci==bi) continue; // Same hit
double score = scoreTriple(ai,bi,ci); // Check helix propagation
if (score>SWEIGHT) continue; // bad helix hypothesis
triple t(ai,bi,ci,score,vz);
v.push_back(t);
}
// Sort the result by score using lambda function
sort(begin(v), end(v),[](triple const &t1, triple const &t2) {return get<3>(t1) < get<3>(t2);} );
if (v.size()>target) v.resize(target);
for (auto &t : v) {
double recall = recall3(*gg,t); // Check quality with ANN
if (recall<threshold3) continue;
triples.push_back(t); // Note the good triple candidates
}
}
}
return triples;
}
// Recall function for 2 points (cylinder coordinates)
double Reconstruction::recall1(Graph<long long> &g,int a, int b, double f1, double f2, double z0)
{
point &p1 = polar[a];
point &p2 = polar[b];
#ifdef USETMVA
float *x1 = g.getX1();
#ifdef FOLDEDINPUT1
x1[0] = p1.x; // rz1
x1[1] = fabs(fabs(p1.y)-M_PI_2); // phi1
x1[2] = fabs(p1.z); // z1
x1[3] = p2.x; // rz2
x1[4] = fabs(fabs(p2.y)-M_PI_2); // phi2
x1[5] = fabs(p2.z); // z2
#else
x1[0] = p1.x;
x1[1] = p1.y;
x1[2] = p1.z;
x1[3] = p2.x;
x1[4] = p2.y;
x1[5] = p2.z;
#endif
x1[6] = f1; // dirmiss1
x1[7] = f2; // dirmiss2
#ifdef TMVAREADER
TMVA::Reader *reader = g.getReader1();
double recall = reader->EvaluateMVA("MLP method");
#else
vector<double> x;
for (int i=0;i<8;i++) x.push_back(x1[i]);
double recall = g.getNet1()->GetMvaValue(x);
#endif
#else
float x[10];
#ifdef FOLDEDINPUT1
x[0] = p1.x*0.001; // rz1 [m]
x[1] = fabs(fabs(p1.y)-M_PI_2); // phi1
x[2] = fabs(p1.z-z0)*0.001; // z1 [m]
x[3] = p2.x*0.001; // rz2 [m]
x[4] = fabs(fabs(p2.y)-M_PI_2); // phi2
x[5] = fabs(p2.z-z0)*0.001; // z2 [m]
#else
x[0] = p1.x*0.001; // rz1 [m]
x[1] = p1.y; // phi1
x[2] = p1.z*0.001; // z1 [m]
x[3] = p2.x*0.001; // rz2 [m]
x[4] = p2.y; // phi2
x[5] = p2.z*0.001; // z2 [m]
#endif
x[6] = f1; // feature
x[7] = f2; // feature
double recall = g.net1()->Recallstep(x)[0];
#endif
return recall;
}
// Recall function for 2 points (folded cylinder coordinates)
double Reconstruction::recall2(Graph<long long> &g,int a, int b, double f1, double f2, double f3, double z0)
{
point &p1 = polar[a];
point &p2 = polar[b];
#ifdef USETMVA
float *x2 = g.getX2();
#ifdef FOLDEDINPUT2
x2[0] = p1.x; // rz1
x2[1] = fabs(fabs(p1.y)-M_PI_2); // phi1
x2[2] = fabs(p1.z); // z1
x2[3] = p2.x; // rz2
x2[4] = fabs(fabs(p2.y)-M_PI_2); // phi2
x2[5] = fabs(p2.z); // z2
#else
x2[0] = p1.x;
x2[1] = p1.y;
x2[2] = p1.z;
x2[3] = p2.x;
x2[4] = p2.y;
x2[5] = p2.z;
#endif
x2[6] = f1; // dirmiss1
x2[7] = f2; // dirmiss2
x2[8] = log(f3); // score
#ifdef TMVAREADER
TMVA::Reader *reader = g.getReader2();
double recall = reader->EvaluateMVA("MLP method");
#else
vector<double> x;
for (int i=0;i<9;i++) x.push_back(x2[i]);
double recall = g.getNet2()->GetMvaValue(x);
#endif
#else
float x[10];
#ifdef FOLDEDINPUT2
x[0] = p1.x*0.001; // rz1 [m]
x[1] = fabs(fabs(p1.y)-M_PI_2); // phi1
x[2] = fabs(p1.z-z0)*0.001; // z1 [m]
x[3] = p2.x*0.001; // rz2 [m]
x[4] = fabs(fabs(p2.y)-M_PI_2); // phi2
x[5] = fabs(p2.z-z0)*0.001; // z2 [m]
#else
x[0] = p1.x*0.001; // rz1 [m]
x[1] = p1.y; // phi1
x[2] = p1.z*0.001; // z1 [m]
x[3] = p2.x*0.001; // rz2 [m]
x[4] = p2.y; // phi2
x[5] = p2.z*0.001; // z2 [m]
#endif
x[6] = f1; // feature
x[7] = f2; // feature
x[8] = 0.001*f3; // feature
double recall = g.net2()->Recallstep(x)[0];
#endif
return recall;
}
// Recall function for 3 points
double Reconstruction::recall3(Graph<long long> &g,triple &t)
{
int ai, bi, ci;
double r3,z0;
tie(ai,bi,ci,r3,z0) = t;
r3 = recall3(g,ai,bi,ci,r3,z0);
get<3>(t) = r3;
return r3;
}
// Recall function for 3 points (cylinder coordinates)
double Reconstruction::recall3(Graph<long long> &g,int a, int b, int c, double f1, double z0)
{
point &p1 = polar[a];
point &p2 = polar[b];
point &p3 = polar[c];
#ifdef USETMVA
#ifdef TMVAREADER
TMVA::Reader *reader = g.getReader3();
float *x = g.getX3();
x[0] = p1.x; // rz1
x[1] = p1.y; // phi1
x[2] = p1.z; // z1
x[3] = p2.x; // rz2
x[4] = p2.y; // phi2
x[5] = p2.z; // z2
x[6] = p3.x; // rz3
x[7] = p3.y; // phi23
x[8] = p3.z; // z3
x[9] = log(f1); // score
double recall = reader->EvaluateMVA("MLP method");
#else
vector<double> x;
x.push_back(p1.x);
x.push_back(p1.y);
x.push_back(p1.z);
x.push_back(p2.x);
x.push_back(p2.y);
x.push_back(p2.z);
x.push_back(p3.x);
x.push_back(p3.y);
x.push_back(p3.z);
x.push_back(log(f1));
double recall = g.getNet3()->GetMvaValue(x);
#endif
#else
float x[12];
#ifdef FOLDEDINPUT3
x[0] = p1.x*0.001; // rz1 [m]
x[1] = fabs(fabs(p1.y)-M_PI_2); // phi1
x[2] = fabs(p1.z-z0)*0.001; // z1 [m]
x[3] = p2.x*0.001; // rz2 [m]
x[4] = fabs(fabs(p2.y)-M_PI_2); // phi2
x[5] = fabs(p2.z-z0)*0.001; // z2 [m]
x[6] = p3.x*0.001; // rz3 [m]
x[7] = fabs(fabs(p3.y)-M_PI_2); // phi3
x[8] = fabs(p3.z-z0)*0.001; // z3 [m]
#else
x[0] = p1.x*0.001; // rz1 [m]
x[1] = p1.y; // phi1
x[2] = (p1.z-z0)*0.001; // z1 [m]
x[3] = p2.x*0.001; // rz2 [m]
x[4] = p2.y; // phi2
x[5] = (p2.z-z0)*0.001; // z2 [m]
x[6] = p3.x*0.001; // rz3 [m]
x[7] = p3.y; // phi3
x[8] = (p3.z-z0)*0.001; // z3 [m]
#endif
x[9] = f1; // feature
double recall = g.net3()->Recallstep(x)[0];
#endif
return recall;
}
// The following code has been adopted from Johan Sokrates Wind's award winning trackml Kaggle contribution
// Parameters have been slightly optimized and at some places values are checked to make the code more robust
// Triples have been substituted by standard C++ tuples
// see https://www.kaggle.com/c/trackml-particle-identification/discussion/63249
//Find circle with center p, radius r, going through a, b, and c (in xy plane)
void Reconstruction::circle(point&a, point&b, point&c, point&p, double&r) {
double ax = a.x-c.x, ay = a.y-c.y, bx = b.x-c.x, by = b.y-c.y;
double aa = ax*ax+ay*ay, bb = bx*bx+by*by;
double x = ax*by-ay*bx;
if (x==0) {
r = 0;
return;
}
double idet = .5/x;
p.x = (aa*by-bb*ay)*idet;
p.y = (ax*bb-bx*aa)*idet;
p.z = 0;
r = dist(p.x, p.y);
p.x += c.x;
p.y += c.y;
}
//Score triple based on the deviation from a perfect helix, no prior that it should be straight
double Reconstruction::scoreTriple(int ai, int bi, int ci) {
point center;
double radius;
if (ai==bi || ai==ci || bi==ci) return 1e3;
circle(hits[ai], hits[bi], hits[ci], center, radius);
if (radius==0) return 1e3;
point cb = hits[ci]-hits[bi];
point ba = hits[bi]-hits[ai];
double ang_cb = asin(dist(cb.x, cb.y)*.5/radius)*2;
double ang_ba = asin(dist(ba.x, ba.y)*.5/radius)*2;
if (radius != radius || fabs(radius) > 1e50) {
ang_cb = dist(cb.x, cb.y);
ang_ba = dist(ba.x, ba.y);
}
if (ba.z*cb.z < 0) ang_ba *= -1;
if (ang_cb-ba.z == 0) return 1.E3;
if (ang_ba == 0) return 1.E3;
double y = ang_cb ? (fabs(cb.z*ang_ba/ang_cb-ba.z)) : 1e3;
double z = ang_ba ? (fabs(cb.z-ba.z*ang_cb/ang_ba)) : 1e3;
double score = min(y, z);
return score;
}
//Expand triples into paths, do this by expanding helices through the outermost 3 point in each direction repeatedly
vector<vector<int> > Reconstruction::findPaths(vector<triple>&triples) {
vector<vector<int> > paths;
static const int minpath = 3;
int n = (int) triples.size();
for (int i=0;i<n;i++)
{
vector<vector<int> > batchpaths;
auto &t = triples[i];
vector<int> v;
int ai, bi, ci;
double r3,z0;
tie(ai,bi,ci,r3,z0) = t;
int misses = 0;
for (int li = metai[ai]-1; li >= 0; li--) {
if (next_layer[li][metai[ai]] < adj_thres) continue;
int di = extend3(ci, bi, ai, li);
if (di > 0) {
v.push_back(di);
ci = bi;
bi = ai;
ai = di;
misses = 0;
} else if (di == -1) misses++;
if (misses == 2) break;
}
reverse(v.begin(), v.end());
tie(ai,bi,ci,r3,z0) = t;
v.push_back(ai);
v.push_back(bi);
v.push_back(ci);
misses = 0;
for (int li = metai[ci]+1; li < LAYERS; li++) {
if (next_layer[metai[ci]][li] < adj_thres) continue;
int di = extend3(ai, bi, ci, li);
if (di > 0) {
v.push_back(di);
ai = bi;
bi = ci;
ci = di;
misses = 0;
} else if (di == -1) misses++;
if (misses == 2) break;
}
v.shrink_to_fit();
if (v.size()>minpath) batchpaths.push_back(v);
paths.insert(paths.end(),batchpaths.begin(),batchpaths.end()); // append the candidates
}
// Remove duplicate entries
sort(paths.begin(),paths.end());
paths.erase(unique(paths.begin(),paths.end() ),paths.end());
return paths;
}
//Extend the helix going through hits with ids "ai", "bi", "ci", to layer "li". Do this by looking at the intersection with the layer, and expecting around "target" continuation for each outlier triple. "li" must be after metai[ci]
int Reconstruction::extend3(int ai, int bi, int ci, int li, double target) {
point d, dp, xp, bap;
if (prepareQuadrupleScore(ai,bi,ci,li,d,dp,xp,bap,1)) return -2;
double tt = 400;//findDensity(dp, xp, target, li);
double mins = 1e9;//target;//1e9;
double fac = getDensity3(dp, xp, tt, li)/tt;
tt = target/fac;
int matches = mod[li]->getNear(dp, xp, bap, tt, match);
int mini = -1;
for (int i = 0; i < matches; i++) {
int ti = match[i];
if (ti >= (int)hits.size()){
cout << "ERROR: " << ti << endl;
continue;
}
//if (assignment[ti]) continue;
double s = evaluateScore(ti,dp,xp,bap)*fac;
if (s < mins) {
mins = s;
mini = ti;
}
}
return mini;
}
//Default target is average position of layer
int Reconstruction::prepareQuadrupleScore(int ai, int bi, int ci, int li, point&d, point&dp, point&xp, point&bap, double sign = 1) {
Layer l = layer[li];
point target(l.avgr, 0, l.avgz);
return prepareQuadrupleScore(ai, bi, ci, li, d, dp, xp, bap, target, sign);
}
//Similar to prepareTripleScore, but now we extend the helix that passes through hits with id "ai", "bi", "ci". Assumes li > metai[ci] if sign = 1, and metai[bi] < li < metai[ci] if sign = -1
int Reconstruction::prepareQuadrupleScore(int ai, int bi, int ci, int li, point&d, point&dp, point&xp, point &dirp, point target, double sign = 1) {
Layer l = layer[li];
point p;
double r, ir;
point c = hits[ci];
point cb = hits[ci]-hits[bi];//c-b;
double ang_cb;
if (1) { //Take into account varying magnetic field strength
point a = hits[ai], b = hits[bi], c = hits[ci];
if (l.type == Disc && (c.z-b.z)*(target.z-c.z)*sign < 0) return -1;
double B1 = field((a.z+b.z)*.5), B2 = field((b.z+c.z)*.5), B3;
if (l.type == Disc) B3 = field((c.z+target.z)*.5);
else B3 = field(c.z);
//B1 = B2 = B3 = 1;
double ax = b.x-a.x, ay = b.y-a.y, bx = c.x-b.x, by = c.y-b.y;
double aa = ax*ax+ay*ay, dot = ax*bx+ay*by, cross = ax*by-ay*bx;
double alpha = B2/(2*B3), beta = (-B1*aa-B2*dot)/(2*cross*B3);
//alpha *= -1;
double rx = alpha*bx-beta*by, ry = alpha*by+beta*bx;
p = point(c.x-rx, c.y-ry, 0);
r = dist(rx, ry);
ir = 1./r;
ang_cb = B3/B2*asin(dist(cb.x, cb.y)*.5*ir*B2/B3)*2;
}
//exit(0);
const double slack = 1.00;
xp = point(0,0,0); //Circle for now
if (l.type == Tube) {
double RR = target.x*target.x, pp = dist2(p.x, p.y);
double s = .5+(RR-r*r)/(2*pp);
double sq = RR/pp-s*s;
if (sq < 0) return -1;
double t = sqrt(sq);
if (p.y*c.x-p.x*c.y < 0) t *= -1;
d.x = p.x*s+p.y*t;
d.y = p.y*s-p.x*t;
point dc = d-c;
double A = dist(dc.x, dc.y);
double B = A*.5*ir;
double ang_dc = asin(B)*2;
if (dc.x*cb.x+dc.y*cb.y < 0) ang_cb *= -1;
d.z = c.z+cb.z*ang_dc/ang_cb;
if (!(d.z > l.minz*slack && d.z < l.maxz*slack)) return -1;
point dir;
double s_ = target.x/pp, t_ = s_*(1-s)/t;
dir.x = p.x*s_+p.y*t_;
dir.y = p.y*s_-p.x*t_;
dir.z = (dc.x*dir.x+dc.y*dir.y)*ir*cb.z/(ang_cb*A*sqrt(1-B*B));
dp = point(dist(d.x,d.y), atan2(d.y, d.x), d.z);
dirp = point(d.x*dir.x+d.y*dir.y, d.x*dir.y-d.y*dir.x, dir.z*dp.x);
//cout << dirp << endl; //dirp.x = l.avgr
dirp = dirp*(1./dirp.x);
} else if (l.type == Disc) {
d.z = target.z;
double fac = ang_cb/cb.z;
double ang_dc = (d.z-c.z)*fac;
double sa = sin(ang_dc), ca = cos(ang_dc);
double rx = c.x-p.x, ry = c.y-p.y;
double cross = rx*cb.y-ry*cb.x;
if (cross < 0) sa *= -1;
d.x = ca*rx-sa*ry+p.x;
d.y = sa*rx+ca*ry+p.y;
point dir;
dir.x =-fac*(rx*sa+ry*ca);
dir.y = fac*(rx*ca-ry*sa);
dir.z = cross < 0 ? -1 : 1;
dp = point(dist(d.x,d.y), atan2(d.y, d.x), d.z);
if (!(dp.x > l.minr*(1./slack) && dp.x < l.maxr*slack)) return -1;
dirp = point(d.x*dir.x+d.y*dir.y, d.x*dir.y-d.y*dir.x, dir.z*dp.x);
//cout << dirp << endl; //dirp.x = l.avgr
dirp = dirp*(1./dirp.z);
}
return 0;
}
//Init everything needed for fast density calculations, includes most global variables above
void Reconstruction::initDensity3() {
vector<int>*tube = new vector<int>[48]();
for (int i = 1; i < (int)hits.size(); i++) {
//if (!assignment[i])
tube[metai[i]].push_back(i);
}
for (int li = 0; li < 48; li++) {
sorted_hits[li].clear();
if (layer[li].type == Tube) {
for (int i : tube[li])
sorted_hits[li].push_back(hits[i].z);
} else {
for (int i : tube[li])
sorted_hits[li].push_back(polar[i].x);
}
sorted_hits[li].push_back(-1e50);
sorted_hits[li].push_back(1e50);
sort(sorted_hits[li].begin(), sorted_hits[li].end());
double minx = *next(sorted_hits[li].begin())-1e-8;
double maxx = *next(sorted_hits[li].rbegin())+1e-8;
//cout << maxx << ' ' << minx << endl;
double f = crude_steps/(maxx-minx);
crudeIndex_a[li] = make_pair(f, -minx*f);
for (int i = 0; i < crude_steps; i++) {
double x = (i+.5)/f+minx;
crudeIndex[li][i] = (int) (upper_bound(sorted_hits[li].begin(), sorted_hits[li].end(), x)-sorted_hits[li].begin());
}
double acc[3] = {};
for (int i = 1; i < (int)sorted_hits[li].size(); i++) {
for (int j = 0; j < 3; j++) poly[li][i][j] = acc[j];
double x = sorted_hits[li][i];
for (int j = 0; j < 3; j++)
acc[j] += pow(x, j);
}
}
delete[]tube;
}
//Get expected number of hits on layer "li" in area (in polar/cylindrical coordnates) spanned by (p-dp)^2-dot(p-dp, xp)^2 < tt
double Reconstruction::getDensity3(point&dp, point&xp, double tt, int li) {
Layer l = layer[li];
double x0, dx, dy;
if (l.type == Tube) {
x0 = dp.z;
dx = xp.z;
dy = xp.y;
} else {
x0 = dp.x;
dx = xp.x;
dy = xp.y;
}
double b = tt*(1-dy*dy)/(1-dx*dx-dy*dy);
double a = sqrt(1-dx*dx-dy*dy)/((1-dy*dy)*M_PI*dp.x);
double rx = sqrt(b);
int ai = getIndex(li, x0-rx);
int bi = getIndex(li, x0+rx);
if (bi-ai > 10) {//Approximate integration by 2. order polynomial approximation to half disc
//cout << ai << ' ' << bi << endl;
const double A = 21*M_PI/64., B = -15*M_PI/64.;
double ib = 1./b;
double c0 = A+B*x0*x0*ib, c1 = -2*B*ib*x0, c2 = B*ib;
double ret =
((poly[li][bi][0]-poly[li][ai][0])*c0+
(poly[li][bi][1]-poly[li][ai][1])*c1+
(poly[li][bi][2]-poly[li][ai][2])*c2)*a*rx;
return max(ret,0.);
} else { //Exact integration, uses half disc
double density = 0;
for(int i = ai; i < bi; i++) {
double x = sorted_hits[li][i]-x0;
double h = a*sqrt(b-x*x);/// *it;
//cout << h << endl;
density += h;
}
return density;
}
}
//Use the prepared "dp", "xp", "bap" and return the area that is closer to the collision line (taking into account xp for elliptic behaviour) compared to the hit with id "ci"
double Reconstruction::evaluateScore(int ci, point&dp, point&xp, point&bap) {
point&r = polar[ci];
point err = r-dp;
if (err.y > M_PI) err.y -= M_PI*2;
if (err.y <-M_PI) err.y += M_PI*2;
err.y *= dp.x;
err = err-bap*(layer[metai[ci]].type == Disc ? err.z : err.x);
double r2 = err*err-pow(err*xp, 2);
return r2;
}
//Approximate magnetic field strengh as a function of z coordinate, decays drastically near the ends
double Reconstruction::field(double z) {
z *= 1./2750;
double z2 = z*z;
return 1.002-z*3e-2-z2*(0.55-0.3*(1-z2));
}
// O(1) indexing in sorted_hits
// Functionally similar to "upper_bound(sorted_hits[li].begin(), sorted_hits[li].end(), x)-sorted_hits[li].begin();"
inline int Reconstruction::getIndex(int&li, double x) {
int ci = x*crudeIndex_a[li].first+crudeIndex_a[li].second;
ci = min(crude_steps-1, max(0, ci));
int i = crudeIndex[li][ci];
//Might segfault sometimes :)
while (x >= sorted_hits[li][i]) i++;
while (x < sorted_hits[li][i-1]) i--;
return i;//max(0,min(i,int(sorted_hits[li].size())-1));
}
//Initialize next_layer
void Reconstruction::loadAdjacent(const char *filename) {
FILE*fp = fopen(filename, "r");
if (!fp) {
cout << "Could not open " << filename << endl;
exit(0);
}
for (int i = 0; i < LAYERS; i++)
for (int j = 0; j < LAYERS; j++)
if (!fscanf(fp, "%d", &next_layer[i][j])) cout << "Error reading adjacent file" << endl;
fclose(fp);
}
//Attempt to add all duplicate hits (hits on same layer as an already added hit in the path) to the paths
vector<vector<int> > Reconstruction::addDuplicates(vector<vector<int> >&paths) {
vector<vector<int> > extended;
int n = (int) paths.size();
for (int i=0;i<n;i++)
{
auto &path = paths[i];
if (path.size() < 3) continue;
vector<int> ext;
for (int i = 0; i < (int)path.size(); i++) {
ext.push_back(path[i]);
int ai, bi, ci;
if (i < (int)path.size()-2) {
ai = path[i];
bi = path[i+1];
ci = path[i+2];
}
else if (i == (int)path.size()-1) {
ai = path[i-2];
bi = path[i-1];
ci = path[i];
}
else {
ai = path[i-1];
bi = path[i];
ci = path[i+1];
}
int li = metai[path[i]];
point d, dp, xp, bap;
//Add on average about "target" outliers to each path
const double target = 0.1;
if (prepareDuplicateScore(ai, bi, ci, li, d, dp, xp, bap)) continue;
double tt = findDensity(dp, xp, target, li);
int pi = path[i];
int matches = mod[li]->getNear(dp, xp, bap, tt, match);//target/fac
map<int, pair<double, int> > mins;
for (int i = 0; i < matches; i++) {
int di = match[i];
//if (di == bi) continue; // same hit
//if (assignment[di]!=0) continue;
double s = evaluateScore(di, dp, xp, bap);//*fac; scoreTriple(ai,bi,di);
//if (s > 1.0) continue;
if (meta[di].z != meta[pi].z) {
int zi = metaz[di];
if (!mins.count(zi) || s < mins[zi].first) {
mins[zi] = make_pair(s, di);
}
}
}
for (auto &p : mins)
ext.push_back(p.second.second);
}
path.clear();
path.shrink_to_fit();
extended.push_back(ext);
}
// Remove duplicate hits in a path
// by moving the hits through a set
for (auto &path : extended) {
set<int> s;
for(auto &it : path) s.insert(it);
path.assign( s.begin(), s.end() );
path.shrink_to_fit();
}
// Remove duplicate paths
// by sorting and pruning
sort(extended.begin(),extended.end());
extended.erase(unique(extended.begin(),extended.end() ),extended.end());
return extended;
}
//Similar to the other prepareXScore functions, but now we try to find duplicates on layer "li" to one of the input hits. This means looking for hits that are close to the helix fitted through "ai", "bi", "ci"
int Reconstruction::prepareDuplicateScore(int ai, int bi, int ci, int li, point&d, point&dp, point&xp, point&dirp) {
Layer&l = layer[li];
point a = hits[ai], b = hits[bi], c = hits[ci];
//Find circle with center p, radius r, going through a, b, and c (in xy plane)
double ax = a.x-c.x, ay = a.y-c.y, bx = b.x-c.x, by = b.y-c.y;
double aa = ax*ax+ay*ay, bb = bx*bx+by*by;
double idet = .5/(ax*by-ay*bx);
point p;
p.x = (aa*by-bb*ay)*idet;
p.y = (ax*bb-bx*aa)*idet;
p.z = 0;
double r = dist(p.x, p.y), ir = 1./r;
p.x += c.x;
p.y += c.y;
int di = -1;
if (metai[ai] == li) di = ai;
else if (metai[bi] == li) di = bi;
else if (metai[ci] == li) di = ci;
else {
cout << "prepareDuplocateScore given layeri not corresponding to ai, bi or ci" << endl;
return -1;
}
d = hits[di];
dp = polar[di];
double rx = hits[di].x-p.x, ry = hits[di].y-p.y;
//TODO: do with respect to nearest circle arc, not ca
point ca = hits[ci]-hits[ai];
double ang_ca = asin(dist(ca.x, ca.y)*.5*ir)*2;
double cross = rx*ca.y-ry*ca.x;
point dir;