Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions gemc/actions/run/gRunAction.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<int>(completed_run_data.size()), runNumber);
Expand Down
11 changes: 11 additions & 0 deletions tests/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -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)
42 changes: 42 additions & 0 deletions tests/run_normalization.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include "gemc_options.h"
#include <gemc/actions/run/gRunAction.h>
#include <gemc/gtouchable/gtouchable.h>
#include <gemc/gphysics/gphysics.h>
#include "G4RunManager.hh"
#include "G4Run.hh"

#include <memory>

class FixedRunDigitizer : public GDynamicDigitization {
public:
using GDynamicDigitization::GDynamicDigitization;
bool defineReadoutSpecsImpl() override { return true; }
CollectionMode collection_mode() const override { return CollectionMode::run; }
std::vector<std::string> variables_to_normalizeImpl() override { return {"dose"}; }
};

int main(int argc, char* argv[]) {
auto options = std::make_shared<GOptions>(argc, argv, gemc::defineOptions());
auto manager = std::make_unique<G4RunManager>();
auto physics = std::make_unique<GPhysics>(options);
manager->SetUserInitialization(physics->getPhysList());
auto routines = std::make_shared<gdynamicdigitization::dRoutinesMap>();
(*routines)["fixed"] = std::make_shared<FixedRunDigitizer>(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<GDigitizedData>(options, &hit);
data->includeVariable("dose", 10.0);
action.collect_event_data_collections("fixed", std::move(data));
}
callbacks->EndOfRunAction(&run);
return 0;
}
48 changes: 48 additions & 0 deletions tests/serial_output.py
Original file line number Diff line number Diff line change
@@ -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.')
Loading