File: NavigationKernelBenchmarker.cpp

package info (click to toggle)
vecgeom 1.2.8%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 24,016 kB
  • sloc: cpp: 88,803; ansic: 6,888; python: 1,035; sh: 582; sql: 538; makefile: 23
file content (759 lines) | stat: -rw-r--r-- 28,428 bytes parent folder | download
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
#include "VecGeom/volumes/utilities/VolumeUtilities.h"
#include "VecGeom/base/Global.h"
#include "VecGeom/base/Vector3D.h"
#include "VecGeom/base/SOA3D.h"
#include "VecGeom/base/RNG.h"
#include "VecGeom/navigation/GlobalLocator.h"
#include "VecGeom/navigation/NavStatePool.h"
#include "VecGeom/navigation/NavigationState.h"
#include "VecGeom/volumes/PlacedVolume.h"
#include "VecGeom/volumes/LogicalVolume.h"

#include "VecGeomTest/RootGeoManager.h"

#include "VecGeom/management/GeoManager.h"
#include "VecGeom/base/Stopwatch.h"
#include "VecGeom/navigation/NewSimpleNavigator.h"
#include "VecGeom/navigation/SimpleABBoxNavigator.h"
#include "VecGeom/navigation/SimpleABBoxLevelLocator.h"
#include "VecGeom/navigation/HybridLevelLocator.h"
#include "VecGeom/navigation/HybridNavigator2.h"
#include "VecGeom/management/HybridManager2.h"
#ifdef VECGEOM_EMBREE
#include "VecGeom/navigation/EmbreeNavigator.h"
#endif
//#define BENCH_GENERATED_NAVIGATOR
#ifdef BENCH_GENERATED_NAVIGATOR
#include "VecGeom/navigation/GeneratedNavigator.h"
#endif

#ifdef VECGEOM_ROOT
#include "TGeoNavigator.h"
#include "TGeoNode.h"
#include "TGeoManager.h"
#include "TGeoBranchArray.h"
#include "TGeoBBox.h"
#endif

#ifdef VECGEOM_GEANT4
#include "G4Navigator.hh"
#include "G4VPhysicalVolume.hh"
#include "G4ThreeVector.hh"
#include "VecGeomTest/G4GeoManager.h"
#endif

#include <iostream>
#include <set>
#include <sstream>
#include <dlfcn.h>

#undef NDEBUG
#include <cassert>

//#define CALLGRIND_ENABLED
#ifdef CALLGRIND_ENABLED
#include <valgrind/callgrind.h>
#endif

#ifdef CALLGRIND_ENABLED
#define RUNBENCH(NAME)             \
  CALLGRIND_START_INSTRUMENTATION; \
  NAME;                            \
  CALLGRIND_STOP_INSTRUMENTATION;  \
  CALLGRIND_DUMP_STATS
#else
#define RUNBENCH(NAME) NAME
#endif

using namespace vecgeom;

bool gBenchVecInterface = false;
bool gAnalyseOutStates  = false;
bool gBenchWithSafety   = false;
bool gSpecializedLib    = false;
Precision gMAXSTEP      = vecgeom::kInfLength; // global variable to configure max step asked in ComputeStep

std::string gSpecLibName;
VNavigator const *gSpecializedNavigator;

void InitNavigators()
{
  for (auto &lvol : GeoManager::Instance().GetLogicalVolumesMap()) {
    if (lvol.second->GetDaughtersp()->size() < 4) {
      lvol.second->SetNavigator(NewSimpleNavigator<>::Instance());
    }
    if (lvol.second->GetDaughtersp()->size() >= 5) {
      lvol.second->SetNavigator(SimpleABBoxNavigator<>::Instance());
    }
    if (lvol.second->GetDaughtersp()->size() >= 10) {
      lvol.second->SetNavigator(HybridNavigator<>::Instance());
      HybridManager2::Instance().InitStructure((lvol.second));
    }
    if (lvol.second->GetDaughtersp()->size() >= 10) {
      lvol.second->SetNavigator(HybridNavigator<>::Instance());
      HybridManager2::Instance().InitStructure((lvol.second));
    }

    if (lvol.second->ContainsAssembly()) {
      lvol.second->SetLevelLocator(SimpleAssemblyAwareABBoxLevelLocator::GetInstance());
    } else {
      lvol.second->SetLevelLocator(SimpleABBoxLevelLocator::GetInstance());
    }
  }
}

void InitSpecializedNavigators(std::string libname)
{
  void *handle;
  handle = dlopen(libname.c_str(), RTLD_NOW);
  if (!handle) {
    std::cerr << "Error loading navigator shared lib: " << dlerror() << "\n";
    std::cerr << "doing nothing ... \n";
    return;
  }

  // the create detector "function type":
  typedef void (*InitFunc_t)();

  // find entry symbol correct symbol in lib
  // TODO: get rid of hard coded name (which might not be portable)
  InitFunc_t init = (InitFunc_t)dlsym(handle, "_Z25InitSpecializedNavigatorsv");

  if (init != nullptr) {
    // call the init function which is going to set specific navigators as
    // compiled in by the user
    init();
  } else {
    std::cerr << "Init specialized navigators from shared lib failed; symbol not found\n";
  }
}

void analyseOutStates(NavStatePool &inpool, NavStatePool const &outpool)
{
  std::set<VPlacedVolume const *> pset;
  std::set<LogicalVolume const *> lset;
  std::set<std::string> pathset;
  std::set<std::string> crossset;
  std::set<std::string> diffset;
  std::set<std::string> matrices;
  for (auto j = decltype(outpool.capacity()){0}; j < outpool.capacity(); ++j) {
    std::stringstream pathstringstream2;
    auto *navstate = outpool[j];
    navstate->printValueSequence(pathstringstream2);
    pset.insert(navstate->Top());
    lset.insert(navstate->Top()->GetLogicalVolume());
    pathset.insert(pathstringstream2.str());

    std::stringstream pathstringstream1;
    auto *instate = inpool[j];
    instate->printValueSequence(pathstringstream1);
    crossset.insert(pathstringstream1.str() + " -- " + pathstringstream2.str());
    diffset.insert(instate->RelativePath(*navstate));

    Transformation3D g;
    Transformation3D g2;
    Transformation3D invg2;

    instate->TopMatrix(g);
    navstate->TopMatrix(g2);
    g.SetProperties();
    g2.SetProperties();
    g2.Inverse(invg2);
    invg2.MultiplyFromRight(g);
    invg2.FixZeroes();
    std::stringstream matrixstream;
    invg2.Print(matrixstream);
    matrices.insert(matrixstream.str());
  }

  std::cerr << " size of diffset " << diffset.size() << "\n";
  std::cerr << " size of matrixset " << matrices.size() << "\n";
  std::cerr << " size of target pset " << pset.size() << "\n";
  std::cerr << " size of target lset " << lset.size() << "\n";
  std::cerr << " size of target state set " << pathset.size() << "\n";
  std::cerr << " total combinations " << crossset.size() << "\n";
  std::cerr << " normalized per input state " << crossset.size() / (1. * pathset.size()) << "\n";

  for (auto &s : crossset) {
    std::cerr << s << "\n";
  }
  for (auto &s : diffset) {
    std::cerr << s << "\n";
  }
  for (auto &s : matrices) {
    std::cerr << s << "\n";
  }
}

#ifdef VECGEOM_ROOT
template <bool WithSafety = false, bool WithReloc = true>
__attribute__((noinline)) void benchmarkROOTNavigator(SOA3D<Precision> const &points, SOA3D<Precision> const &dirs)
{

  TGeoNavigator *rootnav      = ::gGeoManager->GetCurrentNavigator();
  auto nPoints                = points.size();
  TGeoBranchArray **instates  = new TGeoBranchArray *[nPoints];
  TGeoBranchArray **outstates = new TGeoBranchArray *[nPoints];
  Precision *steps            = new Precision[points.size()];
  Precision *safeties;
  if (WithSafety) {
    safeties = new Precision[points.size()];
  }
  // we don't have the input state container in ROOT form
  // we generate them but do not take this into account for the timing measurement
  for (size_t i = 0; i < nPoints; ++i) {
    Vector3D<Precision> const &pos = points[i];
    rootnav->ResetState();
    rootnav->FindNode(pos.x(), pos.y(), pos.z());
    instates[i]  = TGeoBranchArray::MakeInstance(GeoManager::Instance().getMaxDepth());
    outstates[i] = TGeoBranchArray::MakeInstance(GeoManager::Instance().getMaxDepth());
    instates[i]->InitFromNavigator(rootnav);
  }
#ifdef CALLGRIND_ENABLED
  CALLGRIND_START_INSTRUMENTATION;
#endif
  Stopwatch timer;
  timer.Start();
  for (size_t i = 0; i < nPoints; ++i) {
    Vector3D<Precision> const &pos = points[i];
    Vector3D<Precision> const &dir = dirs[i];
    rootnav->ResetState();
    instates[i]->UpdateNavigator(rootnav);

    rootnav->SetCurrentPoint(pos.x(), pos.y(), pos.z());
    rootnav->SetCurrentDirection(dir.x(), dir.y(), dir.z());
    if (WithSafety) {
      safeties[i] = rootnav->Safety(true);
    }
    if (WithReloc) {
      volatile TGeoNode *node = rootnav->FindNextBoundaryAndStep(gMAXSTEP);
      (void)node;
    } else {
      volatile TGeoNode *node = rootnav->FindNextBoundary(gMAXSTEP);
      (void)node;
    }
    steps[i] = rootnav->GetStep();
    if (WithReloc) {
      // save output states ( for fair comparison with VecGeom )
      outstates[i]->InitFromNavigator(rootnav);
    }
  }
  timer.Stop();
#ifdef CALLGRIND_ENABLED
  CALLGRIND_STOP_INSTRUMENTATION;
  CALLGRIND_DUMP_STATS;
#endif
  std::cerr << timer.Elapsed() << "\n";
  Precision accum(0.);
  Precision saccum(0.);
  size_t hittargetchecksum = 0L;
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    accum += steps[i];
    if (WithSafety) {
      saccum += safeties[i];
    }
    // target checksum via the table held from RootGeoManager
    std::cerr << "i/size=" << i << '/' << points.size() << "\n";
    hittargetchecksum +=
        (size_t)RootGeoManager::Instance().Lookup(outstates[i]->GetNode(outstates[i]->GetLevel()))->id();
  }
  delete[] steps;
  if (WithSafety) {
    delete[] safeties;
  }

  // cleanup states
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    delete instates[i];
    delete outstates[i];
  }
  delete[] instates;
  delete[] outstates;

  std::cerr << "accum  TGeo " << accum << " target checksum " << hittargetchecksum << "\n";
  if (WithSafety) {
    std::cerr << "safety accum  TGeo " << saccum << "\n";
  }
}

#ifdef VECGEOM_GEANT4
template <bool WithSafety = false>
__attribute__((noinline)) void benchmarkG4Navigator(SOA3D<Precision> const &points, SOA3D<Precision> const &dirs)
{
  G4VPhysicalVolume *world(vecgeom::G4GeoManager::Instance().GetG4GeometryFromROOT());
  if (world != nullptr) G4GeoManager::Instance().LoadG4Geometry(world);

  // Note: Vector3D's are expressed in cm, while G4ThreeVectors are expressed in mm
  const Precision cm = 10.; // cm --> mm conversion
  G4Navigator &g4nav = *(G4GeoManager::Instance().GetNavigator());
  // G4TouchableHistory **g4history = new G4TouchableHistory *[nPoints];

  Precision *steps = new Precision[points.size()];

  // get a time estimate to just to locate points
  // (The reason is that the G4Navigator has a huge internal state and it is not foreseen to do
  //  multi-track processing with a basked of G4TouchableHistories as states)
  Stopwatch timer;
  timer.Start();
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    G4ThreeVector g4pos(points[i].x() * cm, points[i].y() * cm, points[i].z() * cm);
    G4ThreeVector g4dir(dirs[i].x(), dirs[i].y(), dirs[i].z());
    // false --> locate from top
    g4nav.LocateGlobalPointAndSetup(g4pos, &g4dir, false);
  }
  Precision timeForLocate = (Precision)timer.Stop();

#ifdef CALLGRIND_ENABLED
  CALLGRIND_START_INSTRUMENTATION;
#endif
  timer.Start();
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    G4ThreeVector g4pos(points[i].x() * cm, points[i].y() * cm, points[i].z() * cm);
    G4ThreeVector g4dir(dirs[i].x(), dirs[i].y(), dirs[i].z());
    G4double maxStep = gMAXSTEP;

    // false --> locate from top
    G4VPhysicalVolume const *vol = g4nav.LocateGlobalPointAndSetup(g4pos, &g4dir, false);
    (void)vol;
    G4double safety = 0.0;
    steps[i]        = g4nav.ComputeStep(g4pos, g4dir, maxStep, safety);

    G4ThreeVector nextPos = g4pos + (steps[i] + 1.0e-6) * g4dir;
    // TODO: save touchable history array - returnable?  symmetrize with ROOT/VECGEOM benchmark
    g4nav.SetGeometricallyLimitedStep();

    volatile G4VPhysicalVolume const *nextvol = g4nav.LocateGlobalPointAndSetup(nextPos);
    (void)nextvol;
  }
  timer.Stop();
  std::cerr << (Precision)timer.Elapsed() - timeForLocate << "\n";
#ifdef CALLGRIND_ENABLED
  CALLGRIND_STOP_INSTRUMENTATION;
  CALLGRIND_DUMP_STATS;
#endif
  // cleanup
  // delete[] g4history;
  //_mm_free(maxSteps);
  Precision accum{0.};
  size_t hittargetchecksum{0L};
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    accum += steps[i];
    if (WithSafety) {
      // saccum += safeties[i];
    }
    // target checksum via the table held from RootGeoManager
    // hittargetchecksum +=
    //    (size_t)RootGeoManager::Instance().Lookup(outstates[i]->GetNode(outstates[i]->GetLevel()))->id();
  }
  std::cerr << "accum  G4 " << accum / cm << " target checksum " << hittargetchecksum << "\n";
}
#endif // end if G4
#endif // end if ROOT

template <bool WithSafety = true>
__attribute__((noinline)) void benchNavigator(VNavigator const *se, SOA3D<Precision> const &points,
                                              SOA3D<Precision> const &dirs, NavStatePool const &inpool,
                                              NavStatePool &outpool)
{
  Precision *steps = new Precision[points.size()];
  Precision *safeties;
  if (WithSafety) safeties = new Precision[points.size()];
  Stopwatch timer;
  size_t hittargetchecksum = 0L;
  timer.Start();
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    if (WithSafety) {
      steps[i] = se->ComputeStepAndSafetyAndPropagatedState(points[i], dirs[i], gMAXSTEP, *inpool[i], *outpool[i], true,
                                                            safeties[i]);
    } else {
      steps[i] = se->ComputeStepAndPropagatedState(points[i], dirs[i], gMAXSTEP, *inpool[i], *outpool[i]);
    }
  }
  timer.Stop();
  std::cerr << timer.Elapsed() << "\n";
  Precision accum(0.), saccum(0.);
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    accum += steps[i];
    if (WithSafety) {
      saccum += safeties[i];
    }
    if (outpool[i]->Top()) hittargetchecksum += (size_t)outpool[i]->Top()->id();
  }
  delete[] steps;
  std::cerr << "accum  " << se->GetName() << " " << accum << " target checksum " << hittargetchecksum << "\n";
  if (WithSafety) {
    std::cerr << "saccum  " << se->GetName() << " " << saccum << "\n";
  }
}

// version benchmarking navigation without relocation
template <bool WithSafety = true>
__attribute__((noinline)) void benchNavigatorNoReloc(VNavigator const *se, SOA3D<Precision> const &points,
                                                     SOA3D<Precision> const &dirs, NavStatePool const &inpool,
                                                     NavStatePool &outpool)
{
  Precision *steps = new Precision[points.size()];
  Precision *safeties;
  if (WithSafety) safeties = new Precision[points.size()];
  Stopwatch timer;
  size_t hittargetchecksum = 0L;
  timer.Start();
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    if (WithSafety) {
      steps[i] = se->ComputeStepAndSafety(points[i], dirs[i], gMAXSTEP, *const_cast<NavigationState *>(inpool[i]), true,
                                          safeties[i]);
    } else {
      steps[i] = se->ComputeStep(points[i], dirs[i], gMAXSTEP, *inpool[i], *outpool[i]);
    }
  }
  timer.Stop();
  std::cerr << timer.Elapsed() << "\n";
  Precision accum(0.), saccum(0.);
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    accum += steps[i];
    if (WithSafety) {
      saccum += safeties[i];
    }
    if (outpool[i]->Top()) hittargetchecksum += (size_t)outpool[i]->Top()->id();
  }
  delete[] steps;
  std::cerr << "accum  " << se->GetName() << " " << accum << " target checksum " << hittargetchecksum << "\n";
  if (WithSafety) {
    std::cerr << "saccum  " << se->GetName() << " " << saccum << "\n";
  }
}

template <typename T, bool WithSafety = true>
__attribute__((noinline)) void benchVectorNavigator(SOA3D<Precision> const &__restrict__ points,
                                                    SOA3D<Precision> const &__restrict__ dirs,
                                                    NavStatePool const &__restrict__ inpool,
                                                    NavStatePool &__restrict__ outpool)
{
  Precision *step_max = (Precision *)vecCore::AlignedAlloc(32, sizeof(Precision) * points.size());
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    step_max[i] = gMAXSTEP;
  }
  Precision *steps    = (Precision *)vecCore::AlignedAlloc(32, sizeof(Precision) * points.size());
  Precision *safeties = nullptr;
  bool *calcs;
  if (WithSafety) {
    safeties = (Precision *)vecCore::AlignedAlloc(32, sizeof(Precision) * points.size());
    calcs    = (bool *)vecCore::AlignedAlloc(32, sizeof(bool) * points.size());
    for (decltype(points.size()) i = 0; i < points.size(); ++i)
      calcs[i] = true;
  }

  Stopwatch timer;
  VNavigator *se = T::Instance();
  NavigationState const **inpoolarray;
  NavigationState **outpoolarray;
  inpool.ToPlainPointerArray(inpoolarray);
  outpool.ToPlainPointerArray(outpoolarray);
  timer.Start();
  if (WithSafety) {
    se->ComputeStepsAndSafetiesAndPropagatedStates(points, dirs, step_max, inpoolarray, outpoolarray, steps, calcs,
                                                   safeties);
  } else {
    se->ComputeStepsAndPropagatedStates(points, dirs, step_max, inpoolarray, outpoolarray, steps);
  }
  timer.Stop();
  std::cerr << timer.Elapsed() << "\n";
  Precision accum(0.);
  Precision saccum(0.);
  size_t hittargetchecksum = 0L;
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    // std::cerr << "---- " << steps[i] << "\n";
    accum += steps[i];
    if (WithSafety) {
      saccum += safeties[i];
    }
    if (outpool[i]->Top()) hittargetchecksum += (size_t)outpool[i]->Top()->id();
  }
  std::cerr << "VECTOR accum  " << T::GetClassName() << " " << accum << " target checksum " << hittargetchecksum
            << "\n";
  if (WithSafety) {
    std::cerr << "VECTOR saccum  " << T::GetClassName() << " " << saccum << "\n";
    vecCore::AlignedFree(safeties);
  }
  vecCore::AlignedFree(steps);
  vecCore::AlignedFree(step_max);
  delete[] inpoolarray;
  delete[] outpoolarray;
}

template <typename T, bool WithSafety = true>
__attribute__((noinline)) void benchVectorNavigatorNoReloc(SOA3D<Precision> const &__restrict__ points,
                                                           SOA3D<Precision> const &__restrict__ dirs,
                                                           NavStatePool const &__restrict__ inpool,
                                                           NavStatePool &__restrict__ outpool)
{
  Precision *step_max = (Precision *)vecCore::AlignedAlloc(32, sizeof(Precision) * points.size());
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    step_max[i] = gMAXSTEP;
  }
  Precision *steps    = (Precision *)vecCore::AlignedAlloc(32, sizeof(Precision) * points.size());
  Precision *safeties = nullptr;
  bool *calcs;

  if (WithSafety) {
    safeties = (Precision *)vecCore::AlignedAlloc(32, sizeof(Precision) * points.size());
    calcs    = (bool *)vecCore::AlignedAlloc(32, sizeof(bool) * points.size());
    for (decltype(points.size()) i = 0; i < points.size(); ++i)
      calcs[i] = true;
  }

  Stopwatch timer;
  VNavigator *se = T::Instance();
  NavigationState const **inpoolarray;
  NavigationState **outpoolarray;
  inpool.ToPlainPointerArray(inpoolarray);
  outpool.ToPlainPointerArray(outpoolarray);
  timer.Start();
  if (WithSafety) {
    se->ComputeStepsAndSafeties(points, dirs, step_max, inpoolarray, steps, calcs, safeties);
  } else {
    // nothing to do
  }
  timer.Stop();
  std::cerr << timer.Elapsed() << "\n";
  Precision accum(0.);
  Precision saccum(0.);
  size_t hittargetchecksum = 0L;
  for (decltype(points.size()) i = 0; i < points.size(); ++i) {
    // std::cerr << "---- " << steps[i] << "\n";
    accum += steps[i];
    if (WithSafety) {
      saccum += safeties[i];
    }
    if (outpool[i]->Top()) hittargetchecksum += (size_t)outpool[i]->Top()->id();
  }
  std::cerr << "VECTOR accum  " << T::GetClassName() << " " << accum << " target checksum " << hittargetchecksum
            << "\n";
  if (WithSafety) {
    std::cerr << "VECTOR saccum  " << T::GetClassName() << " " << saccum << "\n";
    vecCore::AlignedFree(safeties);
  }
  vecCore::AlignedFree(steps);
  vecCore::AlignedFree(step_max);
  delete[] inpoolarray;
  delete[] outpoolarray;
}

template <bool WithSafety = false>
void benchDifferentNavigators(SOA3D<Precision> const &points, SOA3D<Precision> const &dirs, NavStatePool &pool,
                              NavStatePool &outpool, std::string outfilenamebase)
{
  std::cerr << "##\n";
  if (gSpecializedLib) {
    RUNBENCH((benchNavigator<WithSafety>(gSpecializedNavigator, points, dirs, pool, outpool)));
  }
  std::cerr << "##\n";
  RUNBENCH((benchNavigator<WithSafety>(NewSimpleNavigator<false>::Instance(), points, dirs, pool, outpool)));
  std::stringstream str;
  str << outfilenamebase << "_simple.bin";
  outpool.ToFile(str.str());
  std::cerr << "##\n";
  RUNBENCH((benchNavigator<WithSafety>(NewSimpleNavigator<true>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";

#ifdef VECGEOM_ROOT
  benchmarkROOTNavigator<WithSafety>(points, dirs);
#ifdef VECGEOM_GEANT4
  benchmarkG4Navigator<WithSafety>(points, dirs);
#endif // VECGEOM_GEANT4
#endif

#ifdef BENCH_GENERATED_NAVIGATOR
  RUNBENCH((benchNavigator<GeneratedNavigator, WithSafety>(points, dirs, pool, outpool)));
  outpool.ToFile("generatedoutpool.bin");
  std::cerr << "##\n";
  RUNBENCH((benchVectorNavigator<GeneratedNavigator, WithSafety>(points, dirs, pool, outpool)));
  std::cerr << "##\n";
#endif
  if (gBenchVecInterface) {
    RUNBENCH((benchVectorNavigator<NewSimpleNavigator<false>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
    RUNBENCH((benchVectorNavigator<NewSimpleNavigator<true>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
  }
  RUNBENCH((benchNavigator<WithSafety>(SimpleABBoxNavigator<false>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";
  RUNBENCH((benchNavigator<WithSafety>(SimpleABBoxNavigator<false>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";
  if (gBenchVecInterface) {
    RUNBENCH((benchVectorNavigator<SimpleABBoxNavigator<false>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
    RUNBENCH((benchVectorNavigator<SimpleABBoxNavigator<true>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
  }
  RUNBENCH((benchNavigator<WithSafety>(HybridNavigator<false>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";
  RUNBENCH((benchNavigator<WithSafety>(HybridNavigator<true>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";
  if (gBenchVecInterface) {
    RUNBENCH((benchVectorNavigator<HybridNavigator<false>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
    RUNBENCH((benchVectorNavigator<HybridNavigator<true>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
  }

#ifdef VECGEOM_EMBREE
  // Embree
  RUNBENCH((benchNavigator<WithSafety>(EmbreeNavigator<false>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";
  RUNBENCH((benchNavigator<WithSafety>(EmbreeNavigator<true>::Instance(), points, dirs, pool, outpool)));
  std::cerr << "##\n";
  if (gBenchVecInterface) {
    RUNBENCH((benchVectorNavigator<EmbreeNavigator<false>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
    RUNBENCH((benchVectorNavigator<EmbreeNavigator<true>, WithSafety>(points, dirs, pool, outpool)));
    std::cerr << "##\n";
  }
#endif

#ifdef VECGEOM_ROOT
  benchmarkROOTNavigator<WithSafety>(points, dirs);
#ifdef VECGEOM_GEANT4
  benchmarkG4Navigator<WithSafety>(points, dirs);
#endif // VECGEOM_GEANT4
#endif

  std::cerr << "## -- TESTING WITHOUT RELOC\n";
  // testing interfaces without relocation
  RUNBENCH((benchNavigatorNoReloc<WithSafety>(NewSimpleNavigator<false>::Instance(), points, dirs, pool, outpool)));
  // the vector navigator
  RUNBENCH((benchVectorNavigatorNoReloc<NewSimpleNavigator<false>, WithSafety>(points, dirs, pool, outpool)));
  // testing interfaces without relocation
  RUNBENCH((benchNavigatorNoReloc<WithSafety>(SimpleABBoxNavigator<false>::Instance(), points, dirs, pool, outpool)));
  // the vector navigator
  RUNBENCH((benchVectorNavigatorNoReloc<SimpleABBoxNavigator<false>, WithSafety>(points, dirs, pool, outpool)));

#ifdef VECGEOM_ROOT
  benchmarkROOTNavigator<true, false>(points, dirs);
#endif
  if (gAnalyseOutStates) {
    analyseOutStates(pool, outpool);
  }
}

int main(int argc, char *argv[])
{
  // read in detector passed as argument
  if (argc > 1) {
    RootGeoManager::Instance().set_verbose(3);
    RootGeoManager::Instance().LoadRootGeometry(std::string(argv[1]));
  } else {
    std::cerr << "please give a ROOT geometry file\n";
    return 1;
  }

  // play with some heuristics to init level locators
  for (auto &element : GeoManager::Instance().GetLogicalVolumesMap()) {
    LogicalVolume *lvol = element.second;
    if (lvol->GetDaughtersp()->size() > 8) {
      // HybridManager2::Instance().InitStructure(lvol);
      lvol->SetLevelLocator(SimpleABBoxLevelLocator::GetInstance());
      // lvol->SetLevelLocator(HybridLevelLocator::GetInstance());
    }
  }
  InitNavigators();

  std::string volname(argv[2]);
  auto lvol = GeoManager::Instance().FindLogicalVolume(volname.c_str());
  HybridManager2::Instance().InitStructure(lvol);
#ifdef VECGEOM_EMBREE
  EmbreeManager::Instance().InitStructure(lvol);
#endif

  // some output on volume
  std::cerr << "NavigationKernelBenchmarker run on " << argv[2] << " having " << lvol->GetDaughters().size()
            << " daughters \n";

  bool usecached = false;
  int npoints    = 500000;
  for (auto i = 3; i < argc; i++) {
    if (!strcmp(argv[i], "--usecache")) usecached = true;
    // benchmark vector interface?
    if (!strcmp(argv[i], "--vecbench")) gBenchVecInterface = true;
    // analyse state transitions
    if (!strcmp(argv[i], "--statetrans")) gAnalyseOutStates = true;
    // whether to benchmark navigation with safeties
    if (!strcmp(argv[i], "--withsafety")) gBenchWithSafety = true;
    // to set the maxstep number
    if (!strcmp(argv[i], "--maxstep")) {
      if (i + 1 < argc) {
        gMAXSTEP = atof(argv[i + 1]);
        std::cout << "setting maxstep to " << gMAXSTEP << "\n";
      }
    }
    // to set the number of tracks
    if (!strcmp(argv[i], "--ntracks")) {
      if (i + 1 < argc) {
        npoints = atoi(argv[i + 1]);
        std::cout << "setting npoints to " << npoints << "\n";
      }
    }
    if (!strcmp(argv[i], "--navlib")) {
      if (i + 1 < argc) {
        gSpecializedLib = true;
        gSpecLibName    = argv[i + 1];
        InitSpecializedNavigators(gSpecLibName);
        gSpecializedNavigator = lvol->GetNavigator();
        std::cerr << gSpecializedNavigator->GetName() << "\n";
      }
    }
  }

  // setup data structures
  SOA3D<Precision> points(npoints);
  SOA3D<Precision> localpoints(npoints);
  SOA3D<Precision> directions(npoints);
  NavStatePool statepool(npoints, GeoManager::Instance().getMaxDepth());
  NavStatePool statepoolout(npoints, GeoManager::Instance().getMaxDepth());

  std::stringstream pstream;
  std::string geomfilename(argv[1]);
  std::string geomfilename_nopath(geomfilename.substr(1 + geomfilename.find_last_of("\\/")));
  pstream << "points_" << geomfilename_nopath << "_" << argv[2] << ".bin";
  std::stringstream dstream;
  dstream << "directions_" << geomfilename_nopath << "_" << argv[2] << ".bin";
  std::stringstream statestream;
  statestream << "states_" << geomfilename_nopath << "_" << argv[2] << ".bin";
  std::stringstream outstatestream;
  outstatestream << "outstates_" << geomfilename_nopath << "_" << argv[2];
  if (usecached) {
    std::cerr << " loading points from cache \n";
    bool fail = (npoints != points.FromFile(pstream.str()));
    fail |= (npoints != directions.FromFile(dstream.str()));
    fail |= (npoints != statepool.FromFile(statestream.str()));
    if (fail) {
      std::cerr << " loading points from cache failed ... continuing normally \n";
      usecached = false;
    }
  }
  if (!usecached) {
    volumeUtilities::FillGlobalPointsAndDirectionsForLogicalVolume<SOA3D<Precision>>(lvol, localpoints, points,
                                                                                     directions, 0.4, npoints);
    std::cerr << "\n points filled\n";
    for (unsigned int i = 0; i < points.size(); ++i) {
      GlobalLocator::LocateGlobalPoint(GeoManager::Instance().GetWorld(), points[i], *(statepool[i]), true);
      if (statepool[i]->Top()->GetLogicalVolume() != lvol) {
        //
        std::cerr << "problem : point " << i << " probably in overlapping region \n";
        points.set(i, points[i - 1]);
        statepool[i - 1]->CopyTo(statepool[i]);
      }
    }
    std::cerr << "located ...\n";

    points.ToFile(pstream.str());
    directions.ToFile(dstream.str());
    statepool.ToFile(statestream.str());
  }
  if (gBenchWithSafety) {
    benchDifferentNavigators<true>(points, directions, statepool, statepoolout, outstatestream.str());
  } else {
    benchDifferentNavigators<false>(points, directions, statepool, statepoolout, outstatestream.str());
  }
  return 0;
}