-
Notifications
You must be signed in to change notification settings - Fork 14
/
_geometry.py
1374 lines (1202 loc) · 47.3 KB
/
_geometry.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
"""Objectives for targeting geometrical quantities."""
import warnings
import numpy as np
from desc.backend import jnp
from desc.compute import compute as compute_fun
from desc.compute import get_profiles, get_transforms, rpz2xyz
from desc.compute.utils import safenorm
from desc.grid import LinearGrid, QuadratureGrid
from desc.utils import Timer
from .normalization import compute_scaling_factors
from .objective_funs import _Objective
from .utils import softmin
class AspectRatio(_Objective):
"""Aspect ratio = major radius / minor radius.
Parameters
----------
eq : Equilibrium or FourierRZToroidalSurface
Equilibrium or FourierRZToroidalSurface that
will be optimized to satisfy the Objective.
target : {float, ndarray}, optional
Target value(s) of the objective. Only used if bounds is None.
Must be broadcastable to Objective.dim_f.
bounds : tuple of {float, ndarray}, optional
Lower and upper bounds on the objective. Overrides target.
Both bounds must be broadcastable to to Objective.dim_f
weight : {float, ndarray}, optional
Weighting to apply to the Objective, relative to other Objectives.
Must be broadcastable to to Objective.dim_f
normalize : bool, optional
Whether to compute the error in physical units or non-dimensionalize.
Has no effect for this objective.
normalize_target : bool, optional
Whether target and bounds should be normalized before comparing to computed
values. If `normalize` is `True` and the target is in physical units,
this should also be set to True. Note: Has no effect for this objective.
loss_function : {None, 'mean', 'min', 'max'}, optional
Loss function to apply to the objective values once computed. This loss function
is called on the raw compute value, before any shifting, scaling, or
normalization. Note: Has no effect for this objective.
deriv_mode : {"auto", "fwd", "rev"}
Specify how to compute jacobian matrix, either forward mode or reverse mode AD.
"auto" selects forward or reverse mode based on the size of the input and output
of the objective. Has no effect on self.grad or self.hess which always use
reverse mode and forward over reverse mode respectively.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
name : str, optional
Name of the objective function.
"""
_scalar = True
_units = "(dimensionless)"
_print_value_fmt = "Aspect ratio: {:10.3e} "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
name="aspect ratio",
):
if target is None and bounds is None:
target = 2
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,
)
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:
if hasattr(eq, "L_grid"):
grid = QuadratureGrid(
L=eq.L_grid,
M=eq.M_grid,
N=eq.N_grid,
NFP=eq.NFP,
)
else:
# if not an Equilibrium, is a Surface,
# has no radial resolution so just need
# the surface points
grid = LinearGrid(
rho=1.0,
M=eq.M * 2,
N=eq.N * 2,
NFP=eq.NFP,
)
else:
grid = self._grid
self._dim_f = 1
self._data_keys = ["R0/a"]
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 aspect ratio.
Parameters
----------
params : dict
Dictionary of equilibrium or surface degrees of freedom, eg
Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants
Returns
-------
AR : float
Aspect ratio, dimensionless.
"""
if constants is None:
constants = self.constants
data = compute_fun(
self.things[0],
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
)
return data["R0/a"]
class Elongation(_Objective):
"""Elongation = semi-major radius / semi-minor radius.
Elongation is a function of the toroidal angle.
Default ``loss_function="max"`` returns the maximum of all toroidal angles.
Parameters
----------
eq : Equilibrium or FourierRZToroidalSurface
Equilibrium or FourierRZToroidalSurface that
will be optimized to satisfy the Objective.
target : {float, ndarray}, optional
Target value(s) of the objective. Only used if bounds is None.
Must be broadcastable to Objective.dim_f.
bounds : tuple of {float, ndarray}, optional
Lower and upper bounds on the objective. Overrides target.
Both bounds must be broadcastable to to Objective.dim_f
weight : {float, ndarray}, optional
Weighting to apply to the Objective, relative to other Objectives.
Must be broadcastable to to Objective.dim_f
normalize : bool, optional
Whether to compute the error in physical units or non-dimensionalize.
Has no effect for this objective.
normalize_target : bool, optional
Whether target and bounds should be normalized before comparing to computed
values. If `normalize` is `True` and the target is in physical units,
this should also be set to True. Note: Has no effect for this objective.
loss_function : {None, 'mean', 'min', 'max'}, optional
Loss function to apply to the objective values once computed. This loss function
is called on the raw compute value, before any shifting, scaling, or
normalization. Note: Has no effect for this objective.
deriv_mode : {"auto", "fwd", "rev"}
Specify how to compute jacobian matrix, either forward mode or reverse mode AD.
"auto" selects forward or reverse mode based on the size of the input and output
of the objective. Has no effect on self.grad or self.hess which always use
reverse mode and forward over reverse mode respectively.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
name : str, optional
Name of the objective function.
"""
_scalar = True
_units = "(dimensionless)"
_print_value_fmt = "Elongation: {:10.3e} "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function="max",
deriv_mode="auto",
grid=None,
name="elongation",
):
if target is None and bounds is None:
target = 1
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,
)
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:
if hasattr(eq, "L_grid"):
grid = QuadratureGrid(
L=eq.L_grid,
M=eq.M_grid,
N=eq.N_grid,
NFP=eq.NFP,
)
else:
# if not an Equilibrium, is a Surface,
# has no radial resolution so just need
# the surface points
grid = LinearGrid(
rho=1.0,
M=eq.M * 2,
N=eq.N * 2,
NFP=eq.NFP,
)
else:
grid = self._grid
self._dim_f = grid.num_zeta
self._data_keys = ["a_major/a_minor"]
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 elongation.
Parameters
----------
params : dict
Dictionary of equilibrium or surface degrees of freedom,
eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants
Returns
-------
elongation : float
Elongation, dimensionless.
"""
if constants is None:
constants = self.constants
data = compute_fun(
self.things[0],
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
)
return self._constants["transforms"]["grid"].compress(
data["a_major/a_minor"], surface_label="zeta"
)
class Volume(_Objective):
"""Plasma volume.
Parameters
----------
eq : Equilibrium or FourierRZToroidalSurface
Equilibrium or FourierRZToroidalSurface that
will be optimized to satisfy the Objective.
target : {float, ndarray}, optional
Target value(s) of the objective. Only used if bounds is None.
Must be broadcastable to Objective.dim_f.
bounds : tuple of {float, ndarray}, optional
Lower and upper bounds on the objective. Overrides target.
Both bounds must be broadcastable to to Objective.dim_f
weight : {float, ndarray}, optional
Weighting to apply to the Objective, relative to other Objectives.
Must be broadcastable to to Objective.dim_f
normalize : bool, optional
Whether to compute the error in physical units or non-dimensionalize.
normalize_target : bool, optional
Whether target and bounds should be normalized before comparing to computed
values. If `normalize` is `True` and the target is in physical units,
this should also be set to True.
be set to True.
loss_function : {None, 'mean', 'min', 'max'}, optional
Loss function to apply to the objective values once computed. This loss function
is called on the raw compute value, before any shifting, scaling, or
normalization. Note: Has no effect for this objective.
deriv_mode : {"auto", "fwd", "rev"}
Specify how to compute jacobian matrix, either forward mode or reverse mode AD.
"auto" selects forward or reverse mode based on the size of the input and output
of the objective. Has no effect on self.grad or self.hess which always use
reverse mode and forward over reverse mode respectively.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
name : str, optional
Name of the objective function.
"""
_scalar = True
_units = "(m^3)"
_print_value_fmt = "Plasma volume: {:10.3e} "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
name="volume",
):
if target is None and bounds is None:
target = 1
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,
)
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:
if hasattr(eq, "L_grid"):
grid = QuadratureGrid(
L=eq.L_grid,
M=eq.M_grid,
N=eq.N_grid,
NFP=eq.NFP,
)
else:
# if not an Equilibrium, is a Surface,
# has no radial resolution so just need
# the surface points
grid = LinearGrid(
rho=1.0,
M=eq.M * 2,
N=eq.N * 2,
NFP=eq.NFP,
)
else:
grid = self._grid
self._dim_f = 1
self._data_keys = ["V"]
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["V"]
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params, constants=None):
"""Compute plasma volume.
Parameters
----------
params : dict
Dictionary of equilibrium or surface degrees of freedom,
eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants
Returns
-------
V : float
Plasma volume (m^3).
"""
if constants is None:
constants = self.constants
data = compute_fun(
self.things[0],
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
)
return data["V"]
class PlasmaVesselDistance(_Objective):
"""Target the distance between the plasma and a surrounding surface.
Computes the minimum distance from each point on the surface grid to a point on the
plasma grid. For dense grids, this will approximate the global min, but in general
will only be an upper bound on the minimum separation between the plasma and the
surrounding surface.
NOTE: By default, assumes the surface is not fixed and its coordinates are computed
at every iteration, for example if the winding surface you compare to is part of the
optimization and thus changing.
If the bounding surface is fixed, set surface_fixed=True to precompute the surface
coordinates and improve the efficiency of the calculation
NOTE: for best results, use this objective in combination with either MeanCurvature
or PrincipalCurvature, to penalize the tendency for the optimizer to only move the
points on surface corresponding to the grid that the plasma-vessel distance
is evaluated at, which can cause cusps or regions of very large curvature.
NOTE: When use_softmin=True, ensures that alpha*values passed in is
at least >1, otherwise the softmin will return inaccurate approximations
of the minimum. Will automatically multiply array values by 2 / min_val if the min
of alpha*array is <1. This is to avoid inaccuracies that arise when values <1
are present in the softmin, which can cause inaccurate mins or even incorrect
signs of the softmin versus the actual min.
Parameters
----------
eq : Equilibrium, optional
Equilibrium that will be optimized to satisfy the Objective.
surface : Surface
Bounding surface to penalize distance to.
target : {float, ndarray}, optional
Target value(s) of the objective. Only used if bounds is None.
Must be broadcastable to Objective.dim_f.
bounds : tuple of {float, ndarray}, optional
Lower and upper bounds on the objective. Overrides target.
Both bounds must be broadcastable to to Objective.dim_f
weight : {float, ndarray}, optional
Weighting to apply to the Objective, relative to other Objectives.
Must be broadcastable to to Objective.dim_f
normalize : bool, optional
Whether to compute the error in physical units or non-dimensionalize.
normalize_target : bool
Whether target should be normalized before comparing to computed values.
if `normalize` is `True` and the target is in physical units, this should also
be set to True.
loss_function : {None, 'mean', 'min', 'max'}, optional
Loss function to apply to the objective values once computed. This loss function
is called on the raw compute value, before any shifting, scaling, or
normalization.
deriv_mode : {"auto", "fwd", "rev"}
Specify how to compute jacobian matrix, either forward mode or reverse mode AD.
"auto" selects forward or reverse mode based on the size of the input and output
of the objective. Has no effect on self.grad or self.hess which always use
reverse mode and forward over reverse mode respectively.
surface_grid : Grid, optional
Collocation grid containing the nodes to evaluate surface geometry at.
plasma_grid : Grid, optional
Collocation grid containing the nodes to evaluate plasma geometry at.
use_softmin: bool, optional
Use softmin or hard min.
surface_fixed: bool, optional
Whether the surface the distance from the plasma is computed to
is fixed or not. If True, the surface is fixed and its coordinates are
precomputed, which saves on computation time during optimization, and
self.things = [eq] only.
If False, the surface coordinates are computed at every iteration.
False by default, so that self.things = [eq, surface]
alpha: float, optional
Parameter used for softmin. The larger alpha, the closer the softmin
approximates the hardmin. softmin -> hardmin as alpha -> infinity.
if alpha*array < 1, the underlying softmin will automatically multiply
the array by 2/min_val to ensure that alpha*array>1. Making alpha larger
than this minimum value will make the softmin a more accurate approximation
of the true min.
name : str, optional
Name of the objective function.
"""
_coordinates = "rtz"
_units = "(m)"
_print_value_fmt = "Plasma-vessel distance: {:10.3e} "
def __init__(
self,
eq,
surface,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
surface_grid=None,
plasma_grid=None,
use_softmin=False,
surface_fixed=False,
alpha=1.0,
name="plasma-vessel distance",
):
if target is None and bounds is None:
bounds = (1, np.inf)
self._surface = surface
self._surface_grid = surface_grid
self._plasma_grid = plasma_grid
self._use_softmin = use_softmin
self._surface_fixed = surface_fixed
self._alpha = alpha
super().__init__(
things=[eq, self._surface] if not surface_fixed else [eq],
target=target,
bounds=bounds,
weight=weight,
normalize=normalize,
normalize_target=normalize_target,
loss_function=loss_function,
deriv_mode=deriv_mode,
name=name,
)
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]
surface = self._surface if self._surface_fixed else self.things[1]
# if things[1] is different than self._surface, update self._surface
if surface != self._surface:
self._surface = surface
if self._surface_grid is None:
surface_grid = LinearGrid(M=eq.M_grid, N=eq.N_grid, NFP=eq.NFP)
else:
surface_grid = self._surface_grid
if self._plasma_grid is None:
plasma_grid = LinearGrid(M=eq.M_grid, N=eq.N_grid, NFP=eq.NFP)
else:
plasma_grid = self._plasma_grid
if not np.allclose(surface_grid.nodes[:, 0], 1):
warnings.warn("Surface grid includes off-surface pts, should be rho=1")
if not np.allclose(plasma_grid.nodes[:, 0], 1):
warnings.warn("Plasma grid includes interior points, should be rho=1")
self._dim_f = surface_grid.num_nodes
self._equil_data_keys = ["R", "phi", "Z"]
self._surface_data_keys = ["x"]
timer = Timer()
if verbose > 0:
print("Precomputing transforms")
timer.start("Precomputing transforms")
equil_profiles = get_profiles(
self._equil_data_keys,
obj=eq,
grid=plasma_grid,
has_axis=plasma_grid.axis.size,
)
equil_transforms = get_transforms(
self._equil_data_keys,
obj=eq,
grid=plasma_grid,
has_axis=plasma_grid.axis.size,
)
surface_transforms = get_transforms(
self._surface_data_keys,
obj=surface,
grid=surface_grid,
has_axis=surface_grid.axis.size,
)
# compute returns points on the grid of the surface
# (dim_f = surface_grid.num_nodes)
# so set quad_weights to the surface grid
# to avoid it being incorrectly set in the super build
w = surface_grid.weights
w *= jnp.sqrt(surface_grid.num_nodes)
self._constants = {
"equil_transforms": equil_transforms,
"equil_profiles": equil_profiles,
"surface_transforms": surface_transforms,
"quad_weights": w,
}
if self._surface_fixed:
# precompute the surface coordinates
# as the surface is fixed during the optimization
surface_coords = compute_fun(
self._surface,
self._surface_data_keys,
params=self._surface.params_dict,
transforms=surface_transforms,
profiles={},
basis="xyz",
)["x"]
self._constants["surface_coords"] = surface_coords
timer.stop("Precomputing transforms")
if verbose > 1:
timer.disp("Precomputing transforms")
if self._normalize:
scales = compute_scaling_factors(eq)
self._normalization = scales["a"]
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, equil_params, surface_params=None, constants=None):
"""Compute plasma-surface distance.
Parameters
----------
equil_params : dict
Dictionary of equilibrium degrees of freedom, eg Equilibrium.params_dict
surface_params : dict
Dictionary of surface degrees of freedom, eg Surface.params_dict
Only needed if self._surface_fixed = False
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants
Returns
-------
d : ndarray, shape(surface_grid.num_nodes,)
For each point in the surface grid, approximate distance to plasma.
"""
if constants is None:
constants = self.constants
data = compute_fun(
"desc.equilibrium.equilibrium.Equilibrium",
self._equil_data_keys,
params=equil_params,
transforms=constants["equil_transforms"],
profiles=constants["equil_profiles"],
)
plasma_coords = rpz2xyz(jnp.array([data["R"], data["phi"], data["Z"]]).T)
if self._surface_fixed:
surface_coords = constants["surface_coords"]
else:
surface_coords = compute_fun(
self._surface,
self._surface_data_keys,
params=surface_params,
transforms=constants["surface_transforms"],
profiles={},
basis="xyz",
)["x"]
d = safenorm(plasma_coords[:, None, :] - surface_coords[None, :, :], axis=-1)
if self._use_softmin: # do softmin
return jnp.apply_along_axis(softmin, 0, d, self._alpha)
else: # do hardmin
return d.min(axis=0)
class MeanCurvature(_Objective):
"""Target a particular value for the mean curvature.
The mean curvature H of a surface is an extrinsic measure of curvature that locally
describes the curvature of an embedded surface in Euclidean space.
Positive mean curvature generally corresponds to "concave" regions of the plasma
boundary which may be difficult to create with coils or magnets.
Parameters
----------
eq : Equilibrium or FourierRZToroidalSurface
Equilibrium or FourierRZToroidalSurface that
will be optimized to satisfy the Objective.
target : {float, ndarray}, optional
Target value(s) of the objective. Only used if bounds is None.
Must be broadcastable to Objective.dim_f.
bounds : tuple of {float, ndarray}, optional
Lower and upper bounds on the objective. Overrides target.
Both bounds must be broadcastable to to Objective.dim_f
weight : {float, ndarray}, optional
Weighting to apply to the Objective, relative to other Objectives.
Must be broadcastable to to Objective.dim_f
normalize : bool, optional
Whether to compute the error in physical units or non-dimensionalize.
normalize_target : bool
Whether target should be normalized before comparing to computed values.
if `normalize` is `True` and the target is in physical units, this should also
be set to True.
loss_function : {None, 'mean', 'min', 'max'}, optional
Loss function to apply to the objective values once computed. This loss function
is called on the raw compute value, before any shifting, scaling, or
normalization.
deriv_mode : {"auto", "fwd", "rev"}
Specify how to compute jacobian matrix, either forward mode or reverse mode AD.
"auto" selects forward or reverse mode based on the size of the input and output
of the objective. Has no effect on self.grad or self.hess which always use
reverse mode and forward over reverse mode respectively.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
name : str, optional
Name of the objective function.
"""
_coordinates = "rtz"
_units = "(m^-1)"
_print_value_fmt = "Mean curvature: {:10.3e} "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
name="mean curvature",
):
if target is None and bounds is None:
bounds = (-np.inf, 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,
)
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( # getattr statements in case a surface is passed in
M=getattr(eq, "M_grid", eq.M * 2),
N=getattr(eq, "N_grid", eq.N * 2),
NFP=eq.NFP,
sym=eq.sym,
)
else:
grid = self._grid
self._dim_f = grid.num_nodes
self._data_keys = ["curvature_H_rho"]
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 = 1 / scales["a"]
super().build(use_jit=use_jit, verbose=verbose)
def compute(self, params, constants=None):
"""Compute mean curvature.
Parameters
----------
params : dict
Dictionary of equilibrium or surface degrees of freedom,
eg Equilibrium.params_dict
constants : dict
Dictionary of constant data, eg transforms, profiles etc. Defaults to
self.constants
Returns
-------
H : ndarray
Mean curvature at each point (m^-1).
"""
if constants is None:
constants = self.constants
data = compute_fun(
self.things[0],
self._data_keys,
params=params,
transforms=constants["transforms"],
profiles=constants["profiles"],
)
return data["curvature_H_rho"]
class PrincipalCurvature(_Objective):
"""Target a particular value for the (unsigned) principal curvature.
The two principal curvatures at a given point of a surface are the maximum and
minimum values of the curvature as expressed by the eigenvalues of the shape
operator at that point. They measure how the surface bends by different amounts in
different directions at that point.
This objective targets the maximum absolute value of the two principal curvatures.
Principal curvature with large absolute value indicates a tight radius of curvature
which may be difficult to obtain with coils or magnets.
Parameters
----------
eq : Equilibrium or FourierRZToroidalSurface
Equilibrium or FourierRZToroidalSurface that
will be optimized to satisfy the Objective.
target : {float, ndarray}, optional
Target value(s) of the objective. Only used if bounds is None.
Must be broadcastable to Objective.dim_f.
bounds : tuple of {float, ndarray}, optional
Lower and upper bounds on the objective. Overrides target.
Both bounds must be broadcastable to to Objective.dim_f
weight : {float, ndarray}, optional
Weighting to apply to the Objective, relative to other Objectives.
Must be broadcastable to to Objective.dim_f
normalize : bool, optional
Whether to compute the error in physical units or non-dimensionalize.
normalize_target : bool
Whether target should be normalized before comparing to computed values.
if `normalize` is `True` and the target is in physical units, this should also
be set to True.
loss_function : {None, 'mean', 'min', 'max'}, optional
Loss function to apply to the objective values once computed. This loss function
is called on the raw compute value, before any shifting, scaling, or
normalization.
deriv_mode : {"auto", "fwd", "rev"}
Specify how to compute jacobian matrix, either forward mode or reverse mode AD.
"auto" selects forward or reverse mode based on the size of the input and output
of the objective. Has no effect on self.grad or self.hess which always use
reverse mode and forward over reverse mode respectively.
grid : Grid, optional
Collocation grid containing the nodes to evaluate at.
name : str, optional
Name of the objective function.
"""
_coordinates = "rtz"
_units = "(m^-1)"
_print_value_fmt = "Principal curvature: {:10.3e} "
def __init__(
self,
eq,
target=None,
bounds=None,
weight=1,
normalize=True,
normalize_target=True,
loss_function=None,
deriv_mode="auto",
grid=None,
name="principal-curvature",
):
if target is None and bounds is None:
target = 1
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,
)
def build(self, use_jit=True, verbose=1):
"""Build constant arrays.
Parameters
----------
use_jit : bool, optional