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
DESC version 0.10.2+280.gad1dd690.dirty,using JAX backend, jax version=0.4.13, jaxlib version=0.4.13, dtype=float64
Using device: CPU, with 14.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 0x7f17b152f7c0>
<desc.objectives.linear_objectives.FixBoundaryZ object at 0x7f17b152f460>
<desc.objectives.linear_objectives.FixPsi object at 0x7f17b152f670>
<desc.objectives.linear_objectives.FixPressure object at 0x7f17b152f9a0>
<desc.objectives.linear_objectives.FixCurrent object at 0x7f17b152f700>

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 = 4.17 sec
Timer: Objective build = 8.29 sec
Timer: Linear constraint projection build = 4.57 sec
Compiling objective function and derivatives: ['force']
Timer: Objective compilation time = 1.40 sec
Timer: Jacobian compilation time = 3.07 sec
Timer: Total compilation time = 4.48 sec
Number of parameters: 27
Number of objectives: 98
Starting optimization
Using method: lsq-exact
   Iteration     Total nfev        Cost      Cost reduction    Step norm     Optimality
       0              1          5.673e-03                                    6.271e-01
       1              2          1.043e-03      4.630e-03      2.108e-01      4.286e-01
       2              3          1.068e-04      9.364e-04      8.901e-02      1.354e-01
       3              4          2.265e-06      1.045e-04      5.145e-02      1.341e-02
       4              5          1.600e-07      2.105e-06      3.861e-02      4.019e-03
       5              6          1.067e-08      1.493e-07      1.658e-02      1.960e-03
       6              7          9.095e-11      1.058e-08      3.866e-03      1.085e-04
       7              8          5.407e-11      3.688e-11      8.400e-03      2.692e-04
       8              9          2.028e-13      5.387e-11      9.622e-04      6.896e-06
       9             11          3.245e-14      1.704e-13      6.780e-04      2.137e-06
      10             13          3.277e-15      2.917e-14      2.260e-04      6.548e-07
      11             15          5.597e-16      2.718e-15      1.074e-04      2.288e-07
      12             16          4.640e-16      9.570e-17      3.502e-04      2.504e-07
      13             17          5.172e-18      4.588e-16      9.745e-05      1.657e-08
      14             19          1.720e-19      5.000e-18      4.832e-05      2.899e-09
`gtol` condition satisfied.
         Current function value: 1.720e-19
         Total delta_x: 1.839e-01
         Iterations: 14
         Function evaluations: 19
         Jacobian evaluations: 15
Timer: Solution time = 4.24 sec
Timer: Avg time per step = 282 ms
Start of solver
Total (sum of squares):  5.673e-03,
Maximum absolute Force error:  7.882e+04 (N)
Minimum absolute Force error:  1.042e-11 (N)
Average absolute Force error:  2.555e+04 (N)
Maximum absolute Force error:  4.952e-03 (normalized)
Minimum absolute Force error:  6.547e-19 (normalized)
Average absolute Force error:  1.605e-03 (normalized)
R boundary error:  0.000e+00 (m)
Z boundary error:  0.000e+00 (m)
Fixed-Psi error:  0.000e+00 (Wb)
Fixed-pressure profile error:  0.000e+00 (Pa)
Fixed-current profile error:  0.000e+00 (A)
End of solver
Total (sum of squares):  1.720e-19,
Maximum absolute Force error:  1.661e-03 (N)
Minimum absolute Force error:  2.852e-06 (N)
Average absolute Force error:  1.160e-04 (N)
Maximum absolute Force error:  1.044e-10 (normalized)
Minimum absolute Force error:  1.792e-13 (normalized)
Average absolute Force error:  7.286e-12 (normalized)
R boundary error:  0.000e+00 (m)
Z boundary error:  0.000e+00 (m)
Fixed-Psi error:  0.000e+00 (Wb)
Fixed-pressure profile error:  0.000e+00 (Pa)
Fixed-current profile error:  0.000e+00 (A)

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);
../../_images/notebooks_tutorials_continuation_step_by_step_18_0.png
../../_images/notebooks_tutorials_continuation_step_by_step_18_1.png

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 288x288 with 1 Axes>,
 <AxesSubplot:xlabel='$\\rho$', ylabel='$ \\iota ~(~)$'>)
../../_images/notebooks_tutorials_continuation_step_by_step_20_1.png
../../_images/notebooks_tutorials_continuation_step_by_step_20_2.png

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 = 1.75 sec
Timer: Objective build = 4.89 sec
Perturbing Rb_lmn, Zb_lmn
Factorizing linear constraints
Timer: linear constraint factorize = 2.70 sec
Computing df
Timer: df computation = 16.0 sec
Factoring df
Timer: df/dx factorization = 993 ms
Computing d^2f
Timer: d^2f computation = 11.7 sec
||dx||/||x|| =  3.775e-02
Timer: Total perturbation = 35.3 sec
[14]:
Equilibrium at 0x7f17b152f4c0 (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");
No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
../../_images/notebooks_tutorials_continuation_step_by_step_31_1.png
../../_images/notebooks_tutorials_continuation_step_by_step_31_2.png

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);
../../_images/notebooks_tutorials_continuation_step_by_step_33_0.png

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
)
Timer: Linear constraint projection build = 1.97 sec
Compiling objective function and derivatives: ['force']
Timer: Objective compilation time = 2.27 sec
Timer: Jacobian compilation time = 7.66 sec
Timer: Total compilation time = 9.94 sec
Number of parameters: 1011
Number of objectives: 6050
Starting optimization
Using method: lsq-exact
   Iteration     Total nfev        Cost      Cost reduction    Step norm     Optimality
       0              1          7.428e-02                                    1.445e+01
       1              2          2.140e-03      7.214e-02      1.291e-01      3.965e+00
       2              3          1.398e-04      2.001e-03      1.116e-01      6.969e-01
       3              4          3.443e-05      1.053e-04      8.128e-02      2.881e-01
       4              5          2.015e-05      1.428e-05      1.067e-01      1.408e-01
       5              6          1.059e-06      1.909e-05      6.011e-02      2.870e-02
       6              7          7.184e-08      9.876e-07      3.398e-02      8.516e-03
       7              8          2.418e-09      6.942e-08      8.535e-03      2.212e-03
       8              9          1.255e-09      1.163e-09      5.051e-03      1.615e-03
       9             10          2.899e-10      9.647e-10      3.426e-03      8.323e-04
      10             11          1.524e-11      2.746e-10      1.662e-03      2.486e-04
      11             12          6.143e-12      9.095e-12      1.346e-03      1.586e-04
Optimization terminated successfully.
`xtol` condition satisfied.
         Current function value: 6.143e-12
         Total delta_x: 3.355e-01
         Iterations: 11
         Function evaluations: 12
         Jacobian evaluations: 12
Timer: Solution time = 1.31 min
Timer: Avg time per step = 6.57 sec
Start of solver
Total (sum of squares):  7.428e-02,
Maximum absolute Force error:  3.724e+06 (N)
Minimum absolute Force error:  1.109e+00 (N)
Average absolute Force error:  5.825e+04 (N)
Maximum absolute Force error:  2.340e-01 (normalized)
Minimum absolute Force error:  6.967e-08 (normalized)
Average absolute Force error:  3.660e-03 (normalized)
R boundary error:  0.000e+00 (m)
Z boundary error:  0.000e+00 (m)
Fixed-Psi error:  0.000e+00 (Wb)
Fixed-pressure profile error:  0.000e+00 (Pa)
Fixed-current profile error:  0.000e+00 (A)
End of solver
Total (sum of squares):  6.143e-12,
Maximum absolute Force error:  2.730e+01 (N)
Minimum absolute Force error:  2.219e-05 (N)
Average absolute Force error:  5.460e-01 (N)
Maximum absolute Force error:  1.715e-06 (normalized)
Minimum absolute Force error:  1.394e-12 (normalized)
Average absolute Force error:  3.430e-08 (normalized)
R boundary error:  0.000e+00 (m)
Z boundary error:  0.000e+00 (m)
Fixed-Psi error:  0.000e+00 (Wb)
Fixed-pressure profile error:  0.000e+00 (Pa)
Fixed-current profile error:  0.000e+00 (A)

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);
No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
../../_images/notebooks_tutorials_continuation_step_by_step_37_1.png
../../_images/notebooks_tutorials_continuation_step_by_step_37_2.png
../../_images/notebooks_tutorials_continuation_step_by_step_37_3.png
../../_images/notebooks_tutorials_continuation_step_by_step_37_4.png

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 = 234 ms
Timer: Objective build = 561 ms
Perturbing p_l
Factorizing linear constraints
Timer: linear constraint factorize = 1.79 sec
Computing df
Timer: df computation = 15.7 sec
Factoring df
Timer: df/dx factorization = 892 ms
Computing d^2f
Timer: d^2f computation = 11.6 sec
||dx||/||x|| =  6.325e-02
Timer: Total perturbation = 32.2 sec
[21]:
Equilibrium at 0x7f17b152f4c0 (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);
No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
../../_images/notebooks_tutorials_continuation_step_by_step_45_1.png
../../_images/notebooks_tutorials_continuation_step_by_step_45_2.png
../../_images/notebooks_tutorials_continuation_step_by_step_45_3.png
[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
)
Timer: Linear constraint projection build = 641 ms
Compiling objective function and derivatives: ['force']
Timer: Objective compilation time = 2.26 sec
Timer: Jacobian compilation time = 7.83 sec
Timer: Total compilation time = 10.1 sec
Number of parameters: 1011
Number of objectives: 6050
Starting optimization
Using method: lsq-exact
   Iteration     Total nfev        Cost      Cost reduction    Step norm     Optimality
       0              1          1.176e-01                                    4.329e+01
       1              2          1.336e-03      1.162e-01      9.653e-02      8.839e+00
       2              3          6.489e-04      6.876e-04      1.147e-01      3.173e+00
       3              5          2.238e-04      4.251e-04      5.974e-02      4.057e+00
       4              6          2.832e-05      1.955e-04      6.178e-02      7.364e-01
       5              8          7.778e-06      2.054e-05      2.607e-02      4.198e-01
       6              9          2.482e-06      5.296e-06      3.159e-02      2.647e-01
       7             10          1.490e-06      9.920e-07      2.960e-02      1.102e-01
       8             12          1.962e-07      1.294e-06      8.119e-03      8.609e-03
       9             14          1.826e-07      1.365e-08      3.852e-03      2.700e-03
      10             16          1.803e-07      2.301e-09      1.943e-03      5.940e-04
      11             17          1.790e-07      1.260e-09      3.845e-03      2.154e-03
Optimization terminated successfully.
`ftol` condition satisfied.
         Current function value: 1.790e-07
         Total delta_x: 2.175e-01
         Iterations: 11
         Function evaluations: 17
         Jacobian evaluations: 12
Timer: Solution time = 48.9 sec
Timer: Avg time per step = 4.08 sec
Start of solver
Total (sum of squares):  1.176e-01,
Maximum absolute Force error:  1.005e+06 (N)
Minimum absolute Force error:  4.798e+00 (N)
Average absolute Force error:  5.618e+04 (N)
Maximum absolute Force error:  1.092e-01 (normalized)
Minimum absolute Force error:  5.213e-07 (normalized)
Average absolute Force error:  6.104e-03 (normalized)
R boundary error:  0.000e+00 (m)
Z boundary error:  0.000e+00 (m)
Fixed-Psi error:  0.000e+00 (Wb)
Fixed-pressure profile error:  0.000e+00 (Pa)
Fixed-current profile error:  0.000e+00 (A)
End of solver
Total (sum of squares):  1.790e-07,
Maximum absolute Force error:  4.771e+02 (N)
Minimum absolute Force error:  2.019e-02 (N)
Average absolute Force error:  7.029e+01 (N)
Maximum absolute Force error:  5.184e-05 (normalized)
Minimum absolute Force error:  2.194e-09 (normalized)
Average absolute Force error:  7.638e-06 (normalized)
R boundary error:  0.000e+00 (m)
Z boundary error:  0.000e+00 (m)
Fixed-Psi error:  0.000e+00 (Wb)
Fixed-pressure profile error:  0.000e+00 (Pa)
Fixed-current profile error:  0.000e+00 (A)

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);
../../_images/notebooks_tutorials_continuation_step_by_step_48_0.png