From aa4807ab471d88ddf54760e08af1cda41ace7bfb Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 16:59:35 +0600 Subject: [PATCH 1/7] Add activation-to-transport handoff and validation --- CHANGELOG.md | 47 + Cargo.lock | 1 + README.md | 11 +- bindings/python/src/lib.rs | 339 +++ bindings/wasm/src/lib.rs | 172 ++ crates/r2s/AGENTS.md | 37 +- crates/r2s/Cargo.toml | 7 + crates/r2s/benches/source_bench.rs | 75 + crates/r2s/src/lib.rs | 5 + crates/r2s/src/source.rs | 1850 +++++++++++++++++ crates/tritium/AGENTS.md | 6 +- docs/README.md | 4 +- docs/architecture/crate-responsibilities.md | 9 +- docs/plan/roadmap.md | 5 + docs/reference/python-api.mdx | 144 +- docs/theory/tritium.mdx | 7 +- docs/tutorials/interactive/blanket.mdx | 2 +- docs/tutorials/interactive/clearance.mdx | 2 +- docs/tutorials/interactive/damage.mdx | 2 +- docs/tutorials/interactive/equilibrium.mdx | 2 +- docs/tutorials/interactive/index.mdx | 3 + docs/tutorials/interactive/kinetics.mdx | 2 +- docs/tutorials/interactive/spectroscopy.mdx | 2 +- .../interactive/transport-source.mdx | 47 + docs/tutorials/interactive/tritium.mdx | 2 +- docs/tutorials/interactive/unfold.mdx | 2 +- docs/tutorials/interactive/uq.mdx | 2 +- .../python/activation-to-transport.md | 269 +++ docs/tutorials/python/index.md | 3 + python/nucleide/_internal.pyi | 62 + python/nucleide/openmc.py | 876 +++++++- python/nucleide/r2s.py | 149 ++ tests/test_openmc_bridge.py | 4 +- tests/test_openmc_handoff.py | 583 ++++++ validation/AGENTS.md | 23 +- validation/README.md | 59 +- validation/openmc_handoff_probe.py | 1703 +++++++++++++++ validation/tritium_vs_festim.py | 699 ++++++- website/AGENTS.md | 7 + website/e2e/smoke.spec.ts | 28 + .../interactive/InteractiveDemo.astro | 3 +- .../interactive/InteractiveDemo.tsx | 6 +- .../interactive/PhotonSourceDemo.tsx | 315 +++ website/src/types/nucleide-wasm.d.ts | 34 + 44 files changed, 7523 insertions(+), 87 deletions(-) create mode 100644 crates/r2s/benches/source_bench.rs create mode 100644 crates/r2s/src/source.rs create mode 100644 docs/tutorials/interactive/transport-source.mdx create mode 100644 docs/tutorials/python/activation-to-transport.md create mode 100644 tests/test_openmc_handoff.py create mode 100644 validation/openmc_handoff_probe.py create mode 100644 website/src/components/interactive/PhotonSourceDemo.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index e032e86..b120850 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,53 @@ workspace crates from tags. ## [Unreleased] +### Added + +- Activation-to-transport handoff. `nucleide.openmc.normalize_flux` converts + raw OpenMC tally arrays into physical group flux only after an explicit + normalization declaration. It distinguishes volume-integrated from + volume-averaged data and per-source-particle from source-rate-scaled data + (OpenMC 0.16 scales fixed-source tallies by the configured total source + strength), rejects double scaling, preserves relative errors and records + units, source rate and the input state. The CSV interchange moves to v2 with + normalization/units metadata while v1 files still read as `unknown`. +- Regular-mesh photon-source contract in `nucleide-r2s`: ascending eV edges, + integrated photons/s per voxel and group, C-order voxel identity, density + conversion applying volume once, joint voxel/group probabilities, sparse + exported-group restoration with explicit dense indices, checked totals, + exact cooling-offset selection and a bounded structured validation report + with stable issue codes and explicit uniform-bin/uniform-voxel assumptions. +- Optional OpenMC 0.16 `MeshSource` adapter (`nucleide.openmc.mesh_source`) + with explicit structured-mesh index mapping, per-element histogram energy + densities, absolute photons/s strengths, self-contained `settings.xml` + export and a real pinned-OpenMC validation probe. +- Exact cooling-time batch export with deterministic collision-free names, + all-or-nothing prevalidation, atomic per-file replacement, zero-source skip + policy, partial-failure reporting and a batch manifest; compact + reproducibility manifests record measured input/output SHA-256 hashes, the + energy-grid identity, voxel order and validation summary. Verification is + offline and detects tampered or missing outputs. +- Executable activation-to-transport tutorial covering normalization, + source validation, sparse grids, cooling batches, manifests and the + optional OpenMC export path. +- FESTIM F6 trapped-plus-recombination validation leg with explicit + molar/atomic conversion, a checked two-identical-reactant surface factor, + mobile and trapped inventory histories, bracketed output sampling and + independent space/time refinement with a mobile-plus-trapped mass + balance; F1–F5 checks and pins are unchanged. +- Pinned OpenMC 0.16.0 handoff probe (`validation/openmc_handoff_probe.py`) + recording the observed tally normalization, C-order/Fortran-order mesh + mapping, differential histogram density, XML roundtrip, seeded joint-source + sampling and a vacuum track-length tally at two source strengths that pins + the integrated/rate-scaled convention; no interacting transport. + +### Fixed + +- The OpenMC tally bridge documents and tests the observed 0.16 normalization + convention (per-source-particle denominator, source-strength tally scale, + volume-integrated track-length flux by default) instead of implying that a + field named `flux` is already physical. + ## [0.18.1] - 2026-11-14 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 09b54b5..cc15a49 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -966,6 +966,7 @@ dependencies = [ name = "nucleide-r2s" version = "0.18.1" dependencies = [ + "criterion", "nucleide-alara-io", "nucleide-depletion", "nucleide-material", diff --git a/README.md b/README.md index d48b429..267a999 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ Nucleide is a modern Rust toolkit for nuclear-engineering data, measurement, and workflow glue: legacy transport-code I/O, nuclide identification, materials, CRAM depletion, enrichment analytics, point kinetics, gamma-ray spectroscopy, tritium transport, TBR/blanket bookkeeping, equilibrium data readers, - an OpenMC statepoint tally bridge, fusion neutron sources, spectrum - unfolding, conservative spectral regrouping, volume-aware source splitting, variance + an OpenMC statepoint tally bridge with explicit physical-flux normalization + and photon-source export, fusion neutron sources, spectrum unfolding, + conservative spectral regrouping, volume-aware source splitting, variance reduction, UQ sampling, CSG translation, and code-card emission — exposed through a typed Python API. @@ -54,13 +55,13 @@ rebuilds the high-value subset in memory-safe Rust with one-command | Spectroscopy (`nucleide-spectroscopy`) | Spectrum smoothing, gross/net counting, energy/efficiency calibration, X-ray lines, SPE parsing, decay-line SDEF source cards (E9) fed from caller lists or the runtime decay-lines TSV interchange | | Spectrum unfolding (`nucleide-unfold`) | SAND-II, STAYSL-class least-squares, GRAVEL chi-square-weighted, and MAXED maximum-entropy adjustment of a guess neutron spectrum against measured activation rates (caller-supplied response matrix, or the IRDFF-II runtime pack), with convergence diagnostics; non-convergence is a hard error | | Equilibrium data (`nucleide-equilib-io`) | Classic-netCDF VMEC `wout` reader (CDF-1/CDF-2 only; netCDF-4/CDF-5 convert facade-side) plus the `&INDATA` input-text grammar, with flux-surface Jacobian helpers for volume weighting and wall-load mapping in flux coordinates (reads data, never solves equilibria) | -| OpenMC tally bridge (`nucleide.openmc`, pure Python) | Statepoint mesh/cell tally extraction through the caller-side OpenMC API into plain arrays the damage folds accept, plus a CSV interchange for the same dict | +| OpenMC tally bridge (`nucleide.openmc`, pure Python) | Statepoint mesh/cell tally extraction through the caller-side OpenMC API into plain arrays the damage folds accept, v1/v2 CSV interchange, explicit raw-to-physical flux normalization, optional `MeshSource` export, exact cooling-time batches and reproducibility manifests | | Variance reduction (`nucleide-vr-tools`) | MAGIC weight-window generation, OpenMC/Serpent weight-window emission, mesh source sampling with alias tables, Gaussian KDE source resampling (Silverman, fixed, and adaptive kNN bandwidths) | | UQ sampling (`nucleide-linalg`) | Seeded MVN + log-normal + LHS draws over caller-supplied covariance blocks, SANDY-compatible estimators, decay-data and fission-yield perturbation consumers | | CCCC I/O (`nucleide-cccc-io`) | ISOTXS/RTFLUX text-subset parsers + PARTISN deck writer (no solver) | | FISPACT I/O (`nucleide-fispact-io`) | FISPACT-II inventory output parser reusing the ALARA response frame, plus the clearance-bearing wide inventory table printed with the `HAZARDS` + `CLEAR` keywords (output-only) | | ORIGEN I/O (`nucleide-origen-io`) | Scoped ORIGEN 2.2 TAPE5 input-echo, TAPE6 inventory, and TAPE9 decay readers | -| R2S (`nucleide-r2s`) | Scoped R2S workflow builder: zone-to-flux linking, schedule expansion, photon assembly (uniform-split placeholder plus per-voxel source tags with count- or volume-weighted integrated splitting and `.photonSrc` group spectra), ARMI database-snapshot adapter | +| R2S (`nucleide-r2s`) | Scoped R2S workflow builder: zone-to-flux linking, schedule expansion, photon assembly (uniform-split placeholder plus per-voxel source tags with count- or volume-weighted integrated splitting and `.photonSrc` group spectra), an explicit regular-mesh photon-source contract with joint voxel/group probabilities, sparse-grid restoration and structured validation reports, ARMI database-snapshot adapter | | Emit (`nucleide-emit`) | Single-material emission to MCNP/Serpent/FLUKA/ALARA/PARTISN cards with mass-drift report, plus an ARMI blueprint-key bridge | | Python bindings | PyO3 extension module behind a typed pure-Python facade (`nucleide._internal`, `.pyi` stubs, `py.typed`) | @@ -85,7 +86,7 @@ nucleide/ │ ├── cccc-io/ # ISOTXS/RTFLUX text-subset parsers + PARTISN writer (no solver) │ ├── fispact-io/ # FISPACT-II inventory output + CLEAR-keyword clearance table (output-only) │ ├── origen-io/ # scoped ORIGEN TAPE5/6/9 readers -│ ├── r2s/ # scoped R2S workflows (volume-aware photon tags + spectra) +│ ├── r2s/ # scoped R2S workflows, photon-source contract, flux handoff │ ├── vr-tools/ # MAGIC weight windows + OpenMC/Serpent emission, source sampling, KDE │ ├── enrichment/ # cascades, SWU │ ├── depletion/ # CRAM + chain files diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index d3c1b32..670b475 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -4267,6 +4267,337 @@ fn r2s_tag_zone_strength( Ok(out.into_any().unbind()) } +fn r2s_fixed3_usize(values: Vec, name: &str) -> PyResult<[usize; 3]> { + let len = values.len(); + values.try_into().map_err(|_| { + PyValueError::new_err(format!("{name} must have exactly 3 entries, got {len}")) + }) +} + +fn r2s_fixed3_f64(values: Vec, name: &str) -> PyResult<[f64; 3]> { + let len = values.len(); + values.try_into().map_err(|_| { + PyValueError::new_err(format!("{name} must have exactly 3 entries, got {len}")) + }) +} + +fn r2s_source_report_to_py( + py: Python<'_>, + report: &nucleide_r2s::SourceReport, +) -> PyResult> { + use pyo3::types::{PyDict, PyList}; + let issues = PyList::empty(py); + for issue in &report.issues { + let item = PyDict::new(py); + item.set_item("code", issue.code)?; + item.set_item( + "severity", + match issue.severity { + nucleide_r2s::IssueSeverity::Error => "error", + nucleide_r2s::IssueSeverity::Warning => "warning", + nucleide_r2s::IssueSeverity::Assumption => "assumption", + }, + )?; + item.set_item("location", &issue.location)?; + item.set_item("message", &issue.message)?; + item.set_item("remedy", &issue.remedy)?; + issues.append(item)?; + } + let out = PyDict::new(py); + out.set_item("issues", issues)?; + out.set_item("issue_count", report.issue_count)?; + out.set_item("truncated", report.truncated)?; + out.set_item("valid", report.is_valid())?; + if let Some(totals) = &report.totals { + let totals_dict = PyDict::new(py); + totals_dict.set_item("total_photons_per_s", totals.total_photons_per_s)?; + totals_dict.set_item( + "voxel_totals_photons_per_s", + &totals.voxel_totals_photons_per_s, + )?; + totals_dict.set_item( + "group_totals_photons_per_s", + &totals.group_totals_photons_per_s, + )?; + out.set_item("totals", totals_dict)?; + } else { + out.set_item("totals", py.None())?; + } + Ok(out.into_any().unbind()) +} + +fn r2s_photon_source_to_py( + py: Python<'_>, + source: &nucleide_r2s::PhotonSource, +) -> PyResult> { + use pyo3::types::PyDict; + let draft = nucleide_r2s::PhotonSourceDraft::new( + source.mesh_shape, + source.lower_left_cm, + source.upper_right_cm, + source.voxel_volumes_cm3.clone(), + source.edges_ev.clone(), + source.cooling_s, + source.strengths_photons_per_s.clone(), + ); + let report = nucleide_r2s::SourceReport::from_draft(&draft); + let out = PyDict::new(py); + out.set_item("mesh_shape", source.mesh_shape.to_vec())?; + out.set_item("lower_left_cm", source.lower_left_cm.to_vec())?; + out.set_item("upper_right_cm", source.upper_right_cm.to_vec())?; + out.set_item("voxel_volumes_cm3", &source.voxel_volumes_cm3)?; + out.set_item("edges_ev", &source.edges_ev)?; + out.set_item("cooling_s", source.cooling_s)?; + out.set_item("strengths_photons_per_s", &source.strengths_photons_per_s)?; + out.set_item("n_voxels", source.n_voxels())?; + out.set_item("n_groups", source.n_groups())?; + out.set_item( + "total_photons_per_s", + source + .checked_total_photons_per_s() + .map_err(|e| PyValueError::new_err(e.to_string()))?, + )?; + out.set_item( + "voxel_totals_photons_per_s", + source + .voxel_totals() + .map_err(|e| PyValueError::new_err(e.to_string()))?, + )?; + out.set_item( + "group_totals_photons_per_s", + source + .group_totals() + .map_err(|e| PyValueError::new_err(e.to_string()))?, + )?; + out.set_item("validation", r2s_source_report_to_py(py, &report)?)?; + Ok(out.into_any().unbind()) +} + +/// Convert a raw tally into physical group flux (shared Rust kernel). +/// +/// `normalization` is `"volume-integrated"` for OpenMC's default +/// track-length flux tally or `"volume-averaged"` for random-ray output with +/// volume-normalized tallies. The `-rate-scaled` variants skip the source-rate +/// multiplication because OpenMC already applied the configured total source +/// strength; using the per-source spelling there would double-count the rate. +/// Already-physical input is rejected rather than scaled twice. Thin wrapper +/// over `nucleide-r2s` `normalize_flux`. +#[pyfunction] +fn r2s_normalize_flux( + tally: Vec>, + source_rate_s: f64, + volumes_cm3: Vec, + normalization: &str, +) -> PyResult>> { + let mode = match normalization { + "volume-integrated" => nucleide_r2s::TallyNormalization::VolumeIntegratedPerSource, + "volume-integrated-rate-scaled" => { + nucleide_r2s::TallyNormalization::VolumeIntegratedRateScaled + } + "volume-averaged" => nucleide_r2s::TallyNormalization::VolumeAveragedPerSource, + "volume-averaged-rate-scaled" => nucleide_r2s::TallyNormalization::VolumeAveragedRateScaled, + "physical" => nucleide_r2s::TallyNormalization::Physical, + other => { + return Err(PyValueError::new_err(format!( + "unknown tally normalization {other:?}; want 'volume-integrated', \ + 'volume-integrated-rate-scaled', 'volume-averaged', \ + 'volume-averaged-rate-scaled', or 'physical'" + ))) + } + }; + nucleide_r2s::normalize_flux(&tally, source_rate_s, &volumes_cm3, mode) + .map_err(|e| PyValueError::new_err(e.to_string())) +} + +/// Build and validate an integrated photon source at one cooling time. +/// +/// Returns the validated fields, checked totals and the structured source +/// report. Thin wrapper over `nucleide-r2s` `PhotonSource::new`. +#[pyfunction] +#[allow(clippy::too_many_arguments)] +fn r2s_photon_source( + py: Python<'_>, + mesh_shape: Vec, + lower_left_cm: Vec, + upper_right_cm: Vec, + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, +) -> PyResult> { + let source = nucleide_r2s::PhotonSource::new( + r2s_fixed3_usize(mesh_shape, "mesh_shape")?, + r2s_fixed3_f64(lower_left_cm, "lower_left_cm")?, + r2s_fixed3_f64(upper_right_cm, "upper_right_cm")?, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + ) + .map_err(|e| PyValueError::new_err(e.to_string()))?; + r2s_photon_source_to_py(py, &source) +} + +/// Rebuild a dense source from exported groups plus explicit dense indices. +/// +/// Omitted groups become exactly zero; duplicate, unsorted or out-of-range +/// indices are rejected. Thin wrapper over +/// `nucleide-r2s` `PhotonSource::from_exported_groups`. +#[pyfunction] +#[allow(clippy::too_many_arguments)] +fn r2s_photon_source_exported( + py: Python<'_>, + mesh_shape: Vec, + lower_left_cm: Vec, + upper_right_cm: Vec, + voxel_volumes_cm3: Vec, + full_edges_ev: Vec, + cooling_s: f64, + exported_group_indices: Vec, + exported_strengths_photons_per_s: Vec>, +) -> PyResult> { + let source = nucleide_r2s::PhotonSource::from_exported_groups( + &full_edges_ev, + r2s_fixed3_usize(mesh_shape, "mesh_shape")?, + r2s_fixed3_f64(lower_left_cm, "lower_left_cm")?, + r2s_fixed3_f64(upper_right_cm, "upper_right_cm")?, + voxel_volumes_cm3, + cooling_s, + &exported_group_indices, + &exported_strengths_photons_per_s, + ) + .map_err(|e| PyValueError::new_err(e.to_string()))?; + r2s_photon_source_to_py(py, &source) +} + +/// Return the structured, bounded validation report for a source draft. +/// +/// Never repairs the input; ordinary constructors and exporters still raise. +/// Thin wrapper over `nucleide-r2s` `SourceReport::from_draft`. +#[pyfunction] +#[allow(clippy::too_many_arguments)] +fn r2s_source_report( + py: Python<'_>, + mesh_shape: Vec, + lower_left_cm: Vec, + upper_right_cm: Vec, + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, +) -> PyResult> { + let draft = nucleide_r2s::PhotonSourceDraft::new( + r2s_fixed3_usize(mesh_shape, "mesh_shape")?, + r2s_fixed3_f64(lower_left_cm, "lower_left_cm")?, + r2s_fixed3_f64(upper_right_cm, "upper_right_cm")?, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + ); + let report = nucleide_r2s::SourceReport::from_draft(&draft); + r2s_source_report_to_py(py, &report) +} + +/// Joint voxel/group sampling probabilities (zero total is a loud error). +/// +/// Thin wrapper over `nucleide-r2s` `PhotonSource::joint_probabilities`. +#[pyfunction] +#[allow(clippy::too_many_arguments)] +fn r2s_source_probabilities( + mesh_shape: Vec, + lower_left_cm: Vec, + upper_right_cm: Vec, + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, +) -> PyResult>> { + let source = nucleide_r2s::PhotonSource::new( + r2s_fixed3_usize(mesh_shape, "mesh_shape")?, + r2s_fixed3_f64(lower_left_cm, "lower_left_cm")?, + r2s_fixed3_f64(upper_right_cm, "upper_right_cm")?, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + ) + .map_err(|e| PyValueError::new_err(e.to_string()))?; + source + .joint_probabilities() + .map_err(|e| PyValueError::new_err(e.to_string())) +} + +/// Per-voxel energy probabilities (`strength / voxel total`). +/// +/// Zero-source voxels yield all-zero rows; the joint distribution lives in +/// `r2s_source_probabilities`. Thin wrapper over +/// `nucleide-r2s` `PhotonSource::energy_probabilities`. +#[pyfunction] +#[allow(clippy::too_many_arguments)] +fn r2s_source_energy_probabilities( + mesh_shape: Vec, + lower_left_cm: Vec, + upper_right_cm: Vec, + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, +) -> PyResult>> { + let source = nucleide_r2s::PhotonSource::new( + r2s_fixed3_usize(mesh_shape, "mesh_shape")?, + r2s_fixed3_f64(lower_left_cm, "lower_left_cm")?, + r2s_fixed3_f64(upper_right_cm, "upper_right_cm")?, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + ) + .map_err(|e| PyValueError::new_err(e.to_string()))?; + source + .energy_probabilities() + .map_err(|e| PyValueError::new_err(e.to_string())) +} + +/// Integrated photons/(s cm3), applying each voxel volume exactly once. +/// +/// Thin wrapper over `nucleide-r2s` `PhotonSource::density_photons_per_s_cm3`. +#[pyfunction] +#[allow(clippy::too_many_arguments)] +fn r2s_source_density( + mesh_shape: Vec, + lower_left_cm: Vec, + upper_right_cm: Vec, + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, +) -> PyResult>> { + let source = nucleide_r2s::PhotonSource::new( + r2s_fixed3_usize(mesh_shape, "mesh_shape")?, + r2s_fixed3_f64(lower_left_cm, "lower_left_cm")?, + r2s_fixed3_f64(upper_right_cm, "upper_right_cm")?, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + ) + .map_err(|e| PyValueError::new_err(e.to_string()))?; + source + .density_photons_per_s_cm3() + .map_err(|e| PyValueError::new_err(e.to_string())) +} + +/// Exact cooling-offset selection (no interpolation or nearest matching). +/// +/// Returns indices into `available_s` in requested order. Thin wrapper over +/// `nucleide-r2s` `select_cooling_indices`. +#[pyfunction] +fn r2s_select_cooling(available_s: Vec, requested_s: Vec) -> PyResult> { + nucleide_r2s::select_cooling_indices(&available_s, &requested_s) + .map_err(|e| PyValueError::new_err(e.to_string())) +} + /// Select and sum `.photonSrc` group spectra for `nuclides` at `time_s`. /// /// Parses ALARA photon-source text, keeps rows matching the named nuclides @@ -11197,6 +11528,14 @@ fn _internal(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(r2s_expand, m)?)?; m.add_function(wrap_pyfunction!(r2s_assemble, m)?)?; m.add_function(wrap_pyfunction!(r2s_tag_zone_strength, m)?)?; + m.add_function(wrap_pyfunction!(r2s_normalize_flux, m)?)?; + m.add_function(wrap_pyfunction!(r2s_photon_source, m)?)?; + m.add_function(wrap_pyfunction!(r2s_photon_source_exported, m)?)?; + m.add_function(wrap_pyfunction!(r2s_source_report, m)?)?; + m.add_function(wrap_pyfunction!(r2s_source_probabilities, m)?)?; + m.add_function(wrap_pyfunction!(r2s_source_energy_probabilities, m)?)?; + m.add_function(wrap_pyfunction!(r2s_source_density, m)?)?; + m.add_function(wrap_pyfunction!(r2s_select_cooling, m)?)?; m.add_function(wrap_pyfunction!(r2s_photon_group_sums, m)?)?; m.add_function(wrap_pyfunction!(r2s_snapshot_inventory, m)?)?; m.add_function(wrap_pyfunction!(r2s_expand_sweep, m)?)?; diff --git a/bindings/wasm/src/lib.rs b/bindings/wasm/src/lib.rs index f98cae5..a780c25 100644 --- a/bindings/wasm/src/lib.rs +++ b/bindings/wasm/src/lib.rs @@ -4279,6 +4279,178 @@ pub fn voxel_photon_sums(input: JsValue) -> Result { }) } +// --------------------------------------------------------------------------- +// Activation-to-transport photon source (shared source contract) +// --------------------------------------------------------------------------- + +/// Browser-demo cap on photon-source voxels and groups. +const MAX_PHOTON_SOURCE_CELLS: usize = 200; + +#[derive(Deserialize)] +struct PhotonSourceInputJson { + #[serde(rename = "meshShape", alias = "mesh_shape")] + mesh_shape: Vec, + #[serde(rename = "lowerLeftCm", alias = "lower_left_cm")] + lower_left_cm: Vec, + #[serde(rename = "upperRightCm", alias = "upper_right_cm")] + upper_right_cm: Vec, + #[serde(rename = "voxelVolumesCm3", alias = "voxel_volumes_cm3")] + voxel_volumes_cm3: Vec, + #[serde(rename = "edgesEv", alias = "edges_ev")] + edges_ev: Vec, + #[serde(rename = "coolingS", alias = "cooling_s", default)] + cooling_s: f64, + #[serde(rename = "strengthsPhotonsPerS", alias = "strengths_photons_per_s")] + strengths_photons_per_s: Vec>, +} + +#[derive(Serialize)] +struct PhotonSourceIssueJson { + code: String, + severity: String, + location: String, + message: String, + remedy: String, +} + +#[derive(Serialize)] +struct PhotonSourceEvaluateResult { + valid: bool, + issues: Vec, + issue_count: usize, + truncated: bool, + total_photons_per_s: Option, + voxel_totals_photons_per_s: Vec, + group_totals_photons_per_s: Vec, + density_photons_per_s_cm3: Option>>, + energy_probabilities: Option>>, + joint_probabilities: Option>>, + sampling_error: Option, +} + +fn photon_source_draft( + input: PhotonSourceInputJson, +) -> Result { + let mesh_shape: [usize; 3] = input.mesh_shape.as_slice().try_into().map_err(|_| { + js_err(format!( + "meshShape must have exactly 3 entries, got {}", + input.mesh_shape.len() + )) + })?; + let lower_left: [f64; 3] = input.lower_left_cm.as_slice().try_into().map_err(|_| { + js_err(format!( + "lowerLeftCm must have exactly 3 entries, got {}", + input.lower_left_cm.len() + )) + })?; + let upper_right: [f64; 3] = input.upper_right_cm.as_slice().try_into().map_err(|_| { + js_err(format!( + "upperRightCm must have exactly 3 entries, got {}", + input.upper_right_cm.len() + )) + })?; + let voxels = mesh_shape + .iter() + .try_fold(1usize, |acc, dim| acc.checked_mul(*dim)) + .ok_or_else(|| js_err("mesh dimensions overflow the browser demo limit"))?; + if voxels > MAX_PHOTON_SOURCE_CELLS { + return Err(js_err(format!( + "voxel count {voxels} exceeds the demo cap of {MAX_PHOTON_SOURCE_CELLS}" + ))); + } + let groups = input.edges_ev.len().saturating_sub(1); + if groups > MAX_PHOTON_SOURCE_CELLS { + return Err(js_err(format!( + "group count {groups} exceeds the demo cap of {MAX_PHOTON_SOURCE_CELLS}" + ))); + } + Ok(nucleide_r2s::PhotonSourceDraft::new( + mesh_shape, + lower_left, + upper_right, + input.voxel_volumes_cm3, + input.edges_ev, + input.cooling_s, + input.strengths_photons_per_s, + )) +} + +/// Validate a photon source and return totals, assumptions and distributions. +/// +/// Dict-in with camelCase keys (snake_case aliases accepted): `meshShape`, +/// `lowerLeftCm`, `upperRightCm`, `voxelVolumesCm3`, `edgesEv`, `coolingS`, +/// `strengthsPhotonsPerS`. Calls the shared `r2s` source contract, returns the +/// bounded report plus checked totals, density, per-voxel energy +/// probabilities and the joint voxel/group distribution. An all-zero source +/// stays valid data but reports a `samplingError` instead of probabilities. +#[wasm_bindgen(js_name = photonSourceEvaluate)] +pub fn photon_source_evaluate(input: JsValue) -> Result { + let parsed: PhotonSourceInputJson = serde_wasm_bindgen::from_value(input).map_err(js_err)?; + let draft = photon_source_draft(parsed)?; + let report = nucleide_r2s::SourceReport::from_draft(&draft); + let issues: Vec = report + .issues + .iter() + .map(|issue| PhotonSourceIssueJson { + code: issue.code.to_string(), + severity: match issue.severity { + nucleide_r2s::IssueSeverity::Error => "error", + nucleide_r2s::IssueSeverity::Warning => "warning", + nucleide_r2s::IssueSeverity::Assumption => "assumption", + } + .to_string(), + location: issue.location.clone(), + message: issue.message.clone(), + remedy: issue.remedy.clone(), + }) + .collect(); + let mut result = PhotonSourceEvaluateResult { + valid: report.is_valid(), + issues, + issue_count: report.issue_count, + truncated: report.truncated, + total_photons_per_s: report.totals.as_ref().map(|t| t.total_photons_per_s), + voxel_totals_photons_per_s: report + .totals + .as_ref() + .map(|t| t.voxel_totals_photons_per_s.clone()) + .unwrap_or_default(), + group_totals_photons_per_s: report + .totals + .as_ref() + .map(|t| t.group_totals_photons_per_s.clone()) + .unwrap_or_default(), + density_photons_per_s_cm3: None, + energy_probabilities: None, + joint_probabilities: None, + sampling_error: None, + }; + if let Ok(source) = nucleide_r2s::PhotonSource::from_draft(&draft) { + result.density_photons_per_s_cm3 = source.density_photons_per_s_cm3().ok(); + result.energy_probabilities = source.energy_probabilities().ok(); + match source.joint_probabilities() { + Ok(probabilities) => result.joint_probabilities = Some(probabilities), + Err(error) => result.sampling_error = Some(error.to_string()), + } + } + to_js(&result) +} + +/// Exact cooling-offset selection over available and requested times. +/// +/// Returns the selected indices in requested order; duplicates, missing +/// offsets and non-finite values are loud errors (no interpolation or +/// nearest-time substitution). +#[wasm_bindgen(js_name = photonSourceSelectCooling)] +pub fn photon_source_select_cooling( + available_s: Vec, + requested_s: Vec, +) -> Result { + let indices = + nucleide_r2s::select_cooling_indices(&available_s, &requested_s).map_err(js_err)?; + to_js(&indices) +} + // --------------------------------------------------------------------------- // Point kinetics (step-reactivity transient + prompt jump) // --------------------------------------------------------------------------- diff --git a/crates/r2s/AGENTS.md b/crates/r2s/AGENTS.md index dec2e81..74f4cee 100644 --- a/crates/r2s/AGENTS.md +++ b/crates/r2s/AGENTS.md @@ -3,14 +3,15 @@ ## Purpose Rigorous two-step (R2S) shutdown-dose-rate orchestration: ALARA deck -workflows, versionless ARMI snapshot bridge, photon assembly, voxel tags, +workflows, versionless ARMI snapshot bridge, photon assembly, flux +normalization, activation-to-transport source handoff, voxel tags, parameter-sweep expansion (WATTS-class), and facility-flow accounting. Builds decks, links zones, assembles sources; transport and activation solving stay inside their respective codes. ## Ownership -Owns `crates/r2s/src/` (`workflow.rs`, `tags.rs`, `photon.rs`, +Owns `crates/r2s/src/` (`workflow.rs`, `tags.rs`, `photon.rs`, `source.rs`, `snapshot.rs`, `sweep.rs`), the Python surface (`nucleide.r2s`), and `tests/test_r2s.py` + `tests/test_r2s_tags.py`. @@ -30,6 +31,33 @@ Owns `crates/r2s/src/` (`workflow.rs`, `tags.rs`, `photon.rs`, total getters; `checked_total_strength` provides an additive finite aggregate. Underflowing strengths can round to zero, so relative conservation cannot be promised below the representable range. +- `source`: activation-to-transport handoff. `normalize_flux` takes an + explicit `TallyNormalization`; per-source volume-integrated tallies + multiply by the source rate and divide by caller voxel volumes, + per-source volume-averaged tallies multiply by the source rate only, and + the `*RateScaled` variants skip the rate multiplication because OpenMC + fixed-source tallies already include the configured total source strength. + `Physical` input is rejected. All tally/volume/rate inputs and + intermediate/result values must be finite; inputs are never mutated. + `PhotonSource` is the dense structured-mesh + contract: C-order voxels (`(i*ny+j)*nz+k`), finite ascending mesh bounds, + positive finite voxel volumes, `G+1` strictly ascending finite bin edges + with first `>= 0` (centroids are never accepted), finite `cooling_s >= 0`, + finite nonnegative integrated photons/s with one row per voxel and `G` + entries per row. Totals and densities use Neumaier compensation; + `joint_probabilities` is the joint voxel/group distribution and rejects a + non-finite or `<= 0` total; `energy_probabilities` is the per-voxel + spectrum (zero rows for zero-source voxels). `from_exported_groups` requires + strictly increasing unique in-range indices and zero-fills omitted bins. + `select_cooling_indices` matches exact `==` only, preserves requested + order, and rejects duplicates/missing offsets loudly. +- `source` diagnostics: `PhotonSourceDraft` is unvalidated; `SourceReport` + and `PhotonSource::from_draft` share one check order (mesh, bounds, + volumes, edges, cooling, strengths, totals, warnings, assumptions), never + repair, and use stable kebab-case codes documented in `source.rs`. + `SOURCE_ISSUE_LIMIT` caps stored examples while `issue_count` and + `truncated` keep the true count. Assumptions (`source-assumption-*`) and + `source-all-zero` do not invalidate a source; any `Error` severity does. - `snapshot`: ARMI dict-in bridge (never touches HDF5, never mirrors ARMI internals); `snapshot_inventory` totals atoms per bare name (`N × V × 1e-24`) for facility snapshot differencing. @@ -49,7 +77,10 @@ Owns `crates/r2s/src/` (`workflow.rs`, `tags.rs`, `photon.rs`, ## Verification - `cargo test -p nucleide-r2s`. -- `pytest tests/test_r2s.py tests/test_r2s_tags.py` after `maturin develop`. +- `cargo bench -p nucleide-r2s --bench source_bench` for the 1k/10k/100k + voxel source-contract baseline (24 groups; no I/O). +- `pytest tests/test_r2s.py tests/test_r2s_tags.py tests/test_openmc_handoff.py` + after `maturin develop`. - `validation/activation_vs_refs.py` runs inside `run_all.sh`. ## Child NAD Index diff --git a/crates/r2s/Cargo.toml b/crates/r2s/Cargo.toml index d32e80e..fd934c5 100644 --- a/crates/r2s/Cargo.toml +++ b/crates/r2s/Cargo.toml @@ -16,3 +16,10 @@ nucleide-nuclei.workspace = true serde.workspace = true thiserror.workspace = true nucleide-vr-tools.workspace = true + +[dev-dependencies] +criterion = "0.5" + +[[bench]] +name = "source_bench" +harness = false diff --git a/crates/r2s/benches/source_bench.rs b/crates/r2s/benches/source_bench.rs new file mode 100644 index 0000000..4ea071e --- /dev/null +++ b/crates/r2s/benches/source_bench.rs @@ -0,0 +1,75 @@ +//! Criterion benchmarks for the activation-to-transport source contract. +//! +//! Synthetic regular meshes with 24 groups and irregular per-voxel spectra. +//! Measures source construction/validation, structured reporting, density +//! conversion and joint probabilities separately at 1k, 10k and 100k +//! voxels (2.4M values at the top size). No I/O and no OpenMC objects. + +use criterion::{criterion_group, criterion_main, Criterion, Throughput}; +use nucleide_r2s::{PhotonSource, PhotonSourceDraft, SourceReport}; + +const GROUPS: usize = 24; + +fn source(voxels: usize) -> PhotonSource { + let mut strengths = Vec::with_capacity(voxels); + for voxel in 0..voxels { + let mut row = Vec::with_capacity(GROUPS); + for group in 0..GROUPS { + let value = if (voxel + group) % 7 == 0 { + 0.0 + } else { + ((voxel * 31 + group * 17) % 1000) as f64 + 0.25 + }; + row.push(value); + } + strengths.push(row); + } + let mut edges = Vec::with_capacity(GROUPS + 1); + for group in 0..=GROUPS { + edges.push(group as f64 * (group as f64 + 1.0)); + } + PhotonSource::new( + [voxels, 1, 1], + [0.0, 0.0, 0.0], + [voxels as f64, 1.0, 1.0], + vec![1.0; voxels], + edges, + 0.0, + strengths, + ) + .expect("synthetic source") +} + +fn bench_source(c: &mut Criterion) { + let mut group = c.benchmark_group("r2s_source_contract"); + group.sample_size(10); + + for voxels in [1_000usize, 10_000, 100_000] { + let built = source(voxels); + group.throughput(Throughput::Elements((voxels * GROUPS) as u64)); + + group.bench_function(format!("new_{voxels}"), |b| b.iter(|| source(voxels))); + group.bench_function(format!("report_{voxels}"), |b| { + let draft = PhotonSourceDraft::new( + built.mesh_shape, + built.lower_left_cm, + built.upper_right_cm, + built.voxel_volumes_cm3.clone(), + built.edges_ev.clone(), + built.cooling_s, + built.strengths_photons_per_s.clone(), + ); + b.iter(|| SourceReport::from_draft(&draft)) + }); + group.bench_function(format!("density_{voxels}"), |b| { + b.iter(|| built.density_photons_per_s_cm3().expect("density")) + }); + group.bench_function(format!("joint_probabilities_{voxels}"), |b| { + b.iter(|| built.joint_probabilities().expect("probabilities")) + }); + } + group.finish(); +} + +criterion_group!(benches, bench_source); +criterion_main!(benches); diff --git a/crates/r2s/src/lib.rs b/crates/r2s/src/lib.rs index ecf9940..c9116c3 100644 --- a/crates/r2s/src/lib.rs +++ b/crates/r2s/src/lib.rs @@ -10,6 +10,7 @@ pub mod error; pub mod photon; pub mod snapshot; +pub mod source; pub mod sweep; pub mod tags; pub mod workflow; @@ -20,6 +21,10 @@ pub use snapshot::{ deck_from_snapshot, snapshot_inventory, snapshot_workflow, SnapshotFluxDef, SnapshotInput, SnapshotZone, }; +pub use source::{ + normalize_flux, select_cooling_indices, IssueSeverity, PhotonSource, PhotonSourceDraft, + SourceIssue, SourceReport, SourceTotals, TallyNormalization, SOURCE_ISSUE_LIMIT, +}; pub use sweep::{assemble_results, expand_sweep, SweepAxis, SweepCase}; pub use tags::{ photon_groups_at, split_zone_totals, split_zone_totals_by_volume, sum_group_strengths, diff --git a/crates/r2s/src/source.rs b/crates/r2s/src/source.rs new file mode 100644 index 0000000..52c2fd1 --- /dev/null +++ b/crates/r2s/src/source.rs @@ -0,0 +1,1850 @@ +//! Activation-to-transport photon-source handoff for R2S. +//! +//! This module carries the activation-side results into a transport-ready +//! source without silently reinterpreting them: +//! +//! - [`normalize_flux`] converts a declared flux tally into a physical flux +//! using an explicit [`TallyNormalization`] contract; per-source and +//! source-rate-scaled variants never multiply the rate twice. +//! - [`PhotonSource`] is the dense structured-mesh photon source: voxel +//! volumes, energy-bin edges, one cooling time, and integrated +//! photons/s per voxel and group. [`PhotonSource::from_exported_groups`] +//! expands a sparse group export back onto the full energy grid with +//! zeros in omitted bins. +//! - [`select_cooling_indices`] selects cooling times by exact equality +//! only; no interpolation or nearest-neighbour matching happens here. +//! - [`SourceReport`] validates a [`PhotonSourceDraft`] and explains every +//! problem with a stable code, severity, location, message, and remedy. +//! [`PhotonSource::from_draft`] rejects a draft exactly when the report +//! contains an [`IssueSeverity::Error`]. +//! +//! # Flat voxel order +//! +//! A voxel is identified by `(i, j, k)` with flat index +//! `(i * ny + j) * nz + k` (C order), where `mesh_shape = [nx, ny, nz]`. +//! +//! # Energy bins +//! +//! `edges_ev` holds bin edges, not centroids: `G + 1` strictly ascending +//! finite values whose first entry is `>= 0`. Centroids are never accepted +//! or converted into edges. +//! +//! # Issue codes +//! +//! Codes are stable, kebab-case, and reported in deterministic check order +//! (mesh, bounds, volumes, edges, cooling, strengths, totals, warnings, +//! assumptions). [`SOURCE_ISSUE_LIMIT`] caps the stored examples; +//! [`SourceReport::issue_count`] keeps the true count. +//! +//! Errors: +//! +//! - `source-mesh-degenerate`: a mesh dimension is zero. +//! - `source-mesh-overflow`: the mesh voxel product overflows `usize`. +//! - `source-bounds-non-finite`: a mesh-bound component is not finite. +//! - `source-bounds-not-ascending`: `upper_right_cm <= lower_left_cm` on an +//! axis. +//! - `source-volume-count-mismatch`: volume count differs from the mesh +//! voxel product. +//! - `source-volume-not-finite`: a voxel volume is not finite. +//! - `source-volume-not-positive`: a voxel volume is zero or negative. +//! - `source-edges-too-short`: fewer than two energy edges. +//! - `source-edge-not-finite`: an energy edge is not finite. +//! - `source-edges-not-ascending`: an energy edge does not exceed the +//! previous edge. +//! - `source-edge-negative`: the first energy edge is negative. +//! - `source-cooling-not-finite`: the cooling time is not finite. +//! - `source-cooling-negative`: the cooling time is negative. +//! - `source-strength-count-mismatch`: strength-row count differs from +//! the mesh voxel product. +//! - `source-group-count-mismatch`: a voxel row width differs from the +//! energy-group count. +//! - `source-strength-not-finite`: a group strength is not finite. +//! - `source-strength-negative`: a group strength is negative. +//! - `source-total-not-finite`: compensated totals overflow. +//! +//! Warnings: +//! +//! - `source-all-zero`: every strength is zero, so sampling has no +//! probability mass. +//! +//! Assumptions: +//! +//! - `source-assumption-uniform-within-bin`: emission has uniform density +//! per eV inside each group (not uniform per group). +//! - `source-assumption-uniform-within-voxel`: emission is uniform in +//! position inside each voxel. + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +/// Maximum number of [`SourceIssue`] examples stored in a [`SourceReport`]. +pub const SOURCE_ISSUE_LIMIT: usize = 100; + +/// How a flux tally is normalized before conversion to physical flux. +/// +/// OpenMC fixed-source tallies are normalized by the number of source +/// particles **and** scaled by the sum of the configured source strengths +/// (`settings::run_mode == FIXED_SOURCE` in OpenMC 0.16's +/// `src/tallies/tally.cpp`). A source with strength `1.0` therefore yields a +/// per-source-particle tally, while a source configured in absolute +/// particles/s or photons/s yields a source-rate-scaled tally. The state +/// must be declared, because multiplying a rate-scaled tally by the rate a +/// second time is wrong. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TallyNormalization { + /// Track-length / volume-integrated tally per source particle (OpenMC's + /// default flux tally when the configured source strengths sum to 1). + VolumeIntegratedPerSource, + /// Volume-integrated tally already scaled by the configured total source + /// strength (OpenMC source strengths sum to the physical rate). + VolumeIntegratedRateScaled, + /// Volume-averaged flux per source particle (e.g. random-ray + /// volume-normalized tallies with normalized source weights). + VolumeAveragedPerSource, + /// Volume-averaged tally already scaled by the configured total source + /// strength. + VolumeAveragedRateScaled, + /// Already physical flux; converting again is an error. + Physical, +} + +/// Convert a flux tally into physical flux using a declared normalization. +/// +/// `tally[v][g]` is the tally in voxel `v` and group `g`; `volumes_cm3[v]` +/// is that voxel's volume in cm³. The tally must be nonempty and +/// rectangular, one volume is required per tally row, source rates must be +/// finite and `>= 0`, and every tally value must be finite and `>= 0`. +/// +/// The per-source variants multiply by `source_rate_s`: +/// [`TallyNormalization::VolumeIntegratedPerSource`] computes +/// `value * source_rate_s / volume`; the volume-averaged variant computes +/// `value * source_rate_s`. The rate-scaled variants skip that multiplication +/// because OpenMC already applied the configured total source strength: +/// volume-integrated divides by volume only, volume-averaged returns the +/// values unchanged. [`TallyNormalization::Physical`] is rejected because +/// normalizing twice would silently corrupt the units. Shape, group order, +/// zeros, and caller inputs are preserved; non-finite intermediates or +/// results are errors. +pub fn normalize_flux( + tally: &[Vec], + source_rate_s: f64, + volumes_cm3: &[f64], + input: TallyNormalization, +) -> Result>> { + if matches!(input, TallyNormalization::Physical) { + return Err(Error::Invalid( + "flux tally is already normalized; do not normalize twice".to_string(), + )); + } + if !source_rate_s.is_finite() || source_rate_s < 0.0 { + return Err(Error::Invalid( + "source rate must be finite and nonnegative".to_string(), + )); + } + let Some(first) = tally.first() else { + return Err(Error::Invalid("flux tally is empty".to_string())); + }; + if first.is_empty() { + return Err(Error::Invalid( + "flux tally rows must be nonempty".to_string(), + )); + } + for (voxel, row) in tally.iter().enumerate() { + if row.len() != first.len() { + return Err(Error::Invalid(format!( + "flux tally is ragged: voxel {voxel} has {} groups but voxel 0 has {}", + row.len(), + first.len() + ))); + } + } + if volumes_cm3.len() != tally.len() { + return Err(Error::Invalid(format!( + "flux tally has {} voxel rows but {} volumes were supplied", + tally.len(), + volumes_cm3.len() + ))); + } + for (voxel, &volume) in volumes_cm3.iter().enumerate() { + if !volume.is_finite() || volume <= 0.0 { + return Err(Error::Invalid(format!( + "voxel {voxel} volume must be finite and positive" + ))); + } + } + for (voxel, row) in tally.iter().enumerate() { + for (group, &value) in row.iter().enumerate() { + if !value.is_finite() || value < 0.0 { + return Err(Error::Invalid(format!( + "voxel {voxel} group {group} tally value must be finite and nonnegative" + ))); + } + } + } + + let rate_scaled = matches!( + input, + TallyNormalization::VolumeIntegratedRateScaled + | TallyNormalization::VolumeAveragedRateScaled + ); + let mut flux = Vec::with_capacity(tally.len()); + for (voxel, row) in tally.iter().enumerate() { + let mut converted = Vec::with_capacity(row.len()); + for (group, &value) in row.iter().enumerate() { + let scaled = if rate_scaled { + value + } else { + let scaled = value * source_rate_s; + if !scaled.is_finite() { + return Err(Error::Invalid(format!( + "flux normalization overflowed at voxel {voxel} group {group}" + ))); + } + scaled + }; + let normalized = match input { + TallyNormalization::VolumeIntegratedPerSource + | TallyNormalization::VolumeIntegratedRateScaled => scaled / volumes_cm3[voxel], + TallyNormalization::VolumeAveragedPerSource + | TallyNormalization::VolumeAveragedRateScaled => scaled, + TallyNormalization::Physical => unreachable!("physical input rejected above"), + }; + if !normalized.is_finite() { + return Err(Error::Invalid(format!( + "flux normalization overflowed at voxel {voxel} group {group}" + ))); + } + converted.push(normalized); + } + flux.push(converted); + } + Ok(flux) +} + +/// Dense structured-mesh photon source handed from activation to transport. +/// +/// Fields are public so callers can assemble and inspect the contract, but +/// every accessor revalidates the full layout through [`SourceReport`], so a +/// mutated source cannot silently produce totals or sampling probabilities +/// from inconsistent data. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PhotonSource { + /// Mesh dimensions `[nx, ny, nz]`; every dimension is at least 1. + /// The flat voxel index is `(i * ny + j) * nz + k` (C order). + pub mesh_shape: [usize; 3], + /// Lower-left mesh corner in cm (finite). + pub lower_left_cm: [f64; 3], + /// Upper-right mesh corner in cm (finite, strictly above the lower + /// corner on every axis). + pub upper_right_cm: [f64; 3], + /// Voxel volumes in cm³, one per voxel in flat order (finite and + /// positive). + pub voxel_volumes_cm3: Vec, + /// Energy-bin edges in eV: `G + 1` strictly ascending, finite values + /// whose first entry is `>= 0`. These are edges, never centroids. + pub edges_ev: Vec, + /// Cooling time in seconds after shutdown (finite and `>= 0`). + pub cooling_s: f64, + /// Integrated group strengths in photons/s, indexed `[voxel][group]` + /// (finite and `>= 0`, one row per voxel, `G` entries per row). + pub strengths_photons_per_s: Vec>, +} + +impl PhotonSource { + /// Build and validate a dense photon source. + /// + /// Equivalent to [`Self::from_draft`] on a freshly built + /// [`PhotonSourceDraft`]: the constructor and the report share one set + /// of checks. + pub fn new( + mesh_shape: [usize; 3], + lower_left_cm: [f64; 3], + upper_right_cm: [f64; 3], + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, + ) -> Result { + let draft = PhotonSourceDraft::new( + mesh_shape, + lower_left_cm, + upper_right_cm, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + ); + Self::from_draft(&draft) + } + + /// Build a dense photon source from an unvalidated draft. + /// + /// Returns [`Error::Invalid`] when the shared validation report contains + /// any [`IssueSeverity::Error`]; warnings such as + /// `source-all-zero` do not block construction. + pub fn from_draft(draft: &PhotonSourceDraft) -> Result { + let report = SourceReport::from_draft(draft); + if !report.is_valid() { + return Err(validation_error(&report)); + } + if report.totals.is_none() { + return Err(Error::Invalid( + "photon source totals are not computable; check the mesh, edges, volumes, and \ + strengths" + .to_string(), + )); + } + Ok(Self { + mesh_shape: draft.mesh_shape, + lower_left_cm: draft.lower_left_cm, + upper_right_cm: draft.upper_right_cm, + voxel_volumes_cm3: draft.voxel_volumes_cm3.clone(), + edges_ev: draft.edges_ev.clone(), + cooling_s: draft.cooling_s, + strengths_photons_per_s: draft.strengths_photons_per_s.clone(), + }) + } + + /// Number of voxel rows in the strength layout. + /// + /// Validation requires this to equal `nx * ny * nz`. + pub fn n_voxels(&self) -> usize { + self.strengths_photons_per_s.len() + } + + /// Number of energy groups (`edges_ev.len() - 1`, or zero for an + /// invalid edge list). + pub fn n_groups(&self) -> usize { + self.edges_ev.len().saturating_sub(1) + } + + /// Compensated total photon strength in photons/s. + /// + /// Uses Neumaier compensation and rejects non-finite cells or + /// aggregates. An all-zero source returns `0.0` even though it cannot be + /// sampled. + pub fn checked_total_photons_per_s(&self) -> Result { + Ok(self.checked_totals()?.total_photons_per_s) + } + + /// Compensated per-voxel totals in photons/s in flat voxel order. + pub fn voxel_totals(&self) -> Result> { + Ok(self.checked_totals()?.voxel_totals_photons_per_s) + } + + /// Compensated per-group totals in photons/s in energy-group order. + pub fn group_totals(&self) -> Result> { + Ok(self.checked_totals()?.group_totals_photons_per_s) + } + + /// Photon density per voxel and group in photons/s/cm³. + /// + /// Each integrated strength is divided by its voxel volume exactly once. + /// Zero-strength voxels stay zero; non-finite densities are errors. + pub fn density_photons_per_s_cm3(&self) -> Result>> { + self.checked_totals()?; + let mut densities = Vec::with_capacity(self.strengths_photons_per_s.len()); + for (voxel, (row, &volume)) in self + .strengths_photons_per_s + .iter() + .zip(&self.voxel_volumes_cm3) + .enumerate() + { + let mut voxel_densities = Vec::with_capacity(row.len()); + for (group, &value) in row.iter().enumerate() { + let density = value / volume; + if !density.is_finite() { + return Err(Error::Invalid(format!( + "photon density at voxel {voxel} group {group} is not finite" + ))); + } + voxel_densities.push(density); + } + densities.push(voxel_densities); + } + Ok(densities) + } + + /// Joint voxel/group sampling probabilities (`strength / total`). + /// + /// Returns shape `[voxel][group]`; this is the joint distribution over + /// voxels and groups. Do not factor it into independent spatial and + /// energy marginals. A non-finite total or a total `<= 0` (including an + /// all-zero source) is an error. + pub fn joint_probabilities(&self) -> Result>> { + let totals = self.checked_totals()?; + let total = totals.total_photons_per_s; + if !total.is_finite() || total <= 0.0 { + return Err(Error::Invalid(format!( + "photon source total {total} photons/s cannot be sampled; joint probabilities \ + require a finite positive total" + ))); + } + let mut probabilities = Vec::with_capacity(self.strengths_photons_per_s.len()); + for (voxel, row) in self.strengths_photons_per_s.iter().enumerate() { + let mut voxel_probabilities = Vec::with_capacity(row.len()); + for (group, &value) in row.iter().enumerate() { + let probability = value / total; + if !probability.is_finite() { + return Err(Error::Invalid(format!( + "joint probability at voxel {voxel} group {group} is not finite" + ))); + } + voxel_probabilities.push(probability); + } + probabilities.push(voxel_probabilities); + } + Ok(probabilities) + } + + /// Per-voxel energy probabilities (`strength / voxel total`). + /// + /// Returns shape `[voxel][group]`. Each positive-total row sums to one + /// and describes only the energy distribution inside that voxel; a + /// zero-source voxel yields an all-zero row (it carries no sampling + /// distribution). Use [`Self::joint_probabilities`] for the joint + /// voxel/group distribution. An all-zero source is not an error here + /// because zero rows are meaningful data; callers that need a sampling + /// distribution must reject a zero total themselves. + pub fn energy_probabilities(&self) -> Result>> { + let mut probabilities = Vec::with_capacity(self.strengths_photons_per_s.len()); + for (voxel, row) in self.strengths_photons_per_s.iter().enumerate() { + let total: f64 = row.iter().sum(); + if !total.is_finite() { + return Err(Error::Invalid(format!( + "voxel {voxel} total strength is not finite" + ))); + } + let mut voxel_probabilities = Vec::with_capacity(row.len()); + for (group, &value) in row.iter().enumerate() { + let probability = if total > 0.0 { value / total } else { 0.0 }; + if !probability.is_finite() { + return Err(Error::Invalid(format!( + "energy probability at voxel {voxel} group {group} is not finite" + ))); + } + voxel_probabilities.push(probability); + } + probabilities.push(voxel_probabilities); + } + Ok(probabilities) + } + + /// Expand a sparse group export back onto the full energy grid. + /// + /// `full_edges_ev` describes the complete `G`-group grid; + /// `exported_group_indices` lists the exported bins in strictly + /// increasing, unique order; `exported_strengths[v][k]` is voxel `v`'s + /// strength in exported bin `k`. Omitted groups are filled with zeros. + /// + /// Empty, duplicate, out-of-range, or unsorted indices are rejected, + /// and every exported row must have exactly one value per index. + /// `full_edges_ev` must be bin edges; centroids are never accepted or + /// converted. + #[allow(clippy::too_many_arguments)] + pub fn from_exported_groups( + full_edges_ev: &[f64], + mesh_shape: [usize; 3], + lower_left_cm: [f64; 3], + upper_right_cm: [f64; 3], + voxel_volumes_cm3: Vec, + cooling_s: f64, + exported_group_indices: &[usize], + exported_strengths: &[Vec], + ) -> Result { + let full_groups = full_edges_ev + .len() + .checked_sub(1) + .filter(|groups| *groups > 0) + .ok_or_else(|| { + Error::Invalid("full energy grid must contain at least two edges".to_string()) + })?; + if exported_group_indices.is_empty() { + return Err(Error::Invalid( + "exported group indices must be nonempty".to_string(), + )); + } + let mut previous = None; + for &index in exported_group_indices { + if index >= full_groups { + return Err(Error::Invalid(format!( + "exported group index {index} is outside the {full_groups}-group full grid" + ))); + } + if let Some(previous) = previous { + if index == previous { + return Err(Error::Invalid(format!( + "exported group indices contain duplicate {index}" + ))); + } + if index < previous { + return Err(Error::Invalid( + "exported group indices must be strictly increasing".to_string(), + )); + } + } + previous = Some(index); + } + let width = exported_group_indices.len(); + if let Some((voxel, row)) = exported_strengths + .iter() + .enumerate() + .find(|(_, row)| row.len() != width) + { + return Err(Error::Invalid(format!( + "exported strength row {voxel} has {} groups but {width} indices were supplied", + row.len() + ))); + } + + let mut dense = vec![vec![0.0; full_groups]; exported_strengths.len()]; + for (voxel, row) in exported_strengths.iter().enumerate() { + for (column, &index) in exported_group_indices.iter().enumerate() { + dense[voxel][index] = row[column]; + } + } + Self::new( + mesh_shape, + lower_left_cm, + upper_right_cm, + voxel_volumes_cm3, + full_edges_ev.to_vec(), + cooling_s, + dense, + ) + } + + fn checked_totals(&self) -> Result { + let report = inspect_source( + self.mesh_shape, + self.lower_left_cm, + self.upper_right_cm, + &self.voxel_volumes_cm3, + &self.edges_ev, + self.cooling_s, + &self.strengths_photons_per_s, + ); + if !report.is_valid() { + return Err(validation_error(&report)); + } + report + .totals + .ok_or_else(|| Error::Invalid("photon source totals are not computable".to_string())) + } +} + +/// Unvalidated photon-source draft. +/// +/// Carries the same fields as [`PhotonSource`] but imposes no invariants. +/// Run [`SourceReport::from_draft`] to obtain structured diagnostics, or +/// [`PhotonSource::from_draft`] to validate and construct. +#[derive(Debug, Clone, Default)] +pub struct PhotonSourceDraft { + /// Mesh dimensions `[nx, ny, nz]`; may be degenerate. + pub mesh_shape: [usize; 3], + /// Lower-left mesh corner in cm; may be non-finite. + pub lower_left_cm: [f64; 3], + /// Upper-right mesh corner in cm; may be non-finite or inverted. + pub upper_right_cm: [f64; 3], + /// Candidate voxel volumes in cm³. + pub voxel_volumes_cm3: Vec, + /// Candidate energy-bin edges in eV. + pub edges_ev: Vec, + /// Candidate cooling time in seconds. + pub cooling_s: f64, + /// Candidate integrated group strengths in photons/s. + pub strengths_photons_per_s: Vec>, +} + +impl PhotonSourceDraft { + /// Build an unvalidated draft from the photon-source fields. + pub fn new( + mesh_shape: [usize; 3], + lower_left_cm: [f64; 3], + upper_right_cm: [f64; 3], + voxel_volumes_cm3: Vec, + edges_ev: Vec, + cooling_s: f64, + strengths_photons_per_s: Vec>, + ) -> Self { + Self { + mesh_shape, + lower_left_cm, + upper_right_cm, + voxel_volumes_cm3, + edges_ev, + cooling_s, + strengths_photons_per_s, + } + } +} + +/// Severity of one [`SourceIssue`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IssueSeverity { + /// The source cannot be used or constructed. + Error, + /// The source is constructible but a sampling limitation is worth + /// surfacing (for example an all-zero total). + Warning, + /// A modelling assumption implied by the source representation. + Assumption, +} + +/// One structured diagnostic from [`SourceReport`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SourceIssue { + /// Stable kebab-case issue code (see the module-level list). + pub code: &'static str, + /// How the issue affects construction or sampling. + pub severity: IssueSeverity, + /// Deterministic location string such as `"mesh"`, `"voxel 3"`, or + /// `"group 4"`. + pub location: String, + /// Human-readable description of the problem. + pub message: String, + /// Suggested corrective action; assumptions carry a "none" remedy. + pub remedy: String, +} + +/// Compensated totals computed for a source draft. +#[derive(Debug, Clone, PartialEq)] +pub struct SourceTotals { + /// Compensated total over every voxel and group in photons/s. + pub total_photons_per_s: f64, + /// Compensated per-voxel totals in flat voxel order. + pub voxel_totals_photons_per_s: Vec, + /// Compensated per-group totals in energy-group order. + pub group_totals_photons_per_s: Vec, +} + +/// Structured validation report for a [`PhotonSourceDraft`]. +#[derive(Debug, Clone, PartialEq)] +pub struct SourceReport { + /// Stored diagnostics in deterministic check order, capped at + /// [`SOURCE_ISSUE_LIMIT`]. + pub issues: Vec, + /// Total diagnostics found before capping. + pub issue_count: usize, + /// Whether [`Self::issues`] omits diagnostics beyond the limit. + pub truncated: bool, + /// Compensated totals, or `None` when they are not computable. + pub totals: Option, +} + +impl SourceReport { + /// Build a validation report for `draft`. + /// + /// The report never repairs the draft. Checks run in a fixed order: + /// mesh, bounds, volumes, edges, cooling, strengths, totals, warnings, + /// then assumptions. + pub fn from_draft(draft: &PhotonSourceDraft) -> SourceReport { + inspect_source( + draft.mesh_shape, + draft.lower_left_cm, + draft.upper_right_cm, + &draft.voxel_volumes_cm3, + &draft.edges_ev, + draft.cooling_s, + &draft.strengths_photons_per_s, + ) + } + + /// Whether the report contains no [`IssueSeverity::Error`]. + /// + /// Warnings and assumptions do not make a source invalid. + pub fn is_valid(&self) -> bool { + !self + .issues + .iter() + .any(|issue| issue.severity == IssueSeverity::Error) + } +} + +/// Select the index of each requested cooling time in `available_s`. +/// +/// Matching is exact `==` only: no interpolation and no nearest-neighbour +/// snapping. Requested order is preserved, so repeated available times +/// resolve to the first occurrence. Available and requested times must be +/// finite and `>= 0`; duplicate requested offsets and missing offsets are +/// errors, and a missing-offset error names both the requested value and +/// the available times. +pub fn select_cooling_indices(available_s: &[f64], requested_s: &[f64]) -> Result> { + for (index, &value) in available_s.iter().enumerate() { + if !value.is_finite() || value < 0.0 { + return Err(Error::Invalid(format!( + "available cooling time {index} must be finite and nonnegative (found {value})" + ))); + } + } + for (index, &value) in requested_s.iter().enumerate() { + if !value.is_finite() || value < 0.0 { + return Err(Error::Invalid(format!( + "requested cooling time {index} must be finite and nonnegative (found {value})" + ))); + } + } + for (index, &value) in requested_s.iter().enumerate() { + if requested_s[..index].contains(&value) { + return Err(Error::Invalid(format!( + "requested cooling time {value} s appears more than once" + ))); + } + } + + let mut selected = Vec::with_capacity(requested_s.len()); + for &value in requested_s { + let index = available_s + .iter() + .position(|&other| other == value) + .ok_or_else(|| { + let available = available_s + .iter() + .map(|time| time.to_string()) + .collect::>() + .join(", "); + Error::Invalid(format!( + "requested cooling time {value} s is not among available times [{available}]" + )) + })?; + selected.push(index); + } + Ok(selected) +} + +/// Validate one draft and build its report. +/// +/// This is the single interpretation shared by [`SourceReport::from_draft`] +/// and every [`PhotonSource`] accessor. +fn inspect_source( + mesh_shape: [usize; 3], + lower_left_cm: [f64; 3], + upper_right_cm: [f64; 3], + voxel_volumes_cm3: &[f64], + edges_ev: &[f64], + cooling_s: f64, + strengths_photons_per_s: &[Vec], +) -> SourceReport { + let mut issues = IssueBuilder::default(); + + let mut mesh_ok = true; + for (axis, &dimension) in mesh_shape.iter().enumerate() { + if dimension == 0 { + mesh_ok = false; + issues.error( + "source-mesh-degenerate", + "mesh", + format!("mesh dimension {axis} must be at least 1 (found {dimension})"), + "give every mesh dimension at least one voxel", + ); + } + } + let product = mesh_shape + .iter() + .try_fold(1usize, |product, &dimension| product.checked_mul(dimension)); + let product = match product { + Some(product) => Some(product), + None => { + mesh_ok = false; + issues.error( + "source-mesh-overflow", + "mesh", + format!( + "mesh shape {}x{}x{} overflows the voxel count", + mesh_shape[0], mesh_shape[1], mesh_shape[2] + ), + "use a smaller mesh; the voxel count must fit in usize", + ); + None + } + }; + + let mut bounds_ok = true; + for (axis, (&lower, &upper)) in lower_left_cm.iter().zip(upper_right_cm.iter()).enumerate() { + if !lower.is_finite() { + bounds_ok = false; + issues.error( + "source-bounds-non-finite", + format!("lower_left_cm[{axis}]"), + format!("lower mesh bound on axis {axis} is not finite"), + "supply finite mesh bounds in cm", + ); + } + if !upper.is_finite() { + bounds_ok = false; + issues.error( + "source-bounds-non-finite", + format!("upper_right_cm[{axis}]"), + format!("upper mesh bound on axis {axis} is not finite"), + "supply finite mesh bounds in cm", + ); + } + } + for (axis, (&lower, &upper)) in lower_left_cm.iter().zip(upper_right_cm.iter()).enumerate() { + if lower.is_finite() && upper.is_finite() && upper <= lower { + bounds_ok = false; + issues.error( + "source-bounds-not-ascending", + format!("bounds[{axis}]"), + format!("upper bound {upper} cm must exceed lower bound {lower} cm on axis {axis}"), + "set upper_right_cm above lower_left_cm on every axis", + ); + } + } + + let mut volume_count_ok = false; + if let Some(product) = product { + if voxel_volumes_cm3.len() == product { + volume_count_ok = true; + } else { + issues.error( + "source-volume-count-mismatch", + "voxel_volumes_cm3", + format!( + "mesh has {product} voxels but {} volumes were supplied", + voxel_volumes_cm3.len() + ), + "supply one volume per mesh voxel", + ); + } + } + let mut volumes_ok = volume_count_ok; + for (voxel, &volume) in voxel_volumes_cm3.iter().enumerate() { + if !volume.is_finite() { + volumes_ok = false; + issues.error( + "source-volume-not-finite", + format!("voxel {voxel}"), + "voxel volume is not finite", + "supply finite voxel volumes in cm3", + ); + } else if volume <= 0.0 { + volumes_ok = false; + issues.error( + "source-volume-not-positive", + format!("voxel {voxel}"), + format!("voxel volume {volume} cm3 must be positive"), + "use positive voxel volumes; zero-volume voxels cannot carry density", + ); + } + } + + let edges_len_ok = edges_ev.len() >= 2; + let mut edges_ok = edges_len_ok; + if !edges_len_ok { + issues.error( + "source-edges-too-short", + "edges_ev", + format!( + "energy grid has {} edges; at least 2 are required", + edges_ev.len() + ), + "supply at least one energy bin (two edges) in eV", + ); + } + for (edge_index, &edge) in edges_ev.iter().enumerate() { + if !edge.is_finite() { + edges_ok = false; + issues.error( + "source-edge-not-finite", + format!("edge {edge_index}"), + format!("energy edge {edge_index} is not finite"), + "supply finite energy edges in eV", + ); + } + } + if edges_len_ok { + for (edge_index, window) in edges_ev.windows(2).enumerate() { + let (previous, edge) = (window[0], window[1]); + let next = edge_index + 1; + if previous.is_finite() && edge.is_finite() && edge <= previous { + edges_ok = false; + issues.error( + "source-edges-not-ascending", + format!("edge {next}"), + format!( + "energy edge {next} ({edge} eV) must exceed edge {edge_index} \ + ({previous} eV)" + ), + "sort energy edges strictly ascending", + ); + } + } + if edges_ev[0].is_finite() && edges_ev[0] < 0.0 { + edges_ok = false; + issues.error( + "source-edge-negative", + "edge 0", + format!("first energy edge {} eV must be >= 0", edges_ev[0]), + "start the energy grid at 0 eV or above", + ); + } + } + + if !cooling_s.is_finite() { + issues.error( + "source-cooling-not-finite", + "cooling_s", + "cooling time is not finite", + "supply a finite cooling time in seconds", + ); + } else if cooling_s < 0.0 { + issues.error( + "source-cooling-negative", + "cooling_s", + format!("cooling time {cooling_s} s must be >= 0"), + "supply cooling_s >= 0 (seconds after shutdown)", + ); + } + + let mut rows_ok = false; + if let Some(product) = product { + if strengths_photons_per_s.len() == product { + rows_ok = true; + } else { + issues.error( + "source-strength-count-mismatch", + "strengths_photons_per_s", + format!( + "mesh has {product} voxels but {} strength rows were supplied", + strengths_photons_per_s.len() + ), + "supply one strength row per mesh voxel", + ); + } + } + + let group_count = if edges_len_ok { + Some(edges_ev.len() - 1) + } else { + None + }; + let mut widths_ok = group_count.is_some(); + if let Some(group_count) = group_count { + for (voxel, row) in strengths_photons_per_s.iter().enumerate() { + if row.len() != group_count { + widths_ok = false; + issues.error( + "source-group-count-mismatch", + format!("voxel {voxel}"), + format!( + "voxel {voxel} has {} group strengths; expected {group_count}", + row.len() + ), + "pad or trim each voxel row to the energy-group count", + ); + } + } + } + + let mut values_finite = true; + let mut any_negative = false; + for (voxel, row) in strengths_photons_per_s.iter().enumerate() { + for (group, &value) in row.iter().enumerate() { + if !value.is_finite() { + values_finite = false; + issues.error( + "source-strength-not-finite", + format!("voxel {voxel} group {group}"), + "strength is not finite", + "replace non-finite strengths with finite photons/s", + ); + } else if value < 0.0 { + any_negative = true; + issues.error( + "source-strength-negative", + format!("voxel {voxel} group {group}"), + format!("strength {value} photons/s must be >= 0"), + "replace negative strengths with photons/s >= 0", + ); + } + } + } + + let mut totals = None; + if mesh_ok && rows_ok && widths_ok && values_finite { + if let Some(group_count) = group_count { + let mut voxel_totals = Vec::with_capacity(strengths_photons_per_s.len()); + let mut group_sums = vec![CompensatedSum::default(); group_count]; + let mut total_sum = CompensatedSum::default(); + let mut aggregates_finite = true; + for row in strengths_photons_per_s { + let mut voxel_sum = CompensatedSum::default(); + for (group, &value) in row.iter().enumerate() { + voxel_sum.add(value); + group_sums[group].add(value); + total_sum.add(value); + } + let voxel_total = voxel_sum.total(); + aggregates_finite &= voxel_total.is_finite(); + voxel_totals.push(voxel_total); + } + let group_totals: Vec = group_sums.iter().map(CompensatedSum::total).collect(); + let total = total_sum.total(); + aggregates_finite &= + total.is_finite() && group_totals.iter().all(|value| value.is_finite()); + if aggregates_finite { + if !any_negative && total == 0.0 { + issues.warning( + "source-all-zero", + "totals", + "every group strength is zero; sampling has no probability mass", + "provide a nonzero source or skip sampling", + ); + } + totals = Some(SourceTotals { + total_photons_per_s: total, + voxel_totals_photons_per_s: voxel_totals, + group_totals_photons_per_s: group_totals, + }); + } else { + issues.error( + "source-total-not-finite", + "totals", + "compensated photon total is not finite", + "reduce the source magnitude; the aggregate must be finite", + ); + } + } + } + + let geometry_ok = mesh_ok && bounds_ok && volume_count_ok && volumes_ok; + if geometry_ok && edges_ok { + issues.assumption( + "source-assumption-uniform-within-bin", + "edges_ev", + "photon emission is uniform in energy within each group", + "none; sampling treats each energy bin as uniform", + ); + issues.assumption( + "source-assumption-uniform-within-voxel", + "mesh", + "photon emission is uniform in position within each voxel", + "none; sampling treats each voxel as uniform", + ); + } + + issues.finish(totals) +} + +/// Neumaier-compensated accumulator. +#[derive(Clone, Copy, Default)] +struct CompensatedSum { + sum: f64, + correction: f64, +} + +impl CompensatedSum { + fn add(&mut self, value: f64) { + let next = self.sum + value; + self.correction += if self.sum.abs() >= value.abs() { + (self.sum - next) + value + } else { + (value - next) + self.sum + }; + self.sum = next; + } + + fn total(&self) -> f64 { + self.sum + self.correction + } +} + +/// Issue collector that caps stored examples but counts every issue. +#[derive(Default)] +struct IssueBuilder { + issues: Vec, + issue_count: usize, +} + +impl IssueBuilder { + fn push(&mut self, issue: SourceIssue) { + self.issue_count += 1; + if self.issues.len() < SOURCE_ISSUE_LIMIT { + self.issues.push(issue); + } + } + + fn error( + &mut self, + code: &'static str, + location: impl Into, + message: impl Into, + remedy: impl Into, + ) { + self.push(SourceIssue { + code, + severity: IssueSeverity::Error, + location: location.into(), + message: message.into(), + remedy: remedy.into(), + }); + } + + fn warning( + &mut self, + code: &'static str, + location: impl Into, + message: impl Into, + remedy: impl Into, + ) { + self.push(SourceIssue { + code, + severity: IssueSeverity::Warning, + location: location.into(), + message: message.into(), + remedy: remedy.into(), + }); + } + + fn assumption( + &mut self, + code: &'static str, + location: impl Into, + message: impl Into, + remedy: impl Into, + ) { + self.push(SourceIssue { + code, + severity: IssueSeverity::Assumption, + location: location.into(), + message: message.into(), + remedy: remedy.into(), + }); + } + + fn finish(self, totals: Option) -> SourceReport { + let truncated = self.issue_count > self.issues.len(); + SourceReport { + issues: self.issues, + issue_count: self.issue_count, + truncated, + totals, + } + } +} + +/// First-error summary used by construction and accessor failures. +fn validation_error(report: &SourceReport) -> Error { + match report + .issues + .iter() + .find(|issue| issue.severity == IssueSeverity::Error) + { + Some(issue) => { + let more = report.issue_count.saturating_sub(1); + if more == 0 { + Error::Invalid(format!( + "invalid photon source: {} at {}: {}", + issue.code, issue.location, issue.message + )) + } else { + Error::Invalid(format!( + "invalid photon source: {} at {}: {} ({more} more issues)", + issue.code, issue.location, issue.message + )) + } + } + None => Error::Invalid(format!( + "invalid photon source: {} issues reported but none stored", + report.issue_count + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn edges_for(groups: usize) -> Vec { + (0..=groups).map(|index| index as f64).collect() + } + + fn valid_draft() -> PhotonSourceDraft { + PhotonSourceDraft::new( + [2, 3, 2], + [0.0, 0.0, 0.0], + [2.0, 3.0, 2.0], + vec![1.0; 12], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![1.0, 2.0]; 12], + ) + } + + fn codes(report: &SourceReport) -> Vec<&'static str> { + report.issues.iter().map(|issue| issue.code).collect() + } + + // ---- normalization ------------------------------------------------- + + #[test] + fn normalization_hand_example_divides_by_volume() { + let tally = vec![vec![4.0, 9.0]]; + let flux = normalize_flux( + &tally, + 10.0, + &[2.0], + TallyNormalization::VolumeIntegratedPerSource, + ) + .unwrap(); + assert_eq!(flux, vec![vec![20.0, 45.0]]); + } + + #[test] + fn normalization_uses_each_voxel_volume() { + let tally = vec![vec![4.0, 9.0], vec![2.0, 3.0]]; + let flux = normalize_flux( + &tally, + 10.0, + &[2.0, 4.0], + TallyNormalization::VolumeIntegratedPerSource, + ) + .unwrap(); + assert_eq!(flux, vec![vec![20.0, 45.0], vec![5.0, 7.5]]); + } + + #[test] + fn normalization_zero_rate_preserves_shape_and_zeros() { + let tally = vec![vec![4.0, 9.0, 0.0], vec![2.0, 3.0, 5.0]]; + let flux = normalize_flux( + &tally, + 0.0, + &[2.0, 4.0], + TallyNormalization::VolumeIntegratedPerSource, + ) + .unwrap(); + assert_eq!(flux, vec![vec![0.0; 3], vec![0.0; 3]]); + } + + #[test] + fn normalization_volume_averaged_branch_skips_division() { + let tally = vec![vec![4.0, 9.0]]; + let flux = normalize_flux( + &tally, + 10.0, + &[2.0], + TallyNormalization::VolumeAveragedPerSource, + ) + .unwrap(); + assert_eq!(flux, vec![vec![40.0, 90.0]]); + } + + #[test] + fn normalization_rate_scaled_variants_skip_the_rate_multiplication() { + let tally = vec![vec![4.0, 9.0]]; + let integrated = normalize_flux( + &tally, + 10.0, + &[2.0], + TallyNormalization::VolumeIntegratedRateScaled, + ) + .unwrap(); + assert_eq!(integrated, vec![vec![2.0, 4.5]]); + let averaged = normalize_flux( + &tally, + 10.0, + &[2.0], + TallyNormalization::VolumeAveragedRateScaled, + ) + .unwrap(); + assert_eq!(averaged, vec![vec![4.0, 9.0]]); + } + + #[test] + fn normalization_rejects_physical_input() { + let error = normalize_flux(&[vec![1.0]], 1.0, &[1.0], TallyNormalization::Physical) + .unwrap_err() + .to_string(); + assert!(error.contains("already normalized")); + assert!(error.contains("do not normalize twice")); + } + + #[test] + fn normalization_rejects_bad_shapes_and_values() { + let integrated = TallyNormalization::VolumeIntegratedPerSource; + assert!(normalize_flux(&[], 1.0, &[], integrated).is_err()); + assert!(normalize_flux(&[vec![]], 1.0, &[1.0], integrated).is_err()); + assert!( + normalize_flux(&[vec![1.0, 2.0], vec![3.0]], 1.0, &[1.0, 1.0], integrated).is_err() + ); + assert!(normalize_flux(&[vec![1.0]], 1.0, &[], integrated).is_err()); + assert!(normalize_flux(&[vec![1.0]], 1.0, &[1.0, 2.0], integrated).is_err()); + for volume in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(normalize_flux(&[vec![1.0]], 1.0, &[volume], integrated).is_err()); + } + for rate in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(normalize_flux(&[vec![1.0]], rate, &[1.0], integrated).is_err()); + } + for value in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(normalize_flux(&[vec![value]], 1.0, &[1.0], integrated).is_err()); + } + } + + #[test] + fn normalization_detects_intermediate_and_result_overflow() { + let integrated = TallyNormalization::VolumeIntegratedPerSource; + assert!(normalize_flux(&[vec![f64::MAX]], 2.0, &[1.0], integrated).is_err()); + assert!(normalize_flux(&[vec![f64::MAX]], 1.0, &[f64::MIN_POSITIVE], integrated).is_err()); + } + + #[test] + fn normalization_does_not_mutate_inputs() { + let tally = vec![vec![4.0, 9.0], vec![2.0, 3.0]]; + let volumes = vec![2.0, 4.0]; + let tally_before = tally.clone(); + let volumes_before = volumes.clone(); + normalize_flux( + &tally, + 10.0, + &volumes, + TallyNormalization::VolumeIntegratedPerSource, + ) + .unwrap(); + assert_eq!(tally, tally_before); + assert_eq!(volumes, volumes_before); + } + + // ---- construction and validation ---------------------------------- + + #[test] + fn construction_accepts_a_dense_mesh_product() { + let source = PhotonSource::from_draft(&valid_draft()).unwrap(); + assert_eq!(source.mesh_shape, [2, 3, 2]); + assert_eq!(source.n_voxels(), 12); + assert_eq!(source.n_groups(), 2); + assert_eq!(source.checked_total_photons_per_s().unwrap(), 36.0); + assert_eq!(source.voxel_totals().unwrap(), vec![3.0; 12]); + assert_eq!(source.group_totals().unwrap(), vec![12.0, 24.0]); + } + + #[test] + fn construction_rejects_bad_mesh_and_geometry() { + let good = valid_draft(); + + let mut bad = good.clone(); + bad.mesh_shape = [0, 3, 2]; + assert!(PhotonSource::from_draft(&bad).is_err()); + + let mut bad = good.clone(); + bad.voxel_volumes_cm3.pop(); + assert!(PhotonSource::from_draft(&bad).is_err()); + + let mut bad = good.clone(); + bad.strengths_photons_per_s.pop(); + assert!(PhotonSource::from_draft(&bad).is_err()); + + let mut bad = good.clone(); + bad.upper_right_cm[1] = bad.lower_left_cm[1]; + assert!(PhotonSource::from_draft(&bad).is_err()); + + for volume in [0.0, -1.0, f64::NAN, f64::INFINITY] { + let mut bad = good.clone(); + bad.voxel_volumes_cm3[2] = volume; + assert!(PhotonSource::from_draft(&bad).is_err()); + } + for edges in [ + vec![0.0], + vec![0.0, 1.0, 1.0], + vec![1.0, 0.0], + vec![-1.0, 1.0], + vec![0.0, f64::NAN], + ] { + let mut bad = good.clone(); + let groups = edges.len().saturating_sub(1); + bad.edges_ev = edges; + bad.strengths_photons_per_s = vec![vec![1.0; groups]; 12]; + assert!(PhotonSource::from_draft(&bad).is_err()); + } + for cooling in [-1.0, f64::NAN, f64::INFINITY] { + let mut bad = good.clone(); + bad.cooling_s = cooling; + assert!(PhotonSource::from_draft(&bad).is_err()); + } + + let mut bad = good.clone(); + bad.strengths_photons_per_s[0].push(3.0); + assert!(PhotonSource::from_draft(&bad).is_err()); + + for value in [-1.0, f64::NAN, f64::INFINITY] { + let mut bad = good.clone(); + bad.strengths_photons_per_s[3][1] = value; + assert!(PhotonSource::from_draft(&bad).is_err()); + } + } + + #[test] + fn zero_source_voxel_is_allowed() { + let source = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![1.0, 1.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![0.0, 0.0], vec![3.0, 4.0]], + ) + .unwrap(); + assert_eq!(source.voxel_totals().unwrap(), vec![0.0, 7.0]); + assert_eq!( + source.density_photons_per_s_cm3().unwrap(), + vec![vec![0.0, 0.0], vec![3.0, 4.0]] + ); + } + + #[test] + fn all_zero_source_constructs_but_cannot_be_sampled() { + let source = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![1.0, 1.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![0.0, 0.0]; 2], + ) + .unwrap(); + assert_eq!(source.checked_total_photons_per_s().unwrap(), 0.0); + assert!(source.joint_probabilities().is_err()); + } + + #[test] + fn joint_probabilities_are_joint_not_factored() { + let source = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![2.0, 4.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![100.0, 0.0], vec![0.0, 300.0]], + ) + .unwrap(); + assert_eq!( + source.joint_probabilities().unwrap(), + vec![vec![0.25, 0.0], vec![0.0, 0.75]] + ); + } + + #[test] + fn energy_probabilities_are_per_voxel() { + let source = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![1.0, 1.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![100.0, 0.0], vec![0.0, 300.0]], + ) + .unwrap(); + assert_eq!( + source.energy_probabilities().unwrap(), + vec![vec![1.0, 0.0], vec![0.0, 1.0]] + ); + let zero_voxel = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![1.0, 1.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![100.0, 0.0], vec![0.0, 0.0]], + ) + .unwrap(); + assert_eq!( + zero_voxel.energy_probabilities().unwrap(), + vec![vec![1.0, 0.0], vec![0.0, 0.0]] + ); + } + + #[test] + fn density_divides_by_volume_exactly_once() { + let source = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![2.0, 4.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![100.0, 0.0], vec![0.0, 300.0]], + ) + .unwrap(); + let density = source.density_photons_per_s_cm3().unwrap(); + assert_eq!(density, vec![vec![50.0, 0.0], vec![0.0, 75.0]]); + for (voxel, row) in density.iter().enumerate() { + for (group, value) in row.iter().enumerate() { + assert_eq!( + value * source.voxel_volumes_cm3[voxel], + source.strengths_photons_per_s[voxel][group] + ); + } + } + } + + #[test] + fn irregular_edges_preserve_group_order() { + let source = PhotonSource::new( + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![1.0, 1.0], + vec![0.0, 0.5, 7.0, 20.0], + 0.0, + vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]], + ) + .unwrap(); + assert_eq!(source.n_groups(), 3); + assert_eq!(source.group_totals().unwrap(), vec![5.0, 7.0, 9.0]); + assert_eq!(source.checked_total_photons_per_s().unwrap(), 21.0); + } + + #[test] + fn checked_total_compensates_many_small_groups() { + let small = f64::EPSILON / 4.0; + let groups = 100_001usize; + let mut strengths = vec![small; groups]; + strengths[0] = 1.0; + let source = PhotonSource::new( + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![1.0], + edges_for(groups), + 0.0, + vec![strengths], + ) + .unwrap(); + let expected = 1.0 + 100_000.0 * small; + assert_eq!(source.checked_total_photons_per_s().unwrap(), expected); + // The ordinary floating-point sum loses the small terms. + assert_eq!(source.strengths_photons_per_s[0].iter().sum::(), 1.0); + } + + #[test] + fn construction_rejects_non_finite_totals() { + let draft = PhotonSourceDraft::new( + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![1.0], + vec![0.0, 1.0, 2.0], + 0.0, + vec![vec![f64::MAX, f64::MAX]], + ); + assert!(PhotonSource::from_draft(&draft).is_err()); + let report = SourceReport::from_draft(&draft); + assert!(!report.is_valid()); + assert!(report.totals.is_none()); + assert!(codes(&report).contains(&"source-total-not-finite")); + } + + // ---- sparse group export ------------------------------------------ + + #[test] + fn exported_groups_fill_omitted_bins_with_zeros() { + let edges = edges_for(24); + let exported = vec![vec![10.0, 20.0, 30.0], vec![40.0, 50.0, 60.0]]; + let source = PhotonSource::from_exported_groups( + &edges, + [1, 1, 2], + [0.0; 3], + [1.0, 1.0, 2.0], + vec![1.0, 2.0], + 0.0, + &[1, 5, 23], + &exported, + ) + .unwrap(); + assert_eq!(source.n_groups(), 24); + assert_eq!(source.n_voxels(), 2); + assert_eq!(source.strengths_photons_per_s[0][1], 10.0); + assert_eq!(source.strengths_photons_per_s[0][5], 20.0); + assert_eq!(source.strengths_photons_per_s[0][23], 30.0); + assert_eq!(source.strengths_photons_per_s[1][1], 40.0); + assert_eq!(source.strengths_photons_per_s[1][5], 50.0); + assert_eq!(source.strengths_photons_per_s[1][23], 60.0); + for group in 0..24 { + if ![1, 5, 23].contains(&group) { + assert_eq!(source.strengths_photons_per_s[0][group], 0.0); + assert_eq!(source.strengths_photons_per_s[1][group], 0.0); + } + } + assert_eq!(source.checked_total_photons_per_s().unwrap(), 210.0); + } + + #[test] + fn exported_groups_reject_ambiguous_indices() { + let edges = edges_for(24); + let exported = vec![vec![1.0, 2.0]]; + let call = |indices: &[usize], strengths: &[Vec]| { + PhotonSource::from_exported_groups( + &edges, + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![1.0], + 0.0, + indices, + strengths, + ) + }; + assert!(call(&[], &[]).is_err()); + assert!(call(&[1, 5, 5], &[vec![1.0, 2.0, 3.0]]).is_err()); + assert!(call(&[1, 24], &exported).is_err()); + assert!(call(&[5, 1], &exported).is_err()); + assert!(call(&[1, 5], &[vec![1.0]]).is_err()); + assert!(PhotonSource::from_exported_groups( + &[0.0], + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![1.0], + 0.0, + &[0], + &[vec![1.0]], + ) + .is_err()); + } + + // ---- cooling-time selection --------------------------------------- + + #[test] + fn cooling_selection_preserves_requested_order() { + assert_eq!( + select_cooling_indices(&[0.0, 10.0, 100.0], &[100.0, 0.0]).unwrap(), + vec![2, 0] + ); + assert_eq!(select_cooling_indices(&[0.0], &[0.0]).unwrap(), vec![0]); + assert_eq!( + select_cooling_indices(&[0.0, 10.0], &[]).unwrap(), + Vec::::new() + ); + } + + #[test] + fn cooling_selection_is_exact_only() { + let near = f64::MIN_POSITIVE; + let error = select_cooling_indices(&[0.0], &[near]) + .unwrap_err() + .to_string(); + assert!(error.contains(&near.to_string())); + assert!(error.contains("available")); + } + + #[test] + fn cooling_selection_rejects_duplicates_and_invalid_times() { + assert!(select_cooling_indices(&[0.0, 10.0], &[10.0, 10.0]).is_err()); + for bad in [-1.0, f64::NAN, f64::INFINITY] { + assert!(select_cooling_indices(&[bad], &[0.0]).is_err()); + assert!(select_cooling_indices(&[0.0], &[bad]).is_err()); + } + let error = select_cooling_indices(&[0.0, 10.0], &[2.5]) + .unwrap_err() + .to_string(); + assert!(error.contains("2.5")); + assert!(error.contains("0, 10")); + } + + // ---- structured report -------------------------------------------- + + #[test] + fn report_valid_source_has_assumptions_and_totals() { + let report = SourceReport::from_draft(&valid_draft()); + assert!(report.is_valid()); + assert!(!report.truncated); + assert_eq!(report.issue_count, 2); + assert_eq!(report.issues.len(), 2); + assert_eq!( + codes(&report), + vec![ + "source-assumption-uniform-within-bin", + "source-assumption-uniform-within-voxel" + ] + ); + assert!(report + .issues + .iter() + .all(|issue| issue.severity == IssueSeverity::Assumption)); + let totals = report.totals.unwrap(); + assert_eq!(totals.total_photons_per_s, 36.0); + assert_eq!(totals.voxel_totals_photons_per_s, vec![3.0; 12]); + assert_eq!(totals.group_totals_photons_per_s, vec![12.0, 24.0]); + } + + #[test] + fn report_has_stable_codes_and_deterministic_order() { + let draft = PhotonSourceDraft::new( + [0, 2, 2], + [0.0, 2.0, 0.0], + [0.0, 1.0, 1.0], + vec![1.0, 0.0, -2.0, f64::NAN], + vec![1.0, 1.0, 0.0], + -1.0, + vec![vec![1.0], vec![f64::NAN]], + ); + let report = SourceReport::from_draft(&draft); + assert_eq!( + codes(&report), + vec![ + "source-mesh-degenerate", + "source-bounds-not-ascending", + "source-bounds-not-ascending", + "source-volume-count-mismatch", + "source-volume-not-positive", + "source-volume-not-positive", + "source-volume-not-finite", + "source-edges-not-ascending", + "source-edges-not-ascending", + "source-cooling-negative", + "source-strength-count-mismatch", + "source-group-count-mismatch", + "source-group-count-mismatch", + "source-strength-not-finite", + ] + ); + assert_eq!(report.issue_count, 14); + assert_eq!(report.issue_count, report.issues.len()); + assert!(!report.truncated); + assert!(report.totals.is_none()); + assert!(!report.is_valid()); + + let repeated = SourceReport::from_draft(&draft); + assert_eq!(report.issues, repeated.issues); + assert_eq!(report.issue_count, repeated.issue_count); + assert_eq!(report.truncated, repeated.truncated); + } + + #[test] + fn report_flags_non_finite_bounds_and_edges() { + let draft = PhotonSourceDraft::new( + [1, 1, 1], + [f64::NAN, 0.0, 0.0], + [1.0, f64::INFINITY, 1.0], + vec![1.0], + vec![0.0, f64::NAN, 2.0], + 0.0, + vec![vec![1.0, 2.0]], + ); + let report = SourceReport::from_draft(&draft); + let all = codes(&report); + assert!(all.contains(&"source-bounds-non-finite")); + assert!(all.contains(&"source-edge-not-finite")); + assert!(!all.contains(&"source-edges-not-ascending")); + assert!(!report.is_valid()); + + let negative_start = PhotonSourceDraft::new( + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![1.0], + vec![-1.0, 1.0], + 0.0, + vec![vec![1.0]], + ); + let report = SourceReport::from_draft(&negative_start); + assert!(codes(&report).contains(&"source-edge-negative")); + } + + #[test] + fn report_flags_mesh_overflow_and_short_edges() { + let draft = PhotonSourceDraft::new( + [usize::MAX, 2, 2], + [0.0; 3], + [1.0; 3], + Vec::new(), + vec![1.0], + 0.0, + Vec::new(), + ); + let report = SourceReport::from_draft(&draft); + assert!(codes(&report).contains(&"source-mesh-overflow")); + assert!(codes(&report).contains(&"source-edges-too-short")); + assert!(!report.is_valid()); + assert!(report.totals.is_none()); + } + + #[test] + fn report_notes_all_zero_sources() { + let draft = PhotonSourceDraft::new( + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![1.0], + vec![0.0, 1.0], + 0.0, + vec![vec![0.0]], + ); + let report = SourceReport::from_draft(&draft); + assert!(report.is_valid()); + assert!(report.issues.iter().any(|issue| { + issue.code == "source-all-zero" && issue.severity == IssueSeverity::Warning + })); + assert_eq!(report.totals.unwrap().total_photons_per_s, 0.0); + assert!(PhotonSource::from_draft(&draft).is_ok()); + assert!(PhotonSource::from_draft(&draft) + .unwrap() + .joint_probabilities() + .is_err()); + } + + #[test] + fn report_caps_stored_diagnostics_but_counts_every_issue() { + let voxels = 1000; + let draft = PhotonSourceDraft::new( + [voxels, 1, 1], + [0.0; 3], + [1.0; 3], + vec![-1.0; voxels], + vec![0.0, 1.0], + 0.0, + vec![vec![1.0]; voxels], + ); + let report = SourceReport::from_draft(&draft); + assert_eq!(report.issue_count, voxels); + assert_eq!(report.issues.len(), SOURCE_ISSUE_LIMIT); + assert!(report.truncated); + assert!(!report.is_valid()); + assert!(report + .issues + .iter() + .all(|issue| issue.code == "source-volume-not-positive")); + assert_eq!(report.issues[0].location, "voxel 0"); + assert_eq!( + report.issues[SOURCE_ISSUE_LIMIT - 1].location, + format!("voxel {}", SOURCE_ISSUE_LIMIT - 1) + ); + // Totals remain computable even though volumes are invalid. + assert_eq!(report.totals.unwrap().total_photons_per_s, 1000.0); + } + + #[test] + fn report_and_constructor_share_one_interpretation() { + let draft = PhotonSourceDraft::new( + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![0.0], + vec![0.0, 1.0], + 0.0, + vec![vec![1.0]], + ); + let report = SourceReport::from_draft(&draft); + assert!(!report.is_valid()); + let from_draft = PhotonSource::from_draft(&draft).unwrap_err().to_string(); + let from_new = PhotonSource::new( + [1, 1, 1], + [0.0; 3], + [1.0; 3], + vec![0.0], + vec![0.0, 1.0], + 0.0, + vec![vec![1.0]], + ) + .unwrap_err() + .to_string(); + assert!(from_draft.contains("source-volume-not-positive")); + assert_eq!(from_draft, from_new); + } +} diff --git a/crates/tritium/AGENTS.md b/crates/tritium/AGENTS.md index 04e4c63..2b89f98 100644 --- a/crates/tritium/AGENTS.md +++ b/crates/tritium/AGENTS.md @@ -158,7 +158,11 @@ facade, the `TritiumBreakthrough` demo, and are probe-only; the Rust kernel retains molar SI inputs. Validation pins, thresholds and reproduction commands live in `validation/README.md`. The probe prefers an installed rebuilt release wheel; a checkout extension - is a fallback only when no package is installed. + is a fallback only when no package is installed. F6 adds the single-layer + McNabb-Foster trap plus that recombination outlet: explicit atomic/molar + conversion, a two-identical-reactant surface check, mobile/trapped + inventories, bracketed sampling and independent space/time refinement with + a mobile-plus-trapped mass balance. ## Verification diff --git a/docs/README.md b/docs/README.md index 08e2b29..77478a3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -46,7 +46,7 @@ need. Fusion sources · Spectrum unfolding Damage metrics (dpa/appm) · Clearance screening TBR/blanket bookkeeping - R2S workflows and volume-aware source splitting + R2S, flux normalization, and photon-source export @@ -103,6 +103,7 @@ status, and license. | [Clearance screening](tutorials/python/clearance-screening.md) | Classify parsed activation inventories against EU or Spanish clearance tables | | [Fusion first wall](tutorials/python/fusion-first-wall.md) | Run the end-to-end first-wall workflow from tokamak source to a foil check | | [Solve activation with ACTINV](tutorials/python/solve-with-actinv.md) | Map one material, spectrum, and schedule to an `actinv-spec-1` problem, solve with the optional ACTINV solver, and read the photon source back with Nucleide | +| [Activation to transport](tutorials/python/activation-to-transport.md) | Normalize OpenMC tallies into physical flux, build/validate an explicit photon source, export cooling-time batches, and verify a manifest | | [Interactive tutorials](tutorials/interactive/index.mdx) | Run Nucleide in the browser through the WASM build | | [Interactive — nuclides](tutorials/interactive/nuclides.mdx) | Nuclide identifiers and nuclear data | | [Interactive — materials](tutorials/interactive/materials.mdx) | Formulas, fractions, mixing, and XML export | @@ -118,6 +119,7 @@ status, and license. | [Interactive — code-card emission](tutorials/interactive/emitter.mdx) | Five-dialect card emission with a per-dialect mass-drift audit | | [Interactive — fusion sources](tutorials/interactive/fusion-sources.mdx) | Sample D-D/D-T ring, lattice, and parametric sources (mixtures, single-fuel species pairs), emit SDEF cards, and check ECRH access | | [Interactive — activation](tutorials/interactive/activation.mdx) | Activation file readers, spectral regrouping, and R2S source splitting by volume | +| [Interactive — photon source handoff](tutorials/interactive/transport-source.mdx) | Validate integrated voxel spectra, inspect joint sampling probabilities, and select exact cooling offsets | | [Interactive — clearance screening](tutorials/interactive/clearance.mdx) | Sum-of-fractions classification against EU or Spanish limits, plus the S3–S7 radiological totals | | [Interactive — damage metrics](tutorials/interactive/damage.mdx) | Fold a multigroup flux into dpa and gas production, propagate He/dpa ratio uncertainty, plus coil fast-flux and lifetime | | [Interactive — spectroscopy](tutorials/interactive/spectroscopy.mdx) | Spectrum smoothing and peak counting | diff --git a/docs/architecture/crate-responsibilities.md b/docs/architecture/crate-responsibilities.md index 659c27c..c9228d4 100644 --- a/docs/architecture/crate-responsibilities.md +++ b/docs/architecture/crate-responsibilities.md @@ -213,8 +213,13 @@ workspace crates; burnup driving stays inside ORIGEN. Scoped rigorous two-step (R2S) workflow builder: zone-to-flux linking from ALARA decks, schedule expansion, uniform-split photon-source assembly, count- or volume-weighted splitting of integrated zone strengths into voxel tags, -WATTS-class sweep expansion (`expand_sweep`), and facility-flow accounting -(`snapshot_inventory`) for differencing facility snapshots. Also owns the +an explicit regular-mesh photon-source contract (`source.rs`: integrated +photons/s per voxel and group, ascending eV edges, explicit sparse-group +mapping, density conversion, joint voxel/group probabilities, bounded +structured reports and exact cooling-offset selection), raw Monte Carlo flux +normalization with declared input states, WATTS-class sweep expansion +(`expand_sweep`), and facility-flow accounting (`snapshot_inventory`) for +differencing facility snapshots. Also owns the versionless ARMI DB-snapshot → deck adapter (`snapshot.rs`): dict-in only, no HDF5, no ARMI layout versioning, opaque zone ids, volumes-method decks with per-zone mixtures carrying atoms/barn-cm number diff --git a/docs/plan/roadmap.md b/docs/plan/roadmap.md index c557fb8..9859426 100644 --- a/docs/plan/roadmap.md +++ b/docs/plan/roadmap.md @@ -14,6 +14,11 @@ clippy, workspace tests, maturin build, pytest, ruff, mypy) run on every PR. ## Recently landed +- Activation-to-transport handoff: explicit OpenMC tally normalization with + declaration-checked raw states and v2 CSV metadata, a regular-mesh photon + source contract with joint voxel/group probabilities, sparse group + restoration, structured validation reports, exact cooling-time batches, + reproducibility manifests and an optional OpenMC `MeshSource` adapter. - Canonical `nucid` representation and cross-code naming dialects (`nuclei`). - Material compositions, compendium loading, and XML export (`material`). - MCNP-family readers for xsdir, meshtal, SSW, PTRAC, WWINP, and MCTAL diff --git a/docs/reference/python-api.mdx b/docs/reference/python-api.mdx index 67dfc5e..1f38fa6 100644 --- a/docs/reference/python-api.mdx +++ b/docs/reference/python-api.mdx @@ -208,9 +208,9 @@ Backing crate: [`nucleide-nuclei`](../architecture/crate-responsibilities.md#nuc - `geant4() -> str | None` - [`from_zaid(zaid: int) -> Nuclide`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L437) -- [`armi_to_nucid(name: str) -> Nuclide`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1072) -- [`nucid_to_armi(nuclide: Nuclide) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1073) -- [`mcc3_to_nucid(name: str) -> Nuclide`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1074) +- [`armi_to_nucid(name: str) -> Nuclide`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1134) +- [`nucid_to_armi(nuclide: Nuclide) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1135) +- [`mcc3_to_nucid(name: str) -> Nuclide`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1136) - [`normalize_nuclide(name: str) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L496) - [`atomic_mass(key: int | str) -> float | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L438) - [`natural_abundance(key: int | str) -> float | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L439) @@ -277,7 +277,7 @@ Backing crate: pure Python · [source file](https://github.com/nukehub-dev/nucle - `names() -> list[str]` - `get(name: str, as_material: bool = False) -> dict[str, Any] | None` -- [`Cusum`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1098) +- [`Cusum`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1160) — One-sided upper Page CUSUM change detector with Welford statistics. - `__init__(ref_shift_k: float = 0.5, alarm_h: float = 4.0, startup: int = 10) -> None` - `update(x: float) -> bool` @@ -294,10 +294,10 @@ Backing crate: pure Python · [source file](https://github.com/nukehub-dev/nucle - [`decay_heat(comp: dict[str, float]) -> float`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L497) - [`dose_per_g(comp: dict[str, float], pathway: str, source: str = 'EPA') -> float`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L499) - [`to_xml(comp: dict[str, float], name: str, density: float, units: str = 'g/cm3') -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L514) -- [`check_labels(comp: dict[str, float], widths: list[int] | None = None) -> list[dict[str, Any]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1075) -- [`audit_material(comp: dict[str, float]) -> list[dict[str, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1078) -- [`separate_material(comp: dict[str, float], effs: dict[str, float]) -> tuple[dict[str, float], dict[str, float]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1079) -- [`blend_material(parts: list[tuple[dict[str, float], float]]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1082) +- [`check_labels(comp: dict[str, float], widths: list[int] | None = None) -> list[dict[str, Any]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1137) +- [`audit_material(comp: dict[str, float]) -> list[dict[str, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1140) +- [`separate_material(comp: dict[str, float], effs: dict[str, float]) -> tuple[dict[str, float], dict[str, float]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1141) +- [`blend_material(parts: list[tuple[dict[str, float], float]]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1144) - [`mix_by_mass(parts: list[tuple[dict[str, float], float]]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L503) - [`mix_by_volume(parts: list[tuple[dict[str, float], float, float]]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L504) - [`specific_activity(comp: dict[str, float]) -> float`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L505) @@ -443,7 +443,7 @@ Backing crate: [`nucleide-mcnp-io`](../architecture/crate-responsibilities.md#nu get_rx(nuc: int | str, p_in: int, rdesc: int, rprop: int, x1: int | None = None, p_out: int | None = None) -> list[list[float]] ``` -- [`DeckProblem`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L661) +- [`DeckProblem`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L723) — Parsed MCNP input deck with format-preserving write-back. - `loads(text: str) -> DeckProblem` - `message: str` (property) @@ -483,17 +483,17 @@ Backing crate: [`nucleide-mcnp-io`](../architecture/crate-responsibilities.md#nu - [`combine_ssw_files(output: str, inputs: list[str]) -> None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L436) - [`ssw_combine_main(argv: Sequence[str] | None = None) -> None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/mcnp.py#L225) - [`read_inp(path: str) -> list[dict[str, Any]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L511) -- [`parse_deck(text: str) -> DeckProblem`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L733) -- [`read_deck(path: str) -> DeckProblem`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L734) -- [`parse_sdef(text: str) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L735) -- [`parse_csg_to_openmc(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L736) -- [`read_csg_to_openmc(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L737) -- [`parse_csg_to_serpent(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L738) -- [`read_csg_to_serpent(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L739) -- [`parse_csg_to_phits(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L740) -- [`read_csg_to_phits(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L741) -- [`parse_csg_to_gdml(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L742) -- [`read_csg_to_gdml(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L743) +- [`parse_deck(text: str) -> DeckProblem`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L795) +- [`read_deck(path: str) -> DeckProblem`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L796) +- [`parse_sdef(text: str) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L797) +- [`parse_csg_to_openmc(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L798) +- [`read_csg_to_openmc(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L799) +- [`parse_csg_to_serpent(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L800) +- [`read_csg_to_serpent(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L801) +- [`parse_csg_to_phits(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L802) +- [`read_csg_to_phits(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L803) +- [`parse_csg_to_gdml(text: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L804) +- [`read_csg_to_gdml(path: str) -> tuple[str, list[dict[str, str]]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L805) - [`mesh_to_geom`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L544): @@ -554,8 +554,8 @@ Backing crate: [`nucleide-mcpl-io`](../architecture/crate-responsibilities.md#nu mcpl2ssw(mcpl_path: str, reference_ssw_path: str, ssw_out_path: str, surface: int | None = None, force_cs_to_one: bool = False, niss: int | None = None, allow_polarisation: bool = False) -> int ``` -- [`mcpl_statsum_validate(comment: str) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1094) -- [`mcpl_statsum_comment(key: str, value: float) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1095) +- [`mcpl_statsum_validate(comment: str) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1156) +- [`mcpl_statsum_comment(key: str, value: float) -> str`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1157) {/*GEN:module-mcpl:END*/} @@ -731,7 +731,7 @@ Backing crate: [`nucleide-depletion`](../architecture/crate-responsibilities.md# - `solve(n0: dict[str, float], dt: float, order: int = 48, method: str = 'cram48') -> dict[str, float]` - `solve_vec(n0: list[float], dt: float, order: int = 48, method: str = 'cram48') -> list[float]` -- [`Inventory`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L706) +- [`Inventory`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L768) — Unit-aware decay inventory over a depletion chain. - `__init__(chain: Chain, comp: dict[str, float], units: str = 'atoms') -> None` - `numbers() -> dict[str, float]` @@ -771,16 +771,16 @@ Backing crate: [`nucleide-depletion`](../architecture/crate-responsibilities.md# deplete_series(chain: Chain, n0: dict[str, float], dts: list[float], rates: dict[str, float] | None = None, rates_list: list[dict[str, float] | None] | None = None, integrator: str = 'predictor', order: int = 48, method: str = 'cram48') -> dict[str, Any] ``` -- [`cumulative_decays`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L744): +- [`cumulative_decays`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L806): ```python cumulative_decays(chain: Chain, n0: dict[str, float], dt: float, rates: dict[str, float] | None = None) -> dict[str, float] ``` -- [`progeny(chain: Chain, name: str) -> list[tuple[str, float, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1068) -- [`branching_fraction(chain: Chain, parent: str, child: str) -> float | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1069) -- [`decay_mode(chain: Chain, parent: str, child: str) -> str | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1070) -- [`chain_edges(chain: Chain) -> list[tuple[str, str, float, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1071) +- [`progeny(chain: Chain, name: str) -> list[tuple[str, float, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1130) +- [`branching_fraction(chain: Chain, parent: str, child: str) -> float | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1131) +- [`decay_mode(chain: Chain, parent: str, child: str) -> str | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1132) +- [`chain_edges(chain: Chain) -> list[tuple[str, str, float, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1133) {/*GEN:module-depletion:END*/} @@ -1200,18 +1200,18 @@ Backing crate: [`nucleide-r2s`](../architecture/crate-responsibilities.md#nuclei - [`r2s_photon_group_sums(photon_text: str, nuclides: list[str], time_s: float) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L654) - [`r2s_snapshot_inventory(snapshot: dict[str, Any]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L657) - [`r2s_expand_sweep(axes: list[dict[str, Any]]) -> list[dict[str, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L658) -- [`from_deck(deck_text: str) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L35) +- [`from_deck(deck_text: str) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L59) (alias of `r2s_from_deck`) -- [`from_snapshot(snapshot: dict[str, Any]) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L36) +- [`from_snapshot(snapshot: dict[str, Any]) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L60) (alias of `r2s_from_snapshot`) -- [`validate(workflow: dict[str, Any], deck_text: str) -> None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L37) +- [`validate(workflow: dict[str, Any], deck_text: str) -> None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L61) (alias of `r2s_validate`) -- [`expand(deck_text: str, top: str | None = None) -> list[dict[str, Any]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L38) +- [`expand(deck_text: str, top: str | None = None) -> list[dict[str, Any]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L62) (alias of `r2s_expand`) -- [`assemble(output_text: str, run_lbl: str, zone: str, groups: int) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L39) +- [`assemble(output_text: str, run_lbl: str, zone: str, groups: int) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L63) (alias of `r2s_assemble`) -- [`tag_zone_strength`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L40): +- [`tag_zone_strength`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L64): ```python tag_zone_strength(totals: list[float], zone_of_voxel: list[int], split: bool = False, *, voxel_volumes_cm3: list[float] | None = None) -> dict[str, Any] @@ -1219,7 +1219,7 @@ Backing crate: [`nucleide-r2s`](../architecture/crate-responsibilities.md#nuclei (alias of `r2s_tag_zone_strength`) -- [`photon_group_sums`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L41): +- [`photon_group_sums`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L65): ```python photon_group_sums(photon_text: str, nuclides: list[str], time_s: float) -> dict[str, Any] @@ -1227,11 +1227,29 @@ Backing crate: [`nucleide-r2s`](../architecture/crate-responsibilities.md#nuclei (alias of `r2s_photon_group_sums`) -- [`snapshot_inventory(snapshot: dict[str, Any]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L42) +- [`snapshot_inventory(snapshot: dict[str, Any]) -> dict[str, float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L66) (alias of `r2s_snapshot_inventory`) -- [`expand_sweep(axes: list[dict[str, Any]]) -> list[dict[str, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L43) +- [`expand_sweep(axes: list[dict[str, Any]]) -> list[dict[str, str]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L67) (alias of `r2s_expand_sweep`) +- [`photon_source`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L70): + + ```python + photon_source(mesh_shape: Sequence[int], lower_left_cm: Sequence[float], upper_right_cm: Sequence[float], voxel_volumes_cm3: Sequence[float], edges_ev: Sequence[float], cooling_s: float, strengths_photons_per_s: Sequence[Sequence[float]]) -> dict[str, Any] + ``` + +- [`photon_source_exported`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L102): + + ```python + photon_source_exported(mesh_shape: Sequence[int], lower_left_cm: Sequence[float], upper_right_cm: Sequence[float], voxel_volumes_cm3: Sequence[float], full_edges_ev: Sequence[float], cooling_s: float, exported_group_indices: Sequence[int], exported_strengths_photons_per_s: Sequence[Sequence[float]]) -> dict[str, Any] + ``` + +- [`source_report(source: dict[str, Any]) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L131) +- [`source_probabilities(source: dict[str, Any]) -> list[list[float]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L142) +- [`source_energy_probabilities(source: dict[str, Any]) -> list[list[float]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L147) +- [`source_density(source: dict[str, Any]) -> list[list[float]]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L152) +- [`select_cooling(available_s: Sequence[float], requested_s: Sequence[float]) -> list[int]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/r2s.py#L157) + {/*GEN:module-r2s:END*/} ## `nucleide.emit` @@ -1240,25 +1258,25 @@ Backing crate: [`nucleide-r2s`](../architecture/crate-responsibilities.md#nuclei Backing crate: [`nucleide-emit`](../architecture/crate-responsibilities.md#nucleide-emit) · [source dir](https://github.com/nukehub-dev/nucleide/tree/main/crates/emit) -- [`emit_armi_cards`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1132): +- [`emit_armi_cards`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1194): ```python emit_armi_cards(comp: dict[str, float], name: str, density: float | None = None, mcnp_number: int = 1, xs_suffix: str = '80c', serpent_lib: str = '03c', fluka_fid: int = 1, partisn_zone: int = 1) -> dict[str, str] ``` -- [`emit_armi_drift_table`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1142): +- [`emit_armi_drift_table`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1204): ```python emit_armi_drift_table(comp: dict[str, float], name: str, density: float | None = None, mcnp_number: int = 1, xs_suffix: str = '80c', serpent_lib: str = '03c', fluka_fid: int = 1, partisn_zone: int = 1) -> list[dict[str, Any]] ``` -- [`emit_cards`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1112): +- [`emit_cards`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1174): ```python emit_cards(comp: dict[str, float], name: str, density: float | None = None, mcnp_number: int = 1, xs_suffix: str = '80c', serpent_lib: str = '03c', fluka_fid: int = 1, partisn_zone: int = 1) -> dict[str, str] ``` -- [`emit_drift_table`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1122): +- [`emit_drift_table`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/_internal.pyi#L1184): ```python emit_drift_table(comp: dict[str, float], name: str, density: float | None = None, mcnp_number: int = 1, xs_suffix: str = '80c', serpent_lib: str = '03c', fluka_fid: int = 1, partisn_zone: int = 1) -> list[dict[str, Any]] @@ -1325,13 +1343,43 @@ OpenMC reads the statepoint, Nucleide takes plain arrays. Backing crate: pure Python · [source file](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/data.py) -- [`openmc_version() -> str | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L80) -- [`tally_arrays(statepoint: Any, tally_id: int, score: str = 'flux') -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L106) -- [`read_statepoint(path: str | Path, tally_id: int, score: str = 'flux') -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L181) -- [`cell_flux(arrays: dict[str, Any]) -> list[float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L205) -- [`voxel_flux(arrays: dict[str, Any], voxel: int) -> list[float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L222) -- [`tally_to_csv(arrays: dict[str, Any], path: str | Path) -> None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L232) -- [`tally_from_csv(path: str | Path) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L316) +- [`openmc_version() -> str | None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L143) +- [`tally_arrays(statepoint: Any, tally_id: int, score: str = 'flux') -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L169) +- [`read_statepoint(path: str | Path, tally_id: int, score: str = 'flux') -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L250) +- [`cell_flux(arrays: dict[str, Any]) -> list[float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L274) +- [`voxel_flux(arrays: dict[str, Any], voxel: int) -> list[float]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L291) +- [`tally_to_csv(arrays: dict[str, Any], path: str | Path) -> None`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L301) +- [`tally_from_csv(path: str | Path) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L396) + +- [`normalize_flux`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L532): + + ```python + normalize_flux(arrays: dict[str, Any], source_rate_s: float, volumes_cm3: Sequence[float], *, input_normalization: str | None = None) -> dict[str, Any] + ``` + +- [`source_manifest`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L755): + + ```python + source_manifest(*, source: dict[str, Any], input_files: Iterable[str | Path] = (), output_files: Iterable[str | Path] = (), external_solver: str | None = None, external_version: str | None = None, adapter: str = 'openmc-mesh-source', adapter_version: str = '1', evaluated_library: str | None = None, validation: dict[str, Any] | None = None) -> dict[str, Any] + ``` + +- [`write_manifest(manifest: dict[str, Any], path: str | Path) -> Path`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L825) +- [`read_manifest(path: str | Path) -> dict[str, Any]`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L844) + +- [`verify_manifest`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L864): + + ```python + verify_manifest(manifest_or_path: dict[str, Any] | str | Path, *, base_dir: str | Path | None = None) -> dict[str, Any] + ``` + +- [`export_cooling_batch`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L937): + + ```python + export_cooling_batch(sources: Sequence[dict[str, Any]], requested_times_s: Sequence[float], out_dir: str | Path, *, writer: Callable[[dict[str, Any], Path], None] | None = None, overwrite: bool = False, skip_zero: bool = False) -> dict[str, Any] + ``` + +- [`mesh_source(source: dict[str, Any]) -> Any`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L639) +- [`write_mesh_source_xml(source: dict[str, Any], path: str | Path) -> Path`](https://github.com/nukehub-dev/nucleide/blob/main/python/nucleide/openmc.py#L736) {/*GEN:module-openmc:END*/} diff --git a/docs/theory/tritium.mdx b/docs/theory/tritium.mdx index dd964b4..567ba09 100644 --- a/docs/theory/tritium.mdx +++ b/docs/theory/tritium.mdx @@ -567,8 +567,11 @@ flux is still `≈2.3e-3 J_ss` at `t = 31.6 s` and reaches `0.9999 J_ss` by `fixtures/tritium/`), following the kinetics oracle pattern. - **Probe-only external oracle**: `validation/tritium_vs_festim.py` compares the kernel against FESTIM 2.1 (Apache-2.0, black-box v2.x API) on - trap-free, one-trap, Sieverts, and two-layer legs, with the always-run - V1/M1 analytic legs gating the Nucleide side. The probe needs DOLFINx, so + trap-free, one-trap, Sieverts, two-layer, trap-free recombination (F5) and + one-trap-plus-recombination (F6) legs, with the always-run V1/M1 analytic + legs gating the Nucleide side. F5/F6 add explicit molar/atomic conversion, + independent space/time refinement, mobile and trapped inventories and an + exported-history mobile-plus-trapped mass balance. The probe needs DOLFINx, so it runs only in the separate `dolfinx/dolfinx:stable` image; outside that image the cross-code legs SKIP loudly with their reason. FESTIM/FEniCS never enter the main validation container or the Rust workspace, and diff --git a/docs/tutorials/interactive/blanket.mdx b/docs/tutorials/interactive/blanket.mdx index 7fdc703..d6accb2 100644 --- a/docs/tutorials/interactive/blanket.mdx +++ b/docs/tutorials/interactive/blanket.mdx @@ -2,7 +2,7 @@ title: TBR bookkeeping description: Turn caller tritium tallies into raw and effective TBR, the breeding margin, and daily burn and surplus numbers. sidebar: - order: 22 + order: 23 --- A breeding blanket must make at least as much tritium as the plasma burns. diff --git a/docs/tutorials/interactive/clearance.mdx b/docs/tutorials/interactive/clearance.mdx index b5659fa..72afd6b 100644 --- a/docs/tutorials/interactive/clearance.mdx +++ b/docs/tutorials/interactive/clearance.mdx @@ -2,7 +2,7 @@ title: Clearance screening description: Screen a nuclide inventory against the EU 2013/59/Euratom Annex VII Table A clearance levels with the sum-of-fractions rule. sidebar: - order: 15 + order: 16 --- Material leaving a regulated radiation area can be cleared for reuse or diff --git a/docs/tutorials/interactive/damage.mdx b/docs/tutorials/interactive/damage.mdx index b436e9a..ebbad56 100644 --- a/docs/tutorials/interactive/damage.mdx +++ b/docs/tutorials/interactive/damage.mdx @@ -2,7 +2,7 @@ title: Damage metrics description: Fold a three-group flux with damage and gas response cross sections and read NRT-dpa, arc-dpa, helium production, and the He/dpa ratio. sidebar: - order: 16 + order: 17 --- Neutron bombardment displaces atoms from their lattice sites and transmutes diff --git a/docs/tutorials/interactive/equilibrium.mdx b/docs/tutorials/interactive/equilibrium.mdx index 83cedbd..7e3d54e 100644 --- a/docs/tutorials/interactive/equilibrium.mdx +++ b/docs/tutorials/interactive/equilibrium.mdx @@ -2,7 +2,7 @@ title: Equilibrium data description: Parse a VMEC INDATA namelist and map a birth-rate field onto the wall in flux coordinates. sidebar: - order: 23 + order: 24 --- Stellarator and tokamak equilibria arrive as data files, never as something diff --git a/docs/tutorials/interactive/index.mdx b/docs/tutorials/interactive/index.mdx index 84599bc..adc13ef 100644 --- a/docs/tutorials/interactive/index.mdx +++ b/docs/tutorials/interactive/index.mdx @@ -44,6 +44,9 @@ required; every example is live. ### Activation and radiological analysis - [Activation](activation.mdx) — activation file readers, spectral regrouping, and R2S source splitting by volume. +- [Photon source handoff](transport-source.mdx) — validate integrated voxel + spectra, inspect joint sampling probabilities, and select exact cooling + offsets. - [Clearance screening](clearance.mdx) — sum-of-fractions classification against EU or Spanish limits. - [Radiological totals](clearance.mdx#radiological-totals-s3s7) — committed hazards, transport ratio, IAEA clearance, and gamma dose over caller inventories. diff --git a/docs/tutorials/interactive/kinetics.mdx b/docs/tutorials/interactive/kinetics.mdx index 180d5df..80af0d9 100644 --- a/docs/tutorials/interactive/kinetics.mdx +++ b/docs/tutorials/interactive/kinetics.mdx @@ -2,7 +2,7 @@ title: Point kinetics description: Solve a step-reactivity point-kinetics transient and read the prompt-jump estimate. sidebar: - order: 20 + order: 21 --- Prescribed-reactivity point kinetics tracks the neutron population $n(t)$ diff --git a/docs/tutorials/interactive/spectroscopy.mdx b/docs/tutorials/interactive/spectroscopy.mdx index 39856d5..5591598 100644 --- a/docs/tutorials/interactive/spectroscopy.mdx +++ b/docs/tutorials/interactive/spectroscopy.mdx @@ -2,7 +2,7 @@ title: Gamma-ray spectroscopy description: Smooth a spectrum and count gross, background, and net peak counts. sidebar: - order: 17 + order: 18 --- Gamma-ray pulse-height spectra arrive as counts per channel. Answering diff --git a/docs/tutorials/interactive/transport-source.mdx b/docs/tutorials/interactive/transport-source.mdx new file mode 100644 index 0000000..8847c9f --- /dev/null +++ b/docs/tutorials/interactive/transport-source.mdx @@ -0,0 +1,47 @@ +--- +title: Photon source handoff +description: Validate an integrated photon source, inspect joint voxel/group probabilities, and select exact cooling offsets. +sidebar: + order: 15 +--- + +The activation-to-transport handoff keeps three things separate: the raw +Monte Carlo tally, the physical group flux, and the integrated photon source a +transport code samples. This demo exercises the shared Rust source contract — +the same validator, density conversion and joint-probability kernel the Python +package uses. + +## Voxel spectra and units + +The mesh is a regular `(2, 1, 1)` grid with caller voxel volumes `1` and `1` cm³. +The table shows **integrated photons/s** per group, not a density and not a +probability. Change a value and select **Evaluate source**; the shared +validator reports stable issue codes and keeps modelling assumptions separate +from errors. + +Negative values, non-finite cells, a zero total, irregular edges and +mismatched dimensions raise clear errors. A zero-source voxel inside a nonzero source is +valid data and remains unsampleable; an all-zero source is valid data but has +no sampling distribution. + +## Joint voxel/group sampling + +The probability table is the joint distribution over voxel/group pairs. It is +not the product of a spatial marginal and an energy marginal: independent +sampling would invent cross-pairs that carry no source. The declared +assumptions are uniform photon density per eV inside each group and uniform +position inside each voxel. + +## Cooling times + +The three buttons are **declared snapshots** at 0 s, 3600 s and 7200 s; the +browser does not compute decay physics. The cooling-selection check calls the +shared exact-match kernel. Requested offsets must match an available offset +exactly, duplicates are rejected, and a near match is not substituted. + +Python adds the transport-facing pieces: OpenMC `MeshSource` export, batch +files, and reproducibility manifests. See +[Activation to transport](../python/activation-to-transport.md) for the full +workflow. + + diff --git a/docs/tutorials/interactive/tritium.mdx b/docs/tutorials/interactive/tritium.mdx index bb6d400..5f67e21 100644 --- a/docs/tutorials/interactive/tritium.mdx +++ b/docs/tutorials/interactive/tritium.mdx @@ -2,7 +2,7 @@ title: Tritium permeation description: Solve a 1D permeation transient and read the breakthrough curve and time lag. sidebar: - order: 21 + order: 22 --- A 1D slab $0 \le x \le L$ holds mobile tritium $c_m(x, t)$ with Fickian diff --git a/docs/tutorials/interactive/unfold.mdx b/docs/tutorials/interactive/unfold.mdx index fb115f4..12a3038 100644 --- a/docs/tutorials/interactive/unfold.mdx +++ b/docs/tutorials/interactive/unfold.mdx @@ -2,7 +2,7 @@ title: Spectrum unfolding description: Adjust a guess neutron spectrum against measured foil-activation rates with the SAND-II iteration and compare guess vs unfolded. sidebar: - order: 18 + order: 19 --- Foil-activation spectrometry measures a handful of reaction rates — each diff --git a/docs/tutorials/interactive/uq.mdx b/docs/tutorials/interactive/uq.mdx index 0a83916..acb843e 100644 --- a/docs/tutorials/interactive/uq.mdx +++ b/docs/tutorials/interactive/uq.mdx @@ -2,7 +2,7 @@ title: UQ sampling description: Draw seeded multivariate-normal samples over a caller-supplied covariance block and compare sample moments. sidebar: - order: 19 + order: 20 --- Seeded MVN sampling in the SANDY role starts from a covariance block: given a diff --git a/docs/tutorials/python/activation-to-transport.md b/docs/tutorials/python/activation-to-transport.md new file mode 100644 index 0000000..48b56d9 --- /dev/null +++ b/docs/tutorials/python/activation-to-transport.md @@ -0,0 +1,269 @@ +--- +title: Activation to transport +sidebar: + order: 24 +--- + +This tutorial connects three things that are easy to mix up: a raw OpenMC +tally, a physical group flux, and an activation-derived photon source that a +transport code can sample. Nucleide keeps the raw data, the physical +conversion and the source contract separate so a downstream fold cannot +silently use the wrong units. + +The example is synthetic. No activation solve, transport run or evaluated +data is required. + +## 1. Declare the raw tally normalization + +OpenMC's default track-length `flux` tally is volume-integrated. In a +fixed-source run it is normalized by the simulated particle count **and** +scaled by the sum of the configured source strengths. With the default source +strength (`1.0`, or normalized selection weights), the result is per source +particle; with source strengths written as absolute particles/s or photons/s, +the source rate is already inside the tally. A random-ray tally run with +`settings.random_ray["volume_normalized_flux_tallies"] = True` is +volume-averaged instead. The statepoint bridge cannot infer which combination +a caller produced, so it records `normalization = "unknown"` and the +conversion asks for a declaration. + +```python +import json +import tempfile +from pathlib import Path + +import nucleide.openmc as omc +import nucleide.r2s as r2s + +raw = { + "tally_id": 7, + "score": "flux", + "kind": "cell", + "n_voxels": 1, + "n_groups": 2, + "energy_bounds_mev": [0.0, 1.0, 2.0], + "flux": [[4.0, 9.0]], + "rel_err": [[0.05, 0.10]], + "mesh_shape": None, + "mesh_bounds": None, + "openmc_version": "0.16.0", + "normalization": "unknown", + "units": "unknown", +} + +physical = omc.normalize_flux( + raw, + source_rate_s=10.0, + volumes_cm3=[2.0], + input_normalization="per-source-volume-integrated", +) +assert physical["flux"] == [[20.0, 45.0]] +assert physical["units"] == "1/(cm2 s)" +assert raw["flux"] == [[4.0, 9.0]] +``` + +The arithmetic is `raw × source_rate / volume` for per-source +volume-integrated input. Volume-averaged input applies only `source_rate`. +When OpenMC already applied the total source strength, declare +`rate-scaled-volume-integrated` (divide by volume only) or +`rate-scaled-volume-averaged` (no arithmetic); multiplying those by the rate +again would double-count it. Physical input is rejected rather than scaled +twice. Relative errors are unchanged, and source-rate or volume uncertainty is +not folded in. + +```python +rate_scaled = omc.normalize_flux( + raw, + source_rate_s=10.0, + volumes_cm3=[2.0], + input_normalization="rate-scaled-volume-integrated", +) +assert rate_scaled["flux"] == [[2.0, 4.5]] +``` + +A cell tally uses one volume. For a mesh tally, pass one positive volume per +voxel in the bridge's C-order (x slowest, then y, then z). + +## 2. Keep the metadata through a CSV roundtrip + +Legacy `nucleide-openmc-tally-v1` files carry no normalization state and read +back as `unknown`; they are never relabelled as physical flux by default. New +files use v2 and retain the normalization, units and optional source rate. + +```python +with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "flux.csv" + omc.tally_to_csv(physical, path) + readback = omc.tally_from_csv(path) +assert readback["normalization"] == "physical" +assert readback["source_rate_s"] == 10.0 +assert readback["flux"] == [[20.0, 45.0]] +``` + +## 3. Build an explicit photon source + +The R2S source contract takes a regular mesh, ascending eV group edges, one +cooling time and **integrated** photons/s per voxel and group. The mesh shape +`(2, 1, 1)` below means two voxels in x; each voxel has its own spectrum. + +```python +source = r2s.photon_source( + mesh_shape=[2, 1, 1], + lower_left_cm=[0.0, 0.0, 0.0], + upper_right_cm=[2.0, 1.0, 1.0], + voxel_volumes_cm3=[1.0, 1.0], + edges_ev=[0.0, 1.0e6, 2.0e6, 5.0e6], + cooling_s=0.0, + strengths_photons_per_s=[[100.0, 0.0, 20.0], [0.0, 300.0, 0.0]], +) + +assert source["total_photons_per_s"] == 420.0 +assert source["voxel_totals_photons_per_s"] == [120.0, 300.0] +assert r2s.source_density(source) == [[100.0, 0.0, 20.0], [0.0, 300.0, 0.0]] +``` + +A density applies each voxel volume exactly once. Do not multiply an +integrated source by volume again when handing it to a transport code. The +exportable example uses uniform 1 cm³ regular-mesh cells; the contract also +accepts caller volumes for density conversion, but OpenMC export requires them +to match the regular-mesh cell volume. + +The joint voxel/group probabilities are derived from the same strengths, not +from independent spatial and energy marginals: + +```python +probabilities = r2s.source_probabilities(source) +assert probabilities == [[100.0 / 420.0, 0.0, 20.0 / 420.0], [0.0, 300.0 / 420.0, 0.0]] +``` + +## 4. Inspect validation and assumptions + +The report uses stable issue codes and deterministic ordering. Assumptions +are labelled separately from errors, and invalid data never gets repaired. + +```python +report = r2s.source_report(source) +assert report["valid"] is True +codes = [issue["code"] for issue in report["issues"]] +assert "source-assumption-uniform-within-bin" in codes +assert "source-assumption-uniform-within-voxel" in codes +``` + +The two modelling assumptions are deliberate: photons are uniform in energy +density inside each group (per eV) and uniform in position inside each voxel. +They conserve group and voxel strengths; they do not reconstruct unresolved +emission lines or sub-voxel structure. A zero-source voxel is valid inside a +nonzero source; an all-zero distribution is valid data but cannot be sampled +as a probability distribution. + +## 5. Restore omitted groups explicitly + +Activation exports sometimes drop zero groups. Pass the original full grid and +the dense indices of the exported columns; omitted groups become exactly zero. +Centroids are never interpreted as bin edges. + +```python +restored = r2s.photon_source_exported( + mesh_shape=[1, 1, 1], + lower_left_cm=[0.0, 0.0, 0.0], + upper_right_cm=[1.0, 1.0, 1.0], + voxel_volumes_cm3=[1.0], + full_edges_ev=[0.0, 1.0e6, 2.0e6, 5.0e6], + cooling_s=0.0, + exported_group_indices=[1, 2], + exported_strengths_photons_per_s=[[5.0, 7.0]], +) +assert restored["strengths_photons_per_s"] == [[0.0, 5.0, 7.0]] +``` + +Duplicate, out-of-range or unsorted indices raise clear errors. + +## 6. Export a cooling-time batch and verify it + +Batch selection is exact. There is no interpolation, no nearest-time +substitution and no silent duplicate collapse. Distinct float spellings keep +close-but-distinct offsets in separate files. The batch manifest is written +only after every requested output succeeds. + +```python +def write_json_source(item: dict, path: Path) -> None: + path.write_text( + json.dumps( + { + "cooling_s": item["cooling_s"], + "total_photons_per_s": item["total_photons_per_s"], + } + ), + encoding="utf-8", + ) + +hour = r2s.photon_source( + mesh_shape=[2, 1, 1], + lower_left_cm=[0.0, 0.0, 0.0], + upper_right_cm=[2.0, 1.0, 1.0], + voxel_volumes_cm3=[1.0, 1.0], + edges_ev=[0.0, 1.0e6, 2.0e6, 5.0e6], + cooling_s=3600.0, + strengths_photons_per_s=[[7.0, 0.0, 1.0], [0.0, 13.0, 0.0]], +) + +with tempfile.TemporaryDirectory() as tmp: + batch = omc.export_cooling_batch( + [source, hour], + requested_times_s=[0.0, 3600.0], + out_dir=tmp, + writer=write_json_source, + ) + manifest = omc.read_manifest(Path(tmp) / "batch-manifest.json") + check = omc.verify_manifest(manifest, base_dir=tmp) + +assert batch["manifest"]["status"] == "complete" +assert [entry["time_s"] for entry in batch["outputs"]] == [0.0, 3600.0] +assert check["ok"] is True +``` + +A failed writer raises `nucleide.openmc.BatchExportError` with the partial +outputs attached; no complete manifest is claimed. Existing outputs are +refused unless `overwrite=True`. An all-zero time is an error unless +`skip_zero=True`, which records the skipped time in the manifest. The batch +manifest records its schema, requested offsets, units, voxel order, +assumptions, and each output's SHA-256, total photons/s, energy-grid hash and +validation summary; skipped entries are listed separately. + +`source_manifest` records the measured input/output hashes, the energy-grid +hash, voxel order, cooling offset and validation summary in a compact JSON +document that can be checked offline: + +```python +manifest = omc.source_manifest(source=source, input_files=[]) +assert manifest["source"]["voxel_order"] == "c-order-(i,j,k)" +assert len(manifest["source"]["energy_grid_sha256"]) == 64 +``` + +Caller-supplied evaluated-library identity is recorded as such, without an +invented hash. Timestamps and environment variables are deliberately absent +from the deterministic content. + +## 7. Optional OpenMC mesh source + +If caller-side OpenMC 0.16.0 is installed, the same source becomes a +`MeshSource` with one energy distribution per mesh element. The adapter maps +the C-order voxel list into OpenMC's structured-mesh order explicitly and +stores absolute photons/s as the element strengths. OpenMC then scales its own +tallies by that total strength, so a subsequent flux conversion declares a +`rate-scaled-*` input; do not multiply the same rate again. + + + +```python +if omc.openmc_version() is not None: + mesh_source = omc.mesh_source(source) + assert mesh_source.strength == 420.0 + with tempfile.TemporaryDirectory() as tmp: + omc.write_mesh_source_xml(source, Path(tmp) / "settings.xml") +``` + +OpenMC is optional and imported lazily. The generic tutorial above runs +without it. Exporting a source is not transport validation: source +conservation, XML/API compatibility and spatial-energy sampling are separate +claims from shutdown dose rate, which needs geometry, evaluated photon data, +a dose response and an independent reference. diff --git a/docs/tutorials/python/index.md b/docs/tutorials/python/index.md index 9ebfd1d..06f2ba0 100644 --- a/docs/tutorials/python/index.md +++ b/docs/tutorials/python/index.md @@ -60,6 +60,9 @@ and assumes you have already installed the project (see 23. [Solve activation with ACTINV](solve-with-actinv.md) — map one material, spectrum, and schedule to an `actinv-spec-1` problem, solve with the optional ACTINV solver, and read the photon source back with Nucleide. +24. [Activation to transport](activation-to-transport.md) — normalize OpenMC + tallies into physical flux, build and validate an explicit photon source, + export cooling-time batches, and verify a reproducibility manifest. ## End-to-end notebooks diff --git a/python/nucleide/_internal.pyi b/python/nucleide/_internal.pyi index 5a15d19..5d0557d 100644 --- a/python/nucleide/_internal.pyi +++ b/python/nucleide/_internal.pyi @@ -656,6 +656,68 @@ def r2s_photon_group_sums( ) -> dict[str, Any]: ... def r2s_snapshot_inventory(snapshot: dict[str, Any]) -> dict[str, float]: ... def r2s_expand_sweep(axes: list[dict[str, Any]]) -> list[dict[str, str]]: ... +def r2s_normalize_flux( + tally: list[list[float]], + source_rate_s: float, + volumes_cm3: list[float], + normalization: str, +) -> list[list[float]]: ... +def r2s_photon_source( + mesh_shape: list[int], + lower_left_cm: list[float], + upper_right_cm: list[float], + voxel_volumes_cm3: list[float], + edges_ev: list[float], + cooling_s: float, + strengths_photons_per_s: list[list[float]], +) -> dict[str, Any]: ... +def r2s_photon_source_exported( + mesh_shape: list[int], + lower_left_cm: list[float], + upper_right_cm: list[float], + voxel_volumes_cm3: list[float], + full_edges_ev: list[float], + cooling_s: float, + exported_group_indices: list[int], + exported_strengths_photons_per_s: list[list[float]], +) -> dict[str, Any]: ... +def r2s_source_report( + mesh_shape: list[int], + lower_left_cm: list[float], + upper_right_cm: list[float], + voxel_volumes_cm3: list[float], + edges_ev: list[float], + cooling_s: float, + strengths_photons_per_s: list[list[float]], +) -> dict[str, Any]: ... +def r2s_source_probabilities( + mesh_shape: list[int], + lower_left_cm: list[float], + upper_right_cm: list[float], + voxel_volumes_cm3: list[float], + edges_ev: list[float], + cooling_s: float, + strengths_photons_per_s: list[list[float]], +) -> list[list[float]]: ... +def r2s_source_energy_probabilities( + mesh_shape: list[int], + lower_left_cm: list[float], + upper_right_cm: list[float], + voxel_volumes_cm3: list[float], + edges_ev: list[float], + cooling_s: float, + strengths_photons_per_s: list[list[float]], +) -> list[list[float]]: ... +def r2s_source_density( + mesh_shape: list[int], + lower_left_cm: list[float], + upper_right_cm: list[float], + voxel_volumes_cm3: list[float], + edges_ev: list[float], + cooling_s: float, + strengths_photons_per_s: list[list[float]], +) -> list[list[float]]: ... +def r2s_select_cooling(available_s: list[float], requested_s: list[float]) -> list[int]: ... @final class DeckProblem: diff --git a/python/nucleide/openmc.py b/python/nucleide/openmc.py index 39f3638..d72feb0 100644 --- a/python/nucleide/openmc.py +++ b/python/nucleide/openmc.py @@ -32,6 +32,17 @@ machine with OpenMC can export and any machine can read back bit-identically — no OpenMC, no pandas, no HDF5 on the reading side. +Normalization and source handoff: raw extraction is intentionally not +relabelled as physical flux. OpenMC 0.16 fixed-source tallies are normalized +by the simulated particle count and scaled by the configured total source +strength, so a default unit-strength source is per source particle while an +absolute-rate source is already scaled. :func:`normalize_flux` requires the +caller to declare the volume state and rate state, and rejects double +scaling. :func:`mesh_source` builds an optional ``openmc.MeshSource`` from an +integrated photon-source dict, with explicit C-order/Fortran-order mapping +and per-element histogram densities; :func:`export_cooling_batch` and the +manifest helpers add deterministic files and offline hash verification. + Failure stance: a missing file, a missing OpenMC, a missing tally/score, a multi-nuclide tally, a multi-bin non-energy filter (caller slices with ``get_slice`` first), a second mesh/energy filter, or a non-regular mesh are @@ -53,9 +64,18 @@ from __future__ import annotations import csv +import hashlib import itertools +import json +import math +import os +import struct +import tempfile +from collections.abc import Callable, Iterable, Sequence from pathlib import Path -from typing import Any +from typing import Any, NamedTuple + +from nucleide import _internal as _core __all__ = [ "openmc_version", @@ -65,6 +85,14 @@ "voxel_flux", "tally_to_csv", "tally_from_csv", + "normalize_flux", + "source_manifest", + "write_manifest", + "read_manifest", + "verify_manifest", + "export_cooling_batch", + "mesh_source", + "write_mesh_source_xml", ] #: OpenMC release the export call sequence is pinned against (validation @@ -72,8 +100,43 @@ #: already carries ``get_reshaped_data(expand_dims=...)``). VERSION_CONTRACT = "0.16.0" +#: Input normalization states for :func:`normalize_flux`. OpenMC's default +#: track-length ``flux`` tally is volume-integrated per source particle; a +#: random-ray tally run with ``volume_normalized_flux_tallies`` is +#: volume-averaged per source particle. The bridge cannot infer which one a +#: caller produced, so conversion requires an explicit declaration. +NORMALIZATION_UNKNOWN = "unknown" +NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE = "per-source-volume-integrated" +NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED = "rate-scaled-volume-integrated" +NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE = "per-source-volume-averaged" +NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED = "rate-scaled-volume-averaged" +NORMALIZATION_PHYSICAL = "physical" + +UNITS_VOLUME_INTEGRATED_PER_SOURCE = "cm per source particle" +UNITS_VOLUME_INTEGRATED_RATE_SCALED = "cm/s (source-rate scaled)" +UNITS_VOLUME_AVERAGED_PER_SOURCE = "1/(cm2 source-particle)" +UNITS_VOLUME_AVERAGED_RATE_SCALED = "1/(cm2 s) (source-rate scaled)" +UNITS_PHYSICAL = "1/(cm2 s)" + +_MANIFEST_SCHEMA = "nucleide-source-manifest-v1" +_BATCH_SCHEMA = "nucleide-source-batch-v1" +_VOXEL_ORDER = "c-order-(i,j,k)" +_ASSUMPTIONS = [ + "uniform-position-within-voxel", + "uniform-density-per-ev-within-group", +] +_NORMALIZATION_STATES = { + NORMALIZATION_UNKNOWN, + NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE, + NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED, + NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE, + NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED, + NORMALIZATION_PHYSICAL, +} + _EV_PER_MEV = 1.0e6 -_CSV_FORMAT = "nucleide-openmc-tally-v1" +_CSV_FORMAT = "nucleide-openmc-tally-v2" +_CSV_FORMATS = {_CSV_FORMAT, "nucleide-openmc-tally-v1"} _CSV_HEADER = ["voxel", "group", "lower_mev", "upper_mev", "flux", "rel_err"] @@ -175,6 +238,12 @@ def tally_arrays(statepoint: Any, tally_id: int, score: str = "flux") -> dict[st "mesh_shape": mesh_shape, "mesh_bounds": mesh_bounds, "openmc_version": openmc_version(), + # Raw extraction is per source particle, but whether a flux tally is + # volume-integrated (default track-length) or already volume-averaged + # (random ray) is caller-configured. Never guess: normalize_flux + # requires an explicit declaration. + "normalization": NORMALIZATION_UNKNOWN, + "units": "unknown", } @@ -271,6 +340,13 @@ def tally_to_csv(arrays: dict[str, Any], path: str | Path) -> None: else: raise ValueError(f"unknown tally kind {kind!r}; want 'mesh' or 'cell'") version = arrays.get("openmc_version") + normalization = _csv_normalization(arrays) + units = str(arrays.get("units", _default_units(normalization))) + rate = arrays.get("source_rate_s") + if rate is not None: + rate = float(rate) + if not math.isfinite(rate) or rate < 0.0: + raise ValueError("tally_to_csv needs a finite nonnegative source_rate_s") lines: dict[str, str] = { "format": _CSV_FORMAT, "tally_id": str(arrays.get("tally_id")), @@ -281,7 +357,11 @@ def tally_to_csv(arrays: dict[str, Any], path: str | Path) -> None: "mesh_shape": "-" if mesh_shape is None else ",".join(str(d) for d in mesh_shape), "energy_bounds": "-" if not energy_bounds else ",".join(repr(b) for b in energy_bounds), "openmc_version": "-" if version is None else str(version), + "normalization": normalization, + "units": units, } + if rate is not None: + lines["source_rate_s"] = repr(rate) if isinstance(mesh_bounds, dict): for axis in ("x", "y", "z"): bounds = mesh_bounds.get(axis) @@ -334,9 +414,10 @@ def tally_from_csv(path: str | Path) -> dict[str, Any]: header = next(csv.reader([line])) else: rows.append(next(csv.reader([line]))) - if meta.get("format") != _CSV_FORMAT: + file_format = meta.get("format") + if file_format not in _CSV_FORMATS: raise ValueError( - f"{state_path} is not a {_CSV_FORMAT} file " + f"{state_path} is not a {_CSV_FORMAT} (or legacy v1) file " "(export one with tally_to_csv, or read the statepoint with read_statepoint)" ) for key in ("tally_id", "score", "kind", "n_voxels", "n_groups"): @@ -405,7 +486,30 @@ def tally_from_csv(path: str | Path) -> dict[str, Any]: else: raise ValueError(f"{state_path}: unknown tally kind {kind!r}") version = meta.get("openmc_version", "-") - return { + if file_format == _CSV_FORMAT: + normalization = meta.get("normalization", NORMALIZATION_UNKNOWN) + if normalization not in _NORMALIZATION_STATES: + raise ValueError( + f"{state_path}: unknown tally normalization {normalization!r}; " + f"want one of {sorted(_NORMALIZATION_STATES)}" + ) + units = meta.get("units", _default_units(normalization)) + rate_text = meta.get("source_rate_s") + source_rate_s = None + if rate_text not in (None, "-"): + try: + source_rate_s = float(rate_text) + except ValueError as exc: + raise ValueError(f"{state_path}: source_rate_s is not a float") from exc + if not math.isfinite(source_rate_s) or source_rate_s < 0.0: + raise ValueError(f"{state_path}: source_rate_s must be finite and nonnegative") + else: + # Legacy v1 carries no normalization metadata. Raw data is not + # physical flux; callers must declare its state before conversion. + normalization = NORMALIZATION_UNKNOWN + units = "unknown" + source_rate_s = None + out: dict[str, Any] = { "tally_id": int(meta["tally_id"]), "score": meta["score"], "kind": kind, @@ -417,6 +521,557 @@ def tally_from_csv(path: str | Path) -> dict[str, Any]: "mesh_shape": mesh_shape, "mesh_bounds": mesh_bounds, "openmc_version": None if version == "-" else version, + "normalization": normalization, + "units": units, + } + if source_rate_s is not None: + out["source_rate_s"] = source_rate_s + return out + + +def normalize_flux( + arrays: dict[str, Any], + source_rate_s: float, + volumes_cm3: Sequence[float], + *, + input_normalization: str | None = None, +) -> dict[str, Any]: + """Convert raw OpenMC tally arrays into physical group-integrated flux. + + The conversion is additive: ``arrays`` is not mutated and its raw + extraction semantics are preserved for every caller that does not opt in. + ``input_normalization`` declares both axes: volume-integrated + (:data:`NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE`, OpenMC's default + track-length flux tally) or volume-averaged + (:data:`NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE`, random-ray output run + with ``volume_normalized_flux_tallies``), and per-source-particle or + rate-scaled. OpenMC 0.16 fixed-source tallies are also scaled by the + configured total source strength, so the ``*_RATE_SCALED`` variants + declare that the source rate is already inside the tally and must not be + multiplied again. The declaration may be omitted only when the arrays dict + already carries one of those states. Legacy CSV v1 data and fresh + :func:`tally_arrays` output are ``unknown`` and require a caller + declaration; :data:`NORMALIZATION_PHYSICAL` is rejected as a double + normalization. + + For per-source volume-integrated input + ``phi[v,g] = raw[v,g] * rate / volume[v]``; the rate-scaled variant + computes only ``raw / volume``. Volume-averaged input applies only the + declared rate scale (or nothing when already rate-scaled). Output units + are ``1/(cm2 s)``. Relative errors are copied unchanged (deterministic + scaling preserves them); source-rate and volume uncertainty, cross-group + covariance and representability limits are outside this conversion. + """ + flux = _flux_table(arrays) + rel_err = arrays.get("rel_err") + n_voxels, n_groups = len(flux), len(flux[0]) + if ( + not isinstance(rel_err, list) + or len(rel_err) != n_voxels + or any(not isinstance(row, list) or len(row) != n_groups for row in rel_err) + ): + raise ValueError( + "normalize_flux needs the dict from tally_arrays/tally_from_csv " + "(flux and matching rel_err tables)" + ) + rate = float(source_rate_s) + if not math.isfinite(rate) or rate < 0.0: + raise ValueError(f"source_rate_s must be finite and nonnegative, got {source_rate_s!r}") + volumes = [float(v) for v in volumes_cm3] + if len(volumes) != n_voxels: + raise ValueError( + f"volumes_cm3 has {len(volumes)} entries for {n_voxels} voxels; " + "pass one positive volume per voxel" + ) + recorded = str(arrays.get("normalization", NORMALIZATION_UNKNOWN)) + if input_normalization is None: + if recorded == NORMALIZATION_UNKNOWN: + raise ValueError( + "raw tally normalization is unknown; declare input_normalization=" + f"{NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE!r} for OpenMC's default " + "track-length flux tally with normalized source weights, " + f"{NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED!r} when the configured " + "source strengths already sum to the physical rate, or " + f"{NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE!r}/" + f"{NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED!r} for random-ray output" + ) + declared = recorded + else: + declared = str(input_normalization) + if recorded not in (NORMALIZATION_UNKNOWN, declared): + raise ValueError( + f"declared input_normalization {declared!r} disagrees with the arrays " + f"metadata {recorded!r}; refusing to guess which normalization applies" + ) + if declared == NORMALIZATION_PHYSICAL: + raise ValueError( + "these arrays are already physical flux; refusing to normalize twice " + "(use the input normalization state from before the first conversion)" + ) + if declared == NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE: + mode = "volume-integrated" + elif declared == NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED: + mode = "volume-integrated-rate-scaled" + elif declared == NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE: + mode = "volume-averaged" + elif declared == NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED: + mode = "volume-averaged-rate-scaled" + else: + raise ValueError( + f"unsupported input_normalization {declared!r}; want " + f"{NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE!r}, " + f"{NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED!r}, " + f"{NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE!r}, or " + f"{NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED!r}" + ) + units = UNITS_PHYSICAL + converted = _core.r2s_normalize_flux(flux, rate, volumes, mode) + out = dict(arrays) + out["flux"] = converted + out["rel_err"] = [list(row) for row in rel_err] + out["normalization"] = NORMALIZATION_PHYSICAL + out["units"] = units + out["input_normalization"] = declared + out["source_rate_s"] = rate + return out + + +def mesh_source(source: dict[str, Any]) -> Any: + """Build a caller-side OpenMC ``MeshSource`` from a validated source dict. + + ``source`` is the dict returned by ``nucleide.r2s.photon_source`` or + ``photon_source_exported``: regular-mesh geometry, ascending eV group + edges, caller voxel volumes and ``[voxel][group]`` integrated photons/s. + OpenMC is imported lazily; the base package never depends on it. + + Each mesh element receives its own ``IndependentSource`` with a + histogram energy density (integrated group strength divided by the group + width, per eV) and the voxel's absolute photons/s as its strength. The + joint voxel/group distribution is therefore carried by the element + strengths and per-element spectra, never reconstructed from independent + spatial and energy marginals. Voxel order is the bridge's C-order + ``(i, j, k)``; the nested array passed to OpenMC is indexed ``[i][j][k]`` + so OpenMC's internal Fortran flattening preserves the same elements. + OpenMC scales its fixed-source tallies by the sum of these strengths, so a + later flux conversion uses a ``rate-scaled-*`` declaration and must not + multiply by the same total rate again. + + Zero-source voxels are allowed inside a nonzero source: they receive a + uniform zero-strength spectrum so OpenMC's sampling probability for them + is exactly zero. An all-zero source is rejected by the shared validator. + The regular-mesh cell volumes must equal ``voxel_volumes_cm3``; a + mismatch is a loud error rather than a bounding-box approximation. + """ + om = _require_openmc() + args = _source_args(source) + mesh_shape, lower, upper, volumes, edges, _cooling, strengths = args + report = _source_report_from_args(args) + if not report["valid"]: + codes = ", ".join( + issue["code"] for issue in report["issues"] if issue["severity"] == "error" + ) + raise ValueError(f"cannot export an invalid photon source; errors: {codes}") + total = float(source.get("total_photons_per_s", 0.0)) + if not math.isclose(total, _sum_table(strengths), rel_tol=1e-12, abs_tol=0.0): + raise ValueError( + "source dict total_photons_per_s disagrees with its strengths table; " + "rebuild it with nucleide.r2s.photon_source" + ) + if total <= 0.0: + raise ValueError("an all-zero photon source cannot be exported for sampling") + probabilities = _core.r2s_source_energy_probabilities(*args) + widths = [edges[g + 1] - edges[g] for g in range(len(edges) - 1)] + n_x, n_y, n_z = mesh_shape + dx = (upper[0] - lower[0]) / n_x + dy = (upper[1] - lower[1]) / n_y + dz = (upper[2] - lower[2]) / n_z + expected_volume = dx * dy * dz + for voxel, volume in enumerate(volumes): + if not math.isclose(volume, expected_volume, rel_tol=1e-9, abs_tol=0.0): + raise ValueError( + f"voxel {voxel} volume {volume!r} cm3 does not match the regular-mesh " + f"cell volume {expected_volume!r} cm3; OpenMC export supports only a " + "regular mesh, not a bounding-box approximation of another geometry" + ) + mesh = om.RegularMesh() + mesh.dimension = (n_x, n_y, n_z) + mesh.lower_left = tuple(lower) + mesh.upper_right = tuple(upper) + nested: list[list[list[Any]]] = [] + for i in range(n_x): + plane: list[list[Any]] = [] + for j in range(n_y): + column: list[Any] = [] + for k in range(n_z): + voxel = (i * n_y + j) * n_z + k + strength = _sum_row(strengths[voxel]) + if strength > 0.0: + # OpenMC histogram distributions take a differential PDF + # per energy unit; group probabilities must be divided by + # the bin width, never passed as integrated bins. + density = [ + probabilities[voxel][group] / widths[group] for group in range(len(widths)) + ] + energy: Any = om.stats.Tabular(edges, density, interpolation="histogram") + else: + energy = om.stats.Uniform(edges[0], edges[-1]) + column.append( + om.IndependentSource( + energy=energy, + strength=strength, + particle="photon", + ) + ) + plane.append(column) + nested.append(plane) + mesh_source_obj = om.MeshSource(mesh=mesh, sources=nested) + if not math.isclose(float(mesh_source_obj.strength), total, rel_tol=1e-12, abs_tol=0.0): + raise RuntimeError( + "OpenMC MeshSource strength does not match the validated absolute total; " + "refusing to export an inconsistent source" + ) + return mesh_source_obj + + +def write_mesh_source_xml(source: dict[str, Any], path: str | Path) -> Path: + """Write a self-contained OpenMC ``settings.xml`` for one photon source. + + The file contains the regular-mesh definition and the mesh source, so + caller OpenMC can read it back with ``openmc.Settings.from_xml`` without + a separate ``meshes.xml``. The parent directory must already exist; + callers that need atomic replacement should use :func:`export_cooling_batch` + or write through a temporary path. + """ + om = _require_openmc() + target = Path(path) + if not target.parent.is_dir(): + raise FileNotFoundError(f"output directory does not exist: {target.parent}") + settings = om.Settings() + settings.source = [mesh_source(source)] + settings.export_to_xml(target) + return target + + +def source_manifest( + *, + source: dict[str, Any], + input_files: Iterable[str | Path] = (), + output_files: Iterable[str | Path] = (), + external_solver: str | None = None, + external_version: str | None = None, + adapter: str = "openmc-mesh-source", + adapter_version: str = "1", + evaluated_library: str | None = None, + validation: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build a compact, versioned source reproducibility manifest. + + The manifest records identifiers and measured SHA-256 hashes for files + that exist, the energy-grid identity, voxel order, cooling offset, + absolute photons/s and the shared validation summary. It never invents + hashes for evaluated data: ``evaluated_library`` is a caller-supplied + identity only. Bulk arrays are referenced by grid hash, not duplicated. + JSON serialization is deterministic through :func:`write_manifest`; no + timestamps, environment variables or credentials are recorded. + """ + args = _source_args(source) + report = _source_report_from_args(args) + if not report["valid"]: + codes = ", ".join( + issue["code"] for issue in report["issues"] if issue["severity"] == "error" + ) + raise ValueError(f"cannot manifest an invalid photon source; errors: {codes}") + grid_hash = _energy_grid_sha256(args[4]) + validation_summary = ( + _report_summary(report) if validation is None else _validation_summary(validation) + ) + manifest: dict[str, Any] = { + "schema": _MANIFEST_SCHEMA, + "created_by": {"nucleide": _core.version()}, + "external": { + "solver": external_solver, + "solver_version": external_version, + "solver_version_source": "caller-supplied" if external_version else None, + "adapter": adapter, + "adapter_version": adapter_version, + }, + "source": { + "kind": "photons", + "strength_units": "photons/s", + "normalization": "integrated-per-voxel-and-group", + "cooling_s": args[5], + "mesh_shape": args[0], + "lower_left_cm": args[1], + "upper_right_cm": args[2], + "n_voxels": len(args[3]), + "n_groups": len(args[4]) - 1, + "voxel_order": _VOXEL_ORDER, + "energy_grid_sha256": grid_hash, + "total_photons_per_s": report["totals"]["total_photons_per_s"], + "assumptions": list(_ASSUMPTIONS), + }, + "evaluated_library": ( + None + if evaluated_library is None + else {"identity": evaluated_library, "hash": None, "status": "caller-supplied"} + ), + "inputs": [_file_record(path, require_exists=True) for path in input_files], + "outputs": [_file_record(path, require_exists=False) for path in output_files], + "validation": validation_summary, + } + return manifest + + +def write_manifest(manifest: dict[str, Any], path: str | Path) -> Path: + """Write a manifest or batch manifest as deterministic, atomic JSON.""" + schema = manifest.get("schema") + if schema not in {_MANIFEST_SCHEMA, _BATCH_SCHEMA}: + raise ValueError( + f"unknown manifest schema {schema!r}; want {_MANIFEST_SCHEMA!r} or {_BATCH_SCHEMA!r}" + ) + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + try: + text = json.dumps(manifest, sort_keys=True, indent=2, allow_nan=False) + "\n" + except (TypeError, ValueError) as exc: + raise ValueError( + "manifest is not JSON-serializable (non-finite number or bad type)" + ) from exc + _write_text_atomic(target, text) + return target + + +def read_manifest(path: str | Path) -> dict[str, Any]: + """Read a source or batch manifest, rejecting unknown schemas.""" + manifest_path = Path(path) + if not manifest_path.is_file(): + raise FileNotFoundError(f"manifest not found: {manifest_path}") + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + raise ValueError(f"{manifest_path} is not valid JSON") from exc + if not isinstance(manifest, dict): + raise ValueError(f"{manifest_path}: manifest root must be a JSON object") + schema = manifest.get("schema") + if schema not in {_MANIFEST_SCHEMA, _BATCH_SCHEMA}: + raise ValueError( + f"{manifest_path}: unknown manifest schema {schema!r}; " + f"want {_MANIFEST_SCHEMA!r} or {_BATCH_SCHEMA!r}" + ) + return manifest + + +def verify_manifest( + manifest_or_path: dict[str, Any] | str | Path, + *, + base_dir: str | Path | None = None, +) -> dict[str, Any]: + """Verify recorded file hashes and report mismatches, never repair them. + + ``manifest_or_path`` may be a previously built manifest dict or a path. + Relative paths resolve against the manifest's directory (path input) or + ``base_dir`` (dict input; default ``"."``). Records without a measured + hash (explicit unknown/caller-supplied provenance) are not treated as + verified files; missing files and hash mismatches make ``ok`` false. + """ + if isinstance(manifest_or_path, (str, Path)): + manifest_path = Path(manifest_or_path) + manifest = read_manifest(manifest_path) + base = manifest_path.parent + else: + manifest = manifest_or_path + base = Path(base_dir if base_dir is not None else ".") + if manifest.get("schema") not in {_MANIFEST_SCHEMA, _BATCH_SCHEMA}: + raise ValueError(f"unknown manifest schema {manifest.get('schema')!r}") + checked = 0 + mismatches: list[dict[str, Any]] = [] + missing: list[dict[str, Any]] = [] + for section in ("inputs", "outputs"): + records = manifest.get(section, []) + if not isinstance(records, list): + raise ValueError(f"manifest {section!r} must be a list") + for record in records: + if not isinstance(record, dict) or "path" not in record: + raise ValueError(f"manifest {section!r} entry is missing 'path'") + digest = record.get("sha256") + if digest is None: + if record.get("status") == "missing": + missing.append({"path": str(record["path"]), "section": section}) + continue + path = Path(str(record["path"])) + resolved = path if path.is_absolute() else base / path + if not resolved.is_file(): + missing.append({"path": str(record["path"]), "section": section}) + continue + checked += 1 + actual = _sha256_file(resolved) + if actual != digest: + mismatches.append( + { + "path": str(record["path"]), + "section": section, + "expected_sha256": digest, + "actual_sha256": actual, + } + ) + return { + "ok": not mismatches and not missing, + "checked": checked, + "mismatches": mismatches, + "missing": missing, + } + + +class BatchExportError(RuntimeError): + """A cooling-time batch failed after zero or more outputs were written. + + ``partial`` carries the same fields as a batch manifest with + ``"status": "partial"``; no success manifest is written for the batch. + """ + + def __init__(self, message: str, *, partial: dict[str, Any]) -> None: + super().__init__(message) + self.partial = partial + + +def export_cooling_batch( + sources: Sequence[dict[str, Any]], + requested_times_s: Sequence[float], + out_dir: str | Path, + *, + writer: Callable[[dict[str, Any], Path], None] | None = None, + overwrite: bool = False, + skip_zero: bool = False, +) -> dict[str, Any]: + """Export one source per exact requested cooling offset plus a manifest. + + ``sources`` carry ``cooling_s`` plus the photon-source fields; matching is + exact (no interpolation, nearest-time substitution or duplicate offsets). + Outputs are named ``source-t.xml`` from the round-trippable float + spelling, so distinct times cannot collide. Every selection, report and + name is prevalidated before the first write. Files are replaced + atomically; existing files are refused unless ``overwrite=True``. An + all-zero source is an error unless ``skip_zero=True``, in which case the + skipped time is recorded instead of exported. On failure the raised + :class:`BatchExportError` carries partial outputs and no complete manifest + is written. The default writer emits OpenMC ``settings.xml`` via + :func:`write_mesh_source_xml`. + """ + selected = list(sources) + if not selected: + raise ValueError("export_cooling_batch needs at least one source") + times = [float(t) for t in requested_times_s] + if not times: + raise ValueError("requested_times_s must not be empty") + for t in times: + if not math.isfinite(t) or t < 0.0: + raise ValueError(f"cooling offsets must be finite and nonnegative, got {t!r}") + available: list[float] = [] + for index, source in enumerate(selected): + cooling = source.get("cooling_s") + if cooling is None: + raise ValueError(f"source {index} is missing cooling_s") + value = float(cooling) + if not math.isfinite(value) or value < 0.0: + raise ValueError(f"source {index} cooling_s must be finite and nonnegative") + available.append(value) + indices = _core.r2s_select_cooling(available, times) + directory = Path(out_dir) + directory.mkdir(parents=True, exist_ok=True) + plans: list[tuple[float, dict[str, Any], Path, dict[str, Any], str]] = [] + skipped: list[dict[str, Any]] = [] + for t, index in zip(times, indices, strict=True): + source = selected[index] + args = _source_args(source) + report = _source_report_from_args(args) + if not report["valid"]: + codes = ", ".join( + issue["code"] for issue in report["issues"] if issue["severity"] == "error" + ) + raise ValueError(f"source at cooling_s={t!r} is invalid; errors: {codes}") + total = float(report["totals"]["total_photons_per_s"]) + if total <= 0.0: + if skip_zero: + skipped.append({"time_s": t, "reason": "all-zero-source"}) + continue + raise ValueError( + f"source at cooling_s={t!r} has zero total photons/s; an all-zero " + "distribution cannot be exported as a sampling source (pass skip_zero=True " + "to record it as skipped instead)" + ) + plans.append( + ( + t, + source, + directory / f"source-t{_time_token(t)}.xml", + report, + _energy_grid_sha256(args[4]), + ) + ) + manifest_path = directory / "batch-manifest.json" + if not overwrite: + existing = [str(path) for _, _, path, _, _ in plans if path.exists()] + if manifest_path.exists(): + existing.append(str(manifest_path)) + if existing: + raise FileExistsError( + "refusing to overwrite existing batch outputs without overwrite=True: " + + ", ".join(existing) + ) + if len({path for _, _, path, _, _ in plans}) != len(plans): + raise ValueError("deterministic output names collided; distinct cooling offsets required") + writer_fn = writer if writer is not None else write_mesh_source_xml + outputs: list[dict[str, Any]] = [] + batch_meta: dict[str, Any] = { + "schema": _BATCH_SCHEMA, + "created_by": {"nucleide": _core.version()}, + "requested_times_s": times, + "normalization": "integrated-per-voxel-and-group", + "units": "photons/s", + "voxel_order": _VOXEL_ORDER, + "assumptions": list(_ASSUMPTIONS), + "outputs": outputs, + "skipped": skipped, + } + partial: dict[str, Any] = dict(batch_meta, status="partial") + try: + for t, source, target, report, grid_hash in plans: + fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=f".{target.name}.", suffix=".tmp") + os.close(fd) + tmp_path = Path(tmp_name) + try: + writer_fn(source, tmp_path) + if not tmp_path.is_file(): + raise RuntimeError(f"writer did not produce {tmp_path}") + os.replace(tmp_path, target) + except BaseException: + tmp_path.unlink(missing_ok=True) + raise + total = float(report["totals"]["total_photons_per_s"]) + outputs.append( + { + "time_s": t, + "path": target.name, + "sha256": _sha256_file(target), + "size_bytes": target.stat().st_size, + "total_photons_per_s": total, + "energy_grid_sha256": grid_hash, + "validation": _report_summary(report), + } + ) + partial["outputs"] = outputs + manifest: dict[str, Any] = dict(batch_meta, status="complete") + write_manifest(manifest, manifest_path) + except BaseException as exc: + raise BatchExportError( + f"cooling batch failed after {len(outputs)} output(s); no complete manifest written", + partial=partial, + ) from exc + return { + "manifest": manifest, + "manifest_path": str(manifest_path), + "outputs": outputs, + "skipped": skipped, } @@ -648,3 +1303,214 @@ def _parse_float_list(text: str, path: Path, key: str) -> list[float]: return [float(part) for part in text.split(",")] except ValueError as exc: raise ValueError(f"{path}: tally CSV {key!r} is not a float list") from exc + + +def _csv_normalization(arrays: dict[str, Any]) -> str: + """Normalization state recorded on a tally-arrays dict (validated).""" + normalization = str(arrays.get("normalization", NORMALIZATION_UNKNOWN)) + if normalization not in _NORMALIZATION_STATES: + raise ValueError( + f"unknown tally normalization {normalization!r}; want one of " + f"{sorted(_NORMALIZATION_STATES)}" + ) + return normalization + + +def _default_units(normalization: str) -> str: + """Default units for a declared normalization state.""" + return { + NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE: UNITS_VOLUME_INTEGRATED_PER_SOURCE, + NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED: UNITS_VOLUME_INTEGRATED_RATE_SCALED, + NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE: UNITS_VOLUME_AVERAGED_PER_SOURCE, + NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED: UNITS_VOLUME_AVERAGED_RATE_SCALED, + NORMALIZATION_PHYSICAL: UNITS_PHYSICAL, + }.get(normalization, "unknown") + + +class _SourceArgs(NamedTuple): + """Validated photon-source fields passed to the shared Rust kernel.""" + + mesh_shape: list[int] + lower_left_cm: list[float] + upper_right_cm: list[float] + volumes_cm3: list[float] + edges_ev: list[float] + cooling_s: float + strengths: list[list[float]] + + +def _source_args(source: dict[str, Any]) -> _SourceArgs: + """Extract and type-check the photon-source dict fields.""" + if not isinstance(source, dict): + raise TypeError("photon source must be the dict returned by nucleide.r2s.photon_source") + required = ( + "mesh_shape", + "lower_left_cm", + "upper_right_cm", + "voxel_volumes_cm3", + "edges_ev", + "cooling_s", + "strengths_photons_per_s", + ) + missing = [key for key in required if key not in source] + if missing: + raise ValueError( + "photon source is missing fields: " + + ", ".join(missing) + + " (build it with nucleide.r2s.photon_source)" + ) + try: + cooling = float(source["cooling_s"]) + except (TypeError, ValueError) as exc: + raise ValueError("cooling_s must be a finite nonnegative float") from exc + return _SourceArgs( + mesh_shape=_int_list(source["mesh_shape"], "mesh_shape"), + lower_left_cm=_float_list(source["lower_left_cm"], "lower_left_cm"), + upper_right_cm=_float_list(source["upper_right_cm"], "upper_right_cm"), + volumes_cm3=_float_list(source["voxel_volumes_cm3"], "voxel_volumes_cm3"), + edges_ev=_float_list(source["edges_ev"], "edges_ev"), + cooling_s=cooling, + strengths=_float_matrix(source["strengths_photons_per_s"], "strengths_photons_per_s"), + ) + + +def _source_report_from_args(args: _SourceArgs) -> dict[str, Any]: + """Run the shared Rust report on validated source fields.""" + return _core.r2s_source_report(*args) + + +def _report_summary(report: dict[str, Any]) -> dict[str, Any]: + """Compact stable validation summary for a manifest.""" + codes: list[str] = [] + for issue in report.get("issues", []): + code = str(issue.get("code", "")) + if code and code not in codes: + codes.append(code) + return { + "valid": bool(report.get("valid", False)), + "issue_count": int(report.get("issue_count", 0)), + "truncated": bool(report.get("truncated", False)), + "codes": codes, + } + + +def _validation_summary(validation: dict[str, Any]) -> dict[str, Any]: + """Normalize a caller-supplied validation summary or report to stable keys.""" + if not isinstance(validation, dict): + raise TypeError("validation must be a dict with at least a 'valid' flag") + if "valid" not in validation: + raise ValueError("validation summary is missing 'valid'") + if "codes" not in validation and isinstance(validation.get("issues"), list): + summary = _report_summary(validation) + else: + summary = { + "valid": bool(validation["valid"]), + "issue_count": int(validation.get("issue_count", 0)), + "truncated": bool(validation.get("truncated", False)), + "codes": [str(code) for code in validation.get("codes", [])], + } + return summary + + +def _file_record(path: str | Path, *, require_exists: bool) -> dict[str, Any]: + """Measure one file (SHA-256 + size) or mark it explicitly missing.""" + file_path = Path(path) + record: dict[str, Any] = {"path": file_path.as_posix()} + if not file_path.is_file(): + if require_exists: + raise FileNotFoundError(f"manifest input not found: {file_path}") + record.update({"sha256": None, "size_bytes": None, "status": "missing"}) + return record + record.update({"sha256": _sha256_file(file_path), "size_bytes": file_path.stat().st_size}) + return record + + +def _sha256_file(path: Path) -> str: + """Streaming SHA-256 of one file.""" + digest = hashlib.sha256() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _energy_grid_sha256(edges_ev: Sequence[float]) -> str: + """Deterministic identity of an energy grid (little-endian float64 edges).""" + payload = b"nucleide-energy-grid-ev\x00" + b"".join( + struct.pack(" str: + """Round-trippable, filename-safe spelling of one cooling offset.""" + token = repr(0.0 if time_s == 0.0 else float(time_s)) + return token.replace("+", "p") + + +def _write_text_atomic(target: Path, text: str) -> None: + """Write UTF-8 text through a same-directory temporary file.""" + fd, name = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + os.replace(name, target) + except BaseException: + Path(name).unlink(missing_ok=True) + raise + + +def _sum_row(row: Sequence[float]) -> float: + """Accurate sum of one strength row.""" + return math.fsum(float(value) for value in row) + + +def _sum_table(table: Sequence[Sequence[float]]) -> float: + """Accurate sum of a rectangular strength table.""" + return math.fsum(_sum_row(row) for row in table) + + +def _int_list(value: Any, name: str) -> list[int]: + """Validate a sequence of integers (bools rejected).""" + if isinstance(value, (str, bytes)) or not isinstance(value, Sequence): + raise TypeError(f"{name} must be a sequence of ints") + out: list[int] = [] + for entry in value: + if isinstance(entry, bool) or not isinstance(entry, int): + raise TypeError(f"{name} must contain only ints, got {entry!r}") + out.append(entry) + return out + + +def _float_list(value: Any, name: str) -> list[float]: + """Validate a sequence of finite floats (bools rejected).""" + if isinstance(value, (str, bytes)) or not isinstance(value, Sequence): + raise TypeError(f"{name} must be a sequence of floats") + out: list[float] = [] + for entry in value: + if isinstance(entry, bool): + raise TypeError(f"{name} must contain only floats, got {entry!r}") + try: + number = float(entry) + except (TypeError, ValueError) as exc: + raise TypeError(f"{name} must contain only floats, got {entry!r}") from exc + if not math.isfinite(number): + raise ValueError(f"{name} must contain only finite values, got {entry!r}") + out.append(number) + return out + + +def _float_matrix(value: Any, name: str) -> list[list[float]]: + """Validate a rectangular sequence of float sequences.""" + if isinstance(value, (str, bytes)) or not isinstance(value, Sequence): + raise TypeError(f"{name} must be a sequence of float sequences") + rows: list[list[float]] = [] + width: int | None = None + for row in value: + parsed = _float_list(row, name) + if width is None: + width = len(parsed) + elif len(parsed) != width: + raise ValueError(f"{name} must be rectangular; found rows of {width} and {len(parsed)}") + rows.append(parsed) + return rows diff --git a/python/nucleide/r2s.py b/python/nucleide/r2s.py index 7567541..1fa7e1b 100644 --- a/python/nucleide/r2s.py +++ b/python/nucleide/r2s.py @@ -17,8 +17,25 @@ requested energy groups. The uniform split preserves only the total shutdown strength; real decay photons follow the nuclide- and energy-dependent lines in ALARA ``.photonSrc`` spectra. + +Transport handoff: :func:`photon_source` builds and validates an explicit +regular-mesh source at one cooling time (ascending eV edges, integrated +photons/s per voxel/group, C-order voxels, positive volumes). The returned +dict carries checked totals and a bounded structured report with stable issue +codes. :func:`photon_source_exported` restores sparse group exports with +explicit dense indices; :func:`source_probabilities` returns the joint +voxel/group distribution (never factored marginals), +:func:`source_energy_probabilities` returns per-voxel spectra and +:func:`source_density` applies each volume exactly once. :func:`select_cooling` +matches offsets exactly. OpenMC export and manifests live in +:mod:`nucleide.openmc`. """ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + from nucleide._internal import ( r2s_assemble, r2s_expand, @@ -26,7 +43,14 @@ r2s_from_deck, r2s_from_snapshot, r2s_photon_group_sums, + r2s_photon_source, + r2s_photon_source_exported, + r2s_select_cooling, r2s_snapshot_inventory, + r2s_source_density, + r2s_source_energy_probabilities, + r2s_source_probabilities, + r2s_source_report, r2s_tag_zone_strength, r2s_validate, ) @@ -42,6 +66,124 @@ snapshot_inventory = r2s_snapshot_inventory expand_sweep = r2s_expand_sweep + +def photon_source( + mesh_shape: Sequence[int], + lower_left_cm: Sequence[float], + upper_right_cm: Sequence[float], + voxel_volumes_cm3: Sequence[float], + edges_ev: Sequence[float], + cooling_s: float, + strengths_photons_per_s: Sequence[Sequence[float]], +) -> dict[str, Any]: + """Build and validate an integrated photon source at one cooling time. + + The regular mesh is ``(nx, ny, nz)`` with C-order voxel index + ``(i*ny + j)*nz + k``; ``edges_ev`` are ascending group edges in eV and + ``strengths_photons_per_s[v][g]`` are integrated photons/s per voxel and + group. ``voxel_volumes_cm3`` is parallel to the voxel order and is used + only when converting to a density (never multiplied into an integrated + strength twice). The returned dict carries the validated fields, checked + totals and the structured report, including the explicit modelling + assumptions (uniform position within a voxel, uniform density per eV in a + group). An all-zero source stays valid data but cannot be sampled. + """ + return r2s_photon_source( + list(mesh_shape), + list(lower_left_cm), + list(upper_right_cm), + list(voxel_volumes_cm3), + list(edges_ev), + float(cooling_s), + [list(row) for row in strengths_photons_per_s], + ) + + +def photon_source_exported( + mesh_shape: Sequence[int], + lower_left_cm: Sequence[float], + upper_right_cm: Sequence[float], + voxel_volumes_cm3: Sequence[float], + full_edges_ev: Sequence[float], + cooling_s: float, + exported_group_indices: Sequence[int], + exported_strengths_photons_per_s: Sequence[Sequence[float]], +) -> dict[str, Any]: + """Rebuild a dense source from exported groups plus explicit indices. + + ``exported_group_indices`` names the dense group positions of the + exported columns and must be strictly increasing, unique and in range. + Omitted groups are filled with exactly zero; centroids are never accepted + as bin edges and missing/duplicate indices are loud errors. + """ + return r2s_photon_source_exported( + list(mesh_shape), + list(lower_left_cm), + list(upper_right_cm), + list(voxel_volumes_cm3), + list(full_edges_ev), + float(cooling_s), + list(exported_group_indices), + [list(row) for row in exported_strengths_photons_per_s], + ) + + +def source_report(source: dict[str, Any]) -> dict[str, Any]: + """Return the structured, bounded validation report for a source dict. + + Issue codes are stable, deterministic, and classified by severity + (``error`` / ``warning`` / ``assumption``). The report is an inspection + surface: constructors and exporters still raise on invalid input rather + than silently repairing it. + """ + return r2s_source_report(*_source_args(source)) + + +def source_probabilities(source: dict[str, Any]) -> list[list[float]]: + """Joint voxel/group sampling probabilities (never factor the marginals).""" + return r2s_source_probabilities(*_source_args(source)) + + +def source_energy_probabilities(source: dict[str, Any]) -> list[list[float]]: + """Per-voxel energy probabilities, with all-zero rows for zero voxels.""" + return r2s_source_energy_probabilities(*_source_args(source)) + + +def source_density(source: dict[str, Any]) -> list[list[float]]: + """Integrated photons/(s cm3), applying each voxel volume exactly once.""" + return r2s_source_density(*_source_args(source)) + + +def select_cooling(available_s: Sequence[float], requested_s: Sequence[float]) -> list[int]: + """Exact cooling-offset selection: no interpolation or nearest substitution.""" + return r2s_select_cooling([float(t) for t in available_s], [float(t) for t in requested_s]) + + +def _source_args( + source: dict[str, Any], +) -> tuple[ + list[int], + list[float], + list[float], + list[float], + list[float], + float, + list[list[float]], +]: + """Unpack a source dict into the shared binding's positional fields.""" + if not isinstance(source, dict): + raise TypeError("photon source must be the dict returned by nucleide.r2s.photon_source") + return ( + list(source["mesh_shape"]), + list(source["lower_left_cm"]), + list(source["upper_right_cm"]), + list(source["voxel_volumes_cm3"]), + list(source["edges_ev"]), + float(source["cooling_s"]), + [list(row) for row in source["strengths_photons_per_s"]], + ) + + __all__ = [ "r2s_from_deck", "r2s_from_snapshot", @@ -61,4 +203,11 @@ "photon_group_sums", "snapshot_inventory", "expand_sweep", + "photon_source", + "photon_source_exported", + "source_report", + "source_probabilities", + "source_energy_probabilities", + "source_density", + "select_cooling", ] diff --git a/tests/test_openmc_bridge.py b/tests/test_openmc_bridge.py index 9b1eb2b..30c6198 100644 --- a/tests/test_openmc_bridge.py +++ b/tests/test_openmc_bridge.py @@ -298,8 +298,8 @@ def test_csv_malformed_is_loud(tmp_path: Path) -> None: omc.tally_to_csv(arrays, good) text = good.read_text(encoding="utf-8") bad_format = tmp_path / "bad-format.csv" - bad_format.write_text(text.replace("nucleide-openmc-tally-v1", "other"), encoding="utf-8") - with pytest.raises(ValueError, match="not a nucleide-openmc-tally-v1"): + bad_format.write_text(text.replace("nucleide-openmc-tally-v2", "other"), encoding="utf-8") + with pytest.raises(ValueError, match="not a nucleide-openmc-tally-v2"): omc.tally_from_csv(bad_format) bad_header = tmp_path / "bad-header.csv" bad_header.write_text(text.replace("voxel,group,lower_mev", "voxel,group,X"), encoding="utf-8") diff --git a/tests/test_openmc_handoff.py b/tests/test_openmc_handoff.py new file mode 100644 index 0000000..699b232 --- /dev/null +++ b/tests/test_openmc_handoff.py @@ -0,0 +1,583 @@ +"""Activation-to-transport handoff tests (synthetic; no OpenMC import). + +Covers physical flux normalization, the v2 CSV metadata interchange, the +shared photon-source contract, the reproducibility manifest and exact +cooling-time batch export. Real pinned-OpenMC index/XML behaviour lives in +``validation/openmc_handoff_probe.py``; the adapter test here uses a fake +``openmc`` module built to the documented 0.16.0 object protocol so the +C-order-to-Fortran-order mapping is checked without the optional dependency. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest + +import nucleide.openmc as omc +import nucleide.r2s as r2s + +# --------------------------------------------------------------------------- +# fixtures / helpers + + +def _tally(flux: list[list[float]], *, normalization: str | None = None) -> dict[str, Any]: + n_voxels = len(flux) + n_groups = len(flux[0]) + arrays: dict[str, Any] = { + "tally_id": 1, + "score": "flux", + "kind": "mesh" if n_voxels > 1 else "cell", + "n_voxels": n_voxels, + "n_groups": n_groups, + "energy_bounds_mev": [0.0, 1.0, 2.0][: n_groups + 1], + "flux": [list(row) for row in flux], + "rel_err": [[0.1] * n_groups for _ in range(n_voxels)], + "mesh_shape": [n_voxels, 1, 1] if n_voxels > 1 else None, + "mesh_bounds": ( + {"x": [0.0, 1.0, 2.0], "y": [0.0, 1.0], "z": [0.0, 1.0]} if n_voxels > 1 else None + ), + "openmc_version": "0.16.0", + "normalization": normalization if normalization is not None else omc.NORMALIZATION_UNKNOWN, + "units": "unknown", + } + return arrays + + +def _source( + strengths: list[list[float]] | None = None, + *, + cooling_s: float = 0.0, + mesh_shape: list[int] | None = None, + volumes: list[float] | None = None, + edges: list[float] | None = None, +) -> dict[str, Any]: + strengths = strengths if strengths is not None else [[100.0, 0.0], [0.0, 300.0]] + mesh_shape = mesh_shape if mesh_shape is not None else [2, 1, 1] + volumes = volumes if volumes is not None else [1.0, 1.0] + edges = edges if edges is not None else [0.0, 2.0, 4.0] + nx, ny, nz = mesh_shape + return r2s.photon_source( + mesh_shape, + [0.0, 0.0, 0.0], + [float(nx), float(ny), float(nz)], + volumes, + edges, + cooling_s, + strengths, + ) + + +# --------------------------------------------------------------------------- +# W1: flux normalization + + +def test_normalize_flux_hand_case_and_metadata() -> None: + arrays = _tally([[4.0, 9.0]]) + out = omc.normalize_flux( + arrays, + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE, + ) + assert out["flux"] == [[20.0, 45.0]] + assert out["rel_err"] == arrays["rel_err"] + assert out["normalization"] == omc.NORMALIZATION_PHYSICAL + assert out["units"] == omc.UNITS_PHYSICAL + assert out["source_rate_s"] == 10.0 + assert out["input_normalization"] == omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE + # Additive: the raw arrays are untouched. + assert arrays["flux"] == [[4.0, 9.0]] + assert arrays["normalization"] == omc.NORMALIZATION_UNKNOWN + + +def test_normalize_flux_two_unequal_volumes_and_zero_rate() -> None: + arrays = _tally([[4.0, 9.0], [8.0, 3.0]]) + out = omc.normalize_flux( + arrays, + 10.0, + [2.0, 4.0], + input_normalization=omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE, + ) + assert out["flux"] == [[20.0, 45.0], [20.0, 7.5]] + zero = omc.normalize_flux( + arrays, + 0.0, + [2.0, 4.0], + input_normalization=omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE, + ) + assert zero["flux"] == [[0.0, 0.0], [0.0, 0.0]] + + +def test_normalize_flux_volume_averaged_branch_does_not_divide_again() -> None: + arrays = _tally([[4.0, 9.0]]) + out = omc.normalize_flux( + arrays, + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE, + ) + assert out["flux"] == [[40.0, 90.0]] + + +def test_normalize_flux_rate_scaled_does_not_multiply_the_rate_again() -> None: + arrays = _tally([[4.0, 9.0]]) + integrated = omc.normalize_flux( + arrays, + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_VOLUME_INTEGRATED_RATE_SCALED, + ) + assert integrated["flux"] == [[2.0, 4.5]] + averaged = omc.normalize_flux( + arrays, + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_VOLUME_AVERAGED_RATE_SCALED, + ) + assert averaged["flux"] == [[4.0, 9.0]] + assert averaged["normalization"] == omc.NORMALIZATION_PHYSICAL + + +def test_normalize_flux_requires_declaration_and_rejects_double_scaling() -> None: + arrays = _tally([[4.0, 9.0]]) + with pytest.raises(ValueError, match="normalization is unknown"): + omc.normalize_flux(arrays, 10.0, [2.0]) + with pytest.raises(ValueError, match="already physical"): + omc.normalize_flux( + arrays, + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_PHYSICAL, + ) + recorded = _tally([[4.0, 9.0]], normalization=omc.NORMALIZATION_PHYSICAL) + with pytest.raises(ValueError, match="already physical"): + omc.normalize_flux(recorded, 10.0, [2.0]) + with pytest.raises(ValueError, match="disagrees"): + omc.normalize_flux( + _tally([[4.0, 9.0]], normalization=omc.NORMALIZATION_VOLUME_AVERAGED_PER_SOURCE), + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE, + ) + with pytest.raises(ValueError, match="unsupported input_normalization"): + omc.normalize_flux(arrays, 10.0, [2.0], input_normalization="mystery") + + +def test_normalize_flux_rejects_bad_rate_volume_and_values() -> None: + arrays = _tally([[4.0, 9.0]]) + declared = omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE + with pytest.raises(ValueError, match="source_rate_s"): + omc.normalize_flux(arrays, -1.0, [2.0], input_normalization=declared) + with pytest.raises(ValueError, match="source_rate_s"): + omc.normalize_flux(arrays, float("nan"), [2.0], input_normalization=declared) + with pytest.raises(ValueError, match="volumes_cm3"): + omc.normalize_flux(arrays, 1.0, [2.0, 3.0], input_normalization=declared) + with pytest.raises(ValueError): + omc.normalize_flux(_tally([[-1.0, 9.0]]), 1.0, [2.0], input_normalization=declared) + with pytest.raises(ValueError): + omc.normalize_flux(_tally([[4.0, 9.0]]), 1.0, [0.0], input_normalization=declared) + + +def test_csv_v1_reads_as_unknown_and_v2_roundtrips_physical() -> None: + arrays = _tally([[4.0, 9.0]]) + v1 = "\n".join( + [ + "# format = nucleide-openmc-tally-v1", + "# tally_id = 1", + "# score = flux", + "# kind = cell", + "# n_voxels = 1", + "# n_groups = 2", + "# mesh_shape = -", + "# energy_bounds = 0.0,1e-06,2e-06", + "# openmc_version = 0.16.0", + "# mesh_x_bounds = -", + "# mesh_y_bounds = -", + "# mesh_z_bounds = -", + "voxel,group,lower_mev,upper_mev,flux,rel_err", + "0,0,0.0,1e-06,4.0,0.1", + "0,1,1e-06,2e-06,9.0,0.1", + "", + ] + ) + # The reader accepts v1 metadata but never relabels it as physical. + from tempfile import TemporaryDirectory + + with TemporaryDirectory() as tmp: + source = Path(tmp) / "legacy.csv" + source.write_text(v1, encoding="utf-8") + legacy = omc.tally_from_csv(source) + assert legacy["normalization"] == omc.NORMALIZATION_UNKNOWN + assert legacy["units"] == "unknown" + with pytest.raises(ValueError, match="normalization is unknown"): + omc.normalize_flux(legacy, 10.0, [2.0]) + converted = omc.normalize_flux( + legacy, + 10.0, + [2.0], + input_normalization=omc.NORMALIZATION_VOLUME_INTEGRATED_PER_SOURCE, + ) + target = Path(tmp) / "converted.csv" + omc.tally_to_csv(converted, target) + back = omc.tally_from_csv(target) + assert back["flux"] == [[20.0, 45.0]] + assert back["normalization"] == omc.NORMALIZATION_PHYSICAL + assert back["units"] == omc.UNITS_PHYSICAL + assert back["source_rate_s"] == 10.0 + assert back["rel_err"] == arrays["rel_err"] + + +def test_csv_v2_preserves_raw_metadata(tmp_path: Path) -> None: + arrays = _tally([[1.0, 2.0]]) + path = tmp_path / "raw.csv" + omc.tally_to_csv(arrays, path) + assert "nucleide-openmc-tally-v2" in path.read_text(encoding="utf-8") + back = omc.tally_from_csv(path) + assert back == arrays + + +# --------------------------------------------------------------------------- +# W2: shared photon source contract + + +def test_photon_source_totals_density_and_joint_probabilities() -> None: + source = _source() + assert source["n_voxels"] == 2 + assert source["n_groups"] == 2 + assert source["total_photons_per_s"] == pytest.approx(400.0) + assert source["voxel_totals_photons_per_s"] == pytest.approx([100.0, 300.0]) + assert source["group_totals_photons_per_s"] == pytest.approx([100.0, 300.0]) + assert r2s.source_density(source) == [[100.0, 0.0], [0.0, 300.0]] + assert r2s.source_probabilities(source) == [[0.25, 0.0], [0.0, 0.75]] + report = r2s.source_report(source) + assert report["valid"] is True + codes = [issue["code"] for issue in report["issues"]] + assert "source-assumption-uniform-within-bin" in codes + assert "source-assumption-uniform-within-voxel" in codes + + +def test_photon_source_unequal_volumes_and_zero_voxel() -> None: + source = _source( + [[100.0, 0.0], [0.0, 300.0]], + volumes=[1.0, 3.0], + ) + assert r2s.source_density(source) == [[100.0, 0.0], [0.0, 100.0]] + # A zero-source voxel is valid inside a nonzero source. + zero_voxel = _source([[100.0, 0.0], [0.0, 0.0]]) + assert zero_voxel["voxel_totals_photons_per_s"] == pytest.approx([100.0, 0.0]) + assert r2s.source_probabilities(zero_voxel) == [[1.0, 0.0], [0.0, 0.0]] + + +def test_all_zero_source_is_data_but_not_a_distribution() -> None: + source = _source([[0.0, 0.0], [0.0, 0.0]]) + assert source["total_photons_per_s"] == 0.0 + assert r2s.source_report(source)["valid"] is True + with pytest.raises(ValueError): + r2s.source_probabilities(source) + + +def test_sparse_group_export_fills_omitted_bins_with_zero() -> None: + full_edges = [0.0, 1.0, 2.0, 3.0, 4.0] + source = r2s.photon_source_exported( + [1, 1, 1], + [0.0, 0.0, 0.0], + [1.0, 1.0, 1.0], + [1.0], + full_edges, + 0.0, + [1, 3], + [[5.0, 7.0]], + ) + assert source["strengths_photons_per_s"] == [[0.0, 5.0, 0.0, 7.0]] + assert source["total_photons_per_s"] == pytest.approx(12.0) + with pytest.raises(ValueError): + r2s.photon_source_exported( + [1, 1, 1], + [0.0, 0.0, 0.0], + [1.0, 1.0, 1.0], + [1.0], + full_edges, + 0.0, + [1, 1], + [[5.0, 7.0]], + ) + + +def test_source_report_flags_negative_strength() -> None: + source = _source() + with pytest.raises(ValueError): + r2s.photon_source( + source["mesh_shape"], + source["lower_left_cm"], + source["upper_right_cm"], + source["voxel_volumes_cm3"], + source["edges_ev"], + source["cooling_s"], + [[100.0, -1.0], [0.0, 300.0]], + ) + draft = dict(source) + draft["strengths_photons_per_s"] = [[100.0, -1.0], [0.0, 300.0]] + report = r2s.source_report(draft) + assert report["valid"] is False + assert any(issue["code"] == "source-strength-negative" for issue in report["issues"]) + + +def test_select_cooling_is_exact_and_order_preserving() -> None: + assert r2s.select_cooling([0.0, 3600.0, 7200.0], [7200.0, 0.0]) == [2, 0] + with pytest.raises(ValueError): + r2s.select_cooling([0.0, 3600.0], [3600.0, 3600.0]) + with pytest.raises(ValueError): + r2s.select_cooling([0.0, 3600.0], [3600.0000001]) + # Close but distinct offsets stay distinct. + assert r2s.select_cooling([3600.0, 3600.0000000000005], [3600.0000000000005]) == [1] + + +# --------------------------------------------------------------------------- +# W3: OpenMC adapter (fake 0.16.0 protocol) + + +class _FakeTabular: + def __init__(self, x: list[float], p: list[float], interpolation: str) -> None: + assert interpolation == "histogram" + self.x = list(x) + self.p = list(p) + self.interpolation = interpolation + + +class _FakeUniform: + def __init__(self, a: float, b: float) -> None: + self.a = a + self.b = b + + +class _FakeIndependentSource: + def __init__(self, *, energy: Any, strength: float, particle: str) -> None: + self.energy = energy + self.strength = strength + self.particle = particle + + +class _FakeMesh: + def __init__(self) -> None: + self.dimension: tuple[int, int, int] | None = None + self.lower_left: tuple[float, float, float] | None = None + self.upper_right: tuple[float, float, float] | None = None + + @property + def n_elements(self) -> int: + assert self.dimension is not None + return self.dimension[0] * self.dimension[1] * self.dimension[2] + + +class _FakeMeshSource: + def __init__(self, *, mesh: _FakeMesh, sources: Any) -> None: + self.mesh = mesh + # OpenMC 0.16.0 flattens multidimensional arrays in Fortran order. + flat = [] + assert mesh.dimension is not None + nx, ny, nz = mesh.dimension + for k in range(nz): + for j in range(ny): + for i in range(nx): + flat.append(sources[i][j][k]) + self.sources = flat + self.strength = sum(src.strength for src in flat) + + +def _install_fake_openmc(monkeypatch: pytest.MonkeyPatch) -> None: + fake = ModuleType("openmc") + fake.RegularMesh = _FakeMesh # type: ignore[attr-defined] + fake.IndependentSource = _FakeIndependentSource # type: ignore[attr-defined] + fake.MeshSource = _FakeMeshSource # type: ignore[attr-defined] + fake.__version__ = "0.16.0" # type: ignore[attr-defined] + stats = ModuleType("openmc.stats") + stats.Tabular = _FakeTabular # type: ignore[attr-defined] + stats.Uniform = _FakeUniform # type: ignore[attr-defined] + fake.stats = stats # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "openmc", fake) + monkeypatch.setitem(sys.modules, "openmc.stats", stats) + + +def test_mesh_source_maps_2x3x2_cells_in_c_order(monkeypatch: pytest.MonkeyPatch) -> None: + _install_fake_openmc(monkeypatch) + strengths = [[float(100 + i), 1.0] for i in range(12)] + source = _source( + strengths, + mesh_shape=[2, 3, 2], + volumes=[1.0] * 12, + edges=[0.0, 1.0, 2.0], + ) + converted = omc.mesh_source(source) + # Fake MeshSource stores native OpenMC order (x fastest, then y, then z). + for i in range(2): + for j in range(3): + for k in range(2): + c_order = (i * 3 + j) * 2 + k + native = i + 2 * (j + 3 * k) + assert converted.sources[native].strength == pytest.approx(sum(strengths[c_order])) + assert converted.mesh.dimension == (2, 3, 2) + + +def test_mesh_source_energy_pdf_is_per_ev(monkeypatch: pytest.MonkeyPatch) -> None: + _install_fake_openmc(monkeypatch) + source = _source( + [[100.0, 0.0], [0.0, 300.0]], + edges=[0.0, 2.0, 10.0], + volumes=[1.0, 1.0], + ) + converted = omc.mesh_source(source) + first = converted.sources[0].energy + assert isinstance(first, _FakeTabular) + # Group strength / (voxel total * width): 100/(100*2), 0. + assert first.p == pytest.approx([0.5, 0.0]) + second = converted.sources[1].energy + assert second.p == pytest.approx([0.0, 300.0 / (300.0 * 8.0)]) + + +def test_mesh_source_zero_voxel_gets_zero_strength_uniform(monkeypatch: pytest.MonkeyPatch) -> None: + _install_fake_openmc(monkeypatch) + source = _source([[100.0, 0.0], [0.0, 0.0]]) + converted = omc.mesh_source(source) + assert converted.sources[0].strength == pytest.approx(100.0) + assert converted.sources[1].strength == 0.0 + assert isinstance(converted.sources[1].energy, _FakeUniform) + + +def test_mesh_source_rejects_nonregular_volumes(monkeypatch: pytest.MonkeyPatch) -> None: + _install_fake_openmc(monkeypatch) + source = _source(volumes=[1.0, 2.0]) + with pytest.raises(ValueError, match="regular-mesh cell volume"): + omc.mesh_source(source) + + +# --------------------------------------------------------------------------- +# W4b: reproducibility manifest + + +def test_manifest_roundtrip_hash_and_tamper(tmp_path: Path) -> None: + source = _source() + input_file = tmp_path / "flux.csv" + input_file.write_text("raw\n", encoding="utf-8") + output_file = tmp_path / "source.xml" + output_file.write_text("\n", encoding="utf-8") + manifest = omc.source_manifest( + source=source, + input_files=[input_file], + output_files=[output_file], + external_solver="openmc", + external_version="0.16.0", + evaluated_library="caller-library-v1", + ) + path = tmp_path / "manifest.json" + omc.write_manifest(manifest, path) + first = path.read_bytes() + omc.write_manifest(omc.read_manifest(path), path) + assert path.read_bytes() == first + parsed = omc.read_manifest(path) + assert parsed["source"]["energy_grid_sha256"] == manifest["source"]["energy_grid_sha256"] + assert parsed["source"]["voxel_order"] == "c-order-(i,j,k)" + assert parsed["external"]["solver_version_source"] == "caller-supplied" + assert parsed["evaluated_library"]["hash"] is None + check = omc.verify_manifest(path) + assert check["ok"] is True and check["checked"] == 2 + output_file.write_text("\n", encoding="utf-8") + tampered = omc.verify_manifest(path) + assert tampered["ok"] is False + assert tampered["mismatches"][0]["path"].endswith("source.xml") + + +def test_manifest_missing_output_and_unknown_schema(tmp_path: Path) -> None: + source = _source() + manifest = omc.source_manifest( + source=source, + output_files=[tmp_path / "not-written.xml"], + ) + check = omc.verify_manifest(manifest, base_dir=tmp_path) + assert check["ok"] is False + assert check["missing"][0]["path"].endswith("not-written.xml") + with pytest.raises(ValueError, match="unknown manifest schema"): + omc.write_manifest({"schema": "other"}, tmp_path / "bad.json") + with pytest.raises(ValueError, match="not JSON-serializable"): + bad = dict(manifest) + bad["source"] = dict(bad["source"]) + bad["source"]["total_photons_per_s"] = float("nan") + omc.write_manifest(bad, tmp_path / "bad-nan.json") + + +# --------------------------------------------------------------------------- +# W5: cooling-time batch export + + +def _writer(source: dict[str, Any], path: Path) -> None: + path.write_text( + json.dumps({"cooling_s": source["cooling_s"], "total": source["total_photons_per_s"]}), + encoding="utf-8", + ) + + +def test_cooling_batch_exports_distinct_times_and_manifest(tmp_path: Path) -> None: + zero = _source(cooling_s=0.0) + hour = _source([[7.0, 11.0], [13.0, 17.0]], cooling_s=3600.0) + batch = omc.export_cooling_batch([hour, zero], [0.0, 3600.0], tmp_path, writer=_writer) + assert batch["manifest"]["status"] == "complete" + assert [entry["time_s"] for entry in batch["outputs"]] == [0.0, 3600.0] + assert [entry["total_photons_per_s"] for entry in batch["outputs"]] == pytest.approx( + [400.0, 48.0] + ) + for entry in batch["outputs"]: + assert (tmp_path / entry["path"]).is_file() + manifest = omc.read_manifest(tmp_path / "batch-manifest.json") + assert manifest["schema"] == "nucleide-source-batch-v1" + assert manifest["units"] == "photons/s" + assert manifest["voxel_order"] == "c-order-(i,j,k)" + assert manifest["outputs"][0]["validation"]["valid"] is True + assert len(manifest["outputs"][0]["energy_grid_sha256"]) == 64 + assert omc.verify_manifest(manifest, base_dir=tmp_path)["ok"] is True + + +def test_cooling_batch_rejects_duplicates_missing_and_existing(tmp_path: Path) -> None: + zero = _source(cooling_s=0.0) + hour = _source(cooling_s=3600.0) + with pytest.raises(ValueError): + omc.export_cooling_batch([zero, hour], [3600.0, 3600.0], tmp_path, writer=_writer) + with pytest.raises(ValueError): + omc.export_cooling_batch([zero], [1.0], tmp_path, writer=_writer) + omc.export_cooling_batch([zero], [0.0], tmp_path, writer=_writer) + with pytest.raises(FileExistsError): + omc.export_cooling_batch([zero], [0.0], tmp_path, writer=_writer) + # Distinct names for close-but-distinct offsets. + close_a = _source(cooling_s=3600.0) + close_b = _source(cooling_s=3600.0000000000005) + batch = omc.export_cooling_batch( + [close_a, close_b], + [3600.0, 3600.0000000000005], + tmp_path / "close", + writer=_writer, + ) + assert len({entry["path"] for entry in batch["outputs"]}) == 2 + + +def test_cooling_batch_zero_policy_and_partial_failure(tmp_path: Path) -> None: + zero = _source([[0.0, 0.0], [0.0, 0.0]], cooling_s=0.0) + live = _source(cooling_s=3600.0) + with pytest.raises(ValueError, match="zero total"): + omc.export_cooling_batch([zero], [0.0], tmp_path, writer=_writer) + skipped = omc.export_cooling_batch( + [zero, live], [0.0, 3600.0], tmp_path, writer=_writer, skip_zero=True + ) + assert skipped["skipped"] == [{"time_s": 0.0, "reason": "all-zero-source"}] + assert [entry["time_s"] for entry in skipped["outputs"]] == [3600.0] + + def failing_writer(source: dict[str, Any], path: Path) -> None: + raise OSError("simulated disk failure") + + with pytest.raises(omc.BatchExportError) as caught: + omc.export_cooling_batch([live], [3600.0], tmp_path / "fail", writer=failing_writer) + assert caught.value.partial["status"] == "partial" + assert caught.value.partial["outputs"] == [] + assert not (tmp_path / "fail" / "batch-manifest.json").exists() diff --git a/validation/AGENTS.md b/validation/AGENTS.md index a04e06a..24a196b 100644 --- a/validation/AGENTS.md +++ b/validation/AGENTS.md @@ -54,8 +54,9 @@ reference tally (`magic_tally.txt`), and the committed results document. - F5 recombination uses atomic-unit conversion with exact SI Avogadro constant, the two-reactant coefficient `Kr/(2 NA)`, quadratic elements, independent three-level mesh/time refinement and exported-history mass - balance. Preserve F1–F4 gates. Missing FESTIM is SKIP; installed/broken oracle environments and - configured solver/export errors fail for every leg. Unconverged F5 refinement is INCONCLUSIVE + balance. Preserve F1–F4 gates. Missing FESTIM is SKIP and a skip run must + not overwrite the committed probe results; installed/broken oracle + environments and configured solver/export errors fail for every leg. Unconverged F5 refinement is INCONCLUSIVE and exits nonzero. Image/package pins and execution limits live in `validation/README.md`; never claim an unexecuted F5 pass. Resolve startup before nominal time-step refinement. Reduced-run caches under `.cache/` @@ -68,10 +69,28 @@ reference tally (`magic_tally.txt`), and the committed results document. fixed throughout a probe invocation. Recompute acceptance gates on reuse. Prefer an installed rebuilt release wheel; bootstrap a checkout extension only when the package is absent. + F6 adds the single-layer McNabb-Foster trap plus recombination outlet: + identical scalar-temperature parameters on both sides, explicit + molar/atomic conversion for concentrations, fluxes, inventories and the + second-order trap constant (`p0` unchanged), a factor-of-two check for + the two identical surface reactants, mobile and trapped inventory + histories, bracketed FESTIM sampling (never extrapolation), and + independent space/time refinement plus a mobile-plus-trapped balance. + Preserve F1-F5 gates; F6 cache entries under `.cache/f6-runs` include + all F6 parameters and the same runtime identity. - `actinv_handoff_probe.py` is an optional synthetic exchange check, separate from `*_vs_*.py` physics comparisons. Require an explicit hash-pinned CLI, bound the leaf export process wait, retain JSON receipts under `.cache/`, and never download evaluated data or claim an activation solve from it. +- `openmc_handoff_probe.py` is a probe-only check of the pinned OpenMC 0.16.0 + handoff contract: exact-version gate, source-inspected tally normalization, + C-order/Fortran-order mesh mapping, histogram density semantics, XML + roundtrip, seeded joint-source sampling, and a vacuum track-length tally at + two source strengths that pins the integrated/rate-scaled convention. It may + create a placeholder `cross_sections.xml` under its temp directory solely to + initialize OpenMC; it must not read evaluated data or run interacting + transport. Record the probe's JSON output and never turn source sampling or + the void tally into a physics, transport or dose claim. - Fresh ACTINV activation comparisons execute the source-pinned external example separately from the synthetic probe. Retain original/compatible script hashes and diff, verified data hashes, compiled-extension identity, diff --git a/validation/README.md b/validation/README.md index 833450d..33c59fe 100644 --- a/validation/README.md +++ b/validation/README.md @@ -21,6 +21,7 @@ committed `results.md` holds the measured numbers that the paper quotes. | `unfold_vs_analytic.py` | SAND-II neutron spectrum unfolding: synthetic forward-fold round-trips + IRDFF-II analytical benchmark shapes (published facts, cited; no external unfolding oracle exists) | | `equilib_vs_desc.py` | Equilibrium data readers: synthetic classic-`wout` magic/format/Jacobian gates + `&INDATA` grammar gates (always run) with DESC/simsopt container probes (loud SKIP outside) | | `actinv_handoff_probe.py` | Optional pinned ACTINV CLI synthetic export/readback, with binary/source hashes and conservation receipts; no activation solve | +| `openmc_handoff_probe.py` | Pinned OpenMC 0.16.0 source/tally normalization, C-to-F mesh ordering, histogram-density, XML roundtrip and seeded joint-source sampling probe; no transport run | | `tritium_vs_festim.py` | 1D tritium kernel parity probe vs FESTIM 2.1 (black-box; probe-only image; see probe section below) | | `timings.py` | Coarse wall-time comparisons (Python overhead included) | | `make_figures.py` | Generates the paper figures in `figures/` from the JSON reports | @@ -173,6 +174,31 @@ against hardcoded NIST NCNR anchors, and checks decay energies against hardcoded chain/ENDF-derived spot values; `depletion_vs_openmc.py` builds its synthetic A→B→C chain inline in a temp file (no new fixtures). +## OpenMC activation-to-transport probe + +`openmc_handoff_probe.py` runs in the canonical validation image and records +the OpenMC 0.16.0 conventions behind the source handoff: regular fixed-source +tallies divide by `settings::n_particles` and multiply by the sum of the +configured source strengths; `MeshSource` ravels multidimensional arrays in +Fortran order (`openmc_sources[i + nx*j + nx*ny*k]` for the bridge's +`(i*ny + j)*nz + k` C-order); `openmc.stats.Tabular(..., interpolation= +"histogram")` takes differential density per eV; and `Settings.export_to_xml` +/ `from_xml` round-trip the mesh and source strengths. A child process samples the joint +source distribution with a fixed seed and a predeclared tolerance. A second +child runs a vacuum sphere with a centered point source at strengths 1 and 10 +to confirm that the track-length flux tally is volume-integrated and scaled by +the total source strength, not volume-averaged. The probe writes a placeholder +`cross_sections.xml` only to let OpenMC initialize; it reads no evaluated data +and runs no interacting transport. + +```bash +docker run --rm --cpus=2 --memory=6g --memory-swap=6g \ + -v "$PWD/validation:/work:ro" -w /work \ + localhost/nucleide-validation:latest python openmc_handoff_probe.py +``` + +It emits one JSON document and exits nonzero if any check fails. + ## Optional ACTINV synthetic exchange probe `actinv_handoff_probe.py` checks the released ACTINV 1.7.2 Linux exporter @@ -300,7 +326,8 @@ docker run --rm --memory=6g --memory-swap=6g --pids-limit=128 --cpus=2 \ ``` Progression: F1 trap-free Dirichlet-Dirichlet → F2 one McNabb-Foster trap -→ F3 Sieverts ends → F4 two-layer stack → F5 trap-free recombination outlet. +→ F3 Sieverts ends → F4 two-layer stack → F5 trap-free recombination outlet +→ F6 one McNabb-Foster trap plus that recombination outlet. F1–F4 gates: J_ss 2%, J(t) 3% above a `1e-3·J_ss` floor excluding t < 0.2·t_lag, t_lag 5%, steady c(x) 2% max-norm; each side self-converges to < 1/3 of its gate first, otherwise the leg is inconclusive, never a @@ -364,6 +391,36 @@ the new identity. Acceptance verdicts are recomputed on reuse. Adding the probe does not establish a measured F5 pass: regenerate the report in the pinned image before quoting its results. +F6 combines one McNabb-Foster trap with the F5 recombination outlet on the +same single-layer, scalar-500 K slab. It uses the F2 trap +(`k0=0.5 m³/(mol s)`, `p0=0.5 s⁻¹`, `N=2 mol/m³`), the F5 outlet +(`Kr=1e-6 m⁴/(mol s)`) and zero initial mobile/trapped loads. The Oriani +effective lag `L²/(6D_eff)=500 s` sets samples at `t/t_lag_eff = +{0.2,0.5,1,2,5,10}` (100–5000 s); no closed-form time-lag gate is used. +FESTIM receives atomic units: multiply concentrations, fluxes and +inventories by exact SI `NA`; divide the second-order trap constant by `NA` +(`p0` unchanged) and use `N_atom=NA*N_mol`, so `N*K` and the Langmuir load +are invariant. The outlet uses two identical reactants, so FESTIM applies +two partial fluxes; `k_r0=Kr/(2 NA)` gives the molar flux `Kr*c_mol²`. +The exported FESTIM face concentration checks that factor of two and its +trapped profile checks the distinct-reactant Langmuir equilibrium. Space +refinement is 50/100/200 cells at `dt=0.25 s`; time refinement is +`dt=0.5/0.25/0.125 s` at 200 cells, separately in each code. Every F6 +refinement change must be below one third of its gate (J(t) 3% above a +`1e-3 J_ss` floor, mobile/trapped inventory and profile histories 2%, +FESTIM reaction/Langmuir checks 2%), otherwise F6 is INCONCLUSIVE and the +script exits nonzero. The mass balance compares the mobile-plus-trapped +inventory change with integrated inlet minus outlet flux on the actual +exported grid (relative residual at most `1e-3`, stride-2/4 quadrature +changes below `1e-3/3`). Requested FESTIM times are sampled only between +exported brackets; a missing bracket or short history fails instead of +extrapolating. F6 reuses the pinned image and package set above; its cache +entries under `.cache/f6-runs` include the actual image ID, native-library +hashes, package versions, source/extension hashes and all F6 parameters. +A full F6 report is valid only after the five-level probe runs in that +pinned image. Running the probe without FESTIM prints a named SKIP and leaves +the committed `validation/results/tritium_festim.json` untouched. + ## Parser oracle notes `parsers_vs_refs.py` cross-checks Nucleide's readers against independent diff --git a/validation/openmc_handoff_probe.py b/validation/openmc_handoff_probe.py new file mode 100644 index 0000000..5a04908 --- /dev/null +++ b/validation/openmc_handoff_probe.py @@ -0,0 +1,1703 @@ +#!/usr/bin/env python3 +"""OpenMC 0.16.0 activation-to-transport handoff probe (no transport run). + +This probe answers seven questions with the OpenMC package installed in the +validation image: + +1. Is the exact expected OpenMC version installed? +2. How does OpenMC 0.16.0 normalize regular tally results, and what role does + ``SourceBase.strength`` / ``MeshSource.strength`` play? A vacuum-sphere + fixed-source run at strengths 1 and 10 checks the observed scale directly + without interacting material or evaluated data. +3. Does a C-order ``[nx][ny][nz]`` source array reach the expected + ``(i, j, k)`` mesh element when passed to ``openmc.MeshSource``? +4. Does an OpenMC histogram distribution interpret ``p`` as a differential + density (per unit energy), not as an integrated bin strength? +5. Do mesh id, source count, strengths, energy edges and source ordering + survive ``Settings.export_to_xml`` / ``Settings.from_xml``? +6. Does real OpenMC source sampling reproduce the exact joint voxel/group + probabilities, using a fixed seed and a predeclared tolerance? + +The script runs no interacting transport calculation. Source sampling is +isolated in a child process and uses ``openmc.Model.sample_external_source``, +which starts OpenMC in volume-calculation mode. A second child runs a vacuum +sphere with a centered point source and a cell flux tally at two source +strengths; this checks the volume-integrated, source-rate-scaled normalization +without cross sections or material interactions. OpenMC still requires a +cross-sections XML file to initialize; the children write a placeholder +containing one nonexistent library entry. No evaluated data are read or +downloaded, and only the vacuum track-length tally is produced. The +placeholder is an initialization shim, not physics input. + +Output is a single JSON document on stdout. Human-readable failures and +OpenMC warnings go to stderr. Exit status is 0 only when every check passes. +""" + +from __future__ import annotations + +import hashlib +import importlib.metadata +import inspect +import json +import math +import os +import re +import subprocess +import sys +import tempfile +import traceback +import warnings +from pathlib import Path +from typing import Any + +EXPECTED_OPENMC = "0.16.0" +PROBE_NAME = "openmc_handoff_probe" + +# Fixed, predeclared sampling contract. +PRN_SEED = 20261116 +JOINT_SAMPLES = 200_000 +JOINT_TOLERANCE = 0.01 +ORDER_SAMPLES = 120_000 +ZERO_SAMPLES = 20_000 + +# Void fixed-source normalization check: an isotropic point source at the +# center of a vacuum sphere has exactly one track of length R per source +# particle, so the volume-integrated flux tally mean is R * total strength. +VOID_RADIUS = 10.0 +VOID_STRENGTHS = (1.0, 10.0) +VOID_PARTICLES = 2_000 +VOID_SEED = 20261116 + +# Two-voxel, two-group scenario from the transport handoff plan. +JOINT_EDGES = (1.0, 2.0, 10.0) +JOINT_VOXEL_STRENGTHS = (100.0, 300.0) +JOINT_INTEGRATED = ((1.0, 0.0), (0.0, 1.0)) +JOINT_EXACT = ((0.25, 0.0), (0.0, 0.75)) + +# 2 x 3 x 2 ordering mesh. Every cell gets a unique strength and a unique +# non-overlapping energy band so sampled energies reveal the selected cell. +ORDER_DIMENSION = (2, 3, 2) +ORDER_LOWER = (0.0, 0.0, 0.0) +ORDER_UPPER = (2.0, 3.0, 2.0) +ORDER_BAND_WIDTH = 10.0 +ORDER_BAND_LOW = 1.0 +ORDER_BAND_SPAN = 4.0 + +# Irregular three-bin histogram with a zero-strength middle bin. +HIST_EDGES = (1.0, 2.0, 5.0, 10.0) +HIST_INTEGRATED = (0.25, 0.0, 0.75) + + +def histogram_density(edges: tuple[float, ...], integrated: tuple[float, ...]) -> list[float]: + """Convert integrated bin strengths to differential densities per unit x.""" + if len(integrated) != len(edges) - 1: + raise ValueError("integrated strengths must match the number of bins") + return [ + strength / (hi - lo) + for strength, lo, hi in zip(integrated, edges[:-1], edges[1:], strict=True) + ] + + +HIST_DENSITIES = tuple(histogram_density(HIST_EDGES, HIST_INTEGRATED)) + + +def sha256_file(path: Path) -> str: + """Hash a file without loading the whole file at once.""" + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def find_openmc_source_dir() -> tuple[Path | None, str]: + """Find the OpenMC source tree that the installed package was built from.""" + candidates: list[tuple[Path, str]] = [] + env_dir = os.environ.get("OPENMC_SOURCE_DIR") + if env_dir: + candidates.append((Path(env_dir), "OPENMC_SOURCE_DIR")) + try: + distribution = importlib.metadata.distribution("openmc") + direct_url = json.loads(distribution.read_text("direct_url.json")) + url = direct_url.get("url", "") + if url.startswith("file://"): + candidates.append((Path(url.removeprefix("file://")), "direct_url.json")) + except Exception: + pass + candidates.extend( + [ + (Path("/opt/openmc"), "default /opt/openmc"), + (Path("/usr/local/src/openmc"), "default /usr/local/src/openmc"), + ] + ) + for candidate, origin in candidates: + if (candidate / "src/tallies/tally.cpp").is_file(): + return candidate.resolve(), origin + return None, "not found" + + +def find_pattern(text: str, pattern: str, context: int = 2) -> dict[str, Any]: + """Locate a regex match and return its line number and a small context window.""" + match = re.search(pattern, text, flags=re.MULTILINE) + if match is None: + return {"found": False, "pattern": pattern} + start_line = text.count("\n", 0, match.start()) + 1 + lines = text.splitlines() + lo = max(1, start_line - context) + hi = min(len(lines), start_line + context) + return { + "found": True, + "pattern": pattern, + "line": start_line, + "match": match.group(0).strip(), + "context": "\n".join(lines[lo - 1 : hi]), + } + + +def collect_source_provenance(source_dir: Path | None) -> dict[str, Any]: + """Inspect the installed OpenMC C++/docs source for normalization and sampling rules.""" + if source_dir is None: + return {"available": False, "reason": "OpenMC source tree not found"} + + files = { + "tally_cpp": source_dir / "src/tallies/tally.cpp", + "settings_cpp": source_dir / "src/settings.cpp", + "distribution_cpp": source_dir / "src/distribution.cpp", + "source_cpp": source_dir / "src/source.cpp", + "simulation_cpp": source_dir / "src/simulation.cpp", + "tallies_rst": source_dir / "docs/source/usersguide/tallies.rst", + "settings_rst": source_dir / "docs/source/usersguide/settings.rst", + "io_settings_rst": source_dir / "docs/source/io_formats/settings.rst", + } + missing = [str(path) for path in files.values() if not path.is_file()] + if missing: + return {"available": False, "reason": "missing source files", "missing": missing} + + patterns: dict[str, list[tuple[str, str]]] = { + "tally_cpp": [ + ("total_source", r"double total_source = 0\.0;"), + ( + "contributing_particles", + r"double contributing_particles = settings::reduce_tallies", + ), + ( + "regular_norm", + r"double norm =\s*total_source / " + r"\(contributing_particles \* settings::gen_per_batch\);", + ), + ("regular_accumulate", r"double val = results_\(i, j, TallyResult::VALUE\) \* norm;"), + ( + "global_total_weight", + r"double val = gt\(i, TallyResult::VALUE\) / simulation::total_weight;", + ), + ], + "settings_cpp": [ + ("source_strengths_push", r"source_strengths\.push_back\(s->strength\(\)\);"), + ( + "external_sources_probability", + r"model::external_sources_probability\.assign\(source_strengths\);", + ), + ], + "distribution_cpp": [ + ( + "discrete_integral", + r"integral_ = std::accumulate\(prob_\.begin\(\), prob_\.end\(\), 0\.0\);", + ), + ("discrete_normalize", r"p_i /= integral_;"), + ], + "source_cpp": [ + ( + "mesh_strengths", + r"strengths\.push_back\(sources_\.back\(\)->strength\(\)\);", + ), + ( + "mesh_spatial", + r"space_ = std::make_unique\(mesh_idx, strengths\);", + ), + ( + "mesh_sample_element", + r"int32_t element = space_->sample_element_index\(seed\);", + ), + ], + "simulation_cpp": [ + ("total_weight_reset", r"simulation::total_weight = 0\.0;"), + ("total_weight_accum", r"simulation::total_weight \+= p\.wgt\(\);"), + ], + "tallies_rst": [ + ( + "per_source_particle", + r"all tally scores are normalized per\s+source particle simulated", + ), + ( + "strength_as_unit_conversion", + r"the tally results just need to be multipled by 10\\?\s*" + r":sup:`4`\. This can either be done manually or using the\s+" + r":attr:`openmc\.SourceBase\.strength` attribute\.", + ), + ], + "settings_rst": [ + ( + "relative_strength", + r"attribute that indicates the relative strength of a source distribution", + ), + ( + "uniform_sampling_weight", + r"applying the source strength as a weight on the sampled source particles", + ), + ], + "io_settings_rst": [ + ( + "mesh_element_relative_strength", + r"relative source strength of each mesh element", + ), + ], + } + + text_by_name: dict[str, str] = {} + provenance: dict[str, Any] = {"available": True, "source_dir": str(source_dir)} + for name, path in files.items(): + text = path.read_text(encoding="utf-8", errors="replace") + text_by_name[name] = text + provenance[name] = { + "path": str(path), + "sha256": sha256_file(path), + "patterns": {label: find_pattern(text, pattern) for label, pattern in patterns[name]}, + } + + # Compute the exact regular-tally normalization context without relying on + # the literal string "total_weight" appearing anywhere in the file. + tally_text = text_by_name["tally_cpp"] + regular_norm_match = re.search( + r"double norm =\s*total_source / " + r"\(contributing_particles \* settings::gen_per_batch\);", + tally_text, + ) + regular_norm_window = "" + if regular_norm_match is not None: + start = max(0, regular_norm_match.start() - 800) + end = min(len(tally_text), regular_norm_match.end() + 800) + regular_norm_window = tally_text[start:end] + provenance["derived"] = { + "regular_norm_uses_simulation_total_weight": "simulation::total_weight" + in regular_norm_window, + "regular_norm_uses_n_particles": "contributing_particles" in regular_norm_window + and "settings::gen_per_batch" in regular_norm_window + and "settings::n_particles" + in provenance["tally_cpp"]["patterns"]["contributing_particles"].get("context", ""), + "regular_norm_scales_by_total_source": "total_source" in regular_norm_window + and "external_sources_probability" in text_by_name["tally_cpp"], + "mesh_source_strength_is_sum": "sum(s.strength for s in self.sources)" + in inspect.getsource(__import__("openmc").MeshSource.strength.fget), + } + return provenance + + +def collect_python_provenance(openmc: Any) -> dict[str, Any]: + """Record the exact installed Python API lines that define the bridge contract.""" + targets = { + "mesh_source_sources_setter": openmc.MeshSource.sources.fset, + "mesh_source_strength_getter": openmc.MeshSource.strength.fget, + "mesh_source_set_total_strength": openmc.MeshSource.set_total_strength, + "source_base_strength_setter": openmc.SourceBase.strength.fset, + "regular_mesh_indices": openmc.RegularMesh.indices.fget, + "regular_mesh_get_indices_at_coords": openmc.RegularMesh.get_indices_at_coords, + "tabular_cdf": openmc.stats.Tabular.cdf, + "tabular_integral": openmc.stats.Tabular.integral, + } + result: dict[str, Any] = {} + for name, target in targets.items(): + try: + lines, start = inspect.getsourcelines(target) + result[name] = { + "file": inspect.getsourcefile(target), + "line": start, + "snippet": "".join(lines), + } + except (OSError, TypeError) as error: + result[name] = {"error": str(error)} + result["histogram_class_available"] = hasattr(openmc.stats, "Histogram") + result["mesh_source_doc"] = inspect.getdoc(openmc.MeshSource) + return result + + +def build_ordering_mesh(openmc: Any, mesh_id: int) -> tuple[Any, list[list[list[Any]]], Any]: + """Build a 2 x 3 x 2 mesh with a unique strength and energy band per cell.""" + nx, ny, nz = ORDER_DIMENSION + mesh = openmc.RegularMesh() + mesh.id = mesh_id + mesh.dimension = ORDER_DIMENSION + mesh.lower_left = ORDER_LOWER + mesh.upper_right = ORDER_UPPER + + sources_c: list[list[list[Any]]] = [] + for i in range(nx): + plane: list[list[Any]] = [] + for j in range(ny): + column: list[Any] = [] + for k in range(nz): + c_index = (i * ny + j) * nz + k + low = ORDER_BAND_LOW + ORDER_BAND_WIDTH * c_index + energy = openmc.stats.Uniform(low, low + ORDER_BAND_SPAN) + source = openmc.IndependentSource( + energy=energy, + strength=float(c_index + 1), + particle="photon", + ) + column.append(source) + plane.append(column) + sources_c.append(plane) + + mesh_source = openmc.MeshSource(mesh, sources_c) + return mesh, sources_c, mesh_source + + +def build_joint_mesh(openmc: Any, mesh_id: int) -> tuple[Any, Any]: + """Build the two-voxel, two-group joint scenario with zero cross bins.""" + mesh = openmc.RegularMesh() + mesh.id = mesh_id + mesh.dimension = (2, 1, 1) + mesh.lower_left = (0.0, 0.0, 0.0) + mesh.upper_right = (2.0, 1.0, 1.0) + + sources = [] + for voxel, strength in enumerate(JOINT_VOXEL_STRENGTHS): + densities = histogram_density(JOINT_EDGES, JOINT_INTEGRATED[voxel]) + energy = openmc.stats.Tabular( + list(JOINT_EDGES), + densities, + interpolation="histogram", + ) + sources.append( + openmc.IndependentSource(energy=energy, strength=strength, particle="photon") + ) + return mesh, openmc.MeshSource(mesh, sources) + + +def build_histogram_case(openmc: Any) -> dict[str, Any]: + """Verify histogram density semantics, a zero bin, and a zero-strength voxel.""" + distribution = openmc.stats.Tabular( + list(HIST_EDGES), + list(HIST_DENSITIES), + interpolation="histogram", + ) + wrong_control = openmc.stats.Tabular( + list(HIST_EDGES), + list(HIST_INTEGRATED), + interpolation="histogram", + ) + all_zero = openmc.stats.Tabular( + list(HIST_EDGES), + [0.0, 0.0, 0.0], + interpolation="histogram", + ) + + midpoints = [0.5 * (lo + hi) for lo, hi in zip(HIST_EDGES[:-1], HIST_EDGES[1:], strict=True)] + widths = [hi - lo for lo, hi in zip(HIST_EDGES[:-1], HIST_EDGES[1:], strict=True)] + cdf = distribution.cdf().tolist() + integral = float(distribution.integral()) + zero_density = float(distribution.p[1]) + + zero_strength_source = openmc.IndependentSource( + energy=all_zero, strength=0.0, particle="photon" + ) + mesh = openmc.RegularMesh() + mesh.id = 19003 + mesh.dimension = (2, 1, 1) + mesh.lower_left = (0.0, 0.0, 0.0) + mesh.upper_right = (2.0, 1.0, 1.0) + nonzero_source = openmc.IndependentSource(energy=distribution, strength=1.0, particle="photon") + zero_voxel_mesh_source = openmc.MeshSource(mesh, [nonzero_source, zero_strength_source]) + + return { + "histogram_class_available": hasattr(openmc.stats, "Histogram"), + "supported_equivalent": "openmc.stats.Tabular(..., interpolation='histogram')", + "edges_eV": list(HIST_EDGES), + "bin_widths_eV": widths, + "integrated_strengths": list(HIST_INTEGRATED), + "expected_density_pdf_per_eV": list(HIST_DENSITIES), + "readback_x": distribution.x.tolist(), + "readback_p": distribution.p.tolist(), + "interpolation": distribution.interpolation, + "cdf": cdf, + "integral": integral, + "evaluate_at_bin_midpoints": [float(distribution.evaluate(x)) for x in midpoints], + "zero_bin": { + "index": 1, + "width_eV": widths[1], + "integrated_strength": HIST_INTEGRATED[1], + "density": zero_density, + "evaluate_midpoint": float(distribution.evaluate(midpoints[1])), + "cdf_flat": cdf[1] == cdf[2], + }, + "wrong_control_integral": float(wrong_control.integral()), + "wrong_control_note": ( + "Passing integrated strengths as histogram densities gives integral " + f"{float(wrong_control.integral()):.6g}, not 1" + ), + "all_zero_distribution": { + "integral": float(all_zero.integral()), + "cdf": all_zero.cdf().tolist(), + "pdf_valid": float(all_zero.integral()) > 0.0, + "note": "A zero distribution is data, not a samplable PDF", + }, + "zero_strength_voxel": { + "source_strength": float(zero_strength_source.strength), + "mesh_source_total_strength": float(zero_voxel_mesh_source.strength), + "element_strengths": [ + float(source.strength) for source in zero_voxel_mesh_source.sources + ], + "relative_probabilities": [ + float(source.strength) / float(zero_voxel_mesh_source.strength) + for source in zero_voxel_mesh_source.sources + ], + }, + } + + +def check_ordering_objects( + openmc: Any, mesh: Any, sources_c: list[list[list[Any]]], mesh_source: Any +) -> dict[str, Any]: + """Verify object-level Fortran-order flattening and 0-based coordinate lookup.""" + nx, ny, nz = ORDER_DIMENSION + flat_sources = mesh_source.sources + mapping_ok = True + strengths_f_order: list[float] = [0.0] * int(mesh_source.sources.size) + bands_f_order: list[float] = [0.0] * int(mesh_source.sources.size) + for i in range(nx): + for j in range(ny): + for k in range(nz): + f_index = i + nx * j + nx * ny * k + source = sources_c[i][j][k] + if flat_sources[f_index] is not source: + mapping_ok = False + strengths_f_order[f_index] = float(flat_sources[f_index].strength) + bands_f_order[f_index] = float(flat_sources[f_index].energy.a) + + expected_indices = [ + (i + 1, j + 1, k + 1) for k in range(nz) for j in range(ny) for i in range(nx) + ] + indices_match = list(mesh.indices) == expected_indices + + spacing = [ + (hi - lo) / n for lo, hi, n in zip(ORDER_LOWER, ORDER_UPPER, ORDER_DIMENSION, strict=True) + ] + coordinate_lookup_ok = True + coordinate_lookup_examples: list[dict[str, Any]] = [] + for i in range(nx): + for j in range(ny): + for k in range(nz): + center = ( + ORDER_LOWER[0] + (i + 0.5) * spacing[0], + ORDER_LOWER[1] + (j + 0.5) * spacing[1], + ORDER_LOWER[2] + (k + 0.5) * spacing[2], + ) + actual = mesh.get_indices_at_coords(center) + expected = (i, j, k) + if actual != expected: + coordinate_lookup_ok = False + if len(coordinate_lookup_examples) < 4: + coordinate_lookup_examples.append( + {"center": center, "get_indices_at_coords": actual} + ) + + return { + "mesh_id": int(mesh.id), + "dimension": list(mesh.dimension), + "n_elements": int(mesh.n_elements), + "source_count": int(flat_sources.size), + "source_strengths_f_order": strengths_f_order, + "source_energy_lower_edges_f_order": bands_f_order, + "mesh_source_total_strength": float(mesh_source.strength), + "expected_total_strength": float(sum(range(1, nx * ny * nz + 1))), + "object_mapping_fortran_order_ok": mapping_ok, + "regular_mesh_indices_are_1_based_fortran": indices_match, + "get_indices_at_coords_is_0_based": coordinate_lookup_ok, + "coordinate_lookup_examples": coordinate_lookup_examples, + "mapping_rule": { + "openmc_internal_flat_index": "i + nx*j + nx*ny*k (Fortran order, 0-based)", + "nucleide_c_order_flat_index": "(i*ny + j)*nz + k (C order, 0-based)", + "pass_c_order_array": ( + "reshape the C-ordered values to (nx, ny, nz) and pass that array; " + "OpenMC ravels it with order='F'" + ), + "pass_flat_list": ("openmc_sources[i + nx*j + nx*ny*k] = c_sources[(i*ny + j)*nz + k]"), + }, + } + + +def check_mesh_source_strength_normalization( + openmc: Any, mesh: Any, mesh_source: Any +) -> dict[str, Any]: + """Show that MeshSource strength is the sum and that normalizing scales children.""" + clone_sources = [] + for source in mesh_source.sources: + clone_sources.append( + openmc.IndependentSource( + energy=source.energy, + strength=float(source.strength), + particle="photon", + ) + ) + clone = openmc.MeshSource(mesh, clone_sources) + before = [float(source.strength) for source in clone.sources] + clone.normalize_source_strengths() + after = [float(source.strength) for source in clone.sources] + ratios_before = [value / sum(before) for value in before] + ratios_after = [value / sum(after) for value in after] + return { + "mesh_source_total_strength": float(mesh_source.strength), + "sum_of_element_strengths": float(sum(source.strength for source in mesh_source.sources)), + "before_normalization": before, + "after_normalize_source_strengths": after, + "after_total_strength": float(clone.strength), + "relative_selection_preserved": all( + math.isclose(a, b, rel_tol=0.0, abs_tol=1e-12) + for a, b in zip(ratios_before, ratios_after, strict=True) + ), + "note": ( + "normalize_source_strengths() makes the total 1.0 (per-source-particle " + "tally convention); element ratios are unchanged" + ), + } + + +def read_settings_silencing_mesh_id_warning(openmc: Any, path: Path) -> Any: + """Read settings while ignoring the expected duplicate mesh-id warning.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", openmc.IDWarning) + return openmc.Settings.from_xml(path) + + +def check_xml_roundtrip( + openmc: Any, ordering_mesh: Any, ordering_ms: Any, joint_mesh: Any, joint_ms: Any +) -> dict[str, Any]: + """Export both MeshSources through settings.xml, read them back, and compare.""" + with tempfile.TemporaryDirectory(prefix="openmc-handoff-xml-") as tmp: + directory = Path(tmp) + settings_path = directory / "settings.xml" + settings = openmc.Settings( + particles=1, + batches=1, + run_mode="fixed source", + output={"summary": False}, + ) + settings.source = [ordering_ms, joint_ms] + settings.export_to_xml(settings_path) + xml_text = settings_path.read_text(encoding="utf-8") + + restored = read_settings_silencing_mesh_id_warning(openmc, settings_path) + by_mesh_id = { + int(source.mesh.id): source + for source in restored.source + if isinstance(source, openmc.MeshSource) + } + ordering_restored = by_mesh_id.get(int(ordering_mesh.id)) + joint_restored = by_mesh_id.get(int(joint_mesh.id)) + + ordering_sources_ok = ordering_restored is not None + ordering_mesh_ok = ordering_restored is not None + ordering_strengths_ok = ordering_restored is not None + ordering_energies_ok = ordering_restored is not None + if ordering_restored is not None: + ordering_mesh_ok = ( + tuple(ordering_restored.mesh.dimension) == ORDER_DIMENSION + and tuple(ordering_restored.mesh.lower_left) == ORDER_LOWER + and tuple(ordering_restored.mesh.upper_right) == ORDER_UPPER + and int(ordering_restored.mesh.id) == int(ordering_mesh.id) + ) + ordering_sources_ok = int(ordering_restored.sources.size) == 12 + strengths = [float(source.strength) for source in ordering_restored.sources] + original_strengths = [float(source.strength) for source in ordering_ms.sources] + ordering_strengths_ok = strengths == original_strengths + energies = [] + for source in ordering_restored.sources: + if not isinstance(source.energy, openmc.stats.Uniform): + ordering_energies_ok = False + break + energies.append((float(source.energy.a), float(source.energy.b))) + original_energies = [ + (float(source.energy.a), float(source.energy.b)) for source in ordering_ms.sources + ] + ordering_energies_ok = ordering_energies_ok and energies == original_energies + + joint_mesh_ok = joint_restored is not None + joint_strengths_ok = joint_restored is not None + joint_edges_ok = joint_restored is not None + if joint_restored is not None: + joint_mesh_ok = ( + tuple(joint_restored.mesh.dimension) == (2, 1, 1) + and tuple(joint_restored.mesh.lower_left) == (0.0, 0.0, 0.0) + and tuple(joint_restored.mesh.upper_right) == (2.0, 1.0, 1.0) + and int(joint_restored.mesh.id) == int(joint_mesh.id) + ) + joint_strengths_ok = [float(source.strength) for source in joint_restored.sources] == [ + float(value) for value in JOINT_VOXEL_STRENGTHS + ] + joint_edges_ok = True + for voxel, source in enumerate(joint_restored.sources): + if not isinstance(source.energy, openmc.stats.Tabular): + joint_edges_ok = False + break + if source.energy.interpolation != "histogram": + joint_edges_ok = False + break + expected = histogram_density(JOINT_EDGES, JOINT_INTEGRATED[voxel]) + if source.energy.x.tolist() != list(JOINT_EDGES): + joint_edges_ok = False + break + if source.energy.p.tolist() != expected: + joint_edges_ok = False + break + + # The strength attribute is derived from its child + # sources. Change it on a temporary copy and confirm it is ignored. + mesh_strength_attribute_ignored = None + mesh_strength_pattern = ( + rf'()' + ) + modified_text, replacements = re.subn( + mesh_strength_pattern, + r"\g<1>999999.0\g<2>", + xml_text, + count=1, + ) + if replacements == 1: + modified_path = directory / "modified-settings.xml" + modified_path.write_text(modified_text, encoding="utf-8") + modified = read_settings_silencing_mesh_id_warning(openmc, modified_path) + modified_by_mesh_id = { + int(source.mesh.id): source + for source in modified.source + if isinstance(source, openmc.MeshSource) + } + modified_ordering = modified_by_mesh_id.get(int(ordering_mesh.id)) + if modified_ordering is not None: + mesh_strength_attribute_ignored = math.isclose( + float(modified_ordering.strength), + float(ordering_ms.strength), + rel_tol=0.0, + abs_tol=1e-12, + ) + + return { + "route": "openmc.Settings.export_to_xml() -> openmc.Settings.from_xml()", + "settings_xml_sha256": sha256_file(settings_path), + "mesh_elements_in_xml": len(re.findall(r" Path: + """Write the smallest cross_sections.xml that lets OpenMC initialize.""" + path = directory / "cross_sections_placeholder.xml" + path.write_text( + '\n' + "\n" + ' \n' + "\n", + encoding="utf-8", + ) + return path + + +def redirect_c_stdout_to_stderr() -> int: + """Duplicate fd 1 onto stderr so OpenMC C++ output cannot corrupt JSON.""" + sys.stdout.flush() + saved = os.dup(1) + os.dup2(2, 1) + return saved + + +def restore_c_stdout(saved: int) -> None: + """Restore the original stdout file descriptor.""" + sys.stdout.flush() + os.dup2(saved, 1) + os.close(saved) + + +def sample_with_openmc( + openmc: Any, mesh: Any, mesh_source: Any, n_samples: int, seed: int, sphere_radius: float +) -> Any: + """Sample source sites through the installed OpenMC library, without transport.""" + settings = openmc.Settings( + particles=1, + batches=1, + run_mode="fixed source", + output={"summary": False}, + ) + settings.source = [mesh_source] + sphere = openmc.Sphere(r=sphere_radius, boundary_type="vacuum") + cell = openmc.Cell(region=-sphere) + geometry = openmc.Geometry([cell]) + model = openmc.Model(settings=settings, geometry=geometry) + saved = redirect_c_stdout_to_stderr() + try: + particles = model.sample_external_source( + n_samples=n_samples, + prn_seed=seed, + as_array=True, + ) + finally: + restore_c_stdout(saved) + return particles + + +def sample_joint(openmc: Any) -> dict[str, Any]: + """Sample the two-voxel/two-group scenario and compare joint frequencies.""" + import numpy as np + + mesh, mesh_source = build_joint_mesh(openmc, mesh_id=19101) + particles = sample_with_openmc( + openmc, + mesh, + mesh_source, + n_samples=JOINT_SAMPLES, + seed=PRN_SEED, + sphere_radius=100.0, + ) + positions = np.asarray(particles["r"]) + indices = np.asarray([mesh.get_indices_at_coords(position) for position in positions]) + voxel = indices[:, 0] + energies = np.asarray(particles["E"]) + group = np.searchsorted(np.asarray(JOINT_EDGES), energies, side="right") - 1 + + joint = np.zeros((2, 2), dtype=np.int64) + np.add.at(joint, (voxel, group), 1) + empirical = joint / float(JOINT_SAMPLES) + exact = np.asarray(JOINT_EXACT) + max_abs_error = float(np.max(np.abs(empirical - exact))) + zero_cross_count = int(joint[0, 1] + joint[1, 0]) + weights = np.asarray(particles["wgt"]) + inside = bool( + np.all(voxel >= 0) + and np.all(voxel < 2) + and np.all(group >= 0) + and np.all(group < 2) + and np.all(np.isfinite(energies)) + ) + weights_unity = bool(np.all(weights == 1.0)) + passed = max_abs_error <= JOINT_TOLERANCE and zero_cross_count == 0 and weights_unity and inside + return { + "n_samples": JOINT_SAMPLES, + "seed": PRN_SEED, + "tolerance_abs": JOINT_TOLERANCE, + "exact_joint": exact.tolist(), + "counts": joint.tolist(), + "empirical_joint": empirical.tolist(), + "max_abs_error": max_abs_error, + "zero_cross_count": zero_cross_count, + "inside_mesh": inside, + "weights": { + "min": float(np.min(weights)), + "max": float(np.max(weights)), + "unique": np.unique(weights).tolist(), + "all_unity": weights_unity, + }, + "particle_codes": np.unique(np.asarray(particles["particle"])).tolist(), + "mesh_total_strength": float(mesh_source.strength), + "relative_selection_probabilities": [ + float(source.strength) / float(mesh_source.strength) for source in mesh_source.sources + ], + "pass": bool(passed), + } + + +def sample_ordering(openmc: Any) -> dict[str, Any]: + """Sample the 2 x 3 x 2 ordering mesh and check the C-to-F mapping in practice.""" + import numpy as np + + mesh, _, mesh_source = build_ordering_mesh(openmc, mesh_id=19102) + particles = sample_with_openmc( + openmc, + mesh, + mesh_source, + n_samples=ORDER_SAMPLES, + seed=PRN_SEED, + sphere_radius=100.0, + ) + positions = np.asarray(particles["r"]) + indices = np.asarray([mesh.get_indices_at_coords(position) for position in positions]) + i = indices[:, 0] + j = indices[:, 1] + k = indices[:, 2] + c_index = (i * ORDER_DIMENSION[1] + j) * ORDER_DIMENSION[2] + k + f_index = i + ORDER_DIMENSION[0] * j + ORDER_DIMENSION[0] * ORDER_DIMENSION[1] * k + energies = np.asarray(particles["E"]) + band = np.floor((energies - ORDER_BAND_LOW) / ORDER_BAND_WIDTH).astype(np.int64) + band_in_range = bool(np.all(band >= 0) and np.all(band < 12)) + mismatch_count = int(np.count_nonzero(band != c_index)) + counts_c = np.bincount(c_index, minlength=12) + counts_f = np.bincount(f_index, minlength=12) + weights = np.asarray(particles["wgt"]) + all_cells_seen = bool(np.all(counts_c > 0)) + weights_unity = bool(np.all(weights == 1.0)) + passed = ( + band_in_range + and mismatch_count == 0 + and all_cells_seen + and weights_unity + and bool(np.all(i >= 0)) + and bool(np.all(i < 2)) + and bool(np.all(j >= 0)) + and bool(np.all(j < 3)) + and bool(np.all(k >= 0)) + and bool(np.all(k < 2)) + ) + return { + "n_samples": ORDER_SAMPLES, + "seed": PRN_SEED, + "mismatch_count": mismatch_count, + "band_in_range": band_in_range, + "all_12_cells_seen": all_cells_seen, + "counts_by_c_order_index": counts_c.tolist(), + "counts_by_openmc_f_order_index": counts_f.tolist(), + "weights_unity": weights_unity, + "pass": bool(passed), + } + + +def sample_zero_voxel(openmc: Any) -> dict[str, Any]: + """Sample a mesh with one nonzero and one zero-strength element.""" + import numpy as np + + mesh = openmc.RegularMesh() + mesh.id = 19103 + mesh.dimension = (2, 1, 1) + mesh.lower_left = (0.0, 0.0, 0.0) + mesh.upper_right = (2.0, 1.0, 1.0) + sources = [ + openmc.IndependentSource( + energy=openmc.stats.Uniform(1.0, 2.0), strength=1.0, particle="photon" + ), + openmc.IndependentSource( + energy=openmc.stats.Uniform(3.0, 4.0), strength=0.0, particle="photon" + ), + ] + mesh_source = openmc.MeshSource(mesh, sources) + particles = sample_with_openmc( + openmc, + mesh, + mesh_source, + n_samples=ZERO_SAMPLES, + seed=PRN_SEED, + sphere_radius=100.0, + ) + positions = np.asarray(particles["r"]) + indices = np.asarray([mesh.get_indices_at_coords(position) for position in positions]) + voxel = indices[:, 0] + counts = np.bincount(voxel, minlength=2) + weights = np.asarray(particles["wgt"]) + passed = ( + int(counts[0]) == ZERO_SAMPLES + and int(counts[1]) == 0 + and bool(np.all(weights == 1.0)) + and float(mesh_source.strength) == 1.0 + ) + return { + "n_samples": ZERO_SAMPLES, + "seed": PRN_SEED, + "counts": counts.tolist(), + "element_strengths": [float(source.strength) for source in mesh_source.sources], + "mesh_total_strength": float(mesh_source.strength), + "weights": { + "min": float(np.min(weights)), + "max": float(np.max(weights)), + "all_unity": bool(np.all(weights == 1.0)), + }, + "pass": bool(passed), + } + + +def run_void_tally_worker() -> int: + """Child-process entry point: run a void fixed-source tally normalization check. + + The model is a vacuum sphere with an isotropic point source at its center. + Every particle travels exactly one radius before leaving, so the + volume-integrated track-length flux tally mean is ``radius * total source + strength``. Running at strengths 1 and 10 distinguishes a per-source- + particle tally (unchanged except by statistics) from a rate-scaled tally + (ten times larger), and distinguishes an integrated flux score from a + volume-averaged one. No evaluated data or interacting material is used. + """ + try: + import openmc + except Exception as error: # pragma: no cover - only for broken environments + print(json.dumps({"status": "SKIP", "reason": f"OpenMC import failed: {error}"})) + return 2 + if openmc.__version__ != EXPECTED_OPENMC: + print( + json.dumps( + { + "status": "SKIP", + "reason": f"OpenMC {openmc.__version__} != {EXPECTED_OPENMC}", + } + ) + ) + return 2 + + result: dict[str, Any] = { + "radius_cm": VOID_RADIUS, + "n_particles": VOID_PARTICLES, + "seed": VOID_SEED, + "strengths": list(VOID_STRENGTHS), + "runs": [], + "transport_run": "void-track-length-only", + } + with tempfile.TemporaryDirectory(prefix="openmc-void-tally-") as tmp: + directory = Path(tmp) + cross_sections = write_cross_sections_placeholder(directory) + previous = os.environ.get("OPENMC_CROSS_SECTIONS") + os.environ["OPENMC_CROSS_SECTIONS"] = str(cross_sections) + try: + for strength in VOID_STRENGTHS: + model_dir = directory / f"strength-{strength:g}" + model_dir.mkdir() + sphere = openmc.Sphere(r=VOID_RADIUS, boundary_type="vacuum") + cell = openmc.Cell(region=-sphere) + geometry = openmc.Geometry([cell]) + source = openmc.IndependentSource( + space=openmc.stats.Point((0.0, 0.0, 0.0)), + energy=openmc.stats.Discrete([14.0e6], [1.0]), + strength=strength, + particle="neutron", + ) + settings = openmc.Settings( + particles=VOID_PARTICLES, + batches=1, + run_mode="fixed source", + output={"summary": False, "tallies": False}, + ) + settings.seed = VOID_SEED + settings.source = [source] + tally = openmc.Tally(name="void flux") + tally.filters = [openmc.CellFilter(cell)] + tally.scores = ["flux"] + model = openmc.Model( + geometry=geometry, + materials=openmc.Materials([]), + settings=settings, + tallies=openmc.Tallies([tally]), + ) + model.export_to_xml(model_dir) + saved = redirect_c_stdout_to_stderr() + try: + openmc.run(output=False, cwd=str(model_dir)) + finally: + restore_c_stdout(saved) + statepoint = openmc.StatePoint(str(model_dir / "statepoint.1.h5")) + try: + data = statepoint.tallies[tally.id] + mean = float(data.mean.ravel()[0]) + std_dev = float(data.std_dev.ravel()[0]) + if not math.isfinite(std_dev): + # A zero-variance void tally reports NaN in 0.16.0; + # keep the JSON document strict. + std_dev = None + finally: + close = getattr(statepoint, "close", None) + if callable(close): + close() + result["runs"].append( + { + "source_strength": strength, + "mean": mean, + "std_dev": std_dev, + "expected_integrated_track_length": VOID_RADIUS * strength, + "expected_if_volume_averaged": ( + VOID_RADIUS * strength / (4.0 / 3.0 * math.pi * VOID_RADIUS**3) + ), + } + ) + finally: + if previous is None: + os.environ.pop("OPENMC_CROSS_SECTIONS", None) + else: + os.environ["OPENMC_CROSS_SECTIONS"] = previous + print(json.dumps(result, sort_keys=True)) + return 0 + + +def run_sample_worker() -> int: + """Child-process entry point: sample sources, print one JSON document.""" + try: + import openmc + except Exception as error: # pragma: no cover - only for broken environments + print(json.dumps({"status": "SKIP", "reason": f"OpenMC import failed: {error}"})) + return 2 + if openmc.__version__ != EXPECTED_OPENMC: + print( + json.dumps( + { + "status": "SKIP", + "reason": f"OpenMC {openmc.__version__} != {EXPECTED_OPENMC}", + } + ) + ) + return 2 + + with tempfile.TemporaryDirectory(prefix="openmc-handoff-sample-") as tmp: + directory = Path(tmp) + cross_sections = write_cross_sections_placeholder(directory) + previous = os.environ.get("OPENMC_CROSS_SECTIONS") + os.environ["OPENMC_CROSS_SECTIONS"] = str(cross_sections) + try: + result: dict[str, Any] = { + "cross_sections_placeholder": { + "path": str(cross_sections), + "sha256": sha256_file(cross_sections), + "library_path": "/tmp/nonexistent-openmc-handoff.h5", + "library_path_exists": Path("/tmp/nonexistent-openmc-handoff.h5").exists(), + "note": ( + "Initialization shim only. OpenMC runs in volume-calculation " + "mode; no cross-section data are read and no transport run occurs." + ), + }, + "transport_run": False, + } + result["joint"] = sample_joint(openmc) + result["ordering"] = sample_ordering(openmc) + result["zero_voxel"] = sample_zero_voxel(openmc) + finally: + if previous is None: + os.environ.pop("OPENMC_CROSS_SECTIONS", None) + else: + os.environ["OPENMC_CROSS_SECTIONS"] = previous + print(json.dumps(result, sort_keys=True)) + return 0 + + +def record_check(checks: dict[str, Any], name: str, passed: bool, **details: Any) -> None: + """Record a named boolean check with supporting detail.""" + checks[name] = {"pass": bool(passed), **details} + + +def build_summary(openmc: Any) -> dict[str, Any]: + """Run all Python-level checks and the isolated sampling worker.""" + checks: dict[str, Any] = {} + summary: dict[str, Any] = { + "probe": PROBE_NAME, + "status": "FAIL", + "openmc_version": openmc.__version__, + "python_version": sys.version.split()[0], + "openmc_package_file": str(Path(openmc.__file__).resolve()), + "transport_run": False, + "void_track_length_check": True, + "limitations": [ + "No evaluated cross-section or photon data are installed. The only " + "transport run is a vacuum track-length tally normalization check; no " + "interacting transport calculation or physical tally result is produced " + "or claimed.", + "Source sampling verifies the OpenMC source API and joint probabilities only.", + "The placeholder cross_sections.xml is an initialization shim, not physics input.", + "The 2 x 3 x 2 and two-voxel scenarios are synthetic; they are not an ACTINV case.", + "An all-zero MeshSource was not sampled: OpenMC 0.16.0 DiscreteIndex::normalize " + "divides by integral_ with no zero guard. A single zero-strength voxel inside a " + "nonzero source is verified; the adapter must reject an all-zero total strength " + "itself.", + ], + } + + try: + metadata_version = importlib.metadata.version("openmc") + except importlib.metadata.PackageNotFoundError: + metadata_version = "not installed as a distribution" + version_ok = openmc.__version__ == EXPECTED_OPENMC and metadata_version == EXPECTED_OPENMC + record_check( + checks, + "openmc_version_exactly_0_16_0", + version_ok, + runtime_version=openmc.__version__, + distribution_version=metadata_version, + expected=EXPECTED_OPENMC, + ) + summary["openmc_distribution_version"] = metadata_version + + source_dir, source_origin = find_openmc_source_dir() + summary["openmc_source"] = { + "path": str(source_dir) if source_dir is not None else None, + "origin": source_origin, + } + provenance = collect_source_provenance(source_dir) + summary["normalization"] = { + "inspected_source": provenance, + "inspected_python": collect_python_provenance(openmc), + } + record_check( + checks, + "openmc_source_tree_available", + bool(provenance.get("available")), + source_dir=str(source_dir) if source_dir is not None else None, + reason=provenance.get("reason"), + ) + + derived = provenance.get("derived", {}) if provenance.get("available") else {} + per_source_particle_docs = ( + provenance.get("available", False) + and provenance["tallies_rst"]["patterns"]["per_source_particle"]["found"] + ) + strength_unit_conversion_docs = ( + provenance.get("available", False) + and provenance["tallies_rst"]["patterns"]["strength_as_unit_conversion"]["found"] + ) + relative_strength_docs = ( + provenance.get("available", False) + and provenance["settings_rst"]["patterns"]["relative_strength"]["found"] + ) + regular_norm_found = ( + provenance.get("available", False) + and provenance["tally_cpp"]["patterns"]["regular_norm"]["found"] + ) + global_total_weight_found = ( + provenance.get("available", False) + and provenance["tally_cpp"]["patterns"]["global_total_weight"]["found"] + ) + regular_uses_total_weight = bool( + derived.get("regular_norm_uses_simulation_total_weight", False) + ) + regular_uses_n_particles = bool(derived.get("regular_norm_uses_n_particles", False)) + regular_scales_by_total_source = bool(derived.get("regular_norm_scales_by_total_source", False)) + mesh_strength_sum = bool(derived.get("mesh_source_strength_is_sum", False)) + discrete_selection = ( + provenance.get("available", False) + and provenance["distribution_cpp"]["patterns"]["discrete_integral"]["found"] + and provenance["distribution_cpp"]["patterns"]["discrete_normalize"]["found"] + ) + mesh_element_selection = ( + provenance.get("available", False) + and provenance["source_cpp"]["patterns"]["mesh_sample_element"]["found"] + and provenance["source_cpp"]["patterns"]["mesh_strengths"]["found"] + ) + + record_check( + checks, + "tally_results_use_per_source_particle_denominator", + bool(per_source_particle_docs and regular_norm_found and regular_uses_n_particles), + expected=True, + observed=bool(per_source_particle_docs and regular_uses_n_particles), + normalization_expression=( + "norm = total_source / (contributing_particles * settings::gen_per_batch); " + "contributing_particles = settings::n_particles" + ), + detail=( + "OpenMC 0.16 docs and Tally::accumulate confirm a per-source-particle " + "denominator. The numerator is the total source strength, so the result is " + "per-source-particle x total source strength." + ), + ) + record_check( + checks, + "regular_tallies_do_not_use_simulation_total_weight_denominator", + not regular_uses_total_weight, + expected=True, + observed=not regular_uses_total_weight, + detail=( + "Regular tallies in 0.16.0 use settings::n_particles, not " + "simulation::total_weight. simulation::total_weight is used for global " + "tallies (k/leakage) and MPI reduction. In default unweighted sampling " + "total_weight equals n_particles numerically, but it is not the regular-" + "tally denominator." + ), + ) + record_check( + checks, + "source_strength_serves_as_relative_selection_weight", + bool(relative_strength_docs and discrete_selection and mesh_element_selection), + expected=True, + observed=bool(relative_strength_docs and discrete_selection and mesh_element_selection), + detail=( + "Per-element strength is used as a relative selection weight: DiscreteIndex " + "normalizes it, and MeshSource samples an element by relative strength." + ), + ) + record_check( + checks, + "source_strength_is_relative_weight_and_tally_scale", + bool( + relative_strength_docs + and regular_scales_by_total_source + and strength_unit_conversion_docs + ), + expected=True, + observed=bool( + relative_strength_docs + and regular_scales_by_total_source + and strength_unit_conversion_docs + ), + detail=( + "Source strength is both a relative selection weight and the tally scale: " + "the sum of source strengths is total_source in Tally::accumulate, and the " + "docs describe using SourceBase.strength to convert per-source-particle " + "tallies to absolute units." + ), + ) + record_check( + checks, + "source_strength_sum_scales_tally_results", + bool(regular_scales_by_total_source and strength_unit_conversion_docs), + expected=True, + observed=bool(regular_scales_by_total_source and strength_unit_conversion_docs), + detail=( + "Observed behavior: total_source = external_sources_probability.integral() " + "= sum of source strengths; MeshSource.strength = sum of element strengths." + ), + ) + record_check( + checks, + "global_tallies_use_simulation_total_weight", + bool(global_total_weight_found), + expected=True, + observed=bool(global_total_weight_found), + detail="Global tally accumulation divides by simulation::total_weight.", + ) + record_check( + checks, + "mesh_source_strength_is_sum_of_element_strengths", + mesh_strength_sum, + expected=True, + observed=mesh_strength_sum, + detail="openmc.MeshSource.strength returns sum(s.strength for s in self.sources).", + ) + + ordering_mesh, sources_c, ordering_ms = build_ordering_mesh(openmc, mesh_id=19001) + joint_mesh, joint_ms = build_joint_mesh(openmc, mesh_id=19002) + ordering = check_ordering_objects(openmc, ordering_mesh, sources_c, ordering_ms) + summary["mapping"] = ordering + record_check( + checks, + "c_order_array_maps_to_expected_openmc_mesh_elements", + bool(ordering["object_mapping_fortran_order_ok"]), + expected=True, + observed=ordering["object_mapping_fortran_order_ok"], + mapping_rule=ordering["mapping_rule"], + ) + record_check( + checks, + "regular_mesh_indices_fortran_order_1_based", + bool(ordering["regular_mesh_indices_are_1_based_fortran"]), + expected=True, + observed=ordering["regular_mesh_indices_are_1_based_fortran"], + ) + record_check( + checks, + "get_indices_at_coords_zero_based", + bool(ordering["get_indices_at_coords_is_0_based"]), + expected=True, + observed=ordering["get_indices_at_coords_is_0_based"], + ) + summary["normalization"]["mesh_source_strength"] = check_mesh_source_strength_normalization( + openmc, joint_mesh, joint_ms + ) + summary["normalization"]["observed"] = { + "regular_tally_denominator": ( + "settings::n_particles * settings::gen_per_batch " + "(settings::work_per_rank when reduce_tallies is false)" + ), + "regular_tally_scale": ( + "external_sources_probability.integral(), the sum of source strengths" + ), + "simulation_total_weight_role": ( + "global tallies and MPI reduction; accumulated from p.wgt() for each " + "source particle and numerically equal to n_particles in default " + "unweighted sampling" + ), + "mesh_source_total_strength": float(joint_ms.strength), + "mesh_source_element_strengths": [float(source.strength) for source in joint_ms.sources], + "mesh_source_element_selection_probabilities": [ + float(source.strength) / float(joint_ms.strength) for source in joint_ms.sources + ], + "per_source_particle_conversion": ( + "If element strengths sum to 1.0, raw tallies are per source particle and " + "physical_flux = raw * source_rate_s / volume_cm3. If element strengths are " + "absolute photons/s, their sum is already applied by OpenMC and multiplying " + "by source_rate_s again would double-count it." + ), + } + + histogram = build_histogram_case(openmc) + summary["histogram"] = histogram + density_ok = ( + math.isclose(histogram["integral"], 1.0, rel_tol=0.0, abs_tol=1e-12) + and all( + math.isclose(actual, expected, rel_tol=0.0, abs_tol=1e-12) + for actual, expected in zip( + histogram["readback_p"], + histogram["expected_density_pdf_per_eV"], + strict=True, + ) + ) + and histogram["interpolation"] == "histogram" + and math.isclose(histogram["wrong_control_integral"], 4.0, rel_tol=0.0, abs_tol=1e-12) + ) + record_check( + checks, + "histogram_p_is_differential_density_per_eV", + bool(density_ok), + expected=True, + observed=bool(density_ok), + integral=histogram["integral"], + wrong_control_integral=histogram["wrong_control_integral"], + ) + zero_bin_ok = ( + histogram["zero_bin"]["integrated_strength"] == 0.0 + and histogram["zero_bin"]["density"] == 0.0 + and histogram["zero_bin"]["evaluate_midpoint"] == 0.0 + and bool(histogram["zero_bin"]["cdf_flat"]) + ) + record_check( + checks, + "zero_bin_has_zero_density_and_zero_integral_contribution", + bool(zero_bin_ok), + expected=True, + observed=bool(zero_bin_ok), + ) + zero_voxel_ok = ( + histogram["zero_strength_voxel"]["source_strength"] == 0.0 + and histogram["zero_strength_voxel"]["mesh_source_total_strength"] == 1.0 + and histogram["zero_strength_voxel"]["relative_probabilities"] == [1.0, 0.0] + and not histogram["all_zero_distribution"]["pdf_valid"] + ) + record_check( + checks, + "zero_strength_voxel_is_data_but_not_samplable_pdf", + bool(zero_voxel_ok), + expected=True, + observed=bool(zero_voxel_ok), + ) + record_check( + checks, + "openmc_stats_Histogram_class_absent_use_Tabular", + not histogram["histogram_class_available"], + expected=False, + observed=histogram["histogram_class_available"], + supported_equivalent=histogram["supported_equivalent"], + note="The brief's openmc.stats.Histogram name does not exist in 0.16.0.", + ) + + roundtrip = check_xml_roundtrip(openmc, ordering_mesh, ordering_ms, joint_mesh, joint_ms) + summary["xml_roundtrip"] = roundtrip + record_check( + checks, + "settings_xml_roundtrip_preserves_mesh_sources", + bool(roundtrip["roundtrip_ok"]), + expected=True, + observed=bool(roundtrip["roundtrip_ok"]), + route=roundtrip["route"], + ) + record_check( + checks, + "mesh_source_strength_attribute_is_derived_not_authoritative", + roundtrip["mesh_source_strength_attribute_ignored"] is True, + expected=True, + observed=roundtrip["mesh_source_strength_attribute_ignored"], + note=( + 'Changing the attribute on a temporary ' + "XML copy does not change the read-back MeshSource.strength." + ), + ) + + worker_command = [sys.executable, str(Path(__file__).resolve()), "--sample-worker"] + worker: dict[str, Any] = {} + worker_error = None + try: + completed = subprocess.run( + worker_command, + capture_output=True, + text=True, + timeout=180, + check=False, + ) + summary["sampling_worker"] = { + "command": worker_command, + "returncode": completed.returncode, + "stdout_tail": completed.stdout[-4000:], + "stderr_tail": completed.stderr[-4000:], + } + if completed.returncode == 0: + worker = json.loads(completed.stdout) + else: + worker_error = f"sampling worker exited {completed.returncode}" + except (OSError, subprocess.SubprocessError, json.JSONDecodeError) as error: + worker_error = f"sampling worker failed: {type(error).__name__}: {error}" + summary["sampling_worker"] = {"command": worker_command, "error": worker_error} + + summary["sampling"] = worker + worker_ok = bool(worker) and worker_error is None + record_check( + checks, + "source_sampling_worker_succeeded", + worker_ok, + expected=True, + observed=worker_ok, + error=worker_error, + ) + joint_sampling = worker.get("joint", {}) if worker_ok else {} + joint_sampling_ok = bool(joint_sampling.get("pass", False)) if worker_ok else False + record_check( + checks, + "sampled_joint_voxel_group_probabilities_match", + joint_sampling_ok, + expected=True, + observed=joint_sampling_ok, + exact_joint=joint_sampling.get("exact_joint"), + empirical_joint=joint_sampling.get("empirical_joint"), + counts=joint_sampling.get("counts"), + tolerance_abs=JOINT_TOLERANCE, + n_samples=JOINT_SAMPLES, + seed=PRN_SEED, + ) + zero_cross_ok = worker_ok and int(joint_sampling.get("zero_cross_count", -1)) == 0 + record_check( + checks, + "sampled_zero_cross_bins_are_never_selected", + zero_cross_ok, + expected=True, + observed=zero_cross_ok, + zero_cross_count=joint_sampling.get("zero_cross_count"), + ) + weights_ok = worker_ok and bool(joint_sampling.get("weights", {}).get("all_unity", False)) + record_check( + checks, + "default_sampling_particle_weights_are_unity", + weights_ok, + expected=True, + observed=weights_ok, + weights=joint_sampling.get("weights"), + detail="Source strength selects a voxel; it is not applied as a particle weight.", + ) + ordering_sampling = worker.get("ordering", {}) if worker_ok else {} + ordering_sampling_ok = bool(ordering_sampling.get("pass", False)) if worker_ok else False + record_check( + checks, + "sampled_2x3x2_cells_match_c_order_band_mapping", + ordering_sampling_ok, + expected=True, + observed=ordering_sampling_ok, + mismatch_count=ordering_sampling.get("mismatch_count"), + counts_by_c_order_index=ordering_sampling.get("counts_by_c_order_index"), + n_samples=ORDER_SAMPLES, + seed=PRN_SEED, + ) + zero_voxel_sampling = worker.get("zero_voxel", {}) if worker_ok else {} + zero_voxel_sampling_ok = bool(zero_voxel_sampling.get("pass", False)) if worker_ok else False + record_check( + checks, + "sampled_zero_strength_voxel_is_never_selected", + zero_voxel_sampling_ok, + expected=True, + observed=zero_voxel_sampling_ok, + counts=zero_voxel_sampling.get("counts"), + n_samples=ZERO_SAMPLES, + seed=PRN_SEED, + ) + + void_command = [sys.executable, str(Path(__file__).resolve()), "--void-tally-worker"] + void_worker: dict[str, Any] = {} + void_error = None + try: + completed = subprocess.run( + void_command, + capture_output=True, + text=True, + timeout=180, + check=False, + ) + summary["void_tally_worker"] = { + "command": void_command, + "returncode": completed.returncode, + "stdout_tail": completed.stdout[-4000:], + "stderr_tail": completed.stderr[-4000:], + } + if completed.returncode == 0: + void_worker = json.loads(completed.stdout) + else: + void_error = f"void tally worker exited {completed.returncode}" + except (OSError, subprocess.SubprocessError, json.JSONDecodeError) as error: + void_error = f"void tally worker failed: {type(error).__name__}: {error}" + summary["void_tally_worker"] = {"command": void_command, "error": void_error} + + summary["void_tally"] = void_worker + void_runs = void_worker.get("runs", []) if void_worker else [] + void_exact = len(void_runs) == len(VOID_STRENGTHS) and all( + math.isclose( + float(run["mean"]), + float(run["expected_integrated_track_length"]), + rel_tol=1e-9, + abs_tol=1e-12, + ) + and not math.isclose( + float(run["mean"]), + float(run["expected_if_volume_averaged"]), + rel_tol=1e-3, + abs_tol=0.0, + ) + for run in void_runs + ) + ratio_ok = len(void_runs) == 2 and float(void_runs[1]["mean"]) == 10.0 * float( + void_runs[0]["mean"] + ) + record_check( + checks, + "void_fixed_source_flux_tally_is_integrated_and_rate_scaled", + bool(void_error is None and void_exact and ratio_ok), + expected=True, + observed=bool(void_error is None and void_exact and ratio_ok), + runs=void_runs, + expected_integrated_track_length="radius * total source strength", + expected_if_volume_averaged="radius * strength / sphere volume", + error=void_error, + detail=( + "A vacuum sphere with a centered isotropic point source has exactly one " + "track of length R per particle. The tally mean is R * strength, not " + "R * strength / volume, and the 10x strength run is 10x the unit run." + ), + ) + + summary["api_mismatches"] = [ + { + "api": "openmc.stats.Histogram", + "status": "absent in 0.16.0", + "use_instead": "openmc.stats.Tabular(x, p, interpolation='histogram')", + "detail": "Tabular p values are densities per unit x, not integrated bin strengths.", + }, + { + "api": "regular tally normalization", + "status": "brief premise mismatch", + "detail": ( + "Regular tallies divide by settings::n_particles and multiply by the " + "sum of source strengths; they do not divide by simulation::total_weight." + ), + }, + { + "api": "SourceBase.strength / MeshSource.strength", + "status": "brief premise mismatch", + "detail": ( + "Element strengths are relative selection weights, but their sum is the " + "tally normalization scale. A mesh source with absolute photons/s " + "strengths therefore produces tallies already multiplied by the total rate." + ), + }, + { + "api": "openmc.MeshSource.sample", + "status": "no such method", + "detail": ( + "Use openmc.Model.sample_external_source or openmc.lib.sample_external_source. " + "OpenMC must be initialized; source sites must lie inside the geometry." + ), + }, + { + "api": "RegularMesh index bases", + "status": "mixed", + "detail": ( + "RegularMesh.indices yields 1-based (i, j, k) tuples in Fortran order; " + "RegularMesh.get_indices_at_coords returns 0-based indices." + ), + }, + { + "api": "MeshSource.sources ravel order", + "status": "Fortran order", + "detail": ( + "A multidimensional source array is flattened with order='F'. The " + "bridge's C-order voxel index is (i*ny + j)*nz + k." + ), + }, + { + "api": "MeshSource XML strength attribute", + "status": "derived", + "detail": ( + 'The attribute is the sum of child ' + "source strengths; from_xml_element rebuilds the sum from children." + ), + }, + { + "api": "all-zero MeshSource", + "status": "no explicit rejection in the inspected source path", + "detail": ( + "DiscreteIndex::normalize divides by integral_ with no zero-integral guard. " + "A zero element inside a nonzero source is valid, but all-zero total " + "strength must be rejected by the adapter before export or sampling. It " + "was not sampled here." + ), + }, + ] + + failed = [name for name, value in checks.items() if not value["pass"]] + summary["checks"] = checks + summary["failed_checks"] = failed + summary["status"] = "PASS" if not failed else "FAIL" + summary["exit_code"] = 0 if not failed else 1 + return summary + + +def main() -> int: + """Validate the environment, run the probe, and print one JSON summary.""" + try: + import openmc + except Exception as error: + reason = f"OpenMC import failed: {type(error).__name__}: {error}" + print(f"SKIP: {reason}", file=sys.stderr) + print(json.dumps({"probe": PROBE_NAME, "status": "SKIP", "reason": reason})) + return 2 + + if openmc.__version__ != EXPECTED_OPENMC: + reason = f"OpenMC {openmc.__version__} is installed; expected exactly {EXPECTED_OPENMC}" + print(f"SKIP: {reason}", file=sys.stderr) + print(json.dumps({"probe": PROBE_NAME, "status": "SKIP", "reason": reason})) + return 2 + + try: + summary = build_summary(openmc) + except Exception as error: + summary = { + "probe": PROBE_NAME, + "status": "FAIL", + "openmc_version": getattr(openmc, "__version__", None), + "error": f"{type(error).__name__}: {error}", + "traceback": traceback.format_exc(), + "exit_code": 1, + } + print(json.dumps(summary, indent=2, sort_keys=True)) + return 1 + + print(json.dumps(summary, indent=2, sort_keys=True)) + return int(summary["exit_code"]) + + +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "--sample-worker": + sys.exit(run_sample_worker()) + if len(sys.argv) == 2 and sys.argv[1] == "--void-tally-worker": + sys.exit(run_void_tally_worker()) + sys.exit(main()) diff --git a/validation/tritium_vs_festim.py b/validation/tritium_vs_festim.py index ceefad9..3dc7919 100644 --- a/validation/tritium_vs_festim.py +++ b/validation/tritium_vs_festim.py @@ -17,6 +17,13 @@ covered separately by F5: a trap-free outlet with scalar steady oracle, atomic-unit conversion, independent three-level space/time refinement, transient flux/profile parity and integrated mass balance. + F6 combines one McNabb-Foster trap with that recombination outlet: + the same single-layer scalar-temperature slab, explicit molar/atomic + conversion for concentrations, fluxes, inventories and the trap rate, + a checked factor of two for the two identical surface reactants, + mobile/trapped inventory histories, outlet parity, and a mobile-plus- + trapped mass balance, with independent space and time refinement on + both sides. Probe environment (never the main validation container, never the Rust workspace): FESTIM 2.1 needs DOLFINx, so the probe runs in the separate @@ -943,6 +950,39 @@ def probe_legs(fine_legs: dict[str, dict]) -> tuple[list[list[str]], list[str], F5_INITIAL_DT = 1.0e-6 F5_GROWTH = 1.02 +# F6: one McNabb-Foster trap plus the F5 recombination outlet. Same slab, +# trap and outlet as F2/F5 (hand-picked synthetic SI values), scalar 500 K, +# zero Arrhenius energies. The Oriani effective diffusivity +# D_eff = D/(1 + K N) = D/3 gives t_lag_eff = L^2/(6 D_eff) = 500 s; the +# trajectory ends at 10 t_lag_eff (5000 s) so the late-flux gate matches the +# F5 2%/3 rule. Three mesh levels isolate space at dt=0.25 s and three time +# caps isolate time at 200 cells, independently in each code. The levels and +# gates are the F5 evidence pattern (2% steady/profile/inventory, 3% J(t), +# <1/3 self-convergence); exploratory F6 runs at 50/100/200 cells and +# 0.5/0.25/0.125 s showed the finest-level reaction law and inventories +# converged well below these gates. +F6_KR = F5_KR +F6_K0 = TRAP_K0 +F6_P0 = TRAP_P0 +F6_TRAP_N = TRAP_N +F6_TEMPERATURE = 500.0 +F6_D_EFF = D / (1.0 + (F6_K0 / F6_P0) * F6_TRAP_N) +F6_TLAG = L * L / (6.0 * F6_D_EFF) +F6_T_END = 10.0 * F6_TLAG +F6_TIMES = [fraction * F6_TLAG for fraction in (0.2, 0.5, 1.0, 2.0, 5.0, 10.0)] +F6_LEVELS = [(50, 0.25), (100, 0.25), (200, 0.25), (200, 0.5), (200, 0.125)] +F6_IMAGE = F5_IMAGE +F6_INITIAL_DT = 1.0e-6 +F6_GROWTH = 1.02 +F6_FLUX_GATE = 0.03 +F6_INVENTORY_GATE = 0.02 +F6_PROFILE_GATE = 0.02 +F6_REACTION_GATE = 0.02 +F6_TRAP_EQ_GATE = 0.02 +F6_BALANCE_GATE = 1.0e-3 +F6_QUADRATURE_GATE = 1.0e-3 / 3.0 +F6_LATE_GATE = 0.02 / 3.0 + def _f5_oracle() -> tuple[float, float]: a = D / L @@ -1363,6 +1403,641 @@ def gate(label, error, threshold): return rows, notes +def _f6_bracket(times: np.ndarray, requested: float, label: str) -> tuple[int, float]: + """Return the lower exported-time bracket and interpolation weight. + + Every requested sample must sit inside the exported range. A missing + bracket raises instead of extending or extrapolating the history; the + only roundoff allowance is the final endpoint, matching the F5 rule. + """ + if times.size < 2 or times[0] != 0.0 or np.any(np.diff(times) <= 0.0): + raise ValueError("F6 requires strictly ascending exported times starting at zero") + if requested > times[-1]: + slack = 8.0 * math.ulp(max(abs(float(times[-1])), abs(requested))) + if requested - times[-1] <= slack: + requested = float(times[-1]) + if requested < times[0] or requested > times[-1]: + raise ValueError( + f"F6 {label} requested time {requested:.17g} s is outside exported " + f"range [{times[0]:.17g}, {times[-1]:.17g}] s" + ) + lower = int(np.searchsorted(times, requested, side="right")) - 1 + if lower < 0: + lower = 0 + if times[lower] == requested: + return lower, 0.0 + if lower + 1 >= times.size: + raise ValueError( + f"F6 {label} requested time {requested:.17g} s has no upper export bracket" + ) + weight = (requested - times[lower]) / (times[lower + 1] - times[lower]) + return lower, float(weight) + + +def _f6_sample(times: np.ndarray, values: np.ndarray, requested: float, label: str) -> np.ndarray: + """Bracketed linear sample of one history column; never extrapolate.""" + lower, weight = _f6_bracket(times, requested, label) + if weight == 0.0: + return np.array(values[lower], copy=True) + return values[lower] + weight * (values[lower + 1] - values[lower]) + + +def _f6_reduce( + times: list[float], + flux_left: list[float], + flux_right: list[float], + x: list[float], + mobile: np.ndarray, + trapped: np.ndarray, + mobile_inventory: list[float], + trapped_inventory: list[float], +) -> dict[str, Any]: + """Reduce exported F6 histories without substituting a boundary flux.""" + t = np.asarray(times, dtype=float) + jl = np.asarray(flux_left, dtype=float).reshape(-1) + jr = np.asarray(flux_right, dtype=float).reshape(-1) + m = np.asarray(mobile, dtype=float) + tr = np.asarray(trapped, dtype=float) + im = np.asarray(mobile_inventory, dtype=float).reshape(-1) + it = np.asarray(trapped_inventory, dtype=float).reshape(-1) + if not (len(t) == len(jl) == len(jr) == len(im) == len(it) == m.shape[0] == tr.shape[0]): + raise ValueError( + f"F6 history lengths differ: t={len(t)} jl={len(jl)} jr={len(jr)} " + f"im={len(im)} it={len(it)} mobile={m.shape} trapped={tr.shape}" + ) + if m.shape[1] != tr.shape[1] or m.shape[1] != len(x): + raise ValueError("F6 mobile, trapped and profile grids differ") + if not all(np.all(np.isfinite(v)) for v in (t, jl, jr, im, it, m, tr)): + raise ValueError("F6 nonfinite history export") + requested_end = F6_TIMES[-1] + slack = 8.0 * math.ulp(max(abs(float(t[-1])), abs(requested_end))) + if requested_end - t[-1] > slack: + raise ValueError( + f"F6 history ends at {t[-1]:.17g} s before requested " + f"{requested_end:.17g} s (difference {requested_end - t[-1]:.17g} s, " + f"roundoff allowance {slack:.17g} s)" + ) + flux_t = np.asarray([_f6_sample(t, jr, at, "outlet flux") for at in F6_TIMES]) + mobile_inventory_t = np.asarray([_f6_sample(t, im, at, "mobile inventory") for at in F6_TIMES]) + trapped_inventory_t = np.asarray( + [_f6_sample(t, it, at, "trapped inventory") for at in F6_TIMES] + ) + mobile_t = np.asarray([_f6_sample(t, m, at, "mobile profile") for at in F6_TIMES]) + trapped_t = np.asarray([_f6_sample(t, tr, at, "trapped profile") for at in F6_TIMES]) + + # Explicit trapezoidal formula works on NumPy 1.x and 2.x. + def integrate(values, indices): + return float(np.sum(np.diff(t[indices]) * (values[indices][1:] + values[indices][:-1]) / 2)) + + indices = np.arange(len(t)) + inward = -jl + net = inward - jr + net_integrals = [] + for stride in (1, 2, 4): + selected = np.unique(np.append(indices[::stride], indices[-1])) + net_integrals.append(integrate(net, selected)) + delta = float((im[-1] + it[-1]) - (im[0] + it[0])) + throughput = integrate(np.abs(inward) + np.abs(jr), indices) + norm = max(abs(delta), throughput, 1e-30) + balance = abs(delta - net_integrals[0]) / norm + quadrature = [abs(net_integrals[i] - net_integrals[i + 1]) / norm for i in (0, 1)] + jss = float(jr[-1]) + late = float(_f6_sample(t, jr, 0.9 * requested_end, "late flux")) + return { + "times": list(F6_TIMES), + "flux_t": flux_t.tolist(), + "mobile_inventory_t": mobile_inventory_t.tolist(), + "trapped_inventory_t": trapped_inventory_t.tolist(), + "profiles": mobile_t.tolist(), + "trapped_profiles": trapped_t.tolist(), + "x": [float(v) for v in x], + "c": mobile_t[-1].tolist(), + "ct": trapped_t[-1].tolist(), + "jss": jss, + "late_change": abs(jss - late) / jss, + "balance": balance, + "quadrature": quadrature, + "grid": f"{len(t)} exported times, [{t[0]:g}, {t[-1]:g}] s, " + f"dt range [{min(np.diff(t)):g}, {max(np.diff(t)):g}] s", + "inventory_change": delta, + "net_integral": net_integrals[0], + "throughput": throughput, + "requested_end": requested_end, + "actual_end": float(t[-1]), + "endpoint_roundoff_allowance": slack, + } + + +def _f6_nucleide(cells: int, dt: float) -> dict[str, Any]: + """F6 Nucleide run: one trap plus the recombination outlet.""" + times = [] + at = 0.0 + step = F6_INITIAL_DT + while at < F6_T_END: + at = min(F6_T_END, at + step) + times.append(at) + step = min(dt, step * F6_GROWTH) + out = tri.transient( + L, + cells, + D, + {"kind": "dirichlet", "value": C0}, + {"kind": "recombination", "rate": F6_KR}, + times, + traps=[ + { + "k0": F6_K0, + "p0": F6_P0, + "site_density": F6_TRAP_N, + "e_k": 0.0, + "e_p": 0.0, + } + ], + temperature=[F6_TEMPERATURE], + dt_max=dt, + rtol=1e-10, + atol=1e-14, + ) + dx = L / cells + mobile = np.vstack((np.zeros(cells), np.asarray(out["mobile"], dtype=float))) + trapped = np.vstack((np.zeros((1, cells)), np.asarray(out["trapped"], dtype=float)[:, :, 0])) + centres = ((np.arange(cells) + 0.5) * dx).tolist() + # Initial state: zero mobile/trapped load and the hand-derived left + # Dirichlet-layer flux (the first cell is half a cell from the C0 face). + # This is the same startup balance as F5/G6c; a zero inlet flux would + # corrupt the cumulative balance. + initial_left_flux = -2.0 * D * C0 / dx + return _f6_reduce( + [0.0, *out["times"]], + [initial_left_flux, *out["flux_left"]], + [0.0, *out["flux_right"]], + centres, + mobile, + trapped, + np.sum(mobile, axis=1) * dx, + np.sum(trapped, axis=1) * dx, + ) + + +def _f6_festim(festim: Any, cells: int, dt: float) -> dict[str, Any]: + """F6 FESTIM run in atomic units; all returned quantities are molar SI.""" + model = festim.HydrogenTransportProblem() + model.mesh = festim.Mesh1D(vertices=np.linspace(0.0, L, cells + 1)) + volume = festim.VolumeSubdomain1D( + id=1, borders=[0.0, L], material=festim.Material(D_0=D, E_D=0.0) + ) + left = festim.SurfaceSubdomain1D(id=1, x=0.0) + right = festim.SurfaceSubdomain1D(id=2, x=L) + mobile = festim.Species("T") + empty = festim.Species("empty_traps", mobile=False) + trapped = festim.Species("trapped_T", mobile=False) + model.subdomains = [volume, left, right] + model.species = [mobile, empty, trapped] + model.temperature = F6_TEMPERATURE + model.boundary_conditions = [ + festim.FixedConcentrationBC(subdomain=left, value=C0 * AVOGADRO, species=mobile), + # reactant=[T, T] is the A=A surface reaction: FESTIM applies two + # partial fluxes for the identical reactants, so the atomic particle + # flux is 2*k_r0*c_atom^2. With k_r0=Kr/(2 NA) this is + # (Kr/NA)*c_atom^2, and the molar flux is Kr*c_mol^2. The written + # coefficient checks that factor of two against the exported face + # concentration below. + festim.SurfaceReactionBC( + reactant=[mobile, mobile], + gas_pressure=0.0, + k_r0=F6_KR / (2.0 * AVOGADRO), + E_kr=0.0, + k_d0=0.0, + E_kd=0.0, + subdomain=right, + ), + ] + model.reactions = [ + # c_atom = NA*c_mol and N_atom = NA*N_mol. Dividing the second-order + # trapping constant by NA keeps k0*c_mol invariant; p0 is first order + # and unchanged. The equilibrium K=k0/p0 is therefore divided by NA, + # and N_atom*K_atom = N_mol*K_mol. + festim.Reaction( + reactant=[mobile, empty], + product=[trapped], + k_0=F6_K0 / AVOGADRO, + E_k=0.0, + p_0=F6_P0, + E_p=0.0, + volume=volume, + ) + ] + model.initial_conditions = [ + festim.InitialConcentration(value=F6_TRAP_N * AVOGADRO, species=empty, volume=volume) + ] + model.settings = festim.Settings( + atol=AVOGADRO * 1e-14, + rtol=1e-10, + transient=True, + element_degree=2, + final_time=F6_T_END + 2.0 * dt, + stepsize=festim.Stepsize( + initial_value=F6_INITIAL_DT, + growth_factor=F6_GROWTH, + cutback_factor=0.8, + target_nb_iterations=100, + max_stepsize=dt, + milestones=list(F6_TIMES), + ), + ) + inlet = festim.SurfaceFlux(field=mobile, surface=left) + outlet = festim.SurfaceFlux(field=mobile, surface=right) + profile = festim.Profile1DExport(field=mobile, subdomain=volume) + trapped_profile = festim.Profile1DExport(field=trapped, subdomain=volume) + mobile_inventory = festim.TotalVolume(field=mobile, volume=volume) + trapped_inventory = festim.TotalVolume(field=trapped, volume=volume) + model.exports = [ + inlet, + outlet, + profile, + trapped_profile, + mobile_inventory, + trapped_inventory, + ] + model.show_progress_bar = False + model.initialise() + model.run() + n = len(outlet.data) + if n < 2: + raise ValueError("F6 FESTIM outlet export has fewer than 2 timesteps") + if len(model.timesteps) != n: + raise ValueError(f"F6 FESTIM timesteps ({len(model.timesteps)}) and exports ({n}) differ") + times = [float(v) for v in model.timesteps] + x = np.asarray(profile.x, dtype=float).reshape(-1) + order = np.argsort(x) + x = x[order] + mobile_profiles = np.asarray(profile.data, dtype=float)[:, order] / AVOGADRO + trapped_profiles = np.asarray(trapped_profile.data, dtype=float)[:, order] / AVOGADRO + jl = np.asarray(inlet.data, dtype=float).reshape(-1) / AVOGADRO + jr = np.asarray(outlet.data, dtype=float).reshape(-1) / AVOGADRO + im = np.asarray(mobile_inventory.data, dtype=float).reshape(-1) / AVOGADRO + it = np.asarray(trapped_inventory.data, dtype=float).reshape(-1) / AVOGADRO + return _f6_reduce(times, jl, jr, x, mobile_profiles, trapped_profiles, im, it) + + +def _f6_flux_error(first: dict[str, Any], second: dict[str, Any]) -> float: + jss = max(abs(first["jss"]), abs(second["jss"])) + floor = 1.0e-3 * jss + return max( + abs(a - b) / max(abs(b), floor) + for a, b in zip(first["flux_t"], second["flux_t"], strict=True) + ) + + +def _f6_inventory_error( + first: dict[str, Any], second: dict[str, Any], key: str, scale: float +) -> float: + floor = 1.0e-3 * scale + return max( + abs(a - b) / max(abs(a), abs(b), floor) + for a, b in zip(first[key], second[key], strict=True) + ) + + +def _f6_profile_error( + first: dict[str, Any], second: dict[str, Any], key: str, norm: float +) -> float: + grid = np.linspace( + max(first["x"][0], second["x"][0]), min(first["x"][-1], second["x"][-1]), 201 + ) + worst = 0.0 + for a, b in zip(first[key], second[key], strict=True): + ia = np.interp(grid, first["x"], a) + ib = np.interp(grid, second["x"], b) + worst = max(worst, float(np.max(np.abs(ia - ib))) / norm) + return worst + + +def _f6_reaction_law_error(result: dict[str, Any]) -> float: + """FESTIM factor-of-two check: J_out = Kr c_face^2 (molar units).""" + if abs(result["x"][-1] - L) > 1e-12 * L: + raise ValueError("F6 FESTIM profile does not end at the outlet face") + return abs(result["jss"] - F6_KR * result["c"][-1] ** 2) / result["jss"] + + +def _f6_trap_equilibrium_error(result: dict[str, Any]) -> float: + """FESTIM trap reaction check: c_t = N K c/(1+K c), K=k0/p0.""" + k = F6_K0 / F6_P0 + c = np.asarray(result["c"], dtype=float) + expected = F6_TRAP_N * k * c / (1.0 + k * c) + return float(np.max(np.abs(np.asarray(result["ct"], dtype=float) - expected))) / F6_TRAP_N + + +def _f6_scalar_oracle() -> tuple[float, float]: + """Steady recombination face and flux with traps (linear c(x) still).""" + a = D / L + face = 2.0 * a * C0 / (a + math.sqrt(a * a + 4.0 * F6_KR * a * C0)) + return face, a * (C0 - face) + + +def _f6_cached_run(code: str, cells: int, dt: float, run: Any) -> dict[str, Any]: + """Cache F6 reductions only with verified runtime and model identity.""" + import nucleide._internal as extension + + identity = { + "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "facade_sha256": hashlib.sha256(Path(tri.__file__).read_bytes()).hexdigest(), + "extension_sha256": hashlib.sha256(Path(extension.__file__).read_bytes()).hexdigest(), + "case": "F6", + "code": code, + "cells": cells, + "dt": dt, + "parameters": [ + L, + D, + C0, + F6_KR, + F6_K0, + F6_P0, + F6_TRAP_N, + F6_TEMPERATURE, + AVOGADRO, + F6_TIMES, + F6_T_END, + F6_IMAGE, + F6_INITIAL_DT, + F6_GROWTH, + ], + "python": platform.python_version(), + "packages": { + name: common._dist_version(name) + for name in ( + "festim", + "fenics-dolfinx", + "scifem", + "io4dolfinx", + "fenicsx-compat", + "numpy", + ) + }, + } + cache = Path(__file__).resolve().parent / ".cache" / "f6-runs" + label = f"F6 {code} cells={cells} dt={dt:g}" + runtime, reason = _f5_runtime_identity() + if runtime is None: + print(f"{label}: {reason}", flush=True) + return cached_run(cache, identity, runtime, run, label=label) + + +def trapped_recombination_probe() -> tuple[list[list[str]], list[str]]: + """F6: one McNabb-Foster trap plus a recombining outlet, both codes.""" + rows: list[list[str]] = [] + notes = [ + "F6 single-layer trapped recombination: L=1e-3 m, D=1e-9 m²/s, " + "C0=1 mol/m³, Kr=1e-6 m⁴/(mol s), one trap k0=0.5 m³/(mol s), " + "p0=0.5 s⁻¹, N=2 mol/m³, scalar 500 K, zero Arrhenius energies. " + "Mobile and trapped initial loads are zero; outlet law J=Kr c². " + "The Oriani effective lag L²/(6D_eff)=500 s sets the output fractions " + "{0.2,0.5,1,2,5,10} (100–5000 s); no closed-form time-lag gate exists " + "for traps plus recombination. Independent space levels 50/100/200 " + "cells at dt=0.25 s and time caps 0.5/0.25/0.125 s at 200 cells; " + "each side self-converges to <1/3 of its parity gate first.", + "F6 unit conversion: FESTIM receives atomic concentrations/fluxes/" + "inventories (multiply molar values by exact SI NA=6.02214076e23 " + "mol⁻¹). The second-order trap constant is divided by NA " + "(k0_atom=k0_mol/NA), p0 is unchanged and N_atom=NA*N_mol, so " + "N*K and the Langmuir load are invariant. The surface reaction uses " + "two identical reactants: FESTIM applies two partial fluxes, so " + "k_r0=Kr/(2 NA) gives the molar flux Kr*c_mol². The exported FESTIM " + "face concentration checks that factor of two; the exported trapped " + "profile checks the distinct-reactant Langmuir equilibrium. FESTIM " + "uses quadratic elements, atol=NA*1e-14 and rtol=1e-10; Nucleide uses " + "the landed CN kernel with rtol=1e-10/atol=1e-14 and the same " + "hand-derived initial Dirichlet-layer flux as F5.", + "F6 gates (predeclared from the refinement evidence, not tuned to a " + "desired parity): J(t) 3% with a 1e-3*J_ss denominator floor, mobile " + "and trapped inventory histories 2%, mobile and trapped profile " + "histories 2% (normalized by C0 and N), FESTIM reaction-law and " + "Langmuir checks 2%, late-flux change 2%/3, mobile-plus-trapped " + "inventory balance 1e-3 relative with independent stride-2/4 flux " + "quadrature below 1e-3/3. All refinement changes must be below one " + "third of the corresponding gate; otherwise F6 is INCONCLUSIVE and " + "the script exits nonzero. Requested output times are sampled only " + "between exported FESTIM brackets; a missing bracket or a short " + "history fails instead of extrapolating.", + ] + try: + festim = _require_festim() + except ProbeSkip as exc: + rows.append( + ["F6 external trapped-recombination probe", str(exc), "available oracle", "SKIP"] + ) + notes.append(f"F6 SKIP: {exc}") + return rows, notes + except Exception as exc: # noqa: BLE001 — installed oracle errors must fail + rows.append( + [ + "F6 oracle configuration", + repr(exc), + "working FESTIM 2.1", + _check(False, "F6 oracle configuration"), + ] + ) + notes.append(f"F6 FAIL: installed oracle could not be loaded: {exc!r}") + return rows, notes + notes.append( + f"F6 required image: {F6_IMAGE}; Python {platform.python_version()}; " + + ", ".join( + f"{name}={common._dist_version(name)}" + for name in ("festim", "fenics-dolfinx", "scifem", "io4dolfinx", "numpy") + ) + ) + runtime, reason = _f5_runtime_identity() + if runtime is None: + notes.append(f"F6 persistent cache disabled: {reason}; all calculations run fresh.") + else: + digest = hashlib.sha256(json.dumps(runtime, sort_keys=True).encode()).hexdigest() + notes.append( + f"F6 actual runner image ID: {runtime['image_id']}; runtime fingerprint " + f"SHA-256 {digest}. The environment is held fixed during this probe." + ) + + def gate(label: str, error: float, threshold: float) -> None: + rows.append( + [ + f"F6 {label}", + fmt(error), + f"< {threshold:g}", + _check(math.isfinite(error) and error < threshold, f"F6 {label}"), + ] + ) + + native_scale_m = C0 * L + native_scale_t = F6_TRAP_N * L + try: + native = [ + _f6_cached_run( + "Nucleide", cells, dt, lambda cells=cells, dt=dt: _f6_nucleide(cells, dt) + ) + for cells, dt in F6_LEVELS + ] + external = [ + _f6_cached_run( + "FESTIM", + cells, + dt, + lambda cells=cells, dt=dt: _f6_festim(festim, cells, dt), + ) + for cells, dt in F6_LEVELS + ] + converged = True + for name, runs in (("Nucleide", native), ("FESTIM", external)): + for label, a, b in ( + ("space 50→100", 0, 1), + ("space 100→200", 1, 2), + ("time .5→.25", 3, 2), + ("time .25→.125", 2, 4), + ): + flux_error = _f6_flux_error(runs[a], runs[b]) + mobile_error = _f6_inventory_error( + runs[a], runs[b], "mobile_inventory_t", native_scale_m + ) + trapped_error = _f6_inventory_error( + runs[a], runs[b], "trapped_inventory_t", native_scale_t + ) + mobile_profile_error = _f6_profile_error(runs[a], runs[b], "profiles", C0) + trapped_profile_error = _f6_profile_error( + runs[a], runs[b], "trapped_profiles", F6_TRAP_N + ) + ok = ( + flux_error < F6_FLUX_GATE / 3.0 + and mobile_error < F6_INVENTORY_GATE / 3.0 + and trapped_error < F6_INVENTORY_GATE / 3.0 + and mobile_profile_error < F6_PROFILE_GATE / 3.0 + and trapped_profile_error < F6_PROFILE_GATE / 3.0 + ) + converged = converged and ok + rows.append( + [ + f"F6 {name} {label} J(t)/mobile inventory", + f"{flux_error:.6e} / {mobile_error:.6e}", + f"< {F6_FLUX_GATE / 3.0:.3e} / {F6_INVENTORY_GATE / 3.0:.3e}", + "PASS" if ok else "INCONCLUSIVE", + ] + ) + rows.append( + [ + f"F6 {name} {label} trapped inventory/profiles", + f"{trapped_error:.6e} / {mobile_profile_error:.6e} / " + f"{trapped_profile_error:.6e}", + f"< {F6_INVENTORY_GATE / 3.0:.3e} / " + f"{F6_PROFILE_GATE / 3.0:.3e} / {F6_PROFILE_GATE / 3.0:.3e}", + "PASS" if ok else "INCONCLUSIVE", + ] + ) + final = runs[-1] + gate(f"{name} late flux change (0.9 tend→tend)", final["late_change"], F6_LATE_GATE) + gate(f"{name} mobile+trapped inventory balance", final["balance"], F6_BALANCE_GATE) + for index, error in enumerate(final["quadrature"]): + gate( + f"{name} flux quadrature stride {2**index}→{2 ** (index + 1)}", + error, + F6_QUADRATURE_GATE, + ) + notes.append( + f"F6 {name} balance grid: {final['grid']}; mobile+trapped inventory " + f"change {final['inventory_change']:.12e} mol/m², net integrated " + f"inlet minus outlet {final['net_integral']:.12e} mol/m², absolute " + f"throughput {final['throughput']:.12e} mol/m². Requested end " + f"{final['requested_end']:.17g} s; actual end " + f"{final['actual_end']:.17g} s; endpoint roundoff allowance " + f"{final['endpoint_roundoff_allowance']:.6e} s. Balance uses the " + "actual exported initial inventories and time grid." + ) + if converged: + for index, (cells, dt) in enumerate(F6_LEVELS): + gate( + f"cross-code J(t), cells={cells}, dt={dt}", + _f6_flux_error(native[index], external[index]), + F6_FLUX_GATE, + ) + gate( + "cross-code mobile inventory history", + _f6_inventory_error(native[-1], external[-1], "mobile_inventory_t", native_scale_m), + F6_INVENTORY_GATE, + ) + gate( + "cross-code trapped inventory history", + _f6_inventory_error( + native[-1], external[-1], "trapped_inventory_t", native_scale_t + ), + F6_INVENTORY_GATE, + ) + gate( + "cross-code mobile profile history", + _f6_profile_error(native[-1], external[-1], "profiles", C0), + F6_PROFILE_GATE, + ) + gate( + "cross-code trapped profile history", + _f6_profile_error(native[-1], external[-1], "trapped_profiles", F6_TRAP_N), + F6_PROFILE_GATE, + ) + gate( + "FESTIM two-reactant reaction law J=Kr c_face²", + _f6_reaction_law_error(external[-1]), + F6_REACTION_GATE, + ) + gate( + "FESTIM trap Langmuir equilibrium", + _f6_trap_equilibrium_error(external[-1]), + F6_TRAP_EQ_GATE, + ) + face, jss = _f6_scalar_oracle() + steady = tri.steady( + L, + F6_LEVELS[-1][0], + D, + {"kind": "dirichlet", "value": C0}, + {"kind": "recombination", "rate": F6_KR}, + traps=[ + { + "k0": F6_K0, + "p0": F6_P0, + "site_density": F6_TRAP_N, + "e_k": 0.0, + "e_p": 0.0, + } + ], + temperature=[F6_TEMPERATURE], + ) + gate("Nucleide steady scalar flux", abs(steady["flux_right"] - jss) / jss, 0.02) + expected = C0 + (face - C0) * np.asarray(steady["centres"]) / L + gate( + "Nucleide steady mobile profile", + float(np.max(np.abs(np.asarray(steady["mobile"]) - expected))) / C0, + 0.02, + ) + gate( + "Nucleide final vs steady mobile profile", + float(np.max(np.abs(np.asarray(native[-1]["c"]) - np.asarray(steady["mobile"])))) + / C0, + 0.02, + ) + steady_trapped = np.asarray(steady["trapped"], dtype=float)[:, 0] + gate( + "Nucleide final vs steady trapped profile", + float(np.max(np.abs(np.asarray(native[-1]["ct"]) - steady_trapped))) / F6_TRAP_N, + 0.02, + ) + else: + rows.append( + ["F6 cross-code parity", "refinement not established", "converged", "INCONCLUSIVE"] + ) + _check(False, "F6 self-convergence inconclusive") + except Exception as exc: # noqa: BLE001 — configured solver failure must fail + rows.append( + ["F6 execution", repr(exc), "successful calculation", _check(False, "F6 execution")] + ) + notes.append(f"F6 FAIL: configured probe calculation failed: {exc!r}") + return rows, notes + + def main() -> int: report = Report( "tritium_festim", "Tritium 1D kernel vs FESTIM 2.1 probe (`tritium_vs_festim.py`)" @@ -1374,10 +2049,13 @@ def main() -> int: "digest-pinned DOLFINx image (docker; never the main validation " "container, never the Rust workspace). Progression F1 trap-free " "Dirichlet-Dirichlet, F2 one McNabb-Foster trap, F3 Sieverts ends, " - "F4 two-layer stack; F5 independently refined trap-free recombination outlet. Always-run " - "legs VV Val-1da (analytic permeation) and M1 (manufactured-solution " - "order) gate the Nucleide side everywhere; every FESTIM leg SKIPs " - "loudly with its reason outside the probe image." + "F4 two-layer stack; F5 independently refined trap-free recombination " + "outlet; F6 one McNabb-Foster trap combined with the same " + "recombination outlet, with mobile/trapped inventories and a " + "mobile-plus-trapped mass balance. Always-run legs VV Val-1da " + "(analytic permeation) and M1 (manufactured-solution order) gate the " + "Nucleide side everywhere; every FESTIM leg SKIPs loudly with its " + "reason outside the probe image." ) import nucleide._internal as compiled @@ -1409,6 +2087,19 @@ def main() -> int: report.table(["Recombination gate", "Value", "Gate", "Status"], f5_rows) for note in f5_notes: report.prose(note) + f6_rows, f6_notes = trapped_recombination_probe() + report.table(["Trapped-recombination gate", "Value", "Gate", "Status"], f6_rows) + for note in f6_notes: + report.prose(note) + if importlib.util.find_spec("festim") is None: + # A no-oracle run must not replace the committed probe results with a + # page of SKIP rows. The always-run VV/M1 tables above still execute. + print( + "SKIP: FESTIM not installed; committed tritium/FESTIM probe results " + "were not overwritten.", + file=sys.stderr, + ) + return 0 report.emit() if FAILURES: diff --git a/website/AGENTS.md b/website/AGENTS.md index 8e5b58b..16be5c0 100644 --- a/website/AGENTS.md +++ b/website/AGENTS.md @@ -22,6 +22,13 @@ Parent-level Rust/Python/verification rules remain in the root `AGENTS.md`. flat-per-eV and uniform-source-density assumptions visible, cap source/target spectra and voxel/zone counts at 200, and clear computed results when inputs change. Preserve copy and equal-count modes alongside volume weighting. +- **Photon source handoff**: the `transport-source` demo calls the shared + `r2s` source contract for validation, totals, density and joint + voxel/group probabilities; it never re-implements the arithmetic in + TypeScript. Cooling buttons select declared snapshots (no browser decay + physics); exact selection goes through the shared kernel. Keep units next + to values, label assumptions separately from errors, cap cells/groups at + 200, and reject all-zero sampling without treating zero voxels as invalid. - **Tutorial forms**: group related source/target inputs, keep labels short and units separate, and verify desktop/mobile layout visually. Input rows must stay aligned when labels wrap; stack fields on narrow screens. diff --git a/website/e2e/smoke.spec.ts b/website/e2e/smoke.spec.ts index f1f2c7b..e1144e8 100644 --- a/website/e2e/smoke.spec.ts +++ b/website/e2e/smoke.spec.ts @@ -180,6 +180,12 @@ end`, { button: "Parse", output: "text=S1 total activity:" }, ], }, + { + path: "tutorials/interactive/transport-source", + button: "Evaluate source", + output: "text=Joint voxel/group probabilities", + extraSteps: [{ button: "Check selection", output: "text=indices: [1]" }], + }, { path: "tutorials/interactive/deterministic", button: "Parse", @@ -327,6 +333,28 @@ NUCLIDE PU239 94239 2 }, ]; +test("transport source demo handles narrow layout and invalid input", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto("tutorials/interactive/transport-source"); + await waitForWasmReady(page); + await expect(page.getByText("photons/s", { exact: false }).first()).toBeVisible(); + + const firstCell = page.getByLabel("voxel 1 group 1 photons per second"); + await firstCell.fill("-5"); + await page.getByRole("button", { name: "Evaluate source", exact: true }).click(); + await expect(page.getByText("invalid source", { exact: false })).toBeVisible(); + await expect(page.getByText("source-strength-negative", { exact: false })).toBeVisible(); + + await page.locator("#cooling-request").fill("1"); + await page.getByRole("button", { name: "Check selection", exact: true }).click(); + await expect(page.getByText("not among available times", { exact: false })).toBeVisible(); + + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1, + ); + expect(overflow).toBe(false); +}); + for (const { path, button, output, cell, chart, paste, extraSteps } of INTERACTIVE_PAGES) { test(`interactive demo: ${path}`, async ({ page }) => { await page.goto(path); diff --git a/website/src/components/interactive/InteractiveDemo.astro b/website/src/components/interactive/InteractiveDemo.astro index 62662c0..f333a7c 100644 --- a/website/src/components/interactive/InteractiveDemo.astro +++ b/website/src/components/interactive/InteractiveDemo.astro @@ -27,7 +27,8 @@ interface Props { | "blanket" | "equilibrium" | "unfold" - | "clearance"; + | "clearance" + | "transport-source"; } const { kind } = Astro.props; diff --git a/website/src/components/interactive/InteractiveDemo.tsx b/website/src/components/interactive/InteractiveDemo.tsx index 58a5591..8f718bd 100644 --- a/website/src/components/interactive/InteractiveDemo.tsx +++ b/website/src/components/interactive/InteractiveDemo.tsx @@ -24,6 +24,7 @@ import { EquilibDemo } from "./EquilibDemo"; import { UnfoldDemo } from "./UnfoldDemo"; import { ClearanceDemo } from "./ClearanceDemo"; import { SubletDemo } from "./SubletDemo"; +import { PhotonSourceDemo } from "./PhotonSourceDemo"; interface InteractiveDemoProps { kind: @@ -52,7 +53,8 @@ interface InteractiveDemoProps { | "equilibrium" | "unfold" | "clearance" - | "sublet"; + | "sublet" + | "transport-source"; } export function InteractiveDemo({ kind }: InteractiveDemoProps) { @@ -109,6 +111,8 @@ export function InteractiveDemo({ kind }: InteractiveDemoProps) { return ; case "sublet": return ; + case "transport-source": + return ; default: return
Unknown demo kind: {kind}
; } diff --git a/website/src/components/interactive/PhotonSourceDemo.tsx b/website/src/components/interactive/PhotonSourceDemo.tsx new file mode 100644 index 0000000..ed249e8 --- /dev/null +++ b/website/src/components/interactive/PhotonSourceDemo.tsx @@ -0,0 +1,315 @@ +import { useEffect, useState } from "react"; +import { useWasm } from "../../lib/wasm"; +import type { + PhotonSourceEvaluateResult, + PhotonSourceInputJson, + WasmApi, +} from "../../types/nucleide-wasm"; +import { Button } from "@nukehub/docs-kit/components/ui/Button"; +import { Input } from "@nukehub/docs-kit/components/ui/Input"; +import { Label } from "@nukehub/docs-kit/components/ui/Label"; + +// Synthetic snapshots: three declared cooling times, two voxels, three +// groups. The browser never computes decay physics; it selects one declared +// snapshot and lets the shared Rust source contract validate and normalize it. +const EDGES_EV = [0, 1, 3, 10]; +const VOLUMES_CM3 = [1, 1]; +const TIMES = [ + { + coolingS: 0, + strengths: [ + [100, 0, 20], + [0, 300, 0], + ], + }, + { + coolingS: 3600, + strengths: [ + [71, 0, 14], + [0, 212, 0], + ], + }, + { + coolingS: 7200, + strengths: [ + [50, 0, 10], + [0, 150, 0], + ], + }, +]; + +function initialText(): string[][] { + return TIMES[0].strengths.map((row) => row.map(String)); +} + +export function PhotonSourceDemo() { + const { wasm, ready, error } = useWasm(); + const [timeIndex, setTimeIndex] = useState(0); + const [strengthsText, setStrengthsText] = useState(initialText); + const [result, setResult] = useState(null); + const [localError, setLocalError] = useState(null); + const [requestedText, setRequestedText] = useState("3600"); + const [selection, setSelection] = useState(null); + + function buildInput(text: string[][]): PhotonSourceInputJson { + const strengths = text.map((row, voxel) => + row.map((cell, group) => { + if (cell.trim() === "") { + throw new Error(`voxel ${voxel + 1} group ${group + 1} is empty`); + } + const value = Number(cell); + if (!Number.isFinite(value)) { + throw new Error(`voxel ${voxel + 1} group ${group + 1} is not a finite number`); + } + return value; + }), + ); + return { + meshShape: [2, 1, 1], + lowerLeftCm: [0, 0, 0], + upperRightCm: [2, 1, 1], + voxelVolumesCm3: VOLUMES_CM3, + edgesEv: EDGES_EV, + coolingS: TIMES[timeIndex].coolingS, + strengthsPhotonsPerS: strengths, + }; + } + + function evaluate(api: WasmApi, text: string[][]) { + try { + const next = api.photonSourceEvaluate(buildInput(text)); + setResult(next); + setLocalError(null); + } catch (e) { + setResult(null); + setLocalError(e instanceof Error ? e.message : String(e)); + } + } + + useEffect(() => { + if (wasm) evaluate(wasm, initialText()); + // The first evaluation deliberately runs once per loaded module; later + // edits are explicit so a malformed cell remains visible. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [wasm]); + + function selectTime(index: number) { + setTimeIndex(index); + setStrengthsText(TIMES[index].strengths.map((row) => row.map(String))); + setSelection(null); + } + + function updateCell(voxel: number, group: number, value: string) { + setStrengthsText((current) => + current.map((row, i) => + i === voxel ? row.map((cell, g) => (g === group ? value : cell)) : row, + ), + ); + } + + function checkSelection() { + if (!wasm) return; + try { + const requested = requestedText + .split(",") + .map((part) => part.trim()) + .filter((part) => part.length > 0) + .map((part) => Number(part)); + setSelection( + wasm.photonSourceSelectCooling( + TIMES.map((entry) => entry.coolingS), + requested, + ), + ); + setLocalError(null); + } catch (e) { + setSelection(null); + setLocalError(e instanceof Error ? e.message : String(e)); + } + } + + const total = result?.total_photons_per_s ?? null; + + return ( +
+
+ Cooling time + {TIMES.map((entry, index) => ( + + ))} + + declared snapshots, no decay calculation in the browser + +
+ +
+
+
+

Voxel spectra

+

+ Integrated photons/s. Regular mesh (2, 1, 1); group edges {EDGES_EV.join(", ")} eV; + voxel volumes {VOLUMES_CM3.join(", ")} cm³. +

+
+
+ + + + + {EDGES_EV.slice(0, -1).map((low, group) => ( + + ))} + + + + {strengthsText.map((row, voxel) => ( + + + {row.map((cell, group) => ( + + ))} + + ))} + +
Voxel + {low}–{EDGES_EV[group + 1]} eV +
+ {voxel} · {VOLUMES_CM3[voxel]} cm³ + + updateCell(voxel, group, event.target.value)} + /> +
+
+
+ + {total !== null && ( + + Total {total.toFixed(3)} photons/s + + )} +
+ {error &&

{error}

} + {localError &&

{localError}

} + {!ready && !error && ( +

Loading the live demo…

+ )} +
+ +
+
+

Checks

+ {result ? ( +

+ {result.valid ? "valid source" : "invalid source"} · {result.issue_count} issue + {result.issue_count === 1 ? "" : "s"} + {result.truncated ? " (diagnostics capped)" : ""} +

+ ) : ( +

Evaluate to run the shared validator.

+ )} +
+ {result && result.issues.length > 0 && ( +
    + {result.issues.map((issue, index) => ( +
  • + + {issue.severity} + {" "} + {issue.code} at {issue.location}: {issue.message}{" "} + {issue.remedy} +
  • + ))} +
+ )} + {result?.sampling_error && ( +

{result.sampling_error}

+ )} + {result?.joint_probabilities && ( +
+

Joint voxel/group probabilities

+

+ Sampling uses these pairs directly; independent spatial and energy marginals would + invent cross-pairs that carry no source. +

+
+ + + + + {EDGES_EV.slice(0, -1).map((low, group) => ( + + ))} + + + + {result.joint_probabilities.map((row, voxel) => ( + + + {row.map((probability, group) => ( + + ))} + + ))} + +
Voxel + group {group} +
{voxel} + {(probability * 100).toFixed(2)}% +
+
+
+ )} +
+
+ +
+

Exact cooling selection

+

+ Available offsets: {TIMES.map((entry) => entry.coolingS).join(", ")} s. Requested offsets + must match exactly; duplicates and near matches fail. +

+
+
+ + setRequestedText(event.target.value)} + /> +
+ + {selection && ( + indices: [{selection.join(", ")}] + )} +
+
+
+ ); +} diff --git a/website/src/types/nucleide-wasm.d.ts b/website/src/types/nucleide-wasm.d.ts index 2d3d0c8..0fcd087 100644 --- a/website/src/types/nucleide-wasm.d.ts +++ b/website/src/types/nucleide-wasm.d.ts @@ -631,6 +631,38 @@ export interface VoxelPhotonSummary { total: number; } +export interface PhotonSourceInputJson { + meshShape: number[]; + lowerLeftCm: number[]; + upperRightCm: number[]; + voxelVolumesCm3: number[]; + edgesEv: number[]; + coolingS: number; + strengthsPhotonsPerS: number[][]; +} + +export interface PhotonSourceIssueJson { + code: string; + severity: "error" | "warning" | "assumption"; + location: string; + message: string; + remedy: string; +} + +export interface PhotonSourceEvaluateResult { + valid: boolean; + issues: PhotonSourceIssueJson[]; + issue_count: number; + truncated: boolean; + total_photons_per_s: number | null; + voxel_totals_photons_per_s: number[]; + group_totals_photons_per_s: number[]; + density_photons_per_s_cm3: number[][] | null; + energy_probabilities: number[][] | null; + joint_probabilities: number[][] | null; + sampling_error: string | null; +} + export interface CompendiumEntryInfo { name: string; acronym: string[]; @@ -1162,6 +1194,8 @@ export interface WasmApi { r2sFromSnapshot(snapshot: SnapshotInputJson): SnapshotBundleJson; voxelTagsFromTotals(input: VoxelTagsInputJson): VoxelTagsSummary; voxelPhotonSums(input: VoxelPhotonInputJson): VoxelPhotonSummary; + photonSourceEvaluate(input: PhotonSourceInputJson): PhotonSourceEvaluateResult; + photonSourceSelectCooling(availableS: number[], requestedS: number[]): number[]; parseIsotxs(text: string): IsotxsSummary; partisnRender(deck: PartisnDeck): string; partisnValidate(deck: PartisnDeck, isotxsText: string): void; From 45779e4aac6e7be5bba4c9cec5561dc6d023d4a4 Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 17:22:33 +0600 Subject: [PATCH 2/7] Add real-data OpenMC validation and expand photon source demo --- CHANGELOG.md | 6 +- .../interactive/transport-source.mdx | 16 +- .../python/activation-to-transport.md | 8 + validation/AGENTS.md | 7 + validation/README.md | 28 +- validation/openmc_real_data_probe.py | 325 ++++++++++++++++++ .../interactive/PhotonSourceDemo.tsx | 76 ++-- 7 files changed, 437 insertions(+), 29 deletions(-) create mode 100644 validation/openmc_real_data_probe.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b120850..61a36f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,7 +51,11 @@ workspace crates from tags. recording the observed tally normalization, C-order/Fortran-order mesh mapping, differential histogram density, XML roundtrip, seeded joint-source sampling and a vacuum track-length tally at two source strengths that pins - the integrated/rate-scaled convention; no interacting transport. + the integrated/rate-scaled convention; no interacting transport. An optional + real-data companion (`validation/openmc_real_data_probe.py`) runs a bounded + OpenMC 0.16 transport check with caller-mounted NNDC HDF5 files and verifies + source-strength scaling, per-source vs rate-scaled flux agreement and the + package `normalize_flux` path. ### Fixed diff --git a/docs/tutorials/interactive/transport-source.mdx b/docs/tutorials/interactive/transport-source.mdx index 8847c9f..9820661 100644 --- a/docs/tutorials/interactive/transport-source.mdx +++ b/docs/tutorials/interactive/transport-source.mdx @@ -13,11 +13,11 @@ package uses. ## Voxel spectra and units -The mesh is a regular `(2, 1, 1)` grid with caller voxel volumes `1` and `1` cm³. -The table shows **integrated photons/s** per group, not a density and not a -probability. Change a value and select **Evaluate source**; the shared -validator reports stable issue codes and keeps modelling assumptions separate -from errors. +The mesh is a regular `(2, 2, 1)` grid with four 1 cm³ voxels and four photon +groups spanning 0–0.1, 0.1–0.5, 0.5–2 and 2–10 MeV. The table shows +**integrated photons/s** per group, not a density and not a probability. +Change a value and select **Evaluate source**; the shared validator reports +stable issue codes and keeps modelling assumptions separate from errors. Negative values, non-finite cells, a zero total, irregular edges and mismatched dimensions raise clear errors. A zero-source voxel inside a nonzero source is @@ -44,4 +44,10 @@ files, and reproducibility manifests. See [Activation to transport](../python/activation-to-transport.md) for the full workflow. +The browser snapshots are synthetic because no nuclear data or transport +engine is shipped to the page. The shared kernel is checked against real +OpenMC 0.16 transport with a caller-mounted NNDC HDF5 library in +`validation/openmc_real_data_probe.py`; that check covers normalization, +source-strength scaling and data loading, not dose or transport accuracy. + diff --git a/docs/tutorials/python/activation-to-transport.md b/docs/tutorials/python/activation-to-transport.md index 48b56d9..489c27b 100644 --- a/docs/tutorials/python/activation-to-transport.md +++ b/docs/tutorials/python/activation-to-transport.md @@ -267,3 +267,11 @@ without it. Exporting a source is not transport validation: source conservation, XML/API compatibility and spatial-energy sampling are separate claims from shutdown dose rate, which needs geometry, evaluated photon data, a dose response and an independent reference. + +The validation harness carries the external checks separately: +`validation/openmc_handoff_probe.py` pins the OpenMC 0.16 source/tally/XML +semantics, and `validation/openmc_real_data_probe.py` runs a bounded +fixed-source water/iron sphere with a caller-mounted NNDC HDF5 library and +checks the same per-source and rate-scaled conversions through +`normalize_flux`. The latter is a normalization and data-loading check, not a +dose or transport benchmark. diff --git a/validation/AGENTS.md b/validation/AGENTS.md index 24a196b..16bea29 100644 --- a/validation/AGENTS.md +++ b/validation/AGENTS.md @@ -91,6 +91,13 @@ reference tally (`magic_tally.txt`), and the committed results document. initialize OpenMC; it must not read evaluated data or run interacting transport. Record the probe's JSON output and never turn source sampling or the void tally into a physics, transport or dose claim. +- `openmc_real_data_probe.py` is the optional real-data companion: it requires + caller-mounted `H1.h5`, `O16.h5` and `Fe56.h5`, writes only a temporary + `cross_sections.xml`, and runs a bounded fixed-source water/iron sphere. Its + claims are limited to source-strength scaling, the per-source vs rate-scaled + flux conversion, data loading and the package `normalize_flux` path. Never + describe it as a transport benchmark, shutdown-dose validation or + independent physics oracle; never vendor or download the caller's data. - Fresh ACTINV activation comparisons execute the source-pinned external example separately from the synthetic probe. Retain original/compatible script hashes and diff, verified data hashes, compiled-extension identity, diff --git a/validation/README.md b/validation/README.md index 33c59fe..32e7067 100644 --- a/validation/README.md +++ b/validation/README.md @@ -21,7 +21,8 @@ committed `results.md` holds the measured numbers that the paper quotes. | `unfold_vs_analytic.py` | SAND-II neutron spectrum unfolding: synthetic forward-fold round-trips + IRDFF-II analytical benchmark shapes (published facts, cited; no external unfolding oracle exists) | | `equilib_vs_desc.py` | Equilibrium data readers: synthetic classic-`wout` magic/format/Jacobian gates + `&INDATA` grammar gates (always run) with DESC/simsopt container probes (loud SKIP outside) | | `actinv_handoff_probe.py` | Optional pinned ACTINV CLI synthetic export/readback, with binary/source hashes and conservation receipts; no activation solve | -| `openmc_handoff_probe.py` | Pinned OpenMC 0.16.0 source/tally normalization, C-to-F mesh ordering, histogram-density, XML roundtrip and seeded joint-source sampling probe; no transport run | +| `openmc_handoff_probe.py` | Pinned OpenMC 0.16.0 source/tally normalization, C-to-F mesh ordering, histogram-density, XML roundtrip and seeded joint-source sampling probe; no interacting transport | +| `openmc_real_data_probe.py` | Optional real NNDC/OpenMC HDF5 transport check: source-strength scaling, per-source vs rate-scaled flux agreement, data loading, and package `normalize_flux` | | `tritium_vs_festim.py` | 1D tritium kernel parity probe vs FESTIM 2.1 (black-box; probe-only image; see probe section below) | | `timings.py` | Coarse wall-time comparisons (Python overhead included) | | `make_figures.py` | Generates the paper figures in `figures/` from the JSON reports | @@ -199,6 +200,31 @@ docker run --rm --cpus=2 --memory=6g --memory-swap=6g \ It emits one JSON document and exits nonzero if any check fails. +## OpenMC real-data normalization probe + +`openmc_real_data_probe.py` uses an actual NNDC/OpenMC HDF5 cross-section +library to run a small fixed-source transport calculation and check the +handoff against it. It requires `H1.h5`, `O16.h5` and `Fe56.h5` in the supplied +directory; the files are mounted read-only and never copied, vendored or +downloaded. A centered 14 MeV point source in a 10 cm water sphere is run at +source strengths 1 and 10 with the same seed and 20 000 particles × 5 batches. +The probe checks that the tally scales by the strength, that +`raw × rate / volume` (per-source input) equals `raw / volume` (rate-scaled +input), and that the iron sphere produces a different flux, proving the real +cross sections were loaded. When the rebuilt Nucleide package is installed, it +also checks the same conversion through `nucleide.openmc.normalize_flux`. + +```bash +docker run --rm --cpus=2 --memory=6g --memory-swap=6g \ + -v /path/to/nndc_hdf5:/data:ro \ + -v "$PWD/validation:/work:ro" -w /work \ + localhost/nucleide-validation:latest \ + python openmc_real_data_probe.py --data-dir /data +``` + +This is a normalization/units and data-loading check, not a transport +benchmark, shutdown-dose calculation or independent physics oracle. + ## Optional ACTINV synthetic exchange probe `actinv_handoff_probe.py` checks the released ACTINV 1.7.2 Linux exporter diff --git a/validation/openmc_real_data_probe.py b/validation/openmc_real_data_probe.py new file mode 100644 index 0000000..cee808f --- /dev/null +++ b/validation/openmc_real_data_probe.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +"""OpenMC 0.16 real-data normalization probe (no dose or transport claim). + +Runs a small fixed-source neutron problem with an actual NNDC/OpenMC HDF5 +cross-section library and checks the activation-to-transport normalization +contract against the transport result: + +- A centered 14 MeV point source in a 10 cm radius water sphere. +- Two runs with the same seed and particle count, source strengths 1 and 10. +- The fixed-source tally must scale exactly by the source strength, so the + per-source conversion ``raw * rate / volume`` for the unit-strength run + must agree with the rate-scaled conversion ``raw / volume`` for the + strength-10 run. +- A second material (iron) must produce a different tally, confirming that + the HDF5 cross sections were actually loaded and used. +- When ``nucleide.openmc.normalize_flux`` is importable, the same conversion + is checked through the package API. + +This is a normalization/units and data-loading check. It is not a transport +benchmark, a shutdown-dose calculation, or an independent physics oracle. +The real nuclear data are supplied by the caller and never vendored or +downloaded by this script. + +Usage: + python validation/openmc_real_data_probe.py --data-dir /path/to/hdf5 + +The data directory must contain ``H1.h5``, ``O16.h5`` and ``Fe56.h5``. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import sys +import tempfile +import traceback +from pathlib import Path +from typing import Any + +EXPECTED_OPENMC = "0.16.0" +RADIUS_CM = 10.0 +SOURCE_ENERGY_EV = 14.0e6 +PARTICLES = 20_000 +BATCHES = 5 +SEED = 20261116 +STRENGTHS = (1.0, 10.0) +REQUIRED_DATA = ("H1", "O16", "Fe56") + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def write_library(openmc: Any, data_dir: Path, work: Path) -> Path: + """Register the required HDF5 files and write a temporary cross_sections.xml.""" + missing = [name for name in REQUIRED_DATA if not (data_dir / f"{name}.h5").is_file()] + if missing: + raise FileNotFoundError( + f"data directory {data_dir} is missing required files: " + + ", ".join(f"{name}.h5" for name in missing) + ) + library = openmc.data.DataLibrary() + for name in REQUIRED_DATA: + library.register_file(str(data_dir / f"{name}.h5")) + path = work / "cross_sections.xml" + library.export_to_xml(str(path)) + return path + + +def run_case(openmc: Any, work: Path, material_name: str, strength: float) -> dict[str, Any]: + """Run one fixed-source sphere case and return the cell flux tally.""" + case_dir = work / f"{material_name}-s{strength:g}" + case_dir.mkdir() + sphere = openmc.Sphere(r=RADIUS_CM, boundary_type="vacuum") + cell = openmc.Cell(region=-sphere) + if material_name == "water": + material = openmc.Material(name="water") + material.add_nuclide("H1", 2.0) + material.add_nuclide("O16", 1.0) + material.set_density("g/cm3", 1.0) + elif material_name == "iron": + material = openmc.Material(name="iron") + material.add_nuclide("Fe56", 1.0) + material.set_density("g/cm3", 7.874) + else: + raise ValueError(f"unknown material {material_name}") + cell.fill = material + geometry = openmc.Geometry([cell]) + materials = openmc.Materials([material]) + source = openmc.IndependentSource( + space=openmc.stats.Point((0.0, 0.0, 0.0)), + energy=openmc.stats.Discrete([SOURCE_ENERGY_EV], [1.0]), + strength=strength, + particle="neutron", + ) + settings = openmc.Settings( + particles=PARTICLES, + batches=BATCHES, + run_mode="fixed source", + seed=SEED, + output={"summary": False, "tallies": False}, + ) + settings.source = [source] + tally = openmc.Tally(name=f"{material_name} flux") + tally.filters = [openmc.CellFilter(cell)] + tally.scores = ["flux"] + model = openmc.Model( + geometry=geometry, + materials=materials, + settings=settings, + tallies=openmc.Tallies([tally]), + ) + model.export_to_xml(case_dir) + openmc.run(output=False, cwd=str(case_dir)) + statepoint = openmc.StatePoint(str(case_dir / f"statepoint.{BATCHES}.h5")) + try: + data = statepoint.tallies[tally.id] + mean = float(data.mean.ravel()[0]) + std_dev = float(data.std_dev.ravel()[0]) + finally: + close = getattr(statepoint, "close", None) + if callable(close): + close() + if not math.isfinite(mean) or mean <= 0.0: + raise RuntimeError( + f"{material_name} strength {strength}: nonpositive/nonfinite tally {mean}" + ) + if not math.isfinite(std_dev): + std_dev = None + return { + "material": material_name, + "source_strength": strength, + "mean_volume_integrated_track_length": mean, + "std_dev": std_dev, + "relative_error": (std_dev / mean if std_dev is not None else None), + } + + +def package_check( + water_unit: dict[str, Any], water_ten: dict[str, Any], volume: float +) -> dict[str, Any]: + """Check the same conversion through the optional Nucleide package.""" + try: + from nucleide import openmc as omc + except Exception as error: # pragma: no cover - optional environment + return {"status": "SKIP", "reason": f"nucleide import failed: {error}"} + if not hasattr(omc, "normalize_flux"): + return {"status": "SKIP", "reason": "nucleide.openmc.normalize_flux is absent"} + arrays_unit = { + "flux": [[water_unit["mean_volume_integrated_track_length"]]], + "rel_err": [[0.0]], + "normalization": "unknown", + "units": "unknown", + } + arrays_ten = { + "flux": [[water_ten["mean_volume_integrated_track_length"]]], + "rel_err": [[0.0]], + "normalization": "unknown", + "units": "unknown", + } + unit = omc.normalize_flux( + arrays_unit, + 10.0, + [volume], + input_normalization="per-source-volume-integrated", + ) + ten = omc.normalize_flux( + arrays_ten, + 10.0, + [volume], + input_normalization="rate-scaled-volume-integrated", + ) + unit_flux = float(unit["flux"][0][0]) + ten_flux = float(ten["flux"][0][0]) + return { + "status": "PASS" + if math.isclose(unit_flux, ten_flux, rel_tol=1e-12, abs_tol=0.0) + else "FAIL", + "per_source_flux": unit_flux, + "rate_scaled_flux": ten_flux, + "relative_difference": abs(unit_flux - ten_flux) / ten_flux, + "units": unit["units"], + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--data-dir", + type=Path, + required=True, + help="directory containing H1.h5, O16.h5 and Fe56.h5", + ) + args = parser.parse_args() + + try: + import openmc + except Exception as error: + print(json.dumps({"status": "SKIP", "reason": f"OpenMC import failed: {error}"})) + return 2 + if openmc.__version__ != EXPECTED_OPENMC: + print( + json.dumps( + { + "status": "SKIP", + "reason": f"OpenMC {openmc.__version__} != {EXPECTED_OPENMC}", + } + ) + ) + return 2 + data_dir = args.data_dir.expanduser().resolve() + if not data_dir.is_dir(): + print(json.dumps({"status": "SKIP", "reason": f"data directory not found: {data_dir}"})) + return 2 + + volume = 4.0 / 3.0 * math.pi * RADIUS_CM**3 + with tempfile.TemporaryDirectory(prefix="openmc-real-data-") as tmp: + work = Path(tmp) + cross_sections = write_library(openmc, data_dir, work) + previous = os.environ.get("OPENMC_CROSS_SECTIONS") + os.environ["OPENMC_CROSS_SECTIONS"] = str(cross_sections) + try: + water_unit = run_case(openmc, work, "water", STRENGTHS[0]) + water_ten = run_case(openmc, work, "water", STRENGTHS[1]) + iron_ten = run_case(openmc, work, "iron", STRENGTHS[1]) + except Exception as error: + print( + json.dumps( + { + "status": "FAIL", + "error": f"{type(error).__name__}: {error}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + return 1 + finally: + if previous is None: + os.environ.pop("OPENMC_CROSS_SECTIONS", None) + else: + os.environ["OPENMC_CROSS_SECTIONS"] = previous + + raw_unit = water_unit["mean_volume_integrated_track_length"] + raw_ten = water_ten["mean_volume_integrated_track_length"] + ratio = raw_ten / raw_unit + per_source_flux = raw_unit * 10.0 / volume + rate_scaled_flux = raw_ten / volume + iron_flux = iron_ten["mean_volume_integrated_track_length"] / volume + water_flux = rate_scaled_flux + ratio_ok = math.isclose(ratio, 10.0, rel_tol=1e-12, abs_tol=0.0) + conversion_ok = math.isclose(per_source_flux, rate_scaled_flux, rel_tol=1e-12, abs_tol=0.0) + data_applied = not math.isclose(water_flux, iron_flux, rel_tol=1e-3, abs_tol=0.0) + api = package_check(water_unit, water_ten, volume) + api_ok = api.get("status") in ("PASS", "SKIP") + checks = [ + {"name": "source_strength_scales_tally", "pass": ratio_ok, "ratio": ratio}, + { + "name": "per_source_and_rate_scaled_flux_agree", + "pass": conversion_ok, + "per_source_flux": per_source_flux, + "rate_scaled_flux": rate_scaled_flux, + "relative_difference": abs(per_source_flux - rate_scaled_flux) / rate_scaled_flux, + }, + { + "name": "real_cross_sections_change_transport", + "pass": data_applied, + "water_flux": water_flux, + "iron_flux": iron_flux, + }, + { + "name": "nucleide_package_normalize_flux", + "pass": api_ok, + "status": api.get("status"), + "detail": api, + }, + ] + passed = all(check["pass"] for check in checks) + summary = { + "probe": "openmc_real_data_probe", + "status": "PASS" if passed else "FAIL", + "openmc_version": openmc.__version__, + "data_dir": str(data_dir), + "required_data": { + name: { + "path": str(data_dir / f"{name}.h5"), + "sha256": sha256_file(data_dir / f"{name}.h5"), + "size_bytes": (data_dir / f"{name}.h5").stat().st_size, + } + for name in REQUIRED_DATA + }, + "case": { + "geometry": f"vacuum sphere r={RADIUS_CM} cm", + "materials": ["water (H1/O16, 1.0 g/cm3)", "iron (Fe56, 7.874 g/cm3)"], + "source": ( + f"centered 14 MeV point source, {PARTICLES} particles x " + f"{BATCHES} batches, seed {SEED}" + ), + "volume_cm3": volume, + }, + "water_unit": water_unit, + "water_ten": water_ten, + "iron_ten": iron_ten, + "checks": checks, + "limitations": [ + "This is a normalization/units and data-loading check, not an independent " + "transport or shutdown-dose validation.", + "The sphere and source are synthetic; no evaluated activation or photon " + "source data are used.", + "The real HDF5 files are caller-supplied and never vendored or downloaded.", + ], + } + print(json.dumps(summary, indent=2, sort_keys=True)) + return 0 if passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/website/src/components/interactive/PhotonSourceDemo.tsx b/website/src/components/interactive/PhotonSourceDemo.tsx index ed249e8..7b82a09 100644 --- a/website/src/components/interactive/PhotonSourceDemo.tsx +++ b/website/src/components/interactive/PhotonSourceDemo.tsx @@ -12,28 +12,35 @@ import { Label } from "@nukehub/docs-kit/components/ui/Label"; // Synthetic snapshots: three declared cooling times, two voxels, three // groups. The browser never computes decay physics; it selects one declared // snapshot and lets the shared Rust source contract validate and normalize it. -const EDGES_EV = [0, 1, 3, 10]; -const VOLUMES_CM3 = [1, 1]; +const EDGES_EV = [0, 1e5, 5e5, 2e6, 1e7]; +const GROUP_LABELS = ["0–0.1 MeV", "0.1–0.5 MeV", "0.5–2 MeV", "2–10 MeV"]; +const VOLUMES_CM3 = [1, 1, 1, 1]; const TIMES = [ { coolingS: 0, strengths: [ - [100, 0, 20], - [0, 300, 0], + [420, 180, 40, 4], + [160, 360, 90, 8], + [80, 140, 380, 50], + [20, 60, 220, 300], ], }, { coolingS: 3600, strengths: [ - [71, 0, 14], - [0, 212, 0], + [300, 150, 35, 3.5], + [120, 270, 80, 7], + [60, 110, 300, 45], + [15, 45, 180, 270], ], }, { coolingS: 7200, strengths: [ - [50, 0, 10], - [0, 150, 0], + [210, 110, 28, 3], + [90, 200, 65, 6], + [45, 85, 230, 38], + [12, 35, 140, 220], ], }, ]; @@ -65,9 +72,9 @@ export function PhotonSourceDemo() { }), ); return { - meshShape: [2, 1, 1], + meshShape: [2, 2, 1], lowerLeftCm: [0, 0, 0], - upperRightCm: [2, 1, 1], + upperRightCm: [2, 2, 1], voxelVolumesCm3: VOLUMES_CM3, edgesEv: EDGES_EV, coolingS: TIMES[timeIndex].coolingS, @@ -129,6 +136,7 @@ export function PhotonSourceDemo() { } const total = result?.total_photons_per_s ?? null; + const peakVoxelTotal = Math.max(0, ...(result?.voxel_totals_photons_per_s ?? []), 1e-30); return (
@@ -149,13 +157,16 @@ export function PhotonSourceDemo() {
-
+

Voxel spectra

- Integrated photons/s. Regular mesh (2, 1, 1); group edges {EDGES_EV.join(", ")} eV; - voxel volumes {VOLUMES_CM3.join(", ")} cm³. + Integrated photons/s. Regular 2×2×1 mesh (four 1 cm³ cells); group edges{" "} + {EDGES_EV.join(", ")} eV.

@@ -163,9 +174,9 @@ export function PhotonSourceDemo() { Voxel - {EDGES_EV.slice(0, -1).map((low, group) => ( - - {low}–{EDGES_EV[group + 1]} eV + {GROUP_LABELS.map((label) => ( + + {label} ))} @@ -173,14 +184,14 @@ export function PhotonSourceDemo() { {strengthsText.map((row, voxel) => ( - - {voxel} · {VOLUMES_CM3[voxel]} cm³ + + V{voxel} · {VOLUMES_CM3[voxel]} cm³ {row.map((cell, group) => ( updateCell(voxel, group, event.target.value)} @@ -246,6 +257,27 @@ export function PhotonSourceDemo() { {result?.sampling_error && (

{result.sampling_error}

)} + {result && result.voxel_totals_photons_per_s.length > 0 && ( +
+

Per-voxel totals

+
+ {result.voxel_totals_photons_per_s.map((total, voxel) => ( +
+ V{voxel} +
+
+
+ {total.toFixed(1)} photons/s +
+ ))} +
+
+ )} {result?.joint_probabilities && (

Joint voxel/group probabilities

@@ -258,9 +290,9 @@ export function PhotonSourceDemo() { Voxel - {EDGES_EV.slice(0, -1).map((low, group) => ( - - group {group} + {GROUP_LABELS.map((label) => ( + + {label} ))} From d804a09d16fc3ba14d70238a09e581b5ef1636a0 Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 17:25:33 +0600 Subject: [PATCH 3/7] Extend real-data probe to photon transport --- CHANGELOG.md | 8 +- .../interactive/transport-source.mdx | 7 +- .../python/activation-to-transport.md | 10 +- validation/AGENTS.md | 14 +- validation/README.md | 20 +- validation/openmc_real_data_probe.py | 271 +++++++++++------- 6 files changed, 203 insertions(+), 127 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61a36f7..3e08943 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,10 +52,10 @@ workspace crates from tags. mapping, differential histogram density, XML roundtrip, seeded joint-source sampling and a vacuum track-length tally at two source strengths that pins the integrated/rate-scaled convention; no interacting transport. An optional - real-data companion (`validation/openmc_real_data_probe.py`) runs a bounded - OpenMC 0.16 transport check with caller-mounted NNDC HDF5 files and verifies - source-strength scaling, per-source vs rate-scaled flux agreement and the - package `normalize_flux` path. + real-data companion (`validation/openmc_real_data_probe.py`) runs bounded + OpenMC 0.16 photon and neutron transport checks with caller-mounted NNDC + HDF5 files and verifies source-strength scaling, per-source vs rate-scaled + flux agreement and the package `normalize_flux` path. ### Fixed diff --git a/docs/tutorials/interactive/transport-source.mdx b/docs/tutorials/interactive/transport-source.mdx index 9820661..9c866fb 100644 --- a/docs/tutorials/interactive/transport-source.mdx +++ b/docs/tutorials/interactive/transport-source.mdx @@ -46,8 +46,9 @@ workflow. The browser snapshots are synthetic because no nuclear data or transport engine is shipped to the page. The shared kernel is checked against real -OpenMC 0.16 transport with a caller-mounted NNDC HDF5 library in -`validation/openmc_real_data_probe.py`; that check covers normalization, -source-strength scaling and data loading, not dose or transport accuracy. +OpenMC 0.16 photon and neutron transport with a caller-mounted NNDC HDF5 +library in `validation/openmc_real_data_probe.py`; that check covers +normalization, source-strength scaling and data loading, not dose or +transport accuracy. diff --git a/docs/tutorials/python/activation-to-transport.md b/docs/tutorials/python/activation-to-transport.md index 489c27b..272a345 100644 --- a/docs/tutorials/python/activation-to-transport.md +++ b/docs/tutorials/python/activation-to-transport.md @@ -270,8 +270,8 @@ a dose response and an independent reference. The validation harness carries the external checks separately: `validation/openmc_handoff_probe.py` pins the OpenMC 0.16 source/tally/XML -semantics, and `validation/openmc_real_data_probe.py` runs a bounded -fixed-source water/iron sphere with a caller-mounted NNDC HDF5 library and -checks the same per-source and rate-scaled conversions through -`normalize_flux`. The latter is a normalization and data-loading check, not a -dose or transport benchmark. +semantics, and `validation/openmc_real_data_probe.py` runs bounded +fixed-source photon and neutron water/iron spheres with a caller-mounted NNDC +HDF5 library and checks the same per-source and rate-scaled conversions +through `normalize_flux`. The latter is a normalization and data-loading +check, not a dose or transport benchmark. diff --git a/validation/AGENTS.md b/validation/AGENTS.md index 16bea29..f989ccf 100644 --- a/validation/AGENTS.md +++ b/validation/AGENTS.md @@ -92,12 +92,14 @@ reference tally (`magic_tally.txt`), and the committed results document. transport. Record the probe's JSON output and never turn source sampling or the void tally into a physics, transport or dose claim. - `openmc_real_data_probe.py` is the optional real-data companion: it requires - caller-mounted `H1.h5`, `O16.h5` and `Fe56.h5`, writes only a temporary - `cross_sections.xml`, and runs a bounded fixed-source water/iron sphere. Its - claims are limited to source-strength scaling, the per-source vs rate-scaled - flux conversion, data loading and the package `normalize_flux` path. Never - describe it as a transport benchmark, shutdown-dose validation or - independent physics oracle; never vendor or download the caller's data. + caller-mounted neutron (`H1.h5`, `O16.h5`, `Fe56.h5`) and photon + (`photon/H.h5`, `photon/O.h5`, `photon/Fe.h5`) files, writes only a temporary + `cross_sections.xml`, and runs bounded fixed-source photon and neutron + water/iron spheres. Its claims are limited to source-strength scaling, the + per-source vs rate-scaled flux conversion, data loading and the package + `normalize_flux` path. Never describe it as a transport benchmark, + shutdown-dose validation or independent physics oracle; never vendor or + download the caller's data. - Fresh ACTINV activation comparisons execute the source-pinned external example separately from the synthetic probe. Retain original/compatible script hashes and diff, verified data hashes, compiled-extension identity, diff --git a/validation/README.md b/validation/README.md index 32e7067..b87e360 100644 --- a/validation/README.md +++ b/validation/README.md @@ -203,16 +203,18 @@ It emits one JSON document and exits nonzero if any check fails. ## OpenMC real-data normalization probe `openmc_real_data_probe.py` uses an actual NNDC/OpenMC HDF5 cross-section -library to run a small fixed-source transport calculation and check the -handoff against it. It requires `H1.h5`, `O16.h5` and `Fe56.h5` in the supplied +library to run small fixed-source photon and neutron transport calculations +and check the handoff against them. It requires `H1.h5`, `O16.h5` and +`Fe56.h5` plus `photon/H.h5`, `photon/O.h5` and `photon/Fe.h5` in the supplied directory; the files are mounted read-only and never copied, vendored or -downloaded. A centered 14 MeV point source in a 10 cm water sphere is run at -source strengths 1 and 10 with the same seed and 20 000 particles × 5 batches. -The probe checks that the tally scales by the strength, that -`raw × rate / volume` (per-source input) equals `raw / volume` (rate-scaled -input), and that the iron sphere produces a different flux, proving the real -cross sections were loaded. When the rebuilt Nucleide package is installed, it -also checks the same conversion through `nucleide.openmc.normalize_flux`. +downloaded. Centered photon (2 MeV) and neutron (14 MeV) point sources in a +10 cm water sphere are run at source strengths 1 and 10 with the same seed and +20 000 particles × 5 batches. The probe checks that each tally scales by the +strength, that `raw × rate / volume` (per-source input) equals +`raw / volume` (rate-scaled input), and that the iron sphere produces a +different flux, proving the real cross sections were loaded. When the rebuilt +Nucleide package is installed, it also checks the same conversion through +`nucleide.openmc.normalize_flux`. ```bash docker run --rm --cpus=2 --memory=6g --memory-swap=6g \ diff --git a/validation/openmc_real_data_probe.py b/validation/openmc_real_data_probe.py index cee808f..f22b17e 100644 --- a/validation/openmc_real_data_probe.py +++ b/validation/openmc_real_data_probe.py @@ -1,30 +1,31 @@ #!/usr/bin/env python3 -"""OpenMC 0.16 real-data normalization probe (no dose or transport claim). +"""OpenMC 0.16 real-data normalization probe (no dose claim). -Runs a small fixed-source neutron problem with an actual NNDC/OpenMC HDF5 -cross-section library and checks the activation-to-transport normalization -contract against the transport result: +Runs small fixed-source neutron and photon problems with an actual +NNDC/OpenMC HDF5 library and checks the activation-to-transport +normalization contract against transport: -- A centered 14 MeV point source in a 10 cm radius water sphere. +- Water and iron spheres (10 cm radius) with a centered point source. - Two runs with the same seed and particle count, source strengths 1 and 10. -- The fixed-source tally must scale exactly by the source strength, so the - per-source conversion ``raw * rate / volume`` for the unit-strength run - must agree with the rate-scaled conversion ``raw / volume`` for the - strength-10 run. -- A second material (iron) must produce a different tally, confirming that - the HDF5 cross sections were actually loaded and used. +- The fixed-source tally must scale by source strength, so the per-source + conversion ``raw * rate / volume`` for the unit-strength run must agree with + the rate-scaled conversion ``raw / volume`` for the strength-10 run. +- The iron sphere must produce a different flux than water, confirming that + the real cross sections were loaded and used. - When ``nucleide.openmc.normalize_flux`` is importable, the same conversion is checked through the package API. -This is a normalization/units and data-loading check. It is not a transport -benchmark, a shutdown-dose calculation, or an independent physics oracle. -The real nuclear data are supplied by the caller and never vendored or -downloaded by this script. +Both particle types are exercised because the handoff source is photons and +the normalization convention is shared. This is a normalization/units and +data-loading check. It is not a transport benchmark, a shutdown-dose +calculation, or an independent physics oracle. The real nuclear data are +supplied by the caller and never vendored or downloaded. + +The data directory must contain ``H1.h5``, ``O16.h5`` and ``Fe56.h5`` plus +``photon/H.h5``, ``photon/O.h5`` and ``photon/Fe.h5``. Usage: python validation/openmc_real_data_probe.py --data-dir /path/to/hdf5 - -The data directory must contain ``H1.h5``, ``O16.h5`` and ``Fe56.h5``. """ from __future__ import annotations @@ -42,12 +43,15 @@ EXPECTED_OPENMC = "0.16.0" RADIUS_CM = 10.0 -SOURCE_ENERGY_EV = 14.0e6 PARTICLES = 20_000 BATCHES = 5 SEED = 20261116 STRENGTHS = (1.0, 10.0) -REQUIRED_DATA = ("H1", "O16", "Fe56") +NEUTRON_DATA = ("H1", "O16", "Fe56") +PHOTON_DATA = ("H", "O", "Fe") +NEUTRON_ENERGY_EV = 14.0e6 +PHOTON_ENERGY_EV = 2.0e6 +PARTICLES_TO_RUN = ("photon", "neutron") def sha256_file(path: Path) -> str: @@ -58,25 +62,37 @@ def sha256_file(path: Path) -> str: return digest.hexdigest() -def write_library(openmc: Any, data_dir: Path, work: Path) -> Path: - """Register the required HDF5 files and write a temporary cross_sections.xml.""" - missing = [name for name in REQUIRED_DATA if not (data_dir / f"{name}.h5").is_file()] - if missing: - raise FileNotFoundError( - f"data directory {data_dir} is missing required files: " - + ", ".join(f"{name}.h5" for name in missing) - ) - library = openmc.data.DataLibrary() - for name in REQUIRED_DATA: - library.register_file(str(data_dir / f"{name}.h5")) - path = work / "cross_sections.xml" - library.export_to_xml(str(path)) - return path +def write_library(data_dir: Path, work: Path) -> Path: + """Write a temporary cross_sections.xml with neutron and photon libraries.""" + entries: list[str] = [] + for name in NEUTRON_DATA: + path = data_dir / f"{name}.h5" + if not path.is_file(): + raise FileNotFoundError(f"missing neutron data file: {path}") + entries.append(f' ') + for name in PHOTON_DATA: + path = data_dir / "photon" / f"{name}.h5" + if not path.is_file(): + raise FileNotFoundError(f"missing photon data file: {path}") + entries.append(f' ') + xml = '\n\n' + "\n".join(entries) + "\n\n" + cross_sections = work / "cross_sections.xml" + cross_sections.write_text(xml, encoding="utf-8") + return cross_sections -def run_case(openmc: Any, work: Path, material_name: str, strength: float) -> dict[str, Any]: +def run_case( + openmc: Any, + work: Path, + material_name: str, + particle: str, + strength: float, +) -> dict[str, Any]: """Run one fixed-source sphere case and return the cell flux tally.""" - case_dir = work / f"{material_name}-s{strength:g}" + if particle not in PARTICLES_TO_RUN: + raise ValueError(f"unknown particle {particle}") + energy = PHOTON_ENERGY_EV if particle == "photon" else NEUTRON_ENERGY_EV + case_dir = work / f"{particle}-{material_name}-s{strength:g}" case_dir.mkdir() sphere = openmc.Sphere(r=RADIUS_CM, boundary_type="vacuum") cell = openmc.Cell(region=-sphere) @@ -96,9 +112,9 @@ def run_case(openmc: Any, work: Path, material_name: str, strength: float) -> di materials = openmc.Materials([material]) source = openmc.IndependentSource( space=openmc.stats.Point((0.0, 0.0, 0.0)), - energy=openmc.stats.Discrete([SOURCE_ENERGY_EV], [1.0]), + energy=openmc.stats.Discrete([energy], [1.0]), strength=strength, - particle="neutron", + particle=particle, ) settings = openmc.Settings( particles=PARTICLES, @@ -108,7 +124,9 @@ def run_case(openmc: Any, work: Path, material_name: str, strength: float) -> di output={"summary": False, "tallies": False}, ) settings.source = [source] - tally = openmc.Tally(name=f"{material_name} flux") + if particle == "photon": + settings.photon_transport = True + tally = openmc.Tally(name=f"{particle}-{material_name} flux") tally.filters = [openmc.CellFilter(cell)] tally.scores = ["flux"] model = openmc.Model( @@ -130,22 +148,22 @@ def run_case(openmc: Any, work: Path, material_name: str, strength: float) -> di close() if not math.isfinite(mean) or mean <= 0.0: raise RuntimeError( - f"{material_name} strength {strength}: nonpositive/nonfinite tally {mean}" + f"{particle} {material_name} strength {strength}: nonpositive/nonfinite tally {mean}" ) if not math.isfinite(std_dev): std_dev = None return { + "particle": particle, "material": material_name, "source_strength": strength, + "source_energy_ev": energy, "mean_volume_integrated_track_length": mean, "std_dev": std_dev, "relative_error": (std_dev / mean if std_dev is not None else None), } -def package_check( - water_unit: dict[str, Any], water_ten: dict[str, Any], volume: float -) -> dict[str, Any]: +def package_check(unit: dict[str, Any], ten: dict[str, Any], volume: float) -> dict[str, Any]: """Check the same conversion through the optional Nucleide package.""" try: from nucleide import openmc as omc @@ -154,31 +172,31 @@ def package_check( if not hasattr(omc, "normalize_flux"): return {"status": "SKIP", "reason": "nucleide.openmc.normalize_flux is absent"} arrays_unit = { - "flux": [[water_unit["mean_volume_integrated_track_length"]]], + "flux": [[unit["mean_volume_integrated_track_length"]]], "rel_err": [[0.0]], "normalization": "unknown", "units": "unknown", } arrays_ten = { - "flux": [[water_ten["mean_volume_integrated_track_length"]]], + "flux": [[ten["mean_volume_integrated_track_length"]]], "rel_err": [[0.0]], "normalization": "unknown", "units": "unknown", } - unit = omc.normalize_flux( + per_source = omc.normalize_flux( arrays_unit, 10.0, [volume], input_normalization="per-source-volume-integrated", ) - ten = omc.normalize_flux( + rate_scaled = omc.normalize_flux( arrays_ten, 10.0, [volume], input_normalization="rate-scaled-volume-integrated", ) - unit_flux = float(unit["flux"][0][0]) - ten_flux = float(ten["flux"][0][0]) + unit_flux = float(per_source["flux"][0][0]) + ten_flux = float(rate_scaled["flux"][0][0]) return { "status": "PASS" if math.isclose(unit_flux, ten_flux, rel_tol=1e-12, abs_tol=0.0) @@ -186,7 +204,50 @@ def package_check( "per_source_flux": unit_flux, "rate_scaled_flux": ten_flux, "relative_difference": abs(unit_flux - ten_flux) / ten_flux, - "units": unit["units"], + "units": per_source["units"], + } + + +def conversion_checks( + particle: str, + unit: dict[str, Any], + ten: dict[str, Any], + iron: dict[str, Any], + volume: float, +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """Build the scaling, conversion and data-loading checks for one particle.""" + raw_unit = unit["mean_volume_integrated_track_length"] + raw_ten = ten["mean_volume_integrated_track_length"] + ratio = raw_ten / raw_unit + per_source_flux = raw_unit * 10.0 / volume + rate_scaled_flux = raw_ten / volume + iron_flux = iron["mean_volume_integrated_track_length"] / volume + checks = [ + { + "name": f"{particle}_source_strength_scales_tally", + "pass": math.isclose(ratio, 10.0, rel_tol=1e-12, abs_tol=0.0), + "ratio": ratio, + }, + { + "name": f"{particle}_per_source_and_rate_scaled_flux_agree", + "pass": math.isclose(per_source_flux, rate_scaled_flux, rel_tol=1e-12, abs_tol=0.0), + "per_source_flux": per_source_flux, + "rate_scaled_flux": rate_scaled_flux, + "relative_difference": abs(per_source_flux - rate_scaled_flux) / rate_scaled_flux, + }, + { + "name": f"{particle}_real_cross_sections_change_transport", + "pass": not math.isclose(rate_scaled_flux, iron_flux, rel_tol=1e-3, abs_tol=0.0), + "water_flux": rate_scaled_flux, + "iron_flux": iron_flux, + }, + ] + return checks, { + "water_unit": unit, + "water_ten": ten, + "iron_ten": iron, + "per_source_flux": per_source_flux, + "rate_scaled_flux": rate_scaled_flux, } @@ -196,7 +257,7 @@ def main() -> int: "--data-dir", type=Path, required=True, - help="directory containing H1.h5, O16.h5 and Fe56.h5", + help="directory containing H1.h5, O16.h5, Fe56.h5 and photon/{H,O,Fe}.h5", ) args = parser.parse_args() @@ -223,13 +284,27 @@ def main() -> int: volume = 4.0 / 3.0 * math.pi * RADIUS_CM**3 with tempfile.TemporaryDirectory(prefix="openmc-real-data-") as tmp: work = Path(tmp) - cross_sections = write_library(openmc, data_dir, work) + try: + cross_sections = write_library(data_dir, work) + except Exception as error: + print( + json.dumps( + { + "status": "SKIP", + "reason": f"{type(error).__name__}: {error}", + } + ) + ) + return 2 previous = os.environ.get("OPENMC_CROSS_SECTIONS") os.environ["OPENMC_CROSS_SECTIONS"] = str(cross_sections) try: - water_unit = run_case(openmc, work, "water", STRENGTHS[0]) - water_ten = run_case(openmc, work, "water", STRENGTHS[1]) - iron_ten = run_case(openmc, work, "iron", STRENGTHS[1]) + results: dict[str, dict[str, Any]] = {} + for particle in PARTICLES_TO_RUN: + unit = run_case(openmc, work, "water", particle, STRENGTHS[0]) + ten = run_case(openmc, work, "water", particle, STRENGTHS[1]) + iron = run_case(openmc, work, "iron", particle, STRENGTHS[1]) + results[particle] = {"unit": unit, "ten": ten, "iron": iron} except Exception as error: print( json.dumps( @@ -248,40 +323,25 @@ def main() -> int: else: os.environ["OPENMC_CROSS_SECTIONS"] = previous - raw_unit = water_unit["mean_volume_integrated_track_length"] - raw_ten = water_ten["mean_volume_integrated_track_length"] - ratio = raw_ten / raw_unit - per_source_flux = raw_unit * 10.0 / volume - rate_scaled_flux = raw_ten / volume - iron_flux = iron_ten["mean_volume_integrated_track_length"] / volume - water_flux = rate_scaled_flux - ratio_ok = math.isclose(ratio, 10.0, rel_tol=1e-12, abs_tol=0.0) - conversion_ok = math.isclose(per_source_flux, rate_scaled_flux, rel_tol=1e-12, abs_tol=0.0) - data_applied = not math.isclose(water_flux, iron_flux, rel_tol=1e-3, abs_tol=0.0) - api = package_check(water_unit, water_ten, volume) + checks: list[dict[str, Any]] = [] + particle_blocks: dict[str, Any] = {} + for particle in PARTICLES_TO_RUN: + block = results[particle] + particle_checks, summary = conversion_checks( + particle, block["unit"], block["ten"], block["iron"], volume + ) + checks.extend(particle_checks) + particle_blocks[particle] = summary + api = package_check(results["photon"]["unit"], results["photon"]["ten"], volume) api_ok = api.get("status") in ("PASS", "SKIP") - checks = [ - {"name": "source_strength_scales_tally", "pass": ratio_ok, "ratio": ratio}, - { - "name": "per_source_and_rate_scaled_flux_agree", - "pass": conversion_ok, - "per_source_flux": per_source_flux, - "rate_scaled_flux": rate_scaled_flux, - "relative_difference": abs(per_source_flux - rate_scaled_flux) / rate_scaled_flux, - }, - { - "name": "real_cross_sections_change_transport", - "pass": data_applied, - "water_flux": water_flux, - "iron_flux": iron_flux, - }, + checks.append( { "name": "nucleide_package_normalize_flux", "pass": api_ok, "status": api.get("status"), "detail": api, - }, - ] + } + ) passed = all(check["pass"] for check in checks) summary = { "probe": "openmc_real_data_probe", @@ -289,31 +349,42 @@ def main() -> int: "openmc_version": openmc.__version__, "data_dir": str(data_dir), "required_data": { - name: { - "path": str(data_dir / f"{name}.h5"), - "sha256": sha256_file(data_dir / f"{name}.h5"), - "size_bytes": (data_dir / f"{name}.h5").stat().st_size, - } - for name in REQUIRED_DATA + "neutron": { + name: { + "path": str(data_dir / f"{name}.h5"), + "sha256": sha256_file(data_dir / f"{name}.h5"), + "size_bytes": (data_dir / f"{name}.h5").stat().st_size, + } + for name in NEUTRON_DATA + }, + "photon": { + name: { + "path": str(data_dir / "photon" / f"{name}.h5"), + "sha256": sha256_file(data_dir / "photon" / f"{name}.h5"), + "size_bytes": (data_dir / "photon" / f"{name}.h5").stat().st_size, + } + for name in PHOTON_DATA + }, }, "case": { "geometry": f"vacuum sphere r={RADIUS_CM} cm", - "materials": ["water (H1/O16, 1.0 g/cm3)", "iron (Fe56, 7.874 g/cm3)"], - "source": ( - f"centered 14 MeV point source, {PARTICLES} particles x " - f"{BATCHES} batches, seed {SEED}" - ), + "materials": [ + "water (H1/O16, 1.0 g/cm3)", + "iron (Fe56, 7.874 g/cm3)", + ], + "sources": [ + f"photon {PHOTON_ENERGY_EV / 1e6:g} MeV point, centered", + f"neutron {NEUTRON_ENERGY_EV / 1e6:g} MeV point, centered", + ], + "histories": f"{PARTICLES} particles x {BATCHES} batches, seed {SEED}", "volume_cm3": volume, }, - "water_unit": water_unit, - "water_ten": water_ten, - "iron_ten": iron_ten, + "particles": particle_blocks, "checks": checks, "limitations": [ - "This is a normalization/units and data-loading check, not an independent " - "transport or shutdown-dose validation.", - "The sphere and source are synthetic; no evaluated activation or photon " - "source data are used.", + "This is a normalization/units and data-loading check, not an " + "independent transport or shutdown-dose validation.", + "The sphere and source are synthetic; no evaluated activation data are used.", "The real HDF5 files are caller-supplied and never vendored or downloaded.", ], } From f3da8126849843b5752a4668b5138f747a9b6528 Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 17:26:16 +0600 Subject: [PATCH 4/7] Show external OpenMC validation summary in the demo page --- docs/tutorials/interactive/transport-source.mdx | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/tutorials/interactive/transport-source.mdx b/docs/tutorials/interactive/transport-source.mdx index 9c866fb..cdd6cb5 100644 --- a/docs/tutorials/interactive/transport-source.mdx +++ b/docs/tutorials/interactive/transport-source.mdx @@ -51,4 +51,16 @@ library in `validation/openmc_real_data_probe.py`; that check covers normalization, source-strength scaling and data loading, not dose or transport accuracy. +| External check (OpenMC 0.16 + NNDC HDF5) | Photon | Neutron | +| --- | --- | --- | +| strength-10 / strength-1 tally ratio | 9.999999999999988 | 10.000000000000014 | +| per-source vs rate-scaled flux difference | 1.26e-15 | 1.33e-15 | +| water flux, 1/(cm²·s) | 0.027611 | 0.031235 | +| iron flux, 1/(cm²·s) | 0.019920 | 0.041691 | + +The runs use 10 cm water/iron spheres, a centered 2 MeV photon or 14 MeV +neutron point source, and 20 000 particles × 5 batches with a fixed seed. The +water and iron fluxes differ because the real cross sections are loaded; the +checks do not establish a dose or transport-accuracy claim. + From fd378835b4bb1681f38777f11ec2547460ea7a4f Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 20:34:28 +0600 Subject: [PATCH 5/7] Rename transport probe and remove user-specific validation paths --- CHANGELOG.md | 2 +- docs/tutorials/interactive/transport-source.mdx | 2 +- docs/tutorials/python/activation-to-transport.md | 2 +- validation/AGENTS.md | 2 +- validation/README.md | 8 ++++---- ...real_data_probe.py => openmc_transport_probe.py} | 13 +++++++------ validation/run_all.sh | 13 +++++++------ 7 files changed, 22 insertions(+), 20 deletions(-) rename validation/{openmc_real_data_probe.py => openmc_transport_probe.py} (97%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e08943..3eed767 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,7 +52,7 @@ workspace crates from tags. mapping, differential histogram density, XML roundtrip, seeded joint-source sampling and a vacuum track-length tally at two source strengths that pins the integrated/rate-scaled convention; no interacting transport. An optional - real-data companion (`validation/openmc_real_data_probe.py`) runs bounded + caller-data companion (`validation/openmc_transport_probe.py`) runs bounded OpenMC 0.16 photon and neutron transport checks with caller-mounted NNDC HDF5 files and verifies source-strength scaling, per-source vs rate-scaled flux agreement and the package `normalize_flux` path. diff --git a/docs/tutorials/interactive/transport-source.mdx b/docs/tutorials/interactive/transport-source.mdx index cdd6cb5..1faa6c5 100644 --- a/docs/tutorials/interactive/transport-source.mdx +++ b/docs/tutorials/interactive/transport-source.mdx @@ -47,7 +47,7 @@ workflow. The browser snapshots are synthetic because no nuclear data or transport engine is shipped to the page. The shared kernel is checked against real OpenMC 0.16 photon and neutron transport with a caller-mounted NNDC HDF5 -library in `validation/openmc_real_data_probe.py`; that check covers +library in `validation/openmc_transport_probe.py`; that check covers normalization, source-strength scaling and data loading, not dose or transport accuracy. diff --git a/docs/tutorials/python/activation-to-transport.md b/docs/tutorials/python/activation-to-transport.md index 272a345..f04f4a1 100644 --- a/docs/tutorials/python/activation-to-transport.md +++ b/docs/tutorials/python/activation-to-transport.md @@ -270,7 +270,7 @@ a dose response and an independent reference. The validation harness carries the external checks separately: `validation/openmc_handoff_probe.py` pins the OpenMC 0.16 source/tally/XML -semantics, and `validation/openmc_real_data_probe.py` runs bounded +semantics, and `validation/openmc_transport_probe.py` runs bounded fixed-source photon and neutron water/iron spheres with a caller-mounted NNDC HDF5 library and checks the same per-source and rate-scaled conversions through `normalize_flux`. The latter is a normalization and data-loading diff --git a/validation/AGENTS.md b/validation/AGENTS.md index f989ccf..182710a 100644 --- a/validation/AGENTS.md +++ b/validation/AGENTS.md @@ -91,7 +91,7 @@ reference tally (`magic_tally.txt`), and the committed results document. initialize OpenMC; it must not read evaluated data or run interacting transport. Record the probe's JSON output and never turn source sampling or the void tally into a physics, transport or dose claim. -- `openmc_real_data_probe.py` is the optional real-data companion: it requires +- `openmc_transport_probe.py` is the optional caller-data companion: it requires caller-mounted neutron (`H1.h5`, `O16.h5`, `Fe56.h5`) and photon (`photon/H.h5`, `photon/O.h5`, `photon/Fe.h5`) files, writes only a temporary `cross_sections.xml`, and runs bounded fixed-source photon and neutron diff --git a/validation/README.md b/validation/README.md index b87e360..0ec98bf 100644 --- a/validation/README.md +++ b/validation/README.md @@ -22,7 +22,7 @@ committed `results.md` holds the measured numbers that the paper quotes. | `equilib_vs_desc.py` | Equilibrium data readers: synthetic classic-`wout` magic/format/Jacobian gates + `&INDATA` grammar gates (always run) with DESC/simsopt container probes (loud SKIP outside) | | `actinv_handoff_probe.py` | Optional pinned ACTINV CLI synthetic export/readback, with binary/source hashes and conservation receipts; no activation solve | | `openmc_handoff_probe.py` | Pinned OpenMC 0.16.0 source/tally normalization, C-to-F mesh ordering, histogram-density, XML roundtrip and seeded joint-source sampling probe; no interacting transport | -| `openmc_real_data_probe.py` | Optional real NNDC/OpenMC HDF5 transport check: source-strength scaling, per-source vs rate-scaled flux agreement, data loading, and package `normalize_flux` | +| `openmc_transport_probe.py` | Optional caller-data NNDC/OpenMC HDF5 transport check: source-strength scaling, per-source vs rate-scaled flux agreement, data loading, and package `normalize_flux` | | `tritium_vs_festim.py` | 1D tritium kernel parity probe vs FESTIM 2.1 (black-box; probe-only image; see probe section below) | | `timings.py` | Coarse wall-time comparisons (Python overhead included) | | `make_figures.py` | Generates the paper figures in `figures/` from the JSON reports | @@ -200,9 +200,9 @@ docker run --rm --cpus=2 --memory=6g --memory-swap=6g \ It emits one JSON document and exits nonzero if any check fails. -## OpenMC real-data normalization probe +## OpenMC transport normalization probe -`openmc_real_data_probe.py` uses an actual NNDC/OpenMC HDF5 cross-section +`openmc_transport_probe.py` uses an actual NNDC/OpenMC HDF5 cross-section library to run small fixed-source photon and neutron transport calculations and check the handoff against them. It requires `H1.h5`, `O16.h5` and `Fe56.h5` plus `photon/H.h5`, `photon/O.h5` and `photon/Fe.h5` in the supplied @@ -221,7 +221,7 @@ docker run --rm --cpus=2 --memory=6g --memory-swap=6g \ -v /path/to/nndc_hdf5:/data:ro \ -v "$PWD/validation:/work:ro" -w /work \ localhost/nucleide-validation:latest \ - python openmc_real_data_probe.py --data-dir /data + python openmc_transport_probe.py --data-dir /data ``` This is a normalization/units and data-loading check, not a transport diff --git a/validation/openmc_real_data_probe.py b/validation/openmc_transport_probe.py similarity index 97% rename from validation/openmc_real_data_probe.py rename to validation/openmc_transport_probe.py index f22b17e..61a32a0 100644 --- a/validation/openmc_real_data_probe.py +++ b/validation/openmc_transport_probe.py @@ -68,12 +68,12 @@ def write_library(data_dir: Path, work: Path) -> Path: for name in NEUTRON_DATA: path = data_dir / f"{name}.h5" if not path.is_file(): - raise FileNotFoundError(f"missing neutron data file: {path}") + raise FileNotFoundError(f"missing neutron data file: {name}.h5") entries.append(f' ') for name in PHOTON_DATA: path = data_dir / "photon" / f"{name}.h5" if not path.is_file(): - raise FileNotFoundError(f"missing photon data file: {path}") + raise FileNotFoundError(f"missing photon data file: photon/{name}.h5") entries.append(f' ') xml = '\n\n' + "\n".join(entries) + "\n\n" cross_sections = work / "cross_sections.xml" @@ -278,7 +278,8 @@ def main() -> int: return 2 data_dir = args.data_dir.expanduser().resolve() if not data_dir.is_dir(): - print(json.dumps({"status": "SKIP", "reason": f"data directory not found: {data_dir}"})) + print(f"data directory not found: {data_dir}", file=sys.stderr) + print(json.dumps({"status": "SKIP", "reason": "data directory not found"})) return 2 volume = 4.0 / 3.0 * math.pi * RADIUS_CM**3 @@ -347,11 +348,11 @@ def main() -> int: "probe": "openmc_real_data_probe", "status": "PASS" if passed else "FAIL", "openmc_version": openmc.__version__, - "data_dir": str(data_dir), + "data_dir": "", "required_data": { "neutron": { name: { - "path": str(data_dir / f"{name}.h5"), + "relative_path": f"{name}.h5", "sha256": sha256_file(data_dir / f"{name}.h5"), "size_bytes": (data_dir / f"{name}.h5").stat().st_size, } @@ -359,7 +360,7 @@ def main() -> int: }, "photon": { name: { - "path": str(data_dir / "photon" / f"{name}.h5"), + "relative_path": f"photon/{name}.h5", "sha256": sha256_file(data_dir / "photon" / f"{name}.h5"), "size_bytes": (data_dir / "photon" / f"{name}.h5").stat().st_size, } diff --git a/validation/run_all.sh b/validation/run_all.sh index 0d563e3..8900d57 100755 --- a/validation/run_all.sh +++ b/validation/run_all.sh @@ -4,15 +4,16 @@ # Usage: # ./validation/run_all.sh [PYTHON] # -# The optional PYTHON argument defaults to the conda env used for JOSS -# validation. Every validation/*_vs_*.py comparison script is auto-discovered -# and run in sorted order, followed by timings.py, render_results.py, and -# make_figures.py. All scripts are run with -e so the first failure stops the -# suite. +# The optional PYTHON argument defaults to the PYTHON environment variable, +# then to `python3` on PATH. Pass a prepared validation environment explicitly +# when the default interpreter does not carry the oracle dependencies. Every +# validation/*_vs_*.py comparison script is auto-discovered and run in sorted +# order, followed by timings.py, render_results.py, and make_figures.py. All +# scripts are run with -e so the first failure stops the suite. set -euo pipefail -PYTHON="${1:-/home/tahmid/.conda/envs/nuke-validation/bin/python}" +PYTHON="${1:-${PYTHON:-python3}}" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" echo "Using Python: $PYTHON" From de89f4902e51f7215a7f82a1e021231282547ae3 Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 20:40:13 +0600 Subject: [PATCH 6/7] Fit photon source demo without horizontal scrolling --- validation/AGENTS.md | 6 ++-- validation/openmc_transport_probe.py | 16 +++++----- .../interactive/PhotonSourceDemo.tsx | 29 ++++++++++--------- 3 files changed, 28 insertions(+), 23 deletions(-) diff --git a/validation/AGENTS.md b/validation/AGENTS.md index 182710a..c18ee59 100644 --- a/validation/AGENTS.md +++ b/validation/AGENTS.md @@ -99,7 +99,9 @@ reference tally (`magic_tally.txt`), and the committed results document. per-source vs rate-scaled flux conversion, data loading and the package `normalize_flux` path. Never describe it as a transport benchmark, shutdown-dose validation or independent physics oracle; never vendor or - download the caller's data. + download the caller's data. Probe JSON records relative data names, sizes + and SHA-256 hashes; never write host absolute paths, user home directories + or usernames into reports or committed docs. - Fresh ACTINV activation comparisons execute the source-pinned external example separately from the synthetic probe. Retain original/compatible script hashes and diff, verified data hashes, compiled-extension identity, @@ -126,7 +128,7 @@ reference tally (`magic_tally.txt`), and the committed results document. and harness. Limit runtime jobs to 6 GiB RAM/no swap, 128 tasks and 2 CPUs; OpenMC and Rust builds use two compilation jobs. Build context is validation/. - A conda env fallback also works: - (`mamba create -p ~/.conda/envs/nuke-validation -c conda-forge pyne openmc`) + (`mamba create -p /path/to/validation-env -c conda-forge pyne openmc`) with the Nucleide release wheel installed into that env (`maturin build --release`, then `pip install --force-reinstall target/wheels/nucleide-*.whl`). - Run: `./validation/run_container.sh`, or `./validation/run_all.sh [python-binary]` diff --git a/validation/openmc_transport_probe.py b/validation/openmc_transport_probe.py index 61a32a0..d943fec 100644 --- a/validation/openmc_transport_probe.py +++ b/validation/openmc_transport_probe.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""OpenMC 0.16 real-data normalization probe (no dose claim). +"""OpenMC 0.16 caller-data transport normalization probe (no dose claim). Runs small fixed-source neutron and photon problems with an actual NNDC/OpenMC HDF5 library and checks the activation-to-transport @@ -11,21 +11,21 @@ conversion ``raw * rate / volume`` for the unit-strength run must agree with the rate-scaled conversion ``raw / volume`` for the strength-10 run. - The iron sphere must produce a different flux than water, confirming that - the real cross sections were loaded and used. + the loaded cross sections affect transport. - When ``nucleide.openmc.normalize_flux`` is importable, the same conversion is checked through the package API. Both particle types are exercised because the handoff source is photons and the normalization convention is shared. This is a normalization/units and data-loading check. It is not a transport benchmark, a shutdown-dose -calculation, or an independent physics oracle. The real nuclear data are +calculation, or an independent physics oracle. The nuclear data are supplied by the caller and never vendored or downloaded. The data directory must contain ``H1.h5``, ``O16.h5`` and ``Fe56.h5`` plus ``photon/H.h5``, ``photon/O.h5`` and ``photon/Fe.h5``. Usage: - python validation/openmc_real_data_probe.py --data-dir /path/to/hdf5 + python validation/openmc_transport_probe.py --data-dir /path/to/hdf5 """ from __future__ import annotations @@ -236,7 +236,7 @@ def conversion_checks( "relative_difference": abs(per_source_flux - rate_scaled_flux) / rate_scaled_flux, }, { - "name": f"{particle}_real_cross_sections_change_transport", + "name": f"{particle}_cross_sections_change_transport", "pass": not math.isclose(rate_scaled_flux, iron_flux, rel_tol=1e-3, abs_tol=0.0), "water_flux": rate_scaled_flux, "iron_flux": iron_flux, @@ -283,7 +283,7 @@ def main() -> int: return 2 volume = 4.0 / 3.0 * math.pi * RADIUS_CM**3 - with tempfile.TemporaryDirectory(prefix="openmc-real-data-") as tmp: + with tempfile.TemporaryDirectory(prefix="openmc-transport-") as tmp: work = Path(tmp) try: cross_sections = write_library(data_dir, work) @@ -345,7 +345,7 @@ def main() -> int: ) passed = all(check["pass"] for check in checks) summary = { - "probe": "openmc_real_data_probe", + "probe": "openmc_transport_probe", "status": "PASS" if passed else "FAIL", "openmc_version": openmc.__version__, "data_dir": "", @@ -386,7 +386,7 @@ def main() -> int: "This is a normalization/units and data-loading check, not an " "independent transport or shutdown-dose validation.", "The sphere and source are synthetic; no evaluated activation data are used.", - "The real HDF5 files are caller-supplied and never vendored or downloaded.", + "The HDF5 files are caller-supplied and never vendored or downloaded.", ], } print(json.dumps(summary, indent=2, sort_keys=True)) diff --git a/website/src/components/interactive/PhotonSourceDemo.tsx b/website/src/components/interactive/PhotonSourceDemo.tsx index 7b82a09..d9ca75c 100644 --- a/website/src/components/interactive/PhotonSourceDemo.tsx +++ b/website/src/components/interactive/PhotonSourceDemo.tsx @@ -13,7 +13,7 @@ import { Label } from "@nukehub/docs-kit/components/ui/Label"; // groups. The browser never computes decay physics; it selects one declared // snapshot and lets the shared Rust source contract validate and normalize it. const EDGES_EV = [0, 1e5, 5e5, 2e6, 1e7]; -const GROUP_LABELS = ["0–0.1 MeV", "0.1–0.5 MeV", "0.5–2 MeV", "2–10 MeV"]; +const GROUP_LABELS = ["0–0.1", "0.1–0.5", "0.5–2", "2–10"]; const VOLUMES_CM3 = [1, 1, 1, 1]; const TIMES = [ { @@ -159,7 +159,7 @@ export function PhotonSourceDemo() {
@@ -175,8 +175,9 @@ export function PhotonSourceDemo() { Voxel {GROUP_LABELS.map((label) => ( - - {label} + + {label} + MeV ))} @@ -184,14 +185,12 @@ export function PhotonSourceDemo() { {strengthsText.map((row, voxel) => ( - - V{voxel} · {VOLUMES_CM3[voxel]} cm³ - + V{voxel} {row.map((cell, group) => ( - + updateCell(voxel, group, event.target.value)} @@ -291,8 +290,12 @@ export function PhotonSourceDemo() { Voxel {GROUP_LABELS.map((label) => ( - - {label} + + {label} + MeV ))} @@ -300,9 +303,9 @@ export function PhotonSourceDemo() { {result.joint_probabilities.map((row, voxel) => ( - {voxel} + {voxel} {row.map((probability, group) => ( - + {(probability * 100).toFixed(2)}% ))} From c9c8a9552e87675b73e62b6f54ee9cd2494b7131 Mon Sep 17 00:00:00 2001 From: Ahnaf Tahmid Chowdhury Date: Mon, 16 Nov 2026 20:47:27 +0600 Subject: [PATCH 7/7] Improve cooling selection feedback and joint probability table --- website/e2e/smoke.spec.ts | 2 +- .../interactive/PhotonSourceDemo.tsx | 154 ++++++++++++------ 2 files changed, 109 insertions(+), 47 deletions(-) diff --git a/website/e2e/smoke.spec.ts b/website/e2e/smoke.spec.ts index e1144e8..cb8cbea 100644 --- a/website/e2e/smoke.spec.ts +++ b/website/e2e/smoke.spec.ts @@ -184,7 +184,7 @@ end`, path: "tutorials/interactive/transport-source", button: "Evaluate source", output: "text=Joint voxel/group probabilities", - extraSteps: [{ button: "Check selection", output: "text=indices: [1]" }], + extraSteps: [{ button: "Check selection", output: "text=Exact match" }], }, { path: "tutorials/interactive/deterministic", diff --git a/website/src/components/interactive/PhotonSourceDemo.tsx b/website/src/components/interactive/PhotonSourceDemo.tsx index d9ca75c..0854214 100644 --- a/website/src/components/interactive/PhotonSourceDemo.tsx +++ b/website/src/components/interactive/PhotonSourceDemo.tsx @@ -8,6 +8,7 @@ import type { import { Button } from "@nukehub/docs-kit/components/ui/Button"; import { Input } from "@nukehub/docs-kit/components/ui/Input"; import { Label } from "@nukehub/docs-kit/components/ui/Label"; +import { DataTable } from "@nukehub/docs-kit/components/mdx/DataTable"; // Synthetic snapshots: three declared cooling times, two voxels, three // groups. The browser never computes decay physics; it selects one declared @@ -49,6 +50,11 @@ function initialText(): string[][] { return TIMES[0].strengths.map((row) => row.map(String)); } +interface CoolingSelection { + requested: number[]; + indices: number[]; +} + export function PhotonSourceDemo() { const { wasm, ready, error } = useWasm(); const [timeIndex, setTimeIndex] = useState(0); @@ -56,7 +62,8 @@ export function PhotonSourceDemo() { const [result, setResult] = useState(null); const [localError, setLocalError] = useState(null); const [requestedText, setRequestedText] = useState("3600"); - const [selection, setSelection] = useState(null); + const [selection, setSelection] = useState(null); + const [selectionError, setSelectionError] = useState(null); function buildInput(text: string[][]): PhotonSourceInputJson { const strengths = text.map((row, voxel) => @@ -104,6 +111,7 @@ export function PhotonSourceDemo() { setTimeIndex(index); setStrengthsText(TIMES[index].strengths.map((row) => row.map(String))); setSelection(null); + setSelectionError(null); } function updateCell(voxel: number, group: number, value: string) { @@ -122,16 +130,21 @@ export function PhotonSourceDemo() { .map((part) => part.trim()) .filter((part) => part.length > 0) .map((part) => Number(part)); - setSelection( - wasm.photonSourceSelectCooling( - TIMES.map((entry) => entry.coolingS), - requested, - ), + if (requested.length === 0) { + throw new Error("enter at least one cooling offset"); + } + if (requested.some((time) => !Number.isFinite(time) || time < 0)) { + throw new Error("cooling offsets must be finite nonnegative seconds"); + } + const indices = wasm.photonSourceSelectCooling( + TIMES.map((entry) => entry.coolingS), + requested, ); - setLocalError(null); + setSelection({ requested, indices }); + setSelectionError(null); } catch (e) { setSelection(null); - setLocalError(e instanceof Error ? e.message : String(e)); + setSelectionError(e instanceof Error ? e.message : String(e)); } } @@ -284,36 +297,31 @@ export function PhotonSourceDemo() { Sampling uses these pairs directly; independent spatial and energy marginals would invent cross-pairs that carry no source.

-
- - - - - {GROUP_LABELS.map((label) => ( - - ))} - - - - {result.joint_probabilities.map((row, voxel) => ( - - - {row.map((probability, group) => ( - - ))} - - ))} - -
Voxel - {label} - MeV -
{voxel} - {(probability * 100).toFixed(2)}% -
-
+ { + const record: Record = { voxel: `V${voxel}` }; + row.forEach((probability, group) => { + record[`g${group}`] = `${(probability * 100).toFixed(2)}%`; + }); + return record; + })} + columns={[ + { key: "voxel", header: "Voxel", align: "left" as const }, + ...GROUP_LABELS.map((label, group) => ({ + key: `g${group}`, + header: ( + + {label} + + MeV + + + ), + align: "right" as const, + })), + ]} + />
)}
@@ -321,29 +329,83 @@ export function PhotonSourceDemo() {

Exact cooling selection

+
+ Available offsets: + {TIMES.map((entry) => ( + + ))} +

- Available offsets: {TIMES.map((entry) => entry.coolingS).join(", ")} s. Requested offsets - must match exactly; duplicates and near matches fail. + Requested offsets must match exactly; duplicates and near matches fail.

-
+
setRequestedText(event.target.value)} + onChange={(event) => { + setRequestedText(event.target.value); + setSelection(null); + setSelectionError(null); + }} />
- {selection && ( - indices: [{selection.join(", ")}] - )}
+ {selectionError && ( +
+

No exact match

+

{selectionError}

+

+ Pick one of the available offsets above; near matches are not substituted. +

+
+ )} + {selection && ( +
+

Exact match

+
    + {selection.requested.map((time, position) => { + const index = selection.indices[position]; + const matchedTime = TIMES[index]?.coolingS; + return ( +
  • + {time} s + → + + snapshot {index} + + ({matchedTime ?? "?"} s) +
  • + ); + })} +
+
+ )}
);