Skip to content

Python API

The reference below is generated by mkdocstrings from the package's type stubs. Classes appear under their public names (yamc.Material, yamc.Tally, ...) with their typed constructors. The private yamc._core module that holds the compiled extension is not listed.

yamc -- Yet Another Monte Carlo code.

AngleDistribution

Energy-dependent secondary-angle distribution; sample(energy) draws a scattering cosine (mu) for a given incoming energy.

energy property

energy: list[float]

Get energy grid

num_energy_points property

num_energy_points: int

Get number of energy points

sample

sample(incoming_energy: float) -> float

Sample scattering cosine (mu) for a given incoming energy

Source code in yamc/_core/__init__.pyi
157
158
159
160
def sample(self, incoming_energy: builtins.float) -> builtins.float:
    r"""
    Sample scattering cosine (mu) for a given incoming energy
    """

BoundingBox

BoundingBox(lower_left: Sequence[float], upper_right: Sequence[float])

Axis-aligned bounding box in 3D space.

This class is typically returned by geometry methods rather than constructed directly.

Create a bounding box from corner coordinates.

Parameters:

Name Type Description Default
lower_left Sequence[float]

Lower-left corner [x, y, z] in cm.

required
upper_right Sequence[float]

Upper-right corner [x, y, z] in cm.

required

Returns:

Name Type Description
BoundingBox BoundingBox

An axis-aligned bounding box.

Source code in yamc/_core/__init__.pyi
200
201
202
203
204
205
206
207
208
209
210
def __new__(cls, lower_left: typing.Sequence[builtins.float], upper_right: typing.Sequence[builtins.float]) -> BoundingBox:
    r"""
    Create a bounding box from corner coordinates.

    Args:
        lower_left: Lower-left corner [x, y, z] in cm.
        upper_right: Upper-right corner [x, y, z] in cm.

    Returns:
        BoundingBox: An axis-aligned bounding box.
    """

lower_left property

lower_left: list[float]

Lower-left corner coordinates [x, y, z] in cm.

upper_right property

upper_right: list[float]

Upper-right corner coordinates [x, y, z] in cm.

center property

center: list[float]

Center coordinates [x, y, z] in cm.

width property

width: list[float]

Width along each axis [dx, dy, dz] in cm.

is_finite

is_finite() -> bool

True when every corner coordinate is finite.

An unbounded region (a half-space, or a cell with no outer surface) produces infinite extents, which cannot be voxelized. Mirrors [yamc_geo::BoundingBox::is_finite].

Returns:

Type Description
bool

bool

Source code in yamc/_core/__init__.pyi
189
190
191
192
193
194
195
196
197
198
199
def is_finite(self) -> builtins.bool:
    r"""
    True when every corner coordinate is finite.

    An unbounded region (a half-space, or a cell with no outer surface)
    produces infinite extents, which cannot be voxelized. Mirrors
    [`yamc_geo::BoundingBox::is_finite`].

    Returns:
        bool
    """

ClearanceResult

The outcome of assessing a material against one clearance limit set.

Every regulation here uses the same arithmetic: each radionuclide's activity divided by its tabulated limit, summed. The material meets the limits when that sum, index, is below threshold. The per-nuclide dicts are ordered largest first.

Examples:

>>> result = material.clearance_index("UK_EPR16_out_of_scope")
>>> result.clearable
False
>>> result.dominant(2)
[('Co60', 11.2...), ('Cs137', 0.029...)]
>>> print(result)

limit_set property

limit_set: str

Name of the limit set assessed against.

index property

index: float

The sum of activity-to-limit ratios.

threshold property

threshold: float

The value the index must stay below, normally 1.

units property

units: str

Activity units the comparison was made in: "Bq/g", "Ci/m3" or "Bq".

clearable property

clearable: bool

Whether the material meets this set's limits.

out_of_scope property

out_of_scope: bool

Whether the regulation excludes this material outright, which for the UK sets means every radionuclide present is shorter lived than 100 s.

by_nuclide property

by_nuclide: dict[str, float]

Each nuclide's contribution to the index, largest first.

activities property

activities: dict[str, float]

Each nuclide's activity in units, largest first.

limits_used property

limits_used: dict[str, float]

The limit applied to each nuclide, after any metal, per-gram, dynamic or secular equilibrium adjustment.

defaulted property

defaulted: list[str]

Nuclides that took the set's catch-all limit because the table does not list them.

excluded property

excluded: dict[str, str]

Nuclide to the reason its activity was left out, which is always that a parent's limit already accounts for it in full.

credited property

credited: dict[str, float]

Nuclide to the activity a parent accounted for, where the parent could only support part of it. The remainder was assessed against the nuclide's own limit.

uncovered property

uncovered: dict[str, float]

Activity present with no limit and no catch-all, so absent from the index entirely. The number to check before trusting a comfortable index.

unlimited property

unlimited: list[str]

Nuclides present that the source explicitly places no limit on.

uncovered_activity property

uncovered_activity: float

Total activity with no limit, in units.

uncovered_fraction property

uncovered_fraction: float

Share of total activity that falls outside the sum, from 0 to 1.

material_name property

material_name: str

The material's name, carried through for reporting.

assessed_activity

assessed_activity(nuclide: str) -> float

The activity actually charged against the limit for one nuclide: its total activity, less any part a parent accounted for.

Parameters:

Name Type Description Default
nuclide str

Nuclide name, such as "Co60".

required
Source code in yamc/_core/__init__.pyi
529
530
531
532
533
534
535
536
def assessed_activity(self, nuclide: builtins.str) -> builtins.float:
    r"""
    The activity actually charged against the limit for one nuclide: its
    total activity, less any part a parent accounted for.

    Args:
        nuclide (str): Nuclide name, such as ``"Co60"``.
    """

dominant

dominant(count: int = 10) -> list[tuple[str, float]]

The nuclides contributing most to the index, largest first.

Parameters:

Name Type Description Default
count int

How many to return.

10
Source code in yamc/_core/__init__.pyi
537
538
539
540
541
542
543
def dominant(self, count: builtins.int = 10) -> builtins.list[tuple[builtins.str, builtins.float]]:
    r"""
    The nuclides contributing most to the index, largest first.

    Args:
        count (int): How many to return.
    """

to_json

to_json(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save the result as JSON: the limit set, material, index, threshold and units, whether it is clearable or out of scope, and per nuclide the index contributions, activities and limits used, with the defaulted, excluded, credited, uncovered and unlimited nuclides.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write. None returns the JSON as bytes instead, for a browser or Pyodide session.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The JSON when path is None.

Examples:

>>> result.to_json("clearance.json")
>>> json.loads(result.to_json())["clearable"]
True
Source code in yamc/_core/__init__.pyi
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def to_json(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save the result as JSON: the limit set, material, index, threshold
    and units, whether it is clearable or out of scope, and per nuclide
    the index contributions, activities and limits used, with the
    defaulted, excluded, credited, uncovered and unlimited nuclides.

    Args:
        path (str | os.PathLike | None): Where to write. None returns the
            JSON as bytes instead, for a browser or Pyodide session.

    Returns:
        bytes | None: The JSON when ``path`` is None.

    Examples:
        >>> result.to_json("clearance.json")
        >>> json.loads(result.to_json())["clearable"]
        True
    """

ConvergencePoint

One snapshot of a tally's aggregate statistics versus history count.

elapsed_secs property

elapsed_secs: float

Transport wall-clock time elapsed at this snapshot, in seconds.

ConvergenceTarget

ConvergenceTarget(metric: str, threshold: float, tally: Optional[str] = None, tally_id: Optional[int] = None)

A precision-based stopping criterion. Attach to model.convergence_targets to stop a (single-process) run early once a tally is precise enough.

model.convergence_targets = [ConvergenceTarget("relative_error", 0.02, tally="flux")]

metric is one of "relative_error", "std_dev", "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, so a mesh tally converges voxel by voxel rather than in total (CPU only). Restrict to one tally with tally (name) or tally_id; otherwise the threshold must hold for every tally.

Source code in yamc/_core/__init__.pyi
604
605
606
607
608
609
610
611
612
def __new__(cls, metric: builtins.str, threshold: builtins.float, tally: typing.Optional[builtins.str] = None, tally_id: typing.Optional[builtins.int] = None) -> ConvergenceTarget:
    r"""
    ``metric`` is one of ``"relative_error"``, ``"std_dev"``,
    ``"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, so a mesh tally converges voxel by voxel rather than
    in total (CPU only). Restrict to one tally with ``tally`` (name) or
    ``tally_id``; otherwise the threshold must hold for every tally.
    """

Cooldown

Cooldown(duration: Any, model: Optional[Any] = None, moves: Optional[Any] = None)

A cooling step: no source, the materials just decay for duration.

Create a cooling step.

Parameters:

Name Type Description Default
duration Any

A number of seconds, or a (value, unit) tuple such as (7, "d"). Units: s, min, h, d, a (year).

required
model Optional[Any]

The yamc Model the machine is in while it cools, for yamc.simulate_shutdown_dose: the decay photons of every earlier irradiation are transported through its geometry. It needs no source. Cells absent from it have been removed and no longer emit; a cell of the same name is the same component. A later step without a model stays in this one.

None
moves Optional[Any]

Cells of model that sit away from their reference position (where they were built in the model they were irradiated in, unless that step moved them too), as {cell or cell name: (dx, dy, dz)} in cm or a 4x4 rigid transformation matrix. The activation moves with the cell; model must already hold the cell at its moved position.

None
Source code in yamc/_core/__init__.pyi
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
def __new__(cls, duration: typing.Any, model: typing.Optional[typing.Any] = None, moves: typing.Optional[typing.Any] = None) -> Cooldown:
    r"""
    Create a cooling step.

    Args:
        duration: A number of seconds, or a ``(value, unit)`` tuple such as
            ``(7, "d")``. Units: s, min, h, d, a (year).
        model: The yamc ``Model`` the machine is in while it cools, for
            ``yamc.simulate_shutdown_dose``: the decay photons of every
            earlier irradiation are transported through its geometry. It
            needs no source. Cells absent from it have been removed and no
            longer emit; a cell of the same name is the same component. A
            later step without a ``model`` stays in this one.
        moves: Cells of ``model`` that sit away from their reference
            position (where they were built in the model they were
            irradiated in, unless that step moved them too), as
            ``{cell or cell name: (dx, dy, dz)}`` in cm or a 4x4 rigid
            transformation matrix. The activation moves with the cell;
            ``model`` must already hold the cell at its moved position.
    """

model property

model: Optional[Any]

The Model the machine cools in, or None.

moves property

moves: dict[str, list[list[float]]]

The moved cells, {name: 4x4 matrix}.

duration property

duration: float

Cooldown duration in seconds.

DoseCoefficients

Fluence-to-dose conversion coefficients (effective dose or ambient dose equivalent H*(10)), returned by :func:yamc.data.dose_coefficients.

Carries the energy grid, the coefficients, and their units, and can repackage itself for a tally via :meth:as_energy_function.

energy property

energy: list[float]

Incident energies in eV.

coefficients property

coefficients: list[float]

Fluence-to-dose coefficients, one per energy.

units property

units: str

Units of the coefficients ("pSv cm2").

as_energy_function

as_energy_function() -> tuple[list[float], list[float], str, str]

Repackage as the (energy, coefficients, units, interpolation) tuple accepted by Tally(energy_function=...). The interpolation is "log-log", how the tabulation is read everywhere else.

Source code in yamc/_core/__init__.pyi
937
938
939
940
941
942
def as_energy_function(self) -> tuple[builtins.list[builtins.float], builtins.list[builtins.float], builtins.str, builtins.str]:
    r"""
    Repackage as the ``(energy, coefficients, units, interpolation)`` tuple
    accepted by ``Tally(energy_function=...)``. The interpolation is
    ``"log-log"``, how the tabulation is read everywhere else.
    """

DoseResult

The result of time-correcting a tally: dose at the selected cooling step(s).

mean / std_dev are 1-D (one selected step, when steps was a single int) or 2-D (one row per selected step). by_nuclide maps each parent radionuclide to its mean contribution, in the same shape. times is the elapsed time (seconds) at the end of each selected step.

mean property

mean: Any

Mean dose rate, 1-D for a single selected step or 2-D (one row per step).

std_dev property

std_dev: Any

Standard error on mean, same shape: the transport's statistical uncertainty alone.

data_std_dev property

data_std_dev: Optional[Any]

The nuclear-data uncertainty on mean, same shape, when time_correct_tally was given data_uncertainty; None otherwise. From the half-lives behind the time-correction factors and the decay photon spectrum normalisations that scale each emitter's tally, with an emitter's gamma and x-ray normalisations drawn independently: the lower end of the range data_std_dev_correlated closes.

data_std_dev_standard_error property

data_std_dev_standard_error: Optional[Any]

The standard error of data_std_dev, same shape: how far another ensemble of the same size could put it. It allows for a heavy tail (it carries the sample kurtosis). None when data_std_dev is, and NaN in a bin below four replicas.

data_std_dev_correlated property

data_std_dev_correlated: Optional[Any]

data_std_dev with each emitter's gamma and x-ray normalisations drawn fully correlated, the upper end of the range the decay data leave by not stating their correlation. Equal to data_std_dev when no normalisation is drawn. Negative correlations are not considered: what the spectra share (a decay scheme's normalisation, its conversion coefficients) moves them the same way.

total_std_dev property

total_std_dev: Optional[Any]

std_dev and data_std_dev in quadrature, when both exist. They are independent: one is the transport's sampling, the other the evaluated decay data.

total_std_dev_correlated property

total_std_dev_correlated: Optional[Any]

std_dev and data_std_dev_correlated in quadrature, when both exist.

data_uncertainty_info property

data_uncertainty_info: Optional[Any]

What the nuclear-data uncertainty covered, when asked for: the half-lives sampled, those with no stated sigma, the emitters whose photon normalisation was drawn (decay_photon_normalisations_perturbed) and those with a spectrum whose normalisation is folded into its line sigmas (decay_photon_spectra_folded), the replica count, the convergence target, whether every time-correction factor's sigma reached it (converged), whether the replica cap stopped the run (hit_cap), the ones that missed (unconverged), and what was held at nominal (not_perturbed).

by_nuclide property

by_nuclide: Any

Per-radionuclide mean contribution: {nuclide: values} in the same shape as mean.

times property

times: Any

Elapsed time (seconds) at the end of each selected step.

Element

Element(name: str)

Chemical element container providing isotope helper methods.

Parameters:

Name Type Description Default
name str

Element symbol (e.g. "Fe", "U", "H").

required

Create a new Element.

Parameters:

Name Type Description Default
name str

Element symbol (e.g. "Fe", "U", "H").

required
Source code in yamc/_core/__init__.pyi
1046
1047
1048
1049
1050
1051
1052
def __new__(cls, name: builtins.str) -> Element:
    r"""
    Create a new Element.

    Args:
        name (str): Element symbol (e.g. "Fe", "U", "H").
    """

name property

name: str

Element symbol.

get_nuclides

get_nuclides() -> list[str]

Return list of isotope (nuclide) identifiers for this element.

Returns:

Type Description
list[str]

List[str]: Isotope names sorted by mass number (e.g. ["Fe54", "Fe56"]).

Source code in yamc/_core/__init__.pyi
1054
1055
1056
1057
1058
1059
1060
def get_nuclides(self) -> builtins.list[builtins.str]:
    r"""
    Return list of isotope (nuclide) identifiers for this element.

    Returns:
        List[str]: Isotope names sorted by mass number (e.g. ["Fe54", "Fe56"]).
    """

Enriched

Enriched(fraction: float, *, target: str, percent: float, fraction_type: str = 'atom')

Enrichment specification for use in Material composition dicts.

Build one with enriched() rather than by hand; the constructor is the same either way.

Create an enrichment specification.

Parameters:

Name Type Description Default
fraction float

Fraction of this component in the material.

required
target str

Target nuclide for enrichment (e.g. "Li6").

required
percent float

Enrichment percentage of the target isotope.

required
fraction_type str

"atom" for atom percent or "mass" for weight percent.

'atom'

Returns:

Name Type Description
Enriched Enriched

An enrichment specification.

Source code in yamc/_core/__init__.pyi
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def __new__(cls, fraction: builtins.float, *, target: builtins.str, percent: builtins.float, fraction_type: builtins.str = 'atom') -> Enriched:
    r"""
    Create an enrichment specification.

    Args:
        fraction (float): Fraction of this component in the material.
        target (str): Target nuclide for enrichment (e.g. "Li6").
        percent (float): Enrichment percentage of the target isotope.
        fraction_type (str): "atom" for atom percent or "mass" for weight percent.

    Returns:
        Enriched: An enrichment specification.
    """

fraction property

fraction: float

Fraction of this component in the material.

target property

target: str

Target nuclide for enrichment (e.g. "Li6").

percent property

percent: float

Enrichment percentage of the target isotope.

fraction_type property

fraction_type: str

"atom" for atom percent or "mass" for weight percent.

Estimate

A quantity's value, and the spread the nuclear-data ensemble puts on it.

nominal is the unperturbed run, and is present whether or not uncertainty was asked for. mean and std_dev are None below two replicas: a spread over fewer than two samples is unmeasured, not zero, and reporting it as zero would read as a quantity known exactly.

A quantity a decay photon intensity enters (contact dose, the photon spectrum, and the decay heat through its gamma part) has a range rather than one spread when the "decay_photon_lines" source is on, because the decay data do not state how a nuclide's photon intensities are correlated. std_dev is the lower end, every unstated correlation taken as zero, and std_dev_correlated the upper end, every one taken as one; std_dev_range gives both. For any other quantity, or with the source off, the two are equal.

nominal property

nominal: float

The quantity from the unperturbed inventory.

mean property

mean: Optional[float]

The ensemble mean, or None below two replicas.

Worth comparing against nominal: activity and decay heat are linear in the atom densities, so the two agree to within the sampling error, and a gap between them says the perturbation is biased rather than merely wide.

std_dev property

std_dev: Optional[float]

The ensemble's sample standard deviation, or None below two replicas.

The lower end of std_dev_range: where the "decay_photon_lines" source is drawn, the correlations the decay data leave unstated between a nuclide's photon intensities are taken as zero, which is the evaluation read literally.

std_dev_correlated property

std_dev_correlated: Optional[float]

The ensemble's sample standard deviation with those correlations taken as one, or None below two replicas: within each nuclide the lines of a spectrum, the spectrum's normalisation and its lines, and its gamma and x-ray spectra all move together. The upper end of std_dev_range.

Evaluated on the same inventories as std_dev, so the two differ by the line data alone. Equal to std_dev for activity, or when the "decay_photon_lines" source is not drawn.

std_dev_range property

std_dev_range: Optional[tuple[float, float]]

(std_dev, std_dev_correlated), the range every non-negative correlation between a nuclide's photon intensities gives, or None below two replicas.

Negative correlations are not considered: what the intensities leave unstated is a shared normalisation, which moves every line it scales the same way and cannot anticorrelate them.

relative_std_dev property

relative_std_dev: Optional[float]

std_dev as a fraction of nominal, or None if either is absent.

relative_std_dev_correlated property

relative_std_dev_correlated: Optional[float]

std_dev_correlated as a fraction of nominal, or None if either is absent.

std_dev_standard_error property

std_dev_standard_error: Optional[float]

The standard error of std_dev: how far another ensemble of the same size could put it, or None below four replicas.

It allows for a heavy tail, Var(s^2) = s^4 (2/(n-1) + kappa/n) with kappa the sample excess kurtosis, so a lognormal-tailed quantity reads as less settled than a Gaussian one at the same replica count.

replicas property

replicas: int

How many replicas the ensemble held.

replica_spread property

replica_spread: Optional[float]

The replicas' standard deviation as they were solved, before any Monte Carlo noise was removed, or None below two replicas. Equal to std_dev where no noise was measured.

noise property

noise: Optional[float]

The standard deviation of the Monte Carlo noise removed from replica_spread, so std_dev**2 = replica_spread**2 - noise**2 (floored at zero), or None where it was not measured.

With transport replica weights each replica's tallied shift from the nominal is resolved only to the transport's history count. Each replica is solved a second time from the even half of the histories, and the spread of the difference measures that noise.

noise_dominated property

noise_dominated: bool

Whether the noise removed exceeded a quarter of the variance left: the sigma is then mostly what more transport histories would sharpen.

FaceOutput

Python-visible face output.

FaceVolumeMesh

FaceVolumeMesh(vertices: Sequence[Sequence[float]], triangles: Sequence[Sequence[int]], face_ids: Sequence[int])

A welded surface mesh being corrected so each curved CAD face encloses its CAD volume (the compiled core of :mod:yamc.cad._face_volumes).

It holds the mesh and its adjacency and does the volume sums, the root finding and the vertex moves; the caller evaluates the CAD (curve points and normals, a face's exact volume) and hands it in.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

List of [x, y, z] coordinates.

required
triangles Sequence[Sequence[int]]

List of [i, j, k] vertex indices.

required
face_ids Sequence[int]

The CAD face of each triangle.

required

Raises:

Type Description
ValueError

If face_ids is not one per triangle or a triangle indexes past the vertices.

Source code in yamc/_core/__init__.pyi
1260
def __new__(cls, vertices: typing.Sequence[typing.Sequence[builtins.float]], triangles: typing.Sequence[typing.Sequence[builtins.int]], face_ids: typing.Sequence[builtins.int]) -> FaceVolumeMesh: ...

faces

faces() -> list[int]

The face ids, in order of first appearance among the triangles.

Source code in yamc/_core/__init__.pyi
1261
1262
1263
1264
def faces(self) -> builtins.list[builtins.int]:
    r"""
    The face ids, in order of first appearance among the triangles.
    """

vertices

vertices() -> list[list[float]]

The vertices, as moved so far.

Source code in yamc/_core/__init__.pyi
1265
1266
1267
1268
def vertices(self) -> builtins.list[builtins.list[builtins.float]]:
    r"""
    The vertices, as moved so far.
    """

neighbours

neighbours(faces: Sequence[int]) -> list[int]

faces and every face sharing a mesh edge of their boundaries, sorted.

Source code in yamc/_core/__init__.pyi
1269
1270
1271
1272
1273
def neighbours(self, faces: typing.Sequence[builtins.int]) -> builtins.list[builtins.int]:
    r"""
    ``faces`` and every face sharing a mesh edge of their boundaries,
    sorted.
    """

boundary_points

boundary_points(faces: Sequence[int], lo: Sequence[float], hi: Sequence[float]) -> list[tuple[int, list[float]]]

[(vertex, [x, y, z]), ...]: the vertices on the boundaries of faces inside the box from lo to hi (bounds included), by vertex index.

Source code in yamc/_core/__init__.pyi
1274
1275
1276
1277
1278
1279
def boundary_points(self, faces: typing.Sequence[builtins.int], lo: typing.Sequence[builtins.float], hi: typing.Sequence[builtins.float]) -> builtins.list[tuple[builtins.int, builtins.list[builtins.float]]]:
    r"""
    ``[(vertex, [x, y, z]), ...]``: the vertices on the boundaries of
    ``faces`` inside the box from ``lo`` to ``hi`` (bounds included), by
    vertex index.
    """

is_chain

is_chain(chain: Sequence[int]) -> bool

Whether every two consecutive vertices of chain share a mesh edge.

Source code in yamc/_core/__init__.pyi
1280
1281
1282
1283
def is_chain(self, chain: typing.Sequence[builtins.int]) -> builtins.bool:
    r"""
    Whether every two consecutive vertices of ``chain`` share a mesh edge.
    """

add_edge

add_edge(chain: Sequence[int], arcs: Sequence[Sequence[Sequence[float]]]) -> int

Record a matched CAD edge: its mesh vertices chain in curve order and arcs, per segment, points of the edge from the segment's first vertex to its second, ends included. Returns the edge's index.

Raises:

Type Description
ValueError

If there is not one arc of at least two points per segment, or a vertex is not in the mesh.

Source code in yamc/_core/__init__.pyi
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
def add_edge(self, chain: typing.Sequence[builtins.int], arcs: typing.Sequence[typing.Sequence[typing.Sequence[builtins.float]]]) -> builtins.int:
    r"""
    Record a matched CAD edge: its mesh vertices ``chain`` in curve order
    and ``arcs``, per segment, points of the edge from the segment's first
    vertex to its second, ends included. Returns the edge's index.

    Raises:
        ValueError: If there is not one arc of at least two points per
            segment, or a vertex is not in the mesh.
    """

move_edge

move_edge(edge: int, faces: Sequence[int], outward: Sequence[Optional[Sequence[float]]], cap: float) -> Optional[bool]

Move the vertices inside edge edge along outward (per interior vertex of its chain, the unit vector away from the centre of curvature, or None), all by one distance of at most cap, so the polyline cuts off the arc's area. Only vertices on no face but faces move. Returns whether the move hit the cap, or None when nothing moved.

Raises:

Type Description
ValueError

If there is no such edge or outward is not one per interior vertex.

Source code in yamc/_core/__init__.pyi
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
def move_edge(self, edge: builtins.int, faces: typing.Sequence[builtins.int], outward: typing.Sequence[typing.Optional[typing.Sequence[builtins.float]]], cap: builtins.float) -> typing.Optional[builtins.bool]:
    r"""
    Move the vertices inside edge ``edge`` along ``outward`` (per interior
    vertex of its chain, the unit vector away from the centre of
    curvature, or None), all by one distance of at most ``cap``, so the
    polyline cuts off the arc's area. Only vertices on no face but
    ``faces`` move. Returns whether the move hit the cap, or None when
    nothing moved.

    Raises:
        ValueError: If there is no such edge or ``outward`` is not one per
            interior vertex.
    """

face_apex

face_apex(face_id: int) -> Optional[list[float]]

Start correcting face face_id: the point to take the CAD face's volume from, or None (with the reason counted) when the face has no vertex it may move or its boundary is not matched to added edges.

Raises:

Type Description
ValueError

If the mesh has no such face.

Source code in yamc/_core/__init__.pyi
1307
1308
1309
1310
1311
1312
1313
1314
1315
def face_apex(self, face_id: builtins.int) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Start correcting face ``face_id``: the point to take the CAD face's
    volume from, or None (with the reason counted) when the face has no
    vertex it may move or its boundary is not matched to added edges.

    Raises:
        ValueError: If the mesh has no such face.
    """

move_face

move_face(cad_volume: float, cap: float) -> bool

Finish the face face_apex started: move its own vertices along their normals, all by one distance of at most cap, so its triangles enclose cad_volume (the CAD face's volume from the apex) once closed to the CAD edges. Returns whether the move hit the cap.

Raises:

Type Description
ValueError

If no face was started since the last move.

Source code in yamc/_core/__init__.pyi
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
def move_face(self, cad_volume: builtins.float, cap: builtins.float) -> builtins.bool:
    r"""
    Finish the face ``face_apex`` started: move its own vertices along
    their normals, all by one distance of at most ``cap``, so its
    triangles enclose ``cad_volume`` (the CAD face's volume from the apex)
    once closed to the CAD edges. Returns whether the move hit the cap.

    Raises:
        ValueError: If no face was started since the last move.
    """

stats

stats() -> list[tuple[str, int]]

Counts of what the moves did: [(name, count), ...].

Source code in yamc/_core/__init__.pyi
1326
1327
1328
1329
def stats(self) -> builtins.list[tuple[builtins.str, builtins.int]]:
    r"""
    Counts of what the moves did: ``[(name, count), ...]``.
    """

GeometrySliceData

Rich return type for sample_slice() on Geometry, Cell, and Model.

Behaves like a (cell_ids, material_ids) tuple for backward compatibility (supports tuple unpacking), while also exposing coordinate metadata and an edges() method for matplotlib outline overlays.

edges

edges(color_by: str = 'material') -> list[list[bool]]

Compute edge-detection mask for cell or material boundaries.

Parameters:

Name Type Description Default
color_by str

"cell" or "material". Defaults to "material".

'material'

Returns:

Type Description
list[list[bool]]

2D list of bools -- True at boundary pixels.

Source code in yamc/_core/__init__.pyi
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
def edges(self, color_by: builtins.str = 'material') -> builtins.list[builtins.list[builtins.bool]]:
    r"""
    Compute edge-detection mask for cell or material boundaries.

    Args:
        color_by: ``"cell"`` or ``"material"``. Defaults to ``"material"``.

    Returns:
        2D list of bools -- ``True`` at boundary pixels.
    """

InteractivePlot

Result of .plot() -- renders inline in Jupyter and supports saving to .html or .png.

In a Jupyter notebook the plot renders automatically via _repr_html_(). Use :meth:save to write the result to disk.

Examples:

>>> plot = geometry.plot(basis="xy")
>>> plot.to_html("geometry.html")   # interactive HTML
>>> plot.to_png("geometry.png")     # static PNG snapshot

html property

html: str

The raw HTML string.

to_html

to_html(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save the plot as a self-contained interactive HTML page, or return its bytes when path is None.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The page when path is None.

Source code in yamc/_core/__init__.pyi
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
def to_html(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save the plot as a self-contained interactive HTML page, or return
    its bytes when ``path`` is None.

    Args:
        path (str | os.PathLike | None): Where to write.

    Returns:
        bytes | None: The page when ``path`` is None.
    """

to_png

to_png(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save the plot as a static PNG image with axes, border and tick marks, or return its bytes when path is None.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The image when path is None.

Source code in yamc/_core/__init__.pyi
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
def to_png(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save the plot as a static PNG image with axes, border and tick
    marks, or return its bytes when ``path`` is None.

    Args:
        path (str | os.PathLike | None): Where to write.

    Returns:
        bytes | None: The image when ``path`` is None.
    """

InteractiveTallyPlot

Result object for interactive tally plots.

Renders inline in Jupyter notebooks via _repr_html_(). Use :meth:save to write the result to disk.

Examples:

>>> plot = tally.interactive_plot(geometry=geo, basis="xy")
>>> plot.to_html("tally.html")   # interactive HTML

html property

html: str

The raw HTML string.

to_html

to_html(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save the plot as a self-contained interactive HTML page, or return its bytes when path is None.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The page when path is None.

Source code in yamc/_core/__init__.pyi
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
def to_html(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save the plot as a self-contained interactive HTML page, or return
    its bytes when ``path`` is None.

    Args:
        path (str | os.PathLike | None): Where to write.

    Returns:
        bytes | None: The page when ``path`` is None.
    """

LineEstimate

One decay-photon line, with the ensemble's spread on its emission rate and on the energy it is emitted at.

The set of lines is not the same in every replica: a nuclide that falls below the density floor in one draw takes its lines out of that draw. The spectrum is reported over the union, a line missing from a replica counts as a zero in it, and emitting says how many replicas emitted it at all -- which is the difference between a line that is dim and a line that is sometimes not there.

energy property

energy: float

Nominal line energy [eV], the one the evaluation states. Lines are matched across replicas on it.

energy_mean property

energy_mean: Optional[float]

The mean energy the emitting replicas drew for this line [eV], or None below two of them. Equal to energy unless the "decay_photon_lines" source drew line energies.

energy_std_dev property

energy_std_dev: Optional[float]

The sample standard deviation of the drawn energy over the emitting replicas [eV], or None below two of them. Zero unless the "decay_photon_lines" source drew line energies.

nominal property

nominal: float

Emission rate from the unperturbed inventory [photons/s].

mean property

mean: Optional[float]

The ensemble mean [photons/s], or None below two replicas.

std_dev property

std_dev: Optional[float]

The ensemble's sample standard deviation [photons/s], or None below two replicas.

The lower end of std_dev_range: where the "decay_photon_lines" source is drawn, the correlations the decay data leave unstated between a nuclide's photon intensities are taken as zero, which is the evaluation read literally.

std_dev_correlated property

std_dev_correlated: Optional[float]

The ensemble's sample standard deviation with those correlations taken as one, or None below two replicas: within each nuclide the lines of a spectrum, the spectrum's normalisation and its lines, and its gamma and x-ray spectra all move together. The upper end of std_dev_range.

Evaluated on the same inventories as std_dev, so the two differ by the line data alone. Equal to std_dev when the "decay_photon_lines" source is not drawn.

std_dev_range property

std_dev_range: Optional[tuple[float, float]]

(std_dev, std_dev_correlated), the range every non-negative correlation between a nuclide's photon intensities gives, or None below two replicas.

Negative correlations are not considered: what the intensities leave unstated is a shared normalisation, which moves every line it scales the same way and cannot anticorrelate them.

relative_std_dev property

relative_std_dev: Optional[float]

std_dev as a fraction of nominal, or None if either is absent.

relative_std_dev_correlated property

relative_std_dev_correlated: Optional[float]

std_dev_correlated as a fraction of nominal, or None if either is absent.

std_dev_standard_error property

std_dev_standard_error: Optional[float]

The standard error of std_dev, or None below four replicas (see Estimate.std_dev_standard_error).

replicas property

replicas: int

How many replicas the ensemble held.

emitting property

emitting: int

Replicas that emitted this line at a positive rate.

Below replicas when the emitter dropped out of some draws. A line with emitting far below replicas has a mean that is mostly zeros, and its spread says more about whether the line is there than about how bright it is.

LostParticle

A particle that was lost during transport due to a geometry gap.

Contains diagnostic information about the particle's state at the time it was lost, including position, direction, energy, and the last known cell and surface.

Examples:

>>> model.simulate_transport()
>>> for lp in model.lost_particles:
...     print(f"Lost {lp.particle_type} at {lp.position}, E={lp.energy} eV")
...     print(f"  Last cell: {lp.last_cell_name} (ID: {lp.last_cell_id})")
...     print(f"  Surface crossed: {lp.surface_id}")

particle_type property

particle_type: str

Particle type ("neutron" or "photon").

position property

position: list[float]

Position where the particle was lost [x, y, z] in cm.

direction property

direction: list[float]

Direction the particle was traveling [u, v, w].

energy property

energy: float

Energy of the particle in eV.

last_cell_id property

last_cell_id: Optional[int]

Cell ID of the last cell the particle was in before getting lost.

last_cell_name property

last_cell_name: Optional[str]

Name of the last cell the particle was in before getting lost.

surface_id property

surface_id: Optional[int]

Surface ID of the surface that was crossed when the particle got lost.

Material

Material(composition: dict[str | Nuclide, float | Enriched], density: float, *, density_units: str = 'g/cm3', name: Optional[str] = None, id: Optional[int] = None, fraction_type: str = 'atom', transmutable: bool = False, volume: Optional[float] = None, temperature: Optional[float] = None, s_alpha_beta: str | list[str] | dict[str, float] | None = None)

A homogeneous mixture of nuclides at a fixed density and temperature.

A Material is built from a composition dictionary whose keys may be nuclide names ("Fe56"), element symbols ("Fe"), chemical formulas ("H2O"), or :class:Nuclide objects, and whose values are atom or weight fractions (or :func:enriched specifications). Density is always a float; density_units sets its meaning (g/cm3 by default, or atom/barn-cm for a total atom density). For absolute per-nuclide atom densities use :meth:Material.from_atom_densities.

Every Material has an id from construction: the one passed to the constructor, or else a fresh one that no earlier material in the process was given, so a yamc.Tally can filter on it before any geometry exists. Materials may also carry a name, volume (cm³), temperature (K), and a transmutable flag that marks them for depletion by Model.simulate_transmutation (not needed for Material.transmute()).

Examples:

>>> import yamc
>>> water = yamc.Material(composition={"H2O": 1.0}, density=1.0)
>>> iron = yamc.Material(
...     composition={"Fe54": 0.0585, "Fe56": 0.9175,
...                  "Fe57": 0.0212, "Fe58": 0.0028},
...     density=7.874, name="iron")

Create a new material with a declarative composition and density.

Parameters:

Name Type Description Default
composition dict[str | Nuclide, float | Enriched]

Material composition. Keys are element symbols ("Fe"), nuclide names ("Fe56"), chemical formulas ("H2O"), or yamc.Nuclide objects. Values are fractions (float) or enriched() objects.

required
density float

Density value, interpreted per density_units. For density_units="atom/barn-cm" it is the total atom density and the composition values are relative atom fractions.

required
density_units str

Density units: "g/cm3", "g/cc", "kg/m3", or "atom/barn-cm" (total atom density; requires fraction_type="atom").

'g/cm3'
name Optional[str]

Name for the material.

None
id Optional[int]

ID for the material. Defaults to a fresh one, which no earlier material was given.

None
fraction_type str

"atom" for atom fractions or "mass" for mass fractions.

'atom'
transmutable bool

Mark this material for depletion by Model.simulate_transmutation. Not needed for Material.transmute(), which depletes whatever it is called on.

False
volume Optional[float]

Material volume in cm³.

None
temperature Optional[float]

Temperature in Kelvin. If omitted, 294 K is used, or the only temperature the nuclear data carries when it carries just one.

None
s_alpha_beta str | list[str] | dict[str, float] | None

Thermal scattering tables for bound nuclides, by name, such as "c_H_in_H2O" or ["c_Li_in_FLiBe", "c_Be_in_FLiBe", "c_F_in_FLiBe"]. A dict gives the fraction of each table's nuclides that is bound ({"c_H_in_ZrH": 0.6}); otherwise all of them are. Which nuclides a table applies to is the table's own data. The tables come from the library the cross sections are read from, at the material's temperature (the table it sits on, or the two it falls between); a library without thermal tables, or a temperature outside a table's range, is refused.

None

Returns:

Name Type Description
Material Material

A new material.

Source code in yamc/_core/__init__.pyi
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
def __new__(cls, composition: dict[str | Nuclide, float | Enriched], density: builtins.float, *, density_units: builtins.str = 'g/cm3', name: typing.Optional[builtins.str] = None, id: typing.Optional[builtins.int] = None, fraction_type: builtins.str = 'atom', transmutable: builtins.bool = False, volume: typing.Optional[builtins.float] = None, temperature: typing.Optional[builtins.float] = None, s_alpha_beta: str | list[str] | dict[str, float] | None = None) -> Material:
    r"""
    Create a new material with a declarative composition and density.

    Args:
        composition (dict[str | Nuclide, float | Enriched]): Material composition.
            Keys are element symbols ("Fe"), nuclide names ("Fe56"),
            chemical formulas ("H2O"), or ``yamc.Nuclide`` objects.
            Values are fractions (float) or enriched() objects.
        density (float): Density value, interpreted per ``density_units``. For
            ``density_units="atom/barn-cm"`` it is the total atom density and the
            composition values are relative atom fractions.
        density_units (str): Density units: "g/cm3", "g/cc", "kg/m3", or
            "atom/barn-cm" (total atom density; requires fraction_type="atom").
        name (Optional[str]): Name for the material.
        id (Optional[int]): ID for the material. Defaults to a fresh one,
            which no earlier material was given.
        fraction_type (str): "atom" for atom fractions or "mass" for mass fractions.
        transmutable (bool): Mark this material for depletion by
            ``Model.simulate_transmutation``. Not needed for
            ``Material.transmute()``, which depletes whatever it is called on.
        volume (Optional[float]): Material volume in cm³.
        temperature (Optional[float]): Temperature in Kelvin. If omitted,
            294 K is used, or the only temperature the nuclear data carries
            when it carries just one.
        s_alpha_beta (str | list[str] | dict[str, float] | None): Thermal
            scattering tables for bound nuclides, by name, such as
            ``"c_H_in_H2O"`` or ``["c_Li_in_FLiBe", "c_Be_in_FLiBe",
            "c_F_in_FLiBe"]``. A dict gives the fraction of each table's
            nuclides that is bound (``{"c_H_in_ZrH": 0.6}``); otherwise all
            of them are. Which nuclides a table applies to is the table's
            own data. The tables come from the library the cross sections
            are read from, at the material's temperature (the table it sits
            on, or the two it falls between); a library without thermal
            tables, or a temperature outside a table's range, is refused.

    Returns:
        Material: A new material.
    """

name property writable

name: Optional[str]

Get the name of the material

s_alpha_beta property writable

s_alpha_beta: dict[str, float]

The thermal scattering tables this material uses, as a dict of table name to the fraction of its nuclides that is bound.

thermal_bindings property

thermal_bindings: dict[str, list[str]]

The nuclides each loaded thermal scattering table applies to, as a dict of table name to nuclide names. Empty until the nuclear data is read.

id property writable

id: int

The material's ID.

Assigned when the material is built: the id given to the constructor, or else a fresh one that no earlier material in the process was given. Copies keep it, as do the materials a transmutation result returns, which keep their original's. Setting it replaces it, but a tally keeps the IDs it was built with. Two different Material objects with one ID are refused where they meet, in a yamc.Geometry (its cells and their mesh fills) or a yamc.MeshGeometry, and a yamc.Tally refuses one ID listed twice.

transmutable property writable

transmutable: bool

Whether this material is marked for depletion by Model.simulate_transmutation.

Only the coupled model driver reads this: in a geometry of many materials it selects which ones to deplete. Material.transmute() ignores it, so you do not need to set it for a standalone transmutation.

fraction_type property

fraction_type: str

Get the percent type ("atom" or "mass") for this material's nuclide fractions.

nuclides property

nuclides: list[tuple[str, float]]

Get the material nuclides as a tuple of (name, fraction) pairs.

When the Material was constructed via the Python API, the order matches the user's composition dict (with each input key's expanded nuclides sorted alphabetically). Nuclides added later (e.g. by transmutation) appear alphabetically at the end. When no input order is tracked, all nuclides are alphabetical.

volume property writable

volume: Optional[float]

Material volume in cm^3, if set.

density property

density: float

Density value, in the material's density_units. Always a float: for "atom/barn-cm" (and transmuted materials) it is the total atom density, otherwise the mass density.

density_units property

density_units: str

Density units string ("g/cm3", "kg/m3", or "atom/barn-cm").

temperature property writable

temperature: str

Temperature label in Kelvin (e.g. "293").

reaction_mts property

reaction_mts: list[int]

Sorted list of all unique MT reaction numbers present.

sample_distance_to_collision

sample_distance_to_collision(energy: float, seed: Optional[int]) -> Optional[float]

Sample a distance to the next neutron collision.

Uses the macroscopic total cross section (calculating it first if missing) and an exponential distribution to sample a path length. A deterministic RNG seed can be supplied for reproducibility.

Parameters:

Name Type Description Default
energy float

Neutron energy in eV.

required
seed Optional[int]

RNG seed; if omitted a fixed internal seed is used.

required

Returns:

Type Description
Optional[float]

Optional[float]: Sampled distance in cm, or None if total XS unavailable.

Source code in yamc/_core/__init__.pyi
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
def sample_distance_to_collision(self, energy: builtins.float, seed: typing.Optional[builtins.int]) -> typing.Optional[builtins.float]:
    r"""
    Sample a distance to the next neutron collision.

    Uses the macroscopic total cross section (calculating it first if missing)
    and an exponential distribution to sample a path length. A deterministic
    RNG seed can be supplied for reproducibility.

    Args:
        energy (float): Neutron energy in eV.
        seed (Optional[int]): RNG seed; if omitted a fixed internal seed is used.

    Returns:
        Optional[float]: Sampled distance in cm, or None if total XS unavailable.
    """

from_atom_densities staticmethod

from_atom_densities(atom_densities: dict, *, name: Optional[str] = None, id: Optional[int] = None, transmutable: bool = False, volume: Optional[float] = None, temperature: Optional[float] = None) -> Material

Build a material directly from absolute per-nuclide atom densities.

Stores the given atoms/barn-cm values verbatim (no normalize-then-recombine round-trip), so callers that already hold raw number densities -- e.g. the transmutation stepper -- keep full precision. density then reports the sum of the values. This replaces the old Material(comp, density="sum").

Parameters:

Name Type Description Default
atom_densities dict[str, float]

nuclide name -> atoms/barn-cm.

required
name Optional[str]

Name for the material.

None
id Optional[int]

ID for the material. Defaults to a fresh one, which no earlier material was given.

None
transmutable bool

Mark this material for depletion by Model.simulate_transmutation. Not needed for Material.transmute(), which depletes whatever it is called on.

False
volume Optional[float]

Material volume in cm³.

None
temperature Optional[float]

Temperature in Kelvin. If omitted, 294 K is used, or the only temperature the nuclear data carries when it carries just one.

None

Returns:

Name Type Description
Material Material

A material whose composition is absolute atom densities.

Source code in yamc/_core/__init__.pyi
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
@staticmethod
def from_atom_densities(atom_densities: dict, *, name: typing.Optional[builtins.str] = None, id: typing.Optional[builtins.int] = None, transmutable: builtins.bool = False, volume: typing.Optional[builtins.float] = None, temperature: typing.Optional[builtins.float] = None) -> Material:
    r"""
    Build a material directly from absolute per-nuclide atom densities.

    Stores the given atoms/barn-cm values verbatim (no normalize-then-recombine
    round-trip), so callers that already hold raw number densities -- e.g. the
    transmutation stepper -- keep full precision. ``density`` then reports the
    sum of the values. This replaces the old ``Material(comp, density="sum")``.

    Args:
        atom_densities (dict[str, float]): nuclide name -> atoms/barn-cm.
        name (Optional[str]): Name for the material.
        id (Optional[int]): ID for the material. Defaults to a fresh one,
            which no earlier material was given.
        transmutable (bool): Mark this material for depletion by
            ``Model.simulate_transmutation``. Not needed for
            ``Material.transmute()``, which depletes whatever it is called on.
        volume (Optional[float]): Material volume in cm³.
        temperature (Optional[float]): Temperature in Kelvin. If omitted,
            294 K is used, or the only temperature the nuclear data carries
            when it carries just one.

    Returns:
        Material: A material whose composition is absolute atom densities.
    """

get_nuclide_names

get_nuclide_names() -> list[str]

Return a list of nuclide names currently present in the material.

Source code in yamc/_core/__init__.pyi
2003
2004
2005
2006
def get_nuclide_names(self) -> builtins.list[builtins.str]:
    r"""
    Return a list of nuclide names currently present in the material.
    """

read_nuclear_data

read_nuclear_data(nuclide_path_map: Optional[Any] = None, photon_data: Optional[Mapping[str, str]] = None) -> None

Bulk load nuclear data from a mapping of nuclide -> file path or a keyword string.

Parameters:

Name Type Description Default
nuclide_path_map Optional[Dict[str, str] | str]

Mapping of nuclide names to file paths or a keyword string.

None
photon_data Optional[Dict[str, str]]

Mapping of element symbols to photon Arrow data paths.

None

Raises:

Type Description
ValueError

If any file cannot be read / parsed.

Source code in yamc/_core/__init__.pyi
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
def read_nuclear_data(self, nuclide_path_map: typing.Optional[typing.Any] = None, photon_data: typing.Optional[typing.Mapping[builtins.str, builtins.str]] = None) -> None:
    r"""
    Bulk load nuclear data from a mapping of nuclide -> file path or a keyword string.

    Args:
        nuclide_path_map (Optional[Dict[str,str] | str]): Mapping of nuclide names to file paths or a keyword string.
        photon_data (Optional[Dict[str,str]]): Mapping of element symbols to photon Arrow data paths.

    Raises:
        ValueError: If any file cannot be read / parsed.
    """

nuclide_ptr_addr

nuclide_ptr_addr(nuclide: str) -> Optional[int]

Return raw pointer address of an internal shared Nuclide (debug only).

Parameters:

Name Type Description Default
nuclide str

Nuclide name.

required

Returns:

Type Description
Optional[int]

Optional[int]: Address value (process-local) or None if not present.

Source code in yamc/_core/__init__.pyi
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
def nuclide_ptr_addr(self, nuclide: builtins.str) -> typing.Optional[builtins.int]:
    r"""
    Return raw pointer address of an internal shared Nuclide (debug only).

    Args:
        nuclide (str): Nuclide name.

    Returns:
        Optional[int]: Address value (process-local) or None if not present.
    """

unified_energy_grid_neutron

unified_energy_grid_neutron() -> list[float]

Return (and build if needed) the unified neutron energy grid.

Returns:

Type Description
list[float]

List[float]: Energy grid in eV.

Source code in yamc/_core/__init__.pyi
2041
2042
2043
2044
2045
2046
2047
def unified_energy_grid_neutron(self) -> builtins.list[builtins.float]:
    r"""
    Return (and build if needed) the unified neutron energy grid.

    Returns:
        List[float]: Energy grid in eV.
    """

calculate_microscopic_xs_neutron

calculate_microscopic_xs_neutron(mt_filter: Optional[Sequence[int]] = None) -> dict[str, dict[int, list[float]]]

Calculate microscopic neutron cross sections on the unified energy grid.

Parameters:

Name Type Description Default
mt_filter Optional[List[int]]

Restrict to these MT numbers.

None

Returns:

Type Description
dict[str, dict[int, list[float]]]

Dict[str, Dict[int, List[float]]]: nuclide -> MT -> xs array

Source code in yamc/_core/__init__.pyi
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
def calculate_microscopic_xs_neutron(self, mt_filter: typing.Optional[typing.Sequence[builtins.int]] = None) -> builtins.dict[builtins.str, builtins.dict[builtins.int, builtins.list[builtins.float]]]:
    r"""
    Calculate microscopic neutron cross sections on the unified energy grid.

    Args:
        mt_filter (Optional[List[int]]): Restrict to these MT numbers.

    Returns:
        Dict[str, Dict[int, List[float]]]: nuclide -> MT -> xs array
    """

get_atoms_per_barn_cm

get_atoms_per_barn_cm() -> dict[str, float]

Number density (atoms / barn-cm) per nuclide.

Returns:

Type Description
dict[str, float]

Dict[str, float]: nuclide -> atoms / b-cm

Source code in yamc/_core/__init__.pyi
2058
2059
2060
2061
2062
2063
2064
def get_atoms_per_barn_cm(self) -> builtins.dict[builtins.str, builtins.float]:
    r"""
    Number density (atoms / barn-cm) per nuclide.

    Returns:
        Dict[str, float]: nuclide -> atoms / b-cm
    """

activity

activity(*, by_nuclide: bool = False, per: Optional[str] = None) -> Any

Calculate the radioactive activity of the current material inventory.

The material must have a volume in cm³. Atom densities are converted to total atoms using atoms/barn-cm * 1e24 * volume. The decay data (transmutation_decay_data, which has no default) provides half-lives; each nuclide's activity is N * ln(2) / half_life. Stable nuclides are omitted.

Parameters:

Name Type Description Default
by_nuclide bool

Return a dict[str, float] by nuclide instead of the total.

False
per str | None

None (default) for the total, which needs volume; "cm3" for Bq/cm³, which needs nothing; "g" for Bq/g, which needs only density.

None

Returns:

Type Description
Any

float | dict[str, float]: Activity, in Bq when per is None,

Any

Bq/cm³ when it is "cm3" and Bq/g when it is "g". The unit of

Any

a by_nuclide dict's values is the same.

Source code in yamc/_core/__init__.pyi
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
def activity(self, *, by_nuclide: builtins.bool = False, per: typing.Optional[builtins.str] = None) -> typing.Any:
    r"""
    Calculate the radioactive activity of the current material inventory.

    The material must have a ``volume`` in cm³. Atom densities are converted
    to total atoms using ``atoms/barn-cm * 1e24 * volume``. The decay data
    (``transmutation_decay_data``, which has no default) provides
    half-lives; each nuclide's activity is ``N * ln(2) / half_life``.
    Stable nuclides are omitted.

    Args:
        by_nuclide (bool): Return a ``dict[str, float]`` by nuclide instead
            of the total.
        per (str | None): ``None`` (default) for the total, which needs
            ``volume``; ``"cm3"`` for Bq/cm³, which needs nothing; ``"g"``
            for Bq/g, which needs only ``density``.

    Returns:
        float | dict[str, float]: Activity, in Bq when ``per`` is ``None``,
        Bq/cm³ when it is ``"cm3"`` and Bq/g when it is ``"g"``. The unit of
        a ``by_nuclide`` dict's values is the same.
    """

decay_heat

decay_heat(*, by_nuclide: bool = False, per: Optional[str] = None, component: Optional[str] = None) -> Any

Calculate decay heat from the current material inventory.

The material must have a volume in cm³. Atom densities are converted to total atoms using atoms/barn-cm * 1e24 * volume. The decay data (transmutation_decay_data, which has no default) provides half-lives and mean decay energies.

Parameters:

Name Type Description Default
by_nuclide bool

Return a dict[str, float] by nuclide instead of the total.

False
per str | None

None (default) for the total, which needs volume; "cm3" for W/cm³, which needs nothing; "g" for W/g, which needs only density.

None
component str | None

None (default) for the whole decay heat; "beta", "gamma" or "alpha" for one recoverable-heat component alone (the ENDF MT=457 light-particle, electromagnetic and heavy-particle energies). The gamma heat is the part that leaves a thin component; the beta and alpha heat stays put. Raises if a nuclide making decay heat carries no split, which data converted before the split does, rather than understating the component by its share.

None

Returns:

Type Description
Any

float | dict[str, float]: Decay heat, in W when per is None,

Any

W/cm³ when it is "cm3" and W/g when it is "g". The unit of a

Any

by_nuclide dict's values is the same.

Source code in yamc/_core/__init__.pyi
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
def decay_heat(self, *, by_nuclide: builtins.bool = False, per: typing.Optional[builtins.str] = None, component: typing.Optional[builtins.str] = None) -> typing.Any:
    r"""
    Calculate decay heat from the current material inventory.

    The material must have a ``volume`` in cm³. Atom densities are converted
    to total atoms using ``atoms/barn-cm * 1e24 * volume``. The decay data
    (``transmutation_decay_data``, which has no default) provides
    half-lives and mean decay energies.

    Args:
        by_nuclide (bool): Return a ``dict[str, float]`` by nuclide instead
            of the total.
        per (str | None): ``None`` (default) for the total, which needs
            ``volume``; ``"cm3"`` for W/cm³, which needs nothing; ``"g"``
            for W/g, which needs only ``density``.
        component (str | None): ``None`` (default) for the whole decay heat;
            ``"beta"``, ``"gamma"`` or ``"alpha"`` for one recoverable-heat
            component alone (the ENDF MT=457 light-particle, electromagnetic
            and heavy-particle energies). The gamma heat is the part that
            leaves a thin component; the beta and alpha heat stays put.
            Raises if a nuclide making decay heat carries no split, which
            data converted before the split does, rather than understating
            the component by its share.

    Returns:
        float | dict[str, float]: Decay heat, in W when ``per`` is ``None``,
        W/cm³ when it is ``"cm3"`` and W/g when it is ``"g"``. The unit of a
        ``by_nuclide`` dict's values is the same.
    """

decay_photon_spectrum

decay_photon_spectrum(*, per: Optional[str] = None) -> tuple[list[float], list[float]]

The decay photon line spectrum of the current inventory.

The material must have a volume in cm³. Each nuclide's atom count multiplies the line intensities the transmutation chain records for it, which are per atom per second (the emission probability already times the decay constant), so the values are photons per second rather than probabilities. Lines at the same energy are summed and the result is ascending in energy. Stable nuclides, nuclides the chain does not know and non-photon sources contribute nothing.

Lines only. Part of some decay spectra is a continuum, a density per eV rather than a set of lines, and decay_photon_continua() returns it.

The two lists are the (x, p) pair the source distributions take, so the lines round-trip straight into a photon transport source:

>>> energies, rates = activated.decay_photon_spectrum()
>>> source = PhotonSource(energy=sources.Discrete(energies, rates))

Discrete normalizes the weights, so the shape is what transport samples. sum(rates) is the line emission rate (photons/s) only, the rate that scales tallies from this source. That source leaves out every continuum, which for a continuum emitter can be most of its photons (all of them for Sm158 in ENDF/B-VIII.1); the continua emit sum(c.emission_rate for c in activated.decay_photon_continua()) more. No sources distribution yet holds a linear-linear continuum exactly, so a transport source cannot yet carry every continuum.

Returns:

Type Description
list[float]

tuple[list[float], list[float]]: Line energies (eV) and their

list[float]

emission rates (photons/s).

Source code in yamc/_core/__init__.pyi
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
def decay_photon_spectrum(self, *, per: typing.Optional[builtins.str] = None) -> tuple[builtins.list[builtins.float], builtins.list[builtins.float]]:
    r"""
    The decay photon line spectrum of the current inventory.

    The material must have a ``volume`` in cm³. Each nuclide's atom count
    multiplies the line intensities the transmutation chain records for it,
    which are per atom per second (the emission probability already times
    the decay constant), so the values are photons per second rather than
    probabilities. Lines at the same energy are summed and the result is
    ascending in energy. Stable nuclides, nuclides the chain does not know
    and non-photon sources contribute nothing.

    Lines only. Part of some decay spectra is a continuum, a density per eV
    rather than a set of lines, and ``decay_photon_continua()`` returns it.

    The two lists are the ``(x, p)`` pair the source distributions take, so
    the lines round-trip straight into a photon transport source:

        >>> energies, rates = activated.decay_photon_spectrum()
        >>> source = PhotonSource(energy=sources.Discrete(energies, rates))

    ``Discrete`` normalizes the weights, so the shape is what transport
    samples. ``sum(rates)`` is the line emission rate (photons/s) only,
    the rate that scales tallies from this source. That source leaves out
    every continuum, which for a continuum emitter can be most of its
    photons (all of them for Sm158 in ENDF/B-VIII.1); the continua emit
    ``sum(c.emission_rate for c in activated.decay_photon_continua())``
    more. No ``sources`` distribution yet holds a linear-linear continuum
    exactly, so a transport source cannot yet carry every continuum.

    Returns:
        tuple[list[float], list[float]]: Line energies (eV) and their
        emission rates (photons/s).
    """

decay_photon_continua

decay_photon_continua(*, per: Optional[str] = None) -> list[PhotonContinuum]

The decay photon continua of the current inventory, one per nuclide and continuum, in nuclide-name order.

The part of a decay spectrum ENDF gives as a density over energy rather than as lines, which decay_photon_spectrum() does not include. Each continuum keeps its own energy grid and interpolation law, and its rates are photons/s/eV (or per cm³ or per g, following per), so they are not line rates; emission_rate is the integral. A material whose nuclides have no continuum returns an empty list.

Parameters:

Name Type Description Default
per str | None

None for the whole material, which needs a volume, or 'cm3' or 'g', as for decay_photon_spectrum().

None

Returns:

Type Description
list[PhotonContinuum]

list[PhotonContinuum]: The continua, each with its nuclide,

list[PhotonContinuum]

energies, rates, interpolation law and emission rate.

Examples:

>>> for continuum in activated.decay_photon_continua():
...     print(continuum.nuclide, continuum.emission_rate)
Source code in yamc/_core/__init__.pyi
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
def decay_photon_continua(self, *, per: typing.Optional[builtins.str] = None) -> builtins.list[PhotonContinuum]:
    r"""
    The decay photon continua of the current inventory, one per nuclide
    and continuum, in nuclide-name order.

    The part of a decay spectrum ENDF gives as a density over energy rather
    than as lines, which ``decay_photon_spectrum()`` does not include. Each
    continuum keeps its own energy grid and interpolation law, and its
    rates are photons/s/eV (or per cm³ or per g, following ``per``), so
    they are not line rates; ``emission_rate`` is the integral. A material
    whose nuclides have no continuum returns an empty list.

    Args:
        per (str | None): None for the whole material, which needs a
            ``volume``, or ``'cm3'`` or ``'g'``, as for
            ``decay_photon_spectrum()``.

    Returns:
        list[PhotonContinuum]: The continua, each with its nuclide,
        energies, rates, interpolation law and emission rate.

    Examples:
        >>> for continuum in activated.decay_photon_continua():
        ...     print(continuum.nuclide, continuum.emission_rate)
    """

contact_dose

contact_dose(*, dose_quantity: str = 'absorbed-air', build_up: float = 2.0, by_nuclide: bool = False) -> Any

Contact dose rate from the material's own decay photons.

The dose someone receives with a hand on the material. It is a slab estimate rather than a transport result: the material is taken to be a half-space, so half the photons emitted at any depth head for the surface and the ones that arrive are the ones the material did not attenuate itself. That leaves no distance and no volume in the answer -- unlike activity and decay_heat, this needs no material.volume and a bigger lump of the same material reads the same.

Per photon line of energy E and per-atom emission rate S the estimate is (build_up / 2) * (response(E) / mu_material(E)) * S * E for the absorbed dose in air, and the same without the trailing E for the effective dose. mu_material is the material's own linear attenuation coefficient, built from the NIST XCOM mass attenuation coefficients of the elements present; the response is the NIST-126 mass energy-absorption coefficient of air, or the ICRP-116 photon effective-dose coefficient for anterior-posterior irradiation.

Follows the FISPACT-II manual (UKAEA-CCFE-RE(21)02, Appendix C.7.1) for the absorbed-air quantity. For photon lines it agrees with OpenMC's Material.get_photon_contact_dose_rate. A photon continuum is integrated exactly under its evaluated interpolation law.

Bremsstrahlung from decay electrons is not modelled, and nuclides whose radiation the chain file does not describe contribute nothing. Photon lines outside the tabulated range (1 keV to 20 MeV for the absorbed-air quantity, 10 keV to 20 MeV for the effective dose) are dropped, and a continuum is integrated over its part of that range.

Parameters:

Name Type Description Default
dose_quantity str

'absorbed-air' for the absorbed dose in air in Gy/h (the default, following FISPACT-II), or 'effective' for the ICRP-116 effective dose in Sv/h.

'absorbed-air'
build_up float

Build-up factor standing in for the photons that scatter in the slab and still arrive. Default 2.0, as the FISPACT-II manual suggests.

2.0
by_nuclide bool

Return a dict[str, float] by nuclide instead of the total. Nuclides that contribute nothing are left out.

False

Returns:

Type Description
Any

float | dict[str, float]: Contact dose rate in Gy/h

Any

('absorbed-air') or Sv/h ('effective').

Raises:

Type Description
ValueError

If a nuclide in the material has a photon continuum in the dose tables' range that this build cannot integrate: one whose data states no interpolation law, as transmutation data written before the law was stored does, one tabulated under a law other than histogram or linear-linear, or one whose energy and rate lists are unpaired, whose energies are not finite or descend, or whose rates are negative or not finite. Its integral is unknown, and leaving it out would understate the dose.

Examples:

>>> activated.contact_dose()
380.088...
>>> activated.contact_dose(by_nuclide=True)
{'Co60': 380.088...}
>>> activated.contact_dose(dose_quantity='effective')
380.728...
Source code in yamc/_core/__init__.pyi
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
def contact_dose(self, *, dose_quantity: builtins.str = 'absorbed-air', build_up: builtins.float = 2.0, by_nuclide: builtins.bool = False) -> typing.Any:
    r"""
    Contact dose rate from the material's own decay photons.

    The dose someone receives with a hand on the material. It is a slab
    estimate rather than a transport result: the material is taken to be a
    half-space, so half the photons emitted at any depth head for the
    surface and the ones that arrive are the ones the material did not
    attenuate itself. That leaves no distance and no volume in the answer --
    unlike ``activity`` and ``decay_heat``, this needs no ``material.volume``
    and a bigger lump of the same material reads the same.

    Per photon line of energy ``E`` and per-atom emission rate ``S`` the
    estimate is ``(build_up / 2) * (response(E) / mu_material(E)) * S * E``
    for the absorbed dose in air, and the same without the trailing ``E``
    for the effective dose. ``mu_material`` is the material's own linear
    attenuation coefficient, built from the NIST XCOM mass attenuation
    coefficients of the elements present; the response is the NIST-126
    mass energy-absorption coefficient of air, or the ICRP-116 photon
    effective-dose coefficient for anterior-posterior irradiation.

    Follows the FISPACT-II manual (UKAEA-CCFE-RE(21)02, Appendix C.7.1) for
    the absorbed-air quantity. For photon lines it agrees with OpenMC's
    ``Material.get_photon_contact_dose_rate``. A photon continuum is
    integrated exactly under its evaluated interpolation law.

    Bremsstrahlung from decay electrons is not modelled, and nuclides whose
    radiation the chain file does not describe contribute nothing. Photon
    lines outside the tabulated range (1 keV to 20 MeV for the absorbed-air
    quantity, 10 keV to 20 MeV for the effective dose) are dropped, and a
    continuum is integrated over its part of that range.

    Args:
        dose_quantity (str): ``'absorbed-air'`` for the absorbed dose in air
            in Gy/h (the default, following FISPACT-II), or ``'effective'``
            for the ICRP-116 effective dose in Sv/h.
        build_up (float): Build-up factor standing in for the photons that
            scatter in the slab and still arrive. Default 2.0, as the
            FISPACT-II manual suggests.
        by_nuclide (bool): Return a ``dict[str, float]`` by nuclide instead
            of the total. Nuclides that contribute nothing are left out.

    Returns:
        float | dict[str, float]: Contact dose rate in Gy/h
        (``'absorbed-air'``) or Sv/h (``'effective'``).

    Raises:
        ValueError: If a nuclide in the material has a photon continuum
            in the dose tables' range that this build cannot integrate: one
            whose data states no interpolation law, as transmutation data
            written before the law was stored does, one tabulated under a
            law other than histogram or linear-linear, or one whose energy
            and rate lists are unpaired, whose energies are not finite or
            descend, or whose rates are negative or not finite. Its
            integral is unknown, and leaving it out would understate the
            dose.

    Examples:
        >>> activated.contact_dose()
        380.088...
        >>> activated.contact_dose(by_nuclide=True)
        {'Co60': 380.088...}
        >>> activated.contact_dose(dose_quantity='effective')
        380.728...
    """

clearance_index

clearance_index(limit_set: str, *, metal: bool = False, apply_default_limit: bool = True, exclude_daughters: bool = True) -> ClearanceResult

Clearance index of the current inventory against one regulatory limit set.

Each radionuclide's activity is divided by its limit in the set and the ratios are summed; the material meets the limits when the sum is below the set's threshold, normally 1. The limit sets cover UK, German, US, EU and IAEA clearance, exemption and disposal tables, and come from the radiological-material-clearance-finder crate, whose documentation describes each one and where its numbers come from.

Half-lives come from the configured transmutation chain, the same ones activity() and decay_heat() use, so a nuclide the chain calls stable contributes nothing. Specific activities (Bq/g) need nothing beyond the composition, and the volumetric US sets (Ci/m3) use the mass density the atom densities imply. Only the total activity sets (Bq) need material.volume.

Stable isotopes have to stay in the material: they are most of its mass, and so most of the Bq/g denominator.

Parameters:

Name Type Description Default
limit_set str

Name of the limit set, such as "UK_EPR16_out_of_scope" or "StrlSchV_unrestricted". clearance_indices() assesses against every set at once.

required
metal bool

Whether the material is activated metal, which changes some NRC limits and adds others.

False
apply_default_limit bool

Whether to apply the set's catch-all limit to nuclides its table does not list. The UK regulations define one, so leaving this on is what they say.

True
exclude_daughters bool

Whether to leave out daughters whose parent's limit already covers them, as the regulation's own table directs. Turning it off double counts them.

True

Returns:

Name Type Description
ClearanceResult ClearanceResult

The index, whether it clears, each nuclide's

ClearanceResult

contribution, and any activity no limit in the set covers.

Raises:

Type Description
KeyError

If no limit set has that name.

ValueError

If the set is in Bq and the material has no volume.

Examples:

>>> result = material.clearance_index("UK_EPR16_out_of_scope")
>>> result.index
11.24...
>>> result.clearable
False
Source code in yamc/_core/__init__.pyi
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
def clearance_index(self, limit_set: builtins.str, *, metal: builtins.bool = False, apply_default_limit: builtins.bool = True, exclude_daughters: builtins.bool = True) -> ClearanceResult:
    r"""
    Clearance index of the current inventory against one regulatory limit set.

    Each radionuclide's activity is divided by its limit in the set and the
    ratios are summed; the material meets the limits when the sum is below
    the set's threshold, normally 1. The limit sets cover UK, German, US, EU
    and IAEA clearance, exemption and disposal tables, and come from the
    ``radiological-material-clearance-finder`` crate, whose documentation
    describes each one and where its numbers come from.

    Half-lives come from the configured transmutation chain, the same ones
    ``activity()`` and ``decay_heat()`` use, so a nuclide the chain calls
    stable contributes nothing. Specific activities (Bq/g) need nothing
    beyond the composition, and the volumetric US sets (Ci/m3) use the mass
    density the atom densities imply. Only the total activity sets (Bq)
    need ``material.volume``.

    Stable isotopes have to stay in the material: they are most of its
    mass, and so most of the Bq/g denominator.

    Args:
        limit_set (str): Name of the limit set, such as
            ``"UK_EPR16_out_of_scope"`` or ``"StrlSchV_unrestricted"``.
            ``clearance_indices()`` assesses against every set at once.
        metal (bool): Whether the material is activated metal, which
            changes some NRC limits and adds others.
        apply_default_limit (bool): Whether to apply the set's catch-all
            limit to nuclides its table does not list. The UK regulations
            define one, so leaving this on is what they say.
        exclude_daughters (bool): Whether to leave out daughters whose
            parent's limit already covers them, as the regulation's own
            table directs. Turning it off double counts them.

    Returns:
        ClearanceResult: The index, whether it clears, each nuclide's
        contribution, and any activity no limit in the set covers.

    Raises:
        KeyError: If no limit set has that name.
        ValueError: If the set is in Bq and the material has no volume.

    Examples:
        >>> result = material.clearance_index("UK_EPR16_out_of_scope")
        >>> result.index
        11.24...
        >>> result.clearable
        False
    """

clearance_indices

clearance_indices(limit_sets: Optional[Sequence[str]] = None, *, metal: bool = False, apply_default_limit: bool = True, exclude_daughters: bool = True) -> dict[str, ClearanceResult]

Clearance indexes of the current inventory against many limit sets.

The same assessment as clearance_index(), once per set. Sets the material cannot be assessed against are skipped rather than raising, which in practice means the total activity sets (Bq) when the material has no volume.

Parameters:

Name Type Description Default
limit_sets list[str] | None

Names of the limit sets. None (the default) assesses against every available set, which is also the way to see their names.

None
metal bool

As for clearance_index().

False
apply_default_limit bool

As for clearance_index().

True
exclude_daughters bool

As for clearance_index().

True

Returns:

Type Description
dict[str, ClearanceResult]

dict[str, ClearanceResult]: Results keyed by limit set name.

Raises:

Type Description
KeyError

If a named limit set does not exist.

Examples:

>>> results = material.clearance_indices()
>>> [name for name, r in results.items() if r.clearable]
['Fetter', 'NRC_long', ...]
Source code in yamc/_core/__init__.pyi
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
def clearance_indices(self, limit_sets: typing.Optional[typing.Sequence[builtins.str]] = None, *, metal: builtins.bool = False, apply_default_limit: builtins.bool = True, exclude_daughters: builtins.bool = True) -> builtins.dict[builtins.str, ClearanceResult]:
    r"""
    Clearance indexes of the current inventory against many limit sets.

    The same assessment as ``clearance_index()``, once per set. Sets the
    material cannot be assessed against are skipped rather than raising,
    which in practice means the total activity sets (Bq) when the material
    has no ``volume``.

    Args:
        limit_sets (list[str] | None): Names of the limit sets. ``None``
            (the default) assesses against every available set, which is
            also the way to see their names.
        metal (bool): As for ``clearance_index()``.
        apply_default_limit (bool): As for ``clearance_index()``.
        exclude_daughters (bool): As for ``clearance_index()``.

    Returns:
        dict[str, ClearanceResult]: Results keyed by limit set name.

    Raises:
        KeyError: If a named limit set does not exist.

    Examples:
        >>> results = material.clearance_indices()
        >>> [name for name, r in results.items() if r.clearable]
        ['Fetter', 'NRC_long', ...]
    """

mean_free_path_neutron

mean_free_path_neutron(energy: float) -> Optional[float]

Compute neutron mean free path at a given energy.

Parameters:

Name Type Description Default
energy float

Neutron energy in eV.

required

Returns:

Type Description
Optional[float]

Optional[float]: Mean free path (cm) or None if total XS unavailable.

Source code in yamc/_core/__init__.pyi
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
def mean_free_path_neutron(self, energy: builtins.float) -> typing.Optional[builtins.float]:
    r"""
    Compute neutron mean free path at a given energy.

    Args:
        energy (float): Neutron energy in eV.

    Returns:
        Optional[float]: Mean free path (cm) or None if total XS unavailable.
    """

sample_interacting_nuclide

sample_interacting_nuclide(energy: float, seed: Optional[int] = None) -> str

Sample which nuclide undergoes an interaction at a given energy.

Uses per-nuclide macroscopic total cross sections as weights.

Parameters:

Name Type Description Default
energy float

Neutron energy in eV.

required
seed Optional[int]

RNG seed for reproducibility.

None

Returns:

Name Type Description
str str

Selected nuclide name.

Source code in yamc/_core/__init__.pyi
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
def sample_interacting_nuclide(self, energy: builtins.float, seed: typing.Optional[builtins.int] = None) -> builtins.str:
    r"""
    Sample which nuclide undergoes an interaction at a given energy.

    Uses per-nuclide macroscopic total cross sections as weights.

    Args:
        energy (float): Neutron energy in eV.
        seed (Optional[int]): RNG seed for reproducibility.

    Returns:
        str: Selected nuclide name.
    """

macroscopic_cross_section

macroscopic_cross_section(reaction: int | str, temperature: Optional[str] = None) -> tuple[list[float], list[float]]

Calculate macroscopic cross section for a specific reaction.

This method accepts either an integer MT number or a string reaction name (like "(n,gamma)", "fission", etc.) and returns the macroscopic cross section for that reaction.

Parameters:

Name Type Description Default
reaction Union[int, str]

Either an MT number or reaction name.

required
temperature Optional[str]

Temperature key (e.g., "294"). If not provided, uses material.temperature, else the only available temperature if there is just one, else 294 K.

None

Returns:

Type Description
tuple[list[float], list[float]]

Tuple[List[float], List[float]]: (cross_section_values, energy_grid)

Source code in yamc/_core/__init__.pyi
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
def macroscopic_cross_section(self, reaction: builtins.int | builtins.str, temperature: typing.Optional[builtins.str] = None) -> tuple[builtins.list[builtins.float], builtins.list[builtins.float]]:
    r"""
    Calculate macroscopic cross section for a specific reaction.

    This method accepts either an integer MT number or a string reaction name
    (like "(n,gamma)", "fission", etc.) and returns the macroscopic cross section
    for that reaction.

    Args:
        reaction (Union[int, str]): Either an MT number or reaction name.
        temperature (Optional[str]): Temperature key (e.g., "294"). If not provided,
            uses material.temperature, else the only available temperature if
            there is just one, else 294 K.

    Returns:
        Tuple[List[float], List[float]]: (cross_section_values, energy_grid)
    """

transmute

transmute(schedule: Any, data_uncertainty: Optional[DataUncertainty] = None, self_shielding_chord: Optional[float] = None, self_shielding_shape: Optional[Any] = None, displacement_damage: bool = False, displacement_energies: Optional[Mapping[str, float]] = None, product_threshold: float = 1e-12) -> TransmutationResults

Transmute this material over an irradiation/cooling schedule, without re-running transport.

Each irradiation Pulse carries a NeutronSource whose energy is a Histogram (the multigroup spectrum); the pulse rate is the total flux magnitude [n/cm²/s]. The spectrum collapses cross sections into one-group reaction rates, scaled by rate. A Cooldown is a decay-only step. Different pulses may carry different spectra (e.g. a DD and a DT campaign).

Parameters:

Name Type Description Default
schedule PulseSchedule

The irradiation/cooling timeline. Every irradiation Pulse must carry a NeutronSource whose energy is a Histogram; its rate is the flux magnitude [n/cm²/s]. The source's position/direction are ignored (no transport runs). Use Cooldown for decay-only steps.

required

The transmutation network is assembled from the configured per-subsection sources (yamc.transmutation_decay_data / _reactions / _fission_yields); decay-only schedules need only the decay source. There is no default library: a source the schedule reads that is unset raises ValueError before any work, naming each such setting. _reactions and _fission_yields can be set to False instead, for a material with no reaction rates or one in which nothing fissions.

The material does not need transmutable=True. That flag exists so Model.simulate_transmutation can pick which materials in a geometry to deplete; here you have already named the one you mean.

The cross sections this needs are loaded into the material and kept, so calling it again on the same material does no file reading at all. Only the composition's and those of the products the schedule populates are loaded (see product_threshold), not every nuclide the chain can reach. The composition is not modified. A sweep over thousands of distinct compositions should call release_nuclear_data() on each material when it is done with it, since otherwise every one of them holds its nuclides' data for as long as it lives.

Returns:

Name Type Description
TransmutationResults TransmutationResults

The same object Model.simulate_transmutation returns, keyed by this material's id. get_material(id, step) takes step 0 as the initial composition and step i as the state after schedule step i - 1; get_reaction_rates(id, step) indexes the schedule steps directly, so its step 0 is the first step.

data_uncertainty (DataUncertainty, optional)

Ask for nuclear-data uncertainty on the result. Each source DataUncertainty names is sampled where it applies (statistical needs a transport run, flux_spectrum a supplied flux sigma), and the schedule is re-solved until every tracked standard deviation is known to DataUncertainty.convergence (5% by default). Omit it (the default) and nothing is read, folded or sampled: the inventories are bit-identical either way. Read the sigmas with get_nuclide_uncertainty, and what was and was not covered with get_data_uncertainty_info(id).

self_shielding_chord (float, optional)

Mean chord length 4V/S of this material's lump, in cm, which is twice the thickness for a thin slab and 4R/3 for a sphere. Given one, the flux inside each energy group is depressed where the total cross section is large, and the reaction rates come back shielded. Omit it (the default) and nothing is shielded: the rates are bit-identical to a run without it, and no shape is inferred from a geometry this material does not have. Read what was done with get_self_shielding_info(id).

The flux inside the lump comes from a slowing-down solve, which assumes nothing about resonances being narrow. The cheaper narrow-resonance approximation is deliberately not offered: it over-shields strong elastic scatterers badly enough to be worse than applying no correction at all (W186(n,gamma) in FNG-tung measures 1.29 b, where this gives C/E 0.80, no correction gives 0.86 and narrow resonance gives 0.46).

self_shielding_shape (SphereLump | CubeLump | FoilLump | CylinderLump | WireLump, optional)

The lump's form, from shapes, as an alternative to stating the chord yourself. The chord is 4V/S, so the shape decides how much surface a volume hides behind: SphereLump() and CubeLump() are fixed by Material(volume=...) and take no arguments, while FoilLump(thickness=), CylinderLump(radius=) and WireLump(radius=) carry the one dimension a volume cannot imply. Give this or self_shielding_chord, not both.

A sphere has the least surface for its volume, so it has the longest chord and shields more than any other shape of the same size. It is an upper bound rather than a safe default, which is why there is no default here at all.

displacement_damage bool

Also compute displacement damage over the schedule: the damage energy deposited per atom (eV) and NRT displacements per atom, per element and for the material, read with get_dpa, get_damage_energy and get_displacement_damage_info. Each nuclide's MT=444 damage-energy cross section is folded against the pulse spectrum by the same collapse as the reaction rates (self-shielding included), using each step's composition and flux; cooldowns add nothing. dpa is 0.8 * E_damage / (2 * E_d) per element, and the material total weights the elements by atom fraction. Off by default, and then MT=444 is not fetched and nothing about the solve changes. No uncertainty is given for it yet.

displacement_energies (dict[str, float], optional)

Displacement threshold energies E_d in eV by element symbol, e.g. {"Fe": 40.0}, replacing the defaults (ASTM E521, and the OECD-NEA 2015 report "Primary Radiation Damage in Materials" for elements it does not cover). An element of the material in neither source must be given here; it is never guessed. Needs displacement_damage=True.

product_threshold float

The atom fraction, or share of the activity, decay heat or decay photon power, a transmutation product must reach at some state of the schedule for its cross sections to be downloaded and its own neutron reactions solved. Default 1e-12. The schedule is solved with the composition's cross sections, every product crossing this is loaded, and the solve is repeated until nothing new crosses it, so a run fetches the few dozen nuclides an irradiation populates rather than the hundreds its chain can reach. A product below it is still produced, decays and is reported; only its reactions are dropped, which moves its own atom fraction and decay-quantity shares by less than the threshold and what it would have made by less than the summed peak fraction of the products left out. What was loaded and left out is in get_product_screening_info(id). 0 loads every product the solve populates, which is exact.

Raises:

Type Description
ValueError

If an irradiation pulse lacks a NeutronSource, its energy is not a Histogram, a transmutation source the schedule reads is unset, or on other invalid inputs.

Examples:

>>> spectrum = yamc.NeutronSource(energy=yamc.sources.Histogram("CCFE-709", flux_709))
>>> sched = yamc.PulseSchedule([
...     yamc.Pulse(rate=1e14, duration=(1, "h"), source=spectrum),
...     yamc.Cooldown(duration=(7, "d")),
... ])
>>> results = iron.transmute(schedule=sched)
>>> final = results.get_final_material(iron.id)
>>> # the isomeric split of the dominant channel, as two edges of one
>>> # reaction: the sum is sigma * phi * N and the ratio is f_m
>>> results.get_reaction_rates(iron.id, 0)["W186"]["(n,2n)"]
[('W185', 1.1e-08), ('W185_m1', 4.6e-07)]
Source code in yamc/_core/__init__.pyi
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
def transmute(self, schedule: typing.Any, data_uncertainty: typing.Optional[DataUncertainty] = None, self_shielding_chord: typing.Optional[builtins.float] = None, self_shielding_shape: typing.Optional[typing.Any] = None, displacement_damage: builtins.bool = False, displacement_energies: typing.Optional[typing.Mapping[builtins.str, builtins.float]] = None, product_threshold: builtins.float = 1e-12) -> TransmutationResults:
    r"""
    Transmute this material over an irradiation/cooling schedule, without
    re-running transport.

    Each irradiation ``Pulse`` carries a ``NeutronSource`` whose energy is a
    ``Histogram`` (the multigroup spectrum); the pulse ``rate`` is the total
    flux magnitude [n/cm²/s]. The spectrum collapses cross sections into
    one-group reaction rates, scaled by ``rate``. A ``Cooldown`` is a
    decay-only step. Different pulses may carry different spectra (e.g. a DD
    and a DT campaign).

    Args:
        schedule (PulseSchedule): The irradiation/cooling timeline. Every
            irradiation ``Pulse`` must carry a ``NeutronSource`` whose energy
            is a ``Histogram``; its ``rate`` is the flux magnitude [n/cm²/s].
            The source's position/direction are ignored (no transport runs).
            Use ``Cooldown`` for decay-only steps.

    The transmutation network is assembled from the configured per-subsection
    sources (``yamc.transmutation_decay_data`` / ``_reactions`` /
    ``_fission_yields``); decay-only schedules need only the decay source.
    There is no default library: a source the schedule reads that is unset
    raises ``ValueError`` before any work, naming each such setting.
    ``_reactions`` and ``_fission_yields`` can be set to ``False`` instead,
    for a material with no reaction rates or one in which nothing fissions.

    The material does **not** need ``transmutable=True``. That flag exists so
    ``Model.simulate_transmutation`` can pick which materials in a geometry to
    deplete; here you have already named the one you mean.

    The cross sections this needs are loaded **into the material** and kept,
    so calling it again on the same material does no file reading at all.
    Only the composition's and those of the products the schedule populates
    are loaded (see ``product_threshold``), not every nuclide the chain can
    reach. The composition is not modified. A sweep over thousands of
    *distinct* compositions should call ``release_nuclear_data()`` on each
    material when it is done with it, since otherwise every one of them
    holds its nuclides' data for as long as it lives.

    Returns:
        TransmutationResults: The same object ``Model.simulate_transmutation``
            returns, keyed by this material's ``id``.
            ``get_material(id, step)`` takes step 0 as the initial
            composition and step ``i`` as the state after schedule step
            ``i - 1``; ``get_reaction_rates(id, step)`` indexes the schedule
            steps directly, so its step 0 is the first step.

        data_uncertainty (DataUncertainty, optional): Ask for nuclear-data
            uncertainty on the result. Each source ``DataUncertainty`` names
            is sampled where it applies (``statistical`` needs a transport
            run, ``flux_spectrum`` a supplied flux sigma), and the schedule
            is re-solved until every tracked standard deviation is known to
            ``DataUncertainty.convergence`` (5% by default).
            Omit it (the default) and nothing is read, folded or sampled:
            the inventories are bit-identical either way. Read the sigmas
            with ``get_nuclide_uncertainty``, and what was and was not
            covered with ``get_data_uncertainty_info(id)``.

        self_shielding_chord (float, optional): Mean chord length ``4V/S`` of
            this material's lump, in cm, which is twice the thickness for a
            thin slab and ``4R/3`` for a sphere. Given one, the flux inside
            each energy group is depressed where the total cross section is
            large, and the reaction rates come back shielded. Omit it (the
            default) and nothing is shielded: the rates are bit-identical to
            a run without it, and no shape is inferred from a geometry this
            material does not have. Read what was done with
            ``get_self_shielding_info(id)``.

            The flux inside the lump comes from a slowing-down solve, which
            assumes nothing about resonances being narrow. The cheaper
            narrow-resonance approximation is deliberately not offered: it
            over-shields strong elastic scatterers badly enough to be worse
            than applying no correction at all (W186(n,gamma) in FNG-tung
            measures 1.29 b, where this gives C/E 0.80, no correction gives
            0.86 and narrow resonance gives 0.46).

        self_shielding_shape (SphereLump | CubeLump | FoilLump | CylinderLump | WireLump, optional):
            The lump's form, from ``shapes``, as an alternative to stating the
            chord yourself. The chord is ``4V/S``, so the shape decides how
            much surface a volume hides behind: ``SphereLump()`` and ``CubeLump()``
            are fixed by ``Material(volume=...)`` and take no arguments,
            while ``FoilLump(thickness=)``, ``CylinderLump(radius=)``
            and ``WireLump(radius=)`` carry the one dimension a volume cannot imply.
            Give this or ``self_shielding_chord``, not both.

            A sphere has the least surface for its volume, so it has the
            longest chord and shields more than any other shape of the same
            size. It is an upper bound rather than a safe default, which is
            why there is no default here at all.

        displacement_damage (bool): Also compute displacement damage over the
            schedule: the damage energy deposited per atom (eV) and NRT
            displacements per atom, per element and for the material, read
            with ``get_dpa``, ``get_damage_energy`` and
            ``get_displacement_damage_info``. Each nuclide's MT=444
            damage-energy cross section is folded against the pulse spectrum
            by the same collapse as the reaction rates (self-shielding
            included), using each step's composition and flux; cooldowns
            add nothing. dpa is ``0.8 * E_damage / (2 * E_d)`` per element,
            and the material total weights the elements by atom fraction.
            Off by default, and then MT=444 is not fetched and nothing about
            the solve changes. No uncertainty is given for it yet.

        displacement_energies (dict[str, float], optional): Displacement
            threshold energies ``E_d`` in eV by element symbol, e.g.
            ``{"Fe": 40.0}``, replacing the defaults (ASTM E521, and the
            OECD-NEA 2015 report "Primary Radiation Damage in Materials"
            for elements it does not cover). An element of the material in
            neither source must be given here; it is never guessed. Needs
            ``displacement_damage=True``.

        product_threshold (float): The atom fraction, or share of the
            activity, decay heat or decay photon power, a transmutation
            product must reach at some state of the schedule for its cross
            sections to be downloaded and its own neutron reactions solved.
            Default 1e-12. The schedule is solved with the composition's
            cross sections, every product crossing this is loaded, and the
            solve is repeated until nothing new crosses it, so a run fetches
            the few dozen nuclides an irradiation populates rather than the
            hundreds its chain can reach. A product below it is still
            produced, decays and is reported; only its reactions are
            dropped, which moves its own atom fraction and decay-quantity
            shares by less than the threshold and what it would have made
            by less than the summed peak fraction of the products left out.
            What was loaded and left out is in
            ``get_product_screening_info(id)``. 0 loads every product the
            solve populates, which is exact.

    Raises:
        ValueError: If an irradiation pulse lacks a NeutronSource, its energy
            is not a Histogram, a transmutation source the schedule reads is
            unset, or on other invalid inputs.

    Examples:
        >>> spectrum = yamc.NeutronSource(energy=yamc.sources.Histogram("CCFE-709", flux_709))
        >>> sched = yamc.PulseSchedule([
        ...     yamc.Pulse(rate=1e14, duration=(1, "h"), source=spectrum),
        ...     yamc.Cooldown(duration=(7, "d")),
        ... ])
        >>> results = iron.transmute(schedule=sched)
        >>> final = results.get_final_material(iron.id)
        >>> # the isomeric split of the dominant channel, as two edges of one
        >>> # reaction: the sum is sigma * phi * N and the ratio is f_m
        >>> results.get_reaction_rates(iron.id, 0)["W186"]["(n,2n)"]
        [('W185', 1.1e-08), ('W185_m1', 4.6e-07)]
    """

release_nuclear_data

release_nuclear_data() -> None

Drop the nuclear data this material has loaded.

transmute() loads the cross sections it needs into the material and leaves them there, so calling it again on the same material does no file reading at all. That is the composition and the products the irradiation populates, a few dozen nuclides for a pure metal and up to a couple of hundred for a steel, held for as long as the material is.

That is the right trade for a material you transmute more than once, and the wrong one for a sweep over thousands of distinct compositions -- so releasing is explicit rather than automatic. The material stays usable: the next call that needs the data loads it again.

Examples:

>>> for composition in many_compositions:
...     mat = yamc.Material(composition=composition, density=7.9)
...     results = mat.transmute(schedule=sched)
...     mat.release_nuclear_data()
Source code in yamc/_core/__init__.pyi
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
def release_nuclear_data(self) -> None:
    r"""
    Drop the nuclear data this material has loaded.

    ``transmute()`` loads the cross sections it needs into the material and
    leaves them there, so calling it again on the same material does no file
    reading at all. That is the composition and the products the
    irradiation populates, a few dozen nuclides for a pure metal and up to a
    couple of hundred for a steel, held for as long as the material is.

    That is the right trade for a material you transmute more than once, and
    the wrong one for a sweep over thousands of *distinct* compositions --
    so releasing is explicit rather than automatic. The material stays
    usable: the next call that needs the data loads it again.

    Examples:
        >>> for composition in many_compositions:
        ...     mat = yamc.Material(composition=composition, density=7.9)
        ...     results = mat.transmute(schedule=sched)
        ...     mat.release_nuclear_data()
    """

average_molar_mass

average_molar_mass() -> float

Return the average molar mass of this material (g/mol).

Source code in yamc/_core/__init__.pyi
2525
2526
2527
2528
def average_molar_mass(self) -> builtins.float:
    r"""
    Return the average molar mass of this material (g/mol).
    """

get_mass_density

get_mass_density() -> float

Return the mass density in g/cm³ regardless of stored units.

Source code in yamc/_core/__init__.pyi
2529
2530
2531
2532
def get_mass_density(self) -> builtins.float:
    r"""
    Return the mass density in g/cm³ regardless of stored units.
    """

mix_materials classmethod

mix_materials(materials: Sequence[Material], fractions: Sequence[float], fraction_type: str = 'atom', *, name: Optional[str] = None, id: Optional[int] = None) -> Material

Create a new material by mixing multiple materials.

Parameters:

Name Type Description Default
materials List[Material]

Materials to mix.

required
fractions List[float]

Mixing fractions (one per material).

required
fraction_type str

"atom", "mass", or "volume".

'atom'
name Optional[str]

Name for the new material. If omitted, one is built from the components' names and fractions, such as "steel(0.9000)_unnamed(0.1000)".

None
id Optional[int]

ID for the new material. Defaults to a fresh one, which no earlier material was given.

None

Returns:

Name Type Description
Material Material

A new material with the mixed composition and density.

Source code in yamc/_core/__init__.pyi
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
@classmethod
def mix_materials(cls, materials: typing.Sequence[Material], fractions: typing.Sequence[builtins.float], fraction_type: builtins.str = 'atom', *, name: typing.Optional[builtins.str] = None, id: typing.Optional[builtins.int] = None) -> Material:
    r"""
    Create a new material by mixing multiple materials.

    Args:
        materials (List[Material]): Materials to mix.
        fractions (List[float]): Mixing fractions (one per material).
        fraction_type (str): "atom", "mass", or "volume".
        name (Optional[str]): Name for the new material. If omitted, one
            is built from the components' names and fractions, such as
            ``"steel(0.9000)_unnamed(0.1000)"``.
        id (Optional[int]): ID for the new material. Defaults to a fresh
            one, which no earlier material was given.

    Returns:
        Material: A new material with the mixed composition and density.
    """

MeshGeometry

Mesh-based geometry loaded from a mesh file.

The mesh format is the YAMC Arrow IPC mesh (.arrow), as produced by cad_to_yamc. Other meshers are supported by writing that format.

Each volume in the mesh is named by a mat:<name> physical group. The materials dictionary maps the bare <name> (as listed by :attr:volume_names, e.g. {"first_wall": steel}) to a :class:Material. A key that matches no volume raises ValueError with a close match when one exists; volumes with no key are void.

Volumes given the same :class:Material object share it, as CSG cells sharing a material do: its cross sections are held once, so memory follows the number of materials rather than the number of volumes. In a transmutation it is one material, depleted with the flux averaged over all the volumes of the mesh it fills (its volume is set to their total). Give volumes that should deplete separately a :class:Material each.

Outer boundary surfaces should be tagged with a physical group named boundary:vacuum (reflecting boundaries are not yet supported for mesh geometry).

The implicit complement (unmeshed space between volumes) is void by default -- particles free-stream through it with no collisions. To model air or coolant interactions in the gaps, pass a :class:Material as implicit_complement_material.

A vacuum boundary box can be added by setting graveyard_offset. This adds an axis-aligned bounding box expanded by the given offset (cm) around the geometry, with vacuum boundary conditions on all 6 faces. Particles reaching this boundary are killed.

When this geometry is the whole model and the mesh has no vacuum boundary (no graveyard_offset and no boundary:vacuum group, as is usual for a mesh made from CAD), the :class:Model closes it before transport:

  • with a void implicit complement it adds a vacuum box 10 cm outside the mesh's bounding box and prints its extent. In a void the margin changes no result; set graveyard_offset to choose it.
  • with an implicit_complement_material it raises ValueError: the box position sets how much of that material surrounds the model, so graveyard_offset must be given explicitly.

Used as the fill of a CSG cell, the mesh gets no box: the CSG geometry bounds it. Without any of these, a particle with no surface ahead of it is a lost particle.

A mesh made without imprinting (from_cadquery(..., imprint=False)) gives each solid its own surface, so touching solids meet along two independently faceted surfaces that may overlap or leave thin gaps. Such a mesh is tracked discontinuously: a particle leaving a solid is placed in whichever touching solid contains it. Solids closer than the contact tolerance count as touching, so an overlap or a gap thinner than it is crossed straight into the next solid (an overlap stays with the solid the particle was already in); a wider gap, or one the file records as being in the CAD, is the implicit complement. The file records all this; contact_tolerance forces it on for a mesh from another writer, or overrides the tolerance the file records.

Loading warns when a mesh tracked conformally has solids that touch without sharing a surface where they meet: a particle leaving one of them is not placed in the solid it enters.

Made by :meth:from_cadquery or :meth:from_tets, or loaded with :meth:from_arrow, whose arguments these are.

Parameters:

Name Type Description Default
source

Path to an Arrow IPC mesh file (.arrow), or the file's bytes, as :meth:to_arrow returns them with no path.

required
materials

Mapping of volume name (no mat: prefix) to :class:Material.

required
implicit_complement_material

Optional material for the unmeshed space between volumes. Default None means void (free-streaming).

required
graveyard_offset

Optional offset (cm) of a vacuum boundary box around the mesh. None lets the :class:Model add one with a 10 cm offset around a void implicit complement, as above.

required
contact_tolerance

Optional distance (cm) within which two solids' surfaces count as touching. Setting it tracks the mesh discontinuously. It must be at least the deepest overlap between touching solids, and gaps narrower than it are filled by the solid on the far side, except between solids the file records as apart in the CAD (from_cadquery checks this when meshing without imprinting).

required

Raises:

Type Description
ValueError

If the file is not an Arrow IPC mesh, or if it contains a negatively oriented tetrahedron. Transport reads outward tet face normals off a fixed vertex ordering, so an inverted tet is rejected rather than silently re-wound; regenerate the mesh with a writer that emits positively oriented tets.

Examples:

>>> fuel = yamc.Material(composition={"Li6": 1.0}, density=0.534, name="fuel")
>>> fuel.read_nuclear_data({"Li6": "tests/Li6.arrow"})
>>>
>>> mesh_geom = yamc.MeshGeometry.from_arrow("model.arrow", {"fuel": fuel},
...                               graveyard_offset=5.0)
>>> model = yamc.Model(geometry=mesh_geom, source=source)

discontinuous property

discontinuous: bool

True when the mesh is tracked discontinuously: a particle leaving a solid through a surface it does not share is placed in whichever touching solid contains it, rather than read off the surface. So is a mesh whose solids were meshed one by one without imprinting, and an imprinted one in which some solids touch without sharing a surface; shared surfaces still hand over by topology.

contact_tolerance property

contact_tolerance: Optional[float]

Distance (cm) within which two solids' surfaces count as touching, for a discontinuously tracked mesh; None for one tracked conformally.

num_volumes property

num_volumes: int

Number of volumes (cells) in the mesh (excluding implicit complement).

volume_names property

volume_names: list[Optional[str]]

Material names for each volume, in volume-ID order.

These are the names from mat:<name> physical groups. Pass any of these strings as the second element of a tally's mesh=(geometry, name) argument to bin on that volume by name (an integer volume ID is also accepted).

vertices property

vertices: list[list[float]]

All vertex coordinates as a list of [x, y, z] triples.

triangles property

triangles: list[list[int]]

All triangle connectivity as a list of [v0, v1, v2] triples (vertex indices).

tetrahedra property

tetrahedra: list[list[int]]

All tet connectivity as a list of [v0, v1, v2, v3] vertex indices, in the order Model.set_tet_density_factors takes its factors.

tet_volume_ids property

tet_volume_ids: list[Optional[int]]

The volume ID of each tet, parallel to tetrahedra (None for a tet in no volume). Index volume_names with it to find each tet's material name, e.g. to give density factors to one material's tets only.

tet_volume_names property

tet_volume_names: list[Optional[str]]

The volume name of each tet, parallel to tetrahedra: the material tag given to from_cadquery, or None for a tet in no named volume. numpy.array(geometry.tet_volume_names) == "breeder" picks out one material's tets.

tet_volumes property

tet_volumes: list[float]

The volume of each tet in cm³, parallel to tetrahedra. A tet-mesh tally scores the integral over each tet, so dividing by these gives the per-cm³ density.

tet_density_factors property writable

tet_density_factors: Optional[list[float]]

The density of each tet relative to its material's, parallel to tetrahedra, or None (every factor 1).

A field from a thermal or CFD solve on the same tets, for instance. Inside a tet every macroscopic cross section is f * Σ_material, so it needs no extra nuclear data, and heating and reaction-rate scores follow the scaled density. A :class:Model built from this geometry starts from these factors, the way it starts from copies of its materials; change them between runs with Model.set_tet_density_factors, as Model.set_material_density does for a material. Needs tracking_mode="hybrid" (or "woodcock"). Not saved by :meth:to_arrow.

Set it to one non-negative factor per tet (a list, a numpy array or any iterable of numbers), or to None to clear it.

mesh_report property

mesh_report: dict[str, Any] | None

What the mesher reported when it made this mesh, as a dict, or None for a mesh loaded from a file. "conform" holds what making the tets conformal repaired (edges_split, cones, surface_triangles_refined, conflicts, skipped_solids, reverted), "overlaps" the solid pairs whose overlap was resolved, and "face_volumes" what keeping the faceted volumes equal to the CAD's did.

num_triangles property

num_triangles: int

Number of triangles in the entire mesh.

volume_measures property

volume_measures: list[float]

Analytical volume of each mesh volume (cm³), computed via the divergence theorem over the bounding surface triangles.

graveyard_offset property writable

graveyard_offset: Optional[float]

The vacuum boundary (graveyard) offset in cm.

Setting this property triggers a full rebuild (re-reads stored mesh data, adds the vacuum boundary box, and rebuilds the BVH). Set to None to remove the boundary.

from_cadquery classmethod

from_cadquery(assembly: Any, materials: dict, *, material_tags: list[str] | str | None = None, tet_volumes: Optional[Sequence[str]] = None, target_edge_length: Optional[float] = None, implicit_complement_material: Optional[Material] = None, graveyard_offset: Optional[float] = None, boundary_tags: dict[str, list[int] | str] | None = None, **mesh_options: Any) -> MeshGeometry

Mesh a CadQuery assembly and return it as a geometry, ready for transport. No file is written; save it with :meth:to_arrow if wanted.

Needs the cad extra (pip install "yamc[cad]").

Parameters:

Name Type Description Default
assembly Assembly

The CAD, with named parts.

required
materials dict[str, Material]

Material of each volume, keyed by part name (or by the tag material_tags gives it). A part left out is void.

required
material_tags list[str] | str

How each solid is tagged: "assembly_names" (default) uses each part's name, "assembly_materials" its cq.Material name, or a list gives one tag per solid.

None
tet_volumes list[str] | None

Volumes to fill with tetrahedra, by tag; the rest are surface meshes only.

None
target_edge_length float | None

Target tet edge length (cm), needed with tet_volumes.

None
implicit_complement_material Material | None

As for :meth:from_arrow.

None
graveyard_offset float | None

As for :meth:from_arrow.

None
boundary_tags dict[str, list[int] | str] | None

Boundary conditions by name, such as "vacuum", each to the 1-based surface ids it applies to, or to "exterior" for the model's outer shell (:meth:exterior_surface_ids). With a vacuum boundary on the exterior no graveyard is needed.

None
tolerance float | dict

Chordal deflection of the surface mesh (cm), for every solid or a dict by material tag or 1-based solid id; smaller makes more triangles on curved surfaces. A surface two solids share takes the finer of their values, and curved surfaces are moved off the CAD so each solid's mesh encloses its CAD volume. Default 0.5.

required
angular_tolerance float | dict

Angular deflection (radians), as tolerance. Default 0.2.

required
fidelity_check bool

Refuse (MeshFidelityError) a mesh whose face areas or volumes are far from the CAD's, or whose surfaces are open or cross themselves. Default True.

required
imprint bool

Imprint the assembly first, so touching solids share a surface (a conformal mesh). False meshes each solid on its own, faster on a large assembly, and the mesh is tracked discontinuously. Default True.

required
contact_tolerance float | None

With imprint=False, the distance (cm) within which solids count as touching. Defaults to twice the largest deflection.

required
overlaps str

Solids that overlap deeper than their facetings explain: "error" (default) raises OverlappingSolidsError, "smaller_wins" (with imprint=False) gives each overlap to the smaller solid, "ignore" skips the check.

required
imprint_threads int | all

Threads for imprinting. Default all.

required
mesh_threads int | all

Threads for meshing surfaces and tets. Default all; the mesh is the same on any number.

required

Examples:

>>> geometry = yamc.MeshGeometry.from_cadquery(
...     assembly,
...     materials={"breeder": breeder, "structure": steel},
...     tet_volumes=["breeder", "structure"],
...     target_edge_length=2.5,
... )
Source code in yamc/_core/__init__.pyi
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
@classmethod
def from_cadquery(cls, assembly: typing.Any, materials: dict, *, material_tags: list[str] | str | None = None, tet_volumes: typing.Optional[typing.Sequence[builtins.str]] = None, target_edge_length: typing.Optional[builtins.float] = None, implicit_complement_material: typing.Optional[Material] = None, graveyard_offset: typing.Optional[builtins.float] = None, boundary_tags: dict[str, list[int] | str] | None = None, **mesh_options: typing.Any) -> MeshGeometry:
    r"""
    Mesh a CadQuery assembly and return it as a geometry, ready for
    transport. No file is written; save it with :meth:`to_arrow` if wanted.

    Needs the ``cad`` extra (``pip install "yamc[cad]"``).

    Args:
        assembly (cadquery.Assembly): The CAD, with named parts.
        materials (dict[str, Material]): Material of each volume, keyed by
            part name (or by the tag *material_tags* gives it). A part left
            out is void.
        material_tags (list[str] | str): How each solid is tagged:
            ``"assembly_names"`` (default) uses each part's name,
            ``"assembly_materials"`` its ``cq.Material`` name, or a list
            gives one tag per solid.
        tet_volumes (list[str] | None): Volumes to fill with tetrahedra,
            by tag; the rest are surface meshes only.
        target_edge_length (float | None): Target tet edge length (cm),
            needed with *tet_volumes*.
        implicit_complement_material (Material | None): As for
            :meth:`from_arrow`.
        graveyard_offset (float | None): As for :meth:`from_arrow`.
        boundary_tags (dict[str, list[int] | str] | None): Boundary
            conditions by name, such as ``"vacuum"``, each to the 1-based
            surface ids it applies to, or to ``"exterior"`` for the model's
            outer shell (:meth:`exterior_surface_ids`). With a vacuum
            boundary on the exterior no graveyard is needed.
        tolerance (float | dict): Chordal deflection of the surface mesh
            (cm), for every solid or a dict by material tag or 1-based
            solid id; smaller makes more triangles on curved surfaces.
            A surface two solids share takes the finer of their values,
            and curved surfaces are moved off the CAD so each solid's mesh
            encloses its CAD volume. Default 0.5.
        angular_tolerance (float | dict): Angular deflection (radians), as
            *tolerance*. Default 0.2.
        fidelity_check (bool): Refuse (``MeshFidelityError``) a mesh whose
            face areas or volumes are far from the CAD's, or whose surfaces
            are open or cross themselves. Default True.
        imprint (bool): Imprint the assembly first, so touching solids
            share a surface (a conformal mesh). ``False`` meshes each solid
            on its own, faster on a large assembly, and the mesh is tracked
            discontinuously. Default True.
        contact_tolerance (float | None): With ``imprint=False``, the
            distance (cm) within which solids count as touching. Defaults
            to twice the largest deflection.
        overlaps (str): Solids that overlap deeper than their facetings
            explain: ``"error"`` (default) raises
            ``OverlappingSolidsError``, ``"smaller_wins"`` (with
            ``imprint=False``) gives each overlap to the smaller solid,
            ``"ignore"`` skips the check.
        imprint_threads (int | "all"): Threads for imprinting. Default all.
        mesh_threads (int | "all"): Threads for meshing surfaces and tets.
            Default all; the mesh is the same on any number.

    Examples:
        >>> geometry = yamc.MeshGeometry.from_cadquery(
        ...     assembly,
        ...     materials={"breeder": breeder, "structure": steel},
        ...     tet_volumes=["breeder", "structure"],
        ...     target_edge_length=2.5,
        ... )
    """

from_tets classmethod

from_tets(vertices: Sequence[Sequence[float]], tets: Sequence[Sequence[int]], tet_materials: Sequence[str], materials: dict, implicit_complement_material: Optional[Material] = None, graveyard_offset: Optional[float] = None) -> MeshGeometry

A geometry from another code's tet mesh, such as FEniCSx's or gmsh's: every volume is tet-filled.

The volumes are the distinct names in tet_materials, in order of first appearance. Their boundary surfaces are built from the tet faces where the name changes, and from the mesh's outer faces, so they are conformal with the tets by construction: a field on the tets (a temperature, a density) needs no mapping between the two codes. Negatively wound tets are re-wound.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

[x, y, z] per vertex (cm).

required
tets Sequence[Sequence[int]]

Four vertex indices per tet. The order is kept, so tetrahedra[i] is tet i given.

required
tet_materials Sequence[str]

The volume name of each tet.

required
materials dict[str, Material]

Material of each volume, by name. A name left out is void.

required
implicit_complement_material Optional[Material]

As for :meth:from_arrow.

None
graveyard_offset Optional[float]

As for :meth:from_arrow.

None

Raises:

Type Description
ValueError

For a tet with no volume, a vertex index out of range, or a face shared by more than two tets.

Examples:

>>> geometry = yamc.MeshGeometry.from_tets(
...     vertices, tets, ["breeder"] * n_breeder + ["steel"] * n_steel,
...     {"breeder": breeder, "steel": steel},
... )
Source code in yamc/_core/__init__.pyi
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
@classmethod
def from_tets(cls, vertices: typing.Sequence[typing.Sequence[builtins.float]], tets: typing.Sequence[typing.Sequence[builtins.int]], tet_materials: typing.Sequence[builtins.str], materials: dict, implicit_complement_material: typing.Optional[Material] = None, graveyard_offset: typing.Optional[builtins.float] = None) -> MeshGeometry:
    r"""
    A geometry from another code's tet mesh, such as FEniCSx's or
    gmsh's: every volume is tet-filled.

    The volumes are the distinct names in *tet_materials*, in order of
    first appearance. Their boundary surfaces are built from the tet faces
    where the name changes, and from the mesh's outer faces, so they are
    conformal with the tets by construction: a field on the tets (a
    temperature, a density) needs no mapping between the two codes.
    Negatively wound tets are re-wound.

    Args:
        vertices (Sequence[Sequence[float]]): ``[x, y, z]`` per vertex (cm).
        tets (Sequence[Sequence[int]]): Four vertex indices per tet. The
            order is kept, so ``tetrahedra[i]`` is tet ``i`` given.
        tet_materials (Sequence[str]): The volume name of each tet.
        materials (dict[str, Material]): Material of each volume, by name.
            A name left out is void.
        implicit_complement_material: As for :meth:`from_arrow`.
        graveyard_offset: As for :meth:`from_arrow`.

    Raises:
        ValueError: For a tet with no volume, a vertex index out of
            range, or a face shared by more than two tets.

    Examples:
        >>> geometry = yamc.MeshGeometry.from_tets(
        ...     vertices, tets, ["breeder"] * n_breeder + ["steel"] * n_steel,
        ...     {"breeder": breeder, "steel": steel},
        ... )
    """

from_arrow classmethod

from_arrow(source: str | PathLike[str] | bytes, materials: dict, implicit_complement_material: Optional[Material] = None, graveyard_offset: Optional[float] = None, contact_tolerance: Optional[float] = None) -> MeshGeometry

Load a mesh that to_arrow saved.

Parameters:

Name Type Description Default
source str | PathLike | bytes

A file path, or the bytes to_arrow() returned.

required
materials dict

Mapping of volume name to :class:Material.

required
implicit_complement_material Optional[Material]

See the class docstring.

None
graveyard_offset Optional[float]

See the class docstring.

None
contact_tolerance Optional[float]

See the class docstring.

None
Source code in yamc/_core/__init__.pyi
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
@classmethod
def from_arrow(cls, source: str | os.PathLike[str] | bytes, materials: dict, implicit_complement_material: typing.Optional[Material] = None, graveyard_offset: typing.Optional[builtins.float] = None, contact_tolerance: typing.Optional[builtins.float] = None) -> MeshGeometry:
    r"""
    Load a mesh that ``to_arrow`` saved.

    Args:
        source (str | os.PathLike | bytes): A file path, or the bytes
            ``to_arrow()`` returned.
        materials: Mapping of volume name to :class:`Material`.
        implicit_complement_material: See the class docstring.
        graveyard_offset: See the class docstring.
        contact_tolerance: See the class docstring.
    """

to_arrow

to_arrow(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save the mesh to an Arrow IPC file at path, or return the file's bytes when path is None. Materials are not saved: give them again to from_arrow. The graveyard is not saved either, as it is added when the mesh is loaded.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The file's bytes when path is None.

Source code in yamc/_core/__init__.pyi
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
def to_arrow(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save the mesh to an Arrow IPC file at ``path``, or return the file's
    bytes when ``path`` is None. Materials are not saved: give them again
    to ``from_arrow``. The graveyard is not saved either, as it is added
    when the mesh is loaded.

    Args:
        path (str | os.PathLike | None): Where to write.

    Returns:
        bytes | None: The file's bytes when ``path`` is None.
    """

exterior_surface_ids

exterior_surface_ids() -> list[int]

Surface ids (1-based, as the mesh file numbers them) on the model's outer shell: surfaces with a volume on one side and the implicit complement on the other. The surfaces between two volumes, and the graveyard box added on load, are left out. These are the surfaces a standalone mesh wants a vacuum boundary on, as boundary_tags={"vacuum": geometry.exterior_surface_ids()} to from_cadquery does with "exterior".

Raises:

Type Description
ValueError

For a mesh tracked discontinuously (made without imprinting). Every surface of such a mesh belongs to one volume, including where volumes touch, so tagging them vacuum would kill particles inside the model.

Source code in yamc/_core/__init__.pyi
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
def exterior_surface_ids(self) -> builtins.list[builtins.int]:
    r"""
    Surface ids (1-based, as the mesh file numbers them) on the model's
    outer shell: surfaces with a volume on one side and the implicit
    complement on the other. The surfaces between two volumes, and the
    graveyard box added on load, are left out. These are the surfaces a
    standalone mesh wants a vacuum boundary on, as
    ``boundary_tags={"vacuum": geometry.exterior_surface_ids()}`` to
    ``from_cadquery`` does with ``"exterior"``.

    Raises:
        ValueError: For a mesh tracked discontinuously (made without
            imprinting). Every surface of such a mesh belongs to one
            volume, including where volumes touch, so tagging them vacuum
            would kill particles inside the model.
    """

calculate_volume

calculate_volume(samples: int = 0, bounding_box: Optional[BoundingBox] = None, seed: Optional[int] = None) -> dict[int, VolumeResult]

Compute the volume of every mesh volume.

Mesh geometries already know their volumes analytically (via the divergence theorem applied to their bounding triangles when the mesh is loaded), so this method is exact: std_dev is always 0 and no stochastic sampling is performed. The signature matches :meth:Geometry.calculate_volume so the same call works on both CSG and mesh geometries.

Parameters:

Name Type Description Default
samples int

Ignored (kept for signature compatibility).

0
bounding_box Optional[BoundingBox]

Ignored (kept for signature compatibility).

None
seed Optional[int]

Ignored (kept for signature compatibility).

None

Returns:

Type Description
dict[int, VolumeResult]

dict[int, VolumeResult]: Mapping volume_id -> VolumeResult.

Source code in yamc/_core/__init__.pyi
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
def calculate_volume(self, samples: builtins.int = 0, bounding_box: typing.Optional[BoundingBox] = None, seed: typing.Optional[builtins.int] = None) -> builtins.dict[builtins.int, VolumeResult]:
    r"""
    Compute the volume of every mesh volume.

    Mesh geometries already know their volumes analytically (via the
    divergence theorem applied to their bounding triangles when the
    mesh is loaded), so this method is exact: ``std_dev`` is always 0
    and no stochastic sampling is performed. The signature matches
    :meth:`Geometry.calculate_volume` so the same call works on both
    CSG and mesh geometries.

    Args:
        samples: Ignored (kept for signature compatibility).
        bounding_box: Ignored (kept for signature compatibility).
        seed: Ignored (kept for signature compatibility).

    Returns:
        dict[int, VolumeResult]: Mapping volume_id -> VolumeResult.
    """

volume_triangle_indices

volume_triangle_indices(volume_id: int) -> list[int]

Triangle indices belonging to a specific volume.

Returns the global triangle indices for every surface of the given volume: those bounding it, and any internal face (a surface with the volume on both sides, which bounds nothing). These can be used to index into :attr:triangles.

Parameters:

Name Type Description Default
volume_id int

Volume index (0-based).

required

Returns:

Type Description
list[int]

list[int]: Triangle indices for that volume.

Source code in yamc/_core/__init__.pyi
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
def volume_triangle_indices(self, volume_id: builtins.int) -> builtins.list[builtins.int]:
    r"""
    Triangle indices belonging to a specific volume.

    Returns the global triangle indices for every surface of the given
    volume: those bounding it, and any internal face (a surface with the
    volume on both sides, which bounds nothing).  These can be used to
    index into :attr:`triangles`.

    Args:
        volume_id (int): Volume index (0-based).

    Returns:
        list[int]: Triangle indices for that volume.
    """

bounding_box

bounding_box() -> BoundingBox

Bounding box of the entire mesh geometry.

Returns:

Name Type Description
BoundingBox BoundingBox

Axis-aligned bounding box enclosing all mesh volumes.

Source code in yamc/_core/__init__.pyi
2953
2954
2955
2956
2957
2958
2959
def bounding_box(self) -> BoundingBox:
    r"""
    Bounding box of the entire mesh geometry.

    Returns:
        BoundingBox: Axis-aligned bounding box enclosing all mesh volumes.
    """

bounding_box_for_material

bounding_box_for_material(material: Material) -> BoundingBox

Bounding box of volumes matching a specific material.

Parameters:

Name Type Description Default
material Material

A :class:Material, matched to volumes by its id.

required

Returns:

Name Type Description
BoundingBox BoundingBox

Axis-aligned bounding box enclosing only the volumes that use the given material.

Raises:

Type Description
ValueError

If no volumes match.

Source code in yamc/_core/__init__.pyi
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
def bounding_box_for_material(self, material: Material) -> BoundingBox:
    r"""
    Bounding box of volumes matching a specific material.

    Args:
        material: A :class:`Material`, matched to volumes by its ``id``.

    Returns:
        BoundingBox: Axis-aligned bounding box enclosing only the volumes
            that use the given material.

    Raises:
        ValueError: If no volumes match.
    """

add_tets

add_tets(volumes: Optional[Sequence[str]] = None, target_edge_length: float | dict[str, float] | None = None, *, mesh_threads: int | Literal['all'] = 'all') -> MeshGeometry

A copy of this geometry with the named volumes filled with tetrahedra, conformal with the surface and with each other. The geometry itself is unchanged.

Source code in yamc/_core/__init__.pyi
2975
2976
def add_tets(self, volumes: typing.Optional[typing.Sequence[builtins.str]] = None, target_edge_length: builtins.float | dict[builtins.str, builtins.float] | None = None, *, mesh_threads: builtins.int | typing.Literal["all"] = "all") -> MeshGeometry:
    r"""A copy of this geometry with the named volumes filled with tetrahedra, conformal with the surface and with each other. The geometry itself is unchanged."""

to_vtkhdf

to_vtkhdf(path: str | PathLike[str]) -> None

Write the mesh's triangles and tets, with each cell's volume_id and material_id, to a VTKHDF UnstructuredGrid file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
2977
2978
def to_vtkhdf(self, path: builtins.str | os.PathLike[builtins.str]) -> None:
    r"""Write the mesh's triangles and tets, with each cell's volume_id and material_id, to a VTKHDF UnstructuredGrid file for ParaView. Requires h5py (pip install yamc[viz])."""

plot

plot(*args: Any, **kwargs: Any) -> InteractivePlot

Render an interactive plot of this mesh geometry. See the docs for keyword arguments.

Source code in yamc/_core/__init__.pyi
2979
2980
def plot(self, *args: typing.Any, **kwargs: typing.Any) -> InteractivePlot:
    r"""Render an interactive plot of this mesh geometry. See the docs for keyword arguments."""

MeshSliceData

Rich return type for Tally.extract_mesh_slice().

Behaves like a 2D list of floats for backward compatibility (np.array(tally.extract_mesh_slice(...)) still works), while also exposing coordinate metadata for matplotlib plotting.

ModelTransmutationResults

Bases: TransmutationResults

The results of Model.simulate_transmutation: everything TransmutationResults holds, plus the model's own tallies (Model(tallies=[...])) from each step's transport, so anything that changes as the materials burn (TBR as Li6 depletes, heating, flux, spectra, mesh tallies) is read off the one run.

Every step holds the whole TransportResults of that step's transport, so a large mesh tally costs its size once per transport step (once in all for method="independent").

tally_results

tally_results(step: int) -> Optional[TransportResults]

The model's tallies from step step's transport, or None for a decay-only step (a Cooldown, or a Pulse with rate 0), where no transport runs, and for a model with no tallies.

step indexes timesteps, as get_source_rates and get_reaction_rates do: step i is the transport that drove the step from composition i (get_material(id, i)) to composition i + 1. Each step's tallies are reset before its transport, so they reflect that step's compositions only.

The step's source rate is already applied (with_source_strength, per second), so a heating tally converts straight to W with .to("W"). The transmutation's internal tallies and its scouting transport are not among them.

With method="independent" transport runs once, on the initial compositions, and every irradiation step returns that one run's results: they do not follow the burnup.

Parameters:

Name Type Description Default
step int

The schedule step, 0 <= step < len(timesteps).

required

Examples:

>>> for step, t in enumerate(results.timesteps):
...     step_results = results.tally_results(step)
...     if step_results is not None:
...         print(t, step_results[tbr].mean)
Source code in yamc/_core/__init__.pyi
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
def tally_results(self, step: builtins.int) -> typing.Optional[TransportResults]:
    r"""
    The model's tallies from step ``step``'s transport, or ``None`` for a
    decay-only step (a ``Cooldown``, or a ``Pulse`` with rate 0), where no
    transport runs, and for a model with no tallies.

    ``step`` indexes ``timesteps``, as ``get_source_rates`` and
    ``get_reaction_rates`` do: step ``i`` is the transport that drove the
    step from composition ``i`` (``get_material(id, i)``) to composition
    ``i + 1``. Each step's tallies are reset before its transport, so they
    reflect that step's compositions only.

    The step's source rate is already applied (``with_source_strength``,
    per second), so a heating tally converts straight to W with
    ``.to("W")``. The transmutation's internal tallies and its scouting
    transport are not among them.

    With ``method="independent"`` transport runs once, on the initial
    compositions, and every irradiation step returns that one run's
    results: they do not follow the burnup.

    Args:
        step: The schedule step, ``0 <= step < len(timesteps)``.

    Examples:
        >>> for step, t in enumerate(results.timesteps):
        ...     step_results = results.tally_results(step)
        ...     if step_results is not None:
        ...         print(t, step_results[tbr].mean)
    """

tally_evolution

tally_evolution(tally: Tally) -> tuple[list[list[float]], list[list[float]]]

tally's per-bin means and standard deviations over the steps that ran transport, in step order: (means, standard_deviations), each a list with one flat list of bins per transport step, each with its step's source rate applied. TBR against irradiation time is one call. See tally_results for what each step holds.

Parameters:

Name Type Description Default
tally Tally

One of the model's tallies.

required

Examples:

>>> means, std_devs = results.tally_evolution(tbr)
Source code in yamc/_core/__init__.pyi
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
def tally_evolution(self, tally: Tally) -> tuple[builtins.list[builtins.list[builtins.float]], builtins.list[builtins.list[builtins.float]]]:
    r"""
    ``tally``'s per-bin means and standard deviations over the steps that
    ran transport, in step order: ``(means, standard_deviations)``, each a
    list with one flat list of bins per transport step, each with its
    step's source rate applied. TBR against irradiation time is one call.
    See ``tally_results`` for what each step holds.

    Args:
        tally: One of the model's tallies.

    Examples:
        >>> means, std_devs = results.tally_evolution(tbr)
    """

Nuclide

Nuclide(name: Optional[str] = None)

Nuclide data container exposed to Python.

Create a new (optionally named) nuclide instance.

Parameters:

Name Type Description Default
name Optional[str]

Optional nuclide identifier (e.g. "Li6", "Fe56"). If not supplied you must pass path to load later.

None
Notes

Individual fields (e.g. name, atomic_number, available_temperatures, loaded_temperatures) are exposed as read-only attributes via PyO3 getters. Detailed descriptions appear once each in the generated documentation--this summary omits a full per-attribute list to avoid duplication.

Create a new (optionally named) nuclide.

Parameters:

Name Type Description Default
name Optional[str]

Optional nuclide identifier (e.g. "Li6", "Fe56"). If not supplied you must pass path to load later.

None

Returns:

Name Type Description
Nuclide Nuclide

A nuclide object with no data loaded yet.

Source code in yamc/_core/__init__.pyi
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
def __new__(cls, name: typing.Optional[builtins.str] = None) -> Nuclide:
    r"""
    Create a new (optionally named) nuclide.

    Args:
        name (Optional[str]): Optional nuclide identifier (e.g. "Li6", "Fe56"). If not
            supplied you must pass `path` to `load` later.

    Returns:
        Nuclide: A nuclide object with no data loaded yet.
    """

name property

name: Optional[str]

Name / identifier for the nuclide (e.g. "Li6", "Fe56").

Returns:

Type Description
Optional[str]

Optional[str]: Nuclide name or None if not yet set.

element property

element: Optional[str]

Chemical element symbol (e.g. "Fe").

Returns:

Type Description
Optional[str]

Optional[str]: Element symbol or None if data not loaded.

atomic_symbol property

atomic_symbol: Optional[str]

Atomic symbol (currently same as element symbol).

Returns:

Type Description
Optional[str]

Optional[str]: Atomic symbol string.

atomic_number property

atomic_number: Optional[int]

Proton number Z.

Returns:

Type Description
Optional[int]

Optional[int]: Atomic number.

neutron_number property

neutron_number: Optional[int]

Neutron number N.

Returns:

Type Description
Optional[int]

Optional[int]: Neutron count.

mass_number property

mass_number: Optional[int]

Mass number A = Z + N.

Returns:

Type Description
Optional[int]

Optional[int]: Mass number.

atomic_weight_ratio property

atomic_weight_ratio: Optional[float]

Atomic weight ratio (target mass / neutron mass) from nuclear data file.

Returns:

Type Description
Optional[float]

Optional[float]: Atomic weight ratio.

library property

library: Optional[str]

Originating nuclear data library identifier.

Returns:

Type Description
Optional[str]

Optional[str]: Library name/code.

fissionable property

fissionable: bool

Whether the nuclide is fissionable.

Returns:

Name Type Description
bool bool

True if fissionable.

available_temperatures property

available_temperatures: list[str]

All temperatures present in the source data file.

Returns:

Type Description
list[str]

List[str]: Temperature labels in Kelvin (e.g. ["293"]).

loaded_temperatures property

loaded_temperatures: list[str]

Temperatures actually loaded into memory (subset of available_temperatures).

Returns:

Type Description
list[str]

List[str]: Loaded temperatures.

data_path property

data_path: Optional[str]

Path to the data file used to populate this nuclide (if known).

Returns:

Type Description
Optional[str]

Optional[str]: Filesystem path or None.

reactions property

reactions: Any

Mapping of temperature -> MT number -> reaction data.

Returns:

Type Description
Any

Dict[str, Dict[int, Dict[str, Any]]]: Nested dictionary. The innermost

Any

dictionary has these keys:

  • cross_section (List[float])
  • threshold_idx (int)
  • interpolation (List[int])
  • energy (Optional[List[float]]): Present when reaction has its own grid

reaction_mts property

reaction_mts: Optional[list[int]]

List of MT numbers available for the (first) loaded temperature.

Returns:

Type Description
Optional[list[int]]

Optional[List[int]]: List of MT identifiers or None if no data.

energy property

energy: Optional[Any]

Energy grids by temperature.

Returns:

Type Description
Optional[Any]

Optional[Dict[str, List[float]]]: Map of temperature key to energy grid

Optional[Any]

or None if no energy data loaded.

read_nuclear_data

read_nuclear_data(path: Optional[str] = None, temperatures: Optional[Sequence[str]] = None) -> None

Read nuclear data from a file, keyword, or directory.

You can either provide a source explicitly via path or rely on the name given at construction and the global configuration to resolve it. Providing an explicit path will override any global configuration.

The path argument accepts: - A file path (e.g. "tests/Li6.arrow") - A keyword (e.g. "tendl-2025", "fendl-3.2d", "endf-b8.1") - A directory path (e.g. "/path/to/neutron/") -- resolves to <dir>/<name>.arrow - None -- looks up the path from yamc.neutron_cross_section_data

When temperatures is provided only those temperatures are loaded while available_temperatures always lists every temperature present in the file. The subset actually loaded is stored in loaded_temperatures.

Parameters:

Name Type Description Default
path Optional[str]

Optional path to the nuclide data file, keyword, or directory. If omitted, the constructor name is used to look up the source from yamc.neutron_cross_section_data.

None
temperatures Optional[List[str]]

Temperature strings in Kelvin (e.g. ["293"]). If given only these temperatures are loaded.

None

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If neither path nor name is available, if the nuclide name is not found in global configuration (when path not provided), or if the data cannot be read / parsed.

Examples:

Compare the same nuclide from different data sources:

>>> # Set global default
>>> yamc.neutron_cross_section_data = "tendl-2025"
>>>
>>> # Load from global config (will use TENDL)
>>> li6_tendl = yamc.Nuclide("Li6")
>>> li6_tendl.read_nuclear_data()
>>>
>>> # Override to use FENDL for comparison
>>> li6_fendl = yamc.Nuclide("Li6")
>>> li6_fendl.read_nuclear_data("fendl-3.2d")
>>>
>>> # Use a directory
>>> li6_dir = yamc.Nuclide("Li6")
>>> li6_dir.read_nuclear_data("/path/to/neutron/")
>>>
>>> # Use custom local file
>>> li6_custom = yamc.Nuclide("Li6")
>>> li6_custom.read_nuclear_data("path/to/custom_Li6.arrow")
Source code in yamc/_core/__init__.pyi
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
def read_nuclear_data(self, path: typing.Optional[builtins.str] = None, temperatures: typing.Optional[typing.Sequence[builtins.str]] = None) -> None:
    r"""
    Read nuclear data from a file, keyword, or directory.

    You can either provide a source explicitly via `path` or rely on
    the `name` given at construction and the global configuration to resolve it.
    Providing an explicit `path` will override any global configuration.

    The `path` argument accepts:
      - A file path (e.g. "tests/Li6.arrow")
      - A keyword (e.g. "tendl-2025", "fendl-3.2d", "endf-b8.1")
      - A directory path (e.g. "/path/to/neutron/") -- resolves to `<dir>/<name>.arrow`
      - None -- looks up the path from yamc.neutron_cross_section_data

    When `temperatures` is provided only those temperatures are loaded while
    `available_temperatures` always lists every temperature present in the
    file. The subset actually loaded is stored in `loaded_temperatures`.

    Args:
        path (Optional[str]): Optional path to the nuclide data file, keyword,
            or directory. If omitted, the constructor `name` is used to look up
            the source from yamc.neutron_cross_section_data.
        temperatures (Optional[List[str]]): Temperature strings in Kelvin (e.g. ["293"]).
            If given only these temperatures are loaded.

    Returns:
        None

    Raises:
        ValueError: If neither `path` nor `name` is available, if the nuclide
            name is not found in global configuration (when path not provided),
            or if the data cannot be read / parsed.

    Examples:
        Compare the same nuclide from different data sources:

        >>> # Set global default
        >>> yamc.neutron_cross_section_data = "tendl-2025"
        >>>
        >>> # Load from global config (will use TENDL)
        >>> li6_tendl = yamc.Nuclide("Li6")
        >>> li6_tendl.read_nuclear_data()
        >>>
        >>> # Override to use FENDL for comparison
        >>> li6_fendl = yamc.Nuclide("Li6")
        >>> li6_fendl.read_nuclear_data("fendl-3.2d")
        >>>
        >>> # Use a directory
        >>> li6_dir = yamc.Nuclide("Li6")
        >>> li6_dir.read_nuclear_data("/path/to/neutron/")
        >>>
        >>> # Use custom local file
        >>> li6_custom = yamc.Nuclide("Li6")
        >>> li6_custom.read_nuclear_data("path/to/custom_Li6.arrow")
    """

energy_grid

energy_grid(temperature: str) -> Optional[list[float]]

Get the energy grid for a specific temperature.

Parameters:

Name Type Description Default
temperature str

Temperature key in Kelvin (e.g. "293").

required

Returns:

Type Description
Optional[list[float]]

Optional[List[float]]: The energy grid or None if not present.

Source code in yamc/_core/__init__.pyi
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
def energy_grid(self, temperature: builtins.str) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Get the energy grid for a specific temperature.

    Args:
        temperature (str): Temperature key in Kelvin (e.g. "293").

    Returns:
        Optional[List[float]]: The energy grid or None if not present.
    """

get_reaction_energy_grid

get_reaction_energy_grid(temperature: str, mt: int) -> Optional[list[float]]

Get energy grid for a specific temperature and MT number.

Parameters:

Name Type Description Default
temperature str

Temperature to use for reaction data.

required
mt int

ENDF/MT number for the reaction channel.

required

Returns:

Type Description
Optional[list[float]]

Optional[List[float]]: Reaction energy grid if present.

Source code in yamc/_core/__init__.pyi
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
def get_reaction_energy_grid(self, temperature: builtins.str, mt: builtins.int) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Get energy grid for a specific temperature and MT number.

    Args:
        temperature (str): Temperature to use for reaction data.
        mt (int): ENDF/MT number for the reaction channel.

    Returns:
        Optional[List[float]]: Reaction energy grid if present.
    """

microscopic_cross_section

microscopic_cross_section(reaction: int | str, temperature: Optional[str] = None) -> tuple[list[float], list[float]]

Get microscopic cross section data for a specific reaction and temperature.

Parameters:

Name Type Description Default
reaction Union[int, str]

Either an ENDF/MT number (int) or reaction name (str) like "(n,gamma)", "(n,elastic)", "fission", etc.

required
temperature Optional[str]

Temperature to use. If None, uses the single loaded temperature if only one is available.

None

Returns:

Type Description
tuple[list[float], list[float]]

Tuple[List[float], List[float]]: A tuple of (cross_section_values, energy_grid).

Raises:

Type Description
Exception

If temperature not found, reaction not found, multiple temperatures loaded without specifying one, or no data available.

Source code in yamc/_core/__init__.pyi
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
def microscopic_cross_section(self, reaction: builtins.int | builtins.str, temperature: typing.Optional[builtins.str] = None) -> tuple[builtins.list[builtins.float], builtins.list[builtins.float]]:
    r"""
    Get microscopic cross section data for a specific reaction and temperature.

    Args:
        reaction (Union[int, str]): Either an ENDF/MT number (int) or reaction name (str)
            like "(n,gamma)", "(n,elastic)", "fission", etc.
        temperature (Optional[str]): Temperature to use. If None, uses the single
            loaded temperature if only one is available.

    Returns:
        Tuple[List[float], List[float]]: A tuple of (cross_section_values, energy_grid).

    Raises:
        Exception: If temperature not found, reaction not found, multiple temperatures loaded
            without specifying one, or no data available.
    """

sample_reaction

sample_reaction(energy: float, temperature: str, seed: Optional[int] = None) -> Optional[Any]

Sample a reaction based on cross sections at a given energy and temperature.

This method randomly selects a nuclear reaction channel based on the relative cross sections at the specified neutron energy. It uses Monte Carlo sampling to select between absorption, elastic scattering, fission (if fissionable), and non-elastic reactions according to their probabilities.

Parameters:

Name Type Description Default
energy float

Neutron energy in eV.

required
temperature str

Temperature to use for reaction data in Kelvin (e.g. "294", "300").

required
seed Optional[int]

Random seed for reproducible sampling. If None, uses system random state.

None

Returns:

Type Description
Optional[Any]

Optional[Dict[str, Any]]: Dictionary containing the sampled reaction data: - mt_number (int): ENDF/MT number of the sampled reaction - cross_section (List[float]): Cross section values in barns - threshold_idx (int): Index where reaction becomes active - interpolation (List[int]): Interpolation flags - energy (List[float]): Reaction energy grid

Returns None if no reaction could be sampled (e.g., zero total cross section).

Raises:

Type Description
ValueError

If temperature not found or no reaction data available.

Examples:

>>> nuclide = Nuclide("Li6")
>>> nuclide.read_nuclear_data()
>>> reaction = nuclide.sample_reaction(1e-3, "294", seed=42)
>>> if reaction:
...     print(f"Sampled MT {reaction['mt_number']}")
Source code in yamc/_core/__init__.pyi
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
def sample_reaction(self, energy: builtins.float, temperature: builtins.str, seed: typing.Optional[builtins.int] = None) -> typing.Optional[typing.Any]:
    r"""
    Sample a reaction based on cross sections at a given energy and temperature.

    This method randomly selects a nuclear reaction channel based on the relative
    cross sections at the specified neutron energy. It uses Monte Carlo sampling
    to select between absorption, elastic scattering, fission (if fissionable),
    and non-elastic reactions according to their probabilities.

    Args:
        energy (float): Neutron energy in eV.
        temperature (str): Temperature to use for reaction data in Kelvin (e.g. "294", "300").
        seed (Optional[int]): Random seed for reproducible sampling. If None,
            uses system random state.

    Returns:
        Optional[Dict[str, Any]]: Dictionary containing the sampled reaction data:
            - mt_number (int): ENDF/MT number of the sampled reaction
            - cross_section (List[float]): Cross section values in barns
            - threshold_idx (int): Index where reaction becomes active
            - interpolation (List[int]): Interpolation flags
            - energy (List[float]): Reaction energy grid

            Returns None if no reaction could be sampled (e.g., zero total cross section).

    Raises:
        ValueError: If temperature not found or no reaction data available.

    Examples:
        >>> nuclide = Nuclide("Li6")
        >>> nuclide.read_nuclear_data()
        >>> reaction = nuclide.sample_reaction(1e-3, "294", seed=42)
        >>> if reaction:
        ...     print(f"Sampled MT {reaction['mt_number']}")
    """

Particle

Particle(position: Sequence[float], direction: Sequence[float], energy: float, alive: Optional[bool], id: Optional[int])

A single transport particle: position, direction, energy, and alive/id state.

Source code in yamc/_core/__init__.pyi
4427
def __new__(cls, position: typing.Sequence[builtins.float], direction: typing.Sequence[builtins.float], energy: builtins.float, alive: typing.Optional[builtins.bool], id: typing.Optional[builtins.int]) -> Particle: ...

position property

position: list[float]

Particle position in 3D space (x, y, z).

Returns:

Type Description
list[float]

Array of 3 floats [x, y, z]

direction property

direction: list[float]

Particle direction unit vector (u, v, w).

Returns:

Type Description
list[float]

Array of 3 floats [u, v, w]

energy property

energy: float

Particle kinetic energy in eV.

Returns:

Type Description
float

Float energy in eV

alive property

alive: bool

Whether the particle is still alive (not absorbed or leaked).

Returns:

Type Description
bool

Boolean indicating if particle is alive

id property

id: int

Unique identifier for this particle.

Returns:

Type Description
int

Integer particle ID

particle_type property

particle_type: str

Particle type ("neutron" or "photon").

Returns:

Name Type Description
str str

The particle type

ParticleTrack

One particle's track: the ordered list of TrackEvent steps it went through from its birth, with its particle type ("neutron" or "photon"), history, particle ID (unique within the history; 0 is the source particle), parent ID, and generation. Access the steps via track.events; len(track) is the number of events.

particle_type property

particle_type: str

Particle species, "neutron" or "photon".

history property

history: int

Global index of the source history this particle belongs to.

PhotonCoefficients

A photon coefficient tabulated against energy, returned by :func:yamc.data.mass_attenuation_coefficient and :func:yamc.data.mass_energy_absorption_coefficient.

Carries the energy grid and the coefficients, and evaluates itself between the tabulated points with the log-log interpolation NIST publishes these for.

energy property

energy: list[float]

Tabulated energies in eV. An absorption edge appears as two energies one ulp apart, carrying the value below and above the edge.

coefficients property

coefficients: list[float]

The coefficient at each tabulated energy, in cm²/g.

units property

units: str

Units of the coefficients ("cm2/g").

interpolate

interpolate(energy: float) -> float

The coefficient at energy (eV), log-log interpolated.

Energies outside the tabulated range return the nearest end value rather than extrapolating: the tabulation stops where the data does.

Source code in yamc/_core/__init__.pyi
4486
4487
4488
4489
4490
4491
4492
def interpolate(self, energy: builtins.float) -> builtins.float:
    r"""
    The coefficient at ``energy`` (eV), log-log interpolated.

    Energies outside the tabulated range return the nearest end value rather
    than extrapolating: the tabulation stops where the data does.
    """

as_energy_function

as_energy_function() -> tuple[list[float], list[float], str, str]

Repackage as the (energy, coefficients, units, interpolation) tuple accepted by Tally(energy_function=...). The interpolation is "log-log", matching :meth:interpolate, so a tally weights by the same values; its absorption edges are steps rather than the ringing a cubic spline gives across them.

Source code in yamc/_core/__init__.pyi
4493
4494
4495
4496
4497
4498
4499
4500
def as_energy_function(self) -> tuple[builtins.list[builtins.float], builtins.list[builtins.float], builtins.str, builtins.str]:
    r"""
    Repackage as the ``(energy, coefficients, units, interpolation)`` tuple
    accepted by ``Tally(energy_function=...)``. The interpolation is
    ``"log-log"``, matching :meth:`interpolate`, so a tally weights by the
    same values; its absorption edges are steps rather than the ringing a
    cubic spline gives across them.
    """

PhotonContinuum

One nuclide's decay photon continuum within a material's inventory.

ENDF gives part of some decay spectra as a density over energy rather than as lines: the spontaneous-fission photons of an actinide, or the whole photon emission of a nuclide far from stability, whose lines were never measured. The values are a rate per eV, so they are not line rates and cannot be added to decay_photon_spectrum()'s. Their rate is the integral, which emission_rate gives. Both follow the per argument of decay_photon_continua(): for the whole material, or per cm³ or per g.

nuclide property

nuclide: str

The emitting nuclide.

energies property

energies: list[float]

Tabulated energies [eV], ascending.

rates property

rates: list[float]

The emission-rate density at each energy: photons/s/eV for the whole material, or per cm³ or per g following the per argument the continuum was requested with.

interpolation property

interpolation: Optional[str]

How rates is read between the energies: the ENDF law by name ("histogram", "linear-linear", ...), or None where the data states no law, which data written before the law was stored does.

emission_rate property

emission_rate: float

The emission rate over the whole continuum, its integral read under its law: photons/s for the whole material, or per cm³ or per g following the per argument the continuum was requested with.

Raises:

Type Description
ValueError

If the law is not stated, or is one this build does not integrate, or if the energy and rate lists are unpaired, the energies are not finite or descend, or the rates are negative or not finite. The integral is then unknown, and no number is returned in its place.

Pulse

Pulse(rate: float, duration: Any, source: Optional[Any] = None, flux_std_dev: Optional[Sequence[float]] = None, flux_covariance: Optional[Sequence[Sequence[float]]] = None, model: Optional[Any] = None, moves: Optional[Any] = None)

One irradiation campaign: a neutron source held at a constant rate (n/s) for duration.

Create an irradiation pulse.

Parameters:

Name Type Description Default
rate float

For Model.simulate_transmutation, the source emission rate in particles/second (n/s). For Material.transmute, the total flux magnitude [n/cm^2/s] (the source's Histogram energy gives the spectrum shape).

required
duration Any

A number of seconds, or a (value, unit) tuple such as (1, "a") or (30, "d"). Units: s, min, h, d, a (year).

required
source Optional[Any]

The NeutronSource for this campaign. Defaults to None, which Model.simulate_transmutation accepts (transport uses the model's source); Material.transmute requires a source whose energy is a Histogram and ignores its position/direction.

None
flux_std_dev Optional[Sequence[float]]

Per-bin standard deviation of the flux, in the same units and the same order as the Histogram values. Optional, and omitting it is the common case: a spectrum taken from a published reference set carries no stated error. From a yamc run it is results[tally].standard_deviation.

Used only by Material.transmute(data_uncertainty=...) with the flux_spectrum source enabled. Omitted, that source contributes nothing and says so in data_uncertainty_info["spectra_without_flux_sigma"] rather than reading as a flux known exactly.

Treats the bins as independent. A spectrum from a Monte Carlo tally is not: its bins are scored by the same histories and move together, and a per-bin sigma then understates the error of every rate that sums over a band. Give flux_covariance instead when the correlations are known.

None
flux_covariance Optional[Sequence[Sequence[float]]]

The full covariance of the Histogram values, a square matrix (nested lists or a 2-D array) with one row and column per bin, in the square of their units. The alternative to flux_std_dev, whose diagonal it contains: give one or the other. It must be symmetric and positive semi-definite, and is checked. Each replica's flux perturbation is drawn through its factor, so correlated bins move together.

None
model Optional[Any]

The yamc Model this pulse irradiates, for yamc.simulate_shutdown_dose: its geometry, materials and neutron source are the machine during this pulse. Give it instead of source. A later step without a model stays in this one.

None
moves Optional[Any]

Cells of model that sit away from their reference position, as {cell or cell name: (dx, dy, dz)} in cm or a 4x4 rigid transformation matrix. Only with model; see Cooldown for how moves work.

None
Source code in yamc/_core/__init__.pyi
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
def __new__(cls, rate: builtins.float, duration: typing.Any, source: typing.Optional[typing.Any] = None, flux_std_dev: typing.Optional[typing.Sequence[builtins.float]] = None, flux_covariance: typing.Optional[typing.Sequence[typing.Sequence[builtins.float]]] = None, model: typing.Optional[typing.Any] = None, moves: typing.Optional[typing.Any] = None) -> Pulse:
    r"""
    Create an irradiation pulse.

    Args:
        rate: For ``Model.simulate_transmutation``, the source emission rate
            in particles/second (n/s). For ``Material.transmute``, the total
            flux magnitude [n/cm^2/s] (the source's ``Histogram`` energy gives
            the spectrum shape).
        duration: A number of seconds, or a ``(value, unit)`` tuple such as
            ``(1, "a")`` or ``(30, "d")``. Units: s, min, h, d, a (year).
        source: The NeutronSource for this campaign. Defaults to ``None``,
            which ``Model.simulate_transmutation`` accepts (transport uses the
            model's source); ``Material.transmute`` requires a source whose
            energy is a ``Histogram`` and ignores its position/direction.
        flux_std_dev: Per-bin standard deviation of the flux, in the same
            units and the same order as the ``Histogram`` values. Optional,
            and omitting it is the common case: a spectrum taken from a
            published reference set carries no stated error. From a yamc
            run it is ``results[tally].standard_deviation``.

            Used only by ``Material.transmute(data_uncertainty=...)`` with
            the ``flux_spectrum`` source enabled. Omitted, that source
            contributes nothing and says so in
            ``data_uncertainty_info["spectra_without_flux_sigma"]`` rather
            than reading as a flux known exactly.

            Treats the bins as independent. A spectrum from a Monte Carlo
            tally is not: its bins are scored by the same histories and
            move together, and a per-bin sigma then understates the error
            of every rate that sums over a band. Give ``flux_covariance``
            instead when the correlations are known.
        flux_covariance: The full covariance of the ``Histogram`` values, a
            square matrix (nested lists or a 2-D array) with one row and
            column per bin, in the square of their units. The alternative
            to ``flux_std_dev``, whose diagonal it contains: give one or
            the other. It must be symmetric and positive semi-definite, and
            is checked. Each replica's flux perturbation is drawn through
            its factor, so correlated bins move together.
        model: The yamc ``Model`` this pulse irradiates, for
            ``yamc.simulate_shutdown_dose``: its geometry, materials and
            neutron source are the machine during this pulse. Give it
            instead of ``source``. A later step without a ``model`` stays in
            this one.
        moves: Cells of ``model`` that sit away from their reference
            position, as ``{cell or cell name: (dx, dy, dz)}`` in cm or a
            4x4 rigid transformation matrix. Only with ``model``; see
            ``Cooldown`` for how moves work.
    """

model property

model: Optional[Any]

The Model this pulse irradiates, or None.

moves property

moves: dict[str, list[list[float]]]

The moved cells, {name: 4x4 matrix}.

source property

source: Optional[Any]

The neutron source active during this pulse, or None if sourceless.

flux_std_dev property

flux_std_dev: Optional[list[float]]

The per-bin flux standard deviation, or None if none was given.

flux_covariance property

flux_covariance: Optional[list[list[float]]]

The flux covariance, or None if none was given.

rate property

rate: float

Source emission rate in particles/second.

duration property

duration: float

Pulse duration in seconds.

PulseSchedule

PulseSchedule(steps: Any)

An irradiation/cooling timeline built from Pulse and Cooldown steps.

time_correct_tally post-processes a decay-photon tally into shutdown dose rates over the schedule.

Build a schedule from a list of Pulse / Cooldown steps.

Source code in yamc/_core/__init__.pyi
4848
4849
4850
4851
def __new__(cls, steps: typing.Any) -> PulseSchedule:
    r"""
    Build a schedule from a list of `Pulse` / `Cooldown` steps.
    """

sources property

sources: list[Any]

The distinct neutron sources used by the pulses, in first-appearance order. For a mixed-spectrum schedule, pass time_correct_tally a dict mapping each of these to its transport run's tally result.

time_correct_tally

time_correct_tally(results: Any, steps: Optional[Any] = None, data_uncertainty: Optional[DataUncertainty] = None) -> DoseResult

Time-correct a decay-photon tally into shutdown dose rate(s).

Parameters:

Name Type Description Default
results Any

For a single-source schedule, the TallyResult from the decay-photon run. For a mixed-spectrum (multi-source) schedule, a dict mapping each source in self.sources to its run's TallyResult; the per-source corrections are summed exactly.

required
steps Optional[Any]

Which schedule step(s) to evaluate the dose at the END of. None (default) selects every step; an int selects one (returns 1-D arrays; negative counts from the end); a sequence of ints selects a subset in order. The pre-irradiation baseline is never included, so there is no row-0 footgun.

None

The transmutation network is assembled from the configured per-subsection sources: the decay data (yamc.transmutation_decay_data) and the reactions (yamc.transmutation_reactions), which say which emitters a collision makes. There is no default library, so either one unset raises ValueError, naming it.

data_uncertainty (DataUncertainty, optional): Also propagate the
    nuclear-data uncertainty of the dose. Two sources act on it.
    ``"half_life"`` acts through the time correction: a
    time-correction factor is an activity over the schedule, and the
    tally's in-line photon yield is per decay, so the half-lives
    enter there and nowhere else. Each replica draws every half-life
    feeding an emitter once and uses it for every campaign, so one
    evaluation is one uncertainty. ``"decay_photon_lines"`` acts
    through the photon spectrum normalisation (FD, FC), which scales
    an emitter's whole spectrum and so its tally, and is applied to
    it after the fact; an emitter with several spectra is scaled by
    their multipliers weighted by each one's share of its photon
    energy. The draws are those a transmutation with the same seed
    makes. Read ``.data_std_dev``, its standard error
    ``.data_std_dev_standard_error``, and ``.total_std_dev``, and
    ``.data_std_dev_correlated`` and ``.total_std_dev_correlated``
    for the upper end of the range the unstated correlation between
    an emitter's gamma and x-ray normalisations leaves. Replicas are
    added until every emitter's time-correction factor has a
    standard deviation known to the request's ``convergence`` at
    every schedule step, or the request's ``samples`` fixes the
    count. The line intensities (dRI) and energies change the
    spectrum's shape, which needs line-resolved tallies, and are
    held at nominal; ENDF/B-VIII.1 folds the normalisation into the
    dRI, so under it almost nothing is drawn. Decay branching ratios
    also shape a time correction and are held at nominal.
    ``.data_uncertainty_info`` lists everything held under
    ``not_perturbed``.

Returns:

Type Description
DoseResult

DoseResult with .mean / .std_dev / .by_nuclide / .times,

DoseResult

and .data_std_dev / .data_std_dev_standard_error /

DoseResult

.total_std_dev / .data_uncertainty_info when

DoseResult

data_uncertainty was given.

Source code in yamc/_core/__init__.pyi
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
def time_correct_tally(self, results: typing.Any, steps: typing.Optional[typing.Any] = None, data_uncertainty: typing.Optional[DataUncertainty] = None) -> DoseResult:
    r"""
    Time-correct a decay-photon tally into shutdown dose rate(s).

    Args:
        results: For a single-source schedule, the ``TallyResult`` from the
            decay-photon run. For a mixed-spectrum (multi-source) schedule, a
            dict mapping each source in ``self.sources`` to its run's
            ``TallyResult``; the per-source corrections are summed exactly.
        steps: Which schedule step(s) to evaluate the dose at the END of.
            ``None`` (default) selects every step; an ``int`` selects one
            (returns 1-D arrays; negative counts from the end); a sequence of
            ints selects a subset in order. The pre-irradiation baseline is
            never included, so there is no row-0 footgun.

    The transmutation network is assembled from the configured per-subsection
    sources: the decay data (``yamc.transmutation_decay_data``) and the
    reactions (``yamc.transmutation_reactions``), which say which emitters
    a collision makes. There is no default library, so either one unset
    raises ``ValueError``, naming it.

        data_uncertainty (DataUncertainty, optional): Also propagate the
            nuclear-data uncertainty of the dose. Two sources act on it.
            ``"half_life"`` acts through the time correction: a
            time-correction factor is an activity over the schedule, and the
            tally's in-line photon yield is per decay, so the half-lives
            enter there and nowhere else. Each replica draws every half-life
            feeding an emitter once and uses it for every campaign, so one
            evaluation is one uncertainty. ``"decay_photon_lines"`` acts
            through the photon spectrum normalisation (FD, FC), which scales
            an emitter's whole spectrum and so its tally, and is applied to
            it after the fact; an emitter with several spectra is scaled by
            their multipliers weighted by each one's share of its photon
            energy. The draws are those a transmutation with the same seed
            makes. Read ``.data_std_dev``, its standard error
            ``.data_std_dev_standard_error``, and ``.total_std_dev``, and
            ``.data_std_dev_correlated`` and ``.total_std_dev_correlated``
            for the upper end of the range the unstated correlation between
            an emitter's gamma and x-ray normalisations leaves. Replicas are
            added until every emitter's time-correction factor has a
            standard deviation known to the request's ``convergence`` at
            every schedule step, or the request's ``samples`` fixes the
            count. The line intensities (dRI) and energies change the
            spectrum's shape, which needs line-resolved tallies, and are
            held at nominal; ENDF/B-VIII.1 folds the normalisation into the
            dRI, so under it almost nothing is drawn. Decay branching ratios
            also shape a time correction and are held at nominal.
            ``.data_uncertainty_info`` lists everything held under
            ``not_perturbed``.

    Returns:
        DoseResult with ``.mean`` / ``.std_dev`` / ``.by_nuclide`` / ``.times``,
        and ``.data_std_dev`` / ``.data_std_dev_standard_error`` /
        ``.total_std_dev`` / ``.data_uncertainty_info`` when
        ``data_uncertainty`` was given.
    """

Reaction

Reaction(products: Sequence[ReactionProduct], cross_section: Sequence[float], threshold_idx: int, mt_number: int, q_value: float, energy_grid: Sequence[float], scatter_in_cm: bool)

Lightweight reaction summary exposed to Python.

Represents a single nuclear reaction channel with its products and cross section data.

Source code in yamc/_core/__init__.pyi
4956
def __new__(cls, products: typing.Sequence[ReactionProduct], cross_section: typing.Sequence[builtins.float], threshold_idx: builtins.int, mt_number: builtins.int, q_value: builtins.float, energy_grid: typing.Sequence[builtins.float], scatter_in_cm: builtins.bool) -> Reaction: ...

products property

products: list[ReactionProduct]

List of outgoing particles with their yield and secondary distributions.

cross_section property

cross_section: list[float]

Cross section values in barns at each energy point.

threshold_idx property

threshold_idx: int

Index into parent energy grid where this reaction becomes active (threshold).

mt_number property

mt_number: int

ENDF MT number identifying the reaction type (e.g., 2 for elastic, 16 for (n,2n)).

q_value property

q_value: float

Q-value of the reaction in eV (energy released if positive, absorbed if negative).

energy_grid property

energy_grid: list[float]

Reaction-specific energy grid in eV (subset of parent nuclide energy grid).

scatter_in_cm property

scatter_in_cm: bool

Whether scattering is in center-of-mass frame (requires CM to LAB conversion).

ReactionProduct

ReactionProduct(particle: str, emission_mode: str, decay_rate: float)

A product emitted by a nuclear reaction: particle type, emission mode, decay rate, and the angle/energy distributions used to sample it.

Source code in yamc/_core/__init__.pyi
4992
def __new__(cls, particle: builtins.str, emission_mode: builtins.str, decay_rate: builtins.float) -> ReactionProduct: ...

particle property

particle: str

Get particle type as string

emission_mode property

emission_mode: str

Get emission mode

num_distributions property

num_distributions: int

Get number of distributions

distribution_types property

distribution_types: list[str]

Get distribution types as strings

angle_distribution property

angle_distribution: Optional[AngleDistribution]

Get angle distribution if available (for UncorrelatedAngleEnergy) Returns None if no angle distribution exists

sample

sample(incoming_energy: float) -> tuple[float, float]

Sample an outgoing particle from this product Returns tuple of (outgoing_energy, mu_cosine)

Source code in yamc/_core/__init__.pyi
4993
4994
4995
4996
4997
def sample(self, incoming_energy: builtins.float) -> tuple[builtins.float, builtins.float]:
    r"""
    Sample an outgoing particle from this product
    Returns tuple of (outgoing_energy, mu_cosine)
    """

sample_multiple

sample_multiple(incoming_energy: float) -> list[tuple[float, float]]

Sample multiple outgoing particles Returns list of (outgoing_energy, mu_cosine) tuples

Source code in yamc/_core/__init__.pyi
4998
4999
5000
5001
5002
def sample_multiple(self, incoming_energy: builtins.float) -> builtins.list[tuple[builtins.float, builtins.float]]:
    r"""
    Sample multiple outgoing particles
    Returns list of (outgoing_energy, mu_cosine) tuples
    """

is_particle_type

is_particle_type(particle_name: str) -> bool

Check if this product represents a specific particle type

Source code in yamc/_core/__init__.pyi
5003
5004
5005
5006
def is_particle_type(self, particle_name: builtins.str) -> builtins.bool:
    r"""
    Check if this product represents a specific particle type
    """

is_prompt

is_prompt() -> bool

Check if this is a prompt emission

Source code in yamc/_core/__init__.pyi
5007
5008
5009
5010
def is_prompt(self) -> builtins.bool:
    r"""
    Check if this is a prompt emission
    """

is_delayed

is_delayed() -> bool

Check if this is a delayed emission

Source code in yamc/_core/__init__.pyi
5011
5012
5013
5014
def is_delayed(self) -> builtins.bool:
    r"""
    Check if this is a delayed emission
    """

get_decay_rate

get_decay_rate() -> float

Get the decay rate for delayed neutron precursors

Source code in yamc/_core/__init__.pyi
5015
5016
5017
5018
def get_decay_rate(self) -> builtins.float:
    r"""
    Get the decay rate for delayed neutron precursors
    """

RegularCylindricalMesh

RegularCylindricalMesh(r_bounds: tuple[float, float], z_bounds: tuple[float, float], shape: Sequence[int], phi_bounds: tuple[float, float] = (0.0, 6.283185307179586), origin: Sequence[float] = [0.0, 0.0, 0.0])

A cylindrical (r, φ, z) mesh with uniform spacing in each direction.

The mesh divides an annular cylinder into shape = (nr, nphi, nz) cells. Cell volumes are not equal -- outer radial rings are larger (V = ½·(r_o² − r_i²)·Δφ·Δz) -- so normalise per cell when comparing flux across radii (see :meth:element_volume).

phi_bounds may be any sub-interval of [0, 2π] (default the full circle), e.g. (0, math.pi) for a half or (math.pi, 2*math.pi) for a sector. Coordinates are measured relative to origin and the cylinder axis is parallel to +z.

Examples:

>>> import math, yamc
>>> mesh = yamc.RegularCylindricalMesh(
...     r_bounds=(0.0, 10.0),
...     z_bounds=(-5.0, 5.0),
...     shape=(10, 16, 20),
...     phi_bounds=(0.0, 2 * math.pi),
...     origin=(0.0, 0.0, 0.0),
... )

Parameters:

Name Type Description Default
r_bounds tuple[float, float]

Radial extent (r_min, r_max) in cm. r_min must be >= 0.

required
z_bounds tuple[float, float]

Axial extent (z_min, z_max) in cm relative to origin.

required
shape Sequence[int]

Cell counts (nr, nphi, nz).

required
phi_bounds tuple[float, float]

Azimuthal extent (phi_min, phi_max) in radians. Defaults to the full circle, (0.0, 2 * math.pi).

(0.0, 6.283185307179586)
origin Sequence[float]

Cylinder origin [x0, y0, z0] in cm. Defaults to [0.0, 0.0, 0.0].

[0.0, 0.0, 0.0]
Source code in yamc/_core/__init__.pyi
5154
def __new__(cls, r_bounds: tuple[builtins.float, builtins.float], z_bounds: tuple[builtins.float, builtins.float], shape: typing.Sequence[builtins.int], phi_bounds: tuple[builtins.float, builtins.float] = (0.0, 6.283185307179586), origin: typing.Sequence[builtins.float] = [0.0, 0.0, 0.0]) -> RegularCylindricalMesh: ...

r_bounds property

r_bounds: tuple[float, float]

Radial extent (r_min, r_max) in cm.

phi_bounds property

phi_bounds: tuple[float, float]

Azimuthal extent (phi_min, phi_max) in radians.

z_bounds property

z_bounds: tuple[float, float]

Axial extent (z_min, z_max) in cm (relative to origin).

shape property

shape: list[int]

Cell counts (nr, nphi, nz).

origin property

origin: list[float]

Cylinder origin [x0, y0, z0] in cm.

num_bins property

num_bins: int

Total number of cells (nr * nphi * nz).

element_volume

element_volume(bin: int) -> float

Volume of cell bin in cm³ (non-uniform: outer rings are larger).

Source code in yamc/_core/__init__.pyi
5155
5156
5157
5158
def element_volume(self, bin: builtins.int) -> builtins.float:
    r"""
    Volume of cell ``bin`` in cm³ (non-uniform: outer rings are larger).
    """

RegularRectangularMesh

RegularRectangularMesh(lower_left: Sequence[float], upper_right: Sequence[float], shape: Any)

An axis-aligned regular (structured) mesh used for spatial tally binning.

A RegularRectangularMesh divides a rectangular box (lower_left to upper_right) into a grid of voxels of given shape. Pass it to a :class:Tally via mesh= to score quantities per voxel.

Construct from explicit corners and shape, or from a geometry's bounding box via :meth:RegularRectangularMesh.from_domain (which accepts either a target total voxel count as an int, or per-axis counts as a 3-tuple).

Examples:

>>> import yamc
>>> mesh = yamc.RegularRectangularMesh(
...     lower_left=[-10, -10, -10],
...     upper_right=[10, 10, 10],
...     shape=[20, 20, 20],
... )
>>> # shape may also be a single int (total voxels), split over the box:
>>> mesh = yamc.RegularRectangularMesh(
...     lower_left=[-10, -10, -10], upper_right=[10, 10, 10], shape=8000,
... )
>>> # Or fit to the geometry:
>>> mesh = yamc.RegularRectangularMesh.from_domain(geometry, shape=1_000_000)

Parameters:

Name Type Description Default
lower_left Sequence[float]

Lower-left corner of the mesh box, [x, y, z] in cm.

required
upper_right Sequence[float]

Upper-right corner of the mesh box, [x, y, z] in cm.

required
shape Any

Per-axis voxel counts [nx, ny, nz], or a single int for the total voxel count (split into roughly cubic bins using the box size).

required
Source code in yamc/_core/__init__.pyi
5222
def __new__(cls, lower_left: typing.Sequence[builtins.float], upper_right: typing.Sequence[builtins.float], shape: typing.Any) -> RegularRectangularMesh: ...

lower_left property

lower_left: list[float]

Lower-left corner of the mesh box, [x, y, z] in cm.

upper_right property

upper_right: list[float]

Upper-right corner of the mesh box, [x, y, z] in cm.

shape property

shape: list[int]

Number of voxels along each axis, [nx, ny, nz].

width property

width: list[float]

Voxel width along each axis, [dx, dy, dz] in cm.

num_bins property

num_bins: int

Total number of voxels (nx * ny * nz).

This is also the length of a mesh tally's flat result array, and the number of weight-window bounds expected per energy group.

from_domain classmethod

from_domain(domain: Any, shape: Optional[Any] = None, material: Optional[Material] = None) -> RegularRectangularMesh

Create a mesh from a geometry domain object.

The mesh extents are derived automatically from the domain's bounding box. shape can be a single integer (total cell count -- bins are distributed to produce roughly cubic voxels) or a list of three integers [nx, ny, nz].

Parameters:

Name Type Description Default
domain Any

A Region, Cell, Geometry, Model, MeshGeometry, or BoundingBox.

required
shape Optional[Any]

Total number of mesh cells (int) or per-axis bin counts [nx, ny, nz]. Defaults to 1000.

None
material Optional[Material]

Optional Material -- only valid with MeshGeometry domains. When given, the mesh covers only volumes matching that material.

None

Returns:

Name Type Description
RegularRectangularMesh RegularRectangularMesh

A new mesh covering the domain.

Source code in yamc/_core/__init__.pyi
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
@classmethod
def from_domain(cls, domain: typing.Any, shape: typing.Optional[typing.Any] = None, material: typing.Optional[Material] = None) -> RegularRectangularMesh:
    r"""
    Create a mesh from a geometry domain object.

    The mesh extents are derived automatically from the domain's bounding
    box.  ``shape`` can be a single integer (total cell count --
    bins are distributed to produce roughly cubic voxels) or a list of
    three integers ``[nx, ny, nz]``.

    Args:
        domain: A Region, Cell, Geometry, Model, MeshGeometry, or BoundingBox.
        shape: Total number of mesh cells (int) or per-axis bin counts
            ``[nx, ny, nz]``.  Defaults to ``1000``.
        material: Optional Material -- only valid with MeshGeometry domains.
            When given, the mesh covers only volumes matching that material.

    Returns:
        RegularRectangularMesh: A new mesh covering the domain.
    """

SceneFaceOutput

Output from meshing one face in UV space (new scene mesher).

Triangle indices 0..num_boundary_vertices reference boundary_uv_vertices; indices >= num_boundary_vertices reference interior_uv_vertices. The caller evaluates UV -> 3D on the OCC surface itself.

ScorePdf

Raw empirical probability density of the per-history total score: a log-spaced histogram of |total| (counts per magnitude bin, with bin_edges / bin_centers), plus the count of exactly-zero histories.

counts property

counts: list[int]

Per-bin counts (length = number of magnitude bins). Empty when no per-history sampling occurred (e.g. GPU runs).

bin_edges property

bin_edges: list[float]

Lower magnitude edges, one more than counts (so bin i spans bin_edges[i] .. bin_edges[i+1]).

bin_centers property

bin_centers: list[float]

Geometric center magnitude of each bin.

zero property

zero: int

Histories whose total score was exactly zero.

tail_slope property

tail_slope: float

Slope of the large-score tail (variance exists when > 3); 0 if not estimable.

StatisticalChecks

Python-visible outcome of a tally's statistical-reliability checks.

passed property

passed: bool

True when the tail is estimable and every evaluated check passed.

n_passed property

n_passed: int

Number of evaluated checks that passed.

n_evaluated property

n_evaluated: int

Number of checks that could be evaluated.

per_bin_relative_error_ok property

per_bin_relative_error_ok: Optional[bool]

Every populated bin has relative error below 0.10; no per-bin tail or higher-moment state is allocated by this check.

relative_error_rate_ok property

relative_error_rate_ok: Optional[bool]

Relative error falling as 1/sqrt(N) over the last half of the run.

variance_of_variance_rate_ok property

variance_of_variance_rate_ok: Optional[bool]

Variance of the variance falling as 1/N over the last half of the run.

figure_of_merit_no_trend property

figure_of_merit_no_trend: Optional[bool]

Figure of merit shows no systematic trend with N over the last half of the run. None when that half spans under 0.1 s of wall time.

summary

summary() -> str

A plain-text pass / FAIL / n/a table.

Source code in yamc/_core/__init__.pyi
5359
5360
5361
5362
def summary(self) -> builtins.str:
    r"""
    A plain-text pass / FAIL / n/a table.
    """

Surface

A geometric surface (plane, cylinder, sphere, …). Its .below and .above half-spaces, combined with &/|/~, build CSG Regions.

distance property

distance: Optional[float]

Signed distance (cm) of a flux or offset surface from its flux surface (0 for a FluxSurface), else None

formula property

formula: Optional[str]

The formula of an ImplicitSurface as it is stored, which parses back to the same surface, else None

x0 property

x0: Optional[float]

Offset of a plane perpendicular to the x-axis (axis='x'), else None

y0 property

y0: Optional[float]

Offset of a plane perpendicular to the y-axis (axis='y'), else None

z0 property

z0: Optional[float]

Offset of a plane perpendicular to the z-axis (axis='z'), else None

radius property

radius: Optional[float]

Radius for Sphere or Cylinder surfaces, else None

axis_x property

axis_x: Optional[float]

Get the axis_x value for Cylinder surfaces, or None otherwise

axis_y property

axis_y: Optional[float]

Get the axis_y value for Cylinder surfaces, or None otherwise

axis_z property

axis_z: Optional[float]

Get the axis_z value for Cylinder surfaces, or None otherwise

boundary property writable

boundary: Optional[str]

Boundary condition: None for transmission (default) or 'vacuum'.

below property

below: Region

The below (negative-sense) half-space of this surface, as a Region: points where surface.evaluate(p) < 0 (inside a sphere/cylinder, below a plane). Combine with &/|/~. (Replaces the old unary -surface.)

above property

above: Region

The above (positive-sense) half-space of this surface, as a Region: points where surface.evaluate(p) > 0 (outside a sphere/cylinder, above a plane). Combine with &/|/~. (Replaces the old unary +surface.)

evaluate

evaluate(point: tuple[float, float, float]) -> float

Evaluate the surface equation at a point.

For a flux surface the value is the signed distance (cm) from it. For an offset surface it is the signed distance from the underlying flux surface minus distance: the distance to the layer outside it and wherever the layer is not creased, an underestimate inside the layer near a crease. The sign is always exact. For an implicit surface it is the formula's value, a distance only if the formula is one.

Parameters:

Name Type Description Default
point tuple[float, float, float]

Tuple of 3 floats (x, y, z)

required

Returns:

Type Description
float

Float value. Negative means inside/below, positive means outside/above, zero means on surface.

Source code in yamc/_core/__init__.pyi
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
def evaluate(self, point: tuple[builtins.float, builtins.float, builtins.float]) -> builtins.float:
    r"""
    Evaluate the surface equation at a point.

    For a flux surface the value is the signed distance (cm) from it.
    For an offset surface it is the signed distance from the underlying
    flux surface minus ``distance``: the distance to the layer outside
    it and wherever the layer is not creased, an underestimate inside
    the layer near a crease. The sign is always exact. For an implicit
    surface it is the formula's value, a distance only if the formula is
    one.

    Args:
        point: Tuple of 3 floats (x, y, z)

    Returns:
        Float value. Negative means inside/below, positive means outside/above, zero means on surface.
    """

distance_to_surface

distance_to_surface(point: tuple[float, float, float], direction: tuple[float, float, float]) -> Optional[float]

Compute the distance to the surface from a point in a direction. Returns the distance as a float, or None if no intersection is found. A flux, offset or implicit surface searches for it, and finds none if its search runs out of evaluations first, as it can far along a ray through an implicit lattice with no bounding box (which is searched only within 1048576 cm, 2^20 cm, of the origin on each axis).

Source code in yamc/_core/__init__.pyi
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
def distance_to_surface(self, point: tuple[builtins.float, builtins.float, builtins.float], direction: tuple[builtins.float, builtins.float, builtins.float]) -> typing.Optional[builtins.float]:
    r"""
    Compute the distance to the surface from a point in a direction.
    Returns the distance as a float, or None if no intersection is
    found. A flux, offset or implicit surface searches for it, and finds
    none if its search runs out of evaluations first, as it can far
    along a ray through an implicit lattice with no bounding box (which
    is searched only within 1048576 cm, 2^20 cm, of the origin on each
    axis).
    """

bounding_box_inside

bounding_box_inside() -> Optional[BoundingBox]

Get the bounding box for the inside (negative halfspace) of this surface

Source code in yamc/_core/__init__.pyi
5477
5478
5479
5480
def bounding_box_inside(self) -> typing.Optional[BoundingBox]:
    r"""
    Get the bounding box for the inside (negative halfspace) of this surface
    """

axis_constraint

axis_constraint(halfspace_below: bool) -> Optional[tuple[int, bool, float]]

Get axis constraint for this surface when used as a halfspace Returns (axis_index, is_upper_bound, value) or None axis_index: 0=X, 1=Y, 2=Z is_upper_bound: True if this constrains the upper bound, False for lower bound

Source code in yamc/_core/__init__.pyi
5482
5483
5484
5485
5486
5487
5488
def axis_constraint(self, halfspace_below: builtins.bool) -> typing.Optional[tuple[builtins.int, builtins.bool, builtins.float]]:
    r"""
    Get axis constraint for this surface when used as a halfspace
    Returns (axis_index, is_upper_bound, value) or None
    axis_index: 0=X, 1=Y, 2=Z
    is_upper_bound: True if this constrains the upper bound, False for lower bound
    """

SurvivalBiasing

SurvivalBiasing(weight_cutoff: float = 0.25, weight_survive: float = 1.0)

Survival biasing (implicit capture) with weight-cutoff Russian roulette.

Absorption never terminates the particle; instead each collision multiplies its weight by the scattering probability and the particle always scatters. A particle whose weight drops below weight_cutoff plays roulette: it survives with probability weight / weight_survive (continuing at weight_survive) or is killed, conserving weight in expectation.

Parameters:

Name Type Description Default
weight_cutoff float

Weight below which a particle plays Russian roulette (default: 0.25).

0.25
weight_survive float

Weight given to a particle that survives roulette (default: 1.0). Must be >= weight_cutoff.

1.0

Examples:

>>> model = yamc.Model(
...     geometry=geometry,
...     source=source,
...     variance_reduction=[yamc.SurvivalBiasing()],
... )
>>> model.simulate_transport(total_particles=100_000)
Source code in yamc/_core/__init__.pyi
5530
def __new__(cls, weight_cutoff: builtins.float = 0.25, weight_survive: builtins.float = 1.0) -> SurvivalBiasing: ...

weight_cutoff property writable

weight_cutoff: float

Russian-roulette trigger weight.

weight_survive property writable

weight_survive: float

Weight assigned to roulette survivors.

Tabulated

Tabulated(values: Sequence[float], probabilities: Sequence[float])

A tabulated probability distribution (values with their probabilities, internally carrying a precomputed CDF) used for inverse-transform sampling.

Source code in yamc/_core/__init__.pyi
5550
def __new__(cls, values: typing.Sequence[builtins.float], probabilities: typing.Sequence[builtins.float]) -> Tabulated: ...

values property

values: list[float]

The tabulated x values (abscissae).

probabilities property

probabilities: list[float]

The probability density at each x value.

sample

sample() -> float

Sample from the tabulated distribution

Source code in yamc/_core/__init__.pyi
5551
5552
5553
5554
def sample(self) -> builtins.float:
    r"""
    Sample from the tabulated distribution
    """

TallyIter

Iterator over the Tally configs in a TransportResults.

TallyResult

Python-visible wrapper over Arc<TallyResult>.

mean property

mean: list[float]

Mean value per bin, flat row-major over shape, in units.

standard_deviation property

standard_deviation: list[float]

Standard error of the mean per bin, in units.

units property

units: list[str]

Per score, the unit of mean and standard_deviation: the score's own per source particle ("eV/source-particle"), per second or per pulse once a source strength is set ("eV/s"), or the unit given to to.

source_strength property

source_strength: Optional[tuple[float, str]]

The source strength as (value, per), per being "second" or "pulse", or None for results per source particle.

bin_volumes property

bin_volumes: list[float]

Volume in cm3 of each bin, flat in the same order as mean: the mesh element of a mesh tally, or the cell of a cell-filtered tally whose cells have a volume. Raises ValueError when a bin's volume is not known.

relative_error property

relative_error: list[float]

Relative error (std_dev / mean) per bin.

nuclear_data_standard_deviation property

nuclear_data_standard_deviation: Optional[list[float]]

Nuclear-data standard deviation per bin, when the run was given data_uncertainty; None otherwise.

The score's first-order variance along the cross sections' principal modes, which carries no sampling error from the replicas, plus the nonlinear remainder the replicas estimate, each with the Monte Carlo noise of the shared histories deconvolved (nuclear_data_replica_spread is before, nuclear_data_noise what was removed). A bin where that noise swamps the estimate reads zero; it is flagged in nuclear_data_noise_dominated, and more particles would resolve it.

nuclear_data_replica_spread property

nuclear_data_replica_spread: Optional[list[float]]

Standard deviation of the replicas per bin as scored, before the Monte Carlo noise is deconvolved, sqrt(sigma**2 + noise**2), when the run was given data_uncertainty; None otherwise.

nuclear_data_noise property

nuclear_data_noise: Optional[list[float]]

Standard deviation of the Monte Carlo noise deconvolved from the replicas' spread per bin, when the run was given data_uncertainty; None otherwise. Each replica's shift from the nominal is scored on the shared histories, which cancel most but not all of its noise; it falls as 1/sqrt(particles).

nuclear_data_noise_dominated property

nuclear_data_noise_dominated: Optional[list[bool]]

Per bin, whether the noise variance deconvolved exceeded a quarter of the nuclear-data variance left (or that variance came out negative), when the run was given data_uncertainty; None otherwise. The sigma is still the deconvolved one; more particles would sharpen it.

replica_mean property

replica_mean: Optional[list[float]]

Average of the cross-section replicas' means per bin, when the run was given data_uncertainty; None otherwise.

mean stays the nominal result. The two differ where the score responds nonlinearly to the cross sections, such as attenuation through a thick shield. The replicas' linear part, whose average is the nominal exactly, is subtracted from them first, so only the nonlinear part is left to their sampling.

nuclear_data_linear_variance property

nuclear_data_linear_variance: Optional[list[float]]

First-order nuclear-data variance per bin, when the run was given data_uncertainty; None otherwise.

The variance of the score's linear response to the cross sections along their principal modes. nuclear_data_standard_deviation is the square root of this plus the nonlinear remainder.

nuclear_data_variance_by_nuclide property

nuclear_data_variance_by_nuclide: Optional[dict[str, list[float]]]

Each nuclide's share of nuclear_data_linear_variance per bin, as a dict from nuclide name to a list over bins, when the run was given data_uncertainty; None otherwise.

The shares add up to the first-order variance: they say which nuclides' cross sections the score's uncertainty comes from.

replica_standard_error property

replica_standard_error: Optional[list[float]]

Monte Carlo standard error of one replica's mean per bin, averaged over replicas, when the run was given data_uncertainty; None otherwise. Much larger than nuclear_data_standard_deviation means the nuclear-data spread is not resolved.

variance property

variance: list[float]

Variance of the mean per bin (standard_deviation**2), computed on the fly. This is the variance of the mean estimate -- the square of the reported uncertainty.

total_count property

total_count: list[int]

Total score per bin over all histories, per source particle times the history count; not scaled by a source strength or units.

shape property

shape: list[int]

Per-dimension sizes (score → nuclide → energy → mesh_z/y/x as applicable).

dim_labels property

dim_labels: list[str]

Dimension names matching shape axes.

covariance property

covariance: Optional[list[list[float]]]

Covariance of the bin means, a num_bins x num_bins nested list in the same bin order as mean, or None unless the tally was built with covariance=True. Its diagonal is standard_deviation squared; for an energy-binned flux tally it is what Pulse(flux_covariance=...) takes.

m2 property

m2: list[float]

Raw per-bin Welford sum of squared deviations, per source particle: the exact merge state behind standard_deviation. Empty when the producing path recorded no Welford state (e.g. GPU runs).

n_histories property

n_histories: int

Exact total source-history count behind this tally's statistics.

elapsed_secs property

elapsed_secs: float

Wall-clock seconds attributed to this tally's data (its producing run, or for a combined result the sum over contributing runs).

figure_of_merit property

figure_of_merit: list[float]

Per-bin figure of merit 1 / (relative_error^2 x elapsed_secs).

aggregate_figure_of_merit property

aggregate_figure_of_merit: float

Tally-level scalar figure of merit of the integrated response.

aggregate_mean property

aggregate_mean: float

Mean of the per-history total score (the tally total), in units. Raises ValueError after a per-volume to, when the bins were divided by different volumes and their total has no unit.

aggregate_std_dev property

aggregate_std_dev: float

Standard error of the per-history total mean (captures within-history correlation between bins), in units. Raises ValueError as aggregate_mean does.

aggregate_relative_error property

aggregate_relative_error: float

Relative error of the per-history total.

aggregate_variance_of_variance property

aggregate_variance_of_variance: float

Variance of the variance of the per-history total -- a sensitive reliability metric (large values flag an unreliable error estimate).

aggregate_skewness property

aggregate_skewness: float

Skewness of the per-history total score distribution.

aggregate_kurtosis property

aggregate_kurtosis: float

Excess kurtosis of the per-history total score distribution.

aggregate_tail_slope property

aggregate_tail_slope: float

Slope of the large-score PDF tail (the tally's variance is well defined only when this exceeds 3). 0.0 if not estimable.

statistical_checks property

statistical_checks: StatisticalChecks

The statistical-reliability checks (pass/fail verdict).

convergence_history property

convergence_history: list[ConvergencePoint]

Aggregate statistics versus number of histories (a list of points), for inspecting convergence. Empty unless the run recorded it.

score_pdf property

score_pdf: ScorePdf

Raw empirical probability density of the per-history total score.

tally property

tally: Tally

Reference back to the input Tally config.

with_source_strength

with_source_strength(strength: Optional[float], per: str = 'second') -> TallyResult

This result scaled to a source strength: source particles per second (per="second", a steady source) or per pulse (per="pulse"). Transport is linear in the source, so no new run is needed.

Returns a new result. Calling it again replaces the strength rather than multiplying by it, and None returns to values per source particle. mean and standard_deviation scale; relative errors and the statistical checks do not change.

Parameters:

Name Type Description Default
strength Optional[float]

Source particles per second or per pulse, or None.

required
per str

"second" (default) or "pulse".

'second'
Source code in yamc/_core/__init__.pyi
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
def with_source_strength(self, strength: typing.Optional[builtins.float], per: builtins.str = 'second') -> TallyResult:
    r"""
    This result scaled to a source strength: source particles per second
    (``per="second"``, a steady source) or per pulse (``per="pulse"``).
    Transport is linear in the source, so no new run is needed.

    Returns a new result. Calling it again replaces the strength rather
    than multiplying by it, and ``None`` returns to values per source
    particle. ``mean`` and ``standard_deviation`` scale; relative errors
    and the statistical checks do not change.

    Args:
        strength: Source particles per second or per pulse, or None.
        per: ``"second"`` (default) or ``"pulse"``.
    """

to

to(units: Any) -> TallyResult

This result in units: one unit for every score, or a list with one per score.

Energies convert between eV, keV, MeV and J (W per second once a strength per second is set, J per pulse for a strength per pulse). A per-volume unit ("W/cm3", "1/(cm2 s)") divides each bin by its volume: the mesh element, or the cell when the cell has a volume. A unit that needs a source strength the result does not have raises ValueError saying so.

Parameters:

Name Type Description Default
units Any

The unit, e.g. "W/cm3", "MeV", "Sv/h".

required

Examples:

>>> heating = results.with_source_strength(5e15)[tally]
>>> heating.to("W/cm3").mean
Source code in yamc/_core/__init__.pyi
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
def to(self, units: typing.Any) -> TallyResult:
    r"""
    This result in ``units``: one unit for every score, or a list with
    one per score.

    Energies convert between eV, keV, MeV and J (W per second once a
    strength per second is set, J per pulse for a strength per pulse).
    A per-volume unit (``"W/cm3"``, ``"1/(cm2 s)"``) divides each bin by
    its volume: the mesh element, or the cell when the cell has a
    ``volume``. A unit that needs a source strength the result does not
    have raises ``ValueError`` saying so.

    Args:
        units: The unit, e.g. ``"W/cm3"``, ``"MeV"``, ``"Sv/h"``.

    Examples:
        >>> heating = results.with_source_strength(5e15)[tally]
        >>> heating.to("W/cm3").mean
    """

summary

summary() -> str

A human-readable multi-line summary: mean +/- std, figure of merit, the higher-moment reliability metrics, and the pass/fail checks.

Source code in yamc/_core/__init__.pyi
6252
6253
6254
6255
6256
def summary(self) -> builtins.str:
    r"""
    A human-readable multi-line summary: mean +/- std, figure of merit,
    the higher-moment reliability metrics, and the pass/fail checks.
    """

to_numpy

to_numpy(field: str = 'mean') -> Any

A tally field reshaped to self.shape as a numpy ndarray.

Parameters:

Name Type Description Default
field str

which array to return -- "mean" (default), "std_dev", "rel_err", "variance", or "count", the names every export uses. The flat getters mean, standard_deviation, relative_error, variance and total_count return the unshaped 1-D lists.

'mean'

Requires numpy -- pip install numpy. Raises ImportError if numpy is not available, or ValueError for an unknown field.

Source code in yamc/_core/__init__.pyi
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
def to_numpy(self, field: builtins.str = 'mean') -> typing.Any:
    r"""
    A tally field reshaped to ``self.shape`` as a numpy ``ndarray``.

    Args:
        field: which array to return -- ``"mean"`` (default),
            ``"std_dev"``, ``"rel_err"``, ``"variance"``, or ``"count"``,
            the names every export uses. The flat getters ``mean``,
            ``standard_deviation``, ``relative_error``, ``variance`` and
            ``total_count`` return the unshaped 1-D lists.

    Requires numpy -- ``pip install numpy``. Raises ``ImportError`` if
    numpy is not available, or ``ValueError`` for an unknown ``field``.
    """

to_xarray

to_xarray(field: Literal['mean', 'std_dev', 'rel_err', 'variance', 'count'] = 'mean') -> Any

Return one tally field as a labelled xarray.DataArray, its unit in attrs['units']. Requires xarray (pip install yamc[xarray]).

Source code in yamc/_core/__init__.pyi
6279
6280
def to_xarray(self, field: typing.Literal["mean", "std_dev", "rel_err", "variance", "count"] = "mean") -> typing.Any:
    r"""Return one tally field as a labelled xarray.DataArray, its unit in attrs['units']. Requires xarray (pip install yamc[xarray])."""

to_dataset

to_dataset() -> Any

Return mean/std_dev/rel_err as one labelled xarray.Dataset, each with attrs['units']. Requires xarray.

Source code in yamc/_core/__init__.pyi
6281
6282
def to_dataset(self) -> typing.Any:
    r"""Return mean/std_dev/rel_err as one labelled xarray.Dataset, each with attrs['units']. Requires xarray."""

TrackEvent

A single step in a particle's recorded track -- e.g. its birth, a collision, or a surface crossing. Exposes the particle and parent IDs, generation, batch and history indices, the event type, position (x, y, z) and direction (u, v, w), incoming and outgoing energy, statistical weight, the cell ID, and (for collisions) the reaction MT and nuclide.

particle_type property

particle_type: str

Particle species, "neutron" or "photon".

to_dict

to_dict() -> dict

Convert to dict for DataFrame creation

Source code in yamc/_core/__init__.pyi
6340
6341
6342
6343
def to_dict(self) -> dict:
    r"""
    Convert to dict for DataFrame creation
    """

TransmutationChain

A parsed transmutation chain.

Wraps the parsed chain data so it can be reused without re-parsing it.

Examples:

>>> chain = yamc.TransmutationChain.from_arrow("transmutation-endf-b8.1-sfr.arrow")
>>> reduced = chain.reduce(["Fe56"])
>>> reduced.nuclide_names

nuclide_names property

nuclide_names: list[str]

List of nuclide names in the chain.

half_lives property

half_lives: Any

Half-lives of the unstable nuclides in the chain.

Returns:

Type Description
Any

dict[str, float]: nuclide name -> half-life in seconds. Stable

Any

nuclides (no half-life) are omitted.

decay_energies property

decay_energies: Any

Mean decay energies of nuclides in the chain.

Returns:

Type Description
Any

dict[str, float]: nuclide name -> mean decay energy in eV. Nuclides

Any

with zero decay energy are omitted.

reactions property

reactions: Any

Neutron-induced reactions of each nuclide in the chain.

Every nuclide in the chain is a key, including those with no reactions. For the decay half of a production route see :attr:decays.

Returns:

Type Description
Any

dict[str, list[tuple[str, str | None, float]]]: nuclide name ->

Any

list of (reaction_type, target, branching_ratio). target is

Any

None for a channel that names no single product, which in

Any

practice means fission. target can also be the parent itself,

Any

where the evaluation's product has no decay data and the chain

Any

builder stepped from it to a nuclide that has: ENDF/B-VIII.1's

Any

Pu245 (n,p) makes Np245, which has none, and the beta- step

Any

from it lands back on Pu245. Such a channel leaves the parent's

Any

count unchanged and makes no product, so a production-route walk

Any

should skip it, as :meth:TransmutationResults.get_production_routes

Any

does.

decays property

decays: Any

Decay modes of each unstable nuclide in the chain.

The other half of a production route. :attr:reactions gives the neutron-induced edge, and a walk with only that stops at the first product: it reaches the Hf183 in W186(n,a)Hf183 and not the beta- step that carries it on to Ta183, or the IT step that turns an isomer into its own ground state. Multi-step routes are what a decay heat pathway analysis is made of.

Same tuple shape as :attr:reactions, and the same underlying ChainReaction, so a walk can concatenate the two into one edge list.

Returns:

Name Type Description
Any

dict[str, list[tuple[str, str | None, float]]]: nuclide name ->

Any

list of (decay_mode, daughter, branching_ratio), the branchings for

Any

one parent summing to 1. Modes carry the evaluation's own

spellings Any

"beta-", "ec/beta+", "alpha", "IT",

Any

"sf", "p", "n", and multi-particle emissions written as

Any

"beta-,n". daughter is None where the chain models no

product Any

on any mode involving spontaneous fission ("sf",

Any

"ec/beta+,sf"), whose fission products the chain does not

Any

carry, on a mode whose stored daughter is the parent itself, and where

Any

the mode's product is outside the chain. The branching is kept, so a

Any

parent still decays at its full half-life and that share of it

Any

leaves the chain. Stable nuclides have no decay modes and are

Any

omitted, as they are from :attr:half_lives.

photon_sources property

photon_sources: Any

Decay photon sources of each nuclide that has them (D1S data).

A source is lines or a continuum, and the two are in different units, so each one says which it is. Each ENDF spectrum is its own source, so a nuclide emitting gammas and x-rays has one line source for each. Each has its own normalisation in the data file, which this tuple does not expose, and the tuple does not say which radiation a source is, so the gamma and x-ray sources cannot be told apart from Python. In data that keeps the spectra apart (decay/sources.arrow with a radiation column), lines are listed as the evaluation writes them: an energy can appear in both sources, and can repeat within one. Older data holds one merged line source per nuclide, sorted by energy with coincident energies summed. Material.decay_photon_spectrum() sums the lines by energy.

Returns:

Type Description
Any

dict[str, list[tuple[str, list[float], list[float], str | None]]]:

Any

nuclide name -> one (type, energies, intensities, interpolation)

Any

per photon source. A "discrete" source lists lines, each

Any

intensity its emission rate per atom [1/s], and its interpolation is

Any

None. A "tabular" one is a continuum: each intensity is the

Any

emission-rate density per atom [1/s/eV] at that energy, read between

Any

energies by interpolation, the ENDF law by name (e.g.

Any

"histogram" or "linear-linear"), which is None where the

Any

data states no law.

from_arrow staticmethod

from_arrow(path: str) -> TransmutationChain

Parse a transmutation chain from a split (v2) chain directory that holds a decay/ subsection subdir, and the reactions/ and fission_yields/ ones where the chain has them.

A chain is a directory of files, so it is read from a path only.

Parameters:

Name Type Description Default
path str

Path to the chain root directory.

required

Examples:

>>> chain = yani.TransmutationChain.from_arrow("chain_dir")
Source code in yamc/_core/__init__.pyi
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
@staticmethod
def from_arrow(path: builtins.str) -> TransmutationChain:
    r"""
    Parse a transmutation chain from a split (v2) chain directory that
    holds a `decay/` subsection subdir, and the `reactions/` and
    `fission_yields/` ones where the chain has them.

    A chain is a directory of files, so it is read from a path only.

    Args:
        path (str): Path to the chain root directory.

    Examples:
        >>> chain = yani.TransmutationChain.from_arrow("chain_dir")
    """

reduce

reduce(nuclides: Sequence[str], level: Optional[int] = None) -> TransmutationChain

Reduce the chain to nuclides reachable from seed nuclides.

By default this walks until the reachable set stops growing, so the result holds every nuclide the seeds can ever produce, no matter how long they are irradiated. Pass level only to build a deliberately truncated chain (a small test fixture, say); a truncated chain will miss inventory at high fluence.

Parameters:

Name Type Description Default
nuclides list[str]

Seed nuclide names.

required
level int | None

Cap on the number of reaction/decay steps to walk. Default None, meaning walk to saturation.

None

Returns:

Name Type Description
TransmutationChain TransmutationChain

Reduced chain containing only reachable nuclides.

Source code in yamc/_core/__init__.pyi
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
def reduce(self, nuclides: typing.Sequence[builtins.str], level: typing.Optional[builtins.int] = None) -> TransmutationChain:
    r"""
    Reduce the chain to nuclides reachable from seed nuclides.

    By default this walks until the reachable set stops growing, so the
    result holds every nuclide the seeds can ever produce, no matter how
    long they are irradiated. Pass ``level`` only to build a deliberately
    truncated chain (a small test fixture, say); a truncated chain will
    miss inventory at high fluence.

    Args:
        nuclides (list[str]): Seed nuclide names.
        level (int | None): Cap on the number of reaction/decay steps to
            walk. Default None, meaning walk to saturation.

    Returns:
        TransmutationChain: Reduced chain containing only reachable nuclides.
    """

to_arrow

to_arrow(path: str) -> None

Write the chain to a split (v2) chain directory with decay/, reactions/ and fission_yields/ subsection subdirs, which :meth:from_arrow reads back. A directory, so a path is required.

Decay modes the chain models no product for (any mode involving spontaneous fission, and a mode whose stored daughter is the parent itself) are written with no target, as :attr:decays reports them. Loading the export gives the same chain, but for those rows the file does not repeat the target the source file stored.

Parameters:

Name Type Description Default
path str

Output directory path.

required
Source code in yamc/_core/__init__.pyi
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
def to_arrow(self, path: builtins.str) -> None:
    r"""
    Write the chain to a split (v2) chain directory with `decay/`,
    `reactions/` and `fission_yields/` subsection subdirs, which
    :meth:`from_arrow` reads back. A directory, so a path is required.

    Decay modes the chain models no product for (any mode involving
    spontaneous fission, and a mode whose stored daughter is the parent
    itself) are written with no target, as :attr:`decays` reports them.
    Loading the export gives the same chain, but for those rows the file
    does not repeat the target the source file stored.

    Args:
        path (str): Output directory path.
    """

TransmutationResults

Results from a transmutation calculation.

Contains material compositions at each timestep for all transmuted materials. Index 0 is the initial composition, index i is after timestep[i-1].

data_gaps property

data_gaps: dict

What the result rests on that the nuclear data does not give, per material ID.

A product whose decay the decay library has no record for is never booked onto another nuclide: its fate is unknown, so it is counted as produced and kept out of the inventory (get_material does not hold it). Fission in a nuclide the library gives no yields for has unknown products. Each material's entry is a dict:

  • decay_library: the decay data the run read, as configured;
  • volume: the material's volume in cm^3, or None;
  • fate_unknown: per nuclide, atoms_per_barn_cm at each state (index 0 is the initial composition), production_rate over each step and activity_bound at each state, both per barn-cm per second, and produced_by ("<parent> <reaction>", "<parent> decay" or "<parent> fission"). The bound holds whatever the half-life: activity is never more than the largest production rate so far, taken here over each step's average;
  • fission_without_yields: per nuclide, its fission_rate in each step, per barn-cm per second;
  • unknown_fission_share: per step, the share of the whole fission rate whose products are unknown.

Every entry names a gap of the library the run read, which is what its evaluators would need to fill it. A material whose answer rests on nothing missing has empty fate_unknown atoms and no fission_without_yields.

times property

times: list[float]

Cumulative times [s] including t=0.

timesteps property

timesteps: list[float]

Timesteps used [s].

collapse_reuse property

collapse_reuse: Optional[dict]

How much of the multigroup collapse work was shared, or None for a transport-coupled solve, which does none.

A dict with performed, the collapses actually run, and requested, one per distinct spectrum per material. Materials with the same spectrum, composition, temperature and shielding collapse to the same rates and share one, so performed below requested is the saving transmute made over solving them one at a time.

data_releases property

data_releases: dict

The nuclear-data release each library keyword came from, and the release of each local release folder data was read from, as a dict keyed by keyword or by the folder's absolute path. Each value is a dict with release (the release identifier), manifest_sha256 (the hash of that release's manifest, which pins every file in it), format_version, offline (True when the data origin was unreachable and the newest complete cached release was used, always False for a local folder), converters (every build that wrote the release's files, as its manifest lists them, such as "yani-python 0.22.1 (core 250c439e...)"; empty for a release published before releases listed them), locally_processed and library. A transmutation subsection read from a local directory that is not a release folder (one convert_transmutation wrote) is keyed by that directory's absolute path, with locally_processed True, library and release the library and data_version its converter recorded, and manifest_sha256 the sha256 of its files. For a release locally_processed is False and library empty.

num_steps property

num_steps: int

Number of transmutation steps.

material_ids property

material_ids: list[int]

List of material IDs that were transmuted.

get_source_rates

get_source_rates(material_id: int) -> Optional[list[float]]

The rate each step drove a material at, one per timestep, zero for a cooldown.

A spectrum solve (Material.transmute, transmute) gives each material's own flux magnitude in n/cm^2/s, which differs between materials given their own schedules. Model.simulate_transmutation gives the source strength in n/s, the same for every material.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required

Returns:

Type Description
Optional[list[float]]

List of rates, or None if the material is not in the results.

Source code in yamc/_core/__init__.pyi
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
def get_source_rates(self, material_id: builtins.int) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    The rate each step drove a material at, one per timestep, zero for a
    cooldown.

    A spectrum solve (``Material.transmute``, ``transmute``) gives each
    material's own flux magnitude in n/cm^2/s, which differs between
    materials given their own schedules. ``Model.simulate_transmutation``
    gives the source strength in n/s, the same for every material.

    Args:
        material_id: Material ID number.

    Returns:
        List of rates, or None if the material is not in the results.
    """

get_uncertainty_breakdown

get_uncertainty_breakdown(material_id: int, nuclide: str, step: int) -> Optional[dict]

Where a nuclide's uncertainty at one step comes from.

Present when the run was asked for it with DataUncertainty(attribution=True), and None otherwise. A dict:

  • variance: the total, resampled, the square of get_nuclide_uncertainty;
  • by_source: each source alone, resampled the same way, so this says how much is statistical and how much is each kind of nuclear data. The sources are independent and these sum to the total;
  • unattributed: what that sum leaves, interaction and sampling noise, small when the attribution holds;
  • contributors: first order, a list of (source, nuclide, reaction, variance), largest reach first. Within the cross sections a nuclide's whole evaluation has reaction of None and each channel alone names it; a half-life has None. A decay branching contributor is a two-mode parent's one degree of freedom, with reaction of None. It says which evaluation to look at; the total is the resampled one.
  • linearity: how well that first order explains the replicas, per source and as "all" for every source together. Each replica's first-order prediction is the nominal plus every sensitivity times that replica's own change in its input, so no extra solve is made. Per entry: r2 (squared correlation between replicas and predictions), residual_share (the share of the variance first order does not account for), by_contributor ({source: {nuclide: r2}}, each contributor's term alone), ranking_agrees (whether the first-order top contributor is also the best correlated), and flagged (residual_share above 0.1, or the ranking disagrees: read the contributors with care). First order has terms only for cross_sections, half_life and decay_branching. None for every other source (flux_spectrum, statistical, decay_energy, decay_photon_lines, fission_yield), and for "all" when any applied source is one of those; absent for a nuclide with no spread. The default source set applies several of them, so with the defaults "all" is None: restrict DataUncertainty(sources=...) to cross_sections, half_life and decay_branching (or a subset) for an "all" entry.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name.

required
step int

As in get_nuclide_uncertainty: 0 is the initial composition, which carries none.

required
Source code in yamc/_core/__init__.pyi
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
def get_uncertainty_breakdown(self, material_id: builtins.int, nuclide: builtins.str, step: builtins.int) -> typing.Optional[dict]:
    r"""
    Where a nuclide's uncertainty at one step comes from.

    Present when the run was asked for it with
    ``DataUncertainty(attribution=True)``, and ``None`` otherwise. A dict:

    - ``variance``: the total, resampled, the square of
      ``get_nuclide_uncertainty``;
    - ``by_source``: each source alone, resampled the same way, so this
      says how much is statistical and how much is each kind of nuclear
      data. The sources are independent and these sum to the total;
    - ``unattributed``: what that sum leaves, interaction and sampling
      noise, small when the attribution holds;
    - ``contributors``: first order, a list of ``(source, nuclide,
      reaction, variance)``, largest reach first. Within the cross sections
      a nuclide's whole evaluation has ``reaction`` of ``None`` and each
      channel alone names it; a half-life has ``None``. A decay branching
      contributor is a two-mode parent's one degree of freedom, with
      ``reaction`` of ``None``. It says which evaluation to look at; the
      total is the resampled one.
    - ``linearity``: how well that first order explains the replicas, per
      source and as ``"all"`` for every source together. Each replica's
      first-order prediction is the nominal plus every sensitivity times
      that replica's own change in its input, so no extra solve is made.
      Per entry: ``r2`` (squared correlation between replicas and
      predictions), ``residual_share`` (the share of the variance first
      order does not account for), ``by_contributor`` (``{source:
      {nuclide: r2}}``, each contributor's term alone), ``ranking_agrees``
      (whether the first-order top contributor is also the best
      correlated), and ``flagged`` (``residual_share`` above 0.1, or the
      ranking disagrees: read the contributors with care). First order has
      terms only for ``cross_sections``, ``half_life`` and
      ``decay_branching``. ``None`` for every other source
      (``flux_spectrum``, ``statistical``, ``decay_energy``,
      ``decay_photon_lines``, ``fission_yield``), and for ``"all"`` when
      any applied source is one of those; absent for a nuclide with no
      spread. The default source set applies several of them, so with the
      defaults ``"all"`` is ``None``: restrict ``DataUncertainty(sources=...)``
      to ``cross_sections``, ``half_life`` and ``decay_branching`` (or a
      subset) for an ``"all"`` entry.

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name.
        step: As in ``get_nuclide_uncertainty``: 0 is the initial
            composition, which carries none.
    """

get_reaction_rate_uncertainty

get_reaction_rate_uncertainty(material_id: int, step: int) -> Optional[list[tuple[str, str, Optional[str], float, float]]]

The statistical uncertainty of each transport-tallied reaction rate at one step.

Present for Model.simulate_transmutation run with data_uncertainty including the "statistical" source, and None otherwise. Each entry is (nuclide, reaction, target, rate, std_dev) in 1/s per atom: a reaction total has target of None, an isomeric partial names its final state. The rates are the tally's, scaled by the step's source rate, exactly as the step's solve used them before the branching fold.

The rates are correlated, having been scored by the same histories, and the inventory sigmas are computed with those correlations. These standard deviations alone do not carry them.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Schedule step index, as in get_reaction_rates.

required
Source code in yamc/_core/__init__.pyi
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
def get_reaction_rate_uncertainty(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[builtins.list[tuple[builtins.str, builtins.str, typing.Optional[builtins.str], builtins.float, builtins.float]]]:
    r"""
    The statistical uncertainty of each transport-tallied reaction rate
    at one step.

    Present for ``Model.simulate_transmutation`` run with
    ``data_uncertainty`` including the ``"statistical"`` source, and
    ``None`` otherwise. Each entry is ``(nuclide, reaction, target, rate,
    std_dev)`` in 1/s per atom: a reaction total has ``target`` of ``None``,
    an isomeric partial names its final state. The rates are the tally's,
    scaled by the step's source rate, exactly as the step's solve used them
    before the branching fold.

    The rates are correlated, having been scored by the same histories,
    and the inventory sigmas are computed with those correlations. These
    standard deviations alone do not carry them.

    Args:
        material_id: Material ID number.
        step: Schedule step index, as in ``get_reaction_rates``.
    """

get_nuclide_evolution

get_nuclide_evolution(material_id: int, nuclide: str) -> Optional[list[float]]

Get the evolution of a specific nuclide over all timesteps.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name (e.g., "Co60").

required

Returns:

Type Description
Optional[list[float]]

List of atom densities [atoms/barn-cm] at each time point

Optional[list[float]]

(index 0 = initial, index i = after step i).

Optional[list[float]]

Returns None if material_id not found.

Source code in yamc/_core/__init__.pyi
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
def get_nuclide_evolution(self, material_id: builtins.int, nuclide: builtins.str) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Get the evolution of a specific nuclide over all timesteps.

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name (e.g., "Co60").

    Returns:
        List of atom densities [atoms/barn-cm] at each time point
        (index 0 = initial, index i = after step i).
        Returns None if material_id not found.
    """

get_nuclide_density

get_nuclide_density(material_id: int, nuclide: str, step: int) -> Optional[float]

Get nuclide density at a specific timestep.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name (e.g., "U235").

required
step int

Timestep index (0 = initial).

required

Returns:

Type Description
Optional[float]

Atom density [atoms/barn-cm] or None if not found.

Source code in yamc/_core/__init__.pyi
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
def get_nuclide_density(self, material_id: builtins.int, nuclide: builtins.str, step: builtins.int) -> typing.Optional[builtins.float]:
    r"""
    Get nuclide density at a specific timestep.

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name (e.g., "U235").
        step: Timestep index (0 = initial).

    Returns:
        Atom density [atoms/barn-cm] or None if not found.
    """

get_nuclide_uncertainty

get_nuclide_uncertainty(material_id: int, nuclide: str, step: int) -> Optional[float]

Get the nuclear-data standard deviation on a nuclide density.

The spread over an ensemble of solves with the activation cross sections resampled from their MF=33 covariance. In the same units as get_nuclide_density, so the pair reads as mean ± sigma. With transport replica weights the Monte Carlo noise of the replicas' tallies is removed from it (see get_nuclide_uncertainty_noise).

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name (e.g., "Mn56").

required
step int

Timestep index (0 = initial).

required

Returns:

Type Description
Optional[float]

Standard deviation [atoms/barn-cm], or None if the transmutation was

Optional[float]

run without data_uncertainty. Step 0 is the initial composition

Optional[float]

and always reports 0.0: it is an input, and perturbing cross sections

Optional[float]

does not move it.

Optional[float]

A nuclide whose evaluation carries no covariance also reports 0.0.

Optional[float]

That is not a claim of certainty -- check

Optional[float]

get_data_uncertainty_info(material_id)["no_covariance_data"],

Optional[float]

which lists exactly

Optional[float]

those nuclides.

Source code in yamc/_core/__init__.pyi
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
def get_nuclide_uncertainty(self, material_id: builtins.int, nuclide: builtins.str, step: builtins.int) -> typing.Optional[builtins.float]:
    r"""
    Get the nuclear-data standard deviation on a nuclide density.

    The spread over an ensemble of solves with the activation cross sections
    resampled from their MF=33 covariance. In the same units as
    ``get_nuclide_density``, so the pair reads as ``mean ± sigma``. With
    transport replica weights the Monte Carlo noise of the replicas'
    tallies is removed from it (see ``get_nuclide_uncertainty_noise``).

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name (e.g., "Mn56").
        step: Timestep index (0 = initial).

    Returns:
        Standard deviation [atoms/barn-cm], or None if the transmutation was
        run without ``data_uncertainty``. Step 0 is the initial composition
        and always reports 0.0: it is an input, and perturbing cross sections
        does not move it.

        A nuclide whose evaluation carries no covariance also reports 0.0.
        That is not a claim of certainty -- check
        ``get_data_uncertainty_info(material_id)["no_covariance_data"]``,
        which lists exactly
        those nuclides.
    """

get_nuclide_uncertainty_standard_error

get_nuclide_uncertainty_standard_error(material_id: int, nuclide: str, step: int) -> Optional[float]

Get the standard error of get_nuclide_uncertainty: how far another ensemble of the same size could put that sigma.

It allows for a heavy tail, through the replicas' sample kurtosis, so a lognormal-tailed density reads as less settled than a Gaussian one at the same replica count.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name.

required
step int

As in get_nuclide_uncertainty.

required

Returns:

Type Description
Optional[float]

The standard error [atoms/barn-cm], or None if the transmutation was

Optional[float]

run without data_uncertainty or with fewer than four replicas.

Optional[float]

Step 0 reports 0.0.

Source code in yamc/_core/__init__.pyi
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
def get_nuclide_uncertainty_standard_error(self, material_id: builtins.int, nuclide: builtins.str, step: builtins.int) -> typing.Optional[builtins.float]:
    r"""
    Get the standard error of ``get_nuclide_uncertainty``: how far another
    ensemble of the same size could put that sigma.

    It allows for a heavy tail, through the replicas' sample kurtosis, so a
    lognormal-tailed density reads as less settled than a Gaussian one at
    the same replica count.

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name.
        step: As in ``get_nuclide_uncertainty``.

    Returns:
        The standard error [atoms/barn-cm], or None if the transmutation was
        run without ``data_uncertainty`` or with fewer than four replicas.
        Step 0 reports 0.0.
    """

get_nuclide_uncertainty_noise

get_nuclide_uncertainty_noise(material_id: int, nuclide: str, step: int) -> Optional[tuple[float, float]]

Get what get_nuclide_uncertainty is made of: the replicas' spread as solved, and the Monte Carlo noise removed from it.

With transport replica weights, each replica's tallied shift from the nominal carries Monte Carlo noise, which inflates the replicas' spread at low history counts. Each replica is then solved a second time from the even half of the transport's histories, and the spread of the difference between the two solves measures that noise, independent of every data draw. get_nuclide_uncertainty is sqrt(replica_spread**2 - noise**2), zero where the noise is the larger.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name.

required
step int

As in get_nuclide_uncertainty.

required

Returns:

Type Description
Optional[tuple[float, float]]

(replica_spread, noise) [atoms/barn-cm], noise 0.0 where it was

Optional[tuple[float, float]]

not measured, or None if the transmutation was run without

Optional[tuple[float, float]]

data_uncertainty. Step 0 reports zeros.

Source code in yamc/_core/__init__.pyi
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
def get_nuclide_uncertainty_noise(self, material_id: builtins.int, nuclide: builtins.str, step: builtins.int) -> typing.Optional[tuple[builtins.float, builtins.float]]:
    r"""
    Get what ``get_nuclide_uncertainty`` is made of: the replicas' spread
    as solved, and the Monte Carlo noise removed from it.

    With transport replica weights, each replica's tallied shift from the
    nominal carries Monte Carlo noise, which inflates the replicas' spread
    at low history counts. Each replica is then solved a second time from
    the even half of the transport's histories, and the spread of the
    difference between the two solves measures that noise, independent of
    every data draw. ``get_nuclide_uncertainty`` is
    ``sqrt(replica_spread**2 - noise**2)``, zero where the noise is the
    larger.

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name.
        step: As in ``get_nuclide_uncertainty``.

    Returns:
        ``(replica_spread, noise)`` [atoms/barn-cm], noise 0.0 where it was
        not measured, or None if the transmutation was run without
        ``data_uncertainty``. Step 0 reports zeros.
    """

get_nuclide_uncertainty_evolution

get_nuclide_uncertainty_evolution(material_id: int, nuclide: str) -> Optional[list[float]]

Get the standard deviation of a nuclide's density at every timestep.

Parallel to get_nuclide_evolution, leading zero included, so the two can be zipped without an index correction.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

Nuclide name.

required

Returns:

Type Description
Optional[list[float]]

List of standard deviations [atoms/barn-cm], or None if the

Optional[list[float]]

transmutation was run without data_uncertainty.

Source code in yamc/_core/__init__.pyi
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
def get_nuclide_uncertainty_evolution(self, material_id: builtins.int, nuclide: builtins.str) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Get the standard deviation of a nuclide's density at every timestep.

    Parallel to ``get_nuclide_evolution``, leading zero included, so the two
    can be zipped without an index correction.

    Args:
        material_id: Material ID number.
        nuclide: Nuclide name.

    Returns:
        List of standard deviations [atoms/barn-cm], or None if the
        transmutation was run without ``data_uncertainty``.
    """

get_uncertainty_inventories

get_uncertainty_inventories(material_id: int, step: int) -> Optional[list[dict[str, float]]]

Every replica's inventory at one timestep.

For a quantity that has to be evaluated per sample rather than from the mean. Activity, decay heat and the decay-photon spectrum are all functions of a whole inventory, so evaluating one of them once per entry here and taking the spread keeps the correlations between nuclides. Taking the mean inventory and evaluating once throws them away, and summing per-nuclide sigmas in quadrature assumes an independence that the resampling exists precisely to avoid assuming.

These are the replicas as solved. With transport replica weights their spread still holds the Monte Carlo noise that the sigmas this class reports have removed (see get_nuclide_uncertainty_noise).

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial, which has no ensemble).

required

Returns:

Type Description
Optional[list[dict[str, float]]]

List of {nuclide: density} dicts, one per replica, or None if the

Optional[list[dict[str, float]]]

transmutation was run without data_uncertainty.

Source code in yamc/_core/__init__.pyi
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
def get_uncertainty_inventories(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[builtins.list[builtins.dict[builtins.str, builtins.float]]]:
    r"""
    Every replica's inventory at one timestep.

    For a quantity that has to be evaluated per sample rather than from the
    mean. Activity, decay heat and the decay-photon spectrum are all
    functions of a whole inventory, so evaluating one of them once per entry
    here and taking the spread keeps the correlations between nuclides.
    Taking the mean inventory and evaluating once throws them away, and
    summing per-nuclide sigmas in quadrature assumes an independence that the
    resampling exists precisely to avoid assuming.

    These are the replicas as solved. With transport replica weights their
    spread still holds the Monte Carlo noise that the sigmas this class
    reports have removed (see ``get_nuclide_uncertainty_noise``).

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial, which has no ensemble).

    Returns:
        List of ``{nuclide: density}`` dicts, one per replica, or None if the
        transmutation was run without ``data_uncertainty``.
    """

get_activity_uncertainty

get_activity_uncertainty(material_id: int, step: int, *, by_nuclide: bool = False) -> Any

Activity at one timestep [Bq], with the nuclear-data spread on it.

Evaluated once per replica and summed within each, so the correlations between nuclides survive. Doing it any other way gives a plausible number that is wrong in a specific direction: evaluating from the mean inventory gives no spread at all, and adding the per-nuclide sigmas in quadrature double-counts a variance that partly cancels, since every Mn56 atom in an irradiated iron foil came out of an Fe56 atom.

The volume is taken from the stored step material, so the nominal value and every replica are scaled by the same one.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition). The composition at step 0 is an input, but each replica evaluates it with its own sampled half-lives, so the activity at step 0 has a spread whenever the "half_life" source is sampled.

required
by_nuclide bool

Return a dict[str, Estimate] instead of one Estimate for the total. These do not add up to the total in quadrature, and are not meant to.

False

Returns:

Type Description
Any

Estimate | dict[str, Estimate] | None: None if the transmutation

Any

was run without data_uncertainty.

Raises:

Type Description
ValueError

if the material has no volume in cm^3, which a quantity in becquerel needs.

Source code in yamc/_core/__init__.pyi
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
def get_activity_uncertainty(self, material_id: builtins.int, step: builtins.int, *, by_nuclide: builtins.bool = False) -> typing.Any:
    r"""
    Activity at one timestep [Bq], with the nuclear-data spread on it.

    Evaluated once per replica and summed within each, so the correlations
    between nuclides survive. Doing it any other way gives a plausible
    number that is wrong in a specific direction: evaluating from the mean
    inventory gives no spread at all, and adding the per-nuclide sigmas in
    quadrature double-counts a variance that partly cancels, since every
    Mn56 atom in an irradiated iron foil came out of an Fe56 atom.

    The volume is taken from the stored step material, so the nominal value
    and every replica are scaled by the same one.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition). The composition at
            step 0 is an input, but each replica evaluates it with its own
            sampled half-lives, so the activity at step 0 has a spread
            whenever the ``"half_life"`` source is sampled.
        by_nuclide (bool): Return a ``dict[str, Estimate]`` instead of one
            ``Estimate`` for the total. These do not add up to the total in
            quadrature, and are not meant to.

    Returns:
        Estimate | dict[str, Estimate] | None: None if the transmutation
        was run without ``data_uncertainty``.

    Raises:
        ValueError: if the material has no ``volume`` in cm^3, which a
            quantity in becquerel needs.
    """

get_decay_heat_uncertainty

get_decay_heat_uncertainty(material_id: int, step: int, *, by_nuclide: bool = False) -> Any

Decay heat at one timestep [W], with the nuclear-data spread on it.

See get_activity_uncertainty: same ensemble, same rule, and the quantity the FNS decay-heat benchmarks are written against. A calculated band beside the measured one is what turns a C/E into a statement about whether the disagreement is larger than the data uncertainty allows.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required

With the "decay_photon_lines" source on, each replica's gamma decay energy E_EM follows its drawn photon lines and continua rather than an independent "decay_energy" draw, so its gamma heat and its contact dose come from the same draw of one evaluation. E_EM moves by the drawn change in the photon energy per decay (each line's energy times its intensity, plus each continuum's energy integral), and the part of E_EM the tabulated spectra do not carry is held at nominal. The beta and alpha parts keep their "decay_energy" draws. The heat then has a range, Estimate.std_dev to Estimate.std_dev_correlated, from the photon intensities' unstated correlations.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition). As in get_activity_uncertainty, step 0 has a spread whenever the "half_life", "decay_energy" or "decay_photon_lines" source is sampled.

required
by_nuclide bool

Return a dict[str, Estimate] of W by nuclide instead of one Estimate for the total.

False

Returns:

Type Description
Any

Estimate | dict[str, Estimate] | None: None if the transmutation

Any

was run without data_uncertainty.

Raises:

Type Description
ValueError

if the material has no volume in cm^3.

Source code in yamc/_core/__init__.pyi
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
def get_decay_heat_uncertainty(self, material_id: builtins.int, step: builtins.int, *, by_nuclide: builtins.bool = False) -> typing.Any:
    r"""
    Decay heat at one timestep [W], with the nuclear-data spread on it.

    See ``get_activity_uncertainty``: same ensemble, same rule, and the
    quantity the FNS decay-heat benchmarks are written against. A calculated
    band beside the measured one is what turns a C/E into a statement about
    whether the disagreement is larger than the data uncertainty allows.

    Args:
        material_id: Material ID number.
    With the ``"decay_photon_lines"`` source on, each replica's gamma decay
    energy E_EM follows its drawn photon lines and continua rather than an
    independent ``"decay_energy"`` draw, so its gamma heat and its contact
    dose come from the same draw of one evaluation. E_EM moves by the drawn
    change in the photon energy per decay (each line's energy times its
    intensity, plus each continuum's energy integral), and the part of E_EM
    the tabulated spectra do not carry is held at nominal. The beta and
    alpha parts keep their ``"decay_energy"`` draws. The heat then has a
    range, ``Estimate.std_dev`` to ``Estimate.std_dev_correlated``, from the
    photon intensities' unstated correlations.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition). As in
            ``get_activity_uncertainty``, step 0 has a spread whenever the
            ``"half_life"``, ``"decay_energy"`` or ``"decay_photon_lines"``
            source is sampled.
        by_nuclide (bool): Return a ``dict[str, Estimate]`` of W by nuclide
            instead of one ``Estimate`` for the total.

    Returns:
        Estimate | dict[str, Estimate] | None: None if the transmutation
        was run without ``data_uncertainty``.

    Raises:
        ValueError: if the material has no ``volume`` in cm^3.
    """

get_contact_dose_uncertainty

get_contact_dose_uncertainty(material_id: int, step: int, *, dose_quantity: str = 'absorbed-air', build_up: float = 2.0, by_nuclide: bool = False) -> Any

Contact dose rate at one timestep, with the nuclear-data spread on it.

The one derived quantity here that is not linear in the atom densities. The material attenuates its own decay photons, so the emitters sit in the numerator and the whole inventory in the denominator: a replica that makes more of an emitter also absorbs more of it. Scaling the nominal dose by the density spread would report the activity's uncertainty, which is wrong by the whole value; evaluating per replica gets the cancellation for free.

Needs no volume, unlike the other three, because the estimate takes the material for a half-space.

The band is the spread of the replicas' inventories (each with its own half-lives when the "half_life" source is on), and of their decay photon line intensities and energies and continuum normalisations when the "decay_photon_lines" source is on. The photon attenuation (XCOM), air energy absorption (NIST SRD 126), ICRP-116 dose coefficients and the build-up factor are held at their nominal values and contribute nothing to it.

With the "decay_photon_lines" source on, the band is a range: Estimate.std_dev takes each nuclide's photon intensities as independent where the decay data state no correlation, and Estimate.std_dev_correlated as fully correlated (the lines of a spectrum, its normalisation and lines, and its gamma and x-ray spectra). ENDF/B-VIII.1 folds each spectrum's normalisation sigma into every line's, so a multi-line emitter's range there is wide; get_data_uncertainty_info names those spectra under decay_photon_spectra_folded.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition). As in get_activity_uncertainty, step 0 has a spread whenever the "half_life" or "decay_photon_lines" source is sampled.

required
dose_quantity str

'absorbed-air' (Gy/h, the default) or 'effective' (Sv/h), as Material.contact_dose takes them.

'absorbed-air'
build_up float

Build-up factor, a plain multiplier on the answer.

2.0
by_nuclide bool

Return a dict[str, Estimate] instead of one Estimate for the total.

False

Returns:

Type Description
Any

Estimate | dict[str, Estimate] | None: None if the transmutation

Any

was run without data_uncertainty.

Source code in yamc/_core/__init__.pyi
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
def get_contact_dose_uncertainty(self, material_id: builtins.int, step: builtins.int, *, dose_quantity: builtins.str = 'absorbed-air', build_up: builtins.float = 2.0, by_nuclide: builtins.bool = False) -> typing.Any:
    r"""
    Contact dose rate at one timestep, with the nuclear-data spread on it.

    The one derived quantity here that is **not** linear in the atom
    densities. The material attenuates its own decay photons, so the
    emitters sit in the numerator and the whole inventory in the
    denominator: a replica that makes more of an emitter also absorbs more
    of it. Scaling the nominal dose by the density spread would report the
    activity's uncertainty, which is wrong by the whole value; evaluating
    per replica gets the cancellation for free.

    Needs no ``volume``, unlike the other three, because the estimate takes
    the material for a half-space.

    The band is the spread of the replicas' inventories (each with its own
    half-lives when the ``"half_life"`` source is on), and of their decay
    photon line intensities and energies and continuum normalisations when
    the ``"decay_photon_lines"`` source is on. The photon attenuation
    (XCOM), air energy absorption (NIST SRD 126), ICRP-116 dose
    coefficients and the build-up factor are held at their nominal values
    and contribute nothing to it.

    With the ``"decay_photon_lines"`` source on, the band is a range:
    ``Estimate.std_dev`` takes each nuclide's photon intensities as
    independent where the decay data state no correlation, and
    ``Estimate.std_dev_correlated`` as fully correlated (the lines of a
    spectrum, its normalisation and lines, and its gamma and x-ray
    spectra). ENDF/B-VIII.1 folds each spectrum's normalisation sigma into
    every line's, so a multi-line emitter's range there is wide;
    ``get_data_uncertainty_info`` names those spectra under
    ``decay_photon_spectra_folded``.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition). As in
            ``get_activity_uncertainty``, step 0 has a spread whenever the
            ``"half_life"`` or ``"decay_photon_lines"`` source is sampled.
        dose_quantity (str): ``'absorbed-air'`` (Gy/h, the default) or
            ``'effective'`` (Sv/h), as ``Material.contact_dose`` takes them.
        build_up (float): Build-up factor, a plain multiplier on the answer.
        by_nuclide (bool): Return a ``dict[str, Estimate]`` instead of one
            ``Estimate`` for the total.

    Returns:
        Estimate | dict[str, Estimate] | None: None if the transmutation
        was run without ``data_uncertainty``.
    """

get_decay_photon_spectrum_uncertainty

get_decay_photon_spectrum_uncertainty(material_id: int, step: int) -> Optional[list[LineEstimate]]

The decay-photon spectrum at one timestep, line by line, with the nuclear-data spread on each emission rate.

Ascending in energy and coincident lines summed, exactly as Material.decay_photon_spectrum returns them, and over the union of the lines the nominal run and every replica emit. A line a replica does not emit counts as a zero in it -- the same rule the densities follow, and the only one under which two lines' spreads are taken over the same sample -- and LineEstimate.emitting reports how many replicas emitted it, which is what the zero-fill would otherwise hide. Lines only, as there: a photon continuum is not a line and is not reported here.

The band is the spread of the replicas' inventories (each with its own half-lives when the "half_life" source is on), and of each line's intensity per decay when the "decay_photon_lines" source is on. That source draws each line's energy too, so lines are matched across replicas on their nominal energy, and LineEstimate.energy_std_dev gives the spread of the energy drawn. A line's rate spread is a range, LineEstimate.std_dev to LineEstimate.std_dev_correlated, for the reason get_contact_dose_uncertainty gives.

>>> lines = results.get_decay_photon_spectrum_uncertainty(mid, step)
>>> [(l.energy, l.nominal, l.std_dev) for l in lines[:2]]

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition). As in get_activity_uncertainty, step 0 has a spread whenever the "half_life" or "decay_photon_lines" source is sampled.

required

Returns:

Type Description
Optional[list[LineEstimate]]

list[LineEstimate] | None: None if the transmutation was run without

Optional[list[LineEstimate]]

data_uncertainty.

Raises:

Type Description
ValueError

if the material has no volume in cm^3.

Source code in yamc/_core/__init__.pyi
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
def get_decay_photon_spectrum_uncertainty(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[builtins.list[LineEstimate]]:
    r"""
    The decay-photon spectrum at one timestep, line by line, with the
    nuclear-data spread on each emission rate.

    Ascending in energy and coincident lines summed, exactly as
    ``Material.decay_photon_spectrum`` returns them, and over the union of
    the lines the nominal run and every replica emit. A line a replica does
    not emit counts as a zero in it -- the same rule the densities follow,
    and the only one under which two lines' spreads are taken over the same
    sample -- and ``LineEstimate.emitting`` reports how many replicas
    emitted it, which is what the zero-fill would otherwise hide. Lines
    only, as there: a photon continuum is not a line and is not reported
    here.

    The band is the spread of the replicas' inventories (each with its own
    half-lives when the ``"half_life"`` source is on), and of each line's
    intensity per decay when the ``"decay_photon_lines"`` source is on.
    That source draws each line's energy too, so lines are matched across
    replicas on their nominal energy, and ``LineEstimate.energy_std_dev``
    gives the spread of the energy drawn. A line's rate spread is a range,
    ``LineEstimate.std_dev`` to ``LineEstimate.std_dev_correlated``, for the
    reason ``get_contact_dose_uncertainty`` gives.

        >>> lines = results.get_decay_photon_spectrum_uncertainty(mid, step)
        >>> [(l.energy, l.nominal, l.std_dev) for l in lines[:2]]

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition). As in
            ``get_activity_uncertainty``, step 0 has a spread whenever the
            ``"half_life"`` or ``"decay_photon_lines"`` source is sampled.

    Returns:
        list[LineEstimate] | None: None if the transmutation was run without
        ``data_uncertainty``.

    Raises:
        ValueError: if the material has no ``volume`` in cm^3.
    """

get_gas_production

get_gas_production(material_id: int, *, produced: bool = True) -> Optional[dict[str, list[float]]]

Hydrogen and helium gas production in appm, at every time point.

appm is gas atoms per million initial atoms of the material, so the denominator stays fixed as the material transmutes. The gas is what the inventory already holds: H1, H2, H3, He3 and He4 emitted by reactions and by decays, so tritium decaying to He3 during a cooldown shows up as He3 there.

>>> gas = results.get_gas_production(material_id=mid)
>>> gas["He4"][-1], gas["H"][-1]

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
produced bool

Subtract the gas the material started with (water, polymers, lithium compounds), the default, so index 0 is zero and each value is what the schedule made by then. A nuclide consumed faster than it is made reads negative, as H1 in water can through H1(n,gamma)H2. False gives the gas present, starting inventory included.

True

Returns:

Type Description
Optional[dict[str, list[float]]]

dict[str, list[float]] | None: appm keyed "H1", "H2",

Optional[dict[str, list[float]]]

"H3", "He3", "He4" and the totals "H" (H1 + H2 + H3)

Optional[dict[str, list[float]]]

and "He" (He3 + He4). Each list is parallel to times, as

Optional[dict[str, list[float]]]

get_nuclide_evolution is: index 0 is the initial composition,

Optional[dict[str, list[float]]]

index i is after step i. None if the material is not in the results.

Raises:

Type Description
ValueError

if the chain the solve used has no entry for one of the five gas nuclides. The solve follows an emitted particle only when the chain has it, so that gas was dropped and a zero would be wrong rather than measured. The message names the missing nuclides.

Source code in yamc/_core/__init__.pyi
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
def get_gas_production(self, material_id: builtins.int, *, produced: builtins.bool = True) -> typing.Optional[builtins.dict[builtins.str, builtins.list[builtins.float]]]:
    r"""
    Hydrogen and helium gas production in appm, at every time point.

    appm is gas atoms per million **initial** atoms of the material, so the
    denominator stays fixed as the material transmutes. The gas is what the
    inventory already holds: H1, H2, H3, He3 and He4 emitted by reactions
    and by decays, so tritium decaying to He3 during a cooldown shows up as
    He3 there.

        >>> gas = results.get_gas_production(material_id=mid)
        >>> gas["He4"][-1], gas["H"][-1]

    Args:
        material_id: Material ID number.
        produced (bool): Subtract the gas the material started with (water,
            polymers, lithium compounds), the default, so index 0 is zero
            and each value is what the schedule made by then. A nuclide
            consumed faster than it is made reads negative, as H1 in water
            can through H1(n,gamma)H2. ``False`` gives the gas present,
            starting inventory included.

    Returns:
        dict[str, list[float]] | None: appm keyed ``"H1"``, ``"H2"``,
        ``"H3"``, ``"He3"``, ``"He4"`` and the totals ``"H"`` (H1 + H2 + H3)
        and ``"He"`` (He3 + He4). Each list is parallel to ``times``, as
        ``get_nuclide_evolution`` is: index 0 is the initial composition,
        index i is after step i. None if the material is not in the results.

    Raises:
        ValueError: if the chain the solve used has no entry for one of the
            five gas nuclides. The solve follows an emitted particle only
            when the chain has it, so that gas was dropped and a zero would
            be wrong rather than measured. The message names the missing
            nuclides.
    """

get_gas_production_uncertainty

get_gas_production_uncertainty(material_id: int, step: int, *, produced: bool = True) -> Optional[dict[str, Estimate]]

Gas production in appm at one timestep, with the nuclear-data spread on it.

See get_gas_production for the quantity. Evaluated on every replica's inventory against the one initial inventory, which is an input and the same in each, and the totals "H" and "He" are summed within a replica before the spread is taken, as get_activity_uncertainty does.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition, which has no spread).

required
produced bool

As in get_gas_production.

True

Returns:

Type Description
Optional[dict[str, Estimate]]

dict[str, Estimate] | None: keyed as get_gas_production; None if

Optional[dict[str, Estimate]]

the transmutation was run without data_uncertainty.

Raises:

Type Description
ValueError

as get_gas_production, or if there is no such step.

Source code in yamc/_core/__init__.pyi
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
def get_gas_production_uncertainty(self, material_id: builtins.int, step: builtins.int, *, produced: builtins.bool = True) -> typing.Optional[builtins.dict[builtins.str, Estimate]]:
    r"""
    Gas production in appm at one timestep, with the nuclear-data spread
    on it.

    See ``get_gas_production`` for the quantity. Evaluated on every
    replica's inventory against the one initial inventory, which is an
    input and the same in each, and the totals ``"H"`` and ``"He"`` are
    summed within a replica before the spread is taken, as
    ``get_activity_uncertainty`` does.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition, which has no spread).
        produced (bool): As in ``get_gas_production``.

    Returns:
        dict[str, Estimate] | None: keyed as ``get_gas_production``; None if
        the transmutation was run without ``data_uncertainty``.

    Raises:
        ValueError: as ``get_gas_production``, or if there is no such step.
    """

get_data_uncertainty_info

get_data_uncertainty_info(material_id: int) -> Optional[dict]

What the nuclear-data uncertainty covered for one material, and what it did not.

None when the transmutation was run without data_uncertainty, or the material is not in the results. Otherwise a dict whose job is to make gaps visible rather than let them read as confidence:

  • perturbed / no_covariance_data: which nuclides had usable MF=33 covariance and which had none.
  • rate_fraction_covered_total: the per-channel shares below, averaged with each channel weighted by the production it drove (the rate this run used times parent density): the share of the production driven from energies where a covariance states a nonzero variance. None on a decay-only schedule; on a transport run, where the shares are of the dilute rate over the tally spectrum and the covered share of the tallied production is not computed; and under the 1/E within-group weight (Rust API only), whose shares are not exact where a covariance edge cuts a group. None too when a channel is listed in partials_above_rate or partials_below_rate, whose rate is not the one its share is of: the (n,n') of a nuclide with a metastable, whose rate is the MF=10 production of the metastables while its covariance is MT 4's. Read this before any sigma here. It is a different and much sharper question than how many nuclides carry MF=33: an evaluation can state covariance for every isotope in the material and none for the channel making the product of interest, and the count then reads as full coverage while the ensemble perturbs almost nothing.
  • rate_fraction_covered: per nuclide and channel, the share of the reaction rate from energies where the evaluation states a nonzero variance for it, the rate being the dilute one on a dilute run and the shielded one on a self-shielded run. Below one means part of the rate carries no stated uncertainty and dilutes the sigma; on a transport run it is a share of the dilute rate over the tally spectrum, and the dilution applied differs from it. An interval the covariance grid spans with a variance of zero counts as uncovered: ENDF/B-VIII.1 W186 (n,gamma) states zero from 1e-5 eV to 10 keV, where nearly all of its capture rate is. Every consumed self-covariance block counts where it states a nonzero variance, relative (LB=1 to 6), absolute (LB=0) and short-range (LB=8) alike. Exact under the default flat within-group weight; under the 1/E weight (Rust API only) the rate of a group a covariance edge cuts is split by energy width, not lethargy, so the share is off there.
  • partials_above_rate: per nuclide and channel, where the partial rates the covariance was weighted with, zero variance intervals included, add up to more than the rate it was divided by, their ratio to it. Each entry is a channel whose sigma is overstated. Three known causes: a tallied rate on a transport run, which the transport can self-shield within its bins, against partials weighted flat within each bin; a grafted (n,n'), whose rate is the metastables' MF=10 production while the partials are MT 4's; and the 1/E within-group weight (Rust API only) with a covariance edge inside a group. The share in rate_fraction_covered is of the fold's own rate, not of the listed rate, and under the 1/E weight it is off as well wherever an edge cuts a group. On a channel derived through an NC block, the partials of the reactions the block names are checked the same way, and the check is also that they add up to the one it derives over the block's range; a sum above it lands here.
  • partials_below_rate: keyed the same way, where a covariance grid spans the whole flux range and its partial rates add up to less than the rate, their ratio to it: a channel whose sigma is understated. The 1/E weight gives one for a reaction falling with energy when a covariance edge cuts a group. A grid that stops short of the flux range cannot be checked from below, since rate from outside it rightly leaves its partials short. A derived channel whose NC block names reactions adding up to less than the one it derives lands here too: ENDF/B-VIII.1 O16 (n,d) above 20 MeV, whose cross section holds MT 660 to 669 while the block names 650 to 659.
  • derived_opposing_uncorrelated: keyed the same way, for a channel derived through an NC block whose terms name two reactions with opposite signs, each with a variance of its own, and no covariance between them: the [a, b] pairs. The absent block is read as zero, since ENDF-102 33.3.2 a.1 lets a tape leave a zero covariance unstated, and with opposing signs that reading sets the sigma. FENDL-3.2d and TENDL-2017 H2 (n,2n) is σ_1 - σ_2 - σ_102 and folds to about 22% at 14 MeV and thousands of percent near threshold, the tape's literal statement. Counted in has_gaps.
  • lumped_covariance_not_assignable: keyed "Nuclide MT852", a lumped reaction (MT 851-870) with several components, to their kinds ("MT91" for one that is not a channel). ENDF-102 33.2.3 states its covariance for the sum of the components and for none of them. A lump with one component is that component, and its covariance is folded as the component's. A lump an LTY=0 block names is folded through that derivation, with its cross section the sum of its components': ENDF/B-VIII.1 and TENDL-2017 U235 and U238 MT 4 is MT 51 plus MT 851. A component with no covariance of its own takes the lump's relative perturbation, so the components of one lump move together and their sum moves as the lump's covariance states, as NJOY's ERRORR leaves a lump and SANDY applies it: ENDF/B-VIII.1, FENDL-3.2d and JEFF-4.0 W180 to W186 give (n,2n) only as MT 852, the sum of MT 16 and 41. A level sum with no covariance of its own is derived from its levels, each reading its own blocks or its lump's, so W186 (n,p) reads MT 855, the sum of MT 600 and 649. Listed here is only a lump with a block that is not relative, absolute or short-range, which states the sum's spread in barns and nothing of how it splits, where the fold reaches a component; no library yani reads has one. Counted in has_gaps.
  • unsupported_layouts: covariance blocks that were present but not consumed, counted once per spectrum, so a run over several spectra counts the same block once for each.
  • skipped_nc: per nuclide, NC blocks (a covariance derived from other reactions) that could not be derived. An LTY=0 block is derived from the NI covariances of the reactions it names, cross blocks included, over its own energy range: ENDF/B-VIII.1 O16 (n,p) is stated only that way. Left here are LTY 1 to 4 (a covariance from a measurement's ratio to another evaluation's standard, which no library yani reads states), a block in a cross-reaction subsection, one whose list of reactions is empty or does not match its coefficients, one whose own energy range is empty, one naming a reaction with no cross section, and one met only circularly.
  • skipped_cross_material: per nuclide, blocks on a reaction the fold reaches (a channel, or one a channel is derived from) that correlate it with another evaluation, not applied: the evaluation they name is not in the run (or carries no covariance, so its MAT is not known), or one of the two reactions has no relative covariance to correlate. A block naming the nuclide's own MAT is its own evaluation and is folded. applied_cross_material: the same count for the blocks applied, whose two nuclides are drawn jointly, one draw per replica shared by every material of the run. skipped_other_file: blocks whose partner is not a cross section, which no library yani reads states.
  • mirrored_disagree: keyed "Nuclide (n,a) (n,b)", where a pair stored in both orientations has copies that are not each other's transpose, the largest difference relative to the largest entry. The copy in the lower MT's section is the one folded.
  • malformed_blocks: covariance blocks not consumed because they break ENDF-102's rules for their layout: arrays that disagree with their declared sizes, an LB=0 to 2 block carrying a second energy table, an LB=3 or 4 block without one or whose tables share no energy range, or an LB=8 variance stated between two reactions.
  • covariance_source: where each perturbed nuclide's covariance came from, "<library>, MAT <n>", the library being the one its data folder records ("unknown" when none is recorded).
  • covariance_warnings: perturbed nuclides whose library documents a problem with this covariance, each with what it says and where: every FENDL-3.2 covariance, which its own paper says should not be used, and the ENDF/B-VIII.1 evaluations its release paper names (Fe, Cr covariances reused from VIII.0; Cu with no fast-range covariance; Ta, W, Pb resolved-resonance covariance flagged as too low; the Ta181 unresolved covariance overwritten). The evaluation is still sampled as it is; any warning makes has_gaps true.
  • covariance_repaired: nuclides the material can populate (bounded at or above the solver's density floor over the schedule at nominal rates; a replica's rates can sit above them) whose evaluated cell covariance was not positive semi-definite past round-off, with a channel a draw can move (a positive rate on a spectrum the schedule irradiates with). Past round-off means the correlation matrix of the cells has an eigenvalue below -m * 1e-12 (m the number of cells with a positive stated variance), or a cell is stated with a negative variance, or a zero one and a covariance to another cell. The correlation matrix is replaced by the nearest correlation matrix and rescaled by the evaluated sigmas, so every cell keeps its evaluated sigma and only correlations move (a cell stated at zero or negative variance is held at nominal); a channel folding several cells can still be sampled at a sigma other than its evaluation's, either way, and any makes has_gaps true. covariance_repairs gives one dict per repaired populated nuclide and spectrum, including repairs no draw can move, with lambda_min (the most negative eigenvalue of the cells' correlation matrix before the repair), largest_correlation_change and correlation_frobenius_change (the largest and the Frobenius change of that correlation matrix), cells (in the coupled blocks repaired), held_cells, converged and, per channel keyed by kind, evaluated_variance (the folded diagonal as stated, which can be negative), evaluated_sigma (None when that variance is negative) and sampled_sigma. A repair of a nuclide outside the populated bound has no dict; covariance_repaired_outside_bound names those with a channel a draw can move. The bound holds at nominal rates only and a replica's rates can populate them, so any also makes has_gaps true.
  • worst_sigma_change: the largest |sampled / evaluated sigma - 1| over the repaired channels of populated nuclides with a positive rate on a spectrum the schedule irradiates with, float('inf') when a repair gave a spread to a channel whose stated variance is zero or negative. rate_weighted_sigma_change is the weighted mean of |sampled / evaluated sigma - 1| over every sampled channel of a populated nuclide, each weighted by its unit-flux rate times its spectrum's fluence in the schedule times its parent's initial density, so it covers first-generation reactions only (a produced nuclide carries no weight), shows the decomposition's round-off on matrices that needed no repair, and is None when no weighted channel has an evaluated sigma. Both can be float('inf'), which strict JSON does not accept.
  • sigma_at_least_one / sigma_at_least_ten: sampled channels of populated nuclides with a positive rate on a spectrum the schedule irradiates with, keyed "Nuclide (n,x)", whose folded relative sigma as evaluated, before any repair, is at least one or ten. At that width the answer depends on the lognormal chosen to carry the evaluation's two moments, not on the evaluation alone. sigma_at_least_one_outside_bound is the same for nuclides outside the populated bound, whose wide channels a replica's draw can take past it; the ten-or-more subset reads off its values.
  • lognormal_not_carried: nuclides whose evaluated relative covariance is not a lognormal's, keyed by nuclide, each with cells (cells whose sampled sigma or correlation differs from the evaluated one), largest_sigma_change (the largest |sampled / evaluated sigma - 1|), largest_correlation_change and log_space_repair (None, or a dict with the keys of a repair above, of the log-space correlation matrix). Two fully correlated cells with different sigmas, or an anticorrelation with 1 + C <= 0, are not, and the nearest lognormal is sampled: where the log-space covariance is not PSD its correlation matrix is replaced by the nearest correlation matrix, which keeps every sigma. A property of the distribution rather than a defect of the data, so not a gap. flux_lognormal_not_carried is the same for a stated flux covariance, keyed by spectrum index, whose log_space_repair is always None: a flux covariance's log-space negative eigenvalues are clipped.
  • cross_material_adjusted: keyed by a group of nuclides drawn jointly through cross-material covariance, their names joined by + ("U235+U238"), where the covariance stated between their interval averages is not admissible beside each one's own and the closest admissible one was drawn instead, each own covariance kept exactly and the correlations between the averages fitted to the stated ones (each clipped to one first) in the Frobenius norm: relative_change (||X' - X|| / ||X|| of the drawn against the stated log-space covariance between the averages), least_relative_change (the same with each stated entry only clipped to a correlation of one: no admissible draw goes below it), largest_stated_correlation (past one where an entry alone is inadmissible), largest_correlation_change (the largest move of a correlation from its stated value clipped to one), iterations and converged (the fit's; its result is admissible either way). ENDF/B-VIII.1 U235 and U238 fission read about 0.31. Counted in has_gaps.
  • rates_sampled: cross-section rate draws made, each read off one draw of the nuclide's cross sections. rates_floored counts those that came out negative and were floored at zero, which only a channel subtracting reactions or reading an additive (absolute or short-range) covariance can.
  • cross_section_points_floored: with method="coupled", the cross-section grid values a replica's draw took below zero and that were floored at zero, over every replica.
  • half_lives_perturbed / no_half_life_uncertainty: with the "half_life" source, which reachable unstable nuclides had their half-life sampled and which state no sigma to sample from. half_life_uncertainty_not_carried names those whose stated sigma no draw can carry (not finite, or not finite relative to the half-life), held at nominal and counted as a gap. half_lives_sampled counts the draws made. Each is a lognormal matched to the evaluation's mean and sigma, so none can go non-positive and none is floored.
  • decay_energies_perturbed / no_decay_energy_uncertainty: the same for the "decay_energy" source, drawn per nuclide as a lognormal with the stated mean and sigma, per component where the data splits it. decay_energy_uncertainty_not_carried names those with a sigma stated on a zero energy, or not finite, which no draw can carry; that energy is held at nominal and counted as a gap.
  • decay_photon_lines_perturbed / no_decay_photon_line_uncertainty: the same for the "decay_photon_lines" source, over the reachable unstable nuclides with decay photon data. decay_photon_line_uncertainty_not_carried names those with a sigma stated on a zero value, or not finite, which no draw can carry; that value is held at nominal and counted as a gap. decay_photon_spectra_folded maps each perturbed nuclide with a spectrum written the ENDF/B way (a normalisation of 1 with no sigma, its sigma folded into every line's dRI) to the radiation of each such spectrum ("gamma", "xray"). How much of those dRI the lines share is not stated, so they are where most of the range between a photon output's std_dev and std_dev_correlated comes from.
  • fission_yields_perturbed / no_fission_yield_uncertainty: the same for the "fission_yield" source, over the reachable parents the run gives a fission rate (one that never fissions is not drawn). fission_yield_uncertainty_not_carried names those with a DY on a zero yield, or not finite, which is held while the parent's other yields are drawn. fission_yields_mapping_mismatch names those whose tape yields, named and summed by the converter's rule, do not give back the yields the solver reads; they are held rather than drawn through a mapping their yields were not built with. Each is counted as a gap.
  • decay_branchings_perturbed: with the "decay_branching" source, the reachable multi-mode parents whose split was sampled. Held at their evaluated ratios, each a gap: no_decay_branching_uncertainty (no mode states a sigma, or one does beside two or more that do not) and decay_branchings_too_wide (every mode that could move states a sigma no ratio with its mean can have). Sampled but short of the stated sigmas, each a gap too: decay_branchings_partly_held (one or more modes held at their ratios, for such a sigma or for stating none) and decay_branchings_sigma_adjusted (a mode drawn more than 0.1% from its stated sigma: the largest exceeds the sum of the others', or the complement's needs a correlation non-negative ratios cannot carry). decay_branchings_floored / decay_branchings_sampled count draws whose complement was pulled back above zero and draws made.
  • isomer_branchings_perturbed: with the "isomer_branching" source, the reachable reactions, as "Parent reaction", whose isomeric split was drawn from the MF=40 covariance of at least one of their final states. no_isomer_branching_uncertainty lists those whose split can move but whose evaluation states no MF=40 on any state the run folds, held at their nominal shares, a gap. isomer_branching_blocks_not_used gives, per parent, the MF=40 blocks not used, counted by why, a gap. isomer_branching_covariance_repaired and isomer_branching_lognormal_not_carried are the MF=40 matrices repaired to the nearest correlation matrix (a gap) and those not a lognormal's (not a gap), with the same entries as covariance_repairs and lognormal_not_carried. isomer_production_sigma gives, as "Parent reaction Product", the relative sigma MF=40 states for the product's production, folded against the spectrum (the largest over the run's spectra). isomer_branchings_sampled counts the draws, one per drawn parent per replica. isomer_branchings_clipped gives, as "Parent reaction Product", how many list draws (one per replica per spectrum) scaled the product's drawn production back to the drawn reaction total, the stated productions of its list having come out above it; a product never clipped is absent.
  • damage_energy: with displacement_damage=True and the "cross_sections" source, per nuclide of the starting composition {"explained": ..., "sigma": ...}: the share of its stored MT=444 rate its reactions' deposits reproduce, the part a draw moves (the rest, fission's share above all, is held, a gap), and the relative sigma of its drawn damage-energy rate, each weighted over the spectra by fluence.
  • statistical_rates: with the "statistical" source on a transport run, how many tallied rates were sampled from their covariance; statistical_floored / statistical_sampled count draws that came out negative and were floored.
  • resonance_parameters: per nuclide with resonance parameters (MF=2 and MF=32) and a rate in this run, how its resonance-range uncertainty was sampled. method is "parameters sampled" (drawn per replica and the cross sections rebuilt from them, on a transport run against the flux it tallied through the resonances) or "first-order rows" (the MF=32 rows of covariance.arrow), reason why the parameters were not sampled (None where they were), and ranges one sampler report per sampled range: isotope and range indices, the gaussian, lognormal and held parameter counts, zero_mean_widths (widths stated with a zero mean and a nonzero sigma, held at zero) and negative_mean_widths (drawn as signed), each with index, location, quantity, value and sigma, zero_variance_with_covariance, unattainable_pairs, and stated_repair / transformed_repair (the nearest-correlation repair of the stated and of the log-space matrix, each with lambda_min, frobenius_change, max_change, parameters, iterations and converged, None where none was needed). How far the draws' parameter correlations are from the evaluated ones, in the parameters themselves after both repairs and the lognormal transform, reads off largest_correlation_change (the largest change of one correlation) and correlation_frobenius_change, per range and per nuclide over its ranges; every drawn parameter keeps its evaluated mean and sigma, so that is the whole of the difference in the first two moments. Widths stay lognormal, so a pair no lognormal carries (unattainable_pairs) is where it is largest. Empty on a transport run, which keeps the rows.
  • not_perturbed: every input this run held at its nominal value, such as any MF=32 resonance-parameter covariance neither sampled nor in the library's covariance.arrow, the photon and dose data, the material composition, any source switched off, and, where they applied, the self-shielding correction, the flux's response to a perturbed cross section on a transport run, and the per-branch decay emission of a parent whose branching was drawn.
  • samples / converged / convergence / hit_cap / unconverged: how many replicas ran; whether every tracked sigma reached the target, convergence, for the standard error of a sigma relative to it; whether the 1024-replica cap stopped the run first; and, worst first, every sigma that missed, as dicts of output ("density", "activity", "decay_heat" or "decay_photon_rate"), nuclide (None for a total), step and the relative_standard_error it reached. Listed with a fixed samples too, where hit_cap is never set.
  • noise_removed / noisy: whether the Monte Carlo noise in the replicas' spread was measured and removed from every sigma (with transport replica weights, each replica is solved a second time from the even half of the transport's histories, see get_nuclide_uncertainty_noise), and, the largest share first, every tracked sigma whose removed noise variance exceeded a quarter of the variance left, as dicts of output, nuclide, step, replica_spread, noise and std_dev (the sigma reported). Those sigmas would sharpen most with more transport histories.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
Source code in yamc/_core/__init__.pyi
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
def get_data_uncertainty_info(self, material_id: builtins.int) -> typing.Optional[dict]:
    r"""
    What the nuclear-data uncertainty covered for one material, and what it
    did not.

    ``None`` when the transmutation was run without ``data_uncertainty``, or
    the material is not in the results.
    Otherwise a dict whose job is to make gaps visible rather than let them
    read as confidence:

    - ``perturbed`` / ``no_covariance_data``: which nuclides had usable
      MF=33 covariance and which had none.
    - ``rate_fraction_covered_total``: the per-channel shares below,
      averaged with each channel weighted by the production it drove (the
      rate this run used times parent density): the share of the
      production driven from energies where a covariance states a nonzero
      variance. ``None`` on a decay-only schedule; on a transport run,
      where the shares are of the dilute rate over the tally spectrum and
      the covered share of the tallied production is not computed; and
      under the ``1/E`` within-group weight (Rust API only), whose shares
      are not exact where a covariance edge cuts a group. ``None`` too when
      a channel is listed in ``partials_above_rate`` or
      ``partials_below_rate``, whose rate is not the one its share is of:
      the ``(n,n')`` of a nuclide with a metastable, whose rate is the
      MF=10 production of the metastables while its covariance is MT 4's.
      Read this before any sigma here. It is a different and much sharper
      question than how many nuclides carry MF=33: an evaluation can state
      covariance for every isotope in the material and none for the
      channel making the product of interest, and the count then reads as
      full coverage while the ensemble perturbs almost nothing.
    - ``rate_fraction_covered``: per nuclide and channel, the share of the
      reaction rate from energies where the evaluation states a nonzero
      variance for it, the rate being the dilute one on a dilute run and
      the shielded one on a self-shielded run. Below one means part of the
      rate carries no stated uncertainty and dilutes the sigma; on a
      transport run it is a share of the dilute rate over the tally
      spectrum, and the dilution applied differs from it. An
      interval the covariance grid spans with a variance of zero counts as
      uncovered: ENDF/B-VIII.1 W186 ``(n,gamma)`` states zero from 1e-5 eV
      to 10 keV, where nearly all of its capture rate is. Every consumed
      self-covariance block counts where it states a nonzero variance,
      relative (LB=1 to 6), absolute (LB=0) and short-range (LB=8) alike.
      Exact under the default flat within-group weight; under the ``1/E``
      weight (Rust API only) the rate of a group a covariance edge cuts is
      split by energy width, not lethargy, so the share is off there.
    - ``partials_above_rate``: per nuclide and channel, where the partial
      rates the covariance was weighted with, zero variance intervals
      included, add up to more than the rate it was divided by, their
      ratio to it. Each entry is a channel whose sigma is overstated. Three
      known causes: a tallied rate on a transport run, which the transport
      can self-shield within its bins, against partials weighted flat
      within each bin; a grafted ``(n,n')``, whose rate is the metastables'
      MF=10 production while the partials are MT 4's; and the ``1/E``
      within-group weight (Rust API only) with a covariance edge inside a
      group. The share in ``rate_fraction_covered`` is of the fold's own
      rate, not of the listed rate, and under the ``1/E`` weight it is off
      as well wherever an edge cuts a group. On a channel derived through
      an NC block, the partials of the reactions the block names are
      checked the same way, and the check is also that they add up to the
      one it derives over the block's range; a sum above it lands here.
    - ``partials_below_rate``: keyed the same way, where a covariance grid
      spans the whole flux range and its partial rates add up to less than
      the rate, their ratio to it: a channel whose sigma is understated.
      The ``1/E`` weight gives one for a reaction falling with energy when
      a covariance edge cuts a group. A grid that stops short of the flux
      range cannot be checked from below, since rate from outside it
      rightly leaves its partials short. A derived channel whose NC block
      names reactions adding up to less than the one it derives lands here
      too: ENDF/B-VIII.1 O16 ``(n,d)`` above 20 MeV, whose cross section
      holds MT 660 to 669 while the block names 650 to 659.
    - ``derived_opposing_uncorrelated``: keyed the same way, for a channel
      derived through an NC block whose terms name two reactions with
      opposite signs, each with a variance of its own, and no covariance
      between them: the ``[a, b]`` pairs. The absent block is read as zero,
      since ENDF-102 33.3.2 a.1 lets a tape leave a zero covariance
      unstated, and with opposing signs that reading sets the sigma.
      FENDL-3.2d and TENDL-2017 H2 ``(n,2n)`` is ``σ_1 - σ_2 - σ_102`` and
      folds to about 22% at 14 MeV and thousands of percent near
      threshold, the tape's literal statement. Counted in ``has_gaps``.
    - ``lumped_covariance_not_assignable``: keyed ``"Nuclide MT852"``, a
      lumped reaction (MT 851-870) with several components, to their kinds
      (``"MT91"`` for one that is not a channel). ENDF-102 33.2.3 states
      its covariance for the sum of the components and for none of them. A
      lump with one component is that component, and its covariance is
      folded as the component's. A lump an LTY=0 block names is folded
      through that derivation, with its cross section the sum of its
      components': ENDF/B-VIII.1 and TENDL-2017 U235 and U238 MT 4 is MT 51
      plus MT 851. A component with no covariance of its own takes the
      lump's relative perturbation, so the components of one lump move
      together and their sum moves as the lump's covariance states, as
      NJOY's ERRORR leaves a lump and SANDY applies it: ENDF/B-VIII.1,
      FENDL-3.2d and JEFF-4.0 W180 to W186 give ``(n,2n)`` only as MT 852,
      the sum of MT 16 and 41. A level sum with no covariance of its own is
      derived from its levels, each reading its own blocks or its lump's,
      so W186 ``(n,p)`` reads MT 855, the sum of MT 600 and 649. Listed
      here is only a lump with a block that is not relative, absolute or
      short-range, which states the sum's spread in barns and nothing of how
      it splits, where the fold reaches a component; no library yani reads
      has one. Counted in ``has_gaps``.
    - ``unsupported_layouts``: covariance blocks that were present but not
      consumed, counted once per spectrum, so a run over several spectra
      counts the same block once for each.
    - ``skipped_nc``: per nuclide, NC blocks (a covariance derived from
      other reactions) that could not be derived. An LTY=0 block is
      derived from the NI covariances of the reactions it names, cross
      blocks included, over its own energy range: ENDF/B-VIII.1 O16
      ``(n,p)`` is stated only that way. Left here are LTY 1 to 4 (a
      covariance from a measurement's ratio to another evaluation's
      standard, which no library yani reads states), a block in a
      cross-reaction subsection, one whose list of reactions is empty or
      does not match its coefficients, one whose own energy range is empty,
      one naming a reaction with no cross section, and one met only
      circularly.
    - ``skipped_cross_material``: per nuclide, blocks on a reaction the
      fold reaches (a channel, or one a channel is derived from) that
      correlate it with another evaluation, not applied: the evaluation
      they name is not in the run (or carries no covariance, so its MAT is
      not known), or one of the two reactions has no relative covariance to
      correlate. A block naming the nuclide's own MAT is its own evaluation
      and is folded. ``applied_cross_material``: the same count for the
      blocks applied, whose two nuclides are drawn jointly, one draw per
      replica shared by every material of the run. ``skipped_other_file``:
      blocks whose partner is not a cross section, which no library yani
      reads states.
    - ``mirrored_disagree``: keyed ``"Nuclide (n,a) (n,b)"``, where a pair
      stored in both orientations has copies that are not each other's
      transpose, the largest difference relative to the largest entry.
      The copy in the lower MT's section is the one folded.
    - ``malformed_blocks``: covariance blocks not consumed because they
      break ENDF-102's rules for their layout: arrays that disagree with
      their declared sizes, an LB=0 to 2 block carrying a second energy
      table, an LB=3 or 4 block without one or whose tables share no
      energy range, or an LB=8 variance stated between two reactions.
    - ``covariance_source``: where each perturbed nuclide's covariance came
      from, ``"<library>, MAT <n>"``, the library being the one its data
      folder records (``"unknown"`` when none is recorded).
    - ``covariance_warnings``: perturbed nuclides whose library documents
      a problem with this covariance, each with what it says and where:
      every FENDL-3.2 covariance, which its own paper says should not be
      used, and the ENDF/B-VIII.1 evaluations its release paper names (Fe,
      Cr covariances reused from VIII.0; Cu with no fast-range covariance;
      Ta, W, Pb resolved-resonance covariance flagged as too low; the Ta181
      unresolved covariance overwritten). The evaluation is still sampled as
      it is; any warning makes ``has_gaps`` true.
    - ``covariance_repaired``: nuclides the material can populate (bounded
      at or above the solver's density floor over the schedule at nominal
      rates; a replica's rates can sit above them) whose evaluated cell
      covariance was not positive semi-definite past round-off, with a
      channel a draw can move (a positive rate on a spectrum the schedule
      irradiates with). Past round-off means the correlation matrix of the
      cells has an eigenvalue below ``-m * 1e-12`` (``m`` the number of
      cells with a positive stated variance), or a cell is stated with a
      negative variance, or a zero one and a covariance to another cell.
      The correlation matrix is replaced by the nearest correlation
      matrix and rescaled by the evaluated sigmas, so every cell keeps its
      evaluated sigma and only correlations move (a cell stated at zero or
      negative variance is held at nominal); a channel folding several
      cells can still be sampled at a sigma other than its evaluation's,
      either way, and any makes ``has_gaps`` true.
      ``covariance_repairs`` gives one dict per repaired populated nuclide
      and spectrum, including repairs no draw can move, with ``lambda_min``
      (the most negative eigenvalue of the cells' correlation matrix before
      the repair), ``largest_correlation_change`` and
      ``correlation_frobenius_change`` (the largest and the Frobenius
      change of that correlation matrix), ``cells`` (in the coupled blocks
      repaired), ``held_cells``, ``converged`` and, per channel keyed by
      kind,
      ``evaluated_variance`` (the folded diagonal as stated, which can be
      negative), ``evaluated_sigma`` (``None`` when that variance is
      negative) and ``sampled_sigma``. A repair of a nuclide outside the
      populated bound has no dict; ``covariance_repaired_outside_bound``
      names those with a channel a draw can move. The bound holds at
      nominal rates only and a replica's rates can populate them, so any
      also makes ``has_gaps`` true.
    - ``worst_sigma_change``: the largest ``|sampled / evaluated sigma -
      1|`` over the repaired channels of populated nuclides with a
      positive rate on a spectrum the schedule irradiates with,
      ``float('inf')`` when a repair gave a spread to a channel whose stated
      variance is zero or negative. ``rate_weighted_sigma_change`` is the
      weighted mean of ``|sampled / evaluated sigma - 1|`` over every
      sampled channel of a populated nuclide, each weighted by its unit-flux
      rate times its spectrum's fluence in the schedule times its parent's
      initial density, so it covers first-generation reactions only (a
      produced nuclide carries no weight), shows the decomposition's
      round-off on matrices that needed no repair, and is ``None`` when no
      weighted channel has an evaluated sigma. Both can be
      ``float('inf')``, which strict JSON does not accept.
    - ``sigma_at_least_one`` / ``sigma_at_least_ten``: sampled channels of
      populated nuclides with a positive rate on a spectrum the schedule
      irradiates with, keyed ``"Nuclide (n,x)"``, whose folded relative
      sigma as evaluated, before any repair, is at least one or ten. At that
      width the answer depends on the lognormal chosen to carry the
      evaluation's two moments, not on the evaluation alone.
      ``sigma_at_least_one_outside_bound`` is the same for nuclides outside
      the populated bound, whose wide channels a replica's draw can take
      past it; the ten-or-more subset reads off its values.
    - ``lognormal_not_carried``: nuclides whose evaluated relative
      covariance is not a lognormal's, keyed by nuclide, each with
      ``cells`` (cells whose sampled sigma or correlation differs from the
      evaluated one), ``largest_sigma_change`` (the largest
      ``|sampled / evaluated sigma - 1|``), ``largest_correlation_change``
      and ``log_space_repair`` (``None``, or a dict with the keys of a
      repair above, of the log-space correlation matrix).
      Two fully correlated cells with different sigmas, or an
      anticorrelation with ``1 + C <= 0``, are not, and the nearest
      lognormal is sampled: where the log-space covariance is not PSD its
      correlation matrix is replaced by the nearest correlation matrix,
      which keeps every sigma. A property of the distribution rather than a
      defect of the data, so not a gap. ``flux_lognormal_not_carried`` is
      the same for a stated flux covariance, keyed by spectrum index,
      whose ``log_space_repair`` is always ``None``: a flux covariance's
      log-space negative eigenvalues are clipped.
    - ``cross_material_adjusted``: keyed by a group of nuclides drawn jointly
      through cross-material covariance, their names joined by ``+``
      (``"U235+U238"``), where the covariance stated between their interval
      averages is not admissible beside each one's own and the closest
      admissible one was drawn instead, each own covariance kept exactly
      and the correlations between the averages fitted to the stated ones
      (each clipped to one first) in the Frobenius norm:
      ``relative_change`` (``||X' - X|| / ||X||`` of the drawn against the
      stated log-space covariance between the averages),
      ``least_relative_change`` (the same with each stated entry only
      clipped to a correlation of one: no admissible draw goes below it),
      ``largest_stated_correlation`` (past one where an entry alone is
      inadmissible), ``largest_correlation_change`` (the largest move of a
      correlation from its stated value clipped to one), ``iterations``
      and ``converged`` (the fit's; its result is admissible either way).
      ENDF/B-VIII.1 U235 and U238 fission read about 0.31.
      Counted in ``has_gaps``.
    - ``rates_sampled``: cross-section rate draws made, each read off one
      draw of the nuclide's cross sections. ``rates_floored`` counts those
      that came out negative and were floored at zero, which only a channel
      subtracting reactions or reading an additive (absolute or
      short-range) covariance can.
    - ``cross_section_points_floored``: with ``method="coupled"``, the
      cross-section grid values a replica's draw took below zero and that
      were floored at zero, over every replica.
    - ``half_lives_perturbed`` / ``no_half_life_uncertainty``: with the
      ``"half_life"`` source, which reachable unstable nuclides had their
      half-life sampled and which state no sigma to sample from.
      ``half_life_uncertainty_not_carried`` names those whose stated sigma
      no draw can carry (not finite, or not finite relative to the
      half-life), held at nominal and counted as a gap.
      ``half_lives_sampled`` counts the draws made. Each is a lognormal
      matched to the evaluation's mean and sigma, so none can go
      non-positive and none is floored.
    - ``decay_energies_perturbed`` / ``no_decay_energy_uncertainty``: the
      same for the ``"decay_energy"`` source, drawn per nuclide as a
      lognormal with the stated mean and sigma, per component where the
      data splits it. ``decay_energy_uncertainty_not_carried`` names those
      with a sigma stated on a zero energy, or not finite, which no draw
      can carry; that energy is held at nominal and counted as a gap.
    - ``decay_photon_lines_perturbed`` /
      ``no_decay_photon_line_uncertainty``: the same for the
      ``"decay_photon_lines"`` source, over the reachable unstable
      nuclides with decay photon data.
      ``decay_photon_line_uncertainty_not_carried`` names those with a
      sigma stated on a zero value, or not finite, which no draw can carry;
      that value is held at nominal and counted as a gap.
      ``decay_photon_spectra_folded`` maps each perturbed nuclide with a
      spectrum written the ENDF/B way (a normalisation of 1 with no sigma,
      its sigma folded into every line's dRI) to the radiation of each such
      spectrum (``"gamma"``, ``"xray"``). How much of those dRI the lines
      share is not stated, so they are where most of the range between a
      photon output's ``std_dev`` and ``std_dev_correlated`` comes from.
    - ``fission_yields_perturbed`` / ``no_fission_yield_uncertainty``: the
      same for the ``"fission_yield"`` source, over the reachable
      parents the run gives a fission rate (one that never fissions is
      not drawn). ``fission_yield_uncertainty_not_carried`` names
      those with a DY on a zero yield, or not finite, which is held while
      the parent's other yields are drawn.
      ``fission_yields_mapping_mismatch`` names those whose tape yields,
      named and summed by the converter's rule, do not give back the yields
      the solver reads; they are held rather than drawn through a mapping
      their yields were not built with. Each is counted as a gap.
    - ``decay_branchings_perturbed``: with the ``"decay_branching"``
      source, the reachable multi-mode parents whose split was sampled. Held
      at their evaluated ratios, each a gap: ``no_decay_branching_uncertainty``
      (no mode states a sigma, or one does beside two or more that do not)
      and ``decay_branchings_too_wide`` (every mode that could move states
      a sigma no ratio with its mean can have). Sampled but short of the
      stated sigmas, each a gap too: ``decay_branchings_partly_held`` (one
      or more modes held at their ratios, for such a sigma or for stating
      none) and ``decay_branchings_sigma_adjusted`` (a mode drawn more than
      0.1% from its stated sigma: the largest exceeds the sum of the
      others', or the complement's needs a correlation non-negative ratios
      cannot carry). ``decay_branchings_floored`` /
      ``decay_branchings_sampled`` count draws whose complement was pulled
      back above zero and draws made.
    - ``isomer_branchings_perturbed``: with the ``"isomer_branching"``
      source, the reachable reactions, as ``"Parent reaction"``, whose
      isomeric split was drawn from the MF=40 covariance of at least one of
      their final states. ``no_isomer_branching_uncertainty`` lists those
      whose split can move but whose evaluation states no MF=40 on any
      state the run folds, held at their nominal shares, a gap.
      ``isomer_branching_blocks_not_used`` gives, per parent, the MF=40
      blocks not used, counted by why, a gap.
      ``isomer_branching_covariance_repaired`` and
      ``isomer_branching_lognormal_not_carried`` are the MF=40 matrices
      repaired to the nearest correlation matrix (a gap) and those not a
      lognormal's (not a gap), with the same entries as
      ``covariance_repairs`` and ``lognormal_not_carried``.
      ``isomer_production_sigma`` gives, as ``"Parent reaction Product"``,
      the relative sigma MF=40 states for the product's production, folded
      against the spectrum (the largest over the run's spectra).
      ``isomer_branchings_sampled`` counts the draws, one per drawn parent
      per replica. ``isomer_branchings_clipped`` gives, as
      ``"Parent reaction Product"``, how many list draws (one per replica
      per spectrum) scaled the product's drawn production back to the
      drawn reaction total, the stated productions of its list having
      come out above it; a product never clipped is absent.
    - ``damage_energy``: with ``displacement_damage=True`` and the
      ``"cross_sections"`` source, per nuclide of the starting composition
      ``{"explained": ..., "sigma": ...}``: the share of its stored MT=444
      rate its reactions' deposits reproduce, the part a draw moves (the
      rest, fission's share above all, is held, a gap), and the relative
      sigma of its drawn damage-energy rate, each weighted over the spectra
      by fluence.
    - ``statistical_rates``: with the ``"statistical"`` source on a
      transport run, how many tallied rates were sampled from their
      covariance; ``statistical_floored`` / ``statistical_sampled`` count
      draws that came out negative and were floored.
    - ``resonance_parameters``: per nuclide with resonance parameters
      (MF=2 and MF=32) and a rate in this run, how its resonance-range
      uncertainty was sampled. ``method`` is ``"parameters sampled"``
      (drawn per replica and the cross sections rebuilt from them, on a
      transport run against the flux it tallied through the resonances) or
      ``"first-order rows"`` (the MF=32 rows of ``covariance.arrow``),
      ``reason`` why the parameters were not sampled (``None`` where they
      were), and ``ranges`` one sampler report per sampled range:
      ``isotope`` and ``range`` indices, the ``gaussian``, ``lognormal``
      and ``held`` parameter counts, ``zero_mean_widths`` (widths stated
      with a zero mean and a nonzero sigma, held at zero) and
      ``negative_mean_widths`` (drawn as signed), each with ``index``,
      ``location``, ``quantity``, ``value`` and ``sigma``,
      ``zero_variance_with_covariance``, ``unattainable_pairs``, and
      ``stated_repair`` / ``transformed_repair`` (the nearest-correlation
      repair of the stated and of the log-space matrix, each with
      ``lambda_min``, ``frobenius_change``, ``max_change``, ``parameters``,
      ``iterations`` and ``converged``, ``None`` where none was needed).
      How far the draws' parameter correlations are from the evaluated
      ones, in the parameters themselves after both repairs and the
      lognormal transform, reads off ``largest_correlation_change`` (the
      largest change of one correlation) and
      ``correlation_frobenius_change``, per range and per nuclide over its
      ranges; every drawn parameter keeps its evaluated mean and sigma, so
      that is the whole of the difference in the first two moments. Widths
      stay lognormal, so a pair no lognormal carries
      (``unattainable_pairs``) is where it is largest. Empty on a transport
      run, which keeps the rows.
    - ``not_perturbed``: every input this run held at its nominal value,
      such as any MF=32 resonance-parameter covariance neither sampled nor
      in the library's ``covariance.arrow``, the photon and dose data, the
      material composition, any source switched off, and, where they
      applied, the self-shielding correction, the flux's response to a
      perturbed cross section on a transport run, and the per-branch decay
      emission of a parent whose branching was drawn.
    - ``samples`` / ``converged`` / ``convergence`` / ``hit_cap`` /
      ``unconverged``: how many replicas ran; whether every tracked sigma
      reached the target, ``convergence``, for the standard error of a
      sigma relative to it; whether the 1024-replica cap stopped the run
      first; and, worst first, every sigma that missed, as dicts of
      ``output`` (``"density"``, ``"activity"``, ``"decay_heat"`` or
      ``"decay_photon_rate"``), ``nuclide`` (``None`` for a total),
      ``step`` and the ``relative_standard_error`` it reached. Listed with
      a fixed ``samples`` too, where ``hit_cap`` is never set.
    - ``noise_removed`` / ``noisy``: whether the Monte Carlo noise in the
      replicas' spread was measured and removed from every sigma (with
      transport replica weights, each replica is solved a second time from
      the even half of the transport's histories, see
      ``get_nuclide_uncertainty_noise``), and, the largest share first,
      every tracked sigma whose removed noise variance exceeded a quarter
      of the variance left, as dicts of ``output``, ``nuclide``, ``step``,
      ``replica_spread``, ``noise`` and ``std_dev`` (the sigma reported).
      Those sigmas would sharpen most with more transport histories.

    Args:
        material_id: Material ID number.
    """

get_self_shielding_info

get_self_shielding_info(material_id: int) -> Optional[dict]

What the self-shielding did for one material.

Present for every material of a spectrum solve, shielded or not, and None for a transport-coupled solve or a material not in the results. chord_cm of None means the run was dilute and nothing was corrected; otherwise it says how: the method and chord_cm used, which nuclides were shielded, which were not_shielded and why, and strongest_factor, the smallest factor any group average was multiplied by. A run reporting 1.0 there shielded nothing in practice, which is a different statement from not having tried.

would_shield is the other direction, and is filled only on a dilute run: nuclides whose own resonances are structured enough to have suppressed a reaction, each mapped to how strongly.

It is an indicator, not a correction and not a bound. There is no geometry in it: the weight is 1 / (1 + N * sigma_x) on that one reaction and that nuclide's own density, which fixes the background at 1/cm, while the correction proper uses 1 / chord_cm against the material's total. So the number scales with how strongly a nuclide's own resonances could bite without predicting what a given lump would see, and it can sit either side of the real factor: a lump thinner than a centimetre of chord shields less, and a material whose other nuclides dominate the total at the resonance dips the flux further than this one reaction can express.

On the FNS tungsten foil, would_shield reads 0.634 for W186 while the slowing-down correction on the same foil and spectrum saturates at 0.730 from a millimetre of chord upward. Read it as "this answer may be high, and this is a resonance absorber", which is the warning a dilute run should carry rather than silence. Read the size of the effect off a shielded run, by asking for one.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
Source code in yamc/_core/__init__.pyi
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
def get_self_shielding_info(self, material_id: builtins.int) -> typing.Optional[dict]:
    r"""
    What the self-shielding did for one material.

    Present for every material of a spectrum solve, shielded or not, and
    ``None`` for a transport-coupled solve or a material not in the
    results. ``chord_cm`` of ``None`` means the run was dilute and
    nothing was corrected; otherwise it says how: the ``method`` and
    ``chord_cm`` used, which nuclides were ``shielded``, which were
    ``not_shielded`` and why, and ``strongest_factor``, the smallest factor
    any group average was multiplied by. A run reporting ``1.0`` there
    shielded nothing in practice, which is a different statement from not
    having tried.

    ``would_shield`` is the other direction, and is filled only on a dilute
    run: nuclides whose own resonances are structured enough to have
    suppressed a reaction, each mapped to how strongly.

    It is an indicator, not a correction and not a bound. There is no
    geometry in it: the weight is ``1 / (1 + N * sigma_x)`` on that one
    reaction and that nuclide's own density, which fixes the background at
    1/cm, while the correction proper uses ``1 / chord_cm`` against the
    material's total. So the number scales with how strongly a nuclide's own
    resonances could bite without predicting what a given lump would see,
    and it can sit either side of the real factor: a lump thinner than a
    centimetre of chord shields less, and a material whose other nuclides
    dominate the total at the resonance dips the flux further than this one
    reaction can express.

    On the FNS tungsten foil, ``would_shield`` reads 0.634 for W186 while
    the slowing-down correction on the same foil and spectrum saturates at
    0.730 from a millimetre of chord upward. Read it as "this answer may be
    high, and this is a resonance absorber", which is the warning a dilute
    run should carry rather than silence. Read the size of the effect off a
    shielded run, by asking for one.

    Args:
        material_id: Material ID number.
    """

get_product_screening_info

get_product_screening_info(material_id: int) -> Optional[dict]

Which transmutation products had their cross sections loaded, and which were left out below product_threshold.

A product is loaded once its atom fraction, or its share of the activity, decay heat or decay photon power, reaches the threshold at any state of the schedule; one left out is still produced, decays and is reported, and only its own neutron reactions are dropped.

Keys: threshold; rounds, the screening solves run; closure, how many nuclides with neutron reactions the chain reaches from the composition, which is what loading without screening fetched; loaded, the sorted nuclides whose cross sections drive the solve; unavailable, products that crossed the threshold but the library has no data for; below_threshold, each product left out mapped to its largest atom fraction over the schedule; and dropped_fraction, the sum of those, which bounds the share of the material's atoms the left-out reactions could have moved before multiplying by the share of them that react.

None for a material not in the results, and for one a transport-coupled solve did not irradiate.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
Source code in yamc/_core/__init__.pyi
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
def get_product_screening_info(self, material_id: builtins.int) -> typing.Optional[dict]:
    r"""
    Which transmutation products had their cross sections loaded, and
    which were left out below ``product_threshold``.

    A product is loaded once its atom fraction, or its share of the
    activity, decay heat or decay photon power, reaches the threshold at
    any state of the schedule; one left out is still produced, decays and
    is reported, and only its own neutron reactions are dropped.

    Keys: ``threshold``; ``rounds``, the screening solves run;
    ``closure``, how many nuclides with neutron reactions the chain
    reaches from the composition, which is what loading without screening
    fetched; ``loaded``, the sorted nuclides whose cross sections drive
    the solve; ``unavailable``, products that crossed the threshold but
    the library has no data for; ``below_threshold``, each product left
    out mapped to its largest atom fraction over the schedule; and
    ``dropped_fraction``, the sum of those, which bounds the share of the
    material's atoms the left-out reactions could have moved before
    multiplying by the share of them that react.

    ``None`` for a material not in the results, and for one a
    transport-coupled solve did not irradiate.

    Args:
        material_id: Material ID number.
    """

get_material_nuclides

get_material_nuclides(material_id: int, step: int) -> Optional[dict[str, float]]

Get material composition at a specific timestep as a dict.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial).

required

Returns:

Type Description
Optional[dict[str, float]]

Dict of nuclide -> density [atoms/barn-cm], or None if not found.

Source code in yamc/_core/__init__.pyi
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
def get_material_nuclides(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[builtins.dict[builtins.str, builtins.float]]:
    r"""
    Get material composition at a specific timestep as a dict.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial).

    Returns:
        Dict of nuclide -> density [atoms/barn-cm], or None if not found.
    """

get_material

get_material(material_id: int, step: int) -> Optional[Material]

Get material composition at a specific timestep.

The material keeps material_id, so it can stand in for the original in a model. Placed beside the original it needs an id of its own, since a geometry refuses two different materials with one id.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial).

required

Returns:

Type Description
Optional[Material]

Material object with composition at that timestep, or None if not found.

Source code in yamc/_core/__init__.pyi
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
def get_material(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[Material]:
    r"""
    Get material composition at a specific timestep.

    The material keeps ``material_id``, so it can stand in for the
    original in a model. Placed beside the original it needs an id of its
    own, since a geometry refuses two different materials with one id.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial).

    Returns:
        Material object with composition at that timestep, or None if not found.
    """

step_materials

step_materials(material_id: int) -> list[Material]

Composition at the end of each schedule step, without the initial one.

Indexed as timesteps, so entry i is the state at the end of step i and pairs with get_reaction_rates(material_id, i). This is the list Material.transmute used to return on its own. Each keeps material_id, as get_material says.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required

Returns:

Type Description
list[Material]

List[Material]: One material per step; empty if the material is

list[Material]

unknown or was never stepped.

Source code in yamc/_core/__init__.pyi
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
def step_materials(self, material_id: builtins.int) -> builtins.list[Material]:
    r"""
    Composition at the end of each schedule step, without the initial one.

    Indexed as ``timesteps``, so entry ``i`` is the state at the end of step
    ``i`` and pairs with ``get_reaction_rates(material_id, i)``. This is the
    list ``Material.transmute`` used to return on its own. Each keeps
    ``material_id``, as ``get_material`` says.

    Args:
        material_id: Material ID number.

    Returns:
        List[Material]: One material per step; empty if the material is
        unknown or was never stepped.
    """

get_final_material

get_final_material(material_id: int) -> Optional[Material]

Final composition for a material, after the last step. It keeps material_id, as get_material says.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required

Returns:

Type Description
Optional[Material]

Material at the end of the schedule, or None if the material is

Optional[Material]

unknown.

Source code in yamc/_core/__init__.pyi
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
def get_final_material(self, material_id: builtins.int) -> typing.Optional[Material]:
    r"""
    Final composition for a material, after the last step. It keeps
    ``material_id``, as ``get_material`` says.

    Args:
        material_id: Material ID number.

    Returns:
        Material at the end of the schedule, or None if the material is
        unknown.
    """

get_dpa

get_dpa(material_id: int, element: Optional[str] = None) -> Optional[list[float]]

Cumulative NRT displacements per atom (dpa) over the schedule.

Present when the transmute call was given displacement_damage=True, and None otherwise. One value per state, aligned with times: entry 0 is the initial composition and is zero, and entry i is the total after schedule step i - 1. Cooldowns add nothing.

For an element X it is the damage energy deposited per atom of X, from X's own nuclides, converted with X's displacement threshold energy as 0.8 * E_damage / (2 * E_d) (the NRT model, ASTM E521). The material total, with element omitted, is the atom-fraction-weighted sum over elements: each element's recoils are treated as slowing down among atoms of their own kind, which reduces to the elemental value for a pure element and leaves out energy transfer between elements in a cascade. MT=444 is already integrated over the recoil spectrum, so the per-recoil threshold steps of the NRT model (no displacement below E_d, one up to 2 * E_d / 0.8) are not applied, which is the standard practice for a damage-energy cross section. The E_d used and its source are in get_displacement_damage_info, and the nuclear-data spread, when data_uncertainty was given too, in get_dpa_uncertainty.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
element Optional[str]

Element symbol, e.g. "W", for that element's dpa; omit it for the material total.

None

Returns:

Type Description
Optional[list[float]]

List of cumulative dpa, one per state, or None if damage was not

Optional[list[float]]

asked for or the material is not in the results.

Raises:

Type Description
ValueError

If element has no dpa: it is not in the material on an irradiated step, or it is a transmutation product with no displacement threshold energy.

Source code in yamc/_core/__init__.pyi
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
def get_dpa(self, material_id: builtins.int, element: typing.Optional[builtins.str] = None) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Cumulative NRT displacements per atom (dpa) over the schedule.

    Present when the transmute call was given
    ``displacement_damage=True``, and ``None`` otherwise. One value per
    state, aligned with ``times``: entry 0 is the initial composition and
    is zero, and entry ``i`` is the total after schedule step ``i - 1``.
    Cooldowns add nothing.

    For an element ``X`` it is the damage energy deposited per atom of
    ``X``, from ``X``'s own nuclides, converted with ``X``'s displacement
    threshold energy as ``0.8 * E_damage / (2 * E_d)`` (the NRT model,
    ASTM E521). The material total, with ``element`` omitted, is the
    atom-fraction-weighted sum over elements: each element's recoils are
    treated as slowing down among atoms of their own kind, which reduces to
    the elemental value for a pure element and leaves out energy transfer
    between elements in a cascade. MT=444 is already integrated over the
    recoil spectrum, so the per-recoil threshold steps of the NRT model
    (no displacement below ``E_d``, one up to ``2 * E_d / 0.8``) are not
    applied, which is the standard practice for a damage-energy cross
    section. The ``E_d`` used and its source are in
    ``get_displacement_damage_info``, and the nuclear-data spread, when
    ``data_uncertainty`` was given too, in ``get_dpa_uncertainty``.

    Args:
        material_id: Material ID number.
        element: Element symbol, e.g. ``"W"``, for that element's dpa;
            omit it for the material total.

    Returns:
        List of cumulative dpa, one per state, or None if damage was not
        asked for or the material is not in the results.

    Raises:
        ValueError: If ``element`` has no dpa: it is not in the material
            on an irradiated step, or it is a transmutation product with no
            displacement threshold energy.
    """

get_damage_energy

get_damage_energy(material_id: int, element: Optional[str] = None) -> Optional[list[float]]

Cumulative damage energy deposited per atom [eV] over the schedule.

The quantity dpa is computed from, kept separate so the displacement model can be changed without the data: each nuclide's MT=444 damage-energy cross section [eV barn] folded against the pulse spectrum by the same collapse as the reaction rates, times the flux magnitude and the step duration, at each step's composition. Indexed as get_dpa. For an element it is per atom of that element; the material total weights the elements by atom fraction, so it is per atom of the material.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
element Optional[str]

Element symbol for that element's damage energy; omit it for the material total.

None

Returns:

Type Description
Optional[list[float]]

List of cumulative damage energy [eV per atom], one per state, or

Optional[list[float]]

None if damage was not asked for or the material is not in the

Optional[list[float]]

results.

Raises:

Type Description
ValueError

If element is not in the material on an irradiated step.

Source code in yamc/_core/__init__.pyi
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
def get_damage_energy(self, material_id: builtins.int, element: typing.Optional[builtins.str] = None) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Cumulative damage energy deposited per atom [eV] over the schedule.

    The quantity dpa is computed from, kept separate so the displacement
    model can be changed without the data: each nuclide's MT=444
    damage-energy cross section [eV barn] folded against the pulse
    spectrum by the same collapse as the reaction rates, times the flux
    magnitude and the step duration, at each step's composition. Indexed
    as ``get_dpa``. For an element it is per atom of that element; the
    material total weights the elements by atom fraction, so it is per atom
    of the material.

    Args:
        material_id: Material ID number.
        element: Element symbol for that element's damage energy; omit it
            for the material total.

    Returns:
        List of cumulative damage energy [eV per atom], one per state, or
        None if damage was not asked for or the material is not in the
        results.

    Raises:
        ValueError: If ``element`` is not in the material on an irradiated
            step.
    """

get_dpa_uncertainty

get_dpa_uncertainty(material_id: int, step: int, element: Optional[str] = None) -> Optional[Estimate]

NRT dpa at one timestep, with the nuclear-data spread on it.

Present when the transmute call was given both displacement_damage=True and data_uncertainty. Each replica's dpa is accumulated over its own inventory, with each starting nuclide's damage-energy rate moved by the replica's draw:

  • "cross_sections": MT=444 has no covariance of its own, but it is the sum over reactions of each cross section times the damage energy that reaction deposits, so a draw moves it by each reaction's deposit times its drawn change. The elastic and inelastic reactions, which carry most of it, are drawn with the activation channels as one evaluation. What no reaction's deposit reproduces (fission's share) is held; get_data_uncertainty_info(...)["damage_energy"] says how much that is per nuclide.
  • "flux_spectrum": the damage energy's own per-group terms under the replica's flux draw, where the spectrum has a sigma.

Transmutation products' damage energy, short-range (LB=8) covariance and the displacement threshold energies are held at nominal.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition, which has no dpa).

required
element Optional[str]

Element symbol for that element's dpa; omit it for the material total.

None

Returns:

Type Description
Optional[Estimate]

Estimate | None: None if damage or uncertainty was not asked for,

Optional[Estimate]

or the material is not in the results.

Raises:

Type Description
ValueError

If element has no dpa, or there is no such step.

Source code in yamc/_core/__init__.pyi
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
def get_dpa_uncertainty(self, material_id: builtins.int, step: builtins.int, element: typing.Optional[builtins.str] = None) -> typing.Optional[Estimate]:
    r"""
    NRT dpa at one timestep, with the nuclear-data spread on it.

    Present when the transmute call was given both
    ``displacement_damage=True`` and ``data_uncertainty``. Each replica's
    dpa is accumulated over its own inventory, with each starting nuclide's
    damage-energy rate moved by the replica's draw:

    - ``"cross_sections"``: MT=444 has no covariance of its own, but it is
      the sum over reactions of each cross section times the damage energy
      that reaction deposits, so a draw moves it by each reaction's deposit
      times its drawn change. The elastic and inelastic reactions, which
      carry most of it, are drawn with the activation channels as one
      evaluation. What no reaction's deposit reproduces (fission's share)
      is held; ``get_data_uncertainty_info(...)["damage_energy"]`` says how much
      that is per nuclide.
    - ``"flux_spectrum"``: the damage energy's own per-group terms under
      the replica's flux draw, where the spectrum has a sigma.

    Transmutation products' damage energy, short-range (LB=8) covariance
    and the displacement threshold energies are held at nominal.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition, which has no dpa).
        element: Element symbol for that element's dpa; omit it for the
            material total.

    Returns:
        Estimate | None: None if damage or uncertainty was not asked for,
        or the material is not in the results.

    Raises:
        ValueError: If ``element`` has no dpa, or there is no such step.
    """

get_damage_energy_uncertainty

get_damage_energy_uncertainty(material_id: int, step: int, element: Optional[str] = None) -> Optional[Estimate]

Damage energy per atom [eV] at one timestep, with the nuclear-data spread on it.

The same replicas as get_dpa_uncertainty, before the NRT conversion, so its relative spread is the dpa's for a pure element.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Timestep index (0 = initial composition).

required
element Optional[str]

Element symbol for that element's damage energy; omit it for the material total.

None

Returns:

Type Description
Optional[Estimate]

Estimate | None: None if damage or uncertainty was not asked for,

Optional[Estimate]

or the material is not in the results.

Raises:

Type Description
ValueError

If element is not in the material on an irradiated step, or there is no such step.

Source code in yamc/_core/__init__.pyi
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
def get_damage_energy_uncertainty(self, material_id: builtins.int, step: builtins.int, element: typing.Optional[builtins.str] = None) -> typing.Optional[Estimate]:
    r"""
    Damage energy per atom [eV] at one timestep, with the nuclear-data
    spread on it.

    The same replicas as ``get_dpa_uncertainty``, before the NRT
    conversion, so its relative spread is the dpa's for a pure element.

    Args:
        material_id: Material ID number.
        step: Timestep index (0 = initial composition).
        element: Element symbol for that element's damage energy; omit it
            for the material total.

    Returns:
        Estimate | None: None if damage or uncertainty was not asked for,
        or the material is not in the results.

    Raises:
        ValueError: If ``element`` is not in the material on an irradiated
            step, or there is no such step.
    """

get_displacement_damage_info

get_displacement_damage_info(material_id: int) -> Optional[dict]

What the displacement damage was computed with, and what it could not count.

None unless the transmute call was given displacement_damage=True. A dict:

  • model: "NRT", and efficiency: 0.8.
  • displacement_energies: per element with dpa, {"energy": E_d in eV, "source": ...}, where source is "ASTM E521", "OECD-NEA 2015" (Table 2.4 of NEA/NSC/DOC(2015)9, for an element ASTM E521 does not cover) or "user".
  • without_damage_energy: nuclides present on an irradiated step whose data has no MT=444, each with the largest atom fraction it reached there. Their damage energy is not counted, so a large entry here means the totals are low by about that share. Only transmutation products can appear: a nuclide of the starting composition without MT=444 is refused.
  • without_displacement_energy: transmutation-product elements with no displacement threshold energy (hydrogen and helium, typically), each with the largest atom fraction reached. Their damage energy is counted in get_damage_energy; they add nothing to get_dpa. Pass displacement_energies to include them.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
Source code in yamc/_core/__init__.pyi
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
def get_displacement_damage_info(self, material_id: builtins.int) -> typing.Optional[dict]:
    r"""
    What the displacement damage was computed with, and what it could not
    count.

    ``None`` unless the transmute call was given
    ``displacement_damage=True``. A dict:

    - ``model``: ``"NRT"``, and ``efficiency``: ``0.8``.
    - ``displacement_energies``: per element with dpa,
      ``{"energy": E_d in eV, "source": ...}``, where ``source`` is
      ``"ASTM E521"``, ``"OECD-NEA 2015"`` (Table 2.4 of NEA/NSC/DOC(2015)9,
      for an element ASTM E521 does not cover) or ``"user"``.
    - ``without_damage_energy``: nuclides present on an irradiated step
      whose data has no MT=444, each with the largest atom fraction it
      reached there. Their damage energy is not counted, so a large entry
      here means the totals are low by about that share. Only
      transmutation products can appear: a nuclide of the starting
      composition without MT=444 is refused.
    - ``without_displacement_energy``: transmutation-product elements with
      no displacement threshold energy (hydrogen and helium, typically),
      each with the largest atom fraction reached. Their damage energy is
      counted in ``get_damage_energy``; they add nothing to ``get_dpa``.
      Pass ``displacement_energies`` to include them.

    Args:
        material_id: Material ID number.
    """

get_reaction_rates

get_reaction_rates(material_id: int, step: int) -> Optional[Any]

Per-edge reaction rates the solve drove one step with.

The rate of each individual production edge, which the solve computes to build the burnup matrix and used to throw away. Without it a consumer can enumerate the routes into a product but not weight them, so a route carrying 99.9% and one carrying 0.1% look alike.

Both methods report the same quantity in the same shape. method="coupled" takes the rates from that step's transport tallies and method="independent" from the single transport's multigroup fold scaled by the step's source rate; either way the edge rate is that rate times the branching of the chain the step was solved with, isomeric overlay included.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Schedule step index, the same index as timesteps and get_source_rates. This is one less than the step the composition getters take, where 0 is the initial composition.

required

Returns:

Type Description
Optional[Any]

dict[str, dict[str, list[tuple[str | None, float]]]] | None: parent

Optional[Any]

nuclide -> reaction kind -> [(target, rate [1/s])]. A target of

Optional[Any]

None is a channel naming no single product, which in practice

Optional[Any]

means fission, whose products come from the yields rather than from

Optional[Any]

an edge. Empty for a decay-only step, and None if the material

Optional[Any]

or the step is unknown.

Examples:

>>> rates = results.get_reaction_rates(material_id=1, step=0)
>>> rates["Fe56"]["(n,gamma)"]
[('Fe57', 1.7e-09)]
>>> # share of Mn56 production arriving down each route
>>> into_mn56 = [
...     (parent, kind, rate)
...     for parent, kinds in rates.items()
...     for kind, edges in kinds.items()
...     for target, rate in edges
...     if target == "Mn56"
... ]
Source code in yamc/_core/__init__.pyi
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
def get_reaction_rates(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[typing.Any]:
    r"""
    Per-edge reaction rates the solve drove one step with.

    The rate of each individual production edge, which the solve computes to
    build the burnup matrix and used to throw away. Without it a consumer
    can enumerate the routes into a product but not weight them, so a route
    carrying 99.9% and one carrying 0.1% look alike.

    Both methods report the same quantity in the same shape.
    ``method="coupled"`` takes the rates from that step's transport tallies
    and ``method="independent"`` from the single transport's multigroup fold
    scaled by the step's source rate; either way the edge rate is that rate
    times the branching of the chain the step was solved with, isomeric
    overlay included.

    Args:
        material_id: Material ID number.
        step: Schedule step index, the same index as ``timesteps`` and
            ``get_source_rates``. This is one less than the ``step`` the
            composition getters take, where 0 is the initial composition.

    Returns:
        dict[str, dict[str, list[tuple[str | None, float]]]] | None: parent
        nuclide -> reaction kind -> [(target, rate [1/s])]. A ``target`` of
        ``None`` is a channel naming no single product, which in practice
        means fission, whose products come from the yields rather than from
        an edge. Empty for a decay-only step, and ``None`` if the material
        or the step is unknown.

    Examples:
        >>> rates = results.get_reaction_rates(material_id=1, step=0)
        >>> rates["Fe56"]["(n,gamma)"]
        [('Fe57', 1.7e-09)]
        >>> # share of Mn56 production arriving down each route
        >>> into_mn56 = [
        ...     (parent, kind, rate)
        ...     for parent, kinds in rates.items()
        ...     for kind, edges in kinds.items()
        ...     for target, rate in edges
        ...     if target == "Mn56"
        ... ]
    """

get_reaction_rate_spectrum

get_reaction_rate_spectrum(material_id: int, nuclide: str, kind: str, step: int) -> Optional[Any]

One channel's reaction rate over one step, resolved onto the groups of the spectrum that drove it.

get_reaction_rates answers with one number per edge, already collapsed against the whole spectrum. That number cannot say which part of the spectrum made it, and where a cross section spans decades the two readings are different physics: an effective W186(n,gamma) of 57 mb against a spectrum 89% of which sits in 12-16 MeV and 0.7% of which is below 100 keV is either a fast-capture rate or a resonance-region rate, and only the breakdown says which. A disagreement can then be pinned on resonance processing rather than guessed at, and a covariance grid that stops short of the spectrum can be checked against where the rate actually is.

The per-group entries sum to the collapsed rate for the same channel, to floating-point rounding, because both come from the same walk of the same cross sections with the same self-shielding weighting.

Nothing is stored for this. The breakdown is re-derived from the spectrum when asked for, which is one reaction over the group structure; keeping it for every channel would be tens of megabytes on a 709-group structure, and a run that never asks should not pay that.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
nuclide str

The parent the reaction happens on, e.g. "W186".

required
kind str

The reaction, spelled as the chain spells it, e.g. "(n,gamma)".

required
step int

Schedule step index, as get_reaction_rates takes it.

required

Returns:

Type Description
Optional[Any]

dict | None: boundaries, the group boundaries [eV] ascending and

Optional[Any]

one longer than the rates, and rates, each group's contribution

Optional[Any]

to the rate [1/s]. None when the material, the step, the nuclide or

Optional[Any]

the channel is unknown; for a step that drove no flux, whether by

Optional[Any]

being a cooldown or by carrying a zero rate; for (n,n'), whose

Optional[Any]

rate comes from the branching overlay's partials rather than from a

Optional[Any]

group average; and for a transport-coupled solve, which scores its

Optional[Any]

rates at the collision energy and keeps no group structure to

Optional[Any]

resolve them onto.

Examples:

>>> spectrum = results.get_reaction_rate_spectrum(
...     material_id=1, nuclide="W186", kind="(n,gamma)", step=0
... )
>>> sum(spectrum["rates"])  # the collapsed rate
1.9e-09
>>> # where in energy that rate came from
>>> below_100_keV = sum(
...     r
...     for lo, r in zip(spectrum["boundaries"], spectrum["rates"])
...     if lo < 1.0e5
... )
Source code in yamc/_core/__init__.pyi
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
def get_reaction_rate_spectrum(self, material_id: builtins.int, nuclide: builtins.str, kind: builtins.str, step: builtins.int) -> typing.Optional[typing.Any]:
    r"""
    One channel's reaction rate over one step, resolved onto the groups of
    the spectrum that drove it.

    ``get_reaction_rates`` answers with one number per edge, already
    collapsed against the whole spectrum. That number cannot say which part
    of the spectrum made it, and where a cross section spans decades the two
    readings are different physics: an effective ``W186(n,gamma)`` of 57 mb
    against a spectrum 89% of which sits in 12-16 MeV and 0.7% of which is
    below 100 keV is either a fast-capture rate or a resonance-region rate,
    and only the breakdown says which. A disagreement can then be pinned on
    resonance processing rather than guessed at, and a covariance grid that
    stops short of the spectrum can be checked against where the rate
    actually is.

    The per-group entries sum to the collapsed rate for the same channel, to
    floating-point rounding, because both come from the same walk of the
    same cross sections with the same self-shielding weighting.

    Nothing is stored for this. The breakdown is re-derived from the
    spectrum when asked for, which is one reaction over the group structure;
    keeping it for every channel would be tens of megabytes on a 709-group
    structure, and a run that never asks should not pay that.

    Args:
        material_id: Material ID number.
        nuclide: The parent the reaction happens on, e.g. ``"W186"``.
        kind: The reaction, spelled as the chain spells it, e.g.
            ``"(n,gamma)"``.
        step: Schedule step index, as ``get_reaction_rates`` takes it.

    Returns:
        dict | None: ``boundaries``, the group boundaries [eV] ascending and
        one longer than the rates, and ``rates``, each group's contribution
        to the rate [1/s]. None when the material, the step, the nuclide or
        the channel is unknown; for a step that drove no flux, whether by
        being a cooldown or by carrying a zero rate; for ``(n,n')``, whose
        rate comes from the branching overlay's partials rather than from a
        group average; and for a transport-coupled solve, which scores its
        rates at the collision energy and keeps no group structure to
        resolve them onto.

    Examples:
        >>> spectrum = results.get_reaction_rate_spectrum(
        ...     material_id=1, nuclide="W186", kind="(n,gamma)", step=0
        ... )
        >>> sum(spectrum["rates"])  # the collapsed rate
        1.9e-09
        >>> # where in energy that rate came from
        >>> below_100_keV = sum(
        ...     r
        ...     for lo, r in zip(spectrum["boundaries"], spectrum["rates"])
        ...     if lo < 1.0e5
        ... )
    """

get_isomeric_branching

get_isomeric_branching(material_id: int, step: int) -> Optional[Any]

Flux-weighted isomeric branching at one step.

Which state a reaction leaves its product in is energy dependent, so the single number describing a spectrum is the branching collapsed against it, and that number exists only inside a solve. The chain file carries the unweighted ratios, and where the branching overlay supplies the split it carries a placeholder instead: on TENDL-2025 the dominant tungsten channel reads W186 (n,2n) -> W185 1.000000 and W186 (n,2n) -> W185_m1 0.000000 in the file, and the overlay replaces both at solve time with roughly the 54/46 that spectrum gives. On a foil whose decay heat comes from an isomer, that difference is the whole answer.

Only channels landing in more than one final state appear. A channel with one product has no branching to report, and listing it at 1.0 buries the ones that do; get_reaction_rates has the unnormalised edges if the rest is wanted.

This is the number that says whether a disagreement belongs to a cross section or to a branching ratio, which are different data and different fixes.

Channels come back ordered by production, the channel's rate times its parent's atom density at the start of the step. A rate on its own is per atom of the parent, so ordering on it promotes whatever sits on a trace isotope: on an FNS tungsten foil W180(n,2n) has the highest per-atom rate of any channel in the foil, and W180 is 0.12% of it, so by what it made the channel falls to fifth, two orders of magnitude below the W186(n,2n) carrying most of that foil's decay heat.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Schedule step index, the same index get_reaction_rates takes, which is one less than the composition getters' step.

required

Returns:

Type Description
Optional[Any]

list[dict] | None: one entry per splitting channel, most produced

Optional[Any]

first, each with parent, reaction, production and

Optional[Any]

split. split is [(target, fraction)] summing to one and

Optional[Any]

ordered with the largest share first. Empty for a decay-only step,

Optional[Any]

and None if the material or the step is unknown. A parent absent

Optional[Any]

from the step's starting composition has production 0.0 and sorts

Optional[Any]

last rather than being dropped.

Examples:

>>> results.get_isomeric_branching(material_id=1, step=0)[0]
{'parent': 'W186', 'reaction': '(n,2n)', 'production': 9.35e-14,
 'split': [('W185_m1', 0.535), ('W185', 0.465)]}
Source code in yamc/_core/__init__.pyi
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
def get_isomeric_branching(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[typing.Any]:
    r"""
    Flux-weighted isomeric branching at one step.

    Which state a reaction leaves its product in is energy dependent, so the
    single number describing a spectrum is the branching collapsed against
    it, and that number exists only inside a solve. The chain file carries
    the unweighted ratios, and where the branching overlay supplies the
    split it carries a placeholder instead: on TENDL-2025 the dominant
    tungsten channel reads ``W186 (n,2n) -> W185 1.000000`` and
    ``W186 (n,2n) -> W185_m1 0.000000`` in the file, and the overlay
    replaces both at solve time with roughly the 54/46 that spectrum gives.
    On a foil whose decay heat comes from an isomer, that difference is the
    whole answer.

    Only channels landing in more than one final state appear. A channel
    with one product has no branching to report, and listing it at 1.0
    buries the ones that do; ``get_reaction_rates`` has the unnormalised
    edges if the rest is wanted.

    This is the number that says whether a disagreement belongs to a cross
    section or to a branching ratio, which are different data and different
    fixes.

    Channels come back ordered by production, the channel's rate times its
    parent's atom density at the start of the step. A rate on its own is per
    atom of the parent, so ordering on it promotes whatever sits on a trace
    isotope: on an FNS tungsten foil ``W180(n,2n)`` has the highest per-atom
    rate of any channel in the foil, and W180 is 0.12% of it, so by what it
    made the channel falls to fifth, two orders of magnitude below the
    ``W186(n,2n)`` carrying most of that foil's decay heat.

    Args:
        material_id: Material ID number.
        step: Schedule step index, the same index ``get_reaction_rates``
            takes, which is one less than the composition getters' step.

    Returns:
        list[dict] | None: one entry per splitting channel, most produced
        first, each with ``parent``, ``reaction``, ``production`` and
        ``split``. ``split`` is [(target, fraction)] summing to one and
        ordered with the largest share first. Empty for a decay-only step,
        and None if the material or the step is unknown. A parent absent
        from the step's starting composition has production 0.0 and sorts
        last rather than being dropped.

    Examples:
        >>> results.get_isomeric_branching(material_id=1, step=0)[0]
        {'parent': 'W186', 'reaction': '(n,2n)', 'production': 9.35e-14,
         'split': [('W185_m1', 0.535), ('W185', 0.465)]}
    """

get_branching_report

get_branching_report(material_id: int, step: int) -> Optional[dict]

What the isomeric-branching rule did over one step's spectrum.

The branching evaluation gives the split and the cross-section library the total. How a list's values are read is decided by how the evaluation gives them, which the converter records: a complete MF=10 list (its ground state listed) and every MF=9 list are shares of the transport total, applied at each energy; an MF=10 list of isomers only, and every (n,n') list, are absolute productions, the ground state taking the rest. This says, per channel, which of those applied and how much of the parent's removal rate rests on anything the evaluation does not give.

It also says where each split came from. With several branching sources (transmutation_branch_ratios = ["irdff-ii", "endf-b8.1"]) each channel takes its split from the first source that evaluates it, and its source names that one. mixed is True when the splits come from more than one library, or a split from a library other than its reaction's total, so a mixed run reads as one at the top of the report.

MT=5, (n,anything), is the (n,X) reaction: its residuals, read from the reaction library's MF=6 MT=5, are shares of the MT=5 total at each energy (file 6, representation "share"), and its light particles H1 to He4 are their multiplicities times that total (representation "multiplicity", each state's share the multiplicity folded over the spectrum, which can exceed one).

A run refuses when the clipped or held production of its channels, each parent weighted by its density, is more than 0.1% of the material's neutron removal rate; each channel's clipped_share and extrapolated_share are of its own parent's removal. A multiplicity above what the target's nucleons allow is clipped like any other impossible value. unmodelled_mt5 lists the parents whose MT=5 residuals the chain does not model, with the reason; on a reactions subsection that carries MT=5, a run warns when those of the material's own nuclides carry more than 0.1% of the material's removal rate (one written before MT=5 was carried is reported only). The solve continues with an incomplete inventory: absent residuals are not invented, and the missing removal fraction does not bound activity or decay-heat error. The clipped/held production refusals are unchanged.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
step int

Schedule step index, as get_reaction_rates takes it.

required

Returns:

Type Description
Optional[dict]

dict | None: channels, dropped, unmodelled_mt5,

Optional[dict]

sources and mixed, or

Optional[dict]

None if the material or the step is unknown. Each channel has

Optional[dict]

parent, reaction, mt, file (6, 9 or 10),

Optional[dict]

representation ("share", "absolute" or

Optional[dict]

"multiplicity"), complete,

Optional[dict]

completeness_source, denominator, states (each with

Optional[dict]

target, lfs, level_route, level_energy_difference

Optional[dict]

and share, its share of the reaction), removal_share (the

Optional[dict]

reaction's share of the parent's removal rate), clipped_share

Optional[dict]

and extrapolated_share (of the same removal rate),

Optional[dict]

own_total_excess ((energy_ev, ratio) where the listed values

Optional[dict]

most exceed the evaluation's own total, or None),

Optional[dict]

normalisation, source (the branching source the split came

Optional[dict]

from, as named in transmutation_branch_ratios, or None for an

Optional[dict]

(n,X) channel, whose products come from the reactions

Optional[dict]

subsection) and cross_section_library (where the reaction's

Optional[dict]

total came from, or None where that is not known). sources lists

Optional[dict]

the branching sources the channels used, in the configured order,

Optional[dict]

and mixed says whether the run mixes libraries as above. Each

Optional[dict]

dropped channel has parent,

Optional[dict]

reaction, target, reason and removal_share (None

Optional[dict]

where it cannot be folded). unmodelled_mt5 is

Optional[dict]

[(nuclide, share, reason)], MT=5's share of the removal rate

Optional[dict]

of each parent whose MT=5 residuals are not modelled, largest

Optional[dict]

first. Empty for a decay-only step.

Examples:

>>> report = results.get_branching_report(material_id=1, step=0)
>>> report["channels"][0]["representation"]
'absolute'
>>> # A Nb93 foil, transmutation_branch_ratios = ["irdff-ii", "endf-b8.1"]
>>> [(c["reaction"], c["source"]) for c in report["channels"] if c["parent"] == "Nb93"]
[('(n,2n)', 'irdff-ii'), ('(n,gamma)', 'irdff-ii'), ("(n,n')", 'irdff-ii')]
>>> report["mixed"]
True
Source code in yamc/_core/__init__.pyi
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
def get_branching_report(self, material_id: builtins.int, step: builtins.int) -> typing.Optional[dict]:
    r"""
    What the isomeric-branching rule did over one step's spectrum.

    The branching evaluation gives the split and the cross-section library
    the total. How a list's values are read is decided by how the
    evaluation gives them, which the converter records: a complete MF=10
    list (its ground state listed) and every MF=9 list are shares of the
    transport total, applied at each energy; an MF=10 list of isomers only,
    and every ``(n,n')`` list, are absolute productions, the ground state
    taking the rest. This says, per channel, which of those applied and how
    much of the parent's removal rate rests on anything the evaluation
    does not give.

    It also says where each split came from. With several branching
    sources (``transmutation_branch_ratios = ["irdff-ii", "endf-b8.1"]``)
    each channel takes its split from the first source that evaluates it,
    and its ``source`` names that one. ``mixed`` is True when the splits
    come from more than one library, or a split from a library other than
    its reaction's total, so a mixed run reads as one at the top of the
    report.

    MT=5, ``(n,anything)``, is the ``(n,X)`` reaction: its residuals, read
    from the reaction library's MF=6 MT=5, are shares of the MT=5 total
    at each energy (``file`` 6, ``representation`` ``"share"``), and its
    light particles H1 to He4 are their multiplicities times that total
    (``representation`` ``"multiplicity"``, each state's ``share`` the
    multiplicity folded over the spectrum, which can exceed one).

    A run refuses when the clipped or held production of its channels,
    each parent weighted by its density, is more than 0.1% of the
    material's neutron removal rate; each channel's ``clipped_share`` and
    ``extrapolated_share`` are of its own parent's removal. A multiplicity above what the target's nucleons allow is
    clipped like any other impossible value. ``unmodelled_mt5`` lists the
    parents whose MT=5 residuals the chain does not model, with the reason;
    on a reactions subsection that carries MT=5, a run warns when those
    of the material's own nuclides carry more than 0.1% of the material's
    removal rate (one written before MT=5 was carried is reported only).
    The solve continues with an incomplete inventory: absent residuals are
    not invented, and the missing removal fraction does not bound activity
    or decay-heat error. The clipped/held production refusals are unchanged.

    Args:
        material_id: Material ID number.
        step: Schedule step index, as ``get_reaction_rates`` takes it.

    Returns:
        dict | None: ``channels``, ``dropped``, ``unmodelled_mt5``,
        ``sources`` and ``mixed``, or
        None if the material or the step is unknown. Each channel has
        ``parent``, ``reaction``, ``mt``, ``file`` (6, 9 or 10),
        ``representation`` (``"share"``, ``"absolute"`` or
        ``"multiplicity"``), ``complete``,
        ``completeness_source``, ``denominator``, ``states`` (each with
        ``target``, ``lfs``, ``level_route``, ``level_energy_difference``
        and ``share``, its share of the reaction), ``removal_share`` (the
        reaction's share of the parent's removal rate), ``clipped_share``
        and ``extrapolated_share`` (of the same removal rate),
        ``own_total_excess`` (``(energy_ev, ratio)`` where the listed values
        most exceed the evaluation's own total, or None),
        ``normalisation``, ``source`` (the branching source the split came
        from, as named in ``transmutation_branch_ratios``, or None for an
        ``(n,X)`` channel, whose products come from the reactions
        subsection) and ``cross_section_library`` (where the reaction's
        total came from, or None where that is not known). ``sources`` lists
        the branching sources the channels used, in the configured order,
        and ``mixed`` says whether the run mixes libraries as above. Each
        dropped channel has ``parent``,
        ``reaction``, ``target``, ``reason`` and ``removal_share`` (None
        where it cannot be folded). ``unmodelled_mt5`` is
        ``[(nuclide, share, reason)]``, MT=5's share of the removal rate
        of each parent whose MT=5 residuals are not modelled, largest
        first. Empty for a decay-only step.

    Examples:
        >>> report = results.get_branching_report(material_id=1, step=0)
        >>> report["channels"][0]["representation"]
        'absolute'
        >>> # A Nb93 foil, transmutation_branch_ratios = ["irdff-ii", "endf-b8.1"]
        >>> [(c["reaction"], c["source"]) for c in report["channels"] if c["parent"] == "Nb93"]
        [('(n,2n)', 'irdff-ii'), ('(n,gamma)', 'irdff-ii'), ("(n,n')", 'irdff-ii')]
        >>> report["mixed"]
        True
    """

get_production_routes

get_production_routes(material_id: int, product: str, step: int, reaction_depth: int = 1, decay_depth: int = 3) -> Optional[Any]

Every way a product was made over one step, weighted by how much of it arrived down each.

Enumerating routes is easy and weighting them is not. Asked what makes W187, a chain answers Os190(n,a) and Ir192(n,npa) as readily as W186(n,gamma), and nothing in a tungsten foil is osmium. So the walk starts from the nuclides the material actually began with, and each route is weighted by what its own reactions drove rather than by anything read off the chain.

A route is reaction_depth neutron reactions followed by up to decay_depth decays. Its weight is the atoms it starts from, times each reaction step's per-atom production over the step, times the branching of every decay it passes through: a route through a 1% branch delivers 1% of what the reaction made. Reaction steps carry the step duration, so a two-reaction route is in the same units as a one-reaction route and comes out smaller by roughly a factor of the fluence, which is the honest answer for an irradiation short enough that products barely burn.

Parameters:

Name Type Description Default
material_id int

Material ID number.

required
product str

The nuclide whose production is being explained.

required
step int

Schedule step index, as get_reaction_rates takes it.

required
reaction_depth int

Neutron reactions a route may use. 1 is what the published pathway tables carry.

1
decay_depth int

Decays a route may follow after them.

3

Returns:

Type Description
Optional[Any]

list[dict] | None: one entry per route, largest share first, each

Optional[Any]

with route (the string the published tables print, e.g.

Optional[Any]

"W186(n,2n)W185_m1(IT)W185"), steps (the same thing as

Optional[Any]

(parent, kind, target) triples), share (of this product's

Optional[Any]

production, summing to one) and production (atoms per barn-cm,

Optional[Any]

before normalising, so that 100% of almost nothing is

Optional[Any]

distinguishable from 100% of the inventory). Empty when nothing in

Optional[Any]

this material makes the product, which is an answer. None if the

Optional[Any]

material, the step, or the chain is unknown.

Examples:

>>> for r in results.get_production_routes(1, "W185", 0):
...     print(f"{r['route']:<32} {r['share']:.1%}")
W186(n,2n)W185_m1(IT)W185        53.0%
W186(n,2n)W185                   46.8%
Source code in yamc/_core/__init__.pyi
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
def get_production_routes(self, material_id: builtins.int, product: builtins.str, step: builtins.int, reaction_depth: builtins.int = 1, decay_depth: builtins.int = 3) -> typing.Optional[typing.Any]:
    r"""
    Every way a product was made over one step, weighted by how much of it
    arrived down each.

    Enumerating routes is easy and weighting them is not. Asked what makes
    W187, a chain answers ``Os190(n,a)`` and ``Ir192(n,npa)`` as readily as
    ``W186(n,gamma)``, and nothing in a tungsten foil is osmium. So the walk
    starts from the nuclides the material actually began with, and each
    route is weighted by what its own reactions drove rather than by
    anything read off the chain.

    A route is ``reaction_depth`` neutron reactions followed by up to
    ``decay_depth`` decays. Its weight is the atoms it starts from, times
    each reaction step's per-atom production over the step, times the
    branching of every decay it passes through: a route through a 1% branch
    delivers 1% of what the reaction made. Reaction steps carry the step
    duration, so a two-reaction route is in the same units as a one-reaction
    route and comes out smaller by roughly a factor of the fluence, which is
    the honest answer for an irradiation short enough that products barely
    burn.

    Args:
        material_id: Material ID number.
        product: The nuclide whose production is being explained.
        step: Schedule step index, as ``get_reaction_rates`` takes it.
        reaction_depth (int): Neutron reactions a route may use. 1 is what
            the published pathway tables carry.
        decay_depth (int): Decays a route may follow after them.

    Returns:
        list[dict] | None: one entry per route, largest share first, each
        with ``route`` (the string the published tables print, e.g.
        ``"W186(n,2n)W185_m1(IT)W185"``), ``steps`` (the same thing as
        ``(parent, kind, target)`` triples), ``share`` (of this product's
        production, summing to one) and ``production`` (atoms per barn-cm,
        before normalising, so that 100% of almost nothing is
        distinguishable from 100% of the inventory). Empty when nothing in
        this material makes the product, which is an answer. None if the
        material, the step, or the chain is unknown.

    Examples:
        >>> for r in results.get_production_routes(1, "W185", 0):
        ...     print(f"{r['route']:<32} {r['share']:.1%}")
        W186(n,2n)W185_m1(IT)W185        53.0%
        W186(n,2n)W185                   46.8%
    """

to_arrow

to_arrow(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save the result as an Arrow IPC file.

One file holds one result. Every file has the same schema, so the files of a run split into parts read back as one table with polars.scan_ipc("parts/*.arrow") or pyarrow.dataset: one row per stored number, with columns material_id, material_name, step, quantity ("density", "reaction_rate" or "source_rate"), nuclide, reaction, product and value. Everything else the result holds is in the schema metadata, so TransmutationResults.from_arrow gives back the same result.

The file pins, rather than stores, the transmutation chain and the nuclear data the run read; see from_arrow.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write. None returns the file's bytes instead, for a browser or Pyodide session with no file system to write to.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The file's bytes when path is None.

Examples:

>>> results.to_arrow("part_1.arrow")
>>> data = results.to_arrow()
Source code in yamc/_core/__init__.pyi
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
def to_arrow(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save the result as an Arrow IPC file.

    One file holds one result. Every file has the same schema, so the
    files of a run split into parts read back as one table with
    ``polars.scan_ipc("parts/*.arrow")`` or ``pyarrow.dataset``: one row
    per stored number, with columns ``material_id``, ``material_name``,
    ``step``, ``quantity`` (``"density"``, ``"reaction_rate"`` or
    ``"source_rate"``), ``nuclide``, ``reaction``, ``product`` and
    ``value``. Everything else the result holds is in the schema metadata,
    so ``TransmutationResults.from_arrow`` gives back the same result.

    The file pins, rather than stores, the transmutation chain and the
    nuclear data the run read; see ``from_arrow``.

    Args:
        path (str | os.PathLike | None): Where to write. None returns the
            file's bytes instead, for a browser or Pyodide session with no
            file system to write to.

    Returns:
        bytes | None: The file's bytes when ``path`` is None.

    Examples:
        >>> results.to_arrow("part_1.arrow")
        >>> data = results.to_arrow()
    """

from_arrow staticmethod

from_arrow(source: Any) -> TransmutationResults

Load a result that to_arrow saved.

Every getter answers as it did on the saved result, but three of them re-derive from data the run read rather than from what it computed: get_production_routes and get_isomeric_branching walk the transmutation chain, and get_reaction_rate_spectrum reads the initial composition's cross sections. The file pins both: the chain by a sha256 of its contents, and each nuclide by the file it was read from (for a library keyword, a folder of the release the run used). On load the chain is assembled from the configured yamc.transmutation_* sources and kept only if it is the same data, and each nuclide is read again from its file. Whatever cannot be reattached is reported in one UserWarning, and the getters that need it raise RuntimeError rather than answer from other data.

Parameters:

Name Type Description Default
source str | PathLike | bytes

A file path, or the bytes to_arrow() returned.

required

Returns:

Name Type Description
TransmutationResults TransmutationResults

The saved result.

Raises:

Type Description
ValueError

If source is not a transmutation results file, or is from another format version.

Examples:

>>> results = yani.TransmutationResults.from_arrow("part_1.arrow")
Source code in yamc/_core/__init__.pyi
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
@staticmethod
def from_arrow(source: typing.Any) -> TransmutationResults:
    r"""
    Load a result that ``to_arrow`` saved.

    Every getter answers as it did on the saved result, but three of them
    re-derive from data the run read rather than from what it computed:
    ``get_production_routes`` and ``get_isomeric_branching`` walk the
    transmutation chain, and ``get_reaction_rate_spectrum`` reads the
    initial composition's cross sections. The file pins both: the chain by
    a sha256 of its contents, and each nuclide by the file it was read
    from (for a library keyword, a folder of the release the run used).
    On load the chain is assembled from the configured
    ``yamc.transmutation_*`` sources and kept only if it is the same data,
    and each nuclide is read again from its file. Whatever cannot be
    reattached is reported in one ``UserWarning``, and the getters that
    need it raise ``RuntimeError`` rather than answer from other data.

    Args:
        source (str | os.PathLike | bytes): A file path, or the bytes
            ``to_arrow()`` returned.

    Returns:
        TransmutationResults: The saved result.

    Raises:
        ValueError: If ``source`` is not a transmutation results file, or
            is from another format version.

    Examples:
        >>> results = yani.TransmutationResults.from_arrow("part_1.arrow")
    """

TransportResults

Finalized tally results of a simulation run.

Index by tally object, name, or id (results[tally], results["flux"], results[2]); iterate with items().

See also
  • yamc.combine_results(r1, r2, ...) pools independent runs of the same model (distinct seeds) into one result, statistically identical to a single longer run.
  • to_arrow / from_arrow save and reload results losslessly; reloaded results remain combinable.
  • runs lists the provenance (seed, history count, model fingerprint, ...) that combining validates.

source_strength property

source_strength: Optional[tuple[float, str]]

The source strength as (value, per), per being "second" or "pulse", or None for results per source particle.

elapsed property

elapsed: float

Wall-clock elapsed seconds for the simulate call.

tracks property

tracks: Optional[Tracks]

Particle tracks captured during the run, or None if tracking was not requested via simulate_transport(capture_tracks=...).

data_load_time property

data_load_time: Optional[float]

Time spent loading nuclear data and preparing materials (seconds), or None for combined / reloaded results.

transport_time property

transport_time: Optional[float]

Time spent in particle transport only (seconds), or None for combined / reloaded results.

particles_per_second property

particles_per_second: Optional[int]

Particles per second including data loading, or None for combined / reloaded results.

transport_particles_per_second property

transport_particles_per_second: Optional[int]

Particles per second for transport only (excludes data loading), or None for combined / reloaded results.

runs property

runs: list

Provenance of the run(s) behind these results: a list of dicts with seed, n_histories, elapsed_secs, fingerprint, data_libraries, data_releases, material_slots, compute, yamc_version, mpi_size and mpi_rank. One entry per simulate_transport run; concatenated by combine_results.

material_slots maps each geometry material's id to the first slot of the geometry's material store holding it, which is how combine_results tells which material a material filter's id names.

data_releases maps each library keyword the run downloaded data from, and the absolute path of each local release folder it read data from, to a dict with release (the release identifier), manifest_sha256 (the hash of that release's manifest, which pins every file in it), format_version, offline (True when the data origin was unreachable and the newest complete cached release was used; always False for a local folder) and converters (every build that wrote the release's files, as its manifest lists them: the package, its version and the core commit it was compiled from, e.g. ["yani-python 0.22.1 (core 250c439e...)"]; empty for a release published before releases recorded them). Empty when all data came from local directories that are not release folders.

items

items() -> list

for tally, result in results.items(): ...

Source code in yamc/_core/__init__.pyi
8183
8184
8185
8186
def items(self) -> list:
    r"""
    `for tally, result in results.items(): ...`
    """

values

values() -> list

List of TallyResult objects in input order.

Source code in yamc/_core/__init__.pyi
8187
8188
8189
8190
def values(self) -> list:
    r"""
    List of `TallyResult` objects in input order.
    """

keys

keys() -> list

List of Tally configs in input order.

Source code in yamc/_core/__init__.pyi
8191
8192
8193
8194
def keys(self) -> list:
    r"""
    List of `Tally` configs in input order.
    """

with_source_strength

with_source_strength(strength: Optional[float], per: str = 'second') -> TransportResults

These results scaled to a source strength: source particles per second (per="second", a steady source) or per pulse (per="pulse", such as one ICF shot). Transport is linear in the source, so the strength is set after the run and changing it needs no new run.

Returns new results and leaves these unchanged. Calling it again replaces the strength rather than multiplying by it, and None returns to values per source particle. Every tally's mean and standard_deviation scale; relative errors and the statistical checks do not change. The strength is saved by to_arrow, and combine_results refuses results with different strengths.

Parameters:

Name Type Description Default
strength Optional[float]

Source particles per second or per pulse, or None.

required
per str

"second" (default) or "pulse".

'second'

Examples:

>>> per_second = results.with_source_strength(5e15)
>>> per_pulse = results.with_source_strength(1e19, per="pulse")
>>> per_second[heating].to("W/cm3").mean
Source code in yamc/_core/__init__.pyi
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
def with_source_strength(self, strength: typing.Optional[builtins.float], per: builtins.str = 'second') -> TransportResults:
    r"""
    These results scaled to a source strength: source particles per
    second (``per="second"``, a steady source) or per pulse
    (``per="pulse"``, such as one ICF shot). Transport is linear in the
    source, so the strength is set after the run and changing it needs
    no new run.

    Returns new results and leaves these unchanged. Calling it again
    replaces the strength rather than multiplying by it, and ``None``
    returns to values per source particle. Every tally's ``mean`` and
    ``standard_deviation`` scale; relative errors and the statistical
    checks do not change. The strength is saved by ``to_arrow``, and
    ``combine_results`` refuses results with different strengths.

    Args:
        strength: Source particles per second or per pulse, or None.
        per: ``"second"`` (default) or ``"pulse"``.

    Examples:
        >>> per_second = results.with_source_strength(5e15)
        >>> per_pulse = results.with_source_strength(1e19, per="pulse")
        >>> per_second[heating].to("W/cm3").mean
    """

combine

combine(*others: Any) -> TransportResults

Pool this result with one or more other independent runs of the same model into one combined result, statistically identical to a single longer run. Equivalent to yamc.combine_results(self, *others) and to self + other; see combine_results for the validation rules.

Parameters:

Name Type Description Default
*others Any

further TransportResults from distinct-seed runs of the same model.

()
Source code in yamc/_core/__init__.pyi
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
def combine(self, *others: typing.Any) -> TransportResults:
    r"""
    Pool this result with one or more other independent runs of the same
    model into one combined result, statistically identical to a single
    longer run. Equivalent to ``yamc.combine_results(self, *others)`` and
    to ``self + other``; see ``combine_results`` for the validation rules.

    Args:
        *others: further ``TransportResults`` from distinct-seed runs of
            the same model.
    """

to_arrow

to_arrow(path: Optional[str | PathLike | Path] = None) -> Optional[bytes]

Save to an Arrow IPC file at path, or return the file's bytes when path is None (for a browser or Pyodide session).

The round trip is lossless: numeric data, the raw Welford merge state (per-bin m2 and history counts), shapes, the full Tally configurations and the run provenance all survive, so a reloaded result remains fully combinable via combine_results. The file is plain Arrow IPC, directly readable with pyarrow/polars. Captured particle tracks are NOT serialized.

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write.

None

Returns:

Type Description
Optional[bytes]

bytes | None: The file's bytes when path is None.

Source code in yamc/_core/__init__.pyi
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
def to_arrow(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None) -> typing.Optional[bytes]:
    r"""
    Save to an Arrow IPC file at ``path``, or return the file's bytes
    when ``path`` is None (for a browser or Pyodide session).

    The round trip is lossless: numeric data, the raw Welford merge
    state (per-bin ``m2`` and history counts), shapes, the full
    ``Tally`` configurations and the run provenance all survive, so a
    reloaded result remains fully combinable via ``combine_results``.
    The file is plain Arrow IPC, directly readable with
    pyarrow/polars. Captured particle tracks are NOT serialized.

    Args:
        path (str | os.PathLike | None): Where to write.

    Returns:
        bytes | None: The file's bytes when ``path`` is None.
    """

from_arrow classmethod

from_arrow(source: Any) -> TransportResults

Load a TransportResults that to_arrow saved.

Parameters:

Name Type Description Default
source str | PathLike | bytes

A file path, or the bytes to_arrow() returned.

required
Source code in yamc/_core/__init__.pyi
8252
8253
8254
8255
8256
8257
8258
8259
8260
@classmethod
def from_arrow(cls, source: typing.Any) -> TransportResults:
    r"""
    Load a ``TransportResults`` that ``to_arrow`` saved.

    Args:
        source (str | os.PathLike | bytes): A file path, or the bytes
            ``to_arrow()`` returned.
    """

UnstructuredMesh

UnstructuredMesh(vertices: Sequence[Sequence[float]], cells: Sequence[Sequence[int]], cell_regions: Optional[Sequence[str]] = None)

An unstructured mesh for tallies, apart from the transport geometry.

Like an OpenMC/XDG unstructured mesh: any number of them, at any resolution, conformal with the geometry or not, from any mesher. A tally on it (Tally(mesh=mesh)) scores in each cell the track length through it, walking the mesh alongside the transport, so a fine tally mesh does not change how particles are tracked. It carries no materials: where the material state varies cell by cell, the cells belong in the geometry (MeshGeometry.from_tets, MeshGeometry.add_tets), whose own tets a tally takes directly (Tally(mesh=geometry)). The cells are tetrahedra for now.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

[x, y, z] per vertex (cm).

required
cells Sequence[Sequence[int]]

Four vertex indices per cell (a tetrahedron); the tally's bins are in this order. Negatively wound cells are re-wound.

required
cell_regions Sequence[str] | None

A region name per cell, to tally one region with mesh=(mesh, "name"); None puts every cell in one region, "mesh".

None

Raises:

Type Description
ValueError

For a cell with no volume, a vertex index out of range, or a face shared by more than two cells.

Examples:

>>> thermal = yamc.UnstructuredMesh(vertices, cells)  # e.g. a FEniCSx mesh
>>> heating = yamc.Tally(scores=["heating"], mesh=thermal)
Source code in yamc/_core/__init__.pyi
8332
def __new__(cls, vertices: typing.Sequence[typing.Sequence[builtins.float]], cells: typing.Sequence[typing.Sequence[builtins.int]], cell_regions: typing.Optional[typing.Sequence[builtins.str]] = None) -> UnstructuredMesh: ...

regions property

regions: list[str]

The region names, in order of first appearance.

vertices property

vertices: list[list[float]]

All vertex coordinates as [x, y, z] triples (cm).

cells property

cells: list[list[int]]

The cells, as four vertex indices each, in the order given.

cell_regions property

cell_regions: list[str]

The region name of each cell, parallel to cells.

cell_volumes property

cell_volumes: list[float]

The volume of each cell (cm³), parallel to cells.

num_cells property

num_cells: int

Number of cells.

to_vtkhdf

to_vtkhdf(path: str | PathLike[str]) -> None

Write the cells with each one's region_id to a VTKHDF UnstructuredGrid file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
8335
8336
def to_vtkhdf(self, path: builtins.str | os.PathLike[builtins.str]) -> None:
    r"""Write the cells with each one's region_id to a VTKHDF UnstructuredGrid file for ParaView. Requires h5py (pip install yamc[viz])."""

VolumeResult

Result of a stochastic volume calculation: the estimated volume, its std_dev, and the number of num_hits sampled inside the cell.

VoxelData

Result of Geometry.voxelize: flat cell/material id volumes.

cell_ids and material_ids are in (nz, ny, nx) C-order, so numpy.asarray(v.cell_ids).reshape(nz, ny, nx) gives the voxel grid with -1 where no cell is present.

shape property

shape: tuple[int, int, int]

Grid shape as (nx, ny, nz).

WeightWindowBounds

WeightWindowBounds(mesh: RegularRectangularMesh, lower_bounds: Sequence[float], upper_bounds: Optional[Sequence[float]] = None, ratio: float = 5.0, energy_bins: Optional[Sequence[float]] = None, particle: str = 'neutron', survival_factor: float = 3.0, max_split: int = 10, weight_floor: float = 1e-38)

A mesh-based weight-window map applied at collisions: a particle whose weight exceeds the local upper bound is split into equal-weight copies (capped by max_split), one at or below the lower bound plays Russian roulette (survivor weight survival_factor * lower), and one below weight_floor is killed. Bounds are given per (energy group, voxel), flat, indexed group * num_voxels + voxel; a negative lower bound is the "no window" sentinel. Add to Model(variance_reduction=[...]); one entry per particle type is allowed, and two for the same particle is rejected rather than silently shadowed.

A mesh smaller than the geometry is allowed and unbiased: a particle outside it gets no window and behaves analog. That is easy to do by accident and hard to notice, since the only symptom is that the window did not help, so the coverage is reported at the start of a run when verbose includes "summary".

Parameters:

Name Type Description Default
mesh RegularRectangularMesh

RegularRectangularMesh the windows are defined on.

required
lower_bounds Sequence[float]

Lower bound per (group, voxel), flat.

required
upper_bounds Optional[Sequence[float]]

Upper bound per (group, voxel), flat. If omitted, it is ratio * lower_bounds (sentinels preserved).

None
ratio float

Upper/lower ratio used when upper_bounds is omitted (default 5.0).

5.0
energy_bins Optional[Sequence[float]]

Energy group edges in eV, ascending. None = single group.

None
particle str

"neutron" (default) or "photon".

'neutron'
survival_factor float

Roulette survivor weight = factor * lower (default 3).

3.0
max_split int

Maximum copies produced in one split event (default 10).

10
weight_floor float

Absolute weight floor below which a particle is killed (default 1e-38).

1e-38
Source code in yamc/_core/__init__.pyi
8435
def __new__(cls, mesh: RegularRectangularMesh, lower_bounds: typing.Sequence[builtins.float], upper_bounds: typing.Optional[typing.Sequence[builtins.float]] = None, ratio: builtins.float = 5.0, energy_bins: typing.Optional[typing.Sequence[builtins.float]] = None, particle: builtins.str = 'neutron', survival_factor: builtins.float = 3.0, max_split: builtins.int = 10, weight_floor: builtins.float = 1e-38) -> WeightWindowBounds: ...

lower_bounds property

lower_bounds: list[float]

Lower window bounds, flat over (group, voxel).

upper_bounds property

upper_bounds: list[float]

Upper window bounds, flat over (group, voxel).

particle property

particle: str

Particle type these windows apply to ("neutron" or "photon").

survival_factor property

survival_factor: float

Roulette survivor factor.

max_split property

max_split: int

Maximum copies produced in one split event.

weight_floor property

weight_floor: float

Absolute weight floor below which a particle is killed.

WeightWindowGeneratorDeGVR

WeightWindowGeneratorDeGVR(mesh: RegularRectangularMesh, energy_bins: Optional[Sequence[float]] = None, particle: Optional[str | Sequence[str]] = None, density_reduction: Optional[float] = None, ratio: float = 5.0, survival_factor: float = 3.0, max_split: int = 10, weight_floor: float = 1e-38, photon_energy: Optional[float] = None)

DeGVR (Density-extrapolation Global Variance Reduction) weight-window generator. Pass to Model.generate_weight_windows(...), which runs two reduced-density passes internally and returns a WeightWindowBounds for a clean production run.

Parameters:

Name Type Description Default
mesh RegularRectangularMesh

RegularRectangularMesh the windows are generated on.

required
energy_bins Optional[Sequence[float]]

Energy group edges in eV, ascending. None = single group.

None
particle Optional[str | Sequence[str]]

"neutron" (default) or "photon", or a list such as ["neutron", "photon"] to generate a window per particle from a single coupled generation. A single string returns one WeightWindowBounds; a list returns a list, in the given order.

None
density_reduction Optional[float]

Factor N; the fiducial pass uses density / N and the asymptotic pass density / (N / 2). None (default) = auto: N is computed from a particle-free optical-depth ray-trace of the problem (source to deepest voxel; the max over requested particles). Pass a float to override.

None
ratio float

Upper/lower ratio of the generated windows (default 5).

5.0
survival_factor float

Roulette survivor factor (default 3).

3.0
max_split int

Maximum copies per split event (default 10).

10
weight_floor float

Absolute weight floor (default 1e-38).

1e-38
photon_energy Optional[float]

Representative photon energy in eV for the auto-N ray-trace of a photon window. None (default) = auto: the source energy for a photon source, else ~1 MeV for neutron-driven secondary / decay photons. Only affects the auto density_reduction, never bias.

None
Source code in yamc/_core/__init__.pyi
8486
def __new__(cls, mesh: RegularRectangularMesh, energy_bins: typing.Optional[typing.Sequence[builtins.float]] = None, particle: typing.Optional[builtins.str | typing.Sequence[builtins.str]] = None, density_reduction: typing.Optional[builtins.float] = None, ratio: builtins.float = 5.0, survival_factor: builtins.float = 3.0, max_split: builtins.int = 10, weight_floor: builtins.float = 1e-38, photon_energy: typing.Optional[builtins.float] = None) -> WeightWindowGeneratorDeGVR: ...

density_reduction property

density_reduction: Optional[float]

Density-reduction factor N (None = auto, computed at generation time).

photon_energy property

photon_energy: Optional[float]

Representative photon energy (eV) for the auto-N ray-trace, or None (auto).

particle property

particle: Any

Particle type(s), round-tripping the constructor form: a single "neutron" / "photon" string when a string was passed, else a list[str] in request order (a list request always reads back as a list, even of one).

Cell

Cell(region: Region, id: Optional[int] = None, name: Optional[str] = None, material: Optional[Material] = None, volume: Optional[float] = None, fill: MeshGeometry | None = None, translation: Optional[tuple[float, float, float]] = None, rotation: Optional[tuple[float, float, float]] = None, allow_clipping: bool = False)

A region of space filled with an optional material.

A Cell pairs a CSG :class:Region (built from surfaces via the boolean operators &, |, ~ and the halfspace operators +, -) with an optional :class:Material. Cells with no material are void -- particles free-stream through them with no interactions. Each cell may carry an optional integer id and string name; ids are auto-assigned when the cell is added to a :class:Geometry if the user did not set one.

A cell may also be filled by a :class:MeshGeometry (a triangulated CAD body): inside the cell's region a particle is either inside one of the mesh volumes (that volume's material) or in the gap (the cell's own material, which acts as the complement). translation and rotation place the body in the CSG frame.

Examples:

>>> import yamc
>>> sphere = yamc.Sphere(radius=10.0)
>>> iron = yamc.Material(composition={"Fe": 1.0}, density=7.874)
>>> cell = yamc.Cell(region=sphere.below, material=iron, name="iron_ball")

Create a cell from a region, with an optional material and an optional mesh fill.

Parameters:

Name Type Description Default
region Region

CSG region bounding the cell.

required
id Optional[int]

Optional unique integer id (auto-assigned by Geometry).

None
name Optional[str]

Optional name label.

None
material Optional[Material]

Material for the cell. When fill is given this is the complement, filling the region minus the mesh body.

None
volume Optional[float]

Optional known volume in cm^3.

None
fill MeshGeometry | None

Optional :class:MeshGeometry body embedded in the cell. Its volumes keep their own materials; the cell's CSG surfaces still bound everything.

None
translation Optional[tuple[float, float, float]]

Optional (x, y, z) placement of the fill body in the CSG frame, in cm.

None
rotation Optional[tuple[float, float, float]]

Optional (rx, ry, rz) rotation of the fill body in degrees about the CSG-frame x, then y, then z axes, applied before the translation.

None
allow_clipping bool

Permit the fill body to protrude past the region; the protruding part is clipped by the CSG surface. Without it, a protruding fill is a construction error.

False
Source code in yamc/_core/__init__.pyi
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def __new__(cls, region: Region, id: typing.Optional[builtins.int] = None, name: typing.Optional[builtins.str] = None, material: typing.Optional[Material] = None, volume: typing.Optional[builtins.float] = None, fill: MeshGeometry | None = None, translation: typing.Optional[tuple[builtins.float, builtins.float, builtins.float]] = None, rotation: typing.Optional[tuple[builtins.float, builtins.float, builtins.float]] = None, allow_clipping: builtins.bool = False) -> Cell:
    r"""
    Create a cell from a region, with an optional material and an
    optional mesh fill.

    Args:
        region: CSG region bounding the cell.
        id: Optional unique integer id (auto-assigned by Geometry).
        name: Optional name label.
        material: Material for the cell. When ``fill`` is given this
            is the complement, filling the region minus the mesh body.
        volume: Optional known volume in cm^3.
        fill: Optional :class:`MeshGeometry` body embedded in the
            cell. Its volumes keep their own materials; the cell's
            CSG surfaces still bound everything.
        translation: Optional (x, y, z) placement of the fill body in
            the CSG frame, in cm.
        rotation: Optional (rx, ry, rz) rotation of the fill body in
            degrees about the CSG-frame x, then y, then z axes,
            applied before the translation.
        allow_clipping: Permit the fill body to protrude past the
            region; the protruding part is clipped by the CSG surface.
            Without it, a protruding fill is a construction error.
    """

id property writable

id: Optional[int]

Unique numeric identifier for the cell.

Returns:

Type Description
Optional[int]

Integer ID or None if not set

volume property writable

volume: Optional[float]

Volume of the cell in cm^3.

Returns:

Type Description
Optional[float]

Float volume or None if not set

name property writable

name: Optional[str]

Optional name for the cell.

Returns:

Type Description
Optional[str]

String name or None

material property

material: Optional[Material]

Material assigned to this cell.

Returns:

Type Description
Optional[Material]

The Material object the cell was given (not a copy), or None for

Optional[Material]

void cells

fill property

fill: MeshGeometry | None

Mesh body filling this cell.

Returns:

Type Description
MeshGeometry | None

MeshGeometry or None for an ordinary cell

translation property

translation: Optional[tuple[float, float, float]]

Placement of the fill body in the CSG frame, in cm.

Returns:

Type Description
Optional[tuple[float, float, float]]

(x, y, z) tuple or None

rotation property

rotation: Optional[tuple[float, float, float]]

Rotation of the fill body in degrees about the CSG-frame x, y, z axes, applied in that order before the translation.

Returns:

Type Description
Optional[tuple[float, float, float]]

(rx, ry, rz) tuple or None

allow_clipping property

allow_clipping: bool

Whether the fill body may protrude past the region (clipped by the CSG surface).

distance_to_surface

distance_to_surface(point: tuple[float, float, float], direction: tuple[float, float, float]) -> Optional[float]

Compute the distance to the closest surface from a point in a direction (if any)

Source code in yamc/_core/__init__.pyi
312
313
314
315
def distance_to_surface(self, point: tuple[builtins.float, builtins.float, builtins.float], direction: tuple[builtins.float, builtins.float, builtins.float]) -> typing.Optional[builtins.float]:
    r"""
    Compute the distance to the closest surface from a point in a direction (if any)
    """

closest_surface

closest_surface(point: tuple[float, float, float], direction: tuple[float, float, float]) -> Optional[tuple[str, float]]

Return the boundary type and distance to the closest surface, or None if no intersection

Source code in yamc/_core/__init__.pyi
316
317
318
319
def closest_surface(self, point: tuple[builtins.float, builtins.float, builtins.float], direction: tuple[builtins.float, builtins.float, builtins.float]) -> typing.Optional[tuple[builtins.str, builtins.float]]:
    r"""
    Return the boundary type and distance to the closest surface, or None if no intersection
    """

bounding_box

bounding_box() -> BoundingBox

Get the axis-aligned bounding box for this cell's region.

Returns:

Type Description
BoundingBox

BoundingBox object with lower_left and upper_right coordinates

Source code in yamc/_core/__init__.pyi
344
345
346
347
348
349
350
def bounding_box(self) -> BoundingBox:
    r"""
    Get the axis-aligned bounding box for this cell's region.

    Returns:
        BoundingBox object with lower_left and upper_right coordinates
    """

contains

contains(x: float, y: float, z: float) -> bool

Check if a point is inside this cell.

Parameters:

Name Type Description Default
x float

X coordinate

required
y float

Y coordinate

required
z float

Z coordinate

required

Returns:

Type Description
bool

True if the point is inside the cell, False otherwise

Source code in yamc/_core/__init__.pyi
351
352
353
354
355
356
357
358
359
360
361
362
def contains(self, x: builtins.float, y: builtins.float, z: builtins.float) -> builtins.bool:
    r"""
    Check if a point is inside this cell.

    Args:
        x: X coordinate
        y: Y coordinate
        z: Z coordinate

    Returns:
        True if the point is inside the cell, False otherwise
    """

calculate_volume

calculate_volume(samples: int = 100000, bounding_box: Optional[BoundingBox] = None, seed: Optional[int] = None) -> VolumeResult

Estimate the volume of this cell by stochastic sampling.

Sets cell.volume to the estimated value and returns a VolumeResult. For a cell with a mesh fill the estimate covers the complement only (the region minus the placed body), which is the space the cell's own material occupies.

Parameters:

Name Type Description Default
samples int

Number of random points to sample (default 100,000)

100000
bounding_box Optional[BoundingBox]

Optional BoundingBox to sample within. Defaults to the cell's region bounding box.

None
seed Optional[int]

Optional RNG seed for reproducibility (default 1)

None

Returns:

Type Description
VolumeResult

VolumeResult with volume, std_dev, and num_hits

Source code in yamc/_core/__init__.pyi
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def calculate_volume(self, samples: builtins.int = 100000, bounding_box: typing.Optional[BoundingBox] = None, seed: typing.Optional[builtins.int] = None) -> VolumeResult:
    r"""
    Estimate the volume of this cell by stochastic sampling.

    Sets `cell.volume` to the estimated value and returns a VolumeResult.
    For a cell with a mesh ``fill`` the estimate covers the complement
    only (the region minus the placed body), which is the space the
    cell's own material occupies.

    Args:
        samples: Number of random points to sample (default 100,000)
        bounding_box: Optional BoundingBox to sample within. Defaults to the cell's region bounding box.
        seed: Optional RNG seed for reproducibility (default 1)

    Returns:
        VolumeResult with volume, std_dev, and num_hits
    """

sample_slice

sample_slice(origin: Optional[Any] = None, width: Optional[Any] = None, resolution: Optional[Any] = None, basis: str = 'xy') -> GeometrySliceData

Generate 2D maps of cell ID and material ID for this cell.

A mesh fill is not resolved here (the whole region maps to the cell's own ids); use Geometry.sample_slice to see the fill bodies.

Parameters:

Name Type Description Default
origin Optional[Any]

Origin of the plot (tuple/list of 3 floats). Defaults to bbox center or (0,0,0).

None
width Optional[Any]

Width of the plot (tuple/list of 2 floats). Defaults to bbox width or (10,10).

None
resolution Optional[Any]

Raster resolution as a total pixel budget (int) or an explicit (h, v) tuple. Defaults to 40000.

None
basis str

The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

'xy'

Returns:

Name Type Description
A GeometrySliceData

class:GeometrySliceData -- also supports tuple unpacking.

Source code in yamc/_core/__init__.pyi
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def sample_slice(self, origin: typing.Optional[typing.Any] = None, width: typing.Optional[typing.Any] = None, resolution: typing.Optional[typing.Any] = None, basis: builtins.str = 'xy') -> GeometrySliceData:
    r"""
    Generate 2D maps of cell ID and material ID for this cell.

    A mesh ``fill`` is not resolved here (the whole region maps to
    the cell's own ids); use ``Geometry.sample_slice`` to see the
    fill bodies.

    Args:
        origin: Origin of the plot (tuple/list of 3 floats). Defaults to bbox center or (0,0,0).
        width: Width of the plot (tuple/list of 2 floats). Defaults to bbox width or (10,10).
        resolution: Raster resolution as a total pixel budget (int) or an explicit (h, v) tuple. Defaults to 40000.
        basis: The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

    Returns:
        A :class:`GeometrySliceData` -- also supports tuple unpacking.
    """

voxelize

voxelize(lower_left: Sequence[float], spacing: Sequence[float], shape: tuple[int, int, int]) -> list[int]

Rasterize this cell onto a 3D voxel grid (the compiled core of Cell.to_vtkhdf).

The caller resolves the cell / material id; this returns only the inside/outside mask so the hot contains loop runs in Rust.

Parameters:

Name Type Description Default
lower_left Sequence[float]

Grid minimum corner (x, y, z).

required
spacing Sequence[float]

Voxel size (dx, dy, dz).

required
shape tuple[int, int, int]

Voxel counts (nx, ny, nz).

required

Returns:

Type Description
list[int]

Flat mask in (nz, ny, nx) C-order: 1 inside, 0 outside.

Source code in yamc/_core/__init__.pyi
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def voxelize(self, lower_left: typing.Sequence[builtins.float], spacing: typing.Sequence[builtins.float], shape: tuple[builtins.int, builtins.int, builtins.int]) -> builtins.list[builtins.int]:
    r"""
    Rasterize this cell onto a 3D voxel grid (the compiled core of
    ``Cell.to_vtkhdf``).

    The caller resolves the cell / material id; this returns only the
    inside/outside mask so the hot ``contains`` loop runs in Rust.

    Args:
        lower_left: Grid minimum corner ``(x, y, z)``.
        spacing: Voxel size ``(dx, dy, dz)``.
        shape: Voxel counts ``(nx, ny, nz)``.

    Returns:
        Flat mask in (nz, ny, nx) C-order: 1 inside, 0 outside.
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
413
414
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

plot

plot(*args: Any, **kwargs: Any) -> InteractivePlot

Render an interactive plot of this cell. See the docs for keyword arguments.

Source code in yamc/_core/__init__.pyi
415
416
def plot(self, *args: typing.Any, **kwargs: typing.Any) -> InteractivePlot:
    r"""Render an interactive plot of this cell. See the docs for keyword arguments."""

DataUncertainty

DataUncertainty(seed: int = 1, samples: Optional[int] = None, sources: Optional[Sequence[str]] = None, attribution: bool = False, convergence: Optional[float] = None)

Request nuclear-data uncertainty on a transmutation.

Pass one to :meth:Material.transmute and the result carries a standard deviation on every nuclide density alongside the mean.

What it can cover, by source (DataUncertainty.available_sources()):

  • "cross_sections": the activation cross sections, sampled from the ENDF MF=33 covariance folded against this material's own spectrum, and where the library folder carries the evaluation's resonance parameters (MF=2 and MF=32, resonance_parameters.arrow), the parameters themselves: each replica draws them from their covariance, rebuilds the resonance range's cross sections from the draw and Doppler broadens the change to the temperature in use, so the resonance range's uncertainty is exact in the parameters rather than first order. On a transport-coupled run the change is folded against the flux the transport tallied on the nuclide's own energy grid through its resonances, so a self-shielded resonance is weighted with its own flux dip. A nuclide whose parameters cannot be sampled keeps the first-order MF=32 rows of covariance.arrow, and the report says which and why;
  • "flux_spectrum": the spectrum itself, from the per-bin flux_std_dev given on a Pulse;
  • "half_life": every reachable nuclide's half-life, from the decay data's own standard deviation. A replica's half-lives are used in its solve AND in the activity, decay heat and dose evaluated from it, so a saturated activity (lambda N = R) is correctly insensitive to its own half-life rather than inheriting the density's spread;
  • "decay_branching": the decay branching ratios of every reachable parent with several modes and a stated sigma, drawn so the parent's total is kept and every ratio stays between zero and it: each mode but one from a logit-normal with the evaluated ratio as its mean and the stated sigma as its standard deviation, the last their complement, coupled so the modes carry the zero-sum covariance of largest entropy that realises every stated sigma (for two or three modes the only one). A small branch with a large relative sigma is drawn skewed, never below zero. A largest sigma above the sum of the others' is drawn as that sum; a single mode stating no sigma is the complement of the rest when it is the largest or the only way to trade; a mode whose sigma no ratio with its mean can have (sigma**2 >= b * (T - b)), and a mode stating none otherwise, are held at their ratios and the rest share what is left. The report names every parent short of its stated sigmas by why;
  • "statistical": the Monte Carlo uncertainty of transport-tallied reaction rates, from their per-history covariance, drawn independently for each material since their tallies are separate estimates. It applies to Model.simulate_transmutation, as "flux_spectrum" applies only to Material.transmute; each call ignores the other's, and the report's sources lists what actually applied;
  • "decay_energy": each nuclide's mean decay energy, from the sigma the decay data gives each recoverable-heat component (beta, gamma, alpha), or the total's where it gives no split. It moves decay heat only: a decay energy never enters the solve, so the inventory and activity are untouched;
  • "decay_photon_lines": each decay photon spectrum's normalisation (FD for lines, FC for a continuum), one draw per spectrum common to all its lines, and each line's own intensity (dRI) and energy (dER), from the decay data's MT=457 sigmas. It moves the decay photon spectrum, the contact dose and, through the gamma decay energy E_EM, which follows each replica's drawn lines in place of a "decay_energy" draw, the decay heat; no photon enters the solve. The decay data do not state how a nuclide's photon intensities are correlated beyond the normalisation (between the lines' dRI, between a normalisation and its lines, between gamma and x-ray spectra), so each output is evaluated at both ends: Estimate.std_dev takes them independent and Estimate.std_dev_correlated fully correlated. A D1S dose (PulseSchedule.time_correct_tally) draws the normalisations alone;
  • "fission_yield": each fissioning parent's independent yields (MT=454), from the DY the evaluation states on each, drawn on the tape's own products and summed onto the chain's the way the converter summed the nominal yields. No evaluation states a correlation between yields, so each is drawn independently and the yields of a draw are not renormalised. An actinide that borrows another's yields shares its draw. Needs a chain that carries the evaluated yields (fission_yields/evaluated_yields.arrow); without one every parent is listed under no_fission_yield_uncertainty;
  • "isomer_branching": the isomeric split of every reachable reaction whose evaluation states the MF=40 covariance of its final states' production cross sections (the MF=10 partials of the branching subsection, from its branching_covariance.arrow). Each stated state's production is drawn on the covariance's own energy grid, folded against the same spectrum and weight as the nominal split, and the split re-made from the draw by the nominal branching rule. Where the list names its ground state only the shares move, and they still sum to one, while the reaction's total stays the cross sections' (MF=33), so the uncertainty of the total is not counted twice. An isomer listed alone, and every (n,n') isomer, is an absolute production: it is made at its drawn value, the ground state taking the rest of the total, so its own MF=40 sigma replaces the MF=33 sigma of its reaction that it carries with "cross_sections" alone, and can be the smaller. Applies to Material.transmute; a transport run's split comes from tallied partials and is held.

Each cross-section draw is a lognormal multiplier with the covariance's own mean and variance, so a sampled rate is never negative and nothing is floored. The correlated Gaussian deviates are kept (a Gaussian copula), so the ordering between channels is preserved, but the Pearson correlations come out weaker than evaluated as the sigmas grow. Half-lives and decay energies are drawn the same way, one nuclide at a time: the decay data states a mean and a sigma for each and no correlation, so the draws carry exactly what the evaluation states and are never negative. So are the decay photon normalisations, intensities and energies, with the one correlation the data does state, a spectrum's normalisation common to its lines, and the ones it does not state bounded rather than assumed.

Held at their nominal values, with uncertainties of their own that this does not propagate:

  • the decay branching ratios "decay_branching" does not sample (a sigma wider than the ratio allows, or no sigma to draw), and the per-decay photon lines and decay energy of a drawn parent, which follow its nominal branching;
  • the isomeric split of a reaction whose evaluation states no MF=40 covariance on any of its states, listed in no_isomer_branching_uncertainty, and MF=40 blocks "isomer_branching" cannot use (another evaluation's partner, a partner that is not an MF=10 production, NC, absolute and short-range layouts, a state the branching rule folds no curve for), counted in isomer_branching_blocks_not_used;
  • covariance correlating an evaluation with one the run does not hold (MAT1 naming a material not in the run, counted in skipped_cross_material), covariance with a quantity that is not a cross section (XMF1 not 0 or 3), covariance derived from other sections by an NC block that cannot be derived (LTY 1-4, or an LTY=0 block counted in skipped_nc), the covariance of a lumped reaction (MT=851-870) stated in barns, listed in lumped_covariance_not_assignable, and the resonance-parameter covariance (MF=32) of a range neither sampled nor in covariance.arrow: a library converted before the converter wrote either, or a resonance range whose formalism endf does not reconstruct. No library yani reads states an XMF1 other than 0 or 3, an NC block with LTY 1-4, or a lump in barns. What is sampled is each reaction's explicit MF=33 blocks, the resonance parameters where the folder carries them and otherwise the resonance-range blocks the converter derives from MF=32 and writes beside them, the blocks of a lumped reaction for each of its components (one component is the lump; several each take the lump's relative perturbation, moving together), for a level sum with no covariance of its own its levels' (W186 (n,p) as the lumped MT 855 of MT 600 and 649), and for a reaction an LTY=0 NC block states as a sum of others (ENDF/B-VIII.1 O16 (n,p) as MT 600 to 603, U235 MT 4 as MT 51 plus the lumped MT 851), the covariance derived from the named reactions' own blocks and the cross blocks between them. A block correlating two evaluations the run both holds (the neutron standards: ENDF/B-VIII.1 U235 fission with U238 fission and capture, Pu239 fission, Au197 capture and Li6 (n,t)) is applied, counted in applied_cross_material: the two nuclides are drawn jointly, one draw per replica shared by every material;
  • the self-shielding correction, when self_shielding_chord or self_shielding_shape is given: the shielded flux is built once from the nominal cross sections and reused by every replica, sampled resonance parameters included;
  • on a transport run, the flux's response to a perturbed cross section: there is one transport, not one per replica. The tallied values themselves are still drawn by the "statistical" source;
  • the decay photon spectrum covariance and continuum shape (MF=8 MT=457 LCOV, which no library states), photon attenuation (XCOM), air energy absorption (NIST SRD 126), the ICRP-116 fluence-to-dose coefficients and the contact-dose build-up factor;
  • the material's composition, density, natural isotopic abundances and the AME2020 atomic masses used to convert mass fractions;
  • any source switched off with sources, or with nothing to act on (a spectrum given without flux_std_dev). When only some of a material's spectra have one, the entry is "flux spectrum (spectra without a sigma only)" and spectra_without_flux_sigma gives the count. A rate under a spectrum with a sigma that the flux draw cannot move is named in flux_rates_without_terms.

TransmutationResults.get_data_uncertainty_info lists every one of these that applied to a material under not_perturbed, along with any nuclide whose evaluation carries no covariance, any unstable nuclide whose half-life or decay energy has no stated sigma, and any whose stated half-life or decay-energy sigma no draw can carry.

Parameters:

Name Type Description Default
seed int

Base seed. A given nuclide's perturbation in a given replica is a pure function of (seed, replica, nuclide), so the same seed reproduces the same answer regardless of replica count, iteration order, or what else is in the material.

1
samples int

Fixed replica count. Leave as None (the default) to let the solver add replicas, 64 at a time, until every tracked standard deviation is known to convergence. A number here bounds cost or reproduces a specific run: exactly that many replicas run, and the info still lists any standard deviation that did not reach convergence.

None
sources list[str]

Which inputs to perturb. None (the default) means every source this build implements. Restricting it is how a run isolates one contribution, so that adding a source and watching the inventory sigma grow is a measurement rather than a guess.

Naming a source this build cannot perturb raises, rather than being ignored. A source that has not landed yet must not look like one that contributed nothing. DataUncertainty.available_sources() lists what there is.

None
attribution bool

Also say where the uncertainty comes from, read with TransmutationResults.get_uncertainty_breakdown. Off by default because it costs further solves: one ensemble per source, each source alone, and one deterministic solve per contributor. It changes none of the numbers the run otherwise reports.

False
convergence float

How well each standard deviation must be known before the run stops: the standard error of the sample standard deviation, relative to it, SE(sigma) / sigma. None (the default) means 0.05. The standard error allows for a heavy tail (it carries the sample kurtosis), so a skewed output needs more replicas than a Gaussian one, for which a target t needs about 1 / (2 t^2) + 1: 201 at 0.05. It is judged at every step, not only the last, on every nuclide density within 1e-6 of the largest at that step and on the total activity, decay heat and decay photon line rate, leaving out any whose standard deviation is under 0.01% of its value. The photon spectrum line by line and the contact dose are not judged, as their dose quantity and build-up are chosen when they are read. At least 128 replicas run whatever the target, since the kurtosis is too noisy to trust on fewer, and at most 1024: a run that stops there sets hit_cap in the info and lists every output, nuclide and step that missed under unconverged. Must be between 0 and 1.

None

Examples:

>>> results = iron.transmute(
...     schedule=sched,
...     data_uncertainty=yamc.DataUncertainty(seed=42),
... )
>>> results.get_nuclide_density(iron.id, "Mn56", 1)
1.234e-08
>>> results.get_nuclide_uncertainty(iron.id, "Mn56", 1)
8.7e-10
Source code in yamc/_core/__init__.pyi
902
def __new__(cls, seed: builtins.int = 1, samples: typing.Optional[builtins.int] = None, sources: typing.Optional[typing.Sequence[builtins.str]] = None, attribution: builtins.bool = False, convergence: typing.Optional[builtins.float] = None) -> DataUncertainty: ...

attribution property

attribution: bool

Whether the run also says where the uncertainty comes from.

convergence property

convergence: float

The target for each standard deviation's standard error, relative to it, that an adaptive run stops on.

available_sources staticmethod

available_sources() -> list[str]

The uncertainty sources this build can perturb.

Returns:

Type Description
list[str]

list[str]: Names accepted by the sources argument.

Source code in yamc/_core/__init__.pyi
903
904
905
906
907
908
909
910
@staticmethod
def available_sources() -> builtins.list[builtins.str]:
    r"""
    The uncertainty sources this build can perturb.

    Returns:
        list[str]: Names accepted by the ``sources`` argument.
    """

Geometry

Geometry(cells: Sequence[Cell])

A CSG geometry: a list of cells defining the simulation domain.

A Geometry collects :class:Cell objects into a complete spatial description for transport. Cell IDs are auto-assigned where the user did not set them; every :class:Material already has one from construction. The geometry validates that surface IDs are unique, and that no two different Material objects share an ID, across the cells and their mesh fills, on construction.

For mesh-based geometry (an Arrow IPC mesh, e.g. from CAD), use :class:MeshGeometry instead.

Examples:

>>> import yamc
>>> sphere = yamc.Sphere(radius=10.0, boundary='vacuum')
>>> iron = yamc.Material(composition={"Fe": 1.0}, density=7.874)
>>> cell = yamc.Cell(region=sphere.below, material=iron)
>>> geometry = yamc.Geometry([cell])
Source code in yamc/_core/__init__.pyi
1361
def __new__(cls, cells: typing.Sequence[Cell]) -> Geometry: ...

cells property

cells: list[Cell]

List of all cells in the geometry.

Returns:

Type Description
list[Cell]

List of Cell objects

find_cell

find_cell(x: float, y: float, z: float) -> Optional[Cell]

Find the cell containing a given point in space.

Parameters:

Name Type Description Default
x float

X coordinate

required
y float

Y coordinate

required
z float

Z coordinate

required

Returns:

Type Description
Optional[Cell]

Cell object if found, None if the point is outside all cells

Source code in yamc/_core/__init__.pyi
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
def find_cell(self, x: builtins.float, y: builtins.float, z: builtins.float) -> typing.Optional[Cell]:
    r"""
    Find the cell containing a given point in space.

    Args:
        x: X coordinate
        y: Y coordinate
        z: Z coordinate

    Returns:
        Cell object if found, None if the point is outside all cells
    """

bounding_box

bounding_box() -> BoundingBox

Get the axis-aligned bounding box containing all cells in the geometry.

Returns:

Type Description
BoundingBox

BoundingBox object with lower_left and upper_right coordinates

Source code in yamc/_core/__init__.pyi
1375
1376
1377
1378
1379
1380
1381
def bounding_box(self) -> BoundingBox:
    r"""
    Get the axis-aligned bounding box containing all cells in the geometry.

    Returns:
        BoundingBox object with lower_left and upper_right coordinates
    """

calculate_volume

calculate_volume(samples: int = 100000, bounding_box: Optional[BoundingBox] = None, seed: Optional[int] = None) -> dict[int, VolumeResult]

Estimate volumes of all cells by stochastic sampling.

Populates each cell's volume attribute with the estimated value, and the volume of each cell's material. A material held by several cells (cells given the same Material, or the volumes of a mesh fill that share one) gets the total of those cells.

Parameters:

Name Type Description Default
samples int

Number of random points to sample (default 100,000)

100000
bounding_box Optional[BoundingBox]

Optional BoundingBox to sample within. Defaults to the geometry's bounding box.

None
seed Optional[int]

Optional RNG seed for reproducibility (default 1)

None

Returns:

Type Description
dict[int, VolumeResult]

Dictionary mapping cell id -> VolumeResult

Raises:

Type Description
ValueError

If the bounding box is infinite and none is given.

Source code in yamc/_core/__init__.pyi
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
def calculate_volume(self, samples: builtins.int = 100000, bounding_box: typing.Optional[BoundingBox] = None, seed: typing.Optional[builtins.int] = None) -> builtins.dict[builtins.int, VolumeResult]:
    r"""
    Estimate volumes of all cells by stochastic sampling.

    Populates each cell's `volume` attribute with the estimated value, and
    the volume of each cell's material. A material held by several cells
    (cells given the same Material, or the volumes of a mesh fill that
    share one) gets the total of those cells.

    Args:
        samples: Number of random points to sample (default 100,000)
        bounding_box: Optional BoundingBox to sample within. Defaults to the geometry's bounding box.
        seed: Optional RNG seed for reproducibility (default 1)

    Returns:
        Dictionary mapping cell id -> VolumeResult

    Raises:
        ValueError: If the bounding box is infinite and none is given.
    """

sample_slice

sample_slice(origin: Optional[Any] = None, width: Optional[Any] = None, resolution: Optional[Any] = None, basis: str = 'xy') -> GeometrySliceData

Generate 2D maps of cell IDs and material IDs for a slice through the geometry.

Parameters:

Name Type Description Default
origin Optional[Any]

Origin of the plot (tuple of 3 floats). If unspecified, defaults to the center of the bounding box, or (0.0, 0.0, 0.0) if bounding box contains inf.

None
width Optional[Any]

Width of the plot in each basis direction (tuple of 2 floats). If unspecified, defaults to the width of the bounding box, or (10.0, 10.0) if bounding box contains inf.

None
resolution Optional[Any]

Raster resolution as a total pixel budget (int, default 40000) or an explicit (h, v) tuple. If a single int, resolution in each direction are calculated from the aspect ratio.

None
basis str

The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

'xy'

Returns:

Name Type Description
A GeometrySliceData

class:GeometrySliceData with cell_ids, material_ids,

GeometrySliceData

h_edges, v_edges, extent, h_label, v_label, and

GeometrySliceData

an edges() method. Also supports tuple unpacking:

GeometrySliceData

cell_ids, material_ids = geometry.sample_slice(...).

Source code in yamc/_core/__init__.pyi
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
def sample_slice(self, origin: typing.Optional[typing.Any] = None, width: typing.Optional[typing.Any] = None, resolution: typing.Optional[typing.Any] = None, basis: builtins.str = 'xy') -> GeometrySliceData:
    r"""
    Generate 2D maps of cell IDs and material IDs for a slice through the geometry.

    Args:
        origin: Origin of the plot (tuple of 3 floats). If unspecified, defaults to
            the center of the bounding box, or (0.0, 0.0, 0.0) if bounding box contains inf.
        width: Width of the plot in each basis direction (tuple of 2 floats). If unspecified,
            defaults to the width of the bounding box, or (10.0, 10.0) if bounding box contains inf.
        resolution: Raster resolution as a total pixel budget (int, default 40000) or an explicit (h, v) tuple.
            If a single int, resolution in each direction are calculated from the aspect ratio.
        basis: The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

    Returns:
        A :class:`GeometrySliceData` with ``cell_ids``, ``material_ids``,
        ``h_edges``, ``v_edges``, ``extent``, ``h_label``, ``v_label``, and
        an ``edges()`` method.  Also supports tuple unpacking:
        ``cell_ids, material_ids = geometry.sample_slice(...)``.
    """

voxelize

voxelize(lower_left: Sequence[float], spacing: Sequence[float], shape: tuple[int, int, int]) -> VoxelData

Rasterize this geometry onto a 3D voxel grid (the compiled core of Geometry.to_vtkhdf).

Parameters:

Name Type Description Default
lower_left Sequence[float]

Grid minimum corner (x, y, z).

required
spacing Sequence[float]

Voxel size (dx, dy, dz).

required
shape tuple[int, int, int]

Voxel counts (nx, ny, nz).

required

Returns:

Type Description
VoxelData

VoxelData with flat cell_ids / material_ids in (nz, ny, nx)

VoxelData

C-order (-1 where no cell is present).

Source code in yamc/_core/__init__.pyi
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
def voxelize(self, lower_left: typing.Sequence[builtins.float], spacing: typing.Sequence[builtins.float], shape: tuple[builtins.int, builtins.int, builtins.int]) -> VoxelData:
    r"""
    Rasterize this geometry onto a 3D voxel grid (the compiled core of
    ``Geometry.to_vtkhdf``).

    Args:
        lower_left: Grid minimum corner ``(x, y, z)``.
        spacing: Voxel size ``(dx, dy, dz)``.
        shape: Voxel counts ``(nx, ny, nz)``.

    Returns:
        VoxelData with flat ``cell_ids`` / ``material_ids`` in (nz, ny, nx)
        C-order (``-1`` where no cell is present).
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
1435
1436
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

plot

plot(*args: Any, **kwargs: Any) -> InteractivePlot

Render an interactive geometry slice plot. See the docs for keyword arguments.

Source code in yamc/_core/__init__.pyi
1437
1438
def plot(self, *args: typing.Any, **kwargs: typing.Any) -> InteractivePlot:
    r"""Render an interactive geometry slice plot. See the docs for keyword arguments."""

Halfspace

One side of a Surface (positive or negative half-space); the atom from which Regions are composed via boolean operators.

voxelize

voxelize(lower_left: Sequence[float], spacing: Sequence[float], shape: tuple[int, int, int]) -> list[int]

Rasterize this halfspace onto a 3D voxel grid (the compiled core of Halfspace.to_vtkhdf).

Parameters:

Name Type Description Default
lower_left Sequence[float]

Grid minimum corner (x, y, z).

required
spacing Sequence[float]

Voxel size (dx, dy, dz).

required
shape tuple[int, int, int]

Voxel counts (nx, ny, nz).

required

Returns:

Type Description
list[int]

Flat mask in (nz, ny, nx) C-order: 1 inside, 0 outside.

Source code in yamc/_core/__init__.pyi
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
def voxelize(self, lower_left: typing.Sequence[builtins.float], spacing: typing.Sequence[builtins.float], shape: tuple[builtins.int, builtins.int, builtins.int]) -> builtins.list[builtins.int]:
    r"""
    Rasterize this halfspace onto a 3D voxel grid (the compiled core of
    ``Halfspace.to_vtkhdf``).

    Args:
        lower_left: Grid minimum corner ``(x, y, z)``.
        spacing: Voxel size ``(dx, dy, dz)``.
        shape: Voxel counts ``(nx, ny, nz)``.

    Returns:
        Flat mask in (nz, ny, nx) C-order: 1 inside, 0 outside.
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
1506
1507
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

Model

Model(geometry: Geometry | MeshGeometry, tallies: Optional[Sequence[Tally]] = None, source: NeutronSource | PhotonSource | Sequence[NeutronSource | PhotonSource] | None = None, transport_secondary_photons: bool = False, use_decay_photons: bool = False, photon_cutoff_energy: float = 1000.0, electron_treatment: Literal['ttb', 'local'] | None = None, free_gas_threshold: float = 400.0, max_lost_particles: int = 10, gpu_max_steps_per_particle: Optional[int] = None, verbose: Optional[Sequence[str]] = None, tracking_mode: str = 'surface', variance_reduction: Sequence[SurvivalBiasing | WeightWindowBounds] | None = None, gpu_fission_bank: bool = True)

A complete Monte Carlo simulation model.

The Model combines geometry, source, tallies, and simulation parameters into a single object that can be executed to perform particle transport.

The Model describes what to simulate -- the physical system and the observations. Per-run execution parameters (total_particles, seed, threads, max_runtime, compute) are arguments of simulate_transport / simulate_transmutation, not of the Model.

A :class:MeshGeometry used as the whole geometry must be closed by a vacuum boundary. When the mesh has none, the run adds a vacuum box 10 cm outside its bounding box around a void implicit complement (and prints its extent), or raises ValueError when the implicit complement holds a material (pass graveyard_offset to the MeshGeometry then). A mesh tally that reaches outside the vacuum boundary gets a warning, since its outer voxels read zero.

Parameters:

Name Type Description Default
geometry Geometry | MeshGeometry

The geometry defining the problem's spatial domain.

required
tallies Optional[Sequence[Tally]]

Optional list of tallies to score during simulation.

None
source NeutronSource | PhotonSource | Sequence[NeutronSource | PhotonSource] | None

Source distribution(s) for particle sampling.

None
transport_secondary_photons bool

Transport secondary photons produced by neutron interactions, i.e. coupled neutron->photon (default: False). A PhotonSource transports photons regardless of this flag.

False
use_decay_photons bool

Enable D1S decay photon mode (default: False). It reads yamc.transmutation_decay_data and yamc.transmutation_reactions, which have no default: a run with either unset raises ValueError before any data is loaded.

False
photon_cutoff_energy float

Photon energy cutoff in eV (default: 1000.0).

1000.0
electron_treatment Literal['ttb', 'local'] | None

Electron energy treatment, "ttb" (thick-target bremsstrahlung) or "local" (local deposition). Default: "ttb".

None
free_gas_threshold float

Free-gas threshold multiplier (default: 400.0).

400.0
max_lost_particles int

Max lost particles before abort (default: 10). Mesh-geometry transport verifies every surface crossing spatially: a crossing whose flight segment passes through a surface foreign to the current volume (overlapping or self-intersecting mesh volumes, or a corrupted tracking state) records the particle as lost, exactly like a geometry gap.

10
gpu_max_steps_per_particle Optional[int]

Hard cap on transport steps per particle on the GPU path, which needs a bounded loop. CPU transport runs every history to completion (ending it on absorption, leakage or a lost particle) and ignores the value, warning if you set it and then run on the CPU, since the request has no effect there. Default: 100000, high enough that the GPU matches the CPU's run-to-completion behaviour for strong scatterers such as a pure-H2 sphere (a 1000 cap cost ~10% of the integral flux there); the loop exits early once a particle leaks or is absorbed, so it is free for fast-escaping problems. A cap that binds is an error: if any history in a GPU launch is still transporting at the cap, simulate_transport raises ValueError instead of returning the under-counted tallies. Raise the cap or run on the CPU.

None
verbose Optional[Sequence[str]]

Progress output as a list of independent flags (reported in source particles). Any of "progress" (Progress: N/total particles (P%) lines), "eta" (progress with elapsed + ETA), "tally" (each tally's running mean ± std), "summary" (end-of-run completion + per-tally statistics), and "nuclear_data" (one line per nuclear-data file as it loads, plus the transmutation chain file). An empty list [] is fully silent. None (default) uses ["eta", "tally", "summary"].

None
tracking_mode str

Particle-transport algorithm. One of:

  • "surface" (default): standard distance-to-nearest-boundary ray tracing. Always correct; the right choice for typical geometries that mix dense and sparse regions and contain voids.
  • "hybrid": Woodcock delta tracking with an automatic per-cell fallback to surface tracking in voids / large low-density regions. This is the recommended Woodcock mode for real models, since most fusion geometries have a vacuum vessel or air: it keeps delta tracking's speed in dense regions and is never pathological in voids.
  • "woodcock": pure delta tracking with no fallback. Only use this on geometrically dense, void-free models (e.g. finely diced or CAD-tessellated geometry); in a model with large voids it churns fictitious collisions and is much slower than "surface". Prefer "hybrid" unless you know your model has no voids.

All three support neutrons and photons (photon sources, coupled neutron->photon production, and D1S decay photons) and give the same answer within statistics. CPU only: the GPU kernels always surface-track, so compute='gpu' with "hybrid" or "woodcock" prints a one-line notice to stderr (at every verbose setting) and proceeds with surface tracking, whose flux is an unbiased estimate of the same quantity.

'surface'
variance_reduction Sequence[SurvivalBiasing | WeightWindowBounds] | None

List of variance-reduction technique objects applied during transport; an empty list or None (default) is fully analog. Currently accepts yamc.SurvivalBiasing (at most one entry) and yamc.WeightWindowBounds; source biasing joins this list in a future release. Techniques compose and the list order carries no meaning.

None

Examples:

>>> import yamc
>>> geometry = yamc.Geometry(cells)
>>> model = yamc.Model(
...     geometry=geometry,
...     source=source,
... )
>>> model.simulate_transport(total_particles=100_000)

Create a new Model.

Source code in yamc/_core/__init__.pyi
3267
3268
3269
3270
def __new__(cls, geometry: Geometry | MeshGeometry, tallies: typing.Optional[typing.Sequence[Tally]] = None, source: NeutronSource | PhotonSource | typing.Sequence[NeutronSource | PhotonSource] | None = None, transport_secondary_photons: builtins.bool = False, use_decay_photons: builtins.bool = False, photon_cutoff_energy: builtins.float = 1000.0, electron_treatment: typing.Literal['ttb', 'local'] | None = None, free_gas_threshold: builtins.float = 400.0, max_lost_particles: builtins.int = 10, gpu_max_steps_per_particle: typing.Optional[builtins.int] = None, verbose: typing.Optional[typing.Sequence[builtins.str]] = None, tracking_mode: builtins.str = 'surface', variance_reduction: typing.Sequence[SurvivalBiasing | WeightWindowBounds] | None = None, gpu_fission_bank: builtins.bool = True) -> Model:
    r"""
    Create a new Model.
    """

geometry property

geometry: Geometry

Geometry defining the problem's spatial domain.

Returns:

Type Description
Geometry

Geometry object (only for CSG geometry)

source property

source: list[Any]

Source distribution(s) for particle sampling.

Returns:

Name Type Description
list list[Any]

List of NeutronSource / PhotonSource objects

convergence_targets property writable

convergence_targets: list[ConvergenceTarget]

Precision-based stopping criteria. When non-empty, the transport loop ends at the first checkpoint where every convergence target is satisfied: between CPU chunks, or between GPU launches. Under MPI the decision is made on the rank-combined moments.

transport_secondary_photons property

transport_secondary_photons: bool

Whether photon transport is enabled.

use_decay_photons property

use_decay_photons: bool

Whether D1S decay photon mode is enabled.

gpu_fission_bank property writable

gpu_fission_bank: bool

Whether the GPU banks fission progeny on the device.

Default True, and inert without fissile material or on the CPU. With it on, a fissile model's fission progeny are transported in later launches and folded into their source neutron's variance sample, cell and mesh tallies alike. Off, the kernel multiplies the weight by nu_bar in-thread instead, the pre-bank approximation kept for comparison.

photon_cutoff_energy property

photon_cutoff_energy: float

Photon energy cutoff in eV.

electron_treatment property

electron_treatment: str

Electron treatment mode: "ttb" (thick-target bremsstrahlung) or "local" (local energy deposition).

free_gas_threshold property

free_gas_threshold: float

Free-gas threshold multiplier.

max_lost_particles property writable

max_lost_particles: int

Maximum lost particles before abort.

gpu_max_steps_per_particle property writable

gpu_max_steps_per_particle: int

Hard cap on transport steps per particle on the GPU path. Ignored by the CPU path.

verbose property writable

verbose: list[str]

Progress output as a list of flags (reported in source particles). Any combination of "progress", "eta", "tally", "summary", and "nuclear_data"; an empty list [] is fully silent (not even the end-of-run summary). Default: ["eta", "tally", "summary"].

  • "progress" -- periodic Progress: N/total particles (P%) lines
  • "eta" -- progress lines with elapsed wall-clock and ETA
  • "tally" -- each tally's running mean ± std (rel. err)
  • "summary" -- end-of-run completion line and per-tally statistics
  • "nuclear_data" -- one line per nuclear-data file as it loads (nuclide + path), plus the transmutation chain file load

tracking_mode property writable

tracking_mode: str

Particle-transport tracking algorithm: "surface" (default), "hybrid" (recommended Woodcock mode -- delta tracking with a surface fallback in voids/low-density cells), or "woodcock" (pure delta tracking, void-free models only). All support neutrons and photons. See the Model constructor for guidance on each.

variance_reduction property writable

variance_reduction: list[Any]

Variance-reduction techniques applied during transport (list of SurvivalBiasing; empty = fully analog). Returns copies: configure technique objects and assign a whole list, rather than mutating entries in place.

tallies property

tallies: list[Tally]

List of tallies to score during simulation.

Returns:

Type Description
list[Tally]

List of Tally objects

lost_particles property

lost_particles: list[LostParticle]

Lost particles from the last run.

Returns a list of LostParticle objects, each containing diagnostic information about a particle that was lost due to a geometry gap. Empty if no particles were lost. This stays on the Model (rather than TransportResults) so the diagnostics remain inspectable after a max_lost_particles abort, when simulate_transport raises and returns no results object.

Returns:

Type Description
list[LostParticle]

List of LostParticle objects

required_nuclides

required_nuclides() -> list[str]

Nuclide names referenced by this model's materials.

Returns:

Type Description
list[str]

list[str]: Sorted, de-duplicated nuclide names.

Source code in yamc/_core/__init__.pyi
3271
3272
3273
3274
3275
3276
3277
def required_nuclides(self) -> builtins.list[builtins.str]:
    r"""
    Nuclide names referenced by this model's materials.

    Returns:
        list[str]: Sorted, de-duplicated nuclide names.
    """

required_temperatures

required_temperatures() -> dict[str, Optional[list[str]]]

The temperatures this model's materials load each nuclide at.

A nuclide two materials hold at two temperatures is loaded at both. A material with no temperature set loads every temperature the data carries, so a nuclide any such material holds maps to None.

Returns:

Type Description
dict[str, Optional[list[str]]]

dict[str, list[str] | None]: Keyed by nuclide name. Each value is the

dict[str, Optional[list[str]]]

temperature labels in Kelvin, spelled as materials spell them

dict[str, Optional[list[str]]]

("294") and in ascending order, or None for every

dict[str, Optional[list[str]]]

temperature.

Source code in yamc/_core/__init__.pyi
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
def required_temperatures(self) -> builtins.dict[builtins.str, typing.Optional[builtins.list[builtins.str]]]:
    r"""
    The temperatures this model's materials load each nuclide at.

    A nuclide two materials hold at two temperatures is loaded at both. A
    material with no temperature set loads every temperature the data
    carries, so a nuclide any such material holds maps to ``None``.

    Returns:
        dict[str, list[str] | None]: Keyed by nuclide name. Each value is the
        temperature labels in Kelvin, spelled as materials spell them
        (``"294"``) and in ascending order, or ``None`` for every
        temperature.
    """

required_elements

required_elements() -> list[str]

Element symbols this model needs photon data for.

Photon data is per element (Fe, not Fe56). Empty when no photons will be in flight, i.e. neither a photon source nor secondary-photon production.

Returns:

Type Description
list[str]

list[str]: Sorted, de-duplicated element symbols.

Source code in yamc/_core/__init__.pyi
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
def required_elements(self) -> builtins.list[builtins.str]:
    r"""
    Element symbols this model needs photon data for.

    Photon data is per element (``Fe``, not ``Fe56``). Empty when no photons
    will be in flight, i.e. neither a photon source nor secondary-photon
    production.

    Returns:
        list[str]: Sorted, de-duplicated element symbols.
    """

data_uncertainty_coverage

data_uncertainty_coverage() -> dict

What nuclear-data uncertainty this model's transport could carry.

Transport samples the partial reactions that make up each nuclide's total, so for every nuclide in the model's materials this says which of those partials the evaluation states a covariance for, which take one from the summed reaction they belong to (a level of MT 51 to 91 from MT 4, say, the levels then moving together), and which are held at nominal. Nothing is transported; tallies are unaffected.

Loads each material's nuclear data, with covariance, as a run would, and factorizes each nuclide's covariance, so a repair of a covariance that is not positive semidefinite is reported here. A nuclide in several materials is reported from the first one it appears in.

Returns:

Name Type Description
dict dict

With keys

dict
  • nuclides: per nuclide name, a dict with perturbed (per MT, a dict with via, the MT whose covariance it takes, and max_relative_sigma, the largest relative sigma stated on any covariance cell, or for a reaction an NC block derives from others the largest its derived cross section has at any energy), held_at_nominal (sorted MTs no applied covariance reaches), cells and short_range_blocks (the size of the nuclide's covariance field), repair (None, or a dict of what the repair to the nearest correlation matrix did, which keeps every cell's evaluated sigma: lambda_min, the most negative eigenvalue of the cells' correlation matrix before it, largest_correlation_change and correlation_frobenius_change, how far it moved the correlations, cells in the blocks it repaired, held_cells stated at zero or negative variance with a covariance and so held at nominal, and converged), library (the library the covariance came from, or None when its data folder records none) and warnings (what that library's own documentation says is wrong with this covariance, with the source; every FENDL-3.2 covariance, and the ENDF/B-VIII.1 evaluations its release paper names), nubar_covariance (the sorted fission multiplicity MTs, of 452, 455 and 456, the evaluation carries MF=31 covariance for) and spectrum_covariance (whether it carries MF=35, the covariance of the fission spectrum). Both are reported so the data is visible; neither is sampled yet. drawn_with is the sorted names of the other nuclides of the model it is drawn jointly with, those a cross-material covariance block correlates it with (the neutron standards, such as ENDF/B-VIII.1 U235 fission with U238 fission), empty where it is drawn on its own. unexplained_deposit is, per heating or damage-energy row the nuclide carries (301 heating, 444 damage energy, 901 local heating), a list of (lo, hi, share) per energy band in eV (below 1 eV, to 1 keV, to 1 MeV, to 20 MeV, above): the share of the row, over lethargy, that the per-reaction deposits do not reproduce there. A run moves each row by what its perturbed reactions deposit; this share does not move (for a fissile nuclide it holds fission's).
dict
  • without_data: sorted names of nuclides whose data carries no covariance at all.
dict
  • not_perturbed: inputs no transport uncertainty run perturbs whatever the data, such as secondary angular and energy distributions.
dict
  • angular_covariance: per nuclide whose evaluation carries MF=34 (the covariance of angular distributions), {mt: [(l, l1), ...]}: the sorted pairs of Legendre orders a covariance block correlates. Reported so the data is visible; it is not sampled yet.
dict
  • resonance_parameters: per nuclide whose data folder carries its resonance parameters (MF=2 and MF=32, resonance_parameters.arrow), how a run takes its resonance-range uncertainty, in the shape of TransmutationResults.get_data_uncertainty_info's entry of the same name: method is "parameters sampled" (each replica draws them, rebuilds the cross sections and Doppler broadens the change, which the replica weights then carry exactly, flux response included) or "first-order rows" (the MF=32 rows of covariance.arrow, sampled with the cells), with reason why. A sampled nuclide's perturbed reactions are those its MF=33 blocks reach, without the rows.

Raises:

Type Description
RuntimeError

If a material's nuclear data cannot be loaded.

Examples:

>>> coverage = model.data_uncertainty_coverage()
>>> coverage["nuclides"]["Fe56"]["perturbed"][102]["max_relative_sigma"]
>>> coverage["without_data"]
Source code in yamc/_core/__init__.pyi
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
def data_uncertainty_coverage(self) -> dict:
    r"""
    What nuclear-data uncertainty this model's transport could carry.

    Transport samples the partial reactions that make up each nuclide's
    total, so for every nuclide in the model's materials this says which
    of those partials the evaluation states a covariance for, which take
    one from the summed reaction they belong to (a level of MT 51 to 91
    from MT 4, say, the levels then moving together), and which are held at
    nominal. Nothing is transported; tallies are unaffected.

    Loads each material's nuclear data, with covariance, as a run would,
    and factorizes each nuclide's covariance, so a repair of a covariance
    that is not positive semidefinite is reported here. A nuclide in
    several materials is reported from the first one it appears in.

    Returns:
        dict: With keys

        - ``nuclides``: per nuclide name, a dict with ``perturbed`` (per
          MT, a dict with ``via``, the MT whose covariance it takes, and
          ``max_relative_sigma``, the largest relative sigma stated on any
          covariance cell, or for a reaction an NC block derives from
          others the largest its derived cross section has at any
          energy), ``held_at_nominal`` (sorted MTs no applied covariance
          reaches), ``cells`` and ``short_range_blocks`` (the size of the
          nuclide's covariance field), ``repair`` (``None``, or a dict of
          what the repair to the nearest correlation matrix did, which
          keeps every cell's evaluated sigma: ``lambda_min``, the most
          negative eigenvalue of the cells' correlation matrix before it,
          ``largest_correlation_change`` and
          ``correlation_frobenius_change``, how far it moved the
          correlations, ``cells`` in the blocks it repaired,
          ``held_cells`` stated at zero or negative variance with a
          covariance and so held at nominal, and ``converged``),
          ``library`` (the library the covariance came from, or ``None``
          when its data folder records none) and ``warnings`` (what that
          library's own documentation says is wrong with this covariance,
          with the source; every FENDL-3.2 covariance, and the ENDF/B-VIII.1
          evaluations its release paper names), ``nubar_covariance`` (the
          sorted fission multiplicity MTs, of 452, 455 and 456, the
          evaluation carries MF=31 covariance for) and
          ``spectrum_covariance`` (whether it carries MF=35, the covariance
          of the fission spectrum). Both are reported so the data is
          visible; neither is sampled yet. ``drawn_with`` is the sorted
          names of the other nuclides of the model it is drawn jointly
          with, those a cross-material covariance block correlates it with
          (the neutron standards, such as ENDF/B-VIII.1 U235 fission with
          U238 fission), empty where it is drawn on its own.
          ``unexplained_deposit`` is, per heating or damage-energy row
          the nuclide carries (301 heating, 444 damage energy, 901 local
          heating), a list of ``(lo, hi, share)`` per energy band in eV
          (below 1 eV, to 1 keV, to 1 MeV, to 20 MeV, above): the share
          of the row, over lethargy, that the per-reaction deposits do not
          reproduce there. A run moves each row by what its perturbed
          reactions deposit; this share does not move (for a fissile
          nuclide it holds fission's).
        - ``without_data``: sorted names of nuclides whose data carries no
          covariance at all.
        - ``not_perturbed``: inputs no transport uncertainty run perturbs
          whatever the data, such as secondary angular and energy
          distributions.
        - ``angular_covariance``: per nuclide whose evaluation carries MF=34
          (the covariance of angular distributions), ``{mt: [(l, l1), ...]}``:
          the sorted pairs of Legendre orders a covariance block correlates.
          Reported so the data is visible; it is not sampled yet.
        - ``resonance_parameters``: per nuclide whose data folder carries
          its resonance parameters (MF=2 and MF=32,
          ``resonance_parameters.arrow``), how a run takes its
          resonance-range uncertainty, in the shape of
          ``TransmutationResults.get_data_uncertainty_info``'s entry of the
          same name: ``method`` is ``"parameters sampled"`` (each replica
          draws them, rebuilds the cross sections and Doppler broadens the
          change, which the replica weights then carry exactly, flux
          response included) or ``"first-order rows"`` (the MF=32 rows of
          ``covariance.arrow``, sampled with the cells), with ``reason``
          why. A sampled nuclide's ``perturbed`` reactions are those its
          MF=33 blocks reach, without the rows.

    Raises:
        RuntimeError: If a material's nuclear data cannot be loaded.

    Examples:
        >>> coverage = model.data_uncertainty_coverage()
        >>> coverage["nuclides"]["Fe56"]["perturbed"][102]["max_relative_sigma"]
        >>> coverage["without_data"]
    """

has_photons

has_photons() -> bool

True when photons will be in flight during the run, either because a source emits them or because secondary-photon production is enabled.

Returns:

Type Description
bool

bool

Source code in yamc/_core/__init__.pyi
3394
3395
3396
3397
3398
3399
3400
3401
def has_photons(self) -> builtins.bool:
    r"""
    True when photons will be in flight during the run, either because a
    source emits them or because secondary-photon production is enabled.

    Returns:
        bool
    """

radionuclides

radionuclides() -> list[str]

Unstable activation products reachable from this model's materials.

For every nuclide in the model's materials, looks up its chain reactions and collects the photon-emitting nuclides they make, directly or through decay. Pass the result to Tally(parent_nuclides=...) for a D1S decay-photon tally.

An emitter a reaction makes directly is named as itself ("Co60"); one made through a decaying parent is named by its decay path ("Cs137>Ba137m"), since the parent's half-life sets when its photons arrive. An emitter made both ways appears under both names.

The transmutation network is assembled from the configured per-subsection sources: the decay data (yamc.transmutation_decay_data) and the reactions (yamc.transmutation_reactions). There is no default library.

Returns:

Type Description
list[str]

list[str]: Sorted, de-duplicated decay-photon tags.

Raises:

Type Description
ValueError

If either source is unset, naming it.

Source code in yamc/_core/__init__.pyi
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
def radionuclides(self) -> builtins.list[builtins.str]:
    r"""
    Unstable activation products reachable from this model's materials.

    For every nuclide in the model's materials, looks up its chain reactions
    and collects the photon-emitting nuclides they make, directly or through
    decay. Pass the result to ``Tally(parent_nuclides=...)`` for a D1S
    decay-photon tally.

    An emitter a reaction makes directly is named as itself (``"Co60"``); one
    made through a decaying parent is named by its decay path
    (``"Cs137>Ba137m"``), since the parent's half-life sets when its photons
    arrive. An emitter made both ways appears under both names.

    The transmutation network is assembled from the configured per-subsection
    sources: the decay data (``yamc.transmutation_decay_data``) and the
    reactions (``yamc.transmutation_reactions``). There is no default
    library.

    Returns:
        list[str]: Sorted, de-duplicated decay-photon tags.

    Raises:
        ValueError: If either source is unset, naming it.
    """

generate_weight_windows

generate_weight_windows(generator: WeightWindowGeneratorDeGVR, total_particles: Optional[int] = None, seed: int = 1, threads: Optional[int] = None, max_runtime: Optional[Any] = None, compute: str = 'cpu', relative_error: Optional[float] = 0.1) -> Any

Generate weight windows with the DeGVR method (density-extrapolation).

Runs two reduced-density fixed-source passes internally and returns the resulting WeightWindowBounds for a clean production run (add it to a Model's variance_reduction list). The current model is not mutated.

Each generation pass runs until the first of its stop conditions trips: the window mesh is converged (relative_error, on by default), a particle budget (total_particles), or a wall-time budget (max_runtime). So by default no budget has to be guessed: each pass stops once it has enough histories for the windows and no later. A time budget lets a weight-window generation cost be compared apples-to-apples against an equally time-bounded analog run.

Parameters:

Name Type Description Default
generator WeightWindowGeneratorDeGVR

A WeightWindowGeneratorDeGVR configuring the mesh, energy groups, particle, and DeGVR parameters.

required
total_particles Optional[int]

Histories per generation pass, or None (default) for no particle cap. Must be positive when given.

None
seed int

Base RNG seed (default 1).

1
threads Optional[int]

CPU worker threads (default: all cores).

None
max_runtime Optional[Any]

Optional wall-time budget PER PASS. A float (seconds) or a (value, unit) tuple with unit 's', 'min', 'h', 'd', or 'a' (year), e.g. (5, 'min').

None
relative_error Optional[float]

Per-pass convergence target (default 0.1): a pass stops once 95% of the window-mesh voxels that have scored, in every energy group and particle field, reach this relative error. Voxels reached for the first time have an error near 1, so the target is not met while the scored region is still growing, and voxels that never score (outside the geometry) do not count. The same target applies to both passes. None turns it off, leaving total_particles / max_runtime.

0.1

Returns:

Type Description
Any

WeightWindowBounds | list[WeightWindowBounds]: the generated windows,

Any

matching the generator's particle form. A string particle

Any

returns a single WeightWindowBounds; a list particle

Any

returns a list in that order (even a one-element list), e.g. a

Any

coupled ["neutron", "photon"] generation returns ``[neutron_ww,

Any

photon_ww]``. Add a single window to a Model as

Any

variance_reduction=[ww]; pass a returned list straight through as

Any

variance_reduction=windows.

Source code in yamc/_core/__init__.pyi
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
def generate_weight_windows(self, generator: WeightWindowGeneratorDeGVR, total_particles: typing.Optional[builtins.int] = None, seed: builtins.int = 1, threads: typing.Optional[builtins.int] = None, max_runtime: typing.Optional[typing.Any] = None, compute: builtins.str = 'cpu', relative_error: typing.Optional[builtins.float] = 0.1) -> typing.Any:
    r"""
    Generate weight windows with the DeGVR method (density-extrapolation).

    Runs two reduced-density fixed-source passes internally and returns the
    resulting ``WeightWindowBounds`` for a clean production run (add it to a
    Model's ``variance_reduction`` list). The current model is not mutated.

    Each generation pass runs until the first of its stop conditions trips:
    the window mesh is converged (``relative_error``, on by default), a
    particle budget (``total_particles``), or a wall-time budget
    (``max_runtime``). So by default no budget has to be guessed: each pass
    stops once it has enough histories for the windows and no later. A
    time budget lets a weight-window generation cost be compared
    apples-to-apples against an equally time-bounded analog run.

    Args:
        generator: A ``WeightWindowGeneratorDeGVR`` configuring the mesh,
            energy groups, particle, and DeGVR parameters.
        total_particles: Histories per generation pass, or ``None``
            (default) for no particle cap. Must be positive when given.
        seed: Base RNG seed (default 1).
        threads: CPU worker threads (default: all cores).
        max_runtime: Optional wall-time budget PER PASS. A float (seconds)
            or a ``(value, unit)`` tuple with unit ``'s'``, ``'min'``,
            ``'h'``, ``'d'``, or ``'a'`` (year), e.g. ``(5, 'min')``.
        relative_error: Per-pass convergence target (default 0.1): a pass
            stops once 95% of the window-mesh voxels that have scored, in
            every energy group and particle field, reach this relative
            error. Voxels reached for the first time have an error near 1,
            so the target is not met while the scored region is still
            growing, and voxels that never score (outside the geometry) do
            not count. The same target applies to both passes. ``None``
            turns it off, leaving ``total_particles`` / ``max_runtime``.
        At least one of ``relative_error`` / ``total_particles`` /
        ``max_runtime`` must be set (a call with none raises ``ValueError``).
        The model's own ``convergence_targets`` watch its own tallies, which
        the passes do not carry, so they do not apply to generation.

    Returns:
        WeightWindowBounds | list[WeightWindowBounds]: the generated windows,
        matching the generator's ``particle`` form. A **string** ``particle``
        returns a single ``WeightWindowBounds``; a **list** ``particle``
        returns a ``list`` in that order (even a one-element list), e.g. a
        coupled ``["neutron", "photon"]`` generation returns ``[neutron_ww,
        photon_ww]``. Add a single window to a Model as
        ``variance_reduction=[ww]``; pass a returned list straight through as
        ``variance_reduction=windows``.
    """

estimate_density_reduction

estimate_density_reduction(generator: WeightWindowGeneratorDeGVR) -> tuple[float, float]

Estimate the auto DeGVR density-reduction factor N and the optical depth tau for generator, via a particle-free ray-trace (source to deepest voxel). Returns (N, tau) without running generation, so you can inspect what the auto (density_reduction=None) path would choose.

Source code in yamc/_core/__init__.pyi
3476
3477
3478
3479
3480
3481
3482
def estimate_density_reduction(self, generator: WeightWindowGeneratorDeGVR) -> tuple[builtins.float, builtins.float]:
    r"""
    Estimate the auto DeGVR density-reduction factor N and the optical depth
    tau for ``generator``, via a particle-free ray-trace (source to deepest
    voxel). Returns ``(N, tau)`` without running generation, so you can inspect
    what the auto (``density_reduction=None``) path would choose.
    """

to_json

to_json(path: Optional[str | PathLike | Path] = None, pretty: bool = True) -> Optional[bytes]

Save the model as JSON, or return the JSON as bytes when path is None (for a browser or Pyodide session).

The JSON describes the specification -- geometry, materials, source, tallies, run parameters. Nuclide cross-section data is not included; a loaded model still needs nuclide data to run (just like a model built from scratch).

Parameters:

Name Type Description Default
path str | PathLike | None

Where to write; conventional extension .json.

None
pretty bool

Indented multi-line JSON (the default, readable and git diff-friendly) or compact single-line JSON.

True

Returns:

Type Description
Optional[bytes]

bytes | None: The JSON when path is None.

Examples:

>>> model.to_json("blanket_v3.json")
>>> same = yamc.Model.from_json(model.to_json())
Source code in yamc/_core/__init__.pyi
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
def to_json(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None, pretty: builtins.bool = True) -> typing.Optional[bytes]:
    r"""
    Save the model as JSON, or return the JSON as bytes when ``path`` is
    None (for a browser or Pyodide session).

    The JSON describes the *specification* -- geometry, materials,
    source, tallies, run parameters. Nuclide cross-section data is
    **not** included; a loaded model still needs nuclide data to
    run (just like a model built from scratch).

    Args:
        path (str | os.PathLike | None): Where to write; conventional
            extension ``.json``.
        pretty: Indented multi-line JSON (the default, readable and
            ``git diff``-friendly) or compact single-line JSON.

    Returns:
        bytes | None: The JSON when ``path`` is None.

    Examples:
        >>> model.to_json("blanket_v3.json")
        >>> same = yamc.Model.from_json(model.to_json())
    """

from_json staticmethod

from_json(source: Any) -> Model

Load a model that to_json saved.

Parameters:

Name Type Description Default
source str | PathLike | bytes

A file path, or the JSON as bytes, as to_json() returns it.

required

Returns:

Type Description
Model

A new Model. Cross-section data is not loaded -- call

Model

read_nuclear_data on the materials before

Model

simulate_transport.

Examples:

>>> model = yamc.Model.from_json("blanket_v3.json")
Source code in yamc/_core/__init__.pyi
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
@staticmethod
def from_json(source: typing.Any) -> Model:
    r"""
    Load a model that ``to_json`` saved.

    Args:
        source (str | os.PathLike | bytes): A file path, or the JSON as
            bytes, as ``to_json()`` returns it.

    Returns:
        A new Model. Cross-section data is **not** loaded -- call
        ``read_nuclear_data`` on the materials before
        ``simulate_transport``.

    Examples:
        >>> model = yamc.Model.from_json("blanket_v3.json")
    """

simulate_transport

simulate_transport(total_particles: Optional[int] = None, seed: int = 1, threads: Optional[int] = None, capture_tracks: Optional[Any] = None, compute: str = 'cpu', max_runtime: Optional[Any] = None, data_uncertainty: Optional[DataUncertainty] = None, convergence: Optional[str] = None) -> TransportResults

Run the Monte Carlo simulation.

Parameters:

Name Type Description Default
total_particles Optional[int]

Particle-history budget for this run, or None (default) for no particle cap. A property of the run, not the model: the same model can be run at several sample sizes (e.g. a convergence sweep) without rebuilding geometry, sources, or tallies. Must be positive when given (0 is an error; use None for "no cap"). With None the run continues until another stop condition trips (max_runtime or convergence targets). With no stop condition at all the run goes on until every scored bin of every tally passes the statistical checks of convergence at two checkpoints in a row (CPU, single process); the progress line shows an ETA projected from the slowest bin. A tally that converges slowly (deep shielding without variance reduction) runs a long time. On compute='gpu' the launch loop decides convergence targets between launches, so the run overshoots the target by at most one launch chunk.

None
seed int

Base RNG seed for this run (default: 1). Per-particle streams derive from it, so the seed fully determines the run. Give each run a distinct seed when accumulating statistics across runs with combine_results.

1
threads Optional[int]

Number of threads to use for parallel execution. Defaults to None, which uses all available CPU threads. CPU only: passing it with compute='gpu' raises ValueError.

None
capture_tracks Optional[Any]

Which particle histories to record full event tracks for (debugging/visualisation). Histories are addressed by their global 0-based index, so the captured set is the same regardless of thread count. Can be: - None (default): no tracking, zero overhead - int N: the first N histories (i.e. range(0, N)) - range(20, 30): histories 20..29 (half-open); strides too, e.g. range(0, 1000, 10) for every 10th of the first 1000 - Sequence[int] e.g. [20, 30, 45]: exactly those indices - 'all': every history (warns; high memory on large runs) Only supported when compute='cpu'.

None
compute str

Where to run the transport: 'cpu' (default), 'gpu' (auto-selects an adapter, preferring a discrete GPU), or an adapter name from yamc.parallel.list_gpu_adapters() to pin a specific GPU. The GPU runs a subset of the model options, listed per option in the "GPU transport" section of the simulate_transport docs page. capture_tracks, threads and data_uncertainty are CPU only. Raises RuntimeError if no GPU with f64 compute is available, or ValueError if the model uses an option the GPU does not support.

'cpu'
max_runtime Optional[Any]

Optional wall-time budget. The run stops at the first chunk checkpoint where elapsed wall time has reached the budget, then finalizes tallies normally, so the returned TallyResults carry valid statistics and figure of merit. Accepts a float (seconds) or a (value, unit) tuple with unit 's', 'min', 'h', 'd', or 'a' (year), e.g. (5, 'min'). Composes with the other stop conditions: the run ends at the first of {total_particles exhausted, all convergence_targets met, max_runtime elapsed}. Supported on compute='cpu' and compute='gpu' (the GPU can only stop between kernel launches, so it may overshoot the budget by up to one launch). Under MPI (mpi_size > 1) the stop is collective (any rank over budget stops them all at the same checkpoint), and so is the convergence early-stop, decided on the rank-combined moments. A time-bounded run is non-deterministic in history count, but the results are statistically valid for the histories completed.

None
convergence Optional[str]

Which statistical checks every scored bin of every tally must pass before a run with no stop condition ends, each level including the checks of the looser ones: 'loose' (6: relative error < 0.10, mean stable, relative error decreasing and falling as 1/sqrt(N), figure of merit stable with no trend), 'standard' (9, the default: loose plus the variance of the variance < 0.10, decreasing and falling as 1/N) or 'strict' (10: standard plus a large-score tail slope > 3; about 1.6 KiB per scored bin per thread). Only valid with no total_particles, max_runtime or convergence targets.

None
data_uncertainty Optional[DataUncertainty]

Nuclear-data uncertainty on every tally, as a DataUncertainty. Each history is transported once and carries one weight per cross-section replica (samples, 32 when not set), drawn from the evaluations' covariance with seed, so no extra particles are run and mean stays the nominal result, bit for bit. Where a nuclide's data folder carries its resonance parameters (MF=2 and MF=32), each replica draws those instead of the first-order MF=32 rows, rebuilds the resonance cross sections from the draw and Doppler broadens the change, so the resonance range is exact in the parameters and a replica's stronger resonance deepens its own flux dip; data_uncertainty_coverage()["resonance_parameters"] says which nuclides and why not. Each TallyResult then carries nuclear_data_standard_deviation, replica_mean and replica_standard_error. Cross sections only: leave sources unset or pass ["cross_sections"], and attribution and convergence are not supported (the replica count is fixed). The weights are carried through every tracking mode (under delta tracking the majorant is raised to cover every replica's total and virtual collisions carry the replicas' rejection odds), survival biasing, weight windows and MPI. Photons inherit their neutron's weights times the change to the cross section of the reaction that made them, and keep them (photon data carries no covariance), so photon tallies and photon heating get the nuclear-data uncertainty of the neutron transport. Neutron heating (heating, heating-local) and damage-energy move with the cross sections too: each replica adds what its perturbed reactions deposit, the energy each reaction deposits rebuilt from the data by energy balance (heating) and the Lindhard partition of its recoils (damage energy), as NJOY's HEATR builds the stored totals; what those do not reproduce (fission's share) stays nominal, per nuclide in data_uncertainty_coverage(). Not yet supported, and refused with the reason: compute='gpu', overlay tallies, mesh tallies and per-nuclide tally bins. model.data_uncertainty_coverage() lists what the evaluations cover. Default None.

None

Returns:

Type Description
TransportResults

TransportResults containing finalized TallyResults for

TransportResults

every tally attached to the model. When capture_tracks is set,

TransportResults

the captured Tracks are available on results.tracks.

Raises:

Type Description
ValueError

if two tallies share the same name or the same id, or if the model uses a feature the GPU kernel doesn't support, or if a GPU launch truncated histories at gpu_max_steps_per_particle (the under-counted tallies are never returned).

RuntimeError

if compute='gpu' and no GPU with f64 compute is available.

Examples:

>>> results = model.simulate_transport(total_particles=1000)
>>> results[flux_tally].mean
>>> results = model.simulate_transport(total_particles=1000, capture_tracks=100)
>>> df = pd.DataFrame(results.tracks.to_dataframe_records())
>>> results = model.simulate_transport(total_particles=1_000_000, compute='gpu')
>>> # run on a specific GPU by name:
>>> adapters = yamc.parallel.list_gpu_adapters()
>>> results = model.simulate_transport(total_particles=1_000_000, compute=adapters[0])
>>> # no particle cap: run for about 5 minutes, take whatever converged:
>>> results = model.simulate_transport(max_runtime=(5, "min"))
Source code in yamc/_core/__init__.pyi
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
def simulate_transport(self, total_particles: typing.Optional[builtins.int] = None, seed: builtins.int = 1, threads: typing.Optional[builtins.int] = None, capture_tracks: typing.Optional[typing.Any] = None, compute: builtins.str = 'cpu', max_runtime: typing.Optional[typing.Any] = None, data_uncertainty: typing.Optional[DataUncertainty] = None, convergence: typing.Optional[builtins.str] = None) -> TransportResults:
    r"""
    Run the Monte Carlo simulation.

    Args:
        total_particles: Particle-history budget for this run, or ``None``
            (default) for no particle cap. A property of the run, not the
            model: the same model can be run at several sample sizes
            (e.g. a convergence sweep) without rebuilding geometry,
            sources, or tallies. Must be positive when given (``0`` is an
            error; use ``None`` for "no cap"). With ``None`` the run
            continues until another stop condition trips (``max_runtime``
            or convergence targets). With no stop condition at all the run
            goes on until every scored bin of every tally passes the
            statistical checks of ``convergence`` at two checkpoints in a
            row (CPU, single process); the progress line shows an ETA
            projected from the slowest bin. A tally that converges slowly
            (deep shielding without variance reduction) runs a long time.
            On ``compute='gpu'`` the launch loop decides convergence targets
            between launches, so the run overshoots the target by at most
            one launch chunk.
        seed: Base RNG seed for this run (default: 1). Per-particle
            streams derive from it, so the seed fully determines the
            run. Give each run a distinct seed when accumulating
            statistics across runs with ``combine_results``.
        threads: Number of threads to use for parallel execution. Defaults to None,
            which uses all available CPU threads. CPU only: passing it with
            ``compute='gpu'`` raises ``ValueError``.
        capture_tracks: Which particle histories to record full event tracks
            for (debugging/visualisation). Histories are addressed by their
            global 0-based index, so the captured set is the same regardless
            of thread count. Can be:
            - ``None`` (default): no tracking, zero overhead
            - ``int N``: the first ``N`` histories (i.e. ``range(0, N)``)
            - ``range(20, 30)``: histories 20..29 (half-open); strides too,
              e.g. ``range(0, 1000, 10)`` for every 10th of the first 1000
            - ``Sequence[int]`` e.g. ``[20, 30, 45]``: exactly those indices
            - ``'all'``: every history (warns; high memory on large runs)
            Only supported when ``compute='cpu'``.
        compute: Where to run the transport: ``'cpu'`` (default), ``'gpu'``
            (auto-selects an adapter, preferring a discrete GPU), or an
            adapter name from ``yamc.parallel.list_gpu_adapters()`` to pin a
            specific GPU. The GPU runs a subset of the model options, listed
            per option in the "GPU transport" section of the
            ``simulate_transport`` docs page. ``capture_tracks``,
            ``threads`` and ``data_uncertainty`` are CPU only. Raises
            ``RuntimeError`` if no GPU with f64 compute is available, or
            ``ValueError`` if the model uses an option the GPU does not
            support.
        max_runtime: Optional wall-time budget. The run stops at the first
            chunk checkpoint where elapsed wall time has reached the budget,
            then finalizes tallies normally, so the returned ``TallyResult``s
            carry valid statistics and figure of merit. Accepts a float
            (seconds) or a ``(value, unit)`` tuple with unit ``'s'``,
            ``'min'``, ``'h'``, ``'d'``, or ``'a'`` (year), e.g.
            ``(5, 'min')``. Composes with the other stop conditions: the run
            ends at the first of {``total_particles`` exhausted, all
            ``convergence_targets`` met, ``max_runtime`` elapsed}. Supported
            on ``compute='cpu'`` and ``compute='gpu'`` (the GPU can only stop
            between kernel launches, so it may overshoot the budget by up to
            one launch). Under MPI (``mpi_size > 1``) the stop is collective
            (any rank over budget stops them all at the same checkpoint), and
            so is the convergence early-stop, decided on the rank-combined
            moments. A
            time-bounded run is non-deterministic in history count, but the
            results are statistically valid for the histories completed.
        convergence: Which statistical checks every scored bin of every
            tally must pass before a run with no stop condition ends, each
            level including the checks of the looser ones: ``'loose'`` (6:
            relative error < 0.10, mean stable, relative error decreasing
            and falling as 1/sqrt(N), figure of merit stable with no
            trend), ``'standard'`` (9, the default: loose plus the variance
            of the variance < 0.10, decreasing and falling as 1/N) or
            ``'strict'`` (10: standard plus a large-score tail slope > 3;
            about 1.6 KiB per scored bin per thread). Only valid with no
            ``total_particles``, ``max_runtime`` or convergence targets.
        data_uncertainty: Nuclear-data uncertainty on every tally, as a
            ``DataUncertainty``. Each history is transported once and
            carries one weight per cross-section replica (``samples``, 32
            when not set), drawn from the evaluations' covariance with
            ``seed``, so no extra particles are run and ``mean`` stays the
            nominal result, bit for bit. Where a nuclide's data folder
            carries its resonance parameters (MF=2 and MF=32), each
            replica draws those instead of the first-order MF=32 rows,
            rebuilds the resonance cross sections from the draw and Doppler
            broadens the change, so the resonance range is exact in the
            parameters and a replica's stronger resonance deepens its own
            flux dip; ``data_uncertainty_coverage()["resonance_parameters"]``
            says which nuclides and why not. Each ``TallyResult`` then carries
            ``nuclear_data_standard_deviation``, ``replica_mean`` and
            ``replica_standard_error``. Cross sections only: leave
            ``sources`` unset or pass ``["cross_sections"]``, and
            ``attribution`` and ``convergence`` are not supported (the
            replica count is fixed). The weights are carried through every
            tracking mode (under delta tracking the majorant is raised to
            cover every replica's total and virtual collisions carry the
            replicas' rejection odds), survival biasing, weight windows and
            MPI. Photons inherit their neutron's weights times the change to
            the cross section of the reaction that made them, and keep them
            (photon data carries no covariance), so photon tallies and
            photon heating get the nuclear-data uncertainty of the neutron
            transport. Neutron heating (``heating``, ``heating-local``) and
            ``damage-energy`` move with the cross sections too: each
            replica adds what its perturbed reactions deposit, the energy
            each reaction deposits rebuilt from the data by energy balance
            (heating) and the Lindhard partition of its recoils (damage
            energy), as NJOY's HEATR builds the stored totals; what those
            do not reproduce (fission's share) stays nominal, per nuclide
            in ``data_uncertainty_coverage()``. Not yet supported, and
            refused with the reason:
            ``compute='gpu'``, overlay tallies,
            mesh tallies and per-nuclide tally bins.
            ``model.data_uncertainty_coverage()`` lists what the evaluations
            cover. Default ``None``.

    Returns:
        ``TransportResults`` containing finalized ``TallyResult``s for
        every tally attached to the model. When ``capture_tracks`` is set,
        the captured ``Tracks`` are available on ``results.tracks``.

    Raises:
        ValueError: if two tallies share the same name or the same id, or
            if the model uses a feature the GPU kernel doesn't support,
            or if a GPU launch truncated histories at
            ``gpu_max_steps_per_particle``
            (the under-counted tallies are never returned).
        RuntimeError: if ``compute='gpu'`` and no GPU with f64 compute is
            available.

    Examples:
        >>> results = model.simulate_transport(total_particles=1000)
        >>> results[flux_tally].mean
        >>> results = model.simulate_transport(total_particles=1000, capture_tracks=100)
        >>> df = pd.DataFrame(results.tracks.to_dataframe_records())
        >>> results = model.simulate_transport(total_particles=1_000_000, compute='gpu')
        >>> # run on a specific GPU by name:
        >>> adapters = yamc.parallel.list_gpu_adapters()
        >>> results = model.simulate_transport(total_particles=1_000_000, compute=adapters[0])
        >>> # no particle cap: run for about 5 minutes, take whatever converged:
        >>> results = model.simulate_transport(max_runtime=(5, "min"))
    """

set_material_temperature

set_material_temperature(material: Material, temperature: float) -> None

Set the temperature of a material in this model, for the next run.

For feedback loops such as a coupled thermal solve: the geometry, the loaded nuclear data, tallies, weight windows and the other materials' cross sections are all kept. Only the model's copy of the material changes; material itself keeps its old temperature.

Parameters:

Name Type Description Default
material Material

A material used in this model.

required
temperature float

Temperature in Kelvin.

required
Source code in yamc/_core/__init__.pyi
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
def set_material_temperature(self, material: Material, temperature: builtins.float) -> None:
    r"""
    Set the temperature of a material in this model, for the next run.

    For feedback loops such as a coupled thermal solve: the geometry, the
    loaded nuclear data, tallies, weight windows and the other materials'
    cross sections are all kept. Only the model's copy of the material
    changes; ``material`` itself keeps its old temperature.

    Args:
        material: A material used in this model.
        temperature: Temperature in Kelvin.
    """

set_material_density

set_material_density(material: Material, density: float) -> None

Set the density of a material in this model, in the material's own density_units, for the next run.

The microscopic cross sections are reused, so this costs far less than building a new model. Only the model's copy of the material changes; material itself keeps its old density.

Parameters:

Name Type Description Default
material Material

A material used in this model.

required
density float

The new density, in material.density_units.

required
Source code in yamc/_core/__init__.pyi
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
def set_material_density(self, material: Material, density: builtins.float) -> None:
    r"""
    Set the density of a material in this model, in the material's own
    ``density_units``, for the next run.

    The microscopic cross sections are reused, so this costs far less than
    building a new model. Only the model's copy of the material changes;
    ``material`` itself keeps its old density.

    Args:
        material: A material used in this model.
        density: The new density, in ``material.density_units``.
    """

set_tet_density_factors

set_tet_density_factors(factors: Iterable[float] | None) -> None

Scale the density of each tet of a mesh geometry, for the next run.

For per-element density feedback, e.g. from a thermal solve on the same tet mesh. The model starts from MeshGeometry.tet_density_factors; this changes the model's copy, as set_material_density does for a material, and leaves the geometry as it is. Inside a tet every macroscopic cross section is f * Σ_material, so this needs no extra nuclear data. Heating and reaction-rate scores follow the scaled density. Needs tracking_mode="hybrid" (or "woodcock").

Parameters:

Name Type Description Default
factors Iterable[float] | None

One non-negative factor per tet, in the order of MeshGeometry.tetrahedra (a list, a numpy array or any iterable of numbers), or None to clear them.

required
Source code in yamc/_core/__init__.pyi
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
def set_tet_density_factors(self, factors: typing.Iterable[builtins.float] | None) -> None:
    r"""
    Scale the density of each tet of a mesh geometry, for the next run.

    For per-element density feedback, e.g. from a thermal solve on the same
    tet mesh. The model starts from ``MeshGeometry.tet_density_factors``;
    this changes the model's copy, as ``set_material_density`` does for a
    material, and leaves the geometry as it is. Inside a tet every macroscopic cross section is
    ``f * Σ_material``, so this needs no extra nuclear data. Heating and
    reaction-rate scores follow the scaled density. Needs
    ``tracking_mode="hybrid"`` (or ``"woodcock"``).

    Args:
        factors: One non-negative factor per tet, in the order of
            ``MeshGeometry.tetrahedra`` (a list, a numpy array or any
            iterable of numbers), or ``None`` to clear them.
    """

sample_slice

sample_slice(origin: Optional[Any] = None, width: Optional[Any] = None, resolution: Optional[Any] = None, basis: str = 'xy') -> GeometrySliceData

Generate 2D maps of cell IDs and material IDs for the model's geometry.

Parameters:

Name Type Description Default
origin Optional[Any]

Origin of the plot (tuple/list of 3 floats). Defaults to bbox center or (0,0,0).

None
width Optional[Any]

Width of the plot (tuple/list of 2 floats). Defaults to bbox width or (10,10).

None
resolution Optional[Any]

Raster resolution as a total pixel budget (int) or an explicit (h, v) tuple. Defaults to 40000.

None
basis str

The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

'xy'

Returns:

Name Type Description
A GeometrySliceData

class:GeometrySliceData -- also supports tuple unpacking.

Source code in yamc/_core/__init__.pyi
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
def sample_slice(self, origin: typing.Optional[typing.Any] = None, width: typing.Optional[typing.Any] = None, resolution: typing.Optional[typing.Any] = None, basis: builtins.str = 'xy') -> GeometrySliceData:
    r"""
    Generate 2D maps of cell IDs and material IDs for the model's geometry.

    Args:
        origin: Origin of the plot (tuple/list of 3 floats). Defaults to bbox center or (0,0,0).
        width: Width of the plot (tuple/list of 2 floats). Defaults to bbox width or (10,10).
        resolution: Raster resolution as a total pixel budget (int) or an explicit (h, v) tuple. Defaults to 40000.
        basis: The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

    Returns:
        A :class:`GeometrySliceData` -- also supports tuple unpacking.
    """

simulate_transmutation

simulate_transmutation(method: str, schedule: Any, total_particles: Optional[int] = None, seed: int = 1, threads: Optional[int] = None, max_runtime: Optional[Any] = None, compute: str = 'cpu', data_uncertainty: Optional[DataUncertainty] = None, product_threshold: float = 1e-12, processing: Optional[Processing] = None) -> ModelTransmutationResults

Run transport-transmutation calculation.

The transmutation network is assembled from the configured yamc.transmutation_* sources, and there is no default library: the decay data, and when a step irradiates the reactions and fission yields too, must each be set (the latter two to a source or False), or this raises ValueError before any transport, naming each unset one.

Parameters:

Name Type Description Default
method str

Transmutation method -- "coupled" or "independent".

  • "coupled" -- transport runs every timestep with updated material compositions (standard approach).
  • "independent" -- transport runs once; the resulting per-source-particle reaction rates are scaled by each step's source_rate. Much faster for low-burnup / fusion scenarios where compositions barely change.

Both modes run one extra scouting transport first, before any transmutation product is loaded. It supplies the flux spectrum used to work out which products the irradiation can actually populate, and only those are then scored during the steps, which is what keeps the per-step cost off the reachable closure.

required
schedule Any

A :class:PulseSchedule of Pulse / Cooldown steps. Each Pulse contributes its duration and a source rate in n/s; each Cooldown (or a Pulse with rate 0) is a decay-only step with no transport. The Pulse source distribution is not used here: transport always uses the source configured on the Model, and a schedule with more than one distinct Pulse source is rejected.

required
total_particles Optional[int]

Particle histories per transport step, or None (default) for no particle cap. In "coupled" mode every timestep's transport run uses this count; "independent" mode runs transport once. The scouting run uses it too, so that it sees the same histories the steps will. One of total_particles / max_runtime must be set (they are the per-step stop conditions); a run with neither raises ValueError.

None
seed int

Base RNG seed for the transport runs (default: 1). In "coupled" mode it is the first step's; each later step transports on its own seed derived from it, so the steps' noise is independent and a rerun repeats.

1
threads Optional[int]

Optional number of threads for transport. Defaults to all available.

None
max_runtime Optional[Any]

Optional per-step wall-time budget for each transport solve (per timestep in "coupled" mode; the single solve in "independent" mode). Each solve stops at the first chunk checkpoint where its elapsed time reaches the budget, then finalizes normally. Accepts a float (seconds) or a (value, unit) tuple with unit 's', 'min', 'h', 'd', or 'a' (year), e.g. (30, 's'). Composes with total_particles: a solve ends at the first of the two. Because the budget is applied afresh to each timestep, a time-bounded transmutation is non-deterministic in history count.

None
data_uncertainty DataUncertainty

Uncertainty on the inventories. With method="independent", by resampling the one transport's rates and re-solving, as Material.transmute does. With method="coupled", by running the whole coupled calculation once per replica: each step's rates there were tallied in compositions the earlier steps' noise and data had already moved, so no resampling of one step describes the spread. A replica has its own transport seed when "statistical" is on (the nominal one otherwise, so its spread is the decay data's) and its own draw of "half_life", "decay_branching" and "fission_yield", the same draws an independent replica of the same index makes, and every step's transport runs on that replica's compositions. With "cross_sections" every transport of a replica, in every material, reads nuclear data with that replica's MF=33 and resonance-parameter draw applied (the draw an independent replica of the same index makes), so the draw moves the flux, the rates, the compositions and every later step's flux; a product that enters transport mid-run keeps its draw. That source is carried only beside "statistical": a replica on its own cross sections follows its own histories, so its spread holds the transport's noise too, and naming "cross_sections" alone raises. With "isomer_branching" every step of a replica tallies and splits its isomeric partials on production curves carrying that replica's MF=40 draw (again an independent replica's), split by the nominal rule at each collision energy. "decay_energy" and "decay_photon_lines" move what is evaluated from each inventory, as below. This is exact, nothing linearised, and costs the transport of every irradiation step once per replica (at least 128 replicas unless samples is set). An empty sources asks for every source and is carried. attribution reruns the ensemble once per applied source, each drawing that source alone on the same streams, so it costs one more coupled ensemble per source; "cross_sections" is measured beside "statistical" and reported as the variance with both less the variance with "statistical" alone, which can come out negative where the cross sections move a nuclide by less than the transport's noise. There are no first-order contributors and no linearity check with the coupled method. get_data_uncertainty_info's flux_response reads "coupled_replicas". The rest of this entry describes the independent method. The sources that apply there:

  • "statistical": the Monte Carlo uncertainty of the tallied reaction rates, from their per-history covariance, so the correlations between rates scored by the same histories are kept. Each rate's own sigma is read with get_reaction_rate_uncertainty. Different materials' tallies are separate estimates and are drawn independently, while the nuclear-data sources below are drawn once per replica and shared by every material;
  • "cross_sections": the ENDF MF=33 covariance and, where a nuclide's data folder carries them, its resonance parameters (MF=2 and MF=32) drawn per replica and rebuilt in place of the first-order MF=32 rows. The transport carries one likelihood-ratio weight per replica along every history, exactly as simulate_transport(data_uncertainty=...) does, with the same draws, and tallies every reaction rate, isomeric partial and fission-yield weight once per replica under it: replica k's rates are those its own data would give, self-shielding and spectrum shifts included, so a stronger resonance deepens its own dip and a perturbed scatterer moves every rate (W186 capture in a graphite sphere, C:W = 50: 0.2% from replica weights and from perturbed reruns, against 1.4% for a fold of the same draws against the nominal flux). The replica count is fixed before the transport (samples, or 256 at the default convergence), every replica is solved, and the info says whether the sigmas reached the target at that count. get_data_uncertainty_info's flux_response, transport_replicas and resonance_parameters report it;
  • "half_life": the decay data's half-life sigmas;
  • "decay_branching": the decay branching ratios of the parents with a stated sigma, each drawn keeping its total, as DataUncertainty describes;
  • "decay_energy": the decay data's mean decay energy sigmas, which move decay heat only;
  • "decay_photon_lines": the decay data's photon spectrum normalisation, line intensity and line energy sigmas, which move the decay photon spectrum and contact dose only;
  • "fission_yield": the independent fission yields, from the DY the evaluation states on each.

"flux_spectrum" does not apply: there is no supplied spectrum, and the flux's error is the statistical one. "isomer_branching" re-splits the tallied partials: the tally scores each MF=40 state's production on its covariance intervals at the energy of each track segment (per replica with replica weights), and each replica draws the state's production from those weights, as a spectrum run does from its group fold. With replica weights every replica's rates come from the same histories as the nominal ones, so the differences between replicas are resolved far more finely than the rates themselves, and "statistical" adds the nominal tally's error to each replica once; the sources are independent, so sources=["statistical"] isolates the transport's contribution and the default gives the total. The decay-data and fission-yield sources do not move the transport and are drawn per replica on the transmutation side, keyed on the same replica index. Omit data_uncertainty and nothing extra is tallied or solved: the inventories are bit-identical either way, and with replica weights the nominal inventories are too.

None
product_threshold float

The atom fraction, or share of the activity, decay heat or decay photon power, a transmutation product must reach at some point of the schedule for its cross sections to be downloaded and its own reactions tallied and solved. Default 1e-12. The scouting transport's spectrum is solved over the schedule, products crossing this are loaded, and the solve is repeated until nothing new crosses it. A product below it is still produced, decays and is reported; only its neutron reactions are dropped (get_product_screening_info says which). 0 loads every product the solve populates. See Material.transmute.

1e-12
processing Processing

Removals, transfers between materials and feeds, on the transmutable materials. The materials a transfer links are solved together each step. A material it names that is not in the geometry, a storage tank say, is carried unirradiated and reported under its own id, so its activity and contact dose read like any other's. Not yet combined with data_uncertainty.

None

Returns:

Name Type Description
ModelTransmutationResults ModelTransmutationResults

a TransmutationResults with the

ModelTransmutationResults

material compositions at each timestep, plus the model's own tallies

ModelTransmutationResults

from each step's transport (tally_results(step),

ModelTransmutationResults

tally_evolution(tally)).

Examples:

>>> schedule = yamc.PulseSchedule([
...     yamc.Pulse(rate=1e14, duration=86400.0, source=source),
...     yamc.Cooldown(duration=86400.0),
... ])
>>> results = model.simulate_transmutation(
...     method="coupled", schedule=schedule, total_particles=1000)
>>> # keyed by the id of the transmutable material, here steel
>>> co60 = results.get_nuclide_evolution(steel.id, "Co60")
>>> results = model.simulate_transmutation(
...     method="independent", schedule=schedule, total_particles=100_000,
...     data_uncertainty=yamc.DataUncertainty(seed=1))
>>> results.get_nuclide_uncertainty(steel.id, "Co60", 1)
>>> results.get_data_uncertainty_info(steel.id)["flux_response"]
'replica_weights'
Source code in yamc/_core/__init__.pyi
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
def simulate_transmutation(self, method: builtins.str, schedule: typing.Any, total_particles: typing.Optional[builtins.int] = None, seed: builtins.int = 1, threads: typing.Optional[builtins.int] = None, max_runtime: typing.Optional[typing.Any] = None, compute: builtins.str = 'cpu', data_uncertainty: typing.Optional[DataUncertainty] = None, product_threshold: builtins.float = 1e-12, processing: typing.Optional[Processing] = None) -> ModelTransmutationResults:
    r"""
    Run transport-transmutation calculation.

    The transmutation network is assembled from the configured
    ``yamc.transmutation_*`` sources, and there is no default library: the
    decay data, and when a step irradiates the reactions and fission yields
    too, must each be set (the latter two to a source or ``False``), or
    this raises ``ValueError`` before any transport, naming each unset one.

    Args:
        method: Transmutation method -- ``"coupled"`` or ``"independent"``.

            * ``"coupled"`` -- transport runs every timestep with updated
              material compositions (standard approach).
            * ``"independent"`` -- transport runs **once**; the resulting
              per-source-particle reaction rates are scaled by each step's
              ``source_rate``.  Much faster for low-burnup / fusion scenarios
              where compositions barely change.

            Both modes run one extra scouting transport first, before any
            transmutation product is loaded. It supplies the flux spectrum
            used to work out which products the irradiation can actually
            populate, and only those are then scored during the steps, which
            is what keeps the per-step cost off the reachable closure.
        schedule: A :class:`PulseSchedule` of ``Pulse`` / ``Cooldown`` steps.
            Each ``Pulse`` contributes its ``duration`` and a source ``rate``
            in n/s; each ``Cooldown`` (or a ``Pulse`` with rate 0) is a
            decay-only step with no transport. The Pulse source distribution
            is not used here: transport always uses the source configured on
            the Model, and a schedule with more than one distinct Pulse source
            is rejected.
        total_particles: Particle histories per transport step, or ``None``
            (default) for no particle cap. In ``"coupled"`` mode every
            timestep's transport run uses this count; ``"independent"`` mode
            runs transport once. The scouting run uses it too, so that it
            sees the same histories the steps will. One of
            ``total_particles`` / ``max_runtime`` must be set (they are the
            per-step stop conditions); a run with neither raises
            ``ValueError``.
        seed: Base RNG seed for the transport runs (default: 1). In
            ``"coupled"`` mode it is the first step's; each later step
            transports on its own seed derived from it, so the steps'
            noise is independent and a rerun repeats.
        threads: Optional number of threads for transport. Defaults to all available.
        max_runtime: Optional per-step wall-time budget for each transport
            solve (per timestep in ``"coupled"`` mode; the single solve in
            ``"independent"`` mode). Each solve stops at the first chunk
            checkpoint where its elapsed time reaches the budget, then
            finalizes normally. Accepts a float (seconds) or a
            ``(value, unit)`` tuple with unit ``'s'``, ``'min'``, ``'h'``,
            ``'d'``, or ``'a'`` (year), e.g. ``(30, 's')``. Composes with
            ``total_particles``: a solve ends at the first of the two.
            Because the budget is applied afresh to each timestep, a
            time-bounded transmutation is non-deterministic in history count.

        data_uncertainty (DataUncertainty, optional): Uncertainty on the
            inventories. With ``method="independent"``, by resampling the
            one transport's rates and re-solving, as ``Material.transmute``
            does. With ``method="coupled"``, by running the whole coupled
            calculation once per replica: each step's rates there were
            tallied in compositions the earlier steps' noise and data had
            already moved, so no resampling of one step describes the
            spread. A replica has its own transport seed when
            ``"statistical"`` is on (the nominal one otherwise, so its
            spread is the decay data's) and its own draw of
            ``"half_life"``, ``"decay_branching"`` and ``"fission_yield"``,
            the same draws an independent replica of the same index makes,
            and every step's transport runs on that replica's compositions.
            With ``"cross_sections"`` every transport of a replica, in every
            material, reads nuclear data with that replica's MF=33 and
            resonance-parameter draw applied (the draw an independent
            replica of the same index makes), so the draw moves the flux,
            the rates, the compositions and every later step's flux; a
            product that enters transport mid-run keeps its draw. That
            source is carried only beside ``"statistical"``: a replica on
            its own cross sections follows its own histories, so its spread
            holds the transport's noise too, and naming
            ``"cross_sections"`` alone raises. With
            ``"isomer_branching"`` every step of a replica tallies and
            splits its isomeric partials on production curves carrying that
            replica's MF=40 draw (again an independent replica's), split by
            the nominal rule at each collision energy.
            ``"decay_energy"`` and ``"decay_photon_lines"`` move what is
            evaluated from each inventory, as below. This is exact, nothing
            linearised, and costs the transport of every irradiation step
            once per replica (at least 128 replicas unless ``samples`` is
            set). An empty ``sources`` asks for every source and is carried.
            ``attribution`` reruns the ensemble once per applied source,
            each drawing that source alone on the same streams, so it costs
            one more coupled ensemble per source; ``"cross_sections"`` is
            measured beside ``"statistical"`` and reported as the variance
            with both less the variance with ``"statistical"`` alone, which
            can come out negative where the cross sections move a nuclide by
            less than the transport's noise. There are no first-order
            contributors and no linearity check with the coupled method.
            ``get_data_uncertainty_info``'s ``flux_response`` reads
            ``"coupled_replicas"``. The rest of this entry describes the
            independent method. The sources that apply there:

            - ``"statistical"``: the Monte Carlo uncertainty of the tallied
              reaction rates, from their per-history covariance, so the
              correlations between rates scored by the same histories are
              kept. Each rate's own sigma is read with
              ``get_reaction_rate_uncertainty``. Different materials'
              tallies are separate estimates and are drawn independently,
              while the nuclear-data sources below are drawn once per
              replica and shared by every material;
            - ``"cross_sections"``: the ENDF MF=33 covariance and, where a
              nuclide's data folder carries them, its resonance parameters
              (MF=2 and MF=32) drawn per replica and rebuilt in place of the
              first-order MF=32 rows. The transport carries one
              likelihood-ratio weight per replica along every history,
              exactly as ``simulate_transport(data_uncertainty=...)`` does,
              with the same draws, and tallies every reaction rate, isomeric
              partial and fission-yield weight once per replica under it:
              replica ``k``'s rates are those its own data would give,
              self-shielding and spectrum shifts included, so a stronger
              resonance deepens its own dip and a perturbed scatterer moves
              every rate (W186 capture in a graphite sphere, C:W = 50: 0.2%
              from replica weights and from perturbed reruns, against 1.4%
              for a fold of the same draws against the nominal flux). The
              replica count is fixed before the transport (``samples``, or
              256 at the default ``convergence``), every replica is solved,
              and the info says whether the sigmas reached the target at that
              count. ``get_data_uncertainty_info``'s ``flux_response``,
              ``transport_replicas`` and ``resonance_parameters`` report it;
            - ``"half_life"``: the decay data's half-life sigmas;
            - ``"decay_branching"``: the decay branching ratios of the
              parents with a stated sigma, each drawn keeping its total, as
              ``DataUncertainty`` describes;
            - ``"decay_energy"``: the decay data's mean decay energy sigmas,
              which move decay heat only;
            - ``"decay_photon_lines"``: the decay data's photon spectrum
              normalisation, line intensity and line energy sigmas, which
              move the decay photon spectrum and contact dose only;
            - ``"fission_yield"``: the independent fission yields, from the
              DY the evaluation states on each.

            ``"flux_spectrum"`` does not apply: there is no supplied spectrum,
            and the flux's error is the statistical one.
            ``"isomer_branching"`` re-splits the tallied partials: the tally
            scores each MF=40 state's production on its covariance
            intervals at the energy of each track segment (per replica with
            replica weights), and each replica draws the state's production
            from those weights, as a spectrum run does from its group fold.
            With replica weights every replica's rates come from the same
            histories as the nominal ones, so the differences between replicas are resolved
            far more finely than the rates themselves, and ``"statistical"``
            adds the nominal tally's error to each replica once; the sources
            are independent, so ``sources=["statistical"]`` isolates the
            transport's contribution and the default gives the total. The
            decay-data and fission-yield sources do not move the transport
            and are drawn per replica on the transmutation side, keyed on the
            same replica index. Omit ``data_uncertainty`` and nothing extra
            is tallied or solved: the inventories are bit-identical either
            way, and with replica weights the nominal inventories are too.

        product_threshold (float): The atom fraction, or share of the
            activity, decay heat or decay photon power, a transmutation
            product must reach at some point of the schedule for its cross
            sections to be downloaded and its own reactions tallied and
            solved. Default 1e-12. The scouting transport's spectrum is
            solved over the schedule, products crossing this are loaded,
            and the solve is repeated until nothing new crosses it. A
            product below it is still produced, decays and is reported;
            only its neutron reactions are dropped
            (``get_product_screening_info`` says which). 0 loads every
            product the solve populates. See ``Material.transmute``.

        processing (Processing, optional): Removals, transfers between
            materials and feeds, on the transmutable materials. The
            materials a transfer links are solved together each step. A
            material it names that is not in the geometry, a storage tank
            say, is carried unirradiated and reported under its own id, so
            its activity and contact dose read like any other's. Not yet
            combined with ``data_uncertainty``.

    Returns:
        ModelTransmutationResults: a ``TransmutationResults`` with the
        material compositions at each timestep, plus the model's own tallies
        from each step's transport (``tally_results(step)``,
        ``tally_evolution(tally)``).

    Examples:
        >>> schedule = yamc.PulseSchedule([
        ...     yamc.Pulse(rate=1e14, duration=86400.0, source=source),
        ...     yamc.Cooldown(duration=86400.0),
        ... ])
        >>> results = model.simulate_transmutation(
        ...     method="coupled", schedule=schedule, total_particles=1000)
        >>> # keyed by the id of the transmutable material, here steel
        >>> co60 = results.get_nuclide_evolution(steel.id, "Co60")
        >>> results = model.simulate_transmutation(
        ...     method="independent", schedule=schedule, total_particles=100_000,
        ...     data_uncertainty=yamc.DataUncertainty(seed=1))
        >>> results.get_nuclide_uncertainty(steel.id, "Co60", 1)
        >>> results.get_data_uncertainty_info(steel.id)["flux_response"]
        'replica_weights'
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
3921
3922
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

to_html

to_html(path: Optional[str | PathLike | Path] = None, embed_cross_sections: bool | Iterable[str] = False, **kwargs: Any) -> Optional[bytes]

Export a self-contained, browser-runnable interactive HTML page to path, or return its bytes when path is None.

Source code in yamc/_core/__init__.pyi
3923
3924
def to_html(self, path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None, embed_cross_sections: builtins.bool | typing.Iterable[builtins.str] = False, **kwargs: typing.Any) -> typing.Optional[bytes]:
    r"""Export a self-contained, browser-runnable interactive HTML page to path, or return its bytes when path is None."""

plot

plot(*args: Any, **kwargs: Any) -> InteractivePlot

Render an interactive geometry slice plot. See the docs for keyword arguments.

Source code in yamc/_core/__init__.pyi
3925
3926
def plot(self, *args: typing.Any, **kwargs: typing.Any) -> InteractivePlot:
    r"""Render an interactive geometry slice plot. See the docs for keyword arguments."""

NeutronSource

NeutronSource(*, position: Optional[Any] = None, energy: Optional[Any] = None, direction: Optional[Any] = None, strength: Optional[float] = None)

A neutron particle source with spatial, energy, and angular distributions.

Create a neutron source.

Parameters:

Name Type Description Default
position Optional[Any]

Birth location. Pass a tuple/list (x, y, z) in cm for a fixed point (recommended), or a spatial distribution object (yamc.sources.CylindricalRing, yamc.sources.MeshDistribution) for finer control. Defaults to the origin (0, 0, 0).

None
energy Optional[Any]

Birth energy. Pass a float in eV for a single energy (recommended), or an energy distribution (yamc.Discrete, yamc.Uniform, yamc.Normal) for a spectrum. Defaults to 14.06 MeV (D-T fusion).

None
direction Optional[Any]

Angular distribution (e.g., yamc.Isotropic()). Defaults to Isotropic.

None
strength Optional[float]

Source strength for multi-source weighting. Defaults to 1.0.

None

Returns:

Name Type Description
NeutronSource NeutronSource

A neutron source.

Raises:

Type Description
ValueError

If position has a NaN or infinite coordinate, energy is a NaN or infinite number, or strength is NaN, infinite or negative. The message names the parameter and its value.

Source code in yamc/_core/__init__.pyi
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
def __new__(cls, *, position: typing.Optional[typing.Any] = None, energy: typing.Optional[typing.Any] = None, direction: typing.Optional[typing.Any] = None, strength: typing.Optional[builtins.float] = None) -> NeutronSource:
    r"""
    Create a neutron source.

    Args:
        position: Birth location. Pass a tuple/list ``(x, y, z)`` in cm for a fixed
               point (recommended), or a spatial distribution object
               (yamc.sources.CylindricalRing, yamc.sources.MeshDistribution) for finer control.
               Defaults to the origin (0, 0, 0).
        energy: Birth energy. Pass a float in eV for a single energy (recommended),
               or an energy distribution (yamc.Discrete, yamc.Uniform, yamc.Normal)
               for a spectrum. Defaults to 14.06 MeV (D-T fusion).
        direction: Angular distribution (e.g., yamc.Isotropic()).
               Defaults to Isotropic.
        strength: Source strength for multi-source weighting. Defaults to 1.0.

    Returns:
        NeutronSource: A neutron source.

    Raises:
        ValueError: If ``position`` has a NaN or infinite coordinate, ``energy``
            is a NaN or infinite number, or ``strength`` is NaN, infinite or
            negative. The message names the parameter and its value.
    """

position property writable

position: Any

Spatial distribution describing where particles are sampled. Returns an (x, y, z) list for a fixed point, or the spatial distribution object.

energy property writable

energy: Any

Energy distribution describing source particle energies in eV. Returns a Discrete, Uniform, or Normal distribution.

direction property writable

direction: Any

Angular distribution describing source particle directions. Returns an Isotropic or Monodirectional distribution.

strength property writable

strength: float

Relative strength of this source for multi-source weighting. Default is 1.0; only meaningful when multiple sources are passed to a Model.

sample

sample() -> Particle

Sample a particle from the source.

Source code in yamc/_core/__init__.pyi
4064
4065
4066
4067
def sample(self) -> Particle:
    r"""
    Sample a particle from the source.
    """

sample_n

sample_n(n: int) -> tuple[list[list[float]], list[float]]

Sample n particles at once, returning their birth positions and energies.

The compiled batch form of calling :meth:sample in a loop: used by the VTK-HDF source export to avoid one Python<->Rust crossing per sample.

Parameters:

Name Type Description Default
n int

Number of particles to sample.

required

Returns:

Type Description
list[list[float]]

A (positions, energies) tuple where positions is a

list[float]

list of [x, y, z] (length n) and energies is a

tuple[list[list[float]], list[float]]

list of floats in eV (length n).

Source code in yamc/_core/__init__.pyi
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
def sample_n(self, n: builtins.int) -> tuple[builtins.list[builtins.list[builtins.float]], builtins.list[builtins.float]]:
    r"""
    Sample ``n`` particles at once, returning their birth positions
    and energies.

    The compiled batch form of calling :meth:`sample` in a loop:
    used by the VTK-HDF source export to avoid one Python<->Rust
    crossing per sample.

    Args:
        n: Number of particles to sample.

    Returns:
        A ``(positions, energies)`` tuple where ``positions`` is a
        list of ``[x, y, z]`` (length ``n``) and ``energies`` is a
        list of floats in eV (length ``n``).
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
4086
4087
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

PhotonSource

PhotonSource(*, position: Optional[Any] = None, energy: Optional[Any] = None, direction: Optional[Any] = None, strength: Optional[float] = None)

A photon particle source with spatial, energy, and angular distributions.

Create a photon source.

Parameters:

Name Type Description Default
position Optional[Any]

Birth location. Pass a tuple/list (x, y, z) in cm for a fixed point (recommended), or a spatial distribution object (yamc.sources.CylindricalRing, yamc.sources.MeshDistribution) for finer control. Defaults to the origin (0, 0, 0).

None
energy Optional[Any]

Birth energy. Pass a float in eV for a single energy (recommended), or an energy distribution (yamc.Discrete, yamc.Uniform, yamc.Normal) for a spectrum. Required: photons have no default birth energy, so omitting this raises a ValueError.

None
direction Optional[Any]

Angular distribution (e.g., yamc.Isotropic()). Defaults to Isotropic.

None
strength Optional[float]

Source strength for multi-source weighting. Defaults to 1.0.

None

Returns:

Name Type Description
PhotonSource PhotonSource

A photon source.

Raises:

Type Description
ValueError

If energy is omitted, position has a NaN or infinite coordinate, energy is a NaN or infinite number, or strength is NaN, infinite or negative. The message names the parameter and its value.

Source code in yamc/_core/__init__.pyi
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
def __new__(cls, *, position: typing.Optional[typing.Any] = None, energy: typing.Optional[typing.Any] = None, direction: typing.Optional[typing.Any] = None, strength: typing.Optional[builtins.float] = None) -> PhotonSource:
    r"""
    Create a photon source.

    Args:
        position: Birth location. Pass a tuple/list ``(x, y, z)`` in cm for a fixed
               point (recommended), or a spatial distribution object
               (yamc.sources.CylindricalRing, yamc.sources.MeshDistribution) for finer control.
               Defaults to the origin (0, 0, 0).
        energy: Birth energy. Pass a float in eV for a single energy (recommended),
               or an energy distribution (yamc.Discrete, yamc.Uniform, yamc.Normal)
               for a spectrum. Required: photons have no default birth energy, so
               omitting this raises a ValueError.
        direction: Angular distribution (e.g., yamc.Isotropic()).
               Defaults to Isotropic.
        strength: Source strength for multi-source weighting. Defaults to 1.0.

    Returns:
        PhotonSource: A photon source.

    Raises:
        ValueError: If ``energy`` is omitted, ``position`` has a NaN or infinite
            coordinate, ``energy`` is a NaN or infinite number, or ``strength`` is
            NaN, infinite or negative. The message names the parameter and its
            value.
    """

position property writable

position: Any

Spatial distribution describing where particles are sampled. Returns an (x, y, z) list for a fixed point, or the spatial distribution object.

energy property writable

energy: Any

Energy distribution describing source particle energies in eV. Returns a Discrete, Uniform, or Normal distribution.

direction property writable

direction: Any

Angular distribution describing source particle directions. Returns an Isotropic or Monodirectional distribution.

strength property writable

strength: float

Relative strength of this source for multi-source weighting. Default is 1.0; only meaningful when multiple sources are passed to a Model.

sample

sample() -> Particle

Sample a particle from the source.

Source code in yamc/_core/__init__.pyi
4636
4637
4638
4639
def sample(self) -> Particle:
    r"""
    Sample a particle from the source.
    """

sample_n

sample_n(n: int) -> tuple[list[list[float]], list[float]]

Sample n particles at once, returning their birth positions and energies.

The compiled batch form of calling :meth:sample in a loop: used by the VTK-HDF source export to avoid one Python<->Rust crossing per sample.

Parameters:

Name Type Description Default
n int

Number of particles to sample.

required

Returns:

Type Description
list[list[float]]

A (positions, energies) tuple where positions is a

list[float]

list of [x, y, z] (length n) and energies is a

tuple[list[list[float]], list[float]]

list of floats in eV (length n).

Source code in yamc/_core/__init__.pyi
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
def sample_n(self, n: builtins.int) -> tuple[builtins.list[builtins.list[builtins.float]], builtins.list[builtins.float]]:
    r"""
    Sample ``n`` particles at once, returning their birth positions
    and energies.

    The compiled batch form of calling :meth:`sample` in a loop:
    used by the VTK-HDF source export to avoid one Python<->Rust
    crossing per sample.

    Args:
        n: Number of particles to sample.

    Returns:
        A ``(positions, energies)`` tuple where ``positions`` is a
        list of ``[x, y, z]`` (length ``n``) and ``energies`` is a
        list of floats in eV (length ``n``).
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
4658
4659
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

Processing

Processing()

Removals, transfers between materials and feeds, for a transmutation run.

Each term adds to the Bateman equations of the materials it names, and every one is solved exactly: a first-order removal is a loss rate, a transfer is that loss arriving in the destination scaled by the ratio of volumes, and a feed is a source held constant over each interval. Materials a transfer links are solved together each step.

A destination need not be irradiated. One that transmute or simulate_transmutation is not otherwise given (a storage tank outside the geometry, say) is carried unirradiated and reported in the results under its own id, so its activity and contact dose read like any other material's.

A rate is a number, or a table (times, rates): piecewise constant, each rate holding from its time (seconds from the start of the schedule, or (value, unit)) to the next, and zero before the first. Steps are split where a table changes, so a table is solved exactly. steps restricts a term to the listed schedule steps (0-based).

Examples:

>>> loop = yamc.Processing()
>>> # tritium out of the breeder with a 2 h half-time, into a tank
>>> loop.add_transfer(pbli, "H3", rate=(2, "h"), rate_units="half-time",
...                   destination=tank)
>>> loop.add_transfer(pbli, "He", rate=6, rate_units="1/h")  # vented
>>> loop.add_feed(pbli, {"Li6": 1.0}, rate=0.05, rate_units="kg/d", steps=[0, 2])
>>> # a whole liquid circulating between a core and a pool
>>> loop.add_transfer(water, rate=flow / water.volume, destination=pool)
>>> loop.add_transfer(pool, rate=flow / pool.volume, destination=water)
>>> results = yamc.transmute([pbli, water], schedules, processing=loop)
Source code in yamc/_core/__init__.pyi
4701
def __new__(cls) -> Processing: ...

material_ids property

material_ids: list[int]

The ids of every material a term names.

add_transfer

add_transfer(material: Material, component: Optional[str] = None, *, rate: Any, rate_units: str = '1/s', destination: Optional[Material] = None, steps: Optional[Sequence[int]] = None) -> None

Remove component from material continuously, at a first-order rate, into destination when given and out of the system otherwise.

Parameters:

Name Type Description Default
material Material

Where it is removed from.

required
component str

An element ("H", every isotope) or a nuclide ("H3"). None (the default) removes everything, as a flowing liquid does.

None
rate float | tuple

The rate, or a (times, rates) table.

required
rate_units str

"1/s" (or 1/min, 1/h, 1/d, 1/a), or "half-time" for the time to remove half, in seconds or as (value, unit).

'1/s'
destination Material

Where it goes. Both materials need a volume: what leaves is diluted by their ratio.

None
steps list[int]

The schedule steps it acts on; every step by default.

None
Source code in yamc/_core/__init__.pyi
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
def add_transfer(self, material: Material, component: typing.Optional[builtins.str] = None, *, rate: typing.Any, rate_units: builtins.str = '1/s', destination: typing.Optional[Material] = None, steps: typing.Optional[typing.Sequence[builtins.int]] = None) -> None:
    r"""
    Remove ``component`` from ``material`` continuously, at a first-order
    rate, into ``destination`` when given and out of the system otherwise.

    Args:
        material (Material): Where it is removed from.
        component (str, optional): An element (``"H"``, every isotope) or a
            nuclide (``"H3"``). ``None`` (the default) removes everything,
            as a flowing liquid does.
        rate (float | tuple): The rate, or a ``(times, rates)`` table.
        rate_units (str): ``"1/s"`` (or ``1/min``, ``1/h``, ``1/d``,
            ``1/a``), or ``"half-time"`` for the time to remove half, in
            seconds or as ``(value, unit)``.
        destination (Material, optional): Where it goes. Both materials need
            a volume: what leaves is diluted by their ratio.
        steps (list[int], optional): The schedule steps it acts on; every
            step by default.
    """

add_feed

add_feed(material: Material, composition: Mapping[str, float], *, rate: Any, rate_units: str = 'g/s', proportional_to: Optional[str] = None, steps: Optional[Sequence[int]] = None) -> None

Feed composition into material continuously.

Parameters:

Name Type Description Default
material Material

What it is fed into.

required
composition dict[str, float]

Nuclides or natural elements, by atom fraction (normalized).

required
rate float | tuple

The rate, or a (times, rates) table.

required
rate_units str

An amount per time, "g/s", "kg/d", "mol/h" or "atoms/s", for which material needs a volume; or with proportional_to a rate constant "1/s".

'g/s'
proportional_to str

A nuclide of material: the feed is then rate times its inventory, which holds an enrichment (Li6 fed in proportion to Li7, say).

None
steps list[int]

The schedule steps it acts on; every step by default.

None
Source code in yamc/_core/__init__.pyi
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
def add_feed(self, material: Material, composition: typing.Mapping[builtins.str, builtins.float], *, rate: typing.Any, rate_units: builtins.str = 'g/s', proportional_to: typing.Optional[builtins.str] = None, steps: typing.Optional[typing.Sequence[builtins.int]] = None) -> None:
    r"""
    Feed ``composition`` into ``material`` continuously.

    Args:
        material (Material): What it is fed into.
        composition (dict[str, float]): Nuclides or natural elements, by
            atom fraction (normalized).
        rate (float | tuple): The rate, or a ``(times, rates)`` table.
        rate_units (str): An amount per time, ``"g/s"``, ``"kg/d"``,
            ``"mol/h"`` or ``"atoms/s"``, for which ``material`` needs a
            volume; or with ``proportional_to`` a rate constant ``"1/s"``.
        proportional_to (str, optional): A nuclide of ``material``: the feed
            is then ``rate`` times its inventory, which holds an enrichment
            (Li6 fed in proportion to Li7, say).
        steps (list[int], optional): The schedule steps it acts on; every
            step by default.
    """

Region

A CSG region -- half-spaces combined with boolean operators (& intersection, | union, ~ complement) -- used to define a Cell.

contains

contains(point: tuple[float, float, float]) -> bool

Check if a point is inside this region.

Parameters:

Name Type Description Default
point tuple[float, float, float]

Tuple of 3 floats (x, y, z)

required

Returns:

Type Description
bool

True if the point satisfies the region's Boolean expression

Source code in yamc/_core/__init__.pyi
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
def contains(self, point: tuple[builtins.float, builtins.float, builtins.float]) -> builtins.bool:
    r"""
    Check if a point is inside this region.

    Args:
        point: Tuple of 3 floats (x, y, z)

    Returns:
        True if the point satisfies the region's Boolean expression
    """

bounding_box

bounding_box() -> BoundingBox

Get the axis-aligned bounding box for this region.

Returns:

Type Description
BoundingBox

BoundingBox object containing the region

Source code in yamc/_core/__init__.pyi
5038
5039
5040
5041
5042
5043
5044
def bounding_box(self) -> BoundingBox:
    r"""
    Get the axis-aligned bounding box for this region.

    Returns:
        BoundingBox object containing the region
    """

calculate_volume

calculate_volume(samples: int = 100000, bounding_box: Optional[BoundingBox] = None, seed: Optional[int] = None) -> VolumeResult

Estimate the volume of this region by stochastic sampling.

Parameters:

Name Type Description Default
samples int

Number of random points to sample (default 100,000)

100000
bounding_box Optional[BoundingBox]

Optional BoundingBox to sample within. Defaults to the region's bounding box.

None
seed Optional[int]

Optional RNG seed for reproducibility (default 1)

None

Returns:

Type Description
VolumeResult

VolumeResult with volume, std_dev, and num_hits

Source code in yamc/_core/__init__.pyi
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
def calculate_volume(self, samples: builtins.int = 100000, bounding_box: typing.Optional[BoundingBox] = None, seed: typing.Optional[builtins.int] = None) -> VolumeResult:
    r"""
    Estimate the volume of this region by stochastic sampling.

    Args:
        samples: Number of random points to sample (default 100,000)
        bounding_box: Optional BoundingBox to sample within. Defaults to the region's bounding box.
        seed: Optional RNG seed for reproducibility (default 1)

    Returns:
        VolumeResult with volume, std_dev, and num_hits
    """

sample_slice

sample_slice(origin: Optional[Any] = None, width: Optional[Any] = None, resolution: Optional[Any] = None, basis: str = 'xy') -> list[list[int]]

Generate a 2D map showing which points are inside the region.

Parameters:

Name Type Description Default
origin Optional[Any]

Origin of the plot (tuple/list of 3 floats). Defaults to bbox center or (0,0,0).

None
width Optional[Any]

Width of the plot (tuple/list of 2 floats). Defaults to bbox width or (10,10).

None
resolution Optional[Any]

Raster resolution as a total pixel budget (int) or an explicit (h, v) tuple. Defaults to 40000.

None
basis str

The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

'xy'

Returns:

Type Description
list[list[int]]

A 2D list of ints where 1 means inside, -1 means outside.

Source code in yamc/_core/__init__.pyi
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
def sample_slice(self, origin: typing.Optional[typing.Any] = None, width: typing.Optional[typing.Any] = None, resolution: typing.Optional[typing.Any] = None, basis: builtins.str = 'xy') -> builtins.list[builtins.list[builtins.int]]:
    r"""
    Generate a 2D map showing which points are inside the region.

    Args:
        origin: Origin of the plot (tuple/list of 3 floats). Defaults to bbox center or (0,0,0).
        width: Width of the plot (tuple/list of 2 floats). Defaults to bbox width or (10,10).
        resolution: Raster resolution as a total pixel budget (int) or an explicit (h, v) tuple. Defaults to 40000.
        basis: The plane to slice - "xy", "xz", or "yz". Defaults to "xy".

    Returns:
        A 2D list of ints where 1 means inside, -1 means outside.
    """

voxelize

voxelize(lower_left: Sequence[float], spacing: Sequence[float], shape: tuple[int, int, int]) -> list[int]

Rasterize this region onto a 3D voxel grid (the compiled core of Region.to_vtkhdf).

Parameters:

Name Type Description Default
lower_left Sequence[float]

Grid minimum corner (x, y, z).

required
spacing Sequence[float]

Voxel size (dx, dy, dz).

required
shape tuple[int, int, int]

Voxel counts (nx, ny, nz).

required

Returns:

Type Description
list[int]

Flat mask in (nz, ny, nx) C-order: 1 inside, 0 outside.

Source code in yamc/_core/__init__.pyi
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
def voxelize(self, lower_left: typing.Sequence[builtins.float], spacing: typing.Sequence[builtins.float], shape: tuple[builtins.int, builtins.int, builtins.int]) -> builtins.list[builtins.int]:
    r"""
    Rasterize this region onto a 3D voxel grid (the compiled core of
    ``Region.to_vtkhdf``).

    Args:
        lower_left: Grid minimum corner ``(x, y, z)``.
        spacing: Voxel size ``(dx, dy, dz)``.
        shape: Voxel counts ``(nx, ny, nz)``.

    Returns:
        Flat mask in (nz, ny, nx) C-order: 1 inside, 0 outside.
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
5085
5086
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

plot

plot(*args: Any, **kwargs: Any) -> InteractivePlot

Render an interactive plot of this region. See the docs for keyword arguments.

Source code in yamc/_core/__init__.pyi
5087
5088
def plot(self, *args: typing.Any, **kwargs: typing.Any) -> InteractivePlot:
    r"""Render an interactive plot of this region. See the docs for keyword arguments."""

Tally

Tally(scores: Sequence[str | int] | None = None, name: Optional[str] = None, id: Optional[int] = None, nuclides: Optional[Sequence[str]] = None, response: str | Sequence[str] | Material | None = None, cells: Cell | Sequence[Cell] | None = None, materials: Material | Sequence[Material] | None = None, surfaces: Surface | Sequence[Surface] | None = None, cosine_bins: Optional[Sequence[float]] = None, mesh: RegularRectangularMesh | RegularCylindricalMesh | MeshGeometry | UnstructuredMesh | tuple[MeshGeometry | UnstructuredMesh, str] | tuple[MeshGeometry, int] | None = None, energy_bins: Optional[Sequence[float]] = None, energy_group_structure: Optional[str] = None, energy_function: tuple[Sequence[float], Sequence[float]] | tuple[Sequence[float], Sequence[float], str] | tuple[Sequence[float], Sequence[float], str, str] | None = None, interpolation: Optional[str] = None, dose_coefficients: tuple[str, str] | tuple[str, str, str] | None = None, particle: Optional[str] = None, parent_nuclides: Optional[Sequence[str]] = None, estimator: Optional[str] = None, covariance: bool = False)

A tally used to score physical quantities during particle transport simulation.

Tallies accumulate per-history statistics over all source particles for quantities like flux, heating, or reaction rates (via MT numbers). Results include mean values, standard deviations, and relative errors.

Create a new Tally.

Parameters:

Name Type Description Default
scores list

Scores to tally (e.g., ['flux'], [101, 'heating'])

None
name str

Name for the tally

None
id int

Numeric ID for the tally

None
nuclides list

Nuclides for per-nuclide macroscopic breakdown at their real in-material density (e.g. ['Li6', 'Li7', 'total']). Mutually exclusive with response.

None
response str | list[str] | Material

Score a virtual response across the whole geometry (including void), decoupled from the cell material: * str / list[str] -- microscopic cross sections (barns) for those nuclide(s) at unit density; one bin per nuclide. * Material -- the material's macroscopic response, weighting each nuclide's microscopic XS by its real atom density; one combined bin (e.g. a SiO2 dose map). Mutually exclusive with nuclides.

None
cells Cell | list[Cell]

Cell(s) to bin over -- one result bin per cell. A single cell (not in a list) is also accepted.

None
materials Material | list[Material]

Material(s) to bin over -- one result bin per material. A single material (not in a list) is also accepted.

None
surfaces Surface | list[Surface]

Make this a surface-current tally: it scores each time a particle crosses one of these surfaces, rather than along tracks or at collisions, with one result bin per surface in the order given. Its scores count crossings per source particle, by the side of the surface they cross to:

  • "current-above" -- crossings towards the surface's .above side, each adding the particle weight.
  • "current-below" -- crossings towards .below, each adding the particle weight.
  • "current-net" -- above minus below: the weight with a plus sign towards .above and a minus sign towards .below.

Which side is .above is the same as for regions: outside a Sphere, Cylinder, Cone or Torus, and the positive side of a Plane (x > offset for axis="x"). So on a sphere "current-above" is the outward current and "current-below" the inward one; on an x plane they are the currents towards +x and -x. For the outer surface of a body in vacuum nothing comes back, so "current-above" and "current-net" are both the leakage, and "current-below" is zero. Inside a model a particle can cross the same surface several times, and each crossing counts.

A surface tally takes energy_bins (the crossing energy), cosine_bins, particle and an energy function, and no cells, materials, mesh, nuclides, response or estimator. It needs surface tracking (not "woodcock" or "hybrid") and CSG surfaces, and runs on the CPU. Units are particles per source particle.

None
cosine_bins list[float]

Bin a surface tally by the cosine of the angle between the particle's direction and the surface normal at the crossing, the normal pointing to .above (outwards on a sphere). Ascending edges within [-1, 1]: a cosine of 1 is straight along the normal, 0 is grazing, and negative cosines are crossings towards .below. [-1.0, 0.0, 1.0] splits crossings by direction; [math.cos(math.radians(17.28)), 1.0] keeps only particles leaving within 17.28 degrees of the normal, as a detector that views part of a surface sees. Needs surfaces.

None
mesh optional

A mesh to bin on. A RegularRectangularMesh or RegularCylindricalMesh bins on its grid. A MeshGeometry (its own tets) or an UnstructuredMesh (a tally-only mesh) gives a bin per cell, in the order of tetrahedra or cells; with a region name, (geometry, "breeder"), only that volume's cells score.

None
energy_bins list[float]

Energy bin boundaries in eV

None
energy_group_structure str

Named group structure (e.g. "VITAMIN-J-175")

None
energy_function tuple

(energy, y[, units[, interpolation]]) for energy-dependent weighting. The optional fourth item names the interpolation, as as_energy_function() returns it.

None
interpolation str

How energy_function interpolates between its points: "cubic" (natural cubic spline in linear energy, the default, needs 4 points), "linear", or "log-log" (linear in log energy and log value, the convention for tabulated coefficients and how contact dose reads them; an interval with a zero value falls back to linear). Only valid with energy_function.

None
dose_coefficients tuple

(particle, geometry[, data_source]) for dose. The coefficients are interpolated log-log, as contact dose reads the same tables. The tally scores only the particle the coefficients are for, so particle need not be passed as well. The particle is "neutron", "photon" or "neutron_photon". The last is the total dose of a coupled run: neutrons and photons are each weighted by their own coefficients and scored into the same bin, so the standard deviation is that of the total. Two tallies added afterwards cannot give it, because the photons of a history are correlated with the neutrons that produced them. It takes no particle and runs on the CPU only.

None
particle str

"neutron" or "photon". With dose_coefficients it defaults to their particle, and naming the other one raises ValueError.

None
parent_nuclides list[str]

Nuclides for D1S parent binning

None
covariance bool

Also accumulate the covariance of the bin means, history by history, read back as :attr:covariance. Off by default. A per-bin standard_deviation treats the bins as independent, which they are not: bins scored by the same histories move together, so anything summed over them, a reaction rate over a spectrum, inherits an understated error from the standard deviations alone. Meant for spectra: it is limited to 2048 bins, and CPU only.

False
Notes

cells and materials are mutually exclusive -- a single tally binning over both cells and materials is not supported (use separate tallies).

When multiple cells or materials are provided, the mean/std_dev arrays grow to hold one bin per cell/material, in the order given. Flat bin layout (slowest → fastest varying) is: score → cell → material → nuclide → parent_nuclide → energy → mesh.

Source code in yamc/_core/__init__.pyi
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
def __new__(cls, scores: typing.Sequence[builtins.str | builtins.int] | None = None, name: typing.Optional[builtins.str] = None, id: typing.Optional[builtins.int] = None, nuclides: typing.Optional[typing.Sequence[builtins.str]] = None, response: str | typing.Sequence[str] | Material | None = None, cells: Cell | typing.Sequence[Cell] | None = None, materials: Material | typing.Sequence[Material] | None = None, surfaces: Surface | typing.Sequence[Surface] | None = None, cosine_bins: typing.Optional[typing.Sequence[builtins.float]] = None, mesh: RegularRectangularMesh | RegularCylindricalMesh | MeshGeometry | UnstructuredMesh | tuple[MeshGeometry | UnstructuredMesh, builtins.str] | tuple[MeshGeometry, builtins.int] | None = None, energy_bins: typing.Optional[typing.Sequence[builtins.float]] = None, energy_group_structure: typing.Optional[builtins.str] = None, energy_function: tuple[typing.Sequence[builtins.float], typing.Sequence[builtins.float]] | tuple[typing.Sequence[builtins.float], typing.Sequence[builtins.float], builtins.str] | tuple[typing.Sequence[builtins.float], typing.Sequence[builtins.float], builtins.str, builtins.str] | None = None, interpolation: typing.Optional[builtins.str] = None, dose_coefficients: tuple[builtins.str, builtins.str] | tuple[builtins.str, builtins.str, builtins.str] | None = None, particle: typing.Optional[builtins.str] = None, parent_nuclides: typing.Optional[typing.Sequence[builtins.str]] = None, estimator: typing.Optional[builtins.str] = None, covariance: builtins.bool = False) -> Tally:
    r"""
    Create a new Tally.

    Args:
        scores (list, optional): Scores to tally (e.g., ['flux'], [101, 'heating'])
        name (str, optional): Name for the tally
        id (int, optional): Numeric ID for the tally
        nuclides (list, optional): Nuclides for per-nuclide *macroscopic*
            breakdown at their real in-material density (e.g. ['Li6', 'Li7',
            'total']). Mutually exclusive with ``response``.
        response (str | list[str] | Material, optional): Score a *virtual*
            response across the whole geometry (including void), decoupled
            from the cell material:
              * ``str`` / ``list[str]`` -- microscopic cross sections (barns)
                for those nuclide(s) at unit density; one bin per nuclide.
              * ``Material`` -- the material's *macroscopic* response,
                weighting each nuclide's microscopic XS by its real atom
                density; one combined bin (e.g. a SiO2 dose map).
            Mutually exclusive with ``nuclides``.
        cells (Cell | list[Cell], optional): Cell(s) to bin over -- one result bin
            per cell. A single cell (not in a list) is also accepted.
        materials (Material | list[Material], optional): Material(s) to bin over --
            one result bin per material. A single material (not in a list) is also
            accepted.
        surfaces (Surface | list[Surface], optional): Make this a surface-current
            tally: it scores each time a particle crosses one of these surfaces,
            rather than along tracks or at collisions, with one result bin per
            surface in the order given. Its scores count crossings per source
            particle, by the side of the surface they cross to:

              * ``"current-above"`` -- crossings towards the surface's ``.above``
                side, each adding the particle weight.
              * ``"current-below"`` -- crossings towards ``.below``, each adding
                the particle weight.
              * ``"current-net"`` -- above minus below: the weight with a plus
                sign towards ``.above`` and a minus sign towards ``.below``.

            Which side is ``.above`` is the same as for regions: outside a
            ``Sphere``, ``Cylinder``, ``Cone`` or ``Torus``, and the positive side
            of a ``Plane`` (``x > offset`` for ``axis="x"``). So on a sphere
            ``"current-above"`` is the outward current and ``"current-below"``
            the inward one; on an x plane they are the currents towards +x and
            -x. For the outer surface of a body in vacuum nothing comes back, so
            ``"current-above"`` and ``"current-net"`` are both the leakage, and
            ``"current-below"`` is zero. Inside a model a particle can cross the
            same surface several times, and each crossing counts.

            A surface tally takes ``energy_bins`` (the crossing energy),
            ``cosine_bins``, ``particle`` and an energy function, and no cells,
            materials, mesh, nuclides, response or estimator. It needs surface
            tracking (not ``"woodcock"`` or ``"hybrid"``) and CSG surfaces, and
            runs on the CPU. Units are particles per source particle.
        cosine_bins (list[float], optional): Bin a surface tally by the cosine of
            the angle between the particle's direction and the surface normal at
            the crossing, the normal pointing to ``.above`` (outwards on a
            sphere). Ascending edges within ``[-1, 1]``: a cosine of 1 is
            straight along the normal, 0 is grazing, and negative cosines are
            crossings towards ``.below``. ``[-1.0, 0.0, 1.0]`` splits crossings
            by direction; ``[math.cos(math.radians(17.28)), 1.0]`` keeps only
            particles leaving within 17.28 degrees of the normal, as a detector
            that views part of a surface sees. Needs ``surfaces``.
        mesh (optional): A mesh to bin on. A ``RegularRectangularMesh`` or
            ``RegularCylindricalMesh`` bins on its grid. A ``MeshGeometry``
            (its own tets) or an ``UnstructuredMesh`` (a tally-only mesh)
            gives a bin per cell, in the order of ``tetrahedra`` or
            ``cells``; with a region name, ``(geometry, "breeder")``, only
            that volume's cells score.
        energy_bins (list[float], optional): Energy bin boundaries in eV
        energy_group_structure (str, optional): Named group structure (e.g. "VITAMIN-J-175")
        energy_function (tuple, optional): ``(energy, y[, units[, interpolation]])``
            for energy-dependent weighting. The optional fourth item names the
            interpolation, as ``as_energy_function()`` returns it.
        interpolation (str, optional): How ``energy_function`` interpolates
            between its points: ``"cubic"`` (natural cubic spline in linear
            energy, the default, needs 4 points), ``"linear"``, or
            ``"log-log"`` (linear in log energy and log value, the convention
            for tabulated coefficients and how contact dose reads them; an
            interval with a zero value falls back to linear). Only valid with
            ``energy_function``.
        dose_coefficients (tuple, optional): (particle, geometry[, data_source]) for dose.
            The coefficients are interpolated log-log, as contact dose reads
            the same tables. The tally scores only the particle the
            coefficients are for, so ``particle`` need not be passed as well.
            The particle is ``"neutron"``, ``"photon"`` or
            ``"neutron_photon"``. The last is the total dose of a coupled
            run: neutrons and photons are each weighted by their own
            coefficients and scored into the same bin, so the standard
            deviation is that of the total. Two tallies added afterwards
            cannot give it, because the photons of a history are correlated
            with the neutrons that produced them. It takes no ``particle``
            and runs on the CPU only.
        particle (str, optional): "neutron" or "photon". With
            ``dose_coefficients`` it defaults to their particle, and naming
            the other one raises ``ValueError``.
        parent_nuclides (list[str], optional): Nuclides for D1S parent binning
        covariance (bool): Also accumulate the covariance of the bin means,
            history by history, read back as :attr:`covariance`. Off by
            default. A per-bin ``standard_deviation`` treats the bins as
            independent, which they are not: bins scored by the same
            histories move together, so anything summed over them, a
            reaction rate over a spectrum, inherits an understated error
            from the standard deviations alone. Meant for spectra: it is
            limited to 2048 bins, and CPU only.

    Notes:
        ``cells`` and ``materials`` are mutually exclusive -- a single tally
        binning over both cells and materials is not supported (use separate
        tallies).

        When multiple cells or materials are provided, the ``mean``/``std_dev``
        arrays grow to hold one bin per cell/material, in the order given.
        Flat bin layout (slowest → fastest varying) is:
        ``score → cell → material → nuclide → parent_nuclide → energy → mesh``.
    """

scores property

scores: list[Any]

List of scores to tally.

Scores can be specified as: - Integers representing ENDF MT numbers (e.g., 1 for total cross section) - String "flux" for neutron flux - String "heating" for heating/energy deposition

Returns:

Type Description
list[Any]

List of scores (integers or strings)

nuclides property

nuclides: list[str]

List of nuclides for per-nuclide tally breakdown.

When set, each score is broken down by the individual contribution of each listed nuclide. The special string "total" gives the material-total (macroscopic cross section summed over all nuclides).

Compatible with the tally.nuclides property.

Returns:

Type Description
list[str]

list[str]: Nuclide names (e.g., ['Li6', 'Li7', 'total']). Empty list means material-total only (the default).

Examples:

>>> tally.nuclides = ['Li6', 'Li7', 'Be9']
>>> tally.nuclides = ['U235', 'total']

estimator property

estimator: str

Tally estimator: "track-length" (default) or "collision".

"track-length" scores at every cell crossing, weighted by the segment length in each crossed bin. "collision" scores at every collision site as weight / Σ_t. Both converge to the same physical flux for a given history budget, with different variance characteristics -- collision is lower variance in optically-thick regions and touches fewer bins per history, which helps cache pressure on large mesh tallies.

Returns:

Name Type Description
str str

"track-length" or "collision".

response property

response: Optional[Any]

The virtual response target, or None for a normal macroscopic tally.

Mirrors the response= constructor argument, so one of:

  • dict[str, float] (nuclide -> atoms/barn-cm) for a material response (the tally scores that material's macroscopic response).
  • list[str] of nuclide names for a unit-density nuclide overlay.
  • None for a normal (density-multiplied) macroscopic tally.

name property writable

name: Optional[str]

Optional name for the tally.

Returns:

Type Description
Optional[str]

String name or None

id property writable

id: Optional[int]

Optional numeric identifier for the tally.

Returns:

Type Description
Optional[int]

Integer ID or None

units property

units: list[str]

Units of each score's results per source particle.

Derived from the score type and filters: - Flux: "cm/source-particle" (a track length; mesh tallies are per element, not per cm3, until TallyResult.to divides by volume) - Heating: "eV/source-particle" - Reactions: "reactions/source-particle" - With an energy_function= argument: its units times the score's, e.g. "pSv·cm²·cm/source-particle"

Returns:

Type Description
list[str]

list[str]: Units string for each score

mesh property

mesh: Optional[RegularRectangularMesh]

The RegularRectangularMesh used for spatial binning, or None (also None when the tally uses a cylindrical mesh -- see :attr:cylindrical_mesh).

cylindrical_mesh property

cylindrical_mesh: Optional[RegularCylindricalMesh]

The RegularCylindricalMesh used for spatial binning, or None.

particle property

particle: Optional[str]

The particle the tally scores: "neutron" or "photon" from its particle filter, "neutron_photon" for a total dose tally, or None for every particle.

parent_nuclides property

parent_nuclides: Optional[list[str]]

Parent nuclide names for D1S binning, or None.

energy_bins property

energy_bins: Optional[list[float]]

Energy bin boundaries in eV, or None.

energy_function property

energy_function: Optional[tuple[list[float], list[float], Optional[str], str]]

Energy function filter data as an (energy, y, units, interpolation) tuple, or None. Passing it back as energy_function= rebuilds the same filter. For a "neutron_photon" dose tally this is the neutron curve alone.

cells property writable

cells: Optional[list[int]]

Cell IDs of the cell filter, or None if no cell filter is set.

surfaces property

surfaces: Optional[list[int]]

Surface ids of the surface filter, or None for a tally that is not a surface tally.

cosine_bins property

cosine_bins: Optional[list[float]]

Cosine bin edges of a surface tally, or None if it has none.

materials property writable

materials: Optional[list[int]]

Material IDs of the material filter, or None if no material filter is set.

n_energy_bins property

n_energy_bins: int

Number of energy bins (1 if no energy filter).

n_parent_bins property

n_parent_bins: int

Number of parent nuclide bins (1 if no parent nuclide filter).

n_mesh_bins property

n_mesh_bins: int

Number of mesh bins (0 if no mesh filter).

has_unstructured_mesh property

has_unstructured_mesh: bool

Whether this tally uses an unstructured mesh.

unstructured_mesh_vertices property

unstructured_mesh_vertices: Optional[list[list[float]]]

Unstructured mesh vertices (for vtkhdf export). None if no unstructured mesh.

unstructured_mesh_connectivity property

unstructured_mesh_connectivity: Optional[list[list[int]]]

Unstructured mesh connectivity (for vtkhdf export). None if no unstructured mesh.

mean property

mean: list[float]

Per-bin mean value, flat over [score][cell][material][nuclide][parent][energy][mesh] (mesh fastest; dimensions without a filter have a single bin).

Returns:

Type Description
list[float]

list[float]: Mean per bin. All zeros before a simulation has run.

standard_deviation property

standard_deviation: list[float]

Per-bin standard error of the mean, flat in the same bin order as :attr:mean.

Returns:

Type Description
list[float]

list[float]: Standard error of the mean per bin. All zeros before a simulation has run.

covariance property

covariance: Optional[list[list[float]]]

Covariance of the bin means, a num_bins x num_bins nested list in the same bin order as :attr:mean, or None unless the tally was built with covariance=True and a simulation has run.

Its diagonal is standard_deviation squared. For an energy-binned flux tally it is what Pulse(flux_covariance=...) takes, so a transmutation gets the spectrum's error with its correlations.

relative_error property

relative_error: list[float]

Per-bin relative error (standard_deviation / mean, 0 where the mean is not positive), flat in the same bin order as :attr:mean.

Returns:

Type Description
list[float]

list[float]: Relative error per bin.

mesh_element_volumes

mesh_element_volumes() -> Optional[list[float]]

Volumes of every mesh cell in cm³, in one call, for any mesh filter (rectangular, cylindrical, or unstructured). None if the tally has no mesh filter.

Source code in yamc/_core/__init__.pyi
5921
5922
5923
5924
5925
5926
def mesh_element_volumes(self) -> typing.Optional[builtins.list[builtins.float]]:
    r"""
    Volumes of every mesh cell in cm³, in one call, for any mesh filter
    (rectangular, cylindrical, or unstructured). ``None`` if the tally has
    no mesh filter.
    """

mesh_element_volume

mesh_element_volume(bin: int) -> Optional[float]

Volume of mesh cell bin in cm³, for any mesh filter (rectangular, cylindrical, or unstructured). None if the tally has no mesh.

For a rectangular mesh every cell shares the same volume; for a cylindrical mesh outer radial rings are larger; for an unstructured mesh each tetrahedron has its own volume.

Source code in yamc/_core/__init__.pyi
5927
5928
5929
5930
5931
5932
5933
5934
5935
def mesh_element_volume(self, bin: builtins.int) -> typing.Optional[builtins.float]:
    r"""
    Volume of mesh cell ``bin`` in cm³, for any mesh filter (rectangular,
    cylindrical, or unstructured). ``None`` if the tally has no mesh.

    For a rectangular mesh every cell shares the same volume; for a
    cylindrical mesh outer radial rings are larger; for an unstructured
    mesh each tetrahedron has its own volume.
    """

extract_mesh_slice

extract_mesh_slice(basis: str = 'xy', slice_coord: Optional[float] = None, score_index: int = 0, energy_index: Optional[int] = None, value: str = 'mean') -> MeshSliceData

Extract a 2D slice of mesh tally data for plotting.

Returns a 2D list of tally values for the slice plane. The shape is [n_vertical][n_horizontal] matching the mesh dimensions for the chosen basis.

Parameters:

Name Type Description Default
basis str

Slice plane - "xy", "xz", or "yz"

'xy'
slice_coord Optional[float]

Float position along the fixed axis (default: mesh center)

None
score_index int

Which score to extract, 0-indexed (default: 0)

0
energy_index Optional[int]

Which energy bin (default: sum over all)

None
value str

Which statistic - "mean", "standard_deviation", or "relative_error" (default: "mean")

'mean'

Returns:

Name Type Description
A MeshSliceData

class:MeshSliceData with values, h_edges, v_edges,

MeshSliceData

extent, h_label, v_label.

MeshSliceData

Also behaves like a 2D list for backward compatibility

MeshSliceData

(np.array(tally.extract_mesh_slice(...)) still works).

Raises:

Type Description
ValueError

If the tally has no mesh or parameters are invalid

Source code in yamc/_core/__init__.pyi
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
def extract_mesh_slice(self, basis: builtins.str = 'xy', slice_coord: typing.Optional[builtins.float] = None, score_index: builtins.int = 0, energy_index: typing.Optional[builtins.int] = None, value: builtins.str = 'mean') -> MeshSliceData:
    r"""
    Extract a 2D slice of mesh tally data for plotting.

    Returns a 2D list of tally values for the slice plane. The shape
    is ``[n_vertical][n_horizontal]`` matching the mesh dimensions for
    the chosen basis.

    Args:
        basis: Slice plane - "xy", "xz", or "yz"
        slice_coord: Float position along the fixed axis (default: mesh center)
        score_index: Which score to extract, 0-indexed (default: 0)
        energy_index: Which energy bin (default: sum over all)
        value: Which statistic - "mean", "standard_deviation", or "relative_error" (default: "mean")

    Returns:
        A :class:`MeshSliceData` with ``values``, ``h_edges``, ``v_edges``,
        ``extent``, ``h_label``, ``v_label``.
        Also behaves like a 2D list for backward compatibility
        (``np.array(tally.extract_mesh_slice(...))`` still works).

    Raises:
        ValueError: If the tally has no mesh or parameters are invalid
    """

to_vtkhdf

to_vtkhdf(filename: str, **kwargs: Any) -> None

Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
5962
5963
def to_vtkhdf(self, filename: builtins.str, **kwargs: typing.Any) -> None:
    r"""Write to a VTK-HDF file for ParaView. Requires h5py (pip install yamc[viz])."""

interactive_plot

interactive_plot(*args: Any, **kwargs: Any) -> InteractiveTallyPlot

Render an interactive mesh-tally plot. See the docs for keyword arguments.

Source code in yamc/_core/__init__.pyi
5964
5965
def interactive_plot(self, *args: typing.Any, **kwargs: typing.Any) -> InteractiveTallyPlot:
    r"""Render an interactive mesh-tally plot. See the docs for keyword arguments."""

Tracks

All particle tracks recorded by a simulation, one per transported particle (source and secondaries alike), ordered by history then particle ID. Access them via .tracks, the total step count via total_events(), to_dataframe_records() to flatten every event into dict rows for a pandas DataFrame, and to_vtkhdf() to view them in ParaView. len(tracks) is the number of particle tracks.

tracks property

tracks: list[ParticleTrack]

Get all particle tracks

total_events

total_events() -> int

Total number of events across all tracks

Source code in yamc/_core/__init__.pyi
6360
6361
6362
6363
def total_events(self) -> builtins.int:
    r"""
    Total number of events across all tracks
    """

to_dataframe_records

to_dataframe_records() -> list

Convert all events to a flat list of dicts for DataFrame creation

Examples:

df = pd.DataFrame(tracks.to_dataframe_records()) photons = df[df.particle_type == "photon"]

Source code in yamc/_core/__init__.pyi
6366
6367
6368
6369
6370
6371
6372
6373
def to_dataframe_records(self) -> list:
    r"""
    Convert all events to a flat list of dicts for DataFrame creation

    Examples:
        df = pd.DataFrame(tracks.to_dataframe_records())
        photons = df[df.particle_type == "photon"]
    """

polylines

polylines() -> dict

Flatten the tracks into polylines, one per particle track.

Returns a dict of flat lists: points ([x, y, z] per event, cm) and offsets (start of each line in points plus the total, so line j is points[offsets[j]:offsets[j + 1]]); per point energy (eV, after the event), weight, event_type and cell_id (-1 if unknown); per line particle_type, particle_id, parent_id (-1 for source particles), generation and history. event_type and particle_type are integer codes indexing event_type_names and particle_type_names.

Source code in yamc/_core/__init__.pyi
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
def polylines(self) -> dict:
    r"""
    Flatten the tracks into polylines, one per particle track.

    Returns a dict of flat lists: ``points`` (``[x, y, z]`` per event, cm)
    and ``offsets`` (start of each line in ``points`` plus the total, so
    line ``j`` is ``points[offsets[j]:offsets[j + 1]]``); per point
    ``energy`` (eV, after the event), ``weight``, ``event_type`` and
    ``cell_id`` (-1 if unknown); per line ``particle_type``,
    ``particle_id``, ``parent_id`` (-1 for source particles),
    ``generation`` and ``history``. ``event_type`` and ``particle_type``
    are integer codes indexing ``event_type_names`` and
    ``particle_type_names``.
    """

to_vtkhdf

to_vtkhdf(filename: str) -> None

Write one polyline per particle track to a VTK-HDF PolyData file for ParaView. Requires h5py (pip install yamc[viz]).

Source code in yamc/_core/__init__.pyi
6388
6389
def to_vtkhdf(self, filename: builtins.str) -> None:
    r"""Write one polyline per particle track to a VTK-HDF PolyData file for ParaView. Requires h5py (pip install yamc[viz])."""

Cone

Cone(axis: Any, x0: float = 0.0, y0: float = 0.0, z0: float = 0.0, opening_angle: float = 45.0, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a cone surface (double-sheeted / both nappes). The apex is at (x0, y0, z0) (default: origin); unlike a cylinder, all three apex coordinates are meaningful for every axis.

Parameters:

Name Type Description Default
axis Any

Cone axis - 'x'/'y'/'z' or a direction vector.

required
opening_angle float

Half-opening angle in DEGREES (default: 45.0).

45.0
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the (double) cone.

Source code in yamc/_core/__init__.pyi
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
def Cone(axis: typing.Any, x0: builtins.float = 0.0, y0: builtins.float = 0.0, z0: builtins.float = 0.0, opening_angle: builtins.float = 45.0, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a cone surface (double-sheeted / both nappes). The apex is at
    ``(x0, y0, z0)`` (default: origin); unlike a cylinder, all three apex
    coordinates are meaningful for every axis.

    Args:
        axis: Cone axis - 'x'/'y'/'z' or a direction vector.
        opening_angle: Half-opening angle in DEGREES (default: 45.0).
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the (double) cone.
    """

Cylinder

Cylinder(axis: Any, x0: Optional[float] = None, y0: Optional[float] = None, z0: Optional[float] = None, radius: float = 1.0, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a cylinder surface.

The cylinder passes through the point (x0, y0, z0) (default: origin). When the axis is parallel to a coordinate axis, the coordinate along that axis is meaningless (the cylinder is infinite along it) and supplying it raises ValueError; for an oblique axis all three are meaningful.

Parameters:

Name Type Description Default
axis Any

Cylinder axis - 'x'/'y'/'z' or a direction vector. The axis is an undirected line: its sign and magnitude don't matter.

required
radius float

Cylinder radius (default: 1.0)

1.0
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the cylinder

Source code in yamc/_core/__init__.pyi
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
def Cylinder(axis: typing.Any, x0: typing.Optional[builtins.float] = None, y0: typing.Optional[builtins.float] = None, z0: typing.Optional[builtins.float] = None, radius: builtins.float = 1.0, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a cylinder surface.

    The cylinder passes through the point ``(x0, y0, z0)`` (default: origin).
    When the axis is parallel to a coordinate axis, the coordinate along that
    axis is meaningless (the cylinder is infinite along it) and supplying it
    raises ValueError; for an oblique axis all three are meaningful.

    Args:
        axis: Cylinder axis - 'x'/'y'/'z' or a direction vector. The axis is an
            undirected line: its sign and magnitude don't matter.
        radius: Cylinder radius (default: 1.0)
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the cylinder
    """

FluxSurface

FluxSurface(shape: StellaratorShape | TokamakShape, rho: float = 1.0, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a flux surface of a stellarator or tokamak plasma shape.

The surface rho = const of the same shape that drives the plasma source, a StellaratorShape for yamc.sources.stellarator_source or a TokamakShape for yamc.sources.tokamak_source, so a plasma cell and its source share one shape. .below is the plasma inside the surface, .above the rest of space, as for any other surface.

Parameters:

Name Type Description Default
shape StellaratorShape | TokamakShape

The plasma shape, a yamc.sources.StellaratorShape or yamc.sources.TokamakShape

required
rho float

The shape's flux label in (0, 1]; 1 (the default) is the plasma boundary

1.0
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the flux surface

Source code in yamc/_core/__init__.pyi
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
def FluxSurface(shape: sources.StellaratorShape | sources.TokamakShape, rho: builtins.float = 1.0, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a flux surface of a stellarator or tokamak plasma shape.

    The surface ``rho = const`` of the same shape that drives the plasma
    source, a ``StellaratorShape`` for ``yamc.sources.stellarator_source`` or a
    ``TokamakShape`` for ``yamc.sources.tokamak_source``, so a plasma cell and
    its source share one shape. ``.below`` is the plasma inside the surface,
    ``.above`` the rest of space, as for any other surface.

    Args:
        shape: The plasma shape, a ``yamc.sources.StellaratorShape`` or
            ``yamc.sources.TokamakShape``
        rho: The shape's flux label in (0, 1]; 1 (the default) is the plasma
            boundary
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the flux surface
    """

ImplicitSurface

ImplicitSurface(formula: str, *, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a surface from a formula: the points where formula is zero.

.below is where the formula is negative and .above where it is positive, and they combine with &, | and ~ like the half-spaces of any other surface. Coordinates are in cm. evaluate returns the formula's value, which is a distance only if the formula is written as one (sqrt(x^2 + y^2 + z^2) - 5 is, x^2 + y^2 + z^2 - 25 is not); transport reads only its sign.

A formula is made of:

  • numbers (2, 0.5, 1e-3), x, y, z and pi;
  • +, -, *, /, unary - and ^ with a constant exponent. An integer power is a product (x^3 is x^2 * x and x^-2 is 1 / x^2); any other power needs a base that cannot be negative, as in abs(x)^2.5;
  • sqrt, abs, exp, log, sin and cos, and min and max of two or more arguments;
  • smin(a, b, k) and smax(a, b, k): the minimum and maximum blended over a distance k > 0 (a polynomial blend), which round the edge where two shapes meet.

There are no comparisons or jumps (floor, mod, atan2): a jump in sign would be a crossing with no surface there. A formula is refused with a ValueError that says where it goes wrong if it does not parse, if it can be undefined (the square root or logarithm of a negative number, 0 / 0) or divide by zero where it is used, if it is shown never to change sign there, or if it is shown to be zero throughout some part of that region (as max(x, 0) * y is wherever x < 0), whose points would be on neither side of the surface. These checks use interval arithmetic, which loses track of a square written out: write (x - 1)^2 + 1 rather than x^2 - 2 * x + 2, or the formula can be refused as one not shown to be defined. It is kept in a canonical form (Surface.formula) that reads back to the same surface, and its functions give the same results on every platform.

A box holding everything below the surface is proved from the formula where possible (bounding_box_inside). A formula with none, such as a periodic lattice, a plane or a twist, must be bounded by the other surfaces of each cell that uses it, within 1048576 cm (2^20 cm) of the origin, where formulas are checked. Implicit surfaces run on the CPU only (not with compute='gpu'), cannot be offset with OffsetSurface (a layer of even thickness needs a distance), and the browser views show yamc's own image of them.

Parameters:

Name Type Description Default
formula str

The formula, in x, y and z (cm)

required
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the implicit surface

Examples:

>>> import yamc
>>> # A sphere of radius 5 cm, as its signed distance.
>>> ball = yamc.ImplicitSurface("sqrt(x^2 + y^2 + z^2) - 5")
>>> # A gyroid lattice of period 2 cm in a 10 cm box of planes.
>>> gyroid = yamc.ImplicitSurface(
...     "sin(pi * x) * cos(pi * y) + sin(pi * y) * cos(pi * z)"
...     " + sin(pi * z) * cos(pi * x) - 0.3"
... )
>>> box = yamc.Plane("x", -5.0).above & yamc.Plane("x", 5.0).below
>>> box = box & yamc.Plane("y", -5.0).above & yamc.Plane("y", 5.0).below
>>> box = box & yamc.Plane("z", -5.0).above & yamc.Plane("z", 5.0).below
>>> struts = yamc.Cell(region=box & gyroid.below)
>>> pores = yamc.Cell(region=box & gyroid.above)
>>> # A port through a blanket shell, cut by a superellipsoid: a box
>>> # 120 by 60 by 100 cm with rounded edges, across the shell.
>>> port = yamc.ImplicitSurface(
...     "((x - 225) / 60)^4 + (y / 30)^4 + (z / 50)^4 - 1"
... )
>>> shell = yamc.Sphere(radius=200.0).above & yamc.Sphere(radius=250.0).below
>>> blanket = yamc.Cell(region=shell & port.above)
>>> opening = yamc.Cell(region=shell & port.below)
>>> # Two spheres 8 cm apart, blended with a 2 cm fillet where they meet.
>>> pair = yamc.ImplicitSurface(
...     "smin(sqrt((x - 4)^2 + y^2 + z^2) - 5, sqrt((x + 4)^2 + y^2 + z^2) - 5, 2)"
... )
Source code in yamc/_core/__init__.pyi
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
def ImplicitSurface(formula: builtins.str, *, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a surface from a formula: the points where ``formula`` is zero.

    ``.below`` is where the formula is negative and ``.above`` where it is
    positive, and they combine with ``&``, ``|`` and ``~`` like the
    half-spaces of any other surface. Coordinates are in cm. ``evaluate``
    returns the formula's value, which is a distance only if the formula is
    written as one (``sqrt(x^2 + y^2 + z^2) - 5`` is, ``x^2 + y^2 + z^2 - 25``
    is not); transport reads only its sign.

    A formula is made of:

    - numbers (``2``, ``0.5``, ``1e-3``), ``x``, ``y``, ``z`` and ``pi``;
    - ``+``, ``-``, ``*``, ``/``, unary ``-`` and ``^`` with a constant
      exponent. An integer power is a product (``x^3`` is ``x^2 * x`` and
      ``x^-2`` is ``1 / x^2``); any other power needs a base that cannot be
      negative, as in ``abs(x)^2.5``;
    - ``sqrt``, ``abs``, ``exp``, ``log``, ``sin`` and ``cos``, and ``min``
      and ``max`` of two or more arguments;
    - ``smin(a, b, k)`` and ``smax(a, b, k)``: the minimum and maximum
      blended over a distance ``k > 0`` (a polynomial blend), which round
      the edge where two shapes meet.

    There are no comparisons or jumps (``floor``, ``mod``, ``atan2``): a
    jump in sign would be a crossing with no surface there. A formula is
    refused with a ValueError that says where it goes wrong if it does not
    parse, if it can be undefined (the square root or logarithm of a
    negative number, ``0 / 0``) or divide by zero where it is used, if it is
    shown never to change sign there, or if it is shown to be zero
    throughout some part of that region (as ``max(x, 0) * y`` is wherever
    ``x < 0``), whose points would be on neither side of the surface. These
    checks use interval arithmetic, which loses track of a square written
    out: write ``(x - 1)^2 + 1`` rather than ``x^2 - 2 * x + 2``, or the
    formula can be refused as one not shown to be defined. It is kept in a
    canonical form (``Surface.formula``) that reads back to the same
    surface, and its functions give the same results on every platform.

    A box holding everything below the surface is proved from the formula
    where possible (``bounding_box_inside``). A formula with none, such as a
    periodic lattice, a plane or a twist, must be bounded by the other
    surfaces of each cell that uses it, within 1048576 cm (2^20 cm) of the
    origin, where formulas are checked. Implicit surfaces run on the CPU
    only (not with ``compute='gpu'``), cannot be offset with
    ``OffsetSurface`` (a layer of even thickness needs a distance), and the
    browser views show yamc's own image of them.

    Args:
        formula: The formula, in x, y and z (cm)
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the implicit surface

    Examples:
        >>> import yamc
        >>> # A sphere of radius 5 cm, as its signed distance.
        >>> ball = yamc.ImplicitSurface("sqrt(x^2 + y^2 + z^2) - 5")
        >>> # A gyroid lattice of period 2 cm in a 10 cm box of planes.
        >>> gyroid = yamc.ImplicitSurface(
        ...     "sin(pi * x) * cos(pi * y) + sin(pi * y) * cos(pi * z)"
        ...     " + sin(pi * z) * cos(pi * x) - 0.3"
        ... )
        >>> box = yamc.Plane("x", -5.0).above & yamc.Plane("x", 5.0).below
        >>> box = box & yamc.Plane("y", -5.0).above & yamc.Plane("y", 5.0).below
        >>> box = box & yamc.Plane("z", -5.0).above & yamc.Plane("z", 5.0).below
        >>> struts = yamc.Cell(region=box & gyroid.below)
        >>> pores = yamc.Cell(region=box & gyroid.above)
        >>> # A port through a blanket shell, cut by a superellipsoid: a box
        >>> # 120 by 60 by 100 cm with rounded edges, across the shell.
        >>> port = yamc.ImplicitSurface(
        ...     "((x - 225) / 60)^4 + (y / 30)^4 + (z / 50)^4 - 1"
        ... )
        >>> shell = yamc.Sphere(radius=200.0).above & yamc.Sphere(radius=250.0).below
        >>> blanket = yamc.Cell(region=shell & port.above)
        >>> opening = yamc.Cell(region=shell & port.below)
        >>> # Two spheres 8 cm apart, blended with a 2 cm fillet where they meet.
        >>> pair = yamc.ImplicitSurface(
        ...     "smin(sqrt((x - 4)^2 + y^2 + z^2) - 5, sqrt((x + 4)^2 + y^2 + z^2) - 5, 2)"
        ... )
    """

OffsetSurface

OffsetSurface(base: Surface, distance: float, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create the surface at a fixed distance outside (or inside) a flux surface.

The points at signed 3-D distance distance (cm) from the flux surface that base is built on, positive outwards: a first-wall or blanket layer of uniform thickness. Distances are measured from that flux surface, so an offset of an offset adds: OffsetSurface(OffsetSurface(plasma, 15), 2) is OffsetSurface(plasma, 17). Layers built from one flux surface are nested and never cross. .below is the side towards the plasma.

Layers farther out than the flux surface's crease-free distance (the smaller of its tightest concave radius of curvature and half its narrowest gap outside, such as across the central hole) keep their exact distance from it, but have creases (sharp edges) where offset fronts from different parts of the flux surface meet, as a true distance offset does; building one gives a UserWarning saying so.

Parameters:

Name Type Description Default
base Surface

A FluxSurface or OffsetSurface

required
distance float

Signed distance in cm, positive outwards

required
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the offset surface

Source code in yamc/_core/__init__.pyi
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
def OffsetSurface(base: Surface, distance: builtins.float, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create the surface at a fixed distance outside (or inside) a flux surface.

    The points at signed 3-D distance ``distance`` (cm) from the flux surface
    that ``base`` is built on, positive outwards: a first-wall or blanket
    layer of uniform thickness. Distances are measured from that flux surface,
    so an offset of an offset adds: ``OffsetSurface(OffsetSurface(plasma, 15),
    2)`` is ``OffsetSurface(plasma, 17)``. Layers built from one flux surface
    are nested and never cross. ``.below`` is the side towards the plasma.

    Layers farther out than the flux surface's crease-free distance (the
    smaller of its tightest concave radius of curvature and half its narrowest
    gap outside, such as across the central hole) keep their exact distance
    from it, but have creases (sharp edges) where offset fronts from different
    parts of the flux surface meet, as a true distance offset does; building
    one gives a ``UserWarning`` saying so.

    Args:
        base: A FluxSurface or OffsetSurface
        distance: Signed distance in cm, positive outwards
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the offset surface
    """

Plane

Plane(axis: Any, offset: float = 0.0, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a plane surface perpendicular to a direction.

The plane is the set of points where n·(x, y, z) = offset, with n the (normalized) axis.

Parameters:

Name Type Description Default
axis Any

Plane normal - 'x'/'y'/'z' or a direction vector (a, b, c).

required
offset float

Signed position of the plane along axis (default: 0.0). With axis='x', offset=5 is the plane x = 5; with axis=(1, 1, 0), offset=3 (after normalization) is the plane x + y = 3·√2.

0.0
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the plane

Source code in yamc/_core/__init__.pyi
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
def Plane(axis: typing.Any, offset: builtins.float = 0.0, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a plane surface perpendicular to a direction.

    The plane is the set of points where `n·(x, y, z) = offset`, with `n` the
    (normalized) `axis`.

    Args:
        axis: Plane normal - 'x'/'y'/'z' or a direction vector (a, b, c).
        offset: Signed position of the plane along `axis` (default: 0.0).
            With axis='x', offset=5 is the plane x = 5; with axis=(1, 1, 0),
            offset=3 (after normalization) is the plane x + y = 3·√2.
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the plane
    """

Quadric

Quadric(a: float = 0.0, b: float = 0.0, c: float = 0.0, d: float = 0.0, e: float = 0.0, f: float = 0.0, g: float = 0.0, h: float = 0.0, j: float = 0.0, k: float = 0.0, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a general quadric surface (Quadric): a x^2 + b y^2 + c z^2 + d xy + e yz + f xz + g x + h y + j z + k = 0. The coefficients a through k (i is skipped) are the terms of that equation.

Parameters:

Name Type Description Default
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the quadric

Source code in yamc/_core/__init__.pyi
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
def Quadric(a: builtins.float = 0.0, b: builtins.float = 0.0, c: builtins.float = 0.0, d: builtins.float = 0.0, e: builtins.float = 0.0, f: builtins.float = 0.0, g: builtins.float = 0.0, h: builtins.float = 0.0, j: builtins.float = 0.0, k: builtins.float = 0.0, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a general quadric surface (``Quadric``):
    ``a x^2 + b y^2 + c z^2 + d xy + e yz + f xz + g x + h y + j z + k = 0``.
    The coefficients ``a`` through ``k`` (``i`` is skipped) are the terms of
    that equation.

    Args:
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the quadric
    """

Sphere

Sphere(x0: float = 0.0, y0: float = 0.0, z0: float = 0.0, radius: float = 1.0, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a sphere surface.

Parameters:

Name Type Description Default
x0 float

X-coordinate of the sphere center (default: 0.0)

0.0
y0 float

Y-coordinate of the sphere center (default: 0.0)

0.0
z0 float

Z-coordinate of the sphere center (default: 0.0)

0.0
radius float

Radius of the sphere (default: 1.0)

1.0
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None

Returns:

Type Description
Surface

A Surface object representing the sphere

Source code in yamc/_core/__init__.pyi
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
def Sphere(x0: builtins.float = 0.0, y0: builtins.float = 0.0, z0: builtins.float = 0.0, radius: builtins.float = 1.0, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a sphere surface.

    Args:
        x0: X-coordinate of the sphere center (default: 0.0)
        y0: Y-coordinate of the sphere center (default: 0.0)
        z0: Z-coordinate of the sphere center (default: 0.0)
        radius: Radius of the sphere (default: 1.0)
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'

    Returns:
        A Surface object representing the sphere
    """

Torus

Torus(axis: Any, x0: float = 0.0, y0: float = 0.0, z0: float = 0.0, r_major: float = 1.0, r_minor: float = 0.5, r_minor_2: Optional[float] = None, surface_id: Optional[int] = None, boundary: Optional[str] = None, name: Optional[str] = None) -> Surface

Create a torus surface.

The torus is centered at (x0, y0, z0) (default: origin); all three coordinates are meaningful for every axis.

Parameters:

Name Type Description Default
axis Any

Symmetry axis - 'x', 'y', or 'z'. Arbitrary direction vectors are NOT yet supported (a torus is degree-4 and the engine only has axis-locked variants); an oblique vector raises ValueError.

required
r_major float

Major radius (default: 1.0)

1.0
r_minor float

Minor radius along the symmetry axis (default: 0.5)

0.5
r_minor_2 Optional[float]

Minor radius in the transverse plane. Defaults to r_minor (a circular cross-section); set it different from r_minor for an elliptical cross-section.

None
surface_id Optional[int]

Optional surface ID

None
boundary Optional[str]

Boundary condition - None (default, transmission) or 'vacuum'

None
name Optional[str]

Optional surface name

None

Returns:

Type Description
Surface

A Surface object representing the torus

Source code in yamc/_core/__init__.pyi
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
def Torus(axis: typing.Any, x0: builtins.float = 0.0, y0: builtins.float = 0.0, z0: builtins.float = 0.0, r_major: builtins.float = 1.0, r_minor: builtins.float = 0.5, r_minor_2: typing.Optional[builtins.float] = None, surface_id: typing.Optional[builtins.int] = None, boundary: typing.Optional[builtins.str] = None, name: typing.Optional[builtins.str] = None) -> Surface:
    r"""
    Create a torus surface.

    The torus is centered at ``(x0, y0, z0)`` (default: origin); all three
    coordinates are meaningful for every axis.

    Args:
        axis: Symmetry axis - 'x', 'y', or 'z'. Arbitrary direction vectors are
            NOT yet supported (a torus is degree-4 and the engine only has
            axis-locked variants); an oblique vector raises
            ValueError.
        r_major: Major radius (default: 1.0)
        r_minor: Minor radius along the symmetry axis (default: 0.5)
        r_minor_2: Minor radius in the transverse plane. Defaults to `r_minor`
            (a circular cross-section); set it different from `r_minor` for an
            elliptical cross-section.
        surface_id: Optional surface ID
        boundary: Boundary condition - None (default, transmission) or 'vacuum'
        name: Optional surface name

    Returns:
        A Surface object representing the torus
    """

assemble_face_meshes

assemble_face_meshes(faces: Sequence[tuple[int, Sequence[Sequence[float]], Sequence[Sequence[int]]]], rel_tol: float = 1e-06, min_cross_sq: float = 1e-24, seam_rel_tol: float = 1e-09) -> tuple[list[list[float]], list[list[int]], list[int], list[int], list[tuple[int, int]]]

Combine per-face triangulations into one welded surface mesh (the compiled core of the CAD pipeline's mesh assembly).

Faces are taken in the order given. A face's degenerate triangles (two equal corners, or |(b - a) x (c - a)|^2 below min_cross_sq) are dropped, and a face left with none gets no surface id; the others get 1-based surface ids in order. Their vertices are concatenated and welded. Vertices at one position become one. The copies that faces hold of a point on their common edge, the vertices on the open boundary of each face's triangles, are merged within rel_tol times the mesh extent of each other, but two vertices of one face only within seam_rel_tol times it, as the copies of a point on its seam or at a pole are. So a solid thinner than rel_tol keeps its sides apart, and one thinner than seam_rel_tol collapses. Triangles the weld collapses are dropped.

Parameters:

Name Type Description Default
faces Sequence[tuple[int, Sequence[Sequence[float]], Sequence[Sequence[int]]]]

(face_id, vertices, triangles) per face, the triangles as 0-based indices into that face's vertices.

required
rel_tol float

Weld tolerance between faces, as a fraction of the mesh extent.

1e-06
min_cross_sq float

Squared cross-product magnitude below which a triangle is degenerate.

1e-24
seam_rel_tol float

Weld tolerance within one face, as a fraction of the mesh extent.

1e-09

Returns:

Type Description
list[list[float]]

``(vertices, triangles, triangle_face_ids, triangle_surface_ids,

list[list[int]]

face_surface_ids), the last as[(face_id, surface_id), ...]``.

Raises:

Type Description
ValueError

If a triangle indexes past its face's vertices or uses a vertex that is not finite, rel_tol is not positive, or seam_rel_tol is negative.

Source code in yamc/_core/__init__.pyi
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
def assemble_face_meshes(faces: typing.Sequence[tuple[builtins.int, typing.Sequence[typing.Sequence[builtins.float]], typing.Sequence[typing.Sequence[builtins.int]]]], rel_tol: builtins.float = 1e-06, min_cross_sq: builtins.float = 1e-24, seam_rel_tol: builtins.float = 1e-09) -> tuple[builtins.list[builtins.list[builtins.float]], builtins.list[builtins.list[builtins.int]], builtins.list[builtins.int], builtins.list[builtins.int], builtins.list[tuple[builtins.int, builtins.int]]]:
    r"""
    Combine per-face triangulations into one welded surface mesh (the compiled
    core of the CAD pipeline's mesh assembly).

    Faces are taken in the order given. A face's degenerate triangles (two
    equal corners, or ``|(b - a) x (c - a)|^2`` below ``min_cross_sq``) are
    dropped, and a face left with none gets no surface id; the others get
    1-based surface ids in order. Their vertices are concatenated and welded.
    Vertices at one position become one. The copies that faces hold of a
    point on their common edge, the vertices on the open boundary of each
    face's triangles, are merged within ``rel_tol`` times the mesh extent of
    each other, but two vertices of one face only within ``seam_rel_tol``
    times it, as the copies of a point on its seam or at a pole are. So a
    solid thinner than ``rel_tol`` keeps its sides apart, and one thinner than
    ``seam_rel_tol`` collapses. Triangles the weld collapses are dropped.

    Args:
        faces: ``(face_id, vertices, triangles)`` per face, the triangles as
            0-based indices into that face's vertices.
        rel_tol: Weld tolerance between faces, as a fraction of the mesh
            extent.
        min_cross_sq: Squared cross-product magnitude below which a triangle is
            degenerate.
        seam_rel_tol: Weld tolerance within one face, as a fraction of the
            mesh extent.

    Returns:
        ``(vertices, triangles, triangle_face_ids, triangle_surface_ids,
        face_surface_ids)``, the last as ``[(face_id, surface_id), ...]``.

    Raises:
        ValueError: If a triangle indexes past its face's vertices or uses a
            vertex that is not finite, ``rel_tol`` is not positive, or
            ``seam_rel_tol`` is negative.
    """

cache_dir

cache_dir() -> str

The directory downloaded nuclear data is cached in.

A folder in the platform's per-user cache directory (under ~/.cache on Linux, or $XDG_CACHE_HOME when that is set; ~/Library/Caches on macOS; %LOCALAPPDATA% on Windows), shared by both wheels. Inside it each library keeps one folder per published release, <keyword>/<release>/, holding that release's manifest.json and the files downloaded from it, each verified against the manifest. Read only: to use data from somewhere else, point the data source at a local directory instead.

Returns:

Type Description
str

The cache directory as a string, whether or not it exists yet.

Raises:

Type Description
RuntimeError

If the platform resolves no home directory.

Source code in yamc/_core/__init__.pyi
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
def cache_dir() -> builtins.str:
    r"""
    The directory downloaded nuclear data is cached in.

    A folder in the platform's per-user cache directory (under ``~/.cache`` on
    Linux, or ``$XDG_CACHE_HOME`` when that is set; ``~/Library/Caches`` on
    macOS; ``%LOCALAPPDATA%`` on Windows), shared by both wheels. Inside it
    each library keeps one folder per published release,
    ``<keyword>/<release>/``, holding that release's ``manifest.json`` and the
    files downloaded from it, each verified against the manifest. Read only:
    to use data from somewhere else, point the data source at a local
    directory instead.

    Returns:
        The cache directory as a string, whether or not it exists yet.

    Raises:
        RuntimeError: If the platform resolves no home directory.
    """

cad_mesh_labels

cad_mesh_labels(triangle_face_ids: Sequence[int], solid_faces: Sequence[tuple[int, Sequence[int]]], tet_blocks: Sequence[tuple[int, int, Sequence[Sequence[int]]]] = []) -> tuple[list[int], list[int], list[list[int]], list[int]]

Per-cell volume and material labels for the CAD VTKHDF export.

Returns (tri_volume_ids, tri_material_ids, tets, tet_volume_ids): the owning solid id (1-based, -1 when unowned) and material tag index (0-based, -1 when unowned) per triangle, plus the per-solid tet blocks flattened into the global vertex array with the owning solid id per tet.

Parameters:

Name Type Description Default
triangle_face_ids Sequence[int]

BRep face id per triangle.

required
solid_faces Sequence[tuple[int, Sequence[int]]]

(solid_id, face_ids) pairs in ascending solid order.

required
tet_blocks Sequence[tuple[int, int, Sequence[Sequence[int]]]]

(solid_id, vertex_offset, tets) per tetrahedralized solid.

[]
Source code in yamc/_core/__init__.pyi
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
def cad_mesh_labels(triangle_face_ids: typing.Sequence[builtins.int], solid_faces: typing.Sequence[tuple[builtins.int, typing.Sequence[builtins.int]]], tet_blocks: typing.Sequence[tuple[builtins.int, builtins.int, typing.Sequence[typing.Sequence[builtins.int]]]] = []) -> tuple[builtins.list[builtins.int], builtins.list[builtins.int], builtins.list[builtins.list[builtins.int]], builtins.list[builtins.int]]:
    r"""
    Per-cell volume and material labels for the CAD VTKHDF export.

    Returns ``(tri_volume_ids, tri_material_ids, tets, tet_volume_ids)``: the
    owning solid id (1-based, -1 when unowned) and material tag index (0-based,
    -1 when unowned) per triangle, plus the per-solid tet blocks flattened into
    the global vertex array with the owning solid id per tet.

    Args:
        triangle_face_ids: BRep face id per triangle.
        solid_faces: ``(solid_id, face_ids)`` pairs in ascending solid order.
        tet_blocks: ``(solid_id, vertex_offset, tets)`` per tetrahedralized solid.
    """

cad_mesh_to_arrow

cad_mesh_to_arrow(path: Optional[str], vertices: Sequence[Sequence[float]], triangles: Sequence[Sequence[int]], triangle_surface_ids: Sequence[int], triangle_face_ids: Sequence[int], solid_faces: Sequence[tuple[int, Sequence[int]]], material_tags: Sequence[str], face_to_surface_id: Sequence[tuple[int, int]], face_solid_reversed: Mapping[tuple[int, int], bool], tet_blocks: Sequence[tuple[int, int, Sequence[Sequence[int]]]] = [], boundary_tags: Sequence[tuple[str, Sequence[int]]] = [], imprinted: bool = True, contact_tolerance: Optional[float] = None, overlaps: Sequence[tuple[int, int]] = [], volume_measures: Optional[Sequence[float]] = None, separated: Sequence[tuple[int, int]] = []) -> Optional[bytes]

Finalize the CAD pipeline's mesh and write it to an Arrow IPC file, or return the file's bytes when path is None.

Runs the whole export in the compiled core: assigns each triangle and tet the physical group of its first owning solid, offsets the per-solid tet blocks into the global vertex array, builds the physical-group and surface-to-volume topology metadata, and writes the file. The Python exporter does no per-element work.

Parameters:

Name Type Description Default
path Optional[str]

Output file path, or None to return the bytes.

required
vertices Sequence[Sequence[float]]

Global [x, y, z] vertex array (tet vertex blocks appended).

required
triangles Sequence[Sequence[int]]

Per-triangle global vertex indices.

required
triangle_surface_ids Sequence[int]

1-based surface id per triangle.

required
triangle_face_ids Sequence[int]

BRep face id per triangle.

required
solid_faces Sequence[tuple[int, Sequence[int]]]

(solid_id, face_ids) pairs in ascending solid order.

required
material_tags Sequence[str]

Material tag per solid; solid i + 1 carries tag i.

required
face_to_surface_id Sequence[tuple[int, int]]

(face_id, surface_id) pairs (surface ids 1-based).

required
face_solid_reversed Mapping[tuple[int, int], bool]

(solid_id, face_id) -> reversed orientation map.

required
tet_blocks Sequence[tuple[int, int, Sequence[Sequence[int]]]]

(solid_id, vertex_offset, tets) per tetrahedralized solid.

[]
boundary_tags Sequence[tuple[str, Sequence[int]]]

(boundary_name, surface_ids) pairs written as dim=2 boundary:<name> physical groups (surface ids 1-based).

[]
imprinted bool

Whether the assembly was imprinted before meshing. False makes :class:MeshGeometry track the mesh discontinuously.

True
contact_tolerance Optional[float]

For a mesh that was not imprinted, the distance (cm) within which two solids' surfaces count as touching.

None
overlaps Sequence[tuple[int, int]]

For a mesh that was not imprinted, (low, high) solid pairs (1-based solid ids) that overlap; where they do, the cell is high.

[]
volume_measures Optional[Sequence[float]]

Optional volume (cm³) per solid, in solid order, written instead of the volumes the reader would compute from the surfaces (for solids that give up an overlap).

None
separated Sequence[tuple[int, int]]

For a mesh that was not imprinted, (a, b) solid pairs (1-based solid ids) within the contact tolerance in the mesh that do not touch in the CAD, so the gap between them is kept.

[]
Source code in yamc/_core/__init__.pyi
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
def cad_mesh_to_arrow(path: typing.Optional[builtins.str], vertices: typing.Sequence[typing.Sequence[builtins.float]], triangles: typing.Sequence[typing.Sequence[builtins.int]], triangle_surface_ids: typing.Sequence[builtins.int], triangle_face_ids: typing.Sequence[builtins.int], solid_faces: typing.Sequence[tuple[builtins.int, typing.Sequence[builtins.int]]], material_tags: typing.Sequence[builtins.str], face_to_surface_id: typing.Sequence[tuple[builtins.int, builtins.int]], face_solid_reversed: typing.Mapping[tuple[builtins.int, builtins.int], builtins.bool], tet_blocks: typing.Sequence[tuple[builtins.int, builtins.int, typing.Sequence[typing.Sequence[builtins.int]]]] = [], boundary_tags: typing.Sequence[tuple[builtins.str, typing.Sequence[builtins.int]]] = [], imprinted: builtins.bool = True, contact_tolerance: typing.Optional[builtins.float] = None, overlaps: typing.Sequence[tuple[builtins.int, builtins.int]] = [], volume_measures: typing.Optional[typing.Sequence[builtins.float]] = None, separated: typing.Sequence[tuple[builtins.int, builtins.int]] = []) -> typing.Optional[bytes]:
    r"""
    Finalize the CAD pipeline's mesh and write it to an Arrow IPC file, or
    return the file's bytes when ``path`` is ``None``.

    Runs the whole export in the compiled core: assigns each
    triangle and tet the physical group of its first owning solid, offsets the
    per-solid tet blocks into the global vertex array, builds the physical-group
    and surface-to-volume topology metadata, and writes the file. The Python
    exporter does no per-element work.

    Args:
        path: Output file path, or ``None`` to return the bytes.
        vertices: Global ``[x, y, z]`` vertex array (tet vertex blocks appended).
        triangles: Per-triangle global vertex indices.
        triangle_surface_ids: 1-based surface id per triangle.
        triangle_face_ids: BRep face id per triangle.
        solid_faces: ``(solid_id, face_ids)`` pairs in ascending solid order.
        material_tags: Material tag per solid; solid ``i + 1`` carries tag ``i``.
        face_to_surface_id: ``(face_id, surface_id)`` pairs (surface ids 1-based).
        face_solid_reversed: ``(solid_id, face_id) -> reversed`` orientation map.
        tet_blocks: ``(solid_id, vertex_offset, tets)`` per tetrahedralized solid.
        boundary_tags: ``(boundary_name, surface_ids)`` pairs written as
            ``dim=2`` ``boundary:<name>`` physical groups (surface ids 1-based).
        imprinted: Whether the assembly was imprinted before meshing. ``False``
            makes :class:`MeshGeometry` track the mesh discontinuously.
        contact_tolerance: For a mesh that was not imprinted, the distance
            (cm) within which two solids' surfaces count as touching.
        overlaps: For a mesh that was not imprinted, ``(low, high)`` solid
            pairs (1-based solid ids) that overlap; where they do, the cell is
            ``high``.
        volume_measures: Optional volume (cm³) per solid, in solid order,
            written instead of the volumes the reader would compute from the
            surfaces (for solids that give up an overlap).
        separated: For a mesh that was not imprinted, ``(a, b)`` solid pairs
            (1-based solid ids) within the contact tolerance in the mesh that
            do not touch in the CAD, so the gap between them is kept.
    """

combine_results

combine_results(*results: Any) -> TransportResults

Combine results of independent runs of the same model into one pooled result, statistically identical to a single longer run.

The merge pools the raw per-bin Welford state (mean, m2, n) of every tally, so means, standard deviations and figures of merit come out exactly as if all histories had been run in one simulation (FOM uses the summed wall-clock time).

Validation (raises ValueError, never silently combines):

  • every input must carry run provenance (results from simulate_transport or from_arrow);
  • all runs must have distinct seeds -- same-seed runs share their per-particle RNG streams and are not independent;
  • all runs must come from the same model (geometry, materials, source, physics settings and nuclear-data libraries -- library mismatches are reported per nuclide);
  • tallies with the same name must have identical configurations. A material filter's bins are matched by the geometry material each id names, not by the id, so runs of a model built anew (whose materials get new ids) still combine, and filters naming different materials under the same ids do not;
  • GPU-produced results are refused (no Welford merge state), as are non-root MPI results (every rank holds the same statistics, so a non-root result would count the run twice).

Tallies present in only some inputs are carried through unchanged with a UserWarning (their statistics come from the runs that scored them; their FOM uses those runs' time only).

Captured particle tracks are not merged: the combined result has tracks=None. Keep the individual results if you need their tracks.

Examples:

>>> r1 = model.simulate_transport(seed=1)
>>> r2 = model.simulate_transport(seed=2)
>>> combined = yamc.combine_results(r1, r2)
Source code in yamc/_core/__init__.pyi
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
def combine_results(*results: typing.Any) -> TransportResults:
    r"""
    Combine results of independent runs of the same model into one pooled
    result, statistically identical to a single longer run.

    The merge pools the raw per-bin Welford state ``(mean, m2, n)`` of
    every tally, so means, standard deviations and figures of merit come
    out exactly as if all histories had been run in one simulation (FOM
    uses the summed wall-clock time).

    Validation (raises ``ValueError``, never silently combines):

    - every input must carry run provenance (results from
      ``simulate_transport`` or ``from_arrow``);
    - all runs must have **distinct seeds** -- same-seed runs share their
      per-particle RNG streams and are not independent;
    - all runs must come from the **same model** (geometry, materials,
      source, physics settings and nuclear-data libraries -- library
      mismatches are reported per nuclide);
    - tallies with the same name must have identical configurations. A
      material filter's bins are matched by the geometry material each id
      names, not by the id, so runs of a model built anew (whose materials
      get new ids) still combine, and filters naming different materials
      under the same ids do not;
    - GPU-produced results are refused (no Welford merge state), as are
      non-root MPI results (every rank holds the same statistics, so a
      non-root result would count the run twice).

    Tallies present in only some inputs are carried through unchanged
    with a ``UserWarning`` (their statistics come from the runs that
    scored them; their FOM uses those runs' time only).

    Captured particle tracks are not merged: the combined result has
    ``tracks=None``. Keep the individual results if you need their
    tracks.

    Examples:
        >>> r1 = model.simulate_transport(seed=1)
        >>> r2 = model.simulate_transport(seed=2)
        >>> combined = yamc.combine_results(r1, r2)
    """

conform_tet_meshes

conform_tet_meshes(vertices: Sequence[Sequence[float]], surface: Sequence[Sequence[int]], solids: Sequence[tuple[Sequence[int], Sequence[Sequence[int]]]]) -> tuple[list[list[int]], list[int], list[tuple[list[int], list[list[int]]]], tuple[int, int, int, int, int, bool]]

Make per-solid tet meshes conformal with each other and with their surface.

vertices is the shared vertex array, surface the surface triangles bounding the tet-meshed solids (over vertices), and solids one (surface triangle indices, tets) pair per solid. Returns the refined surface triangles, the index in surface each came from, the solids with their refined surface lists and repaired tets, and (edges_split, cones, surface_triangles_refined, conflicts, skipped_solids, reverted).

Source code in yamc/_core/__init__.pyi
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
def conform_tet_meshes(vertices: typing.Sequence[typing.Sequence[builtins.float]], surface: typing.Sequence[typing.Sequence[builtins.int]], solids: typing.Sequence[tuple[typing.Sequence[builtins.int], typing.Sequence[typing.Sequence[builtins.int]]]]) -> tuple[builtins.list[builtins.list[builtins.int]], builtins.list[builtins.int], builtins.list[tuple[builtins.list[builtins.int], builtins.list[builtins.list[builtins.int]]]], tuple[builtins.int, builtins.int, builtins.int, builtins.int, builtins.int, builtins.bool]]:
    r"""
    Make per-solid tet meshes conformal with each other and with their surface.

    ``vertices`` is the shared vertex array, ``surface`` the surface triangles
    bounding the tet-meshed solids (over ``vertices``), and ``solids`` one
    ``(surface triangle indices, tets)`` pair per solid. Returns the refined
    surface triangles, the index in ``surface`` each came from, the solids with
    their refined surface lists and repaired tets, and
    ``(edges_split, cones, surface_triangles_refined, conflicts, skipped_solids,
    reverted)``.
    """

convert_branching

convert_branching(neutron_files: Sequence[str], decay_files: Sequence[str], output_path: str, library: str = '', decay_library: str = '', data_version: str = '', created_utc: Optional[str] = None, tol_ev: float = 3000.0, linearize_tol: float = 0.001) -> dict

Extract isomeric branching from neutron evaluations and write the branching/ subsection.

Separate from :func:convert_transmutation because the branching curves and the decay data routinely come from different libraries: TENDL branching beside ENDF/B decay is the usual combination. Both calls merge into the same manifest.json.

Parameters

neutron_files : list[str] Neutron evaluations of the parent nuclides. MF=8/9/10 radionuclide production is what carries the branching. A file may hold many materials, such as IRDFF-II's tape of 70, and every one is read. decay_files : list[str] Decay evaluations, read only to build the isomer table, so the metastable ones suffice. A tape is read whole, as for the neutron files. output_path : str The transmutation directory to write branching/ into. library, data_version, created_utc As for :func:convert_transmutation. The library here is the branching source, which need not match the chain's. tol_ev : float, optional Energy tolerance when matching a nuclear level to an isomeric state. linearize_tol : float, optional Relative tolerance for resampling a non-lin-lin region onto the lin-lin pairs the format stores.

Returns

dict Coverage: parents read, parents with data, curves linearized, duplicate groups merged, the metastable targets found, level_routes (how many excited production levels were matched to an isomer by energy, by energy within a tenth, by level index, as the only isomer, or not at all) and flagged_levels (one line per level that was unresolved, taken as ground because the decay data has no isomer for its product, matched only by the looser energy pass, matched by energy while its level index pointed at another isomer, or taken as its product's only isomer while further from it than either energy pass accepts; every excited level that ends up at ground is listed), partial_sum_mismatches (one line per reaction whose MF=10 partial cross sections do not sum to its MF=3 total, or whose MF=9 yields do not sum to one, within two percent below 20 MeV), and skipped_states (one line per production state that names no single product nuclide, and so gives no row: fission, an IZAP of zero that no single MF=8 subsection resolves, or any other ZAP whose Z or A is not positive), list_facts (one line per production list, a parent's MT in MF=9 or MF=10: whether the ground state is listed, whether the file has an MF=3 section for the MT, each state's LFS, LMF, target, route and level energy difference, and the MF=1 normalisation lines naming the MT) and list_counts (how many lists are complete or isomers only in each file, have no MF=3 section for their MT, or are normalised). The same facts are stored per row in branching.arrow; they change no rate. The MF=40 production covariance, written as the tape gives it to branching/branching_covariance.arrow, is counted by mf40_sections (sections read, whatever the MT), mf40_blocks (blocks written), mf40_blocks_by_lb (the NI blocks by layout), mf40_nc_blocks, mf40_unmatched_states (one line per product state that matches no MF=9 or MF=10 state, matches several within the tolerance, or is excited with no stated excitation to confirm a level by, written with no target), mf40_states_without_chain_kind (states of an MT with no chain reaction, such as MT 18, written with no reaction), mf40_on_yield_channels (states matched to a level whose production MF=9 gives as a yield rather than an MF=10 cross section; where that yield is merged with another state's, the row carries the state's own yield with quantity "yield"), mf40_mat1_naming_itself (sub-subsections whose MAT1 is the evaluation's own MAT, written as given), mf40_cross_state_blocks (blocks other than a state's covariance with itself; key them on MT, LFS, MT1 and XLFS1, since both states can resolve to one target), mf40_blocks_outside_mf10 (blocks whose partner is in another material or has XMF1 other than 10), mf40_without_blocks (one line per section, state or sub-subsection holding no block, with its tape values, the only part of MF=40 the file cannot show), mf40_partner_unresolved (one line per sub-subsection written with no partner target because the tape does not pin the partner to one state, among them a partner whose level XLFS1 MF=10 numbers differently from MF=40), and mf40_states_placed_by_excitation (one line per product state whose target was matched by excitation because MF=9 and MF=10 give its IZAP and LFS no state or one at another excitation; its self blocks name it by MF=40's own LFS). The four line lists are also written to branching/provenance.json. An evaluation set without MF=40 writes no covariance file, and removes one an earlier conversion left there.

Source code in yamc/_core/__init__.pyi
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
def convert_branching(neutron_files: typing.Sequence[builtins.str], decay_files: typing.Sequence[builtins.str], output_path: builtins.str, library: builtins.str = '', decay_library: builtins.str = '', data_version: builtins.str = '', created_utc: typing.Optional[builtins.str] = None, tol_ev: builtins.float = 3000.0, linearize_tol: builtins.float = 0.001) -> dict:
    r"""
    Extract isomeric branching from neutron evaluations and write the
    ``branching/`` subsection.

    Separate from :func:`convert_transmutation` because the branching curves and
    the decay data routinely come from different libraries: TENDL branching
    beside ENDF/B decay is the usual combination. Both calls merge into the same
    ``manifest.json``.

    Parameters
    ----------
    neutron_files : list[str]
        Neutron evaluations of the parent nuclides. MF=8/9/10 radionuclide
        production is what carries the branching. A file may hold many
        materials, such as IRDFF-II's tape of 70, and every one is read.
    decay_files : list[str]
        Decay evaluations, read only to build the isomer table, so the
        metastable ones suffice. A tape is read whole, as for the neutron files.
    output_path : str
        The transmutation directory to write ``branching/`` into.
    library, data_version, created_utc
        As for :func:`convert_transmutation`. The library here is the branching
        source, which need not match the chain's.
    tol_ev : float, optional
        Energy tolerance when matching a nuclear level to an isomeric state.
    linearize_tol : float, optional
        Relative tolerance for resampling a non-lin-lin region onto the lin-lin
        pairs the format stores.

    Returns
    -------
    dict
        Coverage: parents read, parents with data, curves linearized, duplicate
        groups merged, the metastable targets found, ``level_routes`` (how many
        excited production levels were matched to an isomer by energy, by
        energy within a tenth, by level index, as the only isomer, or not at
        all) and ``flagged_levels`` (one line per level that was unresolved,
        taken as ground because the decay data has no isomer for its product,
        matched only by the looser energy pass, matched by energy while its
        level index pointed at another isomer, or taken as its product's only
        isomer while further from it than either energy pass accepts; every
        excited level that ends up at ground is listed), ``partial_sum_mismatches``
        (one line per reaction whose MF=10 partial cross sections do not sum to
        its MF=3 total, or whose MF=9 yields do not sum to one, within two
        percent below 20 MeV), and ``skipped_states`` (one line per production
        state that names no single product nuclide, and so gives no row:
        fission, an IZAP of zero that no single MF=8 subsection resolves, or
        any other ZAP whose Z or A is not positive), ``list_facts`` (one line
        per production list, a parent's MT in MF=9 or MF=10: whether the ground
        state is listed, whether the file has an MF=3 section for the MT, each
        state's LFS, LMF, target, route and level energy difference, and the
        MF=1 normalisation lines naming the MT) and ``list_counts`` (how many
        lists are complete or isomers only in each file, have no MF=3 section
        for their MT, or are normalised). The same facts are stored per row in
        ``branching.arrow``; they change no rate.
        The MF=40 production
        covariance, written as the tape gives it to
        ``branching/branching_covariance.arrow``, is counted by
        ``mf40_sections`` (sections read, whatever the MT), ``mf40_blocks``
        (blocks written), ``mf40_blocks_by_lb`` (the NI blocks by layout),
        ``mf40_nc_blocks``, ``mf40_unmatched_states`` (one line per product
        state that matches no MF=9 or MF=10 state, matches several within the
        tolerance, or is excited with no stated excitation to confirm a level
        by, written with no target), ``mf40_states_without_chain_kind``
        (states of an MT with no chain reaction, such as MT 18, written with
        no reaction),
        ``mf40_on_yield_channels`` (states matched to a level whose production
        MF=9 gives as a yield rather than an MF=10 cross section; where that
        yield is merged with another state's, the row carries the state's own
        yield with quantity ``"yield"``),
        ``mf40_mat1_naming_itself`` (sub-subsections whose MAT1 is the
        evaluation's own MAT, written as given), ``mf40_cross_state_blocks``
        (blocks other than a state's covariance with itself; key them on MT,
        LFS, MT1 and XLFS1, since both states can resolve to one target),
        ``mf40_blocks_outside_mf10`` (blocks whose partner is in another
        material or has XMF1 other than 10), ``mf40_without_blocks`` (one line
        per section, state or sub-subsection holding no block, with its tape
        values, the only part of MF=40 the file cannot show),
        ``mf40_partner_unresolved`` (one line per sub-subsection written
        with no partner target because the tape does not pin the partner to
        one state, among them a partner whose level XLFS1 MF=10 numbers
        differently from MF=40), and ``mf40_states_placed_by_excitation`` (one
        line per product state whose target was matched by excitation because
        MF=9 and MF=10 give its IZAP and LFS no state or one at another
        excitation; its self blocks name it by MF=40's own LFS). The four line
        lists are also written to ``branching/provenance.json``. An evaluation
        set without MF=40 writes no covariance file, and removes one an
        earlier conversion left there.
    """

convert_neutron_transport

convert_neutron_transport(input_path: str, output_dir: str, njoy_exec: str = 'njoy', temperatures: Optional[Sequence[float]] = None, library: str = '', data_version: str = '', created_utc: Optional[str] = None, covariance: bool = False) -> str

Convert an ENDF evaluation into the full neutron transport data set.

Everything :func:convert_neutron_xs writes, plus the reaction products, their secondary angle and energy distributions, the lookup accelerator the transport hot path reads, and the two fissile-only sections.

ENDF only, deliberately. An ACE table holds one temperature, carries no MT 901 heating and no fission energy release, so a transport conversion from one would be missing the local KERMA and the fission photon scaling with nothing on disk to say so.

Parameters

input_path : str Path to the ENDF evaluation. output_dir : str Directory to write {Nuclide}.arrow/ into. NJOY also works in a hidden directory here, so this disk needs room for its tapes; the directory is removed when the conversion ends. njoy_exec : str The NJOY executable. FENDL needs the IAEA-NDS fork; upstream NJOY does not reproduce the official release, and both builds succeed, so the wrong choice is quiet. temperatures : list[float], optional Temperatures in Kelvin. Defaults to NJOY's own default. library, data_version, created_utc Recorded in version.json. covariance : bool Also write covariance.arrow, the MF=33 cross-section covariance, and the evaluation's other covariance sections where it has them: angular_covariance.arrow (MF=34), nubar_covariance.arrow (MF=31), spectrum_covariance.arrow (MF=35) and resonance_parameters.arrow (the MF=2 resonance parameters with their MF=32 covariance). Off by default: the matrices are large and only an uncertainty calculation reads them.

Returns

str Path to the directory written.

Source code in yamc/_core/__init__.pyi
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
def convert_neutron_transport(input_path: builtins.str, output_dir: builtins.str, njoy_exec: builtins.str = 'njoy', temperatures: typing.Optional[typing.Sequence[builtins.float]] = None, library: builtins.str = '', data_version: builtins.str = '', created_utc: typing.Optional[builtins.str] = None, covariance: builtins.bool = False) -> builtins.str:
    r"""
    Convert an ENDF evaluation into the full neutron transport data set.

    Everything :func:`convert_neutron_xs` writes, plus the reaction products,
    their secondary angle and energy distributions, the lookup accelerator the
    transport hot path reads, and the two fissile-only sections.

    ENDF only, deliberately. An ACE table holds one temperature, carries no
    MT 901 heating and no fission energy release, so a transport conversion
    from one would be missing the local KERMA and the fission photon scaling
    with nothing on disk to say so.

    Parameters
    ----------
    input_path : str
        Path to the ENDF evaluation.
    output_dir : str
        Directory to write ``{Nuclide}.arrow/`` into. NJOY also works in a
        hidden directory here, so this disk needs room for its tapes; the
        directory is removed when the conversion ends.
    njoy_exec : str
        The NJOY executable. FENDL needs the IAEA-NDS fork; upstream NJOY does
        not reproduce the official release, and both builds succeed, so the
        wrong choice is quiet.
    temperatures : list[float], optional
        Temperatures in Kelvin. Defaults to NJOY's own default.
    library, data_version, created_utc
        Recorded in ``version.json``.
    covariance : bool
        Also write ``covariance.arrow``, the MF=33 cross-section covariance,
        and the evaluation's other covariance sections where it has them:
        ``angular_covariance.arrow`` (MF=34), ``nubar_covariance.arrow``
        (MF=31), ``spectrum_covariance.arrow`` (MF=35) and
        ``resonance_parameters.arrow`` (the MF=2 resonance parameters with
        their MF=32 covariance). Off by default: the matrices are large and
        only an uncertainty
        calculation reads them.

    Returns
    -------
    str
        Path to the directory written.
    """

convert_neutron_xs

convert_neutron_xs(input_path: str, output_dir: str, source_format: str = 'endf', njoy_exec: str = 'njoy', temperatures: Optional[Sequence[float]] = None, library: str = '', data_version: str = '', created_utc: Optional[str] = None, covariance: bool = False) -> str

Convert an evaluation into the cross-section data an activation calculation reads.

Writes a {nuclide}.arrow/ directory holding nuclide.arrow, energy.arrow, reactions.arrow and version.json, which is exactly what a transport-free reaction-rate collapse reads. The secondary distributions and lookup tables a transport run needs are deliberately not written: an activation calculation never touches them, and building them from an ACE table would cost heating data it does not carry.

Parameters

input_path : str An ENDF evaluation, or an ACE table when source_format="ace". output_dir : str Directory to write {nuclide}.arrow/ into. With source_format="endf", NJOY also works in a hidden directory here, so this disk needs room for its tapes; the directory is removed when the conversion ends. source_format : {"endf", "ace"} "endf" runs NJOY to reconstruct resonances and Doppler broaden, which is the documented route and the only one that can reach an arbitrary temperature. "ace" reads a table you already have and needs no NJOY, at the cost of being stuck with the temperature it was processed at. njoy_exec : str, optional The NJOY executable, for source_format="endf". Note that FENDL is processed with the IAEA-NDS fork and upstream NJOY does not reproduce the official release; both builds succeed, so the wrong choice is quiet. temperatures : list[float], optional Temperatures in Kelvin. Defaults to NJOY's own default. Ignored for source_format="ace". library, data_version, created_utc Recorded in version.json. data_version identifies the published release and is what a consumer compares a cached copy against. covariance : bool Also write covariance.arrow, the MF=33 cross-section covariance, and the evaluation's other covariance sections where it has them: angular_covariance.arrow (MF=34), nubar_covariance.arrow (MF=31), spectrum_covariance.arrow (MF=35) and resonance_parameters.arrow (the MF=2 resonance parameters with their MF=32 covariance). Off by default: the matrices are large and only an uncertainty calculation reads them. Requires source_format="endf" -- MF=33 is not carried through ACER, so asking for it from an ACE table raises.

Returns

str Path to the directory written.

Source code in yamc/_core/__init__.pyi
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
def convert_neutron_xs(input_path: builtins.str, output_dir: builtins.str, source_format: builtins.str = 'endf', njoy_exec: builtins.str = 'njoy', temperatures: typing.Optional[typing.Sequence[builtins.float]] = None, library: builtins.str = '', data_version: builtins.str = '', created_utc: typing.Optional[builtins.str] = None, covariance: builtins.bool = False) -> builtins.str:
    r"""
    Convert an evaluation into the cross-section data an activation
    calculation reads.

    Writes a ``{nuclide}.arrow/`` directory holding ``nuclide.arrow``,
    ``energy.arrow``, ``reactions.arrow`` and ``version.json``, which is exactly
    what a transport-free reaction-rate collapse reads. The secondary distributions and
    lookup tables a transport run needs are deliberately not written: an
    activation calculation never touches them, and building them from an ACE
    table would cost heating data it does not carry.

    Parameters
    ----------
    input_path : str
        An ENDF evaluation, or an ACE table when ``source_format="ace"``.
    output_dir : str
        Directory to write ``{nuclide}.arrow/`` into. With
        ``source_format="endf"``, NJOY also works in a hidden directory here,
        so this disk needs room for its tapes; the directory is removed when
        the conversion ends.
    source_format : {"endf", "ace"}
        ``"endf"`` runs NJOY to reconstruct resonances and Doppler broaden,
        which is the documented route and the only one that can reach an
        arbitrary temperature. ``"ace"`` reads a table you already have and
        needs no NJOY, at the cost of being stuck with the temperature it was
        processed at.
    njoy_exec : str, optional
        The NJOY executable, for ``source_format="endf"``. Note that FENDL is
        processed with the IAEA-NDS fork and upstream NJOY does not reproduce
        the official release; both builds succeed, so the wrong choice is quiet.
    temperatures : list[float], optional
        Temperatures in Kelvin. Defaults to NJOY's own default. Ignored for
        ``source_format="ace"``.
    library, data_version, created_utc
        Recorded in ``version.json``. ``data_version`` identifies the published
        release and is what a consumer compares a cached copy against.
    covariance : bool
        Also write ``covariance.arrow``, the MF=33 cross-section covariance,
        and the evaluation's other covariance sections where it has them:
        ``angular_covariance.arrow`` (MF=34), ``nubar_covariance.arrow``
        (MF=31), ``spectrum_covariance.arrow`` (MF=35) and
        ``resonance_parameters.arrow`` (the MF=2 resonance parameters with
        their MF=32 covariance). Off by default: the matrices are large and
        only an uncertainty
        calculation reads them. Requires ``source_format="endf"`` -- MF=33 is
        not carried through ACER, so asking for it from an ACE table raises.

    Returns
    -------
    str
        Path to the directory written.
    """

convert_photon

convert_photon(photoatomic_path: str | PathLike | Path, output_dir: str | PathLike | Path, relaxation_path: Optional[str | PathLike | Path] = None, compton_profiles: Optional[str | PathLike | Path] = None, density_effect: Optional[str | PathLike | Path] = None, bremsstrahlung: Optional[str | PathLike | Path] = None, library: str = '', data_version: str = '', created_utc: Optional[str] = None) -> list[str]

Convert a photoatomic evaluation into the per-element photon sections.

Writes element.arrow always, and subshells.arrow, compton.arrow and bremsstrahlung.arrow where there is data for them. No NJOY: a photoatomic evaluation is already pointwise.

Parameters

photoatomic_path : str The photoatomic evaluation. One file may hold several elements, and each is written to its own directory. output_dir : str Directory to write {Element}.arrow/ into. relaxation_path : str, optional The atomic relaxation evaluation for the same element, carrying binding energies, occupancies and the transition cascade. Without it the subshells are written with zero binding energy and no transitions, which is a fluorescence-free atom rather than an error. compton_profiles, density_effect, bremsstrahlung : str or path, optional Other copies of the auxiliary tabulations, which no evaluation carries (Compton profiles, the density effect and bremsstrahlung). The default is the copies compiled into this package, the same in yamc and yani. Give all three or none. library, data_version, created_utc Recorded in version.json.

Returns

list[str] One path per element written.

Source code in yamc/_core/__init__.pyi
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
def convert_photon(photoatomic_path: builtins.str | os.PathLike | pathlib.Path, output_dir: builtins.str | os.PathLike | pathlib.Path, relaxation_path: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None, compton_profiles: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None, density_effect: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None, bremsstrahlung: typing.Optional[builtins.str | os.PathLike | pathlib.Path] = None, library: builtins.str = '', data_version: builtins.str = '', created_utc: typing.Optional[builtins.str] = None) -> builtins.list[builtins.str]:
    r"""
    Convert a photoatomic evaluation into the per-element photon sections.

    Writes ``element.arrow`` always, and ``subshells.arrow``, ``compton.arrow``
    and ``bremsstrahlung.arrow`` where there is data for them. No NJOY: a
    photoatomic evaluation is already pointwise.

    Parameters
    ----------
    photoatomic_path : str
        The photoatomic evaluation. One file may hold several elements, and
        each is written to its own directory.
    output_dir : str
        Directory to write ``{Element}.arrow/`` into.
    relaxation_path : str, optional
        The atomic relaxation evaluation for the same element, carrying binding
        energies, occupancies and the transition cascade. Without it the
        subshells are written with zero binding energy and no transitions,
        which is a fluorescence-free atom rather than an error.
    compton_profiles, density_effect, bremsstrahlung : str or path, optional
        Other copies of the auxiliary tabulations, which no evaluation carries
        (Compton profiles, the density effect and bremsstrahlung). The default
        is the copies compiled into this package, the same in yamc and yani.
        Give all three or none.
    library, data_version, created_utc
        Recorded in ``version.json``.

    Returns
    -------
    list[str]
        One path per element written.
    """

convert_photonuclear

convert_photonuclear(input_path: str, output_dir: str, library: str = '', data_version: str = '', created_utc: Optional[str] = None) -> str

Preserve a photonuclear ENDF evaluation as lossless Arrow tables. Writes native-grid MF=3 cross sections with their ENDF interpolation and every original section, including outgoing-particle data. Requires NSUB=0. No neutron Doppler broadening or photoatomic relaxation is applied. This processes evaluated data; it does not enable photonuclear transport. library, data_version and created_utc are recorded in version.json.

Source code in yamc/_core/__init__.pyi
9177
9178
9179
9180
9181
9182
9183
9184
9185
def convert_photonuclear(input_path: builtins.str, output_dir: builtins.str, library: builtins.str = '', data_version: builtins.str = '', created_utc: typing.Optional[builtins.str] = None) -> builtins.str:
    r"""
    Preserve a photonuclear ENDF evaluation as lossless Arrow tables.
    Writes native-grid MF=3 cross sections with their ENDF interpolation and
    every original section, including outgoing-particle data. Requires NSUB=0.
    No neutron Doppler broadening or photoatomic relaxation is applied. This
    processes evaluated data; it does not enable photonuclear transport.
    ``library``, ``data_version`` and ``created_utc`` are recorded in version.json.
    """

convert_transmutation

convert_transmutation(decay_files: Sequence[str], fpy_files: Sequence[str], neutron_files: Sequence[str], output_path: str, library: str = '', decay_library: str = '', data_version: str = '', created_utc: Optional[str] = None, reactions: Optional[Sequence[str]] = None, branch_ratios: Optional[str] = None, subsections: Optional[Sequence[str]] = None, decay_fill_files: Sequence[str] = [], decay_fill_library: str = '') -> int

Convert ENDF decay, fission product yield and neutron evaluations into a transmutation Arrow directory.

Parameters

decay_files, fpy_files, neutron_files : list[str] ENDF inputs. All three are needed to build a network: the decay data says what decays into what, the neutron data what transmutes into what, and the fission yields what fission produces. A file may hold one evaluation or a whole tape of them, such as JEFF-4.0's decay and fission yield tapes; every material in it is read. output_path : str Directory to write. Created if absent, merged into if it already holds other subsections of the same library. library : str Library name recorded in the provenance, e.g. "endf-b8.1". data_version : str Identifier of the published release. This is what a consumer compares a cached copy against, so a rebuild that changes values must change this. It is not the converter version: two rebuilds from one converter are different data. created_utc : str, optional Timestamp recorded in the provenance. Supply one for a reproducible directory; left unset, the current time is used. branch_ratios : str, optional Path to a JSON branching table in openmc_data shape, {reaction: {parent: {target: fraction}}}. Splits a reaction between a ground state and its metastable partners. Without it every (n,gamma) gives its whole rate to the ground state and the metastable product is absent from the network entirely. subsections : list[str], optional Which of decay, reactions and fission_yields to write. Defaults to all three. A caller assembling a chain from more than one library writes each subsection from the library that has it, and the manifest merges rather than being overwritten. reactions : list[str], optional Reaction names to follow. Defaults to every reaction the chain builder knows, not the six-name short set, so nothing is silently left out. decay_fill_files : list[str], optional Decay evaluations from a second library, read only to replace the placeholder average decay energies in decay_files. Some libraries write a stand-in for nuclides nobody has evaluated: a third of each beta or electron-capture branch's Q to the light particles and a third to the photons, which for an electron-capture emitter can be several times the recoverable energy (Sn111 in ENDF/B-VIII.1 is 1.63 MeV per decay against 0.69 MeV from its decay scheme). A placeholder is replaced only where the second library has an evaluated decay scheme for the same nuclide with a half-life within 25% of the first's. Half-lives and decay modes are never touched. The decay subsection's provenance.json lists every placeholder and every replacement, with or without a fill. A tape is read whole, as for decay_files. decay_fill_library : str, optional The library decay_fill_files came from, e.g. "jendl-5.0". Required with decay_fill_files.

Returns

int The number of nuclides in the network written.

Source code in yamc/_core/__init__.pyi
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
def convert_transmutation(decay_files: typing.Sequence[builtins.str], fpy_files: typing.Sequence[builtins.str], neutron_files: typing.Sequence[builtins.str], output_path: builtins.str, library: builtins.str = '', decay_library: builtins.str = '', data_version: builtins.str = '', created_utc: typing.Optional[builtins.str] = None, reactions: typing.Optional[typing.Sequence[builtins.str]] = None, branch_ratios: typing.Optional[builtins.str] = None, subsections: typing.Optional[typing.Sequence[builtins.str]] = None, decay_fill_files: typing.Sequence[builtins.str] = [], decay_fill_library: builtins.str = '') -> builtins.int:
    r"""
    Convert ENDF decay, fission product yield and neutron evaluations into a
    transmutation Arrow directory.

    Parameters
    ----------
    decay_files, fpy_files, neutron_files : list[str]
        ENDF inputs. All three are needed to build a network: the decay data
        says what decays into what, the neutron data what transmutes into what,
        and the fission yields what fission produces. A file may hold one
        evaluation or a whole tape of them, such as JEFF-4.0's decay and
        fission yield tapes; every material in it is read.
    output_path : str
        Directory to write. Created if absent, merged into if it already holds
        other subsections of the same library.
    library : str
        Library name recorded in the provenance, e.g. ``"endf-b8.1"``.
    data_version : str
        Identifier of the published release. This is what a consumer compares a
        cached copy against, so a rebuild that changes values must change this.
        It is not the converter version: two rebuilds from one converter are
        different data.
    created_utc : str, optional
        Timestamp recorded in the provenance. Supply one for a reproducible
        directory; left unset, the current time is used.
    branch_ratios : str, optional
        Path to a JSON branching table in ``openmc_data`` shape,
        ``{reaction: {parent: {target: fraction}}}``. Splits a reaction between
        a ground state and its metastable partners. Without it every
        ``(n,gamma)`` gives its whole rate to the ground state and the
        metastable product is absent from the network entirely.
    subsections : list[str], optional
        Which of ``decay``, ``reactions`` and ``fission_yields`` to write.
        Defaults to all three. A caller assembling a chain from more than one
        library writes each subsection from the library that has it, and the
        manifest merges rather than being overwritten.
    reactions : list[str], optional
        Reaction names to follow. Defaults to every reaction the chain builder
        knows, not the six-name short set, so nothing is silently left out.
    decay_fill_files : list[str], optional
        Decay evaluations from a second library, read only to replace the
        placeholder average decay energies in ``decay_files``. Some libraries
        write a stand-in for nuclides nobody has evaluated: a third of each
        beta or electron-capture branch's Q to the light particles and a third
        to the photons, which for an electron-capture emitter can be several
        times the recoverable energy (Sn111 in ENDF/B-VIII.1 is 1.63 MeV per
        decay against 0.69 MeV from its decay scheme). A placeholder is
        replaced only where the second library has an evaluated decay scheme
        for the same nuclide with a half-life within 25% of the first's.
        Half-lives and decay modes are never touched. The decay subsection's
        ``provenance.json`` lists every placeholder and every replacement,
        with or without a fill. A tape is read whole, as for ``decay_files``.
    decay_fill_library : str, optional
        The library ``decay_fill_files`` came from, e.g. ``"jendl-5.0"``.
        Required with ``decay_fill_files``.

    Returns
    -------
    int
        The number of nuclides in the network written.
    """

cooldown_steps

cooldown_steps(start: Any, stop: Any, n: int, spacing: str = 'log') -> list[Cooldown]

Build a run of cooling steps at log-spaced cumulative times.

Cooldown takes the duration OF THAT STEP, which is the right primitive and the wrong thing to type. Anyone plotting a decay curve wants points at cumulative times, and would otherwise have to difference them by hand:

HOUR, YEAR = 3600.0, 365.25 * 86400.0
cum  = [HOUR * (10 * YEAR / HOUR) ** (k / (n - 1)) for k in range(n)]
gaps = [cum[0]] + [cum[k] - cum[k - 1] for k in range(1, n)]

Log spacing is the default because decay is exponential, so a linear sweep is wrong twice over: it wastes steps in the flat tail and misses the early fall entirely. Activity and decay heat are plotted on log-log axes, so evenly spaced PLOTTED points means log-spaced times.

Source code in yamc/_core/__init__.pyi
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
def cooldown_steps(start: typing.Any, stop: typing.Any, n: builtins.int, spacing: builtins.str = 'log') -> builtins.list[Cooldown]:
    r"""
    Build a run of cooling steps at log-spaced *cumulative* times.

    `Cooldown` takes the duration OF THAT STEP, which is the right primitive and
    the wrong thing to type. Anyone plotting a decay curve wants points at
    cumulative times, and would otherwise have to difference them by hand:

    ```text
    HOUR, YEAR = 3600.0, 365.25 * 86400.0
    cum  = [HOUR * (10 * YEAR / HOUR) ** (k / (n - 1)) for k in range(n)]
    gaps = [cum[0]] + [cum[k] - cum[k - 1] for k in range(1, n)]
    ```

    Log spacing is the default because decay is exponential, so a linear sweep
    is wrong twice over: it wastes steps in the flat tail and misses the early
    fall entirely. Activity and decay heat are plotted on log-log axes, so
    evenly spaced PLOTTED points means log-spaced times.
    """

create_test_reaction_product

create_test_reaction_product() -> ReactionProduct

Test function to create a simple reaction product for testing

Source code in yamc/_core/__init__.pyi
9270
9271
9272
9273
def create_test_reaction_product() -> ReactionProduct:
    r"""
    Test function to create a simple reaction product for testing
    """

enriched

enriched(fraction: float, *, target: str, percent: float, fraction_type: str = 'atom') -> Enriched

Create an enrichment specification for a Material composition entry.

Parameters:

Name Type Description Default
fraction float

Fraction of this component in the material.

required
target str

Target nuclide for enrichment (e.g. "Li6").

required
percent float

Enrichment percentage of the target isotope.

required
fraction_type str

"atom" for atom percent or "mass" for weight percent.

'atom'

Returns:

Name Type Description
Enriched Enriched

An enrichment specification.

Source code in yamc/_core/__init__.pyi
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
def enriched(fraction: builtins.float, *, target: builtins.str, percent: builtins.float, fraction_type: builtins.str = 'atom') -> Enriched:
    r"""
    Create an enrichment specification for a Material composition entry.

    Args:
        fraction (float): Fraction of this component in the material.
        target (str): Target nuclide for enrichment (e.g. "Li6").
        percent (float): Enrichment percentage of the target isotope.
        fraction_type (str): "atom" for atom percent or "mass" for weight percent.

    Returns:
        Enriched: An enrichment specification.
    """

generate_library

generate_library(keyword: str, path: str, *, parts: Optional[Sequence[str]] = None, nuclides: Optional[Sequence[str]] = None, temperatures: Optional[Sequence[float]] = None, njoy_exec: Optional[str] = None, downloads: Optional[str] = None) -> dict

Build a whole nuclear-data library from its evaluated sources into a folder.

Downloads the library's source archives (each checked against the size and sha256 it is pinned to), unpacks them, converts every evaluation, builds the transmutation chain, checks the result and writes manifest.json last. The folder is laid out as a published release, so it serves every setting:

.. code-block:: python

generate_library("endf-b8.1", "/data/endf-b8.1")
neutron_cross_section_data = "/data/endf-b8.1"
transmutation_decay_data = "/data/endf-b8.1"

Running it again resumes: finished folders are kept and only the rest are converted. A folder holds one library built by one build of this package: the same version compiled from the same core commit.

The build is recorded in the release. manifest.json carries provenance.builder ("yani-python <version>"), provenance.builder_commit (the core commit this extension was compiled from, :data:__commit__) and provenance.builder_dirty (:data:__commit_dirty__), both null when it was built outside a git checkout, beside provenance.njoy. Every version.json and provenance.json carries the same as one converter stamp, such as "yani-python 0.22.1 (core 250c439e...)", and the manifest lists each distinct stamp as converters.

An extension compiled from a tree with uncommitted changes (__commit_dirty__ is True) writes data no commit describes, so it builds only a partial library (parts, nuclides or temperatures given), which is never published. Commit the changes and rebuild to build a whole library.

Some hosts serve their archives only to a web browser (the IAEA's FENDL and IRDFF-II files, JAEA's JENDL-5 files). The error then lists each file with its link; download them with a browser and run again. They are found in the Downloads folder, in downloads, or in <path>/.build/downloads/.

Parameters

keyword : str The library: "endf-b8.1", "jeff-4.0", "jendl-5.0", "tendl-2025", "tendl-2017", "fendl-3.2d" or "irdff-ii". path : str The folder to build in, created if absent. It must be new, empty or an earlier build of the same library, and not inside :func:cache_dir. parts : list of str, optional What to build, of "neutron", "photon", "photonuclear", "thermal", "decay", "reactions", "fission_yields" and "branching". The default is every part the library's published release carries. Only "neutron" and "thermal" run NJOY, so a chain alone builds in minutes. "thermal" is the thermal scattering tables (thermal/c_H_in_H2O.arrow/ and so on), which only "endf-b8.1", "jeff-4.0" and "jendl-5.0" publish. nuclides : list of str, optional Only these nuclides ("Fe56", "Am242_m1") and elements ("Fe", meaning every Fe evaluation and the Fe photon data), and thermal tables by name ("c_H_in_H2O") or by what they bind to ("H" is every table binding hydrogen). The transmutation chain is always built whole. A name the library does not have is refused. temperatures : list of float, optional Neutron temperatures in Kelvin. The default is 250, 293.6, 600, 900, 1200 and 2500 K. The 0 K grid is always kept. njoy_exec : str, optional The NJOY executable. The default is the njoy installed beside this Python (pip install njoy2016), then the one on PATH. FENDL needs the IAEA-NDS fork of NJOY, and a refusal says how to build it. downloads : str, optional A folder of source archives fetched by hand, searched first.

Returns

dict keyword, release (the date the build started, the folder's release stamp), path, parts, converted and reused (sorted "<particle>/<Name>" keys), not_converted (the evaluations the library's recipe declares NJOY cannot process, with the reason each failed), stale_declarations (declared ones that converted after all), njoy (the NJOY version used, or None), chain_nuclides, manifest_sha256, file_count and total_bytes.

Raises

ValueError An unknown keyword or part, or bad temperatures. RuntimeError The build cannot start (an extension compiled from uncommitted changes asked for a whole library, the folder or another build in it, the NJOY, the disk space, or source files that need a browser), or did not finish: evaluations that failed and are not declared, a gate that failed, or Ctrl-C. Nothing finished is lost, and running again retries only what is left. Each failed evaluation's reason is in <path>/.build/failed/.

Source code in yamc/_core/__init__.pyi
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
def generate_library(keyword: builtins.str, path: builtins.str, *, parts: typing.Optional[typing.Sequence[builtins.str]] = None, nuclides: typing.Optional[typing.Sequence[builtins.str]] = None, temperatures: typing.Optional[typing.Sequence[builtins.float]] = None, njoy_exec: typing.Optional[builtins.str] = None, downloads: typing.Optional[builtins.str] = None) -> dict:
    r"""
    Build a whole nuclear-data library from its evaluated sources into a folder.

    Downloads the library's source archives (each checked against the size and
    sha256 it is pinned to), unpacks them, converts every evaluation, builds the
    transmutation chain, checks the result and writes ``manifest.json`` last. The
    folder is laid out as a published release, so it serves every setting:

    .. code-block:: python

        generate_library("endf-b8.1", "/data/endf-b8.1")
        neutron_cross_section_data = "/data/endf-b8.1"
        transmutation_decay_data = "/data/endf-b8.1"

    Running it again resumes: finished folders are kept and only the rest are
    converted. A folder holds one library built by one build of this package:
    the same version compiled from the same core commit.

    The build is recorded in the release. ``manifest.json`` carries
    ``provenance.builder`` (``"yani-python <version>"``),
    ``provenance.builder_commit`` (the core commit this extension was compiled
    from, :data:`__commit__`) and ``provenance.builder_dirty``
    (:data:`__commit_dirty__`), both ``null`` when it was built outside a git
    checkout, beside ``provenance.njoy``. Every ``version.json`` and
    ``provenance.json`` carries the same as one ``converter`` stamp, such as
    ``"yani-python 0.22.1 (core 250c439e...)"``, and the manifest lists each
    distinct stamp as ``converters``.

    An extension compiled from a tree with uncommitted changes
    (``__commit_dirty__`` is ``True``) writes data no commit describes, so it
    builds only a partial library (``parts``, ``nuclides`` or ``temperatures``
    given), which is never published. Commit the changes and rebuild to build
    a whole library.

    Some hosts serve their archives only to a web browser (the IAEA's FENDL and
    IRDFF-II files, JAEA's JENDL-5 files). The error then lists each file with
    its link; download them with a browser and run again. They are found in the
    Downloads folder, in ``downloads``, or in ``<path>/.build/downloads/``.

    Parameters
    ----------
    keyword : str
        The library: ``"endf-b8.1"``, ``"jeff-4.0"``, ``"jendl-5.0"``,
        ``"tendl-2025"``, ``"tendl-2017"``, ``"fendl-3.2d"`` or ``"irdff-ii"``.
    path : str
        The folder to build in, created if absent. It must be new, empty or an
        earlier build of the same library, and not inside :func:`cache_dir`.
    parts : list of str, optional
        What to build, of ``"neutron"``, ``"photon"``, ``"photonuclear"``,
        ``"thermal"``, ``"decay"``, ``"reactions"``, ``"fission_yields"`` and
        ``"branching"``. The default is every part the library's published
        release carries. Only ``"neutron"`` and ``"thermal"`` run NJOY, so a
        chain alone builds in minutes. ``"thermal"`` is the thermal scattering
        tables (``thermal/c_H_in_H2O.arrow/`` and so on), which only
        ``"endf-b8.1"``, ``"jeff-4.0"`` and ``"jendl-5.0"`` publish.
    nuclides : list of str, optional
        Only these nuclides (``"Fe56"``, ``"Am242_m1"``) and elements (``"Fe"``,
        meaning every Fe evaluation and the Fe photon data), and thermal tables
        by name (``"c_H_in_H2O"``) or by what they bind to (``"H"`` is every
        table binding hydrogen). The transmutation chain is always built whole.
        A name the library does not have is refused.
    temperatures : list of float, optional
        Neutron temperatures in Kelvin. The default is 250, 293.6, 600, 900, 1200
        and 2500 K. The 0 K grid is always kept.
    njoy_exec : str, optional
        The NJOY executable. The default is the ``njoy`` installed beside this
        Python (``pip install njoy2016``), then the one on PATH. FENDL needs the
        IAEA-NDS fork of NJOY, and a refusal says how to build it.
    downloads : str, optional
        A folder of source archives fetched by hand, searched first.

    Returns
    -------
    dict
        ``keyword``, ``release`` (the date the build started, the folder's
        release stamp), ``path``, ``parts``, ``converted`` and ``reused`` (sorted
        ``"<particle>/<Name>"`` keys), ``not_converted`` (the evaluations the
        library's recipe declares NJOY cannot process, with the reason each
        failed), ``stale_declarations`` (declared ones that converted after all),
        ``njoy`` (the NJOY version used, or ``None``), ``chain_nuclides``,
        ``manifest_sha256``, ``file_count`` and ``total_bytes``.

    Raises
    ------
    ValueError
        An unknown keyword or part, or bad temperatures.
    RuntimeError
        The build cannot start (an extension compiled from uncommitted changes
        asked for a whole library, the folder or another build in it, the NJOY,
        the disk space, or source files that need a browser), or did not
        finish: evaluations that failed and are not declared, a gate that
        failed, or Ctrl-C. Nothing finished is lost, and running again retries
        only what is left. Each failed evaluation's reason is in
        ``<path>/.build/failed/``.
    """

get_neutron_cross_section_data

get_neutron_cross_section_data() -> Any

Get the current cross-section data mapping.

Returns None if nothing has been set, a string if a single global library keyword or directory is in use, or a dict mapping nuclide names to paths.

Source code in yamc/_core/__init__.pyi
9386
9387
9388
9389
9390
9391
9392
9393
def get_neutron_cross_section_data() -> typing.Any:
    r"""
    Get the current cross-section data mapping.

    Returns ``None`` if nothing has been set, a string if a single global
    library keyword or directory is in use, or a dict mapping nuclide names
    to paths.
    """

get_photon_cross_section_data

get_photon_cross_section_data() -> Any

Get the explicitly selected photon library or element-to-source mapping.

Source code in yamc/_core/__init__.pyi
9395
9396
9397
9398
def get_photon_cross_section_data() -> typing.Any:
    r"""
    Get the explicitly selected photon library or element-to-source mapping.
    """

get_transmutation_branch_ratios

get_transmutation_branch_ratios() -> str | list[str] | None

Get the isomeric-branching sources of the transmutation network.

Returns:

Type Description
str | list[str] | None

What was assigned: one source as a string, a list of sources (in the

str | list[str] | None

order a reaction takes its split from them) as a list, or None

str | list[str] | None

when nothing is set and no isomeric-branching overlay is applied.

Source code in yamc/_core/__init__.pyi
9400
9401
9402
9403
9404
9405
9406
9407
9408
def get_transmutation_branch_ratios() -> builtins.str | list[builtins.str] | None:
    r"""
    Get the isomeric-branching sources of the transmutation network.

    Returns:
        What was assigned: one source as a string, a list of sources (in the
        order a reaction takes its split from them) as a list, or ``None``
        when nothing is set and no isomeric-branching overlay is applied.
    """

get_transmutation_decay_data

get_transmutation_decay_data() -> Optional[str]

Get the decay-data source for the transmutation network, or None when it is unset.

Source code in yamc/_core/__init__.pyi
9410
9411
9412
9413
9414
def get_transmutation_decay_data() -> typing.Optional[builtins.str]:
    r"""
    Get the decay-data source for the transmutation network, or ``None`` when
    it is unset.
    """

get_transmutation_fission_yields

get_transmutation_fission_yields() -> Optional[str | Literal[False]]

Get the fission-yields source for the transmutation network, as it was assigned: the source, False when it is turned off, or None when it is unset.

Source code in yamc/_core/__init__.pyi
9416
9417
9418
9419
9420
9421
def get_transmutation_fission_yields() -> typing.Optional[builtins.str | typing.Literal[False]]:
    r"""
    Get the fission-yields source for the transmutation network, as it was
    assigned: the source, ``False`` when it is turned off, or ``None`` when it
    is unset.
    """

get_transmutation_reactions

get_transmutation_reactions() -> Optional[str | Literal[False]]

Get the reaction-topology source for the transmutation network, as it was assigned: the source, False when it is turned off, or None when it is unset.

Source code in yamc/_core/__init__.pyi
9423
9424
9425
9426
9427
9428
def get_transmutation_reactions() -> typing.Optional[builtins.str | typing.Literal[False]]:
    r"""
    Get the reaction-topology source for the transmutation network, as it was
    assigned: the source, ``False`` when it is turned off, or ``None`` when it
    is unset.
    """

group_structure

group_structure(name: str) -> list[float]

Energy boundaries of a built-in group structure, in eV.

Parameters:

Name Type Description Default
name str

Name of the group structure, case-sensitive, one of the names :func:group_structure_names returns (e.g. "UKAEA-1102").

required

Returns:

Type Description
list[float]

list[float]: The bin edges in eV, ascending. One more than the number

list[float]

of groups, so len(edges) - 1 groups.

Raises:

Type Description
ValueError

If the name is not a built-in group structure. The message lists the ones that are.

Examples:

>>> import yamc
>>> edges = yamc.group_structure("UKAEA-1102")
>>> len(edges), edges[0], edges[-1]
(1103, 1e-05, 1000000000.0)
>>> # the energies a 1102-group spectrum belongs to
>>> midpoints = [(lo + hi) / 2 for lo, hi in zip(edges, edges[1:])]
Source code in yamc/_core/__init__.pyi
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
def group_structure(name: builtins.str) -> builtins.list[builtins.float]:
    r"""
    Energy boundaries of a built-in group structure, in eV.

    Args:
        name: Name of the group structure, case-sensitive, one of the names
            :func:`group_structure_names` returns (e.g. ``"UKAEA-1102"``).

    Returns:
        list[float]: The bin edges in eV, ascending. One more than the number
        of groups, so ``len(edges) - 1`` groups.

    Raises:
        ValueError: If the name is not a built-in group structure. The message
                    lists the ones that are.

    Examples:
        >>> import yamc
        >>> edges = yamc.group_structure("UKAEA-1102")
        >>> len(edges), edges[0], edges[-1]
        (1103, 1e-05, 1000000000.0)
        >>> # the energies a 1102-group spectrum belongs to
        >>> midpoints = [(lo + hi) / 2 for lo, hi in zip(edges, edges[1:])]
    """

group_structure_names

group_structure_names() -> list[str]

Names of the built-in group structures.

Neutron structures first by increasing group count, then photon. Every name except "CCFE-24-PHOTON" carries the same boundaries as OpenMC's openmc.mgxs.GROUP_STRUCTURES entry of that name.

Returns:

Type Description
list[str]

list[str]: The names accepted by :func:group_structure, and anywhere

list[str]

else a group structure can be named.

Examples:

>>> import yamc
>>> names = yamc.group_structure_names()
>>> "CCFE-709" in names
True
>>> {n: len(yamc.group_structure(n)) - 1 for n in names[:2]}
{'XMAS-172': 172, 'VITAMIN-J-175': 175}
Source code in yamc/_core/__init__.pyi
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
def group_structure_names() -> builtins.list[builtins.str]:
    r"""
    Names of the built-in group structures.

    Neutron structures first by increasing group count, then photon. Every name
    except ``"CCFE-24-PHOTON"`` carries the same boundaries as OpenMC's
    ``openmc.mgxs.GROUP_STRUCTURES`` entry of that name.

    Returns:
        list[str]: The names accepted by :func:`group_structure`, and anywhere
        else a group structure can be named.

    Examples:
        >>> import yamc
        >>> names = yamc.group_structure_names()
        >>> "CCFE-709" in names
        True
        >>> {n: len(yamc.group_structure(n)) - 1 for n in names[:2]}
        {'XMAS-172': 172, 'VITAMIN-J-175': 175}
    """

mesh_face

mesh_face(face_id: int, boundary_edges: Sequence[Any], holes: Optional[Sequence[Sequence[Any]]] = None, is_planar: bool = True, mesh_mode: str = 'coarse') -> FaceOutput

Mesh a single face in UV space.

Source code in yamc/_core/__init__.pyi
9487
9488
9489
9490
def mesh_face(face_id: builtins.int, boundary_edges: typing.Sequence[typing.Any], holes: typing.Optional[typing.Sequence[typing.Sequence[typing.Any]]] = None, is_planar: builtins.bool = True, mesh_mode: builtins.str = 'coarse') -> FaceOutput:
    r"""
    Mesh a single face in UV space.
    """

mesh_faces

mesh_faces(faces: Sequence[Any], scheduler: str = 'dag') -> list[FaceOutput]

Mesh multiple faces in batch.

Source code in yamc/_core/__init__.pyi
9492
9493
9494
9495
def mesh_faces(faces: typing.Sequence[typing.Any], scheduler: builtins.str = 'dag') -> builtins.list[FaceOutput]:
    r"""
    Mesh multiple faces in batch.
    """

mesh_faces_scene_resolved

mesh_faces_scene_resolved(faces: Sequence[tuple[int, Sequence[tuple[int, bool, Sequence[Sequence[float]]]], Sequence[Sequence[tuple[int, bool, Sequence[Sequence[float]]]]], bool, str]], tolerance: float = 0.01, angular_tolerance: float = 0.3, threads: Optional[int] = None) -> list[SceneFaceOutput]

Mesh faces from pre-resolved UV boundary loops (empty edge table; yamc owns edge discretization in OCP). Returns one output per input face, in order. The faces are meshed in parallel on threads threads, or on rayon's global pool when threads is None (the default).

Source code in yamc/_core/__init__.pyi
9497
9498
9499
9500
9501
9502
9503
def mesh_faces_scene_resolved(faces: typing.Sequence[tuple[builtins.int, typing.Sequence[tuple[builtins.int, builtins.bool, typing.Sequence[typing.Sequence[builtins.float]]]], typing.Sequence[typing.Sequence[tuple[builtins.int, builtins.bool, typing.Sequence[typing.Sequence[builtins.float]]]]], builtins.bool, builtins.str]], tolerance: builtins.float = 0.01, angular_tolerance: builtins.float = 0.3, threads: typing.Optional[builtins.int] = None) -> builtins.list[SceneFaceOutput]:
    r"""
    Mesh faces from pre-resolved UV boundary loops (empty edge table; yamc owns
    edge discretization in OCP). Returns one output per input face, in order.
    The faces are meshed in parallel on ``threads`` threads, or on rayon's
    global pool when ``threads`` is ``None`` (the default).
    """

mesh_to_arrow

mesh_to_arrow(path: str, vertices: Sequence[float], triangles: Sequence[int], triangle_surface_ids: Sequence[int], triangle_physical_groups: Sequence[int], tetrahedra: Sequence[int] = [], tet_volume_ids: Sequence[int] = [], tet_physical_groups: Sequence[int] = [], physical_groups_json: str = '{}', surface_volumes_json: str = '[]', volume_measures_json: str = '', imprinted: Optional[bool] = None, contact_tolerance: Optional[float] = None, overlaps: Sequence[tuple[int, int]] = [], separated: Sequence[tuple[int, int]] = []) -> None

Write mesh data to an Arrow IPC file.

Tet adjacency is computed here from the flat connectivity, so the caller does not supply it. Bounding boxes are not stored; they are computed from the vertices when the file is read.

surface_volumes_json gives, for each surface, the 0-based ids of the volume its triangles' normals point out of and of the one they point into, null for the implicit complement. A surface with the same volume in both is an internal face of that volume: it bounds nothing, and particles pass it as if it were not there.

imprinted=False records that the solids were meshed one by one, so touching solids each have their own surface where they meet; :class:MeshGeometry then tracks the mesh discontinuously, with contact_tolerance (cm) as the distance within which two solids' surfaces count as touching. Both are left out of the file when None. overlaps lists (low, high) pairs of 0-based volume ids whose solids overlap; where they do, the cell is high. separated lists (a, b) pairs of 0-based volume ids whose surfaces come within the contact tolerance although the solids do not touch, so the gap between them is kept rather than filled.

Source code in yamc/_core/__init__.pyi
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
def mesh_to_arrow(path: builtins.str, vertices: typing.Sequence[builtins.float], triangles: typing.Sequence[builtins.int], triangle_surface_ids: typing.Sequence[builtins.int], triangle_physical_groups: typing.Sequence[builtins.int], tetrahedra: typing.Sequence[builtins.int] = [], tet_volume_ids: typing.Sequence[builtins.int] = [], tet_physical_groups: typing.Sequence[builtins.int] = [], physical_groups_json: builtins.str = '{}', surface_volumes_json: builtins.str = '[]', volume_measures_json: builtins.str = '', imprinted: typing.Optional[builtins.bool] = None, contact_tolerance: typing.Optional[builtins.float] = None, overlaps: typing.Sequence[tuple[builtins.int, builtins.int]] = [], separated: typing.Sequence[tuple[builtins.int, builtins.int]] = []) -> None:
    r"""
    Write mesh data to an Arrow IPC file.

    Tet adjacency is computed here from the flat connectivity, so the caller
    does not supply it. Bounding boxes are not stored; they are computed from
    the vertices when the file is read.

    ``surface_volumes_json`` gives, for each surface, the 0-based ids of the
    volume its triangles' normals point out of and of the one they point into,
    ``null`` for the implicit complement. A surface with the same volume in
    both is an internal face of that volume: it bounds nothing, and particles
    pass it as if it were not there.

    ``imprinted=False`` records that the solids were meshed one by one, so
    touching solids each have their own surface where they meet;
    :class:`MeshGeometry` then tracks the mesh discontinuously, with
    ``contact_tolerance`` (cm) as the distance within which two solids'
    surfaces count as touching. Both are left out of the file when ``None``.
    ``overlaps`` lists ``(low, high)`` pairs of 0-based volume ids whose
    solids overlap; where they do, the cell is ``high``.
    ``separated`` lists ``(a, b)`` pairs of 0-based volume ids whose surfaces
    come within the contact tolerance although the solids do not touch, so the
    gap between them is kept rather than filled.
    """

mesh_volume_rs

mesh_volume_rs(boundary_vertices: Sequence[Sequence[float]], boundary_triangles: Sequence[Sequence[int]], target_edge_length: float, threads: Optional[int] = None) -> tuple[list[list[float]], list[list[int]]]

Tetrahedralize a solid from its conformal boundary surface mesh (replaces netgen). Returns (interior_vertices, tetrahedra). Boundary vertices are preserved exactly (tet indices 0..len(boundary_vertices) reference them, >= reference the returned interior vertices), and tets are pre-oriented to positive volume - so no winding swap or face remapping is needed. The work runs on threads threads, or on rayon's global pool when threads is None (the default).

Source code in yamc/_core/__init__.pyi
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
def mesh_volume_rs(boundary_vertices: typing.Sequence[typing.Sequence[builtins.float]], boundary_triangles: typing.Sequence[typing.Sequence[builtins.int]], target_edge_length: builtins.float, threads: typing.Optional[builtins.int] = None) -> tuple[builtins.list[builtins.list[builtins.float]], builtins.list[builtins.list[builtins.int]]]:
    r"""
    Tetrahedralize a solid from its conformal boundary surface mesh (replaces
    netgen). Returns `(interior_vertices, tetrahedra)`. Boundary vertices are
    preserved exactly (tet indices `0..len(boundary_vertices)` reference them,
    `>=` reference the returned interior vertices), and tets are pre-oriented
    to positive volume - so no winding swap or face remapping is needed. The
    work runs on ``threads`` threads, or on rayon's global pool when
    ``threads`` is ``None`` (the default).
    """

radionuclide_production

radionuclide_production(neutron_files: Sequence[str]) -> list

List the final states each reaction of an evaluation can leave its product in.

A reaction that can leave its product in a metastable state says so in MF=8, one subsection per final state. An evaluation that lists only the ground state is not merely less accurate: the isomer is absent from any network built from it, so no code can make it, and a measurement that sees its decay heat cannot be reproduced by any means. TENDL-2017 omits the 1706 keV state from Os190(n,n'), which is why the FNS osmium foil comes out at a third of the measured heat with that library, in yani and in FISPACT-II alike. Nothing about the reaction looks wrong from outside: it is present, its cross section is reasonable, and only the state list is short. So comparing the state lists of several libraries is how such a gap is found, and this is the read that makes the comparison possible.

A read, not a conversion. Nothing is written, no decay data is involved, and the answer is what the files say rather than what a network built from them would hold.

Parameters

neutron_files : list[str] Neutron evaluations, one or many materials per file. Read one file at a time rather than held, so a whole sublibrary is a valid argument.

Returns

list[dict] One entry per (parent, reaction) carrying MF=9 or MF=10, in file order and then tape order, each with parent, mt, reaction (the transmutation reaction name, or None for an MT no chain reaction covers) and states. Each state has excitation_energy_eV, level_index, product and source. excitation_energy_eV is None for an excited state whose evaluation gives neither a positive MF=8 ELFS nor a positive QM - QI.

``product`` is the product's **ground-state** name even for an excited
state, because naming the isomer needs decay data to say which
isomeric ordinal a level is; pair it with ``excitation_energy_eV``.
It is ``None`` for a state naming no single nuclide: fission, a
subsection whose IZAP is zero with no single MF=8 subsection to name
it, or any other ZAP whose Z or A is not positive.
``level_index`` is the evaluation's own LFS and is not comparable
between libraries: Ir190's 377 keV isomer is level 3 in ENDF/B-VIII.1
and level 37 in JEFF-4.0. ``source`` is ``"cross_section"`` for MF=10
or ``"yield"`` for MF=9.

Examples

>>> [c for c in yani.radionuclide_production(["n-Os190.tendl"])
...  if c["mt"] == 4][0]["states"]
[{'excitation_energy_eV': 0.0, 'level_index': 0, 'product': 'Os190',
  'source': 'cross_section'}]
Source code in yamc/_core/__init__.pyi
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
def radionuclide_production(neutron_files: typing.Sequence[builtins.str]) -> list:
    r"""
    List the final states each reaction of an evaluation can leave its product
    in.

    A reaction that can leave its product in a metastable state says so in
    MF=8, one subsection per final state. An evaluation that lists only the
    ground state is not merely less accurate: the isomer is absent from any
    network built from it, so no code can make it, and a measurement that sees
    its decay heat cannot be reproduced by any means. TENDL-2017 omits the
    1706 keV state from ``Os190(n,n')``, which is why the FNS osmium foil comes
    out at a third of the measured heat with that library, in yani and in
    FISPACT-II alike. Nothing about the reaction looks wrong from outside: it
    is present, its cross section is reasonable, and only the state list is
    short. So comparing the state lists of several libraries is how such a gap
    is found, and this is the read that makes the comparison possible.

    A read, not a conversion. Nothing is written, no decay data is involved,
    and the answer is what the files say rather than what a network built from
    them would hold.

    Parameters
    ----------
    neutron_files : list[str]
        Neutron evaluations, one or many materials per file. Read one file at
        a time rather than held, so a whole sublibrary is a valid argument.

    Returns
    -------
    list[dict]
        One entry per (parent, reaction) carrying MF=9 or MF=10, in file order
        and then tape order, each with ``parent``, ``mt``, ``reaction`` (the
        transmutation reaction name, or ``None`` for an MT no chain reaction
        covers) and ``states``.
        Each state has ``excitation_energy_eV``, ``level_index``, ``product``
        and ``source``. ``excitation_energy_eV`` is ``None`` for an excited
        state whose evaluation gives neither a positive MF=8 ELFS nor a
        positive ``QM - QI``.

        ``product`` is the product's **ground-state** name even for an excited
        state, because naming the isomer needs decay data to say which
        isomeric ordinal a level is; pair it with ``excitation_energy_eV``.
        It is ``None`` for a state naming no single nuclide: fission, a
        subsection whose IZAP is zero with no single MF=8 subsection to name
        it, or any other ZAP whose Z or A is not positive.
        ``level_index`` is the evaluation's own LFS and is not comparable
        between libraries: Ir190's 377 keV isomer is level 3 in ENDF/B-VIII.1
        and level 37 in JEFF-4.0. ``source`` is ``"cross_section"`` for MF=10
        or ``"yield"`` for MF=9.

    Examples
    --------
        >>> [c for c in yani.radionuclide_production(["n-Os190.tendl"])
        ...  if c["mt"] == 4][0]["states"]
        [{'excitation_energy_eV': 0.0, 'level_index': 0, 'product': 'Os190',
          'source': 'cross_section'}]
    """

read_element_from_arrow

read_element_from_arrow(path: str) -> Any

Read a photoatomic Arrow directory through yamc's own loader and describe it.

Parameters

path : str An {Element}.arrow/ directory. Taken verbatim, and read straight rather than through the process-global element store: that store is keyed by element name, so validating two builds of Fe.arrow in one process would get the first one back for the second call and report a false pass.

Publishes none of the process-wide photon grids either. An ordinary
read installs the Compton momentum grid and the two TTB grids on first
use, so inspecting a candidate directory in an interpreter that also
runs transport would hand that candidate's grids to every later element
load and every photon collision. The sampler reads the profile tables
against whichever grid is installed, so a different grid changes every
Doppler sample and says nothing about it.

Returns

dict name, atomic_number, n_energy_points, n_subshells, has_atomic_relaxation, has_compton_profiles and has_bremsstrahlung.

The last three are the auxiliary tabulations that are not in any
evaluation, so a directory converted without them reads back fine and
is still not what transport wants. There is no ``scope`` here: the
photon reader has one mode.

Raises

RuntimeError The directory is absent, or any section fails to parse.

Source code in yamc/_core/__init__.pyi
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
def read_element_from_arrow(path: builtins.str) -> typing.Any:
    r"""
    Read a photoatomic Arrow directory through yamc's own loader and describe it.

    Parameters
    ----------
    path : str
        An ``{Element}.arrow/`` directory. Taken verbatim, and read straight
        rather than through the process-global element store: that store is
        keyed by element name, so validating two builds of ``Fe.arrow`` in one
        process would get the first one back for the second call and report a
        false pass.

        Publishes none of the process-wide photon grids either. An ordinary
        read installs the Compton momentum grid and the two TTB grids on first
        use, so inspecting a candidate directory in an interpreter that also
        runs transport would hand that candidate's grids to every later element
        load and every photon collision. The sampler reads the profile tables
        against whichever grid is installed, so a different grid changes every
        Doppler sample and says nothing about it.

    Returns
    -------
    dict
        ``name``, ``atomic_number``, ``n_energy_points``, ``n_subshells``,
        ``has_atomic_relaxation``, ``has_compton_profiles`` and
        ``has_bremsstrahlung``.

        The last three are the auxiliary tabulations that are not in any
        evaluation, so a directory converted without them reads back fine and
        is still not what transport wants. There is no ``scope`` here: the
        photon reader has one mode.

    Raises
    ------
    RuntimeError
        The directory is absent, or any section fails to parse.
    """

read_nuclide_from_arrow

read_nuclide_from_arrow(path: str, scope: str = 'full') -> Any

Read a nuclide Arrow directory through yamc's own loader and describe it.

Parameters

path : str A {Nuclide}.arrow/ section directory. Taken verbatim: no keyword expansion, no directory search and no download, so a validation run cannot silently check a different file from the one it named. scope : str, optional "full" (default) reads every section, which is what transport needs. "xs" reads nuclide.arrow, energy.arrow and reactions.arrow only, which is what a transport-free reaction-rate collapse touches.

Returns

dict name, atomic_number, mass_number, atomic_weight_ratio, fissionable, urr_present, available_temperatures, loaded_temperatures, mts, energy_points, angular_covariance, nubar_covariance, spectrum_covariance, resonance_parameters and scope_loaded.

``energy_points`` is a dict of temperature to grid length, over the
loaded temperatures. Not one number: the reader also keeps the 0 K union
grid, which is longer than any of them and belongs to no temperature the
other two lists mention, so a single maximum would report a grid nothing
reads and hide a per-temperature grid that had been truncated.

There is no ``library`` key. The Arrow loader does not populate that
field, so it would report ``None`` for every directory, correct or not.
Read ``version.json`` for it.

``angular_covariance`` is the folder's MF=34 (``angular_covariance.arrow``),
summarised as ``{mt: [(l, l1), ...]}``: per reaction, the sorted (L, L1)
pairs of Legendre orders a covariance block correlates. ``None`` when
the folder has none. It is read whatever ``scope`` says, since it is a
separate optional section.

``nubar_covariance`` is the folder's MF=31 (``nubar_covariance.arrow``),
summarised as the sorted fission multiplicity MTs (of 452, 455 and 456)
it carries covariance for, and ``spectrum_covariance`` its MF=35
(``spectrum_covariance.arrow``), as ``{mt: [(e1, e2), ...]}``: per
reaction, the incident energy range of each covariance block, in tape
order. Each is ``None`` when the folder has none, and both are read
whatever ``scope`` says, as ``angular_covariance`` is.

``resonance_parameters`` is the folder's MF=2 and MF=32
(``resonance_parameters.arrow``), both parsed, summarised as the
``(lru, lrf)`` of each MF=2 energy range, isotope by isotope in tape
order: LRU 1 resolved or 2 unresolved, LRF the formalism. ``None`` when
the folder has none, and read whatever ``scope`` says.

``scope_loaded`` is the one to assert on, and it is not always the
``scope`` asked for: a directory holding no transport sections narrows a
``"full"`` request to ``"xs"`` rather than failing it, on the theory
that it is a cross-sections-only conversion. A gate that asks for
``"full"`` and does not check what it got will pass a directory with no
distributions and no products.

Raises

ValueError scope is neither "full" nor "xs". RuntimeError The directory is absent, is not the Arrow format version this build reads, or any section fails to parse, the stored MF=2 and MF=32 text included.

Source code in yamc/_core/__init__.pyi
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
def read_nuclide_from_arrow(path: builtins.str, scope: builtins.str = 'full') -> typing.Any:
    r"""
    Read a nuclide Arrow directory through yamc's own loader and describe it.

    Parameters
    ----------
    path : str
        A ``{Nuclide}.arrow/`` section directory. Taken verbatim: no keyword
        expansion, no directory search and no download, so a validation run
        cannot silently check a different file from the one it named.
    scope : str, optional
        ``"full"`` (default) reads every section, which is what transport
        needs. ``"xs"`` reads ``nuclide.arrow``, ``energy.arrow`` and
        ``reactions.arrow`` only, which is what a transport-free reaction-rate
        collapse touches.

    Returns
    -------
    dict
        ``name``, ``atomic_number``, ``mass_number``, ``atomic_weight_ratio``,
        ``fissionable``, ``urr_present``, ``available_temperatures``,
        ``loaded_temperatures``, ``mts``, ``energy_points``,
        ``angular_covariance``, ``nubar_covariance``, ``spectrum_covariance``,
        ``resonance_parameters`` and ``scope_loaded``.

        ``energy_points`` is a dict of temperature to grid length, over the
        loaded temperatures. Not one number: the reader also keeps the 0 K union
        grid, which is longer than any of them and belongs to no temperature the
        other two lists mention, so a single maximum would report a grid nothing
        reads and hide a per-temperature grid that had been truncated.

        There is no ``library`` key. The Arrow loader does not populate that
        field, so it would report ``None`` for every directory, correct or not.
        Read ``version.json`` for it.

        ``angular_covariance`` is the folder's MF=34 (``angular_covariance.arrow``),
        summarised as ``{mt: [(l, l1), ...]}``: per reaction, the sorted (L, L1)
        pairs of Legendre orders a covariance block correlates. ``None`` when
        the folder has none. It is read whatever ``scope`` says, since it is a
        separate optional section.

        ``nubar_covariance`` is the folder's MF=31 (``nubar_covariance.arrow``),
        summarised as the sorted fission multiplicity MTs (of 452, 455 and 456)
        it carries covariance for, and ``spectrum_covariance`` its MF=35
        (``spectrum_covariance.arrow``), as ``{mt: [(e1, e2), ...]}``: per
        reaction, the incident energy range of each covariance block, in tape
        order. Each is ``None`` when the folder has none, and both are read
        whatever ``scope`` says, as ``angular_covariance`` is.

        ``resonance_parameters`` is the folder's MF=2 and MF=32
        (``resonance_parameters.arrow``), both parsed, summarised as the
        ``(lru, lrf)`` of each MF=2 energy range, isotope by isotope in tape
        order: LRU 1 resolved or 2 unresolved, LRF the formalism. ``None`` when
        the folder has none, and read whatever ``scope`` says.

        ``scope_loaded`` is the one to assert on, and it is not always the
        ``scope`` asked for: a directory holding no transport sections narrows a
        ``"full"`` request to ``"xs"`` rather than failing it, on the theory
        that it is a cross-sections-only conversion. A gate that asks for
        ``"full"`` and does not check what it got will pass a directory with no
        distributions and no products.

    Raises
    ------
    ValueError
        ``scope`` is neither ``"full"`` nor ``"xs"``.
    RuntimeError
        The directory is absent, is not the Arrow format version this build
        reads, or any section fails to parse, the stored MF=2 and MF=32 text
        included.
    """

read_photonuclear_from_arrow

read_photonuclear_from_arrow(path: str) -> Any

Validate evaluated photonuclear Arrow tables against their preserved ENDF. Returns the nuclide identity, MTs, per-MT energy-point counts and preserved (MF, MT) section keys. Does not invoke neutron or photoatomic transport.

Source code in yamc/_core/__init__.pyi
9711
9712
9713
9714
9715
9716
def read_photonuclear_from_arrow(path: builtins.str) -> typing.Any:
    r"""
    Validate evaluated photonuclear Arrow tables against their preserved ENDF.
    Returns the nuclide identity, MTs, per-MT energy-point counts and preserved
    (MF, MT) section keys. Does not invoke neutron or photoatomic transport.
    """

reduce_mesh_tally_block

reduce_mesh_tally_block(block_mean: Sequence[float], block_std: Sequence[float], n_parent: int, n_energy: int, n_mesh: int, parent_iter: Sequence[Optional[int]], energy_iter: Sequence[Optional[int]], vol: Optional[Sequence[float]] = None, scaling: float = 1.0) -> list[tuple[list[float], list[float], list[float]]]

Reduce one score block of a mesh tally over parent/energy bins.

The block is laid out [parent][energy][mesh] (mesh fastest), matching the tally's flat result order. For every (parent_index, energy_index) pair in the cartesian product of parent_iter x energy_iter (parent outer, energy inner), the mesh-length mean is summed over the collapsed axes and the standard deviation is combined in quadrature (sqrt(sum(std^2))). A None index means "sum over that whole axis"; a Some(i) selects a single bin.

When vol is given (length n_mesh), mean and std are divided by the per-voxel volume; scaling then multiplies both. Relative error is std/mean where mean is non-zero, else 0 (both volume and scaling cancel in the ratio, matching the pure-numpy path).

Returns one (mean, std, relative_error) triple per combination, in the same parent-outer/energy-inner order the caller iterates.

Source code in yamc/_core/__init__.pyi
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
def reduce_mesh_tally_block(block_mean: typing.Sequence[builtins.float], block_std: typing.Sequence[builtins.float], n_parent: builtins.int, n_energy: builtins.int, n_mesh: builtins.int, parent_iter: typing.Sequence[typing.Optional[builtins.int]], energy_iter: typing.Sequence[typing.Optional[builtins.int]], vol: typing.Optional[typing.Sequence[builtins.float]] = None, scaling: builtins.float = 1.0) -> builtins.list[tuple[builtins.list[builtins.float], builtins.list[builtins.float], builtins.list[builtins.float]]]:
    r"""
    Reduce one score block of a mesh tally over parent/energy bins.

    The block is laid out `[parent][energy][mesh]` (mesh fastest), matching the
    tally's flat result order. For every `(parent_index, energy_index)` pair in
    the cartesian product of `parent_iter` x `energy_iter` (parent outer, energy
    inner), the mesh-length mean is summed over the collapsed axes and the
    standard deviation is combined in quadrature (`sqrt(sum(std^2))`). A `None`
    index means "sum over that whole axis"; a `Some(i)` selects a single bin.

    When `vol` is given (length `n_mesh`), mean and std are divided by the
    per-voxel volume; `scaling` then multiplies both. Relative error is
    `std/mean` where mean is non-zero, else 0 (both volume and scaling cancel in
    the ratio, matching the pure-numpy path).

    Returns one `(mean, std, relative_error)` triple per combination, in the
    same parent-outer/energy-inner order the caller iterates.
    """

sample_scatter_cosine

sample_scatter_cosine() -> float

Sample a scattering cosine (mu in [-1, 1]) for isotropic scattering.

Source code in yamc/_core/__init__.pyi
9738
9739
9740
9741
def sample_scatter_cosine() -> builtins.float:
    r"""
    Sample a scattering cosine (mu in [-1, 1]) for isotropic scattering.
    """

set_neutron_cross_section_data

set_neutron_cross_section_data(value: str | dict[str, str] | None) -> None

Set the cross-section data mapping.

Accepts None to clear, a string for a global library keyword or directory, or a dict mapping nuclide names to paths or keywords.

Source code in yamc/_core/__init__.pyi
9743
9744
9745
9746
9747
9748
9749
def set_neutron_cross_section_data(value: builtins.str | dict[builtins.str, builtins.str] | None) -> None:
    r"""
    Set the cross-section data mapping.

    Accepts ``None`` to clear, a string for a global library keyword or
    directory, or a dict mapping nuclide names to paths or keywords.
    """

set_photon_cross_section_data

set_photon_cross_section_data(value: str | dict[str, str] | None) -> None

Select photon data explicitly; neutron settings are never used as a fallback.

Source code in yamc/_core/__init__.pyi
9758
9759
9760
9761
def set_photon_cross_section_data(value: builtins.str | dict[builtins.str, builtins.str] | None) -> None:
    r"""
    Select photon data explicitly; neutron settings are never used as a fallback.
    """

set_transmutation_branch_ratios

set_transmutation_branch_ratios(value: Optional[str | Sequence[str]]) -> None

Set the isomeric-branching sources of the transmutation network.

A source is a library keyword or a path to a branching subsection. Give one, or several in order: each reaction of each parent (each channel) takes its isomeric split, and the MF=40 covariance of that split, from the first source that evaluates it, and the other sources' data for that channel are not used. The branching report (TransmutationResults.get_branching_report) names the source of every channel, and says whether the run mixes libraries.

"irdff-ii", the IAEA dosimetry library IRDFF-II, supplies isomeric branching only, so it is only ever a source here, and only where it is named: it is never a default.

It reads back as it was assigned: a string as a string, a list (even one of one) as a list.

Parameters:

Name Type Description Default
value Optional[str | Sequence[str]]

A source, a list of sources in order, or None (or an empty list) for no isomeric-branching overlay.

required

Raises:

Type Description
ValueError

If a source is empty or is listed twice.

Examples:

>>> yani.transmutation_branch_ratios = ["irdff-ii", "endf-b8.1"]
>>> yani.transmutation_branch_ratios
['irdff-ii', 'endf-b8.1']
Source code in yamc/_core/__init__.pyi
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
def set_transmutation_branch_ratios(value: typing.Optional[builtins.str | typing.Sequence[builtins.str]]) -> None:
    r"""
    Set the isomeric-branching sources of the transmutation network.

    A source is a library keyword or a path to a ``branching`` subsection.
    Give one, or several in order: each reaction of each parent (each
    channel) takes its isomeric split, and the MF=40 covariance of that
    split, from the first source that evaluates it, and the other sources'
    data for that channel are not used. The branching report
    (``TransmutationResults.get_branching_report``) names the source of every
    channel, and says whether the run mixes libraries.

    ``"irdff-ii"``, the IAEA dosimetry library IRDFF-II, supplies isomeric
    branching only, so it is only ever a source here, and only where it is
    named: it is never a default.

    It reads back as it was assigned: a string as a string, a list (even one
    of one) as a list.

    Args:
        value: A source, a list of sources in order, or ``None`` (or an empty
            list) for no isomeric-branching overlay.

    Raises:
        ValueError: If a source is empty or is listed twice.

    Examples:
        >>> yani.transmutation_branch_ratios = ["irdff-ii", "endf-b8.1"]
        >>> yani.transmutation_branch_ratios
        ['irdff-ii', 'endf-b8.1']
    """

set_transmutation_decay_data

set_transmutation_decay_data(value: Optional[str]) -> None

Set the decay-data source: a library keyword or a path.

Every transmutation and decay quantity (activity, decay heat, dose) reads it, and there is no default library, so one with it unset is refused before any work, naming the setting. Pass None to unset it.

Source code in yamc/_core/__init__.pyi
9795
9796
9797
9798
9799
9800
9801
9802
def set_transmutation_decay_data(value: typing.Optional[builtins.str]) -> None:
    r"""
    Set the decay-data source: a library keyword or a path.

    Every transmutation and decay quantity (activity, decay heat, dose) reads
    it, and there is no default library, so one with it unset is refused
    before any work, naming the setting. Pass ``None`` to unset it.
    """

set_transmutation_fission_yields

set_transmutation_fission_yields(value: Optional[str | Literal[False]]) -> None

Set the fission-yields source.

Pass a library keyword or a path to choose one. An irradiation reads it, and there is no default library, so one with it unset is refused before any work, naming the setting. Pass None to unset it.

Pass False to turn the subsection off, which is the honest setting for a material nothing in which fissions and for a library that publishes no yields of its own. A non-zero fission rate that then needs them is refused when the burnup matrix is built, naming the nuclide, rather than losing its fission products while still burning it.

Source code in yamc/_core/__init__.pyi
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
def set_transmutation_fission_yields(value: typing.Optional[builtins.str | typing.Literal[False]]) -> None:
    r"""
    Set the fission-yields source.

    Pass a library keyword or a path to choose one. An irradiation reads it,
    and there is no default library, so one with it unset is refused before
    any work, naming the setting. Pass ``None`` to unset it.

    Pass ``False`` to turn the subsection off, which is the honest setting for
    a material nothing in which fissions and for a library that publishes no
    yields of its own. A non-zero fission rate that then needs them is refused
    when the burnup matrix is built, naming the nuclide, rather than losing its
    fission products while still burning it.
    """

set_transmutation_reactions

set_transmutation_reactions(value: Optional[str | Literal[False]]) -> None

Set the reaction-topology source.

Pass a library keyword or a path to choose one. An irradiation, a D1S decay-photon run, Model.radionuclides and PulseSchedule.time_correct_tally read it, and there is no default library, so one with it unset is refused before any work, naming the setting. Pass None to unset it.

Pass False to turn the subsection off, for a decay-only calculation on a material with no reaction rates. A rate that then needs it is refused when the burnup matrix is built, naming the nuclide and the reaction, rather than being solved as though the reaction produced nothing.

Source code in yamc/_core/__init__.pyi
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
def set_transmutation_reactions(value: typing.Optional[builtins.str | typing.Literal[False]]) -> None:
    r"""
    Set the reaction-topology source.

    Pass a library keyword or a path to choose one. An irradiation, a D1S
    decay-photon run, ``Model.radionuclides`` and
    ``PulseSchedule.time_correct_tally`` read it, and there is no default
    library, so one with it unset is refused before any work, naming the
    setting. Pass ``None`` to unset it.

    Pass ``False`` to turn the subsection off, for a decay-only calculation on
    a material with no reaction rates. A rate that then needs it is refused
    when the burnup matrix is built, naming the nuclide and the reaction,
    rather than being solved as though the reaction produced nothing.
    """

simulate_shutdown_dose

simulate_shutdown_dose(schedule: PulseSchedule, tallies: Sequence[Tally], total_particles: int, seed: int = 1, threads: Optional[int] = None, method: str = 'd1s', mesh: RegularRectangularMesh | RegularCylindricalMesh | MeshGeometry | None = None) -> dict[str, DoseResult]

Simulate the shutdown dose rate of a machine that changes along its irradiation and cooling schedule.

Each step of schedule names the Model the machine is in (Pulse(model=...), Cooldown(model=...); a step without one stays in the previous step's). A model can add cells, leave cells out (removed components no longer emit, though what they emitted before still decays with them should they come back) and hold cells somewhere else (say where with the step's moves). Cells are the same component across models when they have the same name, so name every cell that activates.

For every model a pulse irradiates in, the neutrons are transported once and each decay photon (D1S) is recorded where it is born. For every configuration the machine is observed in, each neutron history's photons, from every irradiated model, are then moved with their cells and transported through that model as one photon history, and that history's dose at the end of every step it observes is formed from the per-radionuclide time correction factors of each irradiation's own pulses. No step of the schedule needs a transport run of its own.

std_dev is the standard error of the whole calculation: the spread of those per-history doses, so it covers the neutron transport and the photon transport, and the correlation between radionuclides and between irradiations that one neutron history carries. For a machine that never changes it is the error of the single-model D1S run. Runs on the CPU, on one process.

With method="r2s" (cell-based rigorous two-step) the inventory of every material-filled cell is solved instead, through the whole schedule with the cell's own neutron spectrum, so activation products that are themselves activated and burnup are included. Each step then gets a photon transport of its own, with every cell emitting its decay photons at that time uniformly over its volume (split cells where the flux varies steeply). The pulses must all irradiate in one model; cells are matched across models by name and emit wherever the step's model has them. A cell's volume is estimated by sampling unless Cell(volume=...) gives it.

With method="r2s" and a mesh (cell-under-mesh R2S), every part of a material-filled cell under a voxel is solved instead, with the voxel's neutron spectrum (tallied in VITAMIN-J-175 groups), and emits uniformly over that part, so the source follows the flux gradient through thick cells without splitting them. The parts' volumes are estimated by sampling each voxel. Pulses must irradiate with one set of moves, and a cell moved after irradiation needs its moves, as with D1S. Voxels no neutron reaches are not activated.

With R2S, std_dev is the photon transport's statistical error given the solved inventories; the neutron transport's is not included.

Parameters:

Name Type Description Default
schedule PulseSchedule

A PulseSchedule whose steps name models.

required
tallies Sequence[Tally]

Photon tallies to score the dose in, without parent_nuclides (they are binned by every radionuclide the irradiations make). Each needs a unique name, and must be valid in every model the schedule observes (a cell filter's cells must exist in each).

required
total_particles int

Neutron histories per irradiated model. Every photon run then has one history per neutron history (with R2S, each step's photon run has this many).

required
seed int

Base random seed.

1
threads Optional[int]

Worker threads; None uses all cores.

None
method str

"d1s" (one-step, one photon run per pair of irradiation and observation configurations) or "r2s" (cell inventories, one photon run per step).

'd1s'
mesh RegularRectangularMesh | RegularCylindricalMesh | MeshGeometry | None

With method="r2s", a mesh over the activated components for cell-under-mesh R2S, each element's part of every material-filled cell activated on the element's neutron spectrum: a RegularRectangularMesh, a RegularCylindricalMesh, or a tet MeshGeometry (every tet, each inside one cell, as the model's own tet mesh is). None activates whole cells.

None

Returns:

Type Description
dict[str, DoseResult]

{tally name: DoseResult}, each with one row per schedule step:

dict[str, DoseResult]

.mean / .std_dev / .by_nuclide / .times.

Examples:

>>> schedule = yamc.PulseSchedule([
...     yamc.Pulse(model=dt_reactor, rate=1e18, duration=(1, "a")),
...     yamc.Cooldown(model=opened, duration=(1, "d"),
...                   moves={"blanket": (0, 0, 300)}),
... ])
>>> dose = yamc.simulate_shutdown_dose(schedule, tallies=[dose_tally],
...                                    total_particles=100_000)
>>> dose["dose"].mean[-1]
Source code in yamc/_core/__init__.pyi
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
def simulate_shutdown_dose(schedule: PulseSchedule, tallies: typing.Sequence[Tally], total_particles: builtins.int, seed: builtins.int = 1, threads: typing.Optional[builtins.int] = None, method: builtins.str = 'd1s', mesh: RegularRectangularMesh | RegularCylindricalMesh | MeshGeometry | None = None) -> builtins.dict[builtins.str, DoseResult]:
    r"""
    Simulate the shutdown dose rate of a machine that changes along its
    irradiation and cooling schedule.

    Each step of ``schedule`` names the ``Model`` the machine is in
    (``Pulse(model=...)``, ``Cooldown(model=...)``; a step without one stays in
    the previous step's). A model can add cells, leave cells out (removed
    components no longer emit, though what they emitted before still decays
    with them should they come back) and hold cells somewhere else (say where
    with the step's ``moves``). Cells are the same component across models when
    they have the same name, so name every cell that activates.

    For every model a pulse irradiates in, the neutrons are transported once
    and each decay photon (D1S) is recorded where it is born. For every
    configuration the machine is observed in, each neutron history's photons,
    from every irradiated model, are then moved with their cells and
    transported through that model as one photon history, and that history's
    dose at the end of every step it observes is formed from the
    per-radionuclide time correction factors of each irradiation's own pulses.
    No step of the schedule needs a transport run of its own.

    ``std_dev`` is the standard error of the whole calculation: the spread of
    those per-history doses, so it covers the neutron transport and the photon
    transport, and the correlation between radionuclides and between
    irradiations that one neutron history carries. For a machine that never
    changes it is the error of the single-model D1S run. Runs on the CPU, on
    one process.

    With ``method="r2s"`` (cell-based rigorous two-step) the inventory of every
    material-filled cell is solved instead, through the whole schedule with the
    cell's own neutron spectrum, so activation products that are themselves
    activated and burnup are included. Each step then gets a photon transport
    of its own, with every cell emitting its decay photons at that time
    uniformly over its volume (split cells where the flux varies steeply). The
    pulses must all irradiate in one model; cells are matched across models by
    name and emit wherever the step's model has them. A cell's volume is
    estimated by sampling unless ``Cell(volume=...)`` gives it.

    With ``method="r2s"`` and a ``mesh`` (cell-under-mesh R2S), every part of
    a material-filled cell under a voxel is solved instead, with the voxel's
    neutron spectrum (tallied in VITAMIN-J-175 groups), and emits uniformly
    over that part, so the source follows the flux gradient through thick
    cells without splitting them. The parts' volumes are estimated by sampling
    each voxel. Pulses must irradiate with one set of moves, and a cell moved
    after irradiation needs its ``moves``, as with D1S. Voxels no neutron
    reaches are not activated.

    With R2S, ``std_dev`` is the photon transport's statistical error given
    the solved inventories; the neutron transport's is not included.

    Args:
        schedule: A ``PulseSchedule`` whose steps name models.
        tallies: Photon tallies to score the dose in, without
            ``parent_nuclides`` (they are binned by every radionuclide the
            irradiations make). Each needs a unique ``name``, and must be valid
            in every model the schedule observes (a cell filter's cells must
            exist in each).
        total_particles: Neutron histories per irradiated model. Every photon
            run then has one history per neutron history (with R2S, each
            step's photon run has this many).
        seed: Base random seed.
        threads: Worker threads; ``None`` uses all cores.
        method: ``"d1s"`` (one-step, one photon run per pair of irradiation
            and observation configurations) or ``"r2s"`` (cell inventories,
            one photon run per step).
        mesh: With ``method="r2s"``, a mesh over the activated components for
            cell-under-mesh R2S, each element's part of every material-filled
            cell activated on the element's neutron spectrum: a
            ``RegularRectangularMesh``, a ``RegularCylindricalMesh``, or a tet
            ``MeshGeometry`` (every tet, each inside one cell, as the model's
            own tet mesh is). ``None`` activates whole cells.

    Returns:
        ``{tally name: DoseResult}``, each with one row per schedule step:
        ``.mean`` / ``.std_dev`` / ``.by_nuclide`` / ``.times``.

    Examples:
        >>> schedule = yamc.PulseSchedule([
        ...     yamc.Pulse(model=dt_reactor, rate=1e18, duration=(1, "a")),
        ...     yamc.Cooldown(model=opened, duration=(1, "d"),
        ...                   moves={"blanket": (0, 0, 300)}),
        ... ])
        >>> dose = yamc.simulate_shutdown_dose(schedule, tallies=[dose_tally],
        ...                                    total_particles=100_000)
        >>> dose["dose"].mean[-1]
    """

solid_contact_samples

solid_contact_samples(vertices: Sequence[Sequence[float]], solids: Sequence[tuple[int, Sequence[Sequence[int]]]], tolerance: float, samples: int = 8, threads: Optional[int] = None) -> list[tuple[int, int, list[list[float]]]]

Points where two solids' surface meshes come within tolerance.

For every pair of solids whose meshes come that close, up to samples mesh vertices of one of them lying within tolerance of the other's surface. A mesh vertex lies on its solid's CAD surface, so its exact distance to the other CAD solid says whether the two touch there or are separated by a real gap that faceting has narrowed.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

Global [x, y, z] vertex array.

required
solids Sequence[tuple[int, Sequence[Sequence[int]]]]

(solid_id, triangles) per solid.

required
tolerance float

The contact tolerance (3D units).

required
samples int

Points to return per pair at most.

8
threads Optional[int]

Threads to run the search on, or None (the default) for rayon's global pool.

None

Returns:

Type Description
list[tuple[int, int, list[list[float]]]]

[(solid_a, solid_b, [[x, y, z], ...]), ...], the points on

list[tuple[int, int, list[list[float]]]]

solid_a's surface. A pair whose meshes come close only between

list[tuple[int, int, list[list[float]]]]

vertices returns no points, and so does a pair whose meshes share a

list[tuple[int, int, list[list[float]]]]

vertex (which lies on both CAD surfaces, so the two touch).

Source code in yamc/_core/__init__.pyi
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
def solid_contact_samples(vertices: typing.Sequence[typing.Sequence[builtins.float]], solids: typing.Sequence[tuple[builtins.int, typing.Sequence[typing.Sequence[builtins.int]]]], tolerance: builtins.float, samples: builtins.int = 8, threads: typing.Optional[builtins.int] = None) -> builtins.list[tuple[builtins.int, builtins.int, builtins.list[builtins.list[builtins.float]]]]:
    r"""
    Points where two solids' surface meshes come within ``tolerance``.

    For every pair of solids whose meshes come that close, up to ``samples``
    mesh vertices of one of them lying within ``tolerance`` of the other's
    surface. A mesh vertex lies on its solid's CAD surface, so its exact
    distance to the other CAD solid says whether the two touch there or are
    separated by a real gap that faceting has narrowed.

    Args:
        vertices: Global ``[x, y, z]`` vertex array.
        solids: ``(solid_id, triangles)`` per solid.
        tolerance: The contact tolerance (3D units).
        samples: Points to return per pair at most.
        threads: Threads to run the search on, or ``None`` (the default) for
            rayon's global pool.

    Returns:
        ``[(solid_a, solid_b, [[x, y, z], ...]), ...]``, the points on
        ``solid_a``'s surface. A pair whose meshes come close only between
        vertices returns no points, and so does a pair whose meshes share a
        vertex (which lies on both CAD surfaces, so the two touch).
    """

solid_open_edges

solid_open_edges(vertices: Sequence[Sequence[float]], triangles: Sequence[Sequence[int]], triangle_surface_ids: Sequence[int], solid_faces: Sequence[tuple[int, Sequence[int]]], face_to_surface_id: Sequence[tuple[int, int]], face_solid_reversed: Mapping[tuple[int, int], bool], reach: Mapping[int, float], samples: int = 4) -> list[tuple[int, int, list[list[float]]]]

Solids whose surface mesh is open.

Each solid is bounded by the surfaces :func:cad_mesh_to_arrow writes it with, their triangles wound outward from it. A closed surface runs along each edge of its triangles as often one way as the other; an edge a solid's triangles run along more often one way is open: the rim of a hole or of a face left one-sided, a face wound the wrong way round, or one side of a crack between two facetings of a CAD edge. A surface with the solid on both sides closes on itself. Cracks are not counted: an open edge with an open edge running back alongside it, within the solid's reach.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

Global [x, y, z] vertex array.

required
triangles Sequence[Sequence[int]]

Per-triangle global vertex indices.

required
triangle_surface_ids Sequence[int]

1-based surface id per triangle.

required
solid_faces Sequence[tuple[int, Sequence[int]]]

(solid_id, face_ids) pairs in ascending solid order.

required
face_to_surface_id Sequence[tuple[int, int]]

(face_id, surface_id) pairs (surface ids 1-based).

required
face_solid_reversed Mapping[tuple[int, int], bool]

(solid_id, face_id) -> reversed orientation map.

required
reach Mapping[int, float]

{solid_id: distance} within which an open edge running back closes a crack; a solid it does not name has none.

required
samples int

Open edges to give the midpoint of per solid at most.

4

Returns:

Type Description
list[tuple[int, int, list[list[float]]]]

[(solid_id, edges, [[x, y, z], ...]), ...] for every solid with an

list[tuple[int, int, list[list[float]]]]

open edge outside a crack: how many it has, and the midpoints of the

list[tuple[int, int, list[list[float]]]]

first.

Raises:

Type Description
ValueError

If triangles and triangle_surface_ids differ in length, or a triangle indexes past vertices.

Source code in yamc/_core/__init__.pyi
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
def solid_open_edges(vertices: typing.Sequence[typing.Sequence[builtins.float]], triangles: typing.Sequence[typing.Sequence[builtins.int]], triangle_surface_ids: typing.Sequence[builtins.int], solid_faces: typing.Sequence[tuple[builtins.int, typing.Sequence[builtins.int]]], face_to_surface_id: typing.Sequence[tuple[builtins.int, builtins.int]], face_solid_reversed: typing.Mapping[tuple[builtins.int, builtins.int], builtins.bool], reach: typing.Mapping[builtins.int, builtins.float], samples: builtins.int = 4) -> builtins.list[tuple[builtins.int, builtins.int, builtins.list[builtins.list[builtins.float]]]]:
    r"""
    Solids whose surface mesh is open.

    Each solid is bounded by the surfaces :func:`cad_mesh_to_arrow` writes it
    with, their triangles wound outward from it. A closed surface runs along
    each edge of its triangles as often one way as the other; an edge a
    solid's triangles run along more often one way is open: the rim of a hole
    or of a face left one-sided, a face wound the wrong way round, or one side
    of a crack between two facetings of a CAD edge. A surface with the solid
    on both sides closes on itself. Cracks are not counted: an open edge with
    an open edge running back alongside it, within the solid's ``reach``.

    Args:
        vertices: Global ``[x, y, z]`` vertex array.
        triangles: Per-triangle global vertex indices.
        triangle_surface_ids: 1-based surface id per triangle.
        solid_faces: ``(solid_id, face_ids)`` pairs in ascending solid order.
        face_to_surface_id: ``(face_id, surface_id)`` pairs (surface ids 1-based).
        face_solid_reversed: ``(solid_id, face_id) -> reversed`` orientation map.
        reach: ``{solid_id: distance}`` within which an open edge running back
            closes a crack; a solid it does not name has none.
        samples: Open edges to give the midpoint of per solid at most.

    Returns:
        ``[(solid_id, edges, [[x, y, z], ...]), ...]`` for every solid with an
        open edge outside a crack: how many it has, and the midpoints of the
        first.

    Raises:
        ValueError: If ``triangles`` and ``triangle_surface_ids`` differ in
            length, or a triangle indexes past ``vertices``.
    """

solid_overlaps

solid_overlaps(vertices: Sequence[Sequence[float]], solids: Sequence[tuple[int, Sequence[Sequence[int]]]], depth_tolerance: float, threads: Optional[int] = None) -> list[tuple[int, int, float, float]]

Pairs of solids whose surface meshes overlap deeper than depth_tolerance.

Every vertex, edge and face interior of each solid's closed boundary is tested against every other solid whose bounding box it reaches (the compiled mesh-level overlap check). Contact is not overlap: a point within depth_tolerance of the other surface counts as touching it.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

Global [x, y, z] vertex array.

required
solids Sequence[tuple[int, Sequence[Sequence[int]]]]

(solid_id, triangles) per solid, each its full closed boundary as [i, j, k] indices into vertices.

required
depth_tolerance float

Penetration (3D units) at or below which a feature counts as touching rather than inside.

required
threads Optional[int]

Threads to run the check on, or None (the default) for rayon's global pool.

None

Returns:

Type Description
list[tuple[int, int, float, float]]

[(solid_a, solid_b, max_depth, exposure), ...] for every

list[tuple[int, int, float, float]]

overlapping pair, max_depth the deepest penetration found and

list[tuple[int, int, float, float]]

exposure an order-of-magnitude estimate of the fraction of

list[tuple[int, int, float, float]]

isotropic tracks through the model that cross the overlap.

Source code in yamc/_core/__init__.pyi
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
def solid_overlaps(vertices: typing.Sequence[typing.Sequence[builtins.float]], solids: typing.Sequence[tuple[builtins.int, typing.Sequence[typing.Sequence[builtins.int]]]], depth_tolerance: builtins.float, threads: typing.Optional[builtins.int] = None) -> builtins.list[tuple[builtins.int, builtins.int, builtins.float, builtins.float]]:
    r"""
    Pairs of solids whose surface meshes overlap deeper than ``depth_tolerance``.

    Every vertex, edge and face interior of each solid's closed boundary is
    tested against every other solid whose bounding box it reaches (the
    compiled mesh-level overlap check). Contact is not overlap: a point within
    ``depth_tolerance`` of the other surface counts as touching it.

    Args:
        vertices: Global ``[x, y, z]`` vertex array.
        solids: ``(solid_id, triangles)`` per solid, each its full closed
            boundary as ``[i, j, k]`` indices into ``vertices``.
        depth_tolerance: Penetration (3D units) at or below which a feature
            counts as touching rather than inside.
        threads: Threads to run the check on, or ``None`` (the default) for
            rayon's global pool.

    Returns:
        ``[(solid_a, solid_b, max_depth, exposure), ...]`` for every
        overlapping pair, ``max_depth`` the deepest penetration found and
        ``exposure`` an order-of-magnitude estimate of the fraction of
        isotropic tracks through the model that cross the overlap.
    """

solid_self_intersections

solid_self_intersections(vertices: Sequence[Sequence[float]], solids: Sequence[tuple[int, Sequence[Sequence[int]]]], rel_tol: float = 1e-06, samples: int = 4, threads: Optional[int] = None) -> list[tuple[int, int, float, list[list[float]]]]

Solids whose surface mesh crosses itself.

Every pair of a solid's triangles that share no vertex (by index, or by position within the tolerance) is tested exactly for a crossing: a wall thinner than the faceting whose two faces have been meshed through each other. Triangles that touch, along an edge, at a point or within the tolerance, do not count, and degenerate ones are skipped.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

Global [x, y, z] vertex array.

required
solids Sequence[tuple[int, Sequence[Sequence[int]]]]

(solid_id, triangles) per solid, each its full closed boundary as [i, j, k] indices into vertices.

required
rel_tol float

The contact tolerance as a fraction of the diagonal of the box around the solids' vertices; the default is the tolerance the surface assembler welds vertices at.

1e-06
samples int

Crossing points to return per solid at most, deepest first.

4
threads Optional[int]

Threads to run the check on, or None (the default) for rayon's global pool.

None

Returns:

Type Description
list[tuple[int, int, float, list[list[float]]]]

[(solid_id, pairs, max_depth, [[x, y, z], ...]), ...] for every

list[tuple[int, int, float, list[list[float]]]]

solid that crosses itself: the number of crossing triangle pairs, how

list[tuple[int, int, float, list[list[float]]]]

far the deepest pair passes through each other, and the deepest

list[tuple[int, int, float, list[list[float]]]]

crossing points.

Raises:

Type Description
ValueError

If a triangle indexes past vertices, a vertex is not finite, or rel_tol is negative.

Source code in yamc/_core/__init__.pyi
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
def solid_self_intersections(vertices: typing.Sequence[typing.Sequence[builtins.float]], solids: typing.Sequence[tuple[builtins.int, typing.Sequence[typing.Sequence[builtins.int]]]], rel_tol: builtins.float = 1e-06, samples: builtins.int = 4, threads: typing.Optional[builtins.int] = None) -> builtins.list[tuple[builtins.int, builtins.int, builtins.float, builtins.list[builtins.list[builtins.float]]]]:
    r"""
    Solids whose surface mesh crosses itself.

    Every pair of a solid's triangles that share no vertex (by index, or by
    position within the tolerance) is tested exactly for a crossing: a wall
    thinner than the faceting whose two faces have been meshed through each
    other. Triangles that touch, along an edge, at a point or within the
    tolerance, do not count, and degenerate ones are skipped.

    Args:
        vertices: Global ``[x, y, z]`` vertex array.
        solids: ``(solid_id, triangles)`` per solid, each its full closed
            boundary as ``[i, j, k]`` indices into ``vertices``.
        rel_tol: The contact tolerance as a fraction of the diagonal of the
            box around the solids' vertices; the default is the tolerance
            the surface assembler welds vertices at.
        samples: Crossing points to return per solid at most, deepest first.
        threads: Threads to run the check on, or ``None`` (the default) for
            rayon's global pool.

    Returns:
        ``[(solid_id, pairs, max_depth, [[x, y, z], ...]), ...]`` for every
        solid that crosses itself: the number of crossing triangle pairs, how
        far the deepest pair passes through each other, and the deepest
        crossing points.

    Raises:
        ValueError: If a triangle indexes past ``vertices``, a vertex is not
            finite, or ``rel_tol`` is negative.
    """

solid_shared_volume

solid_shared_volume(vertices: Sequence[Sequence[float]], triangles_a: Sequence[Sequence[int]], triangles_b: Sequence[Sequence[int]], tolerance: float, samples: int = 200000, seed: int = 1, threads: Optional[int] = None) -> tuple[float, float, Optional[int]]

Volume shared by two solids' closed surface meshes.

Parameters:

Name Type Description Default
vertices Sequence[Sequence[float]]

Global [x, y, z] vertex array.

required
triangles_a Sequence[Sequence[int]]

Closed boundary of the first solid, as indices into vertices.

required
triangles_b Sequence[Sequence[int]]

Closed boundary of the second solid.

required
tolerance float

Distance below which the two surfaces count as touching.

required
samples int

Points sampled when the volume has to be estimated.

200000
seed int

Seed of the deterministic sampler.

1
threads Optional[int]

Threads to run the sampling on, or None (the default) for rayon's global pool.

None

Returns:

Type Description
float

(volume, std_err, embedded). When the surfaces never come within

float

tolerance of each other and one solid lies inside the other,

Optional[int]

embedded is 0 or 1 (that solid is wholly shared; volume

tuple[float, float, Optional[int]]

is then 0 and the caller supplies the solid's own volume). Otherwise

tuple[float, float, Optional[int]]

embedded is None and volume is a Monte Carlo estimate with

tuple[float, float, Optional[int]]

standard error std_err.

Source code in yamc/_core/__init__.pyi
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
def solid_shared_volume(vertices: typing.Sequence[typing.Sequence[builtins.float]], triangles_a: typing.Sequence[typing.Sequence[builtins.int]], triangles_b: typing.Sequence[typing.Sequence[builtins.int]], tolerance: builtins.float, samples: builtins.int = 200000, seed: builtins.int = 1, threads: typing.Optional[builtins.int] = None) -> tuple[builtins.float, builtins.float, typing.Optional[builtins.int]]:
    r"""
    Volume shared by two solids' closed surface meshes.

    Args:
        vertices: Global ``[x, y, z]`` vertex array.
        triangles_a: Closed boundary of the first solid, as indices into
            ``vertices``.
        triangles_b: Closed boundary of the second solid.
        tolerance: Distance below which the two surfaces count as touching.
        samples: Points sampled when the volume has to be estimated.
        seed: Seed of the deterministic sampler.
        threads: Threads to run the sampling on, or ``None`` (the default) for
            rayon's global pool.

    Returns:
        ``(volume, std_err, embedded)``. When the surfaces never come within
        ``tolerance`` of each other and one solid lies inside the other,
        ``embedded`` is ``0`` or ``1`` (that solid is wholly shared; ``volume``
        is then 0 and the caller supplies the solid's own volume). Otherwise
        ``embedded`` is ``None`` and ``volume`` is a Monte Carlo estimate with
        standard error ``std_err``.
    """

transmute

transmute(materials: Sequence[Material], schedules: PulseSchedule | Sequence[PulseSchedule], data_uncertainty: Optional[DataUncertainty] = None, self_shielding_chord: Optional[float] = None, self_shielding_shape: SphereLump | CubeLump | FoilLump | CylinderLump | WireLump | None = None, displacement_damage: bool = False, displacement_energies: Optional[Mapping[str, float]] = None, product_threshold: float = 1e-12, processing: Optional[Processing] = None) -> TransmutationResults

Transmute several materials over one timeline in one call.

The plural of Material.transmute, for a mesh from a transport run, a component broken into regions, or a sweep over compositions. The answer for each material is exactly what material.transmute(schedule) gives it, and the result is one TransmutationResults keyed by each material's id, the same shape Model.simulate_transmutation returns.

What a Python loop would repeat is done once instead: the chain is read once, each nuclide's cross sections are decoded once and shared by every material that needs them, and a multigroup collapse runs once for every distinct combination of spectrum, composition, temperature and shielding. Cells of one steel that saw the same spectrum share a collapse, whatever their flux magnitudes. results.collapse_reuse says how many collapses were shared. The materials' solves then run in parallel.

Parameters:

Name Type Description Default
materials list[Material]

The materials, each with a distinct id, since the results are keyed by it. Every material has one from construction; two share one only when one was given the other's explicitly or is a copy of it, as a material a transmutation result returns is of its original. As with Material.transmute, the cross sections each needs are loaded into it and kept, and the composition is not modified.

required
schedules PulseSchedule | list[PulseSchedule]

One schedule for every material, or one per material in the same order. Each material's schedule carries its own spectra (the pulse sources) and flux magnitudes (the pulse rates), which is how each cell of a mesh gets its own flux. They must share one timeline, the same durations and irradiation on the same steps, because the result has one series of times.

required
data_uncertainty DataUncertainty

Nuclear-data uncertainty, applied to every material as Material.transmute applies it to one. The same seed perturbs a given evaluation the same way in every material.

None
self_shielding_chord float

One chord length 4V/S in cm, for every material. See Material.transmute.

None
self_shielding_shape SphereLump | CubeLump | FoilLump | CylinderLump | WireLump

One lump shape for every material, turned into a chord through each material's own volume. Give this or self_shielding_chord, not both.

None
displacement_damage bool

Also compute each material's displacement damage, damage energy per atom and NRT dpa. See Material.transmute. Off by default, and then nothing about the solve or the data it loads changes.

False
displacement_energies dict[str, float]

Displacement threshold energies in eV by element symbol, replacing the defaults, for every material. Needs displacement_damage=True.

None
product_threshold float

The atom fraction, or share of a decay quantity, a product must reach for its cross sections to be loaded and its reactions solved, applied to each material's own schedule. Default 1e-12. See Material.transmute.

1e-12
processing Processing

Removals, transfers between materials and feeds. The materials a transfer links are solved together each step. A material it names that is not in materials, a storage tank say, is carried unirradiated and reported under its own id. Not yet combined with data_uncertainty.

None

Returns:

Name Type Description
TransmutationResults TransmutationResults

Keyed by each material's id. Per material, get_source_rates(id) gives its flux magnitudes and get_self_shielding_info(id) its shielding report.

Raises:

Type Description
ValueError

If two materials share an id, the timelines differ, the number of schedules does not match the number of materials, or any single material would fail Material.transmute, in which case the message names the material.

TypeError

If schedules is neither a PulseSchedule nor a list of them, or the same Material object is given twice.

Examples:

>>> schedules = [
...     yani.PulseSchedule([
...         yani.Pulse(rate=flux[i], duration=(1, "y"), source=spectra[i]),
...         yani.Cooldown(duration=(1, "d")),
...     ])
...     for i in range(len(cells))
... ]
>>> results = yani.transmute(cells, schedules)
>>> results.get_final_material(cells[3].id)
Source code in yamc/_core/__init__.pyi
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
def transmute(materials: typing.Sequence[Material], schedules: PulseSchedule | typing.Sequence[PulseSchedule], data_uncertainty: typing.Optional[DataUncertainty] = None, self_shielding_chord: typing.Optional[builtins.float] = None, self_shielding_shape: shapes.SphereLump | shapes.CubeLump | shapes.FoilLump | shapes.CylinderLump | shapes.WireLump | None = None, displacement_damage: builtins.bool = False, displacement_energies: typing.Optional[typing.Mapping[builtins.str, builtins.float]] = None, product_threshold: builtins.float = 1e-12, processing: typing.Optional[Processing] = None) -> TransmutationResults:
    r"""
    Transmute several materials over one timeline in one call.

    The plural of ``Material.transmute``, for a mesh from a transport run, a
    component broken into regions, or a sweep over compositions. The answer for
    each material is exactly what ``material.transmute(schedule)`` gives it, and
    the result is one ``TransmutationResults`` keyed by each material's ``id``,
    the same shape ``Model.simulate_transmutation`` returns.

    What a Python loop would repeat is done once instead: the chain is read
    once, each nuclide's cross sections are decoded once and shared by every
    material that needs them, and a multigroup collapse runs once for every
    distinct combination of spectrum, composition, temperature and shielding.
    Cells of one steel that saw the same spectrum share a collapse, whatever
    their flux magnitudes. ``results.collapse_reuse`` says how many collapses
    were shared. The materials' solves then run in parallel.

    Args:
        materials (list[Material]): The materials, each with a distinct
            ``id``, since the results are keyed by it. Every material has one
            from construction; two share one only when one was given the
            other's explicitly or is a copy of it, as a material a
            transmutation result returns is of its original. As with
            ``Material.transmute``, the cross sections each needs are loaded
            into it and kept, and the composition is not modified.
        schedules (PulseSchedule | list[PulseSchedule]): One schedule for every
            material, or one per material in the same order. Each material's
            schedule carries its own spectra (the pulse sources) and flux
            magnitudes (the pulse rates), which is how each cell of a mesh gets
            its own flux. They must share one timeline, the same durations and
            irradiation on the same steps, because the result has one series of
            times.
        data_uncertainty (DataUncertainty, optional): Nuclear-data uncertainty,
            applied to every material as ``Material.transmute`` applies it to
            one. The same seed perturbs a given evaluation the same way in every
            material.
        self_shielding_chord (float, optional): One chord length ``4V/S`` in cm,
            for every material. See ``Material.transmute``.
        self_shielding_shape (SphereLump | CubeLump | FoilLump | CylinderLump | WireLump, optional):
            One lump shape for every material, turned into a chord through each
            material's own ``volume``. Give this or ``self_shielding_chord``,
            not both.
        displacement_damage (bool): Also compute each material's displacement
            damage, damage energy per atom and NRT dpa. See
            ``Material.transmute``. Off by default, and then nothing about the
            solve or the data it loads changes.
        displacement_energies (dict[str, float], optional): Displacement
            threshold energies in eV by element symbol, replacing the defaults,
            for every material. Needs ``displacement_damage=True``.
        product_threshold (float): The atom fraction, or share of a decay
            quantity, a product must reach for its cross sections to be loaded
            and its reactions solved, applied to each material's own schedule.
            Default 1e-12. See ``Material.transmute``.
        processing (Processing, optional): Removals, transfers between
            materials and feeds. The materials a transfer links are solved
            together each step. A material it names that is not in
            ``materials``, a storage tank say, is carried unirradiated and
            reported under its own id. Not yet combined with
            ``data_uncertainty``.

    Returns:
        TransmutationResults: Keyed by each material's ``id``. Per material,
            ``get_source_rates(id)`` gives its flux magnitudes and
            ``get_self_shielding_info(id)`` its shielding report.

    Raises:
        ValueError: If two materials share an id, the timelines differ, the
            number of schedules does not match the number of materials, or
            any single material would fail ``Material.transmute``, in which
            case the message names the material.
        TypeError: If ``schedules`` is neither a PulseSchedule nor a list of
            them, or the same Material object is given twice.

    Examples:
        >>> schedules = [
        ...     yani.PulseSchedule([
        ...         yani.Pulse(rate=flux[i], duration=(1, "y"), source=spectra[i]),
        ...         yani.Cooldown(duration=(1, "d")),
        ...     ])
        ...     for i in range(len(cells))
        ... ]
        >>> results = yani.transmute(cells, schedules)
        >>> results.get_final_material(cells[3].id)
    """

verify_library

verify_library(path: str) -> dict

Check a nuclear-data library folder against its manifest.json.

Re-hashes every file the manifest lists and compares its size and sha256 with the manifest, then looks for files the manifest does not list. Loading data from a library folder only checks the sizes of the files it reads; this is the full check, for a library kept for offline use or built locally.

Parameters

path : str A library folder: manifest.json beside the neutron/, photon/, photonuclear/ and transmutation/ folders it describes, laid out as each release in :func:cache_dir is. A release folder in the cache holds only the files runs have downloaded, so the rest are reported missing.

Returns

dict keyword, release, format_version and manifest_sha256 identify the release the manifest describes, and file_count and total_bytes count what it lists. missing (listed but absent), changed (listed, with another size or sha256) and unlisted (in the release's <Name>.arrow/ folders, or a particle's index.json, but not listed) are sorted paths relative to the folder. ok is True when all three are empty.

An unlisted file fails the check: results record the manifest's sha256
as the identity of the library a run read, and a file the manifest
does not list is data that identity does not cover. Files outside the
release's folders, such as a local build's ``.build/`` folder, are not
looked at.

Raises

RuntimeError If path is not a folder or holds no manifest.json, if the manifest is not a version 1 release manifest or is in a format_version this build does not read, or if a listed file cannot be read.

Source code in yamc/_core/__init__.pyi
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
def verify_library(path: builtins.str) -> dict:
    r"""
    Check a nuclear-data library folder against its ``manifest.json``.

    Re-hashes every file the manifest lists and compares its size and sha256
    with the manifest, then looks for files the manifest does not list.
    Loading data from a library folder only checks the sizes of the files it
    reads; this is the full check, for a library kept for offline use or built
    locally.

    Parameters
    ----------
    path : str
        A library folder: ``manifest.json`` beside the ``neutron/``,
        ``photon/``, ``photonuclear/`` and ``transmutation/`` folders it
        describes, laid out as each release in :func:`cache_dir` is. A release
        folder in the cache holds only the files runs have downloaded, so the
        rest are reported missing.

    Returns
    -------
    dict
        ``keyword``, ``release``, ``format_version`` and ``manifest_sha256``
        identify the release the manifest describes, and ``file_count`` and
        ``total_bytes`` count what it lists. ``missing`` (listed but absent),
        ``changed`` (listed, with another size or sha256) and ``unlisted``
        (in the release's ``<Name>.arrow/`` folders, or a particle's
        ``index.json``, but not listed) are sorted paths relative to the
        folder. ``ok`` is ``True`` when all three are empty.

        An unlisted file fails the check: results record the manifest's sha256
        as the identity of the library a run read, and a file the manifest
        does not list is data that identity does not cover. Files outside the
        release's folders, such as a local build's ``.build/`` folder, are not
        looked at.

    Raises
    ------
    RuntimeError
        If ``path`` is not a folder or holds no ``manifest.json``, if the
        manifest is not a version 1 release manifest or is in a
        ``format_version`` this build does not read, or if a listed file
        cannot be read.
    """

available_nuclear_data_libraries

available_nuclear_data_libraries() -> dict

What each hosted nuclear data library provides, keyed by library keyword.

Read from each library's release manifest, which lists every file the release publishes, so this downloads no data: only the small release pointer and the manifest, which are cached after the first call. The release is the one a calculation would read now, or, with the data origin unreachable, the newest cached one.

Every list is complete, so an empty list means the library has none of that: "photon": [] says it publishes no photo-atomic data, not that it was not looked at. A library that could not be resolved at all has None for every entry and its reason under "error".

Each library's entry is a dict:

  • release: the release identifier, and offline: whether it is the newest cached release because the origin could not be reached;
  • neutron: nuclides with neutron cross sections;
  • neutron_covariances: per kind, the nuclides that carry it: cross_section (MF=33), resonance_parameters (MF=32), angular_distribution (MF=34), nubar (MF=31) and fission_spectrum (MF=35);
  • thermal_scattering: thermal scattering tables;
  • photon: elements with photo-atomic data, what photon transport reads;
  • photonuclear: targets with photonuclear data, a different thing from photon;
  • decay, reactions, fission_yields, isomeric_branching: whether the library publishes that transmutation subsection;
  • sources: the upstream files the release was built from, each a dict with name, bytes and sha256.

Returns:

Type Description
dict

dict[str, dict]: Per library keyword, what it provides.

Examples:

>>> libraries = yani.available_nuclear_data_libraries()
>>> list(libraries)
['tendl-2025', 'tendl-2017', 'fendl-3.2d', 'endf-b8.1', 'jeff-4.0', 'jendl-5.0', 'irdff-ii']
>>> libraries["jeff-4.0"]["photon"]
[]
>>> "Fe56" in libraries["endf-b8.1"]["neutron_covariances"]["cross_section"]
True
Source code in yamc/_core/__init__.pyi
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
def available_nuclear_data_libraries() -> dict:
    r"""
    What each hosted nuclear data library provides, keyed by library keyword.

    Read from each library's release manifest, which lists every file the
    release publishes, so this downloads no data: only the small release
    pointer and the manifest, which are cached after the first call. The
    release is the one a calculation would read now, or, with the data
    origin unreachable, the newest cached one.

    Every list is complete, so an empty list means the library has none of
    that: ``"photon": []`` says it publishes no photo-atomic data, not that it
    was not looked at. A library that could not be resolved at all has
    ``None`` for every entry and its reason under ``"error"``.

    Each library's entry is a dict:

    - ``release``: the release identifier, and ``offline``: whether it is the
      newest cached release because the origin could not be reached;
    - ``neutron``: nuclides with neutron cross sections;
    - ``neutron_covariances``: per kind, the nuclides that carry it:
      ``cross_section`` (MF=33), ``resonance_parameters`` (MF=32),
      ``angular_distribution`` (MF=34), ``nubar`` (MF=31) and
      ``fission_spectrum`` (MF=35);
    - ``thermal_scattering``: thermal scattering tables;
    - ``photon``: elements with photo-atomic data, what photon transport
      reads;
    - ``photonuclear``: targets with photonuclear data, a different thing
      from ``photon``;
    - ``decay``, ``reactions``, ``fission_yields``, ``isomeric_branching``:
      whether the library publishes that transmutation subsection;
    - ``sources``: the upstream files the release was built from, each a dict
      with ``name``, ``bytes`` and ``sha256``.

    Returns:
        dict[str, dict]: Per library keyword, what it provides.

    Examples:
        >>> libraries = yani.available_nuclear_data_libraries()
        >>> list(libraries)
        ['tendl-2025', 'tendl-2017', 'fendl-3.2d', 'endf-b8.1', 'jeff-4.0', 'jendl-5.0', 'irdff-ii']
        >>> libraries["jeff-4.0"]["photon"]
        []
        >>> "Fe56" in libraries["endf-b8.1"]["neutron_covariances"]["cross_section"]
        True
    """

lookup_photon_cross_section_data

lookup_photon_cross_section_data(element: str) -> Optional[str]

Resolve one photon element from the explicit photon selection only.

Source code in yamc/_core/__init__.pyi
9482
9483
9484
9485
def lookup_photon_cross_section_data(element: builtins.str) -> typing.Optional[builtins.str]:
    r"""
    Resolve one photon element from the explicit photon selection only.
    """

lookup_neutron_cross_section_data

lookup_neutron_cross_section_data(nuclide: str) -> Optional[str]

Look up the cross-section data path for a single nuclide, applying the global default if no per-nuclide entry is set.

Source code in yamc/_core/__init__.pyi
9476
9477
9478
9479
9480
def lookup_neutron_cross_section_data(nuclide: builtins.str) -> typing.Optional[builtins.str]:
    r"""
    Look up the cross-section data path for a single nuclide, applying the global
    default if no per-nuclide entry is set.
    """

set_neutron_cross_section_data_entry

set_neutron_cross_section_data_entry(nuclide_or_keyword: str, path: Optional[str] = None) -> None

Set the cross-section data path for a single nuclide, or set the global default if path is omitted and nuclide_or_keyword is a library keyword / directory.

Source code in yamc/_core/__init__.pyi
9751
9752
9753
9754
9755
9756
def set_neutron_cross_section_data_entry(nuclide_or_keyword: builtins.str, path: typing.Optional[builtins.str] = None) -> None:
    r"""
    Set the cross-section data path for a single nuclide, or set the global default
    if ``path`` is omitted and ``nuclide_or_keyword`` is a library keyword /
    directory.
    """

Source distributions

The spatial, energy and angular distributions live in the yamc.sources submodule, along with the fusion-spectrum, parametric tokamak and stellarator plasma builders. Usage examples are under Sources.

Discrete

Discrete(energies: Sequence[float], probabilities: Sequence[float])

Discrete energy distribution with specific energies and their probabilities.

Create a discrete energy distribution.

Parameters:

Name Type Description Default
energies Sequence[float]

List of energy values in eV.

required
probabilities Sequence[float]

Relative probability for each energy. Normalized internally, so only the relative values matter.

required

Returns:

Name Type Description
Discrete Discrete

A discrete energy distribution.

Raises:

Type Description
ValueError

If energies and probabilities have different lengths, if any energy or probability is NaN or infinite, if any probability is negative, or if all are zero. The message names the entry and its value.

Examples:

>>> import yamc
>>> # 14.06 MeV neutrons (D-T fusion)
>>> energy_dist = yamc.Discrete([14.06e6], [1.0])
Source code in yamc/_core/sources.pyi
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def __new__(cls, energies: typing.Sequence[builtins.float], probabilities: typing.Sequence[builtins.float]) -> Discrete:
    r"""
    Create a discrete energy distribution.

    Args:
        energies: List of energy values in eV.
        probabilities: Relative probability for each energy. Normalized
            internally, so only the relative values matter.

    Returns:
        Discrete: A discrete energy distribution.

    Raises:
        ValueError: If energies and probabilities have different lengths, if
                    any energy or probability is NaN or infinite, if any
                    probability is negative, or if all are zero. The
                    message names the entry and its value.

    Examples:
        >>> import yamc
        >>> # 14.06 MeV neutrons (D-T fusion)
        >>> energy_dist = yamc.Discrete([14.06e6], [1.0])
    """

energies property

energies: list[float]

Get the energy values.

Returns:

Type Description
list[float]

List[float]: Energy values in eV.

probabilities property

probabilities: list[float]

Get the probability values.

Returns:

Type Description
list[float]

List[float]: Probability for each energy.

sample

sample() -> float

Sample an energy value from the distribution.

Returns:

Name Type Description
float float

Sampled energy in eV.

Source code in yamc/_core/sources.pyi
77
78
79
80
81
82
83
def sample(self) -> builtins.float:
    r"""
    Sample an energy value from the distribution.

    Returns:
        float: Sampled energy in eV.
    """

Histogram

Histogram(boundaries: Any, probabilities: Sequence[float])

Histogram (piecewise-constant) energy distribution over energy bins.

Create a histogram (piecewise-constant) energy distribution.

Each bin i spans boundaries[i] to boundaries[i + 1] and holds probability mass probabilities[i]; an energy is sampled by choosing a bin in proportion to its mass and then drawing uniformly within it.

Parameters:

Name Type Description Default
boundaries Any

Either explicit energy bin edges in eV (length n + 1, strictly ascending) or the name of a built-in group structure (e.g. "CCFE-709", "VITAMIN-J-175"), whose edges are used.

required
probabilities Sequence[float]

Relative probability mass for each of the n bins. Normalized internally, so only the relative values matter (a raw multigroup flux per group can be passed directly).

required

Returns:

Name Type Description
Histogram Histogram

A histogram energy distribution.

Raises:

Type Description
ValueError

If a named group structure is unknown, if boundaries is not exactly one longer than probabilities, if the boundaries are not strictly ascending, if any probability is negative, or if all are zero.

Examples:

>>> import yamc
>>> # 30% of source neutrons in [0, 1] MeV, 70% in [1, 20] MeV
>>> energy_dist = yamc.sources.Histogram([0.0, 1e6, 20e6], [0.3, 0.7])
>>> # or from a named group structure (709 per-group weights)
>>> energy_dist = yamc.sources.Histogram("CCFE-709", flux_709)
Source code in yamc/_core/sources.pyi
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def __new__(cls, boundaries: typing.Any, probabilities: typing.Sequence[builtins.float]) -> Histogram:
    r"""
    Create a histogram (piecewise-constant) energy distribution.

    Each bin ``i`` spans ``boundaries[i]`` to ``boundaries[i + 1]`` and holds
    probability mass ``probabilities[i]``; an energy is sampled by choosing a
    bin in proportion to its mass and then drawing uniformly within it.

    Args:
        boundaries: Either explicit energy bin edges in eV (length ``n + 1``,
            strictly ascending) or the name of a built-in group structure
            (e.g. ``"CCFE-709"``, ``"VITAMIN-J-175"``), whose edges are used.
        probabilities: Relative probability mass for each of the ``n`` bins.
            Normalized internally, so only the relative values matter (a raw
            multigroup flux per group can be passed directly).

    Returns:
        Histogram: A histogram energy distribution.

    Raises:
        ValueError: If a named group structure is unknown, if ``boundaries``
            is not exactly one longer than ``probabilities``, if the
            boundaries are not strictly ascending, if any probability is
            negative, or if all are zero.

    Examples:
        >>> import yamc
        >>> # 30% of source neutrons in [0, 1] MeV, 70% in [1, 20] MeV
        >>> energy_dist = yamc.sources.Histogram([0.0, 1e6, 20e6], [0.3, 0.7])
        >>> # or from a named group structure (709 per-group weights)
        >>> energy_dist = yamc.sources.Histogram("CCFE-709", flux_709)
    """

boundaries property

boundaries: list[float]

Get the bin boundaries.

Returns:

Type Description
list[float]

List[float]: Energy bin edges in eV, length n + 1.

probabilities property

probabilities: list[float]

Get the per-bin probabilities, as supplied.

Returns:

Type Description
list[float]

List[float]: Relative probability mass for each bin.

sample

sample() -> float

Sample an energy value from the distribution.

Returns:

Name Type Description
float float

Sampled energy in eV.

Source code in yamc/_core/sources.pyi
143
144
145
146
147
148
149
def sample(self) -> builtins.float:
    r"""
    Sample an energy value from the distribution.

    Returns:
        float: Sampled energy in eV.
    """

Uniform

Uniform(low: float, high: float)

Uniform energy distribution between two bounds.

Create a uniform energy distribution.

Parameters:

Name Type Description Default
low float

Lower energy bound in eV.

required
high float

Upper energy bound in eV.

required

Returns:

Name Type Description
Uniform Uniform

A uniform energy distribution.

Raises:

Type Description
ValueError

If low or high is NaN or infinite, or if low >= high (lower bound must be less than upper bound).

Examples:

>>> import yamc
>>> # Uniform distribution from 1 MeV to 20 MeV
>>> energy_dist = yamc.Uniform(1e6, 20e6)
Source code in yamc/_core/sources.pyi
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def __new__(cls, low: builtins.float, high: builtins.float) -> Uniform:
    r"""
    Create a uniform energy distribution.

    Args:
        low: Lower energy bound in eV.
        high: Upper energy bound in eV.

    Returns:
        Uniform: A uniform energy distribution.

    Raises:
        ValueError: If low or high is NaN or infinite, or if low >= high
            (lower bound must be less than upper bound).

    Examples:
        >>> import yamc
        >>> # Uniform distribution from 1 MeV to 20 MeV
        >>> energy_dist = yamc.Uniform(1e6, 20e6)
    """

low property

low: float

Get the lower energy bound.

Returns:

Name Type Description
float float

Lower bound in eV.

high property

high: float

Get the upper energy bound.

Returns:

Name Type Description
float float

Upper bound in eV.

sample

sample() -> float

Sample an energy value from the distribution.

Returns:

Name Type Description
float float

Sampled energy in eV, uniformly distributed between low and high.

Source code in yamc/_core/sources.pyi
197
198
199
200
201
202
203
def sample(self) -> builtins.float:
    r"""
    Sample an energy value from the distribution.

    Returns:
        float: Sampled energy in eV, uniformly distributed between low and high.
    """

Normal

Normal(mean: float, std_dev: float)

Normal (Gaussian) energy distribution.

Create a normal (Gaussian) energy distribution.

Parameters:

Name Type Description Default
mean float

Mean energy in eV.

required
std_dev float

Standard deviation in eV (must be positive).

required

Returns:

Name Type Description
Normal Normal

A normal energy distribution.

Raises:

Type Description
ValueError

If mean or std_dev is NaN or infinite, or if std_dev is not positive.

Examples:

>>> import yamc
>>> # Normal distribution centered at 14.06 MeV
>>> energy_dist = yamc.Normal(14.06e6, 0.1e6)
Source code in yamc/_core/sources.pyi
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def __new__(cls, mean: builtins.float, std_dev: builtins.float) -> Normal:
    r"""
    Create a normal (Gaussian) energy distribution.

    Args:
        mean: Mean energy in eV.
        std_dev: Standard deviation in eV (must be positive).

    Returns:
        Normal: A normal energy distribution.

    Raises:
        ValueError: If mean or std_dev is NaN or infinite, or if std_dev is
            not positive.

    Examples:
        >>> import yamc
        >>> # Normal distribution centered at 14.06 MeV
        >>> energy_dist = yamc.Normal(14.06e6, 0.1e6)
    """

mean property

mean: float

Get the mean energy.

Returns:

Name Type Description
float float

Mean energy in eV.

std_dev property

std_dev: float

Get the standard deviation.

Returns:

Name Type Description
float float

Standard deviation in eV.

sample

sample() -> float

Sample an energy value from the distribution.

Returns:

Name Type Description
float float

Sampled energy in eV.

Source code in yamc/_core/sources.pyi
251
252
253
254
255
256
257
def sample(self) -> builtins.float:
    r"""
    Sample an energy value from the distribution.

    Returns:
        float: Sampled energy in eV.
    """

Isotropic

Isotropic()

Isotropic angular distribution (uniform over 4π steradians).

Create an isotropic angular distribution.

Returns:

Name Type Description
Isotropic Isotropic

An isotropic angular distribution.

Examples:

>>> import yamc
>>> angle_dist = yamc.Isotropic()
Source code in yamc/_core/sources.pyi
269
270
271
272
273
274
275
276
277
278
279
def __new__(cls) -> Isotropic:
    r"""
    Create an isotropic angular distribution.

    Returns:
        Isotropic: An isotropic angular distribution.

    Examples:
        >>> import yamc
        >>> angle_dist = yamc.Isotropic()
    """

sample

sample() -> list[float]

Sample a direction vector from the distribution.

Returns:

Type Description
list[float]

List[float]: Unit direction vector [u, v, w].

Source code in yamc/_core/sources.pyi
280
281
282
283
284
285
286
def sample(self) -> builtins.list[builtins.float]:
    r"""
    Sample a direction vector from the distribution.

    Returns:
        List[float]: Unit direction vector [u, v, w].
    """

Monodirectional

Monodirectional(direction: Sequence[float])

Monodirectional angular distribution (single fixed direction).

Create a monodirectional angular distribution.

Parameters:

Name Type Description Default
direction Sequence[float]

Direction vector [u, v, w]. Will be normalized automatically.

required

Returns:

Name Type Description
Monodirectional Monodirectional

A monodirectional angular distribution.

Raises:

Type Description
ValueError

If direction is the zero vector or has a NaN or infinite component, so it points nowhere.

Examples:

>>> import yamc
>>> # Particles emitted in +z direction
>>> angle_dist = yamc.Monodirectional([0.0, 0.0, 1.0])
Source code in yamc/_core/sources.pyi
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def __new__(cls, direction: typing.Sequence[builtins.float]) -> Monodirectional:
    r"""
    Create a monodirectional angular distribution.

    Args:
        direction: Direction vector [u, v, w]. Will be normalized automatically.

    Returns:
        Monodirectional: A monodirectional angular distribution.

    Raises:
        ValueError: If ``direction`` is the zero vector or has a NaN or
            infinite component, so it points nowhere.

    Examples:
        >>> import yamc
        >>> # Particles emitted in +z direction
        >>> angle_dist = yamc.Monodirectional([0.0, 0.0, 1.0])
    """

direction property writable

direction: list[float]

Get the direction vector.

Returns:

Type Description
list[float]

List[float]: Unit direction vector [u, v, w].

sample

sample() -> list[float]

Sample a direction vector from the distribution.

Returns:

Type Description
list[float]

List[float]: Unit direction vector [u, v, w] (always the reference direction).

Source code in yamc/_core/sources.pyi
337
338
339
340
341
342
343
def sample(self) -> builtins.list[builtins.float]:
    r"""
    Sample a direction vector from the distribution.

    Returns:
        List[float]: Unit direction vector [u, v, w] (always the reference direction).
    """

CylindricalRing

CylindricalRing(*, radius: Discrete | Uniform | Normal, phi: Discrete | Uniform | Normal, z: Discrete | Uniform | Normal, origin: Optional[Sequence[float]] = None)

Cylindrical spatial distribution (ring, annulus, or full cylinder).

Samples radius, phi, and z independently from univariate distributions in a cylindrical coordinate system centered at origin.

Positions are computed as

x = origin[0] + radius * cos(phi) y = origin[1] + radius * sin(phi) z = origin[2] + z

Parameters:

Name Type Description Default
radius Discrete | Uniform | Normal

Distribution of radial coordinates (e.g., yamc.Discrete([300], [1]) for a thin ring, or yamc.Uniform(200, 400) for an annulus).

required
phi Discrete | Uniform | Normal

Distribution of azimuthal angle in radians (e.g., yamc.Uniform(0, 2*math.pi) for full ring).

required
z Discrete | Uniform | Normal

Distribution of axial coordinates (e.g., yamc.Discrete([0], [1]) for the midplane).

required
origin Optional[Sequence[float]]

Center of the cylindrical reference frame [x, y, z] in cm. Defaults to [0, 0, 0].

None

Raises:

Type Description
ValueError

If origin has a NaN or infinite coordinate, or a radius, phi or z given as a number is NaN or infinite.

Examples:

>>> import yamc, math
>>> # Ring source at radius=300 cm in the midplane
>>> space = yamc.CylindricalRing(
...     radius=yamc.Discrete([300], [1]),
...     phi=yamc.Uniform(0, 2*math.pi),
...     z=yamc.Discrete([0], [1]),
... )
Source code in yamc/_core/sources.pyi
406
def __new__(cls, *, radius: Discrete | Uniform | Normal, phi: Discrete | Uniform | Normal, z: Discrete | Uniform | Normal, origin: typing.Optional[typing.Sequence[builtins.float]] = None) -> CylindricalRing: ...

origin property

origin: list[float]

Center of the cylindrical reference frame, [x, y, z] in cm.

radius property

radius: Any

Radial distribution.

phi property

phi: Any

Azimuthal-angle distribution (radians).

z property

z: Any

Axial distribution.

sample

sample() -> list[float]

Sample a position from the distribution.

Returns:

Type Description
list[float]

List[float]: Position vector [x, y, z] in cm.

Source code in yamc/_core/sources.pyi
407
408
409
410
411
412
413
def sample(self) -> builtins.list[builtins.float]:
    r"""
    Sample a position from the distribution.

    Returns:
        List[float]: Position vector [x, y, z] in cm.
    """

MeshDistribution

MeshDistribution(mesh: Any, strengths: Optional[Sequence[float]] = None, cells: Optional[Any] = None, materials: Optional[Any] = None)

A source spread over the elements of a mesh.

Each element emits in proportion to its strength, from a point uniform within it. Pass it as position= to NeutronSource or PhotonSource.

Parameters:

Name Type Description Default
mesh Any

A RegularRectangularMesh, RegularCylindricalMesh or a tet MeshGeometry.

required
strengths Optional[Sequence[float]]

One non-negative strength per element (e.g. decay photons per second in each voxel), in the order a tally on the mesh numbers its bins, so a mesh tally's mean can be passed directly. For a MeshGeometry this is one per tetrahedron. Defaults to each element's volume: uniform over the mesh.

None
cells Optional[Any]

A Cell or list of them. Each element then emits only from its points in these cells, keeping its own strength: an R2S voxel's decay photons are born in the activated cells under it, not in the void beside them.

None
materials Optional[Any]

A Material or list of them, as cells but for the cells filled with them. Give cells or materials, not both. Both apply where the source meets a geometry, in a Model; sample() has no geometry and draws from the whole element.

None

Raises:

Type Description
ValueError

If strengths has the wrong length, a value that is NaN, infinite or negative, or sums to zero; or both cells and materials are given. A run refuses a source whose cells or materials are not in the geometry, or with an emitting element holding none of them.

Examples:

>>> import yamc
>>> mesh = yamc.RegularRectangularMesh([0, 0, 0], [10, 10, 10], [2, 1, 1])
>>> space = yamc.sources.MeshDistribution(mesh, strengths=[3.0, 1.0])
>>> source = yamc.PhotonSource(position=space, energy=1e6)
Source code in yamc/_core/sources.pyi
470
def __new__(cls, mesh: typing.Any, strengths: typing.Optional[typing.Sequence[builtins.float]] = None, cells: typing.Optional[typing.Any] = None, materials: typing.Optional[typing.Any] = None) -> MeshDistribution: ...

total_strength property

total_strength: float

Sum of the element strengths: the source rate when they are rates, to scale per-source-particle tallies by.

num_elements property

num_elements: int

Number of elements in the mesh.

sample

sample() -> list[float]

Sample a position from the distribution, anywhere in the chosen element: cells and materials need the geometry of a Model.

Returns:

Type Description
list[float]

List[float]: Position vector [x, y, z] in cm.

Source code in yamc/_core/sources.pyi
471
472
473
474
475
476
477
478
def sample(self) -> builtins.list[builtins.float]:
    r"""
    Sample a position from the distribution, anywhere in the chosen
    element: ``cells`` and ``materials`` need the geometry of a ``Model``.

    Returns:
        List[float]: Position vector [x, y, z] in cm.
    """

TokamakShape

TokamakShape(*, major_radius: float, minor_radius: float, elongation: float, triangularity: float, shafranov_factor: float)

A tokamak plasma shape: nested flux surfaces with elongation, triangularity and a Shafranov shift, in the parameterisation of Fausser et al., Fus. Eng. Des. 87 (2012) 787.

The flux surface at normalised radius rho (0 on the magnetic axis, 1 on the plasma boundary) has minor radius a = rho * minor_radius. At poloidal angle theta it lies at R = major_radius + a * cos(theta + triangularity * sin(theta)) + shift and Z = elongation * a * sin(theta), where the Shafranov shift shift = shafranov_factor * (1 - rho**2) moves the magnetic axis out by shafranov_factor and falls to zero on the boundary.

These are the five shape arguments of the openmc-plasma-source package's tokamak_source, with the same names and units, made into the one shape argument of tokamak_source here, as StellaratorShape is for stellarator_source.

Parameters:

Name Type Description Default
major_radius float

Plasma major radius (cm).

required
minor_radius float

Plasma minor radius (cm), less than major_radius.

required
elongation float

Plasma elongation (dimensionless).

required
triangularity float

Plasma triangularity (dimensionless), from -1 to 1.

required
shafranov_factor float

Shafranov factor (cm), the outward radial shift of the magnetic axis, less than half the minor radius either way.

required

Raises:

Type Description
ValueError

If a parameter is NaN or infinite (the message names it), a radius or the elongation is not positive, the minor radius is not less than the major radius, the triangularity is outside -1 to 1, or the Shafranov factor is half the minor radius or more.

Examples:

>>> import yamc
>>> shape = yamc.sources.TokamakShape(
...     major_radius=906.0,
...     minor_radius=292.258,
...     elongation=1.557,
...     triangularity=0.270,
...     shafranov_factor=0.44789,
... )
>>> r, z = shape.evaluate(1.0, 0.0)  # the outboard midplane
Source code in yamc/_core/sources.pyi
577
def __new__(cls, *, major_radius: builtins.float, minor_radius: builtins.float, elongation: builtins.float, triangularity: builtins.float, shafranov_factor: builtins.float) -> TokamakShape: ...

major_radius property

major_radius: float

Plasma major radius (cm).

minor_radius property

minor_radius: float

Plasma minor radius (cm).

elongation property

elongation: float

Plasma elongation (dimensionless).

triangularity property

triangularity: float

Plasma triangularity (dimensionless).

shafranov_factor property

shafranov_factor: float

Shafranov factor (cm), the outward radial shift of the magnetic axis.

volume

volume() -> float

Plasma volume (cm^3), inside the boundary rho = 1.

Source code in yamc/_core/sources.pyi
578
579
580
581
def volume(self) -> builtins.float:
    r"""
    Plasma volume (cm^3), inside the boundary ``rho = 1``.
    """

evaluate

evaluate(rho: Any, theta: Any) -> tuple[Any, Any]

Cylindrical (R, Z) in cm at flux coordinates (rho, theta).

Either argument is a float or a sequence of floats; a scalar broadcasts against a sequence, so a whole flux surface or radial chord evaluates in one call.

Parameters:

Name Type Description Default
rho Any

Normalised radius, 0 on the magnetic axis and 1 on the boundary.

required
theta Any

Poloidal angle (radians).

required

Returns:

Type Description
tuple[Any, Any]

An (R, Z) tuple in cm, each a float or a list of floats.

Raises:

Type Description
ValueError

If rho is outside 0 to 1, theta is NaN or infinite, or rho and theta are sequences of different lengths.

Source code in yamc/_core/sources.pyi
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def evaluate(self, rho: typing.Any, theta: typing.Any) -> tuple[typing.Any, typing.Any]:
    r"""
    Cylindrical ``(R, Z)`` in cm at flux coordinates ``(rho, theta)``.

    Either argument is a float or a sequence of floats; a scalar
    broadcasts against a sequence, so a whole flux surface or radial
    chord evaluates in one call.

    Args:
        rho: Normalised radius, 0 on the magnetic axis and 1 on the
            boundary.
        theta: Poloidal angle (radians).

    Returns:
        An ``(R, Z)`` tuple in cm, each a float or a list of floats.

    Raises:
        ValueError: If ``rho`` is outside 0 to 1, ``theta`` is NaN or
            infinite, or ``rho`` and ``theta`` are sequences of different
            lengths.
    """

StellaratorShape

StellaratorShape(*, num_field_periods: int, r_modes: Sequence[Sequence[int]], r_lmn: Sequence[float], z_modes: Sequence[Sequence[int]], z_lmn: Sequence[float])

A stellarator plasma shape as a Fourier-Zernike series, in DESC's conventions.

R(rho, theta, zeta) = sum R_lmn * Z_l^m(rho, theta) * F_n(zeta) and likewise for Z, where Z_l^m is the unnormalised Zernike radial polynomial R_l^|m|(rho) (equal to 1 at rho = 1) times cos(m theta) for m >= 0 or sin(|m| theta) for m < 0, and F_n is cos(n N zeta) for n >= 0 or sin(|n| N zeta) for n < 0, with N the number of field periods. rho is the square root of the normalised toroidal flux and zeta the cylindrical toroidal angle.

A DESC equilibrium's R_lmn / Z_lmn with its R_basis.modes / Z_basis.modes are these coefficients directly, times 100 for cm. StellaratorShape.from_vmec fits a shape to the flux surfaces of a VMEC equilibrium.

Parameters:

Name Type Description Default
num_field_periods int

Number of field periods N.

required
r_modes Sequence[Sequence[int]]

(l, m, n) mode numbers of the R series.

required
r_lmn Sequence[float]

Coefficients of the R series (cm).

required
z_modes Sequence[Sequence[int]]

(l, m, n) mode numbers of the Z series.

required
z_lmn Sequence[float]

Coefficients of the Z series (cm).

required

Raises:

Type Description
ValueError

If a mode is not a Zernike mode (l >= |m|, l - |m| even), a mode is repeated, the lengths differ, a coefficient is NaN or infinite, or the surfaces reach R <= 0, self-intersect or are not nested.

Examples:

>>> import yamc
>>> # A circular torus: R = 600 + 150 rho cos(theta), Z = 150 rho sin(theta)
>>> shape = yamc.sources.StellaratorShape(
...     num_field_periods=1,
...     r_modes=[(0, 0, 0), (1, 1, 0)],
...     r_lmn=[600.0, 150.0],
...     z_modes=[(1, -1, 0)],
...     z_lmn=[150.0],
... )
Source code in yamc/_core/sources.pyi
858
def __new__(cls, *, num_field_periods: builtins.int, r_modes: typing.Sequence[typing.Sequence[builtins.int]], r_lmn: typing.Sequence[builtins.float], z_modes: typing.Sequence[typing.Sequence[builtins.int]], z_lmn: typing.Sequence[builtins.float]) -> StellaratorShape: ...

fit_error property

fit_error: Optional[float]

How far the shape is from the VMEC surfaces from_vmec fitted it to: the largest distance (cm) over every surface and an angular grid. None for a shape given as Fourier-Zernike coefficients.

num_field_periods property

num_field_periods: int

Number of field periods.

r_modes property

r_modes: list[tuple[int, int, int]]

(l, m, n) mode numbers of the R series.

r_lmn property

r_lmn: list[float]

Coefficients of the R series (cm), in the order of r_modes.

z_modes property

z_modes: list[tuple[int, int, int]]

(l, m, n) mode numbers of the Z series.

z_lmn property

z_lmn: list[float]

Coefficients of the Z series (cm), in the order of z_modes.

from_vmec staticmethod

from_vmec(*, num_field_periods: int, xm: Sequence[float], xn: Sequence[float], rmnc: Sequence[Sequence[float]], zmns: Sequence[Sequence[float]], rmns: Optional[Sequence[Sequence[float]]] = None, zmnc: Optional[Sequence[Sequence[float]]] = None) -> StellaratorShape

Fit a shape to the flux surfaces of a VMEC equilibrium, given as the Fourier coefficients of a wout file.

VMEC gives the flux surface s_j = j / (ns - 1) (j = 0 is the magnetic axis, j = ns - 1 the boundary and s the normalised toroidal flux) as R = sum rmnc[j] * cos(xm * theta - xn * zeta) + rmns[j] * sin(...) and Z = sum zmns[j] * sin(xm * theta - xn * zeta) + zmnc[j] * cos(...). Each surface is rewritten exactly in the Fourier-Zernike product basis, and the radial profile of each term is fitted by least squares with Zernike radial polynomials in rho = sqrt(s). Every term gets the same number of polynomials, trying up to sqrt(ns) + 1: the fewest whose fit misses the surfaces by no more than twice what the best fit does, nor by more than 1% of the minor radius (the mean distance of the boundary from the magnetic axis). fit_error says how far the fitted surfaces, the boundary included, are from VMEC's.

The angles are VMEC's: the shape at (rho, theta, zeta) is VMEC's surface s = rho**2 at (theta, zeta). A wout file's theta runs counter-clockwise in the (R, Z) plane (VMEC's signgs = -1), as a TokamakShape's does. DESC reverses theta when it imports a wout file, which flips the sign of every m < 0 coefficient, so its R_lmn / Z_lmn for the same equilibrium describe the same surfaces with theta running clockwise.

Parameters:

Name Type Description Default
num_field_periods int

Number of field periods (nfp).

required
xm Sequence[float]

Poloidal mode numbers (xm).

required
xn Sequence[float]

Toroidal mode numbers, including the field-period factor (xn).

required
rmnc Sequence[Sequence[float]]

Cosine coefficients of R (cm): rmnc times 100, one row per surface from the axis out and one column per mode.

required
zmns Sequence[Sequence[float]]

Sine coefficients of Z (cm), as rmnc.

required
rmns Optional[Sequence[Sequence[float]]]

Sine coefficients of R (cm), for an equilibrium that is not stellarator symmetric (lasym).

None
zmnc Optional[Sequence[Sequence[float]]]

Cosine coefficients of Z (cm), likewise.

None

Returns:

Name Type Description
StellaratorShape StellaratorShape

The fitted shape.

Raises:

Type Description
ValueError

If the arrays differ in size, a mode number is not a whole number, an xn is not a multiple of num_field_periods, a mode is listed twice, a coefficient is NaN or infinite, even the best fit misses the surfaces somewhere by more than 1% of the minor radius, or the fitted surfaces reach R <= 0, self-intersect or are not nested.

Examples:

>>> import yamc
>>> from netCDF4 import Dataset
>>> with Dataset("wout_w7x.nc") as wout:
...     # In m, so times 100 for cm. rmns and zmnc are only there for
...     # an equilibrium that is not stellarator symmetric.
...     names = ("rmnc", "zmns", "rmns", "zmnc")
...     cm = {k: 100 * wout[k][:] for k in names if k in wout.variables}
...     shape = yamc.sources.StellaratorShape.from_vmec(
...         num_field_periods=int(wout["nfp"][:]),
...         xm=wout["xm"][:],
...         xn=wout["xn"][:],
...         **cm,
...     )
Source code in yamc/_core/sources.pyi
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
@staticmethod
def from_vmec(*, num_field_periods: builtins.int, xm: typing.Sequence[builtins.float], xn: typing.Sequence[builtins.float], rmnc: typing.Sequence[typing.Sequence[builtins.float]], zmns: typing.Sequence[typing.Sequence[builtins.float]], rmns: typing.Optional[typing.Sequence[typing.Sequence[builtins.float]]] = None, zmnc: typing.Optional[typing.Sequence[typing.Sequence[builtins.float]]] = None) -> StellaratorShape:
    r"""
    Fit a shape to the flux surfaces of a VMEC equilibrium, given as the
    Fourier coefficients of a ``wout`` file.

    VMEC gives the flux surface ``s_j = j / (ns - 1)`` (``j = 0`` is the
    magnetic axis, ``j = ns - 1`` the boundary and ``s`` the normalised
    toroidal flux) as
    ``R = sum rmnc[j] * cos(xm * theta - xn * zeta) + rmns[j] * sin(...)``
    and ``Z = sum zmns[j] * sin(xm * theta - xn * zeta) + zmnc[j] * cos(...)``.
    Each surface is rewritten exactly in the Fourier-Zernike product basis,
    and the radial profile of each term is fitted by least squares with
    Zernike radial polynomials in ``rho = sqrt(s)``. Every term gets the
    same number of polynomials, trying up to ``sqrt(ns) + 1``: the fewest
    whose fit misses the surfaces by no more than twice what the best fit
    does, nor by more than 1% of the minor radius (the mean distance of the
    boundary from the magnetic axis). ``fit_error`` says how far the fitted
    surfaces, the boundary included, are from VMEC's.

    The angles are VMEC's: the shape at ``(rho, theta, zeta)`` is VMEC's
    surface ``s = rho**2`` at ``(theta, zeta)``. A ``wout`` file's
    ``theta`` runs counter-clockwise in the ``(R, Z)`` plane (VMEC's
    ``signgs = -1``), as a ``TokamakShape``'s does. DESC reverses ``theta``
    when it imports a ``wout`` file, which flips the sign of every
    ``m < 0`` coefficient, so its ``R_lmn`` / ``Z_lmn`` for the same
    equilibrium describe the same surfaces with ``theta`` running clockwise.

    Args:
        num_field_periods: Number of field periods (``nfp``).
        xm: Poloidal mode numbers (``xm``).
        xn: Toroidal mode numbers, including the field-period factor
            (``xn``).
        rmnc: Cosine coefficients of ``R`` (cm): ``rmnc`` times 100, one row
            per surface from the axis out and one column per mode.
        zmns: Sine coefficients of ``Z`` (cm), as ``rmnc``.
        rmns: Sine coefficients of ``R`` (cm), for an equilibrium that is
            not stellarator symmetric (``lasym``).
        zmnc: Cosine coefficients of ``Z`` (cm), likewise.

    Returns:
        StellaratorShape: The fitted shape.

    Raises:
        ValueError: If the arrays differ in size, a mode number is not a
            whole number, an ``xn`` is not a multiple of
            ``num_field_periods``, a mode is listed twice, a coefficient is
            NaN or infinite, even the best fit misses the surfaces somewhere
            by more than 1% of the minor radius, or the fitted surfaces
            reach ``R <= 0``, self-intersect or are not nested.

    Examples:
        >>> import yamc
        >>> from netCDF4 import Dataset  # doctest: +SKIP
        >>> with Dataset("wout_w7x.nc") as wout:  # doctest: +SKIP
        ...     # In m, so times 100 for cm. rmns and zmnc are only there for
        ...     # an equilibrium that is not stellarator symmetric.
        ...     names = ("rmnc", "zmns", "rmns", "zmnc")
        ...     cm = {k: 100 * wout[k][:] for k in names if k in wout.variables}
        ...     shape = yamc.sources.StellaratorShape.from_vmec(
        ...         num_field_periods=int(wout["nfp"][:]),
        ...         xm=wout["xm"][:],
        ...         xn=wout["xn"][:],
        ...         **cm,
        ...     )
    """

volume

volume() -> float

Plasma volume (cm^3).

Source code in yamc/_core/sources.pyi
925
926
927
928
def volume(self) -> builtins.float:
    r"""
    Plasma volume (cm^3).
    """

evaluate

evaluate(rho: Any, theta: Any, zeta: Any) -> tuple[Any, Any]

Cylindrical (R, Z) in cm at flux coordinates (rho, theta, zeta).

Each argument is a float or a sequence of floats; scalars broadcast against sequences, so a whole surface or cross-section evaluates in one call.

Parameters:

Name Type Description Default
rho Any

Normalised radius, 0 on the axis and 1 on the boundary.

required
theta Any

Poloidal angle (radians).

required
zeta Any

Toroidal angle (radians).

required

Returns:

Type Description
tuple[Any, Any]

An (R, Z) tuple in cm, each a float or a list of floats.

Raises:

Type Description
ValueError

If rho is outside 0 to 1, theta or zeta is NaN or infinite, or the sequences differ in length.

Source code in yamc/_core/sources.pyi
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
def evaluate(self, rho: typing.Any, theta: typing.Any, zeta: typing.Any) -> tuple[typing.Any, typing.Any]:
    r"""
    Cylindrical ``(R, Z)`` in cm at flux coordinates ``(rho, theta, zeta)``.

    Each argument is a float or a sequence of floats; scalars broadcast
    against sequences, so a whole surface or cross-section evaluates in
    one call.

    Args:
        rho: Normalised radius, 0 on the axis and 1 on the boundary.
        theta: Poloidal angle (radians).
        zeta: Toroidal angle (radians).

    Returns:
        An ``(R, Z)`` tuple in cm, each a float or a list of floats.

    Raises:
        ValueError: If ``rho`` is outside 0 to 1, ``theta`` or ``zeta`` is
            NaN or infinite, or the sequences differ in length.
    """

FluxShell

The part of a stellarator plasma between two flux surfaces, the spatial distribution of a stellarator_source source.

rho property

rho: tuple[float, float]

Inner and outer rho of the shell.

shape property

The plasma shape the shell belongs to.

fusion_neutron_spectrum

fusion_neutron_spectrum(ion_temp: float, reactants: str = 'DT') -> Normal

Return a Gaussian energy distribution for fusion neutron emission.

Computes the mean energy and spectral width using relativistic interpolation formulas from Ballabio et al. (Nucl. Fusion 38, 1998).

Parameters:

Name Type Description Default
ion_temp float

Ion temperature of the plasma in eV.

required
reactants str

Fusion reactants, either 'DD' or 'DT' (default: 'DT').

'DT'

Returns:

Name Type Description
Normal Normal

A Normal distribution with mean and standard deviation corresponding to the fusion neutron energy spectrum (in eV).

Raises:

Type Description
ValueError

If ion_temp is outside [0, 100 keV] or reactants is invalid.

Examples:

>>> import yamc
>>> # D-T fusion neutron spectrum at 20 keV ion temperature
>>> energy_dist = yamc.fusion_neutron_spectrum(20000.0)
>>> # D-D fusion neutron spectrum
>>> energy_dist = yamc.fusion_neutron_spectrum(20000.0, reactants='DD')
Source code in yamc/_core/sources.pyi
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def fusion_neutron_spectrum(ion_temp: builtins.float, reactants: builtins.str = 'DT') -> Normal:
    r"""
    Return a Gaussian energy distribution for fusion neutron emission.

    Computes the mean energy and spectral width using relativistic
    interpolation formulas from Ballabio et al. (Nucl. Fusion 38, 1998).

    Args:
        ion_temp: Ion temperature of the plasma in eV.
        reactants: Fusion reactants, either 'DD' or 'DT' (default: 'DT').

    Returns:
        Normal: A Normal distribution with mean and standard deviation
                corresponding to the fusion neutron energy spectrum (in eV).

    Raises:
        ValueError: If ion_temp is outside [0, 100 keV] or reactants is invalid.

    Examples:
        >>> import yamc
        >>> # D-T fusion neutron spectrum at 20 keV ion temperature
        >>> energy_dist = yamc.fusion_neutron_spectrum(20000.0)
        >>> # D-D fusion neutron spectrum
        >>> energy_dist = yamc.fusion_neutron_spectrum(20000.0, reactants='DD')
    """

tokamak_source

tokamak_source(*, shape: TokamakShape, mode: str, ion_density_centre: float, ion_density_peaking_factor: float, ion_density_pedestal: float, ion_density_separatrix: float, ion_temperature_centre: float, ion_temperature_peaking_factor: float, ion_temperature_beta: float, ion_temperature_pedestal: float, ion_temperature_separatrix: float, pedestal_radius: float, start_angle: float = 0.0, rotation_angle: float = 6.283185307179586, mesh_resolution: tuple[int, int] = (100, 100), grid_density: int = 500, fuel: Optional[Mapping[str, float]] = None) -> list[NeutronSource]

Build the neutron sources describing a parametric tokamak plasma.

The plasma is discretised onto a cylindrical (R, phi, Z) mesh: every non-empty voxel becomes a ring source sampling uniformly across the voxel and across the toroidal sector, emitting isotropically with the Ballabio spectrum at that voxel's emission-weighted ion temperature. One source is returned per (voxel, reaction), so D-D and D-T neutrons keep their own spectra. Strengths are normalised to sum to 1; the absolute neutron rate is set by the simulation, not here.

The shape and profile models are from Fausser et al., 'Tokamak D-T neutron source models for different plasma physics confinement modes', Fus. Eng. Des. 87 (2012) 787, and the arguments are those of the openmc-plasma-source package's tokamak_source, with the same names, units and defaults, so the two can be compared. The exception is the shape: its five arguments (major_radius, minor_radius, elongation, triangularity and shafranov_factor) are given here as one TokamakShape, as stellarator_source takes a StellaratorShape.

Two physics differences to expect in such a comparison: T(t,2n)4He is not included, since yamc has no T-T neutron spectrum model, where openmc-plasma-source takes one from NeSST (for D-T fuel the T-T yield is a small fraction of the D-T yield); and the birth peaks sit a few tens of keV apart, because yamc's Ballabio spectrum takes the zero-temperature neutron energy from the reaction Q value rather than from Ballabio's tabulated 14.021 / 2.4495 MeV.

Parameters:

Name Type Description Default
shape TokamakShape

The plasma shape.

required
mode str

Confinement mode, one of 'L', 'H' or 'A'.

required
ion_density_centre float

Ion density at the plasma centre (m^-3).

required
ion_density_peaking_factor float

Ion density peaking factor (dimensionless).

required
ion_density_pedestal float

Ion density at the pedestal (m^-3).

required
ion_density_separatrix float

Ion density at the separatrix (m^-3).

required
ion_temperature_centre float

Ion temperature at the plasma centre (eV).

required
ion_temperature_peaking_factor float

Ion temperature peaking factor (dimensionless, alpha_T in the reference).

required
ion_temperature_beta float

Ion temperature beta exponent (dimensionless, beta_T in the reference).

required
ion_temperature_pedestal float

Ion temperature at the pedestal (eV).

required
ion_temperature_separatrix float

Ion temperature at the separatrix (eV).

required
pedestal_radius float

Minor radius at the pedestal (cm), less than the shape's minor_radius.

required
start_angle float

Toroidal angle at which the plasma starts, in radians. Defaults to 0.

0.0
rotation_angle float

Toroidal extent of the plasma, in radians. Negative extends the plasma the other way from start_angle. Defaults to a full torus.

6.283185307179586
mesh_resolution tuple[int, int]

Number of (R, Z) mesh bins as a two-value tuple. Defaults to (100, 100). The toroidal direction is not a parameter: the plasma is axisymmetric, so it carries no structure. Each non-empty voxel costs one source, so a coarser mesh is cheaper to sample.

(100, 100)
grid_density int

Points per dimension of the internal (a, alpha) grid mapped onto the mesh. Defaults to 500.

500
fuel Optional[Mapping[str, float]]

Fuel species as keys ('D', 'T') and atom fractions as values, which must sum to 1. Defaults to 50:50 D-T.

None

Returns:

Type Description
list[NeutronSource]

list[NeutronSource]: One ring source per (mesh voxel, reaction).

Raises:

Type Description
ValueError

If a parameter is NaN or infinite (the message names it), the plasma parameters are inconsistent (for example a pedestal radius beyond the shape's minor radius), the fuel is not D and/or T, or the plasma is too cold to make neutrons.

Examples:

>>> import yamc
>>> shape = yamc.sources.TokamakShape(
...     major_radius=906.0,
...     minor_radius=292.258,
...     elongation=1.557,
...     triangularity=0.270,
...     shafranov_factor=0.44789,
... )
>>> sources = yamc.sources.tokamak_source(
...     shape=shape,
...     mode="H",
...     ion_density_centre=1.09e20,
...     ion_density_peaking_factor=1,
...     ion_density_pedestal=1.09e20,
...     ion_density_separatrix=3e19,
...     ion_temperature_centre=45.9e3,
...     ion_temperature_peaking_factor=8.06,
...     ion_temperature_beta=6.0,
...     ion_temperature_pedestal=6.09e3,
...     ion_temperature_separatrix=0.1e3,
...     pedestal_radius=0.8 * 292.258,
... )
>>> model = yamc.Model(geometry, sources, tallies)
Source code in yamc/_core/sources.pyi
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def tokamak_source(*, shape: TokamakShape, mode: builtins.str, ion_density_centre: builtins.float, ion_density_peaking_factor: builtins.float, ion_density_pedestal: builtins.float, ion_density_separatrix: builtins.float, ion_temperature_centre: builtins.float, ion_temperature_peaking_factor: builtins.float, ion_temperature_beta: builtins.float, ion_temperature_pedestal: builtins.float, ion_temperature_separatrix: builtins.float, pedestal_radius: builtins.float, start_angle: builtins.float = 0.0, rotation_angle: builtins.float = 6.283185307179586, mesh_resolution: tuple[builtins.int, builtins.int] = (100, 100), grid_density: builtins.int = 500, fuel: typing.Optional[typing.Mapping[builtins.str, builtins.float]] = None) -> builtins.list[NeutronSource]:
    r"""
    Build the neutron sources describing a parametric tokamak plasma.

    The plasma is discretised onto a cylindrical (R, phi, Z) mesh: every
    non-empty voxel becomes a ring source sampling uniformly across the voxel
    and across the toroidal sector, emitting isotropically with the Ballabio
    spectrum at that voxel's emission-weighted ion temperature. One source is
    returned per (voxel, reaction), so D-D and D-T neutrons keep their own
    spectra. Strengths are normalised to sum to 1; the absolute neutron rate
    is set by the simulation, not here.

    The shape and profile models are from Fausser et al., 'Tokamak D-T neutron
    source models for different plasma physics confinement modes', Fus. Eng.
    Des. 87 (2012) 787, and the arguments are those of the
    ``openmc-plasma-source`` package's ``tokamak_source``, with the same
    names, units and defaults, so the two can be compared. The exception is
    the shape: its five arguments (``major_radius``, ``minor_radius``,
    ``elongation``, ``triangularity`` and ``shafranov_factor``) are given here
    as one ``TokamakShape``, as ``stellarator_source`` takes a
    ``StellaratorShape``.

    Two physics differences to expect in such a comparison: T(t,2n)4He is not
    included, since yamc has no T-T neutron spectrum model, where
    ``openmc-plasma-source`` takes one from NeSST (for D-T fuel the T-T yield
    is a small fraction of the D-T yield); and the birth peaks sit a few tens
    of keV apart, because yamc's Ballabio spectrum takes the zero-temperature
    neutron energy from the reaction Q value rather than from Ballabio's
    tabulated 14.021 / 2.4495 MeV.

    Args:
        shape: The plasma shape.
        mode: Confinement mode, one of 'L', 'H' or 'A'.
        ion_density_centre: Ion density at the plasma centre (m^-3).
        ion_density_peaking_factor: Ion density peaking factor (dimensionless).
        ion_density_pedestal: Ion density at the pedestal (m^-3).
        ion_density_separatrix: Ion density at the separatrix (m^-3).
        ion_temperature_centre: Ion temperature at the plasma centre (eV).
        ion_temperature_peaking_factor: Ion temperature peaking factor
                (dimensionless, alpha_T in the reference).
        ion_temperature_beta: Ion temperature beta exponent (dimensionless,
                beta_T in the reference).
        ion_temperature_pedestal: Ion temperature at the pedestal (eV).
        ion_temperature_separatrix: Ion temperature at the separatrix (eV).
        pedestal_radius: Minor radius at the pedestal (cm), less than the
                shape's ``minor_radius``.
        start_angle: Toroidal angle at which the plasma starts, in radians.
                Defaults to 0.
        rotation_angle: Toroidal extent of the plasma, in radians. Negative
                extends the plasma the other way from ``start_angle``.
                Defaults to a full torus.
        mesh_resolution: Number of (R, Z) mesh bins as a two-value tuple.
                Defaults to (100, 100). The toroidal direction is not a
                parameter: the plasma is axisymmetric, so it carries no
                structure. Each non-empty voxel costs one source, so a coarser
                mesh is cheaper to sample.
        grid_density: Points per dimension of the internal (a, alpha) grid
                mapped onto the mesh. Defaults to 500.
        fuel: Fuel species as keys ('D', 'T') and atom fractions as values,
                which must sum to 1. Defaults to 50:50 D-T.

    Returns:
        list[NeutronSource]: One ring source per (mesh voxel, reaction).

    Raises:
        ValueError: If a parameter is NaN or infinite (the message names it),
                the plasma parameters are inconsistent (for example a pedestal
                radius beyond the shape's minor radius), the fuel is not D
                and/or T, or the plasma is too cold to make neutrons.

    Examples:
        >>> import yamc
        >>> shape = yamc.sources.TokamakShape(
        ...     major_radius=906.0,
        ...     minor_radius=292.258,
        ...     elongation=1.557,
        ...     triangularity=0.270,
        ...     shafranov_factor=0.44789,
        ... )
        >>> sources = yamc.sources.tokamak_source(
        ...     shape=shape,
        ...     mode="H",
        ...     ion_density_centre=1.09e20,
        ...     ion_density_peaking_factor=1,
        ...     ion_density_pedestal=1.09e20,
        ...     ion_density_separatrix=3e19,
        ...     ion_temperature_centre=45.9e3,
        ...     ion_temperature_peaking_factor=8.06,
        ...     ion_temperature_beta=6.0,
        ...     ion_temperature_pedestal=6.09e3,
        ...     ion_temperature_separatrix=0.1e3,
        ...     pedestal_radius=0.8 * 292.258,
        ... )
        >>> model = yamc.Model(geometry, sources, tallies)  # doctest: +SKIP
    """

tokamak_ion_density

tokamak_ion_density(*, mode: str, ion_density_centre: float, ion_density_peaking_factor: float, ion_density_pedestal: float, minor_radius: float, pedestal_radius: float, ion_density_separatrix: float, r: Any) -> Any

Ion density of a tokamak plasma at a given minor radius.

The density depends only on the minor radius, so this is the profile the parametric source is built from. Pass a float or a sequence of floats for r; the return keeps that shape.

Parameters:

Name Type Description Default
mode str

Confinement mode, one of 'L', 'H' or 'A'.

required
ion_density_centre float

Ion density at the plasma centre (m^-3).

required
ion_density_peaking_factor float

Ion density peaking factor (dimensionless).

required
ion_density_pedestal float

Ion density at the pedestal (m^-3).

required
minor_radius float

Plasma minor radius (cm).

required
pedestal_radius float

Minor radius at the pedestal (cm).

required
ion_density_separatrix float

Ion density at the separatrix (m^-3).

required
r Any

Local minor radius (cm), from 0 to minor_radius.

required

Returns:

Type Description
Any

Ion density in m^-3, as a float or a list of floats.

Raises:

Type Description
ValueError

If mode is not 'L', 'H' or 'A', or r falls outside the plasma.

Source code in yamc/_core/sources.pyi
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
def tokamak_ion_density(*, mode: builtins.str, ion_density_centre: builtins.float, ion_density_peaking_factor: builtins.float, ion_density_pedestal: builtins.float, minor_radius: builtins.float, pedestal_radius: builtins.float, ion_density_separatrix: builtins.float, r: typing.Any) -> typing.Any:
    r"""
    Ion density of a tokamak plasma at a given minor radius.

    The density depends only on the minor radius, so this is the profile the
    parametric source is built from. Pass a float or a sequence of floats for
    ``r``; the return keeps that shape.

    Args:
        mode: Confinement mode, one of 'L', 'H' or 'A'.
        ion_density_centre: Ion density at the plasma centre (m^-3).
        ion_density_peaking_factor: Ion density peaking factor (dimensionless).
        ion_density_pedestal: Ion density at the pedestal (m^-3).
        minor_radius: Plasma minor radius (cm).
        pedestal_radius: Minor radius at the pedestal (cm).
        ion_density_separatrix: Ion density at the separatrix (m^-3).
        r: Local minor radius (cm), from 0 to ``minor_radius``.

    Returns:
        Ion density in m^-3, as a float or a list of floats.

    Raises:
        ValueError: If ``mode`` is not 'L', 'H' or 'A', or ``r`` falls outside
                the plasma.
    """

tokamak_ion_temperature

tokamak_ion_temperature(*, r: Any, mode: str, pedestal_radius: float, ion_temperature_pedestal: float, ion_temperature_centre: float, ion_temperature_beta: float, ion_temperature_peaking_factor: float, ion_temperature_separatrix: float, minor_radius: float) -> Any

Ion temperature of a tokamak plasma at a given minor radius.

The temperature depends only on the minor radius, so this is the profile that sets the neutron spectrum across the plasma. Pass a float or a sequence of floats for r; the return keeps that shape.

Unlike the openmc-plasma-source helper of the same name, which takes keV and returns eV, every temperature here is in eV.

Parameters:

Name Type Description Default
r Any

Local minor radius (cm), from 0 to minor_radius.

required
mode str

Confinement mode, one of 'L', 'H' or 'A'.

required
pedestal_radius float

Minor radius at the pedestal (cm).

required
ion_temperature_pedestal float

Ion temperature at the pedestal (eV).

required
ion_temperature_centre float

Ion temperature at the plasma centre (eV).

required
ion_temperature_beta float

Ion temperature beta exponent (dimensionless).

required
ion_temperature_peaking_factor float

Ion temperature peaking factor (dimensionless).

required
ion_temperature_separatrix float

Ion temperature at the separatrix (eV).

required
minor_radius float

Plasma minor radius (cm).

required

Returns:

Type Description
Any

Ion temperature in eV, as a float or a list of floats.

Raises:

Type Description
ValueError

If mode is not 'L', 'H' or 'A', or r falls outside the plasma.

Source code in yamc/_core/sources.pyi
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def tokamak_ion_temperature(*, r: typing.Any, mode: builtins.str, pedestal_radius: builtins.float, ion_temperature_pedestal: builtins.float, ion_temperature_centre: builtins.float, ion_temperature_beta: builtins.float, ion_temperature_peaking_factor: builtins.float, ion_temperature_separatrix: builtins.float, minor_radius: builtins.float) -> typing.Any:
    r"""
    Ion temperature of a tokamak plasma at a given minor radius.

    The temperature depends only on the minor radius, so this is the profile
    that sets the neutron spectrum across the plasma. Pass a float or a
    sequence of floats for ``r``; the return keeps that shape.

    Unlike the ``openmc-plasma-source`` helper of the same name, which takes
    keV and returns eV, every temperature here is in eV.

    Args:
        r: Local minor radius (cm), from 0 to ``minor_radius``.
        mode: Confinement mode, one of 'L', 'H' or 'A'.
        pedestal_radius: Minor radius at the pedestal (cm).
        ion_temperature_pedestal: Ion temperature at the pedestal (eV).
        ion_temperature_centre: Ion temperature at the plasma centre (eV).
        ion_temperature_beta: Ion temperature beta exponent (dimensionless).
        ion_temperature_peaking_factor: Ion temperature peaking factor
                (dimensionless).
        ion_temperature_separatrix: Ion temperature at the separatrix (eV).
        minor_radius: Plasma minor radius (cm).

    Returns:
        Ion temperature in eV, as a float or a list of floats.

    Raises:
        ValueError: If ``mode`` is not 'L', 'H' or 'A', or ``r`` falls outside
                the plasma.
    """

tokamak_neutron_source_density

tokamak_neutron_source_density(*, ion_density: Any, ion_temperature: Any, reaction: str = 'DT') -> Any

Neutron source density of a fusing plasma.

Uses the Bosch-Hale parameterisation of the Maxwellian-averaged reactivity (Nucl. Fusion 32 (1992) 611), which is fitted for ion temperatures from 0.2 keV to 100 keV. Either numeric argument may be a float or a sequence of floats, and a scalar broadcasts against a sequence.

Parameters:

Name Type Description Default
ion_density Any

Density of reacting pairs (m^-6): n_D * n_T for D-T, 0.5 * n_D**2 for D-D.

required
ion_temperature Any

Ion temperature (eV).

required
reaction str

The fusing pair, either 'DD' or 'DT'. 'DD' counts the neutron-producing D(d,n)3He branch only.

'DT'

Returns:

Type Description
Any

Neutron source density in neutrons/s/m^3, as a float or a list of

Any

floats.

Raises:

Type Description
ValueError

If reaction is not 'DD' or 'DT'.

Source code in yamc/_core/sources.pyi
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
def tokamak_neutron_source_density(*, ion_density: typing.Any, ion_temperature: typing.Any, reaction: builtins.str = 'DT') -> typing.Any:
    r"""
    Neutron source density of a fusing plasma.

    Uses the Bosch-Hale parameterisation of the Maxwellian-averaged
    reactivity (Nucl. Fusion 32 (1992) 611), which is fitted for ion
    temperatures from 0.2 keV to 100 keV. Either numeric argument may be a
    float or a sequence of floats, and a scalar broadcasts against a sequence.

    Args:
        ion_density: Density of reacting pairs (m^-6): ``n_D * n_T`` for D-T,
                ``0.5 * n_D**2`` for D-D.
        ion_temperature: Ion temperature (eV).
        reaction: The fusing pair, either 'DD' or 'DT'. 'DD' counts the
                neutron-producing D(d,n)3He branch only.

    Returns:
        Neutron source density in neutrons/s/m^3, as a float or a list of
        floats.

    Raises:
        ValueError: If ``reaction`` is not 'DD' or 'DT'.
    """

stellarator_source

stellarator_source(*, shape: StellaratorShape, mode: str, ion_density_centre: float, ion_density_peaking_factor: float, ion_density_pedestal: float, ion_density_separatrix: float, ion_temperature_centre: float, ion_temperature_peaking_factor: float, ion_temperature_beta: float, ion_temperature_pedestal: float, ion_temperature_separatrix: float, pedestal_rho: float, fuel: Optional[Mapping[str, float]] = None) -> list[NeutronSource]

Build the neutron sources describing a stellarator plasma.

The plasma is split into radial shells in rho. Each shell becomes one source per reaction, sampling positions with density S(rho) * R * |tau| (the emission density times the volume element of the shape) and emitting isotropically with the Ballabio spectrum at the shell's emission-weighted ion temperature, so D-D and D-T neutrons keep their own spectra. Strengths are normalised to sum to 1; the absolute neutron rate is set by the simulation, not here.

The density and temperature profiles are those of tokamak_source (Fausser et al., Fus. Eng. Des. 87 (2012) 787), with the normalised minor radius they take there (the rho of a TokamakShape) replaced by this shape's rho, so the pedestal is placed by pedestal_rho. Plot them with tokamak_ion_density / tokamak_ion_temperature using minor_radius=1, pedestal_radius=pedestal_rho and r=rho.

Parameters:

Name Type Description Default
shape StellaratorShape

The plasma shape.

required
mode str

Confinement mode, one of 'L', 'H' or 'A'.

required
ion_density_centre float

Ion density on the magnetic axis (m^-3).

required
ion_density_peaking_factor float

Ion density peaking factor (dimensionless).

required
ion_density_pedestal float

Ion density at the pedestal (m^-3).

required
ion_density_separatrix float

Ion density at the boundary (m^-3).

required
ion_temperature_centre float

Ion temperature on the magnetic axis (eV).

required
ion_temperature_peaking_factor float

Ion temperature peaking factor (dimensionless, alpha_T in the reference).

required
ion_temperature_beta float

Ion temperature beta exponent (dimensionless, beta_T in the reference).

required
ion_temperature_pedestal float

Ion temperature at the pedestal (eV).

required
ion_temperature_separatrix float

Ion temperature at the boundary (eV).

required
pedestal_rho float

rho of the pedestal, between 0 and 1.

required
fuel Optional[Mapping[str, float]]

Fuel species as keys ('D', 'T') and atom fractions as values, which must sum to 1. Defaults to 50:50 D-T.

None

Returns:

Type Description
list[NeutronSource]

list[NeutronSource]: One source per (radial shell, reaction).

Raises:

Type Description
ValueError

If a parameter is NaN or infinite, out of range (for example pedestal_rho outside 0 to 1), the fuel is not D and/or T, or the plasma is too cold to make neutrons.

Examples:

>>> import yamc
>>> sources = yamc.sources.stellarator_source(
...     shape=shape,
...     mode="H",
...     ion_density_centre=1.09e20,
...     ion_density_peaking_factor=1,
...     ion_density_pedestal=1.09e20,
...     ion_density_separatrix=3e19,
...     ion_temperature_centre=45.9e3,
...     ion_temperature_peaking_factor=8.06,
...     ion_temperature_beta=6.0,
...     ion_temperature_pedestal=6.09e3,
...     ion_temperature_separatrix=0.1e3,
...     pedestal_rho=0.8,
... )
Source code in yamc/_core/sources.pyi
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
def stellarator_source(*, shape: StellaratorShape, mode: builtins.str, ion_density_centre: builtins.float, ion_density_peaking_factor: builtins.float, ion_density_pedestal: builtins.float, ion_density_separatrix: builtins.float, ion_temperature_centre: builtins.float, ion_temperature_peaking_factor: builtins.float, ion_temperature_beta: builtins.float, ion_temperature_pedestal: builtins.float, ion_temperature_separatrix: builtins.float, pedestal_rho: builtins.float, fuel: typing.Optional[typing.Mapping[builtins.str, builtins.float]] = None) -> builtins.list[NeutronSource]:
    r"""
    Build the neutron sources describing a stellarator plasma.

    The plasma is split into radial shells in ``rho``. Each shell becomes one
    source per reaction, sampling positions with density
    ``S(rho) * R * |tau|`` (the emission density times the volume element of
    the shape) and emitting isotropically with the Ballabio spectrum at the
    shell's emission-weighted ion temperature, so D-D and D-T neutrons keep
    their own spectra. Strengths are normalised to sum to 1; the absolute
    neutron rate is set by the simulation, not here.

    The density and temperature profiles are those of ``tokamak_source``
    (Fausser et al., Fus. Eng. Des. 87 (2012) 787), with the normalised minor
    radius they take there (the ``rho`` of a ``TokamakShape``) replaced by
    this shape's ``rho``, so the pedestal is placed by ``pedestal_rho``. Plot
    them with ``tokamak_ion_density`` / ``tokamak_ion_temperature`` using
    ``minor_radius=1``, ``pedestal_radius=pedestal_rho`` and ``r=rho``.

    Args:
        shape: The plasma shape.
        mode: Confinement mode, one of 'L', 'H' or 'A'.
        ion_density_centre: Ion density on the magnetic axis (m^-3).
        ion_density_peaking_factor: Ion density peaking factor (dimensionless).
        ion_density_pedestal: Ion density at the pedestal (m^-3).
        ion_density_separatrix: Ion density at the boundary (m^-3).
        ion_temperature_centre: Ion temperature on the magnetic axis (eV).
        ion_temperature_peaking_factor: Ion temperature peaking factor
                (dimensionless, alpha_T in the reference).
        ion_temperature_beta: Ion temperature beta exponent (dimensionless,
                beta_T in the reference).
        ion_temperature_pedestal: Ion temperature at the pedestal (eV).
        ion_temperature_separatrix: Ion temperature at the boundary (eV).
        pedestal_rho: ``rho`` of the pedestal, between 0 and 1.
        fuel: Fuel species as keys ('D', 'T') and atom fractions as values,
                which must sum to 1. Defaults to 50:50 D-T.

    Returns:
        list[NeutronSource]: One source per (radial shell, reaction).

    Raises:
        ValueError: If a parameter is NaN or infinite, out of range (for
                example ``pedestal_rho`` outside 0 to 1), the fuel is not D
                and/or T, or the plasma is too cold to make neutrons.

    Examples:
        >>> import yamc
        >>> sources = yamc.sources.stellarator_source(
        ...     shape=shape,
        ...     mode="H",
        ...     ion_density_centre=1.09e20,
        ...     ion_density_peaking_factor=1,
        ...     ion_density_pedestal=1.09e20,
        ...     ion_density_separatrix=3e19,
        ...     ion_temperature_centre=45.9e3,
        ...     ion_temperature_peaking_factor=8.06,
        ...     ion_temperature_beta=6.0,
        ...     ion_temperature_pedestal=6.09e3,
        ...     ion_temperature_separatrix=0.1e3,
        ...     pedestal_rho=0.8,
        ... )  # doctest: +SKIP
    """

Self-shielding shapes

The lump shapes Material.transmute() takes for its resonance self-shielding correction. Usage is under Materials.

SphereLump

SphereLump()

A sphere, sized by the material's volume.

The extreme case: a sphere has the least surface for its volume, so it has the longest mean chord and shields more than any other shape of the same volume. Convenient, but an upper bound rather than a neutral choice.

A sphere. Its radius follows from Material(volume=...).

Source code in yamc/_core/shapes.pyi
30
31
32
33
def __new__(cls) -> SphereLump:
    r"""
    A sphere. Its radius follows from ``Material(volume=...)``.
    """

CubeLump

CubeLump()

A cube, sized by the material's volume.

A cube. Its side follows from Material(volume=...).

Source code in yamc/_core/shapes.pyi
41
42
43
44
def __new__(cls) -> CubeLump:
    r"""
    A cube. Its side follows from ``Material(volume=...)``.
    """

FoilLump

FoilLump(thickness: float)

A flat slab of a stated thickness.

The chord is twice the thickness whatever the area, so a foil's shielding does not depend on the volume at all -- the volume is still what makes activity and decay_heat available, but it plays no part here.

Args: thickness (float): Foil thickness in cm.

Source code in yamc/_core/shapes.pyi
58
59
60
61
62
def __new__(cls, thickness: builtins.float) -> FoilLump:
    r"""
    Args:
    thickness (float): Foil thickness in cm.
    """

CylinderLump

CylinderLump(radius: float)

A cylinder of a stated radius; its height follows from the volume.

Args: radius (float): Cylinder radius in cm.

Source code in yamc/_core/shapes.pyi
72
73
74
75
76
def __new__(cls, radius: builtins.float) -> CylinderLump:
    r"""
    Args:
    radius (float): Cylinder radius in cm.
    """

WireLump

WireLump(radius: float)

A cylinder long enough that its ends do not matter. Chord 2r.

Args: radius (float): Wire radius in cm.

Source code in yamc/_core/shapes.pyi
86
87
88
89
90
def __new__(cls, radius: builtins.float) -> WireLump:
    r"""
    Args:
    radius (float): Wire radius in cm.
    """

Data helpers

Cross-section inspection, dose and attenuation coefficients, element and reaction names, and the nuclide cache are accessed through yamc.data. See Nuclear data for examples and data configuration.

dose_coefficients

dose_coefficients(particle: str, geometry: Optional[str] = None, data_source: Optional[str] = None, dose_quantity: str = 'effective') -> DoseCoefficients

Return fluence-to-dose conversion coefficients.

dose_quantity='effective' (the default) returns fluence-to-effective-dose coefficients from ICRP Publication 74 or 116 for an irradiation geometry.

dose_quantity='ambient' returns fluence-to-ambient-dose-equivalent H(10) coefficients from ICRP Publication 74 (Table A.21 for photons, Table A.42 for neutrons), the ICRU-57 definition most regulations still reference. H(10) is defined at 10 mm depth in the ICRU sphere in an aligned and expanded field, so it takes no geometry, and ICRP-116 does not tabulate it. It is designed to over-estimate effective dose for area monitoring, but for high-energy neutrons it under-reads it. The tables cover 1 meV to 20 MeV for neutrons and 10 keV to 10 MeV for photons, and are not extrapolated: a tally folded with them scores nothing for particles outside that range.

Parameters:

Name Type Description Default
particle str

'neutron' or 'photon'.

required
geometry str

Irradiation geometry for effective dose. One of: 'AP' (Anterior-Posterior), 'PA' (Posterior-Anterior), 'LLAT' (Left Lateral), 'RLAT' (Right Lateral), 'ROT' (Rotational), 'ISO' (Isotropic). Defaults to 'AP'. Must not be given for dose_quantity='ambient'.

None
data_source str

'icrp74' or 'icrp116'. Defaults to 'icrp116' for effective dose and 'icrp74' for ambient dose equivalent, which only ICRP-74 tabulates.

None
dose_quantity str

'effective' (default) for effective dose or 'ambient' for ambient dose equivalent H*(10).

'effective'

Returns:

Name Type Description
DoseCoefficients DoseCoefficients

an object with .energy (eV), .coefficients

DoseCoefficients

(pSv cm2), .units, and .as_energy_function().

Examples:

import yamc

Get ICRP-116 AP geometry dose coefficients

dc = yamc.data.dose_coefficients('neutron', 'AP') dc.energy # incident energies in eV dc.coefficients # fluence-to-dose coefficients dc.units # 'pSv cm2'

ICRP-74 ambient dose equivalent H*(10)

h10 = yamc.data.dose_coefficients('neutron', dose_quantity='ambient')

Fold them into a flux tally via the energy_function= argument

dose_tally = yamc.Tally(scores=['flux'], energy_function=dc.as_energy_function())

Or let the tally fetch the same coefficients itself:

dose_tally = yamc.Tally(scores=['flux'], dose_coefficients=('neutron', 'AP'))

References
  • ICRP Publication 74: https://doi.org/10.1016/S0146-6453(96)90010-X
  • ICRP Publication 116: https://doi.org/10.1016/j.icrp.2011.10.001
Source code in yamc/_core/data.pyi
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def dose_coefficients(particle: builtins.str, geometry: typing.Optional[builtins.str] = None, data_source: typing.Optional[builtins.str] = None, dose_quantity: builtins.str = 'effective') -> DoseCoefficients:
    r"""
    Return fluence-to-dose conversion coefficients.

    ``dose_quantity='effective'`` (the default) returns fluence-to-effective-dose
    coefficients from ICRP Publication 74 or 116 for an irradiation geometry.

    ``dose_quantity='ambient'`` returns fluence-to-ambient-dose-equivalent
    H*(10) coefficients from ICRP Publication 74 (Table A.21 for photons, Table
    A.42 for neutrons), the ICRU-57 definition most regulations still reference.
    H*(10) is defined at 10 mm depth in the ICRU sphere in an aligned and
    expanded field, so it takes no ``geometry``, and ICRP-116 does not tabulate
    it. It is designed to over-estimate effective dose for area monitoring, but
    for high-energy neutrons it under-reads it. The tables cover 1 meV to 20 MeV
    for neutrons and 10 keV to 10 MeV for photons, and are not extrapolated: a
    tally folded with them scores nothing for particles outside that range.

    Args:
        particle (str): 'neutron' or 'photon'.
        geometry (str, optional): Irradiation geometry for effective dose. One of:
            'AP' (Anterior-Posterior), 'PA' (Posterior-Anterior),
            'LLAT' (Left Lateral), 'RLAT' (Right Lateral),
            'ROT' (Rotational), 'ISO' (Isotropic). Defaults to 'AP'. Must not be
            given for ``dose_quantity='ambient'``.
        data_source (str, optional): 'icrp74' or 'icrp116'. Defaults to
            'icrp116' for effective dose and 'icrp74' for ambient dose
            equivalent, which only ICRP-74 tabulates.
        dose_quantity (str): 'effective' (default) for effective dose or
            'ambient' for ambient dose equivalent H*(10).

    Returns:
        DoseCoefficients: an object with ``.energy`` (eV), ``.coefficients``
        (pSv cm2), ``.units``, and ``.as_energy_function()``.

    Examples:
        import yamc

        # Get ICRP-116 AP geometry dose coefficients
        dc = yamc.data.dose_coefficients('neutron', 'AP')
        dc.energy          # incident energies in eV
        dc.coefficients    # fluence-to-dose coefficients
        dc.units           # 'pSv cm2'

        # ICRP-74 ambient dose equivalent H*(10)
        h10 = yamc.data.dose_coefficients('neutron', dose_quantity='ambient')

        # Fold them into a flux tally via the energy_function= argument
        dose_tally = yamc.Tally(scores=['flux'], energy_function=dc.as_energy_function())

        # Or let the tally fetch the same coefficients itself:
        dose_tally = yamc.Tally(scores=['flux'], dose_coefficients=('neutron', 'AP'))

    References:
        - ICRP Publication 74: https://doi.org/10.1016/S0146-6453(96)90010-X
        - ICRP Publication 116: https://doi.org/10.1016/j.icrp.2011.10.001
    """

mass_attenuation_coefficient

mass_attenuation_coefficient(element: Any) -> PhotonCoefficients

Return the photon mass attenuation coefficient mu/rho of an element.

Total attenuation with coherent scattering, from the NIST XCOM database, tabulated from 1 keV to 20 MeV for Z = 1 to 100. Dividing a material's dose or fluence by sum(density_i * mu_over_rho_i(E)) is what a self-shielding estimate like :meth:Material.contact_dose does with it.

Parameters:

Name Type Description Default
element str | int

Element symbol ('Fe') or atomic number (26).

required

Returns:

Name Type Description
PhotonCoefficients PhotonCoefficients

mu/rho in cm²/g against energy in eV.

Examples:

import yamc

iron = yamc.data.mass_attenuation_coefficient('Fe') iron.interpolate(1.0e6) # 0.05995 cm2/g at 1 MeV iron.energy, iron.coefficients

References
Source code in yamc/_core/data.pyi
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def mass_attenuation_coefficient(element: typing.Any) -> PhotonCoefficients:
    r"""
    Return the photon mass attenuation coefficient mu/rho of an element.

    Total attenuation with coherent scattering, from the NIST XCOM database,
    tabulated from 1 keV to 20 MeV for Z = 1 to 100. Dividing a material's dose
    or fluence by ``sum(density_i * mu_over_rho_i(E))`` is what a self-shielding
    estimate like :meth:`Material.contact_dose` does with it.

    Args:
        element (str | int): Element symbol (``'Fe'``) or atomic number (``26``).

    Returns:
        PhotonCoefficients: mu/rho in cm²/g against energy in eV.

    Examples:
        import yamc

        iron = yamc.data.mass_attenuation_coefficient('Fe')
        iron.interpolate(1.0e6)     # 0.05995 cm2/g at 1 MeV
        iron.energy, iron.coefficients

    References:
        - NIST Standard Reference Database 8 (XCOM): <https://doi.org/10.18434/T48G6X>
    """

mass_energy_absorption_coefficient

mass_energy_absorption_coefficient(material: str = 'air') -> PhotonCoefficients

Return the mass energy-absorption coefficient mu_en/rho of a material.

The fraction of incident photon energy actually absorbed per unit mass, less what scattered photons carry away, from NIST SRD 126. This is the response an absorbed dose in air folds against, and it is a different quantity from the attenuation coefficient: attenuation counts photons removed from the beam, this counts energy deposited.

Parameters:

Name Type Description Default
material str

Currently only 'air' (dry, near sea level), tabulated from 1 keV to 20 MeV.

'air'

Returns:

Name Type Description
PhotonCoefficients PhotonCoefficients

mu_en/rho in cm²/g against energy in eV.

Examples:

import yamc

air = yamc.data.mass_energy_absorption_coefficient('air') air.interpolate(1.0e6) # 0.02789 cm2/g at 1 MeV

References
Source code in yamc/_core/data.pyi
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def mass_energy_absorption_coefficient(material: builtins.str = 'air') -> PhotonCoefficients:
    r"""
    Return the mass energy-absorption coefficient mu_en/rho of a material.

    The fraction of incident photon energy actually absorbed per unit mass, less
    what scattered photons carry away, from NIST SRD 126. This is the response an
    absorbed dose in air folds against, and it is a different quantity from the
    attenuation coefficient: attenuation counts photons removed from the beam,
    this counts energy deposited.

    Args:
        material (str): Currently only ``'air'`` (dry, near sea level), tabulated
            from 1 keV to 20 MeV.

    Returns:
        PhotonCoefficients: mu_en/rho in cm²/g against energy in eV.

    Examples:
        import yamc

        air = yamc.data.mass_energy_absorption_coefficient('air')
        air.interpolate(1.0e6)      # 0.02789 cm2/g at 1 MeV

    References:
        - NIST Standard Reference Database 126: <https://doi.org/10.18434/T4D01F>
    """

natural_abundance

natural_abundance() -> Any

Return a dict of natural isotopic abundances by nuclide name.

Returns:

Type Description
Any

dict[str, float]: e.g. {"Li6": 0.07589, "Li7": 0.92411, ...}

Source code in yamc/_core/data.pyi
138
139
140
141
142
143
144
def natural_abundance() -> typing.Any:
    r"""
    Return a dict of natural isotopic abundances by nuclide name.

    Returns:
        dict[str, float]: e.g. ``{"Li6": 0.07589, "Li7": 0.92411, ...}``
    """

natural_abundance_records

natural_abundance_records() -> Any

Return the TICE 2013 record behind each natural abundance, by nuclide name.

Table 1 of Meija et al., "Isotopic compositions of the elements 2013 (IUPAC Technical Report)", Pure Appl. Chem. 88(3), 293-306 (2016), doi:10.1515/pac-2015-0503 (© IUPAC, De Gruyter 2016), columns 4, 5, 6 and 9. :func:natural_abundance gives column 9 where it is a value and the column 6 best measurement where column 9 is an interval.

Each value is a dict with keys:

  • representative_value, representative_uncertainty: column 9. TICE gives no coverage factor for this uncertainty.
  • representative_interval: column 9 as (low, high) for the 12 elements given an interval instead of a value (H, Li, B, C, N, O, Mg, Si, S, Cl, Br, Tl).
  • observed_interval: column 4, (low, high) of natural variation.
  • best_measurement, best_measurement_uncertainty: column 6.
  • best_measurement_coverage: column 6 coverage, e.g. "2s".
  • best_measurement_calibration: "C", "F" or "N". TICE prints this and the coverage once per element; they apply to every isotope of it.
  • annotations: column 5, e.g. "g,r".

None means the table leaves that field empty ("not stated", never zero). These uncertainties are reference data only: no calculation samples or propagates them.

Returns:

Type Description
Any

dict[str, dict[str, Any]]: e.g. {"Fe58": {"representative_value": 0.00282, "representative_uncertainty": 0.00012, ...}, ...}

Source code in yamc/_core/data.pyi
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def natural_abundance_records() -> typing.Any:
    r"""
    Return the TICE 2013 record behind each natural abundance, by nuclide name.

    Table 1 of Meija et al., "Isotopic compositions of the elements 2013
    (IUPAC Technical Report)", Pure Appl. Chem. 88(3), 293-306 (2016),
    doi:10.1515/pac-2015-0503 (© IUPAC, De Gruyter 2016), columns 4, 5, 6
    and 9.
    :func:`natural_abundance` gives column 9 where it is a value and the
    column 6 best measurement where column 9 is an interval.

    Each value is a dict with keys:

    - ``representative_value``, ``representative_uncertainty``: column 9. TICE
      gives no coverage factor for this uncertainty.
    - ``representative_interval``: column 9 as ``(low, high)`` for the 12
      elements given an interval instead of a value (H, Li, B, C, N, O, Mg,
      Si, S, Cl, Br, Tl).
    - ``observed_interval``: column 4, ``(low, high)`` of natural variation.
    - ``best_measurement``, ``best_measurement_uncertainty``: column 6.
    - ``best_measurement_coverage``: column 6 coverage, e.g. ``"2s"``.
    - ``best_measurement_calibration``: ``"C"``, ``"F"`` or ``"N"``. TICE
      prints this and the coverage once per element; they apply to every
      isotope of it.
    - ``annotations``: column 5, e.g. ``"g,r"``.

    ``None`` means the table leaves that field empty ("not stated", never
    zero). These uncertainties are reference data only: no calculation
    samples or propagates them.

    Returns:
        dict[str, dict[str, Any]]: e.g. ``{"Fe58": {"representative_value": 0.00282, "representative_uncertainty": 0.00012, ...}, ...}``
    """

element_nuclides

element_nuclides() -> Any

Return a dict mapping element symbol to its naturally occurring nuclides.

Each value is a sorted list of nuclide names for that element.

Returns:

Type Description
Any

dict[str, list[str]]: e.g. {"Fe": ["Fe54", "Fe56", "Fe57", "Fe58"], ...}

Source code in yamc/_core/data.pyi
180
181
182
183
184
185
186
187
188
def element_nuclides() -> typing.Any:
    r"""
    Return a dict mapping element symbol to its naturally occurring nuclides.

    Each value is a sorted list of nuclide names for that element.

    Returns:
        dict[str, list[str]]: e.g. ``{"Fe": ["Fe54", "Fe56", "Fe57", "Fe58"], ...}``
    """

element_names

element_names() -> Any

Return a dict mapping element symbol to full element name.

Returns:

Type Description
Any

dict[str, str]: e.g. {"Fe": "iron", "Li": "lithium", ...}

Source code in yamc/_core/data.pyi
190
191
192
193
194
195
196
def element_names() -> typing.Any:
    r"""
    Return a dict mapping element symbol to full element name.

    Returns:
        dict[str, str]: e.g. ``{"Fe": "iron", "Li": "lithium", ...}``
    """

reaction_names

reaction_names() -> Any

Return a dict mapping MT numbers (int) to ENDF reaction notation strings. e.g. {2: "(n,elastic)", 18: "(n,fission)", 102: "(n,gamma)", ...}

Each MT's own name, not an inversion of REACTION_MT. Several names map to one MT ("fission" and "(n,fission)" are both MT 18), so inverting a HashMap picked whichever the iteration order reached last: the same build could return {18: "fission"} on one run and {18: "(n,fission)"} on the next.

Source code in yamc/_core/data.pyi
198
199
200
201
202
203
204
205
206
207
208
def reaction_names() -> typing.Any:
    r"""
    Return a dict mapping MT numbers (int) to ENDF reaction notation strings.
    e.g. {2: "(n,elastic)", 18: "(n,fission)", 102: "(n,gamma)", ...}

    Each MT's own name, not an inversion of `REACTION_MT`. Several names map to
    one MT (`"fission"` and `"(n,fission)"` are both MT 18), so inverting a
    HashMap picked whichever the iteration order reached last: the same build
    could return `{18: "fission"}` on one run and `{18: "(n,fission)"}` on the
    next.
    """

clear_nuclide_cache

clear_nuclide_cache() -> None

Clear any internally cached nuclide data.

This forces subsequent reads to re-parse JSON files.

Returns:

Type Description
None

None

Source code in yamc/_core/data.pyi
210
211
212
213
214
215
216
217
218
def clear_nuclide_cache() -> None:
    r"""
    Clear any internally cached nuclide data.

    This forces subsequent reads to re-parse JSON files.

    Returns:
        None
    """

split_nuclide

split_nuclide(name: str) -> tuple[str, int, int]

Split a nuclide name into its element symbol, mass number and isomeric state.

The one place downstream code should ask, because the obvious way of doing it by hand is wrong for exactly the entry that is easiest to forget: stripping the trailing digits off "Ta180_m1" leaves "Ta180_m" and a mass number of 1, and natural tantalum really does contain Ta180m, so a composition built from :func:natural_abundance will hand you that name.

Parameters:

Name Type Description Default
name str

A nuclide name, e.g. "Fe56" or "Ta180_m1".

required

Returns:

Type Description
tuple[str, int, int]

tuple[str, int, int]: Element symbol, mass number, and isomeric state (0 for a ground state, 1 for the first metastable, and so on).

Raises:

Type Description
ValueError

If the name is not a nuclide name.

Examples:

>>> yani.data.split_nuclide("Fe56")
('Fe', 56, 0)
>>> yani.data.split_nuclide("Ta180_m1")
('Ta', 180, 1)
Source code in yamc/_core/data.pyi
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def split_nuclide(name: builtins.str) -> tuple[builtins.str, builtins.int, builtins.int]:
    r"""
    Split a nuclide name into its element symbol, mass number and isomeric state.

    The one place downstream code should ask, because the obvious way of doing
    it by hand is wrong for exactly the entry that is easiest to forget:
    stripping the trailing digits off ``"Ta180_m1"`` leaves ``"Ta180_m"`` and a
    mass number of 1, and natural tantalum really does contain Ta180m, so a
    composition built from :func:`natural_abundance` will hand you that name.

    Args:
        name (str): A nuclide name, e.g. ``"Fe56"`` or ``"Ta180_m1"``.

    Returns:
        tuple[str, int, int]: Element symbol, mass number, and isomeric state
            (0 for a ground state, 1 for the first metastable, and so on).

    Raises:
        ValueError: If the name is not a nuclide name.

    Examples:
        >>> yani.data.split_nuclide("Fe56")
        ('Fe', 56, 0)
        >>> yani.data.split_nuclide("Ta180_m1")
        ('Ta', 180, 1)
    """

atomic_symbol

atomic_symbol(z: int) -> str

Return the chemical symbol of an atomic number.

Bound so that a caller naming files or directories from ENDF data does not have to carry its own copy of the periodic table, or install a second nuclear-data package to borrow one.

Parameters:

Name Type Description Default
z int

Atomic number, 0 to 118.

required

Returns:

Name Type Description
str str

The chemical symbol, e.g. "Fe".

Raises:

Type Description
ValueError

If there is no element with that atomic number.

Examples:

>>> yani.data.atomic_symbol(26)
'Fe'
>>> yani.data.atomic_symbol(0)
'n'
Note

Z = 0 is the neutron, "n", and is not an error. ENDF libraries really do ship a neutron material (JENDL is one), so a caller walking a sublibrary will meet it.

Source code in yamc/_core/data.pyi
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def atomic_symbol(z: builtins.int) -> builtins.str:
    r"""
    Return the chemical symbol of an atomic number.

    Bound so that a caller naming files or directories from ENDF data does not
    have to carry its own copy of the periodic table, or install a second
    nuclear-data package to borrow one.

    Args:
        z (int): Atomic number, 0 to 118.

    Returns:
        str: The chemical symbol, e.g. ``"Fe"``.

    Raises:
        ValueError: If there is no element with that atomic number.

    Examples:
        >>> yani.data.atomic_symbol(26)
        'Fe'
        >>> yani.data.atomic_symbol(0)
        'n'

    Note:
        Z = 0 is the neutron, ``"n"``, and is not an error. ENDF libraries
        really do ship a neutron material (JENDL is one), so a caller walking a
        sublibrary will meet it.
    """

atomic_number

atomic_number(symbol: str) -> int

Return the atomic number of a chemical symbol.

The inverse of :func:atomic_symbol.

Parameters:

Name Type Description Default
symbol str

A chemical symbol, e.g. "Fe". Case sensitive, and the symbol only: "fe" and "iron" are both refused.

required

Returns:

Name Type Description
int int

The atomic number.

Raises:

Type Description
ValueError

If the symbol names no element.

Examples:

>>> yani.data.atomic_number("Fe")
26
Source code in yamc/_core/data.pyi
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def atomic_number(symbol: builtins.str) -> builtins.int:
    r"""
    Return the atomic number of a chemical symbol.

    The inverse of :func:`atomic_symbol`.

    Args:
        symbol (str): A chemical symbol, e.g. ``"Fe"``. Case sensitive, and the
            symbol only: ``"fe"`` and ``"iron"`` are both refused.

    Returns:
        int: The atomic number.

    Raises:
        ValueError: If the symbol names no element.

    Examples:
        >>> yani.data.atomic_number("Fe")
        26
    """

Material collections

The bundled PNNL collection is available as yamc.materials.pnnl; see PNNL material list for selecting a composition.

pnnl module-attribute

The PNNL Compendium of Material Composition Data for Radiation Transport Modeling (PNNL-15870, Rev. 2): 410 materials keyed by the report's own names.

MaterialCollection

A read-only, name-keyed table of published material compositions.

Indexing returns an ordinary :class:Material, freshly built each time, so it can be renamed and mutated without affecting the collection or any other lookup of the same name.

Examples:

>>> import yamc
>>> steel = yamc.materials.pnnl["Steel, Stainless 304"]
>>> steel.name = "firstwall_material"
>>> yamc.materials.pnnl.search("concrete")[:2]
['Concrete, Barite (Type BA)', 'Concrete, Barytes-Limonite']

citation property

citation: str

Short citation for the source document, e.g. "PNNL-15870, Rev. 2".

url property

url: str

URL of the source document.

names

names() -> list[str]

Every material name, in source-document order.

Returns:

Type Description
list[str]

list[str]: All names in the collection.

Source code in yamc/_core/materials.pyi
74
75
76
77
78
79
80
def names(self) -> builtins.list[builtins.str]:
    r"""
    Every material name, in source-document order.

    Returns:
        list[str]: All names in the collection.
    """

search

search(query: str) -> list[str]

Names containing query, compared case-insensitively.

Parameters:

Name Type Description Default
query str

Substring to look for, e.g. "concrete".

required

Returns:

Type Description
list[str]

list[str]: Matching names, ready to pass straight back to [].

Source code in yamc/_core/materials.pyi
81
82
83
84
85
86
87
88
89
90
def search(self, query: builtins.str) -> builtins.list[builtins.str]:
    r"""
    Names containing ``query``, compared case-insensitively.

    Args:
        query (str): Substring to look for, e.g. ``"concrete"``.

    Returns:
        list[str]: Matching names, ready to pass straight back to ``[]``.
    """

material

material(key: str, *, name: Optional[str] = None, density: Optional[float] = None, density_units: str = 'g/cm3', temperature: Optional[float] = None, volume: Optional[float] = None, transmutable: bool = False, id: Optional[int] = None) -> Material

Build the named material, overriding fields the collection does not set.

Equivalent to collection[key] followed by attribute assignment, except for density, which :class:Material does not allow to be reassigned after construction. Use it for a material used at other than its reference density, e.g. a concrete at a different porosity or a steel diluted by a coolant void fraction.

Examples:

>>> steel = yamc.materials.pnnl.material("Steel, Stainless 316", temperature=600)
>>> porous = yamc.materials.pnnl.material(
...     "Steel, Stainless 316", density=7000, density_units="kg/m3"
... )

Parameters:

Name Type Description Default
key str

The source document's name, verbatim.

required
name Optional[str]

Rename the material, e.g. to match a mesh geometry's material name.

None
density Optional[float]

Density in density_units, replacing the collection's reference density. Warns when it is higher than the reference density, which no void fraction or porosity can give.

None
density_units str

Units of density: "g/cm3" (default), "g/cc", "kg/m3" or "atom/barn-cm".

'g/cm3'
temperature Optional[float]

Temperature in Kelvin. If omitted, 294 K is used, or the only temperature the nuclear data carries when it carries just one.

None
volume Optional[float]

Volume in cm³.

None
transmutable bool

Mark for depletion by Model.simulate_transmutation.

False
id Optional[int]

Material ID. Defaults to a fresh one, which no earlier material was given.

None

Returns:

Name Type Description
Material Material

The material with the overrides applied.

Source code in yamc/_core/materials.pyi
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def material(self, key: builtins.str, *, name: typing.Optional[builtins.str] = None, density: typing.Optional[builtins.float] = None, density_units: builtins.str = 'g/cm3', temperature: typing.Optional[builtins.float] = None, volume: typing.Optional[builtins.float] = None, transmutable: builtins.bool = False, id: typing.Optional[builtins.int] = None) -> Material:
    r"""
    Build the named material, overriding fields the collection does not set.

    Equivalent to ``collection[key]`` followed by attribute assignment,
    except for ``density``, which :class:`Material` does not allow to be
    reassigned after construction. Use it for a material used at other
    than its reference density, e.g. a concrete at a different porosity
    or a steel diluted by a coolant void fraction.

    Examples:
        >>> steel = yamc.materials.pnnl.material("Steel, Stainless 316", temperature=600)
        >>> porous = yamc.materials.pnnl.material(
        ...     "Steel, Stainless 316", density=7000, density_units="kg/m3"
        ... )

    Args:
        key (str): The source document's name, verbatim.
        name (Optional[str]): Rename the material, e.g. to match a mesh
            geometry's material name.
        density (Optional[float]): Density in ``density_units``, replacing
            the collection's reference density. Warns when it is higher
            than the reference density, which no void fraction or porosity
            can give.
        density_units (str): Units of ``density``: ``"g/cm3"`` (default),
            ``"g/cc"``, ``"kg/m3"`` or ``"atom/barn-cm"``.
        temperature (Optional[float]): Temperature in Kelvin. If omitted,
            294 K is used, or the only temperature the nuclear data carries
            when it carries just one.
        volume (Optional[float]): Volume in cm³.
        transmutable (bool): Mark for depletion by
            ``Model.simulate_transmutation``.
        id (Optional[int]): Material ID. Defaults to a fresh one, which no
            earlier material was given.

    Returns:
        Material: The material with the overrides applied.
    """

entry

entry(name: str) -> dict

The source document's own record for a material, for citation.

Parameters:

Name Type Description Default
name str

The source document's name, verbatim.

required

Returns:

Name Type Description
dict dict

name, number (the entry number in the source

dict

document), density (g/cm3), formula (or None),

dict

composition (element symbol or nuclide name -> atom

dict

fraction), citation and url.

Source code in yamc/_core/materials.pyi
129
130
131
132
133
134
135
136
137
138
139
140
141
def entry(self, name: builtins.str) -> dict:
    r"""
    The source document's own record for a material, for citation.

    Args:
        name (str): The source document's name, verbatim.

    Returns:
        dict: ``name``, ``number`` (the entry number in the source
        document), ``density`` (g/cm3), ``formula`` (or None),
        ``composition`` (element symbol or nuclide name -> atom
        fraction), ``citation`` and ``url``.
    """

NameIter

Iterator over a collection's material names.

collections

collections() -> list[str]

Names of the available material collections.

Returns:

Type Description
list[str]

list[str]: Collection names, each an attribute of yamc.materials.

Source code in yamc/_core/materials.pyi
151
152
153
154
155
156
157
def collections() -> builtins.list[builtins.str]:
    r"""
    Names of the available material collections.

    Returns:
        list[str]: Collection names, each an attribute of ``yamc.materials``.
    """

Parallel execution

GPU adapter discovery and MPI support are accessed through yamc.parallel. See Simulate transport for backend selection and MPI execution.

has_mpi

has_mpi() -> bool

Return True if yamc was built with MPI support.

Source code in yamc/_core/parallel.pyi
22
23
24
25
def has_mpi() -> builtins.bool:
    r"""
    Return ``True`` if yamc was built with MPI support.
    """

gpu_available

gpu_available() -> bool

Return True if the GPU compute path is usable -- yamc was built with the gpu feature and an f64-capable Vulkan adapter is present.

Source code in yamc/_core/parallel.pyi
27
28
29
30
31
def gpu_available() -> builtins.bool:
    r"""
    Return ``True`` if the GPU compute path is usable -- yamc was built with the
    ``gpu`` feature and an f64-capable Vulkan adapter is present.
    """

list_gpu_adapters

list_gpu_adapters() -> list[str]

List the names of the f64-capable Vulkan GPU adapters on this host.

Pass one of these names directly as compute=<name> to :meth:Model.simulate_transport to run on that specific adapter; plain compute='gpu' auto-selects (preferring a discrete GPU). Returns an empty list when there's no usable GPU (or yamc was built without the gpu feature). Pure enumeration -- it does not initialize the GPU.

Source code in yamc/_core/parallel.pyi
33
34
35
36
37
38
39
40
41
42
def list_gpu_adapters() -> builtins.list[builtins.str]:
    r"""
    List the names of the f64-capable Vulkan GPU adapters on this host.

    Pass one of these names directly as ``compute=<name>`` to
    :meth:`Model.simulate_transport` to run on that specific adapter; plain
    ``compute='gpu'`` auto-selects (preferring a discrete GPU). Returns an
    empty list when there's no usable GPU (or yamc was built without the
    ``gpu`` feature). Pure enumeration -- it does not initialize the GPU.
    """

mpi_rank

mpi_rank() -> int

Return this process's MPI rank (0 when not running under MPI).

Source code in yamc/_core/parallel.pyi
44
45
46
47
def mpi_rank() -> builtins.int:
    r"""
    Return this process's MPI rank (``0`` when not running under MPI).
    """

mpi_size

mpi_size() -> int

Return the number of MPI ranks (1 when not running under MPI).

Source code in yamc/_core/parallel.pyi
49
50
51
52
def mpi_size() -> builtins.int:
    r"""
    Return the number of MPI ranks (``1`` when not running under MPI).
    """

mpi_finalize

mpi_finalize() -> None

Finalize MPI if yamc initialised it. MPI started by the host (e.g. mpi4py) is left for the host to finalize. Registered with atexit; a no-op without MPI.

Source code in yamc/_core/parallel.pyi
54
55
56
57
58
def mpi_finalize() -> None:
    r"""
    Finalize MPI if yamc initialised it. MPI started by the host (e.g. mpi4py) is
    left for the host to finalize. Registered with ``atexit``; a no-op without MPI.
    """