Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API at a glance

This page is a cheat sheet, not the specification. It gathers the Python API into lookup tables so you can find a name quickly. Behaviour is shown in context by the notebooks under Examples, and the authoritative signatures are the hand-written type stubs (src/mefikit/*.pyi) and your editor’s autocompletion. If something here disagrees with them, they win.

Meshes are UMesh objects. Fields and element groups live in two dict-like mappings on the mesh, and selections are lazy views that only evaluate when queried.

Some insights on how to use the current Python library:

  • Use autocompletion with the tool you like, type hints are provided! A missing type hint is a bug, please report it.
  • Only high level whole mesh operations are supported through python. For finer grain ops either reach me or implement it in rust consuming the mefikit rust crate.
  • Use lazy expressions wherever possible, they are fast, reusable, expressive and less error prone than manual indexing. They are inspired from polars, a DataFrame python-rust lib.
  • Visualize with pyvista. It lacks type hints and the syntax may not feel familiar but the overall experience is really better than anything else.

The fields mapping

mesh.fields behaves like a dict keyed by field name. Each entry returns a FieldRef, a handle to read, reduce, or write the stored values.

OperationCallNotes
list namesmesh.fields.keys() / items() / len() / name in mesh.fieldssorted, deterministic
get a handleref = mesh.fields["T"]KeyError if missing
create / replacemesh.fields["T"] = valuesee accepted values below
deletedel mesh.fields["T"]removes every instance
renamemesh.fields.rename("T", "T2")KeyError / ValueError on bad names
bulk exportmesh.fields.to_dict(){name: {etype: array}}; mesh.fields.values() returns the FieldRef list
per-etype valuesref.values(){etype: array}
single arrayref.numpy()one array when the mesh has one element type
metadataref.shape, ref.dimension(), len(ref)component shape, mesh dimension, element count

Accepted values for creation and writes:

  • a float — broadcast to every row
  • an np.ndarray — full column or per-block rows
  • a dict {etype: array} — per element type
  • an expression: mf.Field("T") * 2 or another field object
  • a string naming an existing field (e.g. "T") — copies it

Reductions over all elements carrying the field: min(), max(), sum(), mean(), var(ddof=0), std(ddof=0), integral() (measure-weighted).

Partial reads and writes

ref[selector] gathers the selected rows as {etype: array}; assigning through ref[selector] = value writes them. Selectors are:

  • wildcards: ..., : (full slice), or None
  • an ids dict: {"QUAD4": [0, 3]}
  • any selection expression: mf.sel.rect(...), mf.Field("T") > 1.0, …

The time-series mapping

Steps of a transient field are stored as ordinary fields named "<base>_step_<n>_time_<t>". The mesh.time_series mapping groups them by base into TimeSeries handles.

OperationCallNotes
list basesmesh.time_series.keys() / items() / len() / name in mesh.time_seriessorted
get a seriess = mesh.time_series["T"]factory: creates a handle even before the series exists
add a stepmesh.time_series["T"].add(value, time=0.5, dim=None)step = max + 1; returns a FieldRef; creates the series on first add
series metadatas.base, s.dim(), s.steps(), s.times()times need not be sorted nor unique
get a steps.at(step) / s.at_time(t)KeyError if absent
closest steps.nearest(t)ties go to the lower step
last steps.latest()highest step number
add to seriess.add(value, time=...)appends at max step + 1
re-stamps.set_time(step, t)ValueError on name collision
removes.remove(step) / del s[step]KeyError if absent
renames.rename("T2")moves every step; the handle follows
iteratelist(s) → (time, FieldRef), s.items() → (step, time, FieldRef)in step order
indexs[0] (step only)TypeError for float keys; use at_time / nearest for times

Static, non-stepped fields are unaffected and live in mesh.fields alongside the encoded step names.

The groups mapping

mesh.groups behaves like a dict keyed by group name. Each entry is a GroupRef.

OperationCall
create / replacemesh.groups["wall"] = sel_expr or = {"QUAD4": [0, 1]}
grow / shrinkref.add(source) / ref.remove(source)
element idsref.ids() → {etype: uint64 array}, len(ref)
renamemesh.groups.rename("old", "new")
deletedel mesh.groups["wall"]

Groups feed back into selections through mf.sel.group("wall") and mf.sel.exclude_group("wall").

Selections

Selection factories live in the mf.sel module:

FactoryElements matched by
bbox(min, max) / sphere(center, r)centroid position (3D)
rect(min, max) / circle(center, r)centroid position (2D); bounds are min-inclusive / max-exclusive
nbbox / nsphere / nrect / ncircle(..., all)node positions, with all/any semantics
ids({"ETYPE": [...]})explicit element ids
types(["QUAD4", ...])element types
group(name) / exclude_group(name)membership in a named group
all() — also None, ..., [:] where a selector is expectedeverything

Selections compose with &, |, ^, -, ~. Field thresholds produce selections too: mf.Field("T") > 1.0.

Two families of spatial selectors are available (showcased in the selection notebook):

  • the n* variants (nbbox, nrect, nsphere, ncircle, nids) match node positions and take an all= flag (all vs. any node of the element must match);
  • bbox, rect, sphere, circle, ids match element centroids.

Lazy results

mesh.select(expr) does not build a mesh; it returns a lightweight SelectionResult that re-evaluates on every call:

  • result.ids() → {etype: array}
  • len(result)
  • reductions with any field expression: min/max/sum/mean(expr), var/std(expr, ddof=0), integral(expr)
  • result.to_mesh(with_fields=True) materializes a sub-mesh when needed
hot = mesh.select(mf.Field("energy") > 1e6)
print(hot.mean("energy"))
submesh = hot.to_mesh()

Mesh modification

Most topological tools return a new UMesh; the *_update variants operate in-place and return a new mesh only when the result displaced elements (otherwise None).

OperationCall
build structured grid (SEG2/QUAD4/HEX8)mf.build_cmesh(*axes)
descending/finer connectivitymesh.descend(src_dim, target_dim) / descend_update(...)
boundaries of a dimensionmesh.boundaries(src_dim, target_dim) / boundaries_update(...)
connected partsmesh.connected_components(src_dim, link_dim, with_fields)
crack / snap / merge nodesmesh.crack(cut), mesh.snap(ref, eps), mesh.merge_nodes(eps)
extrudemesh.extrude(along), extrude_parallel(...), extrude_curv(...)
slice by a plane (3D) or line (2D)mesh.slice(origin, normal)
slice by a line (2D or 3D)mesh.slice_line(origin, direction)
split / polygonizemesh.split(), mesh.polyze() / unpolyze()
boolean overlaymesh.overlay(mesh2, operation=None)
surface imprint in 3Dmesh.overlay_surfaces(mesh2, tol=1e-9) → mf.SurfaceOverlay
join meshes as-ismf.aggregate(meshes), mf.concat(a, b)
stitch volumes at shared boundariesmf.stitch(meshes, tol=1e-9) → UMesh

mf.stitch makes two or more volume meshes (TET4, HEX8 or PHED) conformal wherever their boundaries coincide, so that they can be used as a single mesh:

import mefikit as mf

plate = mf.build_cmesh([0, 2], [0, 2], [0, 1])  # one HEX8
block = mf.build_cmesh([0, 1, 2], [0, 1, 2], [1, 2])  # four HEX8
stitched = mf.stitch([plate, block])  # one PHED mesh, 5 cells

# The interface on z = 1 is now shared: every face there belongs to two cells.
coords = stitched.coords()

The result is a single polyhedral mesh: interface nodes exist once, families are relabeled per input mesh, and fields and groups are dropped. Coincident interfaces must be piecewise planar within tol. This is an imprint only operation: overlapping volumes are not detected, so the output may contain overlapping cells.

mesh.slice(origin, normal) cuts a 3D mesh with the plane through origin with normal normal, producing a 2D PGON mesh embedded in 3D. On a 2D mesh the hyperplane is the line through origin normal to normal, and the result is a 1D SEG2 mesh. mesh.slice_line(origin, direction) cuts a 2D or 3D mesh with the line through origin along direction; both produce a 1D SEG2 mesh (in 3D the line is embedded in 3D). Quadrangular sections are kept as PGON (they are not converted to QUAD4). Slicing does not copy fields; remap them with a transfer operator, for example sliced.fields["T"] = mf.transfer.ConstantPiecewise(src, sliced)("T") (see the Slicing notebook).

Geometric transforms

Pure coordinate transformations, each returning a new UMesh (the source is left untouched):

OperationCall
translate by a vectormesh.translate([x, y, z])
scale per axis / uniformlymesh.scale([sx, sy, sz]) / mesh.scale_uniform(s)
rotate around an axis through the originmesh.rotate(axis, angle)
rotate around an axis through a pointmesh.rotate_about(center, axis, angle)
mirror across a plane through the originmesh.mirror(normal)
mirror across a plane through a pointmesh.mirror_about(point, normal)
apply an arbitrary affine transformmesh.transform(mf.Transform(matrix))
repeat a shape with a step transformmesh.duplicate(step, n)

Angles are in radian. mf.Transform also offers the identity, translation, scaling, rotation, reflection and from_matrix constructors; transform also accepts a plain 4x4 numpy array.

Field expressions (notably mf.M for the on-the-fly measure) can be evaluated without a stored field:

  • mesh.eval(expr, dim=None) → {etype: array}, e.g. mf.M or mf.Field("T") * 2
  • mesh.eval_update(name, expr, dim=None) stores the result in-place
  • mesh.measure() → per-type measures; mesh.measure_update() materializes a "Measure" field (usually unnecessary, prefer mf.M)

Input / output

UMesh.read and UMesh.write build a mesh from — or dump it to — a file, the format being selected by the file extension (.json, .yaml, .vtk, .vtu, .vtkhdf, .cgns, .med):

OperationCall
read a mesh from diskmf.UMesh.read(path)
write a mesh to diskmesh.write(path)
in-memory PyVista objectmesh.to_pyvista(dim=None, with_fields=True)
in-memory meshio objectmesh.to_meshio()
in-memory medcoupling twinmesh.to_mc(lev=None) / mf.UMesh.from_mc(mc_mesh)

to_pyvista copies the mesh (and, by default, its fields) into a pyvista.UnstructuredGrid; to_meshio produces a meshio.Mesh; the medcoupling pair converts to / from a MEDCouplingUMesh. See the Input/Output notebook and the .med round-trip in mefikit vs. medcoupling.

Field transfers

Remapping a field from a source mesh onto a target mesh is done with the mf.transfer operators. All of them share the same prepare / apply split: construction builds the interpolation coefficients once, and applying the operator to any field is then a single fast sparse product:

OperatorKindConservesSignature
ConstantPiecewisecell-based, point locationno(src, tgt, def_val=0.0)
InverseDistancemeshless, k-nearestno(src, tgt, k=4, exponent=2.0, def_val=0.0)
MovingLeastSquaresmeshless, local fitno(src, tgt, k=10, weighting=DistanceWeighting.Constant(), def_val=0.0)
ConservativeP0measure-weighted overlap (same-dim and downcast)yes(src, tgt, def_val=0.0)

Weighting kernels for MovingLeastSquares come from mf.DistanceWeighting: Constant(), InverseDistance(exponent) and Gaussian().

Once built, every operator is used the same way:

  • tr(expr, extensive=False) → the transferred field, as a Field on tgt; store it with tgt.fields[name] = tr(expr)
  • tr.eval(expr, extensive=False) → {etype: array}
  • tr.save(path) writes the prepared sparse matrix to a SciPy-compatible .npz file; mf.transfer.load(path, src_mesh, tgt_mesh=None) restores it and validates its element-block counts against the meshes.

extensive=True treats the field as extensive (mass, energy): ConservativeP0 then keeps the raw measure-weighted sum, whereas intensive fields are normalized by the target cell measure. Cells uncovered by any source cell keep the transfer def_val. ConservativeP0 also supports downcast transfers: 3D volume → 2D surface / 1D line / 0D point, 2D surface → 1D line / 0D point, and 1D line → 0D point, weighted by the intersection measure in the target dimension. See the Field transfers notebook for the exact formula and assumptions; the timing and correctness comparison with medcoupling is at the end of mefikit vs. medcoupling.

When the source and target meshes are split across MPI ranks, mf.transfer.DistributedConservativeP0(src, tgt, comm=...) prepares the same conservative P0 operator on each rank’s local pieces and performs the communication through mpi4py. Only the Python side requires MPI (install the optional mpi extra); the Rust library and its wheels stay MPI-independent. The operator is reused across fields with the same eval / apply_update calls, or use the one-shot mf.transfer.distributed(src, expr, tgt, comm=...).

Field gradients

mf.Gradient differentiates a scalar field with a moving least-squares (MLS) fit over the k nearest source cell centres. Like the transfers it has a prepare / apply split: the geometric operator is built once and can be applied to any number of fields. The result is a vector field with one component per space direction (d = 2 or 3).

ConstructorEvaluated atSignature
mf.Gradient(src)the source mesh’s own cell centroids(src, tgt=None, k=10, weighting=DistanceWeighting.Constant(), def_val=0.0)
mf.Gradient(src, tgt)the target mesh’s cell centroidssame
mf.Gradient.at_points(src, points)an explicit (n, d) point array(src, points, k=10, weighting=..., def_val=0.0)

weighting reuses the transfer kernels (mf.DistanceWeighting: Constant(), InverseDistance(exponent), CompactSupport(exponent), Gaussian()). A degree-1 fit reproduces affine fields exactly. The source domain must be full-dimensional (a 2D region in 2D, a 3D volume in 3D); on a lower-dimensional mesh embedded in a higher-dimensional space (a surface in 3D) the local system is rank-deficient and the gradient is zero.

Usage mirrors the transfers:

CallResult
grad(expr)the gradient as a lazy vector Field on the target; index components with grad(expr)[0], …
grad.eval(expr){etype: array}, shape (n_tgt, d)
grad.eval_points(expr)(n_points, d) array (point operators only)
grad = mf.Gradient(src, tgt, k=12)
tgt.fields["grad_T"] = grad("T")  # lazy vector field
tgt.fields["dTdx"] = grad("T")[0]  # one component

The Field gradients notebook validates the operators against analytic gradients and compares the kernels.