File indexing completed on 2026-12-03 09:53:54
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018 #include "DDG4/Geant4SteppingAction.h"
0019
0020
0021 #include <G4Step.hh>
0022 #include <G4RunManager.hh>
0023 #include <G4TrackStatus.hh>
0024 #include <G4Run.hh>
0025 #include <G4Event.hh>
0026 #include <G4UnitsTable.hh>
0027 #include <G4ParticleDefinition.hh>
0028 #include <G4ThreeVector.hh>
0029 #include <CLHEP/Units/SystemOfUnits.h>
0030
0031
0032 #include <fstream>
0033 #include <iostream>
0034 #include <sstream>
0035 #include <string>
0036 #include <vector>
0037 #include <map>
0038 #include <stack>
0039 #include <cmath>
0040 #include <limits>
0041 #include <fmt/core.h>
0042 #include <fmt/format.h>
0043
0044
0045 namespace dd4hep {
0046
0047
0048 namespace sim {
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070 class FirebirdTrajectoryWriterSteppingAction : public Geant4SteppingAction {
0071 protected:
0072
0073 std::string m_outputFile {"trajectories.firebird.json"};
0074 std::ofstream m_output;
0075 std::size_t m_totalSteps {0UL};
0076 std::size_t m_totalTracks {0UL};
0077 std::size_t m_totalEvents {0UL};
0078 std::size_t m_filteredTracks {0UL};
0079 std::size_t m_stepsFiltered {0UL};
0080
0081
0082 std::string m_componentName {"Geant4TrueTrajectories"};
0083
0084
0085 double m_minMomentum {300 * CLHEP::MeV};
0086 double m_maxMomentum {10000 * CLHEP::TeV};
0087 bool m_saveOptical {false};
0088 bool m_onlyPrimary {true};
0089
0090
0091 bool m_vertexCut {true};
0092 double m_vertexZMin {-4500};
0093 double m_vertexZMax {4500};
0094
0095
0096 bool m_stepCut {false};
0097 double m_stepZMin {-5000};
0098 double m_stepZMax {5000};
0099 double m_stepRMax {5000};
0100
0101
0102 std::vector<int> m_saveParticles {};
0103
0104
0105 double m_minTrackLength {0};
0106
0107
0108 std::once_flag m_initFlag;
0109 int m_prevEvent {-1};
0110 int m_prevTrackId {-1};
0111 bool m_skippingTrack {false};
0112
0113
0114 std::vector<std::string> m_eventEntries;
0115 std::vector<std::string> m_pointEntries;
0116
0117
0118
0119
0120
0121
0122 int m_currentEventNumber {0};
0123 std::vector<std::string> m_trackPointsJson;
0124 std::vector<int> m_colPdg;
0125 std::vector<std::string> m_colType;
0126 std::vector<double> m_colCharge, m_colPx, m_colPy, m_colPz,
0127 m_colVx, m_colVy, m_colVz,
0128 m_colTheta, m_colPhi, m_colQOverP, m_colTime;
0129
0130
0131
0132 int m_pendingPdg {0};
0133 std::string m_pendingType;
0134 double m_pendingCharge {0}, m_pendingPx {0}, m_pendingPy {0}, m_pendingPz {0},
0135 m_pendingVx {0}, m_pendingVy {0}, m_pendingVz {0},
0136 m_pendingTheta {0}, m_pendingPhi {0}, m_pendingQOverP {0}, m_pendingTime {0};
0137
0138
0139 double m_currentTrackLength {0};
0140 G4ThreeVector m_lastPointPosition;
0141 bool m_hasLastPoint {false};
0142
0143
0144 void ensureOutputWritable() {
0145 if (!m_output.is_open() || !m_output.good()) {
0146 auto errMsg = fmt::format("Failed to open the file or file stream is in a bad state. File name: '{}'", m_outputFile);
0147 error(errMsg.c_str());
0148 throw std::runtime_error(errMsg);
0149 }
0150 }
0151
0152
0153 double calculateR(const G4ThreeVector& position) const {
0154 return std::sqrt(position.x() * position.x() + position.y() * position.y());
0155 }
0156
0157
0158 void initializeOutput() {
0159
0160 fmt::print("Plugin {} info: \n", typeid(*this).name());
0161 fmt::print(" OutputFile {}\n", m_outputFile);
0162 fmt::print(" ComponentName {}\n", m_componentName);
0163 fmt::print(" MinMomentum {}\n", m_minMomentum);
0164 fmt::print(" MaxMomentum {}\n", m_maxMomentum);
0165 fmt::print(" SaveOptical {}\n", m_saveOptical);
0166 fmt::print(" OnlyPrimary {}\n", m_onlyPrimary);
0167 fmt::print(" VertexCut {}\n", m_vertexCut);
0168 fmt::print(" VertexZMin {}\n", m_vertexZMin);
0169 fmt::print(" VertexZMax {}\n", m_vertexZMax);
0170 fmt::print(" StepCut {}\n", m_stepCut);
0171 fmt::print(" StepZMin {}\n", m_stepZMin);
0172 fmt::print(" StepZMax {}\n", m_stepZMax);
0173 fmt::print(" StepRMax {}\n", m_stepRMax);
0174 fmt::print(" TrackLengthMin {}\n", m_minTrackLength);
0175
0176 if (!m_saveParticles.empty()) {
0177 std::stringstream ss;
0178 for (size_t i = 0; i < m_saveParticles.size(); ++i) {
0179 if (i > 0) ss << ", ";
0180 ss << m_saveParticles[i];
0181 }
0182 fmt::print(" SaveParticles {}\n", ss.str());
0183 } else {
0184 fmt::print(" SaveParticles [all]\n");
0185 }
0186
0187
0188 m_output.open(m_outputFile);
0189 ensureOutputWritable();
0190 }
0191
0192
0193 void writeOutputFile() {
0194 ensureOutputWritable();
0195
0196
0197 m_output << fmt::format(R"({{"type":"firebird-dex-json","version":"1.0","origin":{{"file":"{}","entries_count":{}}},)",
0198 m_outputFile, m_eventEntries.size());
0199
0200
0201 m_output << "\"events\":[";
0202
0203
0204 for (size_t i = 0; i < m_eventEntries.size(); ++i) {
0205 m_output << m_eventEntries[i];
0206 if (i < m_eventEntries.size() - 1) {
0207 m_output << ",";
0208 }
0209 }
0210
0211
0212 m_output << "]}";
0213 }
0214
0215
0216 static double sanitise(double v) {
0217 return (std::isinf(v) || std::isnan(v)) ? 0.0 : v;
0218 }
0219
0220
0221
0222 void captureTrackParams(const G4Track* track) {
0223 G4ThreeVector momentum = track->GetMomentum();
0224 G4double p = std::max(momentum.mag(), 1e-10);
0225 G4ThreeVector vertex = track->GetVertexPosition();
0226 G4double charge = track->GetParticleDefinition()->GetPDGCharge();
0227
0228 m_pendingPdg = track->GetParticleDefinition()->GetPDGEncoding();
0229 m_pendingType = track->GetParticleDefinition()->GetParticleName();
0230 m_pendingCharge = sanitise(charge);
0231 m_pendingPx = sanitise(momentum.x() / CLHEP::MeV);
0232 m_pendingPy = sanitise(momentum.y() / CLHEP::MeV);
0233 m_pendingPz = sanitise(momentum.z() / CLHEP::MeV);
0234 m_pendingVx = sanitise(vertex.x() / CLHEP::mm);
0235 m_pendingVy = sanitise(vertex.y() / CLHEP::mm);
0236 m_pendingVz = sanitise(vertex.z() / CLHEP::mm);
0237 m_pendingTheta = sanitise(momentum.theta());
0238 m_pendingPhi = sanitise(momentum.phi());
0239 m_pendingQOverP = sanitise(charge / (p / CLHEP::GeV));
0240 m_pendingTime = sanitise(track->GetGlobalTime() / CLHEP::ns);
0241 }
0242
0243 static std::string numbersJson(const std::vector<double>& values) {
0244 std::string out = "[";
0245 for (size_t i = 0; i < values.size(); ++i) {
0246 if (i) out += ',';
0247 out += fmt::format("{}", values[i]);
0248 }
0249 return out + "]";
0250 }
0251
0252
0253 std::string formatPoint(G4StepPoint* point) {
0254 G4ThreeVector position = point->GetPosition();
0255
0256
0257 double x = position.x() / CLHEP::mm;
0258 double y = position.y() / CLHEP::mm;
0259 double z = position.z() / CLHEP::mm;
0260 double time = point->GetGlobalTime() / CLHEP::ns;
0261
0262
0263 if (std::isinf(x) || std::isnan(x)) x = 0.0;
0264 if (std::isinf(y) || std::isnan(y)) y = 0.0;
0265 if (std::isinf(z) || std::isnan(z)) z = 0.0;
0266 if (std::isinf(time) || std::isnan(time)) time = 0.0;
0267
0268
0269 return fmt::format("[{},{},{},{},{}]", x, y, z, time, 0);
0270 }
0271
0272
0273 void startNewEvent(int runNumber, int eventNumber) {
0274
0275 finalizeEvent();
0276
0277
0278 m_prevTrackId = -1;
0279 m_pointEntries.clear();
0280 m_currentEventNumber = eventNumber;
0281 m_trackPointsJson.clear();
0282 m_colPdg.clear(); m_colType.clear(); m_colCharge.clear();
0283 m_colPx.clear(); m_colPy.clear(); m_colPz.clear();
0284 m_colVx.clear(); m_colVy.clear(); m_colVz.clear();
0285 m_colTheta.clear(); m_colPhi.clear(); m_colQOverP.clear(); m_colTime.clear();
0286
0287 m_totalEvents++;
0288 fmt::print("Started processing event: {} (run: {})\n", eventNumber, runNumber);
0289 }
0290
0291
0292 void finalizeEvent() {
0293 if (m_prevEvent < 0) return;
0294
0295
0296 if (m_trackPointsJson.empty()) {
0297 fmt::print("Skipping empty event {}\n", m_prevEvent);
0298 return;
0299 }
0300
0301 std::string pdgJson = "[";
0302 std::string typeJson = "[";
0303 for (size_t i = 0; i < m_colPdg.size(); ++i) {
0304 if (i) { pdgJson += ','; typeJson += ','; }
0305 pdgJson += fmt::format("{}", m_colPdg[i]);
0306 typeJson += fmt::format("\"{}\"", m_colType[i]);
0307 }
0308 pdgJson += ']';
0309 typeJson += ']';
0310
0311 std::string columnsJson = fmt::format(
0312 R"({{"pdg":{},"type":{},"charge":{},"px":{},"py":{},"pz":{},"vx":{},"vy":{},"vz":{},"theta":{},"phi":{},"q_over_p":{},"time":{}}})",
0313 pdgJson, typeJson, numbersJson(m_colCharge),
0314 numbersJson(m_colPx), numbersJson(m_colPy), numbersJson(m_colPz),
0315 numbersJson(m_colVx), numbersJson(m_colVy), numbersJson(m_colVz),
0316 numbersJson(m_colTheta), numbersJson(m_colPhi), numbersJson(m_colQOverP),
0317 numbersJson(m_colTime));
0318
0319 std::string pointsJson = "[";
0320 for (size_t i = 0; i < m_trackPointsJson.size(); ++i) {
0321 if (i) pointsJson += ',';
0322 pointsJson += m_trackPointsJson[i];
0323 }
0324 pointsJson += ']';
0325
0326 m_eventEntries.push_back(fmt::format(
0327 R"({{"id":{},"pieces":[{{"name":"{}","type":"PointTrajectory","version":"1.0",)"
0328 R"("origin":{{"type":["G4Track","G4StepPoint"]}},)"
0329 R"("count":{},"columns":{},)"
0330 R"("pointColumns":["x","y","z","t","aux"],)"
0331 R"("points":{}}}]}})",
0332 m_currentEventNumber, m_componentName, m_trackPointsJson.size(), columnsJson, pointsJson));
0333
0334 fmt::print("Finalized event {} with {} tracks\n", m_prevEvent, m_trackPointsJson.size());
0335 }
0336
0337
0338 bool passesFilters(const G4Track* track) {
0339
0340 std::string particleName = track->GetParticleDefinition()->GetParticleName();
0341 int pdgCode = track->GetParticleDefinition()->GetPDGEncoding();
0342 int parentID = track->GetParentID();
0343 G4ThreeVector momentum = track->GetMomentum();
0344 double p = momentum.mag();
0345 G4ThreeVector vertex = track->GetVertexPosition();
0346 double vz = vertex.z() / CLHEP::mm;
0347
0348
0349 if (particleName == "opticalphoton" && m_saveOptical) {
0350 return true;
0351 }
0352
0353
0354 if (m_onlyPrimary && parentID != 0) {
0355 return false;
0356 }
0357
0358
0359 if (p < m_minMomentum || p > m_maxMomentum) {
0360 return false;
0361 }
0362
0363
0364 if (m_vertexCut && (vz < m_vertexZMin || vz > m_vertexZMax)) {
0365 return false;
0366 }
0367
0368
0369 if (!m_saveParticles.empty()) {
0370 bool found = false;
0371 for (int code : m_saveParticles) {
0372 if (pdgCode == code) {
0373 found = true;
0374 break;
0375 }
0376 }
0377 if (!found) {
0378 return false;
0379 }
0380 }
0381
0382
0383 return true;
0384 }
0385
0386
0387 bool pointPassesFilters(const G4ThreeVector& position) {
0388 if (!m_stepCut) {
0389 return true;
0390 }
0391
0392
0393 double z = position.z() / CLHEP::mm;
0394 double r = calculateR(position) / CLHEP::mm;
0395
0396
0397 if (z < m_stepZMin || z > m_stepZMax || r > m_stepRMax) {
0398 m_stepsFiltered++;
0399 return false;
0400 }
0401
0402 return true;
0403 }
0404
0405
0406 void startNewTrack(const G4Track* track) {
0407
0408 int trackId = track->GetTrackID();
0409 m_prevTrackId = trackId;
0410
0411
0412 if (!passesFilters(track)) {
0413 m_skippingTrack = true;
0414 m_filteredTracks++;
0415 return;
0416 }
0417
0418 m_skippingTrack = false;
0419
0420
0421
0422 captureTrackParams(track);
0423
0424
0425 m_pointEntries.clear();
0426 m_currentTrackLength = 0;
0427 m_hasLastPoint = false;
0428
0429 if (trackId < 1000) {
0430 G4ThreeVector vertex = track->GetVertexPosition();
0431 fmt::print("Processing track: {}, {} (parent: {}), vertex: ({:.2f}, {:.2f}, {:.2f})\n",
0432 trackId,
0433 track->GetParticleDefinition()->GetParticleName(),
0434 track->GetParentID(),
0435 vertex.x(), vertex.y(), vertex.z());
0436 }
0437 }
0438
0439
0440 void addStepPoint(G4StepPoint* point) {
0441 if (m_skippingTrack) return;
0442
0443
0444 if (!pointPassesFilters(point->GetPosition())) {
0445 return;
0446 }
0447
0448
0449 if (m_hasLastPoint) {
0450 m_currentTrackLength += (point->GetPosition() - m_lastPointPosition).mag() / CLHEP::mm;
0451 }
0452 m_lastPointPosition = point->GetPosition();
0453 m_hasLastPoint = true;
0454
0455
0456 std::string pointEntry = formatPoint(point);
0457
0458
0459 if (!m_pointEntries.empty()) {
0460 m_pointEntries.push_back("," + pointEntry);
0461 } else {
0462 m_pointEntries.push_back(pointEntry);
0463 }
0464 }
0465
0466
0467
0468 void finalizeTrack() {
0469 if (m_skippingTrack) return;
0470
0471
0472 if (m_pointEntries.empty() || (m_minTrackLength > 0 && m_currentTrackLength < m_minTrackLength)) {
0473 m_skippingTrack = true;
0474 m_filteredTracks++;
0475 return;
0476 }
0477
0478 std::string points = "[";
0479 for (size_t i = 0; i < m_pointEntries.size(); i++) {
0480 points += m_pointEntries[i];
0481 }
0482 points += "]";
0483 m_trackPointsJson.push_back(std::move(points));
0484
0485 m_colPdg.push_back(m_pendingPdg);
0486 m_colType.push_back(m_pendingType);
0487 m_colCharge.push_back(m_pendingCharge);
0488 m_colPx.push_back(m_pendingPx);
0489 m_colPy.push_back(m_pendingPy);
0490 m_colPz.push_back(m_pendingPz);
0491 m_colVx.push_back(m_pendingVx);
0492 m_colVy.push_back(m_pendingVy);
0493 m_colVz.push_back(m_pendingVz);
0494 m_colTheta.push_back(m_pendingTheta);
0495 m_colPhi.push_back(m_pendingPhi);
0496 m_colQOverP.push_back(m_pendingQOverP);
0497 m_colTime.push_back(m_pendingTime);
0498
0499 m_totalTracks++;
0500 }
0501
0502 public:
0503
0504 FirebirdTrajectoryWriterSteppingAction(Geant4Context* context, const std::string& name = "FirebirdTrajectoryWriterSteppingAction")
0505 : Geant4SteppingAction(context, name)
0506 {
0507 declareProperty("OutputFile", m_outputFile);
0508 declareProperty("ComponentName", m_componentName);
0509 declareProperty("MomentumMin", m_minMomentum);
0510 declareProperty("MomentumMax", m_maxMomentum);
0511 declareProperty("SaveOptical", m_saveOptical);
0512 declareProperty("OnlyPrimary", m_onlyPrimary);
0513 declareProperty("VertexCut", m_vertexCut);
0514 declareProperty("VertexZMin", m_vertexZMin);
0515 declareProperty("VertexZMax", m_vertexZMax);
0516 declareProperty("StepCut", m_stepCut);
0517 declareProperty("StepZMin", m_stepZMin);
0518 declareProperty("StepZMax", m_stepZMax);
0519 declareProperty("StepRMax", m_stepRMax);
0520 declareProperty("TrackLengthMin", m_minTrackLength);
0521 declareProperty("SaveParticles", m_saveParticles);
0522 }
0523
0524
0525 ~FirebirdTrajectoryWriterSteppingAction() override
0526 {
0527
0528 if (m_prevTrackId > 0 && !m_skippingTrack) {
0529 finalizeTrack();
0530 }
0531 finalizeEvent();
0532
0533
0534 if (!m_eventEntries.empty()) {
0535 writeOutputFile();
0536 info("[firebird-stepping-writer] Successfully wrote JSON trajectories to: %s", m_outputFile.c_str());
0537 } else {
0538 warning("[firebird-stepping-writer] No events were processed. Output file not created.");
0539 }
0540
0541
0542 if (m_output.is_open() && m_output.good()) {
0543 m_output.close();
0544 }
0545
0546
0547 info("[firebird-stepping-writer] Statistics:");
0548 info("[firebird-stepping-writer] Total Events: %ld", m_totalEvents);
0549 info("[firebird-stepping-writer] Total Tracks: %ld (filtered: %ld, written: %ld)",
0550 m_totalTracks + m_filteredTracks, m_filteredTracks, m_totalTracks);
0551 info("[firebird-stepping-writer] Total Steps: %ld (filtered: %ld)",
0552 m_totalSteps, m_stepsFiltered);
0553 }
0554
0555
0556 void operator()(const G4Step* step, G4SteppingManager*) override
0557 {
0558
0559 std::call_once(m_initFlag, [this]() { initializeOutput(); });
0560
0561
0562 auto runNum = context()->run().run().GetRunID();
0563 auto eventNum = context()->event().event().GetEventID();
0564
0565
0566 if (eventNum != m_prevEvent) {
0567 startNewEvent(runNum, eventNum);
0568 m_prevEvent = eventNum;
0569 }
0570
0571
0572 auto track = step->GetTrack();
0573 int trackId = track->GetTrackID();
0574
0575
0576 if (trackId != m_prevTrackId) {
0577
0578 if (m_prevTrackId > 0 && !m_skippingTrack) {
0579 finalizeTrack();
0580 }
0581
0582
0583 startNewTrack(track);
0584
0585
0586 if (!m_skippingTrack) {
0587 addStepPoint(step->GetPreStepPoint());
0588 }
0589 }
0590
0591
0592 if (!m_skippingTrack) {
0593 addStepPoint(step->GetPostStepPoint());
0594 }
0595
0596
0597 m_totalSteps++;
0598 }
0599 };
0600
0601 }
0602 }
0603
0604
0605 #include "DDG4/Factories.h"
0606 DECLARE_GEANT4ACTION_NS(dd4hep::sim,FirebirdTrajectoryWriterSteppingAction)