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

Introduction

About mefikit

mefikit — short for Mesh and Field Kit — is a comprehensive library for generating, manipulating, and analyzing unstructured meshes together with associated scalar, vector, and tensor fields. Its goal is to provide a unified in-memory representation of meshes and fields, along with a set of robust, efficient tools that support numerical simulation workflows in research, engineering, and scientific computing.

This book documents the Python API. The heavy lifting is done by the mefikit Rust crate, which the Python bindings wrap; the same crate can be used directly from Rust for performance-critical code.

mefikit focuses on three core principles:

  1. A flexible mesh model capable of representing mixed-element unstructured meshes.
  2. A consistent field and group architecture that attaches data to mesh entities across dimensions.
  3. Zero-copy, iterator-based access patterns to efficiently navigate and process large meshes.

This design positions mefikit as a modern core library for algorithm development.

mefikit provides

  • UMesh, the unstructured mesh container supporting mixed element types, fields, and groups.
  • I/O for reading and writing meshes in various formats (VTK, VTKHDF, CGNS, MED, JSON, YAML).
  • topology tools for analyzing mesh connectivity, computing descending meshes, neighbours, domain boundaries, etc.
  • geometry tools for computing element measures, centroids, overlays, etc.
  • transfer operators for remapping fields between meshes, and meshless field gradients.
  • selections (mf.sel) for querying and filtering mesh elements based on geometric or topological criteria.

Continue to Getting Started.

Getting started

mefikit builds, reads, writes and transforms unstructured meshes and the fields living on them, from Python. This notebook is the shortest path from zero to a mesh with a field, a selection and a figure — everything below runs as-is.

The whole book is organized so that you can copy any code cell into your own script: the API at a glance gathers the API in reference tables, and the examples build on top of it.

Install

Mefikit is released on PyPI. The [all] extra pulls the optional I/O and plotting dependencies (medcoupling, meshio, pyvista):

pip install "mefikit[all]"      # or: uv add "mefikit[all]"

A plain pip install mefikit also works if you only need the core — numpy is the sole mandatory dependency — and you can add the extras later with pip install mefikit[io]. Building from source (for the Rust API) is covered in the README.

A first mesh

A UMesh is an unstructured mesh: one global node-coordinates array plus a set of element blocks, one per element type. mf.build_cmesh(*axes) builds a structured cartesian grid in a single call — give it the node coordinates along each axis and it fills the cells for you.

import mefikit as mf

mesh = mf.build_cmesh(range(2), range(5), range(4))
print("coords :", mesh.coords().shape)
print("blocks :", {et: conn.shape for et, conn in mesh.blocks().items()})
coords : (40, 3)
blocks : {'HEX8': (12, 8)}

Fields in one line

Data is attached to a mesh through the dict-like mesh.fields mapping. You assign a field expression and mefikit evaluates it lazily, on demand — the expression is a tree, not a stored array. Geometry primitives exist ready to use: mf.X/mf.Y/mf.Z (node or cell centroids), mf.M (measure: length / area / volume), mf.Normal (normals).

import numpy as np

mesh = mf.build_cmesh(
    np.linspace(0.0, 1.0, 30), np.linspace(0.0, 1.0, 20), np.linspace(0.0, 1.0, 10)
)
mesh.fields["T"] = 1.0 + 2.0 * mf.X  # a linear temperature profile in x

ref = mesh.fields["T"]
print("min / mean / max :", ref.min(), ref.mean(), ref.max())
print("values           :", {et: a.shape for et, a in ref.values().items()})
min / mean / max : 1.0344827586206897 2.0 2.9655172413793105
values           : {'HEX8': (4959,)}

Selecting elements

mesh.select(expr) returns a lazy view: nothing is computed until you reduce it or materialize it. Spatial filters from mf.sel combine with field thresholds; sum/mean/… reduce over the selection, and .to_mesh() builds a real sub-mesh when you need one.

hot = mesh.select(mf.Field("T") > 1.25)
print("hot cells   :", len(hot))
print("hot volume  :", hot.sum(mf.M))
print("mean pos    :", hot.mean(mf.C))

bubble = mesh.select(mf.sel.sphere([0.5, 0.5, 0.5], 0.3))
print("bubble cells:", len(bubble))
bubble_mesh = bubble.to_mesh()  # materialize a real UMesh when needed
hot cells   : 4275
hot volume  : 0.8620689655172395
mean pos    : [0.56896552 0.5        0.5       ]
bubble cells: 559

Plotting

UMesh converts to PyVista in one call; fields ride along, so volume rendering and slicing work with no glue code.

mesh.to_pyvista().plot(scalars="T", show_edges=True)

The mental model in one glance

Three rules cover most of the API:

  • A mesh is coordinates + blocks. Node coordinates are one array; each block stores the connectivity of one element type (HEX8, QUAD4, …). The UMesh basics notebook explores this in depth.
  • Fields live per element type, and expressions are lazy. mesh.fields["T"] must cover all elements of its type. Assignments accept any expression (mf.X, mf.Field("T") * 2, …) which is materialized only when you ask: a reduction, a select(...), or mesh.eval(...). mf.M computes the measure on the fly instead of storing it. See the Fields notebook.
  • Selections are lazy views. select(...) never builds a mesh; reductions re-evaluate on each call and .to_mesh() materializes when you truly need a sub-mesh. See the Selection notebook.

Mechanical detail that bites: most *_update methods operate in place and return a new mesh only when the operation displaced elements — otherwise they return None.

Where to go next

Mesh basics

GoalPage
understand what a UMesh containsUMesh basics
read / write .med and interchangeInput/Output

Building and transforming meshes

GoalPage
build meshes by sweepingExtrusions
translate, rotate and mirror a meshGeometric transforms
topology tools (descend, crack, …)Topological tools
geometry tools (overlay, merge, snap, …)Geometric tools

Fields and selections

GoalPage
field expressions, eval, reductionsFields
spatial filters and groupsSelection
move fields between meshesField transfers

Worked examples

GoalPage
a full use case end to endBubbles
how mefikit compares to a mature librarymefikit vs. medcoupling

The API at a glance is the condensed API reference behind all of these examples.

The mesh model

This chapter defines the core concepts of mefikit: the elements that make up a mesh, the distinction between topological and spatial dimension, and the rules a mesh must follow to be considered valid.

Element

An element is an abstract mesh entity specified by:

  • its type (e.g., triangle, hexahedron, polygon, polyhedron)
  • its connectivity (indices referencing the global coordinate array)

In mefikit, elements are ephemeral, zero-copy views constructed on the fly when iterating through a mesh block. They do not own memory; instead they refer to underlying index and coordinate buffers. This mirrors VTK’s “cell iterator” pattern while improving cache locality and reducing overhead.

Element iteration is a Rust-API detail. The Python bindings do not expose elements directly, because Python is meant for high-level scripting where you operate on whole meshes; the Rust API is where per-element work belongs.

Topological Dimension

The topological dimension of an element is the dimension of the mathematical object it represents:

  • 0D → vertices
  • 1D → edges / segments
  • 2D → faces
  • 3D → volumes

This categorization is independent of the embedding space and is central for field association and mesh validity checks.

Spatial Dimension

The spatial dimension is the dimension of the coordinate system in which the mesh is embedded, typically 2D or 3D. All element coordinates must be consistent with this spatial dimension. For example, one may have:

  • 2D elements in 2D (pure surface mesh)
  • 2D elements in 3D (surface embedded in 3D)
  • 3D volumetric elements in 3D

mefikit does not assume a fixed coordinate system beyond this requirement.

Mesh

A mesh in mefikit is a container that holds:

  • the global node coordinate array,
  • a set of blocks, each containing elements of a given type,
  • fields (scalar/vector/tensor) attached to elements of a given topological dimension,
  • groups, i.e., labeled subsets of elements for boundary conditions, materials, or post-processing.

Properties:

  • You may attach any number of fields or groups.
  • Groups may overlap arbitrarily.
  • A field must cover all elements of its associated topological dimension (similar to Gmsh’s “node data” or “element data” consistency).

If these constraints seem restrictive, mefikit encourages using multiple meshes (e.g., one per partition, or one per physical domain) to better match specialized workflows.

Topologically Valid Mesh

A topologically valid mesh in mefikit satisfies the following conditions:

  1. No overlapping higher-dimensional elements Two 3D elements may share faces or edges, but they must not occupy the same region of space. (Duplicate faces in a hex-dominant mesh are allowed and interpreted in context.)

  2. Lower-dimensional entities derive consistently from higher-dimensional ones

    • All edges must be edges of some face or volume.
    • All faces must be boundaries of some volume.
    • No “floating” or orphaned lower-dimension elements are allowed. This is consistent with the expectations of many finite-element and finite-volume codes.
  3. Non-degenerate geometry Elements must not be geometrically degenerate:

    • triangles must have non-zero area,
    • tetrahedra must have non-zero volume,
    • polygons must be well-defined and non-self-intersecting, etc. These checks are similar to the geometric validation steps performed by MeshGems and various meshing libraries.

Element Conventions

This chapter defines the node ordering and face orientation conventions used throughout mefikit. These conventions follow the VTK convention for element node ordering and face definitions.

Note: TET10 uses MEDFile mid-side node numbering (deferred migration).

Element types

TypeDimNodesRegularityDescription
VERTEX0D1RegularPoint
SEG21D2RegularLinear segment
SEG31D3RegularQuadratic segment
SEG41D4RegularCubic segment
TRI32D3RegularLinear triangle
TRI62D6RegularQuadratic triangle
TRI72D7RegularQuadratic triangle + centroid
QUAD42D4RegularLinear quadrilateral
QUAD82D8RegularQuadratic quadrilateral (serendipity)
QUAD92D9RegularBiquadratic quadrilateral
TET43D4RegularLinear tetrahedron
TET103D10RegularQuadratic tetrahedron
WEDGE63D6RegularLinear wedge
WEDGE153D15RegularQuadratic wedge
HEX83D8RegularLinear hexahedron
HEX213D21RegularTricubic hexahedron
PLINE1Dvar.PolyPolyline
PGON2Dvar.PolyPolygon
PHED3Dvar.PolyPolyhedron

Poly element representation

Poly elements (PLINE, PGON, PHED) store their connectivity as a flat array of node indices. Faces are delimited by usize::MAX sentinel values.

  • PGON: nodes form a single face, no sentinel needed. [n0, n1, n2, n3] — a 4-node polygon.

  • PHED: each face is a closed polygon (PGON), separated by sentinels.

    [f0_n0, f0_n1, f0_n2, MAX, f1_n0, f1_n1, f1_n2, f1_n3, MAX, ...]
    

    The last face has no trailing sentinel.

Face orientation convention

All subentities (edges of 2D elements, faces of 3D elements) are defined with consistent counter-clockwise (CCW) winding when viewed from outside the element. This ensures that:

  • Each outward-facing normal follows the right-hand rule.
  • Shared lower-dimensional entities are traversed in opposite directions by adjacent higher-dimensional elements.

The subentity definitions below are the canonical reference for node orderings.

2D elements

TRI3 / TRI6 / TRI7 — Triangle

Nodes 0, 1, 2 are the three vertices. Edges follow CCW winding:

        2
       / \
      /   \
     /     \
    0-------1
EdgeNodesDescription
0[0, 1]Edge 0→1
1[1, 2]Edge 1→2
2[2, 0]Edge 2→0

For TRI6/TRI7, mid-side nodes are placed as: node 3 on edge 01, node 4 on edge 12, node 5 on edge 20. TRI7 additionally has a centroid node (node 6).

QUAD4 / QUAD8 / QUAD9 — Quadrilateral

Nodes 0–3 are the four vertices, numbered counter-clockwise:

    3-------2
    |       |
    |       |
    0-------1
EdgeNodesDescription
0[0, 1]Bottom
1[1, 2]Right
2[2, 3]Top
3[3, 0]Left

3D elements

TET4 — Tetrahedron

Nodes 0–3 are the four vertices. The tetrahedron is defined by its four triangular faces (VTK convention):

          3
         /|\
        / | \
       /  |  \
      /   |   \
     /    |    \
    2-----+-----1
     \    |    /
      \   |   /
       \  |  /
        \ | /
         \|/
          0
FaceNodesDescription
0[0, 1, 3]Opposite node 2
1[1, 2, 3]Opposite node 0
2[2, 0, 3]Opposite node 1
3[0, 2, 1]Base (opposite node 3)

Each face lists the three nodes that do not include the opposite vertex, in CCW order when viewed from outside the element.

For TET10, the vertex convention is: nodes 0–3 vertices, mid-side nodes 4 (edge 01), 5 (edge 12), 6 (edge 02), 7 (edge 03), 8 (edge 13), 9 (edge 23).

WEDGE6 — Wedge

Nodes 0-5 are the 6 vertices of a unit wedge, numbered following the VTK convention:

    5 +----------+ 4
      |\        /|
      |  \     / |
      |    \  /  |
      |      + 3 |
      |      |   |
    2 + - - -|- -+ 1
       \     |  /
         \   | /
           \ |/
             + 0
FaceNodesDescription
0[0, 2, 1]Bottom
1[3, 4, 5]Top
2[0, 1, 4, 3]Starting node 0
3[1, 2, 5, 4]Starting node 1
4[2, 0, 3, 5]Starting node 2

For WEDGE15, the vertex convention is: nodes 0–5 vertices, mid-side nodes (bottom, top, middle): 6 (edge 01), 7 (edge 12), 8 (edge 02), 9 (edge 34), 10 (edge 45), 11 (edge 35), 12 (edge 03), 13 (edge 14), 14 (edge 25).

HEX8 — Hexahedron

Nodes 0–7 are the eight vertices of a unit cube, numbered following the VTK convention:

        7---------6
       /|        /|
      / |       / |
     /  |      /  |
    4---------5   |
    |   3-----|---2
    |  /      |  /
    | /       | /
    |/        |/
    0---------1

Bottom face: nodes 0, 1, 2, 3 (CCW viewed from below). Top face: nodes 4, 5, 6, 7 (CCW viewed from above). Node 4 is directly above node 0, node 5 above node 1, etc.

FaceNodesDescription
0[0, 3, 2, 1]Bottom (z = 0)
1[4, 5, 6, 7]Top (z = 1)
2[0, 1, 5, 4]Front (y = 0)
3[2, 3, 7, 6]Back (y = 1)
4[1, 2, 6, 5]Right (x = 1)
5[3, 0, 4, 7]Left (x = 0)

All faces are wound CCW when viewed from outside the element.

Differences with MEDFile: MEDFile HEX8 has a different node numbering: MED node 0 is top-left-front, while VTK node 0 is bottom-left-front. The MED→VTK node permutation is [4,5,6,7,0,1,2,3] (self-inverse). Do not mix VTK and MEDFile conventions

For HEX21, the vertex convention is: nodes 0–7 vertices, mid-side nodes 8 (edge 01), 9 (edge 12), 10 (edge 23), 11 (edge 30), 12 (edge 45), 13 (edge 56), 14 (edge 67), 15 (edge 74), 16 (edge 04), 17 (edge 15), 18 (edge 26), 19 (edge 37).

PHED — Polyhedron

A polyhedron is stored as a sequence of polygonal faces, each wound CCW when viewed from outside the element. Faces are delimited by usize::MAX sentinels in the flat connectivity array.

The constraints for a valid PHED are:

  1. Each face is a closed polygon — its nodes form a simple, non-self-intersecting loop.
  2. Consistent orientation — every edge shared by exactly two faces is traversed in opposite directions by those two faces. Equivalently, the outward normal of every face follows the right-hand rule.
  3. Closed surface — the collection of faces forms a topologically closed manifold (no dangling edges).

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.

UMesh basics

Figures use PyVista; verbose plotting boilerplate is omitted.

UMesh is the unstructured-mesh type at the heart of mefikit: a flat coordinates array plus a set of element blocks, each storing the connectivity of one element type (HEX8, QUAD4, SEG2, VERTEX, polyhedra…). This notebook builds two meshes — the trivial way with build_cmesh, then from raw coordinates and explicit connectivity — to show what a UMesh actually contains.

import numpy as np

import mefikit as mf

Building cartesian meshes

mf.build_cmesh(*axes) builds a structured (cartesian) mesh in one call: it takes the node coordinates along each axis and generates the regular grid of cells. Here x has 2 nodes, y 3 and z 4, so the mesh holds (2-1) x (3-1) x (4-1) = 6 HEX8 cells over 2 x 3 x 4 = 24 nodes.

volumes = mf.build_cmesh(
    range(2), np.linspace(0.0, 1.0, 3), np.logspace(0.0, 1.0, 4) / 10.0
)
print(volumes)
UMeshBase {
    coords: [[0.0, 0.0, 0.1],
     [1.0, 0.0, 0.1],
     [0.0, 0.5, 0.1],
     [1.0, 0.5, 0.1],
     [0.0, 1.0, 0.1],
     [1.0, 1.0, 0.1],
     [0.0, 0.0, 0.2154434690031884],
     [1.0, 0.0, 0.2154434690031884],
     [0.0, 0.5, 0.2154434690031884],
     [1.0, 0.5, 0.2154434690031884],
     [0.0, 1.0, 0.2154434690031884],
     [1.0, 1.0, 0.2154434690031884],
     [0.0, 0.0, 0.46415888336127786],
     [1.0, 0.0, 0.46415888336127786],
     [0.0, 0.5, 0.46415888336127786],
     [1.0, 0.5, 0.46415888336127786],
     [0.0, 1.0, 0.46415888336127786],
     [1.0, 1.0, 0.46415888336127786],
     [0.0, 0.0, 1.0],
     [1.0, 0.0, 1.0],
     [0.0, 0.5, 1.0],
     [1.0, 0.5, 1.0],
     [0.0, 1.0, 1.0],
     [1.0, 1.0, 1.0]], shape=[24, 3], strides=[3, 1], layout=Cc (0x5), const ndim=2,
    element_blocks: {
        HEX8: ElementBlockBase {
            cell_type: HEX8,
            connectivity: Regular(
                [[0, 1, 3, 2, 6, 7, 9, 8],
                 [2, 3, 5, 4, 8, 9, 11, 10],
                 [6, 7, 9, 8, 12, 13, 15, 14],
                 [8, 9, 11, 10, 14, 15, 17, 16],
                 [12, 13, 15, 14, 18, 19, 21, 20],
                 [14, 15, 17, 16, 20, 21, 23, 22]], shape=[6, 8], strides=[8, 1], layout=Cc (0x5), const ndim=2,
            ),
            fields: {},
            families: [0, 0, 0, 0, 0, 0], shape=[6], strides=[1], layout=CFcf (0xf), const ndim=1,
            groups: ArcGroups(
                {},
            ),
        },
    },
}

print(volumes) shows the two ingredients. The coords array lists every node with its coordinates (here 24 nodes, 3 values each). The element_blocks entry groups the connectivity of one element type; a Regular block stores it as a dense table where each row is one cell (6 HEX8 cells x 8 node ids each). Fields, families and groups are empty in a freshly built mesh.

volumes.to_pyvista().plot(show_edges=True)

Building mesh with custom connectivity

Sometimes blocks must be built by hand. mf.UMesh(coords) starts from a plain coordinates array, and add_regular_block("TYPE", conn) appends a block of a given element type from an explicit connectivity table. Here one mesh mixes three topologies: 9 isolated VERTEX nodes, a set of SEG2 edges and one QUAD4 face. to_pyvista(dim="all") renders every dimension at once.

x, y = np.meshgrid(np.linspace(0.0, 1.0, 5), np.linspace(0.0, 1.0, 5))
coords = np.c_[x.flatten(), y.flatten()]
conn = np.array(
    [
        [0, 1],
        [1, 6],
        [6, 5],
        [5, 0],
        [6, 7],
        [7, 12],
        [12, 11],
        [11, 6],
        [12, 17],
        [17, 16],
        [16, 11],
    ],
    dtype=np.uint,
)
mesh = mf.UMesh(coords)
mesh.add_regular_block("VERTEX", np.arange(13, 22, dtype=np.uint)[..., np.newaxis])
mesh.add_regular_block("SEG2", conn)
mesh.add_regular_block("QUAD4", np.array([[3, 4, 9, 8]], dtype=np.uint))
mesh.to_pyvista(dim="all").plot(cpos="xy", show_edges=True)


Read next: Getting started is the 30-second tour; Fields attaches data to a mesh like this one.

Input / Output

Figures use PyVista; verbose plotting boilerplate is omitted.

import numpy as np

import mefikit as mf
volumes = mf.build_cmesh(
    range(2), np.linspace(0.0, 1.0, 5), np.logspace(0.0, 1.0, 5) / 10.0
)

Memory exports

A UMesh can be handed to other libraries without ever touching the disk:

print(volumes.to_mc())
Unstructured mesh with name : "mf_UMesh"
Description of mesh : ""
Time attached to the mesh [unit] : 0 []
Iteration : -1 Order : -1
Mesh dimension : 3
Space dimension : 3
Info attached on space dimension : "" "" ""
Number of nodes : 50
Number of cells : 16
Cell types present : NORM_HEXA8
print(volumes.to_pyvista())
UnstructuredGrid (0x78585195b280)
  N Cells:    16
  N Points:   50
  X Bounds:   0.000e+00, 1.000e+00
  Y Bounds:   0.000e+00, 1.000e+00
  Z Bounds:   1.000e-01, 1.000e+00
  N Arrays:   0
volumes.to_pyvista().plot(show_edges=True)

print(volumes.to_meshio())
<meshio mesh object>
  Number of points: 50
  Number of cells:
    hexahedron: 16
print(volumes.to_json())
{"coords":{"v":1,"dim":[50,3],"data":[0.0,0.0,0.1,1.0,0.0,0.1,0.0,0.25,0.1,1.0,0.25,0.1,0.0,0.5,0.1,1.0,0.5,0.1,0.0,0.75,0.1,1.0,0.75,0.1,0.0,1.0,0.1,1.0,1.0,0.1,0.0,0.0,0.17782794100389226,1.0,0.0,0.17782794100389226,0.0,0.25,0.17782794100389226,1.0,0.25,0.17782794100389226,0.0,0.5,0.17782794100389226,1.0,0.5,0.17782794100389226,0.0,0.75,0.17782794100389226,1.0,0.75,0.17782794100389226,0.0,1.0,0.17782794100389226,1.0,1.0,0.17782794100389226,0.0,0.0,0.31622776601683794,1.0,0.0,0.31622776601683794,0.0,0.25,0.31622776601683794,1.0,0.25,0.31622776601683794,0.0,0.5,0.31622776601683794,1.0,0.5,0.31622776601683794,0.0,0.75,0.31622776601683794,1.0,0.75,0.31622776601683794,0.0,1.0,0.31622776601683794,1.0,1.0,0.31622776601683794,0.0,0.0,0.5623413251903491,1.0,0.0,0.5623413251903491,0.0,0.25,0.5623413251903491,1.0,0.25,0.5623413251903491,0.0,0.5,0.5623413251903491,1.0,0.5,0.5623413251903491,0.0,0.75,0.5623413251903491,1.0,0.75,0.5623413251903491,0.0,1.0,0.5623413251903491,1.0,1.0,0.5623413251903491,0.0,0.0,1.0,1.0,0.0,1.0,0.0,0.25,1.0,1.0,0.25,1.0,0.0,0.5,1.0,1.0,0.5,1.0,0.0,0.75,1.0,1.0,0.75,1.0,0.0,1.0,1.0,1.0,1.0,1.0]},"element_blocks":{"HEX8":{"cell_type":"HEX8","connectivity":{"Regular":{"v":1,"dim":[16,8],"data":[0,1,3,2,10,11,13,12,2,3,5,4,12,13,15,14,4,5,7,6,14,15,17,16,6,7,9,8,16,17,19,18,10,11,13,12,20,21,23,22,12,13,15,14,22,23,25,24,14,15,17,16,24,25,27,26,16,17,19,18,26,27,29,28,20,21,23,22,30,31,33,32,22,23,25,24,32,33,35,34,24,25,27,26,34,35,37,36,26,27,29,28,36,37,39,38,30,31,33,32,40,41,43,42,32,33,35,34,42,43,45,44,34,35,37,36,44,45,47,46,36,37,39,38,46,47,49,48]}},"fields":{},"families":{"v":1,"dim":[16],"data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},"groups":{}}}}

File read/write

read/write select the format from the file extension:

  • json
  • yaml / yml
  • vtk / vtu (legacy binary VTK 2.0)
  • vtkhdf (HDF5-based VTK)
  • cgns (HDF5-based CGNS)
  • med (medfile)

The legacy vtk reader/writer only handles the old binary VTK 2.0 format; the HDF5-based .vtkhdf and .cgns formats are the recommended options for modern, HPC-friendly storage.

Fields and groups

Cell-centered fields and element groups are stored alongside the geometry in every format. Coordinates are written once, and each field/group refers to cells through the same global cell ordering, so nothing is duplicated per element block.

FormatFieldsGroups
jsonall (any number of components)all
yaml/ymlall (any number of components)all
medall (any number of components)all
vtkhdfscalar/vector, single topological dimall (GroupData, 0-based)
cgnsscalar only, one solution per dimall (ZoneSubRegion_t, 1-based)
vtk/vtunone (legacy reader/writer, geometry only)none

Some restrictions apply to the HDF5 formats:

  • VTKHDF fields are only exported when the mesh has a single topological dimension; on mixed-dimension meshes they are skipped.
  • CGNS cell-centered solutions must be scalar, so multi-component fields are skipped. Each topological dimension gets its own FlowSolution node with a GridLocation matching that dimension (CellCenter, FaceCenter or EdgeCenter) and, when needed, a PointList. Groups are written as ZoneSubRegion_t nodes; a group spanning several dimensions is split into one node per dimension so each node has a single valid GridLocation. Vertex fields/groups cannot be represented and are skipped.
import pathlib

pathlib.Path("data").mkdir(exist_ok=True)
for ext in ("vtk", "yaml", "json", "vtkhdf", "cgns", "med"):
    volumes.write(f"data/volumes.{ext}")
    volumes_from_disk = mf.UMesh.read(f"data/volumes.{ext}")
    assert volumes_from_disk
    assert (
        volumes != volumes_from_disk
    )  # this is a new instance, with a different memory adress

Mesh extrusions

Figures use PyVista; verbose plotting boilerplate is omitted.

Extrusion sweeps a base mesh along a direction to build a mesh one dimension higher: a VERTEX becomes a SEG2, a SEG2 a QUAD4, a QUAD4 a HEX8. mefikit offers three flavours — plain extrude along an existing axis, extrude_parallel along any 3D line, and extrude_curv for a curvilinear sweep.

import numpy as np

import mefikit as mf

Building a 2D base mesh

Any mesh can be extruded, as long as each of its blocks is a lower-dimensional “slice”. Let us first build one by hand with mixed topologies (isolated nodes, edges and one quad), so that every sweeping demo pulls each block up one dimension at once:

x, y = np.meshgrid(np.linspace(0.0, 1.0, 5), np.linspace(0.0, 1.0, 5))
coords = np.c_[x.flatten(), y.flatten()]
conn = np.array(
    [
        [0, 1],
        [1, 6],
        [6, 5],
        [5, 0],
        [6, 7],
        [7, 12],
        [12, 11],
        [11, 6],
        [12, 17],
        [17, 16],
        [16, 11],
    ],
    dtype=np.uint,
)
mesh = mf.UMesh(coords)
mesh.add_regular_block("VERTEX", np.arange(13, 22, dtype=np.uint)[..., np.newaxis])
mesh.add_regular_block("SEG2", conn)
mesh.add_regular_block("QUAD4", np.array([[3, 4, 9, 8]], dtype=np.uint))
mesh.to_pyvista(dim="all").plot(cpos="xy", show_edges=True)

Extrusion along an existing axis

extrude(along) stacks copies of the base mesh at the node ids given by along. Here range(3) steps through three existing nodes, so the quad is swept into three HEX8 cells, the edges into QUAD4 faces and the vertices into SEG2 segments:

Build simple extruded mesh

extruded = mesh.extrude(range(3))
extruded.to_pyvista(dim="all").plot(show_edges=True)

Extrusion along a 3D line, with parallel z faces

extrude_parallel(line) sweeps the base mesh along an arbitrary 3D polyline; the layers follow the line while staying parallel to each other:

n = 50
x = np.sin(np.linspace(0.0, np.pi, n))
y = np.cos(np.linspace(0.0, np.pi, n))
z = np.linspace(0.0, 4.0, n)
line = np.c_[x, y, z]

extruded_par = mesh.extrude_parallel(line)
extruded_par.to_pyvista(dim="all").plot(show_edges=True)

Curvilinear extrusion

Finally, extrude_curv(line) builds a curvilinear sweep: the base mesh is swept along a curve and the nodes settle on it, so the result can be bent or wrapped — a natural fit for pipes, blades and other swept geometries:

mesh = mf.build_cmesh(range(2), range(2))
n = 20
x = np.zeros((n,))
y = np.cos(np.linspace(0.0, np.pi, n))
z = np.sin(np.linspace(0.0, np.pi, n))
line = np.c_[x, y, z]

extruded_curv = mesh.extrude_curv(line)
extruded_curv.to_pyvista(dim="all").plot(show_edges=True)

Mesh slicing

Figures use PyVista; verbose plotting boilerplate is omitted.

UMesh.slice(origin, normal) cuts a mesh with a hyperplane and returns a mesh of one dimension lower: a 3D volume becomes a 2D polygonal (PGON) surface embedded in 3D, and a 2D region becomes a 1D SEG2 line. In both cases the hyperplane passes through origin and is normal to normal.

import numpy as np

import mefikit as mf

Slicing a 3D volume

Let us build a box and cut it with a general oblique plane, neither through a mesh node nor aligned with an axis. The slice is a 2D mesh made of polygons, but its coordinates remain in 3D so it can be plotted with the source volume.

axis = np.linspace(0.0, 1.0, 11)
volume = mf.build_cmesh(axis, axis, axis)

origin = np.array([0.37, 0.42, 0.51])
normal = np.array([0.7, 1.1, 1.3])
surface = volume.slice(origin, normal)

surface.block_types(), surface.coords().shape
(['PGON'], (240, 3))
_, offsets = surface.blocks()["PGON"]
sizes, counts = np.unique(np.diff(offsets), return_counts=True)
dict(zip(sizes.tolist(), counts.tolist()))
{3: 92, 4: 53, 5: 29, 6: 33}

The output only contains the intersection of the volume with the plane. The cells are PGONs, even when the section is a quadrilateral. Here the general cut produces triangles, quadrilaterals, pentagons and hexagons.

plotter = pv.Plotter()
plotter.add_mesh(volume.to_pyvista(), style="wireframe", opacity=0.15)
plotter.add_mesh(surface.to_pyvista(), show_edges=True, color="tab:orange")
plotter.show()

Slicing a 3D volume along a line

slice_line(origin, direction) cuts the volume with the line through origin along direction. Here we use a general oblique line that does not pass through any mesh node. The result is a 1D SEG2 mesh whose coordinates remain in 3D, so it can be drawn on top of the volume.

line3d = volume.slice_line([0.23, 0.37, 0.11], [0.2, -0.3, 1.0])
line3d.block_types(), line3d.coords().shape
(['SEG2'], (16, 3))
plotter = pv.Plotter()
plotter.add_mesh(volume.to_pyvista(), style="wireframe", opacity=0.1)
plotter.add_mesh(
    line3d.to_pyvista(dim="all"),
    color="tab:green",
    line_width=6,
    render_lines_as_tubes=True,
)
plotter.show()

Transferring a field onto the slice

Slicing does not copy fields, because the target cells are not the source cells. The mf.transfer operators remap them. ConstantPiecewise samples the volume cell containing each slice-cell centroid, which is a natural choice for a piecewise-constant field; MovingLeastSquares or InverseDistance can be used when a smoother result is wanted.

volume.fields["T"] = mf.X + 2.0 * mf.Y + 3.0 * mf.Z

surface_transfer = mf.transfer.ConstantPiecewise(volume, surface)
surface.fields["T"] = surface_transfer("T")

line_transfer = mf.transfer.ConstantPiecewise(volume, line3d)
line3d.fields["T"] = line_transfer("T")

surface.fields["T"].values()["PGON"][:5]
array([2.1, 2.2, 2.1, 2.2, 2.3])

The slice now carries T, and the values follow the analytic field T(x, y, z) = x + 2y + 3z sampled in the volume cells:

plotter = pv.Plotter()
plotter.add_mesh(volume.to_pyvista(), style="wireframe", opacity=0.1)
plotter.add_mesh(surface.to_pyvista(), scalars="T", show_edges=True)
plotter.add_mesh(
    line3d.to_pyvista(dim="all"),
    scalars="T",
    line_width=6,
    render_lines_as_tubes=True,
)
plotter.show()

Slicing a 2D mesh

In 2D the cut is a line. Here we use a general oblique line that does not pass through mesh nodes; the result is a SEG2 mesh. Its field is transferred in the same way.

domain = mf.build_cmesh(axis, axis)
line = domain.slice_line([0.13, 0.27], [1.0, 1.7])

domain.fields["T"] = mf.X**2 + mf.Y
line.fields["T"] = mf.transfer.ConstantPiecewise(domain, line)("T")

line.block_types(), line.coords().shape
(['SEG2'], (16, 2))
plotter = pv.Plotter()
plotter.add_mesh(domain.to_pyvista(), style="wireframe", opacity=0.35)
plotter.add_mesh(
    line.to_pyvista(dim="all"), scalars="T", line_width=6, render_lines_as_tubes=True
)
plotter.show()

Geometric transforms

Figures use PyVista; verbose plotting boilerplate is omitted.

import numpy as np

import mefikit as mf

coords = np.array(
    [
        [0.0, 0.0],
        [1.0, 0.0],
        [0.0, 1.0],
        [1.0, 1.0],
    ]
)
mesh = mf.UMesh(coords)
mesh.add_regular_block("QUAD4", np.array([[0, 1, 3, 2]], dtype=np.uint))

All angles are given in radians. A Transform is an affine transformation represented by a 4x4 homogeneous matrix (last row 0 0 0 1). UMesh objects are transformed out-of-place: each transform returns a new mesh and leaves the source unchanged.

Out-of-place transforms

translated = mesh.translate([10.0, 0.0])
translated.to_pyvista().plot()

rotated = mesh.rotate([0.0, 0.0, 1.0], np.pi / 6)
rotated.to_pyvista().plot()

mirrored = mesh.rotate([0.0, 0.0, 1.0], np.pi / 6).mirror([1.0, 0.0, 0.0])
mirrored.to_pyvista().plot()

scaled = mesh.scale([2.0, 3.0])
scaled.to_pyvista().plot()

uniform = mesh.scale_uniform(4.0)
uniform.to_pyvista().plot()

The input mesh is never modified.

Unidirectional (left-to-right) composition

Transform supports composition in both conventions:

  • a @ b (matrix product) applies b first;
  • a.then(b) applies a, then b.
tr = mf.Transform.translation([1.0, 0.0]).then(
    mf.Transform.rotation([0.0, 0.0, 1.0], np.pi / 2)
)
out = mesh.transform(tr)
assert np.allclose(out.coords()[1], [0.0, 2.0], atol=1e-9)

matrix = mf.Transform.translation([1.0, 2.0, 3.0]) @ mf.Transform.scaling([2.0])
assert np.allclose(
    matrix.matrix(),
    mf.Transform.translation([1.0, 2.0, 3.0]).matrix()
    @ mf.Transform.scaling([2.0]).matrix(),
)

Rather than a Transform, mesh.transform(...) also accepts a raw 4x4 numpy array, and Transform.from_matrix(...) wraps one.

mat = np.eye(4)
mat[0, 3] = 7.0
assert np.isclose(mesh.transform(mat).coords()[0, 0], 7.0)

Dimensional consistency is enforced: trying to move a 2D (or 1D) mesh out of its plane (or line) raises a ValueError.

try:
    mesh.translate([0.0, 0.0, 0.5])
except ValueError as err:
    print(err)
This transform moves the mesh out of its plane/line: rows beyond the space dimension must leave the extra coordinates unchanged.

Duplicating a mesh

duplicate(step, n) returns n copies, each transformed by the powers step, step @ step, … of step.

ts = mf.Transform.translation([0.0, 3.0, 0.0])
rt = mf.Transform.rotation([0.0, 0.0, 1.0], np.pi / 4)
column = mesh.duplicate(ts @ rt, 3)
assert column.coords().shape[0] == 12
column.to_pyvista().plot(show_edges=True)

Arbitrary arrangements can be built with the module-level aggregate / concat functions, which concatenate meshes while preserving blocks, fields, families and groups (element ids are relabelled so that the resulting mesh stays valid).

line = mf.concat(mesh, mesh.translate([5.0, 0.0]))
three = mf.aggregate([mesh, mesh.translate([5.0, 0.0]), mesh.translate([15.0, 0.0])])
assert line.coords().shape[0] == 8
assert three.coords().shape[0] == 12
line.to_pyvista().plot()
three.to_pyvista().plot()

Transforms preserve the mesh metadata: blocks, fields, families and groups survive untouched.

Reconstructing coordinates

For non-affine coordinate changes, use UMesh.from_mesh. It accepts a same-shaped coordinate array and preserves the selected source connectivity, fields, families and groups. Omitting coords reuses the source coordinates.

coords = mesh.coords()
coords[:, 0] *= 2.0
coords[:, 1] *= coords[:, 0] + 1.0
warped = mf.UMesh.from_mesh(
    mesh,
    coords,
)
# assert np.allclose(warped.coords()[:, 0], mesh.coords()[:, 0] ** 2)
assert np.allclose(warped.coords(), coords)
warped.to_pyvista().plot()

from_mesh can select source element blocks by topological dimension or by element type. The two selectors are mutually exclusive; the source mesh is never changed.

surfaces = mf.UMesh.from_mesh(mesh, dim=2)
quads = mf.UMesh.from_mesh(mesh, element_types=["QUAD4"])

Coordinate arrays are structurally validated when a mesh is reconstructed; geometric quality checks are not performed.

Topological tools

Figures use PyVista; verbose plotting boilerplate is omitted.

The tools below all rest on one idea: the subentities of an element — its faces, edges and vertices. descend decomposes every element into subentities; boundaries keeps only those on the outside (owned by a single element); and connected_components / crack relate elements that share a lower-dimensional subentity. Two elements are neighbours when they share such a subentity — two volumes sharing a face, two faces sharing an edge, and so on. Everything here assumes a topologically valid mesh (see The mesh model).

import numpy as np

import mefikit as mf

Descending connectivity

Every topological tool here builds and returns a new mesh; the *_update variants turn them into in-place operations (below). descend computes the descending connectivity of a mesh: it decomposes each element into its boundary (cells into faces, faces into edges, edges into vertices) and returns a new mesh of the requested dimension.

Start from the structured volumes built below:

x = range(3)
y = np.linspace(0.0, 3.0, 5, endpoint=True)
z = np.logspace(-0.5, 1, 4, endpoint=True)
volumes = mf.build_cmesh(x, y, z)

Simple descending

Chaining .descend() walks down one dimension at a time — volumes, faces, edges, vertices:

faces = volumes.descend()
edges = faces.descend()
vertex = edges.descend()

Submesh in one go

target_dim jumps straight to the wanted dimension, without chaining:

  • descend(target_dim=1) returns the edges directly,
  • descend(target_dim=0) returns the vertices directly.
edges = volumes.descend(target_dim=1)
vertex = volumes.descend(target_dim=0)

Boundaries computation

boundaries is the closure of a mesh: it keeps only the elements on the outside, not shared with any neighbour — exactly the ones you need for boundary conditions. It differs from descend, which returns every face of the mesh:

face_bounds = volumes.boundaries()
edge_bounds = volumes.boundaries(target_dim=1)
vertex_bounds = volumes.boundaries(target_dim=0)

Descend / boundaries update

Both operations come in an in-place flavour: descend_update / boundaries_update modify the mesh instead of returning a new one.

volumes.boundaries_update()
volumes.boundaries_update(target_dim=1)
volumes.to_pyvista(dim="all").shrink(0.8).plot(show_edges=True)

When using the _update version, the elements of the same dimension of the generated mesh are returned as a new mesh.

old_face_mesh = volumes.descend_update()
volumes.to_pyvista(dim="all").shrink(0.8).plot(show_edges=True)

old_face_mesh.to_pyvista().shrink(0.8).plot(show_edges=True)

Connected components

connected_components() splits a mesh into its connected parts. The link_dim argument decides what glues two elements together: sharing an edge (link_dim=1) or sharing a node (link_dim=0). Below, a small ribbon of QUAD4 cells is a single component when glued by edge, but falls apart as soon as only two cells touch at a corner:

x, y = np.meshgrid(np.linspace(0.0, 1.0, 5), np.linspace(0.0, 1.0, 5))
coords = np.c_[x.flatten(), y.flatten()]
conn = np.array(
    [
        [0, 1, 6, 5],
        [6, 7, 12, 11],
        # [2, 3, 8, 7],
        [11, 12, 17, 16],
    ],
    dtype=np.uint,
)
mesh = mf.UMesh(coords)
mesh.add_regular_block("QUAD4", conn)
mesh.add_regular_block("VERTEX", np.arange(len(coords), dtype=np.uint)[..., np.newaxis])
compos_link_edge = mesh.connected_components(link_dim=1)
compos_link_node = mesh.connected_components(link_dim=0)

print(f"{len(compos_link_edge)=}")
print(f"{len(compos_link_node)=}")
len(compos_link_edge)=2
len(compos_link_node)=1

Crack

crack is the exact opposite of merge_nodes: it duplicates the nodes that sit on a given (descending) mesh, so that the result is dis-connected there — each element along the crack line gets its own copy of those nodes. Here the hexahedral stack is cracked along all its faces, growing from 1 to several connected components:

x = range(2)
y = np.linspace(0.0, 3.0, 3, endpoint=True)
z = np.logspace(0.0, 1.0, 3, endpoint=True)
volumes = mf.build_cmesh(x, y, z)
faces = volumes.descend()
cracked = volumes.crack(faces)
edges = faces.descend()
compos_original = volumes.connected_components()
compos_cracked = cracked.connected_components()

assert len(compos_original) == 1

n_compos = len(compos_cracked)

Split

split cuts every cell into 2^n smaller cells of the same element type (n = topological dimension), keeping the domain and its topology unchanged. Each HEX8 of the mesh below becomes 8 sub-cells:

x = np.linspace(0.0, 3.0, 2, endpoint=True)
y = np.logspace(0.0, 1.0, 2, endpoint=True)
z = range(2)
mesh = mf.build_cmesh(x, y, z)
mesh_splitted = mesh.split()

Polyze

polyze re-emits a regular mesh as a polyhedral one: 2D cells become PGON and 3D cells PHED. unpolyze converts them back. Mesh-generation codes often output polyhedra, hence this round-trip:

x = np.linspace(0.0, 3.0, 4, endpoint=True)
y = np.logspace(0.0, 1.0, 4, endpoint=True)
mesh = mf.build_cmesh(x, y)
print(mesh.blocks())
{'QUAD4': array([[ 0,  1,  5,  4],
       [ 1,  2,  6,  5],
       [ 2,  3,  7,  6],
       [ 4,  5,  9,  8],
       [ 5,  6, 10,  9],
       [ 6,  7, 11, 10],
       [ 8,  9, 13, 12],
       [ 9, 10, 14, 13],
       [10, 11, 15, 14]], dtype=uint64)}
mesh_polyzed = mesh.polyze()
print(mesh_polyzed.blocks())
{'PGON': (array([ 0,  1,  5,  4,  1,  2,  6,  5,  2,  3,  7,  6,  4,  5,  9,  8,  5,
        6, 10,  9,  6,  7, 11, 10,  8,  9, 13, 12,  9, 10, 14, 13, 10, 11,
       15, 14], dtype=uint64), array([ 4,  8, 12, 16, 20, 24, 28, 32, 36], dtype=uint64))}
mesh_polyzed.to_pyvista().plot(show_edges=True)

unpolyzed = mesh_polyzed.unpolyze()
print(unpolyzed.blocks())
unpolyzed.to_pyvista().plot(show_edges=True)
{'QUAD4': array([[ 0,  1,  5,  4],
       [ 1,  2,  6,  5],
       [ 2,  3,  7,  6],
       [ 4,  5,  9,  8],
       [ 5,  6, 10,  9],
       [ 6,  7, 11, 10],
       [ 8,  9, 13, 12],
       [ 9, 10, 14, 13],
       [10, 11, 15, 14]], dtype=uint64)}

Stitch

Meshes are often modeled as separate blocks that were meshed independently, so their nodes do not match on the boundaries they share and they cannot be used as a single mesh. mf.stitch makes them conformal: the faces of each block are split to match the faces of its neighbours.

Here a plate made of a single hexahedron sits below a block of four hexahedra. The plate’s top face is one square while the block’s bottom is four squares, so they do not match.

plate = mf.build_cmesh([0.0, 2.0], [0.0, 2.0], [0.0, 1.0])
block = mf.build_cmesh([0.0, 1.0, 2.0], [0.0, 1.0, 2.0], [1.0, 2.0])

stitched = mf.stitch([plate, block])

print(list(stitched.blocks()))
print(f"{stitched.num_elements()=}")
['PHED']
stitched.num_elements()=5

plate = mf.build_cmesh([0.0, 2.0], [0.0, 2.0], [0.0, 1.0])
block = mf.build_cmesh([0.0, 1.0, 2.2], [0.0, 1.0, 1.5], [1.0, 2.0])
other = mf.build_cmesh([0.0, 1.0, 1.9], [1.5, 2.0], [1.0, 2.0])

stitched = mf.stitch([plate, block, other])

print(list(stitched.blocks()))
print(f"{stitched.num_elements()=}")
['PHED']
stitched.num_elements()=7
stitched.to_pyvista().plot(show_edges=True)

Geometrical tools

Figures use PyVista; verbose plotting boilerplate is omitted.

import numpy as np

import mefikit as mf

Snap points

mesh.snap(mesh2, eps) moves the nodes of mesh so that they coincide with the nodes of mesh2 that are within eps. Below, two staggered grids are offset by about one cell size:

x = np.linspace(0.0, 3.0, 10, endpoint=True)
mesh = mf.build_cmesh(x, x)

eps = 0.1
dec = x[-1] / len(x) + eps
x2 = np.linspace(dec, x[-1] + dec, len(x), endpoint=True)
mesh2 = mf.build_cmesh(x2, x2)

Note: epsilon value used in the following operation is big enough so that there are multiple candidates for some points, but low enough so that there is no degenerated cell created.

snaped = mesh.snap(mesh2, eps=x[-1] / len(x))

Merge nodes

merge_nodes() collapses the duplicated nodes of a single mesh according to a tolerance. It is the natural counterpart of crack: the mesh below was built with a duplicated internal interface (hence many connected components), and the merge re-glues it into one piece:

x = range(2)
y = np.linspace(0.0, 3.0, 3, endpoint=True)
z = np.logspace(0.0, 1.0, 3, endpoint=True)
volumes = mf.build_cmesh(x, y, z)
faces = volumes.descend()
cracked = volumes.crack(faces)
merged = cracked.merge_nodes()
edges = faces.descend()
compos_merged = merged.connected_components()
compos_cracked = cracked.connected_components()

assert len(compos_merged) == 1

n_compos = len(compos_cracked)

Overlay

overlay computes the boolean combination of two 2D meshes. The two grids below are staggered by half a cell, and we apply the four classic operations plus the two ways to imprint one grid into the other:

The intersection is valid in the following conditions :

  • mesh1 and mesh2 are valid (no self recovering),
  • mesh1 and mesh2 are 2d (xy),
  • correctly oriented (CCW element connectivity),
  • and fully merged (no unmerged nodes).

Mesh1 and mesh2 may have any number of kind of 2d elements of the first order (TRI3, QUAD4, PGON). A future version of this algorithm will work with quadratic elements (TRI7, QUAD8, QPGON).

x = np.linspace(0.0, 3.0, 4, endpoint=True)
mesh = mf.build_cmesh(x, x)

eps = 0.5
dec = x[-1] / len(x) + eps
x2 = np.linspace(dec, x[-1] + dec, len(x), endpoint=True)
mesh2 = mf.build_cmesh(x2, x2)

imprint2on1 = mesh.overlay(mesh2, mf.OverlayOperation.IMPRINT)
imprint1on2 = mesh2.overlay(mesh, mf.OverlayOperation.IMPRINT)

union = mesh.overlay(mesh2, mf.OverlayOperation.UNION)
diff = mesh.overlay(mesh2, mf.OverlayOperation.DIFFERENCE)
symdiff = mesh.overlay(mesh2, mf.OverlayOperation.SYMMETRIC_DIFFERENCE)
intersection = mesh.overlay(mesh2, mf.OverlayOperation.INTERSECTION)

meshes = [
    [mesh, mesh2],
    [union, intersection],
    [diff, symdiff],
    [imprint2on1, imprint1on2],
]
labels = [
    ["Mesh1", "Mesh2, staggered"],
    ["Union", "Intersection"],
    ["Difference", "Symmetric difference"],
    ["Imprint over 1", "Imprint over 2"],
]

The ugly cell in the center in the difference and symmetric difference comes from the plotting of non convex cells in pyvista. It is just a known plotting bug (due to optimisation quirks).

Surface overlay

overlay_surfaces is the 3D counterpart of overlay: it imprints two 2D surfaces (meshes embedded in 3D space) wherever they coincide.

overlay_surfaces imprints two 2D surfaces (meshes embedded in 3D space) wherever they coincide. Both surfaces must be piecewise planar; here they are built in the plane z = 0 and tilted onto a common plane with the same Transform.

The two refined surfaces share their intersection nodes, so they become mutually conformal on the overlap. Parts not covered by the other surface are copied verbatim.

def quad_surface(extent, n):
    """Flat QUAD4 grid spanning extent=(xmin, xmax, ymin, ymax) in the plane z=0."""
    x = np.linspace(extent[0], extent[1], n + 1)
    y = np.linspace(extent[2], extent[3], n + 1)
    flat = mf.build_cmesh(x, y)
    coords = np.c_[flat.coords(), np.zeros(flat.coords().shape[0])]
    mesh = mf.UMesh(coords)
    mesh.add_regular_block("QUAD4", flat.blocks()["QUAD4"])
    return mesh


# Two quad surfaces with different sizes and discretizations on the same plane.
surface1 = quad_surface((0.0, 2.0, 0.0, 2.0), n=4)
surface2 = quad_surface((1.0, 2.8, 0.5, 1.9), n=5)

# Tilt both onto the same plane of 3D space (out-of-place transforms).
tilt = mf.Transform.rotation([1.0, 0.0, 0.0], -0.6) @ mf.Transform.rotation(
    [0.0, 1.0, 0.0], 0.5
)
surface1 = surface1.transform(tilt)
surface2 = surface2.transform(tilt)
overlay = surface1.overlay_surfaces(surface2)

# The refined surfaces are mutually conformal: they share the very same nodes.
assert np.array_equal(
    np.asarray(overlay.refined1.coords()), np.asarray(overlay.refined2.coords())
)

# The parents maps relate each input face to the elements it produced.
print("surface1:", len(overlay.parents1), "input faces")
print("surface2:", len(overlay.parents2), "input faces")
surface1: 16 input faces
surface2: 25 input faces

Fields

Figures use PyVista; verbose plotting boilerplate is omitted.

import numpy as np

import mefikit as mf

Field expressions

FieldExpr are composition of floats and mf.Field(“fieldname”) or custom fields. Available operations on fields include :

  • binary expresions + - / *
  • unary expr sin(), cos(), abs(), ln(), log10(), exp()
  • primitives :
    • M: the measure, ie length/area/volume of an element
    • C: the node centroid of an element, not the volume barycenter
    • X: the X compo of the node centroid
    • Y: the Y compo of the node centroid
    • Z: the Z compo of the node centroid

Scalar binary operations

toto = mf.Field("toto")
tata = mf.Field("tata")
toto + tata
toto * tata
toto - tata
toto / tata
toto + 2.0
toto - 2.0
toto * 2.0

Scalar unary ops

toto.sin()
toto.cos()
toto.abs()
toto.exp()
toto.ln()
toto.square()
toto.sqrt()
toto.tan()
toto.log10()
<Field at 0x72523d78a7b0>

Vector ops

toto.dot(tata)
toto @ tata  # same as dot
toto[0]

Primitives

m = mf.M  # measure: length/area/volume
c = mf.C  # node centroids
x = mf.X  # x compo of node centroid
y = mf.Y  # y compo of node centroid
z = mf.Z  # z compo of node centroid
n = mf.Normal  # normal to n-1 dim elements, ie 2d elems in 3d or 1d elems in 2d
nx = mf.Nx  # x compo of element normal
ny = mf.Ny  # y compo of element normal
nz = mf.Nz  # z compo of element normal

How does it work?

The operations build a binary operation tree structure. Mefikit knows how to interpret this binary tree to compute fields.

print(toto * mf.M + 3.0 * mf.X)
BinaryExpr {
    operator: Add,
    left: BinaryExpr {
        operator: Mul,
        left: Field(
            "toto",
        ),
        right: Measure,
    },
    right: BinaryExpr {
        operator: Mul,
        left: Array(
            3.0, shape=[], strides=[], layout=CFcf (0xf), dynamic ndim=0,
        ),
        right: X,
    },
}

This is quite handfull because it enables two patterns:

  • reusability and composition of filters
  • evaluation optimizations of selections : some selection filters are evaluated in parallel, some are evaluated first if they are discriminant

Mesh fields mapping

x = np.logspace(-5, 0.0, 50)
z = np.linspace(0.0, 0.1, 3)
mesh2 = mf.build_cmesh(x, x, z)
mesh2.to_pyvista().plot(show_edges=True)

The fields attribute is dict-like: fields can be accessed, modified, added and defined through it, using field expressions evaluated on the mesh.

Field expressions are independent from the mesh and light; fields are the evaluated expressions stored alongside the mesh.

mesh2.fields["Measure"] = mf.M
mesh2.to_pyvista().plot()

mesh2.fields["toto"] = mf.X + mf.Y

# List and look up fields by name.
print(mesh2.fields.keys())
print(mesh2.fields.values())
['Measure', 'toto']
[FieldRef("Measure"), FieldRef("toto")]
for n, f in mesh2.fields.items():
    print(n, ":", f)
Measure : FieldRef("Measure")
toto : FieldRef("toto")
del mesh2.fields["toto"]  # remove it
print(mesh2.fields)
FieldsMapping(["Measure"])

Field references

Fields live in a dict-like mapping on the mesh, keyed by name. Each entry is a handle (FieldRef) to read values, reduce them, or write through selectors. Fields reference are always bound to a given mesh.

mes = mesh2.fields["Measure"]
print("shape:", mes.shape, "| elements:", len(mes))
shape: (1,) | elements: 4802

Whole reductions

Field references support reductions evaluated eagerly :

# Whole-domain reductions over every element carrying the field.
print(mes.min(), mes.max(), mes.mean())
3.507414294773286e-13 0.002192327517292864 2.0824239902124112e-05

Numpy input/ouput

# Bulk export as {etype: array} (or a single array via `.numpy()` when the
# mesh has one element type).
vals = mes.values()
print(vals.keys())
shortcut_vals = mes.numpy()
print(shortcut_vals.shape)
assert np.allclose(vals["HEX8"], shortcut_vals)
dict_keys(['HEX8'])
(4802,)
# Bulk import a dict[str, ndarray] as new field
# Field size checks are done so that the field lay on all elements of the same dim.
mesh2.fields["toto"] = {"HEX8": shortcut_vals * 3.0}

Regional filtered fields

Lazy selections (see selection notebook) allow to compute regional reduction with any field expression, including plain existing field names as strings.

rect = mf.sel.bbox([0.25, 0.25, 0.0], [0.7, 0.7, 0.1])
zone = mesh2.select(rect)
print(zone.mean("toto"), zone.max(mf.M * 4))
0.0013598121884658915 0.003426116772966117

Writes accept scalars, arrays, field expressions or existing field names, targeted by wildcards (...) or selectors.

mesh2.fields["Scratch"] = 0.0  # create by broadcast
mesh2.fields["Scratch"][...] = (
    "Measure"  # whole selection, copy an existing field inplace
)

A field can be overwritten on a specific region. The overwrite is done using an expression formulae which can even reference the previous field values.

sel = mf.sel.bbox([0.0, 0.0, 0.0], [0.3, 1.0, 0.1])
mesh2.fields["Scratch"][sel] = mf.Field("Scratch") * 2  # scaled sub-region
sel2 = mf.sel.sphere(center=[0.5, 0.5, 0.05], r=0.3)
m = mesh2.select(sel2).mean("Scratch")  # compute the mean of scratch in a region
mesh2.fields["Scratch"][sel2] = m  # assign this constant value to the whole region

Direct field expression evaluation to numpy

It is not recommended to bypass the .fields storage — it provides complete integration with mefikit — but it is nevertheless possible to evaluate an expression and export the result directly as a numpy array. The eval method does exactly this:

m = mf.Field("Measure")
m2 = mf.Field("4 * M2")
mesh2.fields["4 * M2"] = 4.0 * m * m
mesh2.eval(m2 - 4.0 * mf.M.square())
{'HEX8': array([0., 0., 0., ..., 0., 0., 0.], shape=(4802,))}

Field to selection

Field expressions can be converted to threshold selections expressions. The available comparisons are <, <=, >, >=, == :

maxM = mesh2.select(mf.sel.all()).max(mf.M)
minM = mesh2.select(mf.sel.all()).min(mf.M)
meanM = mesh2.select(mf.sel.all()).mean(mf.M)
lb = (minM + meanM) / 2.0
hb = (maxM + meanM) / 2.0
m = mf.Field("Measure")

th = (m > lb) & (m <= hb)
m2sel = mesh2.select(th).to_mesh()

Those threshold selections can be combined with other selections.

r = mf.sel.bbox([0.5, 0.5, 0.0], [0.8, 0.8, 0.1])
c = mf.sel.sphere([0.12, 0.12, 0.05], 0.05)
mesh2.select(th - r - c).to_mesh().to_pyvista().plot()

Vector/Matrix/Tensor fields

Normals of hyperplane dim elements

Let first add the elements of the boundaries to the current mesh :

mesh2.boundaries_update()

Now normals can be computed on those elements.

mesh2.fields["N"] = mf.Normal
mesh2.fields["N"].values()
{'QUAD4': array([[ 0.,  0., -1.],
        [ 0.,  0., -1.],
        [ 0.,  0.,  1.],
        ...,
        [ 0.,  0.,  1.],
        [ 0.,  0.,  1.],
        [ 0.,  0.,  1.]], shape=(5194, 3))}

Dot product / matrix multiplication is available through a numpy like syntax with the .dot operator or the @ operator :

ev = mesh2.eval(mf.Normal @ np.array([0.0, 1.0, 0.0]))["QUAD4"]
(ev > 0.5).sum()  # number of faces oriented towards y
np.int64(98)
mesh2.groups["top"] = mf.Nz > 0.9
top = mesh2.select(mf.sel.group("top")).to_mesh()


Read next: Field transfers moves fields from one mesh to another, reusing the same expressions.

Time series

Figures are omitted; the API is the focus here.

import numpy as np

import mefikit as mf

Creating a time series

A time series is a set of fields sharing a common base name, each step stored as a field named "<base>_step_<n>_time_<t>". Steps are numbered automatically (0, 1, 2, ...), and the time stamps are yours to choose: they need not be sorted nor unique.

mesh = mf.build_cmesh(np.linspace(0.0, 1.0, 3), np.linspace(0.0, 1.0, 3))
mesh.time_series["T"].add(20.0, time=0.0)
FieldRef("T_step_0_time_0")
mesh.time_series["T"].add(40.0, time=0.5)
mesh.time_series["T"].add(60.0, time=1.0)
FieldRef("T_step_2_time_1")
mesh.time_series
TimeSeriesMapping(["T"])
mesh.fields.keys()  # the same data, seen as raw steps
['T_step_0_time_0', 'T_step_1_time_0.5', 'T_step_2_time_1']

Step access

mesh.time_series maps base names to TimeSeries handles. A handle knows its base, the dimension it lives on, and its ordered steps.

s = mesh.time_series["T"]
s.base, s.dim()
('T', 2)
s.steps()
[0, 1, 2]
s.times()
[0.0, 0.5, 1.0]
s.at(0).numpy()  # exact step
array([20., 20., 20., 20.])
s.at_time(0.5).numpy()  # exact time
array([40., 40., 40., 40.])
s.nearest(0.7).numpy()  # closest time
array([40., 40., 40., 40.])
s.latest().numpy()  # last step
array([60., 60., 60., 60.])
s[1]  # int -> step
s.nearest(0.9)  # float lookups go through nearest()/at_time()
FieldRef("T_step_2_time_1")

TimeSeries also supports the usual collection protocol.

list(s)  # (time, FieldRef) pairs, in step order
[(0.0, FieldRef("T_step_0_time_0")),
 (0.5, FieldRef("T_step_1_time_0.5")),
 (1.0, FieldRef("T_step_2_time_1"))]
s.items()  # (step, time, FieldRef) triples
[(0, 0.0, FieldRef("T_step_0_time_0")),
 (1, 0.5, FieldRef("T_step_1_time_0.5")),
 (2, 1.0, FieldRef("T_step_2_time_1"))]
(len(s), 1 in s, 7 in s)
(3, True, False)
s  # compact repr
TimeSeries('T', dim=2) {0:0, 1:0.5, 2:1}

Growing a series

add appends the next step (max step + 1) with the given time. Values accept the same inputs as fields: scalars, arrays, per-block dicts, field expressions,

mesh.time_series["T"].add(np.array([1.0, 2.0, 3.0, 4.0]), time=1.5)
FieldRef("T_step_3_time_1.5")
s.times()
[0.0, 0.5, 1.0, 1.5]
s.at(3).numpy()
array([1., 2., 3., 4.])

Mutating steps

Timestamps can be rewritten in place, and steps removed again.

s.set_time(0, -0.1)  # re-stamp step 0
s.times()
[-0.1, 0.5, 1.0, 1.5]
s.remove(1)
print(s.steps(), s.times())
[0, 2, 3] [-0.1, 1.0, 1.5]

TimeSeries is also subscript-settable / deletable through dunder methods.

del s[3]
print(s.steps(), s.times())
[0, 2] [-0.1, 1.0]

Renaming a series

Renaming moves every step to a new base name, and the handle follows.

s.rename("Temperature")
print(s.base)
Temperature
mesh.time_series
TimeSeriesMapping(["Temperature"])
sorted(mesh.fields.keys())
['Temperature_step_0_time_-0.1', 'Temperature_step_2_time_1']

Coexisting with plain fields

Static, non-stepped fields live alongside the series and are untouched by any of the time-series helpers.

mesh.fields["steady"] = 3.0
print(sorted(mesh.fields.keys()))
['Temperature_step_0_time_-0.1', 'Temperature_step_2_time_1', 'steady']

Limitations

Time series are a light naming scheme over ordinary fields: they do not model MED’s multi-step fields. MED import/export currently only handle the first step of a series; a conversion with time-stepping is not provided (yet).

Selection tool

Figures use PyVista; verbose plotting boilerplate is omitted.

import numpy as np

import mefikit as mf

Element selection expressions

Elements can be selected based on their:

  • types
  • ids
  • dimensions

Elements can be selected based on their centroid position. The selection methods using centroids are :

  • bbox
  • sphere
  • rectangle
  • circle

As you can guess, bbox and sphere should be used for 3d meshes and rectangle and circle for 2d meshes.

Elements can be selected based on the nodes position and a boolean : whether to select element with all nodes matching the condition or any node matching the condition.

  • nbbox
  • nsphere
  • nrect
  • ncircle
  • nids

Elements can be selected based on their group membership :

  • group(name)
  • exclude_group(name)

Elements can be selected based on their scalar fields values :

  • FieldExpr > FieldExpr
  • FieldExpr >= FieldExpr
  • FieldExpr < FieldExpr
  • FieldExpr <= FieldExpr
  • FieldExpr == FieldExpr

Wherever a selector is expected, the wildcards None, ... and [:] select every element — the explicit form is mf.sel.all().

sphere = mf.sel.sphere([0.5, 0.5, 0.5], 0.5)
clip_x = mf.sel.bbox([0.5, -np.inf, -np.inf], [np.inf, np.inf, np.inf])  # x > 0.5
compound_sel = ~(sphere & clip_x)

Selections are light objects: they are cheap to create and combine, and independent from any support mesh. You should just not mix 2d selectors with 3d selectors (sphere vs circle, bbox vs rectangle).

How does it work?

Each object generated by a selection function (a function from the mf.sel module) is of the Selection type. It implements operators so that it knows how to compose into an expression. That way an expression generates a new SelectionExpr which can be interpreted by the .select(expr) method.

print(sphere)
CentroidSelection(
    Sphere {
        center: [
            0.5,
            0.5,
            0.5,
        ],
        r: 0.5,
    },
)
print(compound_sel)
NotExpr(
    NotExpr(
        BinarayExpr(
            BinarayExpr {
                operator: And,
                left: CentroidSelection(
                    Sphere {
                        center: [
                            0.5,
                            0.5,
                            0.5,
                        ],
                        r: 0.5,
                    },
                ),
                right: CentroidSelection(
                    BBox {
                        min: [
                            0.5,
                            -inf,
                            -inf,
                        ],
                        max: [
                            inf,
                            inf,
                            inf,
                        ],
                    },
                ),
            },
        ),
    ),
)

You can see two layers of NotExpr and BinaryExpr. That is perfectly normal, it does not mean that the operation is applied twice, both NotExpr operations and both BinaryExpr op actually comes from different namespaces and it is just a form of encapsulation (first is a variant, second is an enum).

Select to extract part of a mesh

Here the types manipulated are Selection. They are simple objects that know how to compose themselves. When applied on a mesh the mesh selection is computed.

clip = mf.sel.bbox([-np.inf, -np.inf, -np.inf], [np.inf, np.inf, 0.5])
sphere = mf.sel.sphere([0.5, 0.5, 0.5], 0.5)
x = np.linspace(0.0, 1.0, 20, endpoint=True)
volumes = mf.build_cmesh(x, x, x)
volumes.to_pyvista().plot(show_edges=True)

volumes.select(clip).to_mesh().to_pyvista().plot()

volumes.select(sphere).to_mesh().to_pyvista().plot()

Selection composition

One of the great strengths of select is its composability. See for yourself: the operators &, |, ^, - and ~ are available.

2D composition examples

x = np.linspace(0.0, 2.0, 100)
y = np.linspace(0.0, 1.0, 50)
faces = mf.build_cmesh(x, y)
circle1 = mf.sel.circle([0.75, 0.5], 0.5)
circle2 = mf.sel.circle([1.25, 0.5], 0.5)
union = faces.select(circle1 | circle2).to_mesh()

intersection = faces.select(circle1 & circle2).to_mesh()

sym_diff = faces.select(circle1 ^ circle2).to_mesh()

diff = faces.select(circle1 - circle2).to_mesh()

notsel = faces.select(~circle1).to_mesh()

A 3D complex example

sphere = mf.sel.sphere([0.5, 0.5, 0.5], 0.5)
clip_x = mf.sel.bbox([0.5, -np.inf, -np.inf], [np.inf, np.inf, np.inf])  # x > 0.5
clip_z = mf.sel.bbox([-np.inf, -np.inf, -np.inf], [np.inf, np.inf, 0.5])  # z < 0.5
volumes.select(
    (clip_x & sphere & clip_z) | (sphere & ~clip_x & ~clip_z)
).to_mesh().to_pyvista().plot()

Select API

.select() returns a lazy view: ids(), len(), to_mesh() and reductions evaluate it on demand.

volumes.select(sphere)
SelectionResult(n_elements=3695)

The number of elements referenced here is the number of elements of volumes. The selection was not yet computed.

two_quarters_expr = (clip_x & sphere & clip_z) | (sphere & ~clip_x & ~clip_z)
volumes.select(two_quarters_expr).ids()
{'HEX8': array([ 143,  144,  162, ..., 6715, 6716, 6735],
       shape=(1838,), dtype=uint64)}
len(volumes.select(two_quarters_expr))
1838

Selection to reduction

One might want to compute a reduction (min, max, mean, std, etc) on part of a mesh. This can be done applying a reduction and using a field expression (see fields section).

volumes.select(two_quarters_expr).mean(mf.X)
0.5171525113109214

Groups

Groups API

Selections can be stored on the mesh as named groups. The mesh.groups mapping behaves like a dict: assign a selection expression (or a {etype: ids} dict) to create or replace a group, then manage groups with the usual operations.

volumes.groups["two_quarters"] = two_quarters_expr
volumes.groups
GroupsMapping(["two_quarters"])
volumes.groups["two_quarters"].ids()
{'HEX8': array([ 143,  144,  162, ..., 6715, 6716, 6735],
       shape=(1838,), dtype=uint64)}
tq = volumes.groups["two_quarters"].to_mesh()
tq.to_pyvista().plot()

len(volumes.groups["two_quarters"])
1838
volumes.groups.rename("two_quarters", "quarter_tag")
volumes.groups
GroupsMapping(["quarter_tag"])
del volumes.groups["quarter_tag"]
volumes.groups
GroupsMapping([])

Groups inplace modifications

Groups can be modified inplace, either using SelectionExpr (including existing groups expr):

volumes.groups["two_quarters"] = two_quarters_expr
n = len(volumes.groups["two_quarters"])
added_sel = mf.sel.bbox([-np.inf, -np.inf, -np.inf], [np.inf, np.inf, 0.2])
volumes.groups["two_quarters"].add(added_sel)
print(len(volumes.groups["two_quarters"]), "after adding a slab (was", n, ")")
3089 after adding a slab (was 1838 )
volumes.groups["two_quarters"].to_mesh().to_pyvista().plot()

… or directly with element ids per element type.

print(len(volumes.groups["two_quarters"]))
volumes.groups["two_quarters"].remove({"HEX8": [0, 1]})
print(len(volumes.groups["two_quarters"]))
volumes.groups["two_quarters"].add({"HEX8": [0, 1]})
print(len(volumes.groups["two_quarters"]), "back to the original size")
3089
3087
3089 back to the original size

Read next: Bubbles applies selections and groups end to end on a single mesh.

Field transfers

Figures use PyVista; verbose plotting boilerplate is omitted.

This notebook shows how to remap fields between meshes with the mf.transfer operators: interpolation, extrapolation and conservative remapping, all sharing the same prepare / apply split.

The setup below is self-contained: a log-spaced box mesh carrying a "Measure" field (cell volumes) and an analytic expression "4 * M2", plus a couple of spatial selections used to crop the source. If anything looks unfamiliar, the Fields and Selection notebooks cover their meaning.

import numpy as np

import mefikit as mf

x = np.logspace(-5, 0.0, 1000)
mesh2 = mf.build_cmesh(x, x)

mesh2.fields["Measure"] = mf.M

m = mf.Field("Measure")
m2 = mf.Field("4 * M2")
mesh2.fields["4 * M2"] = m * m * 4.0

r = mf.sel.rect([0.25, 0.25], [0.7, 0.7])
c = mf.sel.circle([0.875, 0.875], 0.05)

Transferring fields

A transfer maps a field from a source mesh onto a target mesh. Every mf.transfer operator reduces to the same operation — each target cell is a weighted sum of source cells:

t_j = sum_i w_ji s_i

The weights are computed once, at construction time (the prepare step); applying the operator to any field is then a single, fast matrix-vector product. Reuse one operator for many fields, as long as the two meshes do not change.

What differs between the four operators is only how the weights are obtained:

OperatorKindSampling / supportConserves the integralTypical use
ConstantPiecewisecell-basedtarget cell center located in a source cell (centroid)nofaithful piecewise-constant copy, coarsening
InverseDistancemeshlessk nearest source cell centers, weights 1 / r**exponentnocheap local fallback, unrelated point clouds
MovingLeastSquaresmeshlessk nearest source cell centers, local fit with a distance kernelnosmooth fields, trend reconstruction
ConservativeP0overlapmeasure-weighted intersection (same-dim and downcast)yeskeep the target integral exact, ALE / coupling, volume → surface / line

Some shared rules:

  • Interpolation methods (ConstantPiecewise, InverseDistance, MovingLeastSquares) combine a few source cells per target cell and never conserve the integral.
  • ConservativeP0 weights each contribution by the intersection measure. For intensive fields (temperature, density) it normalizes by the target cell measure afterwards — enough to behave like an interpolation — while extensive fields (mass, energy) keep the raw weighted sum. Pass extensive=True to treat a field as extensive.
  • Target cells covered by no source cell keep the default value def_val (defaults to 0.0; np.nan makes the uncovered cells explicit).
  • All operators share one calling convention: build them with tr = mf.transfer.Op(src, tgt, ...), then assign the lazy result to a target field with tgt.fields[name] = tr(expr). tr.eval(expr) returns the per-type arrays directly.

Cross-dimensional ConservativeP0

ConservativeP0 also transfers from higher- to lower-dimensional cells in the same space:

SourceTargetIntersection measure
3D volume2D surfacearea
3D volume1D linelength
3D volume0D point1 if the point is in the cell
2D surface (2D or 3D space)1D linelength
2D surface (2D or 3D space)0D point1 if the point is in the cell
1D line0D point1 if the point is on the segment

The class, signature and prepare / apply split are unchanged:

# src is a volume mesh, tgt a surface mesh (for example a cutting plane)
tr = mf.transfer.ConservativeP0(src, tgt)
tr.apply_update(src, "T", tgt, "T")

For an intensive field the result is the area- (or length-) weighted average over the target cell, normalized by the whole target measure: a target cell that is only half covered by the source mesh is attenuated by one half. For an extensive field the raw measure-weighted sum is kept, i.e. the integral of the source field over the target cell. For point targets the target measure is the counting measure (1), and each point is assigned to a single source cell (on a conforming interface the lowest source index wins).

The usual assumptions apply: convex, first-order cells (TET4, HEX8, WEDGE6, PHED, TRI3, QUAD4, PGON, SEG2, VERTEX), and 2D cells embedded in 3D are planar up to a small tolerance. Same-dimensional transfers still require both meshes to be full-dimensional.

ConstantPiecewise Transfer

The transfer is very simple. It is based on the cells of src_mesh and the cells center of the target mesh. It assigns to a cell from the target the value of the cell in which the center is located in. This is a point location based value assignment. By default the centroid (mean of cell nodes) is used because it is fast to compute and is accurate with regular cells.

m_src = mesh2.select((m2 > 4e-9) - r - c).to_mesh()
m_tgt = mf.build_cmesh(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20))

# The transfer is computed between source and target geometry.
# This step is computationnaly heavy, but done once.
cpt = mf.transfer.ConstantPiecewise(m_src, m_tgt, def_val=np.nan)
# The transfer is applied. This step is much faster.
m_tgt.fields["Projection"] = cpt("Measure")
m_tgt.to_pyvista().plot(show_edges=True)

As you can see the "Measure" field from m_src was used to compute the "Projection" field on m_tgt. Both meshes are not completely overlapping but that is not an issue: cells from m_tgt whose center is not in a cell from m_src take a default value def_val. Default is 0.0, but any floating point value, such as np.nan, is accepted.

This interpolation is a good fit when coarsening a mesh and you do not need conservation. It is fast, though not as fast as the meshless methods, because of the is_in_cell exact geometrical query.

InverseDistance Transfer

The meshless counterpart of the piecewise-constant copy: each target cell center samples its k nearest source cell centers and receives their weighted mean, with weights w_i ~ 1 / r**exponent (defaults: k = 4, exponent = 2.0). The weights are non-negative and normalized, so the value is a convex combination of the neighbours — it stays inside the source range, never overshoots, and is cheap to evaluate.

Use it when ConstantPiecewise leaves holes (uncovered cells) or when the source and target meshes are unrelated point clouds. A higher exponent concentrates the weight on the closest neighbour; k = 1 degenerates to exact nearest-neighbour sampling.

MovingLeastSquares Transfer

The most flexible of the meshless methods: for each target cell center it fits a local least-squares polynomial through the k nearest source centers (default k = 10) and evaluates it at the target point. The neighbour weights are shaped by a distance kernel, one of the mf.DistanceWeighting choices:

  • Constant() — a plain (linear) least-squares fit over the k neighbours;
  • InverseDistance(exponent) — neighbours weighted by (h / r)**exponent where h is the distance to the farthest selected neighbour;
  • Gaussian() — a gaussian kernel.

It smooths the field and reconstructs trends, but it is the only method that can overshoot the source values and extrapolate outside the source domain. Watch the boundaries — using def_val=np.nan as target for the uncovered cells makes the extrapolated region visible.

m_src = mesh2.select((m2 > 4e-9) - r - c).to_mesh()
m_tgt = mf.build_cmesh(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20))

# The transfer is computed between source and target geometry.
# This step is computationnaly heavy, but done once.
mlsqt = mf.transfer.MovingLeastSquares(m_src, m_tgt, k=10, def_val=np.nan)
# The transfer is applied. This step is much faster.
m_tgt.fields["Projection"] = mlsqt("Measure")
m_tgt.to_pyvista().plot(show_edges=True)

As you can see the projection gets a value everywhere, even outside the initial domain. This can lead to bad extrapolations, so it is to your responsability. Here as an example the extrapolated Measure can have negative values.

Inside the domain the interpolation works like a charm.

Transfer methods comparison

Which method to use? ConstantPiecewise (CPW) is local and cheap, MovingLeastSquares (MLS) smooths the field but can extrapolate outside the source, InverseDistance (ID) is a tunable local fallback, and ConservativeP0 conserves the integral.

Every method is timed on the same grid pair, split between the one-shot prepare (slow) and the repeated apply (fast). The timing loop is hidden for readability — it only fills the chart below.

Transfer of 3D fields

The same benchmark on a hexahedral grid pair — here ConstantPiecewise, InverseDistance and ConservativeP0 are timed. The prepare / apply split is unchanged:

Transfer between surfaces

Transfers do not apply to volumetric meshes only: they also work between surface meshes, i.e. 2D domains embedded in 3D space. Here sin_mesh builds such a surface by extruding a sine line along an increasing height. The cell Measure is remapped from a coarse surface to a finer one with the InverseDistance interpolation.

def sin_mesh(n=20):
    x = np.linspace(0.0, 1.0, n)
    coords = np.c_[x, 0.1 * np.sin(x * 2.0 * np.pi)]
    conn = np.c_[np.arange(0, n - 1, dtype=np.uint), np.arange(1, n, dtype=np.uint)]
    res = mf.UMesh(coords)
    res.add_regular_block("SEG2", conn)
    return res.extrude(np.linspace(0.0, 1.0, n) ** 2)
coarse = sin_mesh(9)
coarse.measure_update()
coarse.to_pyvista().plot(show_edges=True)

fine = sin_mesh(20)
fine.to_pyvista().plot(show_edges=True)

tr = mf.transfer.InverseDistance(coarse, fine)
fine.fields["Measure"] = tr("Measure")
fine.to_pyvista().plot()

Comparison to medcoupling

import medcoupling as mc
from medcoupling import MEDCouplingRemapper
m_src = mf.build_cmesh(
    np.logspace(-2.0, 0.0, 20), np.logspace(-2.0, 0.0, 20), np.linspace(0.0, 0.1, 5)
)
m_tgt = mf.build_cmesh(
    np.linspace(-0.05, 1.1, 40), np.linspace(-0.05, 1.1, 40), np.linspace(0.0, 0.1, 3)
)
m_src.fields["Measure"] = mf.M

t0 = time.time()
tr = mf.transfer.ConservativeP0(m_src, m_tgt)
t1 = time.time()
m_tgt.fields["Measure"] = tr("Measure")
t2 = time.time()

mf_prepare = t1 - t0
mf_apply = t2 - t1

mc_src = m_src.to_mc()
mc_tgt = m_tgt.to_mc()

f_src = mc_src.getMeasureField(True)
f_src.setNature(mc.IntensiveConservation)

remap = MEDCouplingRemapper()
t0 = time.time()
remap.prepare(mc_src, mc_tgt, "P0P0")
t1 = time.time()
f_tgt = remap.transferField(f_src, 0.0)
t2 = time.time()

mc_prepare = t1 - t0
mc_apply = t2 - t1
# Identical fields, whichever library computed them
mf_f = m_tgt.fields["Measure"].numpy()
mc_f = f_tgt.getArray().toNumPyArray()
assert np.allclose(mc_f, mf_f)

Using transfer as a FieldExpressions

trsf = mf.transfer.ConservativeP0(m_src, m_tgt)
rho = 3.0 * mf.X + mf.Y.square()
cp = 10.0 * mf.M
m_src.fields["rhoCp"] = rho * cp
m_tgt.fields["temp"] = trsf(rho * cp)

About the default value and the zeros

Target cells that are not covered by any source cell keep the transfer def_val, which defaults to 0.0. With the log-pressure source m_src confined to ~[0.001, 0.1] above, most of the large m_tgt (up to 1.5) is outside the source, so most target cells are legitimately zero. The earlier cells set def_val=np.nan on purpose so that uncovered cells show up as NaN instead of 0.0; use def_val=np.nan (or any other sentinel) the same way with eval/__call__:

trsf = mf.transfer.ConservativeP0(m_src, m_tgt, def_val=np.nan)
m_tgt.fields["temp"] = trsf(rho)   # uncovered cells -> NaN, covered cells -> rho

Cells covered by the source are transferred correctly; only the uncovered cells differ because of the chosen default value.

Saving and reusing a prepared operator

Building a transfer operator is the expensive part; applying it is a sparse matrix-vector product. An operator can be written to disk and loaded back in a later session:

trsf = mf.transfer.ConservativeP0(m_src, m_tgt, def_val=np.nan)
trsf.save("transfer.npz")

# src_mesh is required; tgt_mesh is optional but enables stronger validation.
loaded = mf.transfer.load("transfer.npz", src_mesh=m_src, tgt_mesh=m_tgt)
m_tgt.fields["temp"] = loaded("temp")

The file is a standard NumPy .npz archive, so it can also be opened without mefikit:

import scipy.sparse as sp

matrix = sp.load_npz("transfer.npz")  # CSR matrix

The CSR matrix has one row per target cell and one column per source cell. Blocks are stored by element type; the file metadata records each block’s element type, size and explicit row/column offset. mf.transfer.load uses those offsets to remap columns to the current in-memory element-type order, so files remain valid if new element types are inserted into the enum later. The extra mefikit_meta array contains the JSON metadata; SciPy ignores it.

On load, mefikit checks the CSR structure (row pointers, index bounds, array lengths), the method parameters, and, when meshes are supplied, the per-element- type block counts of both meshes. A mismatch raises ValueError with the expected and actual blocks. Validation is structural: it does not compare cell coordinates, so a saved operator is only meaningful for the geometry it was built from. Pass compressed=False to save if you prefer uncompressed (faster) I/O.

Parallel transfer with MPI

When the source and target meshes are split across MPI ranks, mf.transfer.DistributedConservativeP0 performs the same conservative P0 transfer on each rank’s local pieces and exchanges only the source values that are actually needed. MPI is used from Python through mpi4py; the Rust extension itself stays MPI-free. Install the optional dependency with:

pip install "mefikit[mpi]"

The example below builds one local piece per rank. Running it normally executes the single-rank path; running it with mpirun -n N splits the cells over the ranks (the piece construction is only here to make the example self-contained).

import numpy as np
from mpi4py import MPI

import mefikit as mf

comm = MPI.COMM_WORLD
rank, size = comm.Get_rank(), comm.Get_size()
print(f"rank {rank}/{size}")

x = np.linspace(0.0, 1.0, 17)
src_full = mf.build_cmesh(x, x)
tgt_full = mf.build_cmesh(np.linspace(0.0, 1.0, 13), np.linspace(0.0, 1.0, 13))
values = (np.arange(src_full.num_elements(), dtype=float) + 1.0).reshape(-1, 1)
src_full.set_field("T", {"QUAD4": values})


def local_piece(mesh, et, start, stop):
    if stop <= start:
        return None
    ids = np.arange(start, stop, dtype=np.uintp)
    return mesh.select({et: ids}).to_mesh(False).remove_unused_coords()


s_lo = rank * src_full.num_elements() // size
s_hi = (rank + 1) * src_full.num_elements() // size
t_lo = rank * tgt_full.num_elements() // size
t_hi = (rank + 1) * tgt_full.num_elements() // size

src = local_piece(src_full, "QUAD4", s_lo, s_hi)
tgt = local_piece(tgt_full, "QUAD4", t_lo, t_hi)
if src is not None:
    src.set_field("T", {"QUAD4": np.ascontiguousarray(values[s_lo:s_hi])})

print(f"local source cells: {0 if src is None else src.num_elements()}")
print(f"local target cells: {0 if tgt is None else tgt.num_elements()}")
rank 0/1
local source cells: 256
local target cells: 144
transfer = mf.transfer.DistributedConservativeP0(src, tgt, comm=comm)
local = transfer.eval("T")
local_values = (
    np.asarray(local["QUAD4"]).reshape(-1, 1) if "QUAD4" in local else np.empty((0, 1))
)
print(f"local transferred shape: {local_values.shape}")

# extensive=True keeps the integral: the target integral equals the source one.
extensive = transfer.eval("T", extensive=True)
local_integral = (
    float(np.asarray(extensive["QUAD4"]).sum()) if "QUAD4" in extensive else 0.0
)
total = comm.allreduce(local_integral, op=MPI.SUM)
if rank == 0:
    print(f"distributed extensive integral: {total:.12f}")

# Store the result on the local target mesh, as with the sequential operators.
transfer.apply_update(src, "T", tgt, "T_mpi")
if tgt is not None:
    print(f"target field T_mpi: {tgt.fields['T_mpi'].numpy().shape}")

# Gather the local pieces on rank 0 and compare with the sequential operator.
gathered = comm.gather(local_values, root=0)
if rank == 0:
    distributed = np.concatenate(gathered, axis=0)
    sequential = np.asarray(
        mf.transfer.ConservativeP0(src_full, tgt_full).eval("T")["QUAD4"]
    ).reshape(-1, 1)
    print(
        "max |distributed - sequential| = "
        f"{np.max(np.abs(distributed - sequential)):.3e}"
    )
local transferred shape: (144, 1)
distributed extensive integral: 128.500000000000
target field T_mpi: (144, 1)
max |distributed - sequential| = 0.000e+00

The operator is prepared once and can be reused for any number of fields, for example in a time loop. Intensive fields are normalized by the target cell measure, while extensive=True keeps the raw measure-weighted sum. For a one-shot transfer, use mf.transfer.distributed(src, expr, tgt, comm=...); for repeated fields, keep the DistributedConservativeP0 object.

Field gradients

Figures use PyVista; verbose plotting boilerplate is omitted.

A transfer copies a field from one mesh onto another; a gradient differentiates it. mf.Gradient reconstructs the gradient of a scalar field with a moving least-squares (MLS) fit over the k nearest source cell centres, using the same prepare / apply split as the field transfers: the geometric operator is built once and can then be applied to any number of scalar fields.

Unlike a transfer, whose per-target weights are scalar, the gradient carries d weights per neighbour — one per space direction — so the result is a vector field with d trailing components. This page covers the three evaluation targets (the source cells, a target mesh, an arbitrary point cloud), validates them against analytic gradients, and compares the distance kernels.

import numpy as np

import mefikit as mf

# A smooth, non-affine scalar field on the unit square grid:
#     f(x, y) = sin(pi x) sin(pi y)
n = 41
src = mf.build_cmesh(np.linspace(0.0, 1.0, n), np.linspace(0.0, 1.0, n))
src.fields["f"] = (mf.X * np.pi).sin() * (mf.Y * np.pi).sin()

The gradient operator

mf.Gradient(src, tgt=None, k=10, weighting=..., def_val=0.0) builds the MLS operator. The evaluation points depend on how it is built:

ConstructorEvaluated at
mf.Gradient(src)the source mesh’s own cell centroids
mf.Gradient(src, tgt)the target mesh’s cell centroids
mf.Gradient.at_points(src, points)an explicit (n, d) point array

k is the number of nearest source cells used in each local fit and weighting is one of the mf.DistanceWeighting kernels — Constant, InverseDistance(exponent), CompactSupport(exponent) or Gaussian — shared with the transfer operators. A degree-1 fit reproduces affine fields exactly, which is the validation used below.

Gradient at the source cells

With no target mesh the gradient is evaluated at the source cell centroids. grad("f") is a lazy vector Field; grad.eval("f") materialises it as {etype: array} of shape (n_cells, d).

grad = mf.Gradient(src, k=12)
grad_f = np.asarray(grad.eval("f")["QUAD4"])
grad_f.shape
(1600, 2)

The analytic gradient of f is grad f = (pi cos(pi x) sin(pi y), pi sin(pi x) cos(pi y)). Sampling it at the cell centroids gives a reference to compare against:

cx = np.asarray(src.eval(mf.X)["QUAD4"]).ravel()
cy = np.asarray(src.eval(mf.Y)["QUAD4"]).ravel()
exact = np.c_[
    np.pi * np.cos(np.pi * cx) * np.sin(np.pi * cy),
    np.pi * np.sin(np.pi * cx) * np.cos(np.pi * cy),
]

err = np.linalg.norm(grad_f - exact, axis=1)
h = 1.0 / (n - 1)
interior = (cx > 2 * h) & (cx < 1 - 2 * h) & (cy > 2 * h) & (cy < 1 - 2 * h)
print(f"max |grad f - exact| : {err.max():.3e}")
print(f"interior max error   : {err[interior].max():.3e}")
max |grad f - exact| : 2.844e-01
interior max error   : 5.152e-02

The reconstruction is accurate in the interior; accuracy drops near the boundary, where all k neighbours lie on one side of the cell.

Gradient on a target mesh

Passing a second mesh moves the evaluation to its cell centroids — useful to compute a gradient on a coarser or differently-shaped mesh, or on the boundary of the source.

tgt = mf.build_cmesh(np.linspace(0.05, 0.95, 15), np.linspace(0.05, 0.95, 15))
grad_tgt = mf.Gradient(src, tgt, k=12)
grad_tgt.eval("f")["QUAD4"].shape
(196, 2)

Gradient at arbitrary points

mf.Gradient.at_points takes the evaluation points explicitly as an (n, d) array; grad.eval_points("f") then returns the (n, d) gradient directly. This is convenient to sample the gradient along a curve or at sparse probes.

t = np.linspace(0.0, 1.0, 120)
curve = np.c_[t, 0.5 + 0.3 * np.sin(2 * np.pi * t)]
grad_pts = mf.Gradient.at_points(src, curve, k=12)
grad_curve = grad_pts.eval_points("f")
grad_curve.shape
(120, 2)

Lazy fields, components and in-place results

Because grad("f") returns a lazy Field, it composes with the rest of the expression system: index the components with [0] / [1], combine them into derived quantities, and assign them to named target fields.

tgt.fields["dfdx"] = grad_tgt("f")[0]
tgt.fields["dfdy"] = grad_tgt("f")[1]
tgt.fields["grad_mag"] = (grad_tgt("f")[0].square() + grad_tgt("f")[1].square()).sqrt()

tgt.fields["grad_f"] = grad_tgt("f")
tgt.fields["grad_f"].numpy().shape
(196, 2)

Kernels and neighbour count

The kernel only changes how the local least-squares weights decay with distance:

  • Constant — an unweighted affine fit;
  • InverseDistance(exponent) — weight (h / r)**exponent;
  • CompactSupport(exponent) — a compactly-supported power kernel;
  • Gaussian — a bell-shaped kernel.

On a smooth field the kernel choice mostly changes the boundary. k balances locality against smoothness: a small k follows the field tightly and is the most accurate on smooth data, but is more sensitive to noise, while a large k averages over a wider stencil and smooths the reconstruction, at the cost of a larger error near the boundary.

for name, weighting in {
    "Constant": mf.DistanceWeighting.Constant(),
    "InverseDistance(2)": mf.DistanceWeighting.InverseDistance(2.0),
    "CompactSupport(2)": mf.DistanceWeighting.CompactSupport(2.0),
    "Gaussian": mf.DistanceWeighting.Gaussian(),
}.items():
    vals = np.asarray(mf.Gradient(src, k=12, weighting=weighting).eval("f")["QUAD4"])
    print(f"{name:18s} max |grad f - exact| = {np.abs(vals - exact).max():.3e}")
Constant           max |grad f - exact| = 2.407e-01
InverseDistance(2) max |grad f - exact| = 1.599e-01
CompactSupport(2)  max |grad f - exact| = 1.424e-01
Gaussian           max |grad f - exact| = 2.028e-01
for k in (4, 8, 16, 32):
    vals = np.asarray(mf.Gradient(src, k=k).eval("f")["QUAD4"])
    print(f"k = {k:2d}  max |grad f - exact| = {np.abs(vals - exact).max():.3e}")
k =  4  max |grad f - exact| = 1.222e-01
k =  8  max |grad f - exact| = 1.700e-01
k = 16  max |grad f - exact| = 3.360e-01
k = 32  max |grad f - exact| = 4.692e-01

3D gradients

The tool works in 3D space too; the gradient then has three components. On the linear field f = 1 + 2x - 3y + 4z the reconstruction is exact.

mesh3d = mf.build_cmesh(
    np.linspace(0.0, 1.0, 6), np.linspace(0.0, 1.0, 6), np.linspace(0.0, 1.0, 6)
)
mesh3d.fields["f"] = 1.0 + 2.0 * mf.X - 3.0 * mf.Y + 4.0 * mf.Z

grad3d = mf.Gradient(mesh3d, k=8)
vals3d = np.asarray(grad3d.eval("f")["HEX8"])
print(vals3d.shape, np.abs(vals3d - np.array([2.0, -3.0, 4.0])).max())
(125, 3) 4.973799150320701e-14

Scope and caveats

The MLS fit needs a full-dimensional neighbourhood: a 2D region for a 2D space, a 3D volume for a 3D space. A lower-dimensional mesh embedded in a higher-dimensional space — a surface in 3D, a line in 2D — has a rank-deficient local geometry, so the operator returns a zero gradient there instead of failing:

# A planar quad mesh living in 3D: locally rank-deficient, gradient is zero.
flat = mf.build_cmesh(np.linspace(0.0, 1.0, 6), np.linspace(0.0, 1.0, 6))
planar = mf.UMesh(np.c_[flat.coords(), np.zeros(len(flat.coords()))])
planar.add_regular_block("QUAD4", flat.blocks()["QUAD4"])
planar.fields["f"] = 2.0 * mf.X - 3.0 * mf.Y

vals = np.asarray(mf.Gradient(planar, k=8).eval("f")["QUAD4"])
print(vals.shape, np.abs(vals).max())
(25, 3) 0.0

Treat mf.Gradient as a meshless differential operator built on the same machinery as the field transfers: build it once, then reuse it for every scalar field and every time step.

Bubbles example

Figures use PyVista; verbose plotting boilerplate is omitted.

A hexahedral box is seeded with spherical bubbles. This is a small end-to-end tour of the selection pipeline on a single mesh: tag regions with groups, extract them with select, crack them out of the matrix, split them into connected components, and measure volumes and positions with one-line reductions.

import numpy as np

import mefikit as mf

rng = np.random.default_rng(seed=123)

Setup

xmax = 5.0
ymax = 1.0
r = 0.17
nb = 15
nr = 12.5
nx = int(xmax / r * nr)
ny = int(ymax / r * nr)
print(f"Number of elements : {nx * ny * ny:,}")
Number of elements : 1,955,743

The box xmax x ymax x ymax is discretised with nx x ny x ny cells, fine enough to resolve the nb = 15 spheres of radius r sitting inside it. Their centres are sampled in the interior so that every sphere stays fully inside the box; each one becomes a mf.sel.sphere(...) selection, and all of them are combined with | into a single union.

xc = rng.uniform(r, xmax - r, nb)
yc = rng.uniform(r, ymax - r, nb)
zc = rng.uniform(r, ymax - r, nb)
spheres = [mf.sel.sphere([x, y, z], r) for x, y, z in zip(xc, yc, zc)]
sphere_union = spheres[0]
for s in spheres[1:]:
    sphere_union = sphere_union | s
x = np.linspace(0.0, xmax, nx)
y = np.linspace(0.0, ymax, ny)
volumes = mf.build_cmesh(x, y, y)

The background is a plain structured hexa grid. Let us look at its boundaries first.

volumes.boundaries().to_pyvista().plot(opacity=0.4)

Selecting bubbles

mesh.select(...) returns a lazy view: nothing is computed until you materialise it (.to_mesh()) or take a reduction. Storing a selection in mesh.groups lets you reuse it later by name.

# `select` returns a lazy view: materialize it into a sub-mesh with `.to_mesh()`.
inner_bubbles = volumes.select(sphere_union).to_mesh()
interface = inner_bubbles.boundaries()
cracked = volumes.crack(interface)
# Named groups live in a dict-like mapping on the mesh:
# assign any selection expression (or {etype: ids} dict) to tag elements.
volumes.groups["bubbles"] = sphere_union
print(len(volumes.groups["bubbles"]), "elements tagged in group 'bubbles'")
105990 elements tagged in group 'bubbles'

Cracking and connected components

crack duplicates the nodes that sit on the bubble interfaces, so the bubbles become elements with their own nodes. Then connected_components() isolates each bubble.

So far crack has duplicated the nodes that sit on the cell interfaces, so neighbouring elements no longer share their faces. The bubble fronts are now open surfaces wrapped around the matrix:

cracked.boundaries().to_pyvista().plot(opacity=0.4)

bubble_groups = inner_bubbles.connected_components()

inner_bubbles.connected_components() groups the cracked bubble mesh into its connected parts. Each component is one bubble (or a touching cluster); the plot colours them one by one on top of the box edges.

Selections compose. A clip is just a mf.sel.bbox(...); intersecting it with ~sphere_union selects the box elements that are outside the bubbles — the matrix stays crack-free where bubbles have been removed from the picture:

clip1 = mf.sel.bbox([-np.inf] * 3, [np.inf, ymax / 3.0, np.inf])

Computing statistics

Reductions evaluate lazily over a selection or a group. Bubble volumes are compared with the analytic result 4/3 pi r**3 for an ideal sphere, and mean(mf.C) (mean of the node centroids) gives the barycentre of the bubble mass:

bubble_volumes = volumes.select("bubbles").sum(mf.M)
print(nb * 4.0 / 3.0 * np.pi * r**3.0)
bubble_volumes
0.3086928941417331





0.2793115007084435

The bubble volume returned by sum(mf.M) is close to nb * 4/3 pi r**3; the small gap is the staircase discretisation of spheres on a regular hexa grid.

bubbles_mean_pos = volumes.select("bubbles").mean(mf.C)
print(bubbles_mean_pos)
[2.49923348 0.4928932  0.5314482 ]

mefikit vs. medcoupling

Figures use PyVista; verbose plotting boilerplate is omitted.

A friendly, side-by-side look at two libraries that solve the same class of problems, in slightly different ways.

medcoupling is the reference implementation of the MED world: mature, broad and battle-tested in industrial workflows. It set the bar for mesh interchange — mefikit itself happily reads and writes the very same .med files.

mefikit is a younger library, written in Rust and exposed to Python. It pursues the same goal — manipulate unstructured meshes and their fields — with a shorter, more expressive API and a performance-oriented core.

This notebook is neither a verdict nor a “rip and replace”. It is an invitation: we build the same meshes, run the same operations, and compare the interface and the timings step by step. If you know medcoupling, you should find your bearings immediately — and, hopefully, be tempted.

Every mesh below is built from the exact same geometry on both sides, and every value is cross-checked against the other library before we say one word about speed.

import os
import time
from pathlib import Path

import medcoupling as mc
import numpy as np

import mefikit as mf

print("medcoupling version:", mc.__version__)
print("numpy       :", np.__version__)
medcoupling version: V9_15_0
numpy       : 2.5.4

Helpers

Small utilities :

def used_nodes(mesh):
    ids = np.concatenate([np.asarray(b) for b in mesh.blocks().values()])
    return int(np.unique(ids).size)


def area_2d(mesh):
    return float(sum(np.asarray(v).sum() for v in mesh.measure().values()))

Building the same mesh

Every mesh workflow starts with creating a grid. In mefikit, build_cmesh builds a structured (cartesian) mesh from the coordinate axes in one call.

In medcoupling the standard route goes through a structured MEDCouplingCMesh, materialised as an unstructured mesh with buildUnstructured(). Three lines, still very readable.

The good news: the result is the same mesh — same nodes, same cells — because a cartesian grid is just a very regular unstructured mesh.

def medcoupling_cmesh(*axes):
    # medcoupling counterpart of mf.build_cmesh(*axes): build a structured
    # MEDCouplingCMesh, then materialise it as an unstructured mesh with the
    # standard buildUnstructured() call.
    cmesh = mc.MEDCouplingCMesh()
    cmesh.setCoords(
        *[mc.DataArrayDouble(np.ascontiguousarray(a, np.float64)) for a in axes]
    )
    umesh = cmesh.buildUnstructured()
    umesh.setMeshDimension(len(axes))
    return umesh


x = np.linspace(0.0, 1.0, 6)
mf_mesh = mf.build_cmesh(x, x)  # mefikit    : one call
mc_mesh = medcoupling_cmesh(x, x)  # medcoupling: structured -> unstructured
print(
    "mefikit     :",
    mf_mesh.num_elements(),
    "QUAD4 cells,",
    mf_mesh.coords().shape[0],
    "nodes",
)
print(
    "medcoupling :",
    mc_mesh.getNumberOfCells(),
    "QUAD4 cells,",
    mc_mesh.getNumberOfNodes(),
    "nodes",
)

assert mc_mesh.getNumberOfCells() == mf_mesh.num_elements()
assert np.allclose(mc_mesh.getCoords().toNumPyArray(), mf_mesh.coords())
print("identical geometry (nodes and cells): OK")
mefikit     : 25 QUAD4 cells, 36 nodes
medcoupling : 25 QUAD4 cells, 36 nodes
identical geometry (nodes and cells): OK
# The bridge in the other direction is a one-liner: mefikit meshes
# export to medcoupling with to_mc(), geometry untouched.
twin = mf_mesh.to_mc()
twin.setMeshDimension(2)
print(
    "to_mc() bridge:",
    twin.getNumberOfCells(),
    "cells,",
    twin.getNumberOfNodes(),
    "nodes",
)
to_mc() bridge: 25 cells, 36 nodes

Fields, measures, and one-line expressions

Everyone needs per-cell measures in remapping workflows. mefikit exposes a symbolic field mf.M — the measure — evaluated on demand, together with a small expression DSL on mf.Field: you write the computation, mefikit evaluates it on the mesh, and combinations of select / mean / sum become one-liners.

medcoupling takes the more explicit route: you build a DataArrayDouble, wrap it into a MEDCouplingFieldDouble, and attach it to the mesh. Both compute exactly the same numbers.

# --- mefikit ----------------------------------------------------------------
mf_mesh.fields["Measure"] = mf.M  # symbolic measure
mf_mesh.fields["T"] = 1.0 + mf.X**2 + 0.5 * mf.Y

print("measure sum  :", mf_mesh.fields["Measure"].sum())
hot = mf_mesh.select(mf.Field("T") > 1.5)
print("cells T > 1.5:", len(hot))
print("mean T above :", hot.mean("T"))
measure sum  : 1.0
cells T > 1.5: 13
mean T above : 1.8338461538461535
# --- medcoupling -------------------------------------------------------------
mc_measure = mc_mesh.getMeasureField(True)
mc_measure.setNature(mc.IntensiveConservation)

centers = mc_mesh.computeCellCenterOfMass().toNumPyArray()
mc_T = mc_cell_field(
    mc_mesh,
    1.0 + centers[:, 0] ** 2 + 0.5 * centers[:, 1],
    nature=mc.IntensiveConservation,
)

print("measure sum  :", mc_measure_sum(mc_mesh))
measure sum  : 1.0
# identical numbers, whichever library computed them
mf_T_vals = mf_mesh.fields["T"].numpy()
mc_T_vals = mc_T.getArray().toNumPyArray()
print("max |mf_T - mc_T|:", np.abs(mf_T_vals - mc_T_vals).max())
assert np.allclose(mf_T_vals, mc_T_vals, atol=1e-12)
max |mf_T - mc_T|: 1.3322676295501878e-15

Common operations, side by side

Descending connectivity

The faces of a volume mesh — the bread and butter of boundary conditions and surface integrals. mefikit: one call, descend(). medcoupling: buildDescendingConnectivity(). Both report the same face count.

axes3 = [np.linspace(0.0, 1.0, 5)] * 3
m3 = mf.build_cmesh(*axes3)
mc3 = medcoupling_cmesh(*axes3)

mf_faces = m3.descend()
mc_faces = mc_descend(mc3)

print("faces (mefikit)    :", mf_faces.num_elements())
print("faces (medcoupling):", mc_faces.getNumberOfCells())
assert mf_faces.num_elements() == mc_faces.getNumberOfCells()
print("identical face count: OK")
faces (mefikit)    : 240
faces (medcoupling): 240
identical face count: OK

Merging duplicated nodes

Meshes often carry duplicated nodes (split or intersected interfaces). The reference cure is a node merge. mefikit’s merge_nodes() and medcoupling’s mergeNodes() collapse the same duplicates.

A small nuance worth knowing: mefikit keeps the coordinate array untouched and rewires the connectivity — cheap and zero-copy friendly — while medcoupling physically compacts nodes. The number of used nodes is identical.

# crack a small hex stack so its shared interface is duplicated
volumes = mf.build_cmesh([0.0, 1.0], np.linspace(0.0, 1.0, 5), np.linspace(0.0, 1.0, 5))
faces = volumes.descend()
cracked = volumes.crack(faces)
cracked_mc = mc_twin(cracked, 3)

merged = cracked.merge_nodes()
merged_mc = cracked_mc.deepCopy()
merged_mc.mergeNodes(1e-12)

print("components before merge:", len(cracked.connected_components()))
print("components after merge :", len(merged.connected_components()))
print(
    "used nodes  before/after (mefikit)    :",
    used_nodes(cracked),
    "->",
    used_nodes(merged),
)
print(
    "nodes       before/after (medcoupling):",
    cracked_mc.getNumberOfNodes(),
    "->",
    merged_mc.getNumberOfNodes(),
)
assert len(merged.connected_components()) == 1
assert used_nodes(merged) == merged_mc.getNumberOfNodes()
print("identical result: OK")
components before merge: 16
components after merge : 1
used nodes  before/after (mefikit)    : 128 -> 50
nodes       before/after (medcoupling): 128 -> 50
identical result: OK

2D overlay / imprint

Boolean overlay of two 2D meshes (insert an embedded mesh into a background one). mefikit: overlay(). medcoupling: Intersect2DMeshes(). Both imprint the embedded grid into the background and preserve the total area.

g1 = mf.build_cmesh(np.linspace(0.0, 1.0, 7), np.linspace(0.0, 1.0, 7))
g2 = mf.build_cmesh(np.linspace(0.25, 0.75, 5), np.linspace(0.25, 0.75, 5))

imprint = g1.overlay(g2, mf.OverlayOperation.IMPRINT)

g1m, g2m = mc_twin(g1, 2), mc_twin(g2, 2)
mc_imprint = mc.MEDCouplingUMesh.Intersect2DMeshes(g1m, g2m, 1e-12)[0]

a_mf = area_2d(imprint)
a_mc = mc_measure_sum(mc_imprint)
print("imprint area (mefikit)    :", a_mf)
print("imprint area (medcoupling):", a_mc)
assert abs(a_mf - 1.0) < 1e-9 and abs(a_mc - 1.0) < 1e-9
print("identical (unit) area: OK")
imprint area (mefikit)    : 1.0000000000000002
imprint area (medcoupling): 1.0
identical (unit) area: OK

Conservative P0/P0 field transfer (QUAD4)

The flagship operation: transfer a cell field from a source mesh to a target mesh, conserving mass. Same prepare / apply split on both sides:

  • mefikit: build the operator once (mf.transfer.ConservativeP0), then assign its result with tgt.fields["T"] = op("T").
  • medcoupling: MEDCouplingRemapper, prepare("P0P0"), then transferField.

The transferred fields match to machine precision.

ConservativeP0 also handles volume → surface/line/point downcasts. For the comparison: MEDCoupling’s P0P0 supports 3D → 2D directly, and 2D → 1D in a 2D space after setIntersectionType(mc.Geometric2D). MEDCoupling has no measure-based P0P0 for 3D → 1D, 3D → 0D or 2D → 1D in 3D space (its PointLocator option is point location, not an intersection measure), so those pairs are checked against exact analytic references in the tests.

# --- mefikit ----------------------------------------------------------------
src2 = mf.build_cmesh(np.linspace(0.0, 1.0, 20), np.linspace(0.0, 1.0, 20))
tgt2 = mf.build_cmesh(np.linspace(0.0, 1.0, 24), np.linspace(0.0, 1.0, 24))
src2.fields["T"] = 1.0 + (mf.X - 0.5) ** 2 + 0.5 * mf.Y

op = mf.transfer.ConservativeP0(src2, tgt2)  # prepare once
tgt2.fields["T"] = op("T")
mf_tgt_vals = tgt2.fields["T"].numpy()

# --- medcoupling -------------------------------------------------------------
sc, tc = mc_twin(src2, 2), mc_twin(tgt2, 2)
f_src = mc_cell_field(sc, src2.fields["T"].numpy(), nature=mc.IntensiveConservation)

remap = mc.MEDCouplingRemapper()
remap.prepare(sc, tc, "P0P0")  # prepare once
f_tgt = remap.transferField(f_src, 0.0)
mc_tgt_vals = f_tgt.getArray().toNumPyArray()

print(
    "max |mefikit - medcoupling| after P0P0:",
    float(np.abs(mf_tgt_vals - mc_tgt_vals).max()),
)
assert np.allclose(mf_tgt_vals, mc_tgt_vals, atol=1e-9)
print("transferred fields match: OK")
max |mefikit - medcoupling| after P0P0: 3.552713678800501e-15
transferred fields match: OK

Polyhedra, where mefikit shines the most

Real-world meshes are very often polyhedral: Voronoi meshes, cell-centred finite volumes, unrolled CAD… Both libraries store them; the difference shows when it is time to use them.

We take two different 2000-cell polyhedral meshes shipped with mefikit’s test suite — mesh_36.med and mesh_27.med — and feed the same .med files to both libraries.

# locate the test meshes whatever the current working directory is
root = Path(os.getcwd())
while root != root.parent and not (root / "tests" / "data" / "mesh_36.med").exists():
    root = root.parent
data = root / "tests" / "data"

mf_src = mf.UMesh.read(str(data / "mesh_36.med"))  # mefikit : 1 line
mf_tgt = mf.UMesh.read(str(data / "mesh_27.med"))
mc_src = mc.ReadMeshFromFile(str(data / "mesh_36.med"), 0)  # medcoupling
mc_tgt = mc.ReadMeshFromFile(str(data / "mesh_27.med"), 0)

print("mefikit  mesh_36 :", mf_src.block_types(), mf_src.num_elements(), "cells")
print("mefikit  mesh_27 :", mf_tgt.block_types(), mf_tgt.num_elements(), "cells")
print(
    "medcoupl mesh_36 :",
    mc_src.getNumberOfCells(),
    "cells,",
    mc_src.getNumberOfNodes(),
    "nodes",
)
print("medcoupl mesh_27 :", mc_tgt.getNumberOfCells(), "cells")

# measure + a field + a selection, poly edition, all in mefikit
mf_src.fields["Measure"] = mf.M
mf_src.fields["T"] = 1.0 + 2.0 * mf.M
print("volume(mesh_36):", mf_src.fields["Measure"].sum())
big = mf_src.select(mf.M > mf_src.fields["Measure"].mean())
print("cells above mean volume:", len(big))
mefikit  mesh_36 : ['PHED'] 2000 cells
mefikit  mesh_27 : ['PHED'] 2000 cells
medcoupl mesh_36 : 2000 cells, 12404 nodes
medcoupl mesh_27 : 2000 cells
volume(mesh_36): 0.99999999869571
cells above mean volume: 898
# boundaries and descending connectivity on polyhedra
mf_bnd = mf_src.boundaries()
mf_desc = mf_src.descend()

mc_bnd = mc_src.buildBoundaryMesh(True)
mc_desc = mc_descend(mc_src)

print(
    "boundary faces (mefikit)     :",
    mf_bnd.num_elements(),
    "| medcoupling:",
    mc_bnd.getNumberOfCells(),
)
print(
    "descending    (mefikit)     :",
    mf_desc.num_elements(),
    "| medcoupling:",
    mc_desc.getNumberOfCells(),
)
assert mf_bnd.num_elements() == mc_bnd.getNumberOfCells()
assert mf_desc.num_elements() == mc_desc.getNumberOfCells()
print("identical counts: OK")
boundary faces (mefikit)     : 888 | medcoupling: 888
descending    (mefikit)     : 14401 | medcoupling: 14401
identical counts: OK

Polyhedral-to-polyhedral remap

Same P0/P0 transfer, but between the two real polyhedral meshes. Prepare once, apply many times is the name of the game for unsteady runs, so both sides are timed separately. We scan a few mesh sizes (always the same geometry on both sides) and check that the actual transferred fields coincide.

The poly_subset / median_ms helpers used below are small bookkeeping utilities (isolating a sub-mesh, taking a median timing) — hidden here for readability.

def bench_poly_once(n, data):
    # Time one P0/P0 polyhedral remap size on both libraries; return the
    # (prepare, apply) medians in ms plus the transferred-field difference.
    p_src = poly_subset(data / "mesh_36.med", n, False)
    p_tgt = poly_subset(data / "mesh_27.med", n, False)
    p_src.fields["T"] = 1.0 + 2.0 * mf.M

    mf_prepare = median_ms(lambda: mf.transfer.ConservativeP0(p_src, p_tgt))
    op = mf.transfer.ConservativeP0(p_src, p_tgt)

    def apply_mf():
        p_tgt.fields["T"] = op("T")

    mf_apply = median_ms(apply_mf)

    c_src = poly_subset(data / "mesh_36.med", n, True)
    c_tgt = poly_subset(data / "mesh_27.med", n, True)
    f_src = mc_cell_field(
        c_src, p_src.fields["T"].numpy(), nature=mc.IntensiveConservation
    )

    remap = mc.MEDCouplingRemapper()
    mc_prepare = median_ms(lambda: remap.prepare(c_src, c_tgt, "P0P0"))
    mc_apply = median_ms(lambda: remap.transferField(f_src, 0.0))

    p_tgt.fields["T"] = op("T")
    out_mf = p_tgt.fields["T"].numpy()
    remap.prepare(c_src, c_tgt, "P0P0")
    out_mc = remap.transferField(f_src, 0.0).getArray().toNumPyArray()
    diff = float(np.abs(out_mf - out_mc).max())
    return mf_prepare, mf_apply, mc_prepare, mc_apply, diff


poly_res = []
for n in (100, 200, 400):
    mf_prepare, mf_apply, mc_prepare, mc_apply, diff = bench_poly_once(n, data)
    poly_res.append((n, mf_prepare, mf_apply, mc_prepare, mc_apply, diff))
    print(
        f"poly n={n:4d} | mefikit {mf_prepare:7.2f} ms (prepare) / {mf_apply:5.2f} ms (apply)"
        f" | medcoupling {mc_prepare:8.1f} ms / {mc_apply:5.2f} ms | {mc_prepare / mf_prepare:4.0f}x faster"
    )
    print(
        f"            | max |mefikit - medcoupling| on the transferred field: {diff:.2e}"
    )

assert all(r[5] < 1e-9 for r in poly_res)
print("transferred fields match at every size: OK")
poly n= 100 | mefikit    1.83 ms (prepare) /  0.00 ms (apply) | medcoupling     76.4 ms /  0.05 ms |   42x faster
            | max |mefikit - medcoupling| on the transferred field: 5.88e-15


poly n= 200 | mefikit    4.30 ms (prepare) /  0.00 ms (apply) | medcoupling    273.4 ms /  0.11 ms |   64x faster
            | max |mefikit - medcoupling| on the transferred field: 6.38e-15


poly n= 400 | mefikit   14.71 ms (prepare) /  0.01 ms (apply) | medcoupling   1076.1 ms /  0.22 ms |   73x faster
            | max |mefikit - medcoupling| on the transferred field: 7.22e-15
transferred fields match at every size: OK

r = poly_res[-1]
print(
    f"At {r[0]} cells mefikit prepares the polyhedral remap {r[3] / r[1]:.0f} times faster "
    "than medcoupling, and the gap grows with the mesh size."
)
At 400 cells mefikit prepares the polyhedral remap 73 times faster than medcoupling, and the gap grows with the mesh size.

Performance on common operations

Now the same benchmark spirit on the structured meshes (quad / hexa) of daily life. Timings are medians of several runs on this machine; tiny absolute values should be read with perspective. Both libraries always work on the exact same geometry: this is what fairness looks like.

The benchmark harness itself is hidden for readability. It mirrors mefikit’s tests/bench_vs_medcoupling.py, where the full workload definitions live; the cells below only show how the runs are launched.

bench = {}
bench["remap-2d"] = bench_remap(2, N2D, build_iter=10, poly=False)
print("remap-2d done")
bench["remap-3d"] = bench_remap(3, N3D, build_iter=10, poly=False)
print("remap-3d done")
bench["remap-3d-poly"] = bench_remap(3, NPOLY, build_iter=5, poly=True)
print("remap-3d-poly done")
bench["merge-nodes"] = bench_merge()
print("merge-nodes done")
bench["descend"] = bench_descend()
print("descend done")
bench["overlay"] = bench_overlay()
print("overlay done")
bench["crack"] = bench_crack()
print("crack done")
remap-2d done


remap-3d done


remap-3d-poly done
merge-nodes done


descend done
overlay done


crack done
def mf_mc(case, mf_key, mc_key):
    return bench[case][mf_key], bench[case][mc_key]


spec = [
    ("remap-2d", "build/prepare", "mf_build", "mc_prepare"),
    ("remap-2d", "transfer", "mf_apply", "mc_transfer"),
    ("remap-3d", "build/prepare", "mf_build", "mc_prepare"),
    ("remap-3d", "transfer", "mf_apply", "mc_transfer"),
    ("remap-3d-poly", "build/prepare", "mf_build", "mc_prepare"),
    ("remap-3d-poly", "transfer", "mf_apply", "mc_transfer"),
    ("merge-nodes", "merge", "mf", "mc"),
    ("descend", "run", "mf", "mc"),
    ("overlay", "run", "mf", "mc"),
    ("crack", "crack", "mf", "mc"),
]
rows = [(case, step, *mf_mc(case, mk, ck)) for case, step, mk, ck in spec]

print(
    f"{'case':<14s} {'step':<14s} {'mefikit ms':>12s} {'medcoup ms':>12s} {'mc/mf':>9s}"
)
print("-" * 62)
for case, step, mf_t, mc_t in rows:
    print(f"{case:<14s} {step:<14s} {mf_t:>12.3f} {mc_t:>12.3f} {mc_t / mf_t:>8.1f}x")

print()
print("correctness cross-checks:")
all_ok = True
for tag in bench:
    for label, (ok, info) in bench[tag]["checks"].items():
        all_ok &= ok
        print(f"  [{'OK' if ok else 'FAIL'}] {tag}: {label}  {info}")
assert all_ok, "a cross-check failed"
case           step             mefikit ms   medcoup ms     mc/mf
--------------------------------------------------------------
remap-2d       build/prepare         7.805       12.052      1.5x
remap-2d       transfer              0.040        0.227      5.7x
remap-3d       build/prepare        65.415      184.369      2.8x
remap-3d       transfer              0.020        0.534     27.1x
remap-3d-poly  build/prepare        65.900     1228.287     18.6x
remap-3d-poly  transfer              0.020        0.577     28.6x
merge-nodes    merge                 0.262        0.313      1.2x
descend        run                   7.539       15.981      2.1x
overlay        run                   1.430       10.420      7.3x
crack          crack                33.303      291.792      8.8x

correctness cross-checks:
  [OK] remap-2d: intensive match (mf == mc)  7.752687380957468e-13
  [OK] remap-2d: mass (mf == analytic)  (1.0, 1.0)
  [OK] remap-2d: mass (mc == mf)  (1.0, 1.0)
  [OK] remap-3d: intensive match (mf == mc)  0.0
  [OK] remap-3d: mass (mf == analytic)  (1.0, 1.0)
  [OK] remap-3d: mass (mc == mf)  (1.0, 1.0)
  [OK] remap-3d-poly: mass (mf == analytic)  (1.0, 1.0)
  [OK] remap-3d-poly: mass (mc == mf)  (1.0, 1.0)
  [OK] merge-nodes: used nodes == 1875  1875
  [OK] merge-nodes: mc nodes == mf  (1875, 1875)
  [OK] descend: faces == 3 n^2 (n+1)  (43200, 43200, 43200)
  [OK] overlay: area == 1 (both)  (1.0, 1.0)
  [OK] crack: node count (mf == mc)  (64000, 64000)

Feature comparison at a glance

Both libraries cover the common operations shown above. Beyond that, mefikit adds ergonomics of its own — most of it already exercised in this notebook.

Operationmedcouplingmefikit
Structured gridMEDCouplingCMesh + buildUnstructured()build_cmesh(*axes) — one call
Read / write .medReadMeshFromFile / writeUMesh.read / write (same format)
Per-cell measuregetMeasureField + field plumbingmf.M — symbolic, evaluated on demand
P0/P0 conservative remap (quad / hex)MEDCouplingRemapper.prepare("P0P0")mf.transfer.ConservativeP0
P0/P0 volume → surface remapMEDCouplingRemapper.prepare("P0P0")mf.transfer.ConservativeP0
Polyhedral remapMEDCouplingRemapper.prepare("P0P0")mf.transfer.ConservativeP0
Faces of a volume meshbuildDescendingConnectivitydescend()
Merge duplicated nodesmergeNodesmerge_nodes()
2D boolean overlay / imprintIntersect2DMeshesoverlay(operation=...)
Mixed element typesyesyes
Fields, groups and selectionsDataArray arithmetic + explicit plumbingmf.Field DSL, select / eval, groups
Meshless field transfersmanual / lower-levelConstantPiecewise, MovingLeastSquares
File formatsMED, VTK, ENSIGHT, …med, vtk/vtu, vtkhdf, cgns, json, yaml
Native API languageC++ (with Python bindings)Rust core with first-class Python bindings

Let us be perfectly honest: medcoupling remains far broader than mefikit — decades of API surface, advanced field machinery, spline remapping and a huge ecosystem around the MED format. mefikit does not try to replace that. It tries to be direct for the operations above, and fast where it counts: two propositions you have just measured.

Closing thoughts

A fair question: should a medcoupling user switch to mefikit? As always, it depends.

  • You already have a solid, mature medcoupling pipeline: nothing here is broken, and mefikit reads the very same .med files — you can adopt it as a complement. mesh.to_mc() hands you the medcoupling twin of a mefikit mesh in one line.
  • You are starting a new project, work a lot with polyhedral meshes, value a short readable API and care about remap performance: give mefikit a try, you should feel at home very quickly.

Both libraries agree on the most important thing: the meshes are the same, the physics is the same, and the results match to machine precision. Thank you medcoupling for setting such a high bar — mefikit simply tries to reach it with fewer keystrokes and a bit more speed.

If you want to go further: browse the other notebooks of this book, have a look at the roadmap and try the operations above on your own meshes.