From d5669051802bf99642ee53844c2c56e8c29a34a2 Mon Sep 17 00:00:00 2001 From: Zhiwen Zhao Date: Sun, 15 Nov 2026 18:17:58 -0500 Subject: [PATCH] fix: preserve saved configuration types and replay --- gemc/goptions/goption.cc | 52 +++---------------------------------- gemc/goptions/goption.h | 2 +- gemc/goptions/goptions.cc | 2 +- tests/goptions_roundtrip.py | 38 +++++++++++++++++++++++++++ tests/meson.build | 5 ++++ 5 files changed, 48 insertions(+), 51 deletions(-) create mode 100644 tests/goptions_roundtrip.py diff --git a/gemc/goptions/goption.cc b/gemc/goptions/goption.cc index 45b134fd..793d5701 100644 --- a/gemc/goptions/goption.cc +++ b/gemc/goptions/goption.cc @@ -21,7 +21,6 @@ #include #include -#include using std::cerr; using std::endl; @@ -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 missing; // paths of null values - - // -------------------------------------------------------------------- - // recursive lambda: returns a *new* node with nulls → "not provided" - // -------------------------------------------------------------------- - std::function 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(); - 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'; } diff --git a/gemc/goptions/goption.h b/gemc/goptions/goption.h index 0f293f43..d320dadb 100644 --- a/gemc/goptions/goption.h +++ b/gemc/goptions/goption.h @@ -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. diff --git a/gemc/goptions/goptions.cc b/gemc/goptions/goptions.cc index 38bf761d..ef9aba56 100644 --- a/gemc/goptions/goptions.cc +++ b/gemc/goptions/goptions.cc @@ -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); diff --git a/tests/goptions_roundtrip.py b/tests/goptions_roundtrip.py new file mode 100644 index 00000000..dadc2fa4 --- /dev/null +++ b/tests/goptions_roundtrip.py @@ -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.') diff --git a/tests/meson.build b/tests/meson.build index 32b204b1..b5ee4ea1 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -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')