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
52 changes: 3 additions & 49 deletions gemc/goptions/goption.cc
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

#include <iostream>
#include <algorithm>
#include <functional>

using std::cerr;
using std::endl;
Expand Down Expand Up @@ -146,55 +145,10 @@ bool GOption::does_the_option_set_all_necessary_values(const YAML::Node& v) {
return true;
}

// See goption.h for API docs.
/*
* Implementation notes:
* - Writes comment lines for nulls so the saved YAML explains which values were not provided.
* - Produces a cleaned copy of the node (nulls replaced) to keep output valid YAML scalars.
*/
// Save a named mapping and preserve semantic nulls, including unset cumulative options.
void GOption::saveOption(std::ofstream* yamlConf) const {
std::vector<std::string> missing; // paths of null values

// --------------------------------------------------------------------
// recursive lambda: returns a *new* node with nulls → "not provided"
// --------------------------------------------------------------------
std::function<YAML::Node(YAML::Node, std::string)> clean =
[&](YAML::Node n, const std::string& path) -> YAML::Node {
if (n.IsNull()) {
missing.push_back(path.empty() ? name : path);
return YAML::Node("not provided"); // null replaced
}

if (n.IsMap()) {
YAML::Node res(YAML::NodeType::Map);
for (auto it : n) {
const std::string key = it.first.as<std::string>();
res[it.first] = clean(it.second, path.empty() ? key : path + "." + key);
}
return res;
}

if (n.IsSequence()) {
YAML::Node res(YAML::NodeType::Sequence);
for (std::size_t i = 0; i < n.size(); ++i) {
res.push_back(clean(n[i], path + "[" + std::to_string(i) + "]"));
}
return res;
}

return n; // scalar, already OK
};

YAML::Node out = clean(value, ""); // fully cleaned copy

// --------------------------------------------------------------------
// write one comment line per missing entry
// --------------------------------------------------------------------
for (const auto& p : missing) {
*yamlConf << "# " << p << " not provided\n";
}

// write the YAML itself (block style)
YAML::Node out(YAML::NodeType::Map);
out[name] = value.IsMap() ? YAML::Clone(value[name]) : YAML::Node(YAML::NodeType::Null);
out.SetStyle(YAML::EmitterStyle::Block);
*yamlConf << out << '\n';
}
Expand Down
2 changes: 1 addition & 1 deletion gemc/goptions/goption.h
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ class GOption
*
* @details
* Serialization behavior:
* - Writes comment lines for any YAML null values (paths) to help users understand which fields were not provided.
* - Preserves YAML nulls and writes each option under its name, including unset cumulative options.
* - Writes the YAML node in block style so nested maps/sequences remain readable.
*
* This method is invoked by the option manager during configuration snapshot writing.
Expand Down
2 changes: 1 addition & 1 deletion gemc/goptions/goptions.cc
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ void GOptions::printWebHelp() const {
void GOptions::saveOptions() const {
for (auto& s : switches) {
string status = s.second.getStatus() ? "true" : "false";
*yamlConf << s.first + ": " + status << "," << endl;
*yamlConf << s.first + ": " + status << endl;
}
for (const auto& option : goptions) {
option.saveOption(yamlConf);
Expand Down
38 changes: 38 additions & 0 deletions tests/goptions_roundtrip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Save/load preserves unset options, values, collections, and false switches."""
from pathlib import Path
import json
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]
import yaml

binary = str(Path(sys.argv[1]).resolve())
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for name in ['initial','replay']:
(root/name).mkdir()
result = subprocess.run([binary, '-n=1', '-nthreads=1', '-seed=12345', '-print_summary=false', '-gparticle=[{name: geantino, p: 1*GeV}]', '-recordZeroEdep', '-gparticlefile=[]', '-gstreamer=[{format: json, filename: particles}]'], cwd=root/'initial', capture_output=True, text=True)
assert result.returncode == 0, result.stdout+result.stderr
saved = root/'initial/gemc.saved_configuration.yaml'
config = yaml.safe_load(saved.read_text())
assert config['gui'] is False and config['print_summary'] is False, config
for key in ['run_weights','geant4_macro','gmultipoles','gfields','gsystem']:
assert config[key] is None, (key,config[key])
assert config['seed'] == 12345 or config['seed'] == '12345'
assert config['gparticlefile'] == []
assert config['recordZeroEdep'] is True
assert config['gstreamer'][0]['type'] is None
result = subprocess.run([binary, str(saved)], cwd=root/'replay', capture_output=True, text=True)
assert result.returncode == 0, result.stdout+result.stderr
replay = yaml.safe_load((root/'replay/gemc.saved_configuration.yaml').read_text())
for key in ['gui','print_summary','seed','gparticle','gstreamer','run_weights','gsystem']:
assert replay[key] == config[key], (key,config[key],replay[key])
original=json.loads((root/'initial/particles_t0.json').read_text())['events'][0]['generated']
repeated=json.loads((root/'replay/particles_t0.json').read_text())['events'][0]['generated']
assert repeated==original,(original,repeated)
print('Configuration typed-null/boolean/empty/nested values and CLI replay passed.')
5 changes: 5 additions & 0 deletions tests/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,8 @@ material_optics = executable('test_material_optics', 'material_optics.cc',
dependencies: gui_probe_dependencies,
link_with: all_libs)
test('material_optics', material_optics, suite: 'gsystem')

test('goptions_roundtrip', python_exe,
args: [files('goptions_roundtrip.py'), gemc, '--plugin-path=' + build_root],
depends: plugin_target_maps.values(),
env: project_test_env, suite: 'goptions')
Loading