forked from acts-project/acts
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGeant4Simulation.cpp
More file actions
424 lines (356 loc) · 15 KB
/
Geant4Simulation.cpp
File metadata and controls
424 lines (356 loc) · 15 KB
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
// This file is part of the ACTS project.
//
// Copyright (C) 2016 CERN for the benefit of the ACTS project
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
#include "ActsExamples/Geant4/Geant4Simulation.hpp"
#include "Acts/Definitions/Algebra.hpp"
#include "Acts/Utilities/Logger.hpp"
#include "ActsExamples/Framework/AlgorithmContext.hpp"
#include "ActsExamples/Framework/IAlgorithm.hpp"
#include "ActsExamples/Framework/RandomNumbers.hpp"
#include "ActsExamples/Framework/WhiteBoard.hpp"
#include "ActsExamples/Geant4/EventStore.hpp"
#include "ActsExamples/Geant4/Geant4Manager.hpp"
#include "ActsExamples/Geant4/MagneticFieldWrapper.hpp"
#include "ActsExamples/Geant4/MaterialPhysicsList.hpp"
#include "ActsExamples/Geant4/MaterialSteppingAction.hpp"
#include "ActsExamples/Geant4/ParticleKillAction.hpp"
#include "ActsExamples/Geant4/ParticleTrackingAction.hpp"
#include "ActsExamples/Geant4/SensitiveSteppingAction.hpp"
#include "ActsExamples/Geant4/SensitiveSurfaceMapper.hpp"
#include "ActsExamples/Geant4/SimParticleTranslation.hpp"
#include "ActsExamples/Geant4/SteppingActionList.hpp"
#include "ActsPlugins/FpeMonitoring/FpeMonitor.hpp"
#include <stdexcept>
#include <utility>
#include <G4FieldManager.hh>
#include <G4RunManager.hh>
#include <G4TransportationManager.hh>
#include <G4UniformMagField.hh>
#include <G4UserEventAction.hh>
#include <G4UserLimits.hh>
#include <G4UserRunAction.hh>
#include <G4UserSteppingAction.hh>
#include <G4UserTrackingAction.hh>
#include <G4VUserDetectorConstruction.hh>
#include <G4VUserPhysicsList.hh>
#include <G4Version.hh>
#include <Randomize.hh>
namespace ActsExamples {
Geant4SimulationBase::Geant4SimulationBase(
const Config& cfg, const std::string& name,
std::unique_ptr<const Acts::Logger> logger)
: IAlgorithm(name, std::move(logger)) {
if (cfg.inputParticles.empty()) {
throw std::invalid_argument("Missing input particle collection");
}
if (cfg.detector == nullptr) {
throw std::invalid_argument("Missing detector construction factory");
}
if (cfg.randomNumbers == nullptr) {
throw std::invalid_argument("Missing random numbers");
}
m_eventStore = std::make_shared<Geant4::EventStore>();
// tweak logging
// If we are in VERBOSE mode, set the verbose level in Geant4 to 2.
// 3 would be also possible, but that produces infinite amount of output.
m_geant4Level = this->logger().level() == Acts::Logging::VERBOSE ? 2 : 0;
}
Geant4SimulationBase::~Geant4SimulationBase() = default;
void Geant4SimulationBase::commonInitialization() {
// Set the detector construction
{
// Clear detector construction if it exists
if (runManager().GetUserDetectorConstruction() != nullptr) {
delete runManager().GetUserDetectorConstruction();
}
// G4RunManager will take care of deletion
m_detectorConstruction =
config()
.detector
->buildGeant4DetectorConstruction(config().constructionOptions)
.release();
runManager().SetUserInitialization(m_detectorConstruction);
runManager().InitializeGeometry();
}
m_geant4Instance->tweakLogging(m_geant4Level);
}
G4RunManager& Geant4SimulationBase::runManager() const {
return *m_geant4Instance->runManager;
}
Geant4::EventStore& Geant4SimulationBase::eventStore() const {
return *m_eventStore;
}
ProcessCode Geant4SimulationBase::initialize() {
// Initialize the Geant4 run manager
runManager().Initialize();
return ProcessCode::SUCCESS;
}
ProcessCode Geant4SimulationBase::execute(const AlgorithmContext& ctx) const {
// Ensure exclusive access to the Geant4 run manager
std::lock_guard<std::mutex> guard(m_geant4Instance->mutex);
// Set the seed new per event, so that we get reproducible results
G4Random::setTheSeed(config().randomNumbers->generateSeed(ctx));
// Get and reset event registry state
eventStore() = Geant4::EventStore{};
// Register the current event store to the registry
// this will allow access from the User*Actions
eventStore().store = &(ctx.eventStore);
// Register the input particle read handle
eventStore().inputParticles = &m_inputParticles;
eventStore().geoContext = ctx.geoContext;
ACTS_DEBUG("Sending Geant RunManager the BeamOn() command.");
{
ActsPlugins::FpeMonitor mon{0}; // disable all FPEs while we're in Geant4
// Start simulation. each track is simulated as a separate Geant4 event.
runManager().BeamOn(1);
}
// Print out warnings about possible particle collision if happened
if (eventStore().particleIdCollisionsInitial > 0 ||
eventStore().particleIdCollisionsFinal > 0 ||
eventStore().parentIdNotFound > 0) {
ACTS_WARNING(
"Particle ID collisions detected, don't trust the particle "
"identification!");
ACTS_WARNING(
"- initial states: " << eventStore().particleIdCollisionsInitial);
ACTS_WARNING("- final states: " << eventStore().particleIdCollisionsFinal);
ACTS_WARNING("- parent ID not found: " << eventStore().parentIdNotFound);
}
if (eventStore().hits.empty()) {
ACTS_DEBUG("Step merging: No steps recorded");
} else {
ACTS_DEBUG("Step merging: mean hits per hit: "
<< static_cast<double>(eventStore().numberGeantSteps) /
eventStore().hits.size());
ACTS_DEBUG(
"Step merging: max hits per hit: " << eventStore().maxStepsForHit);
}
return ProcessCode::SUCCESS;
}
std::shared_ptr<Geant4Handle> Geant4SimulationBase::geant4Handle() const {
return m_geant4Instance;
}
Geant4Simulation::Geant4Simulation(const Config& cfg,
std::unique_ptr<const Acts::Logger> logger)
: Geant4SimulationBase(cfg, "Geant4Simulation", std::move(logger)),
m_cfg(cfg) {
m_geant4Instance =
m_cfg.geant4Handle
? m_cfg.geant4Handle
: Geant4Manager::instance().createHandle(m_cfg.physicsList);
if (m_geant4Instance->physicsListName != m_cfg.physicsList) {
throw std::runtime_error("inconsistent physics list");
}
commonInitialization();
// Set the primarty generator
{
// Clear primary generation action if it exists
if (runManager().GetUserPrimaryGeneratorAction() != nullptr) {
delete runManager().GetUserPrimaryGeneratorAction();
}
Geant4::SimParticleTranslation::Config prCfg;
prCfg.eventStore = m_eventStore;
// G4RunManager will take care of deletion
auto primaryGeneratorAction = new Geant4::SimParticleTranslation(
prCfg, this->logger().cloneWithSuffix("SimParticleTranslation"));
// Set the primary generator action
runManager().SetUserAction(primaryGeneratorAction);
}
// Particle action
{
// Clear tracking action if it exists
if (runManager().GetUserTrackingAction() != nullptr) {
delete runManager().GetUserTrackingAction();
}
Geant4::ParticleTrackingAction::Config trackingCfg;
trackingCfg.eventStore = m_eventStore;
trackingCfg.keepParticlesWithoutHits = cfg.keepParticlesWithoutHits;
// G4RunManager will take care of deletion
auto trackingAction = new Geant4::ParticleTrackingAction(
trackingCfg, this->logger().cloneWithSuffix("ParticleTracking"));
runManager().SetUserAction(trackingAction);
}
// Stepping actions
Geant4::SensitiveSteppingAction* sensitiveSteppingActionAccess = nullptr;
{
// Clear stepping action if it exists
if (runManager().GetUserSteppingAction() != nullptr) {
delete runManager().GetUserSteppingAction();
}
Geant4::ParticleKillAction::Config particleKillCfg;
particleKillCfg.eventStore = m_eventStore;
particleKillCfg.volume = cfg.killVolume;
particleKillCfg.maxTime = cfg.killAfterTime;
particleKillCfg.secondaries = cfg.killSecondaries;
Geant4::SensitiveSteppingAction::Config stepCfg;
stepCfg.eventStore = m_eventStore;
stepCfg.charged = cfg.recordHitsOfCharged;
stepCfg.neutral = cfg.recordHitsOfNeutrals;
stepCfg.primary = cfg.recordHitsOfPrimaries;
stepCfg.secondary = cfg.recordHitsOfSecondaries;
stepCfg.stepLogging = cfg.recordPropagationSummaries;
Geant4::SteppingActionList::Config steppingCfg;
steppingCfg.actions.push_back(std::make_unique<Geant4::ParticleKillAction>(
particleKillCfg, this->logger().cloneWithSuffix("Killer")));
auto sensitiveSteppingAction =
std::make_unique<Geant4::SensitiveSteppingAction>(
stepCfg, this->logger().cloneWithSuffix("SensitiveStepping"));
sensitiveSteppingActionAccess = sensitiveSteppingAction.get();
steppingCfg.actions.push_back(std::move(sensitiveSteppingAction));
// G4RunManager will take care of deletion
auto steppingAction = new Geant4::SteppingActionList(steppingCfg);
runManager().SetUserAction(steppingAction);
}
// Get the g4World cache
G4VPhysicalVolume* g4World = m_detectorConstruction->Construct();
// Please note:
// The following two blocks rely on the fact that the Acts
// detector constructions cache the world volume
// Set the magnetic field
if (cfg.magneticField) {
ACTS_LOG_WITH_LOGGER(this->logger(), Acts::Logging::INFO,
"Setting ACTS configured field to Geant4.");
Geant4::MagneticFieldWrapper::Config g4FieldCfg;
g4FieldCfg.magneticField = cfg.magneticField;
m_magneticField =
std::make_unique<Geant4::MagneticFieldWrapper>(g4FieldCfg);
// Set the field or the G4Field manager
m_fieldManager = std::make_unique<G4FieldManager>();
m_fieldManager->SetDetectorField(m_magneticField.get());
m_fieldManager->CreateChordFinder(m_magneticField.get());
// Propagate down to all childrend
g4World->GetLogicalVolume()->SetFieldManager(m_fieldManager.get(), true);
}
// ACTS sensitive surfaces are provided, so hit creation is turned on
if (cfg.sensitiveSurfaceMapper != nullptr) {
Geant4::SensitiveSurfaceMapper::State sState;
ACTS_LOG_WITH_LOGGER(this->logger(), Acts::Logging::INFO,
"Remapping selected volumes from Geant4 to "
"Acts::Surface::GeometryID");
cfg.sensitiveSurfaceMapper->remapSensitiveNames(
sState, Acts::GeometryContext::dangerouslyDefaultConstruct(), g4World,
Acts::Transform3::Identity());
auto allSurfacesMapped = cfg.sensitiveSurfaceMapper->checkMapping(
sState, Acts::GeometryContext::dangerouslyDefaultConstruct(), false,
false);
if (!allSurfacesMapped) {
ACTS_LOG_WITH_LOGGER(this->logger(), Acts::Logging::WARNING,
"Not all sensitive surfaces have been mapped to "
"Geant4 volumes!");
}
sensitiveSteppingActionAccess->assignSurfaceMapping(
sState.g4VolumeToSurfaces);
}
m_inputParticles.initialize(cfg.inputParticles);
m_outputSimHits.initialize(cfg.outputSimHits);
m_outputParticles.initialize(cfg.outputParticles);
if (cfg.recordPropagationSummaries) {
m_outputPropagationSummaries.initialize(cfg.outputPropagationSummaries);
}
}
Geant4Simulation::~Geant4Simulation() = default;
ProcessCode Geant4Simulation::execute(const AlgorithmContext& ctx) const {
auto ret = Geant4SimulationBase::execute(ctx);
if (ret != ProcessCode::SUCCESS) {
return ret;
}
// Output handling: Simulation
m_outputParticles(
ctx, SimParticleContainer(eventStore().particlesSimulated.begin(),
eventStore().particlesSimulated.end()));
m_outputSimHits(
ctx, SimHitContainer(eventStore().hits.begin(), eventStore().hits.end()));
// Output the propagation summaries if requested
if (m_cfg.recordPropagationSummaries) {
PropagationSummaries summaries;
summaries.reserve(eventStore().propagationRecords.size());
for (auto& [trackId, summary] : eventStore().propagationRecords) {
summaries.push_back(std::move(summary));
}
m_outputPropagationSummaries(ctx, std::move(summaries));
}
return ProcessCode::SUCCESS;
}
Geant4MaterialRecording::Geant4MaterialRecording(
const Config& cfg, std::unique_ptr<const Acts::Logger> logger)
: Geant4SimulationBase(cfg, "Geant4Simulation", std::move(logger)),
m_cfg(cfg) {
auto physicsListName = "MaterialPhysicsList";
m_geant4Instance =
m_cfg.geant4Handle
? m_cfg.geant4Handle
: Geant4Manager::instance().createHandle(
std::make_unique<Geant4::MaterialPhysicsList>(
this->logger().cloneWithSuffix("MaterialPhysicsList")),
physicsListName);
if (m_geant4Instance->physicsListName != physicsListName) {
throw std::runtime_error("inconsistent physics list");
}
commonInitialization();
// Set the primarty generator
{
// Clear primary generation action if it exists
if (runManager().GetUserPrimaryGeneratorAction() != nullptr) {
delete runManager().GetUserPrimaryGeneratorAction();
}
Geant4::SimParticleTranslation::Config prCfg;
prCfg.eventStore = m_eventStore;
prCfg.forcedPdgCode = 0;
prCfg.forcedCharge = 0.;
prCfg.forcedMass = 0.;
// G4RunManager will take care of deletion
auto primaryGeneratorAction = new Geant4::SimParticleTranslation(
prCfg, this->logger().cloneWithSuffix("SimParticleTranslation"));
// Set the primary generator action
runManager().SetUserAction(primaryGeneratorAction);
}
// Particle action
{
// Clear tracking action if it exists
if (runManager().GetUserTrackingAction() != nullptr) {
delete runManager().GetUserTrackingAction();
}
Geant4::ParticleTrackingAction::Config trackingCfg;
trackingCfg.eventStore = m_eventStore;
trackingCfg.keepParticlesWithoutHits = true;
// G4RunManager will take care of deletion
auto trackingAction = new Geant4::ParticleTrackingAction(
trackingCfg, this->logger().cloneWithSuffix("ParticleTracking"));
runManager().SetUserAction(trackingAction);
}
// Stepping action
{
// Clear stepping action if it exists
if (runManager().GetUserSteppingAction() != nullptr) {
delete runManager().GetUserSteppingAction();
}
Geant4::MaterialSteppingAction::Config steppingCfg;
steppingCfg.eventStore = m_eventStore;
steppingCfg.excludeMaterials = m_cfg.excludeMaterials;
steppingCfg.recordElementFractions = m_cfg.recordElementFractions;
// G4RunManager will take care of deletion
auto steppingAction = new Geant4::MaterialSteppingAction(
steppingCfg, this->logger().cloneWithSuffix("MaterialSteppingAction"));
runManager().SetUserAction(steppingAction);
}
runManager().Initialize();
m_inputParticles.initialize(cfg.inputParticles);
m_outputMaterialTracks.initialize(cfg.outputMaterialTracks);
}
Geant4MaterialRecording::~Geant4MaterialRecording() = default;
ProcessCode Geant4MaterialRecording::execute(
const AlgorithmContext& ctx) const {
const auto ret = Geant4SimulationBase::execute(ctx);
if (ret != ProcessCode::SUCCESS) {
return ret;
}
// Output handling: Material tracks
m_outputMaterialTracks(
ctx, decltype(eventStore().materialTracks)(eventStore().materialTracks));
return ProcessCode::SUCCESS;
}
} // namespace ActsExamples