-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy path_omnigenity.py
More file actions
997 lines (867 loc) · 31.9 KB
/
Copy path_omnigenity.py
File metadata and controls
997 lines (867 loc) · 31.9 KB
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
"""Objectives for targeting quasisymmetry."""
import warnings
from desc.backend import jnp
from desc.batching import vmap_chunked
from desc.compute import get_profiles, get_transforms
from desc.compute._omnigenity import _omnigenity_mapping
from desc.compute.utils import _compute as compute_fun
from desc.grid import LinearGrid
from desc.utils import Timer, errorif, warnif
from desc.vmec_utils import ptolemy_linear_transform
from .normalization import compute_scaling_factors
from .objective_funs import _Objective, collect_docs
class QuasisymmetryBoozer(_Objective):
"""Quasi-symmetry Boozer harmonics error.
Parameters
----------
eq : Equilibrium
Equilibrium that will be optimized to satisfy the Objective.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
Must be a LinearGrid with sym=False.
Defaults to ``LinearGrid(M=M_booz, N=N_booz)``.
helicity : tuple, optional
Type of quasi-symmetry (M, N). Default = quasi-axisymmetry (1, 0).
M_booz : int, optional
Poloidal resolution of Boozer transformation. Default = 2 * eq.M.
N_booz : int, optional
Toroidal resolution of Boozer transformation. Default = 2 * eq.N.
surf_batch_size: int
Number of flux surfaces to compute simultaneously. Defaults to
computing all flux surfaces simultaneously. Decrease to reduce
memory required for computation.
"""
__doc__ = __doc__.rstrip() + collect_docs(
target_default="``target=0``.", bounds_default="``target=0``."
)
_units = "(T)"
_print_value_fmt = "Quasi-symmetry Boozer error: "
_static_attrs = _Objective._static_attrs + ["_helicity"]
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
helicity=(1, 0),
M_booz=None,
N_booz=None,
name="QS Boozer",
jac_chunk_size=None,
surf_batch_size=None,
):
if target is None and bounds is None:
target = 0
self._grid = grid
self.helicity = helicity
self.M_booz = M_booz
self.N_booz = N_booz
self.surf_batch_size = surf_batch_size
super().__init__(
things=eq,
target=target,
bounds=bounds,
weight=weight,
normalize=normalize,
normalize_target=normalize_target,
loss_function=loss_function,
deriv_mode=deriv_mode,
name=name,
jac_chunk_size=jac_chunk_size,
)
self._print_value_fmt = "Quasi-symmetry ({},{}) Boozer error: ".format(
self.helicity[0], self.helicity[1]
)
def build(self, use_jit=True, verbose=1):
"""Build constant arrays.
Parameters
----------
use_jit : bool, optional
Whether to just-in-time compile the objective and derivatives.
verbose : int, optional
Level of output.
"""
eq = self.things[0]
M_booz = self.M_booz or 2 * eq.M
N_booz = self.N_booz or 2 * eq.N
if self._grid is None:
grid = LinearGrid(M=2 * M_booz, N=2 * N_booz, NFP=eq.NFP, sym=False)
else:
grid = self._grid
errorif(grid.sym, ValueError, "QuasisymmetryBoozer grid must be non-symmetric")
warnif(
grid.num_theta < 2 * eq.M,
RuntimeWarning,
"QuasisymmetryBoozer objective grid requires poloidal "
"resolution for surface averages",
)
warnif(
grid.num_zeta < 2 * eq.N,
RuntimeWarning,
"QuasisymmetryBoozer objective grid requires toroidal "
"resolution for surface averages",
)
self._data_keys = ["|B|_mn_B"]
timer = Timer()
if verbose > 0:
print("Precomputing transforms")
timer.start("Precomputing transforms")
profiles = get_profiles(self._data_keys, obj=eq, grid=grid)
transforms = get_transforms(
self._data_keys,
obj=eq,
grid=grid,
M_booz=M_booz,
N_booz=N_booz,
)
matrix, _, idx = ptolemy_linear_transform(
transforms["B"].basis.modes,
helicity=self.helicity,
NFP=transforms["B"].basis.NFP,
)
self._constants = {
"transforms": transforms,
"profiles": profiles,
"matrix": matrix,
"idx": idx,
"surf_batch_size": self.surf_batch_size,
}
timer.stop("Precomputing transforms")
if verbose > 1:
timer.disp("Precomputing transforms")
self._dim_f = idx.size * grid.num_rho
if self._normalize:
scales = compute_scaling_factors(eq)
self._normalization = scales["B"]
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params, constants=None):
"""Compute quasi-symmetry Boozer harmonics error.
Parameters
----------
params : dict
Dictionary of equilibrium degrees of freedom, eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants. (Deprecated)
Returns
-------
f : ndarray
Symmetry breaking harmonics of B (T).
"""
constants = self._get_deprecated_constants(constants)
data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
surf_batch_size=constants["surf_batch_size"],
)
B_mn = data["|B|_mn_B"].reshape((constants["transforms"]["grid"].num_rho, -1))
B_mn = constants["matrix"] @ B_mn.T
# output order = (rho, mn).flatten(), ie all the surfaces concatenated
# one after the other
return B_mn[constants["idx"]].T.flatten()
@property
def helicity(self):
"""tuple: Type of quasi-symmetry (M, N)."""
return self._helicity
@helicity.setter
def helicity(self, helicity):
assert (
(len(helicity) == 2)
and (int(helicity[0]) == helicity[0])
and (int(helicity[1]) == helicity[1])
)
if hasattr(self, "_helicity") and self._helicity != helicity:
self._built = False
warnings.warn("Re-build objective after changing the helicity!")
self._helicity = helicity
if hasattr(self, "_print_value_fmt"):
self._print_value_fmt = "Quasi-symmetry ({},{}) Boozer error: ".format(
self.helicity[0], self.helicity[1]
)
class QuasisymmetryTwoTerm(_Objective):
"""Quasi-symmetry two-term error.
Parameters
----------
eq : Equilibrium
Equilibrium that will be optimized to satisfy the Objective.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
Defaults to ``LinearGrid(M=eq.M_grid, N=eq.N_grid)``.
helicity : tuple, optional
Type of quasi-symmetry (M, N).
"""
__doc__ = __doc__.rstrip() + collect_docs(
target_default="``target=0``.", bounds_default="``target=0``."
)
_coordinates = "rtz"
_units = "(T^3)"
_print_value_fmt = "Quasi-symmetry two-term error: "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
helicity=(1, 0),
name="QS two-term",
jac_chunk_size=None,
):
if target is None and bounds is None:
target = 0
self._grid = grid
self.helicity = helicity
super().__init__(
things=eq,
target=target,
bounds=bounds,
weight=weight,
normalize=normalize,
normalize_target=normalize_target,
loss_function=loss_function,
deriv_mode=deriv_mode,
name=name,
jac_chunk_size=jac_chunk_size,
)
self._print_value_fmt = "Quasi-symmetry ({},{}) two-term error: ".format(
self.helicity[0], self.helicity[1]
)
def build(self, use_jit=True, verbose=1):
"""Build constant arrays.
Parameters
----------
use_jit : bool, optional
Whether to just-in-time compile the objective and derivatives.
verbose : int, optional
Level of output.
"""
eq = self.things[0]
if self._grid is None:
grid = LinearGrid(M=eq.M_grid, N=eq.N_grid, NFP=eq.NFP, sym=eq.sym)
else:
grid = self._grid
warnif(
(grid.num_theta * (1 + eq.sym)) < 2 * eq.M,
RuntimeWarning,
"QuasisymmetryTwoTerm objective grid requires poloidal "
"resolution for surface averages",
)
warnif(
grid.num_zeta < 2 * eq.N,
RuntimeWarning,
"QuasisymmetryTwoTerm objective grid requires toroidal "
"resolution for surface averages",
)
self._dim_f = grid.num_nodes
self._data_keys = ["f_C"]
timer = Timer()
if verbose > 0:
print("Precomputing transforms")
timer.start("Precomputing transforms")
profiles = get_profiles(self._data_keys, obj=eq, grid=grid)
transforms = get_transforms(self._data_keys, obj=eq, grid=grid)
self._constants = {
"transforms": transforms,
"profiles": profiles,
"helicity": self.helicity,
}
timer.stop("Precomputing transforms")
if verbose > 1:
timer.disp("Precomputing transforms")
if self._normalize:
scales = compute_scaling_factors(eq)
self._normalization = scales["B"] ** 3
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params, constants=None):
"""Compute quasi-symmetry two-term errors.
Parameters
----------
params : dict
Dictionary of equilibrium degrees of freedom, eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants. (Deprecated)
Returns
-------
f : ndarray
Quasi-symmetry flux function error at each node (T^3).
"""
constants = self._get_deprecated_constants(constants)
data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
helicity=constants["helicity"],
)
return data["f_C"]
@property
def helicity(self):
"""tuple: Type of quasi-symmetry (M, N)."""
return self._helicity
@helicity.setter
def helicity(self, helicity):
assert (
(len(helicity) == 2)
and (int(helicity[0]) == helicity[0])
and (int(helicity[1]) == helicity[1])
)
if hasattr(self, "_helicity") and self._helicity != helicity:
self._built = False
self._helicity = helicity
if hasattr(self, "_print_value_fmt"):
self._print_value_fmt = "Quasi-symmetry ({},{}) error: ".format(
self.helicity[0], self.helicity[1]
)
class QuasisymmetryTripleProduct(_Objective):
"""Quasi-symmetry triple product error.
Parameters
----------
eq : Equilibrium
Equilibrium that will be optimized to satisfy the Objective.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
Defaults to ``LinearGrid(M=eq.M_grid, N=eq.N_grid)``.
"""
__doc__ = __doc__.rstrip() + collect_docs(
target_default="``target=0``.", bounds_default="``target=0``."
)
_coordinates = "rtz"
_units = "(T^4/m^2)"
_print_value_fmt = "Quasi-symmetry error: "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
name="QS triple product",
jac_chunk_size=None,
):
if target is None and bounds is None:
target = 0
self._grid = grid
super().__init__(
things=eq,
target=target,
bounds=bounds,
weight=weight,
normalize=normalize,
normalize_target=normalize_target,
loss_function=loss_function,
deriv_mode=deriv_mode,
name=name,
jac_chunk_size=jac_chunk_size,
)
def build(self, use_jit=True, verbose=1):
"""Build constant arrays.
Parameters
----------
use_jit : bool, optional
Whether to just-in-time compile the objective and derivatives.
verbose : int, optional
Level of output.
"""
eq = self.things[0]
if self._grid is None:
grid = LinearGrid(M=eq.M_grid, N=eq.N_grid, NFP=eq.NFP, sym=eq.sym)
else:
grid = self._grid
self._dim_f = grid.num_nodes
self._data_keys = ["f_T"]
timer = Timer()
if verbose > 0:
print("Precomputing transforms")
timer.start("Precomputing transforms")
profiles = get_profiles(self._data_keys, obj=eq, grid=grid)
transforms = get_transforms(self._data_keys, obj=eq, grid=grid)
self._constants = {
"transforms": transforms,
"profiles": profiles,
}
timer.stop("Precomputing transforms")
if verbose > 1:
timer.disp("Precomputing transforms")
if self._normalize:
scales = compute_scaling_factors(eq)
self._normalization = scales["B"] ** 4 / scales["a"] ** 2
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params, constants=None):
"""Compute quasi-symmetry triple product errors.
Parameters
----------
params : dict
Dictionary of equilibrium degrees of freedom, eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants. (Deprecated)
Returns
-------
f : ndarray
Quasi-symmetry flux function error at each node (T^4/m^2).
"""
constants = self._get_deprecated_constants(constants)
data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
)
return data["f_T"]
class Omnigenity(_Objective):
"""Omnigenity error.
Errors are relative to a target field that is perfectly omnigenous,
and are computed on a collocation grid in (ρ,η,α) coordinates.
This objective assumes that the collocation point (θ=0,ζ=0) lies on the contour of
maximum field strength ||B||=B_max.
Parameters
----------
eq : Equilibrium
Equilibrium to be optimized to satisfy the Objective.
field : OmnigenousField
Omnigenous magnetic field to be optimized to satisfy the Objective.
eq_grid : Grid, optional
Collocation grid containing the nodes to evaluate at for equilibrium data.
Defaults to a linearly space grid on the rho=1 surface.
Must be without stellarator symmetry.
field_grid : Grid, optional
Collocation grid containing the nodes to evaluate at for omnigenous field data.
The grid nodes are given in the usual (ρ,θ,ζ) coordinates (with θ ∈ [0, 2π),
ζ ∈ [0, 2π/NFP)), but θ is mapped to η and ζ is mapped to α. Defaults to a
linearly space grid on the rho=1 surface. Must be without stellarator symmetry.
M_booz : int, optional
Poloidal resolution of Boozer transformation. Default = 2 * eq.M.
N_booz : int, optional
Toroidal resolution of Boozer transformation. Default = 2 * eq.N.
eta_weight : float, optional
Magnitude of relative weight as a function of η:
w(η) = (`eta_weight` + 1) / 2 + (`eta_weight` - 1) / 2 * cos(η)
Default value of 1 weights all nodes equally.
eq_fixed: bool, optional
Whether the Equilibrium `eq` is fixed or not.
If True, the equilibrium is fixed and its values are precomputed, which saves on
computation time during optimization and only ``field`` is allowed to change.
If False, the equilibrium is allowed to change during the optimization and its
associated data are re-computed at every iteration (Default).
field_fixed: bool, optional
Whether the OmnigenousField `field` is fixed or not.
If True, the field is fixed and its values are precomputed, which saves on
computation time during optimization and only ``eq`` is allowed to change.
If False, the field is allowed to change during the optimization and its
associated data are re-computed at every iteration (Default).
surf_batch_size: int
Number of flux surfaces to compute simultaneously. Defaults to
computing all flux surfaces simultaneously. Decrease to reduce
memory required for computation.
"""
__doc__ = __doc__.rstrip() + collect_docs(
target_default="``target=0``.", bounds_default="``target=0``."
)
_static_attrs = _Objective._static_attrs + [
"_eq_data_keys",
"_eq_fixed",
"_field_data_keys",
"_field_fixed",
"_helicity",
]
_coordinates = "rtz"
_units = "(T)"
_print_value_fmt = "Omnigenity error: "
def __init__(
self,
eq,
field,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
eq_grid=None,
field_grid=None,
M_booz=None,
N_booz=None,
eta_weight=1,
eq_fixed=False,
field_fixed=False,
name="omnigenity",
jac_chunk_size=None,
surf_batch_size=None,
):
if target is None and bounds is None:
target = 0
self._eq = eq
self._field = field
self._eq_grid = eq_grid
self._field_grid = field_grid
self.helicity = field.helicity
self.M_booz = M_booz
self.N_booz = N_booz
self.eta_weight = eta_weight
self._eq_fixed = eq_fixed
self._field_fixed = field_fixed
self._surf_batch_size = surf_batch_size
if not eq_fixed and not field_fixed:
things = [eq, field]
elif eq_fixed and not field_fixed:
things = [field]
elif field_fixed and not eq_fixed:
things = [eq]
else:
raise ValueError("Cannot fix both the eq and field.")
super().__init__(
things=things,
target=target,
bounds=bounds,
weight=weight,
normalize=normalize,
normalize_target=normalize_target,
loss_function=loss_function,
deriv_mode=deriv_mode,
name=name,
jac_chunk_size=jac_chunk_size,
)
def build(self, use_jit=True, verbose=1):
"""Build constant arrays.
Parameters
----------
use_jit : bool, optional
Whether to just-in-time compile the objective and derivatives.
verbose : int, optional
Level of output.
"""
if self._eq_fixed:
eq = self._eq
field = self.things[0]
elif self._field_fixed:
eq = self.things[0]
field = self._field
else:
eq = self.things[0]
field = self.things[1]
M_booz = self.M_booz or 2 * eq.M
N_booz = self.N_booz or 2 * eq.N
# default grids
if self._eq_grid is None and self._field_grid is not None:
rho = self._field_grid.nodes[self._field_grid.unique_rho_idx, 0]
elif self._eq_grid is not None and self._field_grid is None:
rho = self._eq_grid.nodes[self._eq_grid.unique_rho_idx, 0]
elif self._eq_grid is None and self._field_grid is None:
rho = 1.0
if self._eq_grid is None:
eq_grid = LinearGrid(
rho=rho, M=2 * M_booz, N=2 * N_booz, NFP=eq.NFP, sym=False
)
else:
eq_grid = self._eq_grid
if self._field_grid is None:
field_grid = LinearGrid(
rho=rho, theta=2 * field.M_B, N=2 * field.N_x, NFP=field.NFP, sym=False
)
else:
field_grid = self._field_grid
self._dim_f = field_grid.num_nodes
self._eq_data_keys = ["|B|_mn_B"]
self._field_data_keys = ["|B|", "theta_B", "zeta_B"]
errorif(
eq_grid.NFP != field_grid.NFP,
msg="eq_grid and field_grid must have the same number of field periods",
)
errorif(eq_grid.sym, msg="eq_grid must not be symmetric")
errorif(field_grid.sym, msg="field_grid must not be symmetric")
field_rho = field_grid.nodes[field_grid.unique_rho_idx, 0]
eq_rho = eq_grid.nodes[eq_grid.unique_rho_idx, 0]
errorif(
any(eq_rho != field_rho),
msg="eq_grid and field_grid must be the same surface(s), "
+ f"eq_grid has surfaces {eq_rho}, "
+ f"field_grid has surfaces {field_rho}",
)
errorif(
jnp.any(field.B_lm[: field.M_B] < 0),
msg="|B| on axis must be positive! Check B_lm input.",
)
timer = Timer()
if verbose > 0:
print("Precomputing transforms")
timer.start("Precomputing transforms")
profiles = get_profiles(self._eq_data_keys, obj=eq, grid=eq_grid)
eq_transforms = get_transforms(
self._eq_data_keys,
obj=eq,
grid=eq_grid,
M_booz=M_booz,
N_booz=N_booz,
)
field_transforms = get_transforms(
self._field_data_keys,
obj=field,
grid=field_grid,
)
# compute returns points on the grid of the field (dim_f = field_grid.num_nodes)
# so set quad_weights to the field grid
# to avoid it being incorrectly set in the super build
w = field_grid.weights
w *= jnp.sqrt(field_grid.num_nodes)
self._constants = {
"eq_profiles": profiles,
"eq_transforms": eq_transforms,
"field_transforms": field_transforms,
"quad_weights": w,
"helicity": self.helicity,
"surf_batch_size": self._surf_batch_size,
}
if self._eq_fixed:
# precompute the eq data since it is fixed during the optimization
eq_data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._eq_data_keys,
params=self._eq.params_dict,
transforms=self._constants["eq_transforms"],
profiles=self._constants["eq_profiles"],
surf_batch_size=self._surf_batch_size,
)
self._constants["eq_data"] = eq_data
if self._field_fixed:
# precompute the field data since it is fixed during the optimization
field_data = compute_fun(
"desc.magnetic_fields._core.OmnigenousField",
self._field_data_keys,
params=self._field.params_dict,
transforms=self._constants["field_transforms"],
profiles={},
helicity=self._constants["helicity"],
surf_batch_size=self._surf_batch_size,
)
self._constants["field_data"] = field_data
timer.stop("Precomputing transforms")
if verbose > 1:
timer.disp("Precomputing transforms")
if self._normalize:
# average |B| on axis
self._normalization = jnp.mean(field.B_lm[: field.M_B])
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params_1=None, params_2=None, constants=None):
"""Compute omnigenity errors.
Parameters
----------
params_1 : dict
If eq_fixed=True, dictionary of field degrees of freedom,
eg OmnigenousField.params_dict. Otherwise, dictionary of equilibrium degrees
of freedom, eg Equilibrium.params_dict.
params_2 : dict
If eq_fixed=False and field_fixed=False, dictionary of field degrees of
freedom, eg OmnigenousField.params_dict. Otherwise None.
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants. (Deprecated)
Returns
-------
omnigenity_error : ndarray
Omnigenity error at each node (T).
"""
constants = self._get_deprecated_constants(constants)
# sort parameters
if self._eq_fixed:
field_params = params_1
elif self._field_fixed:
eq_params = params_1
else:
eq_params = params_1
field_params = params_2
eq_grid = constants["eq_transforms"]["grid"]
field_grid = constants["field_transforms"]["grid"]
# compute eq data
if self._eq_fixed:
eq_data = constants["eq_data"]
else:
eq_data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._eq_data_keys,
params=eq_params,
transforms=constants["eq_transforms"],
profiles=constants["eq_profiles"],
surf_batch_size=constants["surf_batch_size"],
)
# compute field data
if self._field_fixed:
field_data = constants["field_data"]
# update theta_B and zeta_B with new iota from the equilibrium
M, N = constants["helicity"]
iota = eq_data["iota"][eq_grid.unique_rho_idx]
theta_B, zeta_B = _omnigenity_mapping(
M,
N,
iota,
field_data["alpha"],
field_data["h"],
field_grid,
)
else:
field_data = compute_fun(
"desc.magnetic_fields._core.OmnigenousField",
self._field_data_keys,
params=field_params,
transforms=constants["field_transforms"],
profiles={},
helicity=constants["helicity"],
iota=eq_data["iota"][eq_grid.unique_rho_idx],
surf_batch_size=constants["surf_batch_size"],
)
theta_B = field_data["theta_B"]
zeta_B = field_data["zeta_B"]
# additional computations that cannot be part of the regular compute API
def _compute_B_eta_alpha(theta_B, zeta_B, B_mn):
nodes = jnp.vstack(
(
jnp.zeros_like(theta_B),
theta_B,
zeta_B,
)
).T
B_eta_alpha = jnp.matmul(
constants["eq_transforms"]["B"].basis.evaluate(nodes), B_mn
)
return B_eta_alpha
theta_B = field_grid.meshgrid_reshape(theta_B, "rtz").reshape(
(field_grid.num_rho, -1)
)
zeta_B = field_grid.meshgrid_reshape(zeta_B, "rtz").reshape(
(field_grid.num_rho, -1)
)
B_mn = eq_data["|B|_mn_B"].reshape((eq_grid.num_rho, -1))
B_eta_alpha = vmap_chunked(
_compute_B_eta_alpha,
in_axes=(0, 0, 0),
chunk_size=constants["surf_batch_size"],
)(theta_B, zeta_B, B_mn)
B_eta_alpha = B_eta_alpha.reshape(
(field_grid.num_rho, field_grid.num_theta, field_grid.num_zeta)
)
B_eta_alpha = jnp.moveaxis(B_eta_alpha, 0, 1).flatten(order="F")
omnigenity_error = B_eta_alpha - field_data["|B|"]
weights = (self.eta_weight + 1) / 2 + (self.eta_weight - 1) / 2 * jnp.cos(
field_data["eta"]
)
return omnigenity_error * weights
class Isodynamicity(_Objective):
"""Isodynamicity metric for cross field transport.
Note: This is NOT the same as Quasi-isodynamicity (QI), which is a more general
condition. This specifically penalizes the local cross field transport, rather than
just the average.
Parameters
----------
eq : Equilibrium
Equilibrium that will be optimized to satisfy the Objective.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
Defaults to ``LinearGrid(M=eq.M_grid, N=eq.N_grid)``.
"""
__doc__ = __doc__.rstrip() + collect_docs(
target_default="``target=0``.", bounds_default="``target=0``."
)
_coordinates = "rtz"
_units = "(dimensionless)"
_print_value_fmt = "Isodynamicity error: "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=False,
normalize_target=False,
loss_function=None,
deriv_mode="auto",
grid=None,
name="Isodynamicity",
jac_chunk_size=None,
):
if target is None and bounds is None:
target = 0
self._grid = grid
super().__init__(
things=eq,
target=target,
bounds=bounds,
weight=weight,
normalize=normalize,
normalize_target=normalize_target,
loss_function=loss_function,
deriv_mode=deriv_mode,
name=name,
jac_chunk_size=jac_chunk_size,
)
def build(self, use_jit=True, verbose=1):
"""Build constant arrays.
Parameters
----------
use_jit : bool, optional
Whether to just-in-time compile the objective and derivatives.
verbose : int, optional
Level of output.
"""
eq = self.things[0]
if self._grid is None:
grid = LinearGrid(M=eq.M_grid, N=eq.N_grid, NFP=eq.NFP, sym=eq.sym)
else:
grid = self._grid
self._dim_f = grid.num_nodes
self._data_keys = ["isodynamicity"]
timer = Timer()
if verbose > 0:
print("Precomputing transforms")
timer.start("Precomputing transforms")
profiles = get_profiles(self._data_keys, obj=eq, grid=grid)
transforms = get_transforms(self._data_keys, obj=eq, grid=grid)
self._constants = {
"transforms": transforms,
"profiles": profiles,
}
timer.stop("Precomputing transforms")
if verbose > 1:
timer.disp("Precomputing transforms")
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params, constants=None):
"""Compute isodynamicity errors.
Parameters
----------
params : dict
Dictionary of equilibrium degrees of freedom, eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants. (Deprecated)
Returns
-------
f : ndarray
Isodynamicity error at each node (~).
"""
constants = self._get_deprecated_constants(constants)
data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
)
return data["isodynamicity"]