API Reference#

The public functions of magpylib-material-response, grouped by module.

Demagnetization solver — demag#

magpylib_material_response.demag.apply_demag(collection, susceptibility=None, inplace=False, pairs_matching=False, max_dist=0, split=1, min_log_time=None, style=None, solver='direct', solver_tol=1e-06, max_iter=50)#

Computes the interaction between all collection magnets and fixes their polarization.

Parameters:
  • collection (magpylib.Collection object with n magnet sources) – Each magnet source in collection is treated as a magnetic cell.

  • susceptibility (array_like, shape (n,)) – Vector of n magnetic susceptibilities of the cells. If not defined, values are searched at object level or parent level if needed.

  • inplace (bool) – If False, applies demagnetization on a copy of the input collection and returns the demagnetized collection

  • pairs_matching (bool) – If True, equivalent pair of interactions are identified and unique pairs are calculated only once and copied to duplicates. This parameter is not compatible with max_dist or split and applies only cuboid cells. Forces the legacy point-matched tensor for all pairs.

  • max_dist (float) – Positive number representing the max_dimension to distance ratio for each pair of interacting cells. This filters out far interactions. If max_dist=0, all interactions are calculated. This parameter is not compatible with pairs_matching or split and applies only cuboid cells. Forces the legacy point-matched tensor for all pairs.

  • split (int) – Number of times the sources list is split before getH calculation ind demag tensor calculation. This parameter is not compatible with pairs_matching or max_dist. Forces the legacy point-matched tensor for all pairs.

  • min_log_time – Minimum logging time in seconds. If computation time is below this value, step will not be logged. If None (default), the value set by magpylib_material_response.configure_logging() is used (1.0 s by default).

  • style (dict) – Set collection style. If inplace=False only affects the copied collection

  • solver ({"direct", "iterative"}) – Linear solver to use. Both solvers share the same interaction model (analytical volume-averaged Newell tensor for parallel cuboid cells, point matching otherwise) and agree to solver_tol. "direct" (default) builds the dense Q matrix and calls numpy.linalg.solve() — exact within floating-point precision. "iterative" solves matrix-free with scipy.sparse.linalg.gmres() and a diagonal Jacobi preconditioner; uniform-grid clusters of cells use an FFT-accelerated \(O(n \log n)\) matvec.

  • solver_tol (float) – Relative residual tolerance passed to GMRES when solver="iterative".

  • max_iter (int) – Maximum number of GMRES iterations when solver="iterative". Non-convergence raises RuntimeError.

Return type:

demagnetized collection or None (if inplace=True)

magpylib_material_response.demag.demag_tensor(src_list, pairs_matching=False, split=False, max_dist=0, min_log_time=None)#

Compute the demagnetization tensor T for n sources.

By default the tensor is assembled with the unified pair rule: the analytical volume-averaged Newell tensor for parallel Cuboid cells (generalized to different sizes) and point matching (see Chadebec 2006) otherwise. The legacy options pairs_matching, split and max_dist force the historical point-matching evaluation for all pairs.

Parameters:
  • src_list (sequence of magpylib magnet sources) – Each source is treated as a magnetic cell.

  • pairs_matching (bool) – If True, equivalent pair of interactions are identified and unique pairs are calculated only once and copied to duplicates. Implies point matching.

  • split (int) – Number of times the sources list is split before getH calculation ind demag tensor calculation. Implies point matching.

  • max_dist (float) – Maximum distance-to-dimension ratio; farther interactions are dropped. Implies point matching.

  • min_log_time – Minimum logging time in seconds. If computation time is below this value, step will not be logged.

Returns:

  • Demagnetization tensor (ndarray, shape (3,n,n,3), pre-mu_0:) – T[k, i, j, m] = -N_mk(pos_j - pos_i) / mu_0

  • TODO (allow multi-point matching)

magpylib_material_response.demag.get_susceptibilities(sources, susceptibility=None)#

Return a list of length (len(sources)) with susceptibility values Priority is given at the source level, however if value is not found, it is searched up the parent tree, if available. Raises an error if no value is found when reached the top level of the tree.

magpylib_material_response.demag.get_H_ext(*sources)#

Return a list of length (len(sources)) with H_ext values.

The H_ext attribute is interpreted as the externally applied flux density in Tesla (B-field convention). Priority is given at the source level; if no value is found, the parent tree is searched. Defaults to zero at the top of the tree.

Meshing — meshing#

magpylib_material_response.meshing.mesh_all(obj, target_elems, min_elems=8, per_child_elems=False, inplace=False, **kwargs)#

Mesh all the supported objects into a Collection of equivalent children, replacing them with their meshed version.

Parameters:
  • obj (Collection, magnet.Cuboid, magnet.Cylinder, magnet.CylinderSegment, magnet.TriangularMesh) – The object to be meshed. If a Collection, all its children will be meshed. BaseCurrent objects are allowed but not meshed.

  • target_elems (int) – Target number of elements for the meshing.

  • min_elems (int, optional, default=8) – Minimum number of elements allowed in the mesh.

  • per_child_elems (bool, optional, default=False) – If False, target_elems will be divided among children objects based on their volumes. If True, all children objects will have the same target_elems.

  • inplace (bool, optional, default=False) – If True, meshing will be performed in-place, modifying the original object. If False, a new object will be created.

Returns:

obj – The meshed object or a new object with meshed components.

Return type:

magpy.Collection, original object

Raises:

TypeError – If there are incompatible objects found.

magpylib_material_response.meshing.mesh_Cuboid(cuboid, target_elems, verbose=False, **kwargs)#

Split Magpylib cuboid up into small cuboid cells

Parameters:
  • cuboid (magpylib.magnet.Cuboid object) – Input object to be discretized

  • target_elems (triple of int or int) – Target number of cells. If target_elems is a triple of integers, the number of divisions corresponds respectively to the x,y,z components of the unrotated cuboid in the global CS. If an integer, the number of divisions is apportioned proportionally to the cuboid dimensions. The resulting meshing cuboid cells are then the closest to cubes as possible.

  • verbose (bool) – If True, prints out meshing information

Returns:

discretization – Collection of Cuboid cells

Return type:

magpylib.Collection

magpylib_material_response.meshing.slice_Cuboid(cuboid, shift=0.5, axis='z', **kwargs)#

Slice a cuboid magnet along a specified axis and return a collection of the resulting parts.

Parameters:
  • cuboid (magpy.magnet.Cuboid) – The cuboid to be sliced.

  • shift (float, optional, default=0.5) – The relative position of the slice along the specified axis, ranging from 0 to 1 (exclusive).

  • axis ({'x', 'y', 'z'}, optional, default='z') – The axis along which to slice the cuboid.

  • **kwargs – Additional keyword arguments to pass to the magpy.Collection constructor.

Returns:

coll – A collection of the resulting parts after slicing the cuboid.

Return type:

magpy.Collection

Raises:

ValueError – If the shift value is not between 0 and 1 (exclusive).

magpylib_material_response.meshing.mesh_Cylinder(cylinder, target_elems, verbose=False, **kwargs)#

Split Cylinder or CylinderSegment up into small cylindrical or cylinder segment cells. In case of the cylinder, the middle cells are cylinders, all other being cylinder segments.

Parameters:
  • cylinder (magpylib.magnet.Cylinder or magpylib.magnet.CylinderSegment object) – Input object to be discretized

  • target_elems (int) – Target number of cells. If target_elems is a triple of integers, the number of divisions corresponds respectively to the divisions along the circumference, over the radius and over the height. If an integer, the number of divisions is apportioned proportionally to the cylinder (or cylinder segment) dimensions. The resulting meshing cylinder segment cells are then the closest to cubes as possible.

  • verbose (bool) – If True, prints out meshing information

Returns:

discretization – Collection of Cylinder and CylinderSegment cells

Return type:

magpylib.Collection

magpylib_material_response.meshing.mesh_TriangularMesh(obj, target_elems, minratio=1.5, mindihedral=10.0, quality=True, verbose=False, **kwargs)#

Split a TriangularMesh magnet into conforming Tetrahedron cells using TetGen.

TetGen generates a surface-conforming tetrahedral mesh: all tetrahedra are strictly inside the closed surface and no vertex protrudes outside. Cell sizes are controlled via target_elems (sets maxvolume from the object volume). Quality is controlled by minratio and mindihedral.

Parameters:
  • obj (magpy.magnet.TriangularMesh) – Input object to be discretized.

  • target_elems (int) – Target number of tetrahedra. Sets maxvolume = obj.volume / target_elems.

  • minratio (float, default 1.5) – TetGen quality constraint — maximum radius-edge ratio. Lower values give better-shaped tetrahedra but more cells. 1.0 is near-equilateral; 2.0 is permissive.

  • mindihedral (float, default 10.0) – TetGen quality constraint — minimum dihedral angle in degrees. Prevents flat/sliver tetrahedra.

  • quality (bool, default True) – If True, TetGen inserts Steiner points to meet the volume constraint set by target_elems and improve element quality. If False, only the input surface vertices are tetrahedralized and target_elems has no effect.

  • verbose (bool) – If True, prints out meshing information.

Returns:

discretization – Collection of Tetrahedron cells.

Return type:

magpy.Collection

magpylib_material_response.meshing.mesh_thin_CylinderSegment_with_cuboids(cyl_seg, target_elems, ratio_limit=10, match_volume=True, **kwargs)#

Split-up a Magpylib thin-walled cylinder segment into cuboid cells. Over the thickness, only one layer of cells is used.

Parameters:
  • cyl_seg (magpylib.magnet.CylinderSegment object) – CylinderSegment object to be discretized

  • target_elems (int or tuple of int,) – If target_elems is a tuple of integers, the cylinder segment is respectively divided over circumference and height, if an integer, divisions are inferred to build cuboids with close to squared faces.

  • ratio_limit (positive number,) – Sets the r2/(r2-r1) limit to be considered as thin-walled, r1 being the inner radius.

  • match_volume (bool,) – If True, it ensures the meshed volume equals the original CylinderSegment by allowing mesh elements overlapping. This improves the field calculation approximation accuracy.

Returns:

discretization – Collection of Cuboid cells

Return type:

magpylib.Collection

Coil construction — polyline#

magpylib_material_response.polyline.create_polyline_fillet(polyline, max_radius, N)#

Create a filleted polyline with specified maximum radius and number of points.

Parameters:
  • polyline (list | ndarray) – List or array of vertices forming the polyline with shape (N, 2) or (N, 3).

  • max_radius (float) – Maximum radius of the fillet.

  • N (int) – Number of points to interpolate along the fillet.

Returns:

Array of filleted points with shape (M, 2) or (M, 3), where M depends on the number of filleted segments.

Return type:

ndarray

magpylib_material_response.polyline.move_grid_along_polyline(verts, grid)#

Move a grid along a polyline, defined by the vertices.

Parameters:
  • verts (ndarray) – Array of polyline vertices, where n is the number of vertices and d is the dimension.

  • grid (ndarray) – Array of grid points to move along the polyline, where m is the number of points.

Returns:

Array of moved grid points along the polyline, with the same dimensions as the input grid.

Return type:

ndarray

Structure analysis and FFT kernels — demag_fft#

magpylib_material_response.demag_fft.analyze_collection(sources, atol=1e-09)#

Partition magnet objects into structure clusters (see analyze_structure()).

Convenience wrapper that extracts positions (barycentre when available), dimensions, orientations and the cuboid mask from a sequence of magpylib magnet objects (e.g. collection.sources_all) and returns the cluster list together with the extracted positions.

Returns:

magpylib_material_response.demag_fft.analyze_structure(positions, dimensions, rotations, is_cuboid, atol=1e-09)#

Partition cells into structure clusters covering every cell exactly once.

Parameters:
  • positions (ndarray (n, 3)) – Cell barycentres, world frame.

  • dimensions (ndarray (n, 3)) – Cuboid side lengths (rows for non-cuboid cells are ignored).

  • rotations (scipy Rotation, length n) – Per-cell orientations.

  • is_cuboid (ndarray (n,) of bool) – Which cells are magpylib.magnet.Cuboid instances.

  • atol (float) – Quaternion comparison tolerance.

Returns:

clusters – Every cell index appears in exactly one cluster. Each dict has keys:

  • kind : "grid" | "loose" | "generic"

  • indices : ndarray(int) — original cell indices

  • dim : tuple(3) cell side lengths (cuboid kinds only)

  • r_common : scipy Rotation — common orientation (cuboid kinds)

  • is_identity: bool (cuboid kinds)

  • grid kind adds shape, spacing, origin, order (order indexes within the cluster).

Return type:

list[dict]

magpylib_material_response.demag_fft.detect_uniform_grid(positions, dimensions, rotations, atol=1e-09)#

Detect whether all cells form one uniform grid of identical cuboids.

Convenience wrapper around _detect_grid() that first checks for identical dimensions and a single common rotation. For a non-identity common rotation, the grid is detected in the cells’ local frame.

Returns None on failure, else a dict with keys shape, spacing, origin, order, dim, r_common, is_identity.

magpylib_material_response.demag_fft.build_fft_kernel(grid_shape, spacing, dim)#

Build the 6-component Newell demag kernel on the doubled grid, FFTed.

Parameters:
  • grid_shape (tuple (Nx, Ny, Nz))

  • spacing (tuple (px, py, pz)) – Grid pitch per axis (>= cell size for non-overlapping cells).

  • dim (tuple (sx, sy, sz)) – Cell side lengths.

Returns:

kernel_fft – Components in order (Nxx, Nyy, Nzz, Nxy, Nxz, Nyz). The last axis is the half-spectrum produced by np.fft.rfftn applied to the doubled real-space kernel.

Return type:

ndarray, shape (6, 2*Nx, 2*Ny, Nz+1), complex

magpylib_material_response.demag_fft.demag_fft_matvec(M, kernel_fft, grid_shape)#

Compute the demag matvec H = T @ M via 3-D FFT convolution.

Parameters:
  • M (ndarray, shape (Nx, Ny, Nz, 3)) – Polarization per cell, in the grid’s local (axis-aligned) frame.

  • kernel_fft (ndarray) – Output of build_fft_kernel().

  • grid_shape (tuple (Nx, Ny, Nz))

Returns:

HT @ M with T = -N (the demag field scaled by mu_0, matching the dense demag matrix used in apply_demag()).

Return type:

ndarray, shape (Nx, Ny, Nz, 3)

Analytical Newell tensors — newell#

magpylib_material_response.newell.demag_block(disp, dim)#

Compute the 3x3 demag tensor block N for given displacement and dimension.

Parameters:
  • disp (array_like, shape (..., 3)) – Centre-to-centre displacement obs - src (observer minus source).

  • dim (array_like, shape (3,)) – Common cell side lengths (a, b, c).

Returns:

N – Symmetric demag tensor block. N_ii are diagonal demag factors (sum to 1 for disp = 0); off-diagonal terms are mutual coupling.

Return type:

ndarray, shape (…, 3, 3)

magpylib_material_response.newell.demag_block_general(disp, dim_src, dim_obs)#

3x3 volume-averaged demag tensor between two parallel rectangular prisms.

Generalizes demag_block() to source and observer prisms of different side lengths (both axis-aligned in the same frame).

Parameters:
  • disp (array_like, shape (..., 3)) – Centre-to-centre displacement obs - src.

  • dim_src (array_like, shape (3,)) – Source prism side lengths (a1, b1, c1).

  • dim_obs (array_like, shape (3,)) – Observer prism side lengths (a2, b2, c2).

Returns:

NN_mk such that the H-field volume-averaged over the observer prism per unit magnetization of the source prism is H = -N @ M. Satisfies the volume-weighted reciprocity V_obs * N(d; s, o) = V_src * N(d; o, s).T.

Return type:

ndarray, shape (…, 3, 3)

magpylib_material_response.newell.demag_tensor_newell(positions, dim, mu_0)#

Volume-averaged demag tensor for n identical axis-aligned cuboids.

Parameters:
  • positions (array_like, shape (n, 3)) – Centre positions of the cells (world frame).

  • dim (array_like, shape (3,)) – Common side lengths (a, b, c).

  • mu_0 (float) – Magnetic constant (magpylib.mu_0).

Returns:

T – Same layout as magpylib_material_response.demag.demag_tensor(): T[k, i, j, m] = -N_mk(pos[j] - pos[i]) / mu_0: component m of the volume-averaged field over observer cell j per unit polarization along axis k of source cell i. The returned tensor is pre-mu_0; multiplying by mu_0 (as apply_demag does) yields the dimensionless -N.

Return type:

ndarray, shape (3, n, n, 3)

magpylib_material_response.newell.self_demag_factors(dim)#

Return (Nxx, Nyy, Nzz) for an isolated rectangular prism.

Sum to 1 by Brown’s identity; equal to 1/3 each for a cube.

Utilities#

magpylib_material_response.utils.to_json(*objs, **json_kwargs)#

Serialize one or more magpylib objects to a JSON string.

json_kwargs are forwarded to json.dumps() (e.g. indent=2).

magpylib_material_response.utils.from_json(s)#

Deserialize a JSON string produced by to_json().

Returns a list of magpylib objects.

magpylib_material_response.get_dataset(name)#
magpylib_material_response.configure_logging(level=None, enable_colors=None, show_time=None, sink=None, min_log_time=None)#

Enable and configure logging for the package.

The library is silent by default. Call this function from an application to see log messages.

Parameters:
  • level (str | None) – Log level. Defaults to "INFO". Can be overridden with the MAGPYLIB_LOG_LEVEL environment variable.

  • enable_colors (bool | None) – Enable colored output. Defaults to True. Can be overridden with MAGPYLIB_LOG_COLORS.

  • show_time (bool | None) – Show timestamps. Defaults to True. Can be overridden with MAGPYLIB_LOG_TIME.

  • sink (Any) – Loguru sink (file path, stream, or callable). Defaults to sys.stderr, following the convention for library logs.

  • min_log_time (float | None) – Default minimum duration (in seconds) for timelog() blocks to emit a record. Steps that complete faster than this are not logged. Functions like apply_demag honour this value when their own min_log_time argument is left at its default. Can be overridden with MAGPYLIB_LOG_MIN_TIME. Defaults to 1.0.

Returns:

The id of the added sink, so callers can remove it with loguru.logger.remove(handler_id) if desired.

Return type:

int

magpylib_material_response.disable_logging()#

Disable logging output from the package.

Removes any sinks previously added by configure_logging() and disables the package via logger.disable. Other sinks configured by the application are left untouched.

Return type:

None