Note
Go to the end to download the full example code.
Biplanar coil design¶
Example showing a basic biplanar coil producing homogeneous field in a target region between the two coil planes.
import pyvista as pv
pv.set_plot_theme("document")
import numpy as np
import matplotlib.pyplot as plt
import trimesh
from bfieldtools.mesh_conductor import MeshConductor
from bfieldtools.coil_optimize import optimize_streamfunctions
from bfieldtools.viz import plot_cross_section
from bfieldtools.utils import combine_meshes, load_example_mesh
# Load simple plane mesh that is centered on the origin
planemesh = load_example_mesh("10x10_plane_hires")
# Specify coil plane geometry
center_offset = np.array([0, 0, 0])
standoff = np.array([0, 3, 0])
# Create coil plane pairs
coil_plus = trimesh.Trimesh(
planemesh.vertices + center_offset + standoff, planemesh.faces, process=False
)
coil_minus = trimesh.Trimesh(
planemesh.vertices + center_offset - standoff, planemesh.faces, process=False
)
joined_planes = combine_meshes((coil_plus, coil_minus))
# Create mesh class object
coil = MeshConductor(
mesh_obj=joined_planes, fix_normals=True, basis_name="suh", N_suh=100
)
Calculating surface harmonics expansion...
Computing the laplacian matrix...
Computing the mass matrix...
Set up target and stray field points
# Here, the target points are on a volumetric grid within a sphere
center = np.array([0, 0, 0])
sidelength = 1.5
n = 8
xx = np.linspace(-sidelength / 2, sidelength / 2, n)
yy = np.linspace(-sidelength / 2, sidelength / 2, n)
zz = np.linspace(-sidelength / 2, sidelength / 2, n)
X, Y, Z = np.meshgrid(xx, yy, zz, indexing="ij")
x = X.ravel()
y = Y.ravel()
z = Z.ravel()
target_points = np.array([x, y, z]).T
# Turn cube into sphere by rejecting points "in the corners"
target_points = (
target_points[np.linalg.norm(target_points, axis=1) < sidelength / 2] + center
)
# Here, the stray field points are on a spherical surface
stray_radius = 20
stray_points_mesh = trimesh.creation.icosphere(subdivisions=3, radius=stray_radius)
stray_points = stray_points_mesh.vertices + center
n_stray_points = len(stray_points)
Create bfield specifications used when optimizing the coil geometry
# The absolute target field amplitude is not of importance,
# and it is scaled to match the C matrix in the optimization function
target_field = np.zeros(target_points.shape)
target_field[:, 0] += 1
target_spec = {
"coupling": coil.B_coupling(target_points),
"abs_error": 0.01,
"target": target_field,
}
stray_spec = {
"coupling": coil.B_coupling(stray_points),
"abs_error": 0.01,
"target": np.zeros((n_stray_points, 3)),
}
bfield_specification = [target_spec, stray_spec]
Computing magnetic field coupling matrix, 3184 vertices by 160 target points... took 0.31 seconds.
Computing magnetic field coupling matrix, 3184 vertices by 642 target points... took 1.32 seconds.
# Compute the optimal stream function, either using a numerical solver or regularized least squares
# import mosek
coil.s, prob = optimize_streamfunctions(
coil,
[target_spec, stray_spec],
objective="minimum_ohmic_power",
# solver="CLARABEL",
# solver_opts={"mosek_params": {mosek.iparam.num_threads: 8}},
)
Computing the resistance matrix...
Passing problem to solver...
===============================================================================
CVXPY
v1.9.2
===============================================================================
-------------------------------------------------------------------------------
Compilation
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
Numerical solver
-------------------------------------------------------------------------------
-----------------------------------------------------------------
OSQP v1.0.0 - Operator Splitting QP Solver
(c) The OSQP Developer Team
-----------------------------------------------------------------
problem: variables n = 100, constraints m = 4812
nnz(P) + nnz(A) = 486244
settings: algebra = Built-in,
OSQPInt = 4 bytes, OSQPFloat = 8 bytes,
linear system solver = QDLDL v0.1.8,
eps_abs = 1.0e-05, eps_rel = 1.0e-05,
eps_prim_inf = 1.0e-04, eps_dual_inf = 1.0e-04,
rho = 1.00e-01 (adaptive: 50 iterations),
sigma = 1.00e-06, alpha = 1.60, max_iter = 10000
check_termination: on (interval 25, duality gap: on),
time_limit: 1.00e+10 sec,
scaling: on (10 iterations), scaled_termination: off
warm starting: on, polishing: on,
iter objective prim res dual res gap rel kkt rho time
1 0.0000e+00 9.90e-01 1.67e+01 -2.28e+02 1.67e+01 1.00e-01 4.77e-02s
200 8.2090e+00 6.54e-04 2.57e-03 -6.63e-02 2.57e-03 1.00e-01 2.08e-01s
400 8.2121e+00 6.24e-04 3.35e-05 -5.03e-02 6.24e-04 1.00e-01 3.68e-01s
600 8.2126e+00 6.18e-04 3.43e-05 -7.39e-02 6.18e-04 1.00e-01 5.28e-01s
800 8.2982e+00 5.64e-05 2.83e-03 -6.32e-02 2.83e-03 1.43e-02* 6.89e-01s
1000 8.3073e+00 2.82e-05 2.33e-06 1.47e-03 1.47e-03 1.43e-02 8.76e-01s
1200 8.3061e+00 2.59e-05 2.81e-07 1.64e-04 1.64e-04 8.40e-02* 1.04e+00s
1400 8.3059e+00 2.54e-05 8.49e-07 -5.12e-05 2.54e-05 8.40e-02 1.23e+00s
1600 8.3059e+00 2.52e-05 8.41e-07 -5.51e-05 2.52e-05 8.40e-02 1.39e+00s
1800 8.3059e+00 2.50e-05 8.33e-07 -5.90e-05 2.50e-05 8.40e-02 1.55e+00s
2000 8.3059e+00 2.48e-05 8.25e-07 -6.27e-05 2.48e-05 8.40e-02 1.72e+00s
2200 8.3059e+00 2.46e-05 8.18e-07 -6.64e-05 2.46e-05 8.40e-02 1.89e+00s
2400 8.3059e+00 2.44e-05 8.11e-07 -6.99e-05 2.44e-05 8.40e-02 2.05e+00s
2600 8.3059e+00 2.43e-05 8.04e-07 -7.34e-05 2.43e-05 8.40e-02 2.22e+00s
2800 8.3059e+00 2.41e-05 7.98e-07 -7.68e-05 2.41e-05 8.40e-02 2.38e+00s
3000 8.3059e+00 2.39e-05 7.92e-07 -8.01e-05 2.39e-05 8.40e-02 2.54e+00s
3200 8.3059e+00 2.37e-05 7.85e-07 -8.33e-05 2.37e-05 8.40e-02 2.71e+00s
3400 8.3059e+00 2.35e-05 7.79e-07 -8.65e-05 2.35e-05 8.40e-02 2.88e+00s
3600 8.3059e+00 2.34e-05 7.73e-07 -8.95e-05 2.34e-05 8.40e-02 3.04e+00s
3800 8.3059e+00 2.32e-05 7.67e-07 -9.25e-05 2.32e-05 8.40e-02 3.21e+00s
4000 8.3059e+00 2.30e-05 7.61e-07 -9.54e-05 2.30e-05 8.40e-02 3.37e+00s
4200 8.3059e+00 2.28e-05 7.56e-07 -9.82e-05 2.28e-05 8.40e-02 3.53e+00s
4400 8.3059e+00 2.27e-05 7.50e-07 -1.01e-04 2.27e-05 8.40e-02 3.70e+00s
4600 8.3059e+00 2.25e-05 7.44e-07 -1.04e-04 2.25e-05 8.40e-02 3.86e+00s
4800 8.3059e+00 2.23e-05 7.39e-07 -1.06e-04 2.23e-05 8.40e-02 4.03e+00s
5000 8.3059e+00 2.22e-05 7.33e-07 -1.09e-04 2.22e-05 8.40e-02 4.19e+00s
5200 8.3059e+00 2.20e-05 7.28e-07 -1.11e-04 2.20e-05 8.40e-02 4.36e+00s
5400 8.3059e+00 2.18e-05 7.22e-07 -1.14e-04 2.18e-05 8.40e-02 4.52e+00s
5600 8.3059e+00 2.17e-05 7.17e-07 -1.16e-04 2.17e-05 8.40e-02 4.68e+00s
5800 8.3059e+00 2.15e-05 7.11e-07 -1.18e-04 2.15e-05 8.40e-02 4.85e+00s
6000 8.3059e+00 2.13e-05 7.06e-07 -1.20e-04 2.13e-05 8.40e-02 5.01e+00s
6200 8.3059e+00 2.12e-05 7.01e-07 -1.23e-04 2.12e-05 8.40e-02 5.19e+00s
6400 8.3059e+00 2.10e-05 6.95e-07 -1.25e-04 2.10e-05 8.40e-02 5.35e+00s
6600 8.3059e+00 2.09e-05 6.90e-07 -1.27e-04 2.09e-05 8.40e-02 5.52e+00s
6800 8.3059e+00 2.07e-05 6.85e-07 -1.29e-04 2.07e-05 8.40e-02 5.68e+00s
7000 8.3059e+00 2.06e-05 6.80e-07 -1.31e-04 2.06e-05 8.40e-02 5.84e+00s
7200 8.3059e+00 2.04e-05 6.75e-07 -1.32e-04 2.04e-05 8.40e-02 6.01e+00s
7400 8.3059e+00 2.03e-05 6.70e-07 -1.34e-04 2.03e-05 8.40e-02 6.18e+00s
7600 8.3059e+00 2.01e-05 6.65e-07 -1.36e-04 2.01e-05 8.40e-02 6.34e+00s
7700 8.3059e+00 2.00e-05 6.62e-07 -1.37e-04 2.00e-05 8.40e-02 6.42e+00s
status: solved
solution polishing: unsuccessful
number of iterations: 7700
optimal objective: 8.3059
dual objective: 8.3060
duality gap: -1.3679e-04
primal-dual integral: 2.3219e+02
run time: 6.42e+00s
optimal rho estimate: 2.83e-01
-------------------------------------------------------------------------------
Summary
-------------------------------------------------------------------------------
Plot the optimized stream function, then discretize it and plot coil windings and the resultant magnetic field
plotter = coil.s.plot()
loops = coil.s.discretize(N_contours=10)
fig = loops.plot_loops()
B_target = loops.magnetic_field(target_points)
fig.add_arrows(target_points, B_target, mag=1e6)


Processing contour, value: -10958797.390404392
Processing contour, value: -8523475.891897963
Processing contour, value: -6088154.393391535
Processing contour, value: -3652832.894885106
Processing contour, value: -1217511.3963786792
Processing contour, value: 1217810.1021277495
Processing contour, value: 3653131.600634178
Processing contour, value: 6088453.099140607
Processing contour, value: 8523774.597647034
Processing contour, value: 10959096.096153464
Actor (0x7f8944f55f00)
Center: (0.20510876178741455, 0.0, 7.539987564086914e-06)
Pickable: True
Position: (0.0, 0.0, 0.0)
Scale: (1.0, 1.0, 1.0)
Visible: True
X Bounds -5.358E-01, 9.461E-01
Y Bounds -5.783E-01, 5.783E-01
Z Bounds -5.719E-01, 5.719E-01
User matrix: Identity
Has mapper: True
Property (0x7f890c6c4b20)
Ambient: 0.0
Ambient color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Anisotropy: 0.0
Color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Culling: "none"
Diffuse: 1.0
Diffuse color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Edge color: Color(name='black', hex='#000000ff', opacity=255)
Edge opacity: 1.0
Interpolation: InterpolationType.FLAT
Lighting: True
Line width: 1.0
Metallic: 0.0
Opacity: 1.0
Point size: 5.0
Render lines as tubes: False
Render points as spheres: False
Roughness: 0.5
Show edges: False
Specular: 0.0
Specular color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Specular power: 100.0
Style: "Surface"
DataSetMapper (0x7f890c6c4b20)
Scalar visibility: True
Scalar range: (0.40836381912231445, 0.41387873888015747)
Interpolate before mapping: True
Scalar map mode: point
Color mode: map
Attached dataset:
PolyData (0x7f890c5eebc0)
N Cells: 2400
N Points: 4960
N Strips: 0
X Bounds: -5.358e-01, 9.461e-01
Y Bounds: -5.783e-01, 5.783e-01
Z Bounds: -5.719e-01, 5.719e-01
N Arrays: 2
Lets also do the same coil optimization using regularized least-squares. Now we can’t specify inequality constraints (e.g. use error margins in the specification).
from bfieldtools.coil_optimize import optimize_lsq
coil.s2 = optimize_lsq(
coil, [target_spec, stray_spec], objective="minimum_ohmic_power", reg=1e6
)
Error tolerances in specification will be ignored when using lsq
Plot the optimized stream function, then discretize it and plot coil windings and the resultant magnetic field
plotter = coil.s2.plot()
loops2 = coil.s2.discretize(N_contours=10)
fig = loops2.plot_loops()
B_target = loops2.magnetic_field(target_points)
fig.add_arrows(target_points, B_target, mag=1e6)


Processing contour, value: -16796733.680609692
Processing contour, value: -13064302.081263892
Processing contour, value: -9331870.481918091
Processing contour, value: -5599438.88257229
Processing contour, value: -1867007.28322649
Processing contour, value: 1865424.3161193132
Processing contour, value: 5597855.915465113
Processing contour, value: 9330287.514810912
Processing contour, value: 13062719.114156716
Processing contour, value: 16795150.713502515
Actor (0x7f892cb96320)
Center: (0.13489896059036255, 0.0, 3.489851951599121e-05)
Pickable: True
Position: (0.0, 0.0, 0.0)
Scale: (1.0, 1.0, 1.0)
Visible: True
X Bounds -5.358E-01, 8.055E-01
Y Bounds -5.634E-01, 5.634E-01
Z Bounds -5.592E-01, 5.592E-01
User matrix: Identity
Has mapper: True
Property (0x7f890c5ed3c0)
Ambient: 0.0
Ambient color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Anisotropy: 0.0
Color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Culling: "none"
Diffuse: 1.0
Diffuse color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Edge color: Color(name='black', hex='#000000ff', opacity=255)
Edge opacity: 1.0
Interpolation: InterpolationType.FLAT
Lighting: True
Line width: 1.0
Metallic: 0.0
Opacity: 1.0
Point size: 5.0
Render lines as tubes: False
Render points as spheres: False
Roughness: 0.5
Show edges: False
Specular: 0.0
Specular color: Color(name='light_blue', hex='#add8e6ff', opacity=255)
Specular power: 100.0
Style: "Surface"
DataSetMapper (0x7f890c5ed3c0)
Scalar visibility: True
Scalar range: (0.2686965763568878, 0.2699730694293976)
Interpolate before mapping: True
Scalar map mode: point
Color mode: map
Attached dataset:
PolyData (0x7f890c96bf40)
N Cells: 2400
N Points: 4960
N Strips: 0
X Bounds: -5.358e-01, 8.055e-01
Y Bounds: -5.634e-01, 5.634e-01
Z Bounds: -5.592e-01, 5.592e-01
N Arrays: 2
Plot cross-section of magnetic field and magnetic potential of the discretized loops
x = y = np.linspace(-12, 12, 250)
X, Y = np.meshgrid(x, y, indexing="ij")
points = np.zeros((X.flatten().shape[0], 3))
points[:, 0] = X.flatten()
points[:, 1] = Y.flatten()
B = loops2.magnetic_field(points)
U = loops2.scalar_potential(points)
U = U.reshape(x.shape[0], y.shape[0])
B = B.T[:2].reshape(2, x.shape[0], y.shape[0])
lw = np.sqrt(B[0] ** 2 + B[1] ** 2)
lw = 2 * lw / np.max(lw)
plot_cross_section(X, Y, U, log=False, contours=False)
seed_points = points[:, :2] * 0.3
plt.streamplot(
x,
y,
B[0],
B[1],
density=2,
linewidth=lw,
color="k",
integration_direction="both",
start_points=seed_points,
)
plt.axis("equal")
plt.axis("off")
plt.plot([-5, 5], [-3, -3], "k", linewidth=3, alpha=1)
plt.plot([-5, 5], [3, 3], "k", linewidth=3, alpha=1)
plt.tight_layout()
# Display the assembled scene (Sphinx-Gallery captures it during docs builds).
if "plotter" in globals() and not plotter._closed:
plotter.show()

Total running time of the script: (1 minutes 15.357 seconds)