magpylib.misc package#

Miscellaneous source objects.

class magpylib.misc.CustomSource(position=(0, 0, 0), orientation=None, field_func=None, style=None, **kwargs)#

Bases: BaseSource

User-defined custom source.

Can be used as sources input for magnetic field computation.

When position=(0, 0, 0) and orientation=None global 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). position and orientation attributes define the object path.

  • orientation (None | Rotation, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p. None generates a unit-rotation.

  • field_func (None | callable, default None) – Function for B- and H-field computation with the two positional arguments field and observers. With field='B' or field='H' the function must return the B-field (T) or H-field (A/m) respectively. observers must accept an ndarray of shape (o, 3) in units (m) and the returned array must have shape (o, 3).

  • style (None | dict, 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.

  • field_func (None | callable) – Same as constructor parameter field_func.

  • parent (Collection | None) – Parent collection of the object.

  • style (dict) – Style dictionary defining visual properties.

Examples

With version 4, CustomSource objects enable users to define their own source objects and embed them in the Magpylib object-oriented interface. In this example we create a source that generates a constant field and evaluate the field at the observer position (0.01, 0.01, 0.01) in units (m):

>>> import numpy as np
>>> import magpylib as magpy
>>> def funcBH(field, observers):
...     return np.array([(0.01 if field == 'B' else 0.08, 0, 0)] * len(observers))
>>> src = magpy.misc.CustomSource(field_func=funcBH)
>>> H = src.getH((0.01, 0.01, 0.01))
>>> print(H)
[0.08 0.   0.  ]
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 Sensor object 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 True return the description string; if False print it and return None.

Returns:

Description string if return_string=True else None.

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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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] | list[dict[str, Any]]#

Creates the plotly scatter3d parameters for an object with no specifically supported representation. The object will be represented by a scatter point and text above with object name.

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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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. None is interpreted as unit rotation.

  • anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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'. If canvas is 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 True and 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. True forces update, False suppresses 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; otherwise None.

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 field_func#

Function for B- and H-field computation.

The callable must accept the two positional arguments field and observers. With field='B' or field='H' the function must return the B-field (T) or H-field (A/m) respectively. observers is an ndarray of shape (n, 3) in units (m). The returned array must have shape (n, 3).

property orientation#

Return object orientation.

None corresponds to unit rotation.

property parent#

Parent collection of the object.

property position#

Return object position in global coordinates (m).

property style#

Return object style as a BaseStyle instance.

class magpylib.misc.Dipole(position=(0, 0, 0), orientation=None, moment=None, style=None, **kwargs)#

Bases: BaseSource, BaseDipoleMoment

Magnetic dipole moment.

Can be used as sources input for magnetic field computation and target input for force computation.

When position=(0, 0, 0) and orientation=None global 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). position and orientation attributes define the object path.

  • orientation (None | Rotation, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p. None generates a unit-rotation.

  • moment (None | array-like, shape (3,), default None) – Magnetic dipole moment (A·m²) in local object coordinates. For homogeneous magnets the relation moment = magnetization * volume holds. For current loops the relation moment = current * loop_surface holds.

  • style (None | dict, 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.

  • moment (None | ndarray, shape (3,)) – Same as constructor parameter moment.

  • 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.

  • parent (Collection | None) – Parent collection of the object.

  • style (dict) – Style dictionary defining visual properties.

Notes

Returns inf or nan at the dipole position.

Examples

Dipole objects are magnetic field sources. In this example we compute the H-field (A/m) of a magnetic dipole with moment (10, 10, 10) (A·m²) at the observer position (10, 10, 10) centimeters:

>>> import numpy as np
>>> import magpylib as magpy
>>> src = magpy.misc.Dipole(moment=(10, 10, 10))
>>> H = src.getH((0.01, 0.01, 0.01))
>>> with np.printoptions(precision=0):
...     print(H)
[306294. 306294. 306294.]
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 Sensor object 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 True return the description string; if False print it and return None.

Returns:

Description string if return_string=True else None.

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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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(autosize=None, **kwargs) dict[str, Any]#

Create the plotly mesh3d parameters for a dipole 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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. None is interpreted as unit rotation.

  • anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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'. If canvas is 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 True and 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. True forces update, False suppresses 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; otherwise None.

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 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 field and observers. With field='B' or field='H' the function must return the B-field (T) or H-field (A/m) respectively. observers is an ndarray of shape (n, 3) in units (m). The returned array must have shape (n, 3).

property moment#

Magnetic dipole moment (A·m²) in local object coordinates.

property orientation#

Return object orientation.

None corresponds to unit rotation.

property parent#

Parent collection of the object.

property position#

Return object position in global coordinates (m).

property style#

Return object style as a BaseStyle instance.

class magpylib.misc.Triangle(position=(0, 0, 0), orientation=None, vertices=None, polarization=None, magnetization=None, style=None, **kwargs)#

Bases: BaseMagnet

Triangular surface with homogeneous magnetic surface charge.

Can be used as sources input for magnetic field computation and target input for force computation.

When position=(0, 0, 0) and orientation=None the local object coordinates of the Triangle vertices coincide with 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). position and orientation attributes define the object path.

  • orientation (None | Rotation, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p. None generates a unit-rotation.

  • vertices (None | array-like, shape (3, 3), default None) – Triangle vertices in the local object coordinates 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 (None | dict, 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 (None | ndarray, shape (3, 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.

  • centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.

  • parent (Collection | None) – Parent collection of the object.

  • style (dict) – Style dictionary defining visual properties.

Notes

Returns (0, 0, 0) on corners.

Examples

Triangle objects are magnetic field sources. Below we compute the H-field in (A/m) of a Triangle object with magnetic polarization (0.1, 0.2, 0.3) in units (T), defined by the vertices (0, 0, 0), (0.01, 0, 0) and (0, 0.01, 0) (m) at the observer position (0.1, 0.1, 0.1) (m):

>>> import numpy as np
>>> import magpylib as magpy
>>> verts = [(0, 0, 0), (0.01, 0, 0), (0, 0.01, 0)]
>>> src = magpy.misc.Triangle(polarization=(0.1, 0.2, 0.3), vertices=verts)
>>> H = src.getH((0.1, 0.1, 0.1))
>>> with np.printoptions(precision=3):
...     print(H)
[18.889 18.889 19.546]
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 Sensor object 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 True return the description string; if False print it and return None.

Returns:

Description string if return_string=True else None.

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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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 Sensor object with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unless pixel_agg is used).

  • squeeze (bool, default True) – If True squeeze 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] | list[dict[str, Any]]#

Creates the plotly mesh3d parameters for a Triangular facet 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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. None is interpreted as unit rotation.

  • anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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). None rotates 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 sets start=0 (modify whole path) and vector input sets start=len(path) (append). See Notes for details.

  • degrees (bool, default True) – If True, interpret angle input 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 index start. 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 to start=0 for scalar input corresponding to moving the entire path, and to start=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'. If canvas is 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 True and 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. True forces update, False suppresses 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; otherwise None.

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 in units (m) in global coordinates.

property centroid#

Return centroid (m).

property field_func#

Function for B- and H-field computation.

The callable must accept the two positional arguments field and observers. With field='B' or field='H' the function must return the B-field (T) or H-field (A/m) respectively. observers is an ndarray of 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.

None corresponds 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 BaseStyle instance.

property vertices#

Triangle vertices in local object coordinates in units (m).