Results and post-processing
Tally results
model.simulate_transport() returns a TransportResults indexed by tally:
results = model.simulate_transport()
result = results[tally]
print(result.mean) # list of mean values
print(result.standard_deviation) # list of standard deviations
print(result.relative_error) # list of relative errors
Statistical reliability
Every TallyResult also carries reliability statistics. They are computed automatically from a small per-history aggregate, so the runtime cost is negligible. Printing a result shows all of them: the mean ± std, the figure of merit, the higher-moment metrics, and a PASS/FAIL verdict:
result = results["flux"]
print(result)
# TallyResult 'flux' shape=[1] particles=1000000 elapsed=1.025 s
# mean . . . . . . . 1.7667e1 +/- 1.21e-2 (0.07% rel err)
# figure of merit .. 2.080e6
# variance of var. . 7.277e-6 skewness 1.875 kurtosis 5.277
# large-score tail slope .. 7.78
# statistical checks: PASSED (11/11)
# mean stable....................... pass
# relative error < 0.10............. pass
# per-bin relative error < 0.10..... pass
# relative error decreasing......... pass
# relative error falls as 1/sqrt(N). pass
# variance of variance < 0.10....... pass
# variance of variance decreasing... pass
# variance of variance falls as 1/N. pass
# figure of merit stable............ pass
# figure of merit has no trend...... pass
# large-score tail slope > 3........ pass
Per-bin array (same shape as mean):
| Attribute | Meaning |
|---|---|
variance |
variance of the mean (standard_deviation ** 2) |
Tally-level reliability scalars, computed from the per-history total score:
| Attribute | Meaning |
|---|---|
aggregate_mean / aggregate_std_dev / aggregate_relative_error |
statistics of the integrated tally total |
aggregate_variance_of_variance |
relative variance of the variance; large values flag an unreliable error estimate (rare large contributions are undersampled) |
aggregate_skewness / aggregate_kurtosis |
shape of the history-score distribution |
aggregate_tail_slope |
slope of the large-score PDF tail; the variance is well-defined only when this exceeds 3 |
The statistical_checks object gives the pass/fail verdict, and convergence_history records the statistics versus number of histories:
checks = result.statistical_checks
checks.passed # bool: overall verdict, False if the tail slope could not be estimated
checks.relative_error_ok # individual checks: True / False / None (not evaluated)
print(checks.summary()) # the pass/fail table and verdict: PASSED, FAILED or INCOMPLETE
for point in result.convergence_history:
print(point.n_histories, point.relative_error, point.figure_of_merit)
The raw empirical history-score PDF is available for inspection or plotting:
pdf = result.score_pdf
pdf.counts # histogram counts per log-spaced magnitude bin
pdf.bin_centers # bin centers (len == counts); bin_edges has one more
pdf.zero # histories whose score was exactly zero
pdf.tail_slope # the fitted large-score tail slope
Stopping on a precision target
A ConvergenceTarget ends a run early once a tally is precise enough. It works on the CPU (under MPI the decision is made on the rank-combined statistics) and on the GPU, where it is decided between kernel launches, so the run overshoots the target by at most one launch chunk:
model.convergence_targets = [yamc.ConvergenceTarget("relative_error", 0.02, tally="flux")]
# the run stops once flux relative error <= 2% (or total_particles / max_runtime is reached)
The metric is one of "relative_error", "std_dev", or "variance_of_variance", all on the tally's total, or "bin_relative_error", the relative error that 95% of the tally's scored bins meet (CPU only). Use "bin_relative_error" for a mesh tally, whose total converges long before its deep voxels do. Omit tally= to require the threshold for every tally.
Nuclear-data uncertainty diagnostics
When transport was requested with data_uncertainty, a tally exposes the
nuclear-data spread separately from ordinary transport statistics. The
attributes below are None on a run without that request:
sigma = result.nuclear_data_standard_deviation
if sigma is not None:
print(sigma, result.nuclear_data_replica_spread, result.nuclear_data_noise)
print(result.nuclear_data_noise_dominated)
print(result.replica_mean, result.replica_standard_error)
print(result.nuclear_data_linear_variance)
print(result.nuclear_data_variance_by_nuclide)
mean remains the nominal calculation; replica_mean is the ensemble mean.
Replica spread includes Monte Carlo noise, so it is not interchangeable with
the noise-corrected nuclear-data sigma. The noise flag identifies bins where
that separation is poorly resolved. Per-nuclide contributions describe the
first-order variance, not every nonlinear contribution to the final spread.
See Nuclear-data uncertainty for the
sampling controls and coverage limitations.
Structured results
Each TallyResult exposes shape and dim_labels for reshaping into numpy arrays.
result = results[tally]
print(result.shape) # e.g. (1, 2, 20, 20, 20)
print(result.dim_labels) # e.g. ('score', 'energy', 'mesh_z', 'mesh_y', 'mesh_x')
import numpy as np
data = np.array(result.mean).reshape(result.shape)
xarray integration
With xarray installed (pip install "yamc[xarray]"), the built-in exporters
retain the tally's dimensions and coordinates:
result = results[tally]
da = result.to_xarray(field="mean")
std_dev = result.to_xarray(field="std_dev")
dataset = result.to_dataset()
# Select a single energy bin
flux_high = da.isel(energy=1)
to_dataset() exports mean, standard deviation and relative error together.
For manual array handling, to_numpy() and the flat arrays remain available.
Plotting mesh tallies
tally.plot() returns an interactive InteractiveTallyPlot that renders inline in Jupyter and saves as a self-contained HTML page with .to_html("file.html"). Without a path to_html() returns the page as bytes.
plot = tally.plot(geometry=geometry, basis="xz")
plot.to_html("flux_map.html")
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
geometry |
Geometry or MeshGeometry | None |
Optional outline overlay |
basis |
str | "xy" |
Initial slice plane: "xy", "xz", or "yz" |
slice_coord |
float | mesh center | Initial slice coordinate (cm) |
slices |
None, list[int], or "all" |
None | Which slices to embed for the in-browser slider. None = just the initial slice; "all" = every bin (larger HTML, full slider) |
score_index |
int | 0 | Which score (when the tally has multiple) |
energy_index |
int or None | None | Energy bin; None sums over energy |
value |
str | "mean" |
"mean", "standard_deviation", or "relative_error" |
colorscale |
str | "Viridis" |
Plotly colorscale name (Viridis, Cividis, Hot, etc.) |
log_scale |
bool | True |
Logarithmic color scale |
outline |
str or None | "material" |
Outline by "material", "cell", or None |
resolution |
int | 400000 | Total pixel budget for geometry-outline sampling |
axis_units |
str | "cm" |
Axis units: "mm", "cm", "m", or "km" |
contour_kwargs |
dict | None | Outline appearance: {"colors": [...], "linewidths": int} |
title |
str or None | None | Plot title (auto-generated if None) |
colorbar_title |
str or None | None | Colorbar label (auto-generated if None) |
scaling_factor |
float | 1.0 | Multiply all tally values by this factor (unit conversion) |
font_size |
int | 18 | Base font size in pixels for labels and ticks |
show_colorbar |
bool | True |
Show the colorbar alongside the plot |
# Per-energy-bin slider over every bin, log scale, source-strength scaled
plot = tally.plot(
geometry=geometry,
basis="xz",
slices="all",
energy_index=0,
value="mean",
colorscale="Cividis",
log_scale=True,
axis_units="m",
scaling_factor=1e14, # multiply by source strength
title="Fast neutron flux",
colorbar_title="Flux [n/cm²/s]",
)
plot.to_html("flux_fast.html")
For manual matplotlib plotting, use extract_mesh_slice() with optional geometry outline overlay.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
# Extract tally slice
mean = tally.extract_mesh_slice(basis="xy", value="mean")
mean_2d = np.array(mean)
# Sample geometry for outline overlay
geom_slice = geometry.sample_slice(basis="xy", resolution=(400, 400))
edge_mask = np.array(geom_slice.edges("material"))
# Plot
fig, ax = plt.subplots()
vmin = mean_2d[mean_2d > 0].min()
im = ax.pcolormesh(mean.h_edges, mean.v_edges, mean_2d,
cmap="viridis", norm=LogNorm(vmin=vmin))
outline_rgba = np.zeros((*edge_mask.shape, 4))
outline_rgba[edge_mask] = [1, 1, 1, 0.8]
ax.imshow(outline_rgba, extent=geom_slice.extent, origin="lower",
aspect="auto", interpolation="nearest", zorder=2)
fig.colorbar(im, ax=ax, label=f"Flux [{mean.h_label}]")
plt.savefig("manual_tally_plot.png")
The flux map below is rendered when these docs are built. The model is a small steel pipe carrying water with a 14.06 MeV point source on the axis, sliced in the xz plane:
VTK-HDF export and interactive 3D view
Mesh tally results export to VTK-HDF with Tally.to_vtkhdf(), called after model.simulate_transport() on a tally that has a mesh set. The file opens in ParaView and, as shown below, can also be viewed in the browser.
tally.to_vtkhdf("flux.vtkhdf")
# With options
tally.to_vtkhdf(
"flux.vtkhdf",
scaling_factor=1.6e-19 * 1e21, # eV to W conversion
volume_normalization=True, # divide by voxel volume (default)
sum_energy=True, # sum over energy bins (default)
sum_nuclides=True, # sum over parent nuclide bins (default)
)
# Per-energy-bin export
tally.to_vtkhdf("flux_per_energy.vtkhdf", sum_energy=False)
The viewer below is rendered live when these docs are built. It is a neutron radiograph: the word YAMC is built from boron-10 blocks (a strong thermal-neutron absorber), a thermal point source (orange marker) sits in front of them, and the letters cast a shadow onto a flux screen behind them. Both the flux tally and the geometry are written to VTK-HDF; the grey YAMC blocks are the geometry (read back from geometry.vtkhdf), and the coloured panel is the flux screen (read back from flux.vtkhdf), where the letters appear as dark shadows. Drag to rotate, scroll to zoom, right-drag to pan. The same files open in ParaView for further analysis.
Performance stats
Timing information is stored on the results returned by simulate_transport:
results = model.simulate_transport()
print(f"Total time: {results.elapsed:.2f} s")
print(f"Particles/sec: {results.particles_per_second}")
print(f"Data load time: {results.data_load_time:.2f} s")
print(f"Transport time: {results.transport_time:.2f} s")