-
Notifications
You must be signed in to change notification settings - Fork 26
/
plotting.py
3766 lines (3296 loc) · 125 KB
/
plotting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
108
109
110
111
112
113
114
115
116
117
118
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
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
336
337
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
365
366
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
400
401
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
429
430
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
462
463
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
502
503
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
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
691
692
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
785
786
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
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
953
954
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
"""Functions for plotting and visualizing equilibria."""
import inspect
import numbers
import tkinter
import warnings
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import plotly.graph_objects as go
from matplotlib import cycler, rcParams
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pylatexenc.latex2text import LatexNodes2Text
from termcolor import colored
from desc.backend import sign
from desc.basis import fourier, zernike_radial_poly
from desc.coils import CoilSet, _Coil
from desc.compute import data_index, get_transforms
from desc.compute.utils import _parse_parameterization
from desc.equilibrium.coords import map_coordinates
from desc.grid import Grid, LinearGrid
from desc.integrals import surface_averages_map
from desc.magnetic_fields import field_line_integrate
from desc.utils import errorif, only1, parse_argname_change, setdefault
from desc.vmec_utils import ptolemy_linear_transform
__all__ = [
"plot_1d",
"plot_2d",
"plot_3d",
"plot_basis",
"plot_boozer_modes",
"plot_boozer_surface",
"plot_boundaries",
"plot_boundary",
"plot_coefficients",
"plot_coils",
"plot_comparison",
"plot_fsa",
"plot_grid",
"plot_logo",
"plot_qs_error",
"plot_section",
"plot_surfaces",
"poincare_plot",
]
colorblind_colors = [
(0.0000, 0.4500, 0.7000), # blue
(0.8359, 0.3682, 0.0000), # vermilion
(0.0000, 0.6000, 0.5000), # bluish green
(0.9500, 0.9000, 0.2500), # yellow
(0.3500, 0.7000, 0.9000), # sky blue
(0.8000, 0.6000, 0.7000), # reddish purple
(0.9000, 0.6000, 0.0000), # orange
]
sequential_colors = [
"#c80016", # red
"#dc5b0e", # burnt orange
"#f0b528", # light orange
"#dce953", # yellow
"#7acf7c", # green
"#1fb7c9", # teal
"#2192e3", # medium blue
"#4f66d4", # blue-violet
"#7436a5", # purple
]
dashes = [
(1.0, 0.0, 0.0, 0.0, 0.0, 0.0), # solid
(3.7, 1.6, 0.0, 0.0, 0.0, 0.0), # dashed
(1.0, 1.6, 0.0, 0.0, 0.0, 0.0), # dotted
(6.4, 1.6, 1.0, 1.6, 0.0, 0.0), # dot dash
(3.0, 1.6, 1.0, 1.6, 1.0, 1.6), # dot dot dash
(6.0, 4.0, 0.0, 0.0, 0.0, 0.0), # long dash
(1.0, 1.6, 3.0, 1.6, 3.0, 1.6), # dash dash dot
]
matplotlib.rcdefaults()
rcParams["font.family"] = "DejaVu Serif"
rcParams["mathtext.fontset"] = "cm"
rcParams["font.size"] = 10
rcParams["figure.facecolor"] = (1, 1, 1, 1)
rcParams["figure.figsize"] = (6, 4)
try:
dpi = tkinter.Tk().winfo_fpixels("1i")
except tkinter._tkinter.TclError:
dpi = 72
rcParams["figure.dpi"] = dpi
rcParams["figure.autolayout"] = True
rcParams["axes.spines.top"] = False
rcParams["axes.spines.right"] = False
rcParams["axes.labelsize"] = "small"
rcParams["axes.titlesize"] = "medium"
rcParams["lines.linewidth"] = 1
rcParams["lines.solid_capstyle"] = "round"
rcParams["lines.dash_capstyle"] = "round"
rcParams["lines.dash_joinstyle"] = "round"
rcParams["xtick.labelsize"] = "x-small"
rcParams["ytick.labelsize"] = "x-small"
color_cycle = cycler(color=colorblind_colors)
dash_cycle = cycler(dashes=dashes)
rcParams["axes.prop_cycle"] = color_cycle
_AXIS_LABELS_RTZ = [r"$\rho$", r"$\theta$", r"$\zeta$"]
_AXIS_LABELS_RPZ = [r"$R ~(\mathrm{m})$", r"$\phi$", r"$Z ~(\mathrm{m})$"]
_AXIS_LABELS_XYZ = [r"$X ~(\mathrm{m})$", r"$Y ~(\mathrm{m})$", r"$Z ~(\mathrm{m})$"]
def _set_tight_layout(fig):
# compat layer to deal with API changes in mpl 3.6.0
if int(matplotlib.__version__[0]) == 3 and int(matplotlib.__version__[2]) < 6:
fig.set_tight_layout(True)
else:
fig.set_layout_engine("tight")
def _get_cmap(name, n=None):
# compat layer to deal with API changes in mpl 3.6.0
if int(matplotlib.__version__[0]) == 3 and int(matplotlib.__version__[2]) < 6:
return matplotlib.cm.get_cmap(name, n)
else:
c = matplotlib.colormaps[name]
if n is not None:
c = c.resampled(n)
return c
def _format_ax(ax, is3d=False, rows=1, cols=1, figsize=None, equal=False):
"""Check type of ax argument. If ax is not a matplotlib AxesSubplot, initialize one.
Parameters
----------
ax : None or matplotlib AxesSubplot instance
Axis to plot on.
is3d: bool
Whether the plot is three-dimensional.
rows : int, optional
Number of rows of subplots to create.
cols : int, optional
Number of columns of subplots to create.
figsize : tuple of 2 floats
Figure size (width, height) in inches. Default is (6, 6).
equal : bool
Whether axes should have equal scales for x and y.
Returns
-------
fig : matplotlib.figure.Figure
Figure being plotted to.
ax : matplotlib.axes.Axes or ndarray of Axes
Axes being plotted to.
"""
if figsize is None:
figsize = (6, 6)
if ax is None:
if is3d:
fig = plt.figure(figsize=figsize, dpi=dpi)
ax = np.array(
[
fig.add_subplot(rows, cols, int(r * cols + c + 1), projection="3d")
for r in range(rows)
for c in range(cols)
]
).reshape((rows, cols))
if ax.size == 1:
ax = ax.flatten()[0]
return fig, ax
else:
fig, ax = plt.subplots(
rows,
cols,
figsize=figsize,
squeeze=False,
sharex=True,
sharey=True,
subplot_kw=dict(aspect="equal") if equal else None,
)
if ax.size == 1:
ax = ax.flatten()[0]
return fig, ax
elif isinstance(ax, matplotlib.axes.Axes):
return plt.gcf(), ax
else:
ax = np.atleast_1d(ax)
if isinstance(ax.flatten()[0], matplotlib.axes.Axes):
return plt.gcf(), ax
else:
raise TypeError(
colored(
"ax argument must be None or an axis instance or array of axes",
"red",
)
)
def _get_grid(**kwargs):
"""Get grid for plotting.
Parameters
----------
kwargs
Any arguments taken by LinearGrid.
Returns
-------
grid : LinearGrid
Grid of coordinates to evaluate at.
"""
grid_args = {
"L": None,
"M": None,
"N": None,
"NFP": 1,
"sym": False,
"axis": True,
"endpoint": True,
"rho": np.array([1.0]),
"theta": np.array([0.0]),
"zeta": np.array([0.0]),
}
for key in kwargs.keys():
if key in grid_args.keys():
grid_args[key] = kwargs[key]
grid = LinearGrid(**grid_args)
return grid
def _get_plot_axes(grid):
"""Find which axes are being plotted.
Parameters
----------
grid : Grid
Grid of coordinates to evaluate at.
Returns
-------
axes : tuple of int
Which axes of the grid are being plotted.
"""
plot_axes = [0, 1, 2]
if grid.num_rho == 1:
plot_axes.remove(0)
if grid.num_theta == 1:
plot_axes.remove(1)
if grid.num_zeta == 1:
plot_axes.remove(2)
return tuple(plot_axes)
def _compute(eq, name, grid, component=None, reshape=True):
"""Compute quantity specified by name on grid for Equilibrium eq.
Parameters
----------
eq : Equilibrium
Object from which to plot.
name : str
Name of variable to plot.
grid : Grid
Grid of coordinates to evaluate at.
component : str, optional
For vector variables, which element to plot. Default is the norm of the vector.
Returns
-------
data : float array of shape (M, L, N)
Computed quantity.
"""
parameterization = _parse_parameterization(eq)
if name not in data_index[parameterization]:
raise ValueError(
f"Unrecognized value '{name}' for "
+ f"parameterization {parameterization}."
)
assert component in [
None,
"R",
"phi",
"Z",
], f"component must be one of [None, 'R', 'phi', 'Z'], got {component}"
components = {"R": 0, "phi": 1, "Z": 2}
label = data_index[parameterization][name]["label"]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
data = eq.compute(name, grid=grid)[name]
if data_index[parameterization][name]["dim"] > 1:
if component is None:
data = np.linalg.norm(data, axis=-1)
label = "|" + label + "|"
else:
data = data[:, components[component]]
label = "(" + label + ")_"
if component in ["R", "Z"]:
label += component
else:
label += r"\phi"
label = r"$" + label + "~(" + data_index[parameterization][name]["units"] + ")$"
if reshape:
data = data.reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
return data, label
def plot_coefficients(eq, L=True, M=True, N=True, ax=None, **kwargs):
"""Plot spectral coefficient magnitudes vs spectral mode number.
Parameters
----------
eq : Equilibrium
Object from which to plot.
L : bool
Whether to include radial mode numbers in the x-axis or not.
M : bool
Whether to include poloidal mode numbers in the x-axis or not.
N : bool
Whether to include toroidal mode numbers in the x-axis or not.
ax : matplotlib AxesSubplot, optional
Axis to plot on.
**kwargs : fig,ax and plotting properties
Specify properties of the figure, axis, and plot appearance e.g.::
plot_X(figsize=(4,6))
Valid keyword arguments are:
figsize: tuple of length 2, the size of the figure (to be passed to matplotlib)
title_fontsize: integer, font size of the title
xlabel_fontsize: integer, font size of the x axis label
color: str or tuple, color to use for scatter plot
marker: str, marker to use for scatter plot
Returns
-------
fig : matplotlib.figure.Figure
Figure being plotted to.
ax : matplotlib.axes.Axes or ndarray of Axes
Axes being plotted to.
Examples
--------
.. image:: ../../_static/images/plotting/plot_coefficients.png
.. code-block:: python
from desc.plotting import plot_coefficients
fig, ax = plot_coefficients(eq)
"""
lmn = np.array([], dtype=int)
xlabel = ""
if L:
lmn = np.append(lmn, np.array([0]))
xlabel += "l"
if M or N:
xlabel += " + "
if M:
lmn = np.append(lmn, np.array([1]))
xlabel += "|m|"
if N:
xlabel += " + "
if N:
lmn = np.append(lmn, np.array([2]))
xlabel += "|n|"
fig, ax = _format_ax(ax, rows=1, cols=3, figsize=kwargs.pop("figsize", None))
title_fontsize = kwargs.pop("title_fontsize", None)
xlabel_fontsize = kwargs.pop("xlabel_fontsize", None)
marker = kwargs.pop("marker", "o")
color = kwargs.pop("color", "b")
assert (
len(kwargs) == 0
), f"plot_coefficients got unexpected keyword argument: {kwargs.keys()}"
ax[0, 0].semilogy(
np.sum(np.abs(eq.R_basis.modes[:, lmn]), axis=1),
np.abs(eq.R_lmn),
c=color,
marker=marker,
ls="",
)
ax[0, 1].semilogy(
np.sum(np.abs(eq.Z_basis.modes[:, lmn]), axis=1),
np.abs(eq.Z_lmn),
c=color,
marker=marker,
ls="",
)
ax[0, 2].semilogy(
np.sum(np.abs(eq.L_basis.modes[:, lmn]), axis=1),
np.abs(eq.L_lmn),
c=color,
marker=marker,
ls="",
)
ax[0, 0].set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax[0, 1].set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax[0, 2].set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax[0, 0].set_title("$|R_{lmn}|$", fontsize=title_fontsize)
ax[0, 1].set_title("$|Z_{lmn}|$", fontsize=title_fontsize)
ax[0, 2].set_title("$|\\lambda_{lmn}|$", fontsize=title_fontsize)
_set_tight_layout(fig)
return fig, ax
def plot_1d(eq, name, grid=None, log=False, ax=None, return_data=False, **kwargs):
"""Plot 1D profiles.
Parameters
----------
eq : Equilibrium, Surface, Curve
Object from which to plot.
name : str
Name of variable to plot.
grid : Grid, optional
Grid of coordinates to plot at.
log : bool, optional
Whether to use a log scale.
ax : matplotlib AxesSubplot, optional
Axis to plot on.
return_data : bool
If True, return the data plotted as well as fig,ax
**kwargs : dict, optional
Specify properties of the figure, axis, and plot appearance e.g.::
plot_X(figsize=(4,6),label="your_label")
Valid keyword arguments are:
* ``figsize``: tuple of length 2, the size of the figure (to be passed to
matplotlib)
* ``component``: str, one of [None, 'R', 'phi', 'Z'], For vector variables,
which element to plot. Default is the norm of the vector.
* ``label``: str, label of the plotted line (e.g. to be shown with ax.legend())
* ``xlabel_fontsize``: float, fontsize of the xlabel
* ``ylabel_fontsize``: float, fontsize of the ylabel
* ``linecolor``: str or tuple, color to use for plot line
* ``ls``: str, linestyle to use for plot line
* ``lw``: float, linewidth to use for plot line
Returns
-------
fig : matplotlib.figure.Figure
Figure being plotted to.
ax : matplotlib.axes.Axes or ndarray of Axes
Axes being plotted to.
plot_data : dict
Dictionary of the data plotted, only returned if ``return_data=True``
Examples
--------
.. image:: ../../_static/images/plotting/plot_1d.png
.. code-block:: python
from desc.plotting import plot_1d
plot_1d(eq, 'p')
"""
# If the quantity is a flux surface function, call plot_fsa.
# This is done because the computation of some quantities relies on a
# surface average. Surface averages should be computed over a 2-D grid to
# sample the entire surface. Computing this on a 1-D grid would return a
# misleading plot.
parameterization = _parse_parameterization(eq)
default_L = 100
default_N = 0
if data_index[parameterization][name]["coordinates"] == "r":
if grid is None:
return plot_fsa(
eq,
name,
rho=default_L,
log=log,
ax=ax,
return_data=return_data,
**kwargs,
)
rho = grid.nodes[:, 0]
if not np.all(np.isclose(rho, rho[0])):
# rho nodes are not constant, so user must be plotting against rho
return plot_fsa(
eq, name, rho=rho, log=log, ax=ax, return_data=return_data, **kwargs
)
elif data_index[parameterization][name]["coordinates"] == "s": # curve qtys
default_L = 0
default_N = 100
NFP = getattr(eq, "NFP", 1)
if grid is None:
grid_kwargs = {"L": default_L, "N": default_N, "NFP": NFP}
grid = _get_grid(**grid_kwargs)
plot_axes = _get_plot_axes(grid)
if len(plot_axes) != 1:
return ValueError(colored("Grid must be 1D", "red"))
data, ylabel = _compute(eq, name, grid, kwargs.pop("component", None))
label = kwargs.pop("label", None)
fig, ax = _format_ax(ax, figsize=kwargs.pop("figsize", None))
# reshape data to 1D
data = data.flatten()
linecolor = kwargs.pop("linecolor", colorblind_colors[0])
ls = kwargs.pop("ls", "-")
lw = kwargs.pop("lw", 1)
if log:
data = np.abs(data) # ensure data is positive for log plot
ax.semilogy(
grid.nodes[:, plot_axes[0]],
data,
label=label,
color=linecolor,
ls=ls,
lw=lw,
)
else:
ax.plot(
grid.nodes[:, plot_axes[0]],
data,
label=label,
color=linecolor,
ls=ls,
lw=lw,
)
xlabel_fontsize = kwargs.pop("xlabel_fontsize", None)
ylabel_fontsize = kwargs.pop("ylabel_fontsize", None)
assert len(kwargs) == 0, f"plot_1d got unexpected keyword argument: {kwargs.keys()}"
xlabel = _AXIS_LABELS_RTZ[plot_axes[0]]
ax.set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax.set_ylabel(ylabel, fontsize=ylabel_fontsize)
_set_tight_layout(fig)
plot_data = {xlabel.strip("$").strip("\\"): grid.nodes[:, plot_axes[0]], name: data}
if label is not None:
ax.legend()
if return_data:
return fig, ax, plot_data
return fig, ax
def plot_2d(
eq, name, grid=None, log=False, norm_F=False, ax=None, return_data=False, **kwargs
):
"""Plot 2D cross-sections.
Parameters
----------
eq : Equilibrium, Surface
Object from which to plot.
name : str
Name of variable to plot.
grid : Grid, optional
Grid of coordinates to plot at.
log : bool, optional
Whether to use a log scale.
norm_F : bool, optional
Whether to normalize a plot of force error to be unitless.
Vacuum equilibria are normalized by the gradient of magnetic pressure,
while finite beta equilibria are normalized by the pressure gradient.
ax : matplotlib AxesSubplot, optional
Axis to plot on.
return_data : bool
If True, return the data plotted as well as fig,ax
**kwargs : dict, optional
Specify properties of the figure, axis, and plot appearance e.g.::
plot_X(figsize=(4,6),cmap="plasma")
Valid keyword arguments are:
* ``figsize``: tuple of length 2, the size of the figure (to be passed to
matplotlib)
* ``component``: str, one of [None, 'R', 'phi', 'Z'], For vector variables,
which element to plot. Default is the norm of the vector.
* ``title_fontsize``: integer, font size of the title
* ``xlabel_fontsize``: float, fontsize of the xlabel
* ``ylabel_fontsize``: float, fontsize of the ylabel
* ``cmap``: str, matplotlib colormap scheme to use, passed to ax.contourf
* ``levels``: int or array-like, passed to contourf
* ``field``: MagneticField, a magnetic field with which to calculate Bn on
the surface, must be provided if Bn is entered as the variable to plot.
* ``field_grid``: MagneticField, a Grid to pass to the field as a source grid
from which to calculate Bn, by default None.
* ``filled`` : bool, whether to fill contours or not i.e. whether to use
`contourf` or `contour`
Returns
-------
fig : matplotlib.figure.Figure
Figure being plotted to.
ax : matplotlib.axes.Axes or ndarray of Axes
Axes being plotted to.
plot_data : dict
Dictionary of the data plotted, only returned if ``return_data=True``
Examples
--------
.. image:: ../../_static/images/plotting/plot_2d.png
.. code-block:: python
from desc.plotting import plot_2d
plot_2d(eq, 'sqrt(g)')
"""
parameterization = _parse_parameterization(eq)
if grid is None:
grid_kwargs = {"M": 33, "N": 33, "NFP": eq.NFP, "axis": False}
grid = _get_grid(**grid_kwargs)
plot_axes = _get_plot_axes(grid)
if len(plot_axes) != 2:
return ValueError(colored("Grid must be 2D", "red"))
component = kwargs.pop("component", None)
if name != "B*n":
data, label = _compute(
eq,
name,
grid,
component=component,
)
else:
field = kwargs.pop("field", None)
errorif(
field is None,
ValueError,
"If B*n is entered as the variable to plot, a magnetic field"
" must be provided.",
)
errorif(
not np.all(np.isclose(grid.nodes[:, 0], 1)),
ValueError,
"If B*n is entered as the variable to plot, "
"the grid nodes must be at rho=1.",
)
field_grid = kwargs.pop("field_grid", None)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if grid.endpoint:
# cannot use a grid with endpoint=True for FFT interpolator
vc_grid = LinearGrid(
theta=grid.nodes[grid.unique_theta_idx[0:-1], 1],
zeta=grid.nodes[grid.unique_zeta_idx[0:-1], 2],
NFP=grid.NFP,
endpoint=False,
)
else:
vc_grid = grid
data, _ = field.compute_Bnormal(
eq, eval_grid=vc_grid, source_grid=field_grid, vc_source_grid=vc_grid
)
data = data.reshape((vc_grid.num_theta, vc_grid.num_zeta), order="F")
if grid.endpoint:
data = np.hstack((data, np.atleast_2d(data[:, 0]).T))
data = np.vstack((data, data[0, :]))
data = data.reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
label = r"$\mathbf{B} \cdot \hat{n} ~(\mathrm{T})$"
fig, ax = _format_ax(ax, figsize=kwargs.pop("figsize", None))
divider = make_axes_locatable(ax)
if norm_F:
# normalize force by B pressure gradient
norm_name = kwargs.pop("norm_name", "<|grad(|B|^2)|/2mu0>_vol")
norm_data, _ = _compute(eq, norm_name, grid, reshape=False)
data = data / np.nanmean(np.abs(norm_data)) # normalize
# reshape data to 2D
if 0 in plot_axes:
if 1 in plot_axes: # rho & theta
data = data[:, :, 0]
else: # rho & zeta
data = data[0, :, :]
else: # theta & zeta
data = data[:, 0, :]
contourf_kwargs = {}
if log:
data = np.abs(data) # ensure data is positive for log plot
contourf_kwargs["norm"] = matplotlib.colors.LogNorm()
if norm_F:
contourf_kwargs["levels"] = kwargs.pop("levels", np.logspace(-6, 0, 7))
else:
logmin = max(np.floor(np.nanmin(np.log10(data))).astype(int), -16)
logmax = np.ceil(np.nanmax(np.log10(data))).astype(int)
contourf_kwargs["levels"] = kwargs.pop(
"levels", np.logspace(logmin, logmax, logmax - logmin + 1)
)
else:
contourf_kwargs["norm"] = matplotlib.colors.Normalize()
contourf_kwargs["levels"] = kwargs.pop(
"levels", np.linspace(np.nanmin(data), np.nanmax(data), 100)
)
contourf_kwargs["cmap"] = kwargs.pop("cmap", "jet")
contourf_kwargs["extend"] = "both"
title_fontsize = kwargs.pop("title_fontsize", None)
xlabel_fontsize = kwargs.pop("xlabel_fontsize", None)
ylabel_fontsize = kwargs.pop("ylabel_fontsize", None)
filled = kwargs.pop("filled", True)
assert len(kwargs) == 0, f"plot_2d got unexpected keyword argument: {kwargs.keys()}"
cax_kwargs = {"size": "5%", "pad": 0.05}
xx = (
grid.nodes[:, plot_axes[1]]
.reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
.squeeze()
)
yy = (
grid.nodes[:, plot_axes[0]]
.reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
.squeeze()
)
if not filled:
im = ax.contour(xx, yy, data, **contourf_kwargs)
else:
im = ax.contourf(xx, yy, data, **contourf_kwargs)
cax = divider.append_axes("right", **cax_kwargs)
cbar = fig.colorbar(im, cax=cax)
cbar.update_ticks()
xlabel = _AXIS_LABELS_RTZ[plot_axes[1]]
ylabel = _AXIS_LABELS_RTZ[plot_axes[0]]
ax.set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax.set_ylabel(ylabel, fontsize=ylabel_fontsize)
ax.set_title(label, fontsize=title_fontsize)
if norm_F:
ax.set_title(
"%s / %s"
% (
"$" + data_index[parameterization][name]["label"] + "$",
"$" + data_index[parameterization][norm_name]["label"] + "$",
)
)
_set_tight_layout(fig)
plot_data = {
xlabel.strip("$").strip("\\"): xx,
ylabel.strip("$").strip("\\"): yy,
name: data,
}
if norm_F:
plot_data["normalization"] = np.nanmean(np.abs(norm_data))
else:
plot_data["normalization"] = 1
if return_data:
return fig, ax, plot_data
return fig, ax
def _trimesh_idx(n1, n2, periodic1=True, periodic2=True):
# suppose grid is something like this (n1=3, n2=4):
# 0 1 2 3
# 4 5 6 7
# 8 9 10 11
# first set of triangles are (0,1,4), (1,2,5), (2,3,6), (3,0,7), ... (8,9,0) etc
# second set are (1,5,4), (2,6,5), (3,7,6), (0,4,7) etc.
# for the first set, i1 is the linear index, j1 = i1+1, k1=i1+n2
# for second set, i2 from the second set is j1 from the first, and j2 = k1,
# k2 = i1 + 1 + n2 with some other tricks to handle wrapping or out of bounds
n = n1 * n2
c, r = np.meshgrid(np.arange(n1), np.arange(n2), indexing="ij")
def clip_or_mod(x, p, flag):
if flag:
return x % p
else:
return np.clip(x, 0, p - 1)
i1 = c * n2 + r
j1 = c * n2 + clip_or_mod((r + 1), n2, periodic2)
k1 = clip_or_mod((c + 1), n1, periodic1) * n2 + r
i2 = c * n2 + clip_or_mod((r + 1), n2, periodic2)
j2 = clip_or_mod((c + 1), n1, periodic1) * n2 + r
k2 = clip_or_mod((c + 1), n1, periodic1) * n2 + clip_or_mod((r + 1), n2, periodic2)
i = np.concatenate([i1.flatten(), i2.flatten()])
j = np.concatenate([j1.flatten(), j2.flatten()])
k = np.concatenate([k1.flatten(), k2.flatten()])
# remove degenerate triangles, ie with the same vertex twice
degens = (i == j) | (j == k) | (i == k)
ijk = np.array([i, j, k])[:, ~degens]
# remove out of bounds indices
ijk = ijk[:, np.all(ijk < n, axis=0)]
# remove duplicates
ijk = np.unique(np.sort(ijk, axis=0), axis=1)
# expected number of triangles
# start with 2 per square
exnum = (n1 - 1) * (n2 - 1) * 2
# if periodic, add extra "ghost" cells to connect ends
if periodic1:
exnum += (n2 - 1) * 2
if periodic2:
exnum += (n1 - 1) * 2
# if doubly periodic, there's also 2 at the corner
if periodic1 and periodic2:
exnum += 2
assert ijk.shape[1] == exnum
return ijk
def plot_3d(
eq,
name,
grid=None,
log=False,
fig=None,
return_data=False,
**kwargs,
):
"""Plot 3D surfaces.
Parameters
----------
eq : Equilibrium, Surface
Object from which to plot.
name : str
Name of variable to plot.
grid : Grid, optional
Grid of coordinates to plot at.
log : bool, optional
Whether to use a log scale.
fig : plotly.graph_objs._figure.Figure, optional
Figure to plot on.
return_data : bool
If True, return the data plotted as well as fig,ax
**kwargs : dict, optional
Specify properties of the figure, axis, and plot appearance e.g.::
plot_X(figsize=(4,6), cmap="RdBu")
Valid keyword arguments are:
* ``figsize``: tuple of length 2, the size of the figure in inches
* ``component``: str, one of [None, 'R', 'phi', 'Z'], For vector variables,
which element to plot. Default is the norm of the vector.
* ``title``: title to add to the figure.
* ``cmap``: string denoting colormap to use.
* ``levels``: array of data values where ticks on colorbar should be placed.
* ``alpha``: float in [0,1.0], the transparency of the plotted surface
* ``showscale``: Bool, whether or not to show the colorbar. True by default.
* ``showgrid``: Bool, whether or not to show the coordinate grid lines.
True by default.
* ``showticklabels``: Bool, whether or not to show the coordinate tick labels.
True by default.
* ``showaxislabels``: Bool, whether or not to show the coordinate axis labels.
True by default.
* ``zeroline``: Bool, whether or not to show the zero coordinate axis lines.
True by default.
* ``field``: MagneticField, a magnetic field with which to calculate Bn on
the surface, must be provided if Bn is entered as the variable to plot.
* ``field_grid``: MagneticField, a Grid to pass to the field as a source grid
from which to calculate Bn, by default None.
Returns
-------
fig : plotly.graph_objs._figure.Figure
Figure being plotted to
plot_data : dict
Dictionary of the data plotted, only returned if ``return_data=True``
Examples
--------
.. image:: ../../_static/images/plotting/plot_3d.png
.. code-block:: python
from desc.plotting import plot_3d
from desc.grid import LinearGrid
grid = LinearGrid(
rho=0.5,
theta=np.linspace(0, 2 * np.pi, 100),
zeta=np.linspace(0, 2 * np.pi, 100),
axis=True,
)
fig = plot_3d(eq, "|F|", log=True, grid=grid)
"""
if grid is None:
grid_kwargs = {"M": 50, "N": int(50 * eq.NFP), "NFP": 1, "endpoint": True}
grid = _get_grid(**grid_kwargs)
assert isinstance(grid, LinearGrid), "grid must be LinearGrid for 3d plotting"
assert only1(
grid.num_rho == 1, grid.num_theta == 1, grid.num_zeta == 1
), "Grid must be 2D"
figsize = kwargs.pop("figsize", (10, 10))
alpha = kwargs.pop("alpha", 1.0)
cmap = kwargs.pop("cmap", "RdBu_r")
title = kwargs.pop("title", "")
levels = kwargs.pop("levels", None)
component = kwargs.pop("component", None)
showgrid = kwargs.pop("showgrid", True)
zeroline = kwargs.pop("zeroline", True)
showscale = kwargs.pop("showscale", True)
showticklabels = kwargs.pop("showticklabels", True)
showaxislabels = kwargs.pop("showaxislabels", True)
if name != "B*n":
data, label = _compute(
eq,
name,
grid,
component=component,
)
else:
field = kwargs.pop("field", None)
errorif(
field is None,
ValueError,
"If B*n is entered as the variable to plot, a magnetic field"
" must be provided.",
)
errorif(
not np.all(np.isclose(grid.nodes[:, 0], 1)),
ValueError,
"If B*n is entered as the variable to plot, "
"the grid nodes must be at rho=1.",
)
field_grid = kwargs.pop("field_grid", None)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if grid.endpoint:
# cannot use a grid with endpoint=True for FFT interpolator
vc_grid = LinearGrid(
theta=grid.nodes[grid.unique_theta_idx[0:-1], 1],
zeta=grid.nodes[grid.unique_zeta_idx[0:-1], 2],
NFP=grid.NFP,
endpoint=False,
)
else:
vc_grid = grid
data, _ = field.compute_Bnormal(
eq, eval_grid=vc_grid, source_grid=field_grid, vc_source_grid=vc_grid
)
data = data.reshape((vc_grid.num_theta, vc_grid.num_zeta), order="F")
if grid.endpoint:
data = np.hstack((data, np.atleast_2d(data[:, 0]).T))
data = np.vstack((data, data[0, :]))
data = data.reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
label = r"$\mathbf{B} \cdot \hat{n} ~(\mathrm{T})$"
errorif(
len(kwargs) != 0,
ValueError,
f"plot_3d got unexpected keyword argument: {kwargs.keys()}",
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
coords = eq.compute(["X", "Y", "Z"], grid=grid)
X = coords["X"].reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
Y = coords["Y"].reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
Z = coords["Z"].reshape((grid.num_theta, grid.num_rho, grid.num_zeta), order="F")
if grid.num_rho == 1:
n1, n2 = grid.num_theta, grid.num_zeta
if not grid.nodes[-1][2] == 2 * np.pi:
p1, p2 = False, False
else:
p1, p2 = False, True
elif grid.num_theta == 1:
n1, n2 = grid.num_rho, grid.num_zeta
p1, p2 = False, True
elif grid.num_zeta == 1:
n1, n2 = grid.num_theta, grid.num_rho