From 9090724748d63554d8209b845abbee690c2ab631 Mon Sep 17 00:00:00 2001 From: Zhiwen Zhao Date: Sun, 15 Nov 2026 18:17:58 -0500 Subject: [PATCH] fix: visit allocated hit collection slots --- gemc/actions/event/gEventAction.cc | 4 +- gemc/actions/examples/sro_runtime_example.cc | 10 +++++ .../dbselect/examples/test_reload_sequence.cc | 5 ++- tests/meson.build | 11 +++++ tests/sparse_hit_collections.cc | 44 +++++++++++++++++++ tests/sparse_hit_collections.py | 24 ++++++++++ 6 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 tests/sparse_hit_collections.cc create mode 100644 tests/sparse_hit_collections.py diff --git a/gemc/actions/event/gEventAction.cc b/gemc/actions/event/gEventAction.cc index 52364c9e..ca021361 100644 --- a/gemc/actions/event/gEventAction.cc +++ b/gemc/actions/event/gEventAction.cc @@ -232,7 +232,7 @@ void GEventAction::EndOfEventAction([[maybe_unused]] const G4Event* event) { // Loop over every hit collection produced during this event and dispatch each // collection to the digitization routine registered under its collection name. - for (G4int hci = 0; hci < hcs_this_event->GetNumberOfCollections(); ++hci) { + for (G4int hci = 0; hci < hcs_this_event->GetCapacity(); ++hci) { auto* const this_ghc = static_cast(hcs_this_event->GetHC(hci)); if (this_ghc == nullptr) { continue; @@ -394,7 +394,7 @@ void GEventAction::stream_event(const G4Event* event) { if (auto* collections = event->GetHCofThisEvent()) { const auto routines = run_action->get_digitization_routines_map(); if (!routines) { throw std::runtime_error("SRO requires a digitization routine map"); } - for (int index = 0; index < collections->GetNumberOfCollections(); ++index) { + for (int index = 0; index < collections->GetCapacity(); ++index) { auto* hits = static_cast(collections->GetHC(index)); if (!hits || detector_is_listed(goptions, NO_DIGITIZED_OPTION, hits->GetSDname())) { continue; } const auto& routine = routines->at(hits->GetSDname()); diff --git a/gemc/actions/examples/sro_runtime_example.cc b/gemc/actions/examples/sro_runtime_example.cc index 7c9d94ea..39e28fb6 100644 --- a/gemc/actions/examples/sro_runtime_example.cc +++ b/gemc/actions/examples/sro_runtime_example.cc @@ -24,6 +24,13 @@ void require(bool condition, const char* message) { if (!condition) { throw std::runtime_error(message); } } +// Reserve an inactive slot before the live collection, including empty-event runs. +class Inactive final : public G4VSensitiveDetector { +public: + Inactive() : G4VSensitiveDetector("unused") { collectionName.insert("unused"); } + G4bool ProcessHits(G4Step*, G4TouchableHistory*) override { return false; } +}; + class Sensitive final : public G4VSensitiveDetector { public: Sensitive() : G4VSensitiveDetector("test_sro") { collectionName.insert("hits"); } @@ -55,6 +62,9 @@ class Detector final : public G4VUserDetectorConstruction { return new G4PVPlacement(nullptr, {}, logical, "world", nullptr, false, 0); } void ConstructSDandField() override { + auto* inactive = new Inactive; + G4SDManager::GetSDMpointer()->AddNewDetector(inactive); + inactive->Activate(false); if (!empty) { G4SDManager::GetSDMpointer()->AddNewDetector(new Sensitive); } } private: diff --git a/gemc/dbselect/examples/test_reload_sequence.cc b/gemc/dbselect/examples/test_reload_sequence.cc index 7ef0cc85..3974b8f0 100644 --- a/gemc/dbselect/examples/test_reload_sequence.cc +++ b/gemc/dbselect/examples/test_reload_sequence.cc @@ -74,7 +74,7 @@ class EventAction : public G4UserEventAction { // G4HCofThisEvent::GetHC / GetNumberOfCollections are not marked const in G4 11.4. auto* hc = const_cast(event->GetHCofThisEvent()); if (!hc) return; - for (G4int i = 0; i < hc->GetNumberOfCollections(); ++i) { + for (G4int i = 0; i < hc->GetCapacity(); ++i) { auto* col = static_cast(hc->GetHC(i)); if (!col || col->GetSize() == 0) continue; const std::string sdName = col->GetSDname(); @@ -165,7 +165,7 @@ int main(int argc, char* argv[]) { if (stale_dosi_in_flux) std::cout << "WARNING: unexpected dosimeter hits in flux-only phases (stale SD).\n"; - bool passed = (flux1 > 0) && (flux3 > 0) && !stale_flux_in_b1 && !stale_dosi_in_flux; + bool passed = (flux1 > 0) && (dosi2 > 0) && (flux3 > 0) && !stale_flux_in_b1 && !stale_dosi_in_flux; delete runManager; @@ -175,6 +175,7 @@ int main(int argc, char* argv[]) { } std::cout << "FAILED" << (flux1 == 0 ? " (no flux hits in Phase 1)" : "") + << (dosi2 == 0 ? " (no dosimeter hits in Phase 2)" : "") << (flux3 == 0 ? " (no flux hits in Phase 3)" : "") << (stale_flux_in_b1 ? " (stale flux SD in Phase 2)" : "") << (stale_dosi_in_flux ? " (stale dosimeter SD in flux phases)" : "") diff --git a/tests/meson.build b/tests/meson.build index 32b204b1..e594bf8b 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -221,3 +221,14 @@ material_optics = executable('test_material_optics', 'material_optics.cc', dependencies: gui_probe_dependencies, link_with: all_libs) test('material_optics', material_optics, suite: 'gsystem') + +sparse_hit_collections = executable('test_sparse_hit_collections', + files('sparse_hit_collections.cc', '../gemc_options.cc') + qrc_gemc_sources, + include_directories: gemc_includes, + dependencies: gui_probe_dependencies, + link_with: all_libs, + export_dynamic: true) +test('sparse_hit_collections', python_exe, + args: [files('sparse_hit_collections.py'), sparse_hit_collections, get_option('prefix'), '--plugin-path=' + build_root], + depends: plugin_target_maps.values(), + env: project_test_env, suite: 'gactions', timeout: 180) diff --git a/tests/sparse_hit_collections.cc b/tests/sparse_hit_collections.cc new file mode 100644 index 00000000..d34e7157 --- /dev/null +++ b/tests/sparse_hit_collections.cc @@ -0,0 +1,44 @@ +#include "gemc_options.h" +#include +#include +#include +#include "G4RunManagerFactory.hh" +#include "G4SDManager.hh" +#include "G4VSensitiveDetector.hh" + +#include + +namespace { +class InactiveDetector : public G4VSensitiveDetector { +public: + InactiveDetector() : G4VSensitiveDetector("unused") { collectionName.insert("unused"); } + G4bool ProcessHits(G4Step*, G4TouchableHistory*) override { return false; } +}; + +class SparseDetector : public GDetectorConstruction { +public: + using GDetectorConstruction::GDetectorConstruction; + void ConstructSDandField() override { + // Reserve collection ID 0 in every execution context, then leave its slot empty. + auto* inactive = new InactiveDetector; + G4SDManager::GetSDMpointer()->AddNewDetector(inactive); + inactive->Activate(false); + GDetectorConstruction::ConstructSDandField(); + } +}; +} + +int main(int argc, char* argv[]) { + auto options = std::make_shared(argc, argv, gemc::defineOptions()); + auto manager = std::unique_ptr( + G4RunManagerFactory::CreateRunManager(G4RunManagerType::MTOnly)); + manager->SetNumberOfThreads(1); + auto* detector = new SparseDetector(options); + manager->SetUserInitialization(detector); + auto* physics = new GPhysics(options); + manager->SetUserInitialization(physics->getPhysList()); + manager->SetUserInitialization(new GAction(options, detector->get_digitization_routines_map())); + manager->Initialize(); + manager->BeamOn(1); + return 0; +} diff --git a/tests/sparse_hit_collections.py b/tests/sparse_hit_collections.py new file mode 100644 index 00000000..5887b4fc --- /dev/null +++ b/tests/sparse_hit_collections.py @@ -0,0 +1,24 @@ +"""A real production event action must publish the active collection after an inactive slot.""" +import json +from pathlib import Path +import subprocess +import sys +import os +import tempfile + +for argument in sys.argv[2:]: + if argument.startswith("--plugin-path="): + os.environ["GEMC_PLUGIN_PATH"] = argument.split("=", 1)[1] + +binary=str(Path(sys.argv[1]).resolve());source=Path(__file__).resolve().parents[1] +with tempfile.TemporaryDirectory() as directory: + work=Path(directory) + database=work/'geometry.db' + setup=subprocess.run([sys.executable,str(source/'examples/basic/simple_flux/simple_flux.py'),'-f','sqlite','-sql',str(database)],cwd=work,capture_output=True,text=True) + assert setup.returncode==0,setup.stdout+setup.stderr + run=subprocess.run([binary,'-gsystem=[{name: simple_flux, factory: sqlite}]','-experiment=examples','-runno=1','-sql='+str(database),'-nthreads=1','-recordZeroEdep','-gparticle=[{name: geantino, p: 1*GeV, vz: -3*cm}]','-gstreamer=[{format: json, filename: sparse}]'],cwd=work,capture_output=True,text=True) + assert run.returncode==0,run.stdout+run.stderr + events=json.loads((work/'sparse_t0.json').read_text())['events'] + assert len(events)==1,events + assert events[0].get('detectors',{}).get('digitized_by_detector',{}).get('flux'),events +print('Production event dispatch preserves hits at collection ID 1 with inactive ID 0.')