Skip to content

Python API

Everything in the llevant module. For a guided introduction, read the Python guide first.

A few rules hold throughout:

  • Numbers. Cells, surfaces, materials and universes are MCNP numbers; lengths are in cm.
  • Batches. Functions that take many points or lines take anything numpy.asarray accepts, of shape (N, 3), and return numpy columns.
  • Errors. OSError for files, ValueError for bad arguments, LlevantError for other failures.

llevant: fast, exact queries on MCNP geometry.

Load a model once, then query it::

import llevant
m = llevant.load("model.i")
m.locate(0, 0, 0)               # where a point is
m.classify(points)              # many points: numpy columns
m.trace((0, 0, 0), (100, 0, 0)) # segments of a line
m.slice(z=0)                    # an image (shown inline in Jupyter)
m.volumes(h=1.0).by("material")

Cells, materials and universes are MCNP numbers; lengths are in cm. The command line is python -m llevant --help.

Cell

A cell card, as compiled.

Cells

Cells by MCNP number, in card order.

keys

keys() -> list[int]

The cell numbers, in card order.

values

values() -> list[Cell]

The cells, in card order.

items

items() -> list[tuple[int, Cell]]

(number, cell) pairs, in card order.

get

get(id: int) -> Optional[Cell]

Cell id (MCNP number), None if there is none.

Changes

How the cells (or universes) of two models differ, by MCNP number.

Classification

Labels of a batch of points.

Diagnostic

A problem found while compiling: unsupported features, undefined references... The affected cells are compiled as unsupported.

Diff

What Model.diff finds: cells and universes changes. False when the models are the same up to numbering; str() gives a report.

Field

Numbers over a model's geometry, drawn over its images with field=.

name property

name: str

What the values are (shown on the legend).

unit property

unit: str

The values' unit (shown on the legend).

kind property

kind: Literal['cells', 'instances', 'mesh']

"cells", "instances" or "mesh".

scale property

scale: tuple[float, float, bool]

The colour scale: (low, high, logarithmic).

opacity property

opacity: float

How far the field covers the cells' colours, 0 to 1.

cell_colours_under property

cell_colours_under: bool

Whether the cells' own colours are under the field (and where it has no value) rather than a neutral grey.

cells staticmethod

cells(model: Model, values: Mapping[int, float], *, name: str = '', unit: str = '') -> Field

Values per cell, {cell number: value}; every instance of a cell has its value.

materials staticmethod

materials(model: Model, values: Mapping[int, float], *, name: str = '', unit: str = '') -> Field

Values per material, {material number: value}, on every unfilled cell of each.

instances staticmethod

instances(model: Model, values: Union[Mapping[int, float], Mapping[str, float], ArrayLike], *, name: str = '', unit: str = '') -> Field

Values per cell instance (Label.instance): an array of model.instance_count values (NaN for none), or a dict of instance ids or paths ("12 < 100[1 0 0] < 5") to values.

mesh staticmethod

mesh(model: Model, values: ArrayLike, *, x: Optional[Sequence[float]] = None, y: Optional[Sequence[float]] = None, z: Optional[Sequence[float]] = None, r: Optional[Sequence[float]] = None, theta: Optional[Sequence[float]] = None, origin: Optional[Sequence[float]] = None, axis: Optional[Sequence[float]] = None, vec: Optional[Sequence[float]] = None, transform: Optional[tuple[Sequence[Sequence[float]], Sequence[float]]] = None, name: str = '', unit: str = '') -> Field

Values on a structured mesh, one per voxel in C order of its three axes (an array of that shape, or flat; NaN for none). A rectangular mesh gives the bounds along x, y and z (cm), placed by transform ((rotation, translation): world = rotation · local + translation, as MCNP's TR=); a cylindrical one r, z and theta (revolutions, 0 to 1) about axis through origin, theta 0 along vec.

read staticmethod

read(model: Model, path: Union[str, PathLike[str]], *, tally: Optional[int] = None, energy: str = 'total', time: str = 'total', bins: Optional[Dict[str, Union[int, str]]] = None, error: bool = False) -> Field

A field from a file: a CSV file (first column cell, material, instance or path; second the values, its header the name with the unit in brackets) or an MCNP meshtal file (exact meshes from the model's input, when it has their FMESH cards), D1SUNED cuvmsh (out=cuv, as each voxel's flux) or MCTAL file (cell tallies, per cell or per instance, bins as the model's input writes them): tally (default the first), energy and time ("total" or an index), bins for MCTAL's other dimensions ({"m": 1}), error for relative errors.

with_scale

with_scale(low: Optional[float] = None, high: Optional[float] = None, *, log: Optional[bool] = None) -> Field

The same field on another scale: ends left out are kept, and a change of log fits the scale to the values again.

with_opacity

with_opacity(opacity: float) -> Field

The same field covering the cells' colours opacity of the way.

with_cell_colours_under

with_cell_colours_under(on: bool) -> Field

The same field over the cells' own colours (True) or over a neutral grey, which cells without a value show (False, the default).

value

value(x: Union[float, Sequence[float]], y: Optional[float] = None, z: Optional[float] = None) -> Optional[float]

The value at a point, None where the field has none.

values

values(points: _Points) -> NDArray[float64]

The values at many points (an (N, 3) array), NaN where none.

Fingerprints

Digests of every cell and universe that ignore numbering and card order: cells[n] and universes[n] are (geometry, content) hex digests.

Group

Volume of a cell, material, universe or label (cm³).

Hits

First visible hits of a batch of rays.

t property

t: NDArray[float64]

t (cm along the ray) of each hit (float64), inf where the ray hit nothing.

hit property

hit: NDArray[bool_]

Whether each ray hit something visible.

surface property

surface: NDArray[int64]

Surface entered (MCNP number, int64), -1 when the ray starts inside or misses.

facet property

facet: NDArray[uint8]

Macrobody facet of surface (uint8, 0 for ordinary surfaces).

normal property

normal: NDArray[float64]

Unit normal of the surface entered, (N, 3), zero without one.

ghost_count property

ghost_count: NDArray[uint32]

Ghost boundaries each ray crossed before its hit (0 without ghosts).

ghost_cell property

ghost_cell: NDArray[int64]

MCNP number of the ghost cell at each ray's first ghost boundary, -1 for none.

Image

A slice or render; shown inline in Jupyter.

width property

width: int

Width in pixels.

height property

height: int

Height in pixels.

kind property

kind: Literal['slice', 'render']

slice or render.

rgb property

rgb: NDArray[uint8]

The pixels, (height, width, 3) uint8, rows from the top (for matplotlib.pyplot.imshow).

cell property

cell: NDArray[int64]

MCNP cell under each pixel, (height, width) int64, -1 for none.

ids property

ids: Optional[NDArray[uint32]]

Label id under each pixel, (height, width) uint32 into labels (NO_HIT where a ray hits nothing); None for GPU renders.

labels property

labels: list[Label]

The distinct labels in the image (empty for GPU renders).

at

at(i: int, j: int) -> Optional[Label]

What is under pixel (i, j) (column i, row j from the top): the label at the pixel centre (slices) or the first one the ray hits (renders; None if it hits nothing).

point

point(i: int, j: int) -> Optional[_Xyz]

The point under pixel (i, j): its centre on the plane (slices) or where its ray hits (renders; None if it hits nothing).

problems

problems() -> list[tuple[Label, int]]

Statuses found in the image other than inside (gaps, overlaps...), by number of pixels.

png

png() -> bytes

The image as PNG bytes.

save

save(path: Union[str, PathLike[str]]) -> None

Write the image as a PNG file.

Label

Where a point is. str() gives it in MCNP terms.

status property

status: _StatusName

inside, gap, overlap, on-surface, unsupported or too-deep.

cell property

cell: Optional[int]

The cell that holds the point (MCNP number), when it is inside one.

path property

path: list[tuple[int, Optional[tuple[int, int, int]]]]

Cells from level 0 down, as (cell, lattice element or None). For a point that is not inside, the path ends at the filled cell whose universe has the problem.

involved property

involved: list[int]

The cells involved, for overlaps, on-surface and unsupported points (at the last level of the path); empty otherwise.

universe property

universe: Optional[int]

Universe of the cell that holds the point.

material property

material: Optional[int]

Material of the cell that holds the point (0 for void).

density property

density: Optional[float]

Density of the cell that holds the point, with the MCNP sign.

instance property

instance: Optional[int]

Which instance of its cell holds the point: an id in 0 .. Model.instance_count, one per place the cell occupies (each cell its universe fills, each lattice element). None when not inside a cell.

instance_path property

instance_path: Optional[str]

The path in MCNP's repeated-structure notation, deepest cell first ("12 < 100[1 0 0] < 5"), when inside a cell.

is_inside property

is_inside: bool

Whether the point is inside a cell (status == "inside").

Model

A compiled MCNP model, loaded once and queried.

path property

path: Optional[str]

The file the model was read from (None for from_text).

tolerance property

tolerance: float

Distance (cm) within which a point is on a surface.

cells property

cells: Cells

The cells by MCNP number: m.cells[304], 304 in m.cells.

universes property

universes: list[int]

Universe numbers, 0 (the real world) first.

instance_count property

instance_count: int

Number of cell instance ids: every place a cell occupies (each cell its universe fills, each lattice element) has one id below this (Label.instance). A lattice filled with one universe everywhere numbers the elements of a box around it, so some ids may name no place.

diagnostics property

diagnostics: list[Diagnostic]

Problems found while compiling (unsupported features, undefined references...).

problem_box property

problem_box: Optional[_Box]

The problem box: beyond it only IMP:N=0 cells are checked (usually the box of the graveyard sphere; the cut box of a universe). None without one.

cut_cell property

cut_cell: Optional[int]

The MCNP number of the cell beyond the cut box of a model made by universe (None if it was not cut).

instance_path

instance_path(id: int) -> Optional[str]

The path of instance id in MCNP's repeated-structure notation, deepest cell first ("12 < 100[1 0 0] < 5"); None past the count.

instance

instance(path: str) -> int

The instance id of a path written as instance_path writes it (lattice elements with one to three indices). ValueError if the model has no such path.

material

material(id: int) -> list[tuple[str, float]]

The Mn card: (zaid, fraction) pairs as written (negative fractions are by weight). KeyError if there is none.

materials

materials() -> list[dict[str, Any]]

What each material looks like in realistic images: per material (ascending), a dict of material, cells (that use it), density (smallest and largest, g/cm³, None if unknown), look (main category: steel, concrete, water, ...), colour (#rrggbb), roughness, metalness, clarity, set (whether set_materials gave it) and parts (category → volume fraction, from the composition).

set_materials

set_materials(looks: Optional[Mapping[int, str]] = None) -> None

Change the look of materials in realistic images: {number: spec}, a spec being a category and/or settings, "steel", "copper roughness=0.2", "colour=#806040 metalness=0". Replaces earlier settings; None or {} goes back to the looks classified from the material cards.

This changes how this Model object draws later images (and what materials() reports); the compiled geometry, and other Model objects of the same file, are unchanged. For one image only, pass materials= to slice or render instead.

info

info() -> dict[str, Any]

Sizes, compile times (s) and tolerance.

bounds

bounds(scope: _Scope = 'contents') -> Optional[_Box]

Box around the level-0 cells of scope from their bounding boxes: contents (cells with a material or fill) or problem (all but IMP:N=0). Loose for CAD conversions; see extent.

extent

extent(scope: _Scope = 'contents', n: int = 128) -> Optional[_Box]

Box around scope, measured by tracing n × n lines per axis (the default region of slices, renders and volumes; computed once for n = 128).

bbox

bbox(cells: str) -> Optional[_Box]

Box (global frame) around every instance of the cells of a rule ("c 10-20", "u 5 & m 3", 'label "BSV"': the cells whose $ comments contain BSV, read from the input when a rule has label); None when they are nowhere (cells of universes no cell fills). Conservative: padded outward, and only an outer bound below lattices (see instance_boxes).

instance_boxes

instance_boxes(cells: str) -> list[tuple[int, _Box, bool]]

The box (global frame) of every instance of the cells of a rule: (cell, (lo, hi), exact) per instance, cell by cell. exact is false for boxes that are only an outer bound (below a lattice).

locate

locate(x: Union[float, Sequence[float]], y: Optional[float] = None, z: Optional[float] = None, *, level: Optional[int] = None) -> Label

Where a point is: locate(x, y, z) or locate((x, y, z)); with level, its path down to that universe level at most (0: the top, where a filled cell ends it).

classify

classify(points: _Points, *, level: Optional[int] = None) -> Classification

Labels of many points at once: points is an (N, 3) array (or anything numpy.asarray takes); level as in locate.

trace

trace(start: Sequence[float], end: Optional[Sequence[float]] = None, *, dir: Optional[Sequence[float]] = None, t: Optional[tuple[float, float]] = None, level: Optional[int] = None) -> list[Segment]

Segments of one line, from start to end, or from start along dir for t in (t_min, t_max) (cm); level as in locate.

trace_lines

trace_lines(start: _Points, end: Optional[_Points] = None, *, dir: Optional[_Points] = None, t_min: Optional[_Numbers] = None, t_max: Optional[_Numbers] = None, level: Optional[int] = None) -> Tracing

Segments of many lines at once: from start to end ((N, 3) arrays), or from start along dir for t in (t_min, t_max) (numbers or arrays of N); level as in locate.

first_hit

first_hit(start: _Points, dir: _Points, *, t_min: Optional[_Numbers] = None, t_max: Optional[_Numbers] = None, hide: Sequence[int] = ..., hide_universes: Sequence[int] = ..., hide_materials: Sequence[int] = ..., show_void: bool = False, level: Optional[int] = None, ghost: Sequence[str] = ...) -> Hits

Where rays first enter a visible cell: from start along dir ((N, 3) arrays) for t in (t_min, t_max) (default: far beyond the model). Void cells are hidden unless show_void; hide and hide_universes hide more (and everything inside them), and hide_materials the cells of those materials (filled cells stay, so what fills them shows). level: only cells at that universe level are seen, as MCNP's plotter shows LEVEL n (a filled cell there is solid). ghost: rules ("c 300", "u 20040 & m 5") of cells seen as shells, what fills them shown; Hits.ghost_count and Hits.ghost_cell say what each ray crossed of them.

slice

slice(*, x: Optional[float] = None, y: Optional[float] = None, z: Optional[float] = None, region: Optional[_Region] = None, width: int = 1000, colour: _ColourBy = 'cell', outline: bool = True, outline_by: Literal['cell', 'material', 'universe'] = 'cell', field: Optional[Field] = None, level: Optional[int] = None, materials: Optional[Mapping[int, str]] = None) -> Image

Image of the plane x=, y= or z= (give one) across region (default: the measured extent of the contents), width pixels wide, coloured by cell, material, universe or realistic, with field (a Field of this model) over the cells. level: only cells at that universe level, as MCNP's plotter shows LEVEL n (the rest blank). outline_by: the lines between cells ("cell"), or between the materials ("material", void one of them) or universes ("universe") of the deepest cells.

materials: looks for this image only, {number: spec} as for set_materials, instead of the model's.

render

render(*, direction: Optional[Sequence[float]] = None, eye: Optional[Sequence[float]] = None, target: Optional[Sequence[float]] = None, fov: float = 30.0, size: tuple[int, int] = ..., region: Optional[_Region] = None, clip: Optional[tuple[Sequence[float], Sequence[float]]] = None, hide: Sequence[int] = ..., hide_universes: Sequence[int] = ..., hide_materials: Sequence[int] = ..., show_void: bool = False, colour: _ColourBy = 'cell', gpu: bool = False, field: Optional[Field] = None, level: Optional[int] = None, ghost: Sequence[str] = ..., hide_rules: Sequence[str] = ..., isolate: Optional[str] = None, materials: Optional[Mapping[int, str]] = None) -> Image

3D view: the first visible cell along each pixel's ray, shaded.

The camera looks along direction and frames region (default: around every instance of the cells of isolate, or the measured extent of the contents), or looks from eye at target with a vertical field of view fov (degrees). Without direction, it looks along (0.6, 0.7, -0.4), or with isolate from where the cells show most (as llevant render --isolate). clip=(point, normal) cuts away the half-space the normal points into. Void cells are hidden unless show_void; hide, hide_universes and hide_materials hide more, as in first_hit, and so do hide_rules (rules of cells, "u 20040 & m 5"). isolate (a rule) shows only its cells, what they hold and the cells holding them. gpu=True renders on the GPU (faster, approximate at edges); the model is uploaded once. Not on WARP, Windows' software adapter: an error there.

colour: cell, material, universe or realistic (what the materials look like, see materials(); lit physically, the others flat). field: a Field of this model drawn over the cells. level and ghost as in first_hit: ghosts are drawn as shells over the image.

materials: looks for this image only, {number: spec} as for set_materials, instead of the model's.

volumes

volumes(h: float, *, region: Optional[_Region] = None, seed: int = 1, probes: int = 12) -> Volumes

Volumes of everything in region (default: the measured extent of the problem), from probes lattices of lines in random directions, as many lines as three axis-parallel families h cm apart. Sigma is the standard error over the probes. The same seed gives the same lines, also on another model. Long runs cannot be interrupted with Ctrl-C.

check

check(h: float, *, region: Optional[_Region] = None, seed: int = 1, probes: int = 12) -> list[Group]

Gaps, overlaps, unsupported cells and too-deep nesting found by volumes(h, ...), largest first (empty if none).

volumes_to

volumes_to(h: float, rel_sigma: float, *, h_min: Optional[float] = None, abs_sigma: float = 0.0, max_probes: Optional[int] = None, by: _GroupBy = 'cell', region: Optional[_Region] = None, seed: int = 1, probes: int = 12) -> list[Group]

Volumes grouped by cell, material, universe or label, those inside cells refined until sigma / volume is at most rel_sigma (halving h over the boxes their cells can be in, down to h_min, default h / 64). Every group the model can hold is listed, met or not. Each group's h says which lines gave it, converged whether it got there and outcome how: "converged", "not converged", "not found" or "empty". A group whose sigma is at most abs_sigma cm³ (0: none) is done too, however large its relative sigma. max_probes (default probes: none added) lets groups a little above the target get more probes at one spacing: more converge, for more time.

cell_volumes

cell_volumes(cells: Sequence[int], h: float, rel_sigma: Optional[float] = None, *, h_min: Optional[float] = None, abs_sigma: float = 0.0, max_probes: int = 48, region: Optional[_Region] = None, seed: int = 1, probes: int = 12) -> list[Group]

Volumes of the cells cells (MCNP numbers) alone, in that order: every instance of each together, lines traced only around them; a filled cell's volume is that of its region. Each cell starts at the spacing that puts 8 lines across its box (at most h) and, with rel_sigma, is refined until sigma / volume is at most that, down to h_min (default h / 64), or until sigma is at most abs_sigma cm³ (0: none); without it, one pass. Up to max_probes (default 48) at one spacing. converged and outcome as for volumes_to.

fingerprints

fingerprints(precision: float = ...) -> Fingerprints

Digests of every cell and universe that ignore numbering and card order, at relative precision.

diff

diff(other: Model, precision: float = ...) -> Diff

How other differs from this model, cell by cell and universe by universe, up to numbering.

reload

reload() -> Model

Read and compile the file again, with the same options (and the same universe, for a model made by universe). Only the universes that changed are built again: the rest is taken from this model.

recompile

recompile(text: str) -> Model

Compile text, a new version of this model's input (an edit, or a new assembly made in memory), with the same options (and the same universe, for a model made by universe). Only the universes that changed are built again: the rest is taken from this model. The model it gives is not read from a file (path is None).

universe

universe(u: int, cut: Union[Literal['own', 'none'], _Region, None] = None) -> Model

Universe u as a model of its own, in its own frame, with everything it holds; cell and universe numbers stay the same. Cut to a box beyond which lies one void IMP:N=0 cell (cut_cell): "own" (around what the universe holds, measured, wherever the model places it), "none", or a box as for region.

Segment

A stretch of a line in one label, from t0 to t1 (cm along the line), entered through surface_in and left through surface_out (None at the ends of the line).

length property

length: float

t1 - t0, cm.

Surface

MCNP surface number and macrobody facet (0 for ordinary surfaces).

id property

id: int

MCNP surface number.

facet property

facet: int

Macrobody facet number (1-based), 0 for an ordinary surface.

Tracing

Segments of a batch of lines, ragged: line i is offsets[i]:offsets[i+1].

offsets property

offsets: NDArray[uint64]

Start of each line's segments (uint64, one more than the lines).

t0 property

t0: NDArray[float64]

t (cm along the line) where each segment starts.

t1 property

t1: NDArray[float64]

t where each segment ends.

line property

line: NDArray[int64]

Line of each segment (int64).

surface_in property

surface_in: NDArray[int64]

Surface each segment is entered through (MCNP number, int64), -1 at the start of a line.

surface_out property

surface_out: NDArray[int64]

Surface each segment is left through, -1 at the end of a line.

facet_in property

facet_in: NDArray[uint8]

Macrobody facet of surface_in (uint8, 0 for ordinary surfaces).

facet_out property

facet_out: NDArray[uint8]

Macrobody facet of surface_out.

lengths

lengths(by: _GroupBy = 'cell') -> dict[Any, float]

Total length (cm) by cell, material, universe or label. Segments not inside a cell are keyed by their status name (gap, overlap...) except with by="label", where every key is a label.

Volumes

Volumes of everything a grid of lines met (Model.volumes).

total property

total: float

Sum of all volumes: the region, up to the grid's edges.

h property

h: float

Line spacing (cm).

region property

region: _Box

The box measured, ((x0, y0, z0), (x1, y1, z1)) in cm.

by

by(by: _GroupBy = 'cell') -> list[Group]

Volumes by cell, material, universe or label (every path apart). Cells, materials and universes come first in number order, then gaps, overlaps and the like, one group per label.

problems

problems() -> list[Group]

Gaps, overlaps, unsupported cells and too-deep nesting, largest first.

to_polars

to_polars(by: _GroupBy = 'cell') -> Any

by() as a Polars data frame (needs polars).

to_pandas

to_pandas(by: _GroupBy = 'cell') -> Any

by() as a pandas data frame (needs pandas).

from_text

from_text(text: str, *, tolerance: float = 1e-08, world_half_size: float = 1000000.0, grid: Literal['auto', 'always', 'off'] = 'auto') -> Model

Compile MCNP input text.

load

load(path: Union[str, PathLike[str]], *, tolerance: float = 1e-08, world_half_size: float = 1000000.0, grid: Literal['auto', 'always', 'off'] = 'auto') -> Model

Read and compile an MCNP input file.

main

main(argv: list[str]) -> int

Run the command line (argv[0] is the program name).

set_threads

set_threads(n: int) -> None

Use n worker threads; only before the first query.

threads

threads() -> int

Number of worker threads queries use.

view

view(model=None, *, state=None, backend=None)

Open the interactive viewer on a model; returns when the window closes.

Without model, the viewer's start screen, to open one from. Runs in this process (no extra executable). Call it from a script, not a notebook cell: it blocks. state: view file to open and save to (default <model>.view.json; needs model); backend: "auto", "gpu" or "cpu".