Skip to content

Plots module

pymagnets.plots

This module imports the classes and functions in the private modules to create a public API.

  • Lines and contour plots are drawn using matplotlib
  • 3D surface and volume plots are rendered using plotly.

plot_1D_field(magnet, unit='mm', **kwargs)

Calculates and plots the magnetic field along the central symmetry axis of a cylinder or cuboid magnet, assuming the magnetic field is collinear

Parameters:

Name Type Description Default
magnet Magnet3D

Must be a Magnet3D type of magnet, either Prism, Cube, or Cylinder.

required
Kwargs

num_points (int): Number of points to calculate. Defaults to 101.

Returns:

Type Description
tuple

Point_Array1, Field1: point array struct containing z and the

tuple[Point_Array1, Field1] | None

unit (e/g. 'mm'), vector array containing Bz and the field unit (e.g. 'T').

Source code in src/pymagnet/plots/_plot1D.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def plot_1D_field(
    magnet: Cylinder | Prism, unit: str = "mm", **kwargs: Any
) -> tuple[Point_Array1, Field1] | None:
    """Calculates and plots the magnetic field along the central symmetry axis
    of a cylinder or cuboid magnet, assuming the magnetic field is collinear

    Args:
        magnet (Magnet3D): Must be a Magnet3D type of magnet, either Prism,
            Cube, or Cylinder.

    Kwargs:
        num_points (int): Number of points to calculate. Defaults to 101.

    Returns:
        tuple: Point_Array1, Field1: point array struct containing z and the
        unit (e/g. 'mm'), vector array containing Bz and the field unit (e.g. 'T').
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    num_points = kwargs.pop("num_points", 101)
    return_data = kwargs.pop("return_data", False)
    points = Point_Array1(_np.zeros(num_points), unit=unit)

    if isinstance(magnet, Cylinder):
        mag_boundary = magnet.length / 2
        points.z = _np.linspace(
            -2 * magnet.length + magnet.center[2],
            2 * magnet.length + magnet.center[2],
            num_points,
        )
        field = magnetic_field_cylinder_1D(magnet, points.z)
        if field is None:
            raise ValueError("Failed to compute magnetic field for Cylinder magnet.")
        # if true, apply NaNs to inside the magnet
        if magnet._mask_magnet:
            mask = _generate_mask_1D(mag_boundary, magnet.center[2], points.z)
            field.z[mask] = _np.nan

    elif isinstance(magnet, Prism):
        mag_boundary = magnet.height / 2
        points.z = _np.linspace(
            -2 * magnet.height + magnet.center[2],
            2 * magnet.height + magnet.center[2],
            num_points,
        )
        field = magnetic_field_prism_1D(magnet, points.z)
        if field is None:
            raise ValueError("Failed to compute magnetic field for Prism magnet.")
        # if true, apply NaNs to inside the magnet
        if magnet._mask_magnet:
            mask = _generate_mask_1D(mag_boundary, magnet.center[2], points.z)
            field.z[mask] = _np.nan

    else:
        raise TypeError(
            f"Unsupported magnet type: {type(magnet).__name__}. "
            "Expected Cylinder or Prism."
        )

    _fig, _ax = _plt.subplots(figsize=(8, 8))
    unit_length = "(" + points.unit + ")"
    field_unit = "(" + field.unit + ")"
    _plt.xlabel(r"$z$ " + unit_length)
    _plt.ylabel(r"$B_z$ " + field_unit)
    _plt.plot(points.z, field.z)
    _plt.axvline(x=-mag_boundary + magnet.center[2], c="blue", ls="--")
    _plt.axvline(x=mag_boundary + magnet.center[2], c="red", ls="--")
    _plt.axvline(x=0.0, c="k", ls="-")
    _plt.show()

    if return_data:
        return points, field

plot_2D_contour(point_array, field, **kwargs)

Contour plot of field

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic Field

required
Kwargs

save_fig (bool): Save to png file. Defaults to False xlab (str): x axis label ylab (str): y axis label clab (str): label for colorbar axis_scale (str): axis aspect ratio Defaults to 'equal'. show_magnets (bool): Draw magnets. Defaults to True field_component (str): Defaults to 'n'. plot_type (str): Draw contour or streamplot. Defaults to 'contour' cmap (str): Colormap. Defaults to viridis num_arrows (int or None): Number of arrows per axis. Defaults to None. vector_color (str): Arrow color. Defaults to 'w' cmin (float): Color scale minimum. Defaults to 0.0 cmax (float): Color scale minimum. Defaults to twice the mean field num_levels (int): Number of contour levels. Defaults to 11.

Raises:

Type Description
Exception

plot_type must be 'contour' or 'streamplot'

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def plot_2D_contour(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of field

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic Field

    Kwargs:
        save_fig (bool): Save to png file. Defaults to False
        xlab (str): x axis label
        ylab (str): y axis label
        clab (str): label for colorbar
        axis_scale (str): axis aspect ratio Defaults to 'equal'.
        show_magnets (bool): Draw magnets. Defaults to True
        field_component (str): Defaults to 'n'.
        plot_type (str): Draw `contour` or `streamplot`. Defaults to 'contour'
        cmap (str): Colormap. Defaults to `viridis`
        num_arrows (int or None): Number of arrows per axis. Defaults to None.
        vector_color (str): Arrow color. Defaults to 'w'
        cmin (float): Color scale minimum. Defaults to 0.0
        cmax (float): Color scale minimum. Defaults to twice the mean field
        num_levels (int): Number of contour levels. Defaults to 11.

    Raises:
        Exception: plot_type must be 'contour' or 'streamplot'

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    from ..magnets._polygon2D import PolyMagnet

    show_magnets = kwargs.pop("show_magnets", True)

    xlab = kwargs.pop("xlab", f"x ({point_array.unit})")
    ylab = kwargs.pop("ylab", f"y ({point_array.unit})")
    clab = kwargs.pop("clab", f"B ({field.unit})")
    axis_scale = kwargs.pop("axis_scale", "equal")

    SAVE = kwargs.pop("save_fig", False)

    field_component = kwargs.pop("field_component", "n")

    plot_type = kwargs.pop("plot_type", "contour")
    fig, ax = _plt.subplots(figsize=(8, 8))

    if plot_type.lower() == "contour":
        cmap = kwargs.pop("cmap", "viridis")
        vector_color = kwargs.pop("vector_color", "w")
        NQ = kwargs.pop("num_arrows", None)

        if field_component == "x":
            field_chosen = field.x
        elif field_component == "y":
            field_chosen = field.y
        else:
            field_chosen = field.n

        finite_field = field_chosen[_np.isfinite(field_chosen)]
        cmin = kwargs.pop("cmin", 0)
        cmax = kwargs.pop("cmax", round(finite_field.mean() * 2, 1))
        num_levels = kwargs.pop("num_levels", 11)

        lev2 = _np.linspace(cmin, cmax, 256, endpoint=True)

        CS = _plt.contourf(
            point_array.x,
            point_array.y,
            field_chosen,
            levels=lev2,
            cmap=_plt.get_cmap(cmap),
            extend="max",
        )
        CS.set_edgecolor("face")

        # Draw contour lines
        if num_levels > 1:
            lev1 = _np.linspace(cmin, cmax, num_levels, endpoint=True)
            _ = _plt.contour(
                point_array.x,
                point_array.y,
                field_chosen,
                vmin=cmin,
                vmax=cmax,
                levels=lev1,
                linewidths=1.0,
                colors="k",
            )
            CB = _plt.colorbar(CS, ticks=lev1)
        else:
            CB = _plt.colorbar(CS)

        # Draw field vectors
        if NQ is not None:
            _vector_plot2(point_array, field, NQ, vector_color)

    elif plot_type.lower() == "streamplot":
        xpl = point_array.x[:, 0]
        ypl = point_array.y[0, :]
        cmap = kwargs.pop("cmap", None)

        if cmap is not None:
            cmin = kwargs.pop("cmin", -round(_np.nanmean(field.n), 1))
            cmax = kwargs.pop("cmax", round(_np.nanmean(field.n), 1))
            stream_shading = kwargs.pop("stream_color", "vertical")
            norm = _mcolors.Normalize(vmin=cmin, vmax=cmax)

            stream_dict = {
                "normal": field.n.T,
                "horizontal": field.x.T,
                "vertical": field.y.T,
            }

            CS = _plt.streamplot(
                xpl,
                ypl,
                field.x.T / field.n.T,
                field.y.T / field.n.T,
                color=stream_dict.get(stream_shading, "normal"),
                density=1.2,
                norm=norm,
                cmap=cmap,
                linewidth=0.5,
            )
            CB = _plt.colorbar(CS.lines)

        else:
            color = kwargs.pop("color", "k")
            CS = _plt.streamplot(
                xpl,
                ypl,
                field.x.T / field.n.T,
                field.y.T / field.n.T,
                density=1.2,
                linewidth=0.5,
                color=color,
            )
            CB = None

    else:
        raise ValueError("plot_type must be 'contour' or 'streamplot'")

    # Draw magnets and magnetisation arrows
    if show_magnets:
        _draw_magnets2(ax)
        if len(PolyMagnet.instances) > 0:
            for magnet in PolyMagnet.instances:
                poly = _plt.Polygon(
                    _np.array(magnet.polygon.vertices),
                    ec="k",
                    fc="w",
                    zorder=5,
                )
                ax.add_patch(poly)

    if CB is not None:
        CB.ax.get_yaxis().labelpad = 15
        CB.ax.set_ylabel(clab, rotation=270)
    _plt.axis(axis_scale)
    _plt.xlabel(xlab)
    _plt.ylabel(ylab)
    _plt.show()
    fig.tight_layout()
    ax.axis("scaled")
    if SAVE:
        _plt.savefig("contour_plot.png", dpi=300)

    return fig, ax

plot_2D_contour_BdotgradB(point_array, field, **kwargs)

Contour plot of B . grad(B) tensor force.

Computes the exact tensor product F_i = sum_j B_j * dB_j/dx_i and plots as a filled contour. Delegates to plot_2D_contour.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "B·∇B (T²/{unit})"

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def plot_2D_contour_BdotgradB(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of B . grad(B) tensor force.

    Computes the exact tensor product F_i = sum_j B_j * dB_j/dx_i
    and plots as a filled contour. Delegates to plot_2D_contour.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "B·∇B (T²/{unit})"

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import BdotgradB_2D

    bdg = BdotgradB_2D(field, point_array.x, point_array.y)
    kwargs.setdefault("clab", f"B\u00b7\u2207B (T\u00b2/{point_array.unit})")
    if "cmax" not in kwargs:
        finite = bdg.n[_np.isfinite(bdg.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, bdg, **kwargs)

plot_2D_contour_force(point_array, field, chi_m, c, **kwargs)

Contour plot of the scalar magnetic gradient force.

Computes F = (chi_m / mu_0) * c * |B| * grad(|B|) and plots as a filled contour. Delegates to plot_2D_contour with appropriate labels.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
chi_m float

Magnetic susceptibility

required
c float

Material constant

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "F∇B (T²/{unit})"

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def plot_2D_contour_force(
    point_array: Point_Array2,
    field: Field2,
    chi_m: float,
    c: float,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Contour plot of the scalar magnetic gradient force.

    Computes F = (chi_m / mu_0) * c * |B| * grad(|B|) and plots as a
    filled contour. Delegates to plot_2D_contour with appropriate labels.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field
        chi_m (float): Magnetic susceptibility
        c (float): Material constant

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "F∇B (T²/{unit})"

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import FgradB_2D

    force_field = FgradB_2D(field, point_array.x, point_array.y, chi_m, c)
    kwargs.setdefault("clab", f"F\u2207B (T\u00b2/{point_array.unit})")
    if "cmax" not in kwargs:
        finite = force_field.n[_np.isfinite(force_field.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, force_field, **kwargs)

plot_2D_contour_gradB(point_array, field, **kwargs)

Contour plot of the Jacobian Frobenius norm with grad(|B|) vector overlay.

Computes the full Jacobian J_ij = dB_i/dx_j via jacobian_B_2D, then plots ||J||_F = sqrt(sum of J_ij^2) as a filled contour with quiver arrows showing the direction of grad(|B|) overlaid.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "||∇B|| (T/{unit})" num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def plot_2D_contour_gradB(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of the Jacobian Frobenius norm with grad(|B|) vector overlay.

    Computes the full Jacobian J_ij = dB_i/dx_j via jacobian_B_2D, then plots
    ||J||_F = sqrt(sum of J_ij^2) as a filled contour with quiver arrows
    showing the direction of grad(|B|) overlaid.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "||∇B|| (T/{unit})"
        num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import gradB_2D, jacobian_B_2D

    J = jacobian_B_2D(field, point_array.x, point_array.y)

    # Frobenius norm of the Jacobian: total rate of field variation
    frob = _np.sqrt(J.dBx_dx**2 + J.dBx_dy**2 + J.dBy_dx**2 + J.dBy_dy**2)

    # Build a Field2 with grad(|B|) as the vector components and ||J||_F as norm
    grad_field = gradB_2D(field.n, point_array.x, point_array.y)
    grad_field.n = frob

    kwargs.setdefault("clab", f"||\u2207B|| (T/{point_array.unit})")
    kwargs.setdefault("num_arrows", 10)
    if "cmax" not in kwargs:
        finite = frob[_np.isfinite(frob)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, grad_field, **kwargs)

plot_2D_contour_gradB2(point_array, field, **kwargs)

Contour plot of |∇(B²)| with ∇(B²) vector overlay.

Computes ∇(|B|²) directly by taking the gradient of field.n². The contour shows |∇(B²)| and quiver arrows show the ∇(B²) direction.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "|∇(B²)| (T²/{unit})" num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def plot_2D_contour_gradB2(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of |∇(B²)| with ∇(B²) vector overlay.

    Computes ∇(|B|²) directly by taking the gradient of field.n².
    The contour shows |∇(B²)| and quiver arrows show the ∇(B²) direction.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "|∇(B²)| (T²/{unit})"
        num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import gradB_2D

    # Compute ∇(|B|²) directly from the gradient of the squared magnitude
    grad_B2 = gradB_2D(field.n**2, point_array.x, point_array.y)

    kwargs.setdefault("clab", f"|\u2207(B\u00b2)| (T\u00b2/{point_array.unit})")
    kwargs.setdefault("num_arrows", 10)
    if "cmax" not in kwargs:
        finite = grad_B2.n[_np.isfinite(grad_B2.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, grad_B2, **kwargs)

plot_2D_contour_gradient(point_array, field, **kwargs)

Contour plot of the magnetic field gradient magnitude.

Computes grad(|B|) and plots as a filled contour. Delegates to plot_2D_contour with appropriate default labels.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field (must have .n populated via calc_norm)

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "∇|B| (T/{unit})"

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def plot_2D_contour_gradient(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of the magnetic field gradient magnitude.

    Computes grad(|B|) and plots as a filled contour. Delegates to
    plot_2D_contour with appropriate default labels.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field (must have .n populated via calc_norm)

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "∇|B| (T/{unit})"

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import gradB_2D

    grad_field = gradB_2D(field.n, point_array.x, point_array.y)
    kwargs.setdefault("clab", f"\u2207|B| (T/{point_array.unit})")
    if "cmax" not in kwargs:
        finite = grad_field.n[_np.isfinite(grad_field.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, grad_field, **kwargs)

plot_2D_contour_jacobian(point_array, field, **kwargs)

2x2 contour plot of all Jacobian tensor components.

Computes the full 2D Jacobian J_ij = dB_i/dx_j and plots each of the 4 components (dBx/dx, dBx/dy, dBy/dx, dBy/dy) as a subplot panel.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

cmap (str): Colormap. Defaults to 'RdBu_r' (diverging). cmin (float): Color scale minimum. Defaults to -cmax (symmetric). cmax (float): Color scale maximum. Defaults to max(|data|). num_levels (int): Number of contour levels. Defaults to 11. show_magnets (bool): Draw magnets. Defaults to True. save_fig (bool): Save to png file. Defaults to False.

Returns:

Type Description
tuple

fig, axes (2x2 array of matplotlib axes)

Source code in src/pymagnet/plots/_plot2D.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
def plot_2D_contour_jacobian(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, NDArray]:
    """2x2 contour plot of all Jacobian tensor components.

    Computes the full 2D Jacobian J_ij = dB_i/dx_j and plots each of the
    4 components (dBx/dx, dBx/dy, dBy/dx, dBy/dy) as a subplot panel.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        cmap (str): Colormap. Defaults to 'RdBu_r' (diverging).
        cmin (float): Color scale minimum. Defaults to -cmax (symmetric).
        cmax (float): Color scale maximum. Defaults to max(|data|).
        num_levels (int): Number of contour levels. Defaults to 11.
        show_magnets (bool): Draw magnets. Defaults to True.
        save_fig (bool): Save to png file. Defaults to False.

    Returns:
        tuple: fig, axes (2x2 array of matplotlib axes)
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    from ..magnets._polygon2D import PolyMagnet
    from ..utils._routines2D import jacobian_B_2D

    J = jacobian_B_2D(field, point_array.x, point_array.y)

    cmap = kwargs.pop("cmap", "RdBu_r")
    num_levels = kwargs.pop("num_levels", 11)
    show_magnets = kwargs.pop("show_magnets", True)
    SAVE = kwargs.pop("save_fig", False)
    unit = point_array.unit

    components = [
        (J.dBx_dx, f"\u2202Bx/\u2202x (T/{unit})"),
        (J.dBx_dy, f"\u2202Bx/\u2202y (T/{unit})"),
        (J.dBy_dx, f"\u2202By/\u2202x (T/{unit})"),
        (J.dBy_dy, f"\u2202By/\u2202y (T/{unit})"),
    ]

    # Determine symmetric color limits from all components
    all_finite = _np.concatenate(
        [comp[_np.isfinite(comp)].ravel() for comp, _ in components]
    )
    default_cmax = float(_np.max(_np.abs(all_finite))) if all_finite.size > 0 else 1.0
    cmax = kwargs.pop("cmax", round(default_cmax, 2))
    cmin = kwargs.pop("cmin", -cmax)

    fig, axes = _plt.subplots(2, 2, figsize=(14, 12))
    lev_fill = _np.linspace(cmin, cmax, 256, endpoint=True)
    lev_lines = _np.linspace(cmin, cmax, num_levels, endpoint=True)

    for ax, (data, label) in zip(axes.ravel(), components, strict=False):
        CS = ax.contourf(
            point_array.x,
            point_array.y,
            data,
            levels=lev_fill,
            cmap=_plt.get_cmap(cmap),
            extend="both",
        )
        CS.set_edgecolor("face")

        if num_levels > 1:
            ax.contour(
                point_array.x,
                point_array.y,
                data,
                levels=lev_lines,
                linewidths=0.5,
                colors="k",
            )
            CB = fig.colorbar(CS, ax=ax, ticks=lev_lines)
        else:
            CB = fig.colorbar(CS, ax=ax)

        CB.ax.get_yaxis().labelpad = 15
        CB.ax.set_ylabel(label, rotation=270)
        ax.set_xlabel(f"x ({unit})")
        ax.set_ylabel(f"y ({unit})")
        ax.set_aspect("equal")

        if show_magnets:
            _draw_magnets2(ax)
            if len(PolyMagnet.instances) > 0:
                for magnet in PolyMagnet.instances:
                    poly = _plt.Polygon(
                        _np.array(magnet.polygon.vertices),
                        ec="k",
                        fc="w",
                        zorder=5,
                    )
                    ax.add_patch(poly)

    fig.tight_layout()
    if SAVE:
        _plt.savefig("jacobian_plot.png", dpi=300)

    return fig, axes

plot_2D_line(point_array, field, **kwargs)

Line Plot of field from 2D magnet

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic Field

required
Kwargs

xlab (str): xlabel ylab (str): ylabel axis_scale (str): unused save_fig (bool): Save to png file. Defaults to False

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def plot_2D_line(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Line Plot of field from 2D magnet

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic Field

    Kwargs:
        xlab (str): xlabel
        ylab (str): ylabel
        axis_scale (str): unused
        save_fig (bool): Save to png file. Defaults to False

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    xlab = kwargs.pop("xlab", f"x ({point_array.unit})")
    ylab = kwargs.pop("ylab", f"B ({field.unit})")
    # axis_scale = kwargs.pop("axis_scale", "equal")

    SAVE = kwargs.pop("save_fig", False)

    fig, ax = _plt.subplots(figsize=(8, 8))
    _plt.plot(point_array.x, field.n, label=r"$|\mathbf{B}|$")
    _plt.plot(point_array.x, field.x, label=r"$B_x$")
    _plt.plot(point_array.x, field.y, label=r"$B_y$")
    _plt.legend(loc="best")
    _plt.xlabel(xlab)
    _plt.ylabel(ylab)

    _plt.show()

    if SAVE:
        _plt.savefig("line_plot.png", dpi=300)
        # _plt.savefig('contour_plot.pdf', dpi=300)
    return fig, ax

plot_3D_contour(points, field, plane, **kwargs)

Contour plot of field

Parameters:

Name Type Description Default
points Point_Array2

coordinates

required
field Field2

Magnetic field

required
plane str

Plane to draw contour on. Can be 'xy', 'xz', or 'yz'

required

Raises:

Type Description
Exception

plot_type must be 'contour' or 'streamplot

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
def plot_3D_contour(
    points: Point_Array3,
    field: Field3,
    plane: str,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Contour plot of field

    Args:
        points (Point_Array2): coordinates
        field (Field2): Magnetic field
        plane (str): Plane to draw contour on. Can be 'xy', 'xz', or 'yz'

    Raises:
        Exception: plot_type must be 'contour' or 'streamplot

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    axis_scale = kwargs.pop("axis_scale", "equal")

    plot_type = kwargs.pop("plot_type", "contour")

    xlab = kwargs.pop("xlab", "x (" + points.unit + ")")
    ylab = kwargs.pop("ylab", "y (" + points.unit + ")")
    zlab = kwargs.pop("zlab", "z (" + points.unit + ")")
    clab = kwargs.pop("clab", "B (" + field.unit + ")")

    SAVE = kwargs.pop("save_fig", False)

    finite_field = field.n[_np.isfinite(field.n)]

    cmax = kwargs.pop("cmax", round(finite_field.mean() * 2, 1))
    num_levels = kwargs.pop("num_levels", 11)

    if plane.lower() == "xy":
        plot_x = points.x
        plot_y = points.y
        plot_xlab = xlab
        plot_ylab = ylab
        stream_x = field.x
        stream_y = field.y

    elif plane.lower() == "xz":
        stream_x = field.x
        stream_y = field.z
        plot_x = points.x
        plot_y = points.z
        plot_xlab = xlab
        plot_ylab = zlab

    else:
        stream_x = field.y
        stream_y = field.z
        plot_x = points.y
        plot_y = points.z
        plot_xlab = ylab
        plot_ylab = zlab

    fig, ax = _plt.subplots(figsize=(8, 8))

    # Generate Contour Plot
    if plot_type.lower() == "contour":
        vector_color = kwargs.pop("vector_color", "w")
        NQ = kwargs.pop("num_arrows", None)

        cmap = kwargs.pop("cmap", "viridis")
        cmin = kwargs.pop("cmin", 0)
        lev2 = _np.linspace(cmin, cmax, 256, endpoint=True)
        CS = _plt.contourf(
            plot_x,
            plot_y,
            field.n,
            levels=lev2,
            cmap=_plt.get_cmap(cmap),
            extend="max",
        )

        # Draw contour lines
        if num_levels > 1:
            lev1 = _np.linspace(cmin, cmax, num_levels, endpoint=True)
            _ = _plt.contour(
                plot_x,
                plot_y,
                field.n,
                vmin=cmin,
                vmax=cmax,
                levels=lev1,
                linewidths=1.0,
                colors="k",
            )
            CB = _plt.colorbar(CS, ticks=lev1)

        else:
            CB = _plt.colorbar(CS)

        if NQ is not None:
            B_2D = Field2(stream_x, stream_y, unit=field.unit)
            B_2D.n = field.n
            points_2D = Point_Array2(plot_x, plot_y, unit=points.unit)
            _vector_plot2(points_2D, B_2D, NQ, vector_color)

    # Generates streamplot
    elif plot_type.lower() == "streamplot":
        xpl = plot_x[:, 0]
        ypl = plot_y[0, :]
        cmap = kwargs.pop("cmap", None)
        if cmap is not None:
            cmin = kwargs.pop("cmin", -round(finite_field.mean() * 2, 1))
            cmax = kwargs.pop("cmax", round(finite_field.mean() * 2, 1))

            stream_shading = kwargs.pop("stream_shading", "vertical")
            norm = _mcolors.Normalize(vmin=cmin, vmax=cmax)

            stream_dict = {
                "normal": field.n.T,
                "horizontal": stream_x.T,
                "vertical": stream_y.T,
            }

            CS = _plt.streamplot(
                xpl,
                ypl,
                stream_x.T / field.n.T,
                stream_y.T / field.n.T,
                color=stream_dict.get(stream_shading, "normal"),
                density=1.2,
                norm=norm,
                cmap=cmap,
                linewidth=0.5,
            )
            CS.set_edgecolor("face")
            CB = _plt.colorbar(CS.lines)
        else:
            color = kwargs.pop("color", "k")
            CS = _plt.streamplot(
                xpl,
                ypl,
                stream_x.T / field.n.T,
                stream_y.T / field.n.T,
                density=1.2,
                linewidth=0.5,
                color=color,
            )
            CB = None

    else:
        raise ValueError("plot_type must be 'contour' or 'streamplot'")

    if CB is not None:
        CB.ax.get_yaxis().labelpad = 15
        CB.ax.set_ylabel(clab, rotation=270)
    _plt.xlabel(plot_xlab)
    _plt.ylabel(plot_ylab)
    _plt.axis(axis_scale)

    if SAVE:
        _plt.savefig("contour_plot.png", dpi=300)

    return fig, ax

plot_magnet(unit='mm', **kwargs)

Renders magnets

Parameters:

Name Type Description Default
unit str

unit scale. Defaults to 'mm'.

'mm'

Returns:

Type Description
fig

reference to figure

Source code in src/pymagnet/plots/_plotly3D.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def plot_magnet(unit: str = "mm", **kwargs: Any) -> Figure:
    """Renders magnets

    Args:
        unit (str, optional): unit scale. Defaults to 'mm'.

    Returns:
        fig: reference to figure
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    data_objects = []

    data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + unit + ")",
            yaxis_title="y (" + unit + ")",
            zaxis_title="z (" + unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()
    return fig

plot_sub_contour_3D(plot_x, plot_y, plot_B, **kwargs)

Contour plot of a single magnetic field component of a 3D simulation

Parameters:

Name Type Description Default
plot_x ndarray

coordinates for x-axis of plot

required
plot_y ndarray

coordinates for y-axis of plot

required
plot_B ndarray

Magnetic field component to plot

required

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def plot_sub_contour_3D(
    plot_x: NDArray[_np.floating],
    plot_y: NDArray[_np.floating],
    plot_B: NDArray[_np.floating],
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Contour plot of a single magnetic field component of a 3D simulation

    Args:
        plot_x (ndarray): coordinates for x-axis of plot
        plot_y (ndarray): coordinates for y-axis of plot
        plot_B (ndarray): Magnetic field component to plot

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    cmap = kwargs.pop("cmap", "seismic")
    xlab = kwargs.pop("xlab", "x (m)")
    ylab = kwargs.pop("ylab", "y (m)")
    clab = kwargs.pop("clab", "B (T)")

    # axis_scale = kwargs.pop("axis_scale", "equal")

    # SAVE = kwargs.pop("save_fig", False)

    cmin = kwargs.pop("cmin", -0.5)
    cmax = kwargs.pop("cmax", 0.5)
    num_levels = kwargs.pop("num_levels", 11)

    lev2 = _np.linspace(cmin, cmax, 256, endpoint=True)
    fig, ax = _plt.subplots(figsize=(8, 8))
    CS = _plt.contourf(
        plot_x, plot_y, plot_B, levels=lev2, cmap=_plt.get_cmap(cmap), extend="both"
    )

    if num_levels > 1:
        lev1 = _np.linspace(cmin, cmax, num_levels, endpoint=True)
        _ = _plt.contour(
            plot_x,
            plot_y,
            plot_B,
            vmin=cmin,
            vmax=cmax,
            levels=lev1,
            linewidths=1.0,
            colors="k",
        )
        CB = _plt.colorbar(CS, ticks=lev1)
    else:
        CB = _plt.colorbar(CS)

    CB.ax.get_yaxis().labelpad = 15
    CB.ax.set_ylabel(clab, rotation=270)
    _plt.xlabel(xlab)
    _plt.ylabel(ylab)
    _plt.axis("equal")
    _plt.show()

    return fig, ax

slice_plot(data_dict, **kwargs)

Plots magnetic field slices. A convenience function.

Returns:

Type Description
tuple

fig (reference to figure), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def slice_plot(
    data_dict: dict[str, dict[str, Any]], **kwargs: Any
) -> tuple[Figure, list[Any]]:
    """Plots magnetic field slices.
    A convenience function.

    Returns:
        tuple: fig (reference to figure), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    opacity = kwargs.pop("opacity", 0.8)
    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    cone_opacity = kwargs.pop("cone_opacity", 1.0)

    cmin = kwargs.pop("cmin", 0)
    cmax = kwargs.pop("cmax", 0.5)
    colorscale = kwargs.pop("colorscale", "viridis")
    num_arrows = kwargs.pop("num_arrows", None)

    data_objects = []

    show_magnets = kwargs.pop("show_magnets", True)

    if show_magnets:
        data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    for plane in data_dict:
        points = data_dict[plane]["points"]
        field = data_dict[plane]["field"]

        data_objects.append(
            _draw_surface_slice(
                points,
                field,
                colorscale,
                opacity=opacity,
                cmin=cmin,
                cmax=cmax,
                showscale=True,
            )
        )
        if num_arrows is not None:
            num_points = field.x.shape[0]

            NA = num_points // num_arrows

            if NA > 1:
                data_objects.append(
                    _draw_cones(points, field, NA=NA, cone_opacity=cone_opacity)
                )

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + points.unit + ")",
            yaxis_title="y (" + points.unit + ")",
            zaxis_title="z (" + points.unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()
    return fig, data_objects

slice_quickplot(**kwargs)

Calculates and plots magnetic field slices. A convenience function.

Returns:

Type Description
tuple

fig (reference to figure), cache (cached data for each plane with potential keys: 'xy', 'xz', 'yz'), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
def slice_quickplot(
    **kwargs: Any,
) -> tuple[Figure, dict[str, dict[str, Any]], list[Any]]:
    """Calculates and plots magnetic field slices.
    A convenience function.

    Returns:
        tuple: fig (reference to figure), cache (cached data for each plane with potential keys: 'xy', 'xz', 'yz'), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    max1 = kwargs.pop("max1", 30)
    max2 = kwargs.pop("max2", 30)
    min1 = kwargs.pop("min1", -1 * max1)
    min2 = kwargs.pop("min2", -1 * max2)

    slice_value = kwargs.pop("slice_value", 0.0)
    unit = kwargs.pop("unit", "mm")

    opacity = kwargs.pop("opacity", 0.8)
    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    cone_opacity = kwargs.pop("cone_opacity", 1.0)
    planes = kwargs.pop("planes", ["xy", "xz", "yz"])

    num_arrows = kwargs.pop("num_arrows", None)
    num_points = kwargs.pop("num_points", 100)

    if num_arrows is not None:
        NA = num_points // num_arrows
        if NA < 1:
            NA = 1

    cmin = kwargs.pop("cmin", 0)
    cmax = kwargs.pop("cmax", 0.5)
    colorscale = kwargs.pop("colorscale", "viridis")

    data_objects = []
    cache = {}

    show_magnets = kwargs.pop("show_magnets", True)

    if show_magnets:
        data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    for plane in planes:
        points = slice3D(
            plane=plane,
            max1=max1,
            min1=min1,
            max2=max2,
            min2=min2,
            slice_value=slice_value,
            unit=unit,
            num_points=num_points,
        )
        field = get_field_3D(points)

        cache[plane] = {"points": points, "field": field}

        data_objects.append(
            _draw_surface_slice(
                points,
                field,
                colorscale,
                opacity=opacity,
                cmin=cmin,
                cmax=cmax,
                showscale=True,
            )
        )
        if num_arrows is not None:
            data_objects.append(
                _draw_cones(points, field, NA=NA, cone_opacity=cone_opacity)
            )

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + points.unit + ")",
            yaxis_title="y (" + points.unit + ")",
            zaxis_title="z (" + points.unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()
    return fig, cache, data_objects

volume_plot(points, field, **kwargs)

Plots magnetic field volume.

Parameters:

Name Type Description Default
points Point_Array3

coordinates

required
field Field3

Magnetic field vector

required

Returns:

Type Description
tuple

fig (reference to figure), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def volume_plot(
    points: Point_Array3, field: Field3, **kwargs: Any
) -> tuple[Figure, list[Any]]:
    """Plots magnetic field volume.

    Args:
        points (Point_Array3): coordinates
        field (Field3): Magnetic field vector

    Returns:
        tuple: fig (reference to figure), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    opacity = kwargs.pop("opacity", 0.3)
    opacityscale = kwargs.pop("opacityscale", None)
    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    cone_opacity = kwargs.pop("cone_opacity", 1.0)

    num_arrows = kwargs.pop("num_arrows", None)

    cmin = kwargs.pop("cmin", 0)
    cmax = kwargs.pop("cmax", 0.5)
    num_levels = kwargs.pop("num_levels", 5)

    show_magnets = kwargs.pop("show_magnets", True)

    num_points = len(points.x)

    data_objects = []

    if show_magnets:
        data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    colorscale = kwargs.pop("colorscale", "viridis")

    #     kernel_size = 1
    #     kernel = np.ones([kernel_size, kernel_size, kernel_size]) / kernel_size
    #     B.n = ndimage.convolve(B.n, kernel)

    data_objects.append(
        _generate_volume_data(
            points,
            field,
            cmin=cmin,
            cmax=cmax,
            opacity=opacity,
            colorscale=colorscale,
            num_levels=num_levels,
            opacityscale=opacityscale,
        )
    )

    if num_arrows is not None:
        NA = num_points // num_arrows
        if NA < 1:
            NA = 1
        data_objects.append(
            _draw_cones(points, field, NA=NA, cone_opacity=cone_opacity)
        )

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + points.unit + ")",
            yaxis_title="y (" + points.unit + ")",
            zaxis_title="z (" + points.unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()

    return fig, data_objects

volume_quickplot(**kwargs)

Calculates and plots magnetic field slices. A convenience function.

Kwargs

num_points (int): = kwargs.pop("num_points", 30) unit (str): = kwargs.pop("unit", "mm") xmax (float): Maximum x value. Defaults to 30.0. ymax (float): Maximum y value. Defaults to 30.0. zmax (float): Maximum z value. Defaults to 30.0. xmin (float): Minimum x value. Defaults to -xmax ymin (float): Minimum y value. Defaults to -ymax zmin (float): Minimum z value. Defaults to -zmax

Returns:

Type Description
tuple

fig (reference to figure), cache (cached data dict), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
def volume_quickplot(
    **kwargs: Any,
) -> tuple[Figure, dict[str, Any], list[Any]]:
    """Calculates and plots magnetic field slices.
    A convenience function.

    Kwargs:
        num_points (int): = kwargs.pop("num_points", 30)
        unit (str): = kwargs.pop("unit", "mm")
        xmax (float): Maximum x value. Defaults to 30.0.
        ymax (float): Maximum y value. Defaults to 30.0.
        zmax (float): Maximum z value. Defaults to 30.0.
        xmin (float): Minimum x value. Defaults to -xmax
        ymin (float): Minimum y value. Defaults to -ymax
        zmin (float): Minimum z value. Defaults to -zmax

    Returns:
        tuple: fig (reference to figure), cache (cached data dict), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    num_points = kwargs.pop("num_points", 30)

    unit = kwargs.pop("unit", "mm")

    xmax = kwargs.pop("xmax", 30)
    ymax = kwargs.pop("ymax", 30)
    zmax = kwargs.pop("zmax", 30)

    xmin = kwargs.pop("xmin", -1 * xmax)
    ymin = kwargs.pop("ymin", -1 * ymax)
    zmin = kwargs.pop("zmin", -1 * zmax)

    points = grid3D(
        xmax,
        ymax,
        zmax,
        num_points=num_points,
        xmin=xmin,
        ymin=ymin,
        zmin=zmin,
        unit=unit,
    )
    field = get_field_3D(points)

    fig, data_objects = volume_plot(points, field, num_points=num_points, **kwargs)
    cache = {"points": points, "field": field}

    return fig, cache, data_objects

Plotting routines for calculating along symmetry lines of cubes, cuboids, and cylinders

plot_1D_field(magnet, unit='mm', **kwargs)

Calculates and plots the magnetic field along the central symmetry axis of a cylinder or cuboid magnet, assuming the magnetic field is collinear

Parameters:

Name Type Description Default
magnet Magnet3D

Must be a Magnet3D type of magnet, either Prism, Cube, or Cylinder.

required
Kwargs

num_points (int): Number of points to calculate. Defaults to 101.

Returns:

Type Description
tuple

Point_Array1, Field1: point array struct containing z and the

tuple[Point_Array1, Field1] | None

unit (e/g. 'mm'), vector array containing Bz and the field unit (e.g. 'T').

Source code in src/pymagnet/plots/_plot1D.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def plot_1D_field(
    magnet: Cylinder | Prism, unit: str = "mm", **kwargs: Any
) -> tuple[Point_Array1, Field1] | None:
    """Calculates and plots the magnetic field along the central symmetry axis
    of a cylinder or cuboid magnet, assuming the magnetic field is collinear

    Args:
        magnet (Magnet3D): Must be a Magnet3D type of magnet, either Prism,
            Cube, or Cylinder.

    Kwargs:
        num_points (int): Number of points to calculate. Defaults to 101.

    Returns:
        tuple: Point_Array1, Field1: point array struct containing z and the
        unit (e/g. 'mm'), vector array containing Bz and the field unit (e.g. 'T').
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    num_points = kwargs.pop("num_points", 101)
    return_data = kwargs.pop("return_data", False)
    points = Point_Array1(_np.zeros(num_points), unit=unit)

    if isinstance(magnet, Cylinder):
        mag_boundary = magnet.length / 2
        points.z = _np.linspace(
            -2 * magnet.length + magnet.center[2],
            2 * magnet.length + magnet.center[2],
            num_points,
        )
        field = magnetic_field_cylinder_1D(magnet, points.z)
        if field is None:
            raise ValueError("Failed to compute magnetic field for Cylinder magnet.")
        # if true, apply NaNs to inside the magnet
        if magnet._mask_magnet:
            mask = _generate_mask_1D(mag_boundary, magnet.center[2], points.z)
            field.z[mask] = _np.nan

    elif isinstance(magnet, Prism):
        mag_boundary = magnet.height / 2
        points.z = _np.linspace(
            -2 * magnet.height + magnet.center[2],
            2 * magnet.height + magnet.center[2],
            num_points,
        )
        field = magnetic_field_prism_1D(magnet, points.z)
        if field is None:
            raise ValueError("Failed to compute magnetic field for Prism magnet.")
        # if true, apply NaNs to inside the magnet
        if magnet._mask_magnet:
            mask = _generate_mask_1D(mag_boundary, magnet.center[2], points.z)
            field.z[mask] = _np.nan

    else:
        raise TypeError(
            f"Unsupported magnet type: {type(magnet).__name__}. "
            "Expected Cylinder or Prism."
        )

    _fig, _ax = _plt.subplots(figsize=(8, 8))
    unit_length = "(" + points.unit + ")"
    field_unit = "(" + field.unit + ")"
    _plt.xlabel(r"$z$ " + unit_length)
    _plt.ylabel(r"$B_z$ " + field_unit)
    _plt.plot(points.z, field.z)
    _plt.axvline(x=-mag_boundary + magnet.center[2], c="blue", ls="--")
    _plt.axvline(x=mag_boundary + magnet.center[2], c="red", ls="--")
    _plt.axvline(x=0.0, c="k", ls="-")
    _plt.show()

    if return_data:
        return points, field

Plotting routines

This module contains all functions needed to plot lines and contours for 2D magnetic sources, and

arrow

Encodes magnetisation vector for drawing on plots

Source code in src/pymagnet/plots/_plot2D.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class arrow:
    """Encodes magnetisation vector for drawing on plots"""

    def __init__(self, x, y, dx, dy, transform, width=3):
        """Init Arrow

        Args:
            x (float): arrow tail, x
            y (float): arrow tail, y
            dx (float): arrow head displacement, x
            dy (float): arrow head displacement, y
            transform (matplotlib Affine2D): transformation object, `translate`
            width (int, optional): Arrow width. Defaults to 3.
        """
        if not _has_matplotlib:
            raise ImportError("matplotlib is required to use this plot function.")

        super().__init__()
        self.x = x
        self.y = y
        self.dx = dx
        self.dy = dy
        self.transform = transform
        self.width = width

    def __repr__(self) -> str:
        return (
            f"(x: {self.x}, y: {self.y}, dx: {self.dx}, dy: {self.dy}, w:{self.width})"
        )

    def __str__(self) -> str:
        return (
            f"(x: {self.x}, y: {self.y}, dx: {self.dx}, dy: {self.dy}, w:{self.width})"
        )

__init__(x, y, dx, dy, transform, width=3)

Init Arrow

Parameters:

Name Type Description Default
x float

arrow tail, x

required
y float

arrow tail, y

required
dx float

arrow head displacement, x

required
dy float

arrow head displacement, y

required
transform matplotlib Affine2D

transformation object, translate

required
width int

Arrow width. Defaults to 3.

3
Source code in src/pymagnet/plots/_plot2D.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(self, x, y, dx, dy, transform, width=3):
    """Init Arrow

    Args:
        x (float): arrow tail, x
        y (float): arrow tail, y
        dx (float): arrow head displacement, x
        dy (float): arrow head displacement, y
        transform (matplotlib Affine2D): transformation object, `translate`
        width (int, optional): Arrow width. Defaults to 3.
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    super().__init__()
    self.x = x
    self.y = y
    self.dx = dx
    self.dy = dy
    self.transform = transform
    self.width = width

magnet_patch

Magnet drawing class

Source code in src/pymagnet/plots/_plot2D.py
109
110
111
112
113
114
115
116
117
118
class magnet_patch:
    """Magnet drawing class"""

    def __init__(self, patch, arrow) -> None:
        super().__init__()
        self.patch = patch
        self.arrow = arrow

    def __str__(self) -> str:
        return self.patch.__str__() + self.arrow.__str__()

patch

Encodes magnet dimensions for drawing on plots

Source code in src/pymagnet/plots/_plot2D.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class patch:
    """Encodes magnet dimensions for drawing on plots"""

    def __init__(self, x, y, width, height, transform, type):
        """Initialse a patch

        Args:
            x (float): centre, x
            y (float): center, y
            width (float): width
            height (float): width
            transform (matplotlib Affine2D): transform object, `rotate_deg_around`
        """
        super().__init__()
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.transform = transform
        self.type = type

    def __repr__(self) -> str:
        return f"(x: {self.x}, y: {self.y} w:{self.width}, h: {self.height})"

    def __str__(self) -> str:
        return f"(x: {self.x}, y: {self.y} w:{self.width}, h: {self.height})"

__init__(x, y, width, height, transform, type)

Initialse a patch

Parameters:

Name Type Description Default
x float

centre, x

required
y float

center, y

required
width float

width

required
height float

width

required
transform matplotlib Affine2D

transform object, rotate_deg_around

required
Source code in src/pymagnet/plots/_plot2D.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def __init__(self, x, y, width, height, transform, type):
    """Initialse a patch

    Args:
        x (float): centre, x
        y (float): center, y
        width (float): width
        height (float): width
        transform (matplotlib Affine2D): transform object, `rotate_deg_around`
    """
    super().__init__()
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.transform = transform
    self.type = type

contour_plot_cylinder(magnet, **kwargs)

Calculates and plots the magnetic field of a cylinder

This is an example helper function.

Parameters:

Name Type Description Default
magnet Cylinder

instance of magnetic cylinder

required

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def contour_plot_cylinder(magnet, **kwargs):
    """Calculates and plots the magnetic field
    of a cylinder

    This is an example helper function.


    Args:
        magnet (Cylinder): instance of magnetic cylinder

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    NP = 101
    NPJ = NP * 1j
    rho, z = _np.mgrid[
        -3 * magnet.radius : 3 * magnet.radius : NPJ,
        -magnet.length : magnet.length : NPJ,
    ]
    Br, Bz = magnet._calcB_cyl(rho, z)
    Bn = _np.sqrt(Bz**2 + Br**2)

    xlab = "r (m)"
    ylab = "z (m)"

    # plot_B = Bn
    clab = r"$|B|$ (T)"
    cmap = "viridis"
    fig, ax = plot_sub_contour_3D(
        rho * 1,
        z * 1,
        Bn,
        xlab=xlab,
        ylab=ylab,
        clab=clab,
        cmap=cmap,
        cmin=0,
        cmax=1.0,
    )
    return fig, ax

line_plot_cylinder(magnet, **kwargs)

Calculates and plots the magnetic field along the central axis of a cylinder

This is an example helper function.

Parameters:

Name Type Description Default
magnet Cylinder

instance of magnetic cylinder

required

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
def line_plot_cylinder(magnet, **kwargs):
    """Calculates and plots the magnetic field along the central axis
    of a cylinder

    This is an example helper function.

    Args:
        magnet (Cylinder): instance of magnetic cylinder

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    rho = _np.linspace(-2 * magnet.radius, 2 * magnet.radius, 51)
    z = _np.array([magnet.length * 1.1 / 2])

    Br, Bz = magnet._calcB_cyl(rho, z)
    fig, ax = _plt.subplots(figsize=(8, 8))
    _plt.plot(rho * 1, Bz, label=r"$B_z$")
    _plt.plot(rho * 1, Br, label=r"$B_r$")
    _plt.legend(loc="best")
    _plt.show()
    return fig, ax

plot_2D_contour(point_array, field, **kwargs)

Contour plot of field

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic Field

required
Kwargs

save_fig (bool): Save to png file. Defaults to False xlab (str): x axis label ylab (str): y axis label clab (str): label for colorbar axis_scale (str): axis aspect ratio Defaults to 'equal'. show_magnets (bool): Draw magnets. Defaults to True field_component (str): Defaults to 'n'. plot_type (str): Draw contour or streamplot. Defaults to 'contour' cmap (str): Colormap. Defaults to viridis num_arrows (int or None): Number of arrows per axis. Defaults to None. vector_color (str): Arrow color. Defaults to 'w' cmin (float): Color scale minimum. Defaults to 0.0 cmax (float): Color scale minimum. Defaults to twice the mean field num_levels (int): Number of contour levels. Defaults to 11.

Raises:

Type Description
Exception

plot_type must be 'contour' or 'streamplot'

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def plot_2D_contour(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of field

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic Field

    Kwargs:
        save_fig (bool): Save to png file. Defaults to False
        xlab (str): x axis label
        ylab (str): y axis label
        clab (str): label for colorbar
        axis_scale (str): axis aspect ratio Defaults to 'equal'.
        show_magnets (bool): Draw magnets. Defaults to True
        field_component (str): Defaults to 'n'.
        plot_type (str): Draw `contour` or `streamplot`. Defaults to 'contour'
        cmap (str): Colormap. Defaults to `viridis`
        num_arrows (int or None): Number of arrows per axis. Defaults to None.
        vector_color (str): Arrow color. Defaults to 'w'
        cmin (float): Color scale minimum. Defaults to 0.0
        cmax (float): Color scale minimum. Defaults to twice the mean field
        num_levels (int): Number of contour levels. Defaults to 11.

    Raises:
        Exception: plot_type must be 'contour' or 'streamplot'

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    from ..magnets._polygon2D import PolyMagnet

    show_magnets = kwargs.pop("show_magnets", True)

    xlab = kwargs.pop("xlab", f"x ({point_array.unit})")
    ylab = kwargs.pop("ylab", f"y ({point_array.unit})")
    clab = kwargs.pop("clab", f"B ({field.unit})")
    axis_scale = kwargs.pop("axis_scale", "equal")

    SAVE = kwargs.pop("save_fig", False)

    field_component = kwargs.pop("field_component", "n")

    plot_type = kwargs.pop("plot_type", "contour")
    fig, ax = _plt.subplots(figsize=(8, 8))

    if plot_type.lower() == "contour":
        cmap = kwargs.pop("cmap", "viridis")
        vector_color = kwargs.pop("vector_color", "w")
        NQ = kwargs.pop("num_arrows", None)

        if field_component == "x":
            field_chosen = field.x
        elif field_component == "y":
            field_chosen = field.y
        else:
            field_chosen = field.n

        finite_field = field_chosen[_np.isfinite(field_chosen)]
        cmin = kwargs.pop("cmin", 0)
        cmax = kwargs.pop("cmax", round(finite_field.mean() * 2, 1))
        num_levels = kwargs.pop("num_levels", 11)

        lev2 = _np.linspace(cmin, cmax, 256, endpoint=True)

        CS = _plt.contourf(
            point_array.x,
            point_array.y,
            field_chosen,
            levels=lev2,
            cmap=_plt.get_cmap(cmap),
            extend="max",
        )
        CS.set_edgecolor("face")

        # Draw contour lines
        if num_levels > 1:
            lev1 = _np.linspace(cmin, cmax, num_levels, endpoint=True)
            _ = _plt.contour(
                point_array.x,
                point_array.y,
                field_chosen,
                vmin=cmin,
                vmax=cmax,
                levels=lev1,
                linewidths=1.0,
                colors="k",
            )
            CB = _plt.colorbar(CS, ticks=lev1)
        else:
            CB = _plt.colorbar(CS)

        # Draw field vectors
        if NQ is not None:
            _vector_plot2(point_array, field, NQ, vector_color)

    elif plot_type.lower() == "streamplot":
        xpl = point_array.x[:, 0]
        ypl = point_array.y[0, :]
        cmap = kwargs.pop("cmap", None)

        if cmap is not None:
            cmin = kwargs.pop("cmin", -round(_np.nanmean(field.n), 1))
            cmax = kwargs.pop("cmax", round(_np.nanmean(field.n), 1))
            stream_shading = kwargs.pop("stream_color", "vertical")
            norm = _mcolors.Normalize(vmin=cmin, vmax=cmax)

            stream_dict = {
                "normal": field.n.T,
                "horizontal": field.x.T,
                "vertical": field.y.T,
            }

            CS = _plt.streamplot(
                xpl,
                ypl,
                field.x.T / field.n.T,
                field.y.T / field.n.T,
                color=stream_dict.get(stream_shading, "normal"),
                density=1.2,
                norm=norm,
                cmap=cmap,
                linewidth=0.5,
            )
            CB = _plt.colorbar(CS.lines)

        else:
            color = kwargs.pop("color", "k")
            CS = _plt.streamplot(
                xpl,
                ypl,
                field.x.T / field.n.T,
                field.y.T / field.n.T,
                density=1.2,
                linewidth=0.5,
                color=color,
            )
            CB = None

    else:
        raise ValueError("plot_type must be 'contour' or 'streamplot'")

    # Draw magnets and magnetisation arrows
    if show_magnets:
        _draw_magnets2(ax)
        if len(PolyMagnet.instances) > 0:
            for magnet in PolyMagnet.instances:
                poly = _plt.Polygon(
                    _np.array(magnet.polygon.vertices),
                    ec="k",
                    fc="w",
                    zorder=5,
                )
                ax.add_patch(poly)

    if CB is not None:
        CB.ax.get_yaxis().labelpad = 15
        CB.ax.set_ylabel(clab, rotation=270)
    _plt.axis(axis_scale)
    _plt.xlabel(xlab)
    _plt.ylabel(ylab)
    _plt.show()
    fig.tight_layout()
    ax.axis("scaled")
    if SAVE:
        _plt.savefig("contour_plot.png", dpi=300)

    return fig, ax

plot_2D_contour_BdotgradB(point_array, field, **kwargs)

Contour plot of B . grad(B) tensor force.

Computes the exact tensor product F_i = sum_j B_j * dB_j/dx_i and plots as a filled contour. Delegates to plot_2D_contour.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "B·∇B (T²/{unit})"

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def plot_2D_contour_BdotgradB(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of B . grad(B) tensor force.

    Computes the exact tensor product F_i = sum_j B_j * dB_j/dx_i
    and plots as a filled contour. Delegates to plot_2D_contour.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "B·∇B (T²/{unit})"

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import BdotgradB_2D

    bdg = BdotgradB_2D(field, point_array.x, point_array.y)
    kwargs.setdefault("clab", f"B\u00b7\u2207B (T\u00b2/{point_array.unit})")
    if "cmax" not in kwargs:
        finite = bdg.n[_np.isfinite(bdg.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, bdg, **kwargs)

plot_2D_contour_force(point_array, field, chi_m, c, **kwargs)

Contour plot of the scalar magnetic gradient force.

Computes F = (chi_m / mu_0) * c * |B| * grad(|B|) and plots as a filled contour. Delegates to plot_2D_contour with appropriate labels.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
chi_m float

Magnetic susceptibility

required
c float

Material constant

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "F∇B (T²/{unit})"

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def plot_2D_contour_force(
    point_array: Point_Array2,
    field: Field2,
    chi_m: float,
    c: float,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Contour plot of the scalar magnetic gradient force.

    Computes F = (chi_m / mu_0) * c * |B| * grad(|B|) and plots as a
    filled contour. Delegates to plot_2D_contour with appropriate labels.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field
        chi_m (float): Magnetic susceptibility
        c (float): Material constant

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "F∇B (T²/{unit})"

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import FgradB_2D

    force_field = FgradB_2D(field, point_array.x, point_array.y, chi_m, c)
    kwargs.setdefault("clab", f"F\u2207B (T\u00b2/{point_array.unit})")
    if "cmax" not in kwargs:
        finite = force_field.n[_np.isfinite(force_field.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, force_field, **kwargs)

plot_2D_contour_gradB(point_array, field, **kwargs)

Contour plot of the Jacobian Frobenius norm with grad(|B|) vector overlay.

Computes the full Jacobian J_ij = dB_i/dx_j via jacobian_B_2D, then plots ||J||_F = sqrt(sum of J_ij^2) as a filled contour with quiver arrows showing the direction of grad(|B|) overlaid.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "||∇B|| (T/{unit})" num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def plot_2D_contour_gradB(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of the Jacobian Frobenius norm with grad(|B|) vector overlay.

    Computes the full Jacobian J_ij = dB_i/dx_j via jacobian_B_2D, then plots
    ||J||_F = sqrt(sum of J_ij^2) as a filled contour with quiver arrows
    showing the direction of grad(|B|) overlaid.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "||∇B|| (T/{unit})"
        num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import gradB_2D, jacobian_B_2D

    J = jacobian_B_2D(field, point_array.x, point_array.y)

    # Frobenius norm of the Jacobian: total rate of field variation
    frob = _np.sqrt(J.dBx_dx**2 + J.dBx_dy**2 + J.dBy_dx**2 + J.dBy_dy**2)

    # Build a Field2 with grad(|B|) as the vector components and ||J||_F as norm
    grad_field = gradB_2D(field.n, point_array.x, point_array.y)
    grad_field.n = frob

    kwargs.setdefault("clab", f"||\u2207B|| (T/{point_array.unit})")
    kwargs.setdefault("num_arrows", 10)
    if "cmax" not in kwargs:
        finite = frob[_np.isfinite(frob)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, grad_field, **kwargs)

plot_2D_contour_gradB2(point_array, field, **kwargs)

Contour plot of |∇(B²)| with ∇(B²) vector overlay.

Computes ∇(|B|²) directly by taking the gradient of field.n². The contour shows |∇(B²)| and quiver arrows show the ∇(B²) direction.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "|∇(B²)| (T²/{unit})" num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def plot_2D_contour_gradB2(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of |∇(B²)| with ∇(B²) vector overlay.

    Computes ∇(|B|²) directly by taking the gradient of field.n².
    The contour shows |∇(B²)| and quiver arrows show the ∇(B²) direction.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "|∇(B²)| (T²/{unit})"
        num_arrows (int): Number of quiver arrows per axis side. Defaults to 10.

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import gradB_2D

    # Compute ∇(|B|²) directly from the gradient of the squared magnitude
    grad_B2 = gradB_2D(field.n**2, point_array.x, point_array.y)

    kwargs.setdefault("clab", f"|\u2207(B\u00b2)| (T\u00b2/{point_array.unit})")
    kwargs.setdefault("num_arrows", 10)
    if "cmax" not in kwargs:
        finite = grad_B2.n[_np.isfinite(grad_B2.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, grad_B2, **kwargs)

plot_2D_contour_gradient(point_array, field, **kwargs)

Contour plot of the magnetic field gradient magnitude.

Computes grad(|B|) and plots as a filled contour. Delegates to plot_2D_contour with appropriate default labels.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field (must have .n populated via calc_norm)

required
Kwargs

All kwargs from plot_2D_contour are supported. clab defaults to "∇|B| (T/{unit})"

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def plot_2D_contour_gradient(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Contour plot of the magnetic field gradient magnitude.

    Computes grad(|B|) and plots as a filled contour. Delegates to
    plot_2D_contour with appropriate default labels.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field (must have .n populated via calc_norm)

    Kwargs:
        All kwargs from plot_2D_contour are supported.
        clab defaults to "∇|B| (T/{unit})"

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    from ..utils._routines2D import gradB_2D

    grad_field = gradB_2D(field.n, point_array.x, point_array.y)
    kwargs.setdefault("clab", f"\u2207|B| (T/{point_array.unit})")
    if "cmax" not in kwargs:
        finite = grad_field.n[_np.isfinite(grad_field.n)]
        kwargs["cmax"] = float(_np.max(finite)) if finite.size > 0 else 1.0
    return plot_2D_contour(point_array, grad_field, **kwargs)

plot_2D_contour_jacobian(point_array, field, **kwargs)

2x2 contour plot of all Jacobian tensor components.

Computes the full 2D Jacobian J_ij = dB_i/dx_j and plots each of the 4 components (dBx/dx, dBx/dy, dBy/dx, dBy/dy) as a subplot panel.

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic field

required
Kwargs

cmap (str): Colormap. Defaults to 'RdBu_r' (diverging). cmin (float): Color scale minimum. Defaults to -cmax (symmetric). cmax (float): Color scale maximum. Defaults to max(|data|). num_levels (int): Number of contour levels. Defaults to 11. show_magnets (bool): Draw magnets. Defaults to True. save_fig (bool): Save to png file. Defaults to False.

Returns:

Type Description
tuple

fig, axes (2x2 array of matplotlib axes)

Source code in src/pymagnet/plots/_plot2D.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
def plot_2D_contour_jacobian(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, NDArray]:
    """2x2 contour plot of all Jacobian tensor components.

    Computes the full 2D Jacobian J_ij = dB_i/dx_j and plots each of the
    4 components (dBx/dx, dBx/dy, dBy/dx, dBy/dy) as a subplot panel.

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic field

    Kwargs:
        cmap (str): Colormap. Defaults to 'RdBu_r' (diverging).
        cmin (float): Color scale minimum. Defaults to -cmax (symmetric).
        cmax (float): Color scale maximum. Defaults to max(|data|).
        num_levels (int): Number of contour levels. Defaults to 11.
        show_magnets (bool): Draw magnets. Defaults to True.
        save_fig (bool): Save to png file. Defaults to False.

    Returns:
        tuple: fig, axes (2x2 array of matplotlib axes)
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    from ..magnets._polygon2D import PolyMagnet
    from ..utils._routines2D import jacobian_B_2D

    J = jacobian_B_2D(field, point_array.x, point_array.y)

    cmap = kwargs.pop("cmap", "RdBu_r")
    num_levels = kwargs.pop("num_levels", 11)
    show_magnets = kwargs.pop("show_magnets", True)
    SAVE = kwargs.pop("save_fig", False)
    unit = point_array.unit

    components = [
        (J.dBx_dx, f"\u2202Bx/\u2202x (T/{unit})"),
        (J.dBx_dy, f"\u2202Bx/\u2202y (T/{unit})"),
        (J.dBy_dx, f"\u2202By/\u2202x (T/{unit})"),
        (J.dBy_dy, f"\u2202By/\u2202y (T/{unit})"),
    ]

    # Determine symmetric color limits from all components
    all_finite = _np.concatenate(
        [comp[_np.isfinite(comp)].ravel() for comp, _ in components]
    )
    default_cmax = float(_np.max(_np.abs(all_finite))) if all_finite.size > 0 else 1.0
    cmax = kwargs.pop("cmax", round(default_cmax, 2))
    cmin = kwargs.pop("cmin", -cmax)

    fig, axes = _plt.subplots(2, 2, figsize=(14, 12))
    lev_fill = _np.linspace(cmin, cmax, 256, endpoint=True)
    lev_lines = _np.linspace(cmin, cmax, num_levels, endpoint=True)

    for ax, (data, label) in zip(axes.ravel(), components, strict=False):
        CS = ax.contourf(
            point_array.x,
            point_array.y,
            data,
            levels=lev_fill,
            cmap=_plt.get_cmap(cmap),
            extend="both",
        )
        CS.set_edgecolor("face")

        if num_levels > 1:
            ax.contour(
                point_array.x,
                point_array.y,
                data,
                levels=lev_lines,
                linewidths=0.5,
                colors="k",
            )
            CB = fig.colorbar(CS, ax=ax, ticks=lev_lines)
        else:
            CB = fig.colorbar(CS, ax=ax)

        CB.ax.get_yaxis().labelpad = 15
        CB.ax.set_ylabel(label, rotation=270)
        ax.set_xlabel(f"x ({unit})")
        ax.set_ylabel(f"y ({unit})")
        ax.set_aspect("equal")

        if show_magnets:
            _draw_magnets2(ax)
            if len(PolyMagnet.instances) > 0:
                for magnet in PolyMagnet.instances:
                    poly = _plt.Polygon(
                        _np.array(magnet.polygon.vertices),
                        ec="k",
                        fc="w",
                        zorder=5,
                    )
                    ax.add_patch(poly)

    fig.tight_layout()
    if SAVE:
        _plt.savefig("jacobian_plot.png", dpi=300)

    return fig, axes

plot_2D_line(point_array, field, **kwargs)

Line Plot of field from 2D magnet

Parameters:

Name Type Description Default
point_array Point_Array2

coordinates

required
field Field2

Magnetic Field

required
Kwargs

xlab (str): xlabel ylab (str): ylabel axis_scale (str): unused save_fig (bool): Save to png file. Defaults to False

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def plot_2D_line(
    point_array: Point_Array2, field: Field2, **kwargs: Any
) -> tuple[Figure, Axes]:
    """Line Plot of field from 2D magnet

    Args:
        point_array (Point_Array2): coordinates
        field (Field2): Magnetic Field

    Kwargs:
        xlab (str): xlabel
        ylab (str): ylabel
        axis_scale (str): unused
        save_fig (bool): Save to png file. Defaults to False

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    xlab = kwargs.pop("xlab", f"x ({point_array.unit})")
    ylab = kwargs.pop("ylab", f"B ({field.unit})")
    # axis_scale = kwargs.pop("axis_scale", "equal")

    SAVE = kwargs.pop("save_fig", False)

    fig, ax = _plt.subplots(figsize=(8, 8))
    _plt.plot(point_array.x, field.n, label=r"$|\mathbf{B}|$")
    _plt.plot(point_array.x, field.x, label=r"$B_x$")
    _plt.plot(point_array.x, field.y, label=r"$B_y$")
    _plt.legend(loc="best")
    _plt.xlabel(xlab)
    _plt.ylabel(ylab)

    _plt.show()

    if SAVE:
        _plt.savefig("line_plot.png", dpi=300)
        # _plt.savefig('contour_plot.pdf', dpi=300)
    return fig, ax

plot_3D_contour(points, field, plane, **kwargs)

Contour plot of field

Parameters:

Name Type Description Default
points Point_Array2

coordinates

required
field Field2

Magnetic field

required
plane str

Plane to draw contour on. Can be 'xy', 'xz', or 'yz'

required

Raises:

Type Description
Exception

plot_type must be 'contour' or 'streamplot

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
def plot_3D_contour(
    points: Point_Array3,
    field: Field3,
    plane: str,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Contour plot of field

    Args:
        points (Point_Array2): coordinates
        field (Field2): Magnetic field
        plane (str): Plane to draw contour on. Can be 'xy', 'xz', or 'yz'

    Raises:
        Exception: plot_type must be 'contour' or 'streamplot

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    axis_scale = kwargs.pop("axis_scale", "equal")

    plot_type = kwargs.pop("plot_type", "contour")

    xlab = kwargs.pop("xlab", "x (" + points.unit + ")")
    ylab = kwargs.pop("ylab", "y (" + points.unit + ")")
    zlab = kwargs.pop("zlab", "z (" + points.unit + ")")
    clab = kwargs.pop("clab", "B (" + field.unit + ")")

    SAVE = kwargs.pop("save_fig", False)

    finite_field = field.n[_np.isfinite(field.n)]

    cmax = kwargs.pop("cmax", round(finite_field.mean() * 2, 1))
    num_levels = kwargs.pop("num_levels", 11)

    if plane.lower() == "xy":
        plot_x = points.x
        plot_y = points.y
        plot_xlab = xlab
        plot_ylab = ylab
        stream_x = field.x
        stream_y = field.y

    elif plane.lower() == "xz":
        stream_x = field.x
        stream_y = field.z
        plot_x = points.x
        plot_y = points.z
        plot_xlab = xlab
        plot_ylab = zlab

    else:
        stream_x = field.y
        stream_y = field.z
        plot_x = points.y
        plot_y = points.z
        plot_xlab = ylab
        plot_ylab = zlab

    fig, ax = _plt.subplots(figsize=(8, 8))

    # Generate Contour Plot
    if plot_type.lower() == "contour":
        vector_color = kwargs.pop("vector_color", "w")
        NQ = kwargs.pop("num_arrows", None)

        cmap = kwargs.pop("cmap", "viridis")
        cmin = kwargs.pop("cmin", 0)
        lev2 = _np.linspace(cmin, cmax, 256, endpoint=True)
        CS = _plt.contourf(
            plot_x,
            plot_y,
            field.n,
            levels=lev2,
            cmap=_plt.get_cmap(cmap),
            extend="max",
        )

        # Draw contour lines
        if num_levels > 1:
            lev1 = _np.linspace(cmin, cmax, num_levels, endpoint=True)
            _ = _plt.contour(
                plot_x,
                plot_y,
                field.n,
                vmin=cmin,
                vmax=cmax,
                levels=lev1,
                linewidths=1.0,
                colors="k",
            )
            CB = _plt.colorbar(CS, ticks=lev1)

        else:
            CB = _plt.colorbar(CS)

        if NQ is not None:
            B_2D = Field2(stream_x, stream_y, unit=field.unit)
            B_2D.n = field.n
            points_2D = Point_Array2(plot_x, plot_y, unit=points.unit)
            _vector_plot2(points_2D, B_2D, NQ, vector_color)

    # Generates streamplot
    elif plot_type.lower() == "streamplot":
        xpl = plot_x[:, 0]
        ypl = plot_y[0, :]
        cmap = kwargs.pop("cmap", None)
        if cmap is not None:
            cmin = kwargs.pop("cmin", -round(finite_field.mean() * 2, 1))
            cmax = kwargs.pop("cmax", round(finite_field.mean() * 2, 1))

            stream_shading = kwargs.pop("stream_shading", "vertical")
            norm = _mcolors.Normalize(vmin=cmin, vmax=cmax)

            stream_dict = {
                "normal": field.n.T,
                "horizontal": stream_x.T,
                "vertical": stream_y.T,
            }

            CS = _plt.streamplot(
                xpl,
                ypl,
                stream_x.T / field.n.T,
                stream_y.T / field.n.T,
                color=stream_dict.get(stream_shading, "normal"),
                density=1.2,
                norm=norm,
                cmap=cmap,
                linewidth=0.5,
            )
            CS.set_edgecolor("face")
            CB = _plt.colorbar(CS.lines)
        else:
            color = kwargs.pop("color", "k")
            CS = _plt.streamplot(
                xpl,
                ypl,
                stream_x.T / field.n.T,
                stream_y.T / field.n.T,
                density=1.2,
                linewidth=0.5,
                color=color,
            )
            CB = None

    else:
        raise ValueError("plot_type must be 'contour' or 'streamplot'")

    if CB is not None:
        CB.ax.get_yaxis().labelpad = 15
        CB.ax.set_ylabel(clab, rotation=270)
    _plt.xlabel(plot_xlab)
    _plt.ylabel(plot_ylab)
    _plt.axis(axis_scale)

    if SAVE:
        _plt.savefig("contour_plot.png", dpi=300)

    return fig, ax

plot_sub_contour_3D(plot_x, plot_y, plot_B, **kwargs)

Contour plot of a single magnetic field component of a 3D simulation

Parameters:

Name Type Description Default
plot_x ndarray

coordinates for x-axis of plot

required
plot_y ndarray

coordinates for y-axis of plot

required
plot_B ndarray

Magnetic field component to plot

required

Returns:

Type Description
tuple

fig, ax reference to matplotlib figure and axis objects

Source code in src/pymagnet/plots/_plot2D.py
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def plot_sub_contour_3D(
    plot_x: NDArray[_np.floating],
    plot_y: NDArray[_np.floating],
    plot_B: NDArray[_np.floating],
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Contour plot of a single magnetic field component of a 3D simulation

    Args:
        plot_x (ndarray): coordinates for x-axis of plot
        plot_y (ndarray): coordinates for y-axis of plot
        plot_B (ndarray): Magnetic field component to plot

    Returns:
        tuple: fig, ax reference to matplotlib figure and axis objects
    """
    if not _has_matplotlib:
        raise ImportError("matplotlib is required to use this plot function.")

    cmap = kwargs.pop("cmap", "seismic")
    xlab = kwargs.pop("xlab", "x (m)")
    ylab = kwargs.pop("ylab", "y (m)")
    clab = kwargs.pop("clab", "B (T)")

    # axis_scale = kwargs.pop("axis_scale", "equal")

    # SAVE = kwargs.pop("save_fig", False)

    cmin = kwargs.pop("cmin", -0.5)
    cmax = kwargs.pop("cmax", 0.5)
    num_levels = kwargs.pop("num_levels", 11)

    lev2 = _np.linspace(cmin, cmax, 256, endpoint=True)
    fig, ax = _plt.subplots(figsize=(8, 8))
    CS = _plt.contourf(
        plot_x, plot_y, plot_B, levels=lev2, cmap=_plt.get_cmap(cmap), extend="both"
    )

    if num_levels > 1:
        lev1 = _np.linspace(cmin, cmax, num_levels, endpoint=True)
        _ = _plt.contour(
            plot_x,
            plot_y,
            plot_B,
            vmin=cmin,
            vmax=cmax,
            levels=lev1,
            linewidths=1.0,
            colors="k",
        )
        CB = _plt.colorbar(CS, ticks=lev1)
    else:
        CB = _plt.colorbar(CS)

    CB.ax.get_yaxis().labelpad = 15
    CB.ax.set_ylabel(clab, rotation=270)
    _plt.xlabel(xlab)
    _plt.ylabel(ylab)
    _plt.axis("equal")
    _plt.show()

    return fig, ax

3D Plotting routines

This module contains all functions needed to plot 3D contours for 3D magnetic sources. Unlike the plot2D module, here plotly is used as the backend.

TODO
  • Update str and repr for polyhedra

Graphic_Cuboid

Bases: Polyhedron

Generates Cuboid for plotly rendering

Source code in src/pymagnet/plots/_plotly3D.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class Graphic_Cuboid(Polyhedron):
    """Generates Cuboid for plotly rendering"""

    def __init__(self, center=(0, 0, 0), size=(1, 1, 1), **kwargs):
        """Init method

        Args:
            center (tuple, optional): Cuboid center. Defaults to (0, 0, 0).
            size (tuple, optional): Size of cuboid. Defaults to (1, 1, 1).

        Kwargs:
            alpha (float): rotation wit respect to ? axis. Defaults to 0.0.
            beta (float): rotation wit respect to ? axis. Defaults to 0.0.
            gamma (float): rotation wit respect to ? axis. Defaults to 0.0.
            color (str): color. Defaults to 'w'
        """
        super().__init__(center, size, **kwargs)

        self.vertices = self.generate_vertices()

    def generate_vertices(self):
        """Generates and rotates vertices of a cuboid based on orientation angles

        Returns:
            ndarray: 3xN array of vertex coordinates (columns are x, y, z)
        """
        if self._needs_rotation():
            vertex_coords = self._gen_vertices(center=(0, 0, 0), size=self.size)
            return self._apply_rotation(vertex_coords)
        else:
            return self._gen_vertices(self.center, self.size)

    @staticmethod
    def _gen_vertices(center=(0, 0, 0), size=(1, 1, 1)):
        """Generates coordinates for all cuboid vertices

        Args:
            center (tuple, optional): x,y,z coordinates. Defaults to (0, 0, 0)
            size (tuple, optional): scale the cuboid in x, y, z directons. Defaults to (1, 1, 1).

        Returns:
            ndarray: numpy array of shape (3, 8)
        """
        # Center of this cube is (0.5, 0.5, 0.5)
        x = _np.array([0, 0, 1, 1, 0, 0, 1, 1]) - 0.5
        y = _np.array([0, 1, 1, 0, 0, 1, 1, 0]) - 0.5
        z = _np.array([0, 0, 0, 0, 1, 1, 1, 1]) - 0.5

        vertex_coords = _np.vstack([x, y, z])

        # Scale x, y, z by the size array
        vertex_coords = _np.multiply(vertex_coords.T, size).T

        # Offset by externally set center
        vertex_coords += _np.array(center).reshape(-1, 1)

        return vertex_coords

__init__(center=(0, 0, 0), size=(1, 1, 1), **kwargs)

Init method

Parameters:

Name Type Description Default
center tuple

Cuboid center. Defaults to (0, 0, 0).

(0, 0, 0)
size tuple

Size of cuboid. Defaults to (1, 1, 1).

(1, 1, 1)
Kwargs

alpha (float): rotation wit respect to ? axis. Defaults to 0.0. beta (float): rotation wit respect to ? axis. Defaults to 0.0. gamma (float): rotation wit respect to ? axis. Defaults to 0.0. color (str): color. Defaults to 'w'

Source code in src/pymagnet/plots/_plotly3D.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(self, center=(0, 0, 0), size=(1, 1, 1), **kwargs):
    """Init method

    Args:
        center (tuple, optional): Cuboid center. Defaults to (0, 0, 0).
        size (tuple, optional): Size of cuboid. Defaults to (1, 1, 1).

    Kwargs:
        alpha (float): rotation wit respect to ? axis. Defaults to 0.0.
        beta (float): rotation wit respect to ? axis. Defaults to 0.0.
        gamma (float): rotation wit respect to ? axis. Defaults to 0.0.
        color (str): color. Defaults to 'w'
    """
    super().__init__(center, size, **kwargs)

    self.vertices = self.generate_vertices()

generate_vertices()

Generates and rotates vertices of a cuboid based on orientation angles

Returns:

Type Description
ndarray

3xN array of vertex coordinates (columns are x, y, z)

Source code in src/pymagnet/plots/_plotly3D.py
139
140
141
142
143
144
145
146
147
148
149
def generate_vertices(self):
    """Generates and rotates vertices of a cuboid based on orientation angles

    Returns:
        ndarray: 3xN array of vertex coordinates (columns are x, y, z)
    """
    if self._needs_rotation():
        vertex_coords = self._gen_vertices(center=(0, 0, 0), size=self.size)
        return self._apply_rotation(vertex_coords)
    else:
        return self._gen_vertices(self.center, self.size)

Graphic_Cylinder

Bases: Polyhedron

Generates vertices for a Cylinder for plotly rendering

Source code in src/pymagnet/plots/_plotly3D.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
class Graphic_Cylinder(Polyhedron):
    """Generates vertices for a Cylinder for plotly rendering"""

    def __init__(self, center=(0, 0, 0), radius=1, length=1, **kwargs):
        """Init method

        Args:
            center (tuple, optional): [description]. Defaults to (0, 0, 0).
            radius (float, optional): [description]. Defaults to 1.
            length (float, optional): [description]. Defaults to 1.

        Kwargs:
            alpha (float): rotation wit respect to ? axis. Defaults to 0.0.
            beta (float): rotation wit respect to ? axis. Defaults to 0.0.
            gamma (float): rotation wit respect to ? axis. Defaults to 0.0.
            color (str): color. Defaults to 'w'
        """
        super().__init__(center, size=(radius, radius, length), **kwargs)
        self.radius = radius
        self.length = length
        self.vertices = self.generate_vertices()

    def generate_vertices(self):
        """Generates and rotates vertices of a cylinder based on orientation angles

        Returns:
            ndarray: 3xN array of vertex coordinates (columns are x, y, z)
        """
        if self._needs_rotation():
            vertex_coords = self._gen_vertices(
                center=(0, 0, 0), radius=self.radius, length=self.length
            )
            return self._apply_rotation(vertex_coords)
        else:
            return self._gen_vertices(self.center, self.radius, self.length)

    @staticmethod
    def _gen_vertices(center=(0, 0, 0), radius=1, length=1):
        """Generates coordinates for approximate cylinder vertices

        Args:
            center (tuple, optional): x,y,z coordinates. Defaults to (0, 0, 0)
            radius (float, optional): radius of the cylinder. Defaults to 1.
            length (float, optional): length of the cylinder. Defaults to 1.


        Returns:
            ndarray: numpy array of shape (3, 8)
        """
        rho, z = _np.mgrid[0 : 2 * PI : 40j, -length / 2 : length / 2 : 2j]
        x = radius * _np.cos(rho)
        y = radius * _np.sin(rho)

        vertex_coords = _np.vstack([x.ravel(), y.ravel(), z.ravel()])

        # Offset by externally set center
        vertex_coords += _np.array(center).reshape(-1, 1)
        return vertex_coords

__init__(center=(0, 0, 0), radius=1, length=1, **kwargs)

Init method

Parameters:

Name Type Description Default
center tuple

[description]. Defaults to (0, 0, 0).

(0, 0, 0)
radius float

[description]. Defaults to 1.

1
length float

[description]. Defaults to 1.

1
Kwargs

alpha (float): rotation wit respect to ? axis. Defaults to 0.0. beta (float): rotation wit respect to ? axis. Defaults to 0.0. gamma (float): rotation wit respect to ? axis. Defaults to 0.0. color (str): color. Defaults to 'w'

Source code in src/pymagnet/plots/_plotly3D.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(self, center=(0, 0, 0), radius=1, length=1, **kwargs):
    """Init method

    Args:
        center (tuple, optional): [description]. Defaults to (0, 0, 0).
        radius (float, optional): [description]. Defaults to 1.
        length (float, optional): [description]. Defaults to 1.

    Kwargs:
        alpha (float): rotation wit respect to ? axis. Defaults to 0.0.
        beta (float): rotation wit respect to ? axis. Defaults to 0.0.
        gamma (float): rotation wit respect to ? axis. Defaults to 0.0.
        color (str): color. Defaults to 'w'
    """
    super().__init__(center, size=(radius, radius, length), **kwargs)
    self.radius = radius
    self.length = length
    self.vertices = self.generate_vertices()

generate_vertices()

Generates and rotates vertices of a cylinder based on orientation angles

Returns:

Type Description
ndarray

3xN array of vertex coordinates (columns are x, y, z)

Source code in src/pymagnet/plots/_plotly3D.py
256
257
258
259
260
261
262
263
264
265
266
267
268
def generate_vertices(self):
    """Generates and rotates vertices of a cylinder based on orientation angles

    Returns:
        ndarray: 3xN array of vertex coordinates (columns are x, y, z)
    """
    if self._needs_rotation():
        vertex_coords = self._gen_vertices(
            center=(0, 0, 0), radius=self.radius, length=self.length
        )
        return self._apply_rotation(vertex_coords)
    else:
        return self._gen_vertices(self.center, self.radius, self.length)

Graphic_Mesh

Bases: Polyhedron

Generates Mesh from STL file for plotly rendering

Source code in src/pymagnet/plots/_plotly3D.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class Graphic_Mesh(Polyhedron):
    """Generates Mesh from STL file for plotly rendering"""

    def __init__(self, mesh_vectors, **kwargs):
        """Init Method

        Args:
            mesh_vectors (ndarray): array of mesh vectors

        Kwargs:
            color (str): magnet color. Defaults to 'w'.
        """
        self.color = kwargs.pop("color", "white")
        self.mesh_vectors = mesh_vectors

    def generate_vertices(self):
        """Generates vertices from STL file

        Returns:
            dict: Dictionary of rendering properties for plotly
        """
        # return super().generate_vertices()
        p, q, r = self.mesh_vectors.shape  # (p, 3, 3)

        # the array stl_mesh.vectors.reshape(p*q, r) can contain multiple copies of the same vertex;
        # extract unique vertices from all mesh triangles
        vertices, ixr = _np.unique(
            self.mesh_vectors.reshape(p * q, r), return_inverse=True, axis=0
        )
        _I = _np.take(ixr, [3 * k for k in range(p)])
        _J = _np.take(ixr, [3 * k + 1 for k in range(p)])
        _K = _np.take(ixr, [3 * k + 2 for k in range(p)])
        x, y, z = vertices.T
        trace = _go.Mesh3d(x=x, y=y, z=z, i=_I, j=_J, k=_K, color=self.color)

        # optional parameters to make it look nicer
        trace.update(
            flatshading=True, lighting_facenormalsepsilon=0, lighting_ambient=0.7
        )
        return trace

__init__(mesh_vectors, **kwargs)

Init Method

Parameters:

Name Type Description Default
mesh_vectors ndarray

array of mesh vectors

required
Kwargs

color (str): magnet color. Defaults to 'w'.

Source code in src/pymagnet/plots/_plotly3D.py
297
298
299
300
301
302
303
304
305
306
307
def __init__(self, mesh_vectors, **kwargs):
    """Init Method

    Args:
        mesh_vectors (ndarray): array of mesh vectors

    Kwargs:
        color (str): magnet color. Defaults to 'w'.
    """
    self.color = kwargs.pop("color", "white")
    self.mesh_vectors = mesh_vectors

generate_vertices()

Generates vertices from STL file

Returns:

Type Description
dict

Dictionary of rendering properties for plotly

Source code in src/pymagnet/plots/_plotly3D.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def generate_vertices(self):
    """Generates vertices from STL file

    Returns:
        dict: Dictionary of rendering properties for plotly
    """
    # return super().generate_vertices()
    p, q, r = self.mesh_vectors.shape  # (p, 3, 3)

    # the array stl_mesh.vectors.reshape(p*q, r) can contain multiple copies of the same vertex;
    # extract unique vertices from all mesh triangles
    vertices, ixr = _np.unique(
        self.mesh_vectors.reshape(p * q, r), return_inverse=True, axis=0
    )
    _I = _np.take(ixr, [3 * k for k in range(p)])
    _J = _np.take(ixr, [3 * k + 1 for k in range(p)])
    _K = _np.take(ixr, [3 * k + 2 for k in range(p)])
    x, y, z = vertices.T
    trace = _go.Mesh3d(x=x, y=y, z=z, i=_I, j=_J, k=_K, color=self.color)

    # optional parameters to make it look nicer
    trace.update(
        flatshading=True, lighting_facenormalsepsilon=0, lighting_ambient=0.7
    )
    return trace

Graphic_Sphere

Bases: Polyhedron

Generates vertices for a sphere for plotly rendering

Source code in src/pymagnet/plots/_plotly3D.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class Graphic_Sphere(Polyhedron):
    """Generates vertices for a sphere for plotly rendering"""

    def __init__(self, center=(0, 0, 0), radius=1, **kwargs):
        """Init method

        Args:
            center (tuple, optional): [description]. Defaults to (0, 0, 0).
            radius (float, optional): [description]. Defaults to 1.

        Kwargs:
            alpha (float): rotation wit respect to ? axis. Defaults to 0.0.
            beta (float): rotation wit respect to ? axis. Defaults to 0.0.
            gamma (float): rotation wit respect to ? axis. Defaults to 0.0.
            color (str): color. Defaults to 'w'
        """
        super().__init__(center, size=(radius, radius, radius), **kwargs)
        self.radius = radius
        self.vertices = self.generate_vertices()

    def generate_vertices(self):
        """Generates and rotates vertices of a sphere based on orientation angles

        Returns:
            ndarray: 3xN array of vertex coordinates (columns are x, y, z)
        """
        if self._needs_rotation():
            vertex_coords = self._gen_vertices(center=(0, 0, 0), radius=self.radius)
            return self._apply_rotation(vertex_coords)
        else:
            return self._gen_vertices(self.center, self.radius)

    @staticmethod
    def _gen_vertices(center=(0, 0, 0), radius=1):
        """Generates coordinates for approximate sphere vertices

        Args:
            center (tuple, optional): x,y,z coordinates. Defaults to (0, 0, 0)
            radius (float, optional): radius of the sphere. Defaults to 1.

        Returns:
            ndarray: numpy array of shape (3, 8)
        """
        u, v = _np.mgrid[0 : 2 * PI : 20j, 0:PI:10j]
        x = radius * _np.cos(u) * _np.sin(v)
        y = radius * _np.sin(u) * _np.sin(v)
        z = radius * _np.cos(v)

        vertex_coords = _np.vstack([x.ravel(), y.ravel(), z.ravel()])

        # Offset by externally set center
        vertex_coords += _np.array(center).reshape(-1, 1)

        return vertex_coords

__init__(center=(0, 0, 0), radius=1, **kwargs)

Init method

Parameters:

Name Type Description Default
center tuple

[description]. Defaults to (0, 0, 0).

(0, 0, 0)
radius float

[description]. Defaults to 1.

1
Kwargs

alpha (float): rotation wit respect to ? axis. Defaults to 0.0. beta (float): rotation wit respect to ? axis. Defaults to 0.0. gamma (float): rotation wit respect to ? axis. Defaults to 0.0. color (str): color. Defaults to 'w'

Source code in src/pymagnet/plots/_plotly3D.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def __init__(self, center=(0, 0, 0), radius=1, **kwargs):
    """Init method

    Args:
        center (tuple, optional): [description]. Defaults to (0, 0, 0).
        radius (float, optional): [description]. Defaults to 1.

    Kwargs:
        alpha (float): rotation wit respect to ? axis. Defaults to 0.0.
        beta (float): rotation wit respect to ? axis. Defaults to 0.0.
        gamma (float): rotation wit respect to ? axis. Defaults to 0.0.
        color (str): color. Defaults to 'w'
    """
    super().__init__(center, size=(radius, radius, radius), **kwargs)
    self.radius = radius
    self.vertices = self.generate_vertices()

generate_vertices()

Generates and rotates vertices of a sphere based on orientation angles

Returns:

Type Description
ndarray

3xN array of vertex coordinates (columns are x, y, z)

Source code in src/pymagnet/plots/_plotly3D.py
198
199
200
201
202
203
204
205
206
207
208
def generate_vertices(self):
    """Generates and rotates vertices of a sphere based on orientation angles

    Returns:
        ndarray: 3xN array of vertex coordinates (columns are x, y, z)
    """
    if self._needs_rotation():
        vertex_coords = self._gen_vertices(center=(0, 0, 0), radius=self.radius)
        return self._apply_rotation(vertex_coords)
    else:
        return self._gen_vertices(self.center, self.radius)

Polyhedron

Bases: Registry

Encodes magnet dimensions for drawing a polyhedon on 3D plots

Polyhedra

Cuboid Cylinder Sphere Mesh

Source code in src/pymagnet/plots/_plotly3D.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class Polyhedron(Registry):
    """Encodes magnet dimensions for drawing a polyhedon on 3D plots

    Polyhedra:
        Cuboid
        Cylinder
        Sphere
        Mesh
    """

    # Tolerance for minimum angle needed for rotation of object
    tol = MAG_TOL

    def __init__(self, center, size, **kwargs):
        """Initialises a cuboid

        Args:
            center (tuple): x,y,z
            size (tuple): x,y,z
        """
        super().__init__()

        self.center = _np.asarray(center)
        self.size = _np.asarray(size)

        self.alpha = kwargs.pop("alpha", 0.0)
        self.alpha_rad = _np.deg2rad(self.alpha)
        self.beta = kwargs.pop("beta", 0.0)
        self.beta_rad = _np.deg2rad(self.beta)
        self.gamma = kwargs.pop("gamma", 0.0)
        self.gamma_rad = _np.deg2rad(self.gamma)
        self.color = kwargs.pop("color", "white")

    def __repr__(self) -> str:
        return f"(center: {self.center}, size: {self.size} )"

    def __str__(self) -> str:
        return f"(center: {self.center}, size: {self.size} )"

    def _needs_rotation(self) -> bool:
        """Check if any rotation angles exceed the tolerance threshold."""
        return bool(
            _np.any(
                _np.fabs(_np.array([self.alpha_rad, self.beta_rad, self.gamma_rad]))
                > Polyhedron.tol
            )
        )

    def _apply_rotation(self, vertex_coords: _np.ndarray) -> _np.ndarray:
        """Apply quaternion rotation to vertices and translate to center.

        Args:
            vertex_coords: 3xN array of vertex coordinates centered at origin

        Returns:
            ndarray: 3xN array of rotated and translated vertex coordinates
        """
        forward_rotation = Quaternion.gen_rotation_quaternion(
            self.alpha_rad, self.beta_rad, self.gamma_rad
        )
        reverse_rotation = forward_rotation.get_conjugate()

        # Rotate points
        x, y, z = reverse_rotation * vertex_coords

        # Reconstruct 3xN array and add center offset
        vertex_coords = _np.vstack([x, y, z])
        vertex_coords += _np.array(self.center).reshape(-1, 1)

        return vertex_coords

    def generate_vertices(self):
        """Generates vertices of a polyhedron

        This should be implemented for each Polyhedron child class
        """
        pass

__init__(center, size, **kwargs)

Initialises a cuboid

Parameters:

Name Type Description Default
center tuple

x,y,z

required
size tuple

x,y,z

required
Source code in src/pymagnet/plots/_plotly3D.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(self, center, size, **kwargs):
    """Initialises a cuboid

    Args:
        center (tuple): x,y,z
        size (tuple): x,y,z
    """
    super().__init__()

    self.center = _np.asarray(center)
    self.size = _np.asarray(size)

    self.alpha = kwargs.pop("alpha", 0.0)
    self.alpha_rad = _np.deg2rad(self.alpha)
    self.beta = kwargs.pop("beta", 0.0)
    self.beta_rad = _np.deg2rad(self.beta)
    self.gamma = kwargs.pop("gamma", 0.0)
    self.gamma_rad = _np.deg2rad(self.gamma)
    self.color = kwargs.pop("color", "white")

generate_vertices()

Generates vertices of a polyhedron

This should be implemented for each Polyhedron child class

Source code in src/pymagnet/plots/_plotly3D.py
111
112
113
114
115
116
def generate_vertices(self):
    """Generates vertices of a polyhedron

    This should be implemented for each Polyhedron child class
    """
    pass

list_polyhedra()

Returns a list of all instantiated polyhedra.

Assumes that the child class registries have not been modified outside of using pymagnet.reset().

Source code in src/pymagnet/plots/_plotly3D.py
349
350
351
352
353
354
355
def list_polyhedra():
    """Returns a list of all instantiated polyhedra.

    Assumes that the child class registries have not been modified outside of
    using `pymagnet.reset()`.
    """
    return Polyhedron.print_instances()

plot_magnet(unit='mm', **kwargs)

Renders magnets

Parameters:

Name Type Description Default
unit str

unit scale. Defaults to 'mm'.

'mm'

Returns:

Type Description
fig

reference to figure

Source code in src/pymagnet/plots/_plotly3D.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def plot_magnet(unit: str = "mm", **kwargs: Any) -> Figure:
    """Renders magnets

    Args:
        unit (str, optional): unit scale. Defaults to 'mm'.

    Returns:
        fig: reference to figure
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    data_objects = []

    data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + unit + ")",
            yaxis_title="y (" + unit + ")",
            zaxis_title="z (" + unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()
    return fig

reset_polyhedra()

Returns a list of all instantiated polyhedra.

Source code in src/pymagnet/plots/_plotly3D.py
336
337
338
339
340
341
342
343
344
345
346
def reset_polyhedra():
    """Returns a list of all instantiated polyhedra."""

    polyhedra_classes = [
        Polyhedron,
        Graphic_Cuboid,
        Graphic_Sphere,
        Graphic_Cylinder,
    ]
    for cls in polyhedra_classes:
        cls.reset()

slice_plot(data_dict, **kwargs)

Plots magnetic field slices. A convenience function.

Returns:

Type Description
tuple

fig (reference to figure), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def slice_plot(
    data_dict: dict[str, dict[str, Any]], **kwargs: Any
) -> tuple[Figure, list[Any]]:
    """Plots magnetic field slices.
    A convenience function.

    Returns:
        tuple: fig (reference to figure), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    opacity = kwargs.pop("opacity", 0.8)
    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    cone_opacity = kwargs.pop("cone_opacity", 1.0)

    cmin = kwargs.pop("cmin", 0)
    cmax = kwargs.pop("cmax", 0.5)
    colorscale = kwargs.pop("colorscale", "viridis")
    num_arrows = kwargs.pop("num_arrows", None)

    data_objects = []

    show_magnets = kwargs.pop("show_magnets", True)

    if show_magnets:
        data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    for plane in data_dict:
        points = data_dict[plane]["points"]
        field = data_dict[plane]["field"]

        data_objects.append(
            _draw_surface_slice(
                points,
                field,
                colorscale,
                opacity=opacity,
                cmin=cmin,
                cmax=cmax,
                showscale=True,
            )
        )
        if num_arrows is not None:
            num_points = field.x.shape[0]

            NA = num_points // num_arrows

            if NA > 1:
                data_objects.append(
                    _draw_cones(points, field, NA=NA, cone_opacity=cone_opacity)
                )

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + points.unit + ")",
            yaxis_title="y (" + points.unit + ")",
            zaxis_title="z (" + points.unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()
    return fig, data_objects

slice_quickplot(**kwargs)

Calculates and plots magnetic field slices. A convenience function.

Returns:

Type Description
tuple

fig (reference to figure), cache (cached data for each plane with potential keys: 'xy', 'xz', 'yz'), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
def slice_quickplot(
    **kwargs: Any,
) -> tuple[Figure, dict[str, dict[str, Any]], list[Any]]:
    """Calculates and plots magnetic field slices.
    A convenience function.

    Returns:
        tuple: fig (reference to figure), cache (cached data for each plane with potential keys: 'xy', 'xz', 'yz'), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    max1 = kwargs.pop("max1", 30)
    max2 = kwargs.pop("max2", 30)
    min1 = kwargs.pop("min1", -1 * max1)
    min2 = kwargs.pop("min2", -1 * max2)

    slice_value = kwargs.pop("slice_value", 0.0)
    unit = kwargs.pop("unit", "mm")

    opacity = kwargs.pop("opacity", 0.8)
    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    cone_opacity = kwargs.pop("cone_opacity", 1.0)
    planes = kwargs.pop("planes", ["xy", "xz", "yz"])

    num_arrows = kwargs.pop("num_arrows", None)
    num_points = kwargs.pop("num_points", 100)

    if num_arrows is not None:
        NA = num_points // num_arrows
        if NA < 1:
            NA = 1

    cmin = kwargs.pop("cmin", 0)
    cmax = kwargs.pop("cmax", 0.5)
    colorscale = kwargs.pop("colorscale", "viridis")

    data_objects = []
    cache = {}

    show_magnets = kwargs.pop("show_magnets", True)

    if show_magnets:
        data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    for plane in planes:
        points = slice3D(
            plane=plane,
            max1=max1,
            min1=min1,
            max2=max2,
            min2=min2,
            slice_value=slice_value,
            unit=unit,
            num_points=num_points,
        )
        field = get_field_3D(points)

        cache[plane] = {"points": points, "field": field}

        data_objects.append(
            _draw_surface_slice(
                points,
                field,
                colorscale,
                opacity=opacity,
                cmin=cmin,
                cmax=cmax,
                showscale=True,
            )
        )
        if num_arrows is not None:
            data_objects.append(
                _draw_cones(points, field, NA=NA, cone_opacity=cone_opacity)
            )

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + points.unit + ")",
            yaxis_title="y (" + points.unit + ")",
            zaxis_title="z (" + points.unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()
    return fig, cache, data_objects

volume_plot(points, field, **kwargs)

Plots magnetic field volume.

Parameters:

Name Type Description Default
points Point_Array3

coordinates

required
field Field3

Magnetic field vector

required

Returns:

Type Description
tuple

fig (reference to figure), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def volume_plot(
    points: Point_Array3, field: Field3, **kwargs: Any
) -> tuple[Figure, list[Any]]:
    """Plots magnetic field volume.

    Args:
        points (Point_Array3): coordinates
        field (Field3): Magnetic field vector

    Returns:
        tuple: fig (reference to figure), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    reset_polyhedra()

    opacity = kwargs.pop("opacity", 0.3)
    opacityscale = kwargs.pop("opacityscale", None)
    magnet_opacity = kwargs.pop("magnet_opacity", 1.0)
    cone_opacity = kwargs.pop("cone_opacity", 1.0)

    num_arrows = kwargs.pop("num_arrows", None)

    cmin = kwargs.pop("cmin", 0)
    cmax = kwargs.pop("cmax", 0.5)
    num_levels = kwargs.pop("num_levels", 5)

    show_magnets = kwargs.pop("show_magnets", True)

    num_points = len(points.x)

    data_objects = []

    if show_magnets:
        data_objects.extend(_generate_all_meshes(magnet_opacity=magnet_opacity))

    colorscale = kwargs.pop("colorscale", "viridis")

    #     kernel_size = 1
    #     kernel = np.ones([kernel_size, kernel_size, kernel_size]) / kernel_size
    #     B.n = ndimage.convolve(B.n, kernel)

    data_objects.append(
        _generate_volume_data(
            points,
            field,
            cmin=cmin,
            cmax=cmax,
            opacity=opacity,
            colorscale=colorscale,
            num_levels=num_levels,
            opacityscale=opacityscale,
        )
    )

    if num_arrows is not None:
        NA = num_points // num_arrows
        if NA < 1:
            NA = 1
        data_objects.append(
            _draw_cones(points, field, NA=NA, cone_opacity=cone_opacity)
        )

    fig = _go.Figure(data=data_objects)

    fig.update_layout(
        scene=dict(
            xaxis_title="x (" + points.unit + ")",
            yaxis_title="y (" + points.unit + ")",
            zaxis_title="z (" + points.unit + ")",
        ),
        width=700,
        margin=dict(r=20, b=10, l=10, t=10),
    )
    fig.update_layout(scene_aspectmode="data")
    fig.show()

    return fig, data_objects

volume_quickplot(**kwargs)

Calculates and plots magnetic field slices. A convenience function.

Kwargs

num_points (int): = kwargs.pop("num_points", 30) unit (str): = kwargs.pop("unit", "mm") xmax (float): Maximum x value. Defaults to 30.0. ymax (float): Maximum y value. Defaults to 30.0. zmax (float): Maximum z value. Defaults to 30.0. xmin (float): Minimum x value. Defaults to -xmax ymin (float): Minimum y value. Defaults to -ymax zmin (float): Minimum z value. Defaults to -zmax

Returns:

Type Description
tuple

fig (reference to figure), cache (cached data dict), data_objects (plotly dict)

Source code in src/pymagnet/plots/_plotly3D.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
def volume_quickplot(
    **kwargs: Any,
) -> tuple[Figure, dict[str, Any], list[Any]]:
    """Calculates and plots magnetic field slices.
    A convenience function.

    Kwargs:
        num_points (int): = kwargs.pop("num_points", 30)
        unit (str): = kwargs.pop("unit", "mm")
        xmax (float): Maximum x value. Defaults to 30.0.
        ymax (float): Maximum y value. Defaults to 30.0.
        zmax (float): Maximum z value. Defaults to 30.0.
        xmin (float): Minimum x value. Defaults to -xmax
        ymin (float): Minimum y value. Defaults to -ymax
        zmin (float): Minimum z value. Defaults to -zmax

    Returns:
        tuple: fig (reference to figure), cache (cached data dict), data_objects (plotly dict)
    """
    if not _has_plotly:
        raise ImportError("plotly is required to use this plot function.")

    num_points = kwargs.pop("num_points", 30)

    unit = kwargs.pop("unit", "mm")

    xmax = kwargs.pop("xmax", 30)
    ymax = kwargs.pop("ymax", 30)
    zmax = kwargs.pop("zmax", 30)

    xmin = kwargs.pop("xmin", -1 * xmax)
    ymin = kwargs.pop("ymin", -1 * ymax)
    zmin = kwargs.pop("zmin", -1 * zmax)

    points = grid3D(
        xmax,
        ymax,
        zmax,
        num_points=num_points,
        xmin=xmin,
        ymin=ymin,
        zmin=zmin,
        unit=unit,
    )
    field = get_field_3D(points)

    fig, data_objects = volume_plot(points, field, num_points=num_points, **kwargs)
    cache = {"points": points, "field": field}

    return fig, cache, data_objects