API reference¶
This reference documents the supported public API. Parameter and return-value sections use the NumPy docstring convention and are rendered by Sphinx Napoleon. Backend implementation classes and private helpers are intentionally omitted. The top-level aliases select a backend automatically; the Rust implementation is the documented default.
Magnets and arrangements¶
microcubed.Magnet¶
- class microcubed.backends.rust.RustMagnet(size, center, magnetization)[source]
Cuboid magnet evaluated by the integrated parallel Rust field kernel.
- Parameters:
size, center, magnetization (array-like) – Three Cartesian components in the project’s length unit and A/m.
- Bfield(points: ndarray) ndarray[source]
Evaluate the exterior magnetic flux density.
- Parameters:
points (array-like) – Observation points with shape
(3, N).- Returns:
numpy.ndarray – Flux density
(Bx, By, Bz)in tesla with shape(3, N).
- Hfield(*args, **kwargs)
Calculate the magnetic field strength.
- dBfield(points: ndarray) ndarray[source]
Evaluate the exterior magnetic-flux-density gradient.
- Parameters:
points (array-like) – Observation points with shape
(3, N).- Returns:
numpy.ndarray – Gradient with shape
(3, 3, N). The first axis is the derivative direction and the second is the field component.
- dHfield(*args, **kwargs)
Calculate the magnetic field strength gradient.
- classmethod from_bbox(p1: list | ndarray, p2: list | ndarray, magnetization: list | ndarray) BasicMagnet
Create a Magnet from two points defining the bounding box.
- Parameters:
p1 (np.ndarray) – First point of the bounding box.
p2 (np.ndarray) – Second point of the bounding box.
mag (np.ndarray, optional) – Magnetization of the bar magnet.
- Returns:
BasicMagnet – Magnet with the given bounding box and saturation magnetization.
- mirrored(x: float | None = None, y: float | None = None, z: float | None = None) BasicMagnet
Create a new cuboid magnet instance mirrored across plane(s).
- Parameters:
x (float | None) – Value of x axis to mirror against.
y (float | None) – Value of y axis to mirror against.
z (float | None) – Value of z axis to mirror against.
- Returns:
BasicMagnet – Mirrored magnet.
- moved_by(diff: ndarray)
Create a new magnet with the center moved by the given vector.
- Parameters:
center (np.ndarray) – New center position (3, 1).
- Returns:
BasicMagnet – New Magnet with the center moved by the given vector.
- moved_to(center: ndarray)
Create a new magnet with the center moved to the given position.
- Parameters:
center (np.ndarray) – New center position (3, 1).
- Returns:
BasicMagnet – New Magnet with the center moved to the given position.
- overlapping(other: BasicMagnet) bool
Calculate the axis-aligned ‘overlapping’ between this and another cuboid magnet.
- Parameters:
other (BasicMagnet) – Another magnet instance to check the overlapping to.
- Returns:
bool
- plot_1d(**kwargs)
Plot a one-dimensional field section; see
microcubed.viz.plot_1d().
- plot_2d(**kwargs)
Plot a two-dimensional field section; see
microcubed.viz.plot_2d().
- plot_3d(**kwargs)
Plot a three-dimensional field section; see
microcubed.viz.plot_3d().
- touching(other: BasicMagnet) bool
Calculate the axis-aligned ‘touching’ between this and another cuboid.
- Parameters:
other (BasicMagnet) – Another magnet instance to check the touching to.
- Returns:
bool
- union_boundary(plane: str = 'xy', *, atol: float | None = None) list[ndarray]
Return closed boundary loops of the union of projected cuboid footprints.
- Parameters:
plane (str) – Projection plane:
xy,xzoryz(case-insensitive). Reversed spellings are aliases with canonical axis order, as inchull_points();yxstill returns x then y.atol (float, optional) – Absolute coordinate snapping tolerance in the geometry’s length unit. By default, use 32 machine epsilons times the largest absolute projected coordinate to remove round-off seams. Set zero to disable snapping. Features smaller than this tolerance can collapse.
- Returns:
list of numpy.ndarray – Closed
(2, N)loops, suitable forax.plot(*loop). Outer loops are counterclockwise; holes are clockwise. Disconnected or merely corner-touching components have separate loops. An empty arrangement returns an empty list. Loop ordering is not a component hierarchy.
Notes
This is a 2D projection, not a slice or a 3D surface. Footprints may overlap even when their cuboids are separated along the omitted axis. Unlike a convex hull, the union boundary retains concavities and holes.
microcubed.Arrangement¶
- class microcubed.backends.rust.RustArrangement(magnets=None, validate: bool = True)[source]
Arrangement summed by the integrated parallel Rust field kernel.
- Parameters:
magnets (sequence of Magnet, optional) – Cuboids included in the superposition.
validate (bool, default=True) – Check that cuboids do not overlap.
- Bfield(points: ndarray) ndarray[source]
Evaluate the summed magnetic flux density at observation points.
- Parameters:
points (array-like) – Observation points with shape
(3, N).- Returns:
numpy.ndarray – Flux density in tesla with shape
(3, N).
- Hfield(*args, **kwargs)
Calculate the magnetic field strength.
- dBfield(points: ndarray) ndarray[source]
Evaluate the summed magnetic-flux-density gradient.
- Parameters:
points (array-like) – Observation points with shape
(3, N).- Returns:
numpy.ndarray – Gradient in field units per length with shape
(3, 3, N).
- dHfield(*args, **kwargs)
Calculate the magnetic field strength gradient.
- classmethod from_shape(shape, t: float, delta: float | tuple[float, float], mag: list | ndarray, *, z: float = 0, bounds: tuple[float, float, float, float] | None = None) BasicArrangement
Extrude and decompose a rasterized 2D shape into cuboid magnets.
The shape can be polygon vertices, a
matplotlib.path.Path, or a callableshape(x, y). Callable shapes require explicit bounds. Occupied grid cells are greedily merged into large, non-overlapping rectangles before extrusion by thicknesst.
- classmethod from_voronoi_grains(grains, mag, *, thickness: float | None = None, z: float = 0) BasicArrangement
Convert rasterized 2D or 3D Voronoi grains to cuboid magnets.
For 2D grains,
thicknessis required andzis the extrusion center. Three-dimensional grains already contain their z extent, sothicknessmust be omitted.magcan be one vector shared by all grains, one vector per grain, or a callable receiving all seed points and returning either form.
- mirrored(x: float | None = None, y: float | None = None, z: float | None = None) BasicArrangement
Create a mirrored copy of the arrangement.
- moved_by(diff: ndarray)
Returns a copy of the arrangement moved in its center by the given vector.
- moved_to(center: ndarray)
Create a new magnet with the center moved to the given position.
- Parameters:
center (np.ndarray) – New center position (3, 1).
- Returns:
BasicMagnet – New Magnet with the center moved to the given position.
- plot_1d(**kwargs)
Plot a one-dimensional field section; see
microcubed.viz.plot_1d().
- plot_2d(**kwargs)
Plot a two-dimensional field section; see
microcubed.viz.plot_2d().
- plot_3d(**kwargs)
Plot a three-dimensional field section; see
microcubed.viz.plot_3d().
- union_boundary(plane: str = 'xy', *, atol: float | None = None) list[ndarray]
Return closed boundary loops of the union of projected cuboid footprints.
- Parameters:
plane (str) – Projection plane:
xy,xzoryz(case-insensitive). Reversed spellings are aliases with canonical axis order, as inchull_points();yxstill returns x then y.atol (float, optional) – Absolute coordinate snapping tolerance in the geometry’s length unit. By default, use 32 machine epsilons times the largest absolute projected coordinate to remove round-off seams. Set zero to disable snapping. Features smaller than this tolerance can collapse.
- Returns:
list of numpy.ndarray – Closed
(2, N)loops, suitable forax.plot(*loop). Outer loops are counterclockwise; holes are clockwise. Disconnected or merely corner-touching components have separate loops. An empty arrangement returns an empty list. Loop ordering is not a component hierarchy.
Notes
This is a 2D projection, not a slice or a 3D surface. Footprints may overlap even when their cuboids are separated along the omitted axis. Unlike a convex hull, the union boundary retains concavities and holes.
Backend selection¶
- microcubed.get_backend(name: str = 'auto') Backend[source]¶
Return a backend namespace without changing the process-wide default.
- Parameters:
name ({“auto”, “numpy”, “rust”}, default=”auto”) – Requested backend.
"auto"selects Rust when its compiled extension is available and otherwise selects NumPy.- Returns:
Backend – Namespace exposing matching
Magnet,Arrangement, and shape decomposition helpers.- Raises:
ValueError – If
nameis not a supported backend selector.
- microcubed.available_backends() tuple[str, ...][source]¶
Return calculation backends importable in the current environment.
- Returns:
tuple of str –
("numpy",)when the extension is unavailable, otherwise("numpy", "rust").
- microcubed.set_backend(name: str = 'auto')[source]¶
Set the implementation used by top-level
MagnetandArrangement.- Parameters:
name ({“auto”, “numpy”, “rust”}, default=”auto”) – Backend to select.
"auto"chooses Rust when its extension is importable and otherwise chooses NumPy.- Returns:
microcubed.backends.Backend – The selected backend namespace.
Shape decomposition and grains¶
- microcubed.cuboidize(shape, t, delta, mag, **kwargs)[source]¶
Approximate an extruded two-dimensional shape with cuboids.
- Parameters:
shape (array-like, matplotlib.path.Path, or callable) – Polygon vertices, a Matplotlib path, or a callable Boolean mask.
t (float) – Extrusion thickness.
delta (float or tuple of float) – Maximum raster-cell spacing.
mag (array-like) – Magnetization vector in A/m.
- Returns:
Arrangement – A non-overlapping arrangement representing the rasterized shape.
- microcubed.cuboidize_voronoi(grains, mag, **kwargs)[source]¶
Convert rasterized Voronoi grains into a compact cuboid arrangement.
- Parameters:
grains (VoronoiGrains) – Two- or three-dimensional rasterized grains.
mag (array-like or callable) – Shared, per-grain, or seed-dependent magnetization in A/m.
- Returns:
Arrangement – Cuboids representing the occupied grain cells.
- class microcubed.VoronoiGrains(labels: ndarray, seeds: ndarray, origin: ndarray, size: ndarray, cell_size: ndarray)[source]¶
A rasterized two- or three-dimensional Voronoi tessellation.
Array axes are ordered like image/volume data:
(y, x)in 2D and(z, y, x)in 3D. Coordinate columns and the values inorigin,size, andcell_sizeremain in Cartesian(x, y[, z])order. Cells outside an optional domain mask have label-1.- property cell_centers: tuple[ndarray, ...]¶
Return one-dimensional cell-center coordinates in Cartesian order.
- property dimension: int¶
Spatial dimension of the tessellation (2 or 3).
- property equivalent_diameters: ndarray¶
Circle- or sphere-equivalent diameter of every rasterized grain.
- property grain_count: int¶
Number of represented grains.
- property grain_measures: ndarray¶
Area (2D) or volume (3D) represented by every grain.
- microcubed.generate_voronoi_grains(size: Sequence[float] | ndarray, grain_size: Real, cell_size: Real | Sequence[float] | None = None, *, origin: Sequence[float] | ndarray | None = None, mask: ndarray | None = None, seed: int | Generator | None = None) VoronoiGrains[source]¶
Generate rasterized Voronoi grains in a 2D rectangle or 3D cuboid.
grain_sizeis the target equivalent circle (2D) or sphere (3D) diameter. It determines the seed count automatically.cell_sizeis the maximum raster spacing and defaults to one fifth ofgrain_size. The returned spacing may be slightly smaller so that the domain is tiled exactly. An optional Booleanmaskrestricts the occupied cells; this makes the function directly compatible withrasterize_shape().Seeds are sampled without replacement from occupied cell centers. Thus every requested grain is represented even on comparatively coarse grids.
- microcubed.generate_voronoi_grains_from_shape(shape: Sequence[Sequence[float]] | ndarray | Path | Callable[[ndarray, ndarray], ndarray], grain_size: Real, cell_size: Real | Sequence[float] | None = None, *, bounds: tuple[float, float, float, float] | None = None, seed: int | Generator | None = None) VoronoiGrains[source]¶
Generate 2D Voronoi grains clipped to an arbitrary rasterized shape.
Shape representations and boundary sampling follow
rasterize_shape(). Grain IDs outside the shape are-1.
- microcubed.geometry.rasterize_shape(shape: Sequence[Sequence[float]] | ndarray | Path | Callable[[ndarray, ndarray], ndarray], delta: Real | Sequence[float], *, bounds: tuple[float, float, float, float] | None = None) tuple[ndarray, ndarray, ndarray][source]¶
Sample a 2D shape at cell centers on a grid no coarser than
delta.shapecan be polygon vertices, amatplotlib.path.Path, or a callableshape(x, y)returning a Boolean mask. Callable shapes require explicit(xmin, ymin, xmax, ymax)bounds.
- microcubed.geometry.rectangle_union_boundary(rectangles: ndarray, *, atol: float | None = None) list[ndarray][source]¶
Trace oriented boundary rings of axis-aligned rectangles.
Input rows are
(xmin, ymin, xmax, ymax). A sweep along compressed x coordinates keeps only one y coverage vector in memory. Coordinates closer thanatolare snapped together to remove floating-point seams; the default is 32 machine epsilons times the largest absolute input coordinate.
Sampling and visualisation¶
The following functions are also re-exported from microcubed.
- microcubed.viz.sample_field(source, *, x: Real | tuple[float, float, int] | ndarray | list[float], y: Real | tuple[float, float, int] | ndarray | list[float], z: Real | tuple[float, float, int] | ndarray | list[float], what: str = 'Bfield') tuple[tuple[ndarray, ndarray, ndarray], ndarray][source]¶
Evaluate a field on an x/y/z section.
A scalar fixes an axis;
(start, stop, count)or a one-dimensional array samples it. The returned field retains all three spatial axes, including length-one axes, which makes sections unambiguous.- Parameters:
source (Magnet or Arrangement) – Object providing the field method named by
what.x, y, z (float, tuple of float and int, or numpy.ndarray) – Fixed coordinate, uniform range, or explicit sample coordinates.
what (str, default=”Bfield”) – Field method to evaluate, such as
"Bfield"or"dBfield".
- Returns:
tuple – Cartesian coordinate arrays followed by a field array whose trailing three dimensions correspond to x, y, and z.
- microcubed.viz.plot_1d(source, *, x: Real | tuple[float, float, int] | ndarray | list[float], y: Real | tuple[float, float, int] | ndarray | list[float], z: Real | tuple[float, float, int] | ndarray | list[float], what: str = 'Bfield', component: Literal['x', 'y', 'z'] | int | tuple[Literal['x', 'y', 'z'] | int, Literal['x', 'y', 'z'] | int] | Literal['magnitude'] | None = None, ax: Axes | None = None, **plot_kwargs) tuple[Figure, Axes][source]¶
Plot a field along one varying coordinate section.
- Parameters:
source (Magnet or Arrangement) – Field source to sample.
x, y, z (float, tuple, or numpy.ndarray) – Exactly one coordinate must vary.
what (str, default=”Bfield”) – Field method to evaluate.
component (str, int, tuple, or None, default=None) – Vector component, gradient component pair, or magnitude.
ax (matplotlib.axes.Axes, optional) – Existing axes to draw into.
- Returns:
tuple of matplotlib.figure.Figure and matplotlib.axes.Axes – Figure and axes containing the line plot.
- microcubed.viz.plot_2d(source, *, x: Real | tuple[float, float, int] | ndarray | list[float], y: Real | tuple[float, float, int] | ndarray | list[float], z: Real | tuple[float, float, int] | ndarray | list[float], what: str = 'Bfield', component: Literal['x', 'y', 'z'] | int | tuple[Literal['x', 'y', 'z'] | int, Literal['x', 'y', 'z'] | int] | Literal['magnitude'] | None = None, ax: Axes | None = None, colorbar: bool = True, **mesh_kwargs) tuple[Figure, Axes][source]¶
Plot a scalar field component on a two-dimensional section.
- Parameters:
source (Magnet or Arrangement) – Field source to sample.
x, y, z (float, tuple, or numpy.ndarray) – Exactly two coordinates must vary.
what (str, default=”Bfield”) – Field method to evaluate.
component (str, int, tuple, or None, default=None) – Vector component, gradient component pair, or magnitude.
ax (matplotlib.axes.Axes, optional) – Existing axes to draw into.
colorbar (bool, default=True) – Add a colorbar for the sampled values.
- Returns:
tuple of matplotlib.figure.Figure and matplotlib.axes.Axes – Figure and axes containing the field map.
- microcubed.viz.plot_3d(source, *, x: Real | tuple[float, float, int] | ndarray | list[float], y: Real | tuple[float, float, int] | ndarray | list[float], z: Real | tuple[float, float, int] | ndarray | list[float], what: str = 'Bfield', component: Literal['x', 'y', 'z'] | int | tuple[Literal['x', 'y', 'z'] | int, Literal['x', 'y', 'z'] | int] | Literal['magnitude'] | None = None, ax: Axes | None = None, max_points: int = 2000, cmap: str = 'viridis', **quiver_kwargs) tuple[Figure, Axes][source]¶
Plot a three-dimensional vector field as magnitude-coloured arrows.
- Parameters:
source (Magnet or Arrangement) – Field source to sample.
x, y, z (float, tuple, or numpy.ndarray) – All three coordinates must vary.
what (str, default=”Bfield”) – Vector field method to evaluate.
ax (matplotlib.axes.Axes, optional) – Existing three-dimensional axes to draw into.
max_points (int, default=2000) – Maximum number of arrows after regular subsampling.
- Returns:
tuple of matplotlib.figure.Figure and matplotlib.axes.Axes – Figure and axes containing the vector-field plot.
Units and coordinate helpers¶
- microcubed.utils.spherical2cartesian(r, theta, phi) tuple[ndarray][source]¶
Converts spherical coordinates to cartesian coordinates.
- Parameters:
r (float) – Distance from origin.
theta (float) – Polar angle.
phi (float) – Azimuthal angle.
- Returns:
tuple – (x, y, z) (x-coordinate, y-coordinate, z-coordinate)
- microcubed.utils.cartesian2spherical(x, y, z) tuple[ndarray][source]¶
Converts cartesian coordinates to spherical coordinates.
- Parameters:
x (float) – x-coordinate.
y (float) – y-coordinate.
z (float) – z-coordinate.
- Returns:
tuple – (r, theta, phi) (distance from origin, polar angle, azimuthal angle)