Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 22 additions & 46 deletions src/constellaration/geometry/surface_rz_fourier.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ class SurfaceRZFourier(pydantic_numpy.BaseModelWithNumpy):
- z_cos: z_{m, n}^{cos}

If r_sin and z_cos are None, then stellarator symmetry is assumed and vice versa.
This is a JAX PyTree: Fourier coefficients are differentiable leaves and
symmetry and field periods are static metadata.
"""

r_cos: FourierCoefficients
Expand Down Expand Up @@ -267,7 +269,7 @@ def evaluate_minor_radius(
surface: SurfaceRZFourier,
n_theta: int = 50,
n_phi: int = 51,
) -> pydantic.NonNegativeFloat:
) -> jax.Array:
"""Return the minor radius of the surface defined as the radius of the circle with
the same area as the average cross sectional area of the surface.

Expand All @@ -278,7 +280,7 @@ def evaluate_minor_radius(
n_phi: Number of quadrature points in the phi dimension of the surface,
used for the numerical integration.
"""
return np.sqrt(
return jnp.sqrt(
compute_mean_cross_sectional_area(surface=surface, n_theta=n_theta, n_phi=n_phi)
/ np.pi
)
Expand All @@ -288,57 +290,31 @@ def compute_mean_cross_sectional_area(
surface: SurfaceRZFourier,
n_theta: int = 50,
n_phi: int = 51,
) -> pydantic.NonNegativeFloat:
) -> jax.Array:
"""Compute the mean cross sectional area of the surface.

The mean cross sectional area is defined as the average of the cross sectional areas
of the surface along the toroidal direction.

The code is taken from Simsopt, please refer to the documentation here
https://simsopt.readthedocs.io/en/latest/simsopt.geo.html#simsopt.geo.surface.Surface.mean_cross_sectional_area

The code provides a numerical integration of the cross sectional area of the surface
and an average across the toroidal direction, which is general enough to not assume
that phi is the real toroidal angle.

Args:
surface: The surface to compute the mean cross sectional area of.
n_theta: Number of quadrature points in the theta dimension of the surface,
used for the numerical integration.
n_phi: Number of quadrature points in the phi dimension of the surface,
used for the numerical integration.
Use Green's theorem and periodic quadrature for the poloidal sections.
"""
# n_theta - 1, n_phi - 1 is to make sure this calculation is equivalent to using
# Simsopt
theta_phi_grid = surface_utils.make_theta_phi_grid(
n_theta - 1, n_phi - 1, phi_upper_bound=2 * np.pi, include_endpoints=False
)
xyz = evaluate_points_xyz(surface, theta_phi_grid)
x2y2 = xyz[:, :, 0] ** 2 + xyz[:, :, 1] ** 2
dgamma1 = evaluate_dxyz_dphi(surface, theta_phi_grid) * 2 * np.pi
dgamma2 = evaluate_dxyz_dtheta(surface, theta_phi_grid) * 2 * np.pi

# compute the average cross sectional area
J = np.zeros((xyz.shape[0], xyz.shape[1], 2, 2))
J[:, :, 0, 0] = (
xyz[:, :, 0] * dgamma1[:, :, 1] - xyz[:, :, 1] * dgamma1[:, :, 0]
) / x2y2
J[:, :, 0, 1] = (
xyz[:, :, 0] * dgamma2[:, :, 1] - xyz[:, :, 1] * dgamma2[:, :, 0]
) / x2y2
J[:, :, 1, 0] = 0.0
J[:, :, 1, 1] = 1.0

detJ = np.linalg.det(J)
Jinv = np.linalg.inv(J)

dZ_dtheta = (
dgamma1[:, :, 2] * Jinv[:, :, 0, 1] + dgamma2[:, :, 2] * Jinv[:, :, 1, 1]
)
mean_cross_sectional_area = np.abs(np.mean(np.sqrt(x2y2) * dZ_dtheta * detJ)) / (
2 * np.pi
theta = 2 * jnp.pi * jnp.arange(n_theta - 1) / (n_theta - 1)
phi = 2 * jnp.pi * jnp.arange(n_phi - 1) / (n_phi - 1)
m, n = surface.poloidal_modes, surface.toroidal_modes
phase = (
theta[:, None, None, None] * m
- phi[None, :, None, None] * n * surface.n_field_periods
)
return mean_cross_sectional_area
cos = jnp.cos(phase)
r = jnp.sum(surface.r_cos * cos, axis=(-2, -1))
z_theta = jnp.sum(m * surface.z_sin * cos, axis=(-2, -1))
if not surface.is_stellarator_symmetric:
assert surface.r_sin is not None
assert surface.z_cos is not None
sin = jnp.sin(phase)
r += jnp.sum(surface.r_sin * sin, axis=(-2, -1))
z_theta -= jnp.sum(m * surface.z_cos * sin, axis=(-2, -1))
return 2 * jnp.pi * jnp.abs(jnp.mean(r * z_theta))


def compute_aspect_ratio(surface: SurfaceRZFourier) -> float:
Expand Down
96 changes: 39 additions & 57 deletions src/constellaration/mhd/geometry_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import jax
import jax.numpy as jnp
import jaxtyping as jt
import numpy as np
from scipy import optimize, special

from constellaration.geometry import surface_rz_fourier, surface_utils
from constellaration.geometry import surface_rz_fourier
from constellaration.mhd import vmec_utils


Expand Down Expand Up @@ -170,77 +172,57 @@ def ellipse_perimeter_residual(a):
def average_triangularity(
surface: surface_rz_fourier.SurfaceRZFourier,
n_poloidal_points: int = 201,
) -> float:
r"""Compute the average triangularity of the plasma boundary at the two stellarator
symmetry planes.

The triangularity is defined as:

.. math::
\delta = \frac{\delta_{top} + \delta_{bottom}}{2}
\delta_{top} = 2 \frac{R0 - R_{Zmax}}{R_{max} - R_{min}}
\delta_{bottom} = 2 \frac{R0 - R_{Zmin}}{R_{max} - R_{min}}

where :math:`R_{max}` and :math:`R_{min}` are the maximum and minimum
R in the toroidal cross-section, :math:`R0` is the location of the magnetic axis,
:math:`R_{Zmax}` and :math:`R_{Zmin}` are the R coordinates of the location of the
maximum and minimum Z in the toroidal cross-section.

The average triangularity is then computed by averaging the triangularity over the
two stellarator symmetry planes (phi = 0 and phi = pi/nfp).
"""
) -> jax.Array:
"""Average triangularity of the two stellarator symmetry sections."""
if not surface.is_stellarator_symmetric:
raise NotImplementedError("Non-stellarator symmetric surfaces not supported.")

theta_phi = surface_utils.make_theta_phi_grid(
n_theta=n_poloidal_points,
n_phi=2,
phi_upper_bound=np.pi / surface.n_field_periods,
include_endpoints=True,
)

RZ = surface_rz_fourier.evaluate_points_rz(
surface=surface,
theta_phi=theta_phi,
return _triangularity(
surface.r_cos.ravel(),
surface.z_sin.ravel(),
surface.poloidal_modes.ravel(),
surface.toroidal_modes.ravel() * surface.n_field_periods,
surface.n_field_periods,
n_poloidal_points,
)
return _average_triangularity_from_sections(RZ[..., 0], RZ[..., 1])


def equilibrium_average_triangularity(equilibrium: vmec_utils.VmecppWOut) -> float:
"""Sample triangularity directly on the equilibrium's outermost flux surface."""
def equilibrium_average_triangularity(equilibrium: vmec_utils.VmecppWOut) -> jax.Array:
"""Average triangularity of the equilibrium's outermost flux surface."""
if equilibrium.lasym:
raise NotImplementedError("Non-stellarator symmetric surfaces not supported.")

theta_phi = surface_utils.make_theta_phi_grid(
n_theta=201,
n_phi=2,
phi_upper_bound=np.pi / equilibrium.nfp,
include_endpoints=True,
)
phase = (
theta_phi[..., 0, None] * equilibrium.xm
- theta_phi[..., 1, None] * equilibrium.xn
return _triangularity(
equilibrium.rmnc[:, -1],
equilibrium.zmns[:, -1],
equilibrium.xm,
equilibrium.xn,
equilibrium.nfp,
201,
)
r = np.cos(phase) @ equilibrium.rmnc[:, -1]
z = np.sin(phase) @ equilibrium.zmns[:, -1]
return _average_triangularity_from_sections(r, z)


def _average_triangularity_from_sections(R: np.ndarray, Z: np.ndarray) -> float:
# Approximate the magnetic axis with the surface centroid.
R0 = np.mean(R, axis=0)
def _triangularity(r_cos, z_sin, m, n, nfp, n_theta):
# Keep the legacy centroid and radial width quadrature but refine the height
# maximum continuously so its poloidal angle contributes to the derivative.
theta = jnp.linspace(0, 2 * jnp.pi, n_theta)

R_max = np.max(R, axis=0)
R_min = np.min(R, axis=0)
def one_plane(phi):
def phase(t):
return t[..., None] * m - phi * n

minor_radius = (R_max - R_min) / 2
angles = phase(theta)
r = jnp.cos(angles) @ r_cos
z = jnp.sin(angles) @ z_sin
start = theta[jnp.argmax(z)]

indices_of_max_Z = np.argmax(Z, axis=0)
def step(_, t):
slope = jnp.cos(phase(t)) @ (m * z_sin)
second = -jnp.sin(phase(t)) @ (m**2 * z_sin)
return t - slope / second

# Top and bottom triangularity at the two stellarator symmetry planes are equal.
triangularity = (R0 - R[indices_of_max_Z, np.arange(2)]) / minor_radius
top = jax.lax.fori_loop(0, 5, step, start)
return 2 * (jnp.mean(r) - jnp.cos(phase(top)) @ r_cos) / jnp.ptp(r)

return np.mean(triangularity)
return (one_plane(0.0) + one_plane(jnp.pi / nfp)) / 2


def _get_polygon_area_from_vertices(
Expand Down
8 changes: 5 additions & 3 deletions src/constellaration/mhd/ideal_mhd_parameters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import numpy as np
import pydantic
from vmecpp import enable_x64 # pyright: ignore[reportAttributeAccessIssue]

from constellaration.geometry import surface_rz_fourier
from constellaration.mhd import flux_power_series
Expand Down Expand Up @@ -41,8 +41,10 @@ def boundary_to_ideal_mhd_parameters(
The ideal-MHD parameters, including pressure, toroidal current, and boundary
toroidal flux.
"""
minor_radius = surface_rz_fourier.evaluate_minor_radius(surface=boundary)
boundary_toroidal_flux = np.pi * minor_radius**2
with enable_x64(True):
boundary_toroidal_flux = float(
surface_rz_fourier.compute_mean_cross_sectional_area(boundary)
)
return IdealMHDParameters(
pressure=flux_power_series.FluxPowerSeriesProfile(
coefficients=[1.0, -1.0],
Expand Down
2 changes: 1 addition & 1 deletion tests/augmented_lagrangian_runner_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def evaluate(boundary, settings, ideal_mhd_parameters):
if pressure is None:
assert ideal_mhd_parameters.pressure.coefficients == [1.0, -1.0]
assert ideal_mhd_parameters.toroidal_current.coefficients == [0.0]
area = np.pi * surface_rz_fourier.evaluate_minor_radius(boundary) ** 2
area = float(surface_rz_fourier.compute_mean_cross_sectional_area(boundary))
assert ideal_mhd_parameters.boundary_toroidal_flux == pytest.approx(area)
else:
expected = pressure_profile.to_power_series(pressure)
Expand Down
11 changes: 3 additions & 8 deletions tests/equilibrium_reference_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,10 @@ def test_reference_metrics(name):
)
actual = forward_model.metrics_from_equilibrium(wout, settings)
actual_values, expected_values = actual.model_dump(), expected.model_dump()
# VMEC can shift the poloidal origin. The legacy sampling includes both
# endpoints, giving the poloidal origin double weight in the centroid.
wout_triangularity = {
"boundary_1": -0.5279570064810545,
"boundary_2": -0.4522226497230545,
"finite_beta": -0.004975124378111564,
}
# The outer-surface poloidal origin can shift, and the height maximum is
# now refined between quadrature points rather than rounded to the grid.
key = "average_triangularity"
expected_values[key] = wout_triangularity[name]
assert actual_values.pop(key) == pytest.approx(expected_values.pop(key), abs=0.03)
assert actual_values == pytest.approx(expected_values, rel=3e-5, abs=1e-8)


Expand Down
32 changes: 32 additions & 0 deletions tests/mhd/geometry_utils_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import jax
import numpy as np
import pytest
import vmecpp

from constellaration import initial_guess
from constellaration.geometry import surface_rz_fourier
from constellaration.mhd import geometry_utils
from tests.equilibrium_reference_test import NAMES, reference_inputs


def test_surface_zero_triangularity() -> None:
Expand All @@ -20,3 +25,30 @@ def test_surface_zero_triangularity() -> None:
0.0,
atol=5e-3,
)


@pytest.mark.parametrize("name", NAMES)
def test_boundary_geometry_gradients(name):
surface, mhd, _ = reference_inputs(name)
with vmecpp.enable_x64(True):
area = surface_rz_fourier.compute_mean_cross_sectional_area
np.testing.assert_allclose(
area(surface), mhd.boundary_toroidal_flux, rtol=1e-12
)
for metric in (area, geometry_utils.average_triangularity):
value = jax.jit(metric)
derivative = jax.jit(jax.grad(metric))(surface)
assert derivative.n_field_periods == surface.n_field_periods
for step in (1e-4, 5e-5):
r = surface.r_cos
direction = np.zeros_like(r)
direction[1, surface.max_toroidal_mode] = 1
plus = surface.model_copy(update={"r_cos": r + step * direction})
minus = surface.model_copy(update={"r_cos": r - step * direction})
fd = (value(plus) - value(minus)) / (2 * step)
np.testing.assert_allclose(
derivative.r_cos[1, surface.max_toroidal_mode],
fd,
rtol=1e-3,
atol=2e-7,
)
7 changes: 5 additions & 2 deletions tests/problems_tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np
import pytest
import vmecpp
from scipy.constants import mu_0

from constellaration import forward_model, initial_guess, problems
Expand Down Expand Up @@ -196,15 +197,17 @@ def test_design_without_pressure_uses_near_vacuum_inputs():
mhd = ideal_mhd_parameters_utils.design_to_ideal_mhd_parameters(design)
assert mhd.pressure.coefficients == [1.0, -1.0]
assert mhd.toroidal_current.coefficients == [0.0]
area = np.pi * surface_rz_fourier.evaluate_minor_radius(boundary) ** 2
with vmecpp.enable_x64(True):
area = float(surface_rz_fourier.compute_mean_cross_sectional_area(boundary))
assert mhd.boundary_toroidal_flux == pytest.approx(area)


def test_edge_flux_estimate_tracks_geometry_and_pressure():
boundary = initial_guess.generate_rotating_ellipse(
aspect_ratio=6, elongation=1.5, rotational_transform=0.4, n_field_periods=4
)
area = np.pi * surface_rz_fourier.evaluate_minor_radius(boundary) ** 2
with vmecpp.enable_x64(True):
area = float(surface_rz_fourier.compute_mean_cross_sectional_area(boundary))

def flux(p0, logits=(0.0, 0.0, 0.0)):
candidate = problems.Design(
Expand Down
Loading
Loading