-
Notifications
You must be signed in to change notification settings - Fork 26
/
utils.py
1325 lines (1132 loc) · 49 KB
/
utils.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 flux surface averages and vector algebra operations."""
import copy
import inspect
import warnings
import numpy as np
from termcolor import colored
from desc.backend import cond, fori_loop, jnp, put
from desc.grid import ConcentricGrid, LinearGrid
from .data_index import data_index
# map from profile name to equilibrium parameter name
profile_names = {
"pressure": "p_l",
"iota": "i_l",
"current": "c_l",
"electron_temperature": "Te_l",
"electron_density": "ne_l",
"ion_temperature": "Ti_l",
"atomic_number": "Zeff_l",
}
def _parse_parameterization(p):
if isinstance(p, str):
return p
klass = p.__class__
module = klass.__module__
if module == "builtins":
return klass.__qualname__ # avoid outputs like 'builtins.str'
return module + "." + klass.__qualname__
def compute(parameterization, names, params, transforms, profiles, data=None, **kwargs):
"""Compute the quantity given by name on grid.
Parameters
----------
parameterization : str, class, or instance
Type of object to compute for, eg Equilibrium, Curve, etc.
names : str or array-like of str
Name(s) of the quantity(s) to compute.
params : dict of ndarray
Parameters from the equilibrium, such as R_lmn, Z_lmn, i_l, p_l, etc.
Defaults to attributes of self.
transforms : dict of Transform
Transforms for R, Z, lambda, etc. Default is to build from grid
profiles : dict of Profile
Profile objects for pressure, iota, current, etc. Defaults to attributes
of self
data : dict of ndarray
Data computed so far, generally output from other compute functions
Returns
-------
data : dict of ndarray
Computed quantity and intermediate variables.
"""
p = _parse_parameterization(parameterization)
if isinstance(names, str):
names = [names]
for name in names:
if name not in data_index[p]:
raise ValueError(f"Unrecognized value '{name}' for parameterization {p}.")
allowed_kwargs = {"helicity", "M_booz", "N_booz", "gamma", "basis", "method"}
bad_kwargs = kwargs.keys() - allowed_kwargs
if len(bad_kwargs) > 0:
raise ValueError(f"Unrecognized argument(s): {bad_kwargs}")
for name in names:
assert _has_params(name, params, p), f"Don't have params to compute {name}"
assert _has_profiles(
name, profiles, p
), f"Don't have profiles to compute {name}"
assert _has_transforms(
name, transforms, p
), f"Don't have transforms to compute {name}"
if data is None:
data = {}
data = _compute(
p,
names,
params=params,
transforms=transforms,
profiles=profiles,
data=data,
**kwargs,
)
return data
def _compute(
parameterization, names, params, transforms, profiles, data=None, **kwargs
):
"""Same as above but without checking inputs for faster recursion."""
for name in names:
if name in data:
# don't compute something that's already been computed
continue
if not has_dependencies(
parameterization, name, params, transforms, profiles, data
):
# then compute the missing dependencies
data = _compute(
parameterization,
data_index[parameterization][name]["dependencies"]["data"],
params=params,
transforms=transforms,
profiles=profiles,
data=data,
**kwargs,
)
if transforms["grid"].axis.size:
data = _compute(
parameterization,
data_index[parameterization][name]["dependencies"][
"axis_limit_data"
],
params=params,
transforms=transforms,
profiles=profiles,
data=data,
**kwargs,
)
# now compute the quantity
data = data_index[parameterization][name]["fun"](
params=params, transforms=transforms, profiles=profiles, data=data, **kwargs
)
return data
def get_data_deps(keys, obj, has_axis=False):
"""Get list of data keys needed to compute a given quantity.
Parameters
----------
keys : str or array-like of str
Name of the desired quantity from the data index
obj : Equilibrium, Curve, Surface, Coil, etc.
Object to compute quantity for.
has_axis : bool
Whether the grid to compute on has a node on the magnetic axis.
Returns
-------
deps : list of str
Names of quantities needed to compute key
"""
p = _parse_parameterization(obj)
keys = [keys] if isinstance(keys, str) else keys
def _get_deps_1_key(key):
if has_axis:
if "full_with_axis_dependencies" in data_index[p][key]:
return data_index[p][key]["full_with_axis_dependencies"]["data"]
elif "full_dependencies" in data_index[p][key]:
return data_index[p][key]["full_dependencies"]["data"]
deps = data_index[p][key]["dependencies"]["data"]
if len(deps) == 0:
return deps
out = deps.copy() # to avoid modifying the data_index
for dep in deps:
out += _get_deps_1_key(dep)
if has_axis:
axis_limit_deps = data_index[p][key]["dependencies"]["axis_limit_data"]
out += axis_limit_deps.copy() # to be safe
for dep in axis_limit_deps:
out += _get_deps_1_key(dep)
return sorted(list(set(out)))
out = []
for key in keys:
out += _get_deps_1_key(key)
return sorted(list(set(out)))
def get_derivs(keys, obj, has_axis=False):
"""Get dict of derivative orders needed to compute a given quantity.
Parameters
----------
keys : str or array-like of str
Name of the desired quantity from the data index
obj : Equilibrium, Curve, Surface, Coil, etc.
Object to compute quantity for.
has_axis : bool
Whether the grid to compute on has a node on the magnetic axis.
Returns
-------
derivs : dict of list of int
Orders of derivatives needed to compute key.
Keys for R, Z, L, etc
"""
p = _parse_parameterization(obj)
keys = [keys] if isinstance(keys, str) else keys
def _get_derivs_1_key(key):
if has_axis:
if "full_with_axis_dependencies" in data_index[p][key]:
return data_index[p][key]["full_with_axis_dependencies"]["transforms"]
elif "full_dependencies" in data_index[p][key]:
return data_index[p][key]["full_dependencies"]["transforms"]
deps = [key] + get_data_deps(key, p, has_axis=has_axis)
derivs = {}
for dep in deps:
for key, val in data_index[p][dep]["dependencies"]["transforms"].items():
if key not in derivs:
derivs[key] = []
derivs[key] += val
return derivs
derivs = {}
for key in keys:
derivs1 = _get_derivs_1_key(key)
for key1, val in derivs1.items():
if key1 not in derivs:
derivs[key1] = []
derivs[key1] += val
return {key: np.unique(val, axis=0).tolist() for key, val in derivs.items()}
def get_profiles(keys, obj, grid=None, has_axis=False, jitable=False, **kwargs):
"""Get profiles needed to compute a given quantity on a given grid.
Parameters
----------
keys : str or array-like of str
Name of the desired quantity from the data index.
obj : Equilibrium, Curve, Surface, Coil, etc.
Object to compute quantity for.
grid : Grid
Grid to compute quantity on.
has_axis : bool
Whether the grid to compute on has a node on the magnetic axis.
jitable: bool
Whether to skip certain checks so that this operation works under JIT
Returns
-------
profiles : list of str or dict of Profile
Profiles needed to compute key.
if eq is None, returns a list of the names of profiles needed
otherwise, returns a dict of Profiles
Keys for pressure, iota, etc.
"""
p = _parse_parameterization(obj)
keys = [keys] if isinstance(keys, str) else keys
has_axis = has_axis or (grid is not None and grid.axis.size)
deps = list(keys) + get_data_deps(keys, p, has_axis=has_axis)
profs = []
for key in deps:
profs += data_index[p][key]["dependencies"]["profiles"]
profs = sorted(list(set(profs)))
if isinstance(obj, str) or inspect.isclass(obj):
return profs
# need to use copy here because profile may be None
profiles = {name: copy.deepcopy(getattr(obj, name)) for name in profs}
return profiles
def get_params(keys, obj, has_axis=False, **kwargs):
"""Get parameters needed to compute a given quantity.
Parameters
----------
keys : str or array-like of str
Name of the desired quantity from the data index
obj : Equilibrium, Curve, Surface, Coil, etc.
Object to compute quantity for.
has_axis : bool
Whether the grid to compute on has a node on the magnetic axis.
Returns
-------
params : list of str or dict of ndarray
Parameters needed to compute key.
If eq is None, returns a list of the names of params needed
otherwise, returns a dict of ndarray with keys for R_lmn, Z_lmn, etc.
"""
p = _parse_parameterization(obj)
keys = [keys] if isinstance(keys, str) else keys
deps = list(keys) + get_data_deps(keys, p, has_axis=has_axis)
params = []
for key in deps:
params += data_index[p][key]["dependencies"]["params"]
if isinstance(obj, str) or inspect.isclass(obj):
return params
temp_params = {}
for name in params:
p = getattr(obj, name)
if isinstance(p, dict):
temp_params[name] = p.copy()
else:
temp_params[name] = jnp.atleast_1d(p)
return temp_params
def get_transforms(keys, obj, grid, jitable=False, **kwargs):
"""Get transforms needed to compute a given quantity on a given grid.
Parameters
----------
keys : str or array-like of str
Name of the desired quantity from the data index
obj : Equilibrium, Curve, Surface, Coil, etc.
Object to compute quantity for.
grid : Grid
Grid to compute quantity on
jitable: bool
Whether to skip certain checks so that this operation works under JIT
Returns
-------
transforms : dict of Transform
Transforms needed to compute key.
Keys for R, Z, L, etc
"""
from desc.basis import DoubleFourierSeries
from desc.transform import Transform
method = "jitable" if jitable or kwargs.get("method") == "jitable" else "auto"
keys = [keys] if isinstance(keys, str) else keys
derivs = get_derivs(keys, obj, has_axis=grid.axis.size)
transforms = {"grid": grid}
for c in derivs.keys():
if hasattr(obj, c + "_basis"):
transforms[c] = Transform(
grid,
getattr(obj, c + "_basis"),
derivs=derivs[c],
build=True,
method=method,
)
elif c == "B":
transforms["B"] = Transform(
grid,
DoubleFourierSeries(
M=kwargs.get("M_booz", 2 * obj.M),
N=kwargs.get("N_booz", 2 * obj.N),
NFP=obj.NFP,
sym=obj.R_basis.sym,
),
derivs=derivs["B"],
build=True,
build_pinv=True,
method=method,
)
elif c == "w":
transforms["w"] = Transform(
grid,
DoubleFourierSeries(
M=kwargs.get("M_booz", 2 * obj.M),
N=kwargs.get("N_booz", 2 * obj.N),
NFP=obj.NFP,
sym=obj.Z_basis.sym,
),
derivs=derivs["w"],
build=True,
build_pinv=True,
method=method,
)
elif c not in transforms:
transforms[c] = getattr(obj, c)
return transforms
def has_dependencies(parameterization, qty, params, transforms, profiles, data):
"""Determine if we have the ingredients needed to compute qty.
Parameters
----------
parameterization : str or class
Type of thing we're checking dependencies for. eg desc.equilibrium.Equilibrium
qty : str
Name of something from the data index.
params : dict of ndarray
Dictionary of parameters we have.
transforms : dict of Transform
Dictionary of transforms we have.
profiles : dict of Profile
Dictionary of profiles we have.
data : dict of ndarray
Dictionary of what we've computed so far.
Returns
-------
has_dependencies : bool
Whether we have what we need.
"""
return (
_has_data(qty, data, parameterization)
and (
not transforms["grid"].axis.size
or _has_axis_limit_data(qty, data, parameterization)
)
and _has_params(qty, params, parameterization)
and _has_profiles(qty, profiles, parameterization)
and _has_transforms(qty, transforms, parameterization)
)
def _has_data(qty, data, parameterization):
p = _parse_parameterization(parameterization)
deps = data_index[p][qty]["dependencies"]["data"]
return all(d in data for d in deps)
def _has_axis_limit_data(qty, data, parameterization):
p = _parse_parameterization(parameterization)
deps = data_index[p][qty]["dependencies"]["axis_limit_data"]
return all(d in data for d in deps)
def _has_params(qty, params, parameterization):
p = _parse_parameterization(parameterization)
deps = data_index[p][qty]["dependencies"]["params"]
return all(d in params for d in deps)
def _has_profiles(qty, profiles, parameterization):
p = _parse_parameterization(parameterization)
deps = data_index[p][qty]["dependencies"]["profiles"]
return all(d in profiles for d in deps)
def _has_transforms(qty, transforms, parameterization):
p = _parse_parameterization(parameterization)
flags = {}
derivs = data_index[p][qty]["dependencies"]["transforms"]
for key in derivs.keys():
if key not in transforms:
return False
else:
flags[key] = np.array(
[d in transforms[key].derivatives.tolist() for d in derivs[key]]
).all()
return all(flags.values())
def dot(a, b, axis=-1):
"""Batched vector dot product.
Parameters
----------
a : array-like
First array of vectors.
b : array-like
Second array of vectors.
axis : int
Axis along which vectors are stored.
Returns
-------
y : array-like
y = sum(a*b, axis=axis)
"""
return jnp.sum(a * b, axis=axis, keepdims=False)
def cross(a, b, axis=-1):
"""Batched vector cross product.
Parameters
----------
a : array-like
First array of vectors.
b : array-like
Second array of vectors.
axis : int
Axis along which vectors are stored.
Returns
-------
y : array-like
y = a x b
"""
return jnp.cross(a, b, axis=axis)
def safenorm(x, ord=None, axis=None, fill=0, threshold=0):
"""Like jnp.linalg.norm, but without nan gradient at x=0.
Parameters
----------
x : ndarray
Vector or array to norm.
ord : {non-zero int, inf, -inf, ‘fro’, ‘nuc’}, optional
Order of norm.
axis : {None, int, 2-tuple of ints}, optional
Axis to take norm along.
fill : float, ndarray, optional
Value to return where x is zero.
threshold : float >= 0
How small is x allowed to be.
"""
is_zero = (jnp.abs(x) <= threshold).all(axis=axis, keepdims=True)
x = jnp.where(is_zero, jnp.ones_like(x), x) # replace x with ones if is_zero
n = jnp.linalg.norm(x, ord=ord, axis=axis)
n = jnp.where(is_zero.squeeze(), fill, n) # replace norm with zero if is_zero
return n
def safediv(a, b, fill=0, threshold=0):
"""Divide a/b with guards for division by zero.
Parameters
----------
a, b : ndarray
Numerator and denominator.
fill : float, ndarray, optional
Value to return where b is zero.
threshold : float >= 0
How small is b allowed to be.
"""
mask = jnp.abs(b) <= threshold
num = jnp.where(mask, fill, a)
den = jnp.where(mask, 1, b)
return num / den
def cumtrapz(y, x=None, dx=1.0, axis=-1, initial=None):
"""Cumulatively integrate y(x) using the composite trapezoidal rule.
Taken from SciPy, but changed NumPy references to JAX.NumPy:
https://github.com/scipy/scipy/blob/v1.10.1/scipy/integrate/_quadrature.py
Parameters
----------
y : array_like
Values to integrate.
x : array_like, optional
The coordinate to integrate along. If None (default), use spacing `dx`
between consecutive elements in `y`.
dx : float, optional
Spacing between elements of `y`. Only used if `x` is None.
axis : int, optional
Specifies the axis to cumulate. Default is -1 (last axis).
initial : scalar, optional
If given, insert this value at the beginning of the returned result.
Typically, this value should be 0. Default is None, which means no
value at ``x[0]`` is returned and `res` has one element less than `y`
along the axis of integration.
Returns
-------
res : ndarray
The result of cumulative integration of `y` along `axis`.
If `initial` is None, the shape is such that the axis of integration
has one less value than `y`. If `initial` is given, the shape is equal
to that of `y`.
"""
y = jnp.asarray(y)
if x is None:
d = dx
else:
x = jnp.asarray(x)
if x.ndim == 1:
d = jnp.diff(x)
# reshape to correct shape
shape = [1] * y.ndim
shape[axis] = -1
d = d.reshape(shape)
elif len(x.shape) != len(y.shape):
raise ValueError("If given, shape of x must be 1-D or the " "same as y.")
else:
d = jnp.diff(x, axis=axis)
if d.shape[axis] != y.shape[axis] - 1:
raise ValueError(
"If given, length of x along axis must be the " "same as y."
)
def tupleset(t, i, value):
l = list(t)
l[i] = value
return tuple(l)
nd = len(y.shape)
slice1 = tupleset((slice(None),) * nd, axis, slice(1, None))
slice2 = tupleset((slice(None),) * nd, axis, slice(None, -1))
res = jnp.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)
if initial is not None:
if not jnp.isscalar(initial):
raise ValueError("`initial` parameter should be a scalar.")
shape = list(res.shape)
shape[axis] = 1
res = jnp.concatenate(
[jnp.full(shape, initial, dtype=res.dtype), res], axis=axis
)
return res
def _get_grid_surface(grid, surface_label):
"""Return grid quantities associated with the given surface label.
Parameters
----------
grid : Grid
Collocation grid containing the nodes to evaluate at.
surface_label : str
The surface label of rho, theta, or zeta.
Returns
-------
unique_size : int
The number of the unique values of the surface_label.
inverse_idx : ndarray
Indexing array to go from unique values to full grid.
spacing : ndarray
The relevant columns of grid.spacing.
has_endpoint_dupe : bool
Whether this surface label's nodes have a duplicate at the endpoint
of a periodic domain. (e.g. a node at 0 and 2π).
"""
assert surface_label in {"rho", "theta", "zeta"}
if surface_label == "rho":
unique_size = grid.num_rho
inverse_idx = grid.inverse_rho_idx
spacing = grid.spacing[:, 1:]
has_endpoint_dupe = False
elif surface_label == "theta":
unique_size = grid.num_theta
inverse_idx = grid.inverse_theta_idx
spacing = grid.spacing[:, [0, 2]]
has_endpoint_dupe = (grid.nodes[grid.unique_theta_idx[0], 1] == 0) & (
grid.nodes[grid.unique_theta_idx[-1], 1] == 2 * np.pi
)
else:
unique_size = grid.num_zeta
inverse_idx = grid.inverse_zeta_idx
spacing = grid.spacing[:, :2]
has_endpoint_dupe = (grid.nodes[grid.unique_zeta_idx[0], 2] == 0) & (
grid.nodes[grid.unique_zeta_idx[-1], 2] == 2 * np.pi / grid.NFP
)
return unique_size, inverse_idx, spacing, has_endpoint_dupe
def line_integrals(
grid,
q=jnp.array([1.0]),
line_label="theta",
fix_surface=("rho", 1.0),
expand_out=True,
):
"""Compute line integrals over curves covering the given surface.
As an example, by specifying the combination of ``line_label="theta"`` and
``fix_surface=("rho", 1.0)``, the intention is to integrate along the
outermost perimeter of a particular zeta surface (toroidal cross-section),
for each zeta surface in the grid.
Notes
-----
It is assumed that the integration curve has length 1 when the line
label is rho and length 2π when the line label is theta or zeta.
You may want to multiply the input by the line length Jacobian.
Correctness is not guaranteed on grids with duplicate nodes.
An attempt to print a warning is made if the given grid has duplicate
nodes and is one of the predefined grid types
(``Linear``, ``Concentric``, ``Quadrature``).
If the grid is custom, no attempt is made to warn.
Parameters
----------
grid : Grid
Collocation grid containing the nodes to evaluate at.
q : ndarray
Quantity to integrate.
The first dimension of the array should have size ``grid.num_nodes``.
When ``q`` is 1-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a scalar function over the previously mentioned domain.
When ``q`` is 2-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a vector-valued function over the previously mentioned domain.
When ``q`` is 3-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a matrix-valued function over the previously mentioned domain.
line_label : str
The coordinate curve to compute the integration over.
To clarify, a theta (poloidal) curve is the intersection of a
rho surface (flux surface) and zeta (toroidal) surface.
fix_surface : str, float
A tuple of the form: label, value.
``fix_surface`` label should differ from ``line_label``.
By default, ``fix_surface`` is chosen to be the flux surface at rho=1.
expand_out : bool
Whether to expand the output array so that the output has the same
shape as the input. Defaults to true so that the output may be
broadcast in the same way as the input. Setting to false will save
memory.
Returns
-------
integrals : ndarray
Line integrals of the input over curves covering the given surface.
By default, the returned array has the same shape as the input.
"""
assert (
line_label != fix_surface[0]
), "There is no valid use for this combination of inputs."
assert line_label == "theta" or not isinstance(
grid, ConcentricGrid
), "ConcentricGrid should only be used for theta line integrals."
if isinstance(grid, LinearGrid) and grid.endpoint:
warnings.warn(
colored(
"Correctness not guaranteed on grids with duplicate nodes.", "yellow"
)
)
# Generate a new quantity q_prime which is zero everywhere
# except on the fixed surface, on which q_prime takes the value of q.
# Then forward the computation to surface_integrals().
# The differential element of the line integral, denoted dl,
# should correspond to the line label's spacing.
# The differential element of the surface integral is
# ds = dl * fix_surface_dl, so we scale q_prime by 1 / fix_surface_dl.
labels = {"rho": 0, "theta": 1, "zeta": 2}
column_id = labels[fix_surface[0]]
mask = grid.nodes[:, column_id] == fix_surface[1]
q_prime = (mask * jnp.atleast_1d(q).T / grid.spacing[:, column_id]).T
(surface_label,) = labels.keys() - {line_label, fix_surface[0]}
return surface_integrals(grid, q_prime, surface_label, expand_out)
def surface_integrals(grid, q=jnp.array([1.0]), surface_label="rho", expand_out=True):
"""Compute a surface integral for each surface in the grid.
Notes
-----
It is assumed that the integration surface has area 4π² when the
surface label is rho and area 2π when the surface label is theta or
zeta. You may want to multiply the input by the surface area Jacobian.
Parameters
----------
grid : Grid
Collocation grid containing the nodes to evaluate at.
q : ndarray
Quantity to integrate.
The first dimension of the array should have size ``grid.num_nodes``.
When ``q`` is 1-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a scalar function over the previously mentioned domain.
When ``q`` is 2-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a vector-valued function over the previously mentioned domain.
When ``q`` is 3-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a matrix-valued function over the previously mentioned domain.
surface_label : str
The surface label of rho, theta, or zeta to compute the integration over.
expand_out : bool
Whether to expand the output array so that the output has the same
shape as the input. Defaults to true so that the output may be
broadcast in the same way as the input. Setting to false will save
memory.
Returns
-------
integrals : ndarray
Surface integral of the input over each surface in the grid.
By default, the returned array has the same shape as the input.
"""
return surface_integrals_map(grid, surface_label, expand_out)(q)
def surface_integrals_map(grid, surface_label="rho", expand_out=True):
"""Returns a method to compute any surface integral for each surface in the grid.
Parameters
----------
grid : Grid
Collocation grid containing the nodes to evaluate at.
surface_label : str
The surface label of rho, theta, or zeta to compute the integration over.
expand_out : bool
Whether to expand the output array so that the output has the same
shape as the input. Defaults to true so that the output may be
broadcast in the same way as the input. Setting to false will save
memory.
Returns
-------
function : callable
Method to compute any surface integral of the input ``q`` over each
surface in the grid with code: ``function(q)``.
"""
if surface_label == "theta" and isinstance(grid, ConcentricGrid):
warnings.warn(
colored(
"Integrals over constant theta surfaces are poorly defined for "
+ "ConcentricGrid.",
"yellow",
)
)
unique_size, inverse_idx, spacing, has_endpoint_dupe = _get_grid_surface(
grid, surface_label
)
# Todo: Define masks as a sparse matrix once sparse matrices are no longer
# experimental in jax.
# The ith row of masks is True only at the indices which correspond to the
# ith surface. The integral over the ith surface is the dot product of the
# ith row vector and the vector of integrands of all surfaces.
masks = inverse_idx == jnp.arange(unique_size)[:, jnp.newaxis]
# Imagine a torus cross-section at zeta=π.
# A grid with a duplicate zeta=π node has 2 of those cross-sections.
# In grid.py, we multiply by 1/n the areas of surfaces with
# duplicity n. This prevents the area of that surface from being
# double-counted, as surfaces with the same node value are combined
# into 1 integral, which sums their areas. Thus, if the zeta=π
# cross-section has duplicity 2, we ensure that the area on the zeta=π
# surface will have the correct total area of π+π = 2π.
# An edge case exists if the duplicate surface has nodes with
# different values for the surface label, which only occurs when
# has_endpoint_dupe is true. If ``has_endpoint_dupe`` is true, this grid
# has a duplicate surface at surface_label=0 and
# surface_label=max surface value. Although the modulo of these values
# are equal, their numeric values are not, so the integration
# would treat them as different surfaces. We solve this issue by
# combining the indices corresponding to the integrands of the duplicated
# surface, so that the duplicate surface is treated as one, like in the
# previous paragraph.
masks = cond(
has_endpoint_dupe,
lambda _: put(masks, jnp.array([0, -1]), masks[0] | masks[-1]),
lambda _: masks,
operand=None,
)
spacing = jnp.prod(spacing, axis=1)
def _surface_integrals(q=jnp.array([1.0])):
"""Compute a surface integral for each surface in the grid.
Notes
-----
It is assumed that the integration surface has area 4π² when the
surface label is rho and area 2π when the surface label is theta or
zeta. You may want to multiply the input by the surface area Jacobian.
Parameters
----------
q : ndarray
Quantity to integrate.
The first dimension of the array should have size ``grid.num_nodes``.
When ``q`` is 1-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a scalar function over the previously mentioned domain.
When ``q`` is 2-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a vector-valued function over the previously mentioned domain.
When ``q`` is 3-dimensional, the intention is to integrate,
over the domain parameterized by rho, theta, and zeta,
a matrix-valued function over the previously mentioned domain.
Returns
-------
integrals : ndarray
Surface integral of the input over each surface in the grid.
"""
axis_to_move = (jnp.ndim(q) == 3) * 2
integrands = (spacing * jnp.nan_to_num(q).T).T
# `integrands` may have shape (g.size, f.size, v.size), where
# g is the grid function depending on the integration variables
# f is a function which may be independent of the integration variables
# v is the vector of components of f (or g).
# The intention is to integrate `integrands` which is a
# vector-valued (with v.size components)
# function-valued (with image size of f.size)
# function over the grid (with domain size of g.size = grid.num_nodes)
# over each surface in the grid.
# The distinction between f and v is semantic.
# We may alternatively consider an `integrands` of shape (g.size, f.size) to
# represent a vector-valued (with f.size components) function over the grid.
# Likewise, we may alternatively consider an `integrands` of shape
# (g.size, v.size) to represent a function-valued (with image size v.size)
# function over the grid. When `integrands` has dimension one, it is a
# scalar function over the grid. That is, a
# vector-valued (with 1 component),
# function-valued (with image size of 1)
# function over the grid (with domain size of g.size = grid.num_nodes)
# The integration is performed by applying `masks`, the surface
# integral operator, to `integrands`. This operator hits the matrix formed
# by the last two dimensions of `integrands`, for every element along the
# previous dimension of `integrands`. Therefore, when `integrands` has three
# dimensions, the second must hold g. We may choose which of the first and
# third dimensions hold f and v. The choice below transposes `integrands` to
# shape (v.size, g.size, f.size). As we expect f.size >> v.size, the
# integration is in theory faster since numpy optimizes large matrix
# products. However, timing results showed no difference.
integrals = jnp.moveaxis(
masks @ jnp.moveaxis(integrands, axis_to_move, 0), 0, axis_to_move
)
return grid.expand(integrals, surface_label) if expand_out else integrals
return _surface_integrals
def surface_averages(
grid,
q,
sqrt_g=jnp.array([1.0]),
surface_label="rho",
denominator=None,
expand_out=True,
):
"""Compute a surface average for each surface in the grid.
Notes
-----
Implements the flux-surface average formula given by equation 4.9.11 in
W.D. D'haeseleer et al. (1991) doi:10.1007/978-3-642-75595-8.
Parameters
----------
grid : Grid
Collocation grid containing the nodes to evaluate at.
q : ndarray
Quantity to average.
The first dimension of the array should have size ``grid.num_nodes``.
When ``q`` is 1-dimensional, the intention is to average,
over the domain parameterized by rho, theta, and zeta,
a scalar function over the previously mentioned domain.
When ``q`` is 2-dimensional, the intention is to average,
over the domain parameterized by rho, theta, and zeta,
a vector-valued function over the previously mentioned domain.
When ``q`` is 3-dimensional, the intention is to average,
over the domain parameterized by rho, theta, and zeta,
a matrix-valued function over the previously mentioned domain.
sqrt_g : ndarray
Coordinate system Jacobian determinant; see ``data_index["sqrt(g)"]``.
surface_label : str
The surface label of rho, theta, or zeta to compute the average over.
denominator : ndarray
By default, the denominator is computed as the surface integral of
``sqrt_g``. This parameter can optionally be supplied to avoid
redundant computations or to use a different denominator to compute
the average. This array should broadcast with arrays of size
``grid.num_nodes`` (``grid.num_surface_label``) if ``expand_out``
is true (false).
expand_out : bool
Whether to expand the output array so that the output has the same
shape as the input. Defaults to true so that the output may be
broadcast in the same way as the input. Setting to false will save
memory.
Returns
-------
averages : ndarray
Surface average of the input over each surface in the grid.
By default, the returned array has the same shape as the input.
"""
return surface_averages_map(grid, surface_label, expand_out)(q, sqrt_g, denominator)
def surface_averages_map(grid, surface_label="rho", expand_out=True):
"""Returns a method to compute any surface average for each surface in the grid.
Parameters
----------
grid : Grid