magpylib.magnet package

Contents

magpylib.magnet package#

The magpylib.magnet subpackage contains all magnet classes.

class magpylib.magnet.Cuboid(position=(0, 0, 0), orientation=None, dimension=None, polarization=None, magnetization=None, style=None, **kwargs)#

Bases: BaseMagnet

Cuboid magnet with homogeneous magnetization.

Can be used as sources input for magnetic field computation.

When position=(0,0,0) and orientation=None the Cuboid sides are parallel to the global coordinate basis vectors and the geometric center of the Cuboid is located in the origin.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3), default=`(0,0,0)`) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • dimension (array_like, shape (3,), default=`None`) – Length of the cuboid sides [a,b,c] in meters.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Returns:

magnet source

Return type:

Cuboid object

Examples

Cuboid magnets are magnetic field sources. Below we compute the H-field in A/m of a cubical magnet with magnetic polarization of (0.5,0.6,0.7) in units of T and 0.01 meter sides at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> src = magpy.magnet.Cuboid(polarization=(.5,.6,.7), dimension=(.01,.01,.01))
>>> H = src.getH((.01,.01,.01))
>>> print(H)
[16149.04135639 14906.8074059  13664.57345541]

We rotate the source object, and compute the B-field, this time at a set of observer positions:

>>> src.rotate_from_angax(45, 'x')
Cuboid(id=...)
>>> B = src.getB([(.01,0,0), (0,.01,0), (0,0,.01)])
>>> print(B)
[[ 0.06739119  0.00476528 -0.0619486 ]
 [-0.03557183 -0.01149497 -0.08403664]
 [-0.03557183  0.00646436  0.14943466]]
copy(**kwargs)#

Returns a copy of the current object instance. The copy method returns a deep copy of the object, that is independent of the original object.

Parameters:

kwargs (dict) – Keyword arguments (for example position=(1,2,3)) are applied to the copy.

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

Returns a view of the object properties.

Parameters:
  • exclude (bool, default=("style",)) – Properties to be excluded in the description view.

  • return_string (bool, default=`False`) – If False print description with stdout, if True return as string.

property dimension#

Length of the cuboid sides [a,b,c] in arbitrary length units, e.g. in meter.

property field_func#

The function for B- and H-field computation must have the two positional arguments field and observers. With field=’B’ or field=’H’ the B- or H-field in units of T or A/m must be returned respectively. The observers argument must accept numpy ndarray inputs of shape (n,3), in which case the returned fields must be numpy ndarrays of shape (n,3) themselves.

getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the B-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

B-field – B-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the B-field of a spherical magnet at three positions:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> B = src.getB(((0,0,0), (1,0,0), (2,0,0)))
>>> print(B)
[[ 0.          0.          0.66666667]
 [ 0.          0.         -0.04166667]
 [ 0.          0.         -0.00520833]]

Compute the B-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> B = src.getB(sens1, sens2)
>>> print(B)
[[[ 0.01219289  0.         -0.0398301 ]
  [-0.01219289  0.         -0.0398301 ]]

 [[ 0.00077639  0.         -0.00515004]
  [-0.00077639  0.         -0.00515004]]]
getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

H-field – H-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the H-field of a spherical magnet at three positions:

>>> 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)))
>>> print(H)
[[      0.               0.         -265258.23834209]
 [      0.               0.          -33157.27979276]
 [      0.               0.           -4144.6599741 ]]

Compute the H-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> H = src.getH(sens1, sens2)
>>> print(H)
[[[  9702.79184001      0.         -31695.78667738]
  [ -9702.79184001      0.         -31695.78667738]]

 [[   617.83031344      0.          -4098.27441249]
  [  -617.83031344      0.          -4098.27441249]]]
getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

J-field – J-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the M-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

M-field – M-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

get_trace(**kwargs) Dict[str, Any]#

Create the plotly mesh3d parameters for a Cuboid Magnet in a dictionary based on the provided arguments.

property magnetization#

Object magnetization attribute getter and setter.

move(displacement, start='auto')#

Move object by the displacement input. SI units are used for all inputs and outputs.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • displacement (array_like, shape (3,) or (n,3)) – Displacement vector in units of m.

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Move objects around with scalar input:

>>> 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.]]
property orientation#

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

property parent#

The object is a child of it’s parent collection.

property polarization#

Object polarization attribute getter and setter.

property position#

Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

reset_path()#

Set object position to (0,0,0) and orientation = unit rotation.

Returns:

self

Return type:

magpylib object

Examples

Demonstration of reset_path functionality:

>>> 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 object about a given anchor.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotation (None or scipy Rotation object) – Rotation to be applied to the object. The scipy Rotation input can be scalar or vector type (see terminology above). None input is interpreted as unit rotation.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using angle-axis input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • axis (str or array_like, shape (3,)) – The direction of the axis of rotation. Input can be a vector of shape (3,) or a string ‘x’, ‘y’ or ‘z’ to denote respective directions.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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

Rotates object using Euler angle input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • seq (string) – 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, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using matrix input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • matrix (array_like, shape (n,3,3) or (3,3)) – Rotation input. See scipy.spatial.transform.Rotation for details.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Rotate an object about the origin:

>>> 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')#

Rotates object using Modified Rodrigues Parameters (MRPs) input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • mrp (array_like, shape (n,3) or (3,)) – Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs).

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using quaternion input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • quat (array_like, shape (n,4) or (4,)) – Rotation input in quaternion form.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using rotation vector input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotvec (array_like, shape (n,3) or (3,)) – Rotation input. Rotation vector direction is the rotation axis, vector length is the rotation angle in units of rad.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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>, 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 (Magpylib objects (sources, collections, sensors)) – Objects to be displayed.

  • backend (string, default=`None`) – Define plotting backend. Must be one of [‘auto’, ‘matplotlib’, ‘plotly’, ‘pyvista’]. If not set, parameter will default to magpylib.defaults.display.backend which is ‘auto’ by installation default. With ‘auto’, the backend defaults to ‘plotly’ if plotly is installed and the function is called in an IPython environment, otherwise defaults to ‘matplotlib’ which comes installed with magpylib. If the canvas is set, the backend defaults to the one corresponding to the canvas object (see canvas parameter).

  • canvas (matplotlib.pyplot AxesSubplot or plotly Figure object, default=`None`) – Display graphical output on a given canvas: - with matplotlib: matplotlib.axes.Axes with projection=3d. - with plotly: `plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget. - with pyvista: pyvista.Plotter. By default a new canvas is created and immediately displayed.

  • animation (bool or float, default=`False`) – If True and at least one object has a path, the paths are rendered. If input is a positive float, the animation time is set to the given value. This feature is only available for the plotly backend.

  • zoom (float, default=`0`) – Adjust plot zoom-level. When zoom=0 3D-figure boundaries are tight.

  • markers (array_like, shape (n,3), default=`None`) – Display position markers in the global coordinate system.

  • return_fig (bool, default=False) –

    If True, the function call returns the figure object.

    • with matplotlib: matplotlib.figure.Figure.

    • with plotly: plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget.

    • with pyvista: pyvista.Plotter.

  • row (int or None,) – If provided specifies the row in which the objects will be displayed.

  • col (int or None,) – If provided specifies the column in which the objects will be displayed.

  • output (tuple or string, default="model3d") – Can be a string or a tuple of strings specifying the plot output type. By default output=’model3d’ displays the 3D representations of the objects. If output is a tuple of strings it must be a combination of ‘B’, ‘H’, ‘M’ or ‘J’ and ‘x’, ‘y’ and/or ‘z’. When having multiple coordinates, the field value is the combined vector length (e.g. (‘Bx’, ‘Hxy’, ‘Byz’)) ‘Bxy’ is equivalent to sqrt(|Bx|^2 + |By|^2). A 2D line plot is then represented accordingly if the objects contain at least one source and one sensor.

  • sumup (bool, default=True) – If True, sums the field values of the sources. Applies only if output is not ‘model3d’.

  • pixel_agg (bool, default="mean") – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. Applies only if output is not ‘model3d’.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’. Applies to all objects matching the given style properties.

Return type:

None or figure object

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

Object style in the form of a BaseStyle object. Input must be in the form of a style dictionary.

class magpylib.magnet.Cylinder(position=(0, 0, 0), orientation=None, dimension=None, polarization=None, magnetization=None, style=None, **kwargs)#

Bases: BaseMagnet

Cylinder magnet with homogeneous magnetization.

Can be used as sources input for magnetic field computation.

When position=(0,0,0) and orientation=None the geometric center of the cylinder lies in the origin of the global coordinate system and the cylinder axis coincides with the global z-axis.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3), default=`(0,0,0)`) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • dimension (array_like, shape (2,), default=`None`) – Dimension (d,h) denote diameter and height of the cylinder in units of m.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Returns:

magnet source

Return type:

Cylinder

Examples

Cylinder magnets are magnetic field sources. Below we compute the H-field in A/m of a cylinder magnet with polarization (.1,.2,.3) in units of T and 0.01 meter diameter and height at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> src = magpy.magnet.Cylinder(polarization=(.1,.2,.3), dimension=(.01,.01))
>>> H = src.getH((.01,.01,.01))
>>> print(H)
[4849.91343121 3883.17815517 2739.73202237]

We rotate the source object, and compute the B-field, this time at a set of observer positions:

>>> src.rotate_from_angax(45, 'x')
Cylinder(id=...)
>>> B = src.getB([(.01,.01,.01), (.02,.02,.02), (.03,.03,.03)])
>>> print(B)
[[3.31419501e-03 5.26683023e-03 3.77670149e-04]
 [4.22984050e-04 6.77105357e-04 4.46493154e-05]
 [1.25715233e-04 2.01445027e-04 1.31238931e-05]]

The same result is obtained when the rotated source moves along a path away from an observer at position (0.01,0.01,0.01). Here we use a Sensor object as observer.

>>> sens = magpy.Sensor(position=(.01,.01,.01))
>>> src.move([(-.01,-.01,-.01), (-.02,-.02,-.02)])
Cylinder(id=...)
>>> B = src.getB(sens)
>>> print(B)
[[3.31419501e-03 5.26683023e-03 3.77670149e-04]
 [4.22984050e-04 6.77105357e-04 4.46493154e-05]
 [1.25715233e-04 2.01445027e-04 1.31238931e-05]]
copy(**kwargs)#

Returns a copy of the current object instance. The copy method returns a deep copy of the object, that is independent of the original object.

Parameters:

kwargs (dict) – Keyword arguments (for example position=(1,2,3)) are applied to the copy.

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

Returns a view of the object properties.

Parameters:
  • exclude (bool, default=("style",)) – Properties to be excluded in the description view.

  • return_string (bool, default=`False`) – If False print description with stdout, if True return as string.

property dimension#

Dimension (d,h) denote diameter and height of the cylinder in units of m.

property field_func#

The function for B- and H-field computation must have the two positional arguments field and observers. With field=’B’ or field=’H’ the B- or H-field in units of T or A/m must be returned respectively. The observers argument must accept numpy ndarray inputs of shape (n,3), in which case the returned fields must be numpy ndarrays of shape (n,3) themselves.

getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the B-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

B-field – B-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the B-field of a spherical magnet at three positions:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> B = src.getB(((0,0,0), (1,0,0), (2,0,0)))
>>> print(B)
[[ 0.          0.          0.66666667]
 [ 0.          0.         -0.04166667]
 [ 0.          0.         -0.00520833]]

Compute the B-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> B = src.getB(sens1, sens2)
>>> print(B)
[[[ 0.01219289  0.         -0.0398301 ]
  [-0.01219289  0.         -0.0398301 ]]

 [[ 0.00077639  0.         -0.00515004]
  [-0.00077639  0.         -0.00515004]]]
getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

H-field – H-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the H-field of a spherical magnet at three positions:

>>> 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)))
>>> print(H)
[[      0.               0.         -265258.23834209]
 [      0.               0.          -33157.27979276]
 [      0.               0.           -4144.6599741 ]]

Compute the H-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> H = src.getH(sens1, sens2)
>>> print(H)
[[[  9702.79184001      0.         -31695.78667738]
  [ -9702.79184001      0.         -31695.78667738]]

 [[   617.83031344      0.          -4098.27441249]
  [  -617.83031344      0.          -4098.27441249]]]
getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

J-field – J-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the M-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

M-field – M-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

get_trace(base=50, **kwargs) Dict[str, Any]#

Create the plotly mesh3d parameters for a Cylinder Magnet in a dictionary based on the provided arguments.

property magnetization#

Object magnetization attribute getter and setter.

move(displacement, start='auto')#

Move object by the displacement input. SI units are used for all inputs and outputs.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • displacement (array_like, shape (3,) or (n,3)) – Displacement vector in units of m.

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Move objects around with scalar input:

>>> 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.]]
property orientation#

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

property parent#

The object is a child of it’s parent collection.

property polarization#

Object polarization attribute getter and setter.

property position#

Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

reset_path()#

Set object position to (0,0,0) and orientation = unit rotation.

Returns:

self

Return type:

magpylib object

Examples

Demonstration of reset_path functionality:

>>> 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 object about a given anchor.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotation (None or scipy Rotation object) – Rotation to be applied to the object. The scipy Rotation input can be scalar or vector type (see terminology above). None input is interpreted as unit rotation.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using angle-axis input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • axis (str or array_like, shape (3,)) – The direction of the axis of rotation. Input can be a vector of shape (3,) or a string ‘x’, ‘y’ or ‘z’ to denote respective directions.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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

Rotates object using Euler angle input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • seq (string) – 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, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using matrix input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • matrix (array_like, shape (n,3,3) or (3,3)) – Rotation input. See scipy.spatial.transform.Rotation for details.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Rotate an object about the origin:

>>> 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')#

Rotates object using Modified Rodrigues Parameters (MRPs) input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • mrp (array_like, shape (n,3) or (3,)) – Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs).

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using quaternion input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • quat (array_like, shape (n,4) or (4,)) – Rotation input in quaternion form.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using rotation vector input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotvec (array_like, shape (n,3) or (3,)) – Rotation input. Rotation vector direction is the rotation axis, vector length is the rotation angle in units of rad.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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>, 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 (Magpylib objects (sources, collections, sensors)) – Objects to be displayed.

  • backend (string, default=`None`) – Define plotting backend. Must be one of [‘auto’, ‘matplotlib’, ‘plotly’, ‘pyvista’]. If not set, parameter will default to magpylib.defaults.display.backend which is ‘auto’ by installation default. With ‘auto’, the backend defaults to ‘plotly’ if plotly is installed and the function is called in an IPython environment, otherwise defaults to ‘matplotlib’ which comes installed with magpylib. If the canvas is set, the backend defaults to the one corresponding to the canvas object (see canvas parameter).

  • canvas (matplotlib.pyplot AxesSubplot or plotly Figure object, default=`None`) – Display graphical output on a given canvas: - with matplotlib: matplotlib.axes.Axes with projection=3d. - with plotly: `plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget. - with pyvista: pyvista.Plotter. By default a new canvas is created and immediately displayed.

  • animation (bool or float, default=`False`) – If True and at least one object has a path, the paths are rendered. If input is a positive float, the animation time is set to the given value. This feature is only available for the plotly backend.

  • zoom (float, default=`0`) – Adjust plot zoom-level. When zoom=0 3D-figure boundaries are tight.

  • markers (array_like, shape (n,3), default=`None`) – Display position markers in the global coordinate system.

  • return_fig (bool, default=False) –

    If True, the function call returns the figure object.

    • with matplotlib: matplotlib.figure.Figure.

    • with plotly: plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget.

    • with pyvista: pyvista.Plotter.

  • row (int or None,) – If provided specifies the row in which the objects will be displayed.

  • col (int or None,) – If provided specifies the column in which the objects will be displayed.

  • output (tuple or string, default="model3d") – Can be a string or a tuple of strings specifying the plot output type. By default output=’model3d’ displays the 3D representations of the objects. If output is a tuple of strings it must be a combination of ‘B’, ‘H’, ‘M’ or ‘J’ and ‘x’, ‘y’ and/or ‘z’. When having multiple coordinates, the field value is the combined vector length (e.g. (‘Bx’, ‘Hxy’, ‘Byz’)) ‘Bxy’ is equivalent to sqrt(|Bx|^2 + |By|^2). A 2D line plot is then represented accordingly if the objects contain at least one source and one sensor.

  • sumup (bool, default=True) – If True, sums the field values of the sources. Applies only if output is not ‘model3d’.

  • pixel_agg (bool, default="mean") – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. Applies only if output is not ‘model3d’.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’. Applies to all objects matching the given style properties.

Return type:

None or figure object

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

Object style in the form of a BaseStyle object. Input must be in the form of a style dictionary.

class magpylib.magnet.CylinderSegment(position=(0, 0, 0), orientation=None, dimension=None, polarization=None, magnetization=None, style=None, **kwargs)#

Bases: BaseMagnet

Cylinder segment (ring-section) magnet with homogeneous magnetization.

Can be used as sources input for magnetic field computation.

When position=(0,0,0) and orientation=None the geometric center of the cylinder lies in the origin of the global coordinate system and the cylinder axis coincides with the global z-axis. Section angle 0 corresponds to an x-z plane section of the cylinder.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3), default=`(0,0,0)`) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • dimension (array_like, shape (5,), default=`None`) – Dimension/Size of the cylinder segment of the form (r1, r2, h, phi1, phi2) where r1<r2 denote inner and outer radii in units of m, phi1<phi2 denote the cylinder section angles in units of deg and h is the cylinder height in units of m.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

barycenter#

Read only property that returns the geometric barycenter (=center of mass) of the object.

Type:

array_like, shape (3,)

Returns:

magnet source

Return type:

CylinderSegment object

Examples

CylinderSegment magnets are magnetic field sources. In this example we compute the H-field in A/m of such a cylinder segment magnet with polarization (.1,.2,.3) in units of T, inner radius 0.01 meter, outer radius 0.02 meter, height 0.01 meter, and section angles 0 and 45 deg at the observer position (0.02,0.02,0.02) in units of m:

>>> import magpylib as magpy
>>> src = magpy.magnet.CylinderSegment(polarization=(.1,.2,.3), dimension=(.01,.02,.01,0,45))
>>> H = src.getH((.02,.02,.02))
>>> print(H)
[ 807.84692247 1934.22812757 2741.16804414]

We rotate the source object, and compute the B-field, this time at a set of observer positions:

>>> src.rotate_from_angax(45, 'x')
CylinderSegment(id=...)
>>> B = src.getB([(.01,.01,.01), (.02,.02,.02), (.03,.03,.03)])
>>> print(B)
[[-0.0328285   0.03015882 -0.01632886]
 [ 0.00062876  0.00397579  0.00073298]
 [ 0.00025439  0.00074332  0.00011683]]

The same result is obtained when the rotated source moves along a path away from an observer at position (.01,.01,.01). Here we use a Sensor object as observer.

>>> sens = magpy.Sensor(position=(.01,.01,.01))
>>> src.move([(-.01,-.01,-.01), (-.02,-.02,-.02)])
CylinderSegment(id=...)
>>> B = src.getB(sens)
>>> print(B)
[[-0.0328285   0.03015882 -0.01632886]
 [ 0.00062876  0.00397579  0.00073298]
 [ 0.00025439  0.00074332  0.00011683]]
property barycenter#

Object barycenter.

copy(**kwargs)#

Returns a copy of the current object instance. The copy method returns a deep copy of the object, that is independent of the original object.

Parameters:

kwargs (dict) – Keyword arguments (for example position=(1,2,3)) are applied to the copy.

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

Returns a view of the object properties.

Parameters:
  • exclude (bool, default=("style",)) – Properties to be excluded in the description view.

  • return_string (bool, default=`False`) – If False print description with stdout, if True return as string.

property dimension#

Dimension/Size of the cylinder segment of the form (r1, r2, h, phi1, phi2) where r1<r2 denote inner and outer radii in units of m, phi1<phi2 denote the cylinder section angles in units of deg and h is the cylinder height in units of m.

property field_func#

The function for B- and H-field computation must have the two positional arguments field and observers. With field=’B’ or field=’H’ the B- or H-field in units of T or A/m must be returned respectively. The observers argument must accept numpy ndarray inputs of shape (n,3), in which case the returned fields must be numpy ndarrays of shape (n,3) themselves.

getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the B-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

B-field – B-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the B-field of a spherical magnet at three positions:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> B = src.getB(((0,0,0), (1,0,0), (2,0,0)))
>>> print(B)
[[ 0.          0.          0.66666667]
 [ 0.          0.         -0.04166667]
 [ 0.          0.         -0.00520833]]

Compute the B-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> B = src.getB(sens1, sens2)
>>> print(B)
[[[ 0.01219289  0.         -0.0398301 ]
  [-0.01219289  0.         -0.0398301 ]]

 [[ 0.00077639  0.         -0.00515004]
  [-0.00077639  0.         -0.00515004]]]
getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

H-field – H-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the H-field of a spherical magnet at three positions:

>>> 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)))
>>> print(H)
[[      0.               0.         -265258.23834209]
 [      0.               0.          -33157.27979276]
 [      0.               0.           -4144.6599741 ]]

Compute the H-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> H = src.getH(sens1, sens2)
>>> print(H)
[[[  9702.79184001      0.         -31695.78667738]
  [ -9702.79184001      0.         -31695.78667738]]

 [[   617.83031344      0.          -4098.27441249]
  [  -617.83031344      0.          -4098.27441249]]]
getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

J-field – J-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the M-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

M-field – M-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

get_trace(vertices=25, **kwargs) Dict[str, Any]#

Create the plotly mesh3d parameters for a Cylinder Segment Magnet in a dictionary based on the provided arguments.

property magnetization#

Object magnetization attribute getter and setter.

move(displacement, start='auto')#

Move object by the displacement input. SI units are used for all inputs and outputs.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • displacement (array_like, shape (3,) or (n,3)) – Displacement vector in units of m.

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Move objects around with scalar input:

>>> 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.]]
property orientation#

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

property parent#

The object is a child of it’s parent collection.

property polarization#

Object polarization attribute getter and setter.

property position#

Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

reset_path()#

Set object position to (0,0,0) and orientation = unit rotation.

Returns:

self

Return type:

magpylib object

Examples

Demonstration of reset_path functionality:

>>> 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 object about a given anchor.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotation (None or scipy Rotation object) – Rotation to be applied to the object. The scipy Rotation input can be scalar or vector type (see terminology above). None input is interpreted as unit rotation.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using angle-axis input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • axis (str or array_like, shape (3,)) – The direction of the axis of rotation. Input can be a vector of shape (3,) or a string ‘x’, ‘y’ or ‘z’ to denote respective directions.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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

Rotates object using Euler angle input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • seq (string) – 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, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using matrix input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • matrix (array_like, shape (n,3,3) or (3,3)) – Rotation input. See scipy.spatial.transform.Rotation for details.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Rotate an object about the origin:

>>> 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')#

Rotates object using Modified Rodrigues Parameters (MRPs) input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • mrp (array_like, shape (n,3) or (3,)) – Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs).

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using quaternion input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • quat (array_like, shape (n,4) or (4,)) – Rotation input in quaternion form.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using rotation vector input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotvec (array_like, shape (n,3) or (3,)) – Rotation input. Rotation vector direction is the rotation axis, vector length is the rotation angle in units of rad.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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>, 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 (Magpylib objects (sources, collections, sensors)) – Objects to be displayed.

  • backend (string, default=`None`) – Define plotting backend. Must be one of [‘auto’, ‘matplotlib’, ‘plotly’, ‘pyvista’]. If not set, parameter will default to magpylib.defaults.display.backend which is ‘auto’ by installation default. With ‘auto’, the backend defaults to ‘plotly’ if plotly is installed and the function is called in an IPython environment, otherwise defaults to ‘matplotlib’ which comes installed with magpylib. If the canvas is set, the backend defaults to the one corresponding to the canvas object (see canvas parameter).

  • canvas (matplotlib.pyplot AxesSubplot or plotly Figure object, default=`None`) – Display graphical output on a given canvas: - with matplotlib: matplotlib.axes.Axes with projection=3d. - with plotly: `plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget. - with pyvista: pyvista.Plotter. By default a new canvas is created and immediately displayed.

  • animation (bool or float, default=`False`) – If True and at least one object has a path, the paths are rendered. If input is a positive float, the animation time is set to the given value. This feature is only available for the plotly backend.

  • zoom (float, default=`0`) – Adjust plot zoom-level. When zoom=0 3D-figure boundaries are tight.

  • markers (array_like, shape (n,3), default=`None`) – Display position markers in the global coordinate system.

  • return_fig (bool, default=False) –

    If True, the function call returns the figure object.

    • with matplotlib: matplotlib.figure.Figure.

    • with plotly: plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget.

    • with pyvista: pyvista.Plotter.

  • row (int or None,) – If provided specifies the row in which the objects will be displayed.

  • col (int or None,) – If provided specifies the column in which the objects will be displayed.

  • output (tuple or string, default="model3d") – Can be a string or a tuple of strings specifying the plot output type. By default output=’model3d’ displays the 3D representations of the objects. If output is a tuple of strings it must be a combination of ‘B’, ‘H’, ‘M’ or ‘J’ and ‘x’, ‘y’ and/or ‘z’. When having multiple coordinates, the field value is the combined vector length (e.g. (‘Bx’, ‘Hxy’, ‘Byz’)) ‘Bxy’ is equivalent to sqrt(|Bx|^2 + |By|^2). A 2D line plot is then represented accordingly if the objects contain at least one source and one sensor.

  • sumup (bool, default=True) – If True, sums the field values of the sources. Applies only if output is not ‘model3d’.

  • pixel_agg (bool, default="mean") – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. Applies only if output is not ‘model3d’.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’. Applies to all objects matching the given style properties.

Return type:

None or figure object

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

Object style in the form of a BaseStyle object. Input must be in the form of a style dictionary.

class magpylib.magnet.Sphere(position=(0, 0, 0), orientation=None, diameter=None, polarization=None, magnetization=None, style=None, **kwargs)#

Bases: BaseMagnet

Spherical magnet with homogeneous magnetization.

Can be used as sources input for magnetic field computation.

When position=(0,0,0) and orientation=None the sphere center is located in the origin of the global coordinate system.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3), default=`(0,0,0)`) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • diameter (float, default=`None`) – Diameter of the sphere in units of m.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Returns:

magnet source

Return type:

Sphere object

Examples

Sphere objects are magnetic field sources. In this example we compute the H-field in A/m of a spherical magnet with polarization (0.1,0.2,0.3) in units of T and diameter of 0.01 meter at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(.1,.2,.3), diameter=.01)
>>> H = src.getH((.01,.01,.01))
>>> print(H)
[3190.56073566 2552.44858853 1914.33644139]

We rotate the source object, and compute the B-field, this time at a set of observer positions:

>>> src.rotate_from_angax(45, 'x')
Sphere(id=...)
>>> B = src.getB([(.01,.01,.01), (.02,.02,.02), (.03,.03,.03)])
>>> print(B)
[[2.26804606e-03 3.63693295e-03 2.34863859e-04]
 [2.83505757e-04 4.54616618e-04 2.93579824e-05]
 [8.40017059e-05 1.34701220e-04 8.69866146e-06]]

The same result is obtained when the rotated source moves along a path away from an observer at position (.01,.01,.01). This time we use a Sensor object as observer.

>>> src.move([(-.01,-.01,-.01), (-.02,-.02,-.02)])
Sphere(id=...)
>>> sens = magpy.Sensor(position=(.01,.01,.01))
>>> B = src.getB(sens)
>>> print(B)
[[2.26804606e-03 3.63693295e-03 2.34863859e-04]
 [2.83505757e-04 4.54616618e-04 2.93579824e-05]
 [8.40017059e-05 1.34701220e-04 8.69866146e-06]]
copy(**kwargs)#

Returns a copy of the current object instance. The copy method returns a deep copy of the object, that is independent of the original object.

Parameters:

kwargs (dict) – Keyword arguments (for example position=(1,2,3)) are applied to the copy.

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

Returns a view of the object properties.

Parameters:
  • exclude (bool, default=("style",)) – Properties to be excluded in the description view.

  • return_string (bool, default=`False`) – If False print description with stdout, if True return as string.

property diameter#

Diameter of the sphere in units of m.

property field_func#

The function for B- and H-field computation must have the two positional arguments field and observers. With field=’B’ or field=’H’ the B- or H-field in units of T or A/m must be returned respectively. The observers argument must accept numpy ndarray inputs of shape (n,3), in which case the returned fields must be numpy ndarrays of shape (n,3) themselves.

getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the B-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

B-field – B-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the B-field of a spherical magnet at three positions:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> B = src.getB(((0,0,0), (1,0,0), (2,0,0)))
>>> print(B)
[[ 0.          0.          0.66666667]
 [ 0.          0.         -0.04166667]
 [ 0.          0.         -0.00520833]]

Compute the B-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> B = src.getB(sens1, sens2)
>>> print(B)
[[[ 0.01219289  0.         -0.0398301 ]
  [-0.01219289  0.         -0.0398301 ]]

 [[ 0.00077639  0.         -0.00515004]
  [-0.00077639  0.         -0.00515004]]]
getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

H-field – H-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the H-field of a spherical magnet at three positions:

>>> 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)))
>>> print(H)
[[      0.               0.         -265258.23834209]
 [      0.               0.          -33157.27979276]
 [      0.               0.           -4144.6599741 ]]

Compute the H-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> H = src.getH(sens1, sens2)
>>> print(H)
[[[  9702.79184001      0.         -31695.78667738]
  [ -9702.79184001      0.         -31695.78667738]]

 [[   617.83031344      0.          -4098.27441249]
  [  -617.83031344      0.          -4098.27441249]]]
getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

J-field – J-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the M-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

M-field – M-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

get_trace(vertices=15, **kwargs) Dict[str, Any]#

Create the plotly mesh3d parameters for a Sphere Magnet in a dictionary based on the provided arguments.

property magnetization#

Object magnetization attribute getter and setter.

move(displacement, start='auto')#

Move object by the displacement input. SI units are used for all inputs and outputs.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • displacement (array_like, shape (3,) or (n,3)) – Displacement vector in units of m.

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Move objects around with scalar input:

>>> 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.]]
property orientation#

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

property parent#

The object is a child of it’s parent collection.

property polarization#

Object polarization attribute getter and setter.

property position#

Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

reset_path()#

Set object position to (0,0,0) and orientation = unit rotation.

Returns:

self

Return type:

magpylib object

Examples

Demonstration of reset_path functionality:

>>> 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 object about a given anchor.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotation (None or scipy Rotation object) – Rotation to be applied to the object. The scipy Rotation input can be scalar or vector type (see terminology above). None input is interpreted as unit rotation.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using angle-axis input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • axis (str or array_like, shape (3,)) – The direction of the axis of rotation. Input can be a vector of shape (3,) or a string ‘x’, ‘y’ or ‘z’ to denote respective directions.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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

Rotates object using Euler angle input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • seq (string) – 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, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using matrix input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • matrix (array_like, shape (n,3,3) or (3,3)) – Rotation input. See scipy.spatial.transform.Rotation for details.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Rotate an object about the origin:

>>> 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')#

Rotates object using Modified Rodrigues Parameters (MRPs) input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • mrp (array_like, shape (n,3) or (3,)) – Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs).

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using quaternion input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • quat (array_like, shape (n,4) or (4,)) – Rotation input in quaternion form.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using rotation vector input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotvec (array_like, shape (n,3) or (3,)) – Rotation input. Rotation vector direction is the rotation axis, vector length is the rotation angle in units of rad.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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>, 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 (Magpylib objects (sources, collections, sensors)) – Objects to be displayed.

  • backend (string, default=`None`) – Define plotting backend. Must be one of [‘auto’, ‘matplotlib’, ‘plotly’, ‘pyvista’]. If not set, parameter will default to magpylib.defaults.display.backend which is ‘auto’ by installation default. With ‘auto’, the backend defaults to ‘plotly’ if plotly is installed and the function is called in an IPython environment, otherwise defaults to ‘matplotlib’ which comes installed with magpylib. If the canvas is set, the backend defaults to the one corresponding to the canvas object (see canvas parameter).

  • canvas (matplotlib.pyplot AxesSubplot or plotly Figure object, default=`None`) – Display graphical output on a given canvas: - with matplotlib: matplotlib.axes.Axes with projection=3d. - with plotly: `plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget. - with pyvista: pyvista.Plotter. By default a new canvas is created and immediately displayed.

  • animation (bool or float, default=`False`) – If True and at least one object has a path, the paths are rendered. If input is a positive float, the animation time is set to the given value. This feature is only available for the plotly backend.

  • zoom (float, default=`0`) – Adjust plot zoom-level. When zoom=0 3D-figure boundaries are tight.

  • markers (array_like, shape (n,3), default=`None`) – Display position markers in the global coordinate system.

  • return_fig (bool, default=False) –

    If True, the function call returns the figure object.

    • with matplotlib: matplotlib.figure.Figure.

    • with plotly: plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget.

    • with pyvista: pyvista.Plotter.

  • row (int or None,) – If provided specifies the row in which the objects will be displayed.

  • col (int or None,) – If provided specifies the column in which the objects will be displayed.

  • output (tuple or string, default="model3d") – Can be a string or a tuple of strings specifying the plot output type. By default output=’model3d’ displays the 3D representations of the objects. If output is a tuple of strings it must be a combination of ‘B’, ‘H’, ‘M’ or ‘J’ and ‘x’, ‘y’ and/or ‘z’. When having multiple coordinates, the field value is the combined vector length (e.g. (‘Bx’, ‘Hxy’, ‘Byz’)) ‘Bxy’ is equivalent to sqrt(|Bx|^2 + |By|^2). A 2D line plot is then represented accordingly if the objects contain at least one source and one sensor.

  • sumup (bool, default=True) – If True, sums the field values of the sources. Applies only if output is not ‘model3d’.

  • pixel_agg (bool, default="mean") – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. Applies only if output is not ‘model3d’.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’. Applies to all objects matching the given style properties.

Return type:

None or figure object

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

Object style in the form of a BaseStyle object. Input must be in the form of a style dictionary.

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

Bases: BaseMagnet

Tetrahedron magnet with homogeneous magnetization.

Can be used as sources input for magnetic field computation.

When position=(0,0,0) and orientation=None the Tetrahedron vertices coordinates are the same as in the global coordinate system. The geometric center of the Tetrahedron is determined by its vertices and. It is not necessarily located in the origin an can be computed with the barycenter property.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3)) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path. When setting vertices, the initial position is set to the barycenter.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • vertices (ndarray, shape (4,3)) – Vertices [(x1,y1,z1), (x2,y2,z2), (x3,y3,z3), (x4,y4,z4)], in the relative coordinate system of the tetrahedron.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

barycenter#

Read only property that returns the geometric barycenter (=center of mass) of the object.

Type:

array_like, shape (3,)

Returns:

magnet source

Return type:

Tetrahedron object

Examples

Tetrahedron magnets are magnetic field sources. Below we compute the H-field in A/m of a tetrahedron magnet with polarization (0.1,0.2,0.3) in units of T dimensions defined through the vertices (0,0,0), (.01,0,0), (0,.01,0) and (0,0,.01) in units of m at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> verts = [(0,0,0), (.01,0,0), (0,.01,0), (0,0,.01)]
>>> src = magpy.magnet.Tetrahedron(polarization=(.1,.2,.3), vertices=verts)
>>> H = src.getH((.01,.01,.01))
>>> print(H)
[2070.8978262  1656.71826096 1242.53869572]

We rotate the source object, and compute the B-field, this time at a set of observer positions:

>>> src.rotate_from_angax(45, 'x')
Tetrahedron(id=...)
>>> B = src.getB([(.01,.01,.01), (.02,.02,.02), (.03,.03,.03)])
>>> print(B)
[[ 8.68006559e-04  2.00895792e-03 -5.03469140e-04]
 [ 1.01357229e-04  1.93731796e-04 -1.59677364e-05]
 [ 2.90426931e-05  5.22556994e-05 -1.70596096e-06]]

The same result is obtained when the rotated source moves along a path away from an observer at position (1,1,1). Here we use a Sensor object as observer.

>>> sens = magpy.Sensor(position=(.01,.01,.01))
>>> src.move([(-.01,-.01,-.01), (-.02,-.02,-.02)])
Tetrahedron(id=...)
>>> B = src.getB(sens)
>>> print(B)
[[ 8.68006559e-04  2.00895792e-03 -5.03469140e-04]
 [ 1.01357229e-04  1.93731796e-04 -1.59677364e-05]
 [ 2.90426931e-05  5.22556994e-05 -1.70596096e-06]]
property barycenter#

Object barycenter.

copy(**kwargs)#

Returns a copy of the current object instance. The copy method returns a deep copy of the object, that is independent of the original object.

Parameters:

kwargs (dict) – Keyword arguments (for example position=(1,2,3)) are applied to the copy.

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

Returns a view of the object properties.

Parameters:
  • exclude (bool, default=("style",)) – Properties to be excluded in the description view.

  • return_string (bool, default=`False`) – If False print description with stdout, if True return as string.

property field_func#

The function for B- and H-field computation must have the two positional arguments field and observers. With field=’B’ or field=’H’ the B- or H-field in units of T or A/m must be returned respectively. The observers argument must accept numpy ndarray inputs of shape (n,3), in which case the returned fields must be numpy ndarrays of shape (n,3) themselves.

getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the B-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

B-field – B-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the B-field of a spherical magnet at three positions:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> B = src.getB(((0,0,0), (1,0,0), (2,0,0)))
>>> print(B)
[[ 0.          0.          0.66666667]
 [ 0.          0.         -0.04166667]
 [ 0.          0.         -0.00520833]]

Compute the B-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> B = src.getB(sens1, sens2)
>>> print(B)
[[[ 0.01219289  0.         -0.0398301 ]
  [-0.01219289  0.         -0.0398301 ]]

 [[ 0.00077639  0.         -0.00515004]
  [-0.00077639  0.         -0.00515004]]]
getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

H-field – H-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the H-field of a spherical magnet at three positions:

>>> 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)))
>>> print(H)
[[      0.               0.         -265258.23834209]
 [      0.               0.          -33157.27979276]
 [      0.               0.           -4144.6599741 ]]

Compute the H-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> H = src.getH(sens1, sens2)
>>> print(H)
[[[  9702.79184001      0.         -31695.78667738]
  [ -9702.79184001      0.         -31695.78667738]]

 [[   617.83031344      0.          -4098.27441249]
  [  -617.83031344      0.          -4098.27441249]]]
getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

J-field – J-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the M-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

M-field – M-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

get_trace(**kwargs) Dict[str, Any]#

Create the plotly mesh3d parameters for a Tetrahedron Magnet in a dictionary based on the provided arguments.

property magnetization#

Object magnetization attribute getter and setter.

move(displacement, start='auto')#

Move object by the displacement input. SI units are used for all inputs and outputs.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • displacement (array_like, shape (3,) or (n,3)) – Displacement vector in units of m.

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Move objects around with scalar input:

>>> 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.]]
property orientation#

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

property parent#

The object is a child of it’s parent collection.

property polarization#

Object polarization attribute getter and setter.

property position#

Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

reset_path()#

Set object position to (0,0,0) and orientation = unit rotation.

Returns:

self

Return type:

magpylib object

Examples

Demonstration of reset_path functionality:

>>> 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 object about a given anchor.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotation (None or scipy Rotation object) – Rotation to be applied to the object. The scipy Rotation input can be scalar or vector type (see terminology above). None input is interpreted as unit rotation.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using angle-axis input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • axis (str or array_like, shape (3,)) – The direction of the axis of rotation. Input can be a vector of shape (3,) or a string ‘x’, ‘y’ or ‘z’ to denote respective directions.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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

Rotates object using Euler angle input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • seq (string) – 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, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using matrix input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • matrix (array_like, shape (n,3,3) or (3,3)) – Rotation input. See scipy.spatial.transform.Rotation for details.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Rotate an object about the origin:

>>> 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')#

Rotates object using Modified Rodrigues Parameters (MRPs) input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • mrp (array_like, shape (n,3) or (3,)) – Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs).

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using quaternion input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • quat (array_like, shape (n,4) or (4,)) – Rotation input in quaternion form.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using rotation vector input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotvec (array_like, shape (n,3) or (3,)) – Rotation input. Rotation vector direction is the rotation axis, vector length is the rotation angle in units of rad.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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>, 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 (Magpylib objects (sources, collections, sensors)) – Objects to be displayed.

  • backend (string, default=`None`) – Define plotting backend. Must be one of [‘auto’, ‘matplotlib’, ‘plotly’, ‘pyvista’]. If not set, parameter will default to magpylib.defaults.display.backend which is ‘auto’ by installation default. With ‘auto’, the backend defaults to ‘plotly’ if plotly is installed and the function is called in an IPython environment, otherwise defaults to ‘matplotlib’ which comes installed with magpylib. If the canvas is set, the backend defaults to the one corresponding to the canvas object (see canvas parameter).

  • canvas (matplotlib.pyplot AxesSubplot or plotly Figure object, default=`None`) – Display graphical output on a given canvas: - with matplotlib: matplotlib.axes.Axes with projection=3d. - with plotly: `plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget. - with pyvista: pyvista.Plotter. By default a new canvas is created and immediately displayed.

  • animation (bool or float, default=`False`) – If True and at least one object has a path, the paths are rendered. If input is a positive float, the animation time is set to the given value. This feature is only available for the plotly backend.

  • zoom (float, default=`0`) – Adjust plot zoom-level. When zoom=0 3D-figure boundaries are tight.

  • markers (array_like, shape (n,3), default=`None`) – Display position markers in the global coordinate system.

  • return_fig (bool, default=False) –

    If True, the function call returns the figure object.

    • with matplotlib: matplotlib.figure.Figure.

    • with plotly: plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget.

    • with pyvista: pyvista.Plotter.

  • row (int or None,) – If provided specifies the row in which the objects will be displayed.

  • col (int or None,) – If provided specifies the column in which the objects will be displayed.

  • output (tuple or string, default="model3d") – Can be a string or a tuple of strings specifying the plot output type. By default output=’model3d’ displays the 3D representations of the objects. If output is a tuple of strings it must be a combination of ‘B’, ‘H’, ‘M’ or ‘J’ and ‘x’, ‘y’ and/or ‘z’. When having multiple coordinates, the field value is the combined vector length (e.g. (‘Bx’, ‘Hxy’, ‘Byz’)) ‘Bxy’ is equivalent to sqrt(|Bx|^2 + |By|^2). A 2D line plot is then represented accordingly if the objects contain at least one source and one sensor.

  • sumup (bool, default=True) – If True, sums the field values of the sources. Applies only if output is not ‘model3d’.

  • pixel_agg (bool, default="mean") – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. Applies only if output is not ‘model3d’.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’. Applies to all objects matching the given style properties.

Return type:

None or figure object

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

Object style in the form of a BaseStyle object. Input must be in the form of a style dictionary.

property vertices#

Length of the Tetrahedron sides [a,b,c] in units of m.

class magpylib.magnet.TriangularMesh(position=(0, 0, 0), orientation=None, vertices=None, faces=None, polarization=None, magnetization=None, check_open='warn', check_disconnected='warn', check_selfintersecting='warn', reorient_faces='warn', style=None, **kwargs)#

Bases: BaseMagnet

Magnet with homogeneous magnetization defined by triangular surface mesh. Can be used as sources input for magnetic field computation.

When position=(0,0,0) and orientation=None the TriangularMesh vertices are the same as in the global coordinate system.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3), default=`(0,0,0)`) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • vertices (ndarray, shape (n,3)) – A set of points in units of m in the local object coordinates from which the triangular faces of the mesh are constructed by the additional `faces`input.

  • faces (ndarray, shape (n,3)) – Indices of vertices. Each triplet represents one triangle of the mesh.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • reorient_faces (bool or string, default=`True`) – In a properly oriented mesh, all faces must be oriented outwards. If True, check and fix the orientation of each triangle. Options are ‘skip’`(=`False), ‘warn’`(=`True), ‘raise’, ‘ignore’.

  • check_open (bool or string, default=`True`) – Only a closed mesh guarantees correct B-field computation. If True, check if mesh is open. Options are ‘skip’`(=`False), ‘warn’`(=`True), ‘raise’, ‘ignore’.

  • check_disconnected (bool or string, default=`True`) – Individual magnets should be connected bodies to avoid confusion. If True, check if mesh is disconnected. Options are ‘skip’`(=`False), ‘warn’`(=`True), ‘raise’, ‘ignore’.

  • check_selfintersecting (bool, optional) – a proper body cannot have a self-intersecting mesh. If True, check if mesh is self-intersecting. Options are ‘skip’`(=`False), ‘warn’`(=`True), ‘raise’, ‘ignore’.

  • check_selfintersecting – If True, the provided set of facets is validated by checking if the body is not self-intersecting. Can be deactivated for performance reasons by setting it to False.

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Notes

Faces are automatically reoriented since scipy.spatial.ConvexHull objects do not guarantee that the faces are all pointing outwards. A mesh validation is also performed.

Returns:

magnet source

Return type:

TriangularMesh object

Examples

We compute the B-field in units of T of a triangular mesh (4 vertices, 4 faces) with polarization (0.1,0.2,0.3) in units of T at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> vv = ((0,0,0), (.01,0,0), (0,.01,0), (0,0,.01))
>>> tt = ((0,1,2), (0,1,3), (0,2,3), (1,2,3))
>>> trim = magpy.magnet.TriangularMesh(polarization=(.1,.2,.3), vertices=vv, faces=tt)
>>> print(trim.getB((.01,.01,.01)))
[0.00260237 0.00208189 0.00156142]
property barycenter#

Object barycenter.

check_disconnected(mode='warn')#

Check whether the mesh is connected.

This function checks if the mesh is connected. If the mesh is not connected, it issues a warning or raises a ValueError, depending on the ‘mode’ parameter. If ‘mode’ is set to ‘ignore’, it does not issue a warning or raise an error.

Parameters:

mode (str, optional) – Controls how to handle if the mesh is not connected. Accepted values are “warn”, “raise”, or “ignore”. If “warn”, a warning is issued. If “raise”, a ValueError is raised. If “ignore”, no action is taken. By default “warn”.

Returns:

True if the mesh is disconnected, False otherwise.

Return type:

bool

Raises:

ValueError – If ‘mode’ is not one of the accepted values or if ‘mode’ is “raise” and the mesh is disconnected.

Warns:

UserWarning – If the mesh is disconnected and ‘mode’ is “warn”.

check_open(mode='warn')#

Check whether the mesh is closed.

This function checks if the mesh is closed. If the mesh is not closed, it issues a warning or raises a ValueError, depending on the ‘mode’ parameter. If ‘mode’ is set to ‘ignore’, it does not issue a warning or raise an error.

Parameters:

mode (str, optional) – Controls how to handle if the mesh is not closed. Accepted values are “warn”, “raise”, or “ignore”. If “warn”, a warning is issued. If “raise”, a ValueError is raised. If “ignore”, no action is taken. By default “warn”.

Returns:

True if the mesh is open, False otherwise.

Return type:

bool

Raises:

ValueError – If ‘mode’ is not one of the accepted values or if ‘mode’ is “raise” and the mesh is open.

Warns:

UserWarning – If the mesh is open and ‘mode’ is “warn”.

check_selfintersecting(mode='warn')#

Check whether the mesh is self-intersecting.

This function checks if the mesh is self-intersecting. If the mesh is self-intersecting, it issues a warning or raises a ValueError, depending on the ‘mode’ parameter. If ‘mode’ is set to ‘ignore’, it does not issue a warning or raise an error.

Parameters:

mode (str, optional) – Controls how to handle if the mesh is self-intersecting. Accepted values are “warn”, “raise”, or “ignore”. If “warn”, a warning is issued. If “raise”, a ValueError is raised. If “ignore”, no action is taken. By default “warn”.

Returns:

True if the mesh is self-intersecting, False otherwise.

Return type:

bool

Raises:

ValueError – If ‘mode’ is not one of the accepted values or if ‘mode’ is “raise” and the mesh is self-intersecting.

Warns:

UserWarning – If the mesh is self-intersecting and ‘mode’ is “warn”.

copy(**kwargs)#

Returns a copy of the current object instance. The copy method returns a deep copy of the object, that is independent of the original object.

Parameters:

kwargs (dict) – Keyword arguments (for example position=(1,2,3)) are applied to the copy.

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

Returns a view of the object properties.

Parameters:
  • exclude (bool, default=("style",)) – Properties to be excluded in the description view.

  • return_string (bool, default=`False`) – If False print description with stdout, if True return as string.

property faces#

Mesh faces

property field_func#

The function for B- and H-field computation must have the two positional arguments field and observers. With field=’B’ or field=’H’ the B- or H-field in units of T or A/m must be returned respectively. The observers argument must accept numpy ndarray inputs of shape (n,3), in which case the returned fields must be numpy ndarrays of shape (n,3) themselves.

classmethod from_ConvexHull(position=(0, 0, 0), orientation=None, points=None, polarization=None, magnetization=None, check_open='warn', check_disconnected='warn', reorient_faces=True, style=None, **kwargs)#

Create a TriangularMesh magnet from a point cloud via its convex hull.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3)) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • points (ndarray, shape (n,3)) – Point cloud from which the convex hull is computed.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • reorient_faces (bool, default=`True`) – In a properly oriented mesh, all faces must be oriented outwards. If True, check and fix the orientation of each triangle.

  • check_open ({'warn', 'raise', 'ignore'}, default='warn') – Only a closed mesh guarantees a physical magnet. If the mesh is open and “warn”, a warning is issued. If the mesh is open and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_disconnected ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is disconnected and “warn”, a warning is issued. If the mesh is disconnected and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_selfintersecting ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is self-intersecting and “warn”, a warning is issued. If the mesh is self-intersecting and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Notes

Faces are automatically reoriented since scipy.spatial.ConvexHull objects do not guarantee that the faces are all pointing outwards. A mesh validation is also performed.

Returns:

magnet source

Return type:

TriangularMesh object

Examples

classmethod from_mesh(position=(0, 0, 0), orientation=None, mesh=None, polarization=None, magnetization=None, reorient_faces=True, check_open='warn', check_disconnected='warn', style=None, **kwargs)#

Create a TriangularMesh magnet from a mesh input.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3)) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • mesh (array_like, shape (n,3,3)) – An array_like of triangular faces that make up a triangular mesh.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • reorient_faces (bool, default=`True`) – In a properly oriented mesh, all faces must be oriented outwards. If True, check and fix the orientation of each triangle.

  • check_open ({'warn', 'raise', 'ignore'}, default='warn') – Only a closed mesh guarantees a physical magnet. If the mesh is open and “warn”, a warning is issued. If the mesh is open and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_disconnected ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is disconnected and “warn”, a warning is issued. If the mesh is disconnected and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_selfintersecting ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is self-intersecting and “warn”, a warning is issued. If the mesh is self-intersecting and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Notes

Faces are automatically reoriented since pyvista.core.pointset.PolyData objects do not guarantee that the faces are all pointing outwards. A mesh validation is also performed.

Returns:

magnet source

Return type:

TriangularMesh object

Examples

classmethod from_pyvista(position=(0, 0, 0), orientation=None, polydata=None, polarization=None, magnetization=None, check_open='warn', check_disconnected='warn', reorient_faces=True, style=None, **kwargs)#

Create a TriangularMesh magnet from a pyvista PolyData mesh object.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3)) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • polydata (pyvista.core.pointset.PolyData object) – A valid pyvista Polydata mesh object. (e.g. pyvista.Sphere())

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • reorient_faces (bool, default=`True`) – In a properly oriented mesh, all faces must be oriented outwards. If True, check and fix the orientation of each triangle.

  • check_open ({'warn', 'raise', 'ignore'}, default='warn') – Only a closed mesh guarantees a physical magnet. If the mesh is open and “warn”, a warning is issued. If the mesh is open and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_disconnected ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is disconnected and “warn”, a warning is issued. If the mesh is disconnected and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_selfintersecting ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is self-intersecting and “warn”, a warning is issued. If the mesh is self-intersecting and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Notes

Faces are automatically reoriented since pyvista.core.pointset.PolyData objects do not guarantee that the faces are all pointing outwards. A mesh validation is also performed.

Returns:

magnet source

Return type:

TriangularMesh object

Examples

classmethod from_triangles(position=(0, 0, 0), orientation=None, triangles=None, polarization=None, magnetization=None, reorient_faces=True, check_open='warn', check_disconnected='warn', style=None, **kwargs)#

Create a TriangularMesh magnet from a list or Collection of Triangle objects.

SI units are used for all inputs and outputs.

Parameters:
  • position (array_like, shape (3,) or (m,3)) – Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

  • orientation (scipy Rotation object with length 1 or m, default=`None`) – Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

  • triangles (list or Collection of Triangle objects) – Only vertices of Triangle objects are taken, magnetization is ignored.

  • polarization (array_like, shape (3,), default=`None`) – Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

  • magnetization (array_like, shape (3,), default=`None`) – Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

  • reorient_faces (bool, default=`True`) – In a properly oriented mesh, all faces must be oriented outwards. If True, check and fix the orientation of each triangle.

  • check_open ({'warn', 'raise', 'ignore'}, default='warn') – Only a closed mesh guarantees a physical magnet. If the mesh is open and “warn”, a warning is issued. If the mesh is open and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_disconnected ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is disconnected and “warn”, a warning is issued. If the mesh is disconnected and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • check_selfintersecting ({'warn', 'raise', 'ignore'}, default='warn') – If the mesh is self-intersecting and “warn”, a warning is issued. If the mesh is self-intersecting and “raise”, a ValueError is raised. If “ignore”, no mesh check is performed.

  • parent (Collection object or None) – The object is a child of it’s parent collection.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’.

Notes

Faces are automatically reoriented since pyvista.core.pointset.PolyData objects do not guarantee that the faces are all pointing outwards. A mesh validation is also performed.

Returns:

magnet source

Return type:

TriangularMesh object

Examples

getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the B-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

B-field – B-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the B-field of a spherical magnet at three positions:

>>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> B = src.getB(((0,0,0), (1,0,0), (2,0,0)))
>>> print(B)
[[ 0.          0.          0.66666667]
 [ 0.          0.         -0.04166667]
 [ 0.          0.         -0.00520833]]

Compute the B-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> B = src.getB(sens1, sens2)
>>> print(B)
[[[ 0.01219289  0.         -0.0398301 ]
  [-0.01219289  0.         -0.0398301 ]]

 [[ 0.00077639  0.         -0.00515004]
  [-0.00077639  0.         -0.00515004]]]
getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

H-field – H-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

Examples

Compute the H-field of a spherical magnet at three positions:

>>> 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)))
>>> print(H)
[[      0.               0.         -265258.23834209]
 [      0.               0.          -33157.27979276]
 [      0.               0.           -4144.6599741 ]]

Compute the H-field at two sensors, each one with two pixels

>>> sens1 = magpy.Sensor(position=(1,0,0), pixel=((0,0,.1), (0,0,-.1)))
>>> sens2 = sens1.copy(position=(2,0,0))
>>> H = src.getH(sens1, sens2)
>>> print(H)
[[[  9702.79184001      0.         -31695.78667738]
  [ -9702.79184001      0.         -31695.78667738]]

 [[   617.83031344      0.          -4098.27441249]
  [  -617.83031344      0.          -4098.27441249]]]
getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field at observers in units of T generated by the source.

SI units are used for all inputs and outputs.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

J-field – J-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of T. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the M-field in units of A/m at observers generated by the source.

Parameters:
  • observers (array_like or (list of) Sensor objects) – Can be array_like positions of shape (n1, n2, …, 3) where the field should be evaluated, a Sensor object with pixel shape (n1, n2, …, 3) or a list of such sensor objects (must all have similar pixel shapes). All positions are given in units of m.

  • squeeze (bool, default=`True`) – If True, the output is squeezed, i.e. all axes of length 1 in the output (e.g. only a single source) are eliminated.

  • pixel_agg (str, default=`None`) – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. With this option, observers input with different (pixel) shapes is allowed.

  • output (str, default='ndarray') – Output type, which must be one of (‘ndarray’, ‘dataframe’). By default a multi- dimensional array (‘ndarray’) is returned. If ‘dataframe’ is chosen, the function returns a 2D-table as a pandas.DataFrame object (the Pandas library must be installed).

  • in_out ({'auto', 'inside', 'outside'}) –

    This parameter only applies for magnet bodies. It specifies the location of the observers relative to the magnet body, affecting the calculation of the magnetic field. The options are: - ‘auto’: The location (inside or outside the cuboid) is determined automatically for each observer. - ‘inside’: All observers are considered to be inside the cuboid; use this for

    performance optimization if applicable.

    • ’outside’: All observers are considered to be outside the cuboid; use this for performance optimization if applicable.

    Choosing ‘auto’ is fail-safe but may be computationally intensive if the mix of observer locations is unknown.

Returns:

M-field – M-field at each path position (index m) for each sensor (index k) and each sensor pixel position (indices n1,n2,…) in units of A/m. Sensor pixel positions are equivalent to simple observer positions. Paths of objects that are shorter than index m will be considered as static beyond their end.

Return type:

ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame

get_faces_subsets()#

Obtain and return subsets of the mesh. If the mesh has n parts, returns and list of length n of faces (m,3) vertices indices triplets corresponding to each part.

Returns:

status_disconnected_data – Subsets of faces data.

Return type:

list of numpy.ndarray

get_open_edges()#

Obtain and return the potential open edges. If the mesh has n open edges, returns an corresponding (n,2) array of vertices indices doubles.

Returns:

status_open_data – Open edges data.

Return type:

numpy.ndarray

get_selfintersecting_faces()#

Obtain and return the potential self intersecting faces indices. If the mesh has n intersecting faces, returns a corresponding 1D array length n faces indices.

Returns:

status_open_data – Open edges data.

Return type:

numpy.ndarray

get_trace(**kwargs) Dict[str, Any] | List[Dict[str, Any]]#

Creates the plotly mesh3d parameters for a Trianglular facet mesh in a dictionary based on the provided arguments.

property magnetization#

Object magnetization attribute getter and setter.

property mesh#

Mesh

move(displacement, start='auto')#

Move object by the displacement input. SI units are used for all inputs and outputs.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • displacement (array_like, shape (3,) or (n,3)) – Displacement vector in units of m.

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Move objects around with scalar input:

>>> 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.]]
property orientation#

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation. For m>1, the position and orientation attributes together represent an object path.

property parent#

The object is a child of it’s parent collection.

property polarization#

Object polarization attribute getter and setter.

property position#

Object position(s) in the global coordinates in units of m. For m>1, the position and orientation attributes together represent an object path.

reorient_faces(mode='warn')#

Correctly reorients the mesh’s faces.

In a properly oriented mesh, all faces must be oriented outwards. This function fixes the orientation of each face. It issues a warning or raises a ValueError, depending on the ‘mode’ parameter. If ‘mode’ is set to ‘ignore’, it does not issue a warning or raise an error. Note that this parameter is passed on the check_closed() function as the mesh is only orientable if it is closed.

Parameters:

mode (str, optional) – Controls how to handle if the mesh is open and not orientable. Accepted values are “warn”, “raise”, or “ignore”. If “warn”, a warning is issued. If “raise”, a ValueError is raised. If “ignore”, no action is taken. By default “warn”.

Returns:

True if the mesh is connected, False otherwise.

Return type:

bool

Raises:

ValueError – If ‘mode’ is not one of the accepted values or if ‘mode’ is “raise” and the mesh is open and not orientable.

Warns:

UserWarning – If the mesh is not connected and ‘mode’ is “warn”.

reset_path()#

Set object position to (0,0,0) and orientation = unit rotation.

Returns:

self

Return type:

magpylib object

Examples

Demonstration of reset_path functionality:

>>> 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 object about a given anchor.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotation (None or scipy Rotation object) – Rotation to be applied to the object. The scipy Rotation input can be scalar or vector type (see terminology above). None input is interpreted as unit rotation.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using angle-axis input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • axis (str or array_like, shape (3,)) – The direction of the axis of rotation. Input can be a vector of shape (3,) or a string ‘x’, ‘y’ or ‘z’ to denote respective directions.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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

Rotates object using Euler angle input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • angle (int, float or array_like with shape (n,)) – Angle(s) of rotation in units of deg (by default).

  • seq (string) – 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, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using matrix input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • matrix (array_like, shape (n,3,3) or (3,3)) – Rotation input. See scipy.spatial.transform.Rotation for details.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

Examples

Rotate an object about the origin:

>>> 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')#

Rotates object using Modified Rodrigues Parameters (MRPs) input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • mrp (array_like, shape (n,3) or (3,)) – Rotation input. See scipy Rotation package for details on Modified Rodrigues Parameters (MRPs).

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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')#

Rotates object using quaternion input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • quat (array_like, shape (n,4) or (4,)) – Rotation input in quaternion form.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

Returns:

self

Return type:

Magpylib object

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

Rotates object using rotation vector input.

Terminology for move/rotate methods:

  • path refers to position and orientation of an object.

  • When an input is just a single operation (e.g. one displacement vector or one angle) we call it ‘scalar input’. When it is an array_like of multiple scalars, we refer to it as ‘vector input’.

General move/rotate behavior:

  • Scalar input is applied to the whole object path, starting with path index start.

  • Vector input of length n applies the individual n operations to n object path entries, starting with path index start.

  • When an input extends beyond the object 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 [=move whole object path], and to start=len(object path) for vector input [=append to existing object path].

Parameters:
  • rotvec (array_like, shape (n,3) or (3,)) – Rotation input. Rotation vector direction is the rotation axis, vector length is the rotation angle in units of rad.

  • anchor (None, 0 or array_like with shape (3,) or (n,3), default=`None`) – The axis of rotation passes through the anchor point given in units of m. By default (anchor=None) the object will rotate about its own center. anchor=0 rotates the object about the origin (0,0,0).

  • start (int or str, default=`'auto'`) – Starting index when applying operations. See ‘General move/rotate behavior’ above for details.

  • degrees (bool, default=`True`) – Interpret input in units of deg or rad.

Returns:

self

Return type:

Magpylib object

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>, 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 (Magpylib objects (sources, collections, sensors)) – Objects to be displayed.

  • backend (string, default=`None`) – Define plotting backend. Must be one of [‘auto’, ‘matplotlib’, ‘plotly’, ‘pyvista’]. If not set, parameter will default to magpylib.defaults.display.backend which is ‘auto’ by installation default. With ‘auto’, the backend defaults to ‘plotly’ if plotly is installed and the function is called in an IPython environment, otherwise defaults to ‘matplotlib’ which comes installed with magpylib. If the canvas is set, the backend defaults to the one corresponding to the canvas object (see canvas parameter).

  • canvas (matplotlib.pyplot AxesSubplot or plotly Figure object, default=`None`) – Display graphical output on a given canvas: - with matplotlib: matplotlib.axes.Axes with projection=3d. - with plotly: `plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget. - with pyvista: pyvista.Plotter. By default a new canvas is created and immediately displayed.

  • animation (bool or float, default=`False`) – If True and at least one object has a path, the paths are rendered. If input is a positive float, the animation time is set to the given value. This feature is only available for the plotly backend.

  • zoom (float, default=`0`) – Adjust plot zoom-level. When zoom=0 3D-figure boundaries are tight.

  • markers (array_like, shape (n,3), default=`None`) – Display position markers in the global coordinate system.

  • return_fig (bool, default=False) –

    If True, the function call returns the figure object.

    • with matplotlib: matplotlib.figure.Figure.

    • with plotly: plotly.graph_objects.Figure or plotly.graph_objects.FigureWidget.

    • with pyvista: pyvista.Plotter.

  • row (int or None,) – If provided specifies the row in which the objects will be displayed.

  • col (int or None,) – If provided specifies the column in which the objects will be displayed.

  • output (tuple or string, default="model3d") – Can be a string or a tuple of strings specifying the plot output type. By default output=’model3d’ displays the 3D representations of the objects. If output is a tuple of strings it must be a combination of ‘B’, ‘H’, ‘M’ or ‘J’ and ‘x’, ‘y’ and/or ‘z’. When having multiple coordinates, the field value is the combined vector length (e.g. (‘Bx’, ‘Hxy’, ‘Byz’)) ‘Bxy’ is equivalent to sqrt(|Bx|^2 + |By|^2). A 2D line plot is then represented accordingly if the objects contain at least one source and one sensor.

  • sumup (bool, default=True) – If True, sums the field values of the sources. Applies only if output is not ‘model3d’.

  • pixel_agg (bool, default="mean") – Reference to a compatible numpy aggregator function like ‘min’ or ‘mean’, which is applied to observer output values, e.g. mean of all sensor pixel outputs. Applies only if output is not ‘model3d’.

  • style (dict) – Object style inputs must be in dictionary form, e.g. {‘color’:’red’} or using style underscore magic, e.g. style_color=’red’. Applies to all objects matching the given style properties.

Return type:

None or figure object

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

Return disconnected status

property status_disconnected_data#

Status for connectedness (faces subsets)

property status_open#

Return open status

property status_open_data#

Status for openness (open edges)

property status_reoriented#

Return reoriented status

property status_selfintersecting#

Is-selfintersecting boolean check

property status_selfintersecting_data#

return self-intersecting faces

property style#

Object style in the form of a BaseStyle object. Input must be in the form of a style dictionary.

to_TriangleCollection()#

Return a Collection of Triangle objects from the current TriangularMesh

property vertices#

Mesh vertices