simgeometry.objects
Package exports for geometric object definitions.
Classes
| Name | Description |
|---|---|
Aperture2D | Two plates mirrored about a beam axis: a slit, or the 2D cut of a round aperture. |
Aperture3D | Represent a three-dimensional aperture embedded in a simulation domain. |
Circle | Represent a circular geometry object. |
Cone | A frustum with radius start_radius at start and end_radius at end. |
Cuboid | Represent a cuboid geometry object. |
Cylinder | A solid circular cylinder with its axis from start to end. |
FourierSurface | A closed toroidal surface as a Fourier series, with nfp field periods. |
FunctionObject2D | Represent an arbitrary 2D geometry object defined by a Boolean function. |
FunctionObject3D | Represent an arbitrary 3D geometry object defined by a Boolean function. |
Helix | A helical wire of round cross-section: the points within wire_radius of a helix. |
Line | Represent a line geometry object. |
Polygon | Represent a polygon geometry object. |
Polyline | An open curve through vertices: a thin plate, wire or grid of zero thickness. |
Rectangle | Represent a rectangular geometry object. |
SlantedTube | A tube from start to end whose end at end is cut by a slanted plane. |
Sphere | Represent a spherical geometry object. |
SurfaceHits | First hits of segments with a surface, point-major: (...) and (..., 3). |
Torus | A solid torus: the points within minor_radius of a circle of major_radius. |
Triangle | Represent a triangular geometry object. |
TriangleMesh | A surface made of triangles: closed (a solid) or open (panels). |
Tube | A 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#
simgeometry.objects.aperture2dView sourceclass 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
level set
Assumptions:
- the profile : along the beam axis, across it from the centre line at =
position - each plate is a
Polygon: even-odd rule inside its half-open bounding box - is negative inside a plate and exact while the plates are apart (every ), a bound otherwise
Built from:
simgeometry.objects.polygon.Polygon
exact_outlineattributeclass attributeinstance attribute#
exact_outline = Truehas_level_setattributeclass attributeinstance attribute#
has_level_set = Trueaxispropertywritable#
axis: intReturn the beam axis.
level_set_exactproperty#
level_set_exact: boolWhether the plates are apart, so that the level set is exact.
positionproperty#
position: floatReturn the centre line’s coordinate across the beam.
rvecproperty#
rvec: listReturn the radial aperture coordinate vector.
verticespropertywritable#
vertices: tuple[tuple[float, float], ...]Return the plate profile as (axial, radial) vertices.
zvecproperty#
zvec: listReturn the axial aperture coordinate vector.
containsmethod#
def contains(coords: ndarray) -> boolCheck 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) -> ndarrayVectorised 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) -> Aperture2DA 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#
simgeometry.shapes.Shape2DView sourceclosed: bool = Trueboundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
plotmethod#
simgeometry.shapes.Shape2DView sourcedef plot(ax: Any = None, **kwargs: Any) -> AnyDraw 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#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef copy()Return an independent deep copy.
crossingsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.aperture3dView sourceclass 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
opening
inside
Assumptions:
- the profile of (axial position , radius ) vertices about the axis through
center_coords; fromsearchsorted(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 = axisaxis_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 = Trueverticesattributeinstance attribute#
vertices = xp.array(vertices)max_radiusproperty#
max_radius: floatReturn the largest aperture radius.
min_radiusproperty#
min_radius: floatReturn the smallest aperture radius.
containsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorized contains: a mask of the (3, n) points inside.
copymethod#
def copy() -> Aperture3DCreate 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) -> ConfigValueGet 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) -> NoneMirror the aperture across a specified axis at a given position.
surface_areamethod#
def surface_area() -> NoneDeclare the aperture surface-area interface.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the aperture by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
volumemethod#
def volume() -> NoneDeclare the aperture volume interface.
Inherited from simgeometry.shapes.Shape
has_level_setattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcehas_level_set: bool = Falselevel_set_exactattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcelevel_set_exact: bool = Falsendimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.circleView sourceclass 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
level set
Assumptions:
- closed: points on the circle are inside
- is the exact signed distance, negative inside
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Truemidpointattributeinstance attribute#
midpoint = list(midpoint)radiusattributeinstance attribute#
radius = radiuscontainsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (2, n) points inside.
copymethod#
def copy() -> CircleCreate 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) -> NoneMirror the circle across a specified axis at a given position.
translatemethod#
def translate(offset: tuple[float, float]) -> NoneTranslate the xyz by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy) translation vector. |
Inherited from simgeometry.shapes.Shape2D
closedattributeclass attributeinstance attribute#
simgeometry.shapes.Shape2DView sourceclosed: bool = Trueexact_outlineattributeclass attributeinstance attribute#
simgeometry.shapes.Shape2DView sourceexact_outline: bool = Falseboundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
plotmethod#
simgeometry.shapes.Shape2DView sourcedef plot(ax: Any = None, **kwargs: Any) -> AnyDraw 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#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.coneView sourceclass 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
level set
slant
Assumptions:
- radius at (
start), at (end), one of them may be zero; frame ofAxisymmetricShape - is the radius of the nearer cap; the minus sign where the point is on the inner side of the slant and
- 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() -> ConeCreate a copy of the cone.
surface_areamethod#
def surface_area() -> floatCalculate the surface area of the frustum, with its end discs.
volumemethod#
def volume() -> floatCalculate the volume of the frustum.
Inherited from simgeometry.objects.axisymmetric.CappedAxisymmetricShape
Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Trueaxisproperty#
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) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the solid across the plane where coordinate axis is position.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the solid by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.cuboidView sourceclass 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
level set
Assumptions:
- axis-aligned, centre , half sides ; and of componentwise
- the fillet rounds the edges and corners: the box shrunk by , widened by a ball of radius
- closed: points on the faces are inside
- is the exact signed distance, negative inside
References:
filletattributeinstance attribute#
fillet = float(fillet)has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Truemidpointattributeinstance attribute#
midpoint = xp.array(midpoint)side_lengthsattributeinstance attribute#
side_lengths = xp.array(side_lengths)containsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
copymethod#
def copy() -> CuboidCreate 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) -> ConfigValueGet the corner vertices of a slice of the cuboid along a given axis.
Parameters
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) -> NoneMirror the cuboid across a specified axis at a given position.
surface_areamethod#
def surface_area() -> floatCalculate the surface area of the cuboid, with its rounded edges.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the cuboid by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
volumemethod#
def volume() -> floatCalculate the volume of the cuboid, less the rounded edges.
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.cylinderView sourceclass 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
level set
Assumptions:
- half length , radius , in the frame of
AxisymmetricShape - the fillet rounds the two circular edges
- 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() -> CylinderCreate a copy of the cylinder.
surface_areamethod#
def surface_area() -> floatCalculate the surface area of the cylinder, with its rounded edges.
volumemethod#
def volume() -> floatCalculate the volume of the cylinder, less the rounded edges.
Inherited from simgeometry.objects.axisymmetric.CappedAxisymmetricShape
Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Trueaxisproperty#
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) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the solid across the plane where coordinate axis is position.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the solid by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.fourier_surfaceView sourceclass 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) arraysNumerics
surface
normal
hit
closest
offset
volume
Order of accuracy: 2.
Assumptions:
- VMEC’s and ConStellaration’s
SurfaceRZFourier: , , the cylindrical angle; each cross-section at constant a simple closed curve - membership and the hit search on the triangulation of
resolutionpoints per poloidal turn and per field period, exact for the triangles (TriangleMesh) refine: hits moved onto the surface by Newton steps on from the triangle’s angles, to of the surface’s size; kept on the triangle if a step fails or leaves- whether a segment hits is decided by the triangles: grazing segments within
triangulation_errorof the surface may differ from the exact surface - offset: the normal offset is a surface at distance while is below the smallest radius of curvature of the concave parts; refitted with poloidal and 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 = Noner_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: TriangleMeshThe triangulation at resolution, which answers membership and hit searches.
n_poloidalproperty#
n_poloidal: intThe largest poloidal mode number M.
n_toroidalproperty#
n_toroidal: intThe largest toroidal mode number N.
stellarator_symmetricproperty#
stellarator_symmetric: boolWhether the surface has only r_cos and z_sin terms.
triangulation_errorproperty#
triangulation_error: floatThe 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]) -> boolReturn whether the point is inside (see contains_points).
contains_pointsmethod#
def contains_points(points: Array) -> ArrayReturn 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() -> FourierSurfaceCreate a copy of the surface.
first_hitmethod#
def first_hit(starts: Array, ends: Array) -> SurfaceHitsReturn 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) -> FourierSurfaceReturn 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) -> ArrayReturn whether the points (..., 3) are inside, as (...).
normalmethod#
def normal(theta: Array, phi: Array) -> np.ndarrayReturn 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) -> FourierSurfaceReturn 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.ndarrayReturn 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() -> floatReturn the area of the surface (trapezoidal rule on the exact surface).
to_boundarymethod#
def to_boundary() -> dictReturn 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() -> floatReturn the enclosed volume (trapezoidal rule on the exact surface).
Inherited from simgeometry.shapes.Shape
has_level_setattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcehas_level_set: bool = Falselevel_set_exactattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcelevel_set_exact: bool = Falsendimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.function_objectView sourceclass 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),)containsmethod#
def contains(coords: Array) -> boolCheck 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) -> AnyDraw 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#
simgeometry.shapes.Shape2DView sourceclosed: bool = Trueexact_outlineattributeclass attributeinstance attribute#
simgeometry.shapes.Shape2DView sourceexact_outline: bool = Falseboundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
Inherited from simgeometry.shapes.Shape
has_level_setattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcehas_level_set: bool = Falselevel_set_exactattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcelevel_set_exact: bool = Falsendimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
contains_pointsmethod#
simgeometry.shapes.ShapeView sourcedef contains_points(points: Array) -> ArrayReturn 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#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef copy()Return an independent deep copy.
crossingsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.function_objectView sourceclass 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),)containsmethod#
def contains(coords: Array) -> boolCheck 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) -> tupleReturn an empty array; vertices cannot be derived from an arbitrary function.
surface_areamethod#
def surface_area() -> floatSurface area cannot be analytically derived from an arbitrary function.
volumemethod#
def volume() -> floatVolume cannot be analytically derived from an arbitrary function.
Inherited from simgeometry.shapes.Shape
has_level_setattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcehas_level_set: bool = Falselevel_set_exactattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcelevel_set_exact: bool = Falsendimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
contains_pointsmethod#
simgeometry.shapes.ShapeView sourcedef contains_points(points: Array) -> ArrayReturn 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#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef copy()Return an independent deep copy.
crossingsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.helixView sourceclass 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
level set
descent
bound
Assumptions:
- the unit axis, the direction of the start point from the axis, (right- or left-handed); the point’s cylindrical coordinates in that frame
- the wire’s ends are hemispheres (the points within of the end points of the centreline)
- within of the cylinder the centreline lies on: the minimum over from four starts, the two ends and the linearised minima of the two turns around , by six Newton steps (descent steps on the majorant where is not clearly positive), clipped to ; exact there (tested against dense sampling)
- farther away is the bound (the distance from the cylinder, minus ): a level set that never exceeds the distance
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Falsepitchattributeinstance 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: boolWhether the helix winds clockwise seen from the end the axis points to.
lengthproperty#
length: floatThe 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: floatThe length of the centreline, turns * sqrt((2 pi radius)^2 + pitch^2).
centrelinemethod#
def centreline(t: Array) -> ArrayThe points (3, n) of the centreline at the angles t (0 to 2 pi N).
containsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
copymethod#
def copy() -> HelixCreate a copy of the helix.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the helix across the plane where coordinate axis is position.
A mirror image of a right-handed helix is left-handed.
surface_areamethod#
def surface_area() -> floatThe surface area: the swept circle and the two hemispheres (no overlap).
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the helix by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
volumemethod#
def volume() -> floatThe 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#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.lineView sourceclass 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
level set
Assumptions:
- closed: both end points are inside
- is the exact signed distance, negative inside
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Truemidpointattributeinstance attribute#
midpoint = xp.array(midpoint)side_lengthsattributeinstance attribute#
side_lengths = xp.array(side_lengths)containsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (1, n) points inside.
copymethod#
def copy() -> LineCreate 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() -> ConfigValueReturn the vertices that define the object.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the line across a specified axis at a given position.
translatemethod#
def translate(offset: tuple[float]) -> NoneTranslate the line by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx,) translation vector. |
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.polygonView sourceclass 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
level set
Assumptions:
- the even-odd (crossing-number) rule along a ray towards , not a winding number; is the vertex before , the closing edge implied
- half-open in , so a vertex on the ray is counted once; guards horizontal edges
- inside also needs the half-open bounding box ; the compiled kernel
contains_polygon_2druns the test - : the distance to the nearest edge, negative where
contains_pointsis 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 = Truehas_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Trueverticespropertywritable#
vertices: ndarrayReturn object vertices.
containsmethod#
def contains(coords: ndarray) -> boolCheck 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) -> ndarrayVectorised contains: a mask of the (2, n) points inside.
copymethod#
def copy() -> PolygonCreate 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) -> NoneMirror the polygon across a specified axis at a given position.
translatemethod#
def translate(offset: tuple[float, float]) -> NoneTranslate the polygon by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy) translation vector. |
Inherited from simgeometry.shapes.Shape2D
closedattributeclass attributeinstance attribute#
simgeometry.shapes.Shape2DView sourceclosed: bool = Trueboundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
plotmethod#
simgeometry.shapes.Shape2DView sourcedef plot(ax: Any = None, **kwargs: Any) -> AnyDraw 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#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.polylineView sourceclass 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 = Falseexact_outlineattributeclass attributeinstance attribute#
exact_outline = Truelengthproperty#
length: floatThe length of the curve.
verticesproperty#
vertices: ndarrayThe (n, 2) vertices, one row per point, as given.
containsmethod#
def contains(coords: tuple[float, float]) -> boolAlways False: a curve encloses no area.
contains_pointsmethod#
def contains_points(points: ndarray) -> ndarrayAn all-False mask of the (2, n) points: a curve encloses no area.
Inherited from simgeometry.shapes.Shape2D
boundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
plotmethod#
simgeometry.shapes.Shape2DView sourcedef plot(ax: Any = None, **kwargs: Any) -> AnyDraw 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#
simgeometry.shapes.ShapeView sourcehas_level_set: bool = Falselevel_set_exactattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcelevel_set_exact: bool = Falsendimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef copy()Return an independent deep copy.
crossingsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.rectangleView sourceclass 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
level set
Assumptions:
- axis-aligned, centre , half sides ; and of componentwise
- the fillet rounds the corners: the box shrunk by , widened by a disc of radius
- without a fillet the inside test is the half-open box of
BoundingBox.contains - is the exact signed distance, negative inside
References:
exact_outlineattributeclass attributeinstance attribute#
exact_outline = self.fillet == 0filletattributeinstance attribute#
fillet = float(fillet)has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Truemidpointattributeinstance attribute#
midpoint = list(midpoint)side_lengthsattributeinstance attribute#
side_lengths = side_lengthscontainsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (2, n) points inside.
copymethod#
def copy() -> RectangleCreate 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) -> NoneMirror the rectangle across a specified axis at a given position.
translatemethod#
def translate(offset: tuple[float, float]) -> NoneTranslate the xyz by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy) translation vector. |
Inherited from simgeometry.shapes.Shape2D
closedattributeclass attributeinstance attribute#
simgeometry.shapes.Shape2DView sourceclosed: bool = Trueboundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
plotmethod#
simgeometry.shapes.Shape2DView sourcedef plot(ax: Any = None, **kwargs: Any) -> AnyDraw 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#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.slanted_tubeView sourceclass 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
inside
level set
Assumptions:
- unit axis from
start, length to the centre of the cut; cut plane throughendwith unit outward normal , - the cut misses the start face: ; a rod () has
- , 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 = Trueinner_radiusattributeinstance attribute#
inner_radius = float(inner_radius)level_set_exactattributeclass attributeinstance attribute#
level_set_exact = Falseouter_radiusattributeinstance attribute#
outer_radius = float(outer_radius)axisproperty#
axis: tuple[float, float, float]The unit vector from start to end.
cut_angleproperty#
cut_angle: floatThe 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: floatThe 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) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
copymethod#
def copy() -> SlantedTubeCreate a copy of the slanted tube.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the slanted tube across the plane where coordinate axis is position.
surface_areamethod#
def surface_area() -> floatCalculate the surface area: both walls, the flat end and the elliptic cut.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the slanted tube by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
volumemethod#
def volume() -> floatCalculate the volume: a cut through the axis point leaves that of a straight tube.
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.sphereView sourceclass 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
level set
Assumptions:
- closed: points on the sphere are inside
- is the exact signed distance, negative inside
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Truemidpointattributeinstance attribute#
midpoint = list(midpoint)radiusattributeinstance attribute#
radius = radiuscontainsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
copymethod#
def copy() -> SphereCreate 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) -> ConfigValueGet 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) -> NoneMirror the sphere across a specified axis at a given position.
surface_areamethod#
def surface_area() -> floatCalculate the surface area of the sphere.
translatemethod#
def translate(offset: tuple[float, float]) -> NoneTranslate the xyz by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy) translation vector. |
volumemethod#
def volume() -> floatCalculate the volume of the sphere.
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.triangle_meshView sourceclass 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: Anyfaceattributeinstance attribute#
face: Anyfractionattributeinstance attribute#
fraction: Anyhitattributeinstance attribute#
hit: Anynormalattributeinstance attribute#
normal: Anyphiattributeclass attributeinstance attribute#
phi: Any = Nonepointattributeinstance attribute#
point: Anyrefinedattributeclass attributeinstance attribute#
refined: Any = Nonethetaattributeclass attributeinstance attribute#
theta: Any = NoneTorusclass#
simgeometry.objects.torusView sourceclass 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
level set
Assumptions:
- major radius , minor radius , centre circle in the plane of the frame of
AxisymmetricShape - 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() -> TorusCreate a copy of the torus.
surface_areamethod#
def surface_area() -> floatCalculate the surface area of the torus.
volumemethod#
def volume() -> floatCalculate the volume of the torus.
Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Trueaxisproperty#
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) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the solid across the plane where coordinate axis is position.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the solid by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.triangleView sourceclass 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
level set
Assumptions:
- barycentric coordinates with closed edges, inside the half-open bounding box
- a degenerate triangle contains no point
- : the distance to the nearest edge, negative inside; exact
References:
exact_outlineattributeclass attributeinstance attribute#
exact_outline = Truehas_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Truecontainsmethod#
def contains(coords: Array) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (2, n) points inside.
copymethod#
def copy() -> TriangleCreate 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) -> NoneMirror the triangle across a specified axis at a given position.
translatemethod#
def translate(offset: tuple[float, float]) -> NoneTranslate the xyz by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy) translation vector. |
Inherited from simgeometry.shapes.Shape2D
closedattributeclass attributeinstance attribute#
simgeometry.shapes.Shape2DView sourceclosed: bool = Trueboundary_panelsmethod#
simgeometry.shapes.Shape2DView sourcedef boundary_panels(max_spacing: Spacing | None = None) -> PanelsThe edges of outlines as panels, for boundary-element solvers.
See Panels for the arrays and the normal
convention.
outlinesmethod#
simgeometry.shapes.Shape2DView sourcedef 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
pieces
graded
Order of accuracy: 2.
Assumptions:
- loops are without a repeated vertex; each edge of length is split into 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
plotmethod#
simgeometry.shapes.Shape2DView sourcedef plot(ax: Any = None, **kwargs: Any) -> AnyDraw 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#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.triangle_meshView sourceclass 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) arrayshits.point, hits.normal, hits.faceNumerics
volume
normal
inside
nodes
Order of accuracy: 2.
Assumptions:
- closed: every edge in exactly two faces, each directed edge once (consistent orientation); faces are reoriented so that and points out
- open meshes have no inside (
containsis 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 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 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: floatThe mean length of the faces’ edges.
face_areasproperty#
face_areas: np.ndarrayAreas (F,) of the faces.
face_normalsproperty#
face_normals: np.ndarrayUnit normals (F, 3) of the faces, outward for a closed mesh.
facesproperty#
faces: np.ndarrayThe (F, 3) faces (read-only); outward-oriented for a closed mesh.
n_facesproperty#
n_faces: intThe number of triangles.
verticesproperty#
vertices: np.ndarrayThe (V, 3) vertices (read-only).
containsmethod#
def contains(coords: tuple[float, float, float]) -> boolReturn whether the point is inside (never for an open mesh).
contains_pointsmethod#
def contains_points(points: Array) -> ArrayReturn 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() -> TriangleMeshCreate a copy of the mesh (sharing the read-only arrays).
first_hitmethod#
def first_hit(starts: Array, ends: Array) -> SurfaceHitsReturn 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) -> ArrayReturn 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) -> PathWrite the mesh as .npz, .obj or ASCII .stl (see SurfaceMesh.save).
surface_areamethod#
def surface_area() -> floatReturn 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() -> floatReturn the enclosed volume of a closed mesh.
Inherited from simgeometry.shapes.Shape
has_level_setattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcehas_level_set: bool = Falselevel_set_exactattributeclass attributeinstance attribute#
simgeometry.shapes.ShapeView sourcelevel_set_exact: bool = Falsendimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.objects.tubeView sourceclass 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
level set
Assumptions:
- half length , , in the frame of
AxisymmetricShape; the 2D box distance as forCylinder - the fillet rounds the four circular edges
- 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() -> TubeCreate a copy of the tube.
surface_areamethod#
def surface_area() -> floatCalculate the surface area of the tube, inside and out, with its rounded edges.
volumemethod#
def volume() -> floatCalculate the volume of the tube, less the rounded edges.
Inherited from simgeometry.objects.axisymmetric.CappedAxisymmetricShape
Inherited from simgeometry.objects.axisymmetric.AxisymmetricShape
has_level_setattributeclass attributeinstance attribute#
has_level_set = Truelevel_set_exactattributeclass attributeinstance attribute#
level_set_exact = Trueaxisproperty#
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) -> boolCheck 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) -> ArrayVectorised contains: a mask of the (3, n) points inside.
mirrormethod#
def mirror(axis: int, position: float) -> NoneMirror the solid across the plane where coordinate axis is position.
translatemethod#
def translate(offset: tuple[float, float, float]) -> NoneTranslate the solid by the given offset.
Parameters
| Name | Type | Description |
|---|---|---|
offset | tuple | (dx, dy, dz) translation vector. |
Inherited from simgeometry.shapes.Shape
ndimattributeinstance attribute#
simgeometry.shapes.ShapeView sourcendim = ndimbounding_boxproperty#
simgeometry.shapes.ShapeView sourcebounding_box: BoundingBoxReturn the bounding box.
invertedproperty#
simgeometry.shapes.ShapeView sourceinverted: boolReturn whether this object represents an inverted region.
lower_boundproperty#
simgeometry.shapes.ShapeView sourcelower_bound: tuple[float, ...]Return the lower coordinate bounds.
upper_boundproperty#
simgeometry.shapes.ShapeView sourceupper_bound: tuple[float, ...]Return the upper coordinate bounds.
get_bound_verticesmethod#
simgeometry.shapes.ShapeView sourcedef get_bound_vertices(slice_axis: int) -> xp.ndarrayReturn vertices that bound the shape.
get_indices_in_objectmethod#
simgeometry.shapes.ShapeView sourcedef 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#
simgeometry.shapes.ShapeView sourcedef level_set(points: Array) -> ArrayLevel-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
bound
Assumptions:
- an inverted shape is the complement of its geometry:
contains_pointsis negated and the level set flips sign - equality in the bound where
level_set_exactis true: the Euclidean signed distance - shapes known only by their membership test (
has_level_setFalse) raiseNotImplementedError
node_maskmethod#
simgeometry.shapes.ShapeView sourcedef node_mask(grid: Grid) -> np.ndarrayReturn 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#
simgeometry.shapes.ShapeView sourcedef set_bounding_box(lower_bound: tuple[float, ...], upper_bound: tuple[float, ...]) -> NoneSet the bounding box for the shape.
Inherited from simgeometry.api.GeometryAPI
cell_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef cut_edges(grid, **kwargs)Locate all detected grid-edge surface hits, without solver clamping.
diagnosemethod#
simgeometry.api.GeometryAPIView sourcedef diagnose(grid, **kwargs)Report sampled overlaps, unresolved components, and short cut distances.
differencemethod#
simgeometry.api.GeometryAPIView sourcedef difference(other)evaluatemethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef export(path, **kwargs)Export a sampled mesh as NPZ, OBJ, or STL (3D only).
intersect_segmentmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef intersection(other)level_set_fieldmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef plot(ax=None, **kwargs)Draw without displaying and return axes for composition.
rotatedmethod#
simgeometry.api.GeometryAPIView sourcedef rotated(angle, *, axis=(0, 0, 1), origin=None)Return a rotated snapshot; angle is in degrees, about origin (default 0).
sample_interiormethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef sample_surface(count, *, rng=None, resolution=64, bounds=None)Uniform-by-length/area samples from the faceted boundary mesh.
scaledmethod#
simgeometry.api.GeometryAPIView sourcedef scaled(factors, *, origin=None)Return a snapshot scaled by a nonzero scalar or per-axis factors.
showmethod#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef 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#
simgeometry.api.GeometryAPIView sourcedef transformed(matrix, offset=None)Return an affine-transformed snapshot; the source is unchanged.
translatedmethod#
simgeometry.api.GeometryAPIView sourcedef translated(offset)Return a translated snapshot (unlike legacy in-place translate).
unionmethod#
simgeometry.api.GeometryAPIView sourcedef union(other)yee_fractionsmethod#
simgeometry.api.GeometryAPIView sourcedef 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.