Skip to content
Projects

simgeometry.objects

Package exports for geometric object definitions.

Classes

NameDescription
Aperture2DTwo plates mirrored about a beam axis: a slit, or the 2D cut of a round aperture.
Aperture3DRepresent a three-dimensional aperture embedded in a simulation domain.
CircleRepresent a circular geometry object.
ConeA frustum with radius start_radius at start and end_radius at end.
CuboidRepresent a cuboid geometry object.
CylinderA solid circular cylinder with its axis from start to end.
FourierSurfaceA closed toroidal surface as a Fourier series, with nfp field periods.
FunctionObject2DRepresent an arbitrary 2D geometry object defined by a Boolean function.
FunctionObject3DRepresent an arbitrary 3D geometry object defined by a Boolean function.
HelixA helical wire of round cross-section: the points within wire_radius of a helix.
LineRepresent a line geometry object.
PolygonRepresent a polygon geometry object.
PolylineAn open curve through vertices: a thin plate, wire or grid of zero thickness.
RectangleRepresent a rectangular geometry object.
SlantedTubeA tube from start to end whose end at end is cut by a slanted plane.
SphereRepresent a spherical geometry object.
SurfaceHitsFirst hits of segments with a surface, point-major: (...) and (..., 3).
TorusA solid torus: the points within minor_radius of a circle of major_radius.
TriangleRepresent a triangular geometry object.
TriangleMeshA surface made of triangles: closed (a solid) or open (panels).
TubeA hollow cylinder between inner_radius and outer_radius, from start to end.

Modules

  • aperture2dTwo-dimensional aperture helpers for geometric object definitions.
  • aperture3dThree-dimensional aperture helpers for geometric object definitions.
  • axisymmetricThe common frame of the solids of revolution: Cylinder, Tube, Cone and Torus.
  • circleCircle helpers for geometric object definitions.
  • coneCones and frustums of revolution along any axis.
  • cuboidCuboids, optionally with rounded edges.
  • cylinderSolid cylinders along any axis, optionally with rounded edges.
  • fourier_surfaceToroidal surfaces as Fourier series: a stellarator's plasma boundary or first wall.
  • function_objectFunction-based geometric object definitions.
  • helixHelical wires: the points within a radius of a helix, e.g. the winding of an RF coil.
  • lineLine helpers for geometric object definitions.
  • polygonPolygon helpers for geometric object definitions.
  • polylineOpen polylines: curves of zero thickness, such as thin plates and wires.
  • rectangleRectangles, optionally with rounded corners.
  • slanted_tubeTubes (and rods) along any axis whose far end is cut by a slanted plane.
  • sphereSphere helpers for geometric object definitions.
  • torusSolid tori about any axis.
  • triangleTriangle helpers for geometric object definitions.
  • triangle_meshSurfaces given as triangle meshes: a first wall from CAD, or a sampled surface.
  • tubeHollow cylinders (tubes, ring electrodes) along any axis, optionally rounded.

Aperture2Dclass#

class Aperture2D(axis: int, position: float, vertices: tuple[tuple[float, float], ...], bc: ConfigValue = None, inverted: bool = False)

Bases: Shape2D

Two plates mirrored about a beam axis: a slit, or the 2D cut of a round aperture.

The beam runs along coordinate axis (0 for x, 1 for y), on the centre line where the other coordinate equals position. vertices are the plate profile as (axial, radial) pairs: the coordinate along the beam and the distance from the centre line. One plate is the polygon at position + radial, the other its mirror image at position - radial. slit builds the common rectangular plates.

Its level_set is the signed distance to the plates’ edges, exact while the plates do not touch (every radial coordinate positive).

Numerics

plates

P±={(sk, c±rk)}k,S=P−∪P+P_\pm = \{(s_k,\ c \pm r_k)\}_k, \qquad S = P_- \cup P_+

level set

ϕ(p)=±min⁡edges of P±∣p−a−clip⁡ ⁣((p−a)⋅e∣e∣2,0,1)e∣\phi(p) = \pm \min_{\text{edges of } P_\pm} \left| p - a - \operatorname{clip}\!\left(\tfrac{(p - a)\cdot e}{|e|^2}, 0, 1\right) e \right|

Assumptions:

  • the profile (sk,rk)(s_k, r_k): ss along the beam axis, rr across it from the centre line at cc = position
  • each plate is a Polygon: even-odd rule inside its half-open bounding box
  • ϕ\phi is negative inside a plate and exact while the plates are apart (every rk>0r_k > 0), a bound otherwise

Built from:

  • simgeometry.objects.polygon.Polygon

exact_outlineattributeclass attributeinstance attribute#

exact_outline = True

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

axispropertywritable#

axis: int

Return the beam axis.

level_set_exactproperty#

level_set_exact: bool

Whether the plates are apart, so that the level set is exact.

positionproperty#

position: float

Return the centre line’s coordinate across the beam.

rvecproperty#

rvec: list

Return the radial aperture coordinate vector.

verticespropertywritable#

vertices: tuple[tuple[float, float], ...]

Return the plate profile as (axial, radial) vertices.

zvecproperty#

zvec: list

Return the axial aperture coordinate vector.

containsmethod#

def contains(coords: ndarray) -> bool

Check if the given coordinates are inside one of the plates.

Parameters: coords (list or tuple): Coordinates (x, y).

Returns: bool: True if the point is inside a plate, False otherwise.

contains_pointsmethod#

def contains_points(points: ndarray) -> ndarray

Vectorised contains: a mask of the (2, n) points inside.

slitmethodclassmethod#

def slit(axial_position: float, half_width: float, thickness: float, length: float, *, axis: int = 0, position: float = 0.0, bc: ConfigValue = None, inverted: bool = False) -> Aperture2D

A slit: two rectangular plates with a gap of 2 * half_width between them.

The plates are thickness thick along the beam, centred on axial_position, and extend length outward from the gap.

Inherited from simgeometry.shapes.Shape2D

closedattributeclass attributeinstance attribute#

closed: bool = True

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the shape as filled polygons into ax and return the axes.

Keyword arguments style the polygons (facecolor, alpha, …).

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

copymethod#

def copy()

Return an independent deep copy.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Aperture3Dclass#

class Aperture3D(axis: str, center_coords: tuple, vertices: tuple[tuple[float, float], ...], lower_bound: tuple, upper_bound: tuple, bc: ConfigValue = None, inverted: bool = True)

Bases: Shape3D

Represent a three-dimensional aperture embedded in a simulation domain.

Numerics

radius

r(z)=rk−1+z−zk−1zk−zk−1 (rk−rk−1),zk−1<z≤zkr(z) = r_{k-1} + \frac{z - z_{k-1}}{z_k - z_{k-1}}\,(r_k - r_{k-1}), \qquad z_{k-1} < z \le z_k

opening

open  ⟺  ρ2<rmin⁡2  or  ρ2≤r(z)2,ρ2=∣p⊥−c∣2\text{open} \iff \rho^2 < r_{\min}^2 \;\text{or}\; \rho^2 \le r(z)^2, \qquad \rho^2 = |p_\perp - c|^2

inside

p∈S  ⟺  l≤p<u  and  ¬ open(inverted, the default)p \in S \iff l \le p < u \;\text{and}\; \lnot\,\text{open} \quad (\text{inverted, the default})

Assumptions:

  • the profile of (axial position zkz_k, radius rkr_k) vertices about the axis through center_coords; kk from searchsorted (side left)
  • beyond the first or last vertex the end radius holds
  • the inversion applies before the half-open box test: the solid is the material around the opening within the box only
  • no level set and no analytic crossing: crossings are sampled

axisattributeinstance attribute#

axis = axis

axis_indexattributeinstance attribute#

axis_index = {'x': 0, 'y': 1, 'z': 2}[axis]

center_coordsattributeinstance attribute#

center_coords = xp.array(center_coords, dtype=float)

solid_within_bounding_boxattributeclass attributeinstance attribute#

solid_within_bounding_box = True

verticesattributeinstance attribute#

vertices = xp.array(vertices)

max_radiusproperty#

max_radius: float

Return the largest aperture radius.

min_radiusproperty#

min_radius: float

Return the smallest aperture radius.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the aperture.

Parameters: coords (list or tuple): 3D coordinates.

Returns: bool: True if the coordinates are inside the aperture, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorized contains: a mask of the (3, n) points inside.

copymethod#

def copy() -> Aperture3D

Create a copy of the aperture.

Returns

Aperture3DAperture3D
A new instance of Aperture3D with the same properties.

get_verticesmethod#

def get_vertices(slice_axis: int, slice_position: float) -> ConfigValue

Get the vertices of a slice of the aperture along a given axis.

Parameters: slice_axis (int): Axis along which to slice (0 for x, 1 for y, 2 for z). slice_position (float): Position along the slice_axis where the slice is taken.

vertices (ndarray): Array of vertices defining the slice shape. If the slice does not intersect the aperture, returns an empty array.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the aperture across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

surface_areamethod#

def surface_area() -> None

Declare the aperture surface-area interface.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the aperture by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.

volumemethod#

def volume() -> None

Declare the aperture volume interface.

Inherited from simgeometry.shapes.Shape

has_level_setattributeclass attributeinstance attribute#

has_level_set: bool = False

level_set_exactattributeclass attributeinstance attribute#

level_set_exact: bool = False

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Circleclass#

class Circle(midpoint: BoundsLike, radius: float, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape2D

Represent a circular geometry object.

Its level_set is the exact signed distance |p - midpoint| - radius.

Numerics

inside

p∈S  ⟺  ∣p−c∣2≤r2p \in S \iff |p - c|^2 \le r^2

level set

ϕ(p)=∣p−c∣−r\phi(p) = |p - c| - r

Assumptions:

  • closed: points on the circle are inside
  • ϕ\phi is the exact signed distance, negative inside

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

midpointattributeinstance attribute#

midpoint = list(midpoint)

radiusattributeinstance attribute#

radius = radius

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the circle.

Parameters: coords (list or tuple): Coordinates for each dimension.

Returns: bool: True if the coordinates are inside the circle, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (2, n) points inside.

copymethod#

def copy() -> Circle

Create a copy of the circle.

Returns

CircleCircle
A new instance of Circle with the same midpoint, radius, and boundary conditions.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the circle across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float]) -> None

Translate the xyz by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy) translation vector.
Inherited from simgeometry.shapes.Shape2D

closedattributeclass attributeinstance attribute#

closed: bool = True

exact_outlineattributeclass attributeinstance attribute#

exact_outline: bool = False

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the shape as filled polygons into ax and return the axes.

Keyword arguments style the polygons (facecolor, alpha, …).

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Coneclass#

class Cone(start: BoundsLike, end: BoundsLike, start_radius: float, end_radius: float, bc: ConfigValue = None, inverted: bool = False)

Bases: CappedAxisymmetricShape

A frustum with radius start_radius at start and end_radius at end.

One radius may be zero, which gives a cone with its tip there. The level_set is the exact signed distance.

Example

A cone of base radius 0.5 at z = 0 with its tip at z = 1::

tip = Cone((0, 0, 0), (0, 0, 1), 0.5, 0.0)

Numerics

inside

p∈S  ⟺  ∣s∣≤L,  ρ≤r1+(r2−r1) s+L2Lp \in S \iff |s| \le L,\; \rho \le r_1 + (r_2 - r_1)\,\frac{s + L}{2L}

level set

ϕ=±min⁡(∣(ρ−min⁡(ρ,rcap), ∣s∣−L)∣, ∣(ρ,s)−q∣),q=(r2,L)+clip⁡(τ,0,1) (r1−r2,−2L)\phi = \pm \min\Big(\big|(\rho - \min(\rho, r_\mathrm{cap}),\ |s| - L)\big|,\ \big|(\rho, s) - q\big|\Big), \qquad q = (r_2, L) + \operatorname{clip}(\tau, 0, 1)\,(r_1 - r_2, -2L)

slant

τ=(ρ−r2)(r1−r2)−2L (s−L)(r1−r2)2+4L2\tau = \frac{(\rho - r_2)(r_1 - r_2) - 2L\,(s - L)}{(r_1 - r_2)^2 + 4L^2}

Assumptions:

  • radius r1r_1 at s=−Ls = -L (start), r2r_2 at s=Ls = L (end), one of them may be zero; frame (s,ρ)(s, \rho) of AxisymmetricShape
  • rcapr_\mathrm{cap} is the radius of the nearer cap; the minus sign where the point is on the inner side of the slant and ∣s∣<L|s| < L
  • ϕ\phi is the exact signed distance

References:

Built from:

  • simgeometry.objects.axisymmetric.AxisymmetricShape

end_radiusattributeinstance attribute#

end_radius = float(end_radius)

start_radiusattributeinstance attribute#

start_radius = float(start_radius)

copymethod#

def copy() -> Cone

Create a copy of the cone.

surface_areamethod#

def surface_area() -> float

Calculate the surface area of the frustum, with its end discs.

volumemethod#

def volume() -> float

Calculate the volume of the frustum.

Inherited from simgeometry.objects.axisymmetric.CappedAxisymmetricShape

endproperty#

end: tuple[float, float, float]

The centre of the end face at the end of the axis.

lengthproperty#

length: float

The distance from start to end.

startproperty#

start: tuple[float, float, float]

The centre of the end face at the start of the axis.

Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

axisproperty#

axis: tuple[float, float, float]

The unit vector of the symmetry axis.

midpointproperty#

midpoint: tuple[float, float, float]

The centre of the solid on its axis.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the solid.

Parameters: coords (list or tuple): Coordinates (x, y, z).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the solid across the plane where coordinate axis is position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the solid by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.
Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Cuboidclass#

class Cuboid(midpoint: BoundsLike, side_lengths: BoundsLike, bc: ConfigValue = None, inverted: bool = False, *, fillet: float = 0.0)

Bases: Shape3D

Represent a cuboid geometry object.

fillet rounds the twelve edges and eight corners with that radius, at most half the shortest side, as fillet rounds the edges of a Cylinder. The level_set is the exact signed distance, with or without the fillet.

Example

A 2 x 1 x 0.4 block with edges rounded by 0.05::

block = Cuboid((0, 0, 0), (2.0, 1.0, 0.4), fillet=0.05)

Numerics

inside

p∈S  ⟺  l≤p≤u(f=0),p∈S  ⟺  ϕ(p)≤0(f>0)p \in S \iff l \le p \le u \quad (f = 0), \qquad p \in S \iff \phi(p) \le 0 \quad (f > 0)

level set

ϕ(p)=∣max⁡(d,0)∣+min⁡(max⁡kdk,0)−f,d=∣p−c∣−(h−f)\phi(p) = \big|\max(d, 0)\big| + \min\big(\max_k d_k, 0\big) - f, \qquad d = |p - c| - (h - f)

Assumptions:

  • axis-aligned, centre cc, half sides hh; ∣⋅∣|\cdot| and max⁡(⋅,0)\max(\cdot, 0) of dd componentwise
  • the fillet f≤min⁡khkf \le \min_k h_k rounds the edges and corners: the box shrunk by ff, widened by a ball of radius ff
  • closed: points on the faces are inside
  • ϕ\phi is the exact signed distance, negative inside

References:

filletattributeinstance attribute#

fillet = float(fillet)

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

midpointattributeinstance attribute#

midpoint = xp.array(midpoint)

side_lengthsattributeinstance attribute#

side_lengths = xp.array(side_lengths)

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the cuboid.

Parameters: coords (list or tuple): Coordinates for each dimension.

Returns: bool: True if all coordinates are inside the cuboid, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

copymethod#

def copy() -> Cuboid

Create a copy of the cuboid.

Returns

CuboidCuboid
A new instance of Cuboid with the same midpoint, side lengths, and boundary conditions.

get_verticesmethod#

def get_vertices(slice_axis: int, slice_position: float) -> ConfigValue

Get the corner vertices of a slice of the cuboid along a given axis.

Parameters

NameTypeDescription
slice_axisintAxis along which to slice (0 for x, 1 for y, 2 for z).
slice_indexfloatPosition along the slice_axis where the slice is taken.

Returns

verticeslist
List of corner vertices defining the slice polygon;
ConfigValue
with a fillet, the vertices of the rounded rectangle of the slice.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the cuboid across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

surface_areamethod#

def surface_area() -> float

Calculate the surface area of the cuboid, with its rounded edges.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the cuboid by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.

volumemethod#

def volume() -> float

Calculate the volume of the cuboid, less the rounded edges.

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Cylinderclass#

class Cylinder(start: BoundsLike, end: BoundsLike, radius: float, bc: ConfigValue = None, inverted: bool = False, *, fillet: float = 0.0)

Bases: CappedAxisymmetricShape

A solid circular cylinder with its axis from start to end.

fillet rounds the two circular edges with that radius (at most the radius and half the length). The level_set is the exact signed distance, with or without the fillet.

Example

A rod of radius 0.1 along z, from z = -1 to z = 1::

rod = Cylinder((0, 0, -1), (0, 0, 1), 0.1)

Numerics

inside

p∈S  ⟺  ∣s∣≤L,  ρ2≤R2(f=0),p∈S  ⟺  ϕ(p)≤0(f>0)p \in S \iff |s| \le L,\; \rho^2 \le R^2 \quad (f = 0), \qquad p \in S \iff \phi(p) \le 0 \quad (f > 0)

level set

ϕ=ϕrect(ρ,s; R−f,L−f)−f,ϕrect(x,y;hx,hy)=∣max⁡(d,0)∣+min⁡(max⁡(dx,dy),0),d=(∣x∣−hx,∣y∣−hy)\phi = \phi_\mathrm{rect}(\rho, s;\ R - f, L - f) - f, \qquad \phi_\mathrm{rect}(x, y; h_x, h_y) = \big|\max(d, 0)\big| + \min(\max(d_x, d_y), 0), \quad d = (|x| - h_x, |y| - h_y)

Assumptions:

  • half length LL, radius RR, in the frame (s,ρ)(s, \rho) of AxisymmetricShape
  • the fillet f≤min⁡(R,L)f \le \min(R, L) rounds the two circular edges
  • ϕ\phi is the exact signed distance, negative inside

Built from:

  • simgeometry.objects.axisymmetric.AxisymmetricShape

filletattributeinstance attribute#

fillet = float(fillet)

radiusattributeinstance attribute#

radius = float(radius)

copymethod#

def copy() -> Cylinder

Create a copy of the cylinder.

surface_areamethod#

def surface_area() -> float

Calculate the surface area of the cylinder, with its rounded edges.

volumemethod#

def volume() -> float

Calculate the volume of the cylinder, less the rounded edges.

Inherited from simgeometry.objects.axisymmetric.CappedAxisymmetricShape

endproperty#

end: tuple[float, float, float]

The centre of the end face at the end of the axis.

lengthproperty#

length: float

The distance from start to end.

startproperty#

start: tuple[float, float, float]

The centre of the end face at the start of the axis.

Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

axisproperty#

axis: tuple[float, float, float]

The unit vector of the symmetry axis.

midpointproperty#

midpoint: tuple[float, float, float]

The centre of the solid on its axis.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the solid.

Parameters: coords (list or tuple): Coordinates (x, y, z).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the solid across the plane where coordinate axis is position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the solid by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.
Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

FourierSurfaceclass#

class FourierSurface(r_cos: Array, z_sin: Array, n_field_periods: int, *, r_sin: Array | None = None, z_cos: Array | None = None, resolution: tuple[int, int] = (64, 32), refine: bool = True, cells: int | tuple[int, int, int] | None = None, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape3D

A closed toroidal surface as a Fourier series, with nfp field periods.

Example

A wall 10 cm outside a ConStellaration plasma boundary, and where beam lines meet it::

plasma = FourierSurface.from_boundary(json.loads(row["boundary.json"]))
wall = plasma.offset(0.10)
hits = wall.first_hit(starts, ends) # (..., 3) arrays

Numerics

surface

X(θ,φ)=(Rcos⁡φ,Rsin⁡φ,Z),R=∑m,nrmnccos⁡(mθ−Nfpnφ)+rmnssin⁡(⋅),Z=∑m,nzmnssin⁡(mθ−Nfpnφ)+zmnccos⁡(⋅)X(\theta, \varphi) = (R\cos\varphi, R\sin\varphi, Z), \quad R = \sum_{m,n} r^c_{mn}\cos(m\theta - N_\mathrm{fp} n\varphi) + r^s_{mn}\sin(\cdot), \quad Z = \sum_{m,n} z^s_{mn}\sin(m\theta - N_\mathrm{fp} n\varphi) + z^c_{mn}\cos(\cdot)

normal

n=σ Xθ×Xφ∣Xθ×Xφ∣,σ=sign⁡∮X⋅(Xθ×Xφ) dθ dφn = \sigma\,\frac{X_\theta \times X_\varphi}{|X_\theta \times X_\varphi|}, \qquad \sigma = \operatorname{sign} \oint X \cdot (X_\theta \times X_\varphi)\, d\theta\, d\varphi

hit

a+td=X(θ,φ):(d−Xθ−Xφ)δ=−(a+td−X),(t,θ,φ)+=δa + t d = X(\theta, \varphi): \quad \begin{pmatrix} d & -X_\theta & -X_\varphi \end{pmatrix} \delta = -(a + t d - X), \quad (t, \theta, \varphi) \mathrel{+}= \delta

closest

min⁡θ,φ12∣X−p∣2:Hδ=−((X−p)⋅Xθ,(X−p)⋅Xφ),Hij=Xi⋅Xj+(X−p)⋅Xij\min_{\theta, \varphi} \tfrac12 |X - p|^2: \quad H \delta = -\bigl((X - p)\cdot X_\theta, (X - p)\cdot X_\varphi\bigr), \quad H_{ij} = X_i \cdot X_j + (X - p)\cdot X_{ij}

offset

X′=X+δ n,(R′,Z′) at φ′=φj refitted by least squaresX' = X + \delta\, n, \qquad (R', Z') \text{ at } \varphi' = \varphi_j \text{ refitted by least squares}

volume

V=13∮X⋅n dA,A=∮∣Xθ×Xφ∣ dθ dφ(trapezoidal rule)V = \tfrac13 \oint X \cdot n\, dA, \qquad A = \oint |X_\theta \times X_\varphi|\, d\theta\, d\varphi \quad \text{(trapezoidal rule)}

Order of accuracy: 2.

Assumptions:

  • VMEC’s and ConStellaration’s SurfaceRZFourier: m=0…Mm = 0 \dots M, n=−N…Nn = -N \dots N, φ\varphi the cylindrical angle; each cross-section at constant φ\varphi a simple closed curve
  • membership and the hit search on the triangulation of resolution (nθ,nφ)(n_\theta, n_\varphi) points per poloidal turn and per field period, exact for the triangles (TriangleMesh)
  • refine: hits moved onto the surface by Newton steps on (t,θ,φ)(t, \theta, \varphi) from the triangle’s angles, to 10−1210^{-12} of the surface’s size; kept on the triangle if a step fails or leaves (10−12,1](10^{-12}, 1]
  • whether a segment hits is decided by the triangles: grazing segments within triangulation_error of the surface may differ from the exact surface
  • offset: the normal offset is a surface at distance ∣δ∣|\delta| while ∣δ∣|\delta| is below the smallest radius of curvature of the concave parts; refitted with 2M2M poloidal and 2N2N toroidal modes by default
  • the order is that of the hit fractions from the triangles alone in the angular spacing

Built from:

  • simgeometry.objects.triangle_mesh.TriangleMesh

nfpattributeinstance attribute#

nfp = int(n_field_periods)

offset_residualattributeinstance attribute#

offset_residual: float | None = None

r_cosattributeinstance attribute#

r_cos = np.asarray(r_cos, dtype=float)

r_sinattributeinstance attribute#

r_sin = None if r_sin is None else np.asarray(r_sin, dtype=float)

refineattributeinstance attribute#

refine = bool(refine)

resolutionattributeinstance attribute#

resolution = (n_theta, n_phi)

z_cosattributeinstance attribute#

z_cos = None if z_cos is None else np.asarray(z_cos, dtype=float)

z_sinattributeinstance attribute#

z_sin = np.asarray(z_sin, dtype=float)

meshproperty#

mesh: TriangleMesh

The triangulation at resolution, which answers membership and hit searches.

n_poloidalproperty#

n_poloidal: int

The largest poloidal mode number M.

n_toroidalproperty#

n_toroidal: int

The largest toroidal mode number N.

stellarator_symmetricproperty#

stellarator_symmetric: bool

Whether the surface has only r_cos and z_sin terms.

triangulation_errorproperty#

triangulation_error: float

The largest distance between the faces and the surface at the same angles.

Measured at the centroids and the midpoints of the edges of all faces.

An estimate of how far the triangles deviate from the surface (second order in the spacing); membership differs from the exact surface only within about this distance of it.

closestmethod#

def closest(points: Array) -> tuple[np.ndarray, np.ndarray, np.ndarray]

Return the angles theta, phi and the distance of the closest points.

For points (..., 3): Newton steps on the squared distance from the nearest vertex of the triangulation (Gauss–Newton where the Hessian is not positive). The cost grows with the number of vertices; it is meant for checks, not for every particle of a run.

containsmethod#

def contains(coords: tuple[float, float, float]) -> bool

Return whether the point is inside (see contains_points).

contains_pointsmethod#

def contains_points(points: Array) -> Array

Return a mask of the (3, n) points inside the surface’s triangulation.

Exact for the triangles; within triangulation_error of the surface the result may differ from the exact surface’s.

copymethod#

def copy() -> FourierSurface

Create a copy of the surface.

first_hitmethod#

def first_hit(starts: Array, ends: Array) -> SurfaceHits

Return the first hit of each segment starts[...] -> ends[...], (..., 3).

Point-major SurfaceHits with the face of the triangulation, the angles theta and phi of the hit and whether it was refined onto the exact surface. A segment starting at a refined hit (on the surface) finds the next one, so first_hit(hits.point, ends) follows a line through the surface.

from_boundarymethodclassmethod#

def from_boundary(boundary: Any, **kwargs: Any) -> FourierSurface

Return the surface of ConStellaration’s boundary.json.

boundary is the dict, its JSON string, or an object with the attributes r_cos, z_sin, r_sin, z_cos and n_field_periods (such as constellaration’s SurfaceRZFourier). Other arguments go to FourierSurface.

inside_atmethod#

def inside_at(points: Array) -> Array

Return whether the points (..., 3) are inside, as (...).

normalmethod#

def normal(theta: Array, phi: Array) -> np.ndarray

Return the outward unit normals (..., 3) at broadcast angles.

offsetmethod#

def offset(distance: float, *, tolerance: float | None = None, poloidal_modes: int | None = None, toroidal_modes: int | None = None, **kwargs: Any) -> FourierSurface

Return the surface moved by distance along its outward normal.

Every point of a fine grid is moved, X + distance n; at the grid’s toroidal angles the moved surface’s R and Z are found by fixed-point steps on the toroidal angle of the source point and transformed by an FFT. The series is cut at the fewest modes whose largest misfit on the grid is below tolerance (default: a hundredth of |distance|), with up to MAX_OFFSET_MODES poloidal and half as many toroidal modes, or at poloidal_modes and toroidal_modes if given. The misfit is kept as offset_residual; a warning says when the tolerance is not reached.

A negative distance moves inward. The result is the surface at the given distance as long as |distance| is below the smallest radius of curvature of the concave parts (closest checks it). Other arguments go to FourierSurface (default: this surface’s resolution and refine).

pointmethod#

def point(theta: Array, phi: Array) -> np.ndarray

Return the Cartesian points (..., 3) at broadcast angles.

rzmethod#

def rz(theta: Array, phi: Array) -> tuple[np.ndarray, np.ndarray]

Return R and Z at broadcast angles theta and phi.

surface_areamethod#

def surface_area() -> float

Return the area of the surface (trapezoidal rule on the exact surface).

to_boundarymethod#

def to_boundary() -> dict

Return the coefficients in ConStellaration’s boundary.json layout.

to_meshmethod#

def to_mesh(**kwargs: Any)

Return the triangulation as a SurfaceMesh (resolution and bounds are ignored).

triangulatemethod#

def triangulate(n_theta: int, n_phi: int, *, cells=None) -> tuple[TriangleMesh, np.ndarray]

Return a closed mesh of the surface and the angles of its faces’ corners.

The vertices are a grid of n_theta poloidal angles by n_phi toroidal angles per field period, each grid quad two triangles oriented outward. The angles are (F, 3, 2), (theta, phi) per corner, continuous within a face (not wrapped to [0, 2 pi)).

volumemethod#

def volume() -> float

Return the enclosed volume (trapezoidal rule on the exact surface).

Inherited from simgeometry.shapes.Shape

has_level_setattributeclass attributeinstance attribute#

has_level_set: bool = False

level_set_exactattributeclass attributeinstance attribute#

level_set_exact: bool = False

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

FunctionObject2Dclass#

class FunctionObject2D(func: Callable[[Array], bool], lower_bound: BoundsLike, upper_bound: BoundsLike, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape2D

Represent an arbitrary 2D geometry object defined by a Boolean function.

The object interior is the set of all points for which func(coords) returns True. A bounding box must be supplied by the caller because it cannot in general be derived from an arbitrary function.

Example

Create a ring (annulus) with inner radius 1 and outer radius 2::

def ring(coords):
x, y = coords
r2 = x**2 + y**2
return 1.0**2 <= r2 <= 2.0**2
obj = FunctionObject2D(
func=ring,
lower_bound=(-2.0, -2.0),
upper_bound=(2.0, 2.0),
)

funcproperty#

func: Callable[[Array], bool]

Return the Boolean membership function.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the object.

Parameters

coords: (x, y) coordinates to test.

Returns

bool True if func(coords) is truthy (falsy when inverted).

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the object as a sampled mask into ax and return the axes.

resolution (samples per axis) and bounds set the sampling of the mask, other keyword arguments style the image. With an inspection option (x, y, z, grid, nodes, normals) this is Shape2D.plot.

Inherited from simgeometry.shapes.Shape2D

closedattributeclass attributeinstance attribute#

closed: bool = True

exact_outlineattributeclass attributeinstance attribute#

exact_outline: bool = False

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}
Inherited from simgeometry.shapes.Shape

has_level_setattributeclass attributeinstance attribute#

has_level_set: bool = False

level_set_exactattributeclass attributeinstance attribute#

level_set_exact: bool = False

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Return a mask of the (ndim, n) points inside the shape.

The default calls contains point by point; shapes override it with a vectorised test.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

copymethod#

def copy()

Return an independent deep copy.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

FunctionObject3Dclass#

class FunctionObject3D(func: Callable[[Array], bool], lower_bound: BoundsLike, upper_bound: BoundsLike, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape3D

Represent an arbitrary 3D geometry object defined by a Boolean function.

The object interior is the set of all points for which func(coords) returns True. A bounding box must be supplied by the caller because it cannot in general be derived from an arbitrary function.

A function object has no level set, so crossings and distances are found by sampling its membership. Prefer a primitive where one fits (a torus is Torus, a ring electrode Tube).

Example

Create a rounded cube, the superellipsoid x**4 + y**4 + z**4 <= 1::

def rounded_cube(coords):
x, y, z = coords
return x**4 + y**4 + z**4 <= 1.0
obj = FunctionObject3D(
func=rounded_cube,
lower_bound=(-1.0, -1.0, -1.0),
upper_bound=(1.0, 1.0, 1.0),
)

funcproperty#

func: Callable[[Array], bool]

Return the Boolean membership function.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the object.

Parameters

coords: (x, y, z) coordinates to test.

Returns

bool True if func(coords) is truthy (falsy when inverted).

get_verticesmethod#

def get_vertices(slice_axis: int = 0, slice_position: float | None = None) -> tuple

Return an empty array; vertices cannot be derived from an arbitrary function.

surface_areamethod#

def surface_area() -> float

Surface area cannot be analytically derived from an arbitrary function.

volumemethod#

def volume() -> float

Volume cannot be analytically derived from an arbitrary function.

Inherited from simgeometry.shapes.Shape

has_level_setattributeclass attributeinstance attribute#

has_level_set: bool = False

level_set_exactattributeclass attributeinstance attribute#

level_set_exact: bool = False

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Return a mask of the (ndim, n) points inside the shape.

The default calls contains point by point; shapes override it with a vectorised test.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

copymethod#

def copy()

Return an independent deep copy.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Helixclass#

class Helix(start: BoundsLike, radius: float, pitch: float, turns: float, wire_radius: float, axis: BoundsLike = (0.0, 0.0, 1.0), start_direction: BoundsLike | None = None, left_handed: bool = False, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape3D

A helical wire of round cross-section: the points within wire_radius of a helix.

The centreline winds turns times around axis at radius, advancing pitch along the axis per turn, from its start point at start + radius * u (u the unit vector normal to the axis in the direction of start_direction, by default the one closest to x) to its end pitch * turns further along the axis. Right-handed by default (counter- clockwise seen from the end the axis points to); left_handed reverses it. The wire’s ends are hemispherical caps. The level_set is the signed distance to the centreline minus the wire’s radius, found by Newton steps on the squared distance along the centreline, within a wire radius of the wire; farther away it is a lower bound (level_set_exact is False).

Example

The six windings of an RF coil, radius 0.14 m, 2 cm pitch, a copper tube of 6 mm outer diameter, along z from z = 0.02::

coil = Helix((0, 0, 0.02), 0.14, 0.02, 6, 0.003)

Numerics

centreline

c(t)=p0+R (cos⁡t u+sin⁡t v)+p t2π a,0≤t≤2πN\mathbf c(t) = \mathbf p_0 + R\,(\cos t\,\mathbf u + \sin t\,\mathbf v) + \frac{p\,t}{2\pi}\,\mathbf a, \qquad 0 \le t \le 2\pi N

level set

ϕ(x)=min⁡0≤t≤2πN∣x−c(t)∣−rw\phi(\mathbf x) = \min_{0 \le t \le 2\pi N} |\mathbf x - \mathbf c(t)| - r_w

descent

t←t−f′(t)f′′(t) or 2ρR+2b2,f(t)=ρ2+R2−2ρRcos⁡(t−φ)+(s−bt)2,b=p2πt \leftarrow t - \frac{f'(t)}{f''(t) \text{ or } 2\rho R + 2b^2}, \qquad f(t) = \rho^2 + R^2 - 2\rho R\cos(t - \varphi) + (s - b t)^2, \quad b = \frac{p}{2\pi}

bound

∣x−c(t)∣≥(ρ−R)2+max⁡(−s,s−pN,0)2|\mathbf x - \mathbf c(t)| \ge \sqrt{(\rho - R)^2 + \max(-s, s - pN, 0)^2}

Assumptions:

  • a\mathbf a the unit axis, u\mathbf u the direction of the start point from the axis, v=±a×u\mathbf v = \pm\mathbf a\times\mathbf u (right- or left-handed); (s,ρ,φ)(s, \rho, \varphi) the point’s cylindrical coordinates in that frame
  • the wire’s ends are hemispheres (the points within rwr_w of the end points of the centreline)
  • within 2rw2 r_w of the cylinder the centreline lies on: the minimum over tt from four starts, the two ends and the linearised minima of the two turns around s/bs / b, by six Newton steps (descent steps on the majorant f′′≤2ρR+2b2f'' \le 2\rho R + 2b^2 where f′′f'' is not clearly positive), clipped to [0,2πN][0, 2\pi N]; exact there (tested against dense sampling)
  • farther away ϕ\phi is the bound (the distance from the cylinder, minus rwr_w): a level set that never exceeds the distance

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = False

pitchattributeinstance attribute#

pitch = float(pitch)

radiusattributeinstance attribute#

radius = float(radius)

turnsattributeinstance attribute#

turns = float(turns)

wire_radiusattributeinstance attribute#

wire_radius = float(wire_radius)

axisproperty#

axis: tuple[float, float, float]

The unit vector the helix advances along.

left_handedproperty#

left_handed: bool

Whether the helix winds clockwise seen from the end the axis points to.

lengthproperty#

length: float

The axial length of the centreline, pitch * turns.

startproperty#

start: tuple[float, float, float]

The point on the axis level with the wire’s start.

start_directionproperty#

start_direction: tuple[float, float, float]

The unit vector from the axis to the start point.

wire_lengthproperty#

wire_length: float

The length of the centreline, turns * sqrt((2 pi radius)^2 + pitch^2).

centrelinemethod#

def centreline(t: Array) -> Array

The points (3, n) of the centreline at the angles t (0 to 2 pi N).

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the wire.

Parameters: coords (list or tuple): Coordinates (x, y, z).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

copymethod#

def copy() -> Helix

Create a copy of the helix.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the helix across the plane where coordinate axis is position.

A mirror image of a right-handed helix is left-handed.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

surface_areamethod#

def surface_area() -> float

The surface area: the swept circle and the two hemispheres (no overlap).

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the helix by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.

volumemethod#

def volume() -> float

The volume: the swept disc along the centreline and the two hemispheres.

Exact (Pappus for a curve) as long as the wire does not overlap itself (pitch >= 2 * wire_radius and wire_radius below the radius of curvature).

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Lineclass#

class Line(midpoint: BoundsLike, side_lengths: BoundsLike, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape1D

Represent a line geometry object.

Its level_set is the exact signed distance to the interval.

Numerics

inside

x∈S  ⟺  l≤x≤ux \in S \iff l \le x \le u

level set

ϕ(x)=∣x−l+u2∣−u−l2\phi(x) = \left|x - \tfrac{l + u}{2}\right| - \tfrac{u - l}{2}

Assumptions:

  • closed: both end points are inside
  • ϕ\phi is the exact signed distance, negative inside

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

midpointattributeinstance attribute#

midpoint = xp.array(midpoint)

side_lengthsattributeinstance attribute#

side_lengths = xp.array(side_lengths)

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the line.

Parameters: coords (list or tuple): Coordinates for each dimension.

Returns: bool: True if the coordinates are inside the line, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (1, n) points inside.

copymethod#

def copy() -> Line

Create a copy of the line.

Returns

LineLine
A new instance of Line with the same midpoint, side lengths, and boundary conditions.

get_verticesmethod#

def get_vertices() -> ConfigValue

Return the vertices that define the object.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the line across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float]) -> None

Translate the line by the given offset.

Parameters

NameTypeDescription
offsettuple(dx,) translation vector.
Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Polygonclass#

class Polygon(vertices: ndarray, bc: float | None = None, inverted: bool = False)

Bases: Shape2D

Represent a polygon geometry object.

Its level_set is the exact signed distance: the distance to the nearest edge, negative where contains_points is true. It costs one pass per edge.

Numerics

inside

toggle at edge vjvi  ⟺  (yi>y)≠(yj>y)  and  x<(xj−xi)(y−yi)(yj−yi)+10−16+xi\text{toggle at edge } v_j v_i \iff (y_i > y) \ne (y_j > y) \;\text{and}\; x < \frac{(x_j - x_i)(y - y_i)}{(y_j - y_i) + 10^{-16}} + x_i

level set

ϕ(p)=±min⁡edges∣p−a−clip⁡ ⁣((p−a)⋅e∣e∣2,0,1)e∣,e=b−a\phi(p) = \pm \min_\text{edges} \left| p - a - \operatorname{clip}\!\left(\tfrac{(p - a)\cdot e}{|e|^2}, 0, 1\right) e \right|, \qquad e = b - a

Assumptions:

  • the even-odd (crossing-number) rule along a ray towards +x+x, not a winding number; vjv_j is the vertex before viv_i, the closing edge implied
  • half-open in yy, so a vertex on the ray is counted once; 10−1610^{-16} guards horizontal edges
  • inside also needs the half-open bounding box l≤p<ul \le p < u; the compiled kernel contains_polygon_2d runs the test
  • ϕ\phi: the distance to the nearest edge, negative where contains_points is true; exact for a simple polygon

References:

  • W. R. Franklin, PNPOLY - Point Inclusion in Polygon Test
  • M. Shimrat, Algorithm 112: Position of point relative to polygon, Commun. ACM 5, 434 (1962)
  • Quílez, 2D distance functions

exact_outlineattributeclass attributeinstance attribute#

exact_outline = True

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

verticespropertywritable#

vertices: ndarray

Return object vertices.

containsmethod#

def contains(coords: ndarray) -> bool

Check if the given coordinates are inside the (possibly inverted) polygon.

Parameters: coords (list or tuple): Coordinates (x, y).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: ndarray) -> ndarray

Vectorised contains: a mask of the (2, n) points inside.

copymethod#

def copy() -> Polygon

Create a copy of the polygon.

Returns

PolygonPolygon
A new instance of Polygon with the same vertices and boundary conditions.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the polygon across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis to mirror across (0 for x-axis, 1 for y-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float]) -> None

Translate the polygon by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy) translation vector.
Inherited from simgeometry.shapes.Shape2D

closedattributeclass attributeinstance attribute#

closed: bool = True

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the shape as filled polygons into ax and return the axes.

Keyword arguments style the polygons (facecolor, alpha, …).

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Polylineclass#

class Polyline(vertices: ndarray, bc: ConfigValue = None)

Bases: Shape2D

An open curve through vertices: a thin plate, wire or grid of zero thickness.

It encloses no area, so contains is always False and it cannot be inverted or combined in Boolean shapes. Its geometry is its outline, an open polyline from the first vertex to the last (closed is False), which boundary_panels and crossings() use directly.

closedattributeclass attributeinstance attribute#

closed = False

exact_outlineattributeclass attributeinstance attribute#

exact_outline = True

lengthproperty#

length: float

The length of the curve.

verticesproperty#

vertices: ndarray

The (n, 2) vertices, one row per point, as given.

containsmethod#

def contains(coords: tuple[float, float]) -> bool

Always False: a curve encloses no area.

contains_pointsmethod#

def contains_points(points: ndarray) -> ndarray

An all-False mask of the (2, n) points: a curve encloses no area.

Inherited from simgeometry.shapes.Shape2D

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the shape as filled polygons into ax and return the axes.

Keyword arguments style the polygons (facecolor, alpha, …).

Inherited from simgeometry.shapes.Shape

has_level_setattributeclass attributeinstance attribute#

has_level_set: bool = False

level_set_exactattributeclass attributeinstance attribute#

level_set_exact: bool = False

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

copymethod#

def copy()

Return an independent deep copy.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Rectangleclass#

class Rectangle(midpoint: tuple | list, side_lengths: tuple, bc: ConfigValue = None, inverted: bool = False, *, fillet: float = 0.0)

Bases: Shape2D

Represent a rectangular geometry object.

fillet rounds the four corners with that radius, at most half the shorter side; at half the shorter side the rectangle is a stadium (a circle for a square). Rounded corners keep the surface field of an electrode bounded. The level_set is the exact signed distance, with or without the fillet.

Example

A plate 2 wide and 0.4 thick with rounded corners, and a stadium::

plate = Rectangle((0, 0), (2.0, 0.4), fillet=0.05)
stadium = Rectangle((0, 0), (2.0, 0.4), fillet=0.2)

Numerics

inside

p∈S  ⟺  l≤p<u(f=0),p∈S  ⟺  ϕ(p)≤0(f>0)p \in S \iff l \le p < u \quad (f = 0), \qquad p \in S \iff \phi(p) \le 0 \quad (f > 0)

level set

ϕ(p)=∣max⁡(d,0)∣+min⁡(max⁡kdk,0)−f,d=∣p−c∣−(h−f)\phi(p) = \big|\max(d, 0)\big| + \min\big(\max_k d_k, 0\big) - f, \qquad d = |p - c| - (h - f)

Assumptions:

  • axis-aligned, centre cc, half sides hh; ∣⋅∣|\cdot| and max⁡(⋅,0)\max(\cdot, 0) of dd componentwise
  • the fillet f≤min⁡khkf \le \min_k h_k rounds the corners: the box shrunk by ff, widened by a disc of radius ff
  • without a fillet the inside test is the half-open box of BoundingBox.contains
  • ϕ\phi is the exact signed distance, negative inside

References:

exact_outlineattributeclass attributeinstance attribute#

exact_outline = self.fillet == 0

filletattributeinstance attribute#

fillet = float(fillet)

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

midpointattributeinstance attribute#

midpoint = list(midpoint)

side_lengthsattributeinstance attribute#

side_lengths = side_lengths

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the rectangle.

Parameters: coords (list or tuple): Coordinates for each dimension.

Returns: bool: True if the coordinates are inside the rectangle, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (2, n) points inside.

copymethod#

def copy() -> Rectangle

Create a copy of the rectangle.

Returns

RectangleRectangle
A new instance of Rectangle with the same midpoint, side lengths, and boundary conditions.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the rectangle across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float]) -> None

Translate the xyz by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy) translation vector.
Inherited from simgeometry.shapes.Shape2D

closedattributeclass attributeinstance attribute#

closed: bool = True

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the shape as filled polygons into ax and return the axes.

Keyword arguments style the polygons (facecolor, alpha, …).

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

SlantedTubeclass#

class SlantedTube(start: BoundsLike, end: BoundsLike, inner_radius: float, outer_radius: float, cut_normal: BoundsLike, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape3D

A tube from start to end whose end at end is cut by a slanted plane.

The wall lies between inner_radius and outer_radius about the axis from start to end; inner_radius = 0 gives a solid rod. The end at start is the flat face normal to the axis. The end at end is the plane through end with the outward normal cut_normal, tilted from the axis by cut_angle, like the mouth of an oven nozzle cut at 45°. length is measured along the axis to the centre of the cut, and the cut may not reach the start face (outer_radius * tan(cut_angle) < length).

The level_set is the larger of the signed distance to the tube without the cut and to the cut plane: exact on the faces and inside away from the cut’s rim, a bound elsewhere (level_set_exact is False). crossings are analytic.

Example

A duct along z, 0.1 long, bore radius 0.01, wall 2 mm, cut at 45° so that its mouth faces down (-y)::

c = np.cos(np.pi / 4)
nozzle = SlantedTube((0, 0, 0), (0, 0, 0.1), 0.01, 0.012, (0, -c, c))

Numerics

frame

w=p−pstart,s=w⋅a,ρ=∣w−s a∣,η=w⋅n−L (n⋅a)w = p - p_\mathrm{start}, \qquad s = w\cdot a, \qquad \rho = |w - s\,a|, \qquad \eta = w\cdot n - L\,(n\cdot a)

inside

p∈S  ⟺  s≥0,  η≤0,  ri≤ρ≤rop \in S \iff s \ge 0,\; \eta \le 0,\; r_i \le \rho \le r_o

level set

ϕ=max⁡(ϕtube,η),ϕtube=∣(max⁡(ϱ,0),max⁡(−s,0))∣+min⁡(max⁡(ϱ,−s),0),ϱ=max⁡(ri−ρ,ρ−ro)\phi = \max(\phi_\mathrm{tube}, \eta), \qquad \phi_\mathrm{tube} = \big|(\max(\varrho, 0), \max(-s, 0))\big| + \min(\max(\varrho, -s), 0), \qquad \varrho = \max(r_i - \rho, \rho - r_o)

Assumptions:

  • unit axis aa from start, length LL to the centre of the cut; cut plane through end with unit outward normal nn, n⋅a>0n\cdot a > 0
  • the cut misses the start face: rotan⁡θ<Lr_o \tan\theta < L; a rod (ri=0r_i = 0) has ϱ=ρ−ro\varrho = \rho - r_o
  • ϕ\phi, the larger of the distances to the half-infinite tube and to the cut plane, is exact away from the rim of the cut and a bound near it

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

inner_radiusattributeinstance attribute#

inner_radius = float(inner_radius)

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = False

outer_radiusattributeinstance attribute#

outer_radius = float(outer_radius)

axisproperty#

axis: tuple[float, float, float]

The unit vector from start to end.

cut_angleproperty#

cut_angle: float

The angle between the cut plane and the cross-section, in degrees.

cut_normalproperty#

cut_normal: tuple[float, float, float]

The unit outward normal of the cut plane.

endproperty#

end: tuple[float, float, float]

The centre of the slanted cut, on the axis.

lengthproperty#

length: float

The distance from start to end along the axis.

startproperty#

start: tuple[float, float, float]

The centre of the flat end face.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the slanted tube.

Parameters: coords (list or tuple): Coordinates (x, y, z).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

copymethod#

def copy() -> SlantedTube

Create a copy of the slanted tube.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the slanted tube across the plane where coordinate axis is position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

surface_areamethod#

def surface_area() -> float

Calculate the surface area: both walls, the flat end and the elliptic cut.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the slanted tube by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.

volumemethod#

def volume() -> float

Calculate the volume: a cut through the axis point leaves that of a straight tube.

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Sphereclass#

class Sphere(midpoint: list | tuple, radius: float, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape3D

Represent a spherical geometry object.

Its level_set is the exact signed distance |p - midpoint| - radius.

Numerics

inside

p∈S  ⟺  ∣p−c∣2≤r2p \in S \iff |p - c|^2 \le r^2

level set

ϕ(p)=∣p−c∣−r\phi(p) = |p - c| - r

Assumptions:

  • closed: points on the sphere are inside
  • ϕ\phi is the exact signed distance, negative inside

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

midpointattributeinstance attribute#

midpoint = list(midpoint)

radiusattributeinstance attribute#

radius = radius

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the sphere.

Parameters: coords (list or tuple): Coordinates for each dimension.

Returns: bool: True if the coordinates are inside the sphere, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

copymethod#

def copy() -> Sphere

Create a copy of the sphere.

Returns

SphereSphere
A new instance of Sphere with the same midpoint, radius, and boundary conditions.

get_verticesmethod#

def get_vertices(slice_axis: int, slice_position: float) -> ConfigValue

Get the vertices of a slice of the sphere along a given axis.

Parameters: slice_axis (int): Axis along which to slice (0 for x, 1 for y, 2 for z). slice_position (float): Position along the slice_axis where the slice is taken.

vertices (ndarray): Array of vertices defining the slice circle. If the slice does not intersect the sphere, returns an empty array.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the sphere across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

surface_areamethod#

def surface_area() -> float

Calculate the surface area of the sphere.

translatemethod#

def translate(offset: tuple[float, float]) -> None

Translate the xyz by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy) translation vector.

volumemethod#

def volume() -> float

Calculate the volume of the sphere.

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

SurfaceHitsclassdataclass#

class SurfaceHits(hit: Any, fraction: Any, distance: Any, point: Any, normal: Any, face: Any, theta: Any = None, phi: Any = None, refined: Any = None)

First hits of segments with a surface, point-major: (...) and (..., 3).

hit, fraction (of the segment, in (0, 1]), distance (from the start), face (the triangle hit, -1 for none) and, for a FourierSurface, theta and phi (the surface’s angles at the hit) have the segments’ shape (...); point and normal (unit, out of the region where contains is true; facing the segment for an open mesh) are (..., 3). Where hit is false the floats are NaN. refined (a FourierSurface’s hits) is true where the hit was moved onto the exact surface by Newton steps.

distanceattributeinstance attribute#

distance: Any

faceattributeinstance attribute#

face: Any

fractionattributeinstance attribute#

fraction: Any

hitattributeinstance attribute#

hit: Any

normalattributeinstance attribute#

normal: Any

phiattributeclass attributeinstance attribute#

phi: Any = None

pointattributeinstance attribute#

point: Any

refinedattributeclass attributeinstance attribute#

refined: Any = None

thetaattributeclass attributeinstance attribute#

theta: Any = None

Torusclass#

class Torus(midpoint: BoundsLike, major_radius: float, minor_radius: float, axis: BoundsLike = (0.0, 0.0, 1.0), bc: ConfigValue = None, inverted: bool = False)

Bases: AxisymmetricShape

A solid torus: the points within minor_radius of a circle of major_radius.

The circle is centred at midpoint in the plane normal to axis. The level_set is the exact signed distance.

Example

A torus with major radius 3 and tube radius 1 about the z axis::

ring = Torus((0, 0, 0), 3.0, 1.0)

Numerics

inside

p∈S  ⟺  (ρ−R)2+s2≤r2p \in S \iff (\rho - R)^2 + s^2 \le r^2

level set

ϕ=(ρ−R)2+s2−r\phi = \sqrt{(\rho - R)^2 + s^2} - r

Assumptions:

  • major radius RR, minor radius 0<r≤R0 < r \le R, centre circle in the plane s=0s = 0 of the frame of AxisymmetricShape
  • ϕ\phi is the exact signed distance, negative inside

References:

Built from:

  • simgeometry.objects.axisymmetric.AxisymmetricShape

major_radiusattributeinstance attribute#

major_radius = float(major_radius)

minor_radiusattributeinstance attribute#

minor_radius = float(minor_radius)

copymethod#

def copy() -> Torus

Create a copy of the torus.

surface_areamethod#

def surface_area() -> float

Calculate the surface area of the torus.

volumemethod#

def volume() -> float

Calculate the volume of the torus.

Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

axisproperty#

axis: tuple[float, float, float]

The unit vector of the symmetry axis.

midpointproperty#

midpoint: tuple[float, float, float]

The centre of the solid on its axis.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the solid.

Parameters: coords (list or tuple): Coordinates (x, y, z).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the solid across the plane where coordinate axis is position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the solid by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.
Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Triangleclass#

class Triangle(vertices: Vertices2DLike, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape2D

Represent a triangular geometry object.

Its level_set is the exact signed distance to its edges.

Numerics

inside

p=v0+u (v2−v0)+v (v1−v0),p∈S  ⟺  u≥0,  v≥0,  u+v≤1p = v_0 + u\,(v_2 - v_0) + v\,(v_1 - v_0), \qquad p \in S \iff u \ge 0,\; v \ge 0,\; u + v \le 1

level set

ϕ(p)=±min⁡edges∣p−a−clip⁡ ⁣((p−a)⋅e∣e∣2,0,1)e∣,e=b−a\phi(p) = \pm \min_\text{edges} \left| p - a - \operatorname{clip}\!\left(\tfrac{(p - a)\cdot e}{|e|^2}, 0, 1\right) e \right|, \qquad e = b - a

Assumptions:

  • barycentric coordinates u,vu, v with closed edges, inside the half-open bounding box
  • a degenerate triangle contains no point
  • ϕ\phi: the distance to the nearest edge, negative inside; exact

References:

exact_outlineattributeclass attributeinstance attribute#

exact_outline = True

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the (possibly inverted) triangle.

Parameters: coords (list or tuple): Coordinates (x, y).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (2, n) points inside.

copymethod#

def copy() -> Triangle

Create a copy of the triangle.

Returns

TriangleTriangle
A new instance of Triangle with the same vertices and boundary conditions.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the triangle across a specified axis at a given position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float]) -> None

Translate the xyz by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy) translation vector.
Inherited from simgeometry.shapes.Shape2D

closedattributeclass attributeinstance attribute#

closed: bool = True

boundary_panelsmethod#

def boundary_panels(max_spacing: Spacing | None = None) -> Panels

The edges of outlines as panels, for boundary-element solvers.

See Panels for the arrays and the normal convention.

outlinesmethod#

def outlines(max_spacing: Spacing | None = None) -> list[np.ndarray]

Return the boundary loops of the shape as (2, n) host arrays.

Each loop is counter-clockwise, without repeating its first vertex. A shape made of several pieces (such as Aperture2D’s two plates) has one loop per piece. An open curve (closed is False) gives its polyline instead, from its first vertex to its last. With max_spacing, edges longer than it are split evenly so that no two consecutive vertices are further apart; curved shapes then place every vertex on the curve. max_spacing may also be a function of (2, m) points returning (m,) spacings, to grade the vertices (finer near a corner, say); the spacing then holds approximately. Inversion does not change the outline.

Numerics

orientation

A=12∑i(xiyi+1−xi+1yi)>0(counter-clockwise; otherwise reversed)A = \tfrac12 \sum_i (x_i y_{i+1} - x_{i+1} y_i) > 0 \quad \text{(counter-clockwise; otherwise reversed)}

pieces

n=⌈ℓsmax⁡ (1−10−12)⌉n = \left\lceil \frac{\ell}{s_{\max}}\,(1 - 10^{-12}) \right\rceil

graded

∫0ℓdls(l) in equal steps, trapezoidal on 256 intervals\int_0^{\ell} \frac{dl}{s(l)} \text{ in equal steps, trapezoidal on 256 intervals}

Order of accuracy: 2.

Assumptions:

  • loops are (2,n)(2, n) without a repeated vertex; each edge of length ℓ\ell is split into nn equal pieces
  • curved shapes place every vertex on the curve; a circle gets 100 vertices without max_spacing
  • the order is that of the area enclosed by the outline of a circle in smax⁡s_{\max}

plotmethod#

def plot(ax: Any = None, **kwargs: Any) -> Any

Draw the shape as filled polygons into ax and return the axes.

Keyword arguments style the polygons (facecolor, alpha, …).

Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

TriangleMeshclass#

class TriangleMesh(vertices: Array, faces: Array, *, closed: bool | None = None, cells: int | tuple[int, int, int] | None = None, bc: ConfigValue = None, inverted: bool = False)

Bases: Shape3D

A surface made of triangles: closed (a solid) or open (panels).

Example

A wall exported from CAD as STL, and the first wall hit of a few segments::

wall = TriangleMesh.read("first_wall.stl")
hits = wall.first_hit(starts, ends) # (..., 3) arrays
hits.point, hits.normal, hits.face

Numerics

volume

V=16∑fv0⋅(v1×v2)V = \frac16 \sum_f v_0 \cdot (v_1 \times v_2)

normal

nf=(v1−v0)×(v2−v0)∣(v1−v0)×(v2−v0)∣n_f = \frac{(v_1 - v_0) \times (v_2 - v_0)}{|(v_1 - v_0) \times (v_2 - v_0)|}

inside

p∈S  ⟺  s(q)⊕(#{f:[p,q]∩f≠∅} mod 2),q the node of p’s cell nearest to pp \in S \iff s(q) \oplus \bigl(\#\{f : [p, q] \cap f \ne \emptyset\} \bmod 2\bigr), \qquad q \text{ the node of } p\text{'s cell nearest to } p

nodes

s(q)=maj⁡k=x,y,z(#{f:the grid line along k meets f before q} mod 2)s(q) = \operatorname{maj}_{k = x, y, z}\Bigl(\#\{f : \text{the grid line along } k \text{ meets } f \text{ before } q\} \bmod 2\Bigr)

Order of accuracy: 2.

Assumptions:

  • closed: every edge in exactly two faces, each directed edge once (consistent orientation); faces are reoriented so that V>0V > 0 and nfn_f points out
  • open meshes have no inside (contains is False everywhere) and their normals face the incoming segment
  • a uniform grid of about four cells per face over the mesh’s box, shifted by irrational fractions of a cell; every cell lists the faces whose box (widened by 10−910^{-9} cells) overlaps it
  • first hits walk the segment’s cells in order (Amanatides and Woo) and test their faces exactly (Möller–Trumbore), stopping once the nearest hit lies before the cell’s exit; hits at t≤10−12t \le 10^{-12} are ignored
  • exact for the triangles, except for a segment through an edge or vertex exactly, where a crossing may count twice
  • the order is that of the volume of a sphere’s mesh in the angular spacing

References:

Built from:

  • simgeometry.kernels.triangle_hits.triangle_fractions

closedattributeinstance attribute#

closed = bool(closed)

gridattributeinstance attribute#

grid: TriangleGrid = build_triangle_grid(self._vertices, self._faces, cells=cells, closed=self.closed)

edge_lengthproperty#

edge_length: float

The mean length of the faces’ edges.

face_areasproperty#

face_areas: np.ndarray

Areas (F,) of the faces.

face_normalsproperty#

face_normals: np.ndarray

Unit normals (F, 3) of the faces, outward for a closed mesh.

facesproperty#

faces: np.ndarray

The (F, 3) faces (read-only); outward-oriented for a closed mesh.

n_facesproperty#

n_faces: int

The number of triangles.

verticesproperty#

vertices: np.ndarray

The (V, 3) vertices (read-only).

containsmethod#

def contains(coords: tuple[float, float, float]) -> bool

Return whether the point is inside (never for an open mesh).

contains_pointsmethod#

def contains_points(points: Array) -> Array

Return a mask of the (3, n) points inside the closed mesh.

Exact for the triangles (see the module docstring); an open mesh contains nothing, so the mask is False (True if inverted).

copymethod#

def copy() -> TriangleMesh

Create a copy of the mesh (sharing the read-only arrays).

first_hitmethod#

def first_hit(starts: Array, ends: Array) -> SurfaceHits

Return the first hit of each segment starts[...] -> ends[...], (..., 3).

The point-major form of crossings with the face hit; a hit at the very start of a segment (a fraction below 1e-12) is not counted, so a segment that starts on the wall leaves it.

inside_atmethod#

def inside_at(points: Array) -> Array

Return whether the points (..., 3) are inside, as (...).

The point-major form of contains_points, as freeofcharge’s inside_wall_at takes its points.

readmethodclassmethod#

def read(path: str | Path, *, merge_tolerance: float | None = None, **kwargs)

Read a mesh from STL (ASCII or binary), OBJ, NPZ, or any format meshio reads.

STL stores every triangle on its own, so vertices closer than merge_tolerance (default 1e-9 of the mesh’s extent) are merged to recover the topology; pass 0 to keep them apart. Other arguments go to TriangleMesh. Formats other than STL, OBJ and NPZ (vertices and cells, as written by SurfaceMesh.save) need meshio.

savemethod#

def save(path: str | Path) -> Path

Write the mesh as .npz, .obj or ASCII .stl (see SurfaceMesh.save).

surface_areamethod#

def surface_area() -> float

Return the total area of the faces.

to_meshmethod#

def to_mesh(**kwargs: Any)

Return the triangles as a SurfaceMesh (resolution and bounds are ignored).

volumemethod#

def volume() -> float

Return the enclosed volume of a closed mesh.

Inherited from simgeometry.shapes.Shape

has_level_setattributeclass attributeinstance attribute#

has_level_set: bool = False

level_set_exactattributeclass attributeinstance attribute#

level_set_exact: bool = False

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.

Tubeclass#

class Tube(start: BoundsLike, end: BoundsLike, inner_radius: float, outer_radius: float, bc: ConfigValue = None, inverted: bool = False, *, fillet: float = 0.0)

Bases: CappedAxisymmetricShape

A hollow cylinder between inner_radius and outer_radius, from start to end.

A short tube is a ring electrode; a long one a drift tube or a chamber wall. fillet rounds its four circular edges (at most half the wall thickness and half the length). The level_set is the exact signed distance, with or without the fillet.

Example

A ring of bore radius 1 and outer radius 1.5, 0.4 long, centred at z = 0::

ring = Tube((0, 0, -0.2), (0, 0, 0.2), 1.0, 1.5)

Numerics

inside

p∈S  ⟺  ∣s∣≤L,  ri2≤ρ2≤ro2(f=0),p∈S  ⟺  ϕ(p)≤0(f>0)p \in S \iff |s| \le L,\; r_i^2 \le \rho^2 \le r_o^2 \quad (f = 0), \qquad p \in S \iff \phi(p) \le 0 \quad (f > 0)

level set

ϕ=ϕrect ⁣(ρ−ri+ro2,s; ro−ri2−f,L−f)−f\phi = \phi_\mathrm{rect}\!\left(\rho - \tfrac{r_i + r_o}{2}, s;\ \tfrac{r_o - r_i}{2} - f, L - f\right) - f

Assumptions:

  • half length LL, 0<ri<ro0 < r_i < r_o, in the frame (s,ρ)(s, \rho) of AxisymmetricShape; ϕrect\phi_\mathrm{rect} the 2D box distance as for Cylinder
  • the fillet f≤min⁡(ro−ri2,L)f \le \min(\tfrac{r_o - r_i}{2}, L) rounds the four circular edges
  • ϕ\phi is the exact signed distance, negative inside

Built from:

  • simgeometry.objects.axisymmetric.AxisymmetricShape

filletattributeinstance attribute#

fillet = float(fillet)

inner_radiusattributeinstance attribute#

inner_radius = float(inner_radius)

outer_radiusattributeinstance attribute#

outer_radius = float(outer_radius)

copymethod#

def copy() -> Tube

Create a copy of the tube.

surface_areamethod#

def surface_area() -> float

Calculate the surface area of the tube, inside and out, with its rounded edges.

volumemethod#

def volume() -> float

Calculate the volume of the tube, less the rounded edges.

Inherited from simgeometry.objects.axisymmetric.CappedAxisymmetricShape

endproperty#

end: tuple[float, float, float]

The centre of the end face at the end of the axis.

lengthproperty#

length: float

The distance from start to end.

startproperty#

start: tuple[float, float, float]

The centre of the end face at the start of the axis.

Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape

has_level_setattributeclass attributeinstance attribute#

has_level_set = True

level_set_exactattributeclass attributeinstance attribute#

level_set_exact = True

axisproperty#

axis: tuple[float, float, float]

The unit vector of the symmetry axis.

midpointproperty#

midpoint: tuple[float, float, float]

The centre of the solid on its axis.

containsmethod#

def contains(coords: Array) -> bool

Check if the given coordinates are inside the solid.

Parameters: coords (list or tuple): Coordinates (x, y, z).

Returns: bool: True if the point is inside the object, False otherwise.

contains_pointsmethod#

def contains_points(points: Array) -> Array

Vectorised contains: a mask of the (3, n) points inside.

mirrormethod#

def mirror(axis: int, position: float) -> None

Mirror the solid across the plane where coordinate axis is position.

Parameters

NameTypeDescription
axisintAxis index (0 for x-axis, 1 for y-axis, 2 for z-axis).
positionfloatPosition along the axis to mirror.

translatemethod#

def translate(offset: tuple[float, float, float]) -> None

Translate the solid by the given offset.

Parameters

NameTypeDescription
offsettuple(dx, dy, dz) translation vector.
Inherited from simgeometry.shapes.Shape

ndimattributeinstance attribute#

ndim = ndim

bounding_boxproperty#

bounding_box: BoundingBox

Return the bounding box.

invertedproperty#

inverted: bool

Return whether this object represents an inverted region.

lower_boundproperty#

lower_bound: tuple[float, ...]

Return the lower coordinate bounds.

upper_boundproperty#

upper_bound: tuple[float, ...]

Return the upper coordinate bounds.

get_bound_verticesmethod#

def get_bound_vertices(slice_axis: int) -> xp.ndarray

Return vertices that bound the shape.

get_indices_in_objectmethod#

def get_indices_in_object(grid: Grid) -> list[int] | list[tuple[int, ...]]

Get the indices of grid points that are inside the shape.

Parameters: grid (object): Grid object containing indices and cell sizes.

Returns: list: The Grid.indices of the nodes inside, in their order.

level_setmethod#

def level_set(points: Array) -> Array

Level-set values of the (ndim, n) points: negative inside, positive outside.

The sign follows signed_distance, so it flips for an inverted shape, and the boundary is the zero level (where contains_points may go either way). The magnitude never exceeds the distance to the boundary; with level_set_exact it equals it. Values are on the active cunumpy backend, like contains_points. Raises NotImplementedError when has_level_set is False.

Numerics

inversion

ϕSc(p)=−ϕS(p)\phi_{S^c}(p) = -\phi_S(p)

bound

ϕ<0 inside,ϕ=0 on ∂S,∣ϕ(p)∣≤dist⁡(p,∂S)\phi < 0 \text{ inside}, \quad \phi = 0 \text{ on } \partial S, \quad |\phi(p)| \le \operatorname{dist}(p, \partial S)

Assumptions:

  • an inverted shape is the complement of its geometry: contains_points is negated and the level set flips sign
  • equality in the bound where level_set_exact is true: the Euclidean signed distance
  • shapes known only by their membership test (has_level_set False) raise NotImplementedError

node_maskmethod#

def node_mask(grid: Grid) -> np.ndarray

Return a host boolean array of the grid’s shape, set at the nodes inside.

One vectorised contains_points over Grid.node_points, so the cost is that of a few array passes over the grid.

set_bounding_boxmethod#

def set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> None

Set the bounding box for the shape.

Inherited from simgeometry.api.GeometryAPI

cell_fractionsmethod#

def cell_fractions(grid, *, samples_per_axis=4)

Estimate solid cell-volume and face-area fractions by subcell sampling.

Increase samples_per_axis to check convergence; unresolved thin features can be missed. This is not an exact finite-volume interface reconstruction.

closest_pointmethod#

def closest_point(points, *, resolution=64, bounds=None)

Closest surface coordinates; primitives are exact, others use a mesh.

Mesh fallback requires mesh extras. Its accuracy is controlled by resolution and may miss unresolved components. Points are (ndim, n), or one (ndim,) point; the returned array has the same layout.

crossingsmethod#

def crossings(start, end, *, samples=64, iterations=40)

First boundary crossing of every segment start[:, i] -> end[:, i].

start and end are (ndim, N), such as particle positions before and after a step. Returns a Crossings with hit, fraction, point and normal (out of the region where contains is true) on the active array backend. Polygons, circles, spheres, boxes and their affine transforms are analytic; other shapes sample samples points per segment and bisect iterations times, or refine on their level set (with its gradient as the normal) if they have one.

cut_edgesmethod#

def cut_edges(grid, **kwargs)

Locate all detected grid-edge surface hits, without solver clamping.

diagnosemethod#

def diagnose(grid, **kwargs)

Report sampled overlaps, unresolved components, and short cut distances.

differencemethod#

def difference(other)

evaluatemethod#

def evaluate(x=None, y=None, z=None, *, grid=None, bounds=None, resolution=128, quantity='occupancy')

Sample geometry as an xarray.DataArray (requires the evaluate extra).

Scalars fix axes, sequences form a tensor product, and DataArrays with shared dimension names describe scattered points. Unspecified axes use grid nodes, or resolution samples across bounds/the shape bounds. quantity is occupancy, labels (collections), signed_distance, or level_set (the analytic level set, or the signed distance without one). This is a local host operation, with no implicit MPI collectives.

exportmethod#

def export(path, **kwargs)

Export a sampled mesh as NPZ, OBJ, or STL (3D only).

intersect_segmentmethod#

def intersect_segment(start, end, *, samples=256, tolerance=1e-10)

Return ordered surface hits, including multiple crossings and tangencies.

Primitive intersections are analytic. Generic membership functions use samples intervals and may miss features smaller than that sampling. Result.exact distinguishes these cases. Coincident surface segments do not have a discrete set of hits; their end contacts may be returned.

intersectionmethod#

def intersection(other)

level_set_fieldmethod#

def level_set_field(resolution=64, bounds=None)

The level set on a 3D grid, laid out for plasma-plots’ 3D views.

shape.level_set_field().plasma.plot.isosurface(values=[0]) draws the surface (requires the interactive extra and import plasma_plots).

plotmethod#

def plot(ax=None, **kwargs)

Draw without displaying and return axes for composition.

rotatedmethod#

def rotated(angle, *, axis=(0, 0, 1), origin=None)

Return a rotated snapshot; angle is in degrees, about origin (default 0).

sample_interiormethod#

def sample_interior(count, *, rng=None, bounds=None, max_draws=1000000)

Uniform rejection samples, returned as (ndim, count).

Supply bounds for inverted/unbounded shapes. Raises if max_draws is exhausted; it never silently returns too few samples.

sample_surfacemethod#

def sample_surface(count, *, rng=None, resolution=64, bounds=None)

Uniform-by-length/area samples from the faceted boundary mesh.

scaledmethod#

def scaled(factors, *, origin=None)

Return a snapshot scaled by a nonzero scalar or per-axis factors.

showmethod#

def show(**kwargs)

Display geometry, dispatching to 3D unless a slice is requested.

Returns Matplotlib axes, or a PyVista plotter for backend='pyvista'. Set display=False for scripts. save=path saves the figure.

show_3dmethod#

def show_3d(**kwargs)

Display a surface with optional wireframe, normals and clipping.

backend='pyvista' enables an interactive clipping-plane widget via clip=True (requires the interactive extra). Matplotlib supports a static clip=(origin, normal) plane. Meshes are resolution-dependent.

signed_distancemethod#

def signed_distance(points, *, resolution=64, bounds=None)

Distance to the boundary, negative inside, positive outside.

Exact for balls, boxes, simple polygons and every shape whose level set is exact (level_set_exact, such as cylinders, tubes, cones, tori and their rigid motions), which it returns directly; otherwise distance to the sampled surface mesh. A membership function is not itself a distance.

slicemethod#

def slice(x=None, y=None, z=None, origin=None, normal=None)

Return a queryable section with local-to-world coordinate mappings.

Fix exactly one coordinate, or give a 3D plane’s origin and normal. Axis-aligned sections retain the remaining coordinate names; oblique sections use x/y as their local plane coordinates.

surface_normalmethod#

def surface_normal(points, *, scale=None)

Outward unit normals at boundary points; NaN where undefined.

Primitive faces use analytic normals. Other geometries estimate the normal from nearby membership samples. At corners normals are not unique.

to_meshmethod#

def to_mesh(resolution=64, bounds=None)

Return sampled contours (2D) or triangles (3D), with spacing metadata.

Requires the mesh extra. Open contours/surfaces at the sampling bounds remain open; no artificial caps are added. Refine to resolve thin features.

transformedmethod#

def transformed(matrix, offset=None)

Return an affine-transformed snapshot; the source is unchanged.

translatedmethod#

def translated(offset)

Return a translated snapshot (unlike legacy in-place translate).

unionmethod#

def union(other)

yee_fractionsmethod#

def yee_fractions(grid, **kwargs)

Edge-length and face-area fractions of a Yee grid, and the surface’s traces.

Exact for planes; see simgeometry.fractions.yee_fractions.