microgen.shape package

Shape.

Shape (microgen.shape)

class microgen.shape.Box(dim: tuple[float, float, float] = (1, 1, 1), **kwargs: Vector3DType)

Bases: Shape

Class to generate a box.

The implicit field is the canonical AABB SDF (max(|x|-hx, |y|-hy, |z|-hz) decomposed into outside/inside parts), evaluated in the box’s local frame so center and orientation transform the field correctly. Set on every instance so boxes compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_1_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a box CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int | None = None, level: int = 0, **_: KwargsGenerateType) → pv.PolyData

Generate a box VTK shape using the given parameters.

When bounds or resolution is explicitly provided, fall back to the implicit (marching-cubes-on-SDF) base implementation so polymorphic callers that ask for a specific sampling get what they asked for. Otherwise the native pyvista.Box (fixed 6-face quad mesh controlled by level) is used.

class microgen.shape.Capsule(height: float = 1, radius: float = 0.5, **kwargs: Vector3DType)

Bases: Shape

Class to generate a capsule (cylinder with hemispherical ends).

Canonical frame: capsule axis along +x, segment from (-height/2, 0, 0) to (+height/2, 0, 0), radius radius. The implicit field is the point-to-segment distance minus radius (Inigo Quilez capsule SDF), evaluated in the local frame so center and orientation transform the field correctly. Set on every instance so capsules compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_2_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a capsule CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(resolution: int = 100, theta_resolution: int = 50, phi_resolution: int = 50, **_: KwargsGenerateType) → pv.PolyData

Generate a capsule VTK shape using the given parameters.

class microgen.shape.Cylinder(height: float = 1, radius: float = 0.5, **kwargs: Vector3DType)

Bases: Shape

Class to generate a cylinder.

Canonical frame: cylinder axis along +x from (-height/2, 0, 0) to (+height/2, 0, 0), radius radius. The implicit field is a capped-cylinder SDF (radial + axial distance composition), evaluated in the local frame so center and orientation transform the field correctly. Set on every instance so cylinders compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_3_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a cylinder CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(resolution: int = 100, **_: KwargsGenerateType) → pv.PolyData

Generate a cylinder VTK shape using the given parameters.

class microgen.shape.CylindricalTpms(radius: float, surface_function: Field, offset: float | OffsetGrading | Field | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, center: Vector3DType = (0, 0, 0), orientation: Vector3DType = (0, 0, 0), resolution: int = 20, density: float | None = None)

Bases: Tpms

Class used to generate cylindrical TPMS geometries (sheet or skeletals parts).

class microgen.shape.Ellipsoid(radii: tuple[float, float, float] = (1, 0.5, 0.25), **kwargs: Vector3DType)

Bases: Shape

Class to generate an ellipsoid.

The implicit field is the canonical ellipsoid scalar sqrt((x/rx)^2 + (y/ry)^2 + (z/rz)^2) - 1 (approximate SDF with the correct zero-level set), evaluated in the local frame so center and orientation transform the field correctly. Set on every instance so ellipsoids compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_4_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate an ellipsoid CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(**_: KwargsGenerateType) → pv.PolyData

Generate an ellipsoid VTK polydta using the given parameters.

class microgen.shape.ExtrudedPolygon(list_corners: Sequence[tuple[float, float]] | None = None, height: float = 1, **kwargs: Vector3DType | dict[str, Sequence[tuple[float, float]]])

Bases: Shape

ExtrudedPolygon.

Class to generate an extruded polygon with a given list of points and a thickness

_images/microgen.shape_5_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate an extruded polygon CAD shape (OCCT).

Requires the [cad] extra.

generate_surface_mesh(**_: KwargsGenerateType) → pv.PolyData

Generate an extruded polygon VTK shape using the given parameters.

class microgen.shape.GradedInfill(obj: PolyData, surface_function: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]], offset_skin: float = 0.6, offset_core: float = 0.0, transition: float = 0.5, smoothness: float = 0.2, cell_size: float | Sequence[float] | NDArray[float64] | None = None, repeat_cell: int | Sequence[int] | NDArray[int8] | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), resolution: int = 20)

Bases: Infill

Cartesian TPMS infill with offset graded by distance to the envelope.

Same as Infill (TPMS in the world cartesian frame, clipped by the input object), except the thickness of the TPMS sheet varies with the signed distance to the envelope.

Default behaviour models a graded shell: dense material concentrated at the skin (offset_skin = 0.6, “density 1”), hollowing out toward the core (offset_core = 0.0, “density 0”). Reverse the parameters for a dense-core / porous-skin scaffold.

The cell pattern is still cartesian (axes-aligned gyroid) — only the sheet thickness varies in space — so the pattern tiles cleanly even on bunny-style envelopes with high-curvature features.

class microgen.shape.Infill(obj: PolyData, surface_function: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]], offset: float | OffsetGrading | Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]] | None = None, cell_size: float | Sequence[float] | NDArray[float64] | None = None, repeat_cell: int | Sequence[int] | NDArray[int8] | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), resolution: int = 20, density: float | None = None)

Bases: Tpms

Generate a TPMS infill inside a given object.

property lower_skeletal: PolyData

Lower-skeletal part as a PolyData mesh.

property sheet: PolyData

Sheet part as a PolyData mesh (uses generate_surface_mesh()).

property upper_skeletal: PolyData

Upper-skeletal part as a PolyData mesh.

class microgen.shape.NormedDistance(obj: PolyData, boundary_offset: float, furthest_offset: float, boundary_weight: float = 1.0)

Bases: OffsetGrading

Compute the offset based on the implicit distance to an object.

compute_offset(grid: pv.UnstructuredGrid | pv.StructuredGrid) → npt.NDArray[np.float64]

Compute the offset of the grid.

This method should compute the offset on each point of the grid and return it as a 1D array. The lower_surface and upper_surface fields of the grid will then be updated using this computed offset.

Parameters:

grid (pv.UnstructuredGrid | pv.StructuredGrid) – The grid to compute the offset on.

Returns:

The offset of the grid as a 1D array that matches the number of points in the grid.

Return type:

npt.NDArray[np.float64]

class microgen.shape.Polyhedron(dic: dict[str, list[Vertex | Face]] | None = None, **kwargs: Vector3DType)

Bases: Shape

Class to generate a Polyhedron with a given set of faces and vertices.

The implicit field is the half-space intersection SDF for a convex polyhedron: f(p) = max_k (n_k · (p - c_k)), where n_k is the outward unit normal of face k and c_k its centroid. Points inside all half-spaces satisfy f(p) < 0. Voronoi cells produced by Neper are convex by construction, which is the primary use case.

For non-convex polyhedra the implicit field is meaningless; use generate_cad() / generate_surface_mesh() instead (those work from the explicit face list).

_images/microgen.shape_6_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a polyhedron CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(**_: KwargsGenerateType) → pv.PolyData

Generate a polyhedron VTK shape using the given parameters.

class microgen.shape.Shape(center: Vector3DType = (0, 0, 0), orientation: Vector3DType | Rotation = (0, 0, 0), field: Field | None = None, bounds: BoundsType | None = None, period: PeriodType | None = None)

Bases: object

Unified shape with optional implicit (F-rep) and CAD representations.

Every shape has a center and orientation. It may also carry an implicit scalar field (field), in world coordinates, where f(x, y, z) < 0 means inside. When the implicit field is present, the default generate_surface_mesh() and generate_cad() produce geometry via marching cubes. Subclasses (e.g. Sphere, Tpms) override these methods with their own implementations.

Boolean operators (|, &, -, ~) and smooth boolean methods operate on the implicit field and return a new Shape.

translate(), rotate() and scale() follow the PyVista convention: inplace=False (default) returns a new shape, inplace=True mutates self, and both return the shape. A subclass keeps its class and updates its native parameters (radius, dim, cell_size…) when they can express the transform. When they cannot (e.g. a per-axis scale of a Sphere), inplace=False returns a generic Shape and inplace=True raises ValueError. Shapes without an implicit field (Polyhedron, ExtrudedPolygon, strut lattices) cannot be transformed: the verbs raise ValueError.

Parameters:
  • center – center of the shape

  • orientation – orientation of the shape

  • field – implicit scalar field (x, y, z) -> array, or None

  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax) or None

  • period – (Lx, Ly, Lz) if the field is intrinsically periodic (field(p + L) == field(p) along each axis, up to rounding), or None. Set by Tpms and Spinodoid to cell_size.

property bounds: tuple[float, float, float, float, float, float] | None

The bounding box (xmin, xmax, ymin, ymax, zmin, zmax), or None.

property center: Vector3DType

Geometric center (read-only; changed by the transforms).

Subclasses with a native renderer (Sphere, Tpms, …) read this in their generate_* overrides and bake it into the field. Use translate(), rotate() or scale() to move a shape: they keep the field, the native parameters and the renderers coherent.

copy() → Shape

Return a shallow copy that keeps the subclass and its parameters.

The field callable and immutable parameters are shared; the sampled grid cache and any mutable state listed by the subclass are not, so an inplace=True transform on the copy never touches self.

Returns:

the copy

evaluate(x: NDArray[float64], y: NDArray[float64], z: NDArray[float64]) → NDArray[float64]

Evaluate the implicit scalar field at the given coordinates.

Coordinates are world coordinates: subclasses bake center and orientation into the field, and translate(), rotate() and scale() compose with it.

Parameters:
  • x – x coordinates

  • y – y coordinates

  • z – z coordinates

Returns:

scalar field values (negative = inside)

property field: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]] | None

The implicit scalar field, or None.

generate_cad(bounds: BoundsType | None = None, resolution: int = 50, **_: KwargsGenerateType) → CadShape

Generate a CAD shape.

The default implementation delegates to microgen.cad.shape_to_cad(), which builds a tessellated OCCT BREP from the implicit-field marching-cubes mesh. Concrete subclasses with native primitive paths (Box, Sphere, Cylinder, Capsule, Ellipsoid, Tpms, Spinodoid …) override this method with native OCCT construction.

Requires the optional [cad] install extra (cadquery-ocp-novtk).

Parameters:
  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax)

  • resolution – number of grid points per axis

Returns:

microgen.cad.CadShape wrapping an OCCT TopoDS_Shell

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int = 50, **_: KwargsGenerateType) → pv.PolyData

Generate a surface VTK mesh of the shape.

The default implementation runs marching cubes (f < 0) on the cached implicit grid wrapped in a single-cell halo of “outside” values, so the iso-surface naturally closes at the bbox: where the volume reaches the bounds, cap faces are produced AT the bbox. Subclasses with a native renderer (Sphere, Box, Tpms, …) override this.

The implicit field is expected to be in world coordinates (subclasses with non-zero center / orientation bake those into the field during construction).

The sampled structured grid is cached per (bounds, resolution) on the instance, shared with generate_volume_mesh(). The cache is unbounded — calling this method with many distinct resolution values on the same instance retains every sampled grid until the instance is GC’d.

Parameters:
  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax)

  • resolution – number of grid points per axis

Returns:

triangulated surface mesh

generate_volume_mesh(bounds: BoundsType | None = None, resolution: int = 50, *, backend: str = 'vtk', **options: Any) → pv.UnstructuredGrid

Generate a volumetric VTK mesh of the shape’s interior.

Default implementation samples the implicit field on a structured grid over bounds and keeps cells where f < 0. Subclasses with a native volumetric representation (Tpms, Spinodoid) override this with their cached-grid path.

The implicit field is expected to be in world coordinates (same contract as generate_surface_mesh()).

Backends:

  • "vtk" (default): the clipped structured grid described above; options are ignored.

  • "mmg": the VTK grid remeshed by remesh_keeping_boundaries_for_fem(), which receives options (its default is periodic=True; pass periodic=False for a non-periodic specimen).

  • "meshers": tetrahedra meshed directly from the implicit field by the optional Meshers package (pip install 'microgen[meshers]'). options go to meshers.generate (cells, periodic as one flag per axis, order=2 for Tet10 cells, adapt, …), with these microgen defaults: cells=resolution - 1, periodic=(False, False, False), minimum_quality=0.1, threads=1. The extra option geometry_tolerance_mode is "relative" (default: geometry_tolerance, 0.01 if unset, is a fraction of the smallest extent of bounds) or "absolute" (geometry_tolerance in length units).

The Meshers mesh stores in field_data the boundary facets (meshers_boundary_faces, (M, 3) node indices) and their tags (meshers_boundary_tags) and, for each periodic axis a in x, y, z, the node pairs periodic_pairs_a ((P, 2), lower then upper face) and the translation periodic_shift_a ((1, 3)) from the lower to the upper node.

Parameters:
  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax)

  • resolution – number of grid points per axis

  • backend – "vtk", "mmg" or "meshers"

  • options – options of the "mmg" or "meshers" backend

Returns:

pv.UnstructuredGrid covering the shape’s interior

Raises:
  • ValueError – if backend is unknown

  • ImportError – if backend="meshers" and Meshers is not installed

property orientation: Rotation

Rotation applied by subclasses’ renderers (read-only; see rotate()).

property period: tuple[float, float, float] | None

The intrinsic period (Lx, Ly, Lz) if the field is periodic, else None.

When non-None, self.evaluate(x + Lx, y, z) equals self.evaluate(x, y, z) up to rounding (and analogously for y, z), i.e. periodicity is a data-structure invariant of the field, not a runtime flag. Tpms and Spinodoid set it to cell_size (None for the curvilinear TPMS cells); the transforms keep, permute, scale or reset it.

require_field() → Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]]

Return the implicit field or raise ValueError if it is not set.

rotate(rotation: Rotation | npt.ArrayLike, point: Sequence[float] | None = None, *, inplace: bool = False) → Shape

Rotate the shape about point (PyVista convention).

center rotates about point, orientation composes on the left with rotation and bounds becomes the AABB of the rotated AABB. A rotation within 1e-12 of a signed permutation (quarter turns about the axes) is snapped to it and permutes period; any other rotation sets period to None.

Parameters:
  • rotation – a SciPy Rotation or a proper orthogonal 3x3 matrix

  • point – pivot; defaults to the world origin

  • inplace – mutate self when True; otherwise (default) return a new shape of the same class

Returns:

the rotated shape

Raises:

ValueError – if the shape has no implicit field, or if the matrix is not a rotation

scale(factor: float | Sequence[float], point: Sequence[float] | None = None, *, inplace: bool = False) → Shape

Scale the shape about point (PyVista convention).

A subclass whose native parameters express the scale (uniform scale of a sphere, per-axis scale of an axis-aligned box…) keeps its class and rebuilds its own field. Otherwise the field is composed: \(c\, f(p + (x - p) / s)\) with \(c = \min_i s_i\), exact for a signed distance under a uniform factor and a lower bound of the distance under a per-axis one. period scales with the factors.

Parameters:
  • factor – uniform factor or (sx, sy, sz), strictly positive

  • point – pivot; defaults to the world origin

  • inplace – mutate self when True; otherwise (default) return a new shape (of the same class when its native parameters can express the scale, a generic Shape otherwise)

Returns:

the scaled shape

Raises:

ValueError – if the shape has no implicit field, if a factor is not strictly positive, or if inplace=True and the native parameters cannot express the scale

smooth_difference(other: Shape, k: float) → Shape

Smooth difference with blending radius k.

smooth_intersection(other: Shape, k: float) → Shape

Smooth intersection with blending radius k.

smooth_union(other: Shape, k: float) → Shape

Smooth union with blending radius k.

translate(offset: Sequence[float], *, inplace: bool = False) → Shape

Translate the shape by offset (PyVista convention).

evaluate(p) == old.evaluate(p - offset); center and bounds shift by offset, orientation and period are kept.

Parameters:
  • offset – (dx, dy, dz) world-space shift

  • inplace – mutate self when True; otherwise (default) return a new shape of the same class

Returns:

the translated shape

Raises:

ValueError – if the shape has no implicit field

class microgen.shape.Sphere(radius: float = 1, **kwargs: Vector3DType)

Bases: Shape

Class to generate a sphere.

The implicit field f(p) = ||p - center|| - radius (a true SDF, negative inside) is set on every instance so spheres compose with other shapes through | / & / - and stay usable when the [cad] extra is not installed (only generate_cad() requires CAD).

_images/microgen.shape_7_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a sphere CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int | None = None, theta_resolution: int = 50, phi_resolution: int = 50, **_: KwargsGenerateType) → pv.PolyData

Generate a sphere VTK shape using the given parameters.

When bounds or resolution is explicitly provided, fall back to the implicit (marching-cubes-on-SDF) base implementation so polymorphic callers that ask for a specific sampling get what they asked for. Otherwise the native pyvista.Sphere (parametric, controlled by theta_resolution/phi_resolution) is used.

class microgen.shape.SphericalTpms(radius: float, surface_function: Field, offset: float | OffsetGrading | Field | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, center: Vector3DType = (0, 0, 0), orientation: Vector3DType = (0, 0, 0), resolution: int = 20, density: float | None = None)

Bases: Tpms

Class used to generate spherical TPMS geometries (sheet or skeletals parts).

class microgen.shape.Spinodoid(k0: float = 30.0, bandwidth: float = 5.0, offset: float | None = None, density: float | None = None, anisotropy: Sequence[float] = (1.0, 1.0, 1.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, resolution: int = 32, mode_amplitude_threshold: float = 0.001, seed: int | None = None, center: Vector3DType = (0.0, 0.0, 0.0), orientation: Vector3DType = (0.0, 0.0, 0.0), **kwargs: Vector3DType)

Bases: Shape

Class to generate a periodic Spinodoid microstructure.

Construction is in two stages:

  1. Spectral: an FFT of filtered white noise yields a sparse set of reciprocal-lattice modes (modes, amplitudes, phases) whose magnitudes survive a relative-amplitude threshold.

  2. Geometric: the iso-surface f(x) = offset defines the solid (f(x) ≥ offset is inside). Either offset or density must be given, mirroring microgen.Tpms:

    • offset: the iso-value directly (a scalar in field units).

    • density: target solid volume fraction in (0, 1); microgen finds the offset matching this fraction via Monte Carlo on the F-rep callable.

    The structured grid and grid_solid / surface properties are derived by sampling the callable on a (resolution+1)^3 grid covering the full unit cell.

The implicit field f(x) = Σᵢ Aᵢ cos(kᵢ·x + φᵢ) − offset is bit-for-bit periodic on cell_size (every kᵢ lives on the reciprocal lattice). Periodicity is an invariant — there is no periodic=True flag.

Parameters:
  • k0 – dominant wave number (Gaussian shell center).

  • bandwidth – Gaussian shell width.

  • offset – iso-value defining the solid surface (mutually exclusive with density).

  • density – target solid volume fraction in (0, 1) (mutually exclusive with offset).

  • anisotropy – (aₓ, a_y, a_z) axis-stretch factors applied to wavenumbers in the shell filter K_eff² = (aₓ Kₓ)² + ….

  • cell_size – unit-cell side length(s); scalar or 3-tuple.

  • repeat_cell – integer tiling along each axis.

  • resolution – FFT grid resolution per cell (the structured grid will have resolution + 1 points per axis to cover both endpoints of the periodic cell exactly).

  • mode_amplitude_threshold – keep FFT modes with |F̂| > threshold * max(|F̂|).

  • seed – RNG seed; None for non-deterministic behavior.

  • center – translation of the cell, applied to field and to every generated mesh and CAD shape.

  • orientation – rotation (Euler angles, ZXZ in degrees) of the cell about its local origin, applied before center.

generate_cad(**_: KwargsGenerateType) → CadShape

Generate an OCCT CAD shape (Solid or Compound) of the spinodoid.

Mirrors microgen.Tpms.generate_cad(): extracts the structured-grid surface, builds a closed multi-face periodic shell with planar BREP faces on the cell sides plus per-triangle planar faces on the spinodoid interior, and applies the center / orientation rigid transform. Spinodoids commonly decompose into multiple disjoint solid components — the return type may be a Compound of fused Solids.

Requires the optional [cad] install extra.

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int | None = None, **_: KwargsGenerateType) → pv.PolyData

Generate the iso-surface as a PolyData with center+rotation applied.

The native path uses the cached structured-grid surface whose resolution is fixed at construction time (Spinodoid(resolution=…)). When bounds or resolution is explicitly provided here, fall back to the implicit (marching-cubes-on-SDF) base implementation so polymorphic callers can re-sample the field at an arbitrary resolution / bbox.

generate_volume_mesh(*, backend: str = 'vtk', **options: Any) → pv.UnstructuredGrid

Generate the volumetric solid grid with center+rotation applied.

The backends and the Meshers output are those of Shape.generate_volume_mesh(). "meshers" meshes the Fourier field itself on the local cell, then applies orientation and center. Its defaults here: cells=resolution * repeat_cell, periodic=(True, True, True) (the field is periodic on the cell), and a "relative" geometry_tolerance taken as a fraction of the smallest cell_size.

Parameters:
  • backend – "vtk" (default), "mmg" or "meshers"

  • options – options of the "mmg" or "meshers" backend

Returns:

tetrahedral mesh of the solid phase

Raises:
  • ValueError – if backend is unknown

  • ImportError – if backend="meshers" and Meshers is not installed

property grid: StructuredGrid

Return the structured-grid sampling of the implicit field.

property grid_solid: UnstructuredGrid

Return the volumetric solid grid (cells where f >= 0).

property surface: PolyData

Return the iso-surface mesh of the spinodoid.

class microgen.shape.Sweep(curve_points: npt.NDArray[np.float64] | Callable[[float], npt.NDArray[np.float64]], surface_function: Field, radial_max: float, offset: float | OffsetGrading | Field | None = None, cell_size: float | Sequence[float] | npt.NDArray[np.float64] = 1.0, repeat_cell: int | Sequence[int] | npt.NDArray[np.int8] = 1, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), resolution: int = 20, density: float | None = None, seed_normal: Sequence[float] | None = None, n_curve_samples: int = 200, center: Vector3DType = (0, 0, 0), orientation: Vector3DType = (0, 0, 0))

Bases: Tpms

TPMS along an arbitrary 3D curve — generalisation of CylindricalTpms.

The TPMS is generated in a tube of radius radial_max around an arbitrary curve, in local coordinates (s, r, θ) where:

  • s = arc length along the curve from its start

  • r = perpendicular distance from the curve at the closest point

  • θ = angle around the curve in the local tangent-frame plane

The local frame (T, N, B) is built once at curve setup time using parallel transport along the polyline (tangent from finite differences, normal from a seed transported by Rodrigues rotation between adjacent samples; closed loops get a holonomy correction distributed linearly).

The mesh is generated via the parametric structured-grid path (same as CylindricalTpms / SphericalTpms): we build a structured grid in (s, r, θ) parametric space, evaluate the TPMS field on that grid, and map the parametric points to Cartesian using the parallel-transport frames. generate_surface_mesh then clips the structured grid by the relevant scalar threshold — much cleaner than F-rep MC at a uniform Cartesian resolution, which would under-sample the angular direction and produce dotted artefacts.

CylindricalTpms is a special case of this class (curve = a straight line).

class microgen.shape.Tpms(surface_function: Field, offset: float | OffsetGrading | Field | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, resolution: int = 20, density: float | None = None, **kwargs: Vector3DType)

Bases: Shape

Triply Periodical Minimal Surfaces.

Class to generate Triply Periodical Minimal Surfaces (TPMS) geometry from a given mathematical function, with given offset

functions available :
as_lower_skeletal() → Shape

F-rep Shape for the lower skeletal: {p : f(p) < -offset/2}.

as_sheet(thickness: float | None = None) → Shape

Return an F-rep Shape representing a TPMS sheet of given thickness.

Uses the SDF-normalized field, so thickness is in physical units. If thickness is None, uses self.offset (which may be a scalar, an array sampled on self.grid, or a callable in which case the callable form is used directly). The part is placed at center / orientation, like field.

as_surface() → Shape

Return F-rep Shape for the (open) zero-isosurface, no thickness.

Same field as as_lower_skeletal(); meant for type_part="surface". Marching cubes will produce an open shell — there is no enclosed volume.

as_upper_skeletal() → Shape

F-rep Shape for the upper skeletal: {p : f(p) > offset/2}.

Volume scales with the chosen offset (smaller offset ⇒ larger skeletal), matching the historical CadQuery behaviour and the VTK grid-clip path.

generate_cad(type_part: TpmsPartType = 'sheet', smoothing: int = 0, algo_resolution: int | None = None, **_: KwargsGenerateType) → CadShape

Generate an OCCT CAD shape of the requested TPMS part.

Builds the periodic structured-grid mesh (same as generate_surface_mesh()) and converts it to an OCCT shell with planar BREP faces on the cell-boundary planes (one face per side, carrying its tessellation) plus per-triangle planar faces for the TPMS interior surface. This is the layout gmsh’s setPeriodic expects: it pairs opposite cell-side faces by their plane equation.

Requires the optional [cad] install extra (cadquery-ocp-novtk).

Parameters:
  • type_part – "sheet", "lower skeletal", "upper skeletal" or "surface" (open zero-isosurface, no thickness)

  • smoothing – Laplacian smoothing iterations on the boundary mesh (default 0; non-zero hurts strict periodicity)

  • algo_resolution – temporary-TPMS resolution for density→offset search (only used when self.density is set)

Returns:

microgen.cad.CadShape wrapping an OCCT TopoDS_Shell with 6 planar boundary faces + interior tessellation.

generate_surface_mesh(type_part: TpmsPartType = 'sheet', algo_resolution: int | None = None, **_: KwargsGenerateType) → pv.PolyData

Generate the PyVista mesh of the requested TPMS part.

Same F-rep pipeline as generate_cad() (skeletals are clipped to the cell box), so the two outputs share the exact same triangulation and therefore the same volume.

Parameters:
  • type_part – "sheet", "lower skeletal", "upper skeletal" or "surface"

  • algo_resolution – temporary-TPMS resolution for density→offset search (only used when self.density is set)

generate_volume_mesh(type_part: TpmsPartType = 'sheet', algo_resolution: int | None = None, *, backend: str = 'vtk', **options: Any) → pv.UnstructuredGrid

Generate VTK UnstructuredGrid object of the required TPMS part.

Applies center and orientation to the cached grid so the returned mesh lands at the declared world position — matching the contract of generate_surface_mesh().

The backends and the Meshers output are those of Shape.generate_volume_mesh(). "meshers" meshes the part directly from the raw TPMS field on the local cell (sheet \(|f| < o/2\), upper skeletal \(f > o/2\), lower skeletal \(f < -o/2\), with \(o\) the offset), then applies orientation and center. Its defaults here: cells=resolution * repeat_cell - 1 per axis, periodic on the three axes unless the offset is a callable (a graded offset is in general not periodic: set periodic explicitly), and a "relative" geometry_tolerance taken as a fraction of the smallest cell_size.

Note

With density, the offset is fitted on the VTK grid (algo_resolution), so the Meshers mesh, closer to the exact level set, can differ from density by the VTK discretization error (about 1 % at the default resolution). Increase algo_resolution to reduce it.

Parameters:
  • type_part – "sheet", "lower skeletal" or "upper skeletal"

  • algo_resolution – grid resolution of the density fit

  • backend – "vtk" (default), "mmg" or "meshers"

  • options – options of the "mmg" or "meshers" backend

Returns:

tetrahedral mesh of the part

Raises:
  • ValueError – if type_part or backend is unknown

  • NotImplementedError – with backend="meshers", for a TPMS subclass (mapped, swept or clipped cell) or an offset given as a sampled array or an OffsetGrading

  • ImportError – if backend="meshers" and Meshers is not installed

property grid_lower_skeletal: UnstructuredGrid

Return lower skeletal part.

property grid_sheet: UnstructuredGrid

Return sheet part.

property grid_upper_skeletal: UnstructuredGrid

Return upper skeletal part.

property lower_skeletal: PolyData

Return lower skeletal part.

property offset: float | NDArray[float64] | None

Returns the offset value.

classmethod offset_from_density(surface_function: Field, part_type: TpmsPartType, density: float, resolution: int = 20) → float

Return the offset corresponding to the required density.

Parameters:
  • surface_function – tpms function

  • part_type – type of the part (sheet, lower skeletal or upper skeletal)

  • density – Required density, 0.5 for 50%

  • resolution – resolution of the tpms used to compute the offset

Returns:

corresponding offset value

property raw_field: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]]

The raw (non-SDF-normalized) TPMS field callable, in the local frame.

property sheet: PolyData

Return sheet part.

property skeletals: tuple[PolyData, PolyData]

Returns both skeletal parts.

property surface: PolyData

Returns isosurface f(x, y, z) = 0.

property upper_skeletal: PolyData

Return upper skeletal part.

microgen.shape.batch_smooth_union(shapes: list[Shape], k: float = 0.0) → Shape

Combine many shapes with smooth union in a flat loop (no recursion).

This avoids the recursion-depth limit that arises when chaining hundreds of binary smooth_union calls, each wrapping the previous in a lambda.

microgen.shape.from_field(field: Field, bounds: BoundsType | None = None) → Shape

Wrap any callable f(x, y, z) -> scalar as a Shape with an implicit field.

microgen.shape.new_geometry(shape: str, param_geom: dict[str, GeometryParameterType], center: tuple[float, float, float] = (0, 0, 0), orientation: tuple[float, float, float] = (0, 0, 0)) → Shape

Create a new basic geometry with given shape and geometrical parameters.

Parameters:
  • shape – name of the geometry

  • param_geom – dictionary with required geometrical parameters

  • center – center

  • orientation – orientation

Return geometry:

Shape

Basic Geometry.

Basic Geometry (microgen.shape.shape)

class microgen.shape.shape.Shape(center: Vector3DType = (0, 0, 0), orientation: Vector3DType | Rotation = (0, 0, 0), field: Field | None = None, bounds: BoundsType | None = None, period: PeriodType | None = None)

Bases: object

Unified shape with optional implicit (F-rep) and CAD representations.

Every shape has a center and orientation. It may also carry an implicit scalar field (field), in world coordinates, where f(x, y, z) < 0 means inside. When the implicit field is present, the default generate_surface_mesh() and generate_cad() produce geometry via marching cubes. Subclasses (e.g. Sphere, Tpms) override these methods with their own implementations.

Boolean operators (|, &, -, ~) and smooth boolean methods operate on the implicit field and return a new Shape.

translate(), rotate() and scale() follow the PyVista convention: inplace=False (default) returns a new shape, inplace=True mutates self, and both return the shape. A subclass keeps its class and updates its native parameters (radius, dim, cell_size…) when they can express the transform. When they cannot (e.g. a per-axis scale of a Sphere), inplace=False returns a generic Shape and inplace=True raises ValueError. Shapes without an implicit field (Polyhedron, ExtrudedPolygon, strut lattices) cannot be transformed: the verbs raise ValueError.

Parameters:
  • center – center of the shape

  • orientation – orientation of the shape

  • field – implicit scalar field (x, y, z) -> array, or None

  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax) or None

  • period – (Lx, Ly, Lz) if the field is intrinsically periodic (field(p + L) == field(p) along each axis, up to rounding), or None. Set by Tpms and Spinodoid to cell_size.

property bounds: tuple[float, float, float, float, float, float] | None

The bounding box (xmin, xmax, ymin, ymax, zmin, zmax), or None.

property center: Vector3DType

Geometric center (read-only; changed by the transforms).

Subclasses with a native renderer (Sphere, Tpms, …) read this in their generate_* overrides and bake it into the field. Use translate(), rotate() or scale() to move a shape: they keep the field, the native parameters and the renderers coherent.

copy() → Shape

Return a shallow copy that keeps the subclass and its parameters.

The field callable and immutable parameters are shared; the sampled grid cache and any mutable state listed by the subclass are not, so an inplace=True transform on the copy never touches self.

Returns:

the copy

evaluate(x: NDArray[float64], y: NDArray[float64], z: NDArray[float64]) → NDArray[float64]

Evaluate the implicit scalar field at the given coordinates.

Coordinates are world coordinates: subclasses bake center and orientation into the field, and translate(), rotate() and scale() compose with it.

Parameters:
  • x – x coordinates

  • y – y coordinates

  • z – z coordinates

Returns:

scalar field values (negative = inside)

property field: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]] | None

The implicit scalar field, or None.

generate_cad(bounds: BoundsType | None = None, resolution: int = 50, **_: KwargsGenerateType) → CadShape

Generate a CAD shape.

The default implementation delegates to microgen.cad.shape_to_cad(), which builds a tessellated OCCT BREP from the implicit-field marching-cubes mesh. Concrete subclasses with native primitive paths (Box, Sphere, Cylinder, Capsule, Ellipsoid, Tpms, Spinodoid …) override this method with native OCCT construction.

Requires the optional [cad] install extra (cadquery-ocp-novtk).

Parameters:
  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax)

  • resolution – number of grid points per axis

Returns:

microgen.cad.CadShape wrapping an OCCT TopoDS_Shell

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int = 50, **_: KwargsGenerateType) → pv.PolyData

Generate a surface VTK mesh of the shape.

The default implementation runs marching cubes (f < 0) on the cached implicit grid wrapped in a single-cell halo of “outside” values, so the iso-surface naturally closes at the bbox: where the volume reaches the bounds, cap faces are produced AT the bbox. Subclasses with a native renderer (Sphere, Box, Tpms, …) override this.

The implicit field is expected to be in world coordinates (subclasses with non-zero center / orientation bake those into the field during construction).

The sampled structured grid is cached per (bounds, resolution) on the instance, shared with generate_volume_mesh(). The cache is unbounded — calling this method with many distinct resolution values on the same instance retains every sampled grid until the instance is GC’d.

Parameters:
  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax)

  • resolution – number of grid points per axis

Returns:

triangulated surface mesh

generate_volume_mesh(bounds: BoundsType | None = None, resolution: int = 50, *, backend: str = 'vtk', **options: Any) → pv.UnstructuredGrid

Generate a volumetric VTK mesh of the shape’s interior.

Default implementation samples the implicit field on a structured grid over bounds and keeps cells where f < 0. Subclasses with a native volumetric representation (Tpms, Spinodoid) override this with their cached-grid path.

The implicit field is expected to be in world coordinates (same contract as generate_surface_mesh()).

Backends:

  • "vtk" (default): the clipped structured grid described above; options are ignored.

  • "mmg": the VTK grid remeshed by remesh_keeping_boundaries_for_fem(), which receives options (its default is periodic=True; pass periodic=False for a non-periodic specimen).

  • "meshers": tetrahedra meshed directly from the implicit field by the optional Meshers package (pip install 'microgen[meshers]'). options go to meshers.generate (cells, periodic as one flag per axis, order=2 for Tet10 cells, adapt, …), with these microgen defaults: cells=resolution - 1, periodic=(False, False, False), minimum_quality=0.1, threads=1. The extra option geometry_tolerance_mode is "relative" (default: geometry_tolerance, 0.01 if unset, is a fraction of the smallest extent of bounds) or "absolute" (geometry_tolerance in length units).

The Meshers mesh stores in field_data the boundary facets (meshers_boundary_faces, (M, 3) node indices) and their tags (meshers_boundary_tags) and, for each periodic axis a in x, y, z, the node pairs periodic_pairs_a ((P, 2), lower then upper face) and the translation periodic_shift_a ((1, 3)) from the lower to the upper node.

Parameters:
  • bounds – (xmin, xmax, ymin, ymax, zmin, zmax)

  • resolution – number of grid points per axis

  • backend – "vtk", "mmg" or "meshers"

  • options – options of the "mmg" or "meshers" backend

Returns:

pv.UnstructuredGrid covering the shape’s interior

Raises:
  • ValueError – if backend is unknown

  • ImportError – if backend="meshers" and Meshers is not installed

property orientation: Rotation

Rotation applied by subclasses’ renderers (read-only; see rotate()).

property period: tuple[float, float, float] | None

The intrinsic period (Lx, Ly, Lz) if the field is periodic, else None.

When non-None, self.evaluate(x + Lx, y, z) equals self.evaluate(x, y, z) up to rounding (and analogously for y, z), i.e. periodicity is a data-structure invariant of the field, not a runtime flag. Tpms and Spinodoid set it to cell_size (None for the curvilinear TPMS cells); the transforms keep, permute, scale or reset it.

require_field() → Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]]

Return the implicit field or raise ValueError if it is not set.

rotate(rotation: Rotation | npt.ArrayLike, point: Sequence[float] | None = None, *, inplace: bool = False) → Shape

Rotate the shape about point (PyVista convention).

center rotates about point, orientation composes on the left with rotation and bounds becomes the AABB of the rotated AABB. A rotation within 1e-12 of a signed permutation (quarter turns about the axes) is snapped to it and permutes period; any other rotation sets period to None.

Parameters:
  • rotation – a SciPy Rotation or a proper orthogonal 3x3 matrix

  • point – pivot; defaults to the world origin

  • inplace – mutate self when True; otherwise (default) return a new shape of the same class

Returns:

the rotated shape

Raises:

ValueError – if the shape has no implicit field, or if the matrix is not a rotation

scale(factor: float | Sequence[float], point: Sequence[float] | None = None, *, inplace: bool = False) → Shape

Scale the shape about point (PyVista convention).

A subclass whose native parameters express the scale (uniform scale of a sphere, per-axis scale of an axis-aligned box…) keeps its class and rebuilds its own field. Otherwise the field is composed: \(c\, f(p + (x - p) / s)\) with \(c = \min_i s_i\), exact for a signed distance under a uniform factor and a lower bound of the distance under a per-axis one. period scales with the factors.

Parameters:
  • factor – uniform factor or (sx, sy, sz), strictly positive

  • point – pivot; defaults to the world origin

  • inplace – mutate self when True; otherwise (default) return a new shape (of the same class when its native parameters can express the scale, a generic Shape otherwise)

Returns:

the scaled shape

Raises:

ValueError – if the shape has no implicit field, if a factor is not strictly positive, or if inplace=True and the native parameters cannot express the scale

smooth_difference(other: Shape, k: float) → Shape

Smooth difference with blending radius k.

smooth_intersection(other: Shape, k: float) → Shape

Smooth intersection with blending radius k.

smooth_union(other: Shape, k: float) → Shape

Smooth union with blending radius k.

translate(offset: Sequence[float], *, inplace: bool = False) → Shape

Translate the shape by offset (PyVista convention).

evaluate(p) == old.evaluate(p - offset); center and bounds shift by offset, orientation and period are kept.

Parameters:
  • offset – (dx, dy, dz) world-space shift

  • inplace – mutate self when True; otherwise (default) return a new shape of the same class

Returns:

the translated shape

Raises:

ValueError – if the shape has no implicit field

exception microgen.shape.shape.ShellCreationError

Bases: Exception

Raised when an OCCT shell cannot be created from a mesh.

Box.

Box (microgen.shape.box)

class microgen.shape.box.Box(dim: tuple[float, float, float] = (1, 1, 1), **kwargs: Vector3DType)

Bases: Shape

Class to generate a box.

The implicit field is the canonical AABB SDF (max(|x|-hx, |y|-hy, |z|-hz) decomposed into outside/inside parts), evaluated in the box’s local frame so center and orientation transform the field correctly. Set on every instance so boxes compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_8_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a box CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int | None = None, level: int = 0, **_: KwargsGenerateType) → pv.PolyData

Generate a box VTK shape using the given parameters.

When bounds or resolution is explicitly provided, fall back to the implicit (marching-cubes-on-SDF) base implementation so polymorphic callers that ask for a specific sampling get what they asked for. Otherwise the native pyvista.Box (fixed 6-face quad mesh controlled by level) is used.

Capsule.

Capsule (microgen.shape.capsule)

class microgen.shape.capsule.Capsule(height: float = 1, radius: float = 0.5, **kwargs: Vector3DType)

Bases: Shape

Class to generate a capsule (cylinder with hemispherical ends).

Canonical frame: capsule axis along +x, segment from (-height/2, 0, 0) to (+height/2, 0, 0), radius radius. The implicit field is the point-to-segment distance minus radius (Inigo Quilez capsule SDF), evaluated in the local frame so center and orientation transform the field correctly. Set on every instance so capsules compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_9_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a capsule CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(resolution: int = 100, theta_resolution: int = 50, phi_resolution: int = 50, **_: KwargsGenerateType) → pv.PolyData

Generate a capsule VTK shape using the given parameters.

Cylinder.

Cylinder (microgen.shape.cylinder)

class microgen.shape.cylinder.Cylinder(height: float = 1, radius: float = 0.5, **kwargs: Vector3DType)

Bases: Shape

Class to generate a cylinder.

Canonical frame: cylinder axis along +x from (-height/2, 0, 0) to (+height/2, 0, 0), radius radius. The implicit field is a capped-cylinder SDF (radial + axial distance composition), evaluated in the local frame so center and orientation transform the field correctly. Set on every instance so cylinders compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_10_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a cylinder CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(resolution: int = 100, **_: KwargsGenerateType) → pv.PolyData

Generate a cylinder VTK shape using the given parameters.

Ellipsoid.

Ellipsoid (microgen.shape.ellipsoid)

class microgen.shape.ellipsoid.Ellipsoid(radii: tuple[float, float, float] = (1, 0.5, 0.25), **kwargs: Vector3DType)

Bases: Shape

Class to generate an ellipsoid.

The implicit field is the canonical ellipsoid scalar sqrt((x/rx)^2 + (y/ry)^2 + (z/rz)^2) - 1 (approximate SDF with the correct zero-level set), evaluated in the local frame so center and orientation transform the field correctly. Set on every instance so ellipsoids compose via | / & / - and stay usable without the [cad] extra (only generate_cad() requires CAD).

_images/microgen.shape_11_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate an ellipsoid CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(**_: KwargsGenerateType) → pv.PolyData

Generate an ellipsoid VTK polydta using the given parameters.

Extruded Polygon.

Extruded Polygon (microgen.shape.extruded_polygon)

class microgen.shape.extruded_polygon.ExtrudedPolygon(list_corners: Sequence[tuple[float, float]] | None = None, height: float = 1, **kwargs: Vector3DType | dict[str, Sequence[tuple[float, float]]])

Bases: Shape

ExtrudedPolygon.

Class to generate an extruded polygon with a given list of points and a thickness

_images/microgen.shape_12_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate an extruded polygon CAD shape (OCCT).

Requires the [cad] extra.

generate_surface_mesh(**_: KwargsGenerateType) → pv.PolyData

Generate an extruded polygon VTK shape using the given parameters.

Polyhedron.

Polyhedron (microgen.shape.polyhedron)

class microgen.shape.polyhedron.Polyhedron(dic: dict[str, list[Vertex | Face]] | None = None, **kwargs: Vector3DType)

Bases: Shape

Class to generate a Polyhedron with a given set of faces and vertices.

The implicit field is the half-space intersection SDF for a convex polyhedron: f(p) = max_k (n_k · (p - c_k)), where n_k is the outward unit normal of face k and c_k its centroid. Points inside all half-spaces satisfy f(p) < 0. Voronoi cells produced by Neper are convex by construction, which is the primary use case.

For non-convex polyhedra the implicit field is meaningless; use generate_cad() / generate_surface_mesh() instead (those work from the explicit face list).

_images/microgen.shape_13_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a polyhedron CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(**_: KwargsGenerateType) → pv.PolyData

Generate a polyhedron VTK shape using the given parameters.

microgen.shape.polyhedron.read_obj(filename: str) → dict[str, list[tuple[float, float, float] | dict[str, list[int]]]]

Read vertices and faces from obj format file for polyhedron.

Sphere.

Sphere (microgen.shape.sphere)

class microgen.shape.sphere.Sphere(radius: float = 1, **kwargs: Vector3DType)

Bases: Shape

Class to generate a sphere.

The implicit field f(p) = ||p - center|| - radius (a true SDF, negative inside) is set on every instance so spheres compose with other shapes through | / & / - and stay usable when the [cad] extra is not installed (only generate_cad() requires CAD).

_images/microgen.shape_14_0.png
generate_cad(**_: KwargsGenerateType) → CadShape

Generate a sphere CAD shape (OCCT). Requires the [cad] extra.

generate_surface_mesh(bounds: BoundsType | None = None, resolution: int | None = None, theta_resolution: int = 50, phi_resolution: int = 50, **_: KwargsGenerateType) → pv.PolyData

Generate a sphere VTK shape using the given parameters.

When bounds or resolution is explicitly provided, fall back to the implicit (marching-cubes-on-SDF) base implementation so polymorphic callers that ask for a specific sampling get what they asked for. Otherwise the native pyvista.Sphere (parametric, controlled by theta_resolution/phi_resolution) is used.

TPMS.

TPMS (microgen.shape.tpms)

class microgen.shape.tpms.CylindricalTpms(radius: float, surface_function: Field, offset: float | OffsetGrading | Field | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, center: Vector3DType = (0, 0, 0), orientation: Vector3DType = (0, 0, 0), resolution: int = 20, density: float | None = None)

Bases: Tpms

Class used to generate cylindrical TPMS geometries (sheet or skeletals parts).

class microgen.shape.tpms.GradedInfill(obj: PolyData, surface_function: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]], offset_skin: float = 0.6, offset_core: float = 0.0, transition: float = 0.5, smoothness: float = 0.2, cell_size: float | Sequence[float] | NDArray[float64] | None = None, repeat_cell: int | Sequence[int] | NDArray[int8] | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), resolution: int = 20)

Bases: Infill

Cartesian TPMS infill with offset graded by distance to the envelope.

Same as Infill (TPMS in the world cartesian frame, clipped by the input object), except the thickness of the TPMS sheet varies with the signed distance to the envelope.

Default behaviour models a graded shell: dense material concentrated at the skin (offset_skin = 0.6, “density 1”), hollowing out toward the core (offset_core = 0.0, “density 0”). Reverse the parameters for a dense-core / porous-skin scaffold.

The cell pattern is still cartesian (axes-aligned gyroid) — only the sheet thickness varies in space — so the pattern tiles cleanly even on bunny-style envelopes with high-curvature features.

class microgen.shape.tpms.Infill(obj: PolyData, surface_function: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]], offset: float | OffsetGrading | Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]] | None = None, cell_size: float | Sequence[float] | NDArray[float64] | None = None, repeat_cell: int | Sequence[int] | NDArray[int8] | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), resolution: int = 20, density: float | None = None)

Bases: Tpms

Generate a TPMS infill inside a given object.

property lower_skeletal: PolyData

Lower-skeletal part as a PolyData mesh.

property sheet: PolyData

Sheet part as a PolyData mesh (uses generate_surface_mesh()).

property upper_skeletal: PolyData

Upper-skeletal part as a PolyData mesh.

exception microgen.shape.tpms.ShellCreationError

Bases: Exception

Raised when an OCCT shell cannot be created from a mesh.

class microgen.shape.tpms.SphericalTpms(radius: float, surface_function: Field, offset: float | OffsetGrading | Field | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, center: Vector3DType = (0, 0, 0), orientation: Vector3DType = (0, 0, 0), resolution: int = 20, density: float | None = None)

Bases: Tpms

Class used to generate spherical TPMS geometries (sheet or skeletals parts).

class microgen.shape.tpms.Sweep(curve_points: npt.NDArray[np.float64] | Callable[[float], npt.NDArray[np.float64]], surface_function: Field, radial_max: float, offset: float | OffsetGrading | Field | None = None, cell_size: float | Sequence[float] | npt.NDArray[np.float64] = 1.0, repeat_cell: int | Sequence[int] | npt.NDArray[np.int8] = 1, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), resolution: int = 20, density: float | None = None, seed_normal: Sequence[float] | None = None, n_curve_samples: int = 200, center: Vector3DType = (0, 0, 0), orientation: Vector3DType = (0, 0, 0))

Bases: Tpms

TPMS along an arbitrary 3D curve — generalisation of CylindricalTpms.

The TPMS is generated in a tube of radius radial_max around an arbitrary curve, in local coordinates (s, r, θ) where:

  • s = arc length along the curve from its start

  • r = perpendicular distance from the curve at the closest point

  • θ = angle around the curve in the local tangent-frame plane

The local frame (T, N, B) is built once at curve setup time using parallel transport along the polyline (tangent from finite differences, normal from a seed transported by Rodrigues rotation between adjacent samples; closed loops get a holonomy correction distributed linearly).

The mesh is generated via the parametric structured-grid path (same as CylindricalTpms / SphericalTpms): we build a structured grid in (s, r, θ) parametric space, evaluate the TPMS field on that grid, and map the parametric points to Cartesian using the parallel-transport frames. generate_surface_mesh then clips the structured grid by the relevant scalar threshold — much cleaner than F-rep MC at a uniform Cartesian resolution, which would under-sample the angular direction and produce dotted artefacts.

CylindricalTpms is a special case of this class (curve = a straight line).

class microgen.shape.tpms.Tpms(surface_function: Field, offset: float | OffsetGrading | Field | None = None, phase_shift: Sequence[float] = (0.0, 0.0, 0.0), cell_size: float | Sequence[float] = 1.0, repeat_cell: int | Sequence[int] = 1, resolution: int = 20, density: float | None = None, **kwargs: Vector3DType)

Bases: Shape

Triply Periodical Minimal Surfaces.

Class to generate Triply Periodical Minimal Surfaces (TPMS) geometry from a given mathematical function, with given offset

functions available :
as_lower_skeletal() → Shape

F-rep Shape for the lower skeletal: {p : f(p) < -offset/2}.

as_sheet(thickness: float | None = None) → Shape

Return an F-rep Shape representing a TPMS sheet of given thickness.

Uses the SDF-normalized field, so thickness is in physical units. If thickness is None, uses self.offset (which may be a scalar, an array sampled on self.grid, or a callable in which case the callable form is used directly). The part is placed at center / orientation, like field.

as_surface() → Shape

Return F-rep Shape for the (open) zero-isosurface, no thickness.

Same field as as_lower_skeletal(); meant for type_part="surface". Marching cubes will produce an open shell — there is no enclosed volume.

as_upper_skeletal() → Shape

F-rep Shape for the upper skeletal: {p : f(p) > offset/2}.

Volume scales with the chosen offset (smaller offset ⇒ larger skeletal), matching the historical CadQuery behaviour and the VTK grid-clip path.

generate_cad(type_part: TpmsPartType = 'sheet', smoothing: int = 0, algo_resolution: int | None = None, **_: KwargsGenerateType) → CadShape

Generate an OCCT CAD shape of the requested TPMS part.

Builds the periodic structured-grid mesh (same as generate_surface_mesh()) and converts it to an OCCT shell with planar BREP faces on the cell-boundary planes (one face per side, carrying its tessellation) plus per-triangle planar faces for the TPMS interior surface. This is the layout gmsh’s setPeriodic expects: it pairs opposite cell-side faces by their plane equation.

Requires the optional [cad] install extra (cadquery-ocp-novtk).

Parameters:
  • type_part – "sheet", "lower skeletal", "upper skeletal" or "surface" (open zero-isosurface, no thickness)

  • smoothing – Laplacian smoothing iterations on the boundary mesh (default 0; non-zero hurts strict periodicity)

  • algo_resolution – temporary-TPMS resolution for density→offset search (only used when self.density is set)

Returns:

microgen.cad.CadShape wrapping an OCCT TopoDS_Shell with 6 planar boundary faces + interior tessellation.

generate_surface_mesh(type_part: TpmsPartType = 'sheet', algo_resolution: int | None = None, **_: KwargsGenerateType) → pv.PolyData

Generate the PyVista mesh of the requested TPMS part.

Same F-rep pipeline as generate_cad() (skeletals are clipped to the cell box), so the two outputs share the exact same triangulation and therefore the same volume.

Parameters:
  • type_part – "sheet", "lower skeletal", "upper skeletal" or "surface"

  • algo_resolution – temporary-TPMS resolution for density→offset search (only used when self.density is set)

generate_volume_mesh(type_part: TpmsPartType = 'sheet', algo_resolution: int | None = None, *, backend: str = 'vtk', **options: Any) → pv.UnstructuredGrid

Generate VTK UnstructuredGrid object of the required TPMS part.

Applies center and orientation to the cached grid so the returned mesh lands at the declared world position — matching the contract of generate_surface_mesh().

The backends and the Meshers output are those of Shape.generate_volume_mesh(). "meshers" meshes the part directly from the raw TPMS field on the local cell (sheet \(|f| < o/2\), upper skeletal \(f > o/2\), lower skeletal \(f < -o/2\), with \(o\) the offset), then applies orientation and center. Its defaults here: cells=resolution * repeat_cell - 1 per axis, periodic on the three axes unless the offset is a callable (a graded offset is in general not periodic: set periodic explicitly), and a "relative" geometry_tolerance taken as a fraction of the smallest cell_size.

Note

With density, the offset is fitted on the VTK grid (algo_resolution), so the Meshers mesh, closer to the exact level set, can differ from density by the VTK discretization error (about 1 % at the default resolution). Increase algo_resolution to reduce it.

Parameters:
  • type_part – "sheet", "lower skeletal" or "upper skeletal"

  • algo_resolution – grid resolution of the density fit

  • backend – "vtk" (default), "mmg" or "meshers"

  • options – options of the "mmg" or "meshers" backend

Returns:

tetrahedral mesh of the part

Raises:
  • ValueError – if type_part or backend is unknown

  • NotImplementedError – with backend="meshers", for a TPMS subclass (mapped, swept or clipped cell) or an offset given as a sampled array or an OffsetGrading

  • ImportError – if backend="meshers" and Meshers is not installed

property grid_lower_skeletal: UnstructuredGrid

Return lower skeletal part.

property grid_sheet: UnstructuredGrid

Return sheet part.

property grid_upper_skeletal: UnstructuredGrid

Return upper skeletal part.

property lower_skeletal: PolyData

Return lower skeletal part.

property offset: float | NDArray[float64] | None

Returns the offset value.

classmethod offset_from_density(surface_function: Field, part_type: TpmsPartType, density: float, resolution: int = 20) → float

Return the offset corresponding to the required density.

Parameters:
  • surface_function – tpms function

  • part_type – type of the part (sheet, lower skeletal or upper skeletal)

  • density – Required density, 0.5 for 50%

  • resolution – resolution of the tpms used to compute the offset

Returns:

corresponding offset value

property raw_field: Callable[[NDArray[float64], NDArray[float64], NDArray[float64]], NDArray[float64]]

The raw (non-SDF-normalized) TPMS field callable, in the local frame.

property sheet: PolyData

Return sheet part.

property skeletals: tuple[PolyData, PolyData]

Returns both skeletal parts.

property surface: PolyData

Returns isosurface f(x, y, z) = 0.

property upper_skeletal: PolyData

Return upper skeletal part.

F-rep Implicit Operations.

Implicit Operations (microgen.shape.implicit_ops)

Module-level boolean, blending, and utility operations for shapes that carry an implicit scalar field (field). All functions accept and return Shape instances.

microgen.shape.implicit_ops.batch_smooth_union(shapes: list[Shape], k: float = 0.0) → Shape

Combine many shapes with smooth union in a flat loop (no recursion).

This avoids the recursion-depth limit that arises when chaining hundreds of binary smooth_union calls, each wrapping the previous in a lambda.

microgen.shape.implicit_ops.blend(a: Shape, b: Shape, factor: float = 0.5) → Shape

Linear interpolation between two fields: (1-t)*a + t*b.

microgen.shape.implicit_ops.box(dims: tuple[float, float, float], center: tuple[float, float, float] = (0.0, 0.0, 0.0)) → Shape

Axis-aligned box as an F-rep Shape.

SDF formula max(|x-cx|-hx, |y-cy|-hy, |z-cz|-hz): signed distance to the box surface (negative inside, positive outside, zero on the surface). Useful as a clipping primitive — e.g. intersection(skeletal, box(...)) bounds an unbounded TPMS skeletal field to a single cell.

Parameters:
  • dims – full side lengths (dx, dy, dz)

  • center – box center (default origin)

Returns:

Shape carrying the box SDF

microgen.shape.implicit_ops.complement(a: Shape) → Shape

Complement (negate the field): inside becomes outside and vice versa.

microgen.shape.implicit_ops.difference(a: Shape, b: Shape) → Shape

Difference of two shapes (a minus b).

microgen.shape.implicit_ops.from_field(field: Field, bounds: BoundsType | None = None) → Shape

Wrap any callable f(x, y, z) -> scalar as a Shape with an implicit field.

microgen.shape.implicit_ops.intersection(a: Shape, b: Shape) → Shape

Intersection of two shapes (hard boolean).

microgen.shape.implicit_ops.normalize_to_sdf(shape: Shape, epsilon: float = 1e-10) → Shape

Return a new Shape with gradient-normalized SDF field: f / |nabla f|.

Uses autograd for exact analytical gradients when the field function is differentiable through autograd.numpy. Falls back to central finite differences otherwise.

Parameters:
  • shape – shape whose implicit field to normalize

  • epsilon – floor for gradient magnitude (avoids division by zero at saddle points)

microgen.shape.implicit_ops.repeat(shape: Shape, spacing: tuple[float, float, float], k: float = 0.0) → Shape

Infinite repetition via coordinate modulo.

Parameters:
  • shape – unit cell shape to tile

  • spacing – (sx, sy, sz) repetition period per axis

  • k – smooth blending radius across cell boundaries. When k > 0, the base field is evaluated at the 26 neighboring periodic images in addition to the current cell and all values are combined with smooth minimum, so that primitives from adjacent cells blend seamlessly. When k <= 0 (default), a simple coordinate-modulo repetition is used (hard tiling).

microgen.shape.implicit_ops.shell(shape: Shape, thickness: float | Field) → Shape

Hollow shell: |f(p)| - thickness(p) / 2.

thickness may be a constant (scalar) or a callable thickness(x, y, z) -> array for spatially-varying shells. Negative or zero thickness at a point yields no inclusion in the shell at that point.

microgen.shape.implicit_ops.smooth_difference(a: Shape, b: Shape, k: float) → Shape

Smooth difference (a minus b) with blending radius k.

microgen.shape.implicit_ops.smooth_intersection(a: Shape, b: Shape, k: float) → Shape

Smooth intersection with blending radius k.

microgen.shape.implicit_ops.smooth_union(a: Shape, b: Shape, k: float) → Shape

Smooth union with blending radius k.

microgen.shape.implicit_ops.union(a: Shape, b: Shape) → Shape

Union of two shapes (hard boolean).

TPMS surface functions.

microgen.shape.surface_functions.fischer_koch_s(x: ndarray, y: ndarray, z: ndarray) → ndarray

Fischer-Koch S.

\[cos(2 x) sin(y) cos(z) + cos(x) cos(2 y) sin(z) + sin(x) cos(y) cos(2 z) = 0\]
_images/microgen.shape_16_0.png
microgen.shape.surface_functions.gyroid(x: ndarray, y: ndarray, z: ndarray) → ndarray

Gyroid.

\[sin(x) cos(y) + sin(y) cos(z) + sin(z) cos(x) = 0\]
_images/microgen.shape_17_0.png
microgen.shape.surface_functions.honeycomb(x: ndarray, y: ndarray, z: ndarray) → ndarray

Honneycomb.

\[sin(x) cos(y) + sin(y) + cos(z) = 0\]
_images/microgen.shape_18_0.png
microgen.shape.surface_functions.honeycomb_gyroid(x: ndarray, y: ndarray, _: ndarray) → ndarray

Honeycomb Gyroid.

\[sin(x) cos(y) + sin(y) + cos(x) = 0\]
_images/microgen.shape_19_1.png
microgen.shape.surface_functions.honeycomb_lidinoid(x: ndarray, y: ndarray, _: ndarray) → ndarray

Honeycomb Lidinoid.

\[1.1 (sin(2 x) cos(y) + sin(2 y) sin(x) + cos(x) sin(y)) - (cos(2 x) cos(2 y) + cos(2 y) + cos(2 x)) = 0\]
_images/microgen.shape_20_0.png
microgen.shape.surface_functions.honeycomb_schoen_iwp(x: ndarray, y: ndarray, _: ndarray) → ndarray

Honneycomb Schoen IWP.

\[cos(x) cos(y) + cos(y) + cos(x) = 0\]
_images/microgen.shape_21_0.png
microgen.shape.surface_functions.honeycomb_schwarz_d(x: ndarray, y: ndarray, _: ndarray) → ndarray

Honneycomb Schwarz D.

\[cos(x) cos(y) + sin(x) sin(y) + sin(x) cos(y) + cos(x) sin(y) = 0\]
_images/microgen.shape_22_0.png
microgen.shape.surface_functions.honeycomb_schwarz_p(x: ndarray, y: ndarray, _: ndarray) → ndarray

Honeycomb Schwarz P.

\[cos(x) + cos(y) = 0\]
_images/microgen.shape_23_0.png
microgen.shape.surface_functions.lidinoid(x: ndarray, y: ndarray, z: ndarray) → ndarray

Lidinoid.

\[0.5 (sin(2 x) cos(y) sin(z) + sin(2 y) cos(z) sin(x) + sin(2 z) cos(x) sin(y)) - 0.5 (cos(2 x) cos(2 y) + cos(2 y) cos(2 z) + cos(2 z) cos(2 x)) + 0.3 = 0\]
_images/microgen.shape_24_0.png
microgen.shape.surface_functions.neovius(x: ndarray, y: ndarray, z: ndarray) → ndarray

Neovius.

\[3 cos(x) + cos(y) + cos(z) + 4 cos(x) cos(y) cos(z) = 0\]
_images/microgen.shape_25_0.png
microgen.shape.surface_functions.pmy(x: ndarray, y: ndarray, z: ndarray) → ndarray

PMY.

\[2 cos(x) cos(y) cos(z) + sin(2 x) sin(y) + sin(x) sin(2 z) + sin(2 y) sin(z) = 0\]
_images/microgen.shape_26_0.png
microgen.shape.surface_functions.schoen_frd(x: ndarray, y: ndarray, z: ndarray) → ndarray

Schoen FRD.

\[4 cos(x) cos(y) cos(z) - (cos(2 x) cos(2 y) + cos(2 y) cos(2 z) + cos(2 z) cos(2 x)) = 0\]
_images/microgen.shape_27_0.png
microgen.shape.surface_functions.schoen_iwp(x: ndarray, y: ndarray, z: ndarray) → ndarray

Schoen IWP.

\[2 (cos(x) cos(y) + cos(y) cos(z) + cos(z) cos(x)) - (cos(2 x) + cos(2 y) + cos(2 z)) = 0\]
_images/microgen.shape_28_0.png
microgen.shape.surface_functions.schwarz_d(x: ndarray, y: ndarray, z: ndarray) → ndarray

Schwarz D.

\[sin(x) sin(y) sin(z) + sin(x) cos(y) cos(z) + cos(x) sin(y) cos(z) + cos(x) cos(y) sin(z) = 0\]
_images/microgen.shape_29_0.png
microgen.shape.surface_functions.schwarz_p(x: ndarray, y: ndarray, z: ndarray) → ndarray

Schwarz P.

\[cos(x) + cos(y) + cos(z) = 0\]
_images/microgen.shape_30_0.png
microgen.shape.surface_functions.split_p(x: ndarray, y: ndarray, z: ndarray) → ndarray

Split P.

\[1.1 (sin(2 x) cos(y) sin(z) + sin(2 y) cos(z) sin(x) + sin(2 z) cos(x) sin(y)) - 0.2 (cos(2 x) cos(2 y) + cos(2 y) cos(2 z) + cos(2 z) cos(2 x)) - 0.4 (cos(2 x) + cos(2 y) + cos(2 z)) = 0\]
_images/microgen.shape_31_0.png