diff --git a/src/constellaration/geometry/surface_rz_fourier.py b/src/constellaration/geometry/surface_rz_fourier.py index b52f49a..6f1544c 100644 --- a/src/constellaration/geometry/surface_rz_fourier.py +++ b/src/constellaration/geometry/surface_rz_fourier.py @@ -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 @@ -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. @@ -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 ) @@ -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: diff --git a/src/constellaration/mhd/geometry_utils.py b/src/constellaration/mhd/geometry_utils.py index 31fbfd3..f938a74 100644 --- a/src/constellaration/mhd/geometry_utils.py +++ b/src/constellaration/mhd/geometry_utils.py @@ -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 @@ -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( diff --git a/src/constellaration/mhd/ideal_mhd_parameters.py b/src/constellaration/mhd/ideal_mhd_parameters.py index d382d2e..b276251 100644 --- a/src/constellaration/mhd/ideal_mhd_parameters.py +++ b/src/constellaration/mhd/ideal_mhd_parameters.py @@ -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 @@ -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], diff --git a/tests/augmented_lagrangian_runner_test.py b/tests/augmented_lagrangian_runner_test.py index bd19f73..e1f561a 100644 --- a/tests/augmented_lagrangian_runner_test.py +++ b/tests/augmented_lagrangian_runner_test.py @@ -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) diff --git a/tests/equilibrium_reference_test.py b/tests/equilibrium_reference_test.py index f9b56b2..d2c6dda 100644 --- a/tests/equilibrium_reference_test.py +++ b/tests/equilibrium_reference_test.py @@ -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) diff --git a/tests/mhd/geometry_utils_test.py b/tests/mhd/geometry_utils_test.py index 3e522aa..6078cbc 100644 --- a/tests/mhd/geometry_utils_test.py +++ b/tests/mhd/geometry_utils_test.py @@ -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: @@ -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, + ) diff --git a/tests/problems_tests.py b/tests/problems_tests.py index b82aa61..0a731cc 100644 --- a/tests/problems_tests.py +++ b/tests/problems_tests.py @@ -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 @@ -196,7 +197,8 @@ 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) @@ -204,7 +206,8 @@ 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( diff --git a/tests/utils/vmec_utils_test.py b/tests/utils/vmec_utils_test.py index 0a939a7..36ce7ec 100644 --- a/tests/utils/vmec_utils_test.py +++ b/tests/utils/vmec_utils_test.py @@ -1,6 +1,7 @@ import base64 import io import json +from contextlib import contextmanager from pathlib import Path import jax @@ -8,7 +9,9 @@ import numpy as np import pytest import vmecpp +from vmecpp import autodiff_wout +from constellaration.geometry import surface_utils from constellaration.mhd import vmec_settings, vmec_utils from constellaration.utils import file_exporter from tests.equilibrium_reference_test import NAMES, REFERENCES, reference_inputs @@ -205,3 +208,71 @@ def independently_resolved(t): np.testing.assert_allclose( derivative, finite_difference, rtol=3e-5, atol=2e-7 ) + + +def grid(mpol, ntor, nfp): + ( + ntheta, + nphi, + ) = surface_utils.n_poloidal_toroidal_points_to_satisfy_nyquist_criterion( + mpol, ntor + ) + return jnp.moveaxis( + jnp.asarray( + surface_utils.make_theta_phi_grid( + ntheta, nphi, np.pi / nfp, include_endpoints=True + ) + ), + -1, + 0, + ) + + +def pinned_case(name): + root = REFERENCES / name + boundary, _, settings = reference_inputs(name) + loaded = vmecpp.VmecWOut.from_wout_file(root / "wout.nc") + wout = dict(loaded) + arrays = { + k: jnp.asarray(v) for k, v in wout.items() if isinstance(v, (np.ndarray, float)) + } + return boundary, settings, wout, arrays + + +@contextmanager +def resolved_case(): + """Yield one finite-beta family with pressure and boundary perturbations.""" + with vmecpp.enable_x64(True): + template = finite_beta_input() + solve = vmec_utils.make_equilibrium_solver(template) + modes = { + k: jnp.asarray(v) + for k, v in autodiff_wout.static_fields(template).items() + if k in ("xm", "xn", "xm_nyq", "xn_nyq") + } + b = jnp.stack([template.rbc, template.zbs]) + p = jnp.array([3000.0, -3450.0, 450.0]) + + def family(t): + b_t = b.at[0, 1, template.ntor].add(0.06 * t) + return b_t, solve(b_t, p * (1 + 0.2 * t), template.phiedge * (1 + 0.1 * t)) + + yield template, family, modes + + +def assert_directional_derivative( + function, + *, + steps=(2e-3, 1e-3), + atol=2e-7, + rtol=1e-3, +): + """Test local autodiff against two independent central re-solves.""" + f = jax.jit(function) + result = f(0.0) + derivative = jax.jit(jax.jacrev(function))(0.0) + assert np.all(np.isfinite(result)) + assert np.all(np.isfinite(derivative)) + for step in steps: + fd = (f(step) - f(-step)) / (2 * step) + np.testing.assert_allclose(derivative, fd, rtol=rtol, atol=atol)