diff --git a/src/vmecpp/boozer.py b/src/vmecpp/boozer.py new file mode 100644 index 000000000..8af7a10f7 --- /dev/null +++ b/src/vmecpp/boozer.py @@ -0,0 +1,264 @@ +"""Boozer coordinates of a converged VMEC++ equilibrium, with exact derivatives. + +:class:`BoozerTransform` runs the transformation of booz_xform +(https://github.com/hiddenSymmetries/booz_xform) in C++ on the spectra of a +:class:`vmecpp.VmecWOut`, so the Boozer spectra come straight from an in-memory +solve without a ``wout`` file. Nothing is computed unless it is called. + +The transform also provides its exact tangent (:meth:`BoozerTransform.jvp`) and +adjoint (:meth:`BoozerTransform.vjp`) with respect to the wout spectra it reads, +``rmnc, zmns, lmns, bmnc, bsubumnc, bsubvmnc`` and ``iotas``. Through +:meth:`BoozerTransform.jax` it is a JAX function with a custom VJP, so that it +composes with the differentiable ``vmecpp.run`` (an Enzyme-enabled build): under +``jax.grad`` the wout spectra of a traced boundary come from the implicit adjoint +of the solve and the JAX output stage, and a cotangent on ``bmnc_b`` is pulled +back to the boundary coefficients. + +Only stellarator-symmetric equilibria are supported. The derivatives are those of +the discrete transform, at the given ``mboz``, ``nboz`` and angle grid, and are +smooth while the Jacobian of the map from VMEC to Boozer angles keeps its sign. +booz_xform reads ``bsubumnc`` for the modes with ``m != 0`` and ``bsubvmnc`` only +for ``m = 0``, so the derivative with respect to ``bsubvmnc`` vanishes for the +other modes; for a converged equilibrium the two determine the same scalar +potential, and the exact derivative inherits this choice. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import jax +import jax.numpy as jnp +import numpy as np + +from vmecpp.cpp import _vmecpp # type: ignore + +INPUT_FIELDS = ("rmnc", "zmns", "lmns", "bmnc", "bsubumnc", "bsubvmnc", "iotas") +"""The wout spectra the transform reads, in the layout of :class:`vmecpp.VmecWOut`.""" + +OUTPUT_FIELDS = ( + "bmnc_b", + "rmnc_b", + "zmns_b", + "numns_b", + "gmnc_b", + "iota_b", + "boozer_g", + "boozer_i", +) +"""The Boozer spectra, one column per selected surface, and iota, G and I there.""" + + +def _as_int_list(values) -> list[int]: + return [round(float(v)) for v in np.asarray(values).ravel()] + + +class BoozerTransform: + """The Boozer transform for one mode table, set of surfaces and resolution. + + Args: + wout: A :class:`vmecpp.VmecWOut` that supplies ``nfp``, ``ns`` and the + mode tables ``xm, xn, xm_nyq, xn_nyq``. + mboz: Number of poloidal Boozer modes; ``m_B`` runs from 0 to ``mboz - 1`` + as in booz_xform. + nboz: Maximum toroidal Boozer mode number ``n_B / nfp``. + surfaces: 0-based indices into the half grid without the axis, as + booz_xform's ``compute_surfs``: surface ``j`` lies at + ``s = (j + 1/2) / (ns - 1)``. Defaults to every half-grid surface. + """ + + def __init__( + self, + wout: Any, + mboz: int, + nboz: int, + surfaces: Sequence[int] | None = None, + ) -> None: + if bool(getattr(wout, "lasym", False)): + msg = "the Boozer transform supports stellarator-symmetric equilibria only" + raise NotImplementedError(msg) + ns = int(wout.ns) + if surfaces is None: + surfaces = range(ns - 1) + self._cpp = _vmecpp.BoozerTransform( + nfp=int(wout.nfp), + ns=ns, + xm=_as_int_list(wout.xm), + xn=_as_int_list(wout.xn), + xm_nyq=_as_int_list(wout.xm_nyq), + xn_nyq=_as_int_list(wout.xn_nyq), + surfaces=[int(j) for j in surfaces], + mboz=int(mboz), + nboz=int(nboz), + ) + self.ns = ns + self.mnmax = len(np.asarray(wout.xm)) + self.mnmax_nyq = len(np.asarray(wout.xm_nyq)) + + @property + def xm_b(self) -> np.ndarray: + return np.asarray(self._cpp.xm_b) + + @property + def xn_b(self) -> np.ndarray: + return np.asarray(self._cpp.xn_b) + + @property + def surfaces(self) -> np.ndarray: + return np.asarray(self._cpp.surfaces) + + @property + def s_b(self) -> np.ndarray: + """Normalized toroidal flux of the selected surfaces.""" + return np.asarray(self._cpp.s_b) + + # Conversions between dicts of arrays and the C++ structs. + + def input_shapes(self) -> dict[str, tuple[int, ...]]: + return { + "rmnc": (self.mnmax, self.ns), + "zmns": (self.mnmax, self.ns), + "lmns": (self.mnmax, self.ns), + "bmnc": (self.mnmax_nyq, self.ns), + "bsubumnc": (self.mnmax_nyq, self.ns), + "bsubvmnc": (self.mnmax_nyq, self.ns), + "iotas": (self.ns,), + } + + def output_shapes(self) -> dict[str, tuple[int, ...]]: + spectrum = (len(self.xm_b), len(self.surfaces)) + profile = (len(self.surfaces),) + return { + name: spectrum if name.endswith("_b") and name != "iota_b" else profile + for name in OUTPUT_FIELDS + } + + @staticmethod + def _to_cpp(values: dict[str, Any], fields, cls, shapes): + struct = cls() + for name in fields: + value = values.get(name) + if value is None: + array = np.zeros(shapes[name]) + else: + array = np.asarray(value, dtype=np.float64) + if array.shape != shapes[name]: + msg = f"{name} has shape {array.shape}, expected {shapes[name]}" + raise ValueError(msg) + setattr(struct, name, np.ascontiguousarray(array)) + return struct + + @staticmethod + def _from_cpp(struct, fields) -> dict[str, np.ndarray]: + return {name: np.asarray(getattr(struct, name)) for name in fields} + + def _input(self, spectra: dict[str, Any]): + return self._to_cpp( + spectra, INPUT_FIELDS, _vmecpp.BoozerInputSpectra, self.input_shapes() + ) + + def _output(self, spectra: dict[str, Any]): + return self._to_cpp( + spectra, OUTPUT_FIELDS, _vmecpp.BoozerOutputSpectra, self.output_shapes() + ) + + # The transform and its derivatives on NumPy arrays. + + def __call__(self, spectra: Any) -> dict[str, np.ndarray]: + """Boozer spectra of a :class:`vmecpp.VmecWOut` or a dict of its spectra.""" + result = self._cpp.forward(self._input(wout_spectra(spectra))) + return self._from_cpp(result, OUTPUT_FIELDS) + + def jvp(self, spectra: Any, tangent: dict[str, Any]) -> dict[str, np.ndarray]: + """Tangent of the Boozer spectra; missing tangent fields count as zero.""" + result = self._cpp.jvp(self._input(wout_spectra(spectra)), self._input(tangent)) + return self._from_cpp(result, OUTPUT_FIELDS) + + def vjp(self, spectra: Any, cotangent: dict[str, Any]) -> dict[str, np.ndarray]: + """Cotangent of the wout spectra; missing output cotangents count as zero.""" + result = self._cpp.vjp( + self._input(wout_spectra(spectra)), self._output(cotangent) + ) + return self._from_cpp(result, INPUT_FIELDS) + + def jax(self): + """The transform as a JAX function of a dict of wout spectra. + + The forward pass and the VJP run in C++ through ``jax.pure_callback``; the + function supports reverse-mode differentiation (``jax.grad``, ``jax.vjp``, + ``jax.jacrev``), ``jax.jit`` and ``jax.vmap``. Use :meth:`jvp` for forward-mode products. + """ + input_structs = { + name: jax.ShapeDtypeStruct(shape, jnp.float64) + for name, shape in self.input_shapes().items() + } + output_structs = { + name: jax.ShapeDtypeStruct(shape, jnp.float64) + for name, shape in self.output_shapes().items() + } + + def forward_callback(spectra): + return self(spectra) + + def vjp_callback(spectra, cotangent): + return self.vjp(spectra, cotangent) + + @jax.custom_vjp + def transform(spectra): + return jax.pure_callback( + forward_callback, output_structs, spectra, vmap_method="sequential" + ) + + def transform_fwd(spectra): + return transform(spectra), spectra + + def transform_bwd(spectra, cotangent): + bar = jax.pure_callback( + vjp_callback, + input_structs, + spectra, + cotangent, + vmap_method="sequential", + ) + return (bar,) + + transform.defvjp(transform_fwd, transform_bwd) + + def apply(spectra): + selected = { + name: jnp.asarray(spectra[name], dtype=jnp.float64) + for name in INPUT_FIELDS + } + return transform(selected) + + return apply + + +def wout_spectra(wout: Any) -> dict[str, Any]: + """The fields of :data:`INPUT_FIELDS` from a :class:`vmecpp.VmecWOut` or dict.""" + if isinstance(wout, dict): + return {name: wout[name] for name in INPUT_FIELDS} + return {name: getattr(wout, name) for name in INPUT_FIELDS} + + +def boozer_transform( + wout: Any, + mboz: int, + nboz: int, + surfaces: Sequence[int] | None = None, +) -> dict[str, np.ndarray]: + """Boozer spectra of a :class:`vmecpp.VmecWOut`, with the mode table and grid. + + Returns the fields of :data:`OUTPUT_FIELDS` together with ``xm_b``, ``xn_b``, + ``surfaces`` and ``s_b``. + """ + transform = BoozerTransform(wout, mboz, nboz, surfaces) + result = transform(wout) + result.update( + xm_b=transform.xm_b, + xn_b=transform.xn_b, + surfaces=transform.surfaces, + s_b=transform.s_b, + ) + return result diff --git a/src/vmecpp/cpp/vmecpp/vmec/CMakeLists.txt b/src/vmecpp/cpp/vmecpp/vmec/CMakeLists.txt index 44617890f..dbc925343 100644 --- a/src/vmecpp/cpp/vmecpp/vmec/CMakeLists.txt +++ b/src/vmecpp/cpp/vmecpp/vmec/CMakeLists.txt @@ -1,4 +1,5 @@ add_subdirectory(boundaries) +add_subdirectory(boozer) add_subdirectory(fourier_coefficients) add_subdirectory(fourier_forces) add_subdirectory(fourier_geometry) diff --git a/src/vmecpp/cpp/vmecpp/vmec/boozer/BUILD.bazel b/src/vmecpp/cpp/vmecpp/vmec/boozer/BUILD.bazel new file mode 100644 index 000000000..2e5f5ad1b --- /dev/null +++ b/src/vmecpp/cpp/vmecpp/vmec/boozer/BUILD.bazel @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2024-present Proxima Fusion GmbH +# +# SPDX-License-Identifier: MIT +cc_library( + name = "boozer", + srcs = ["boozer.cc"], + hdrs = ["boozer.h"], + visibility = ["//visibility:public"], + deps = [ + "@abseil-cpp//absl/status:status", + "@abseil-cpp//absl/status:statusor", + "@abseil-cpp//absl/strings:str_format", + "@eigen", + "//vmecpp/common/util", + ], +) diff --git a/src/vmecpp/cpp/vmecpp/vmec/boozer/CMakeLists.txt b/src/vmecpp/cpp/vmecpp/vmec/boozer/CMakeLists.txt new file mode 100644 index 000000000..75e65da8b --- /dev/null +++ b/src/vmecpp/cpp/vmecpp/vmec/boozer/CMakeLists.txt @@ -0,0 +1,5 @@ +list (APPEND vmecpp_sources + ${CMAKE_CURRENT_SOURCE_DIR}/boozer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/boozer.h +) +set (vmecpp_sources "${vmecpp_sources}" PARENT_SCOPE) diff --git a/src/vmecpp/cpp/vmecpp/vmec/boozer/boozer.cc b/src/vmecpp/cpp/vmecpp/vmec/boozer/boozer.cc new file mode 100644 index 000000000..9f6851685 --- /dev/null +++ b/src/vmecpp/cpp/vmecpp/vmec/boozer/boozer.cc @@ -0,0 +1,635 @@ +// SPDX-FileCopyrightText: 2024-present Proxima Fusion GmbH +// +// +// SPDX-License-Identifier: MIT +#include "vmecpp/vmec/boozer/boozer.h" + +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_format.h" + +namespace vmecpp { + +namespace { + +using Eigen::ArrayXd; +using Eigen::VectorXd; + +Eigen::VectorXd ToDouble(const std::vector& v) { + Eigen::VectorXd out(v.size()); + for (std::size_t i = 0; i < v.size(); ++i) { + out[i] = v[i]; + } + return out; +} + +// cos/sin(m theta - n zeta) for the modes (xm, xn) on the points (theta, zeta). +void Harmonics(const VectorXd& theta, const VectorXd& zeta, + const std::vector& xm, const std::vector& xn, + RowMatrixXd& cos_mn, RowMatrixXd& sin_mn) { + const int n_points = static_cast(theta.size()); + const int n_modes = static_cast(xm.size()); + cos_mn.resize(n_points, n_modes); + sin_mn.resize(n_points, n_modes); + for (int j = 0; j < n_points; ++j) { + for (int k = 0; k < n_modes; ++k) { + const double angle = xm[k] * theta[j] - xn[k] * zeta[j]; + cos_mn(j, k) = std::cos(angle); + sin_mn(j, k) = std::sin(angle); + } + } +} + +} // namespace + +// Synthesized fields of one surface on the VMEC grid. +struct BoozerTransform::GridArrays { + VectorXd r, z, lambda, lambda_t, lambda_z; + VectorXd w, w_t, w_z, b; + double boozer_i = 0.0; + double boozer_g = 0.0; + double iota = 0.0; +}; + +// The primal state of one surface, kept for the tangent and the adjoint. +struct BoozerTransform::Surface { + GridArrays grid; + double d = 0.0; // G + iota I + VectorXd nu, nu_t, nu_z; + VectorXd theta_b, zeta_b; + VectorXd jacobian; // d(theta_B, zeta_B) / d(theta, zeta) + VectorXd boozer_jacobian; // (G + iota I) / B^2 + VectorXd weighted; // quadrature weight times jacobian + RowMatrixXd cos_b, sin_b; // [n_grid x mnboz] +}; + +absl::StatusOr BoozerTransform::Create( + int nfp, int ns, const std::vector& xm, const std::vector& xn, + const std::vector& xm_nyq, const std::vector& xn_nyq, + const std::vector& surfaces, int mboz, int nboz) { + if (nfp < 1) { + return absl::InvalidArgumentError("nfp must be at least 1"); + } + if (ns < 3) { + return absl::InvalidArgumentError( + "the Boozer transform needs at least 3 radial surfaces"); + } + if (mboz < 2 || nboz < 0) { + return absl::InvalidArgumentError("need mboz >= 2 and nboz >= 0"); + } + if (xm.size() != xn.size() || xm_nyq.size() != xn_nyq.size() || xm.empty() || + xm_nyq.empty()) { + return absl::InvalidArgumentError("inconsistent mode tables"); + } + for (const int j : surfaces) { + if (j < 0 || j >= ns - 1) { + return absl::InvalidArgumentError(absl::StrFormat( + "surface index %d is outside the half grid [0, %d)", j, ns - 1)); + } + } + const auto count_origin = [](const std::vector& m, + const std::vector& n) { + int count = 0; + for (std::size_t k = 0; k < m.size(); ++k) { + count += (m[k] == 0 && n[k] == 0) ? 1 : 0; + } + return count; + }; + if (count_origin(xm_nyq, xn_nyq) != 1) { + return absl::InvalidArgumentError( + "the Nyquist mode table must contain (m, n) = (0, 0) exactly once"); + } + + BoozerTransform t; + t.nfp_ = nfp; + t.ns_ = ns; + t.mboz_ = mboz; + t.nboz_ = nboz; + t.xm_ = xm; + t.xn_ = xn; + t.xm_nyq_ = xm_nyq; + t.xn_nyq_ = xn_nyq; + t.surfaces_ = surfaces; + + // Grid and mode table of booz_xform's init(). + t.ntheta_ = 2 * (2 * mboz + 1); + t.nzeta_ = nboz == 0 ? 1 : 2 * (2 * nboz + 1); + t.nu2_b_ = t.ntheta_ / 2 + 1; + t.n_grid_ = t.nu2_b_ * t.nzeta_; + for (int m = 0; m <= mboz - 1; ++m) { + for (int n = (m == 0 ? 0 : -nboz); n <= nboz; ++n) { + t.xm_b_.push_back(m); + t.xn_b_.push_back(n * nfp); + } + } + + const double d_theta = 2.0 * M_PI / t.ntheta_; + const double d_zeta = 2.0 * M_PI / (nfp * t.nzeta_); + t.theta_.resize(t.n_grid_); + t.zeta_.resize(t.n_grid_); + t.weight_.setOnes(t.n_grid_); + for (int i = 0; i < t.nu2_b_; ++i) { + for (int k = 0; k < t.nzeta_; ++k) { + const int index = i * t.nzeta_ + k; + t.theta_[index] = i * d_theta; + t.zeta_[index] = k * d_zeta; + if (i == 0 || i == t.nu2_b_ - 1) { + t.weight_[index] = 0.5; + } + } + } + + Harmonics(t.theta_, t.zeta_, xm, xn, t.cos_grid_, t.sin_grid_); + Harmonics(t.theta_, t.zeta_, xm_nyq, xn_nyq, t.cos_grid_nyq_, + t.sin_grid_nyq_); + + t.m_ = ToDouble(xm); + t.n_ = ToDouble(xn); + t.m_nyq_ = ToDouble(xm_nyq); + t.n_nyq_ = ToDouble(xn_nyq); + t.m_b_ = ToDouble(t.xm_b_); + t.n_b_ = ToDouble(t.xn_b_); + + t.fourier_factor_ = 2.0 / ((t.nu2_b_ - 1) * t.nzeta_); + t.normalization_b_.setConstant(t.xm_b_.size(), t.fourier_factor_); + t.normalization_b_[0] *= 0.5; + return t; +} + +Eigen::VectorXd BoozerTransform::s_b() const { + VectorXd s(surfaces_.size()); + for (std::size_t i = 0; i < surfaces_.size(); ++i) { + s[i] = (surfaces_[i] + 0.5) / (ns_ - 1.0); + } + return s; +} + +absl::Status BoozerTransform::CheckInput( + const BoozerInputSpectra& input) const { + const auto check = [&](const RowMatrixXd& a, std::size_t rows, + const char* name) -> absl::Status { + if (a.rows() != static_cast(rows) || a.cols() != ns_) { + return absl::InvalidArgumentError( + absl::StrFormat("%s has shape (%d, %d), expected (%d, %d)", name, + a.rows(), a.cols(), rows, ns_)); + } + return absl::OkStatus(); + }; + for (const auto& status : + {check(input.rmnc, xm_.size(), "rmnc"), + check(input.zmns, xm_.size(), "zmns"), + check(input.lmns, xm_.size(), "lmns"), + check(input.bmnc, xm_nyq_.size(), "bmnc"), + check(input.bsubumnc, xm_nyq_.size(), "bsubumnc"), + check(input.bsubvmnc, xm_nyq_.size(), "bsubvmnc")}) { + if (!status.ok()) { + return status; + } + } + if (input.iotas.size() != ns_) { + return absl::InvalidArgumentError("iotas must have ns entries"); + } + return absl::OkStatus(); +} + +absl::Status BoozerTransform::CheckOutput( + const BoozerOutputSpectra& output) const { + const Eigen::Index n_modes = static_cast(xm_b_.size()); + const Eigen::Index n_surfaces = static_cast(surfaces_.size()); + for (const RowMatrixXd* a : {&output.bmnc_b, &output.rmnc_b, &output.zmns_b, + &output.numns_b, &output.gmnc_b}) { + if (a->rows() != n_modes || a->cols() != n_surfaces) { + return absl::InvalidArgumentError(absl::StrFormat( + "Boozer spectra must have shape (%d, %d)", n_modes, n_surfaces)); + } + } + for (const VectorXd* v : + {&output.iota_b, &output.boozer_g, &output.boozer_i}) { + if (v->size() != n_surfaces) { + return absl::InvalidArgumentError( + "iota_b, boozer_g and boozer_i must have one entry per surface"); + } + } + return absl::OkStatus(); +} + +std::vector BoozerTransform::RadialStencil( + int mode, int j) const { + const int m = xm_[mode]; + if (m % 2 == 0) { + return {{j, 0.5}, {j + 1, 0.5}}; + } + const double hs = 1.0 / (ns_ - 1.0); + const auto sqrt_s_full = [&](int k) { + return k == 0 ? 1.0 : std::sqrt(hs * k); + }; + const double sqrt_s_half = std::sqrt(hs * (j + 0.5)); + if (m == 1 && j == 0) { + return {{1, 1.5 * sqrt_s_half / sqrt_s_full(1)}, + {2, -0.5 * sqrt_s_half / sqrt_s_full(2)}}; + } + return {{j, 0.5 * sqrt_s_half / sqrt_s_full(j)}, + {j + 1, 0.5 * sqrt_s_half / sqrt_s_full(j + 1)}}; +} + +Eigen::VectorXd BoozerTransform::HalfGridGeometry(const RowMatrixXd& full, + int j) const { + VectorXd half(xm_.size()); + for (int mode = 0; mode < static_cast(xm_.size()); ++mode) { + double value = 0.0; + for (const Stencil& s : RadialStencil(mode, j)) { + value += s.weight * full(mode, s.full_index); + } + half[mode] = value; + } + return half; +} + +void BoozerTransform::AccumulateHalfGridGeometryAdjoint( + const Eigen::VectorXd& half_bar, int j, RowMatrixXd& full_bar) const { + for (int mode = 0; mode < static_cast(xm_.size()); ++mode) { + for (const Stencil& s : RadialStencil(mode, j)) { + full_bar(mode, s.full_index) += s.weight * half_bar[mode]; + } + } +} + +// Linear in `input`, so it also maps a tangent to the tangent grid arrays. +BoozerTransform::GridArrays BoozerTransform::Synthesize( + const BoozerInputSpectra& input, int j) const { + const int column = j + 1; // half-grid column of surface j + GridArrays g; + const VectorXd r_half = HalfGridGeometry(input.rmnc, j); + const VectorXd z_half = HalfGridGeometry(input.zmns, j); + const VectorXd lambda = input.lmns.col(column); + g.r = cos_grid_ * r_half; + g.z = sin_grid_ * z_half; + g.lambda = sin_grid_ * lambda; + g.lambda_t = cos_grid_ * m_.cwiseProduct(lambda); + g.lambda_z = -(cos_grid_ * n_.cwiseProduct(lambda)); + + // Periodic part of the scalar potential, booz_xform's transpmn. + VectorXd wmns = VectorXd::Zero(xm_nyq_.size()); + for (int k = 0; k < static_cast(xm_nyq_.size()); ++k) { + if (xm_nyq_[k] != 0) { + wmns[k] = input.bsubumnc(k, column) / xm_nyq_[k]; + } else if (xn_nyq_[k] != 0) { + wmns[k] = -input.bsubvmnc(k, column) / xn_nyq_[k]; + } else { + g.boozer_i = input.bsubumnc(k, column); + g.boozer_g = input.bsubvmnc(k, column); + } + } + g.w = sin_grid_nyq_ * wmns; + g.w_t = cos_grid_nyq_ * m_nyq_.cwiseProduct(wmns); + g.w_z = -(cos_grid_nyq_ * n_nyq_.cwiseProduct(wmns)); + g.b = cos_grid_nyq_ * input.bmnc.col(column); + g.iota = input.iotas[column]; + return g; +} + +void BoozerTransform::BoozerHarmonics(const VectorXd& theta_b, + const VectorXd& zeta_b, + RowMatrixXd& cos_b, + RowMatrixXd& sin_b) const { + // Angle-addition recursion as in booz_xform's init_trig. + const int n_m = mboz_ + 1; + const int n_n = nboz_ + 1; + RowMatrixXd cos_m(n_grid_, n_m), sin_m(n_grid_, n_m); + RowMatrixXd cos_n(n_grid_, n_n), sin_n(n_grid_, n_n); + for (int j = 0; j < n_grid_; ++j) { + cos_m(j, 0) = 1.0; + sin_m(j, 0) = 0.0; + cos_m(j, 1) = std::cos(theta_b[j]); + sin_m(j, 1) = std::sin(theta_b[j]); + for (int m = 2; m < n_m; ++m) { + cos_m(j, m) = + cos_m(j, m - 1) * cos_m(j, 1) - sin_m(j, m - 1) * sin_m(j, 1); + sin_m(j, m) = + sin_m(j, m - 1) * cos_m(j, 1) + cos_m(j, m - 1) * sin_m(j, 1); + } + cos_n(j, 0) = 1.0; + sin_n(j, 0) = 0.0; + if (n_n > 1) { + cos_n(j, 1) = std::cos(nfp_ * zeta_b[j]); + sin_n(j, 1) = std::sin(nfp_ * zeta_b[j]); + } + for (int n = 2; n < n_n; ++n) { + cos_n(j, n) = + cos_n(j, n - 1) * cos_n(j, 1) - sin_n(j, n - 1) * sin_n(j, 1); + sin_n(j, n) = + sin_n(j, n - 1) * cos_n(j, 1) + cos_n(j, n - 1) * sin_n(j, 1); + } + } + const int mnboz = static_cast(xm_b_.size()); + cos_b.resize(n_grid_, mnboz); + sin_b.resize(n_grid_, mnboz); + for (int k = 0; k < mnboz; ++k) { + const int m = xm_b_[k]; + const int abs_n = std::abs(xn_b_[k] / nfp_); + const double sign = xn_b_[k] < 0 ? -1.0 : 1.0; + for (int j = 0; j < n_grid_; ++j) { + cos_b(j, k) = + cos_m(j, m) * cos_n(j, abs_n) + sign * sin_m(j, m) * sin_n(j, abs_n); + sin_b(j, k) = + sin_m(j, m) * cos_n(j, abs_n) - sign * cos_m(j, m) * sin_n(j, abs_n); + } + } +} + +BoozerTransform::Surface BoozerTransform::Solve(const BoozerInputSpectra& input, + int j) const { + Surface s; + s.grid = Synthesize(input, j); + const GridArrays& g = s.grid; + s.d = g.boozer_g + g.iota * g.boozer_i; + s.nu = (g.w - g.boozer_i * g.lambda) / s.d; + s.nu_t = (g.w_t - g.boozer_i * g.lambda_t) / s.d; + s.nu_z = (g.w_z - g.boozer_i * g.lambda_z) / s.d; + s.theta_b = theta_ + g.lambda + g.iota * s.nu; + s.zeta_b = zeta_ + s.nu; + s.jacobian = ((1.0 + g.lambda_t.array()) * (1.0 + s.nu_z.array()) + + (g.iota - g.lambda_z.array()) * s.nu_t.array()) + .matrix(); + s.boozer_jacobian = (s.d / g.b.array().square()).matrix(); + s.weighted = weight_.cwiseProduct(s.jacobian); + BoozerHarmonics(s.theta_b, s.zeta_b, s.cos_b, s.sin_b); + return s; +} + +absl::StatusOr BoozerTransform::Forward( + const BoozerInputSpectra& input) const { + if (absl::Status status = CheckInput(input); !status.ok()) { + return status; + } + const int mnboz = static_cast(xm_b_.size()); + const int n_surfaces = static_cast(surfaces_.size()); + BoozerOutputSpectra out; + for (RowMatrixXd* a : + {&out.bmnc_b, &out.rmnc_b, &out.zmns_b, &out.numns_b, &out.gmnc_b}) { + a->setZero(mnboz, n_surfaces); + } + out.iota_b.setZero(n_surfaces); + out.boozer_g.setZero(n_surfaces); + out.boozer_i.setZero(n_surfaces); + +#pragma omp parallel for schedule(dynamic) + for (int i = 0; i < n_surfaces; ++i) { + const Surface s = Solve(input, surfaces_[i]); + const auto project = [&](const RowMatrixXd& basis, const VectorXd& q) { + return normalization_b_.cwiseProduct(basis.transpose() * + s.weighted.cwiseProduct(q)); + }; + out.bmnc_b.col(i) = project(s.cos_b, s.grid.b); + out.rmnc_b.col(i) = project(s.cos_b, s.grid.r); + out.zmns_b.col(i) = project(s.sin_b, s.grid.z); + out.numns_b.col(i) = project(s.sin_b, s.nu); + out.gmnc_b.col(i) = project(s.cos_b, s.boozer_jacobian); + out.iota_b[i] = s.grid.iota; + out.boozer_g[i] = s.grid.boozer_g; + out.boozer_i[i] = s.grid.boozer_i; + } + return out; +} + +absl::StatusOr BoozerTransform::Jvp( + const BoozerInputSpectra& input, const BoozerInputSpectra& tangent) const { + if (absl::Status status = CheckInput(input); !status.ok()) { + return status; + } + if (absl::Status status = CheckInput(tangent); !status.ok()) { + return status; + } + const int mnboz = static_cast(xm_b_.size()); + const int n_surfaces = static_cast(surfaces_.size()); + BoozerOutputSpectra out; + for (RowMatrixXd* a : + {&out.bmnc_b, &out.rmnc_b, &out.zmns_b, &out.numns_b, &out.gmnc_b}) { + a->setZero(mnboz, n_surfaces); + } + out.iota_b.setZero(n_surfaces); + out.boozer_g.setZero(n_surfaces); + out.boozer_i.setZero(n_surfaces); + +#pragma omp parallel for schedule(dynamic) + for (int i = 0; i < n_surfaces; ++i) { + const int j = surfaces_[i]; + const Surface s = Solve(input, j); + const GridArrays& g = s.grid; + const GridArrays dg = Synthesize(tangent, j); + + const double d_d = + dg.boozer_g + dg.iota * g.boozer_i + g.iota * dg.boozer_i; + const ArrayXd d_nu = (dg.w.array() - dg.boozer_i * g.lambda.array() - + g.boozer_i * dg.lambda.array() - s.nu.array() * d_d) / + s.d; + const ArrayXd d_nu_t = + (dg.w_t.array() - dg.boozer_i * g.lambda_t.array() - + g.boozer_i * dg.lambda_t.array() - s.nu_t.array() * d_d) / + s.d; + const ArrayXd d_nu_z = + (dg.w_z.array() - dg.boozer_i * g.lambda_z.array() - + g.boozer_i * dg.lambda_z.array() - s.nu_z.array() * d_d) / + s.d; + const ArrayXd d_theta_b = + dg.lambda.array() + dg.iota * s.nu.array() + g.iota * d_nu; + const ArrayXd& d_zeta_b = d_nu; + const ArrayXd d_jacobian = + dg.lambda_t.array() * (1.0 + s.nu_z.array()) + + (1.0 + g.lambda_t.array()) * d_nu_z + + (dg.iota - dg.lambda_z.array()) * s.nu_t.array() + + (g.iota - g.lambda_z.array()) * d_nu_t; + const ArrayXd b = g.b.array(); + const ArrayXd d_boozer_jacobian = + d_d / b.square() - 2.0 * s.d * dg.b.array() / (b.square() * b); + const ArrayXd d_weighted = weight_.array() * d_jacobian; + const ArrayXd a = s.weighted.array(); + + // Tangent of normalization * sum_j a_j q_j basis_k(theta_B, zeta_B). + const auto tangent_of = [&](const VectorXd& q, const ArrayXd& d_q, + bool cosine) -> VectorXd { + const ArrayXd aq = a * q.array(); + const VectorXd amplitude = (d_weighted * q.array() + a * d_q).matrix(); + const VectorXd shift_theta = (aq * d_theta_b).matrix(); + const VectorXd shift_zeta = (aq * d_zeta_b).matrix(); + VectorXd result; + if (cosine) { + result = s.cos_b.transpose() * amplitude - + m_b_.cwiseProduct(s.sin_b.transpose() * shift_theta) + + n_b_.cwiseProduct(s.sin_b.transpose() * shift_zeta); + } else { + result = s.sin_b.transpose() * amplitude + + m_b_.cwiseProduct(s.cos_b.transpose() * shift_theta) - + n_b_.cwiseProduct(s.cos_b.transpose() * shift_zeta); + } + return normalization_b_.cwiseProduct(result); + }; + out.bmnc_b.col(i) = tangent_of(g.b, dg.b.array(), true); + out.rmnc_b.col(i) = tangent_of(g.r, dg.r.array(), true); + out.zmns_b.col(i) = tangent_of(g.z, dg.z.array(), false); + out.numns_b.col(i) = tangent_of(s.nu, d_nu, false); + out.gmnc_b.col(i) = tangent_of(s.boozer_jacobian, d_boozer_jacobian, true); + out.iota_b[i] = dg.iota; + out.boozer_g[i] = dg.boozer_g; + out.boozer_i[i] = dg.boozer_i; + } + return out; +} + +absl::StatusOr BoozerTransform::Vjp( + const BoozerInputSpectra& input, + const BoozerOutputSpectra& cotangent) const { + if (absl::Status status = CheckInput(input); !status.ok()) { + return status; + } + if (absl::Status status = CheckOutput(cotangent); !status.ok()) { + return status; + } + const int n_surfaces = static_cast(surfaces_.size()); + const int mnmax = static_cast(xm_.size()); + const int mnmax_nyq = static_cast(xm_nyq_.size()); + + // Per-surface cotangents of the half-grid coefficients; they are folded + // into the shared result after the parallel loop. + struct SurfaceCotangent { + VectorXd r_half, z_half, lambda, bmnc, bsubumnc, bsubvmnc; + double iota = 0.0; + }; + std::vector per_surface(n_surfaces); + +#pragma omp parallel for schedule(dynamic) + for (int i = 0; i < n_surfaces; ++i) { + const Surface s = Solve(input, surfaces_[i]); + const GridArrays& g = s.grid; + const ArrayXd a = s.weighted.array(); + + ArrayXd a_bar = ArrayXd::Zero(n_grid_); + ArrayXd theta_b_bar = ArrayXd::Zero(n_grid_); + ArrayXd zeta_b_bar = ArrayXd::Zero(n_grid_); + + // Adjoint of normalization * sum_j a_j q_j basis_k(theta_B, zeta_B): + // returns the cotangent of q and accumulates those of a and the angles. + const auto pull_back = [&](const VectorXd& q, const RowMatrixXd& out_bar, + bool cosine) -> ArrayXd { + const VectorXd u = normalization_b_.cwiseProduct(out_bar.col(i)); + const ArrayXd aq = a * q.array(); + ArrayXd p_bar; + if (cosine) { + p_bar = (s.cos_b * u).array(); + theta_b_bar -= aq * (s.sin_b * m_b_.cwiseProduct(u)).array(); + zeta_b_bar += aq * (s.sin_b * n_b_.cwiseProduct(u)).array(); + } else { + p_bar = (s.sin_b * u).array(); + theta_b_bar += aq * (s.cos_b * m_b_.cwiseProduct(u)).array(); + zeta_b_bar -= aq * (s.cos_b * n_b_.cwiseProduct(u)).array(); + } + a_bar += p_bar * q.array(); + return p_bar * a; + }; + ArrayXd b_bar = pull_back(g.b, cotangent.bmnc_b, true); + const ArrayXd r_bar = pull_back(g.r, cotangent.rmnc_b, true); + const ArrayXd z_bar = pull_back(g.z, cotangent.zmns_b, false); + ArrayXd nu_bar = pull_back(s.nu, cotangent.numns_b, false); + const ArrayXd boozer_jacobian_bar = + pull_back(s.boozer_jacobian, cotangent.gmnc_b, true); + + double iota_bar = cotangent.iota_b[i]; + double boozer_g_bar = cotangent.boozer_g[i]; + double boozer_i_bar = cotangent.boozer_i[i]; + double d_bar = 0.0; + + // boozer_jacobian = d / b^2 + const ArrayXd b = g.b.array(); + d_bar += (boozer_jacobian_bar / b.square()).sum(); + b_bar -= 2.0 * s.d * boozer_jacobian_bar / (b.square() * b); + + // weighted = weight * jacobian, jacobian = (1 + lambda_t)(1 + nu_z) + // + (iota - lambda_z) nu_t + const ArrayXd jacobian_bar = weight_.array() * a_bar; + ArrayXd lambda_t_bar = jacobian_bar * (1.0 + s.nu_z.array()); + ArrayXd nu_z_bar = jacobian_bar * (1.0 + g.lambda_t.array()); + iota_bar += (jacobian_bar * s.nu_t.array()).sum(); + ArrayXd lambda_z_bar = -jacobian_bar * s.nu_t.array(); + const ArrayXd nu_t_bar = jacobian_bar * (g.iota - g.lambda_z.array()); + + // theta_B = theta + lambda + iota nu, zeta_B = zeta + nu + ArrayXd lambda_bar = theta_b_bar; + iota_bar += (theta_b_bar * s.nu.array()).sum(); + nu_bar += g.iota * theta_b_bar + zeta_b_bar; + + // nu = (w - I lambda) / d, and likewise for the theta and zeta derivatives. + const auto pull_back_nu = [&](const ArrayXd& nu_x_bar, const VectorXd& nu_x, + const VectorXd& lambda_x, + ArrayXd& lambda_x_bar) -> ArrayXd { + boozer_i_bar -= (nu_x_bar * lambda_x.array()).sum() / s.d; + lambda_x_bar -= g.boozer_i * nu_x_bar / s.d; + d_bar -= (nu_x_bar * nu_x.array()).sum() / s.d; + return nu_x_bar / s.d; + }; + const ArrayXd w_bar = pull_back_nu(nu_bar, s.nu, g.lambda, lambda_bar); + const ArrayXd w_t_bar = + pull_back_nu(nu_t_bar, s.nu_t, g.lambda_t, lambda_t_bar); + const ArrayXd w_z_bar = + pull_back_nu(nu_z_bar, s.nu_z, g.lambda_z, lambda_z_bar); + + // d = G + iota I + boozer_g_bar += d_bar; + iota_bar += d_bar * g.boozer_i; + boozer_i_bar += d_bar * g.iota; + + // Transposed synthesis. + SurfaceCotangent& c = per_surface[i]; + c.r_half = cos_grid_.transpose() * r_bar.matrix(); + c.z_half = sin_grid_.transpose() * z_bar.matrix(); + c.lambda = sin_grid_.transpose() * lambda_bar.matrix() + + m_.cwiseProduct(cos_grid_.transpose() * lambda_t_bar.matrix()) - + n_.cwiseProduct(cos_grid_.transpose() * lambda_z_bar.matrix()); + const VectorXd wmns_bar = + sin_grid_nyq_.transpose() * w_bar.matrix() + + m_nyq_.cwiseProduct(cos_grid_nyq_.transpose() * w_t_bar.matrix()) - + n_nyq_.cwiseProduct(cos_grid_nyq_.transpose() * w_z_bar.matrix()); + c.bmnc = cos_grid_nyq_.transpose() * b_bar.matrix(); + c.bsubumnc.setZero(mnmax_nyq); + c.bsubvmnc.setZero(mnmax_nyq); + for (int k = 0; k < mnmax_nyq; ++k) { + if (xm_nyq_[k] != 0) { + c.bsubumnc[k] = wmns_bar[k] / xm_nyq_[k]; + } else if (xn_nyq_[k] != 0) { + c.bsubvmnc[k] = -wmns_bar[k] / xn_nyq_[k]; + } else { + c.bsubumnc[k] = boozer_i_bar; + c.bsubvmnc[k] = boozer_g_bar; + } + } + c.iota = iota_bar; + } + + BoozerInputSpectra bar; + bar.rmnc.setZero(mnmax, ns_); + bar.zmns.setZero(mnmax, ns_); + bar.lmns.setZero(mnmax, ns_); + bar.bmnc.setZero(mnmax_nyq, ns_); + bar.bsubumnc.setZero(mnmax_nyq, ns_); + bar.bsubvmnc.setZero(mnmax_nyq, ns_); + bar.iotas.setZero(ns_); + for (int i = 0; i < n_surfaces; ++i) { + const int j = surfaces_[i]; + const int column = j + 1; + const SurfaceCotangent& c = per_surface[i]; + AccumulateHalfGridGeometryAdjoint(c.r_half, j, bar.rmnc); + AccumulateHalfGridGeometryAdjoint(c.z_half, j, bar.zmns); + bar.lmns.col(column) += c.lambda; + bar.bmnc.col(column) += c.bmnc; + bar.bsubumnc.col(column) += c.bsubumnc; + bar.bsubvmnc.col(column) += c.bsubvmnc; + bar.iotas[column] += c.iota; + } + return bar; +} + +} // namespace vmecpp diff --git a/src/vmecpp/cpp/vmecpp/vmec/boozer/boozer.h b/src/vmecpp/cpp/vmecpp/vmec/boozer/boozer.h new file mode 100644 index 000000000..5f9a1dd19 --- /dev/null +++ b/src/vmecpp/cpp/vmecpp/vmec/boozer/boozer.h @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: 2024-present Proxima Fusion GmbH +// +// +// SPDX-License-Identifier: MIT +#ifndef VMECPP_VMEC_BOOZER_BOOZER_H_ +#define VMECPP_VMEC_BOOZER_BOOZER_H_ + +#include +#include + +#include "absl/status/statusor.h" +#include "vmecpp/common/util/util.h" + +namespace vmecpp { + +// The stellarator-symmetric wout spectra that the Boozer transform consumes, +// in the layout of the Python VmecWOut, with one row per Fourier mode and one +// column per radial surface. rmnc and zmns live on the full radial grid, +// lmns, bmnc, bsubumnc, bsubvmnc and iotas on the half grid, whose column 0 is +// the unused axis entry. The same struct carries tangents and cotangents. +struct BoozerInputSpectra { + RowMatrixXd rmnc; // [mnmax x ns] + RowMatrixXd zmns; // [mnmax x ns] + RowMatrixXd lmns; // [mnmax x ns] + RowMatrixXd bmnc; // [mnmax_nyq x ns] + RowMatrixXd bsubumnc; // [mnmax_nyq x ns] + RowMatrixXd bsubvmnc; // [mnmax_nyq x ns] + Eigen::VectorXd iotas; // [ns] +}; + +// Boozer spectra on the selected half-grid surfaces, one column per surface +// and one row per Boozer mode (xm_b, xn_b), together with iota, G = B_zeta +// and I = B_theta on those surfaces. The same struct carries tangents and +// cotangents. +struct BoozerOutputSpectra { + RowMatrixXd bmnc_b; // [mnboz x n_surfaces] + RowMatrixXd rmnc_b; // [mnboz x n_surfaces] + RowMatrixXd zmns_b; // [mnboz x n_surfaces] + RowMatrixXd numns_b; // [mnboz x n_surfaces] + RowMatrixXd gmnc_b; // [mnboz x n_surfaces] + Eigen::VectorXd iota_b; // [n_surfaces] + Eigen::VectorXd boozer_g; // [n_surfaces] + Eigen::VectorXd boozer_i; // [n_surfaces] +}; + +// The transformation to Boozer coordinates of booz_xform +// (https://github.com/hiddenSymmetries/booz_xform), restricted to +// stellarator symmetry, together with its exact tangent and adjoint. +// +// On every surface the VMEC angles are mapped to the Boozer angles +// theta_B = theta + lambda + iota nu and zeta_B = zeta + nu with +// nu = (w - I lambda) / (G + iota I), where w is the periodic part of the +// magnetic scalar potential assembled from bsubumnc (m != 0) and bsubvmnc +// (m = 0). Every Boozer spectrum is a quadrature over the VMEC angle grid that +// carries the Jacobian of this angle map, so the map is never inverted. The +// grid, the mode table and the half-grid interpolation of R and Z are those of +// booz_xform, so that the primal agrees with booz_xform to roundoff. +// +// The tangent and the adjoint differentiate exactly this discrete map, which +// is smooth as long as the Jacobian of the angle map does not vanish. They are +// hand-written: the map is a linear synthesis on the VMEC grid, a pointwise +// nonlinearity and a projection on the Boozer harmonics, whose adjoint is the +// transposed sum. +class BoozerTransform { + public: + // `surfaces` are 0-based indices into the half grid without the axis, as in + // booz_xform's compute_surfs: surface j lies at s = (j + 1/2) / (ns - 1) and + // reads column j + 1 of the half-grid wout arrays. + static absl::StatusOr Create( + int nfp, int ns, const std::vector& xm, const std::vector& xn, + const std::vector& xm_nyq, const std::vector& xn_nyq, + const std::vector& surfaces, int mboz, int nboz); + + absl::StatusOr Forward( + const BoozerInputSpectra& input) const; + + // Tangent of Forward at `input` in the direction `tangent`. + absl::StatusOr Jvp( + const BoozerInputSpectra& input, const BoozerInputSpectra& tangent) const; + + // Cotangent of the inputs that the cotangent of the outputs pulls back to. + absl::StatusOr Vjp( + const BoozerInputSpectra& input, + const BoozerOutputSpectra& cotangent) const; + + const std::vector& xm_b() const { return xm_b_; } + const std::vector& xn_b() const { return xn_b_; } + const std::vector& surfaces() const { return surfaces_; } + // Normalized toroidal flux of the selected surfaces. + Eigen::VectorXd s_b() const; + int ntheta() const { return ntheta_; } + int nzeta() const { return nzeta_; } + + private: + struct Surface; + struct SurfaceTangent; + struct GridArrays; + + BoozerTransform() = default; + + absl::Status CheckInput(const BoozerInputSpectra& input) const; + absl::Status CheckOutput(const BoozerOutputSpectra& output) const; + + // R and Z of half-grid surface j from the full-grid coefficients: the mean + // of the neighbours for even m, the mean of X / sqrt(s) times sqrt(s) for + // odd m, extrapolated to the axis for m = 1 on the first surface. + struct Stencil { + int full_index; + double weight; + }; + std::vector RadialStencil(int mode, int j) const; + Eigen::VectorXd HalfGridGeometry(const RowMatrixXd& full, int j) const; + void AccumulateHalfGridGeometryAdjoint(const Eigen::VectorXd& half_bar, int j, + RowMatrixXd& full_bar) const; + + GridArrays Synthesize(const BoozerInputSpectra& input, int j) const; + Surface Solve(const BoozerInputSpectra& input, int j) const; + + // Boozer harmonics cos/sin(m theta_B - n zeta_B) on the VMEC grid. + void BoozerHarmonics(const Eigen::VectorXd& theta_b, + const Eigen::VectorXd& zeta_b, RowMatrixXd& cos_b, + RowMatrixXd& sin_b) const; + + int nfp_ = 1; + int ns_ = 0; + int mboz_ = 0; + int nboz_ = 0; + int ntheta_ = 0; + int nzeta_ = 0; + int nu2_b_ = 0; + int n_grid_ = 0; + double fourier_factor_ = 0.0; + + std::vector xm_, xn_, xm_nyq_, xn_nyq_; + std::vector xm_b_, xn_b_; + std::vector surfaces_; + + // Quadrature weight per grid point: 1/2 on theta = 0 and theta = pi. + Eigen::VectorXd weight_; + Eigen::VectorXd theta_; + Eigen::VectorXd zeta_; + + // cos/sin(m theta - n zeta) on the VMEC grid, [n_grid x mnmax(_nyq)]. + RowMatrixXd cos_grid_, sin_grid_; + RowMatrixXd cos_grid_nyq_, sin_grid_nyq_; + + // Mode numbers as doubles, and the Fourier normalization per Boozer mode. + Eigen::VectorXd m_, n_, m_nyq_, n_nyq_, m_b_, n_b_, normalization_b_; +}; + +} // namespace vmecpp + +#endif // VMECPP_VMEC_BOOZER_BOOZER_H_ diff --git a/src/vmecpp/cpp/vmecpp/vmec/pybind11/BUILD.bazel b/src/vmecpp/cpp/vmecpp/vmec/pybind11/BUILD.bazel index e329fc2c7..1b2382857 100644 --- a/src/vmecpp/cpp/vmecpp/vmec/pybind11/BUILD.bazel +++ b/src/vmecpp/cpp/vmecpp/vmec/pybind11/BUILD.bazel @@ -12,6 +12,7 @@ pybind_extension( "//vmecpp/common/util", "//vmecpp/common/vmec_indata", "//vmecpp/common/magnetic_configuration_lib", + "//vmecpp/vmec/boozer", "//vmecpp/vmec/geometry", "//vmecpp/vmec/geometry:vmec_geometry", "//vmecpp/vmec/output_quantities", diff --git a/src/vmecpp/cpp/vmecpp/vmec/pybind11/pybind_vmec.cc b/src/vmecpp/cpp/vmecpp/vmec/pybind11/pybind_vmec.cc index 0c7dac19b..fbc52d633 100644 --- a/src/vmecpp/cpp/vmecpp/vmec/pybind11/pybind_vmec.cc +++ b/src/vmecpp/cpp/vmecpp/vmec/pybind11/pybind_vmec.cc @@ -21,6 +21,7 @@ #include "vmecpp/common/makegrid_lib/makegrid_lib.h" #include "vmecpp/common/util/util.h" #include "vmecpp/common/vmec_indata/vmec_indata.h" +#include "vmecpp/vmec/boozer/boozer.h" #include "vmecpp/vmec/geometry/geometry.h" #include "vmecpp/vmec/geometry/vmec_geometry.h" #include "vmecpp/vmec/output_quantities/output_quantities.h" @@ -1688,6 +1689,72 @@ PYBIND11_MODULE(_vmecpp, m) { vmecpp::GeometryCoefficientState::kPhysical); }); + // Boozer transform of the wout spectra with its tangent and adjoint; see + // vmecpp/vmec/boozer/boozer.h. Computed only on request. + py::class_(m, "BoozerInputSpectra") + .def(py::init<>()) + .def_readwrite("rmnc", &vmecpp::BoozerInputSpectra::rmnc) + .def_readwrite("zmns", &vmecpp::BoozerInputSpectra::zmns) + .def_readwrite("lmns", &vmecpp::BoozerInputSpectra::lmns) + .def_readwrite("bmnc", &vmecpp::BoozerInputSpectra::bmnc) + .def_readwrite("bsubumnc", &vmecpp::BoozerInputSpectra::bsubumnc) + .def_readwrite("bsubvmnc", &vmecpp::BoozerInputSpectra::bsubvmnc) + .def_readwrite("iotas", &vmecpp::BoozerInputSpectra::iotas); + py::class_(m, "BoozerOutputSpectra") + .def(py::init<>()) + .def_readwrite("bmnc_b", &vmecpp::BoozerOutputSpectra::bmnc_b) + .def_readwrite("rmnc_b", &vmecpp::BoozerOutputSpectra::rmnc_b) + .def_readwrite("zmns_b", &vmecpp::BoozerOutputSpectra::zmns_b) + .def_readwrite("numns_b", &vmecpp::BoozerOutputSpectra::numns_b) + .def_readwrite("gmnc_b", &vmecpp::BoozerOutputSpectra::gmnc_b) + .def_readwrite("iota_b", &vmecpp::BoozerOutputSpectra::iota_b) + .def_readwrite("boozer_g", &vmecpp::BoozerOutputSpectra::boozer_g) + .def_readwrite("boozer_i", &vmecpp::BoozerOutputSpectra::boozer_i); + py::class_(m, "BoozerTransform") + .def(py::init([](int nfp, int ns, const std::vector &xm, + const std::vector &xn, + const std::vector &xm_nyq, + const std::vector &xn_nyq, + const std::vector &surfaces, int mboz, int nboz) { + auto t = vmecpp::BoozerTransform::Create( + nfp, ns, xm, xn, xm_nyq, xn_nyq, surfaces, mboz, nboz); + return GetValueOrThrow(t); + }), + "nfp"_a, "ns"_a, "xm"_a, "xn"_a, "xm_nyq"_a, "xn_nyq"_a, + "surfaces"_a, "mboz"_a, "nboz"_a) + .def( + "forward", + [](const vmecpp::BoozerTransform &t, + const vmecpp::BoozerInputSpectra &input) { + auto out = t.Forward(input); + return GetValueOrThrow(out); + }, + "input"_a, py::call_guard()) + .def( + "jvp", + [](const vmecpp::BoozerTransform &t, + const vmecpp::BoozerInputSpectra &input, + const vmecpp::BoozerInputSpectra &tangent) { + auto out = t.Jvp(input, tangent); + return GetValueOrThrow(out); + }, + "input"_a, "tangent"_a, py::call_guard()) + .def( + "vjp", + [](const vmecpp::BoozerTransform &t, + const vmecpp::BoozerInputSpectra &input, + const vmecpp::BoozerOutputSpectra &cotangent) { + auto out = t.Vjp(input, cotangent); + return GetValueOrThrow(out); + }, + "input"_a, "cotangent"_a, py::call_guard()) + .def_property_readonly("xm_b", &vmecpp::BoozerTransform::xm_b) + .def_property_readonly("xn_b", &vmecpp::BoozerTransform::xn_b) + .def_property_readonly("surfaces", &vmecpp::BoozerTransform::surfaces) + .def_property_readonly("s_b", &vmecpp::BoozerTransform::s_b) + .def_property_readonly("ntheta", &vmecpp::BoozerTransform::ntheta) + .def_property_readonly("nzeta", &vmecpp::BoozerTransform::nzeta); + py::class_(m, "HotRestartState") .def(py::init(&MakeHotRestartState), "wout"_a, "indata"_a) .def_readwrite("wout", &vmecpp::HotRestartState::wout) diff --git a/tests/test_boozer.py b/tests/test_boozer.py new file mode 100644 index 000000000..7fbb4f8cf --- /dev/null +++ b/tests/test_boozer.py @@ -0,0 +1,362 @@ +"""The Boozer transform against booz_xform, and its tangent and adjoint.""" + +import subprocess +import sys +from pathlib import Path + +import jax +import jax.numpy as jnp +import numpy as np +import pytest + +import vmecpp +from vmecpp import boozer +from vmecpp.cpp import _vmecpp # type: ignore + +jax.config.update("jax_enable_x64", True) + +REPO_ROOT = Path(__file__).parent.parent +TEST_DATA_DIR = REPO_ROOT / "src" / "vmecpp" / "cpp" / "vmecpp" / "test_data" + +MBOZ = 8 +NBOZ = 6 + + +@pytest.fixture(scope="module") +def wout() -> vmecpp.VmecWOut: + indata = vmecpp.VmecInput.from_file(TEST_DATA_DIR / "cth_like_fixed_bdy.json") + return vmecpp.run(indata, max_threads=1, verbose=False).wout + + +@pytest.fixture(scope="module") +def transform(wout) -> boozer.BoozerTransform: + surfaces = [0, 1, wout.ns // 2, wout.ns - 2] + return boozer.BoozerTransform(wout, MBOZ, NBOZ, surfaces) + + +def _random_like(shapes, seed, scales=None): + generator = np.random.default_rng(seed) + return { + name: generator.standard_normal(shape) + * (1.0 if scales is None else scales[name]) + for name, shape in shapes.items() + } + + +def _input_scales(wout): + """Tangents at a relative size comparable to each field.""" + return { + name: float(np.max(np.abs(np.asarray(value)))) + for name, value in boozer.wout_spectra(wout).items() + } + + +def _perturbed(wout, tangent, step): + spectra = boozer.wout_spectra(wout) + return {name: np.asarray(spectra[name]) + step * tangent[name] for name in spectra} + + +_BOOZ_XFORM_SCRIPT = """ +import sys +import booz_xform +import numpy as np + +wout_path, out_path, mboz, nboz, ns = sys.argv[1:] +b = booz_xform.Booz_xform() +b.verbose = 0 +b.read_wout(wout_path) +b.mboz = int(mboz) +b.nboz = int(nboz) +b.compute_surfs = list(range(int(ns) - 1)) +b.run() +np.savez( + out_path, + xm_b=b.xm_b, xn_b=b.xn_b, s_b=b.s_b, bmnc_b=b.bmnc_b, rmnc_b=b.rmnc_b, + zmns_b=b.zmns_b, numns_b=b.numns_b, gmnc_b=b.gmnc_b, boozer_g=b.Boozer_G, + boozer_i=b.Boozer_I, iota_b=b.iota, +) +""" + + +def test_matches_booz_xform(wout, tmp_path) -> None: + pytest.importorskip("booz_xform") + path = tmp_path / "wout_cth.nc" + wout.save(path) + # booz_xform runs in its own process: its wheel bundles an OpenMP runtime that + # can clash with the one VMEC++ is linked against. + subprocess.run( + [ + sys.executable, + "-c", + _BOOZ_XFORM_SCRIPT, + str(path), + str(tmp_path / "booz.npz"), + str(MBOZ), + str(NBOZ), + str(wout.ns), + ], + check=True, + ) + reference = np.load(tmp_path / "booz.npz") + surfaces = list(range(wout.ns - 1)) + + result = boozer.boozer_transform(wout, MBOZ, NBOZ, surfaces) + np.testing.assert_array_equal(result["xm_b"], reference["xm_b"]) + np.testing.assert_array_equal(result["xn_b"], reference["xn_b"]) + np.testing.assert_allclose(result["s_b"], reference["s_b"], rtol=1e-14) + for name in boozer.OUTPUT_FIELDS: + ref = reference[name] + scale = np.max(np.abs(ref)) if np.any(ref) else 1.0 + np.testing.assert_allclose( + result[name], ref, rtol=0.0, atol=1e-12 * scale, err_msg=name + ) + + +def test_rejects_invalid_surfaces(wout) -> None: + with pytest.raises(ValueError, match="half grid"): + boozer.BoozerTransform(wout, MBOZ, NBOZ, [wout.ns - 1]) + + +@pytest.mark.parametrize("seed", [0, 1]) +def test_jvp_matches_central_differences(wout, transform, seed) -> None: + tangent = _random_like(transform.input_shapes(), seed, _input_scales(wout)) + jvp = transform.jvp(wout, tangent) + step = 1.0e-6 + plus = transform(_perturbed(wout, tangent, step)) + minus = transform(_perturbed(wout, tangent, -step)) + for name in boozer.OUTPUT_FIELDS: + difference = (plus[name] - minus[name]) / (2.0 * step) + scale = np.max(np.abs(difference)) + 1e-300 + np.testing.assert_allclose( + jvp[name], difference, rtol=0.0, atol=1e-7 * scale, err_msg=name + ) + + +@pytest.mark.parametrize("seed", [0, 1, 2]) +def test_vjp_is_the_adjoint_of_the_jvp(wout, transform, seed) -> None: + tangent = _random_like(transform.input_shapes(), seed) + cotangent = _random_like(transform.output_shapes(), seed + 100) + jvp = transform.jvp(wout, tangent) + vjp = transform.vjp(wout, cotangent) + left = sum(float(np.sum(jvp[k] * cotangent[k])) for k in boozer.OUTPUT_FIELDS) + right = sum(float(np.sum(vjp[k] * tangent[k])) for k in boozer.INPUT_FIELDS) + assert abs(left - right) <= 1e-12 * max(abs(left), abs(right)) + + +def _reference_transform(transform, wout): + """An independent JAX implementation of the stellarator-symmetric booz_xform + algorithm, with direct trigonometric evaluation, differentiated by JAX.""" + ns = transform.ns + nfp = int(wout.nfp) + xm, xn = np.asarray(wout.xm, float), np.asarray(wout.xn, float) + xm_nyq, xn_nyq = np.asarray(wout.xm_nyq, float), np.asarray(wout.xn_nyq, float) + xm_b, xn_b = transform.xm_b.astype(float), transform.xn_b.astype(float) + ntheta = 2 * (2 * MBOZ + 1) + nzeta = 2 * (2 * NBOZ + 1) + nu2 = ntheta // 2 + 1 + theta = np.repeat(np.arange(nu2) * 2 * np.pi / ntheta, nzeta) + zeta = np.tile(np.arange(nzeta) * 2 * np.pi / (nfp * nzeta), nu2) + weight = np.ones(nu2 * nzeta) + weight[:nzeta] = 0.5 + weight[-nzeta:] = 0.5 + factor = np.full(len(xm_b), 2.0 / ((nu2 - 1) * nzeta)) + factor[0] *= 0.5 + hs = 1.0 / (ns - 1) + sqrt_full = np.sqrt(hs * np.arange(ns)) + sqrt_full[0] = 1.0 + odd = (xm % 2 == 1)[:, None] + m1 = xm == 1 + origin = np.flatnonzero((xm_nyq == 0) & (xn_nyq == 0))[0] + safe_m = np.where(xm_nyq == 0, 1.0, xm_nyq) + safe_n = np.where(xn_nyq == 0, 1.0, xn_nyq) + + def basis(m, n, t, z): + angle = np.outer(t, np.ones_like(m)) * m - np.outer(z, np.ones_like(n)) * n + return np.cos(angle), np.sin(angle) + + cos_g, sin_g = basis(xm, xn, theta, zeta) + cos_n, sin_n = basis(xm_nyq, xn_nyq, theta, zeta) + + def half(full, j): + sqrt_half = np.sqrt(hs * (j + 0.5)) + even = 0.5 * (full[:, j] + full[:, j + 1]) + odd_value = ( + 0.5 * (full[:, j] / sqrt_full[j] + full[:, j + 1] / sqrt_full[j + 1]) + ) * sqrt_half + if j == 0: + extrapolated = ( + 1.5 * full[:, 1] / sqrt_full[1] - 0.5 * full[:, 2] / sqrt_full[2] + ) * sqrt_half + odd_value = jnp.where(m1, extrapolated, odd_value) + return jnp.where(odd[:, 0], odd_value, even) + + def apply(spectra): + out = {name: [] for name in boozer.OUTPUT_FIELDS} + for j in transform.surfaces: + c = j + 1 + rh, zh = half(spectra["rmnc"], j), half(spectra["zmns"], j) + lam = spectra["lmns"][:, c] + bsubu, bsubv = spectra["bsubumnc"][:, c], spectra["bsubvmnc"][:, c] + iota = spectra["iotas"][c] + big_i, big_g = bsubu[origin], bsubv[origin] + wmns = jnp.where( + xm_nyq != 0, + bsubu / safe_m, + jnp.where(xn_nyq != 0, -bsubv / safe_n, 0.0), + ) + r, z = cos_g @ rh, sin_g @ zh + lam_g, lam_t, lam_z = sin_g @ lam, cos_g @ (xm * lam), -cos_g @ (xn * lam) + w, w_t, w_z = ( + sin_n @ wmns, + cos_n @ (xm_nyq * wmns), + -cos_n @ (xn_nyq * wmns), + ) + b = cos_n @ spectra["bmnc"][:, c] + d = big_g + iota * big_i + nu = (w - big_i * lam_g) / d + nu_t = (w_t - big_i * lam_t) / d + nu_z = (w_z - big_i * lam_z) / d + theta_b = theta + lam_g + iota * nu + zeta_b = zeta + nu + jac = (1 + lam_t) * (1 + nu_z) + (iota - lam_z) * nu_t + angle = jnp.outer(theta_b, xm_b) - jnp.outer(zeta_b, xn_b) + cos_b, sin_b = jnp.cos(angle), jnp.sin(angle) + a = weight * jac + out["bmnc_b"].append(factor * (cos_b.T @ (a * b))) + out["rmnc_b"].append(factor * (cos_b.T @ (a * r))) + out["zmns_b"].append(factor * (sin_b.T @ (a * z))) + out["numns_b"].append(factor * (sin_b.T @ (a * nu))) + out["gmnc_b"].append(factor * (cos_b.T @ (a * d / b**2))) + out["iota_b"].append(iota) + out["boozer_g"].append(big_g) + out["boozer_i"].append(big_i) + return { + name: jnp.stack(values, axis=-1) + if name.endswith(("mnc_b", "mns_b")) + else jnp.stack(values) + for name, values in out.items() + } + + return apply + + +def test_jvp_matches_jax_autodiff_of_an_independent_implementation( + wout, transform +) -> None: + reference = _reference_transform(transform, wout) + spectra = {k: jnp.asarray(v) for k, v in boozer.wout_spectra(wout).items()} + primal = reference(spectra) + result = transform(wout) + for name in boozer.OUTPUT_FIELDS: + scale = np.max(np.abs(np.asarray(primal[name]))) + 1e-300 + np.testing.assert_allclose( + result[name], primal[name], rtol=0.0, atol=1e-12 * scale, err_msg=name + ) + tangent = _random_like(transform.input_shapes(), 7, _input_scales(wout)) + _, reference_tangent = jax.jvp( + reference, (spectra,), ({k: jnp.asarray(v) for k, v in tangent.items()},) + ) + jvp = transform.jvp(wout, tangent) + for name in boozer.OUTPUT_FIELDS: + ref = np.asarray(reference_tangent[name]) + scale = np.max(np.abs(ref)) + 1e-300 + np.testing.assert_allclose( + jvp[name], ref, rtol=0.0, atol=1e-11 * scale, err_msg=name + ) + + +def test_jax_vjp_matches_the_cpp_vjp(wout, transform) -> None: + apply = transform.jax() + spectra = {k: jnp.asarray(v) for k, v in boozer.wout_spectra(wout).items()} + cotangent = _random_like(transform.output_shapes(), 3) + primal, pull_back = jax.vjp(apply, spectra) + (bar,) = pull_back({k: jnp.asarray(v) for k, v in cotangent.items()}) + expected = transform.vjp(wout, cotangent) + np.testing.assert_allclose(primal["bmnc_b"], transform(wout)["bmnc_b"], rtol=1e-15) + for name in boozer.INPUT_FIELDS: + np.testing.assert_allclose(bar[name], expected[name], rtol=1e-15, err_msg=name) + + # jax.jacrev maps the VJP over output cotangents. + jacobian = jax.jacrev(lambda x: apply(x)["bmnc_b"][:2, 0])(spectra) + for row in range(2): + unit = np.zeros(transform.output_shapes()["bmnc_b"]) + unit[row, 0] = 1.0 + expected_row = transform.vjp(wout, {"bmnc_b": unit}) + np.testing.assert_allclose( + jacobian["bmnc"][row], expected_row["bmnc"], rtol=1e-15, atol=0.0 + ) + + +requires_enzyme = pytest.mark.skipif( + not vmecpp.has_exact_force_jacobian(), + reason="the VJP of run() needs an Enzyme-enabled build (VMECPP_ENABLE_ENZYME=ON)", +) + + +def _cth_like_input(ns: int, ftol: float, niter: int) -> vmecpp.VmecInput: + source = vmecpp.VmecInput.from_file( + REPO_ROOT / "examples" / "data" / "cth_like_fixed_bdy.json" + ) + return source.model_copy( + update={ + "ncurr": 0, + "piota_type": "power_series", + "ai": np.asarray([0.35, 0.15]), + "ns_array": np.asarray([ns]), + "ftol_array": np.asarray([ftol]), + "niter_array": np.asarray([niter]), + } + ) + + +@requires_enzyme +def test_boozer_spectrum_gradient_with_respect_to_the_boundary() -> None: + """jax.grad of a Boozer quasi-symmetry residual through the solve, the JAX output + stage and the Boozer adjoint, against a central difference of re-solves with the m=1 + gauge pinned as in the differentiable solve.""" + indata = _cth_like_input(ns=25, ftol=1.0e-14, niter=20000) + ns = int(np.asarray(indata.ns_array)[-1]) + model = _vmecpp.VmecModel.create(indata._to_cpp_vmecindata(), ns) + if not model.has_exact_force_jacobian: + pytest.skip("needs an Enzyme-enabled build for the exact residual transpose") + + boundary = jnp.stack([jnp.asarray(indata.rbc), jnp.asarray(indata.zbs)]) + + def with_boundary(value): + return indata.model_copy(update={"rbc": value[0], "zbs": value[1]}) + + reference_wout = vmecpp.run(indata, verbose=False).wout + transform = boozer.BoozerTransform(reference_wout, MBOZ, NBOZ, [ns // 2, ns - 2]) + apply = transform.jax() + non_symmetric = jnp.asarray(transform.xn_b != 0, dtype=jnp.float64) + + def residual(bmnc_b): + return jnp.sum((non_symmetric[:, None] * bmnc_b) ** 2) / jnp.sum(bmnc_b[0] ** 2) + + def objective(value): + wout = vmecpp.run(with_boundary(value), verbose=False).wout + return residual(apply(boozer.wout_spectra(wout))["bmnc_b"]) + + gradient = np.asarray(jax.grad(objective)(boundary)) + + generator = np.random.default_rng(0) + direction = np.zeros_like(np.asarray(boundary)) + low = generator.standard_normal((2, 3, 3)) + low[1, 0, 1] = 0.0 # zbs(m=0, n=0) is not a degree of freedom + direction[:, :3, indata.ntor - 1 : indata.ntor + 2] = low + direction *= 1.0e-3 * np.linalg.norm(boundary) / np.linalg.norm(direction) + + def pinned(value): + cpp_input = with_boundary(value)._to_cpp_vmecindata() + cpp_input.always_fix_m1_gauge = True + wout = vmecpp.VmecWOut._from_cpp_wout( + _vmecpp.run(cpp_input, verbose=_vmecpp.OutputMode.SILENT).wout + ) + return float(residual(transform(wout)["bmnc_b"])) + + central = 0.5 * ( + pinned(np.asarray(boundary) + direction) + - pinned(np.asarray(boundary) - direction) + ) + directional = float(np.sum(gradient * direction)) + np.testing.assert_allclose(directional, central, rtol=2.0e-2)