Skip to content

Add staged multi-model D1S irradiation and moving-component photon replay - #144

Open
shimwell wants to merge 7 commits into
developfrom
feature/d1s-multi-model
Open

shimwell wants to merge 7 commits into
developfrom
feature/d1s-multi-model

Conversation

@shimwell

@shimwell shimwell commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a staged D1S capture/replay workflow for multiple neutron irradiation models followed by independently specified decay-photon transport models. The public API is exposed through openmc.deplete.d1s: Configuration, Cells, DAGMCVolumes, Irradiation, Cooling, Simulation, Production, Observation, and Results.

This supports, for example, a high-energy/high-rate irradiation in one geometry, a lower-energy/lower-rate irradiation in a second geometry, then shutdown photon transport in a third geometry with components moved or removed. It is D1S with fixed-composition production kernels, not depletion or inventory transfer.

Workflow diagram

flowchart TB
    subgraph production["Neutron production in static irradiation models"]
        A["Irradiation model A<br/>Geometry A, source spectrum A"] --> KA["Neutron transport<br/>Capture decay-photon births, do not transport them"]
        B["Irradiation model B<br/>Geometry B, source spectrum B"] --> KB["Neutron transport<br/>Capture decay-photon births, do not transport them"]
    end

    KA --> H["Retained production banks<br/>Positions, directions, energies, weights,<br/>parent radionuclides and component identities"]
    KB --> H
    H --> W["At each cooling observation<br/>Normalize per original neutron history<br/>and sum time-weighted contributions<br/>from all completed irradiations"]
    W --> C{"Component present<br/>in observation source map?"}
    C -->|"Explicit None"| R["Suppress this component's emission<br/>Retain its decaying history for reinsertion"]
    C -->|"Present"| X["Transfer each component's source<br/>T_target @ inverse(T_origin)<br/>Move positions, rotate directions, preserve energies"]
    X --> V["Validate destination containment<br/>and selected CSG or DAGMC instances"]
    G["User-supplied shutdown model<br/>Actual moved components and shielding<br/>Transforms do not edit geometry"] --> V
    V --> S["Weighted photon replay<br/>Sample births by physical emission weight<br/>Launch unit-weight photons, source strength 1"]
    S --> P["Photon transport through shutdown geometry<br/>Normal interactions, attenuation and scattering"]
    G --> P
    P --> T["Physical tally results<br/>Scale per-replay-photon results once<br/>by total photon rate Q_gamma"]
Loading

Each observation is a separate static geometry snapshot, not continuous motion during tracking. Cooling changes decay weights, not photon flight time. An omitted historical component key is an error; explicit None is required for removal. A zero total photon rate skips replay and transport and returns zero-valued tallies. Standard deviations describe photon transport uncertainty conditional on the sampled production banks.

How transport works with moving geometry

  1. Calculate neutron production separately for each irradiation configuration. Each distinct neutron model contains its own geometry, materials, source spatial/angular distribution, and energy spectrum. The new capture mode runs neutron transport and records sampled decay-photon births instead of transporting those photons immediately. Their positions, directions, energies, weights, parent radionuclides, and emitting component membership are retained. Neutron shielding and spatially nonuniform activation are therefore represented by that configuration's sampled birth distribution. Photon attenuation in the irradiation geometry is not baked into the bank.
  2. Retain cumulative production history on the schedule timeline. Every completed irradiation contributes to subsequent cooling observations. For an interval of duration Δt, neutron rate R, end time b, parent decay constant λ, and global observation time t, its factor is R * (1 - exp(-λ Δt)) * exp(-λ (t - b)). Contributions from all preceding intervals are added, including repeated irradiation of the same physical component. Cooling adds no production. Reusing the same Configuration object allows one production bank to be reused when only rates and durations change.
  3. Move each component's source phase space into the observation configuration. Stable string component names identify physical objects across otherwise unrelated models. A component's proper rigid 4×4 transform maps reference coordinates into that model's global coordinates. Source transfer uses T_target @ inverse(T_origin) for positions and the corresponding rotation for directions. Sampled energies are unchanged. The original nonuniform spatial, angular, energy, and parent correlations are retained rather than replacing activation with a uniform cell source.
  4. Use the actual destination geometry, not a transformed tally. These transforms move source points and directions; they do not edit CSG surfaces or CAD geometry. The user supplies a photon model that actually contains the component in its destination placement, for example with rebuilt CSG geometry, regenerated CAD, or enclosing-universe placement. Transferred births are checked against their destination component and selected instances. CSG, DAGMC, hybrid models, and CSG↔DAGMC transitions use the same physical component identities. DAGMC selection uses raw H5M volume GLOBAL_ID values scoped to a universe, independently of runtime auto_geom_ids.
  5. Transport photons through the complete shutdown model. Replay samples births in proportion to their physical emission weights and launches unit-weight photons. Photons then undergo the normal OpenMC photon transport through the supplied target materials, surfaces, shielding, and boundary conditions. Added passive shielding changes attenuation and scattering without needing its own production identity. An activated added component needs its own irradiation history. Removing an emitting component from the source map does not remove its attenuation: the destination geometry must also omit it if that is intended.
  6. Normalize the result once. Birth weights are normalized by the global number of original sampled external neutron histories, including zero-weight histories rejected by source constraints, then multiplied by their time factors. Their sum is the physical photon rate Q_gamma in photons/s. Replay uses source strength 1, and returned in-memory tally means and standard deviations are multiplied by Q_gamma once. Raw statepoints retain per-replay-photon normalization. Flux volume normalization and dose conversion remain explicit user operations.

Motion is represented by discrete static geometry snapshots. There are no continuously moving surfaces during particle flight. Each irradiation and each photon observation uses a static model. Cooling time changes decay weights, not photon flight time. If a component moves during a period in which observations are needed, represent the required placements with additional configurations and cooling steps.

Removal, reinsertion, and replacement

  • Once a physical component enters the irradiation history, a later configuration must explicitly account for it. components={'insert': None} suppresses its emission there but retains its decaying history for later reinsertion under the same identity.
  • A replacement physical object needs a new identity. It does not inherit the old object's production history.
  • If a removed component remains nearby and should contribute radiation, model it at that location with a destination selector and transform rather than using None.
  • Passive regions need no source component key. Every sampled emitting region must belong to exactly one component when a component map is supplied. Repeated CSG/DAGMC instances can be selected explicitly.

RegularMesh examples and animations

Three runnable examples, plus a CAD version of the third, cover the requested scenarios. All use the same stationary openmc.RegularMesh for neutron irradiation fields and decay-photon cooling fields. The source position and the activated component position are separate inputs.

Use this branch's compiled OpenMC executable, configure OPENMC_CROSS_SECTIONS and a compatible OPENMC_CHAIN_FILE, and install Matplotlib/Pillow for GIF export. Run from the repository root with new or empty output directories:

python examples/d1s_moving/moving_neutron_source.py --output moving-source-results
python examples/d1s_moving/moving_activated_volume.py --output moving-volume-results
python examples/d1s_moving/moving_then_removed_volume.py --output removed-volume-results
# Needs a DAGMC-enabled build and pip install cad_to_dagmc cad-to-dagmc-mesher
python examples/d1s_moving/moving_then_removed_volume_cad.py --output removed-volume-cad-results

Example 3 and its CAD version need a chain with iron activation products, such as the full ENDF/B-VIII.1 chain.

Example 1: static geometry, moving neutron source

The nickel sphere, room, hydrogen shielding slab and mesh remain fixed. A 14.1 MeV neutron beam pointing along +x changes source position between three 20-minute irradiation intervals: (-12, -4, 0), (-12, 0, 0), (-12, 4, 0) cm. Each changed neutron source has its own production configuration. After shutdown, twelve cooling observations use the same stationary photon geometry and the cumulative history of all three irradiations.

The complete driver uses the shared helper in the same example directory:

"""Example 1: fixed geometry irradiated at three neutron source positions."""

import numpy as np
from openmc.deplete import d1s

from d1s_mesh_common import configuration_at, parse_arguments, run_example


NEUTRON_POSITIONS_CM = ((-12.0, -4.0, 0.0),
                        (-12.0, 0.0, 0.0),
                        (-12.0, 4.0, 0.0))


def make_simulation(args):
    # Same physical geometry, materials, and mesh in every neutron model.
    # Changing source position requires a distinct production configuration.
    irradiations = [
        d1s.Irradiation(
            configuration_at(emitter_x_cm=0.0, args=args,
                             neutron_source_position_cm=source_position),
            (20.0, 'min'), source_rate=1.e12, name=f'irradiation-{index}')
        for index, source_position in enumerate(NEUTRON_POSITIONS_CM, 1)
    ]
    shutdown = configuration_at(emitter_x_cm=0.0, args=args)
    simulation = d1s.Simulation([
        *irradiations,
        d1s.Cooling(shutdown, (1.0, 'h'),
                    sample_times=np.linspace(0.0, 3600.0, 12),
                    name='stationary-emitter'),
    ], chain_file=args.chain_file)
    return simulation, {'stationary-emitter': 0.0}


def main():
    args = parse_arguments(__doc__, 'd1s-moving-neutron-source')
    simulation, emitter_positions = make_simulation(args)
    run_example(simulation, args, emitter_positions, NEUTRON_POSITIONS_CM,
                'Fixed geometry; earlier neutron source movement')


if __name__ == '__main__':
    main()

neutron_flux.gif shows the moving neutron source during irradiation. photon_flux.gif shows the subsequent stationary gamma emitter as its activity and parent contributions decay. No neutron source remains active during cooling.

Example 2: static neutron source, one moving activation volume

The neutron source is fixed at (-15, 0, 0) cm, independently of emitter_x_cm. The nickel sphere moves through x=0, 12 and 24 cm in three 20-minute irradiation intervals, while the room, shielding and tally grid remain fixed. Because the irradiation geometry changes, there are three production banks. The same emitter identity carries all of their history.

After neutron shutdown, the sphere moves through x=24, 18, 12, 6, 0 and -6 cm during six 10-minute cooling intervals. Samples at local offsets 0 and 5 minutes produce twelve photon frames. For each frame, source points from all three irradiation banks are transferred into the current sphere placement and transported through that actual geometry.

"""Example 2: fixed neutron source, one moving nickel activation volume."""

from openmc.deplete import d1s

from d1s_mesh_common import configuration_at, parse_arguments, run_example


# This source is independent of the nickel position and never moves.
NEUTRON_POSITION_CM = (-15.0, 0.0, 0.0)
IRRADIATION_POSITIONS_CM = (0.0, 12.0, 24.0)
COOLING_POSITIONS_CM = (24.0, 18.0, 12.0, 6.0, 0.0, -6.0)


def make_simulation(args):
    irradiations = [
        d1s.Irradiation(
            configuration_at(emitter_x_cm=emitter_position, args=args,
                             neutron_source_position_cm=NEUTRON_POSITION_CM),
            (20.0, 'min'), source_rate=1.e12, name=f'irradiation-{index}')
        for index, emitter_position in enumerate(IRRADIATION_POSITIONS_CM, 1)
    ]
    # Stable 'emitter' identity follows the same nickel object through all
    # irradiation and cooling models. History does not reset after a move.
    cooling = []
    emitter_positions = {}
    for index, emitter_position in enumerate(COOLING_POSITIONS_CM, 1):
        name = f'cooling-position-{index}'
        emitter_positions[name] = emitter_position
        cooling.append(d1s.Cooling(
            configuration_at(emitter_x_cm=emitter_position, args=args),
            (10.0, 'min'), sample_times=[0.0, (5.0, 'min')], name=name))
    simulation = d1s.Simulation([*irradiations, *cooling],
                                 chain_file=args.chain_file)
    return simulation, emitter_positions


def main():
    args = parse_arguments(__doc__, 'd1s-moving-activated-volume')
    simulation, emitter_positions = make_simulation(args)
    run_example(simulation, args, emitter_positions, [NEUTRON_POSITION_CM],
                'Fixed neutron source; moving activated nickel volume')


if __name__ == '__main__':
    main()

The source never follows the sphere. Cooling configurations have no assigned neutron source; replay supplies the decay photons. The nickel sphere is the only physical volume that changes placement. The surrounding void fills the remaining space.

RegularMesh tally and animation details

The shared helper creates a fixed world-coordinate grid for every model:

mesh = openmc.RegularMesh()
mesh.dimension = (60, 40, 1)
mesh.lower_left = (-30.0, -24.0, -2.0)
mesh.upper_right = (60.0, 24.0, 2.0)

tally = openmc.Tally(name='decay photon mesh flux')
tally.filters = [openmc.MeshFilter(mesh), openmc.ParticleFilter('photon')]
tally.scores = ['flux']
model.tallies = [tally]

The single z bin has finite 4 cm thickness. Frames show a slab-volume-averaged field, not a zero-thickness plane. For the filter order above:

tally = results.get_tally('decay photon mesh flux', step_name, local_time)
mesh = tally.find_filter(openmc.MeshFilter).mesh
data = tally.get_reshaped_data(expand_dims=True)
# D1S has already scaled by photons/s. Divide only by voxel volume.
flux_xy = data[:, :, 0, 0, 0, 0] / mesh.volumes[:, :, 0]
image.set_data(flux_xy.T)  # Matplotlib rows are y, columns are x.

The helper uses FuncAnimation and PillowWriter to create GIFs, with one fixed logarithmic color scale across all frames. Photon units are photons/cm²/s, not dose. Neutron production tallies are separately scaled by initial neutrons/s and voxel volume. No ffmpeg or unstructured-mesh backend is needed.

Each example saves:

  • neutron_flux.gif: three irradiation snapshots with the active neutron-source marker.
  • photon_flux.gif: twelve cooling snapshots with the current nickel outline and source sites marked off.
  • First and last PNG previews for both animations.
  • neutron_mesh_flux.npz and mesh_flux.npz: physical means, transport/conditional standard deviations, schedule times, source rates and positions. Photon data shape is (frame, nx, ny).
  • Production/replay banks and raw statepoints under their dedicated D1S directories.

Animation previews

Generated using the examples' default (60, 40, 1) RegularMesh with ENDF/B-VIII.1 data. Examples 1 and 2 used 5 batches of 50,000 histories and the nickel test chain. Example 3 and its CAD version used 10 batches of 200,000 histories and the full ENDF/B-VIII.1 chain. Each GIF has a fixed color scale across its frames. The grid stays fixed in world coordinates. White outlines mark nickel, cyan marks the fixed hydrogen slab, a dashed silver outline marks the iron slab, and the green arrow marks the neutron source, a monodirectional 14.1 MeV pencil beam along +x (shown off during cooling).

Example 1: moving neutron source, fixed geometry

Neutron irradiation: three static source positions; the nickel and surrounding geometry do not move.

Example 1 neutron mesh flux: moving neutron source and fixed geometry

Decay photons after shutdown: twelve cooling observations of the stationary activated nickel. The earlier neutron sources are off.

Example 1 decay photon mesh flux: stationary activated nickel cooling

Example 2: fixed neutron source, moving activated nickel volume

Neutron irradiation: the source stays at (-15, 0, 0) cm while the nickel occupies three positions.

Example 2 neutron mesh flux: fixed neutron source and moving nickel volume

Decay photons after shutdown: twelve observations as the same activated nickel volume moves through six positions. Its cumulative activation history follows it; the neutron source is off.

Example 2 decay photon mesh flux: moving activated nickel during cooling

Example 3: fixed iron slab, nickel moves then is removed

Same irradiation as Example 2, plus a stationary 6 cm iron slab along the bottom (y from -18 to -12 cm, z from -8 to 8 cm). It is its own iron slab component, activated mainly by Fe56(n,p)Mn56 from neutrons scattered out of the beam. It needs a chain with iron products, so these previews used the full ENDF/B-VIII.1 chain.

Example 3 neutron mesh flux: fixed source, moving nickel, fixed iron slab

Decay photons after shutdown: the nickel moves through x = 24, 16 and 8 cm, then the final 40-minute cooling model has no nickel cell and 'emitter': None in its source map. The last eight frames show only the decaying iron slab. The iron photon rate is about 60% of the nickel's at removal (4.1e8 vs ~6.7e8 photons/s), and its emission is spread over a much larger volume.

Example 3 decay photon mesh flux: nickel moves then is removed, iron slab stays

The two shields behave as expected. With the nickel at x = 8 cm, its share of the flux (total minus the iron-only frame) is ~7.6e4 photons/cm²/s just above the iron and indistinguishable from zero just below it. Across the 4 cm, 0.07 g/cm³ H1 slab along y = 0, flux × r² from the nickel centre stays flat at ~5.5e7 from x = 32 to 40 cm, so there is no attenuation step.

Example 3 in CAD (DAGMC)

The iron slab, H1 slab and nickel sphere are CadQuery solids with the CSG dimensions, meshed by cad_to_dagmc with meshing_backend='cad-to-dagmc-mesher'. Each model places the DAGMC universe in a padded CSG box, and components are selected with d1s.DAGMCVolumes by raw H5M volume ID (iron 1, H1 2, nickel 3). The removed state maps 'emitter' to None, as in CSG.

Example 3 CAD neutron flux

Example 3 CAD decay photon flux

Against the CSG run, photon source rates agree to four significant figures in every frame, per-voxel flux differences divided by their combined standard deviation have mean -0.13 to 0.09 and standard deviation 0.96 to 0.99, and total mesh flux agrees within 0.3%.

These are sampled flux fields, not dose or continuous-motion tracking. Playback speed is illustrative; titles give the physical schedule times. Photon error estimates exclude neutron production-bank uncertainty. The GIF assets are hosted on a separate preview branch and pinned to an immutable commit, so generated binaries are not part of this implementation PR.

Actual sampled output

Both examples were run at their defaults: 5 batches × 5,000 histories, (60, 40, 1) mesh, nickel test chain, and local ENDF/B-VIII.1 neutron/photon data. Each completed three neutron captures and twelve photon observations. All four GIFs were checked: three neutron frames and twelve photon frames per example. First/last PNGs were visually checked. Values below are illustrative sampled results, not reference values or a convergence claim.

Example 1 (first and last printed cooling rows):

step,minutes_after_shutdown,emitter_x_cm,photons_per_second,max_mesh_flux
stationary-emitter,0.0,0,1.268992e+09,4.040547e+07
... intermediate observations omitted ...
stationary-emitter,60.0,0,5.109621e+08,5.435698e+06

Example 2 (first and last printed cooling rows):

step,minutes_after_shutdown,emitter_x_cm,photons_per_second,max_mesh_flux
cooling-position-1,0.0,24,1.418377e+09,3.934093e+07
... intermediate observations omitted ...
cooling-position-6,55.0,-6,5.626505e+08,1.162973e+07

The last column is maximum sampled voxel photon flux in photons/cm²/s. A local maximum need not decay monotonically when the geometry moves or sampled histories change; total source strength follows cumulative decay. Photon errors remain conditional on the finite neutron banks.

These are discrete static transport snapshots. The neutron animation depicts each interval's steady irradiation field; the photon animation depicts cooling, not concurrent emission tracking during irradiation or integrated dose along a continuous travel path. The pure H1 slab is an illustrative non-decay-emitting shield, not an engineering design. Activating replacement shielding needs its own component selector/history.

Additional introductory example: cell detector and three cooling positions

This example irradiates a nickel emitter for one hour at x=0 cm, then observes its decay photons at three successive placements. The detector stays at x=60 cm. Each placement has a separately constructed, actual photon geometry and the matching component transform. The stable component name emitter carries the original production history across the moves, even though each model has different cell/material IDs.

The neutron source is stationary at (0.0, 0.0, 0.0) and is assigned only to the irradiation model at position A. emitter_x_cm controls the nickel component geometry and its photon-bank transform, not the neutron source. No neutron source is assigned to positions B or C. During all Cooling observations, including position A, the workflow installs the banked decay-photon source automatically. The activated nickel moves after shutdown; the neutron source does not become a photon source.

Prerequisites: build/install this branch, make its OpenMC executable available on PATH, configure nickel neutron and photon cross sections with OPENMC_CROSS_SECTIONS, and set OPENMC_CHAIN_FILE to a compatible reaction/decay chain XML file containing the relevant nickel activation products. The chain provides D1S data; this example does not perform depletion. Keep the caller's openmc.lib session uninitialized. The output directories must be new or empty.

from pathlib import Path

import numpy as np
import openmc
from openmc.deplete import d1s


# Cross sections must be configured through OPENMC_CROSS_SECTIONS.
# OPENMC_CHAIN_FILE must point to compatible reaction/decay data for nickel.
chain_file = openmc.config.get('chain_file')
if chain_file is None:
    raise RuntimeError('Set OPENMC_CHAIN_FILE to a suitable chain XML file')

detector_radius = 5.0  # cm
detector_volume = 4.0 * np.pi * detector_radius**3 / 3.0


def configuration_at(emitter_x_cm):
    """Place the emitter at the specified x coordinate in centimeters."""
    nickel = openmc.Material()
    nickel.add_element('Ni', 1.0)
    nickel.set_density('g/cm3', 8.9)

    outer = openmc.Sphere(r=100.0, boundary_type='vacuum')
    emitter_surface = openmc.Sphere(x0=emitter_x_cm, r=5.0)
    detector_surface = openmc.Sphere(x0=60.0, r=detector_radius)
    emitter = openmc.Cell(fill=nickel, region=-emitter_surface)
    detector = openmc.Cell(region=-detector_surface)
    surrounding_void = openmc.Cell(
        region=-outer & +emitter_surface & +detector_surface)

    model = openmc.Model(
        geometry=openmc.Geometry([emitter, detector, surrounding_void]))
    model.settings.run_mode = 'fixed source'
    model.settings.batches = 5
    model.settings.particles = 10_000
    model.settings.seed = 12345

    flux = openmc.Tally(name='detector photon flux')
    flux.filters = [openmc.ParticleFilter('photon'),
                    openmc.CellFilter(detector)]
    flux.scores = ['flux']
    model.tallies = [flux]

    transform = np.eye(4)
    transform[0, 3] = emitter_x_cm
    return d1s.Configuration(
        model,
        components={'emitter': d1s.Cells([emitter])},
        transforms={'emitter': transform})


# Independent model objects, but one stable physical component identity.
position_a = configuration_at(emitter_x_cm=0.0)
position_b = configuration_at(emitter_x_cm=20.0)
position_c = configuration_at(emitter_x_cm=40.0)

# A stationary neutron source is used only for irradiation at position A.
# Its position does not depend on emitter_x_cm.
position_a.model.settings.source = openmc.IndependentSource(
    space=openmc.stats.Point((0.0, 0.0, 0.0)),
    energy=openmc.stats.Discrete([14.1e6], [1.0]),
    particle='neutron')
# No neutron source is assigned to B or C. Every Cooling observation uses
# banked decay photons instead, including cooling at position A.

simulation = d1s.Simulation([
    d1s.Irradiation(position_a, (1.0, 'h'), source_rate=1.e12,
                   name='irradiate'),
    d1s.Cooling(position_a, (1.0, 'h'),
                sample_times=[0.0, (30.0, 'min')], name='position-a'),
    d1s.Cooling(position_b, (1.0, 'h'),
                sample_times=[0.0, (30.0, 'min')], name='position-b'),
    d1s.Cooling(position_c, (1.0, 'h'),
                sample_times=[0.0, (30.0, 'min'), (1.0, 'h')],
                name='position-c'),
], chain_file=Path(chain_file))

simulation.validate()
production = simulation.prepare(
    output_dir='d1s-multi-position-production',
    run_kwargs={'threads': 2})
results = simulation.evaluate(
    production, output_dir='d1s-multi-position-observations',
    run_kwargs={'threads': 2})

# Local offset 30 minutes into position B is 90 minutes after shutdown.
tally = results.get_tally('detector photon flux', 'position-b', (30.0, 'min'))
# Already physically normalized: do not multiply by photon rate again.
# Divide the cell-integrated flux by detector volume to get photons/cm2/s.
print('Position B detector flux:', tally.mean.item() / detector_volume)

for observation in results.observations.values():
    cooling_age = observation.global_time - simulation.steps[0].duration
    print(observation.step,
          'minutes after shutdown:', cooling_age / 60.0,
          'source photons/s:', observation.source_rate)

# Example output from the validated run with the nickel test chain and
# ENDF/B-VIII.1 cross sections (OpenMC transport logs omitted):
# Position B detector flux: 2237.972268084385
# position-a minutes after shutdown: 0.0 source photons/s: 900620119.8226608
# position-a minutes after shutdown: 30.0 source photons/s: 375101602.7669192
# position-b minutes after shutdown: 60.0 source photons/s: 355244154.9376025
# position-b minutes after shutdown: 90.0 source photons/s: 339146619.8972395
# position-c minutes after shutdown: 120.0 source photons/s: 325727611.07907367
# position-c minutes after shutdown: 150.0 source photons/s: 314472467.18798673
# position-c minutes after shutdown: 180.0 source photons/s: 304975077.9992773
# Detector flux is in photons/cm2/s. These are illustrative sampled results,
# not reference values or evidence of convergence. Values depend on the chain,
# cross sections, particle counts, seed, and transport settings. Reported tally
# uncertainty excludes neutron production-bank uncertainty.

What each API object means

  • Cells([emitter]) selects the emitting material cell in that particular model. Only the nickel emitter needs a source identity here; the void detector and surrounding void do not.
  • Configuration(model, components=..., transforms=...) associates that model-local cell with the physical identity emitter and its reference-to-global placement. configuration_at() moves the actual sphere and declares the same translation for banked births. A transform alone does not move geometry.
  • Irradiation(configuration, duration, source_rate) adds production for the specified neutron model. source_rate is total initial neutrons/s, not local flux. The workflow enables decay-photon capture automatically.
  • Cooling(configuration, duration, sample_times=...) advances time without adding activation. Its configuration is fixed for the whole interval. Different positions require different Cooling steps/configurations, not different sample_times within one step. Sample offsets are local to their interval; 0.0 observes immediately after switching placement.
  • Simulation.prepare() runs neutron capture once for the sole irradiation configuration. evaluate() reweights and transfers that retained bank and runs photon transport for each nonzero observation. It automatically replaces the neutron source with photon replay and applies physical-rate normalization once.
  • Results.get_tally(name, step_name, local_time) selects an already physically scaled result. Observation.global_time includes irradiation and all preceding cooling durations; the code subtracts the irradiation duration to report time since shutdown.

The placement/time sequence is:

Cooling step Emitter x (cm) Interval after shutdown (min) Observation ages after shutdown (min)
position-a 0 0 to 60 0, 30
position-b 20 60 to 120 60, 90
position-c 40 120 to 180 120, 150, 180

Decay is cumulative across the entire timeline. Moving to B or C does not reset activation or cooling age and does not require another neutron calculation. The detector response changes due to both decay and the emitter's new location. This is a sequence of static observations, not emission integrated along a continuous travel path. Add more placements/intervals to approximate a sampled trajectory.

The separate prepare()/evaluate() calls allow the same production to be reused with another cooling path or schedule, provided its irradiation steps reference the same prepared Configuration objects. Do not mutate those objects. Alternatively, simulation.run(output_dir='d1s-multi-position', run_kwargs={'threads': 2}) performs both stages in one call. To model multiple neutron irradiation states as well, insert additional Irradiation steps with a new configuration for each changed neutron geometry or source spectrum.

The exact example above was run using the local nickel chain and ENDF/B-VIII.1 data. It completed one neutron capture and seven photon observations. Checks confirmed translated birth positions, preserved birth directions/energies, and cumulative decay across all three placements. The particle counts are illustrative, not a claim of converged dose or full neutron/photon uncertainty.

Implementation and compatibility

  • Adds the opt-in Settings.d1s_source_write capture setting and per-rank photon-bank shards, including normalization counts on empty ranks.
  • Preserves the ordinary source-bank compound layout. Optional parent tags and weighted file-source sampling enable replay without changing ordinary FileSource uniform sampling/stored-weight behavior.
  • Preserves parent attribution through particle splitting and photon/charged-particle descendants.
  • Keeps existing single-model D1S utilities available. Staged results are already time corrected and must not be corrected a second time.
  • Uses private model clones and isolated executable runs. DAGMC containment and zero-source CAD/unstructured-mesh sizing use an isolated geometry-only shared-library subprocess. Caller models are not modified.
  • Replay drops captured births below the destination model's photon energy cutoff (settings.cutoff['energy_photon'], default 1 keV), matching what ordinary transport would do at the first collision.
  • kernel_index in replayed source sites indexes the kernels actually returned in provenance['kernels'].
  • CSG instance lookup handles 2-D hexagonal lattices, and nonzero-source replay restores DistribcellFilter paths.
  • Replay writes its statepoint at the final batch only and drops any caller sourcepoint batches, so a valid sourcepoint schedule cannot become an invalid one.
  • Documents the staged example, rigid transforms, component identities, capture/replay schema, normalization, and execution limits.

Physics and execution limits

  • Fixed-source, continuous-energy Monte Carlo only. No eigenvalue, multigroup, random-ray, statepoint restart, or particle restart support in this workflow.
  • Zero initial production history and piecewise-constant production per irradiation interval. No burnup, target depletion, composition evolution, or general transmutation/decay-chain inventory solver.
  • Reported standard deviations are photon transport uncertainty conditional on the finite sampled neutron banks. They exclude neutron production/bank-generation uncertainty and are not full coupled uncertainty estimates.
  • A zero sampled bank is not proof of zero physical activation. Zero-source observations skip transport and return correctly sized zero tallies.
  • Banks are held in memory, with O(N) storage in captured births. Production reuse is in-process, not an on-disk restart interface. Configurations must not be mutated after preparation.
  • The bank's history_id is the emitting track ID and is not guaranteed to identify original external-source ancestry for shared-bank secondary tracks. The independent original-history normalization count is unaffected.

Validation

  • After merging current develop: the D1S unit, edge-case, moving-example, settings and d1s_multimodel regression tests give 126 passed on a DAGMC build before the merge and 116 passed, 10 DAGMC skips on a non-DAGMC build after it.
  • 137 focused Python tests passed, covering new staged/edge-case tests, existing D1S utilities, settings, source behavior, and the new integration cases.
  • All four integration transitions passed with two MPI ranks in history-based transport: CSG→CSG, CSG→DAGMC, DAGMC→CSG, and DAGMC→DAGMC.
  • The same four transitions passed with two MPI ranks in event-based transport.
  • Earlier single-rank history-based/event-based and regression --update checks passed.
  • Built with MPI, DAGMC, OpenMP, and strict floating-point settings. CTest: 13 passed, 1 skipped, 0 failed. Clang-format 18 and git diff --check passed.
  • Integration tests check analytic cumulative decay, rate linearity, parent partitioning, rigid source movement, capture normalization, and caller-model immutability rather than adding library-specific golden reference files.
  • Local nuclear data were ENDF/B-VIII.1, not the official NNDC regression dataset. The test runner reports that expected warning. Four expected deprecation warnings exercise retained legacy surface-source settings.
  • Local OpenMPI TCP runs stalled in collective communication. The completed two-rank runs used OMPI_MCA_pml=ob1, OMPI_MCA_btl=self,sm, and OMPI_MCA_coll=^han. This is a local validation environment workaround, not an application default.

jon-proximafusion and others added 3 commits October 14, 2026 18:38
The nickel moves during cooling and is then removed from both the
geometry and the source map, leaving the activated iron slab as the
only emitter. The photon animation contrasts strong attenuation by the
iron with negligible attenuation by the H1 slab.

Co-authored-by: jon-proximafusion <174589458+jon-proximafusion@users.noreply.github.com>
@shimwell

shimwell commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

Example 3 previews: fixed iron slab, nickel moves then is removed

Added in 83e0a4b (moving_then_removed_volume.py). Same irradiation as Example 2, plus a stationary 6 cm iron slab along the bottom (y from -18 to -12 cm, z from -8 to 8 cm). The slab is its own iron slab component and is activated mainly by Fe56(n,p)Mn56 from neutrons scattered out of the beam. Run with the full ENDF/B-VIII.1 chain, 10 batches × 50,000 histories.

Neutron irradiation: source fixed at (-15, 0, 0) cm, nickel at x = 0, 12 and 24 cm, iron slab fixed.

Example 3 neutron mesh flux

Decay photons after shutdown: the nickel moves through x = 24, 16 and 8 cm. It is then removed from the geometry and given 'emitter': None in the source map. The last eight frames show only the decaying iron slab.

Example 3 decay photon mesh flux

What to look for:

  • Iron activation: lower than the nickel. At removal the iron emits about 60% of the nickel's photons (4.1e8 vs about 6.7e8 photons/s), spread over a much larger volume.
  • Attenuation by iron: with the nickel at x = 8 cm, its share of the flux is about 7.6e4 photons/cm²/s just above the slab and indistinguishable from zero just below it.
  • No attenuation by H1: the 4 cm, 0.07 g/cm³ H1 slab shows no step. Flux × r² from the nickel centre stays flat at about 5.5e7 from x = 32 to 40 cm.

The iron slab is drawn as a dashed outline so its own emission stays visible.

shimwell and others added 2 commits November 4, 2026 19:01
…ernel index

Replay now drops births below the destination photon energy cutoff and
excludes them from the photon source rate. External source sites are
only checked against the cutoff at their first collision, so these
photons could otherwise score a first flight. The production bank keeps
every birth.

Target instance checks use only as many lattice indices as the lattice
has dimensions, so 2-D hexagonal lattices resolve to their instance.

Nonzero observations restore DistribcellFilter paths from the target
geometry, matching the zero-source branch, so DataFrames work.

kernel_index now indexes the returned provenance kernels list, which
omits kernels with no surviving births.

Co-authored-by: jon-proximafusion <174589458+jon-proximafusion@users.noreply.github.com>
…arrow

The CAD example builds the same solids with CadQuery and meshes them to
DAGMC with cad_to_dagmc using the cad-to-dagmc-mesher backend. It shares
the schedule, mesh and plotting with the CSG example. The neutron source
marker is now an arrow along the beam direction.

Co-authored-by: jon-proximafusion <174589458+jon-proximafusion@users.noreply.github.com>
@shimwell

shimwell commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

Higher-statistics previews with the beam drawn as an arrow

The neutron source marker is now a green arrow at the source point, pointing along the beam (+x). The source is a monodirectional 14.1 MeV pencil beam. Rendered from 8bc6a17.

Example Histories per model Previous
1: moving neutron source 250,000 (50,000 × 5), 10× 25,000
2: moving activated nickel 250,000 (50,000 × 5), 10× 25,000
3: iron slab, nickel removed 2,000,000 (200,000 × 10), 4× 500,000

Example 3 got 4× rather than 10×. Every observation stores a photon replay bank, and at 5M histories the 14 banks would need about 80 GB of disk. Examples 1 and 2 use the nickel test chain; example 3 uses the full ENDF/B-VIII.1 chain.

Example 1: moving neutron source, fixed geometry

Example 1 neutron flux

Example 1 decay photon flux

Example 2: fixed neutron source, moving activated nickel

Example 2 neutron flux

Example 2 decay photon flux

The dark region to the right of the nickel in the later frames is the nickel shadowing itself. Activation concentrates on the beam-entry side of the sphere, and photons heading right cross about 10 cm of nickel.

Example 3: fixed iron slab, nickel moves then is removed

Example 3 neutron flux

Example 3 decay photon flux

@shimwell

shimwell commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

Example 3 in CAD (DAGMC)

A CAD version of the iron slab example sits alongside the CSG one: moving_then_removed_volume_cad.py, added in 8bc6a17.

  • The iron slab, H1 slab and nickel sphere are CadQuery solids with the same dimensions as the CSG model. The H1 slab has the iron cut out where they meet.
  • cad_to_dagmc meshes them with meshing_backend='cad-to-dagmc-mesher' (cad_to_dagmc 0.15.1, cad-to-dagmc-mesher 0.4.1). It writes one DAGMC file per distinct nickel placement, six in total. The last one, for the removed state, contains only the iron and H1.
  • Each model puts the DAGMC universe (auto_geom_ids=True) in a CSG box with vacuum boundaries, padded 1 cm beyond the room so no CAD surface lies on the boundary.
  • Components are selected with d1s.DAGMCVolumes by raw H5M volume ID: iron 1, H1 2, nickel 3. The removed state maps 'emitter' to None, as in CSG.
  • The schedule, mesh tally and plotting are shared with the CSG example.

Run on a DAGMC-enabled build with 200,000 × 10 histories and the full ENDF/B-VIII.1 chain, the same settings as the CSG preview.

Neutron irradiation

Example 3 CAD neutron flux

Decay photons after shutdown

Example 3 CAD decay photon flux

Agreement with CSG

  • Photon source rates agree to four significant figures in every frame, for example 1.9648e9 vs 1.9652e9 photons/s at shutdown and 3.4369e8 vs 3.4362e8 at 65 min.
  • Per-voxel flux differences, divided by their combined standard deviation, have mean -0.13 to 0.09 and standard deviation 0.96 to 0.99 across the frames checked. That is consistent with statistical noise only.
  • Total mesh flux agrees within 0.3%.

shimwell and others added 2 commits November 4, 2026 19:23
D1S writes a statepoint only at the final batch. A caller sourcepoint
schedule such as batches [1, 3] stored in the statepoint was then no
longer a subset of the statepoint batches, and the backend rejected the
input. Drop the sourcepoint batches so the backend follows the
statepoint, keeping the other sourcepoint options.

Co-authored-by: jon-proximafusion <174589458+jon-proximafusion@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants