diff --git a/gemc/actions/run/gRunAction.cc b/gemc/actions/run/gRunAction.cc index 362ac3c3..8e507967 100644 --- a/gemc/actions/run/gRunAction.cc +++ b/gemc/actions/run/gRunAction.cc @@ -91,10 +91,10 @@ void GRunAction::BeginOfRunAction(const G4Run *aRun) { // Worker threads own event-mode publication, so they lazily build and open // thread-local streamers only when at least one event-mode digitizer exists. - if (!IsMaster() && need_a_thread_streamer) { + if ((!IsMaster() || !G4Threading::IsMultithreadedApplication()) && need_a_thread_streamer) { if (gstreamer_threads_map == nullptr) { log->info(1, "Defining thread gstreamers for run %1 in thread %2", run, thread_id); - gstreamer_threads_map = gstreamer::gstreamersMapPtr(goptions, thread_id); + gstreamer_threads_map = gstreamer::gstreamersMapPtr(goptions, thread_id < 0 ? 0 : thread_id); } if (gstreamer_threads_map == nullptr) { @@ -124,7 +124,7 @@ void GRunAction::BeginOfRunAction(const G4Run *aRun) { } // The master thread owns run-mode publication, so it opens the run streamers // only when at least one digitizer accumulates payload at run scope. - else if (IsMaster() && need_a_run_streamer) { + if (IsMaster() && need_a_run_streamer) { if (gstreamer_run_map == nullptr) { log->info(1, "Defining run gstreamers for run %1", run); gstreamer_run_map = gstreamer::gstreamersMapPtr(goptions); @@ -170,7 +170,7 @@ void GRunAction::EndOfRunAction(const G4Run *aRun) { } } - if (!IsMaster() && need_a_thread_streamer) { + if ((!IsMaster() || !G4Threading::IsMultithreadedApplication()) && need_a_thread_streamer) { if (gstreamer_threads_map == nullptr) { log->error( gaction::ERR_STREAMERMAP_NOT_EXISTING, @@ -213,6 +213,9 @@ void GRunAction::EndOfRunAction(const G4Run *aRun) { // Gather all worker-produced run data for this run and merge them into a // single master-side run-data object before publication. auto completed_run_data = take_completed_worker_run_data(); + if (!G4Threading::IsMultithreadedApplication()) { + completed_run_data.emplace_back(std::move(run_data)); + } log->info( 2, "%1 master collected %2 worker run_data object(s) for run %3", FUNCTION_NAME, static_cast(completed_run_data.size()), runNumber); diff --git a/tests/meson.build b/tests/meson.build index 32b204b1..513255ff 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') + +run_normalization = executable('test_run_normalization', + files('run_normalization.cc', '../gemc_options.cc') + qrc_gemc_sources, + include_directories: gemc_includes, + dependencies: gui_probe_dependencies, + link_with: all_libs, + export_dynamic: true) +test('serial_output', python_exe, + args: [files('serial_output.py'), gemc, get_option('prefix'), run_normalization, '--plugin-path=' + build_root], + depends: plugin_target_maps.values(), + env: project_test_env, suite: 'gactions', timeout: 180) diff --git a/tests/run_normalization.cc b/tests/run_normalization.cc new file mode 100644 index 00000000..62d83d93 --- /dev/null +++ b/tests/run_normalization.cc @@ -0,0 +1,42 @@ +#include "gemc_options.h" +#include +#include +#include +#include "G4RunManager.hh" +#include "G4Run.hh" + +#include + +class FixedRunDigitizer : public GDynamicDigitization { +public: + using GDynamicDigitization::GDynamicDigitization; + bool defineReadoutSpecsImpl() override { return true; } + CollectionMode collection_mode() const override { return CollectionMode::run; } + std::vector variables_to_normalizeImpl() override { return {"dose"}; } +}; + +int main(int argc, char* argv[]) { + auto options = std::make_shared(argc, argv, gemc::defineOptions()); + auto manager = std::make_unique(); + auto physics = std::make_unique(options); + manager->SetUserInitialization(physics->getPhysList()); + auto routines = std::make_shared(); + (*routines)["fixed"] = std::make_shared(options); + (*routines)["fixed"]->set_loggers(options); + GRunAction action(options, routines); + G4UserRunAction* callbacks = &action; + G4Run run; + run.SetRunID(11); + run.SetNumberOfEventToBeProcessed(4); + callbacks->BeginOfRunAction(&run); + auto touchable = GTouchable::create(options); + GHit hit(touchable); + for (int event = 0; event < 4; ++event) { + action.increment_run_events_processed(); + auto data = std::make_unique(options, &hit); + data->includeVariable("dose", 10.0); + action.collect_event_data_collections("fixed", std::move(data)); + } + callbacks->EndOfRunAction(&run); + return 0; +} diff --git a/tests/serial_output.py b/tests/serial_output.py new file mode 100644 index 00000000..b2f656a9 --- /dev/null +++ b/tests/serial_output.py @@ -0,0 +1,48 @@ +"""Serial and MT contexts retain generated events and integrated dose exactly once.""" +import csv +import json +import os +from pathlib import Path +import subprocess +import sys +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] +failures = [] +with tempfile.TemporaryDirectory() as directory: + database=Path(directory)/'geometry.db' + setup=subprocess.run([sys.executable,str(source/'examples/basic/b1/b1.py'),'-f','sqlite','-sql',str(database)],cwd=directory,capture_output=True,text=True) + assert setup.returncode==0,setup.stdout+setup.stderr + for mode, threads in [('Serial',1),('MT',1),('MT',2)]: + work = Path(directory)/f'{mode}_{threads}' + work.mkdir() + env = os.environ.copy(); env['G4RUN_MANAGER_TYPE'] = mode + result = subprocess.run([binary,'-n=4',f'-nthreads={threads}','-gparticle=[{name: geantino, p: 1*GeV}]','-gstreamer=[{format: json, filename: events}]'],cwd=work,env=env,capture_output=True,text=True) + assert result.returncode == 0, result.stdout+result.stderr + count = sum(len(json.loads(p.read_text())['events']) for p in work.glob('events*.json') if p.stat().st_size) + if count != 4: failures.append((mode,threads,'generated events',count)) + result = subprocess.run([binary,str(source/'examples/basic/b1/b1.yaml'),'-sql='+str(database),'-n=10',f'-nthreads={threads}','-seed=12345','-gparticle=[{name: proton, p: 1*GeV, vz: -10*cm}]','-gstreamer=[{format: csv, filename: dose}]'],cwd=work,env=env,capture_output=True,text=True) + assert result.returncode == 0, result.stdout+result.stderr + rows=[] + for p in work.glob('dose*_digitized.csv'): + if p.stat().st_size: rows.extend(csv.DictReader(p.open(),skipinitialspace=True)) + if not rows or not any(float(row.get('dose',0))>0 for row in rows): + failures.append((mode,threads,'integrated dose',rows)) + generated=sum(len(list(csv.DictReader(p.open(),skipinitialspace=True))) for p in work.glob('dose*_generated.csv') if p.stat().st_size) + if generated!=10: failures.append((mode,threads,'mixed generated events',generated)) + if len(rows)>1: failures.append((mode,threads,'duplicate integrated rows',len(rows))) + if len(sys.argv)>3: + work=Path(directory)/'normalization';work.mkdir() + driver=str(Path(sys.argv[3]).resolve()) + result=subprocess.run([driver,'-gstreamer=[{format: csv, filename: normalization}]'],cwd=work,capture_output=True,text=True) + assert result.returncode==0,result.stdout+result.stderr + path=work/'normalization_digitized.csv' + values=list(csv.DictReader(path.open(),skipinitialspace=True)) + assert len(values)==1 and float(values[0]['dose'])==10,(values,'expected 40/4=10 exactly once') +assert not failures, failures +print('Serial, one-worker MT, and two-worker MT event/run publication passed.')