-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathphysics.py
1048 lines (876 loc) · 34.2 KB
/
physics.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
import math
from typing import Optional, Tuple
import torch
from torch import Tensor
from torch.utils.data import IterableDataset
from utils import ift, grad, mae, get_profile_from_wout, get_wout
mu0 = 4 * math.pi * 1e-7
class Equilibrium(IterableDataset):
def __init__(
self,
ndomain: int = 2500,
nboundary: int = 50,
normalized: bool = False,
seed: int = 42,
) -> None:
super().__init__()
# Number of collocation points to use in the domain
self.ndomain = ndomain
# Number of collocation points to use on the boundary
self.nboundary = nboundary
# Whether to use the normalized PDE system
self.normalized = normalized
# Seed to initialize the random generators
self.seed = seed
# Closure functions
if normalized:
self.pde_closure = self._pde_closure_
self.boundary_closure = self._boundary_closure_
self.axis_closure = self._axis_closure_
self.data_closure = self._data_closure_
self.mae_pde_loss = self._mae_pde_loss_
else:
self.pde_closure = self._pde_closure
self.boundary_closure = self._boundary_closure
self.axis_closure = self._axis_closure
self.data_closure = self._data_closure
self.mae_pde_loss = self._mae_pde_loss
def closure(
self,
x_domain: Tensor,
psi_domain: Tensor,
x_boundary: Tensor,
psi_boundary: Tensor,
x_axis: Optional[Tensor] = None,
psi_axis: Optional[Tensor] = None,
return_dict: Optional[bool] = False,
) -> Tensor:
loss = {}
loss["pde"] = self.pde_closure(x_domain, psi_domain)
loss["boundary"] = self.boundary_closure(x_boundary, psi_boundary)
loss["tot"] = loss["pde"] + loss["boundary"]
if x_axis is not None:
loss["axis"] = self.axis_closure(x_axis, psi_axis)
loss["tot"] += loss["axis"]
if return_dict:
return loss
return loss["tot"]
def grid(self, *args, **kwargs) -> Tensor:
raise NotImplementedError
def fluxplot(self, *args, **kwargs):
raise NotImplementedError
def _data_closure(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _pde_closure(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _axis_closure(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _boundary_closure(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _data_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _pde_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _boundary_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _axis_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _mae_pde_loss(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
def _mae_pde_loss_(self, x: Tensor, psi: Tensor) -> Tensor:
raise NotImplementedError
@property
def _mpol(self) -> int:
return len(self.Rb)
def p_fn(self, psi):
p = 0
for i, coef in enumerate(self.p):
p += coef * psi**i
return p
def fsq_fn(self, psi):
fsq = 0
for i, coef in enumerate(self.fsq):
fsq += coef * psi**i
return fsq
def iota_fn(self, psi):
iota = 0
for i, coef in enumerate(self.iota):
iota += coef * psi**i
return iota
def Rb_fn(self, theta):
basis = torch.cos(torch.as_tensor([i * theta for i in range(self._mpol)]))
return (self.Rb * basis).sum()
def Zb_fn(self, theta):
basis = torch.sin(torch.as_tensor([i * theta for i in range(self._mpol)]))
return (self.Zb * basis).sum()
def update_axis(self, axis_guess):
# Axis should have Za=0 by symmetry
self._Ra = axis_guess[0]
class HighBetaEquilibrium(Equilibrium):
def __init__(
self, a: float = 0.1, A: float = 1, C: float = 10, R0: float = 0.6, **kwargs
) -> None:
super().__init__(**kwargs)
self.a = a
self.A = A
self.C = C
self.R0 = R0
self.psi_0 = -2 * A * a**2 / 8
def __iter__(self):
generator = torch.Generator()
generator.manual_seed(self.seed)
if self.normalized:
rho_b = 1.0
else:
rho_b = self.a
while True:
# Domain collocation points
rho = torch.empty(self.ndomain)
rho[0] = 0
rho[1:] = torch.rand(self.ndomain - 1, generator=generator) * rho_b
theta = (2 * torch.rand(self.ndomain, generator=generator) - 1) * math.pi
domain = torch.stack([rho, theta], dim=-1)
# Boundary collocation points
rho = rho_b * torch.ones(self.nboundary)
theta = (2 * torch.rand(self.nboundary, generator=generator) - 1) * math.pi
boundary = torch.stack([rho, theta], dim=-1)
yield domain, boundary, None
def psi(self, x: Tensor) -> Tensor:
rho = x[:, 0]
theta = x[:, 1]
return (
0.125
* (rho**2 - self.a**2)
* (2 * self.A + self.C * rho * torch.cos(theta))
)
def psi_(self, x: Tensor) -> Tensor:
rho = x[:, 0]
theta = x[:, 1]
return (
0.125
* self.a**2
* (rho**2 - 1)
* (2 * self.A + self.C * rho * self.a * torch.cos(theta))
/ self.psi_0
)
def _data_closure(self, x: Tensor, psi: Tensor) -> Tensor:
return ((psi - self.psi(x)) ** 2).sum()
def _data_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
return ((psi - self.psi_(x)) ** 2).sum()
def _pde_closure(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_drho = dpsi_dx[:, 0]
dpsi_dtheta = dpsi_dx[:, 1]
dpsi2_drho2 = grad(dpsi_drho, x, create_graph=True)[:, 0]
dpsi2_dtheta2 = grad(dpsi_dtheta, x, create_graph=True)[:, 1]
rho = x[:, 0]
theta = x[:, 1]
# The one below is the original formulation with axis singularity
# residual = 1 / rho * dpsi_drho + dpsi2_drho2
# residual += 1 / rho ** 2 * dpsi2_dtheta2
# residual -= A + C * rho * torch.cos(theta)
residual = rho * dpsi_drho + rho**2 * dpsi2_drho2 + dpsi2_dtheta2
residual -= rho**2 * (self.A + self.C * rho * torch.cos(theta))
return (residual**2).sum()
def _mae_pde_loss(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_drho = dpsi_dx[:, 0]
dpsi_dtheta = dpsi_dx[:, 1]
dpsi2_drho2 = grad(dpsi_drho, x, create_graph=True)[:, 0]
dpsi2_dtheta2 = grad(dpsi_dtheta, x, create_graph=True)[:, 1]
rho = x[:, 0]
theta = x[:, 1]
residual = rho * dpsi_drho + rho**2 * dpsi2_drho2 + dpsi2_dtheta2
denom = rho**2 * (self.A + self.C * rho * torch.cos(theta))
# Do not compute error at the boundary to avoid division by 0
# TODO: can we relax this?
return mae(residual[rho != self.a], denom[rho != self.a])
def _pde_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_drho = dpsi_dx[:, 0]
dpsi_dtheta = dpsi_dx[:, 1]
dpsi2_drho2 = grad(dpsi_drho, x, create_graph=True)[:, 0]
dpsi2_dtheta2 = grad(dpsi_dtheta, x, create_graph=True)[:, 1]
rho = x[:, 0]
theta = x[:, 1]
residual = rho * dpsi_drho + rho**2 * dpsi2_drho2 + dpsi2_dtheta2
residual -= (
self.a**2
/ self.psi_0
* rho**2
* (self.A + self.a * self.C * rho * torch.cos(theta))
)
return (residual**2).sum()
def _mae_pde_loss_(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_drho = dpsi_dx[:, 0]
dpsi_dtheta = dpsi_dx[:, 1]
dpsi2_drho2 = grad(dpsi_drho, x, create_graph=True)[:, 0]
dpsi2_dtheta2 = grad(dpsi_dtheta, x, create_graph=True)[:, 1]
rho = x[:, 0]
theta = x[:, 1]
residual = rho * dpsi_drho + rho**2 * dpsi2_drho2 + dpsi2_dtheta2
denom = (
self.a**2
/ self.psi_0
* rho**2
* (self.A + self.a * self.C * rho * torch.cos(theta))
)
# Do not compute error at the boundary to avoid division by 0
# TODO: can we relax this?
return mae(residual[rho != 1], denom[rho != 1])
def _boundary_closure(self, x: Tensor, psi: Tensor) -> Tensor:
rho = x[:, 0]
boundary = rho == self.a
return (psi[boundary] ** 2).sum()
def _boundary_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
rho = x[:, 0]
boundary = rho == 1
return (psi[boundary] ** 2).sum()
def grid(self, ns: int = None, normalized: bool = None) -> Tensor:
if normalized is None:
normalized = self.normalized
if ns is None:
ns = int(math.sqrt(self.ndomain))
if normalized:
rho_b = 1.0
else:
rho_b = self.a
rho = torch.linspace(0, rho_b, ns)
theta = torch.linspace(-math.pi, math.pi, ns)
return torch.cartesian_prod(rho, theta)
def fluxplot(self, x, psi, ax, *args, **kwargs):
x = x.detach()
xrho = x[:, 0]
ytheta = x[:, 1]
ns = int(math.sqrt(x.shape[0]))
# Create plotting grid
xrho = xrho.view(ns, ns)
ytheta = ytheta.view(ns, ns)
xx = self.R0 + xrho * torch.cos(ytheta)
yy = xrho * torch.sin(ytheta)
# Detach and reshape tensors
psi = psi.detach().view(xx.shape)
ax.contour(xx, yy, psi, levels=10, **kwargs)
ax.axis("equal")
ax.set_xlabel(r"$R [m]$")
ax.set_ylabel(r"$Z [m]$")
return ax
class GradShafranovEquilibrium(Equilibrium):
"""
The default case is a Solov'ev equilibrium as in the original VMEC paper.
This repository keeps VMEC 2D equilibria under the `data` folder,
they are taken from the DESC repository:
https://github.com/PlasmaControl/DESC/tree/master/tests/inputs
"""
def __init__(
self,
p: Tuple[float] = (0.125 / mu0, -0.125 / mu0),
fsq: Tuple[float] = (4, -4 * 4 / 10),
Rb: Tuple[float] = (
3.9334e00,
-1.0258e00,
-6.8083e-02,
-9.0720e-03,
-1.4531e-03,
),
Zb: Tuple[float] = (0, math.sqrt(10) / 2, 0, 0, 0),
Ra: float = 3.9332,
Za: float = 0.0,
psi_0: float = 1,
wout_path: Optional[str] = None,
is_solovev: Optional[bool] = True,
**kwargs,
) -> None:
super().__init__(**kwargs)
# Pressure and current profile
self.p = torch.as_tensor(p)
self.fsq = torch.as_tensor(fsq)
# Boundary definition
assert len(Rb) == len(Zb)
self.Rb = torch.as_tensor(Rb)
self.Zb = torch.as_tensor(Zb)
# Initial guess for the axis
self.Ra = Ra
self.Za = Za
# Running axis location
self._Ra = Ra
self._Za = Za
# Boundary condition on psi (i.e., psi_edge), the poloidal flux (chi in VMEC)
self.psi_0 = psi_0
# VMEC wout file
self.wout_path = wout_path
# Is a Solov'ev equilibrium?
self.is_solovev = is_solovev
@classmethod
def from_vmec(cls, wout_path, **kwargs):
"""
Instatiate Equilibrium from VMEC wout file.
Example:
>>> from physics import GradShafranovEquilibrium
>>> equi = GradShafranovEquilibrium.from_vmec("data/wout_DSHAPE.nc")
>>> equi.psi_0
-0.665
"""
pressure = get_profile_from_wout(wout_path, "p")
fsq = get_profile_from_wout(wout_path, "f")
wout = get_wout(wout_path)
Rb = wout["rmnc"][-1].data
Zb = wout["zmns"][-1].data
# Remove trailing zeros in boundary definition
Rb = Rb[Rb != 0]
Zb = Zb[: len(Rb)]
Rb, Zb = map(tuple, (Rb, Zb))
Ra = wout["raxis_cc"][:].data.item()
Za = wout["zaxis_cs"][:].data.item()
psi_0 = wout["chi"][-1].data.item()
return cls(
p=pressure,
fsq=fsq,
Rb=Rb,
Zb=Zb,
Ra=Ra,
Za=Za,
psi_0=psi_0,
wout_path=wout_path,
**kwargs,
)
def __iter__(self):
generator = torch.Generator()
generator.manual_seed(self.seed)
while True:
# Domain collocation points
# Create grid by scaling the boundary from the LCFS to the axis
# Achtung: these are not flux surfaces!
domain = []
ns = int(math.sqrt(self.ndomain))
hs = torch.rand(ns, generator=generator) ** 2
for s in hs:
theta = (2 * torch.rand(ns, generator=generator) - 1) * math.pi
Rb = torch.as_tensor([self.Rb_fn(t) for t in theta])
Zb = torch.as_tensor([self.Zb_fn(t) for t in theta])
R = (Rb - self._Ra) * s + self._Ra
Z = (Zb - self._Za) * s + self._Za
domain.append(torch.stack([R, Z], dim=-1))
domain = torch.cat(domain)
# Boundary collocation points
theta = (2 * torch.rand(self.nboundary, generator=generator) - 1) * math.pi
R = torch.as_tensor([self.Rb_fn(t) for t in theta])
Z = torch.as_tensor([self.Zb_fn(t) for t in theta])
boundary = torch.stack([R, Z], dim=-1)
# Axis point
axis = torch.Tensor([self._Ra, self._Za]).view(1, 2)
if self.normalized:
yield domain / self.Rb[0], boundary / self.Rb[0], axis / self.Rb[0]
yield domain, boundary, axis
def eps(self, x: Tensor, psi: Tensor, reduction: Optional[str] = "mean") -> Tensor:
assert reduction in ("mean", None)
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_dR = dpsi_dx[:, 0]
dpsi_dZ = dpsi_dx[:, 1]
dpsi2_dR2 = grad(dpsi_dR, x, retain_graph=True)[:, 0]
dpsi2_dZ2 = grad(dpsi_dZ, x, retain_graph=True)[:, 1]
# Compute normalized poloidal flux
psi_ = psi if self.normalized else psi / self.psi_0
p = self.p_fn(psi_)
dp_dpsi = grad(p, psi, retain_graph=True)
fsq = self.fsq_fn(psi_)
dfsq_dpsi = grad(fsq, psi, retain_graph=True)
R = x[:, 0]
# Force components
nabla_star = -1 / R * dpsi_dR + dpsi2_dR2 + dpsi2_dZ2
if self.normalized:
nabla_star *= self.psi_0 / self.Rb[0] ** 2
term = mu0 * R**2 * dp_dpsi
if self.normalized:
term *= self.Rb[0] ** 2 / self.psi_0
gs = nabla_star + term
term = 0.5 * dfsq_dpsi
if self.normalized:
term *= 1 / self.psi_0
gs += term
fR = -1 / (mu0 * R**2) * dpsi_dR * gs
fZ = -1 / (mu0 * R**2) * dpsi_dZ * gs
fsq = fR**2 + fZ**2
if self.normalized:
fsq *= self.psi_0**2 / self.Rb[0] ** 6
# grad-p
gradpsq = dp_dpsi**2 * (dpsi_dR**2 + dpsi_dZ**2)
if self.normalized:
gradpsq *= 1 / self.Rb[0] ** 2
if reduction is None:
# Compute the local normalized force balance
return torch.sqrt(fsq / gradpsq)
if reduction == "mean":
# Compute the normalized averaged force balance
# The `x` domain is not enforced to be on a equally spaced grid,
# so the sum() here is not strictly an equivalent to an integral
return torch.sqrt(fsq.sum() / gradpsq.sum())
def _pde_closure(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_dR = dpsi_dx[:, 0]
dpsi_dZ = dpsi_dx[:, 1]
dpsi2_dR2 = grad(dpsi_dR, x, create_graph=True)[:, 0]
dpsi2_dZ2 = grad(dpsi_dZ, x, create_graph=True)[:, 1]
p = self.p_fn(psi / self.psi_0)
dp_dpsi = grad(p, psi, create_graph=True)
fsq = self.fsq_fn(psi / self.psi_0)
dfsq_dpsi = grad(fsq, psi, create_graph=True)
R = x[:, 0]
residual = -1 / R * dpsi_dR + dpsi2_dR2 + dpsi2_dZ2
residual += mu0 * R**2 * dp_dpsi + 0.5 * dfsq_dpsi
return (residual**2).sum()
def _pde_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_dR = dpsi_dx[:, 0]
dpsi_dZ = dpsi_dx[:, 1]
dpsi2_dR2 = grad(dpsi_dR, x, create_graph=True)[:, 0]
dpsi2_dZ2 = grad(dpsi_dZ, x, create_graph=True)[:, 1]
p = self.p_fn(psi)
dp_dpsi = grad(p, psi, create_graph=True)
fsq = self.fsq_fn(psi)
dfsq_dpsi = grad(fsq, psi, create_graph=True)
R = x[:, 0]
residual = -1 / R * dpsi_dR + dpsi2_dR2 + dpsi2_dZ2
residual += mu0 * self.Rb[0] ** 4 / self.psi_0**2 * R**2 * dp_dpsi
residual += 0.5 * self.Rb[0] ** 2 / self.psi_0**2 * dfsq_dpsi
return (residual**2).sum()
def _mae_pde_loss(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_dR = dpsi_dx[:, 0]
dpsi_dZ = dpsi_dx[:, 1]
dpsi2_dR2 = grad(dpsi_dR, x, retain_graph=True)[:, 0]
dpsi2_dZ2 = grad(dpsi_dZ, x, retain_graph=True)[:, 1]
p = self.p_fn(psi / self.psi_0)
dp_dpsi = grad(p, psi, retain_graph=True)
fsq = self.fsq_fn(psi / self.psi_0)
dfsq_dpsi = grad(fsq, psi, retain_graph=True)
R = x[:, 0]
nabla_star = -1 / R * dpsi_dR + dpsi2_dR2 + dpsi2_dZ2
denom = mu0 * R**2 * dp_dpsi + 0.5 * dfsq_dpsi
return mae(nabla_star, -denom)
def _mae_pde_loss_(self, x: Tensor, psi: Tensor) -> Tensor:
dpsi_dx = grad(psi, x, create_graph=True)
dpsi_dR = dpsi_dx[:, 0]
dpsi_dZ = dpsi_dx[:, 1]
dpsi2_dR2 = grad(dpsi_dR, x, create_graph=True)[:, 0]
dpsi2_dZ2 = grad(dpsi_dZ, x, create_graph=True)[:, 1]
p = self.p_fn(psi)
dp_dpsi = grad(p, psi, create_graph=True)
fsq = self.fsq_fn(psi)
dfsq_dpsi = grad(fsq, psi, create_graph=True)
R = x[:, 0]
nabla_star = -1 / R * dpsi_dR + dpsi2_dR2 + dpsi2_dZ2
denom = mu0 * self.Rb[0] ** 4 / self.psi_0**2 * R**2 * dp_dpsi
denom += 0.5 * self.Rb[0] ** 2 / self.psi_0**2 * dfsq_dpsi
return mae(nabla_star, -denom)
def _boundary_closure(self, x: Tensor, psi: Tensor) -> Tensor:
return ((psi - self.psi_0) ** 2).sum()
def _boundary_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
return ((psi - 1) ** 2).sum()
def _axis_closure(self, x: Tensor, psi: Tensor) -> Tensor:
return (psi**2).sum()
def _axis_closure_(self, x: Tensor, psi: Tensor) -> Tensor:
return (psi**2).sum()
def psi(self, x: Tensor) -> Tensor:
"""
See Bauer1978 for the nomenclature.
Achtung: this is the analytical solution only in case of a Solov'ev equilibrium.
"""
assert self.is_solovev == True
R = x[:, 0]
Z = x[:, 1]
l2 = self.fsq[0] # R0**2 in VMEC
f0 = -self.fsq[1] / 4 / l2 # beta1 in VMEC
p0 = self.p[0] * mu0 # beta0 in VMEC
# Get axis from R at boundary
Ra = math.sqrt(self.Rb.sum().item() ** 2 + math.sqrt(8 / p0))
return f0 * l2 * Z**2 + p0 / 8 * (R**2 - Ra**2) ** 2
def grid(self, ns: int = None, normalized: bool = None) -> Tensor:
if ns is None:
ns = int(math.sqrt(self.ndomain))
if normalized is None:
normalized = self.normalized
Rb = ift(self.Rb, basis="cos", ntheta=ns)
Zb = ift(self.Zb, basis="sin", ntheta=ns)
grid = []
# Create grid by linearly scaling the boundary from the LCFS to the axis
# Achtung: these are not flux surfaces!
hs = 1 / (ns - 1)
for i in range(ns):
R = (Rb - self._Ra) * i * hs + self._Ra
Z = (Zb - self._Za) * i * hs + self._Za
grid.append(torch.stack([R, Z], dim=-1))
grid = torch.cat(grid)
if normalized:
grid /= self.Rb[0]
return grid
def fluxplot(self, x, psi, ax, filled: Optional[bool] = False, **kwargs):
x = x.detach()
R = x[:, 0]
Z = x[:, 1]
ns = int(math.sqrt(x.shape[0]))
# Create plotting grid
xx = R.view(ns, ns)
yy = Z.view(ns, ns)
# Detach and reshape tensors
psi = psi.detach().view(xx.shape)
if filled:
cs = ax.contourf(xx, yy, psi, **kwargs)
ax.get_figure().colorbar(cs)
else:
cs = ax.contour(xx, yy, psi, levels=10, **kwargs)
ax.clabel(cs, inline=True, fontsize=10, fmt="%1.3f")
ax.axis("equal")
ax.set_xlabel(r"$R [m]$")
ax.set_ylabel(r"$Z [m]$")
return ax
def fluxsurfacesplot(
self,
x,
ax,
psi: Optional[Tensor] = None,
ns: Optional[int] = None,
nplot: Optional[int] = 10,
):
"""
Plot flux surfaces on (R, Z) plane.
TODO: improve ns and nplot handling.
"""
assert len(x.shape) == 2
if ns is None:
# Infer number of flux surfaces
ns = int(math.sqrt(x.shape[0]))
# Create plotting grid
xx = x[:, 0].view(ns, -1)
yy = x[:, 1].view(ns, -1)
if nplot > ns:
nplot = ns
# Plot nplot + 1 since the first one is the axis
ii = torch.linspace(0, ns - 1, nplot + 1, dtype=torch.int).tolist()
# If psi is given, pick equally spaced flux surfaces in terms of psi
if psi is not None:
psi_i = torch.linspace(0, psi[-1], nplot + 1)
ii = []
for p in psi_i:
idx = torch.argmin((psi - p).abs())
ii.append(idx)
for i in ii:
ax.plot(xx[i], yy[i])
if psi is not None:
pi_half = int(xx.shape[1] / 4)
ax.text(xx[i][pi_half], yy[i][pi_half], f"{psi[i].item():.3f}")
ax.axis("equal")
return ax
class InverseGradShafranovEquilibrium(Equilibrium):
"""The default case is a DSHAPE equilibrium as in the original VMEC paper."""
def __init__(
self,
p: Tuple[float] = (1.6e3, -2 * 1.6e3, 1.6e3),
iota: Tuple[float] = (1, -0.67),
Rb: Tuple[float] = (3.51, 1.0, 0.106),
Zb: Tuple[float] = (0, 1.47, -0.16),
Ra: float = 3.51,
Za: float = 0.0,
phi_edge: float = 1,
wout_path: Optional[str] = None,
is_solovev: Optional[bool] = False,
ntheta: Optional[int] = 32,
**kwargs,
) -> None:
super().__init__(**kwargs)
# Pressure and iota profile
self.p = torch.as_tensor(p)
self.iota = torch.as_tensor(iota)
# Boundary definition
assert len(Rb) == len(Zb)
self.Rb = torch.as_tensor(Rb)
self.Zb = torch.as_tensor(Zb)
# Initial guess for the axis
self.Ra = Ra
self.Za = Za
# Running axis location
self._Ra = Ra
self._Za = Za
# Boundary condition on phi (i.e., phi at the VMEC LCFS)
self.phi_edge = phi_edge
# VMEC wout file
self.wout_path = wout_path
# Number of collocation points in the poloidal direction
self.ntheta = ntheta
# Is a Solov'ev equilibrium?
self.is_solovev = is_solovev
# Normalized version is not supported for now
assert self.normalized == False
self._pde_closure_ = None
self._boundary_closure_ = None
self._axis_closure_ = None
@classmethod
def from_vmec(cls, wout_path, **kwargs):
"""
Instatiate Equilibrium from VMEC wout file.
Example:
>>> from physics import InverseGradShafranovEquilibrium
>>> equi = InverseGradShafranovEquilibrium.from_vmec("data/wout_DSHAPE.nc")
>>> equi.phi_edge
1.0
"""
wout = get_wout(wout_path)
ns = wout["ns"][:].data.item()
pressure = wout["am"][:].data
pressure = pressure[pressure != 0].tolist()
iota = wout["ai"][:].data
iota = iota[iota != 0].tolist()
Rb = wout["rmnc"][-1].data
Zb = wout["zmns"][-1].data
# Remove trailing zeros in boundary definition
Rb = Rb[Rb != 0]
Zb = Zb[: len(Rb)]
Rb, Zb = map(tuple, (Rb, Zb))
Ra = wout["raxis_cc"][:].data.item()
Za = wout["zaxis_cs"][:].data.item()
phi_edge = wout["phi"][-1].data.item()
return cls(
p=pressure,
iota=iota,
Rb=Rb,
Zb=Zb,
Ra=Ra,
Za=Za,
phi_edge=phi_edge,
wout_path=wout_path,
ndomain=ns,
**kwargs,
)
def __iter__(self):
# Use equally spaced grid to compute volume averaged quantities in
# closure functions.
while True:
# Domain collocation points
# ndomain is the number of flux surfaces
# Avoid to compute loss on axis due to coordinate singularity
ns = self.ndomain
rho = torch.linspace(0, 1, ns + 1)[1:]
theta = (2 * torch.linspace(0, 1, self.ntheta) - 1) * math.pi
domain = torch.cartesian_prod(rho, theta)
# Boundary collocation points
# Use equally spaced grid
rho = torch.ones(self.ntheta)
boundary = torch.stack([rho, theta], dim=-1)
yield domain, boundary, None
def _pde_closure(self, x: Tensor, RlZ: Tensor) -> Tensor:
# TODO: simplify the expression to reduce torch computational graph
R = RlZ[:, 0]
l = RlZ[:, 1]
Z = RlZ[:, 2]
rho = x[:, 0]
# Compute the flux surface profiles
# self.*_fn(s), where s = rho ** 2
p = self.p_fn(rho**2)
iota = self.iota_fn(rho**2)
# Compute geometry derivatives
dR_dx = grad(R, x, create_graph=True)
Rs = dR_dx[:, 0]
Ru = dR_dx[:, 1]
dl_dx = grad(l, x, create_graph=True)
lu = dl_dx[:, 1]
dZ_dx = grad(Z, x, create_graph=True)
Zs = dZ_dx[:, 0]
Zu = dZ_dx[:, 1]
# Compute jacobian
jacobian = R * (Ru * Zs - Zu * Rs)
# Compute the magnetic fluxes derivatives
phis = self.phi_edge * rho / torch.pi
chis = iota * phis
# Compute the contravariant magnetic field components
bsupu = chis / jacobian
bsupv = phis / jacobian * (1 + lu)
# Compute the metric tensor elements
guu = Ru**2 + Zu**2
gus = Ru * Rs + Zu * Zs
gvv = R**2
# Compute the covariant magnetic field components
bsubs = bsupu * gus
bsubu = bsupu * guu
bsubv = bsupv * gvv
# Compute the covariant force components,
# actually, mu0 * f_*
dbsubv_dx = grad(bsubv, x, create_graph=True)
bsubus = grad(bsubu, x, create_graph=True)[:, 0]
bsubvs = dbsubv_dx[:, 0]
bsubsu = grad(bsubs, x, create_graph=True)[:, 1]
ps = grad(p, x, create_graph=True)[:, 0]
f_rho = bsupu * bsubus + bsupv * bsubvs - bsupu * bsubsu + mu0 * ps
bsubvu = dbsubv_dx[:, 1]
f_theta = bsubvu * bsupv
# Compute the squared norm of the contravariant metric tensor
# grad_rho**2 == gsupss
# grad_theta**2 == gsupuu
grad_rho = R**2 / jacobian**2 * (Ru**2 + Zu**2)
grad_theta = R**2 / jacobian**2 * (Rs**2 + Zs**2)
gsupsu = R**2 / jacobian**2 * (Rs * Ru + Zs * Zu)
# Compute the squared L2-norm of F
fsq = (
f_rho**2 * grad_rho + f_theta**2 * grad_theta + 2 * f_rho * f_theta * gsupsu
)
# Compute the volume-averaged ||f||2, factors missing:
# 1. in MKS units, there should be a 1 / mu0**2 factor
# 2. a 4 * pi**2 / ntheta factor due to volume-averaged integration
return (fsq * jacobian.abs()).sum()
def eps(self, x: Tensor, RlZ: Tensor, reduction: Optional[str] = "mean") -> Tensor:
# TODO: include equilibrium computation in a separate method,
# share it with `_pde_closure`
assert reduction in ("mean", None)
R = RlZ[:, 0]
l = RlZ[:, 1]
Z = RlZ[:, 2]
rho = x[:, 0]
# Compute the flux surface profiles
# self.*_fn(s), where s = rho ** 2
p = self.p_fn(rho**2)
iota = self.iota_fn(rho**2)
# Compute geometry derivatives
dR_dx = grad(R, x, create_graph=True)
Rs = dR_dx[:, 0]
Ru = dR_dx[:, 1]
dl_dx = grad(l, x, create_graph=True)
lu = dl_dx[:, 1]
dZ_dx = grad(Z, x, create_graph=True)
Zs = dZ_dx[:, 0]
Zu = dZ_dx[:, 1]
# Compute jacobian
jacobian = R * (Ru * Zs - Zu * Rs)
# Compute the magnetic fluxes derivatives
phis = self.phi_edge * rho / torch.pi
chis = iota * phis
# Compute the contravariant magnetic field components
bsupu = chis / jacobian
bsupv = phis / jacobian * (1 + lu)
# Compute the metric tensor elements
guu = Ru**2 + Zu**2
gus = Ru * Rs + Zu * Zs
gvv = R**2
# Compute the covariant magnetic field components
bsubs = bsupu * gus
bsubu = bsupu * guu
bsubv = bsupv * gvv
# Compute the covariant force components,
# actually, mu0 * f_*
dbsubv_dx = grad(bsubv, x, create_graph=True)
bsubus = grad(bsubu, x, create_graph=True)[:, 0]
bsubvs = dbsubv_dx[:, 0]
bsubsu = grad(bsubs, x, create_graph=True)[:, 1]
ps = grad(p, x, create_graph=True)[:, 0]
f_rho = bsupu * bsubus + bsupv * bsubvs - bsupu * bsubsu + mu0 * ps
bsubvu = dbsubv_dx[:, 1]
f_theta = bsubvu * bsupv
# Compute the squared norm of the contravariant metric tensor
grad_rho = R**2 / jacobian**2 * (Ru**2 + Zu**2)
grad_theta = R**2 / jacobian**2 * (Rs**2 + Zs**2)
gsupsu = R**2 / jacobian**2 * (Rs * Ru + Zs * Zu)
# Compute the squared L2-norm of F
fsq = (
f_rho**2 * grad_rho + f_theta**2 * grad_theta + 2 * f_rho * f_theta * gsupsu
)
gradpsq = (mu0 * ps) ** 2
if reduction is None:
return torch.sqrt(fsq / gradpsq)
if reduction == "mean":
return torch.sqrt(
(fsq * jacobian.abs()).sum() / (gradpsq * jacobian.abs()).sum()
)
def _mae_pde_loss(self, x: Tensor, RlZ: Tensor) -> Tensor:
print("MAE metric has not been implemented yet for the inverse GS equilibrium")
return 0
def _boundary_closure(self, x: Tensor, RlZ: Tensor) -> Tensor:
assert torch.allclose(x[:, 0], torch.ones(x.shape[0]))
theta = x[:, 1]
Rb = torch.as_tensor([self.Rb_fn(t) for t in theta])
Zb = torch.as_tensor([self.Zb_fn(t) for t in theta])
R = RlZ[:, 0]
Z = RlZ[:, 2]
return ((R - Rb) ** 2).sum() + ((Z - Zb) ** 2).sum()
def _axis_closure(self, x: Tensor, RlZ: Tensor) -> Tensor:
raise NotImplementedError()
def grid(self, ns: int = None, normalized: bool = None) -> Tensor:
if ns is None:
ns = self.ndomain
rho = torch.linspace(0, 1, ns)
theta = (2 * torch.linspace(0, 1, self.ntheta) - 1) * math.pi
grid = torch.cartesian_prod(rho, theta)
return grid
def fluxsurfacesplot(
self,
x,
ax,
interpolation: Optional[str] = None,
phi: Optional[torch.Tensor] = None,
nplot: int = 10,
scalar: Optional[torch.Tensor] = None,
contourf_kwargs: Optional[dict] = None,
add_phi_label: bool = False,
**kwargs,
):
"""
Plot flux surfaces on (R, Z) plane.
TODO: improve ns and nplot handling.
"""
assert len(x.shape) == 2
assert interpolation in (None, "linear")
if phi is None:
# Infer number of flux surfaces
ns = int(x.shape[0] / self.ntheta)
# Assume flux surfaces defined on rho
phi = torch.linspace(0, 1, ns) ** 2
else:
ns = phi.shape[0]
phi = phi.detach()
x = x.detach()
# Create plotting grid
R = x[:, 0].view(ns, -1)
Z = x[:, 1].view(ns, -1)
if nplot > ns:
nplot = ns