### Define System with Paths Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_vis_subplots.html Setup a cylinder magnet and a sensor, both with defined motion paths, to be used in subsequent visualization examples. ```python import numpy as np import magpylib as magpy # Define sensor with path cyl = magpy.magnet.Cylinder( polarization=(1, 0, 0), dimension=(2, 1), position=(4, 0, 0), ) cyl.rotate_from_angax(angle=np.linspace(0, 300, 40), start=0, axis="z", anchor=0) # Define magnet with path sens = magpy.Sensor( pixel=[(-.2, 0, 0), (.2, 0, 0)], position = np.linspace((0, 0, -3), (0, 0, 3), 40) ) ``` -------------------------------- ### Console Output Examples Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_styles.html Expected console output when running the magnetization style demonstration. ```text Default magnetization style ``` ```text Custom magnetization style ``` -------------------------------- ### Install Magpylib via pip Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/guide_start_01_install.html Standard installation method using the Python package manager. ```bash pip install magpylib ``` -------------------------------- ### Setup Magnet Simulation Parameters Source: https://magpylib.readthedocs.io/en/latest/_sources/_pages/user_guide/examples/examples_tutorial_modeling_magnets.md.txt Initializes the simulation environment and defines the linear motion path for the magnet. ```python import numpy as np import matplotlib.pyplot as plt import magpylib as magpy # Testbench positioning xs = np.linspace(-15, 15, 61) ``` -------------------------------- ### Minimal Force Computation Example Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_forcecomp.html A complete example demonstrating the computation of force and torque between a cuboid magnet and a current loop. ```python import numpy as np import magpylib as magpy cube = magpy.magnet.Cuboid(dimension=(1, 1, 1), polarization=(0.1, 0.2, 0.3)) loop = magpy.current.Circle( diameter=2, current=1e3, position=(0, 0, 1), meshing=40, ) F, T = magpy.getFT(cube, loop) print(f"force: {np.round(F, decimals=2)} N") # force: [ 13.67 27.33 -82. ] N print(f"torque: {np.round(T, decimals=2)} N*m") # torque: [-8.54 4.27 0. ] N*m ``` -------------------------------- ### Install Magpylib via conda Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/guide_start_01_install.html Installation method for users managing environments with conda. ```bash conda install -c conda-forge magpylib ``` -------------------------------- ### Compute B-field of a TriangularMesh Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.magnet.html Example demonstrating the initialization of a TriangularMesh and the computation of the B-field at a specific observer position. ```python >>> import numpy as np >>> import magpylib as magpy >>> vv = ((0, 0, 0), (0.01, 0.0, 0.0), (0.0, 0.01, 0.0), (0.0, 0.0, 0.01)) >>> tt = ((0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)) >>> trim = magpy.magnet.TriangularMesh( ... polarization=(0.1, 0.2, 0.3), vertices=vv, faces=tt, ... ) >>> with np.printoptions(precision=3): ... print(trim.getB((0.01, 0.01, 0.01)) * 1000) [2.602 2.082 1.561] ``` -------------------------------- ### Minimal field computation example Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_fieldcomp.html A basic workflow defining a source and observer to compute the magnetic field. ```python import magpylib as magpy # Define source and observer objects loop = magpy.current.Circle(current=1, diameter=0.001) sens = magpy.Sensor() # Compute field B = magpy.getB(loop, sens) print(B) # --> [0. 0. 0.00125664] ``` -------------------------------- ### Load and Simulate Magnetic Field Source: https://magpylib.readthedocs.io/en/latest/_sources/_pages/user_guide/examples/examples_tutorial_modeling_magnets.md.txt Initial setup for loading experimental data and simulating the magnetic field of a cylinder magnet. ```python # Load experimental data data_path = '../../../_static/data/Bomatec_LD025_scan0.npy' Bexp = np.load(data_path) # shape should be (61, 3) # Simulation setup sensor = magpy.Sensor(position=(0, 0, 0)) magnet = magpy.magnet.Cylinder( polarization=(0, 0, 1200), # in mT dimension=(8, 2), # in mm position=[(x,0,7) for x in xs], # z=7 mm center height ) Bsim = sensor.getB(magnet) # Plotting function def plot_field(Bsim, Bexp, xs): """Plot results.""" fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), sharey=True) labels = ['Bx Field (mT)', 'By Field (mT)', 'Bz Field (mT)'] for i,ax in enumerate(axes): ax.plot(xs, Bsim[:, i], color='b', label='Simulation') ax.plot(xs, Bexp[:, i], ls='', marker='.', color='orange', label='Experiment') ax.set_title(labels[i]) ax.set_xlabel('Magnet Position (mm)') ax.grid(color='.85') ax.legend(loc='upper right') plt.tight_layout() plt.show() plot_field(Bsim, Bexp, xs) ``` -------------------------------- ### Calculate B-field with Magpylib Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Examples demonstrating magnetic field calculation for various source and observer configurations. ```python >>> import numpy as np >>> import magpylib as magpy >>> loop = magpy.current.Circle(current=100, diameter=0.002) >>> sph = magpy.magnet.Sphere(polarization=(0.0, 0.0, 0.1), diameter=0.001) >>> B = magpy.getB([loop, sph], (0.01, 0.01, 0.01)) >>> with np.printoptions(precision=3): ... print(B) [[ 6.054e-06 6.054e-06 2.357e-08] [ 8.019e-07 8.019e-07 -9.056e-23]] ``` ```python >>> s1 = magpy.Sensor(position=(0.01, 0.01, 0.01)) >>> s2 = s1.copy(position=(0.01, 0.01, -0.01)) >>> B = magpy.getB([loop, sph], [s1, s2]) >>> with np.printoptions(precision=3): ... print(B) [[[ 6.054e-06 6.054e-06 2.357e-08] [-6.054e-06 -6.054e-06 2.357e-08]] [[ 8.019e-07 8.019e-07 -9.056e-23] [-8.019e-07 -8.019e-07 -9.056e-23]]] ``` -------------------------------- ### Configure Individual Object Styles Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_styles.html Demonstrates setting individual styles at initialization versus after initialization, noting the performance implications of deferred style loading. ```python import magpylib as magpy # Reset defaults from previous example magpy.defaults.reset() # Default style cube = magpy.magnet.Cuboid( polarization=(1, 0, 0), dimension=(1, 1, 1), ) # Good practice: define individual style at object init cylinder = magpy.magnet.Cylinder( polarization=(0, 1, 0), dimension=(1, 1), position=(2, 0, 0), style_magnetization_color_mode="tricycle", ) # Bad practice: set individual style after object init sphere = magpy.magnet.Sphere( polarization=(0, 1, 1), diameter=1, position=(4, 0, 0), ) sphere.style.magnetization.color.mode = "bicolor" # Show styled objects magpy.show(cube, cylinder, sphere, backend="plotly") ``` -------------------------------- ### Apply move operation with start index Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.misc.html Applies a displacement starting from a specific path index. ```python >>> sens.move((0, 0, 2), start=2) Sensor(id=...) >>> print(sens.position) [[2. 2. 2.] [3. 3. 3.] [4. 4. 6.] [5. 5. 7.]] ``` -------------------------------- ### Applying Magnet Color Schemes Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_vis_magnet_colors.html Demonstrates configuring magnetization styles using dictionaries, direct keyword arguments, and object attribute assignment. ```python import magpylib as magpy print('APPLYING DIFFERENT MAGNET COLOR SCHEMES') # Create a magnetization style dictionary mstyle = dict( mode="color+arrow", color=dict(north="magenta", middle="white", south="turquoise"), arrow=dict(width=2, color="k") ) # Create magnet and apply style sphere = magpy.magnet.Sphere( polarization=(1, 1, 1), diameter=1, position=(-1, 1, 0), style_magnetization=mstyle, ) # Create a second magnet with different style cube = magpy.magnet.Cuboid( polarization=(1, 0, 0), dimension=(1, .2, .2), position=(1, 1, 0), style_magnetization_color_mode="bicolor", style_magnetization_color_north="r", style_magnetization_color_south="g", style_magnetization_color_transition=0, ) # Create a third magnet with different style cyl = magpy.magnet.CylinderSegment( polarization=(1, 0, 0), dimension=(1.7, 2, .3, -145, -35), ) cyl.style.magnetization.color.north = "cornflowerblue" cyl.style.magnetization.color.south = "orange" # Show all three magpy.show(sphere, cube, cyl, backend='plotly', style_legend_show=False) ``` -------------------------------- ### Iterate and display with supported backends Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_graphics.html Demonstrates how to iterate through all supported plotting backends and render objects using each one. ```python import magpylib as magpy import numpy as np # Define sources and paths loop = magpy.current.Circle( current=1, diameter=1, position=np.linspace((0, 0, -3), (0, 0, 3), 40) ) cylinder = magpy.magnet.Cylinder( polarization=(0, -1, 0), dimension=(1, 2), position=(0, -3, 0) ) cylinder.rotate_from_angax(np.linspace(0, 300, 40), "z", anchor=0, start=0) for backend in magpy.SUPPORTED_PLOTTING_BACKENDS: print(backend) magpy.show(loop, cylinder, backend=backend) ``` -------------------------------- ### Initialize and compute field for MagnetRing Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_misc_compound.html Demonstrates instantiating the custom MagnetRing, performing transformations, and computing the magnetic field at a sensor. ```python # Continuation from above - ensure previous code is executed # Add a sensor sensor = magpy.Sensor(position=(0, 0, 0)) # Create a MagnetRing object ring = MagnetRing() # Move MagnetRing around ring.rotate_from_angax(angle=45, axis='x') # Compute field print(f"B-field at sensor → {ring.getB(sensor).round(2)}") # Display graphically magpy.show(ring, sensor, backend='plotly') ``` ```text B-field at sensor → [ 0. 0.04 -0.04] ``` -------------------------------- ### Rotate objects using scipy Rotation Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Examples of rotating objects about the origin, about themselves, and creating rotation paths. ```python >>> 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.] ``` ```python >>> 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.] ``` ```python >>> 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.]] ``` -------------------------------- ### Configure Moving and Rotating Sensors Source: https://magpylib.readthedocs.io/en/latest/_sources/_pages/user_guide/examples/examples_tutorial_field_computation.md.txt Demonstrates defining a sensor with multiple pixels and applying movement and rotation paths alongside moving source objects. ```python import numpy as np import magpylib as magpy # Reset defaults set in previous example magpy.defaults.reset() # Define sensor with path sensor = magpy.Sensor(pixel=[(0, 0, -0.0005), (0, 0, 0.0005)], style_size=1.5) sensor.position = np.linspace((0, 0, -0.003), (0, 0, 0.003), 37) angles = np.linspace(0, 360, 37) sensor.rotate_from_angax(angles, "z", start=0) # Define source with path cyl1 = magpy.magnet.Cylinder( polarization=(0.1, 0, 0), dimension=(0.001, 0.002), position=(0.003, 0, 0) ) cyl2 = cyl1.copy(position=(-0.003, 0, 0)) coll = magpy.Collection(cyl1, cyl2) coll.rotate gen_from_angax(-angles, "z", start=0) # Display system and field at sensor with magpy.show_context(sensor, coll, animation=True, backend="plotly"): magpy.show(col=1) magpy.show(output="Bx", col=2, pixel_agg=None) ``` -------------------------------- ### Add objects to a collection Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Shows how to initialize a collection with objects and add additional sensors dynamically. ```python >>> import magpylib as magpy >>> x1 = magpy.Sensor(style_label='x1') >>> coll = magpy.Collection(x1, style_label='coll') >>> coll.describe(format='label') coll └── x1 ``` ```python >>> x2 = magpy.Sensor(style_label='x2') >>> coll.add(x2) Collection(id=...) >>> coll.describe(format='label') coll ├── x1 └── x2 ``` -------------------------------- ### Create Sources and Observers Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/guide_start_02_fundamentals.html Instantiate magnetic sources like Cuboids and measurement sensors as Python objects. ```python import magpylib as magpy # Create a Cuboid magnet with magnetic polarization # of 1 T pointing in x-direction and sides of # 1, 2 and 3 cm respectively (notice the use of SI units). cube = magpy.magnet.Cuboid(polarization=(1, 0, 0), dimension=(0.01, 0.02, 0.03)) # Create a Sensor for measuring the field sensor = magpy.Sensor() ``` -------------------------------- ### Using Show Context Manager Source: https://magpylib.readthedocs.io/en/latest/_sources/_pages/user_guide/examples/examples_vis_subplots.md.txt Utilizes a context manager to easily arrange multiple field outputs and the 3D model into a grid layout. ```python with magpy.show_context([cyl, sens], backend='plotly') as sc: sc.show(output="Bx", col=1, row=1) sc.show(output="By", col=1, row=2) sc.show(output="Bz", col=2, row=1) sc.show(output="model3d", col=2, row=2) ``` -------------------------------- ### Compute Magpylib field Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_graphics.html Basic setup for computing magnetic fields using a circular loop and a sensor array. ```python import magpylib as magpy import numpy as np # Magpylib field computation loop = magpy.current.Circle(current=1, diameter=0.1) sens = magpy.Sensor(position=np.linspace((0, 0, -0.1), (0, 0, 0.1), 100)) B = loop.getB(sens) ``` -------------------------------- ### Add and manipulate 3D traces with generic backend Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_styles.html Demonstrates adding multiple Scatter3d traces to a sensor and manipulating copied Trace3d objects. ```python # Continuation from above - ensure previous code is executed import copy import numpy as np # Generate trace and add to sensor ts = np.linspace(0, 2 * np.pi, 30) trace_scatter3d = { "backend": "generic", "constructor": "Scatter3d", "kwargs": { "x": 1.2*np.cos(ts), "y": 1.2*np.sin(ts), "z": np.zeros(30), "mode": "lines", }, } sensor.style.model3d.add_trace(trace_scatter3d) # Generate new trace from Trace3d object trace2 = copy.deepcopy(sensor.style.model3d.data[1]) trace2.kwargs["x"] = np.zeros(30) trace2.kwargs["z"] = 1.2*np.cos(ts) sensor.style.model3d.add_trace(trace2) # Show magpy.show(sensor) ``` -------------------------------- ### Create a simple animation Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_vis_animations.html Uses the show() function with animation=True to animate objects defined with motion paths. ```python import magpylib as magpy import numpy as np # Define magnet with path magnet = magpy.magnet.Cylinder( polarization=(1, 0, 0), dimension=(2, 1), position=(4, 0, 0), style_label="magnet", ) magnet.rotate_from_angax(angle=np.linspace(0, 300, 40), start=0, axis="z", anchor=0) # Define sensor with path sensor = magpy.Sensor( pixel=[(-0.2, 0, 0), (0.2, 0, 0)], position=np.linspace((0, 0, -3), (0, 0, 3), 40), style_label="sensor", ) # Display as animation - prefers plotly backend magpy.show(sensor, magnet, animation=True, backend="plotly") ``` -------------------------------- ### Pyvista backend warning message Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_styles.html Warning message displayed when using the Pyvista backend in a notebook environment without trame installed. ```text 2026-07-09 13:01:48.039 ( 0.289s) [ 789BA1ABBB80]vtkXOpenGLRenderWindow.:1460 WARN| bad X server connection. DISPLAY= /home/docs/checkouts/readthedocs.org/user_builds/magpylib/checkouts/latest/src/magpylib/_src/display/backend_pyvista.py:366: UserWarning: Using static image for notebook display. Install trame for interactive backends: pip install "pyvista[jupyter]" ``` -------------------------------- ### Pyvista Deprecation Error Traceback Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_vis_pv_streamlines.html Example of a DeprecationError encountered when using the deprecated max_time parameter in Pyvista's streamlines_from_source method. ```text --------------------------------------------------------------------------- DeprecationError Traceback (most recent call last) Cell In[1], line 19 15 grid["B"] = magnet.getB(grid.points) * 1000 # T -> mT 16 17 # Compute the field lines 18 seed = pv.Disc(inner=0.001, outer=0.003, r_res=1, c_res=9) ---> 19 strl = grid.streamlines_from_source( 20 seed, 21 vectors="B", 22 max_step_length=0.1, File ~/checkouts/readthedocs.org/user_builds/magpylib/checkouts/latest/.venv/lib/python3.13/site-packages/pyvista/_deprecate_positional_args.py:243, in _deprecate_positional_args.._inner_deprecate_positional_args..inner_f(*args, **kwargs) 239 warn_external(msg, PyVistaDeprecationWarning) 241 warn_positional_args() --> 243 return f(*args, **kwargs) File ~/checkouts/readthedocs.org/user_builds/magpylib/checkouts/latest/.venv/lib/python3.13/site-packages/pyvista/core/filters/data_set.py:3675, in DataSetFilters.streamlines_from_source(self, source, vectors, integrator_type, integration_direction, surface_streamlines, initial_step_length, step_unit, min_step_length, max_step_length, max_steps, terminal_speed, max_error, max_time, compute_vorticity, rotation_scale, interpolator_type, progress_bar, max_length) 3670 if max_time is not None: 3671 msg = ( 3672 '``max_time`` parameter is deprecated and no longer supported. ' 3673 'Use ``max_length`` instead.' 3674 ) -> 3675 raise DeprecationError(msg) 3677 if max_length is None: 3678 max_length = 4.0 * self.GetLength() DeprecationError: ``max_time`` parameter is deprecated and no longer supported. Use ``max_length`` instead. ``` -------------------------------- ### Initialize TriangularMesh Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_classes.html Constructor signature for creating a TriangularMesh object with specified geometry and magnetization properties. ```python magpylib.magnet.TriangularMesh( position, orientation, vertices, faces, polarization, magnetization, meshing, check_open, check_disconnected, check_selfintersecting, reorient_faces, style, ) ``` -------------------------------- ### Merge Multiple Path Operations Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_tutorial_paths.html Combine linear movement and multiple rotations by specifying start indices to create complex motion paths. ```python import numpy as np from magpylib.magnet import Cuboid # Create cube and set linear path cube = Cuboid(polarization=(0, 0, 0.1), dimension=(0.02, 0.02, 0.02)) cube.position = np.linspace((0, 0, 0), (0.1, 0, 0), 60) # Apply rotation about self - starting at index 0 cube.rotate_from_rotvec(np.linspace((0, 0, 0), (0, 0, 360), 30), start=0) # Apply rotation about origin - starting at index 30 cube.rotate_from_rotvec(np.linspace((0, 0, 0), (0, 0, 360), 30), anchor=0, start=30) # Display paths as animation cube.show(backend="plotly", animation=True) ``` -------------------------------- ### Equivalent show_context Usage Patterns Source: https://magpylib.readthedocs.io/en/latest/_sources/_pages/user_guide/docs/docs_graphics.md.txt Demonstrates that calling show() on the context manager object is equivalent to calling magpy.show() directly within the context block. ```python import magpylib as magpy obj1 = magpy.magnet.Cuboid() obj2 = magpy.magnet.Cylinder() with magpy.show_context() as sc: sc.show(obj1, col=1) sc.show(obj2, col=2) ``` ```python import magpylib as magpy obj1 = magpy.magnet.Cuboid() obj2 = magpy.magnet.Cylinder() with magpy.show_context(): magpy.show(obj1, col=1) magpy.show(obj2, col=2) ``` -------------------------------- ### Rotate an object using angle-axis Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.misc.html Examples of rotating objects using the rotate_from_angax method, covering rotation about the origin, about the object itself, and creating multi-step paths. ```python >>> 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.] ``` ```python >>> 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.] ``` ```python >>> 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.]] ``` -------------------------------- ### Compute B-field with Sensor Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Compute the magnetic B-field in Tesla as seen by a sensor. Examples demonstrate basic computation, rotation, and pixel-based field sensing. ```python >>> import numpy as np >>> import magpylib as magpy >>> sens = magpy.Sensor() >>> loop = magpy.current.Circle(current=1, diameter=0.01) >>> B = sens.getB(loop) >>> with np.printoptions(precision=3): ... print(B*1000) [0. 0. 0.126] ``` ```python >>> sens.rotate_from_rotvec((45, 0, 0)) Sensor(id=...) >>> B = sens.getB(loop) >>> with np.printoptions(precision=3): ... print(B) [0.000e+00 8.886e-05 8.886e-05] ``` ```python >>> sens.pixel = ((0, 0, 0), (0.001, 0, 0), (0.002, 0, 0)) >>> B = sens.getB(loop) >>> with np.printoptions(precision=3): ... print(B) [[0.000e+00 8.886e-05 8.886e-05] [0.000e+00 9.163e-05 9.163e-05] [0.000e+00 1.014e-04 1.014e-04]] ``` -------------------------------- ### Convergence Analysis with Reciprocity Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_force_intro.html Demonstrates how to evaluate force and torque convergence by comparing numerical results against an exact solution using reciprocity. ```python import numpy as np import magpylib as magpy dipole = magpy.misc.Dipole(moment=(0, 0, 1e6), position=(1, 1, 1)) loop = magpy.current.Circle(diameter=1, current=1) # Forward (exact) F0, T0 = magpy.getFT(loop, dipole, pivot=(0, 0, 0)) # Backward (numerical), has opposite sign for meshing in [8, 40, 200, 1000]: # Set meshing parameter loop.meshing = meshing # Compute backward force and torque F1, T1 = magpy.getFT(dipole, loop, pivot=(0, 0, 0)) # Compute vectorwise relative error errF = np.linalg.norm(F1 + F0) / np.linalg.norm(F0) errT = np.linalg.norm(T1 + T0) / np.linalg.norm(T0) print(f"Meshing: {meshing:>4}, Force Error: {errF:.2e}, Torque Error: {errT:.2e}") # Meshing: 8, Force Error: 1.02e-02, Torque Error: 3.93e-03 # Meshing: 40, Force Error: 3.82e-04, Torque Error: 8.30e-05 # Meshing: 200, Force Error: 1.53e-05, Torque Error: 3.31e-06 # Meshing: 1000, Force Error: 6.12e-07, Torque Error: 1.33e-07 ``` -------------------------------- ### Initialize CylinderSegment Magnet Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_classes.html Defines a magnet as a cylindrical ring section with dimensions (inner radius, outer radius, height, start angle, end angle). ```python magpylib.magnet.CylinderSegment( position, orientation, dimension, polarization, magnetization, meshing, style ) ``` -------------------------------- ### Use and manipulate the MagnetRing compound Source: https://magpylib.readthedocs.io/en/latest/_sources/_pages/user_guide/examples/examples_misc_compound.md.txt Demonstrates initializing the custom compound, applying transformations, and computing magnetic fields. ```python # Continuation from above - ensure previous code is executed # Add a sensor sensor = magpy.Sensor(position=(0, 0, 0)) # Create a MagnetRing object ring = MagnetRing() # Move MagnetRing around ring.rotate_from_angax(angle=45, axis='x') # Compute field print(f"B-field at sensor → {ring.getB(sensor).round(2)}") # Display graphically magpy.show(ring, sensor, backend='plotly') ``` -------------------------------- ### Manipulating Object Paths with Move Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_pos_ori.html Demonstrates how scalar and vector inputs affect object paths, including the use of the start parameter to control where operations are applied. ```python import magpylib as magpy # Note that all units are in SI sensor = magpy.Sensor() print(sensor.position) # Default value # --> [0. 0. 0.] sensor.move((1, 1, 1)) # Scalar input is by default applied print(sensor.position) # to the whole path # --> [1. 1. 1.] sensor.move([(1, 1, 1), (2, 2, 2)]) # Vector input is by default appended print(sensor.position) # to the existing path # --> [[1. 1. 1.] [2. 2. 2.] [3. 3. 3.]] sensor.move((1, 1, 1), start=1) # Scalar input and start=1 is applied print(sensor.position) # to whole path starting at index 1 # --> [[1. 1. 1.] [3. 3. 3.] [4. 4. 4.]] sensor.move([(0, 0, 10), (0, 0, 20)], start=1) # Vector input and start=1 merges print(sensor.position) # the input with the existing path # --> [[ 1. 1. 1.] [ 3. 3. 13.] [ 4. 4. 24.]] # starting at index 1. ``` -------------------------------- ### Rotate Object using Euler Angles Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Examples of rotating objects using Euler angles, including rotation about the origin, about the object itself, and creating a rotation path. ```python >>> 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.] ``` ```python >>> 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.] ``` ```python >>> 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.]] ``` -------------------------------- ### show Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Displays objects and their paths graphically. ```APIDOC ## show(*, backend=None, canvas=None, animation=None, zoom=None, markers=None, return_fig=None, canvas_update=None, row=None, col=None, output=None, sumup=None, pixel_agg=None, style=None, **kwargs) ### Description Display objects and paths graphically. Global graphic styles can be set using kwargs or style dictionaries. ``` -------------------------------- ### Initialize CustomSource Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/docs/docs_classes.html Creates a user-defined source using a custom field computation function that must accept field type and observer positions. ```python magpylib.misc.CustomSource(field_func, position, orientation, style) ``` -------------------------------- ### Create and Manipulate a Collection Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Demonstrates creating a collection with two sources and moving the entire group, which updates the positions of all children. ```python >>> import numpy as np >>> import magpylib as magpy >>> src1 = magpy.magnet.Sphere(position=(2, 0, 0), diameter=1, polarization=(0.1, 0.2, 0.3)) >>> src2 = magpy.current.Circle(position=(-2, 0, 0), diameter=1, current=1) >>> col = magpy.Collection(src1, src2) >>> col.move((0, 0, 2)) Collection(id=...) >>> print(src1.position) [2. 0. 2.] >>> print(src2.position) [-2. 0. 2.] >>> print(col.position) [0. 0. 2.] ``` -------------------------------- ### Manipulate Collections and Animations Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_tutorial_collection.html Demonstrates creating a Helmholtz coil collection, applying movement and rotation to sub-groups, and generating an animation. ```python import numpy as np import magpylib as magpy # Construct two coils from windings coil1 = magpy.Collection(style_label="coil1") for z in np.linspace(-0.0005, 0.0005, 5): coil1.add(magpy.current.Circle(current=1, diameter=0.02, position=(0, 0, z))) coil1.position = (0, 0, -0.005) coil2 = coil1.copy(position=(0, 0, 0.005)) # Helmholtz consists of two coils helmholtz = coil1 + coil2 # Move the helmholtz helmholtz.position = np.linspace((0, 0, 0), (0.01, 0, 0), 15) helmholtz.rotate_from_angax(np.linspace(0, 180, 15), "x", start=0) # Move the coils coil1.move(np.linspace((0, 0, 0), (0.005, 0, 0), 15)) coil2.move(np.linspace((0, 0, 0), (-0.005, 0, 0), 15)) # Move the windings for coil in [coil1, coil2]: for i, wind in enumerate(coil): wind.move(np.linspace((0, 0, 0), (0, 0, (2 - i) * 0.001), 15)) # Display as animation magpy.show(*helmholtz, animation=True, style_path_show=False) ``` -------------------------------- ### Verifying convergence with meshing parameters Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_force_intro.html Test convergence by iterating through different meshing densities to ensure result stability. ```python # Test multiple mesh densities meshings = [50, 100, 200] for m in meshings: target.meshing = m F, T = magpy.getFT(source, target) # Compare results... ``` -------------------------------- ### Create a Cuboctahedron Magnet with Triangles Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_shapes_triangle.html Demonstrates defining a collection of triangles to form a cuboctahedron shape and visualizing it with PyVista. ```python import magpylib as magpy import numpy as np # Create collection of triangles triangles_cm = [ ([0, 1, -1], [-1, 1, 0], [1, 1, 0]), ([0, 1, 1], [1, 1, 0], [-1, 1, 0]), ([0, 1, 1], [-1, 0, 1], [0, -1, 1]), ([0, 1, 1], [0, -1, 1], [1, 0, 1]), ([0, 1, -1], [1, 0, -1], [0, -1, -1]), ([0, 1, -1], [0, -1, -1], [-1, 0, -1]), ([0, -1, 1], [-1, -1, 0], [1, -1, 0]), ([0, -1, -1], [1, -1, 0], [-1, -1, 0]), ([-1, 1, 0], [-1, 0, -1], [-1, 0, 1]), ([-1, -1, 0], [-1, 0, 1], [-1, 0, -1]), ([1, 1, 0], [1, 0, 1], [1, 0, -1]), ([1, -1, 0], [1, 0, -1], [1, 0, 1]), ([0, 1, 1], [-1, 1, 0], [-1, 0, 1]), ([0, 1, 1], [1, 0, 1], [1, 1, 0]), ([0, 1, -1], [-1, 0, -1], [-1, 1, 0]), ([0, 1, -1], [1, 1, 0], [1, 0, -1]), ([0, -1, -1], [-1, -1, 0], [-1, 0, -1]), ([0, -1, -1], [1, 0, -1], [1, -1, 0]), ([0, -1, 1], [-1, 0, 1], [-1, -1, 0]), ([0, -1, 1], [1, -1, 0], [1, 0, 1]), ] triangles = np.array(triangles_cm) / 100 # cm -> m cuboc = magpy.Collection() for t in triangles: cuboc.add( magpy.misc.Triangle( polarization=(0.1, 0.2, 0.3), vertices=t, ) ) # Display collection of triangles magpy.show( cuboc, backend="pyvista", style_magnetization_mode="arrow", style_orientation_color="yellow", ) ``` -------------------------------- ### Simulate and Visualize Magnetic Image Method Source: https://magpylib.readthedocs.io/en/latest/_pages/user_guide/examples/examples_misc_image_method.html Uses Magpylib to define a magnet and its mirror image, then computes and renders the magnetic field lines using PyVista. ```python import pyvista as pv import magpylib as magpy from scipy.spatial.transform import Rotation as R # Magnet Parameters height = 1 angle = 30 # Create a cuboid magnet above the mirror plane magnet = magpy.magnet.Cylinder( polarization=(0, 0, 1), dimension=(1, 1), position=(0, 0, height), orientation=R.from_euler('y', angle, degrees=True) ) # Create mirror image of the magnet mirror_magnet = magnet.copy( position=(0, 0, -1), # Mirror position orientation=R.from_euler('y', -angle, degrees=True) # Mirror orientation ) # Create a 3D grid with Pyvista grid = pv.ImageData( dimensions=(61, 61, 61), spacing=(0.1, 0.1, 0.1), origin=(-3, -3, 0), ) # Compute B-field and add as data to grid col = magnet + mirror_magnet grid["B"] = col.getB(grid.points)*1000 # Convert to mT # Compute the field lines seed = pv.Disc(center=(0, 0, 0), inner=2, outer=3, r_res=1, c_res=12) strl = grid.streamlines_from_source( seed, vectors="B", max_step_length=0.02, integration_direction="backward", ) # Create a Pyvista plotting scene pl = pv.Plotter() # Add magnet to scene - streamlines units in (m) magpy.show(magnet, canvas=pl, units_length="m", backend="pyvista") # Prepare legend parameters legend_args = { "title": "B (mT)", "title_font_size": 20, "color": "black", "position_y": 0.25, "vertical": True, } # Add streamlines and legend to scene pl.add_mesh( strl.tube(radius=0.02), cmap="bwr", scalar_bar_args=legend_args, ) # Add mirror to the scene disc = pv.Disc(center=(0, 0, 0), inner=0.0, outer=4, normal=(0, 0, 1), r_res=1, c_res=100) pl.add_mesh(disc, color='lightblue', show_edges=False) # Prepare and show scene pl.camera.position = (5, 15, 10) pl.show() ``` -------------------------------- ### Configure Magpylib Object Styling Source: https://magpylib.readthedocs.io/en/latest/_autogen/magpylib.html Demonstrates setting global and individual object styles for visualization, including path visibility and magnetization representation. ```python >>> 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 ```