magpylib package

This is the top level of the package. From here you can call subpackages source and math, the classes Collection and Sensor as well as the functions getBv and displaySystem.

class magpylib.Collection(*sources, dupWarning=True)[source]

Bases: magpylib._lib.classes.base.FieldSampler

Create a collection of magpylib.source objects for common manipulation.

Parameters:sources (source objects) – python magic variable passes source objects to the collection at initialization.
sources

List of all sources that have been added to the collection.

Type:list of source objects

Example

>>> from magpylib import source, Collection
>>> pm1 = source.magnet.Box(mag=[0,0,1000],dim=[1,1,1])
>>> pm2 = source.magnet.Cylinder(mag=[0,0,1000],dim=[1,1])
>>> pm3 = source.magnet.Sphere(mag=[0,0,1000],dim=1)
>>> col = Collection(pm1,pm2,pm3)
>>> B = col.getB([1,0,1])
>>> print(B)
[9.93360625e+01 1.76697482e-14 3.12727683e+01]
addSources(*sources, dupWarning=True)[source]

This method adds the argument source objects to the collection. May also include other collections.

Parameters:
  • source (source object) – adds the source object source to the collection.
  • dupWarning (bool) – Warn and prevent if there is an attempt to add a duplicate source into the collection. Set to false to disable check and increase performance.
Returns:

Return type:

None

Example

>>> from magpylib import source, Collection
>>> pm1 = source.magnet.Box(mag=[0,0,1000],dim=[1,1,1])
>>> pm2 = source.magnet.Cylinder(mag=[0,0,1000],dim=[1,1])
>>> pm3 = source.magnet.Sphere(mag=[0,0,1000],dim=1)
>>> col = Collection(pm1)
>>> print(col.getB([1,0,1]))
  [4.29223532e+01 1.76697482e-14 1.37461635e+01]
>>> col.addSource(pm2)
>>> print(col.getB([1,0,1]))
  [7.72389756e+01 1.76697482e-14 2.39070726e+01]
>>> col.addSource(pm3)
>>> print(
  [9.93360625e+01 1.76697482e-14 3.12727683e+01]
getB(pos)[source]

This method returns the magnetic field vector generated by the whole collection at the argument position pos in units of [mT]

Parameters:pos (vec3 [mm]) – Position where magnetic field should be determined.
Returns:magnetic field vector – Magnetic field at the argument position pos generated by the collection in units of [mT].
Return type:arr3 [mT]
move(displacement)[source]

This method moves each source in the collection by the argument vector displacement. Vector input format can be either list, tuple or array of any data type (float, int).

Parameters:displacement (vec3 - [mm]) – Displacement vector
Returns:
Return type:None

Example

>>> from magpylib import source, Collection
>>> pm1 = source.magnet.Box(mag=[0,0,1000],dim=[1,1,1])
>>> pm2 = source.magnet.Cylinder(mag=[0,0,1000],dim=[1,1])
>>> print(pm1.position,pm2.position)
  [0. 0. 0.] [0. 0. 0.]
>>> col = Collection(pm1,pm2)
>>> col.move([1,1,1])
>>> print(pm1.position,pm2.position)
  [1. 1. 1.] [1. 1. 1.]
removeSource(source_ref=-1)[source]

Remove a source from the sources list.

Parameters:

source_ref (source object or int) – [Optional] Remove the inputted source from the list [Optional] If given an int, remove a source at the given index position. Default: Last position.

Returns:

Return type:

Popped source object.

Raises:
  • ValueError – Will be thrown if you attempt to remove a source that is not in the Collection.
  • AssertionError – Will be thrown if inputted index kwarg type is not type int

Example

>>> from magpylib import Collection, source
>>> s = source.magnet.Sphere(mag=[1,2,3],dim=1,pos=[3,3,3])
>>> s2 = source.magnet.Sphere(mag=[1,2,3],dim=2,pos=[-3,-3,-3])
>>> m = source.moment.Dipole(moment=[1,2,3],pos=(0,0,0))
>>> c = Collection(s,s2,m)
>>> print(c.sources)
[<magpylib._lib.classes.magnets.Sphere object at 0xa31eafcc>,
<magpylib._lib.classes.magnets.Sphere object at 0xa31ea1cc>,
<magpylib._lib.classes.moments.Dipole object at 0xa31ea06c>]
>>> c.removeSource(s)
>>> print(c.sources)
[<magpylib._lib.classes.magnets.Sphere object at 0xa31ea1cc>,
<magpylib._lib.classes.moments.Dipole object at 0xa31ea06c>]
>>> c.removeSource(s2)
>>> print(c.sources)
[<magpylib._lib.classes.moments.Dipole object at 0xa31ea06c>]
>>> c.removeSource()
>>> print(c.sources)
[]
rotate(angle, axis, anchor='self.position')[source]

This method rotates each source in the collection about axis by angle. The axis passes through the center of rotation anchor. Scalar input is either integer or float. Vector input format can be either list, tuple or array of any data type (float, int).

Parameters:
  • angle (scalar [deg]) – Angle of rotation in units of [deg]
  • axis (vec3) – Axis of rotation
  • anchor (vec3) – The Center of rotation which defines the position of the axis of rotation. If not specified all sources will rotate about their respective center.
Returns:

Return type:

None

Example

>>> from magpylib import source, Collection
>>> pm1 = source.magnet.Box(mag=[0,0,1000],dim=[1,1,1])
>>> pm2 = source.magnet.Cylinder(mag=[0,0,1000],dim=[1,1])
>>> print(pm1.position, pm1.angle, pm1.axis)
  [0. 0. 0.] 0.0 [0. 0. 1.]
>>> print(pm2.position, pm2.angle, pm2.axis)
  [0. 0. 0.] 0.0 [0. 0. 1.]
>>> col = Collection(pm1,pm2)
>>> col.rotate(90, [0,1,0], anchor=[1,0,0])
>>> print(pm1.position, pm1.angle, pm1.axis)
  [1. 0. 1.] 90.0 [0. 1. 0.]
>>> print(pm2.position, pm2.angle, pm2.axis)
  [1. 0. 1.] 90.0 [0. 1. 0.]
class magpylib.Sensor(pos=[0, 0, 0], angle=0, axis=[0, 0, 1])[source]

Bases: magpylib._lib.classes.base.RCS

Create a rotation-enabled sensor to extract B-fields from individual Sources and Source Collections. It may be displayed with Collection’s displaySystem() using the sensors kwarg.

Parameters:
  • position (vec3) – Cartesian position of where the sensor is.
  • angle (scalar) – Angle of rotation
  • axis (vec3) – Rotation axis information (x,y,z)

Example

>>> from magpylib import source, Sensor
>>> sensor = Sensor([0,0,0],90,(0,0,1)) # This sensor is rotated in respect to space
>>> cyl = source.magnet.Cylinder([1,2,300],[1,2])
>>> absoluteReading = cyl.getB([0,0,0])
>>> print(absoluteReading)
    [  0.552   1.105  268.328 ]
>>> relativeReading = sensor.getB(cyl)
>>> print(relativeReading)
    [  1.105  -0.552  268.328 ]
getB(*sources, dupWarning=True)[source]

Extract the magnetic field based on the Sensor orientation

Parameters:dupWarning (Check if there are any duplicate sources, optional.) – This will prevent duplicates and throw a warning, by default True.
Returns:B-Field as perceived by the sensor
Return type:[vec3]

Example

>>> from magpylib import source, Sensor
>>> sensor = Sensor([0,0,0],90,(0,0,1)) # This sensor is rotated in respect to space
>>> cyl = source.magnet.Cylinder([1,2,300],[1,2])
>>> absoluteReading = cyl.getB([0,0,0])
>>> print(absoluteReading)
    [  0.552   1.105  268.328 ]
>>> relativeReading = sensor.getB(cyl)
>>> print(relativeReading)
    [  1.105  -0.552  268.328 ]
move(displacement)

This method moves the source by the argument vector displacement. Vector input format can be either list, tuple or array of any data type (float, int).

Parameters:displacement (vec3 [mm]) – Set displacement vector
Returns:
Return type:None

Example

>>> from magpylib import source
>>> pm = source.magnet.Sphere(mag=[0,0,1000],dim=1,pos=[1,2,3])
>>> print(pm.position)
    [1. 2. 3.]
>>> pm.move([3,2,1])
>>> print(pm.position)
    [4. 4. 4.]
rotate(angle, axis, anchor='self.position')

This method rotates the source about axis by angle. The axis passes through the center of rotation anchor. Scalar input is either integer or float. Vector input format can be either list, tuple or array of any data type (float, int).

Parameters:
  • angle (scalar [deg]) – Set angle of rotation in units of [deg]
  • axis (vec3 []) – Set axis of rotation
  • anchor (vec3 [mm]) – Specify the Center of rotation which defines the position of the axis of rotation. If not specified the source will rotate about its own center.
Returns:

Return type:

None

Example

>>> from magpylib import source
>>> pm = source.magnet.Sphere(mag=[0,0,1000], dim=1)
>>> print(pm.position, pm.angle, pm.axis)
  [0. 0. 0.] 0.0 [0. 0. 1.]
>>> pm.rotate(90, [0,1,0], anchor=[1,0,0])
>>> print(pm.position, pm.angle, pm.axis)
  [1., 0., 1.] 90.0 [0., 1., 0.]
setOrientation(angle, axis)

This method sets a new source orientation given by angle and axis. Scalar input is either integer or float. Vector input format can be either list, tuple or array of any data type (float, int).

Parameters:
  • angle (scalar [deg]) – Set new angle of source orientation.
  • axis (vec3 []) – Set new axis of source orientation.
Returns:

Return type:

None

Example

>>> from magpylib import source
>>> pm = source.magnet.Sphere(mag=[0,0,1000],dim=1)
>>> print([pm.angle,pm.axis])
    [0.0, array([0., 0., 1.])]
>>> pm.setOrientation(45,[0,1,0])
>>> print([pm.angle,pm.axis])
    [45.0, array([0., 1., 0.])]
setPosition(newPos)

This method moves the source to the position given by the argument vector newPos. Vector input format can be either list, tuple or array of any data type (float, int)

Parameters:newPos (vec3 [mm]) – Set new position of the source.
Returns:
Return type:None

Example

>>> from magpylib import source
>>> pm = source.magnet.Sphere(mag=[0,0,1000],dim=1)
>>> print(pm.position)
    [0. 0. 0.]
>>> pm.setPosition([5,5,5])
>>> print(pm.position)
    [5. 5. 5.]
magpylib.displaySystem(sources, markers=[[0.0, 0.0, 0.0]], subplotAx=None, sensors=['sensor type', 'sensor type'], suppress=False, direc=False, figsize=(8, 8))[source]

Shows the collection system in an interactive pyplot and returns a matplotlib figure identifier.

Warning

As a result of an inherent problem in matplotlib the Poly3DCollections z-ordering fails when bounding boxes intersect.

Parameters:markers (list[scalar,scalar,scalar,[label]]) – List of position vectors to add visual markers to the display, optional label. Default: [[0,0,0]]

Example

>>> from magpylib import Collection, source
>>> c=source.current.Circular(3,7)
>>> x = Collection(c)
>>> marker0 = [0,0,0,"Neutral Position"]
>>> marker1 = [10,10,10]
>>> x.displaySystem(markers=[ marker0,
...                           marker1])
Parameters:sensors (list[sensor]) – List of Sensor objects to add the display. Default: None

Example

>>> from magpylib import Collection, source
>>> c=source.current.Circular(3,7)
>>> x = Collection(c)
>>> sensor0 = Sensor()
>>> sensor1 = Sensor(pos=[1,2,3], angle=180)
>>> x.displaySystem(sensors=[ sensor0,
...                           sensor1])
Parameters:suppress (bool) – If True, only return Figure information, do not show. Interactive mode must be off. Default: False.

Example

>>> ## Suppress matplotlib.pyplot.show()
>>> ## and returning figure from showing up
>>> from matplotlib import pyplot
>>> pyplot.ioff()
>>> figureData = Collection.displayFigure(suppress=True)
Parameters:direc (bool) – Set to True to show current directions and magnetization vectors. Default: False
Returns:graphics object is displayed through plt.show()
Return type:matplotlib Figure object

Example

>>> from magpylib import source, Collection
>>> pm1 = source.magnet.Box(mag=[0,0,1000],dim=[1,1,1],pos=[-1,-1,-1],angle=45,axis=[0,0,1])
>>> pm2 = source.magnet.Cylinder(mag=[0,0,1000],dim=[2,2],pos=[0,-1,1],angle=45,axis=[1,0,0])
>>> pm3 = source.magnet.Sphere(mag=[0,0,1000],dim=3,pos=[-2,1,2],angle=45,axis=[1,0,0])
>>> C1 = source.current.Circular(curr=100,dim=6)
>>> col = Collection(pm1,pm2,pm3,C1)
>>> col.displaySystem()
Parameters:subplotAx (matplotlib subplot axe instance) – Use an existing matplotlib subplot instance to draw the 3D system plot into. Default: None

Example

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from magpylib.source.magnet import Box
>>> from magpylib import Collection
>>> #create collection of one magnet
>>> s1 = Box(mag=[ 500,0, 500], dim=[3,3,3], pos=[ 0,0, 3], angle=45, axis=[0,1,0])
>>> c = Collection(s1)
>>> #create positions
>>> xs = np.linspace(-8,8,100)
>>> zs = np.linspace(-6,6,100)
>>> posis = [[x,0,z] for z in zs for x in xs]
>>> #calculate fields
>>> Bs = c.getBsweep(posis)
>>> #reshape array and calculate amplitude
>>> Bs = np.array(Bs).reshape([100,100,3])
>>> Bamp = np.linalg.norm(Bs,axis=2)
>>> X,Z = np.meshgrid(xs,zs)
>>> # Define figure
>>> fig = plt.figure()
>>> ## Define ax for 2D
>>> ax1 = fig.add_subplot(1, 2, 1, axisbelow=True)
>>> ## Define ax for 3D displaySystem
>>> ax2 = fig.add_subplot(1, 2, 2, axisbelow=True,projection='3d')
>>> ## field plot 2D
>>> ax1.contourf(X,Z,Bamp,100,cmap='rainbow')
>>> U,V = Bs[:,:,0], Bs[:,:,2]
>>> ax1.streamplot(X, Z, U, V, color='k', density=2)
>>> ## plot Collection system in 3D ax subplot
>>> c.displaySystem(subplotAx=ax2)
Raises:AssertionError – If Marker position list is poorly defined. i.e. listOfPos=(x,y,z) instead of lisOfPos=[(x,y,z)]