-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
256 lines (214 loc) · 7.32 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
"""Utility functions."""
import math
from typing import Optional, Union
import netCDF4
import numpy as np
import torch
from torch import Tensor
def grad(outputs: Tensor, inputs: Tensor, **kwargs) -> Tensor:
return torch.autograd.grad(
outputs, inputs, grad_outputs=torch.ones(outputs.shape), **kwargs
)[0]
def log_gradients(model, lr: float, t: int):
string = []
for p in model.parameters():
grad = p.grad
if grad is not None:
ratio = lr * torch.linalg.norm(grad) / torch.linalg.norm(p)
string.append(f"ratio={ratio.item():.2e}")
print(f"iter={t:5d}, " + ", ".join(string))
def mae(preds: Tensor, target: Tensor, eps=1.17e-6):
mae = (preds - target).abs() / torch.clamp(torch.abs(target), min=eps)
return mae.mean()
def get_wout(wout_path: str):
return netCDF4.Dataset(wout_path)
def get_profile_from_wout(wout_path: str, profile: str):
"""
Get f(psi) = R**2 * Bsupv or p(psi) from a vmec equilibrium.
Psi is the poloidal flux, which is called chi in VMEC.
"""
assert profile in ("p", "f")
wout = get_wout(wout_path)
# Compute chi (i.e., domain) on half-mesh, normalized to boundary value
phi = wout["phi"][:].data
phi_edge = phi[-1]
chi = wout["chi"][:].data
chi_edge = chi[-1]
if profile == "p":
# Get pressure
p = np.polynomial.Polynomial(wout["am"][:].data)
p_fit = np.polynomial.Polynomial.fit(
chi / chi_edge, p(phi / phi_edge), deg=5, domain=[0, 1], window=[0, 1]
)
return p_fit.coef.tolist()
# In VMEC terms, bvco == f(psi)
# See bcovar.f
bvco = wout["bvco"][:].data
# Move it to full mesh
f = np.empty_like(bvco)
f[1:-1] = 0.5 * (bvco[1:-1] + bvco[2:])
# Extend it to axis and LCFS
f[0] = 1.5 * bvco[1] - 0.5 * bvco[2]
f[-1] = 1.5 * bvco[-1] - 0.5 * bvco[-2]
# Perform f**2 fit
f_fit = np.polynomial.Polynomial.fit(
chi / chi_edge, f**2, deg=5, domain=[0, 1], window=[0, 1]
)
return f_fit.coef.tolist()
def get_flux_surfaces_from_wout(wout_path: str):
wout = get_wout(wout_path)
rmnc = torch.as_tensor(wout["rmnc"][:]).clone()
zmns = torch.as_tensor(wout["zmns"][:]).clone()
R = ift(rmnc, basis="cos")
Z = ift(zmns, basis="sin")
# Return poloidal on the flux surfaces also
chi = torch.as_tensor(wout["chi"][:]).clone()
# Return flux surfaces as grid
return torch.stack([R.view(-1), Z.view(-1)], dim=-1), chi
def ift(
xm: Tensor,
basis: str,
ntheta: Optional[Union[int, Tensor]] = 40,
endpoint: Optional[bool] = True,
):
"""The inverse Fourier transform."""
assert basis in ("cos", "sin")
assert len(xm.shape) <= 2
if isinstance(ntheta, Tensor):
theta = ntheta
else:
if endpoint:
theta = torch.linspace(0, 2 * math.pi, ntheta, dtype=xm.dtype)
else:
theta = torch.linspace(0, 2 * math.pi, ntheta + 1, dtype=xm.dtype)[:-1]
mpol = xm.shape[-1]
tm = torch.outer(theta, torch.arange(mpol, dtype=xm.dtype))
if basis == "cos":
tm = torch.cos(tm)
else:
tm = torch.sin(tm)
# One flux surface only
if len(xm.shape) == 1:
return (tm * xm).sum(dim=1)
# Multiple flux surfaces
tm = tm[None, ...]
return torch.einsum("stm,sm->st", tm, xm).contiguous()
def get_solovev_boundary(
Ra: float,
p0: float,
psi_0: float,
mpol: int = 5,
tolerance: float = 1e-4,
tolerance_change: float = 1e-9,
):
"""
Get Fourier coefficients which describe a given Solov'ev boundary.
Examples:
>>> from utils import get_solovev_boundary
>>> Rb = get_solovev_boundary(Ra=4.0, p0=0.125, psi_0=1.0)
>>> len(Rb)
5
"""
# Build theta grid
ntheta = 40
theta = torch.linspace(0, 2 * math.pi, ntheta, dtype=torch.float64)
# Build boundary from analytical Solov'ev solution
# R**2 = Ra**2 - psi_0 sqrt(8 / p0) rho cos(theta)
Rsq = Ra**2 - psi_0 * math.sqrt(8 / p0) * torch.cos(theta)
# Build boundary and set initial guess
Rb = torch.zeros(mpol, dtype=torch.float64)
Rb[0] = Ra
Rb.requires_grad_(True)
optim = torch.optim.LBFGS([Rb], lr=1e-2)
def loss_fn():
R = ift(Rb, basis="cos", ntheta=ntheta)
return ((R**2 - Rsq) ** 2).sum()
def closure():
optim.zero_grad()
loss = loss_fn()
loss.backward()
return loss
# Get initial loss
loss = loss_fn()
while True:
loss_old = loss
optim.step(closure)
loss = loss_fn()
if loss < tolerance:
break
if abs(loss_old.item() - loss.item()) < tolerance_change:
break
return Rb.detach()
def get_RlZ_from_wout(x: Tensor, wout_path: str):
"""
Compute flux surfaces geometry on a given grid from a VMEC wout file.
Args:
x (torch.Tensor): the rho-theta grid on which to compute the RlZ tensor.
wout_path (str): the wout file path.
"""
wout = get_wout(wout_path)
rho = x[:, 0]
theta = x[:, 1]
ns = wout["ns"][:].data.item()
hs = 1 / (ns - 1)
xm = torch.from_numpy(wout["xm"][:].data).to(int)
def interp_xmn(x: str):
phi = torch.from_numpy(wout["phi"][:].data)
phi = phi / phi[-1]
xmn = torch.from_numpy(wout[x][:].data)
xmns = []
# lmns is defined on half-mesh
if x == "lmns":
phi = torch.linspace(0, 1, ns)[1:] - 0.5 / (ns - 1)
xmn = xmn[1:]
for m in xm:
# Interpolate xmn / rho ** m
xmn_ = xmn[:, m]
if m != 0:
xmn_ = xmn[:, m] / torch.sqrt(phi) ** m
# Quadratic interpolation
idx_l = (
torch.argmin(
torch.relu(rho.detach()[:, None] ** 2 - phi[None, :]), dim=1
)
- 1
)
# Boundary indices
if m == 0:
idx_l[idx_l == -1] = 0
else:
idx_l[idx_l == -1] = 1
idx_l[idx_l == 0] = 1
idx_l[idx_l == len(phi) - 2] = len(phi) - 3
# Coefficients for the quadratic interpolation
# f(x) = b0 + b1 * (x - x0) + b2 * (x - x0) * (x - x1)
b0 = xmn_[idx_l]
b1 = (xmn_[idx_l + 1] - xmn_[idx_l]) / hs
b2 = (xmn_[idx_l + 2] - 2 * xmn_[idx_l + 1] + xmn_[idx_l]) / (2 * hs**2)
interp = (
b0
+ b1 * (rho**2 - phi[idx_l])
+ b2 * (rho**2 - phi[idx_l]) * (rho**2 - phi[idx_l + 1])
)
# Linearly interpolate on axis
if m != 0:
# TODO: this has no effect due to line 216 and 217
interp[idx_l == 0] = xmn[1, m] / phi[1] ** (m / 2)
# Add back the rho**m factor
interp *= rho**m
xmns.append(interp)
return torch.stack(xmns, dim=-1)
rmnc = interp_xmn("rmnc")
lmns = interp_xmn("lmns")
zmns = interp_xmn("zmns")
def get_x(xmn, basis):
angle = theta[:, None] * xm[None, :]
if basis == "cos":
tm = torch.cos(angle)
else:
tm = torch.sin(angle)
return (tm * xmn).sum(dim=1)
R = get_x(rmnc, basis="cos")
l = get_x(lmns, basis="sin")
Z = get_x(zmns, basis="sin")
return torch.stack([R, l, Z], dim=-1)