Continuation method step by step
In this example we step through the continuation method step by step - starting from an axisymmetric vacuum configuration, adding 3D shaping, and then adding pressure.
If you have access to a GPU, uncomment the following two lines. You should see about an order of magnitude speed improvement with only these two lines of code!
[2]:
# from desc import set_device
# set_device("gpu")
[3]:
%matplotlib inline
import numpy as np
from desc.equilibrium import Equilibrium
from desc.geometry import FourierRZToroidalSurface
from desc.objectives import (
ObjectiveFunction,
ForceBalance,
get_fixed_boundary_constraints,
)
from desc.optimize import Optimizer
from desc.plotting import plot_1d, plot_section, plot_surfaces
from desc.profiles import PowerSeriesProfile
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
DESC version 0.12.1+206.g91d82b558.dirty,using JAX backend, jax version=0.4.31, jaxlib version=0.4.31, dtype=float64
Using device: CPU, with 7.44 GB available memory
2D Equilibrium
We start by creating the surface object that represents the axisymmetric boundary.
[4]:
surface_2D = FourierRZToroidalSurface(
R_lmn=np.array([10, -1]), # boundary coefficients
Z_lmn=np.array([1]),
modes_R=np.array([[0, 0], [1, 0]]), # [M, N] boundary Fourier modes
modes_Z=np.array([[-1, 0]]),
NFP=5, # number of (toroidal) field periods (does not matter for 2D, but will for 3D solution)
)
Now we can initialize an Equilibrium with this boundary surface. By default, Equilibrium objects have pressure and net toroidal current profiles of 0 assigned. We also increase the resolution and use a collocation grid that oversamples by a factor of two.
[5]:
# axisymmetric & stellarator symmetric equilibrium
eq = Equilibrium(surface=surface_2D, sym=True)
eq.change_resolution(L=6, M=6, L_grid=12, M_grid=12)
Next we create our objective function, ForceBalance which will seek to make \(\mathbf{F} \equiv \mathbf{J} \times \mathbf{B} - \nabla p = 0\)
[6]:
objective = ObjectiveFunction(ForceBalance(eq=eq))
Next we need to specify the optimization constraints, which indicate what parameters that will remain fixed during the optimization process. For this fixed-boundary problem we can call the utility function get_fixed_boundary_constraints that returns a list of the desired constraints.
[7]:
constraints = get_fixed_boundary_constraints(eq=eq)
for c in constraints:
print(c)
<desc.objectives.linear_objectives.FixBoundaryR object at 0x7f6bb02e83b0>
<desc.objectives.linear_objectives.FixBoundaryZ object at 0x7f6ac8168d10>
<desc.objectives.linear_objectives.FixPsi object at 0x7f6abe7e6510>
<desc.objectives.linear_objectives.FixPressure object at 0x7f6abc58f410>
<desc.objectives.linear_objectives.FixCurrent object at 0x7f6ac8133b00>
<desc.objectives.linear_objectives.FixSheetCurrent object at 0x7f6abe7e7020>
Finally, we can solve the equilibrium with the objective and constraints specified above. We also chose an optimization algorithm by initializing an Optimizer object. The verbose=3 option will display output at each optimization step.
[8]:
# this is a port of scipy's trust region least squares algorithm but using JAX functions for better performance
optimizer = Optimizer("lsq-exact")
eq, solver_outputs = eq.solve(
objective=objective, constraints=constraints, optimizer=optimizer, verbose=3
)
Building objective: force
Precomputing transforms
Timer: Precomputing transforms = 1.33 sec
Timer: Objective build = 3.29 sec
Building objective: lcfs R
Building objective: lcfs Z
Building objective: fixed Psi
Building objective: fixed pressure
Building objective: fixed current
Building objective: fixed sheet current
Building objective: self_consistency R
Building objective: self_consistency Z
Building objective: lambda gauge
Building objective: axis R self consistency
Building objective: axis Z self consistency
Timer: Objective build = 1.03 sec
Timer: Linear constraint projection build = 2.09 sec
Number of parameters: 27
Number of objectives: 98
Timer: Initializing the optimization = 6.48 sec
Starting optimization
Using method: lsq-exact
Iteration Total nfev Cost Cost reduction Step norm Optimality
0 1 5.673e-03 7.906e-01
1 2 1.043e-03 4.630e-03 2.108e-01 4.674e-01
2 3 1.068e-04 9.364e-04 8.901e-02 1.732e-01
3 4 2.265e-06 1.045e-04 5.145e-02 1.316e-02
4 5 1.600e-07 2.105e-06 3.861e-02 4.114e-03
5 6 1.067e-08 1.493e-07 1.658e-02 2.267e-03
6 7 9.095e-11 1.058e-08 3.866e-03 1.176e-04
7 8 5.407e-11 3.688e-11 8.400e-03 3.550e-04
8 9 2.028e-13 5.387e-11 9.622e-04 8.112e-06
9 11 3.892e-14 1.639e-13 9.001e-04 2.203e-06
10 14 1.047e-15 3.787e-14 1.368e-04 2.946e-07
11 16 9.397e-17 9.531e-16 6.484e-05 9.294e-08
12 18 6.842e-18 8.713e-17 3.527e-05 2.616e-08
13 20 1.369e-18 5.473e-18 1.983e-05 4.842e-09
`gtol` condition satisfied.
Current function value: 1.369e-18
Total delta_x: 1.839e-01
Iterations: 13
Function evaluations: 20
Jacobian evaluations: 14
Timer: Solution time = 4.06 sec
Timer: Avg time per step = 290 ms
==============================================================================================================
Start --> End
Total (sum of squares): 5.673e-03 --> 1.369e-18,
Maximum absolute Force error: 7.882e+04 --> 5.229e-03 (N)
Minimum absolute Force error: 1.042e-11 --> 2.308e-06 (N)
Average absolute Force error: 2.555e+04 --> 3.431e-04 (N)
Maximum absolute Force error: 4.952e-03 --> 3.285e-10 (normalized)
Minimum absolute Force error: 6.547e-19 --> 1.450e-13 (normalized)
Average absolute Force error: 1.605e-03 --> 2.155e-11 (normalized)
R boundary error: 0.000e+00 --> 0.000e+00 (m)
Z boundary error: 0.000e+00 --> 0.000e+00 (m)
Fixed Psi error: 0.000e+00 --> 0.000e+00 (Wb)
Fixed pressure profile error: 0.000e+00 --> 0.000e+00 (Pa)
Fixed current profile error: 0.000e+00 --> 0.000e+00 (A)
Fixed sheet current error: 0.000e+00 --> 0.000e+00 (~)
==============================================================================================================
We can analyze the equilibrium solution using the available plotting routines. . Here we plot the magnitude of the total current density \(|\mathbf{J}|\) and the normalized force balance error. We expect both quantities to be low for this vacuum solution.
[9]:
plot_section(eq, "|J|")
plot_section(eq, "|F|", norm_F=True, log=True);
Since this is an axisymmetric vacuum equilibrium, there should be no pressure or rotational transform. We can plot both quantities as follows:
[10]:
plot_1d(eq, "p")
plot_1d(eq, "iota")
[10]:
(<Figure size 384.108x384.108 with 1 Axes>,
<Axes: xlabel='$\\rho$', ylabel='$ \\iota ~(~)$'>)
3D Equilibrium
Now we want to solve a stellarator vacuum equilibrium by perturbing the existing tokamak solution we already found. We start by creating a new surface to represent the 3D (non-axisymmetric) stellarator boundary.
[11]:
surface_3D = FourierRZToroidalSurface(
R_lmn=np.array([10, -1, -0.3, 0.3]), # boundary coefficients
Z_lmn=np.array([1, -0.3, -0.3]),
modes_R=np.array(
[[0, 0], [1, 0], [1, 1], [-1, -1]]
), # [M, N] boundary Fourier modes
modes_Z=np.array([[-1, 0], [-1, 1], [1, -1]]),
NFP=5, # number of (toroidal) field periods
)
In the previous solution we did not use any toroidal Fourier modes because they were unnecessary for axisymmetry. Now we need to increase the toroidal resolution, and we will also increase the radial and poloidal resolutions as well. Again we oversample the collocation grid by a factor of two.
We will also update the resolution of the 3D surface to match the new resolution of the Equilibrium.
[12]:
eq.change_resolution(L=10, M=10, N=6, L_grid=20, M_grid=20, N_grid=12)
surface_3D.change_resolution(eq.L, eq.M, eq.N)
We need to initialize new instances of the objective and constraints. This is necessary because the original instances got built for a specific resolution during the previous 2D equilibrium solve, and are no longer compatible with the Equilibrium after increasing the resolution.
[13]:
objective = ObjectiveFunction(ForceBalance(eq=eq))
constraints = get_fixed_boundary_constraints(eq=eq)
Next is the boundary perturbation. In this step, we approximate the heliotron equilibrium solution from a 2nd-order Taylor expansion about the axisymmetric solution. This is possible thanks to the wealth of derivative information provided by automatic differentiation.
[14]:
eq.perturb(
deltas={
"Rb_lmn": surface_3D.R_lmn - eq.Rb_lmn, # change in the R boundary coefficients
"Zb_lmn": surface_3D.Z_lmn - eq.Zb_lmn, # change in the Z boundary coefficients
},
objective=objective, # perturb the solution such that J=0 is maintained
constraints=constraints, # same constraints used in the equilibrium solve
order=2, # use a 2nd-order Taylor expansion
verbose=2, # display timing data
)
Building objective: force
Precomputing transforms
Timer: Precomputing transforms = 849 ms
Timer: Objective build = 2.71 sec
Building objective: lcfs R
Building objective: lcfs Z
Building objective: fixed Psi
Building objective: fixed pressure
Building objective: fixed current
Building objective: fixed sheet current
Building objective: self_consistency R
Building objective: self_consistency Z
Building objective: lambda gauge
Building objective: axis R self consistency
Building objective: axis Z self consistency
Timer: Objective build = 1.11 sec
Perturbing Rb_lmn, Zb_lmn
Factorizing linear constraints
Timer: linear constraint factorize = 2.72 sec
Computing df
Timer: df computation = 7.78 sec
Factoring df
Timer: df/dx factorization = 1.61 sec
Computing d^2f
Timer: d^2f computation = 4.64 sec
Timer: Objective build = 11.7 ms
||dx||/||x|| = 3.927e-02
Timer: Total perturbation = 20.9 sec
[14]:
Equilibrium at 0x7f6c0da23110 (L=10, M=10, N=6, NFP=5, sym=True, spectral_indexing=ansi)
We now have an approximation of the stellarator equilibrium from the tokamak solution! Let us look at the 3D surfaces and rotational transform profile to check that the perturbation actually updated the solution:
[15]:
plot_surfaces(eq)
plot_1d(eq, "iota");
The surfaces match the heliotron boundary we want and there is non-zero rotational transform as expected. But the equilibrium error is now large because the perturbed solution is only an approximation to the true equilibrium:
[16]:
plot_section(eq, "|F|", norm_F=True, log=True);
We can re-solve the equilibrium using the new 3D boundary constraint. This should converge in only a few Newton iterations because we are starting from a good initial guess.
[17]:
eq, solver_outputs = eq.solve(
objective=objective, # solve JxB-grad(p)=0
constraints=constraints, # fixed-boundary constraints
optimizer=optimizer, # we can use the same optimizer as before
ftol=1e-2, # stopping tolerance on the function value
xtol=1e-4, # stopping tolerance on the step size
gtol=1e-6, # stopping tolerance on the gradient
maxiter=20, # maximum number of iterations
verbose=3, # display output at each iteration
)
Building objective: self_consistency R
Building objective: self_consistency Z
Building objective: lambda gauge
Building objective: axis R self consistency
Building objective: axis Z self consistency
Timer: Objective build = 34.1 ms
Timer: Linear constraint projection build = 1.95 sec
Number of parameters: 1011
Number of objectives: 6050
Timer: Initializing the optimization = 2.08 sec
Starting optimization
Using method: lsq-exact
Iteration Total nfev Cost Cost reduction Step norm Optimality
0 1 5.765e-02 9.160e+00
1 2 1.070e-03 5.658e-02 1.248e-01 1.522e+00
2 3 8.111e-05 9.886e-04 7.494e-02 5.101e-01
3 4 5.262e-05 2.849e-05 1.234e-01 2.564e-01
4 5 2.111e-06 5.051e-05 5.972e-02 5.068e-02
5 7 5.156e-07 1.595e-06 5.028e-02 2.162e-02
6 9 1.196e-07 3.960e-07 4.441e-02 1.192e-02
7 11 1.263e-08 1.070e-07 2.252e-02 2.975e-03
8 13 2.470e-09 1.016e-08 1.284e-02 9.771e-04
9 15 1.081e-09 1.389e-09 6.754e-03 2.598e-04
10 17 9.557e-10 1.248e-10 3.367e-03 5.869e-05
11 18 9.073e-10 4.846e-11 6.367e-03 1.940e-04
12 19 8.292e-10 7.808e-11 5.764e-03 1.364e-04
13 20 8.283e-10 8.702e-13 8.949e-03 2.381e-04
14 21 6.810e-10 1.474e-10 1.960e-03 1.299e-05
15 22 6.435e-10 3.746e-11 3.380e-03 5.026e-05
16 23 6.132e-10 3.029e-11 5.628e-03 1.546e-04
17 24 5.447e-10 6.850e-11 5.526e-03 1.328e-04
18 25 4.866e-10 5.812e-11 5.756e-03 1.362e-04
19 26 4.293e-10 5.733e-11 5.998e-03 1.249e-04
20 27 3.723e-10 5.698e-11 6.209e-03 9.977e-05
Warning: Maximum number of iterations has been exceeded.
Current function value: 3.723e-10
Total delta_x: 2.573e-01
Iterations: 20
Function evaluations: 27
Jacobian evaluations: 21
Timer: Solution time = 2.69 min
Timer: Avg time per step = 7.68 sec
==============================================================================================================
Start --> End
Total (sum of squares): 5.765e-02 --> 3.723e-10,
Maximum absolute Force error: 3.731e+06 --> 5.640e+01 (N)
Minimum absolute Force error: 1.387e-01 --> 1.790e-03 (N)
Average absolute Force error: 5.623e+04 --> 5.063e+00 (N)
Maximum absolute Force error: 2.344e-01 --> 3.544e-06 (normalized)
Minimum absolute Force error: 8.712e-09 --> 1.125e-10 (normalized)
Average absolute Force error: 3.533e-03 --> 3.181e-07 (normalized)
R boundary error: 0.000e+00 --> 0.000e+00 (m)
Z boundary error: 0.000e+00 --> 0.000e+00 (m)
Fixed Psi error: 0.000e+00 --> 0.000e+00 (Wb)
Fixed pressure profile error: 0.000e+00 --> 0.000e+00 (Pa)
Fixed current profile error: 0.000e+00 --> 0.000e+00 (A)
Fixed sheet current error: 0.000e+00 --> 0.000e+00 (~)
==============================================================================================================
We can analyze our final solution using the same plotting commands as before. Note that the flux surfaces and rotational transform profile only had small corrections compared to the perturbed solution, but the equilibrium error was significantly improved.
[18]:
plot_surfaces(eq)
plot_1d(eq, "iota")
plot_section(eq, "|J|", log=True)
plot_section(eq, "|F|", norm_F=True, log=True);
Finite beta stellarator
We’ve solved for a vacuum stellarator, but what if we now want to look at what happens at finite beta? We can simply apply a pressure perturbation.
[19]:
from desc.objectives import ForceBalance
objective = ObjectiveFunction(ForceBalance(eq=eq))
constraints = get_fixed_boundary_constraints(eq=eq, profiles=True)
Next we’ll make our desired pressure profile, corresponding to a profile of the form \(p(\rho) = 2000(1 - 2 \rho^2 + \rho^4) ~\text{Pa}\)
[20]:
from desc.profiles import PowerSeriesProfile
pressure = PowerSeriesProfile([2000, 0, -4000, 0, 2000])
pressure.change_resolution(eq.L)
[21]:
eq.perturb(
deltas={"p_l": pressure.params - eq.p_l}, # change in the pressure coefficients
objective=objective, # perturb the solution such that JxB-grad(p)=0 is maintained
constraints=constraints, # same constraints used in the equilibrium solve
order=2, # use a 2nd-order Taylor expansion
verbose=2, # display timing data
)
Building objective: force
Precomputing transforms
Timer: Precomputing transforms = 48.8 ms
Timer: Objective build = 179 ms
Building objective: lcfs R
Building objective: lcfs Z
Building objective: fixed Psi
Building objective: fixed pressure
Building objective: fixed current
Building objective: fixed sheet current
Building objective: self_consistency R
Building objective: self_consistency Z
Building objective: lambda gauge
Building objective: axis R self consistency
Building objective: axis Z self consistency
Timer: Objective build = 681 ms
Perturbing p_l
Factorizing linear constraints
Timer: linear constraint factorize = 1.49 sec
Computing df
Timer: df computation = 8.14 sec
Factoring df
Timer: df/dx factorization = 2.54 sec
Computing d^2f
Timer: d^2f computation = 5.35 sec
Timer: Objective build = 10.6 ms
||dx||/||x|| = 6.456e-02
Timer: Total perturbation = 20.4 sec
[21]:
Equilibrium at 0x7f6c0da23110 (L=10, M=10, N=6, NFP=5, sym=True, spectral_indexing=ansi)
We can see that the axis has moved due to the Shafranov shift, and the pressure profile is now nonzero. The force balance error is significantly larger, however.
[22]:
plot_surfaces(eq)
plot_1d(eq, "p")
plot_section(eq, "|F|", norm_F=True, log=True);
[23]:
eq, solver_outputs = eq.solve(
objective=objective, # solve JxB-grad(p)=0
constraints=constraints, # fixed-boundary and profile constraints
optimizer=optimizer, # we can use the same optimizer as before
ftol=1e-2, # stopping tolerance on the function value
xtol=1e-4, # stopping tolerance on the step size
gtol=1e-6, # stopping tolerance on the gradient
maxiter=75, # maximum number of iterations
verbose=3, # display output at each iteration
)
Building objective: self_consistency R
Building objective: self_consistency Z
Building objective: lambda gauge
Building objective: axis R self consistency
Building objective: axis Z self consistency
Timer: Objective build = 38.1 ms
Timer: Linear constraint projection build = 1.53 sec
Number of parameters: 1011
Number of objectives: 6050
Timer: Initializing the optimization = 1.65 sec
Starting optimization
Using method: lsq-exact
Iteration Total nfev Cost Cost reduction Step norm Optimality
0 1 3.356e-02 4.474e+01
1 2 1.504e-04 3.341e-02 5.810e-02 9.784e-01
2 5 1.353e-05 1.369e-04 2.660e-02 7.610e-01
3 7 8.706e-07 1.266e-05 1.346e-02 7.776e-02
4 9 4.795e-07 3.910e-07 7.965e-03 2.144e-02
5 11 4.466e-07 3.297e-08 3.992e-03 4.243e-03
6 12 4.443e-07 2.289e-09 7.703e-03 2.832e-02
7 13 4.228e-07 2.144e-08 1.893e-03 1.802e-03
8 14 4.162e-07 6.655e-09 3.684e-03 7.702e-03
9 16 4.115e-07 4.676e-09 1.815e-03 1.929e-03
10 17 4.057e-07 5.854e-09 3.532e-03 7.698e-03
11 19 4.014e-07 4.272e-09 1.741e-03 1.875e-03
12 20 3.961e-07 5.289e-09 3.383e-03 7.191e-03
13 22 3.922e-07 3.859e-09 1.667e-03 1.734e-03
Optimization terminated successfully.
`ftol` condition satisfied.
Current function value: 3.922e-07
Total delta_x: 9.003e-02
Iterations: 13
Function evaluations: 22
Jacobian evaluations: 14
Timer: Solution time = 1.18 min
Timer: Avg time per step = 5.07 sec
==============================================================================================================
Start --> End
Total (sum of squares): 3.356e-02 --> 3.922e-07,
Maximum absolute Force error: 6.931e+05 --> 8.901e+02 (N)
Minimum absolute Force error: 1.202e+01 --> 9.656e-03 (N)
Average absolute Force error: 2.817e+04 --> 1.025e+02 (N)
Maximum absolute Force error: 7.536e-02 --> 9.677e-05 (normalized)
Minimum absolute Force error: 1.307e-06 --> 1.050e-09 (normalized)
Average absolute Force error: 3.062e-03 --> 1.115e-05 (normalized)
R boundary error: 0.000e+00 --> 0.000e+00 (m)
Z boundary error: 0.000e+00 --> 0.000e+00 (m)
Fixed Psi error: 0.000e+00 --> 0.000e+00 (Wb)
Fixed pressure profile error: 0.000e+00 --> 0.000e+00 (Pa)
Fixed current profile error: 0.000e+00 --> 0.000e+00 (A)
Fixed sheet current error: 0.000e+00 --> 0.000e+00 (~)
==============================================================================================================
After re-solving, we find the force blance residuals are much lower, less than 1% normalized errors throughout the volume:
[24]:
plot_section(eq, "|F|", norm_F=True, log=True);