magpylib.current package#
Electric current classes.
- class magpylib.current.Circle(position=(0, 0, 0), orientation=None, diameter=None, current=None, meshing=None, *, style=None, **kwargs)#
Bases:
BaseCurrent,BaseTarget,BaseDipoleMomentCircular current loop.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.When
position=(0, 0, 0)andorientation=Nonethe current loop lies in the x-y plane of the global coordinate system, with its center in the origin.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.diameter (float | None, default None) – Loop diameter (m).
current (float | None, default None) – Electrical current (A).
meshing (int | None, default None) – Mesh fineness for force computation. Must be an integer
>= 4. Points are equally distributed on the circle.style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.diameter (None or float) – Same as constructor parameter
diameter.current (None or float) – Same as constructor parameter
current.meshing (None or int) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates.
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on the loop.
Examples
Circleobjects are magnetic field sources. In this example we compute the H-field (A/m) of such a current loop with 100 A current and a diameter of 2 meters at the observer position (1, 1, 1) (cm):>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.current.Circle(current=100, diameter=2) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [7.501e-03 7.501e-03 5.000e+01]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(base=72, **kwargs) dict[str, Any] | list[dict[str, Any]]#
Creates the plotly scatter3d parameters for a Circle current in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property current#
Electric current amplitude (A).
- property diameter#
Diameter of the loop in units of m.
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- class magpylib.current.Polyline(current=None, vertices=None, position=(0, 0, 0), orientation=None, meshing=None, style=None, **kwargs)#
Bases:
BaseCurrent,BaseTarget,BaseDipoleMomentLine current flowing in straight paths from vertex to vertex.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.The vertex positions are defined in the local object coordinates (rotate with object). When
position=(0, 0, 0)andorientation=Noneglobal and local coordinates coincide.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.vertices (None | array-like, shape (n, 3), default None) – Current flows along the vertices in units (m) in the local object coordinates. At least two vertices must be given.
current (float | None, default None) – Electrical current (A).
meshing (int | None, default None) – Mesh fineness for force computation. Must be a positive integer at least the number of segments. Each segment gets one mesh point at its center. All remaining mesh points are distributed evenly along the polyline.
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.vertices (None or float) – Same as constructor parameter
vertices.current (None or float) – Same as constructor parameter
current.meshing (None or int) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid computed via mean of vertices in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates. Can only be computed for a closed loop.
parent (Collection or None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on the line segments.
Examples
Polylineobjects are magnetic field sources. In this example we compute the H-field (A/m) of a square-shaped line current with 1 A at the observer position (1, 1, 1) (cm):>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.current.Polyline( ... current=1, ... vertices=((0.01, 0, 0), (0, 0.01, 0), (-0.01, 0, 0), (0, -0.01, 0), (0.01, 0, 0)), ... ) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [3.161 3.161 0.767]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(**kwargs) dict[str, Any] | list[dict[str, Any]]#
Creates the plotly scatter3d parameters for a Polyline current in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property current#
Electric current amplitude (A).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property vertices#
Polyline vertices.
The current flows along the vertices which are given in units (m) in the local object coordinates (move/rotate with object). At least two vertices must be given.
- class magpylib.current.TriangleSheet(position=(0, 0, 0), orientation=None, vertices=None, faces=None, current_densities=None, meshing=None, *, style=None, **kwargs)#
Bases:
BaseSource,BaseTargetSurface current density flowing along triangular faces.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.The vertex positions are defined in the local object coordinates (rotate with object). When
position=(0, 0, 0)andorientation=Noneglobal and local coordinates coincide.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.vertices (array-like, shape (n, 3), default None) – Points in units (m) in the local object coordinates from which the triangular faces are constructed by the additional
facesinput.faces (array-like, shape (n, 3), default None) – Triplets of vertex indices. Each triplet represents one triangle of the mesh.
current_densities (array-like, shape (n, 3), default None) – Electrical current densities flowing on the faces in units (A/m). The effective current density is a projection of the given current density vector into the face planes. Input must have the same length as
faces.meshing (int | None, default None) – Mesh fineness for force computation. Must be an integer >= number of faces specifying the target mesh size. The mesh is generated via bisection along longest edges until target number is reached.
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.vertices (None or ndarray, shape (n, 3)) – Same as constructor parameter
vertices.faces (None or ndarray, shape (n, 3)) – Same as constructor parameter
faces.current_densities (None or ndarray, shape (n, 3)) – Same as constructor parameter
current_densities.meshing (None or int) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid computed via mean of vertices in units (m) in global coordinates. Can be a path.
parent (Collection | None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on a sheet.
Examples
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.current.TriangleSheet( ... current_densities=[(1, 0, 0), (0, 1, 0)], ... vertices=((0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)), ... faces=((0, 1, 2), (1, 2, 3)), ... ) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [ 0.005 -0.311 -0.299]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(**kwargs) dict[str, Any] | list[dict[str, Any]]#
Creates the plotly scatter3d parameters for a TriangleSheet current in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property current_densities#
TriangleSheet CurrentDensities
- property faces#
TriangleSheet Faces
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property vertices#
TriangleSheet Vertices
- class magpylib.current.TriangleStrip(current=None, vertices=None, position=(0, 0, 0), orientation=None, meshing=None, *, style=None, **kwargs)#
Bases:
BaseCurrent,BaseTarget,BaseDipoleMomentCurrent flowing in straight lines along a ribbon made of adjacent triangles.
Can be used as
sourcesinput for magnetic field computation andtargetinput for force computation.The vertex positions are defined in the local object coordinates (rotate with object). When
position=(0, 0, 0)andorientation=Noneglobal and local coordinates coincide.SI units are used for all inputs and outputs.
- Parameters:
position (array-like, shape (3,) or (p, 3), default (0, 0, 0)) – Object position(s) in global coordinates in units (m).
positionandorientationattributes define the object path.orientation (Rotation | None, default None) – Object orientation(s) in global coordinates as a scipy Rotation. Rotation can have length 1 or p.
Nonegenerates a unit-rotation.vertices (None | array-like, shape (n, 3), default None) – The current flows along a band that consists of triangles {T1, T2, …} defined by the vertices {V1, V2, V3, V4, …} as T1 = (V1, V2, V3), T2 = (V2, V3, V4), … The vertices are given in units (m) in the local object coordinates (move/rotate with object). At least three vertices must be given, which define the first triangle.
current (float | None, default None) – Total current flowing through the strip in units (A). It flows in the direction V1→V3 in the first triangle, V2→V4 in the second, …
meshing (int | None, default None) – Mesh fineness for force computation. Must be an integer >= number of faces specifying the target mesh size. The mesh is generated via bisection along longest edges until target number is reached.
style (dict | None, default None) – Style dictionary. Can also be provided via style underscore magic, e.g.
style_color='red'.
- Variables:
position (ndarray, shape (3,) or (p, 3)) – Same as constructor parameter
position.orientation (Rotation) – Same as constructor parameter
orientation.vertices (None or ndarray, shape (n, 3)) – Same as constructor parameter
vertices.current (None or float) – Same as constructor parameter
current.meshing (None or int) – Same as constructor parameter
meshing.centroid (ndarray, shape (3,) or (p, 3)) – Read-only. Object centroid computed via mean of vertices in units (m) in global coordinates. Can be a path.
dipole_moment (ndarray, shape (3,)) – Read-only. Object dipole moment (A·m²) in local object coordinates. Can only be computed for a closed loop.
parent (Collection | None) – Parent collection of the object.
style (dict) – Style dictionary defining visual properties.
Notes
Returns (0, 0, 0) on a sheet.
Examples
TriangleStripobjects are magnetic field sources. In this example we compute the H-field in (A/m) of a square current sheet (two triangles) with 1 A current at the observer position (1, 1, 1) cm:>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.current.TriangleStrip( ... current=1, ... vertices=((0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)), ... ) >>> H = src.getH((0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(H) [ 0.026 -0.307 -0.371]
- copy(**kwargs)#
Return deep copy with optional modifications.
- Parameters:
**kwargs – Attribute overrides applied to the copy (e.g.
position=(1, 2, 3)).- Returns:
Deep-copied object (same concrete subclass as original).
- Return type:
Self
Examples
Create a
Sensorobject and copy to an another position:>>> import magpylib as magpy >>> sens1 = magpy.Sensor(style_label='sens1') >>> sens2 = sens1.copy(position=(2, 6, 10), style_label='sens2') >>> print(f'Instance {sens1.style.label} with position {sens1.position}.') Instance sens1 with position [0. 0. 0.]. >>> print(f'Instance {sens2.style.label} with position {sens2.position}.') Instance sens2 with position [ 2. 6. 10.].
- describe(*, exclude=('style', 'field_func'), return_string=False)#
Return or print a formatted description of object properties.
- Parameters:
exclude (str | Sequence[str], default ('style', 'field_func')) – Property names to omit from the description.
return_string (bool, default False) – If
Truereturn the description string; ifFalseprint it and returnNone.
- Returns:
Description string if
return_string=TrueelseNone.- Return type:
str | None
- getB(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return B-field (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | list[Sensor] | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
B-field (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the B-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1.0), diameter=1) >>> B = src.getB(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=3): ... print(B) [[ 0. 0. 0.667] [ 0. 0. -0.042] [ 0. 0. -0.005]]
Compute the B-field at two sensors, each one with two pixels:
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> B = src.getB(sens1, sens2) >>> with np.printoptions(precision=3): ... print(B) [[[ 0.012 0. -0.04 ] [-0.012 0. -0.04 ]] [[ 0.001 0. -0.005] [-0.001 0. -0.005]]]
- getH(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return H-field (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
H-field (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray | DataFrame
Examples
Compute the H-field of a spherical magnet at three positions:
>>> import numpy as np >>> import magpylib as magpy
>>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> H = src.getH(((0, 0, 0), (1, 0, 0), (2, 0, 0))) >>> with np.printoptions(precision=0): ... print(H) [[ 0. 0. -265258.] [ 0. 0. -33157.] [ 0. 0. -4145.]]
Compute the H-field at two sensors, each one with two pixels
>>> sens1 = magpy.Sensor(position=(1, 0, 0), pixel=((0, 0, 0.1), (0, 0, -0.1))) >>> sens2 = sens1.copy(position=(2, 0, 0)) >>> H = src.getH(sens1, sens2) >>> with np.printoptions(precision=0): ... print(H) [[[ 9703. 0. -31696.] [ -9703. 0. -31696.]] [[ 618. 0. -4098.] [ -618. 0. -4098.]]]
- getJ(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetic polarization (T) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Polarization (T) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the polarization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> J = cube.getJ((3, 3, 0)) >>> with np.printoptions(precision=3): ... print(J) [0.707 0.707 0. ]
- getM(*observers, squeeze=True, pixel_agg=None, output='ndarray', in_out='auto')#
Return magnetization (A/m) at o observers generated by the source.
SI units are used for all inputs and outputs.
- Parameters:
*observers (Sensor | array-like, shape (o1, o2, ..., 3)) – Input specifying where the field is evaluated. Each entry can be an array-like of positions in units (m), a
Sensorobject with pixel shape (o1, o2, …, 3) or a list of such objects (all with identical pixel shape unlesspixel_aggis used).squeeze (bool, default True) – If
Truesqueeze singleton axes (e.g. a single source or a single sensor).pixel_agg (str | None, default None) – Name of a NumPy aggregation function (e.g.
'mean','min') applied over the pixel axis of each sensor. Allows mixing sensors with different pixel shapes.output ({'ndarray', 'dataframe'}, default 'ndarray') – Output container type. ‘dataframe’ returns a pandas DataFrame.
in_out ({'auto', 'inside', 'outside'}, default 'auto') – Assumption about observer locations relative to magnet bodies.
'auto'detects per observer (safest, slower).'inside'treats all inside (faster).'outside'treats all outside (faster).
- Returns:
Magnetization (A/m) with squeezed shape (p, o, o1, o2, …, 3) where p is the path length and o the number of observers.
- Return type:
ndarray or DataFrame
Examples
In this example we test the magnetization at an observer point.
>>> import numpy as np >>> import magpylib as magpy >>> cube = magpy.magnet.Cuboid( ... dimension=(10, 1, 1), ... polarization=(1, 0, 0) ... ).rotate_from_angax(45, 'z') >>> M = cube.getM((3, 3, 0)) >>> with np.printoptions(precision=0): ... print(M) [562698. 562698. 0.]
- get_trace(**kwargs) dict[str, Any] | list[dict[str, Any]]#
Creates the plotly scatter3d parameters for a TriangleStrip current in a dictionary based on the provided arguments.
- move(displacement, start='auto')#
Translate position by scalar or vector displacement.
- Parameters:
displacement (array-like, shape (3,) or (n, 3)) – Displacement vector in units (m). Scalar input applies one translation to the path starting at index
start. Vector input extends/appends element-wise. See Notes.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Scalar input (single displacement):
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 1, 1)) >>> print(sens.position) [1. 1. 1.] >>> sens.move((1, 1, 1)) Sensor(id=...) >>> print(sens.position) [2. 2. 2.]
Create len>1 object paths with vector input:
>>> sens.move([(1, 1, 1), (2, 2, 2), (3, 3, 3)]) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 4.] [5. 5. 5.]]
Apply operations starting with a designated path index:
>>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]]
- reset_path()#
Reset path: set position to (0, 0, 0) and orientation to unit rotation.
- Returns:
Self (for chaining).
- Return type:
Self
Examples
>>> import magpylib as magpy >>> obj = magpy.Sensor(position=(1, 2, 3)) >>> obj.rotate_from_angax(45, 'z') Sensor... >>> print(obj.position) [1. 2. 3.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
>>> obj.reset_path() Sensor(id=...) >>> print(obj.position) [0. 0. 0.] >>> print(obj.orientation.as_euler('xyz', degrees=True)) [0. 0. 0.]
- rotate(rotation: Rotation, anchor=None, start='auto')#
Rotate about an anchor.
- Parameters:
rotation (Rotation | None) – Scalar or vector rotation in the form of a scipy Rotation object.
Noneis interpreted as unit rotation.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> from scipy.spatial.transform import Rotation as R >>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate(R.from_euler('z', 45, degrees=True), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate(R.from_euler('z', 45, degrees=True)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate(R.from_euler('z', [[15], [30], [45]], degrees=True), anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_angax(angle, axis, anchor=None, start='auto', degrees=True)#
Rotate with scipy Rotation input.
- Parameters:
angle (float | array-like, shape (n,)) – Rotation angle or sequence of angles in degrees. See property
degrees.axis (str | array-like, shape (3,) or (n, 3)) – Rotation axis direction. Provide a vector or one of
'x','y','z'.anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_angax(45, axis='z', anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_angax(45, axis=(0, 0, 1)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_angax((15, 30, 45), axis='z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_euler(angle, seq, anchor=None, start='auto', degrees=True)#
Rotate with Euler angle sequence.
- Parameters:
angle (float | array-like, shape (n,)) – Angles of rotation in units (deg) by default.
seq (str) – Specifies sequence of axes for rotations. Up to 3 characters belonging to the set {‘X’, ‘Y’, ‘Z’} for intrinsic rotations, or {‘x’, ‘y’, ‘z’} for extrinsic rotations. Extrinsic and intrinsic rotations cannot be mixed in one function call.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_euler(45, 'z', anchor=0) Sensor... >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_euler(45, 'z') Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_euler((15, 30, 45), 'z', anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- rotate_from_matrix(matrix, anchor=None, start='auto')#
Rotate with rotation matrix/matrices.
- Parameters:
matrix (array-like, shape (3, 3) or (n, 3, 3)) – Single rotation matrix or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)], anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_mrp(mrp, anchor=None, start='auto')#
Rotate with Modified Rodrigues Parameters (MRPs).
- Parameters:
mrp (array-like, shape (3,) or (n, 3)) – Modified Rodrigues Parameters vector or sequence.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_mrp((0, 0, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
Rotate the object about itself:
>>> sens.rotate_from_matrix([(0, -1, 0), (1, 0, 0), (0, 0, 1)]) Sensor(id=...) >>> print(sens.position) [-1. 0. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. -90.]
- rotate_from_quat(quat, anchor=None, start='auto')#
Rotate with quaternion(s).
- Parameters:
quat (array-like, shape (4,) or (n, 4)) – Quaternion or quaternion sequence in (x, y, z, w) format.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.
- Returns:
Self (for chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_quat((0, 0, 1, 1), anchor=0) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Rotate the object about itself:
>>> sens.rotate_from_quat((0, 0, 1, 1)) Sensor(id=...) >>> print(sens.position) [0. 1. 0.] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 180.]
- rotate_from_rotvec(rotvec, anchor=None, start='auto', degrees=True)#
Rotate with rotation vector input.
- Parameters:
rotvec (array-like, shape (3,) or (n, 3)) – Rotation vector or sequence. Direction gives axis, magnitude gives angle in radians.
anchor (None | array-like, shape (3,) or (n, 3), default None) – Anchor point(s) (m).
Nonerotates about object position; for a child in a collection it implies compound rotation about the parent position.start (int | str, default 'auto') – Starting index when applying operation. With
'auto'scalar input setsstart=0(modify whole path) and vector input setsstart=len(path)(append). See Notes for details.degrees (bool, default True) – If
True, interpretangleinput in degrees, else radians.
- Returns:
Self (allows chaining).
- Return type:
Self
Notes
A path refers jointly to the position and orientation of the object. Scalar input applies a single operation. It is applied to the whole object path, starting with path index
start. Vector input means a sequence of operations. Vector input of length n applies the individual n operations to n path entries, starting with path indexstart. When an input extends beyond the path, the object path will be padded by its edge-entries before the operation is applied. By default (start='auto') the index is set tostart=0for scalar input corresponding to moving the entire path, and tostart=len(object path)for vector input corresponding to appending to the existing path.Examples
Rotate an object about the origin:
>>> import magpylib as magpy >>> sens = magpy.Sensor(position=(1, 0, 0)) >>> sens.rotate_from_rotvec((0, 0, 45), anchor=0) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 45.]
Rotate the object about itself:
>>> sens.rotate_from_rotvec((0, 0, 45)) Sensor(id=...) >>> print(sens.position) [0.70710678 0.70710678 0. ] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [ 0. 0. 90.]
Create a rotation path by rotating in several steps about an anchor:
>>> sens.rotate_from_rotvec([(0, 0, 15), (0, 0, 30), (0, 0, 45)], anchor=(0, 0, 0)) Sensor(id=...) >>> print(sens.position) [[ 7.07106781e-01 7.07106781e-01 0.00000000e+00] [ 5.00000000e-01 8.66025404e-01 0.00000000e+00] [ 2.58819045e-01 9.65925826e-01 0.00000000e+00] [-2.22044605e-16 1.00000000e+00 0.00000000e+00]] >>> print(sens.orientation.as_euler('xyz', degrees=True)) [[ 0. 0. 90.] [ 0. 0. 105.] [ 0. 0. 120.] [ 0. 0. 135.]]
- show(*, backend=<default>, canvas=<default>, animation=<default>, zoom=<default>, markers=<default>, return_fig=<default>, canvas_update=<default>, row=<default>, col=<default>, output=<default>, sumup=<default>, pixel_agg=<default>, style=<default>, **kwargs)#
Display objects and paths graphically.
Global graphic styles can be set with kwargs as style dictionary or using style underscore magic.
- Parameters:
*objects (Source | Sensor | Collection) – One or multiple Magpylib objects to be displayed.
backend ({'auto', 'matplotlib', 'plotly', 'pyvista'}, default 'auto') – With
'auto'the backend becomes'plotly'inside a notebook when Plotly is installed, otherwise'matplotlib'. Ifcanvasis provided, its type determines the backend.canvas (None | matplotlib.Figure | plotly.Figure | pyvista.Plotter, default None) – Existing canvas to draw on. If
None, a new canvas is created and displayed.animation (bool | float, default False) – If
Trueand at least one object has a path, the path is animated. A positive float sets the total animation duration in seconds (Plotly only).zoom (float, default 0.0) – 3D plot zoom level. 0 means tight bounds.
markers (array-like, shape (n, 3) | None, default None) – Global position markers shown as points.
return_fig (bool, default False) – If
True, return the underlying figure object (Figure / FigureWidget / Plotter).canvas_update (str | bool, default 'auto') – Layout update behaviour when using a provided canvas. With
'auto'applies internal layout only for newly created canvases.Trueforces update,Falsesuppresses it.row (int | None, default None) – Subplot row index.
col (int | None, default None) – Subplot column index.
output (str | tuple[str, ...], default 'model3d') – Plot output type.
'model3d'shows 3D geometry. Field plots are defined via component strings like'Bx','Bxy','Hyz'. Multiple axes in a string imply vector norm combination (e.g.,'Bxy'=>sqrt(Bx**2 + By**2)).sumup (bool, default True) – Sum field contributions of sources.
pixel_agg (str, default 'mean') – NumPy reducer applied across sensor pixels (e.g.,
'min','max','std').style (dict | None, default None) – Global style overrides, e.g.
{'color': 'red'}or via underscore magic (style_color='red'). Applied to matching objects.
- Returns:
The created/updated figure object if
return_fig=True; otherwiseNone.- Return type:
None | matplotlib.Figure | plotly.Figure | pyvista.Plotter
Examples
Display multiple objects, object paths, markers in 3D using Matplotlib or Plotly:
>>> import magpylib as magpy >>> src = magpy.magnet.Sphere(polarization=(0, 0, 1), diameter=1) >>> src.move([(0.1*x, 0, 0) for x in range(50)]) Sphere... >>> src.rotate_from_angax(angle=[*range(0, 400, 10)], axis='z', anchor=0, start=11) Sphere... >>> ts = [-.4, 0, .4] >>> sens = magpy.Sensor(position=(0, 0, 2), pixel=[(x, y, 0) for x in ts for y in ts]) >>> magpy.show(src, sens) >>> magpy.show(src, sens, backend='plotly') >>> # graphic output
Display output on your own canvas (here a Matplotlib 3d-axes):
>>> import matplotlib.pyplot as plt >>> import magpylib as magpy >>> my_axis = plt.axes(projection='3d') >>> magnet = magpy.magnet.Cuboid(polarization=(1, 1, 1), dimension=(1, 2, 3)) >>> sens = magpy.Sensor(position=(0, 0, 3)) >>> magpy.show(magnet, sens, canvas=my_axis, zoom=1) >>> plt.show() >>> # graphic output
Use sophisticated figure styling options accessible from defaults, as individual object styles or as global style arguments in display.
>>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=[(0, 0, 0), (0, 0, 3)], diameter=1, polarization=(1, 1, 1)) >>> src2 = magpy.magnet.Sphere( ... position=[(1, 0, 0), (1, 0, 3)], ... diameter=1, ... polarization=(1, 1, 1), ... style_path_show=False ... ) >>> magpy.defaults.display.style.magnet.magnetization.size = 2 >>> src1.style.magnetization.size = 1 >>> magpy.show(src1, src2, style_color='r') >>> # graphic output
Use a context manager to jointly animate 3d and 2d subplots
>>> import magpylib as magpy >>> import numpy as np >>> import plotly.graph_objects as go >>> path_len = 40 >>> sensor = magpy.Sensor() >>> cyl1 = magpy.magnet.Cylinder( ... polarization=(.1, 0, 0), ... dimension=(1, 2), ... position=(4, 0, 0), ... style_label="Cylinder1", ... ) >>> sensor.move(np.linspace((0, 0, -3), (0, 0, 3), path_len), start=0) Sensor(id=...) >>> cyl1.rotate_from_angax(angle=np.linspace(0, 300, path_len), start=0, axis="z", anchor=0) Cylinder(id=...) >>> cyl2 = cyl1.copy().move((0, 0, 5)) >>> fig = go.Figure() >>> with magpy.show_context(cyl1, cyl2, sensor, canvas=fig, backend="plotly", animation=True): ... magpy.show(col=1, output="model3d") ... magpy.show(col=2, output="Bxy", sumup=True) ... magpy.show(col=3, output="Bz", sumup=False) >>> fig.show() >>> # graphic output
- property centroid#
Return centroid (m).
- property current#
Electric current amplitude (A).
- property dipole_moment#
Return dipole moment vector (A·m²).
- property field_func#
Function for B- and H-field computation.
The callable must accept the two positional arguments
fieldandobservers. Withfield='B'orfield='H'the function must return the B-field (T) or H-field (A/m) respectively.observersis anndarrayof shape (n, 3) in units (m). The returned array must have shape (n, 3).
- property meshing#
Return meshing specification for force computation.
- property orientation#
Return object orientation.
Nonecorresponds to unit rotation.
- property parent#
Parent collection of the object.
- property position#
Return object position in global coordinates (m).
- property style#
Return object style as a
BaseStyleinstance.
- property vertices#
Triangle strip vertices in local object coordinates.