From 222c48a583c7c12772d4e020ba6a69304cdbf3bf Mon Sep 17 00:00:00 2001 From: eduardolneto Date: Mon, 17 Aug 2026 21:39:23 +0100 Subject: [PATCH] Adding capabiility of static frozen dofs. Examples and tests added --- essos/augmented_lagrangian.py | 34 ++++- essos/frozen_dofs.py | 131 ++++++++++++++++++ essos/losses.py | 48 +++++-- .../optimize_coils_frozen_current.py | 39 ++++++ ...ils_frozen_current_augmented_lagrangian.py | 41 ++++++ ...ace_augmented_lagrangian_frozen_current.py | 99 +++++++++++++ ...imize_coils_vmec_surface_frozen_current.py | 95 +++++++++++++ .../simple_examples/freeze_surface_modes.py | 22 +++ tests/test_augmented_lagrangian.py | 20 +++ tests/test_multiobjectives.py | 66 +++++++++ 10 files changed, 579 insertions(+), 16 deletions(-) create mode 100644 essos/frozen_dofs.py create mode 100644 examples/coil_optimization/optimize_coils_frozen_current.py create mode 100644 examples/coil_optimization/optimize_coils_frozen_current_augmented_lagrangian.py create mode 100644 examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_frozen_current.py create mode 100644 examples/coil_optimization/optimize_coils_vmec_surface_frozen_current.py create mode 100644 examples/simple_examples/freeze_surface_modes.py diff --git a/essos/augmented_lagrangian.py b/essos/augmented_lagrangian.py index fce601c4..33a3aeb8 100644 --- a/essos/augmented_lagrangian.py +++ b/essos/augmented_lagrangian.py @@ -10,6 +10,7 @@ import optax import jaxopt import optimistix +from essos.frozen_dofs import FrozenDOFs class LagrangeMultiplier(NamedTuple): """A class containing constrain parameters for Augmented Lagrangian Method""" @@ -50,7 +51,7 @@ def __init__(self, init: Callable, loss: Callable): self.loss = loss -class CompositeConstraint: +class CompositeConstraint(FrozenDOFs): """Mutable composite constraint container. Exposes `init` and `loss` callables (same as `Constraint`) while @@ -67,10 +68,16 @@ def __init__(self, init_fn: Callable, loss_fn: Callable, selective_map=None, arg self._dependencies = {} self._starting_dofs = None self._dofs_to_pytree = None + self._init_frozen_dofs() def clear_cache(self): self._starting_dofs = None self._dofs_to_pytree = None + self._init_frozen_dofs() + + @property + def _dependency_dof_names(self): + return tuple(self.arg_names) @property def dependencies(self): @@ -94,7 +101,8 @@ def starting_dofs(self): if not self._dependencies: raise RuntimeError("dependencies must be set on composite before accessing starting_dofs") vals = tuple(self._dependencies[name] for name in self.arg_names) - self._starting_dofs, self._dofs_to_pytree = jax.flatten_util.ravel_pytree(vals) + self._starting_dofs, unraveler = jax.flatten_util.ravel_pytree(vals) + self._dofs_to_pytree = lambda dofs: unraveler(self._project_dofs(dofs)) return self._starting_dofs @property @@ -104,7 +112,7 @@ def dofs_to_pytree(self): return self._dofs_to_pytree -class SelectiveConstraint: +class SelectiveConstraint(FrozenDOFs): """Wraps a constraint with selective named dependencies, similar to custom_loss. This allows constraints to only depend on a subset of the available degrees of freedom @@ -155,10 +163,16 @@ def __init__(self, constraint: BaseConstraint, *arg_names, **kwargs): self._dependencies = {} self._starting_dofs = None self._dofs_to_pytree = None + self._init_frozen_dofs() def clear_cache(self): self._starting_dofs = None self._dofs_to_pytree = None + self._init_frozen_dofs() + + @property + def _dependency_dof_names(self): + return tuple(self.arg_names) @property def dependencies(self): @@ -191,7 +205,8 @@ def starting_dofs(self): if not self._dependencies: raise RuntimeError("dependencies must be set before accessing starting_dofs") vals = tuple(self._dependencies[name] for name in self.arg_names) - self._starting_dofs, self._dofs_to_pytree = jax.flatten_util.ravel_pytree(vals) + self._starting_dofs, unraveler = jax.flatten_util.ravel_pytree(vals) + self._dofs_to_pytree = lambda dofs: unraveler(self._project_dofs(dofs)) return self._starting_dofs @property @@ -473,6 +488,10 @@ def wrapped_init(*a, **kw): is_object_like = hasattr(first, 'B') or hasattr(first, 'coils') or hasattr(first, 'dofs') or isinstance(first, dict) looks_flat = (hasattr(first, 'ndim') or hasattr(first, 'shape') or hasattr(first, 'aval')) if a and (looks_flat and not is_object_like): + if combined._frozen_dofs_mask is not None: + all_pytrees = combined.dofs_to_pytree(a[0]) + pytrees = tuple(all_pytrees[idx] for idx in s._composite_index_map) + return f(*pytrees, **merged_kw) # Try per-selective unravel first; if it fails, fall back to composite unravel try: pytrees = s.dofs_to_pytree(a[0]) @@ -501,6 +520,10 @@ def wrapped_loss(p, *a, **kw): is_object_like = hasattr(first, 'B') or hasattr(first, 'coils') or hasattr(first, 'dofs') or isinstance(first, dict) looks_flat = (hasattr(first, 'ndim') or hasattr(first, 'shape') or hasattr(first, 'aval')) if a and (looks_flat and not is_object_like): + if combined._frozen_dofs_mask is not None: + all_pytrees = combined.dofs_to_pytree(a[0]) + pytrees = tuple(all_pytrees[idx] for idx in s._composite_index_map) + return f(p, *pytrees, **merged_kw) try: pytrees = s.dofs_to_pytree(a[0]) return f(p, *pytrees, **merged_kw) @@ -846,6 +869,3 @@ def update_fn(params, lag_state,grad,info,beta=beta,mu_max=mu_max,alpha=alpha,ga - - - diff --git a/essos/frozen_dofs.py b/essos/frozen_dofs.py new file mode 100644 index 00000000..80e8a86d --- /dev/null +++ b/essos/frozen_dofs.py @@ -0,0 +1,131 @@ +"""User-facing selectors for freezing ESSOS optimization degrees of freedom.""" +import jax.numpy as jnp +from jax.flatten_util import ravel_pytree + + +class FrozenDOFs: + """Mixin for losses and constraints whose DOFs are built from dependencies. + + Subclasses provide ``dependencies`` and ``_dependency_dof_names`` in the + same order used to construct ``starting_dofs``. + """ + def _init_frozen_dofs(self): + self._frozen_dofs_mask = None + self._frozen_dofs_values = None + + def freeze_dofs(self, mask): + """Freeze a flat boolean mask, or a matching pytree, at initial values.""" + if not hasattr(mask, "shape"): + mask, _ = ravel_pytree(mask) + mask = jnp.asarray(mask, dtype=bool).reshape(-1) + if mask.shape != self.starting_dofs.shape: + raise ValueError( + f"freeze mask has shape {mask.shape}; expected {self.starting_dofs.shape}." + ) + self._frozen_dofs_mask = mask + self._frozen_dofs_values = self.starting_dofs + return self + + def unfreeze_dofs(self): + """Remove every frozen-DOF selection from this loss or constraint.""" + self._init_frozen_dofs() + return self + + def _project_dofs(self, dofs): + if self._frozen_dofs_mask is None: + return dofs + return jnp.where(self._frozen_dofs_mask, self._frozen_dofs_values, dofs) + + def _mask_gradient(self, gradient): + if self._frozen_dofs_mask is None: + return gradient + return jnp.where(self._frozen_dofs_mask, 0, gradient) + + def _dependency_offset(self, dependency): + names = tuple(self._dependency_dof_names) + if dependency not in names: + raise KeyError( + f"{dependency!r} is not an optimizable dependency. Available: {names}." + ) + preceding = tuple(self.dependencies[name] for name in names[:names.index(dependency)]) + return 0 if not preceding else ravel_pytree(preceding)[0].size + + def _add_frozen_indices(self, indices): + mask = (jnp.zeros_like(self.starting_dofs, dtype=bool) + if self._frozen_dofs_mask is None else self._frozen_dofs_mask) + indices = jnp.asarray(indices, dtype=int).reshape(-1) + if jnp.any(indices < 0) or jnp.any(indices >= mask.size): + raise IndexError("selected DOF index is outside starting_dofs.") + return self.freeze_dofs(mask.at[indices].set(True)) + + @staticmethod + def _indices(values, size, label): + values = [values] if isinstance(values, int) else list(values) + if any(value < 0 or value >= size for value in values): + raise IndexError(f"{label} must be in [0, {size - 1}].") + return values + + def freeze_current(self, dependency="field", coil=0): + """Freeze normalized current DOFs for one or more base coils.""" + field = self.dependencies[dependency] + coils = field.coils + current_indices = self._indices(coil, coils.dofs_currents.size, "coil index") + start = self._dependency_offset(dependency) + coils.dofs_curves.size + return self._add_frozen_indices([start + index for index in current_indices]) + + def freeze_coil(self, dependency="field", coil=0): + """Freeze every curve coefficient of one or more base coils.""" + field = self.dependencies[dependency] + shape = field.coils.dofs_curves.shape + coil_indices = self._indices(coil, shape[0], "coil index") + per_coil = shape[1] * shape[2] + start = self._dependency_offset(dependency) + return self._add_frozen_indices( + [start + coil_index * per_coil + local for coil_index in coil_indices for local in range(per_coil)] + ) + + def freeze_curve_dofs(self, dependency="field", coil=0, coordinates=None, modes=None): + """Freeze selected stored curve coefficients of one or more base coils. + + ``coordinates`` accepts ``"x"``, ``"y"``, ``"z"`` (or 0, 1, 2), + and ``modes`` are indices into ``Curves.dofs[..., mode]``. + """ + field = self.dependencies[dependency] + shape = field.coils.dofs_curves.shape + coil_indices = self._indices(coil, shape[0], "coil index") + if coordinates is None: + coordinates = range(shape[1]) + if modes is None: + modes = range(shape[2]) + coordinate_map = {"x": 0, "y": 1, "z": 2} + if isinstance(coordinates, (int, str)): + coordinates = [coordinates] + coordinates = [coordinate_map.get(value, value) for value in coordinates] + coordinates = self._indices(coordinates, shape[1], "coordinate index") + modes = self._indices(modes, shape[2], "mode index") + start = self._dependency_offset(dependency) + per_coil = shape[1] * shape[2] + return self._add_frozen_indices([ + start + coil_index * per_coil + coordinate * shape[2] + mode + for coil_index in coil_indices for coordinate in coordinates for mode in modes + ]) + + def freeze_surface_modes(self, dependency="surface", rc=(), zs=()): + """Freeze ``SurfaceRZFourier`` coefficients by physical ``(m, n)`` mode.""" + surface = self.dependencies[dependency] + start = self._dependency_offset(dependency) + + def mode_indices(modes, coefficients, component): + out = [] + for m, n in modes: + matches = jnp.where((surface.xm == m) & (surface.xn == n))[0] + if matches.size != 1: + raise KeyError(f"{component}({n},{m}) is not present on this surface.") + out.append(start + coefficients + int(matches[0])) + return out + + indices = mode_indices(rc, 0, "RBC") + indices += mode_indices(zs, surface.rc.size, "ZBS") + if not indices: + raise ValueError("select at least one rc or zs surface mode.") + return self._add_frozen_indices(indices) diff --git a/essos/losses.py b/essos/losses.py index 16360d13..fbac1ef5 100644 --- a/essos/losses.py +++ b/essos/losses.py @@ -2,19 +2,22 @@ import jax.numpy as jnp from jax import tree_util, jit, grad as jax_grad, value_and_grad as jax_value_and_grad from jax.flatten_util import ravel_pytree +from essos.frozen_dofs import FrozenDOFs -class base_loss: +class base_loss(FrozenDOFs): def __init__(self): self.losses = [self] self._dependencies = {} self._dependencies_buffer = None self._starting_dofs = None self._dofs_to_pytree = None + self._init_frozen_dofs() def clear_cache(self): self._dependencies_buffer = None self._starting_dofs = None self._dofs_to_pytree = None + self._init_frozen_dofs() @property def dependencies(self): @@ -77,6 +80,10 @@ def clear_cache(self): super().clear_cache() self._dofs_to_args = None + @property + def _dependency_dof_names(self): + return self.args_names + def _ensure_unravelers(self): if self._starting_dofs is None or self._dofs_to_args is None or self._dofs_to_pytree is None: self._starting_dofs, tuple_unraveler = ravel_pytree( @@ -85,6 +92,7 @@ def _ensure_unravelers(self): self._dofs_to_args = tuple_unraveler def _named_unraveler(dofs): + dofs = self._project_dofs(dofs) args = tuple_unraveler(dofs) return {name: value for name, value in zip(self.args_names, args)} @@ -100,44 +108,56 @@ def starting_dofs(self): def dofs_to_pytree(self): self._ensure_unravelers() return self._dofs_to_pytree + + def _project_args(self, args): + if self._frozen_dofs_mask is None: + return args + masks = self._dofs_to_args(self._frozen_dofs_mask) + frozen_args = self._dofs_to_args(self._frozen_dofs_values) + return tuple(jnp.where(mask, frozen, arg) + for arg, mask, frozen in zip(args, masks, frozen_args)) @partial(jit, static_argnames=['self']) def __call__(self, dofs: jnp.ndarray) -> float: self._ensure_unravelers() - args = self._dofs_to_args(dofs) + args = self._dofs_to_args(self._project_dofs(dofs)) return self.fun(*args, **self.kwargs) @partial(jit, static_argnames=['self']) def call_pytree(self, dofs_pytree) -> float: + self._ensure_unravelers() if isinstance(dofs_pytree, dict): args = tuple(dofs_pytree[name] for name in self.args_names) else: args = tuple(dofs_pytree) + args = self._project_args(args) return self.fun(*args, **self.kwargs) @partial(jit, static_argnames=['self']) def grad(self, dofs: jnp.ndarray) -> jnp.ndarray: self._ensure_unravelers() - args = self._dofs_to_args(dofs) + args = self._dofs_to_args(self._project_dofs(dofs)) gradient = jax_grad(self.fun, argnums=tuple(range(len(args))))(*args, **self.kwargs) - return ravel_pytree(gradient)[0] + return self._mask_gradient(ravel_pytree(gradient)[0]) @partial(jit, static_argnames=['self']) def value_and_grad(self, dofs: jnp.ndarray): self._ensure_unravelers() - args = self._dofs_to_args(dofs) + args = self._dofs_to_args(self._project_dofs(dofs)) value, gradient = jax_value_and_grad( self.fun, argnums=tuple(range(len(args))), )(*args, **self.kwargs) - return value, ravel_pytree(gradient)[0] + return value, self._mask_gradient(ravel_pytree(gradient)[0]) @partial(jit, static_argnames=['self']) def grad_pytree(self, dofs_pytree) -> dict: + self._ensure_unravelers() if isinstance(dofs_pytree, dict): args = tuple(dofs_pytree[name] for name in self.args_names) else: args = tuple(dofs_pytree) + args = self._project_args(args) gradient = jax_grad(self.fun, argnums=tuple(range(len(args))))(*args, **self.kwargs) # Build a fresh zeros structure locally instead of using the cached # dependencies_buffer property, which would cache a traced value and @@ -145,6 +165,10 @@ def grad_pytree(self, dofs_pytree) -> dict: buffer = tree_util.tree_map(jnp.zeros_like, self.dependencies) for dep, g in zip(self.args_names, gradient): buffer[dep] = g + if self._frozen_dofs_mask is not None: + masks = self._dofs_to_args(self._frozen_dofs_mask) + for dep, mask in zip(self.args_names, masks): + buffer[dep] = jnp.where(mask, 0, buffer[dep]) return buffer def __mul__(self, other): @@ -172,6 +196,10 @@ def __init__(self, losses: list): @property def dependencies(self): return self._dependencies + + @property + def _dependency_dof_names(self): + return tuple(sorted(self.dependencies)) @dependencies.setter def dependencies(self, value): @@ -185,13 +213,15 @@ def dependencies(self, value): @property def starting_dofs(self): if self._starting_dofs is None: - self._starting_dofs, self._dofs_to_pytree = ravel_pytree(self.dependencies) + self._starting_dofs, unraveler = ravel_pytree(self.dependencies) + self._dofs_to_pytree = lambda dofs: unraveler(self._project_dofs(dofs)) return self._starting_dofs @property def dofs_to_pytree(self): if self._dofs_to_pytree is None: - self._starting_dofs, self._dofs_to_pytree = ravel_pytree(self.dependencies) + self._starting_dofs, unraveler = ravel_pytree(self.dependencies) + self._dofs_to_pytree = lambda dofs: unraveler(self._project_dofs(dofs)) return self._dofs_to_pytree @partial(jit, static_argnames=['self']) @@ -210,4 +240,4 @@ def grad(self, dofs: jnp.ndarray) -> jnp.ndarray: grad = tree_util.tree_map(lambda *dofs: jnp.sum(jnp.stack(dofs), axis=0), *grads_each_loss) dofs_grad = ravel_pytree(grad)[0] - return dofs_grad + return self._mask_gradient(dofs_grad) diff --git a/examples/coil_optimization/optimize_coils_frozen_current.py b/examples/coil_optimization/optimize_coils_frozen_current.py new file mode 100644 index 00000000..70af584d --- /dev/null +++ b/examples/coil_optimization/optimize_coils_frozen_current.py @@ -0,0 +1,39 @@ +"""Optimize coil currents while keeping one normalized current DOF fixed. + +The freeze mask is in the existing flattened optimizer space. Curves are +flattened first and normalized current DOFs are the final ``N_COILS`` entries. +``currents_scale`` remains fixed, so the physical frozen current is also fixed. +""" +import jax.numpy as jnp +from scipy.optimize import least_squares + +from essos.coils import Coils, CreateEquallySpacedCurves +from essos.fields import BiotSavart +from essos.losses import custom_loss + + +N_COILS = 2 +FROZEN_CURRENT = 0 + +curves = CreateEquallySpacedCurves( + n_curves=N_COILS, order=1, R=10.0, r=2.0, n_segments=20, nfp=1, stellsym=False +) +field = BiotSavart(Coils(curves, currents=jnp.array([1.0, 2.0]))) + + +def current_residual(field): + """A small demonstrator objective: drive only free normalized currents to zero.""" + return jnp.sum(field.coils.dofs_currents**2) + + +loss = custom_loss(current_residual, "field") +loss.dependencies = {"field": field} + +loss.freeze_current("field", coil=FROZEN_CURRENT) + +result = least_squares(loss, loss.starting_dofs, jac=loss.grad) +optimized_field = loss.dofs_to_pytree(result.x)["field"] + +print("Initial normalized currents:", field.coils.dofs_currents) +print("Optimized normalized currents:", optimized_field.coils.dofs_currents) +print("Frozen physical current:", optimized_field.coils.dofs_currents_raw[FROZEN_CURRENT]) diff --git a/examples/coil_optimization/optimize_coils_frozen_current_augmented_lagrangian.py b/examples/coil_optimization/optimize_coils_frozen_current_augmented_lagrangian.py new file mode 100644 index 00000000..5af0cd0c --- /dev/null +++ b/examples/coil_optimization/optimize_coils_frozen_current_augmented_lagrangian.py @@ -0,0 +1,41 @@ +"""Augmented-Lagrangian coil-current example with one frozen current DOF. + +The same flat mask convention as the normal custom-loss example is used. The +constraint drives the second current to zero while the first remains frozen. +""" +import jax.numpy as jnp + +import essos.augmented_lagrangian as alm +from essos.coils import Coils, CreateEquallySpacedCurves +from essos.fields import BiotSavart + + +N_COILS = 2 +FROZEN_CURRENT = 0 + +curves = CreateEquallySpacedCurves( + n_curves=N_COILS, order=1, R=10.0, r=2.0, n_segments=20, nfp=1, stellsym=False +) +field = BiotSavart(Coils(curves, currents=jnp.array([1.0, 2.0]))) + + +def free_current_constraint(field): + return field.coils.dofs_currents[1] + + +constraint = alm.SelectiveConstraint(alm.eq(free_current_constraint), "field") +constraints = alm.combine(constraint) +constraints.dependencies = {"field": field} + +constraints.freeze_current("field", coil=FROZEN_CURRENT) + +lagrange_params = constraints.init(field.dofs) +optimizer = alm.ALM_model_jaxopt_lbfgsb(constraints=constraints) +params = (field.dofs, lagrange_params) +state, gradient, info = optimizer.init(params) +params, state, gradient, info = optimizer.update(params, state, gradient, info) + +optimized_field, = constraints.dofs_to_pytree(params[0]) +print("Initial normalized currents:", field.coils.dofs_currents) +print("Optimized normalized currents:", optimized_field.coils.dofs_currents) +print("Frozen physical current:", optimized_field.coils.dofs_currents_raw[FROZEN_CURRENT]) diff --git a/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_frozen_current.py b/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_frozen_current.py new file mode 100644 index 00000000..bfe47767 --- /dev/null +++ b/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_frozen_current.py @@ -0,0 +1,99 @@ +"""VMEC-surface augmented-Lagrangian optimization with one frozen current. + +This is the ALM portion of the existing VMEC-surface comparison example. The +only freezing-specific code is the named current selection on +``C_total_constraint``. +""" +import os +from time import time + +import jax.numpy as jnp +import matplotlib.pyplot as plt + +import essos.augmented_lagrangian as alm +from essos.coils import Coils, CreateEquallySpacedCurves +from essos.fields import BiotSavart +from essos.surfaces import SurfaceRZFourier, BdotN_over_B + + +maximum_function_evaluations = 100 +input_filepath = os.path.join(os.path.dirname(__file__), "..", "input_files") +vmec_input = os.path.join(input_filepath, "wout_LandremanPaul2021_QA_reactorScale_lowres.nc") + +N_COILS = 4; FOURIER_ORDER = 3; LARGE_R = 10.; SMALL_R = 5.7; NFP = 2; N_SEGMENTS = 30; STELLSYM = True +COIL_CURRENT = 1. +FROZEN_CURRENT_INDEX = 0 + +LENGTH_TARGET = 40. +CURVATURE_TARGET = 0.5 +BdotN_TARGET_TOL = 1.e-6 + +curves = CreateEquallySpacedCurves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, + n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) +init_coils = Coils(curves=curves, currents=[COIL_CURRENT] * N_COILS) +init_field = BiotSavart(init_coils) +surface = SurfaceRZFourier.from_wout_file(vmec_input, s=1, ntheta=32, nphi=32, range_torus="half period") + + +def bdotn_constraint(field, surface, target_tol=BdotN_TARGET_TOL): + bdotn_over_b = BdotN_over_B(surface, field) + return jnp.sqrt(jnp.sum(jnp.maximum(jnp.square(bdotn_over_b) - target_tol, 0.0))) + + +def length_constraint(field): + return jnp.maximum(0, field.coils.length - LENGTH_TARGET) + + +def curvature_constraint(field): + return jnp.maximum(0, field.coils.curvature - CURVATURE_TARGET) + + +model_lagrangian = "Standard" +normal_field = alm.eq(bdotn_constraint, model_lagrangian=model_lagrangian) +length = alm.eq(length_constraint, model_lagrangian=model_lagrangian) +curvature = alm.eq(curvature_constraint, model_lagrangian=model_lagrangian) + +C_normal_field = alm.SelectiveConstraint(normal_field, "field", surface=surface) +C_length = alm.SelectiveConstraint(length, "field") +C_curvature = alm.SelectiveConstraint(curvature, "field") +C_total_constraint = alm.combine(C_normal_field, C_length, C_curvature) +C_total_constraint.dependencies = {"field": init_field} + +C_total_constraint.freeze_current("field", coil=FROZEN_CURRENT_INDEX) + +ALM = alm.ALM_model_jaxopt_lbfgsb( + constraints=C_total_constraint, + model_lagrangian=model_lagrangian, + beta=2., mu_max=1.e4, alpha=0.99, gamma=1.e-2, epsilon=1.e-8, + eta_tol=1.e-7, omega_tol=1.e-7, +) + +lagrange_params = C_total_constraint.init(init_field.dofs) +params = (init_field.dofs, lagrange_params) +lag_state, gradient, info = ALM.init(params) + +t_start = time() +i = 0 +while i <= maximum_function_evaluations and ( + jnp.linalg.norm(gradient[0]) > 1.e-7 or alm.norm_constraints(info[2]) > 1.e-7 +): + params, lag_state, gradient, info = ALM.update(params, lag_state, gradient, info) + print(f"i: {i}, loss f: {info[0]:g}, loss L: {info[1]:g}, infeasibility: {alm.total_infeasibility(info[2]):g}") + i += 1 + +opt_field, = C_total_constraint.dofs_to_pytree(params[0]) +opt_coils = opt_field.coils +print(f"\nOptimization took {time() - t_start:.2f} seconds") +print("Initial normalized currents:", init_coils.dofs_currents) +print("Optimized normalized currents:", opt_coils.dofs_currents) +print("Frozen physical current:", opt_coils.dofs_currents_raw[FROZEN_CURRENT_INDEX]) + +fig = plt.figure(figsize=(8, 4)) +ax1 = fig.add_subplot(121, projection="3d") +init_coils.plot(ax=ax1, show=False) +surface.plot(ax=ax1, show=False) +ax2 = fig.add_subplot(122, projection="3d") +opt_coils.plot(ax=ax2, show=False) +surface.plot(ax=ax2, show=False) +plt.tight_layout() +plt.show() diff --git a/examples/coil_optimization/optimize_coils_vmec_surface_frozen_current.py b/examples/coil_optimization/optimize_coils_vmec_surface_frozen_current.py new file mode 100644 index 00000000..658a7b89 --- /dev/null +++ b/examples/coil_optimization/optimize_coils_vmec_surface_frozen_current.py @@ -0,0 +1,95 @@ +"""VMEC-surface coil optimization with one normalized base-current DOF frozen. + +This is the same optimization as ``optimize_coils_vmec_surface.py``. Only the +named frozen-current selection below ``L_total.dependencies`` is new. +""" +import os +from time import time +import jax.numpy as jnp +import matplotlib.pyplot as plt + +from essos.coils import Coils, CreateEquallySpacedCurves +from essos.fields import BiotSavart +from essos.surfaces import SurfaceRZFourier, BdotN_over_B +from essos.losses import custom_loss +from scipy.optimize import least_squares + + +input_filepath = os.path.join(os.path.dirname(__file__), "..", "input_files") +vmec_input = os.path.join(input_filepath, "wout_LandremanPaul2021_QA_reactorScale_lowres.nc") + +""" Creating starting coils and surface """ +N_COILS = 3; FOURIER_ORDER = 3; LARGE_R = 10; SMALL_R = 5.6; NFP = 2; N_SEGMENTS = 45; STELLSYM = True +COIL_CURRENT = 1. +FROZEN_CURRENT_INDEX = 0 # Base-coil current to retain at its initial value. + +init_curves = CreateEquallySpacedCurves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, + n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) +init_coils = Coils(curves=init_curves, currents=[COIL_CURRENT] * N_COILS) +init_field = BiotSavart(init_coils) +surface = SurfaceRZFourier.from_wout_file(vmec_input, s=1, ntheta=30, nphi=30, range_torus="half period") + +""" Setting the losses weights and targets """ +LENGTH_WEIGHT = 1.; LENGTH_TARGET = 32. +CURVATURE_WEIGHT = 1.; CURVATURE_TARGET = 0.1 +NORMAL_FIELD_WEIGHT = 1. + + +def loss(field, surface): + return jnp.sum(jnp.abs(BdotN_over_B(surface, field))) + + +def loss_length(field): + return jnp.mean(jnp.maximum(0, field.coils.length - LENGTH_TARGET)) + + +def loss_curvature(field): + return jnp.mean(jnp.maximum(0, field.coils.curvature - CURVATURE_TARGET)) + + +""" Defining custom losses """ +L_normal_field = custom_loss(loss, "field", surface=surface) +L_length = custom_loss(loss_length, "field") +L_curvature = custom_loss(loss_curvature, "field") + +""" Defining total loss + setting dependencies """ +L_total = NORMAL_FIELD_WEIGHT * L_normal_field + LENGTH_WEIGHT * L_length + CURVATURE_WEIGHT * L_curvature +L_total.dependencies = {"field": init_field} + +L_total.freeze_current("field", coil=FROZEN_CURRENT_INDEX) + +""" Optimizing the total loss """ +t_start = time() +res = least_squares(L_total, L_total.starting_dofs, L_total.grad, verbose=2, + ftol=1e-5, gtol=1e-5, xtol=1e-14, max_nfev=200) +t_end = time() + +print(f"\nOptimization took {t_end - t_start:.2f} seconds") +print("Initial loss:", L_total(L_total.starting_dofs)) +print("Loss after optimization:", L_total(res.x)) + +opt_field = L_total.dofs_to_pytree(res.x)["field"] +opt_coils = opt_field.coils +print("Initial normalized currents:", init_coils.dofs_currents) +print("Optimized normalized currents:", opt_coils.dofs_currents) +print("Frozen physical current:", opt_coils.dofs_currents_raw[FROZEN_CURRENT_INDEX]) + +fig = plt.figure(figsize=(8, 4)) +ax1 = fig.add_subplot(121, projection="3d") +init_coils.plot(ax=ax1, show=False) +surface.plot(ax=ax1, show=False) +ax2 = fig.add_subplot(122, projection="3d") +opt_coils.plot(ax=ax2, show=False) +surface.plot(ax=ax2, show=False) +plt.tight_layout() +plt.show() + +EXPORT = False +if EXPORT: + output_filepath = os.path.join(os.path.dirname(__file__), "output") + init_coils.to_json(os.path.join(output_filepath, "init_coils_vmec_surface.json")) + opt_coils.to_json(os.path.join(output_filepath, "opt_coils_vmec_surface.json")) + surface.to_vtk(os.path.join(output_filepath, "init_surface_vmec_surface.json"), field=init_field) + surface.to_vtk(os.path.join(output_filepath, "final_surface_vmec_surface.json"), field=opt_field) + init_coils.to_vtk(os.path.join(output_filepath, "init_coils_vmec_surface.json")) + opt_coils.to_vtk(os.path.join(output_filepath, "opt_coils_vmec_surface.json")) diff --git a/examples/simple_examples/freeze_surface_modes.py b/examples/simple_examples/freeze_surface_modes.py new file mode 100644 index 00000000..a384a30d --- /dev/null +++ b/examples/simple_examples/freeze_surface_modes.py @@ -0,0 +1,22 @@ +"""Select `SurfaceRZFourier` Fourier coefficients by their physical (m, n) mode.""" +import jax.numpy as jnp + +from essos.losses import custom_loss +from essos.surfaces import SurfaceRZFourier + + +surface = SurfaceRZFourier( + rc=jnp.array([10.0, 1.0]), zs=jnp.array([0.0, 2.0]), + nfp=1, mpol=1, ntor=0, +) + +loss = custom_loss(lambda surface: jnp.sum(surface.rc**2) + jnp.sum(surface.zs**2), "surface") +loss.dependencies = {"surface": surface} + +# Freeze RBC(0,1) and ZBS(0,1), expressed as (m, n) pairs. +loss.freeze_surface_modes("surface", rc=[(1, 0)], zs=[(1, 0)]) + +proposed = loss.starting_dofs + 1.0 +frozen_surface = loss.dofs_to_pytree(proposed)["surface"] +print("Initial rc, zs:", surface.rc, surface.zs) +print("After a proposed update:", frozen_surface.rc, frozen_surface.zs) diff --git a/tests/test_augmented_lagrangian.py b/tests/test_augmented_lagrangian.py index 21462a77..bf9df6a7 100644 --- a/tests/test_augmented_lagrangian.py +++ b/tests/test_augmented_lagrangian.py @@ -78,6 +78,14 @@ def test_selective_constraint_dependencies_reset_cached_dofs(self): self.assertEqual(second.shape[0], 3) self.assertTrue(jnp.allclose(second, jnp.array([3.0, 4.0, 5.0]))) + def test_selective_constraint_freezes_dofs_in_unraveler(self): + selective = SelectiveConstraint(eq(lambda field: field - 1), 'field') + selective.dependencies = {'field': jnp.array([1.0, 2.0])} + selective.freeze_dofs(jnp.array([False, True])) + + field, = selective.dofs_to_pytree(jnp.array([3.0, 4.0])) + self.assertTrue(jnp.allclose(field, jnp.array([3.0, 2.0]))) + def test_composite_constraint_dependencies_reset_cached_dofs(self): c1 = SelectiveConstraint(eq(lambda field: field - 1), 'field') c2 = SelectiveConstraint(eq(lambda surface: surface + 1), 'surface') @@ -98,6 +106,18 @@ def test_composite_constraint_dependencies_reset_cached_dofs(self): self.assertEqual(second.shape[0], 3) self.assertTrue(jnp.allclose(second, jnp.array([3.0, 20.0, 30.0]))) + def test_composite_constraint_freezes_dofs_in_unraveler(self): + c1 = SelectiveConstraint(eq(lambda field: field - 1), 'field') + combined = combine(c1) + combined.dependencies = {'field': jnp.array([1.0, 2.0])} + combined.freeze_dofs(jnp.array([True, False])) + + field, = combined.dofs_to_pytree(jnp.array([3.0, 4.0])) + self.assertTrue(jnp.allclose(field, jnp.array([1.0, 4.0]))) + params = combined.init(combined.starting_dofs) + _, infeasibility = combined.loss(params, jnp.array([3.0, 4.0])) + self.assertTrue(jnp.allclose(infeasibility[0], jnp.array([0.0, 3.0]))) + def test_composite_constraint_set_dependencies_resets_cached_dofs(self): c1 = SelectiveConstraint(eq(lambda field: field - 1), 'field') combined = combine(c1) diff --git a/tests/test_multiobjectives.py b/tests/test_multiobjectives.py index 8461f5b7..a0fab469 100644 --- a/tests/test_multiobjectives.py +++ b/tests/test_multiobjectives.py @@ -5,6 +5,7 @@ from essos.multiobjectiveoptimizer import MultiObjectiveOptimizer from essos.coils import Coils,Curves from essos.fields import BiotSavart +from essos.surfaces import SurfaceRZFourier from essos.objective_functions import loss_coil_length, loss_coil_curvature from essos.surfaces import BdotN_over_B @@ -70,6 +71,71 @@ def loss_fn(curve_dofs, current): assert jnp.array_equal(gradient_tuple["unused"], gradient["unused"]) +def test_custom_loss_freeze_dofs_keeps_pytree_and_zeroes_gradient(): + loss = custom_loss(lambda x: jnp.sum(x**2), "x") + loss.dependencies = {"x": jnp.array([1.0, 2.0, 3.0])} + loss.freeze_dofs(jnp.array([False, True, False])) + + proposed = jnp.array([4.0, 5.0, 6.0]) + assert loss(proposed) == 16.0 + 4.0 + 36.0 + assert jnp.array_equal(loss.dofs_to_pytree(proposed)["x"], jnp.array([4.0, 2.0, 6.0])) + assert jnp.array_equal(loss.grad(proposed), jnp.array([8.0, 0.0, 12.0])) + + +def test_composite_loss_freeze_dofs_keeps_dependency_pytree(): + first = custom_loss(lambda x: jnp.sum(x**2), "x") + second = custom_loss(lambda y: jnp.sum(y**2), "y") + loss = first + second + loss.dependencies = {"x": jnp.array([1.0]), "y": jnp.array([2.0])} + loss.freeze_dofs(jnp.array([True, False])) + + proposed = jnp.array([10.0, 3.0]) + assert jnp.array_equal(loss.dofs_to_pytree(proposed)["x"], jnp.array([1.0])) + assert jnp.array_equal(loss.grad(proposed), jnp.array([0.0, 6.0])) + + +def test_freeze_current_selects_one_base_coil_current(): + curves = Curves(jnp.zeros((2, 3, 3)), n_segments=10, nfp=1, stellsym=False) + field = BiotSavart(Coils(curves, currents=jnp.array([1.0, 2.0]))) + loss = custom_loss(lambda field: jnp.sum(field.coils.dofs_currents**2), "field") + loss.dependencies = {"field": field} + loss.freeze_current("field", coil=0) + + proposed = loss.starting_dofs + 1.0 + optimized = loss.dofs_to_pytree(proposed)["field"] + assert optimized.coils.dofs_currents[0] == field.coils.dofs_currents[0] + assert optimized.coils.dofs_currents[1] == field.coils.dofs_currents[1] + 1.0 + + +def test_freeze_coil_and_curve_dofs_select_geometry_leaves(): + initial_dofs = jnp.arange(18.0).reshape(2, 3, 3) + field = BiotSavart(Coils(Curves(initial_dofs, n_segments=10, nfp=1, stellsym=False), currents=jnp.ones(2))) + loss = custom_loss(lambda field: jnp.sum(field.coils.dofs_curves**2), "field") + loss.dependencies = {"field": field} + loss.freeze_coil("field", coil=0) + loss.freeze_curve_dofs("field", coil=1, coordinates="z", modes=1) + + optimized = loss.dofs_to_pytree(loss.starting_dofs + 1.0)["field"] + assert jnp.array_equal(optimized.coils.dofs_curves[0], field.coils.dofs_curves[0]) + assert optimized.coils.dofs_curves[1, 2, 1] == field.coils.dofs_curves[1, 2, 1] + assert optimized.coils.dofs_curves[1, 0, 0] != field.coils.dofs_curves[1, 0, 0] + + +def test_freeze_surface_modes_selects_rc_and_zs_coefficients(): + surface = SurfaceRZFourier( + rc=jnp.array([10.0, 1.0]), zs=jnp.array([0.0, 2.0]), + nfp=1, mpol=1, ntor=0, + ) + loss = custom_loss(lambda surface: jnp.sum(surface.rc**2) + jnp.sum(surface.zs**2), "surface") + loss.dependencies = {"surface": surface} + loss.freeze_surface_modes("surface", rc=[(1, 0)], zs=[(1, 0)]) + + proposed = loss.starting_dofs + 1.0 + optimized = loss.dofs_to_pytree(proposed)["surface"] + assert optimized.rc[1] == surface.rc[1] + assert optimized.zs[1] == surface.zs[1] + + @pytest.mark.xfail(reason='test_build_available_inputs uses the old optimizer loss API (x, dofs_curves=, currents_scale=); BdotN_over_B now lives in essos.surfaces with signature (surface, field). Needs rewrite to new API.', strict=False) def test_build_available_inputs( vmec=mock_vmec(), dummy_loss_fn=dummy_loss_fn): optimizer = MultiObjectiveOptimizer(