magpylib.magnet package#
Magnet classes.
- class magpylib.magnet.Cuboid(position=(0, 0, 0), orientation=None, dimension=None, polarization=None, magnetization=None, meshing=None, style=None, **kwargs)#
Bases:
BaseMagnet,BaseTarget,BaseVolume,BaseDipoleMomentCuboid magnet with homogeneous magnetization.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.When
position=(0, 0, 0)andorientation=Nonethe Cuboid sides are parallel to the global coordinate basis vectors and the geometric center of the Cuboid is located in the origin.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.dimension (None | array-like, shape (3,), default None) – Lengths of the cuboid sides (a, b, c) in units (m).
polarization (None | array-like, shape (3,), default None) – Magnetic polarization vector J = mu0*M in units (T), given in the local object coordinates. Sets also
magnetization.magnetization (None | array-like, shape (3,), default None) – Magnetization vector M = J/mu0 in units (A/m), given in the local object coordinates. Sets also
polarization.meshing (None | int | array-like, shape (3,), default None) – Mesh fineness for force computation. Must be a positive integer specifying the target mesh size or an explicit splitting of the cuboid into regular cubic grid cells with shape (n1, n2, n3).
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.dimension (None | ndarray, shape (3,)) – Same as constructor parameter
dimension.polarization (None | ndarray, shape (3,)) – Same as constructor parameter
polarization.magnetization (None | ndarray, shape (3,)) – Same as constructor parameter
magnetization.meshing (int | None) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
volume (float) – Read-only. Object physical volume in units (m³).
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on edges and corners.
Examples
Cuboidmagnets are magnetic field sources. Below we compute the H-field in (A/m) of a cubical magnet with magnetic polarization (0.5, 0.6, 0.7) in units (T) and side lengths (0.01, 0.01, 0.01) at the observer position (0.01, 0.01, 0.01) (m):>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Cuboid(polarization=(0.5, 0.6, 0.7), dimension=(0.01, 0.01, 0.01)) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=0): ... print(H) [16149. 14907. 13665.]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(**kwargs) dict[str, Any]#
Create the plotly mesh3d parameters for a Cuboid Magnet in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property dimension#
Cuboid side lengths (a, b, c) in units (m).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property magnetization#
Magnet magnetization vector (A/m) in local coordinates.
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property polarization#
Magnet polarization vector (T) in local coordinates.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property volume#
Return object volume (m³).
- class magpylib.magnet.Cylinder(position=(0, 0, 0), orientation=None, dimension=None, polarization=None, magnetization=None, meshing=None, style=None, **kwargs)#
Bases:
BaseMagnet,BaseTarget,BaseVolume,BaseDipoleMomentCylinder magnet with homogeneous magnetization.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.When
position=(0, 0, 0)andorientation=Nonethe geometric center of the cylinder lies in the origin of the global coordinate system and the cylinder axis coincides with the global z-axis.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.dimension (None | array-like, shape (2,), default None) – Cylinder diameter and height
(d, h)in units (m).polarization (None | array-like, shape (3,), default None) – Magnetic polarization vector J = mu0*M in units (T), given in the local object coordinates. Sets also
magnetization.magnetization (None | array-like, shape (3,), default None) – Magnetization vector M = J/mu0 in units (A/m), given in the local object coordinates. Sets also
polarization.meshing (int | None, default None) – Mesh fineness for force computation. Must be a positive integer specifying the target mesh size.
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.polarization (None | ndarray, shape (3,)) – Same as constructor parameter
polarization.magnetization (None | ndarray, shape (3,)) – Same as constructor parameter
magnetization.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
volume (float) – Read-only. Object physical volume in units (m³).
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on edges.
Examples
Cylindermagnets are magnetic field sources. Below we compute the H-field in (A/m) of a cylinder magnet with polarization(0.1, 0.2, 0.3)in units (T) and diameter and height0.01 mat the observer position(0.01, 0.01, 0.01)(m):>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Cylinder(polarization=(0.1, 0.2, 0.3), dimension=(0.01, 0.01)) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [4849.913 3883.178 2739.732]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(base=50, **kwargs) dict[str, Any]#
Create the plotly mesh3d parameters for a Cylinder Magnet in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property dimension#
Cylinder diameter and height
(d, h)in units (m).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property magnetization#
Magnet magnetization vector (A/m) in local coordinates.
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property polarization#
Magnet polarization vector (T) in local coordinates.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property volume#
Return object volume (m³).
- class magpylib.magnet.CylinderSegment(position=(0, 0, 0), orientation=None, dimension=None, polarization=None, magnetization=None, meshing=None, style=None, **kwargs)#
Bases:
BaseMagnet,BaseTarget,BaseVolume,BaseDipoleMomentCylinder segment (ring-section) magnet with homogeneous magnetization.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.When
position=(0, 0, 0)andorientation=Nonethe geometric center of the cylinder lies in the origin of the global coordinate system and the cylinder axis coincides with the global z-axis. Section angle 0 corresponds to an x-z plane section of the cylinder.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.dimension (None | array-like, shape (5,), default None) – Cylinder segment size (r1, r2, h, phi1, phi2) where r1 < r2 are inner and outer radii in units (m), phi1 < phi2 are section angles in units (deg), and h is the height in units (m).
polarization (None | array-like, shape (3,), default None) – Magnetic polarization vector J = mu0*M in units (T), given in the local object coordinates. Sets also
magnetization.magnetization (None | array-like, shape (3,), default None) – Magnetization vector M = J/mu0 in units (A/m), given in the local object coordinates. Sets also
polarization.meshing (int | None, default None) – Mesh fineness for force computation. Must be a positive integer specifying the target mesh size.
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.polarization (None | ndarray, shape (3,)) – Same as constructor parameter
polarization.magnetization (None | ndarray, shape (3,)) – Same as constructor parameter
magnetization.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
volume (float) – Read-only. Object physical volume in units (m³).
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
barycenter (ndarray, shape (3,)) – Read-only. Geometric barycenter (= center of mass) of the object.
Notes
Returns (0, 0, 0) on surface, edges, and corners.
Examples
CylinderSegmentmagnets are magnetic field sources. In this example we compute the H-field in (A/m) of such a cylinder segment magnet with polarization (0.1, 0.2, 0.3) (T), inner radius 1 (cm), outer radius 2 (cm), height 1 (cm), and section angles 0 and 45 (deg) at the observer position (2, 2, 2) (cm):>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.CylinderSegment( ... polarization=(0.1, 0.2, 0.3), ... dimension=(0.01, 0.02, 0.01, 0.0, 45.0), ... ) >>> H = src.getH((0.02, 0.02, 0.02)) >>> with np.printoptions(precision=3): ... print(H) [ 807.847 1934.228 2741.168]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(vertices=25, **kwargs) dict[str, Any]#
Create the plotly mesh3d parameters for a Cylinder Segment Magnet in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property barycenter#
Object barycenter.
- property centroid#
Return centroid (m).
- property dimension#
Cylinder segment size (r1, r2, h, phi1, phi2).
r1 < r2 denote inner and outer radii in units (m), phi1 < phi2 the section angles in units (deg), and h the height in units (m).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property magnetization#
Magnet magnetization vector (A/m) in local coordinates.
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property polarization#
Magnet polarization vector (T) in local coordinates.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property volume#
Return object volume (m³).
- class magpylib.magnet.Sphere(position=(0, 0, 0), orientation=None, diameter=None, polarization=None, magnetization=None, style=None, **kwargs)#
Bases:
BaseMagnet,BaseVolume,BaseDipoleMomentSpherical magnet with homogeneous magnetization.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation. Nomeshingparameter is required.When
position=(0, 0, 0)andorientation=Nonethe sphere center is located in the origin of the global coordinate system.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.diameter (float | None, default None) – Diameter of the sphere in units (m).
polarization (None | array-like, shape (3,), default None) – Magnetic polarization vector J = mu0*M in units (T), given in the local object coordinates. Sets also
magnetization.magnetization (None | array-like, shape (3,), default None) – Magnetization vector M = J/mu0 in units (A/m), given in the local object coordinates. Sets also
polarization.style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.polarization (None | ndarray, shape (3,)) – Same as constructor parameter
polarization.magnetization (None | ndarray, shape (3,)) – Same as constructor parameter
magnetization.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
volume (float) – Read-only. Object physical volume in units (m³).
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Examples
Sphereobjects are magnetic field sources. In this example we compute the H-field in (A/m) of a spherical magnet with polarization (0.1, 0.2, 0.3) in units (T) and diameter 0.01 m at the observer position (0.01, 0.01, 0.01) (m):>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0.1, 0.2, 0.3), diameter=0.01) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [3190.561 2552.449 1914.336]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(vertices=15, **kwargs) dict[str, Any]#
Create the plotly mesh3d parameters for a Sphere Magnet in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property diameter#
Diameter of the sphere in units (m).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property magnetization#
Magnet magnetization vector (A/m) in local coordinates.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property polarization#
Magnet polarization vector (T) in local coordinates.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property volume#
Return object volume (m³).
- class magpylib.magnet.Tetrahedron(position=(0, 0, 0), orientation=None, vertices=None, polarization=None, magnetization=None, meshing=None, style=None, **kwargs)#
Bases:
BaseMagnet,BaseTarget,BaseVolume,BaseDipoleMomentTetrahedron magnet with homogeneous magnetization.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.When
position=(0, 0, 0)andorientation=Nonethe Tetrahedron vertex coordinates are the same as in the global coordinate system. The geometric center of the Tetrahedron is determined by its vertices and is not necessarily located in the origin. It can be computed with thebarycenterproperty.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path. When settingvertices, the initial position is set to the barycenter.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.vertices (None | array-like, shape (4, 3), default None) – Vertices
[(x1, y1, z1), (x2, y2, z2), (x3, y3, z3), (x4, y4, z4)]in the local object coordinates.polarization (None | array-like, shape (3,), default None) – Magnetic polarization vector J = mu0*M in units (T), given in the local object coordinates. Sets also
magnetization.magnetization (None | array-like, shape (3,), default None) – Magnetization vector M = J/mu0 in units (A/m), given in the local object coordinates. Sets also
polarization.meshing (int | None, default None) – Mesh fineness for force computation. Must be a positive integer specifying the target mesh size.
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.vertices (ndarray, shape (4, 3)) – Same as constructor parameter
vertices.polarization (None | ndarray, shape (3,)) – Same as constructor parameter
polarization.magnetization (None | ndarray, shape (3,)) – Same as constructor parameter
magnetization.meshing (int | None) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
volume (float) – Read-only. Object physical volume in units (m³).
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
barycenter (ndarray, shape (3,)) – Read-only. Geometric barycenter (= center of mass) of the object.
Notes
Returns (0, 0, 0) on corners.
Examples
Tetrahedronmagnets are magnetic field sources. Below we compute the H-field in (A/m) of a tetrahedron magnet with polarization (0.1, 0.2, 0.3) in units (T) and dimensions defined through the vertices (0, 0, 0), (0.01, 0, 0), (0, 0.01, 0) and (0, 0, 0.01) (m) at the observer position (0.01, 0.01, 0.01) (m):>>> import numpy as np >>> import magpylib as magpy >>> verts = [(0, 0, 0), (0.01, 0, 0), (0, 0.01, 0), (0, 0, 0.01)] >>> src = magpy.magnet.Tetrahedron(polarization=(0.1, 0.2, 0.3), vertices=verts) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [2070.898 1656.718 1242.539]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(**kwargs) dict[str, Any]#
Create the plotly mesh3d parameters for a Tetrahedron Magnet in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property barycenter#
Object barycenter.
- property centroid#
Return centroid (m).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property magnetization#
Magnet magnetization vector (A/m) in local coordinates.
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property polarization#
Magnet polarization vector (T) in local coordinates.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property vertices#
Tetrahedron vertices in local object coordinates.
- property volume#
Return object volume (m³).
- class magpylib.magnet.TriangularMesh(position=(0, 0, 0), orientation=None, vertices=None, faces=None, polarization=None, magnetization=None, meshing=None, check_open='warn', check_disconnected='warn', check_selfintersecting='warn', reorient_faces='warn', style=None, **kwargs)#
Bases:
BaseMagnet,BaseTarget,BaseVolume,BaseDipoleMomentMagnet with homogeneous magnetization defined by a triangular surface mesh.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.The vertex positions are defined in the local object coordinates (rotate with object). When
position=(0, 0, 0)andorientation=Noneglobal and local coordinates coincide.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.vertices (array-like, shape (n, 3), default None) – Points in units (m) in the local object coordinates from which the triangular faces of the mesh are constructed by the additional
facesinput.faces (array-like, shape (n, 3), default None) – Triplets of vertex indices. Each triplet represents one triangle of the mesh.
polarization (None | array-like, shape (3,), default None) – Magnetic polarization vector J = mu0*M in units (T), given in the local object coordinates. Sets also
magnetization.magnetization (None | array-like, shape (3,), default None) – Magnetization vector M = J/mu0 in units (A/m), given in the local object coordinates. Sets also
polarization.meshing (int | None, default None) – Mesh fineness for force computation. Must be a positive integer specifying the target mesh size.
reorient_faces (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – In a properly oriented mesh, all faces must be oriented outwards. If
True, check and fix the orientation of each triangle.Truetranslates to'warn'andFalseto'skip'.check_open (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – Only a closed mesh guarantees correct B-field computation. If
True, check if the mesh is open.Truetranslates to'warn'andFalseto'skip'.check_disconnected (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – Individual magnets should be connected bodies to avoid confusion. If
True, check if the mesh is disconnected.Truetranslates to'warn'andFalseto'skip'.check_selfintersecting (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – A proper body cannot have a self-intersecting mesh. If
True, check if the mesh is self-intersecting.Truetranslates to'warn'andFalseto'skip'.style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.vertices (ndarray, shape (n, 3)) – Same as constructor parameter
vertices.faces (ndarray, shape (n, 3)) – Same as constructor parameter
faces.polarization (None | ndarray, shape (3,)) – Same as constructor parameter
polarization.magnetization (None | ndarray, shape (3,)) – Same as constructor parameter
magnetization.meshing (int | None) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
volume (float) – Read-only. Object physical volume in units (m³).
parent (Collection | None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on corners.
Examples
We compute the B-field in units (T) of a triangular mesh (4 vertices, 4 faces) with polarization (0.1, 0.2, 0.3) (T) at the observer position (0.01, 0.01, 0.01) (m):
>>> import numpy as np >>> import magpylib as magpy >>> vv = ((0, 0, 0), (0.01, 0.0, 0.0), (0.0, 0.01, 0.0), (0.0, 0.0, 0.01)) >>> tt = ((0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)) >>> trim = magpy.magnet.TriangularMesh( ... polarization=(0.1, 0.2, 0.3), vertices=vv, faces=tt, ... ) >>> with np.printoptions(precision=3): ... print(trim.getB((0.01, 0.01, 0.01)) * 1000) [2.602 2.082 1.561]
- check_disconnected(mode='warn')#
Check whether the mesh is disconnected.
- Parameters:
mode (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – Controls how to handle disconnected meshes.
Truetranslates to'warn'andFalseto'skip'.- Returns:
Trueif the mesh is disconnected,Falseotherwise.- Return type:
bool
- check_open(mode='warn')#
Check whether the mesh is open.
- Parameters:
mode (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – Controls how to handle open meshes.
Truetranslates to'warn'andFalseto'skip'.- Returns:
Trueif the mesh is open,Falseotherwise.- Return type:
bool
- check_selfintersecting(mode='warn')#
Check whether the mesh is self-intersecting.
- Parameters:
mode (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – Controls how to handle self-intersecting meshes.
Truetranslates to'warn'andFalseto'skip'.- Returns:
Trueif the mesh is self-intersecting,Falseotherwise.- Return type:
bool
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- classmethod from_ConvexHull(position=(0, 0, 0), orientation=None, points=None, polarization=None, magnetization=None, meshing=None, check_open='warn', check_disconnected='warn', reorient_faces=True, style=None, **kwargs)#
Create a TriangularMesh magnet from a point cloud via its convex hull.
SI units are used for all inputs and outputs.
- Parameters:
points (array-like, shape (n, 3)) – Point cloud from which the convex hull is computed.
position – See
TriangularMeshfor shared parameter semantics and defaults.orientation – See
TriangularMeshfor shared parameter semantics and defaults.polarization – See
TriangularMeshfor shared parameter semantics and defaults.magnetization – See
TriangularMeshfor shared parameter semantics and defaults.meshing – See
TriangularMeshfor shared parameter semantics and defaults.reorient_faces – See
TriangularMeshfor shared parameter semantics and defaults.check_open – See
TriangularMeshfor shared parameter semantics and defaults.check_disconnected – See
TriangularMeshfor shared parameter semantics and defaults.style – See
TriangularMeshfor shared parameter semantics and defaults.
- Returns:
New magnet instance defined by the convex hull of
points.- Return type:
- classmethod from_mesh(position=(0, 0, 0), orientation=None, mesh=None, polarization=None, magnetization=None, meshing=None, reorient_faces=True, check_open='warn', check_disconnected='warn', style=None, **kwargs)#
Create a TriangularMesh magnet from a mesh input.
SI units are used for all inputs and outputs.
- Parameters:
mesh (array-like, shape (n, 3, 3)) – Triangular faces that make up a triangular mesh.
position – See
TriangularMeshfor shared parameter semantics and defaults.orientation – See
TriangularMeshfor shared parameter semantics and defaults.polarization – See
TriangularMeshfor shared parameter semantics and defaults.magnetization – See
TriangularMeshfor shared parameter semantics and defaults.meshing – See
TriangularMeshfor shared parameter semantics and defaults.reorient_faces – See
TriangularMeshfor shared parameter semantics and defaults.check_open – See
TriangularMeshfor shared parameter semantics and defaults.check_disconnected – See
TriangularMeshfor shared parameter semantics and defaults.style – See
TriangularMeshfor shared parameter semantics and defaults.
- Returns:
New magnet instance defined by the provided
mesh.- Return type:
- classmethod from_pyvista(position=(0, 0, 0), orientation=None, polydata=None, polarization=None, magnetization=None, meshing=None, check_open='warn', check_disconnected='warn', reorient_faces=True, style=None, **kwargs)#
Create a TriangularMesh magnet from a pyvista PolyData mesh object.
SI units are used for all inputs and outputs.
- Parameters:
polydata (pyvista.core.pointset.PolyData) – A valid pyvista PolyData mesh object (e.g.
pyvista.Sphere()).position – See
TriangularMeshfor shared parameter semantics and defaults.orientation – See
TriangularMeshfor shared parameter semantics and defaults.polarization – See
TriangularMeshfor shared parameter semantics and defaults.magnetization – See
TriangularMeshfor shared parameter semantics and defaults.meshing – See
TriangularMeshfor shared parameter semantics and defaults.reorient_faces – See
TriangularMeshfor shared parameter semantics and defaults.check_open – See
TriangularMeshfor shared parameter semantics and defaults.check_disconnected – See
TriangularMeshfor shared parameter semantics and defaults.style – See
TriangularMeshfor shared parameter semantics and defaults.
- Returns:
New magnet instance defined by
polydata.- Return type:
- classmethod from_triangles(position=(0, 0, 0), orientation=None, triangles=None, polarization=None, magnetization=None, meshing=None, reorient_faces=True, check_open='warn', check_disconnected='warn', style=None, **kwargs)#
Create a TriangularMesh magnet from a list or Collection of Triangle objects.
SI units are used for all inputs and outputs.
- Parameters:
triangles (list or Collection) – Only
verticesofTriangleobjects in list or collection are taken,magnetizationis ignored.position – See
TriangularMeshfor shared parameter semantics and defaults.orientation – See
TriangularMeshfor shared parameter semantics and defaults.polarization – See
TriangularMeshfor shared parameter semantics and defaults.magnetization – See
TriangularMeshfor shared parameter semantics and defaults.meshing – See
TriangularMeshfor shared parameter semantics and defaults.reorient_faces – See
TriangularMeshfor shared parameter semantics and defaults.check_open – See
TriangularMeshfor shared parameter semantics and defaults.check_disconnected – See
TriangularMeshfor shared parameter semantics and defaults.style – See
TriangularMeshfor shared parameter semantics and defaults.
- Returns:
New magnet instance defined by the provided
triangles.- Return type:
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_faces_subsets()#
Get subsets of faces for each disconnected part of the mesh.
If the mesh has
kdisconnected parts, returns a list of lengthkwith arrays of shape (m, 3) containing vertex index triplets for each part.- Returns:
List of ndarrays. Subsets of faces data.
- Return type:
list
- get_selfintersecting_faces()#
Return indices of potentially self-intersecting faces.
If the mesh has n intersecting faces, returns a 1D array of length n with their face indices.
- Returns:
Indices of potentially self-intersecting faces.
- Return type:
ndarray, shape (n,)
- get_trace(**kwargs) dict[str, Any] | list[dict[str, Any]]#
Creates the plotly mesh3d parameters for a Triangular facet mesh in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reorient_faces(mode='warn')#
Reorient all faces to point outwards.
In a properly oriented mesh, all faces must be oriented outwards. This function fixes the orientation of each face. Note that
modeis also considered incheck_open()because the mesh is only orientable if it is closed.- Parameters:
mode (bool | {'warn', 'raise', 'ignore', 'skip'}, default 'warn') – Controls how to handle open meshes during reorientation.
Truetranslates to'warn'andFalseto'skip'.- Return type:
None
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- to_TriangleCollection()#
Return a Collection of Triangle objects from the current TriangularMesh
- property barycenter#
Object barycenter.
- property centroid#
Return centroid (m).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property faces#
Mesh faces
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property magnetization#
Magnet magnetization vector (A/m) in local coordinates.
- property mesh#
Mesh
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property polarization#
Magnet polarization vector (T) in local coordinates.
- property position#
Return object position in global coordinates (m).
- property status_disconnected#
Return disconnected status
- property status_disconnected_data#
Status for connectedness (faces subsets)
- property status_open#
Return open status
- property status_open_data#
Status for openness (open edges)
- property status_reoriented#
Return reoriented status
- property status_selfintersecting#
Is-selfintersecting boolean check
- property status_selfintersecting_data#
return self-intersecting faces
- property style#
Return object style as a
BaseStyleinstance.
- property vertices#
Mesh vertices
- property volume#
Return object volume (m³).