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.asarrayaccepts, of shape(N, 3), and return numpy columns. - Errors.
OSErrorfor files,ValueErrorfor bad arguments,LlevantErrorfor 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.
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=.
cell_colours_under
property
¶
Whether the cells' own colours are under the field (and where it has no value) rather than a neutral grey.
cells
staticmethod
¶
Values per cell, {cell number: value}; every instance of a cell
has its value.
materials
staticmethod
¶
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
¶
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 (cm along the ray) of each hit (float64), inf where the ray
hit nothing.
surface
property
¶
Surface entered (MCNP number, int64), -1 when the ray starts inside
or misses.
normal
property
¶
Unit normal of the surface entered, (N, 3), zero without one.
ghost_count
property
¶
Ghost boundaries each ray crossed before its hit (0 without ghosts).
ghost_cell
property
¶
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.
rgb
property
¶
The pixels, (height, width, 3) uint8, rows from the top (for
matplotlib.pyplot.imshow).
cell
property
¶
MCNP cell under each pixel, (height, width) int64, -1 for none.
ids
property
¶
Label id under each pixel, (height, width) uint32 into labels
(NO_HIT where a ray hits nothing); None 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
¶
The point under pixel (i, j): its centre on the plane (slices) or
where its ray hits (renders; None if it hits nothing).
Label
¶
Where a point is. str() gives it in MCNP terms.
cell
property
¶
The cell that holds the point (MCNP number), when it is inside one.
path
property
¶
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
¶
The cells involved, for overlaps, on-surface and unsupported points (at the last level of the path); empty otherwise.
density
property
¶
Density of the cell that holds the point, with the MCNP sign.
instance
property
¶
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
¶
The path in MCNP's repeated-structure notation, deepest cell first
("12 < 100[1 0 0] < 5"), when inside a cell.
Model
¶
A compiled MCNP model, loaded once and queried.
instance_count
property
¶
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
¶
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
¶
The MCNP number of the cell beyond the cut box of a model made by
universe (None if it was not cut).
instance_path
¶
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
¶
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
¶
The Mn card: (zaid, fraction) pairs as written (negative
fractions are by weight). KeyError if there is none.
materials
¶
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
¶
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.
bounds
¶
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
¶
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
¶
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
¶
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
¶
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).
Surface
¶
Tracing
¶
Segments of a batch of lines, ragged: line i is offsets[i]:offsets[i+1].
offsets
property
¶
Start of each line's segments (uint64, one more than the lines).
surface_in
property
¶
Surface each segment is entered through (MCNP number, int64), -1 at
the start of a line.
surface_out
property
¶
Surface each segment is left through, -1 at the end of a line.
facet_in
property
¶
Macrobody facet of surface_in (uint8, 0 for ordinary surfaces).
lengths
¶
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).
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.
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.
view
¶
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".