magpylib package#

Welcome to Magpylib !#

Magpylib is a Python package for calculating 3D static magnetic fields of magnets, line currents and other sources. The computation is based on analytical expressions and therefore extremely fast. A user friendly geometry interface enables convenient relative positioning between sources and observers.

Help us develop the package further - we appreciate any feedback !

Resources#

Documentation and examples on Read-the-docs:

https://magpylib.readthedocs.io/en/latest/

Our Github repository:

magpylib/magpylib

The original software publication (version 2):

https://www.sciencedirect.com/science/article/pii/S2352711020300170

class magpylib.Collection(*args, position=(0, 0, 0), orientation=None, override_parent=False, style=None, **kwargs)#

Bases: BaseGeo, BaseCollection

Group multiple children (sources, sensors and collections) in a collection for common manipulation.

Collections span a local reference frame. All objects in a collection are held to that reference frame when an operation (e.g. move, rotate, setter, …) is applied to the collection.

Collections can be used as sources and observers input for magnetic field computation. For magnetic field computation a collection that contains sources functions like a single source. When the collection contains sensors it functions like a list of all its sensors.

SI units are used for all inputs and outputs.

Parameters:
  • children (sources, Sensor or Collection objects) – An ordered list of all children in the collection.

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

  • override_parent (bool, default=False) – If False thrown an error when an attempt is made to add an object that has already a parent to a Collection. If True, allow adding the object and override the objects parent attribute thus removing it from its previous collection.

  • sensors (Sensor objects) – An ordered list of all sensor objects in the collection.

  • sources (Source objects) – An ordered list of all source objects (magnets, currents, misc) in the collection.

  • collections (Collection objects) – An ordered list of all collection objects in the collection.

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:

collection

Return type:

Collection object

Examples

Collections function as groups of multiple magpylib objects. In this example we create a collection with two sources and move the whole collection:

>>> import magpylib as magpy
>>> src1 = magpy.magnet.Sphere(position=(2,0,0), diameter=1,polarization=(.1,.2,.3))
>>> src2 = magpy.current.Circle(position=(-2,0,0), diameter=1, current=1)
>>> col = magpy.Collection(src1, src2)
>>> col.move(((0,0,2)))
Collection(id=...)
>>> print(src1.position)
[2. 0. 2.]
>>> print(src2.position)
[-2.  0.  2.]
>>> print(col.position)
[0. 0. 2.]

We can still directly access individual objects by name and by index:

>>> src1.move((2,0,0))
Sphere(id=...)
>>> col[1].move((-2,0,0))
Circle(id=...)
>>> print(src1.position)
[4. 0. 2.]
>>> print(src2.position)
[-4.  0.  2.]
>>> print(col.position)
[0. 0. 2.]

The field can be computed at position (0,0,0) as if the collection was a single source:

>>> B = col.getB((0,0,0))
>>> print(B)
[ 2.32922681e-04 -9.31694991e-05 -3.44484717e-10]

We add a sensor at position (0,0,0) to the collection:

>>> sens = magpy.Sensor()
>>> col.add(sens)
Collection(id=...)
>>> print(col.children)
[Sphere(id=...), Circle(id=...), Sensor(id=...)]

and can compute the field of the sources in the collection seen by the sensor with a single command:

>>> B = col.getB()
>>> print(B)
[ 2.32922681e-04 -9.31694991e-05 -3.44484717e-10]
add(*children, override_parent=False)#

Add sources, sensors or collections.

Parameters:
  • children (sources, sensors or collections) – Add arbitrary sources, sensors or other collections to this collection.

  • override_parent (bool, default=`True`) – Accept objects as children that already have parents. Automatically removes such objects from previous parent collection.

Returns:

self

Return type:

Collection object

Examples

In this example we add a sensor object to a collection:

>>> import magpylib as magpy
>>> x1 = magpy.Sensor(style_label='x1')
>>> coll = magpy.Collection(x1, style_label='coll')
>>> coll.describe(format='label')
coll
└── x1
>>> x2 = magpy.Sensor(style_label='x2')
>>> coll.add(x2)
Collection(id=...)
>>> coll.describe(format='label')
coll
├── x1
└── x2
property children#

An ordered list of top level child objects.

property children_all#

An ordered list of all child objects in the collection tree.

property collections#

An ordered list of top level collection objects.

property collections_all#

An ordered list of all collection objects in the collection tree.

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(format='type+label+id', max_elems=10, return_string=False)#

Returns or prints a tree view of the collection.

Parameters:
  • format (bool, default='type+label+id') – Object description in tree view. Can be any combination of ‘type’, ‘label’ and ‘id’ and ‘properties’.

  • max_elems (default=10) – If number of children at any level is higher than max_elems, elements are replaced by counters.

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

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

Compute B-field for given sources and observers.

SI units are used for all inputs and outputs.

Parameters:
  • inputs (source or observer objects) – Input can only be observers if the collection contains only sources. In this case the collection behaves like a single source. Input can only be sources if the collection contains only sensors. In this case the collection behaves like a list of all its sensors.

  • 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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 are considered as static beyond their end.

Return type:

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

Examples

In this example we create a collection from two sources and two sensors:

>>> import magpylib as magpy
>>> src1 = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> src2 = src1.copy()
>>> sens1 = magpy.Sensor(position=(0,0,1))
>>> sens2 = sens1.copy()
>>> col = src1 + src2 + sens1 + sens2

The following computations all give the same result:

>>> B = col.getB()
>>> B = magpy.getB(col, col)
>>> B = magpy.getB(col, [sens1, sens2])
>>> B = magpy.getB([src1, src2], col)
>>> B = magpy.getB([src1, src2], [sens1, sens2])
>>> print(B)
[[[0.         0.         0.08333333]
  [0.         0.         0.08333333]]

 [[0.         0.         0.08333333]
  [0.         0.         0.08333333]]]
getH(*inputs, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute H-field for given sources and observers.

SI units are used for all inputs and outputs.

Parameters:
  • inputs (source or observer objects) – Input can only be observers if the collection contains only sources. In this case the collection behaves like a single source. Input can only be sources if the collection contains sensors. In this case the collection behaves like a list of all its sensors.

  • 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (the Pandas library must be installed).

Returns:

  • H-field (ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame) – 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 are considered as static beyond their end.

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

Examples

In this example we create a collection from two sources and two sensors:

>>> import magpylib as magpy
>>> src1 = magpy.magnet.Sphere(polarization=(0,0,1.), diameter=1)
>>> src2 = src1.copy()
>>> sens1 = magpy.Sensor(position=(0,0,1))
>>> sens2 = sens1.copy()
>>> col = src1 + src2 + sens1 + sens2

The following computations all give the same result:

>>> H = col.getH()
>>> H = magpy.getH(col, col)
>>> H = magpy.getH(col, [sens1, sens2])
>>> H = magpy.getH([src1, src2], col)
>>> H = magpy.getH([src1, src2], [sens1, sens2])
>>> print(H)
[[[    0.             0.         66314.55958552]
  [    0.             0.         66314.55958552]]

 [[    0.             0.         66314.55958552]
  [    0.             0.         66314.55958552]]]
getJ(*inputs, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute J-field for given sources and observers.

SI units are used for all inputs and outputs.

Parameters:
  • inputs (source or observer objects) – Input can only be observers if the collection contains only sources. In this case the collection behaves like a single source. Input can only be sources if the collection contains only sensors. In this case the collection behaves like a list of all its sensors.

  • 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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 are considered as static beyond their end.

Return type:

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

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

Compute M-field for given sources and observers.

SI units are used for all inputs and outputs.

Parameters:
  • inputs (source or observer objects) – Input can only be observers if the collection contains only sources. In this case the collection behaves like a single source. Input can only be sources if the collection contains sensors. In this case the collection behaves like a list of all its sensors.

  • 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (the Pandas library must be installed).

Returns:

  • M-field (ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame) – 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 are considered as static beyond their end.

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

get_trace = None#
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 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.

remove(*children, recursive=True, errors='raise')#

Remove children from the collection tree.

Parameters:
  • children (child objects) – Remove the given children from the collection.

  • recursive (bool, default=`True`) – Remove children also when they are in child collections.

  • errors (str, default=`'raise'`) – Can be ‘raise’ or ‘ignore’ to toggle error output when child is not found for removal.

Returns:

self

Return type:

Collection object

Examples

In this example we remove a child from a Collection:

>>> import magpylib as magpy
>>> x1 = magpy.Sensor(style_label='x1')
>>> x2 = magpy.Sensor(style_label='x2')
>>> col = magpy.Collection(x1, x2, style_label='col')
>>> col.describe(format='label')
col
├── x1
└── x2
>>> col.remove(x1)
Collection(id=...)
>>> col.describe(format='label')
col
└── x2
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.]]
property sensors#

An ordered list of top level sensor objects.

property sensors_all#

An ordered list of all sensor objects in the collection tree.

set_children_styles(arg=None, recursive=True, _validate=True, **kwargs)#

Set display style of all children in the collection. Only matching properties will be applied.

Parameters:
  • arg (style dictionary or style underscore magic input) – Style arguments to be applied.

  • recursive (bool, default=`True`) – Apply styles also to children of child collections.

Returns:

self

Return type:

Collection object

Examples

In this example we start by creating a collection from three sphere magnets:

>>> import magpylib as magpy
>>>
>>> col = magpy.Collection(
...     [
...         magpy.magnet.Sphere(position=(i, 0, 0), diameter=1, polarization=(0, 0, 0.1))
...         for i in range(3)
...     ]
... )
>>> # We apply styles using underscore magic for magnetization vector size and a style
>>> # dictionary for the color.
>>>
>>> col.set_children_styles(magnetization_size=0.5)
Collection(id=...)
>>> col.set_children_styles({"color": "g"})
Collection(id=...)
>>>
>>> # Finally we create a separate sphere magnet to demonstrate the default style
>>> # the collection and the separate magnet with Matplotlib:
>>>
>>> src = magpy.magnet.Sphere(position=(3, 0, 0), diameter=1, polarization=(0, 0, .1))
>>> magpy.show(col, src) 
>>> # graphic output
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 sources#

An ordered list of top level source objects.

property sources_all#

An ordered list of all source objects in the collection tree.

property style#

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

class magpylib.Sensor(position=(0, 0, 0), orientation=None, pixel=None, handedness='right', style=None, **kwargs)#

Bases: BaseGeo, BaseDisplayRepr

Magnetic field sensor.

Can be used as observers input for magnetic field computation.

When position=(0,0,0) and orientation=None local object coordinates coincide with the global coordinate system.

A sensor is made up of pixel (sensing elements / positions) where the magnetic field is evaluated.

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.

  • pixel (array_like, shape (3,) or (n1,n2,...,3), default=`(0,0,0)`) – Sensor pixel (=sensing elements) positions in the local object coordinates (rotate with object), in units of m.

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

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

  • handedness ({"right", "left"}) – Object local coordinate system handedness. If “left”, the x-axis is flipped.

Returns:

observer

Return type:

Sensor object

Examples

Sensor objects are observers for magnetic field computation. In this example we compute the B-field in units of T as seen by the sensor in the center of a circular current loop:

>>> import magpylib as magpy
>>> sens = magpy.Sensor()
>>> loop = magpy.current.Circle(current=1, diameter=0.01)
>>> B = sens.getB(loop)
>>> print(B)
[0.         0.         0.00012566]

We rotate the sensor by 45 degrees and compute the field again:

>>> sens.rotate_from_rotvec((45,0,0))
Sensor(id=...)
>>> B = sens.getB(loop)
>>> print(B)
[0.00000000e+00 8.88576588e-05 8.88576588e-05]

Finally we set some sensor pixels and compute the field again:

>>> sens.pixel=((0,0,0), (.001,0,0), (.002,0,0))
>>> B = sens.getB(loop)
>>> print(B)
[[0.00000000e+00 8.88576588e-05 8.88576588e-05]
 [0.00000000e+00 9.16274003e-05 9.16274003e-05]
 [0.00000000e+00 1.01415384e-04 1.01415384e-04]]
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.

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

Compute the B-field in units of T as seen by the sensor.

Parameters:
  • sources (source and collection objects or 1D list thereof) – Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l source and/or collection objects.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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 of each source (index l) at each path position (index m) and each sensor pixel position (indices n1,n2,…) in units of T. Paths of objects that are shorter than index m are considered as static beyond their end.

Return type:

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

Examples

Sensors are observers for magnetic field computation. In this example we compute the B-field in T as seen by the sensor in the center of a circular current loop:

>>> import magpylib as magpy
>>> sens = magpy.Sensor()
>>> loop = magpy.current.Circle(current=1, diameter=.01)
>>> B = sens.getB(loop)
>>> print(B)
[0.         0.         0.00012566]

Then we rotate the sensor by 45 degrees and compute the field again:

>>> sens.rotate_from_rotvec((45,0,0))
Sensor(id=...)
>>> B = sens.getB(loop)
>>> print(B)
[0.00000000e+00 8.88576588e-05 8.88576588e-05]

Finally we set some sensor pixels and compute the field again:

>>> sens.pixel=((0,0,0), (.001,0,0), (.002,0,0))
>>> B = sens.getB(loop)
>>> print(B)
[[0.00000000e+00 8.88576588e-05 8.88576588e-05]
 [0.00000000e+00 9.16274003e-05 9.16274003e-05]
 [0.00000000e+00 1.01415384e-04 1.01415384e-04]]
getH(*sources, sumup=False, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the H-field in units of A/m as seen by the sensor.

Parameters:
  • sources (source and collection objects or 1D list thereof) – Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l source and/or collection objects.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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 of each source (index l) at each path position (index m) and each sensor pixel position (indices n1,n2,…) in units of A/m. Paths of objects that are shorter than index m are considered as static beyond their end.

Return type:

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

Examples

Sensors are observers for magnetic field computation. In this example we compute the B-field in T as seen by the sensor in the center of a circular current loop:

>>> import magpylib as magpy
>>> sens = magpy.Sensor()
>>> loop = magpy.current.Circle(current=1, diameter=.01)
>>> H = sens.getH(loop)
>>> print(H)
[  0.   0. 100.]

Then we rotate the sensor by 45 degrees and compute the field again:

>>> sens.rotate_from_rotvec((45,0,0))
Sensor(id=...)
>>> H = sens.getH(loop)
>>> print(H)
[ 0.         70.71067812 70.71067812]

Finally we set some sensor pixels and compute the field again:

>>> sens.pixel=((0,0,0), (.001,0,0), (.002,0,0))
>>> H = sens.getH(loop)
>>> print(H)
[[ 0.         70.71067812 70.71067812]
 [ 0.         72.9147684  72.9147684 ]
 [ 0.         80.7037979  80.7037979 ]]
getJ(*sources, sumup=False, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#

Compute the J-field in units of T as seen by the sensor.

Parameters:
  • sources (source and collection objects or 1D list thereof) – Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l source and/or collection objects.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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 of each source (index l) at each path position (index m) and each sensor pixel position (indices n1,n2,…) in units of T. Paths of objects that are shorter than index m are considered as static beyond their end.

Return type:

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

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

Compute the M-field in units of A/m as seen by the sensor.

Parameters:
  • sources (source and collection objects or 1D list thereof) – Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l source and/or collection objects.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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 of each source (index l) at each path position (index m) and each sensor pixel position (indices n1,n2,…) in units of A/m. Paths of objects that are shorter than index m are considered as static beyond their end.

Return type:

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

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

Create the plotly mesh3d parameters for a Sensor object in a dictionary based on the provided arguments.

size_pixels: float, default=1

A positive number. Adjusts automatic display size of sensor pixels. When set to 0, pixels will be hidden, when greater than 0, pixels will occupy half the ratio of the minimum distance between any pixel of the same sensor, equal to size_pixel.

property handedness#

Sensor handedness in the local object coordinates.

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

Sensor pixel (=sensing elements) positions in the local object coordinates (rotate with object), in units of m.

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.

magpylib.getB(sources=None, observers=None, sumup=False, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto', **kwargs)#

Compute B-field in units of T for given sources and observers.

Field implementations can be directly accessed (avoiding the object oriented Magpylib interface) by providing a string input sources=source_type, array_like positions as observers input, and all other necessary input parameters (see below) as kwargs.

Parameters:
  • sources (source and collection objects or 1D list thereof) –

    Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l sources and/or collection objects.

    Functional interface: input must be one of (Cuboid, Cylinder, CylinderSegment, Sphere, Dipole, Circle or Polyline).

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

    Functional interface: Input must be array_like with shape (3,) or (n,3) corresponding positions to observer positions in units of m.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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.

See also

*Functional interface

position: array_like, shape (3,) or (n,3), default=`(0,0,0)`

Source position(s) in the global coordinates in units of m.

orientation: scipy Rotation object with length 1 or n, default=`None`

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation.

polarization: array_like, shape (3,) or (n,3)

Only source_type in (Cuboid, Cylinder, CylinderSegment, Sphere, Tetrahedron, Triangle, TriangularMesh)! Magnetic polarization vector J = mu0*M in units of T, given in the local object coordinates (rotates with object).

magnetization: array_like, shape (3,) or (n,3)

Only source_type in (Cuboid, Cylinder, CylinderSegment, Sphere, Tetrahedron, Triangle, TriangularMesh)! Magnetization vector M = J/mu0 in units of A/m, given in the local object coordinates (rotates with object).

moment: array_like, shape (3) or (n,3), unit A·m²

Only source_type == Dipole! Magnetic dipole moment(s) in units of A·m² given in the local object coordinates (rotates with object). For homogeneous magnets the relation moment=magnetization*volume holds.

current: array_like, shape (n,)

Only source_type == Circle or Polyline! Electrical current in units of A.

dimension: array_like, shape (x,) or (n,x)

Only source_type in (Cuboid, Cylinder, CylinderSegment)! Magnet dimension input in units of m and deg. Dimension format x of sources is similar as in object oriented interface.

diameter: array_like, shape (n,)

Only source_type == Sphere or Circle! Diameter of source in units of m.

segment_start: array_like, shape (n,3)

Only source_type == Polyline! Start positions of line current segments in units of m.

segment_end: array_like, shape (n,3)

Only source_type == Polyline! End positions of line current segments in units of m.

Returns:

  • B-field (ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame) – 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 are considered as static beyond their end.

  • Functional interface (ndarray, shape (n,3)) – B-field for every parameter set in units of T.

Notes

This function automatically joins all sensor and position inputs together and groups similar sources for optimal vectorization of the computation. For maximal performance call this function as little as possible and avoid using it in loops.

Examples

In this example we compute the B-field in T of a spherical magnet and a current loop at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> src1 = magpy.current.Circle(current=100, diameter=.002)
>>> src2 = magpy.magnet.Sphere(polarization=(0,0,.1), diameter=.001)
>>> B = magpy.getB([src1, src2], (.01,.01,.01))
>>> print(B)
[[ 6.05434592e-06  6.05434592e-06  2.35680448e-08]
 [ 8.01875374e-07  8.01875374e-07 -9.05619815e-23]]

We can also use sensor objects as observers input:

>>> sens1 = magpy.Sensor(position=(.01,.01,.01))
>>> sens2 = sens1.copy(position=(.01,.01,-.01))
>>> B = magpy.getB([src1, src2], [sens1, sens2])
>>> print(B)
[[[ 6.05434592e-06  6.05434592e-06  2.35680448e-08]
  [-6.05434592e-06 -6.05434592e-06  2.35680448e-08]]

 [[ 8.01875374e-07  8.01875374e-07 -9.05619815e-23]
  [-8.01875374e-07 -8.01875374e-07 -9.05619815e-23]]]

Through the functional interface we can compute the same fields for the loop as:

>>> obs = [(.01,.01,.01), (.01,.01,-.01)]
>>> B = magpy.getB('Circle', obs, current=100, diameter=.002)
>>> print(B)
[[ 6.05434592e-06  6.05434592e-06  2.35680448e-08]
 [-6.05434592e-06 -6.05434592e-06  2.35680448e-08]]

But also for a set of four completely different instances:

>>> B = magpy.getB(
...     'Circle',
...     observers=((.01,.01,.01), (.01,.01,-.01), (.01,.02,.03), (.02,.02,.02)),
...     current=(11, 22, 33, 44),
...     diameter=(.001, .002, .003, .004),
...     position=((0,0,0), (0,0,.01), (0,0,.02), (0,0,.03)),
... )
>>> print(B)
[[ 1.66322588e-07  1.66322588e-07  1.61742625e-10]
 [-4.69451598e-07 -4.69451598e-07  4.70690813e-07]
 [ 7.96993186e-07  1.59398637e-06 -7.91258466e-07]
 [-1.37369334e-06 -1.37369334e-06 -1.36554287e-06]]
magpylib.getH(sources=None, observers=None, sumup=False, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto', **kwargs)#

Compute H-field in units of A/m for given sources and observers.

Field implementations can be directly accessed (avoiding the object oriented Magpylib interface) by providing a string input sources=source_type, array_like positions as observers input, and all other necessary input parameters (see below) as kwargs.

Parameters:
  • sources (source and collection objects or 1D list thereof) –

    Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l sources and/or collection objects.

    Functional interface: input must be one of (Cuboid, Cylinder, CylinderSegment, Sphere, Dipole, Circle or Polyline).

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

    Functional interface: Input must be array_like with shape (3,) or (n,3) corresponding positions to observer positions in units of m.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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.

See also

*Functional interface

position: array_like, shape (3,) or (n,3), default=`(0,0,0)`

Source position(s) in the global coordinates in units of m.

orientation: scipy Rotation object with length 1 or n, default=`None`

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation.

magnetization: array_like, shape (3,) or (n,3)

Only source_type in (Cuboid, Cylinder, CylinderSegment, Sphere)! Magnetization vector(s) (mu0*M, remanence field) in units of A/m given in the local object coordinates (rotates with object).

moment: array_like, shape (3) or (n,3), unit A·m²

Only source_type == Dipole! Magnetic dipole moment(s) in units of A·m² given in the local object coordinates (rotates with object). For homogeneous magnets the relation moment=magnetization*volume holds.

current: array_like, shape (n,)

Only source_type == Circle or Polyline! Electrical current in units of A.

dimension: array_like, shape (x,) or (n,x)

Only source_type in (Cuboid, Cylinder, CylinderSegment)! Magnet dimension input in units of m and deg. Dimension format x of sources is similar as in object oriented interface.

diameter: array_like, shape (n,)

Only source_type == Sphere or Circle! Diameter of source in units of m.

segment_start: array_like, shape (n,3)

Only source_type == Polyline! Start positions of line current segments in units of m.

segment_end: array_like, shape (n,3)

Only source_type == Polyline! End positions of line current segments in units of m.

Returns:

  • H-field (ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame) – 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 are considered as static beyond their end.

  • Functional interface (ndarray, shape (n,3)) – H-field for every parameter set in units of A/m.

Notes

This function automatically joins all sensor and position inputs together and groups similar sources for optimal vectorization of the computation. For maximal performance call this function as little as possible and avoid using it in loops.

Examples

In this example we compute the H-field in A/m of a spherical magnet and a current loop at the observer position (0.01,0.01,0.01) given in units of m:

>>> import magpylib as magpy
>>> src1 = magpy.current.Circle(current=100, diameter=.002)
>>> src2 = magpy.magnet.Sphere(polarization=(0,0,.1), diameter=.001)
>>> H = magpy.getH([src1, src2], (.01,.01,.01))
>>> print(H)
[[ 4.81789540e+00  4.81789540e+00  1.87548541e-02]
 [ 6.38112147e-01  6.38112147e-01 -7.20669350e-17]]

We can also use sensor objects as observers input:

>>> sens1 = magpy.Sensor(position=(.01,.01,.01))
>>> sens2 = sens1.copy(position=(.01,.01,-.01))
>>> H = magpy.getH([src1, src2], [sens1, sens2])
>>> print(H)
[[[ 4.81789540e+00  4.81789540e+00  1.87548541e-02]
  [-4.81789540e+00 -4.81789540e+00  1.87548541e-02]]

 [[ 6.38112147e-01  6.38112147e-01 -7.20669350e-17]
  [-6.38112147e-01 -6.38112147e-01 -7.20669350e-17]]]

Through the functional interface we can compute the same fields for the loop as:

>>> obs = [(.01,.01,.01), (.01,.01,-.01)]
>>> H = magpy.getH('Circle', obs, current=100, diameter=.002)
>>> print(H)
[[ 4.8178954   4.8178954   0.01875485]
 [-4.8178954  -4.8178954   0.01875485]]

But also for a set of four completely different instances:

>>> H = magpy.getH(
...     'Circle',
...     observers=((.01,.01,.01), (.01,.01,-.01), (.01,.02,.03), (.02,.02,.02)),
...     current=(11, 22, 33, 44),
...     diameter=(.001, .002, .003, .004),
...     position=((0,0,0), (0,0,.01), (0,0,.02), (0,0,.03)),
... )
>>> print(H)
[[ 1.32355310e-01  1.32355310e-01  1.28710691e-04]
 [-3.73577711e-01 -3.73577711e-01  3.74563848e-01]
 [ 6.34227026e-01  1.26845405e+00 -6.29663481e-01]
 [-1.09315042e+00 -1.09315042e+00 -1.08666449e+00]]
magpylib.getJ(sources=None, observers=None, sumup=False, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto', **kwargs)#

Compute J-field in units of T for given sources and observers.

Field implementations can be directly accessed (avoiding the object oriented Magpylib interface) by providing a string input sources=source_type, array_like positions as observers input, and all other necessary input parameters (see below) as kwargs.

Parameters:
  • sources (source and collection objects or 1D list thereof) –

    Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l sources and/or collection objects.

    Functional interface: input must be one of (Cuboid, Cylinder, CylinderSegment, Sphere, Dipole, Circle or Polyline).

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

    Functional interface: Input must be array_like with shape (3,) or (n,3) corresponding positions to observer positions in units of m.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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.

See also

*Functional interface

position: array_like, shape (3,) or (n,3), default=`(0,0,0)`

Source position(s) in the global coordinates in units of m.

orientation: scipy Rotation object with length 1 or n, default=`None`

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation.

magnetization: array_like, shape (3,) or (n,3)

Only source_type in (Cuboid, Cylinder, CylinderSegment, Sphere)! Magnetization vector(s) (mu0*M, remanence field) in units of A/m given in the local object coordinates (rotates with object).

moment: array_like, shape (3) or (n,3), unit A·m²

Only source_type == Dipole! Magnetic dipole moment(s) in units of A·m² given in the local object coordinates (rotates with object). For homogeneous magnets the relation moment=magnetization*volume holds.

current: array_like, shape (n,)

Only source_type == Circle or Polyline! Electrical current in units of A.

dimension: array_like, shape (x,) or (n,x)

Only source_type in (Cuboid, Cylinder, CylinderSegment)! Magnet dimension input in units of m and deg. Dimension format x of sources is similar as in object oriented interface.

diameter: array_like, shape (n,)

Only source_type == Sphere or Circle! Diameter of source in units of m.

segment_start: array_like, shape (n,3)

Only source_type == Polyline! Start positions of line current segments in units of m.

segment_end: array_like, shape (n,3)

Only source_type == Polyline! End positions of line current segments in units of m.

Returns:

  • J-field (ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame) – 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 are considered as static beyond their end.

  • Functional interface (ndarray, shape (n,3)) – J-field for every parameter set in units of T.

Notes

This function automatically joins all sensor and position inputs together and groups similar sources for optimal vectorization of the computation. For maximal performance call this function as little as possible and avoid using it in loops.

magpylib.getM(sources=None, observers=None, sumup=False, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto', **kwargs)#

Compute M-field in units of A/m for given sources and observers.

Field implementations can be directly accessed (avoiding the object oriented Magpylib interface) by providing a string input sources=source_type, array_like positions as observers input, and all other necessary input parameters (see below) as kwargs.

Parameters:
  • sources (source and collection objects or 1D list thereof) –

    Sources that generate the magnetic field. Can be a single source (or collection) or a 1D list of l sources and/or collection objects.

    Functional interface: input must be one of (Cuboid, Cylinder, CylinderSegment, Sphere, Dipole, Circle or Polyline).

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

    Functional interface: Input must be array_like with shape (3,) or (n,3) corresponding positions to observer positions in units of m.

  • sumup (bool, default=`False`) – If True, the fields of all sources are summed up.

  • 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 sensor or 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 numpy.ndarray object is returned. If ‘dataframe’ is chosen, a pandas.DataFrame object is returned (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.

See also

*Functional interface

position: array_like, shape (3,) or (n,3), default=`(0,0,0)`

Source position(s) in the global coordinates in units of m.

orientation: scipy Rotation object with length 1 or n, default=`None`

Object orientation(s) in the global coordinates. None corresponds to a unit-rotation.

magnetization: array_like, shape (3,) or (n,3)

Only source_type in (Cuboid, Cylinder, CylinderSegment, Sphere)! Magnetization vector(s) (mu0*M, remanence field) in units of A/m given in the local object coordinates (rotates with object).

moment: array_like, shape (3) or (n,3), unit A·m²

Only source_type == Dipole! Magnetic dipole moment(s) in units of A·m² given in the local object coordinates (rotates with object). For homogeneous magnets the relation moment=magnetization*volume holds.

current: array_like, shape (n,)

Only source_type == Circle or Polyline! Electrical current in units of A.

dimension: array_like, shape (x,) or (n,x)

Only source_type in (Cuboid, Cylinder, CylinderSegment)! Magnet dimension input in units of m and deg. Dimension format x of sources is similar as in object oriented interface.

diameter: array_like, shape (n,)

Only source_type == Sphere or Circle! Diameter of source in units of m.

segment_start: array_like, shape (n,3)

Only source_type == Polyline! Start positions of line current segments in units of m.

segment_end: array_like, shape (n,3)

Only source_type == Polyline! End positions of line current segments in units of m.

Returns:

  • M-field (ndarray, shape squeeze(m, k, n1, n2, …, 3) or DataFrame) – 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 are considered as static beyond their end.

  • Functional interface (ndarray, shape (n,3)) – M-field for every parameter set in units of A/m.

Notes

This function automatically joins all sensor and position inputs together and groups similar sources for optimal vectorization of the computation. For maximal performance call this function as little as possible and avoid using it in loops.

magpylib.show(*objects, 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
magpylib.show_context(*objects, 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)#

Context manager to temporarily set display settings in the with statement context.

You need to invoke as show_context(pattern1=value1, pattern2=value2).

See the magpylib.show docstrings for the parameter definitions.

Subpackages#