diff --git a/README.md b/README.md index 0221fbb1..4a2089d2 100644 --- a/README.md +++ b/README.md @@ -64,22 +64,22 @@ curvature. Losses compose with `+`, and `L.grad` is the exact gradient. ![Coils fitted to a QA boundary](docs/readme_coil_optimization.png) ```python -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart -from essos.losses import custom_loss -from essos.surfaces import BdotN_over_B, SurfaceRZFourier +from essos.losses import CustomLoss +from essos.surfaces import bdotn_over_b, SurfaceRZFourier from scipy.optimize import least_squares surface = SurfaceRZFourier.from_wout_file("wout.nc", s=1, ntheta=30, nphi=30, range_torus="half period") -coils = Coils(curves=CreateEquallySpacedCurves(3, 3, 10.0, 5.6, n_segments=45, +coils = Coils(curves=create_equally_spaced_curves(3, 3, 10.0, 5.6, n_segments=45, nfp=2, stellsym=True), currents=[1.0] * 3) -L = (custom_loss(lambda field, surface: abs(BdotN_over_B(surface, field)).sum(), +L = (CustomLoss(lambda field, surface: abs(bdotn_over_b(surface, field)).sum(), "field", surface=surface) - + custom_loss(lambda field: (field.coils.length - 32.0).clip(0).mean(), "field") - + custom_loss(lambda field: (field.coils.curvature - 0.1).clip(0).mean(), "field")) + + CustomLoss(lambda field: (field.coils.length - 32.0).clip(0).mean(), "field") + + CustomLoss(lambda field: (field.coils.curvature - 0.1).clip(0).mean(), "field")) L.dependencies = {"field": BiotSavart(coils)} result = least_squares(L, L.starting_dofs, L.grad, max_nfev=400) @@ -102,7 +102,7 @@ field = BiotSavart(Coils.from_json("coils.json")) R0 = jnp.linspace(1.21, 1.40, 8) seeds = jnp.array([R0, jnp.zeros_like(R0), jnp.zeros_like(R0)]).T -tracing = Tracing(field=field, model="FieldLineAdaptative", initial_conditions=seeds, +tracing = Tracing(field=field, model="FieldLineAdaptive", initial_conditions=seeds, tmax=8000, n_save=40000, atol=1e-8, rtol=1e-8) tracing.poincare_plot(shifts=[0.0]) ``` @@ -132,7 +132,7 @@ from essos.dynamics import Particles, Tracing particles = Particles(initial_xyz=seeds, mass=ALPHA_PARTICLE_MASS, charge=ALPHA_PARTICLE_CHARGE, energy=4000 * ONE_EV) -tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, +tracing = Tracing(field=field, model="GuidingCenterAdaptive", particles=particles, tmax=1e-4, n_save=800, atol=1e-7, rtol=1e-7) tracing.plot() print(tracing.loss_fractions) @@ -155,7 +155,7 @@ with a wall 3 cm outside the LCFS. ```python vmec = vmex.essos_vmec_field(wout) # or Vmec("wout_*.nc") outside = vmex.VmecExtender.from_wout(wout, external_field=coil_grid) -tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, +tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=4e-5, exterior_field=outside, wall=0.03) # gap [m] or a surface print(tracing.wall_hits.mean(), tracing.wall_positions[tracing.wall_hits]) ``` @@ -266,17 +266,17 @@ the `wout` directly and DESC fits it. ± is the binomial standard error. off outside the LCFS. Supplying `stopping_criteria` replaces these events; it is evaluated on `(s, theta, phi, ...)`. See [`examples/particle_tracing/trace_particles_vmec_to_wall.py`](examples/particle_tracing/trace_particles_vmec_to_wall.py). -- **Stopping coil-field traces.** Pass `stopping_criteria=LevelsetStoppingCriterion(...)` - to end Cartesian traces once they leave a prescribed distance from a surface, - and read the per-line mask from `tracing.boundary_hits`. +- **Stopping coil-field traces.** Pass `stopping_criteria` (a level-set callable or + `LevelsetStoppingCriterion(...)`, positive inside) to end a trace at the + boundary and read the per-line mask from `tracing.boundary_hits`. - **Step budget and defaults.** `max_steps` (default 16 times the steps of a fixed-step solve) bounds every Diffrax solve and a `RuntimeWarning` reports orbits that did not finish. `timestep` defaults to 1/400 of the transit time `R0 / v` (1/100 on a VMEC field), `rtol` to `1e-8` and `atol` to `rtol`. - **Progress bars** are off by default; pass `progress=True` when interactive. With `particle_batch_size=n` particles are traced `n` at a time and the bar counts completed particles (batches are bypassed under `jax.jit`/`grad`). -- **Model choice.** `FieldLineArclength` traces a fixed physical length so - rescaling `B` does not change the run; `FieldLineToroidal` sets coverage +- **Model choice.** `field_line_arclength` traces a fixed physical length so + rescaling `B` does not change the run; `field_line_toroidal` sets coverage directly in toroidal angle for flux-coordinate fields. ## Optional: near-axis fields @@ -304,7 +304,6 @@ These renames are breaking and have no aliases. Tracing options are keyword-only | `optimize_loss_function(maximum_function_evaluations=...)`, `MultiObjectiveOptimizer` option of the same name | `max_nfev` | | `optimize_loss_function(tolerance_optimization=...)`, `MultiObjectiveOptimizer` option of the same name | `tol` | | `loss_BdotN`, `loss_BdotN_constraint` | `loss_bdotn`, `loss_bdotn_constraint` | -| `Tracing(condition=...)` | `stopping_criteria` (one callable or a list) | `max_steps` was already the step-cap name and is unchanged; the loss functions now accept it too. @@ -327,6 +326,29 @@ These renames are breaking and have no aliases. Tracing options are keyword-only pytest ``` +## API changes: names + +The PEP 8 renames below are breaking; update calls as shown. + +| Old | New | +| --- | --- | +| `Electric_field_flux` | `ElectricFieldFlux` | +| `Electric_field_zero` | `ElectricFieldZero` | +| `BackgroundSpecies.species_indeces` | `BackgroundSpecies.species_indices` | +| `ALM_model_lbfgs` | `alm_model_lbfgs` | +| `ALM_model_jaxopt_lbfgsb` (alias) | `alm_model_lbfgs` | +| `CreateEquallySpacedCurves`, `RotatedCurve` | `create_equally_spaced_curves`, `rotated_curve` | +| `BdotN`, `BdotN_over_B`, `B_on_surface`, `SquaredFlux` | `bdotn`, `bdotn_over_b`, `b_on_surface`, `squared_flux` | +| `loss_B_difference_coils_near_axis`, `loss_gradB_difference_coils_near_axis`, `loss_particle_Br` | `loss_b_difference_coils_near_axis`, `loss_gradb_difference_coils_near_axis`, `loss_particle_br` | +| `normB_axis`, `loss_normB_axis_average` | `norm_b_axis`, `loss_norm_b_axis_average` | +| `B_regularized_singularity_term`, `B_regularized_pure` | `b_regularized_singularity_term`, `b_regularized_pure` | +| `GuidingCenter*`, `LorentzCollisions*`, `Lorentz`, `FieldLine*` vector-field functions in `essos.dynamics` | snake_case (`guiding_center`, `lorentz`, `field_line_arclength`, ...); the `model=` strings are unchanged | +| `BiotSavart_from_gamma` | `BiotSavartFromGamma` | +| `base_loss`, `custom_loss`, `composite_loss` | `BaseLoss`, `CustomLoss`, `CompositeLoss` | +| `essos.fields.near_axis` (stub that raised `ImportError`) | removed; use `pyqsc_jax.near_axis` | +| `x` property of coils and surfaces | removed; use `dofs` | +| `Coils.from_json` for files with `dofs_curves` / `dofs_currents` | files written by `Coils.to_json` only (keys `dofs_curves_raw`, `dofs_currents_raw`) | + ## License MIT, see [LICENSE](LICENSE). diff --git a/docs/make_readme_figures.py b/docs/make_readme_figures.py index ebf00c4b..7be6b40a 100644 --- a/docs/make_readme_figures.py +++ b/docs/make_readme_figures.py @@ -18,7 +18,7 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.constants import ALPHA_PARTICLE_CHARGE, ALPHA_PARTICLE_MASS, ONE_EV from essos.dynamics import Particles, Tracing from essos.fields import BiotSavart @@ -33,21 +33,21 @@ def coil_optimization() -> None: """Fit coils to a VMEC boundary: normal field, length and curvature.""" from scipy.optimize import least_squares - from essos.losses import custom_loss - from essos.surfaces import BdotN_over_B, SurfaceRZFourier + from essos.losses import CustomLoss + from essos.surfaces import bdotn_over_b, SurfaceRZFourier surface = SurfaceRZFourier.from_wout_file( str(INPUTS / "wout_LandremanPaul2021_QA_reactorScale_lowres.nc"), s=1, ntheta=30, nphi=30, range_torus="half period") - init_coils = Coils(curves=CreateEquallySpacedCurves(3, 3, 10.0, 5.6, n_segments=45, + init_coils = Coils(curves=create_equally_spaced_curves(3, 3, 10.0, 5.6, n_segments=45, nfp=2, stellsym=True), currents=[1.0] * 3) init_field = BiotSavart(init_coils) - L = (custom_loss(lambda field, surface: jnp.sum(jnp.abs(BdotN_over_B(surface, field))), + L = (CustomLoss(lambda field, surface: jnp.sum(jnp.abs(bdotn_over_b(surface, field))), "field", surface=surface) - + custom_loss(lambda field: jnp.mean(jnp.maximum(0, field.coils.length - 32.0)), "field") - + custom_loss(lambda field: jnp.mean(jnp.maximum(0, field.coils.curvature - 0.1)), "field")) + + CustomLoss(lambda field: jnp.mean(jnp.maximum(0, field.coils.length - 32.0)), "field") + + CustomLoss(lambda field: jnp.mean(jnp.maximum(0, field.coils.curvature - 0.1)), "field")) L.dependencies = {"field": init_field} before = float(L(L.starting_dofs)) @@ -76,7 +76,7 @@ def field_line_tracing() -> None: zeros = jnp.zeros_like(R0) seeds = jnp.array([R0, zeros, zeros]).T - tracing = Tracing(field=field, model="FieldLineAdaptative", initial_conditions=seeds, + tracing = Tracing(field=field, model="FieldLineAdaptive", initial_conditions=seeds, tmax=8000, n_save=40000, atol=1e-8, rtol=1e-8) fig, ax = plt.subplots(figsize=(4.4, 4.4)) @@ -97,7 +97,7 @@ def particle_tracing() -> None: mass=ALPHA_PARTICLE_MASS, charge=ALPHA_PARTICLE_CHARGE, energy=4000 * ONE_EV) - tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, + tracing = Tracing(field=field, model="GuidingCenterAdaptive", particles=particles, tmax=1e-4, n_save=800, atol=1e-7, rtol=1e-7) fig = plt.figure(figsize=(5.0, 4.0)) @@ -144,7 +144,7 @@ def wall_tracing() -> None: particles = Particles(initial_xyz=seeds, mass=PROTON_MASS, charge=ELEMENTARY_CHARGE, energy=WALL_ENERGY_EV * ONE_EV, initial_vparallel_over_v=jax.random.uniform(kv, (n,), minval=-1, maxval=1)) - tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, + tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=4e-5, timestep=1e-9, n_save=2000, atol=1e-8, rtol=1e-8, exterior_field=outside, wall=gap) diff --git a/docs/tracing.rst b/docs/tracing.rst index 29dce482..66a96250 100644 --- a/docs/tracing.rst +++ b/docs/tracing.rst @@ -13,7 +13,7 @@ fixed-step defaults; orange is the old setting and blue the current one. Adaptive or fixed ----------------- -* Use the adaptive models (``GuidingCenterAdaptative``, ``FullOrbitAdaptative``) unless a fixed step is required. Their +* Use the adaptive models (``GuidingCenterAdaptive``, ``FullOrbitAdaptive``) unless a fixed step is required. Their cost follows the tolerance and, on a coil field, they reach a given energy error about 4 times faster than a fixed step (4e-8 in 2.4 s against 9.4 s). * The fixed-step models need a step small enough for the field: on a coil field the energy error is 3e-2 at 100 steps per transit and 4e-8 at 400. A smooth VMEC field is converged from about 100. diff --git a/essos/__main__.py b/essos/__main__.py index dd1acef2..f248a800 100644 --- a/essos/__main__.py +++ b/essos/__main__.py @@ -5,7 +5,7 @@ from time import time import jax.numpy as jnp import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart from essos.dynamics import Tracing @@ -27,8 +27,8 @@ def main(cl_args=sys.argv[1:]): # Optimization parameters max_coil_length = 5.0 max_coil_curvature = 4 - order_Fourier_series_coils = 5 - number_coil_points = order_Fourier_series_coils*10 + fourier_order = 5 + number_coil_points = fourier_order*10 max_nfev = 100 number_coils_per_half_field_period = 3 tol = 1e-8 @@ -52,8 +52,8 @@ def main(cl_args=sys.argv[1:]): number_of_field_periods = nfp major_radius_coils = field.R0[0] minor_radius_coils = major_radius_coils/1.5 - curves = CreateEquallySpacedCurves(n_curves=number_coils_per_half_field_period, - order=order_Fourier_series_coils, + curves = create_equally_spaced_curves(n_curves=number_coils_per_half_field_period, + order=fourier_order, R=major_radius_coils, r=minor_radius_coils, n_segments=number_coil_points, nfp=number_of_field_periods, stellsym=True) @@ -62,7 +62,7 @@ def main(cl_args=sys.argv[1:]): # Optimize coils print(f'Optimizing coils with {max_nfev} function evaluations.') time0 = time() - coils_optimized = optimize_loss_function(loss_coils_for_nearaxis, initial_dofs=coils_initial.x, + coils_optimized = optimize_loss_function(loss_coils_for_nearaxis, initial_dofs=coils_initial.dofs, coils=coils_initial, tol=tol, max_nfev=max_nfev, field_nearaxis=field, max_coil_length=max_coil_length, max_coil_curvature=max_coil_curvature,) diff --git a/essos/augmented_lagrangian.py b/essos/augmented_lagrangian.py index 27cac2a3..7a8f1c21 100644 --- a/essos/augmented_lagrangian.py +++ b/essos/augmented_lagrangian.py @@ -42,7 +42,7 @@ class BaseConstraint: """A minimal mutable container holding `init` and `loss` callables for a constraint. This mirrors the simple tuple-like behavior used elsewhere but allows - attribute access and matches the `base_loss` style in `losses.py`. + attribute access and matches the `BaseLoss` style in `losses.py`. """ def __init__(self, init: Callable, loss: Callable): self.init = init @@ -104,7 +104,7 @@ def dofs_to_pytree(self): class SelectiveConstraint: - """Wraps a constraint with selective named dependencies, similar to custom_loss. + """Wraps a constraint with selective named dependencies, similar to CustomLoss. This allows constraints to only depend on a subset of the available degrees of freedom by name, enabling combination of constraints with different argument requirements. @@ -573,22 +573,22 @@ def penalty_average(tree): return jnp.average(penalty[0]) -def apply_mu_tolerance_per_constraint(constraint_dict, grad_dict, constraint_info, constraint_info_prev=None, model_lagrangian='Standard', model_mu='Mu_Adaptative_1', beta=2.0, mu_max=1.e4, alpha=0.99, gamma=1.e-2, epsilon=1.e-8, eta_tol=1.e-4, omega_tol=1.e-6, decrease_tol=0.75): +def apply_mu_tolerance_per_constraint(constraint_dict, grad_dict, constraint_info, constraint_info_prev=None, model_lagrangian='Standard', model_mu='MuAdaptive1', beta=2.0, mu_max=1.e4, alpha=0.99, gamma=1.e-2, epsilon=1.e-8, eta_tol=1.e-4, omega_tol=1.e-6, decrease_tol=0.75): """Apply Mu update rule for vectorized constraints. Supports three strategies: - - Mu_Tolerance: All elements updated together based on norm, uses average penalty - - Mu_Adaptative_1: Element-wise updates using eta parameter - - Mu_Adaptative_2: Element-wise updates using decrease tolerance criterion + - MuTolerance: All elements updated together based on norm, uses average penalty + - MuAdaptive1: Element-wise updates using eta parameter + - MuAdaptive2: Element-wise updates using decrease tolerance criterion Args: constraint_dict: dict with 'lambda' and optionally 'slack' keys containing LagrangeMultiplier objects grad_dict: dict with gradients matching the constraint_dict structure constraint_info: current constraint violation information (array or scalar) - constraint_info_prev: previous constraint violation info (needed for Mu_Adaptative_2) + constraint_info_prev: previous constraint violation info (needed for MuAdaptive2) model_lagrangian: 'Standard' or 'Squared' lagrangian formulation - model_mu: 'Mu_Tolerance' (global norm, avg penalty), 'Mu_Adaptative_1' (element-wise eta), or 'Mu_Adaptative_2' (element-wise decrease) - decrease_tol: tolerance for decrease criterion in Mu_Adaptative_2 (default 0.75 = 25% decrease) + model_mu: 'MuTolerance' (global norm, avg penalty), 'MuAdaptive1' (element-wise eta), or 'MuAdaptive2' (element-wise decrease) + decrease_tol: tolerance for decrease criterion in MuAdaptive2 (default 0.75 = 25% decrease) """ pred = lambda x: isinstance(x, LagrangeMultiplier) @@ -605,7 +605,7 @@ def apply_mu_tolerance_per_constraint(constraint_dict, grad_dict, constraint_inf constraint_abs = jnp.abs(constraint_info) - # Element-wise strategies (Mu_Adaptative_1 or Mu_Adaptative_2) + # Element-wise strategies (MuAdaptive1 or MuAdaptive2) # Compute updated eta and omega (element-wise) eta_updated = jnp.maximum(eta_val / jnp.power(penalty_val, 0.1), eta_tol) omega_updated = jnp.maximum(omega_val / penalty_val, omega_tol) @@ -614,11 +614,11 @@ def apply_mu_tolerance_per_constraint(constraint_dict, grad_dict, constraint_inf omega_updated_false = jnp.maximum(1.0 / penalty_val, omega_tol) # Determine if constraints are satisfied based on model_mu strategy - if model_mu == 'Mu_Adaptative_1': + if model_mu == 'MuAdaptive1': # Strategy 1: Use eta parameter - constraint satisfied if abs(constraint) < eta is_satisfied = constraint_abs < eta_val - elif model_mu == 'Mu_Adaptative_2': + elif model_mu == 'MuAdaptive2': # Strategy 2: Use decrease tolerance - constraint satisfied if abs(constraint) <= decrease_tol * abs(constraint_prev) if constraint_info_prev is None: # If no previous constraint, fall back to eta-based check @@ -628,7 +628,7 @@ def apply_mu_tolerance_per_constraint(constraint_dict, grad_dict, constraint_inf # Check if constraint decreased by specified tolerance factor is_satisfied = constraint_abs <= decrease_tol * constraint_abs_prev else: - # Default to Mu_Adaptative_1 + # Default to MuAdaptive1 is_satisfied = constraint_abs < eta_val if model_lagrangian == 'Standard': @@ -662,7 +662,7 @@ def apply_mu_tolerance_per_constraint(constraint_dict, grad_dict, constraint_inf def apply_mu_tolerance_all_constraints(constraint_dicts_map, grad_dicts_map=None, constraint_infos_map=None, model_lagrangian='Standard', beta=2.0, mu_max=1.e4, alpha=0.99, gamma=1.e-2, epsilon=1.e-8, eta_tol=1.e-4, omega_tol=1.e-6): - """Apply Mu_Tolerance across all constraints (JAX-compatible, no Python loops or dict indexing). + """Apply MuTolerance across all constraints (JAX-compatible, no Python loops or dict indexing). This mirrors the per-constraint updater but computes a single global decision using all constraint infos, then applies the same update to @@ -787,10 +787,10 @@ def to_params(z): #Inner solve with optimistix L-BFGS; bounds are enforced by reparametrization -def ALM_model_lbfgs(constraints: BaseConstraint,#List of constraints +def alm_model_lbfgs(constraints: BaseConstraint,#List of constraints loss= lambda x: 0., #function which represents the loss (Callable, default 0.) model_lagrangian='Standard', - model_mu='Mu_Tolerance', + model_mu='MuTolerance', beta=2.0, mu_max=1.e4, alpha=0.99, @@ -847,8 +847,8 @@ def update_fn(params, lag_state,grad,info,beta=beta,mu_max=mu_max,alpha=alpha,ga main_params = to_x(sol.value) grad,info = jax.grad(lagrangian,has_aux=True,argnums=(0,1))(main_params,lagrange_params,**kargs) - # Choose cross-constraint Mu_Tolerance updater or per-constraint updater - if model_mu == 'Mu_Tolerance': + # Choose cross-constraint MuTolerance updater or per-constraint updater + if model_mu == 'MuTolerance': lag_updates = apply_mu_tolerance_all_constraints( lagrange_params, grad_dicts_map=grad[1], constraint_infos_map=info[2], model_lagrangian=model_lagrangian, beta=beta, mu_max=mu_max, @@ -879,7 +879,6 @@ def update_fn(params, lag_state,grad,info,beta=beta,mu_max=mu_max,alpha=alpha,ga return ALM(init_fn,partial(update_fn,beta=beta,mu_max=mu_max,alpha=alpha,gamma=gamma,epsilon=epsilon,eta_tol=eta_tol,omega_tol=omega_tol)) -ALM_model_jaxopt_lbfgsb = ALM_model_lbfgs # former name diff --git a/essos/background_species.py b/essos/background_species.py index 4ccb831d..2bf42260 100644 --- a/essos/background_species.py +++ b/essos/background_species.py @@ -24,7 +24,7 @@ class BackgroundSpecies(): """ def __init__(self, number_species, mass_array, charge_array, n_array, T_array, radial_grid=None): self.number_species = number_species - self.species_indeces = jnp.arange(number_species) + self.species_indices = jnp.arange(number_species) self.temperature = T_array self.density = n_array self.radial_grid = None if radial_grid is None else jnp.asarray(radial_grid) diff --git a/essos/boozer.py b/essos/boozer.py index bfcdbaa7..8944ff73 100644 --- a/essos/boozer.py +++ b/essos/boozer.py @@ -268,7 +268,7 @@ def guiding_center_rhs(field, y, mu, mass, charge): def _collision_rates(species, mass, charge, v, point): - idx = species.species_indeces + idx = species.species_indices def total(nu): return jnp.sum(jax.vmap(nu, in_axes=(None, None, 0, None, None, None))( @@ -278,7 +278,7 @@ def total(nu): def collision_kick(species, mass, charge, v, pitch, point, dt, noise): - """One Ito Euler-Maruyama step of the Lorentz and energy-scattering operator. + """One Ito Euler-Maruyama step of the lorentz and energy-scattering operator. ``dv = (-nu_s v + v^-2 d(v^2 D)/dv) dt + sqrt(2 D dt) xi_1`` with ``D = v^2 nu_par / 2``, and ``dlambda = -lambda nu_D dt + diff --git a/essos/coils.py b/essos/coils.py index cf12f059..2016f15b 100644 --- a/essos/coils.py +++ b/essos/coils.py @@ -702,16 +702,6 @@ def with_dofs(self, dofs): coils.dofs = dofs return coils - # TODO: remove x property. This is a placeholder for compatibility with the examples that need to be updated. - # x property and setter - @property - def x(self): - return self.dofs - - @x.setter - def x(self, new_dofs): - self.dofs = new_dofs - # currents property @property def currents(self): @@ -878,7 +868,7 @@ def to_json(self, filename: str): "scale_fixed": float(self.curves.scale_fixed), # Save RAW unscaled currents "dofs_currents_raw": jnp.asarray(self._dofs_currents_raw).tolist(), - # Save current scale if computed (optional for backward compat) + # Save current scale if computed "currents_scale": float(self.currents_scale) if self._currents_scale is not None else None, } import json @@ -933,51 +923,20 @@ def from_simsopt(cls, simsopt_coils, nfp=1, stellsym=True, scaling_type=2, scali @classmethod def from_json(cls, filename: str): - """Load coils from JSON with proper scaling metadata. - - Supports both new format (with raw DOFs and scaling) and legacy format - (with scaled DOFs) for backward compatibility. The scaling metadata - includes ``scaling_type``, ``scaling_factor``, and ``scale_fixed``. - """ + """Load coils written by :meth:`to_json`: raw DOFs and scaling metadata.""" import json with open(filename, "r") as file: data = json.load(file) - - # Extract scaling metadata (with defaults for legacy files) - scaling_type = data.get("scaling_type", 2) - scaling_factor = data.get("scaling_factor", 0.0) - scale_fixed = data.get("scale_fixed", 1.0) - - # Check if using NEW format (raw DOFs) or LEGACY format (scaled DOFs) - if "dofs_curves_raw" in data: - # NEW FORMAT: Raw unscaled DOFs with full metadata - curves = Curves( - jnp.array(data["dofs_curves_raw"]), # Raw _dofs - data["n_segments"], - data["nfp"], - data["stellsym"], - scaling_type, - scaling_factor, - scale_fixed - ) - currents_raw = jnp.array(data["dofs_currents_raw"]) - else: - # LEGACY FORMAT: Assume "dofs_curves" are raw DOFs (old behavior) - # This maintains backward compatibility with old JSON files - curves = Curves( - jnp.array(data["dofs_curves"]), # Treat as raw for legacy - data["n_segments"], - data["nfp"], - data["stellsym"], - scaling_type, - scaling_factor, - scale_fixed - ) - # Legacy files may have scaled or raw currents - treat as raw - currents_raw = jnp.array(data["dofs_currents"]) - - # Create Coils object with raw currents - return cls(curves, currents_raw, currents_scale=data.get("currents_scale", None)) + curves = Curves( + jnp.array(data["dofs_curves_raw"]), + data["n_segments"], + data["nfp"], + data["stellsym"], + data["scaling_type"], + data["scaling_factor"], + data["scale_fixed"], + ) + return cls(curves, jnp.array(data["dofs_currents_raw"]), currents_scale=data.get("currents_scale", None)) def _tree_flatten(self): children = (self.curves, self.dofs_currents) # arrays / dynamic values @@ -998,7 +957,7 @@ def _tree_unflatten(cls, aux_data, children): Coils._tree_unflatten) -def CreateEquallySpacedCurves(n_curves: int, +def create_equally_spaced_curves(n_curves: int, order: int, R: float, r: float, @@ -1035,7 +994,7 @@ def CreateEquallySpacedCurves(n_curves: int, @partial(jit, static_argnames=["flip"]) -def RotatedCurve(curve, phi, flip): +def rotated_curve(curve, phi, flip): rotmat_T = jnp.array( [[ jnp.cos(phi), jnp.sin(phi), 0], [-jnp.sin(phi), jnp.cos(phi), 0], @@ -1051,7 +1010,7 @@ def apply_symmetries_to_curves(base_curves, nfp, stellsym): for k in range(0, nfp): for flip in flip_list: for i in range(len(base_curves)): - rotcurve = RotatedCurve(base_curves[i].T, 2*jnp.pi*k/nfp, flip) + rotcurve = rotated_curve(base_curves[i].T, 2*jnp.pi*k/nfp, flip) curves.append(rotcurve.T) return jnp.array(curves) @@ -1065,7 +1024,7 @@ def apply_symmetries_to_gammas(base_gammas, nfp, stellsym): if k == 0 and not flip: gammas.append(base_gammas[i]) else: - rotcurve = RotatedCurve(base_gammas[i], 2*jnp.pi*k/nfp, flip) + rotcurve = rotated_curve(base_gammas[i], 2*jnp.pi*k/nfp, flip) gammas.append(rotcurve) return jnp.array(gammas) @@ -1396,15 +1355,6 @@ def dofs(self, new_dofs): self.dofs_gamma = jnp.reshape(new_dofs[:n_gamma_dofs], self.dofs_gamma.shape) self.dofs_currents = new_dofs[n_gamma_dofs:] - # x property and setter (for compatibility with simsopt) - @property - def x(self): - return self.dofs - - @x.setter - def x(self, new_dofs): - self.dofs = new_dofs - # Compute derivatives using finite differences (circular) def _compute_gamma_dash(self): """Compute first derivative using finite differences on periodic curve""" diff --git a/essos/dynamics.py b/essos/dynamics.py index 8162f868..a03e4616 100644 --- a/essos/dynamics.py +++ b/essos/dynamics.py @@ -29,7 +29,7 @@ from essos.coils import Coils from essos.fields import BiotSavart, ExternalField, MagneticField, Vmec from essos.surfaces import SurfaceClassifier, SurfaceRZFourier -from essos.electric_field import Electric_field_flux, Electric_field_zero +from essos.electric_field import ElectricFieldFlux, ElectricFieldZero from essos.constants import ALPHA_PARTICLE_MASS, ALPHA_PARTICLE_CHARGE, FUSION_ALPHA_PARTICLE_ENERGY,ELEMENTARY_CHARGE,SPEED_OF_LIGHT from essos.plot import fix_matplotlib_3d from essos.background_species import nu_s_ab,nu_D_ab,nu_par_ab, d_nu_par_ab,d_nu_D_ab @@ -309,9 +309,9 @@ def _mu_collision_noise(vpar, mu, points, field, particles, species): m, q, B = particles.mass, particles.charge, field.AbsB(points) v = jnp.sqrt(vpar**2 + 2.*mu*B/m) xi = vpar/v - indeces_species = species.species_indeces - nu_D = jnp.sum(jax.vmap(nu_D_ab, in_axes=(None, None, 0, None, None, None))(m, q, indeces_species, v, points, species), axis=0) - nu_par = jnp.sum(jax.vmap(nu_par_ab, in_axes=(None, None, 0, None, None, None))(m, q, indeces_species, v, points, species), axis=0) + indices_species = species.species_indices + nu_D = jnp.sum(jax.vmap(nu_D_ab, in_axes=(None, None, 0, None, None, None))(m, q, indices_species, v, points, species), axis=0) + nu_par = jnp.sum(jax.vmap(nu_par_ab, in_axes=(None, None, 0, None, None, None))(m, q, indices_species, v, points, species), axis=0) def factor(_): # Velocity-space diffusion of (vpar/v, mu/(m v^2/2B)), divided by v^2 Yvv = (nu_par*xi**2+nu_D*(1.-xi**2))/2. @@ -333,7 +333,7 @@ def factor(_): lambda _: jnp.zeros((2, 2), dtype=v.dtype), factor, None) @partial(jit, static_argnums=(2)) -def GuidingCenterCollisionsDiffusionMu(t, +def guiding_center_collisions_diffusion_mu(t, initial_condition, args) -> jnp.ndarray: x, y, z, vpar,mu = initial_condition @@ -357,7 +357,7 @@ def GuidingCenterCollisionsDiffusionMu(t, @partial(jit, static_argnums=(2)) -def GuidingCenterCollisionsDriftMuStratonovich(t, +def guiding_center_collisions_drift_mu_stratonovich(t, initial_condition, args) -> jnp.ndarray: x, y, z,vpar,mu = initial_condition @@ -377,12 +377,12 @@ def GuidingCenterCollisionsDriftMuStratonovich(t, Bstar=field.B_contravariant(points)+vpar*m/q*field.curl_b(points)#+m/q*flow.curl_U0(points) Ustar=vpar*field.B_contravariant(points)/field.AbsB(points)#+flow.U0(points) F_gc=mu*field.dAbsB_by_dX(points)+m*vpar**2*field.kappa(points)-q*electric_field.E_covariant(points)#+vpar*flow.coriolis(points)+flow.centrifugal(points) - indeces_species=species.species_indeces - nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - dnu_par_dv=jnp.sum(jax.vmap(d_nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - dnu_D_dv=jnp.sum(jax.vmap(d_nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) + indices_species=species.species_indices + nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + dnu_par_dv=jnp.sum(jax.vmap(d_nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + dnu_D_dv=jnp.sum(jax.vmap(d_nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) Diffusion_par=p**2*nu_par/2. Diffusion_perp=p**2*nu_D/2. d_Diffusion_par_dp=p*nu_par+p**2*dnu_par_dv/(2.*m) @@ -420,7 +420,7 @@ def GuidingCenterCollisionsDriftMuStratonovich(t, @partial(jit, static_argnums=(2)) -def GuidingCenterCollisionsDriftMuIto(t, +def guiding_center_collisions_drift_mu_ito(t, initial_condition, args) -> jnp.ndarray: x, y, z,vpar,mu = initial_condition @@ -437,12 +437,12 @@ def GuidingCenterCollisionsDriftMuIto(t, Bstar=field.B_contravariant(points)+vpar*m/q*field.curl_b(points)#+m/q*flow.curl_U0(points) Ustar=vpar*field.B_contravariant(points)/field.AbsB(points)#+flow.U0(points) F_gc=mu*field.dAbsB_by_dX(points)+m*vpar**2*field.kappa(points)-q*electric_field.E_covariant(points)#+vpar*flow.coriolis(points)+flow.centrifugal(points) - indeces_species=species.species_indeces - nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - dnu_par_dv=jnp.sum(jax.vmap(d_nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - dnu_D_dv=jnp.sum(jax.vmap(d_nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) + indices_species=species.species_indices + nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + dnu_par_dv=jnp.sum(jax.vmap(d_nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + dnu_D_dv=jnp.sum(jax.vmap(d_nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) Diffusion_par=p**2*nu_par/2. Diffusion_perp=p**2*nu_D/2. d_Diffusion_par_dp=p*nu_par+p**2*dnu_par_dv/(2.*m) @@ -465,7 +465,7 @@ def GuidingCenterCollisionsDriftMuIto(t, return jnp.append(dxdt,jnp.append(dvpardt,dmudt)) @partial(jit, static_argnums=(2)) -def GuidingCenterCollisionsDiffusion(t, +def guiding_center_collisions_diffusion(t, initial_condition, args) -> jnp.ndarray: x, y, z, v,xi = initial_condition @@ -476,9 +476,9 @@ def GuidingCenterCollisionsDiffusion(t, points = jnp.array([x, y, z]) I_bb_tensor=jnp.identity(3)-jnp.diag(jnp.multiply(field.B_contravariant(points),jnp.reshape(field.B_contravariant(points),(3,1))))/field.AbsB(points)**2 p=m*v - indeces_species=species.species_indeces - nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) + indices_species=species.species_indices + nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) Diffusion_par=p**2/2.*nu_par Diffusion_perp=p**2/2.*nu_D Diffusion_x=0.0#((Diffusion_par-Diffusion_perp)*(1.-xi**2)/2.+Diffusion_perp)/(m*omega_mod)**2 @@ -492,7 +492,7 @@ def GuidingCenterCollisionsDiffusion(t, return jnp.append(jnp.append(dxdt,Dxv,axis=0),jnp.append(Dvx,jnp.diag(jnp.append(dvdt,dxidt)),axis=0),axis=1) @partial(jit, static_argnums=(2)) -def GuidingCenterCollisionsDrift(t, +def guiding_center_collisions_drift(t, initial_condition, args) -> jnp.ndarray: x, y, z, v,xi = initial_condition @@ -508,11 +508,11 @@ def GuidingCenterCollisionsDrift(t, Bstar=field.B_contravariant(points)+vpar*m/q*field.curl_b(points)#+m/q*flow.curl_U0(points) Ustar=vpar*field.B_contravariant(points)/field.AbsB(points)#+flow.U0(points) F_gc=mu*field.dAbsB_by_dX(points)+m*vpar**2*field.kappa(points)-q*electric_field.E_covariant(points)#+vpar*flow.coriolis(points)+flow.centrifugal(points) - indeces_species=species.species_indeces - nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - dnu_par=jnp.sum(jax.vmap(d_nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) + indices_species=species.species_indices + nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + dnu_par=jnp.sum(jax.vmap(d_nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) Diffusion_par=p**2/2.*nu_par Diffusion_perp=p**2/2.*nu_D d_Diffusion_par_dp=p*nu_par+p**2/2.*dnu_par/m @@ -555,7 +555,7 @@ def _guiding_center_velocity(field, electric_field, q, m, points, vpar, mu=None, @partial(jit, static_argnums=(2)) -def GuidingCenter(t, +def guiding_center(t, initial_condition, args) -> jnp.ndarray: x, y, z, vpar = initial_condition @@ -566,7 +566,7 @@ def GuidingCenter(t, @partial(jit, static_argnums=(2)) -def GuidingCenterMu(t, initial_condition, args) -> jnp.ndarray: +def guiding_center_mu(t, initial_condition, args) -> jnp.ndarray: """Collisionless guiding center with state (x, y, z, v_par, mu); mu is constant.""" field, particles, electric_field = args dxdt, dvdt = _guiding_center_velocity(field, electric_field, particles.charge, particles.mass, @@ -578,7 +578,7 @@ def GuidingCenterMu(t, initial_condition, args) -> jnp.ndarray: @partial(jit, static_argnums=(2)) -def LorentzCollisionsDiffusion(t, +def lorentz_collisions_diffusion(t, initial_condition, args) -> jnp.ndarray: x, y, z, vx, vy, vz = initial_condition @@ -593,9 +593,9 @@ def LorentzCollisionsDiffusion(t, v=jnp.sqrt(vx**2+vy**2+vz**2) p=m*v P_v=jnp.outer(v_vector,v_vector)/v**2 # projector on the velocity direction - indeces_species=species.species_indeces - nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) - nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) + indices_species=species.species_indices + nu_D=jnp.sum(jax.vmap(nu_D_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) + nu_par=jnp.sum(jax.vmap(nu_par_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) Diffusion_par=p**2/2.*nu_par Diffusion_perp=p**2/2.*nu_D Dpar=jnp.sqrt(2.*Diffusion_par)#*0.0000 @@ -608,7 +608,7 @@ def LorentzCollisionsDiffusion(t, return jnp.append(jnp.append(dxdt,Dxv,axis=0),jnp.append(Dvx,dvdt,axis=0),axis=1) @partial(jit, static_argnums=(2)) -def LorentzCollisionsDrift(t, +def lorentz_collisions_drift(t, initial_condition, args) -> jnp.ndarray: x, y, z, vx, vy, vz = initial_condition @@ -620,15 +620,15 @@ def LorentzCollisionsDrift(t, # def dxdt_dvdt(_): points = jnp.array([x, y, z]) B_contravariant = field.B_contravariant(points) - indeces_species=species.species_indeces - nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indeces_species,v, points,species),axis=0) + indices_species=species.species_indices + nu_s=jnp.sum(jax.vmap(nu_s_ab,in_axes=(None,None,0,None,None,None))(m, q,indices_species,v, points,species),axis=0) dxdt = jnp.array([vx, vy, vz]) # Noise-induced drift. The Fokker-Planck operator d_i(nu_s v_i f + D_ij d_j f), # D = sigma sigma^T / 2, has Ito drift -nu_s v + d_j D_ij; the Stratonovich # solver (SPaRK) needs that minus sigma_jk d_j sigma_ik / 2, i.e. # -nu_s v + sigma_ik d_j sigma_jk / 2. def sigma(velocity): - return LorentzCollisionsDiffusion(t, jnp.append(points, velocity), args)[3:, 3:] + return lorentz_collisions_diffusion(t, jnp.append(points, velocity), args)[3:, 3:] noise_drift = 0.5*jnp.einsum('ik,jkj->i', sigma(dxdt), jax.jacfwd(sigma)(dxdt)) dvdt = q / m * jnp.cross(dxdt, B_contravariant)-nu_s*dxdt+noise_drift return jnp.append(dxdt, dvdt) @@ -641,7 +641,7 @@ def sigma(velocity): @partial(jit, static_argnums=(2)) -def Lorentz(t, +def lorentz(t, initial_condition, args) -> jnp.ndarray: x, y, z, vx, vy, vz = initial_condition @@ -660,7 +660,7 @@ def Lorentz(t, # return lax.cond(condition, zero_derivatives, dxdt_dvdt, operand=None) @partial(jit, static_argnums=(2)) -def FieldLine(t, +def field_line(t, initial_condition, field) -> jnp.ndarray: x, y, z = initial_condition @@ -676,7 +676,7 @@ def FieldLine(t, @partial(jit, static_argnums=(2)) -def FieldLineArclength(t, initial_condition, field) -> jnp.ndarray: +def field_line_arclength(t, initial_condition, field) -> jnp.ndarray: """Trace the same field line with physical arclength as the parameter.""" del t B = field.B_contravariant(initial_condition) @@ -684,7 +684,7 @@ def FieldLineArclength(t, initial_condition, field) -> jnp.ndarray: @partial(jit, static_argnums=(2)) -def FieldLineToroidal(t, initial_condition, field) -> jnp.ndarray: +def field_line_toroidal(t, initial_condition, field) -> jnp.ndarray: """Trace a flux-coordinate field with toroidal angle as the parameter.""" del t B = field.B_contravariant(initial_condition) @@ -715,11 +715,11 @@ def fill_state(carry, current): _VMEC_GUIDING_CENTER_MODELS = frozenset( { "GuidingCenter", - "GuidingCenterAdaptative", + "GuidingCenterAdaptive", "GuidingCenterCollisions", "GuidingCenterCollisionsMuIto", "GuidingCenterCollisionsMuFixed", - "GuidingCenterCollisionsMuAdaptative", + "GuidingCenterCollisionsMuAdaptive", } ) @@ -728,7 +728,7 @@ def fill_state(carry, current): "GuidingCenterCollisions", "GuidingCenterCollisionsMuIto", "GuidingCenterCollisionsMuFixed", - "GuidingCenterCollisionsMuAdaptative", + "GuidingCenterCollisionsMuAdaptive", } ) @@ -899,18 +899,18 @@ def _keep_energy(vpar, mu, E, B, m): # Drift, diffusion, solver and noise dimension of the stochastic models. _SDE_MODELS = { - 'GuidingCenterCollisions': (GuidingCenterCollisionsDrift, GuidingCenterCollisionsDiffusion, + 'GuidingCenterCollisions': (guiding_center_collisions_drift, guiding_center_collisions_diffusion, diffrax.StratonovichMilstein, 5), - 'GuidingCenterCollisionsMuFixed': (GuidingCenterCollisionsDriftMuStratonovich, GuidingCenterCollisionsDiffusionMu, + 'GuidingCenterCollisionsMuFixed': (guiding_center_collisions_drift_mu_stratonovich, guiding_center_collisions_diffusion_mu, diffrax.StratonovichMilstein, 5), - 'GuidingCenterCollisionsMuIto': (GuidingCenterCollisionsDriftMuIto, GuidingCenterCollisionsDiffusionMu, + 'GuidingCenterCollisionsMuIto': (guiding_center_collisions_drift_mu_ito, guiding_center_collisions_diffusion_mu, diffrax.ItoMilstein, 5), - 'GuidingCenterCollisionsMuAdaptative': (GuidingCenterCollisionsDriftMuStratonovich, - GuidingCenterCollisionsDiffusionMu, diffrax.SPaRK, 5), - 'FullOrbitCollisions': (LorentzCollisionsDrift, LorentzCollisionsDiffusion, diffrax.SPaRK, 6), + 'GuidingCenterCollisionsMuAdaptive': (guiding_center_collisions_drift_mu_stratonovich, + guiding_center_collisions_diffusion_mu, diffrax.SPaRK, 5), + 'FullOrbitCollisions': (lorentz_collisions_drift, lorentz_collisions_diffusion, diffrax.SPaRK, 6), } -_ADAPTIVE_MODELS = ('GuidingCenterAdaptative', 'FullOrbitAdaptative', 'FullOrbitCollisions', - 'FieldLineAdaptative', 'FieldLineArclength', 'FieldLineToroidal') +_ADAPTIVE_MODELS = ('GuidingCenterAdaptive', 'FullOrbitAdaptive', 'FullOrbitCollisions', + 'FieldLineAdaptive', 'FieldLineArcLength', 'FieldLineToroidal') class LevelsetStoppingCriterion: @@ -1062,13 +1062,12 @@ def _batch_solver(tracing, place): class Tracing(): def __init__(self, field=None, particles=None, initial_conditions=None, *, trajectories_input=None, electric_field=None, model=None, tmax: float = 1e-7, timestep: float | None = None, - n_save=None, rtol=1.e-8, atol=None, condition=None, species=None, tag_gc=1., boundary=None, + n_save=None, rtol=1.e-8, atol=None, species=None, tag_gc=1., boundary=None, rejected_steps=None, solver=None, stopping_criteria=None, progress=True, devices=None, max_steps=None, exterior_field=None, wall=None, max_returns=16, reentry_depth=None, particle_batch_size=None, adjoint=None): - if condition is not None and stopping_criteria is not None: - raise ValueError("Pass condition or stopping_criteria, not both") + event = None if stopping_criteria is not None: if callable(stopping_criteria): stopping_criteria = (stopping_criteria,) @@ -1076,14 +1075,14 @@ def __init__(self, field=None, particles=None, initial_conditions=None, *, traje stopping_criteria = tuple(stopping_criteria) if not stopping_criteria or not all(callable(item) for item in stopping_criteria): raise ValueError("stopping_criteria must contain callable criteria") - condition = stopping_criteria[0] if len(stopping_criteria) == 1 else stopping_criteria + event = stopping_criteria[0] if len(stopping_criteria) == 1 else stopping_criteria self.stopping_criteria = stopping_criteria self.devices = tuple(jax.devices() if devices is None else devices) if not self.devices: raise ValueError("devices must contain at least one JAX device") if electric_field==None: - self.electric_field = Electric_field_zero() + self.electric_field = ElectricFieldZero() else: self.electric_field=electric_field @@ -1108,7 +1107,7 @@ def __init__(self, field=None, particles=None, initial_conditions=None, *, traje if particles is None: timestep = tmax / 100 elif any(isinstance(x, jax.core.Tracer) for x in scales): - if model not in ('GuidingCenterAdaptative', 'FullOrbitAdaptative'): + if model not in ('GuidingCenterAdaptive', 'FullOrbitAdaptive'): raise ValueError("timestep=None needs the axis radius and particle speed as concrete values; " "they are traced here, so pass an explicit timestep") timestep = tmax / 100 # only the first trial step of an adaptive solve, which cannot size max_steps @@ -1129,9 +1128,9 @@ def __init__(self, field=None, particles=None, initial_conditions=None, *, traje # Without a user condition, VMEC guiding centers stop at the exact LCFS # crossing, report non-finite steps, and continue outside in # exterior_field up to the wall when one is given; see _vmec_orbit. - self._vmec_default = self._axis_regular and condition is None + self._vmec_default = self._axis_regular and event is None if (exterior_field is not None or wall is not None) and not self._vmec_default: - raise ValueError("exterior_field and wall need a VMEC field, a guiding-center model and no condition") + raise ValueError("exterior_field and wall need a VMEC field, a guiding-center model and no stopping_criteria") if wall is not None and exterior_field is None: raise ValueError("a wall needs an exterior_field to trace the orbits outside the LCFS") if isinstance(exterior_field, Coils): @@ -1175,11 +1174,11 @@ def __init__(self, field=None, particles=None, initial_conditions=None, *, traje # attribute, so it is resolved at trace time and does not affect # differentiability of the traced trajectories. self.solver = solver - if condition is None: - self.condition = _never + if event is None: + self.event = _never if isinstance(field, Vmec): - if model in ('FieldLine', 'FieldLineAdaptative', 'FieldLineArclength', 'FieldLineToroidal'): - self.condition = _vmec_edge + if model in ('FieldLine', 'FieldLineAdaptive', 'FieldLineArcLength', 'FieldLineToroidal'): + self.event = _vmec_edge elif (isinstance(field, Coils) or isinstance(self.field, BiotSavart)) and isinstance(boundary,SurfaceClassifier): if model in _GUIDING_CENTER_COLLISION_MODELS: def condition_BioSavart(t, y, args, **kwargs): @@ -1189,15 +1188,15 @@ def condition_BioSavart(t, y, args, **kwargs): def condition_BioSavart(t, y, args, **kwargs): xx, yy, zz, _ = y return boundary.evaluate_xyz(jnp.array([xx,yy,zz]))#<0. - self.condition = condition_BioSavart + self.event = condition_BioSavart elif self._axis_regular: - self.condition = tree_util.tree_map( + self.event = tree_util.tree_map( lambda c: lambda t, y, args, **kwargs: c(t, _from_axis_regular(y), args, **kwargs), - condition) + event) else: - self.condition = condition - if model == 'GuidingCenter' or model=='GuidingCenterAdaptative': - self.ODE_term = ODETerm(self._vector_field(GuidingCenter)) + self.event = event + if model == 'GuidingCenter' or model=='GuidingCenterAdaptive': + self.ode_term = ODETerm(self._vector_field(guiding_center)) self.args = (self.field, self.particles,self.electric_field) self.initial_conditions = jnp.concatenate([self.particles.initial_xyz, self.particles.initial_vparallel[:, None]], axis=1) elif model == 'GuidingCenterCollisions': @@ -1207,25 +1206,23 @@ def condition_BioSavart(t, y, args, **kwargs): #tol=self.tmax / self.timesteps*0.5 #print('tol: ', tol) #bm = diffrax.VirtualBrownianTree(t0, t1, tol=tol, shape=(5,), key=jax.random.key(0), levy_area=diffrax.SpaceTimeTimeLevyArea) - #self.ODE_term = MultiTerm(ODETerm(GuidingCenterCollisionsDrift),ControlTerm(GuidingCenterCollisionsDiffusion, bm)) self.args = (self.field, self.particles,self.electric_field,self.species,self.tag_gc) total_speed_temp=self.particles.total_speed*jnp.ones(self.particles.nparticles) self.initial_conditions = jnp.concatenate([self.particles.initial_xyz,total_speed_temp[:, None], self.particles.initial_vparallel_over_v[:, None]], axis=1) - elif model == 'GuidingCenterCollisionsMuIto' or model == 'GuidingCenterCollisionsMuFixed' or model == 'GuidingCenterCollisionsMuAdaptative': + elif model == 'GuidingCenterCollisionsMuIto' or model == 'GuidingCenterCollisionsMuFixed' or model == 'GuidingCenterCollisionsMuAdaptive': # Brownian motion #t0=0.0 #t1=self.tmax #tol=self.tmax / self.timesteps*0.5 #print('tol: ', tol) #bm = diffrax.VirtualBrownianTree(t0, t1, tol=tol, shape=(5,), key=jax.random.key(0), levy_area=diffrax.SpaceTimeTimeLevyArea) - #self.ODE_term = MultiTerm(ODETerm(GuidingCenterCollisionsDriftMu),ControlTerm(GuidingCenterCollisionsDiffusionMu, bm)) self.args = (self.field, self.particles,self.electric_field,self.species,self.tag_gc) #x,y,z=self.particles.initial_xyz[] B_particle=jax.vmap(self.field.AbsB,in_axes=0)(self.particles.initial_xyz) mu=self.particles.initial_vperpendicular**2*self.particles.mass*0.5/B_particle/(SPEED_OF_LIGHT**2*self.particles.mass) self.initial_conditions = jnp.concatenate([self.particles.initial_xyz,self.particles.initial_vparallel[:, None]/SPEED_OF_LIGHT,mu[:, None]],axis=1) - elif model == 'FullOrbit' or model == 'FullOrbit_Boris' or model == 'FullOrbitAdaptative': - self.ODE_term = ODETerm(Lorentz) + elif model == 'FullOrbit' or model == 'FullOrbitBoris' or model == 'FullOrbitAdaptive': + self.ode_term = ODETerm(lorentz) self.args = (self.field, self.particles) if self.particles.initial_xyz_fullorbit is None: raise ValueError("Initial full orbit positions require field input to Particles") @@ -1242,12 +1239,12 @@ def condition_BioSavart(t, y, args, **kwargs): self.initial_conditions = jnp.concatenate([self.particles.initial_xyz_fullorbit, self.particles.initial_vxvyvz], axis=1) if field is None: raise ValueError("Field parameter is required for FullOrbit model") - elif model in ('FieldLine', 'FieldLineAdaptative', 'FieldLineArclength', 'FieldLineToroidal'): + elif model in ('FieldLine', 'FieldLineAdaptive', 'FieldLineArcLength', 'FieldLineToroidal'): field_line_rhs = { - 'FieldLineArclength': FieldLineArclength, - 'FieldLineToroidal': FieldLineToroidal, - }.get(model, FieldLine) - self.ODE_term = ODETerm(field_line_rhs) + 'FieldLineArcLength': field_line_arclength, + 'FieldLineToroidal': field_line_toroidal, + }.get(model, field_line) + self.ode_term = ODETerm(field_line_rhs) self.args = self.field if self.n_save is None: @@ -1308,7 +1305,7 @@ def compute_trajectory(initial_condition, particle_key) -> jnp.ndarray: return self._vmec_orbit(initial_condition, particle_key) if self._axis_regular: initial_condition = _to_axis_regular(initial_condition) - if self.model == 'FullOrbit_Boris': + if self.model == 'FullOrbitBoris': # Integrate the whole [0, tmax] span: an inner scan of # Boris pushes between consecutive save times, with dt # adjusted (<= timestep) so the saves land on self.times. @@ -1350,7 +1347,7 @@ def save_interval(carry, _): event_mask = hits[0] if n_criteria == 1 else tuple(hits[i] for i in range(n_criteria)) return trajectory, event_mask return trajectory - solution = self._solve(*self._terms(particle_key), 0.0, initial_condition, self.args, Event(self.condition), + solution = self._solve(*self._terms(particle_key), 0.0, initial_condition, self.args, Event(self.event), throw=self.model in ('GuidingCenter', 'FullOrbit', 'FieldLine')) trajectory = solution.ys[0] if self._axis_regular: @@ -1403,7 +1400,7 @@ def _adaptive_tolerances(self, flag=False): size = self.initial_conditions.shape[-1] + 1 + int(flag) angles = (2, size - 1 - int(flag)) # phi and Theta, before any failure flag elif self.model == 'FieldLineToroidal' or (isinstance(self.field, Vmec) - and self.model in ('FieldLineAdaptative', 'FieldLineArclength')): + and self.model in ('FieldLineAdaptive', 'FieldLineArcLength')): size, angles = self.initial_conditions.shape[-1] + int(flag), (1, 2) else: return self.rtol, self.atol @@ -1431,10 +1428,10 @@ def _terms(self, key, flag=False, events=()): ControlTerm(flagged(self._vector_field(diffusion), drift=False), bm)) solver = solver() else: - terms = ODETerm(flagged(self.ODE_term.vector_field)) + terms = ODETerm(flagged(self.ode_term.vector_field)) solver = self.solver if self.solver is not None else diffrax.Dopri8() controller = diffrax.ConstantStepSize() - if model == 'GuidingCenterCollisionsMuAdaptative': + if model == 'GuidingCenterCollisionsMuAdaptive': rtol, atol = self._adaptive_tolerances(flag) controller = ClipStepSizeController( controller=PIDController(pcoeff=0.1, icoeff=0.3, dcoeff=0.0, rtol=rtol, atol=atol, @@ -1483,10 +1480,10 @@ def _vmec_orbit(self, y0, key): if ext is not None: wall = self.wall if self.wall is not None else (lambda x: jnp.ones(())) depth = lambda y: self.field.boundary_distance(y[:3]) - self.reentry_depth - outside = (ODETerm(_with_failure_flag(lambda t, y, args: self._masked(GuidingCenterMu, t, y, args))), self.solver if self.solver is not None else + outside = (ODETerm(_with_failure_flag(lambda t, y, args: self._masked(guiding_center_mu, t, y, args))), self.solver if self.solver is not None else diffrax.Dopri8(), _EventSteps(pcoeff=0.4, icoeff=0.3, dcoeff=0, rtol=self.rtol, atol=self.atol, events=(lambda y: wall(y[:3]), depth)), - (ext, self.particles, Electric_field_zero()), + (ext, self.particles, ElectricFieldZero()), Event((lambda t, y, args, **kwargs: wall(y[:3]), lambda t, y, args, **kwargs: depth(y), _failed_event), root_finder=_EVENT_ROOT_FINDER)) @@ -1561,7 +1558,7 @@ def _vmec_to_exterior(self, y): """Model state on the LCFS -> (x, y, z, v_par, mu) and energy, keeping E and mu.""" point, m, c = y[:3], self.particles.mass, SPEED_OF_LIGHT B = self.field.AbsB(point) - if self.model in ('GuidingCenter', 'GuidingCenterAdaptative'): + if self.model in ('GuidingCenter', 'GuidingCenterAdaptive'): vpar, E = y[3], self.particles.energy mu = (E - 0.5 * m * vpar**2) / B elif self.model == 'GuidingCenterCollisions': @@ -1582,7 +1579,7 @@ def _vmec_from_exterior(self, y): E = 0.5 * m * y[3]**2 + y[4] * self._masked(lambda e, x: e.AbsB(x), self.exterior_field, y[:3]) point = self.field.flux_coordinates(y[:3])[0] vpar, mu = _keep_energy(y[3], y[4], E, self.field.AbsB(point), m) - if self.model in ('GuidingCenter', 'GuidingCenterAdaptative'): + if self.model in ('GuidingCenter', 'GuidingCenterAdaptive'): return jnp.append(point, vpar) if self.model == 'GuidingCenterCollisions': v = jnp.sqrt(2 * E / m) @@ -1637,10 +1634,10 @@ def trajectories(self, value): self._trajectories = value def energy(self): - assert 'GuidingCenter' in self.model or 'FullOrbit' in self.model or 'FullOrbit_Boris' in self.model, "Energy calculation is only available for GuidingCenter and FullOrbit models" + assert 'GuidingCenter' in self.model or 'FullOrbit' in self.model or 'FullOrbitBoris' in self.model, "Energy calculation is only available for guiding_center and FullOrbit models" mass = self.particles.mass - if self.model == 'GuidingCenter' or self.model == 'GuidingCenterAdaptative': + if self.model == 'GuidingCenter' or self.model == 'GuidingCenterAdaptive': initial_xyz = self.trajectories[:, 0, :3] # t = 0, on the trajectories' devices initial_vparallel = self.trajectories[:, 0, 3] initial_B = vmap(self.field.AbsB)(initial_xyz) @@ -1651,7 +1648,7 @@ def compute_energy(trajectory, mu): AbsB = vmap(self.field.AbsB)(xyz) return 0.5 * mass * jnp.square(vpar) + mu * AbsB energy = vmap(compute_energy)(self.trajectories, mu_array) - elif self.model == 'GuidingCenterCollisionsMuIto' or self.model == 'GuidingCenterCollisionsMuFixed' or self.model == 'GuidingCenterCollisionsMuAdaptative': + elif self.model == 'GuidingCenterCollisionsMuIto' or self.model == 'GuidingCenterCollisionsMuFixed' or self.model == 'GuidingCenterCollisionsMuAdaptive': def compute_energy(trajectory): xyz = trajectory[:, :3] vpar = trajectory[:, 3]*SPEED_OF_LIGHT @@ -1664,7 +1661,7 @@ def compute_energy(trajectory): return 0.5 * mass * trajectory[:, 3]**2 energy = vmap(compute_energy)(self.trajectories) - else: # the full-orbit models: FullOrbit, FullOrbit_Boris, FullOrbitAdaptative, FullOrbitCollisions + else: # the full-orbit models: FullOrbit, FullOrbitBoris, FullOrbitAdaptive, FullOrbitCollisions def compute_energy(trajectory): vxvyvz = trajectory[:, 3:] v_squared = jnp.sum(jnp.square(vxvyvz), axis=1) @@ -1675,10 +1672,10 @@ def compute_energy(trajectory): def v_perp(self): - assert 'GuidingCenter' in self.model or 'FullOrbit' in self.model or 'FullOrbit_Boris' in self.model, "Energy calculation is only available for GuidingCenter and FullOrbit models" + assert 'GuidingCenter' in self.model or 'FullOrbit' in self.model or 'FullOrbitBoris' in self.model, "Energy calculation is only available for guiding_center and FullOrbit models" mass = self.particles.mass - if self.model == 'GuidingCenter' or self.model == 'GuidingCenterAdaptative': + if self.model == 'GuidingCenter' or self.model == 'GuidingCenterAdaptive': initial_xyz = self.trajectories[:, 0, :3] # t = 0, on the trajectories' devices initial_vparallel = self.trajectories[:, 0, 3] initial_B = vmap(self.field.AbsB)(initial_xyz) @@ -1689,7 +1686,7 @@ def compute_vperp(trajectory, mu): return jnp.sqrt(mu * AbsB/mass*2.) v_perp = vmap(compute_vperp)(self.trajectories, mu_array) - elif self.model == 'GuidingCenterCollisionsMuIto' or self.model == 'GuidingCenterCollisionsMuFixed' or self.model == 'GuidingCenterCollisionsMuAdaptative': + elif self.model == 'GuidingCenterCollisionsMuIto' or self.model == 'GuidingCenterCollisionsMuFixed' or self.model == 'GuidingCenterCollisionsMuAdaptive': def compute_vperp(trajectory): xyz = trajectory[:, :3] mu = trajectory[:, 4]*self.particles.mass*SPEED_OF_LIGHT**2 @@ -1701,7 +1698,7 @@ def compute_vperp(trajectory): return trajectory[:, 3]*jnp.sqrt(jnp.maximum(1-trajectory[:, 4]**2, 0.)) v_perp = vmap(compute_vperp)(self.trajectories) - else: # the full-orbit models: FullOrbit, FullOrbit_Boris, FullOrbitAdaptative, FullOrbitCollisions + else: # the full-orbit models: FullOrbit, FullOrbitBoris, FullOrbitAdaptive, FullOrbitCollisions def compute_vperp(trajectory): xyz = trajectory[:, :3] vxvyvz = trajectory[:, 3:] @@ -1926,7 +1923,7 @@ def trace_field_lines( extent = (2.0 * jnp.pi * float(toroidal_turns) if toroidal_turns is not None else float(length)) - model = "FieldLineToroidal" if toroidal_turns is not None else "FieldLineArclength" + model = "FieldLineToroidal" if toroidal_turns is not None else "FieldLineArcLength" if label is not None: print(f"Tracing {label} (the first call compiles ESSOS)...", flush=True) started = perf_counter() diff --git a/essos/electric_field.py b/essos/electric_field.py index 22034ca8..09b294b9 100644 --- a/essos/electric_field.py +++ b/essos/electric_field.py @@ -5,7 +5,7 @@ from jax import jit, jacfwd, grad, vmap, tree_util, lax -class Electric_field_flux(): +class ElectricFieldFlux(): """Radial electric field read from an HDF5 file and mapped to VMEC ``s``. The file needs datasets ``rho`` (normalized minor radius) and ``Er``. @@ -33,17 +33,17 @@ def E_covariant(self, points): return jnp.array([Er_interp,0.0,0.0]) -class Electric_field_zero(): +class ElectricFieldZero(): """No electric field; ``E_covariant`` returns zeros.""" def __init__(self): self.Er_filename = None # Stateless: every instance equals every other, so jit calls with it as a static argument share one compilation. def __eq__(self, other): - return type(other) is Electric_field_zero + return type(other) is ElectricFieldZero def __hash__(self): - return hash(Electric_field_zero) + return hash(ElectricFieldZero) @partial(jit, static_argnames=['self']) def E_covariant(self, points): diff --git a/essos/fields.py b/essos/fields.py index c9510cd6..7d28b99c 100644 --- a/essos/fields.py +++ b/essos/fields.py @@ -9,7 +9,7 @@ from functools import partial from jax import jit, jacfwd, grad, vmap, tree_util, lax from jax.custom_batching import custom_vmap -from essos.surfaces import SurfaceRZFourier, BdotN_over_B, SurfaceClassifier +from essos.surfaces import SurfaceRZFourier, bdotn_over_b, SurfaceClassifier from essos.plot import fix_matplotlib_3d from essos.util import newton @@ -232,7 +232,7 @@ def gamma_dashdash_from_gamma(gamma): d2_dtheta2_fft(gamma[..., 2]), ], axis=-1) -class BiotSavart_from_gamma(MagneticField): +class BiotSavartFromGamma(MagneticField): def __init__(self, gamma, gamma_dash=None, gamma_dashdash=None, currents=None): self.currents = currents self.gamma = gamma @@ -698,15 +698,6 @@ def newton(x, _): s = x[0]**2 + x[1]**2 return jnp.array([s, jnp.mod(jnp.arctan2(x[1], x[0]), 2 * jnp.pi), phi]), residual -class near_axis: - def __init__(self, *args, **kwargs): - raise ImportError( - "The 'near_axis' class has been migrated to the standalone 'pyQSC_JAX' repository. " - "Please run 'pip install git+https://github.com/uwplasma/pyQSC_JAX.git' " - "and import it via 'from pyqsc_jax.near_axis import near_axis'." - ) - - class _VmecStatic: """Non-array state of a ``Vmec`` (mode counts, nfp, ...): equal when those are. The file handle and the boundary surface ride along but do not take part in the comparison.""" diff --git a/essos/losses.py b/essos/losses.py index 949529d6..0b913640 100644 --- a/essos/losses.py +++ b/essos/losses.py @@ -3,7 +3,7 @@ from jax import tree_util, jit, ensure_compile_time_eval, grad as jax_grad, value_and_grad as jax_value_and_grad from jax.flatten_util import ravel_pytree -class base_loss: +class BaseLoss: def __init__(self): self.losses = [self] self._dependencies = {} @@ -33,11 +33,11 @@ def dependencies_buffer(self): return self._dependencies_buffer def __add__(self, other): - if not isinstance(other, base_loss): - raise TypeError("Addition is only defined between base_loss objects.") + if not isinstance(other, BaseLoss): + raise TypeError("Addition is only defined between BaseLoss objects.") losses_list = [*self.losses, *other.losses] # Flatten the losses - out_loss = composite_loss(losses_list) + out_loss = CompositeLoss(losses_list) out_loss.dependencies = self.dependencies | other.dependencies return out_loss @@ -45,13 +45,13 @@ def __iter__(self): return iter(self.losses) def __mul__(self, other): - raise NotImplementedError("Multiplication is only defined in subclasses of base_loss.") + raise NotImplementedError("Multiplication is only defined in subclasses of BaseLoss.") def __rmul__(self, other): return self.__mul__(other) -class custom_loss(base_loss): +class CustomLoss(BaseLoss): def __init__(self, fun, *args_names, **kwargs): """ A custom loss function that can take multiple arguments and compute gradients with respect to specified arguments. @@ -65,7 +65,7 @@ def __init__(self, fun, *args_names, **kwargs): **kwargs: Static (non-differentiable) keyword arguments to be passed to the loss function. Returns: - custom_loss: An instance of the custom_loss class. + CustomLoss: An instance of the CustomLoss class. """ super().__init__() self.fun = fun @@ -153,23 +153,23 @@ def grad_pytree(self, dofs_pytree) -> dict: def __mul__(self, other): if not isinstance(other, (int, float)): - raise TypeError("Multiplication is only defined between base_loss and a scalar.") + raise TypeError("Multiplication is only defined between BaseLoss and a scalar.") new_fun = lambda *args, **kwargs: other * self.fun(*args, **kwargs) - out_loss = custom_loss(new_fun, *self.args_names, **self.kwargs) + out_loss = CustomLoss(new_fun, *self.args_names, **self.kwargs) out_loss.dependencies = self.dependencies return out_loss -class composite_loss(base_loss): +class CompositeLoss(BaseLoss): def __init__(self, losses: list): """ A composite loss function that combines multiple loss functions. Args: losses (list): - A list of loss functions to be combined. Each loss function should be an instance of base_loss or its subclasses. + A list of loss functions to be combined. Each loss function should be an instance of BaseLoss or its subclasses. Returns: - composite_loss: An instance of the composite_loss class. + CompositeLoss: An instance of the CompositeLoss class. """ super().__init__() self.losses = losses diff --git a/essos/multiobjectiveoptimizer.py b/essos/multiobjectiveoptimizer.py index dd7907f7..874f8477 100644 --- a/essos/multiobjectiveoptimizer.py +++ b/essos/multiobjectiveoptimizer.py @@ -6,7 +6,7 @@ import matplotlib.pyplot as plt from jax import jit from functools import partial -from essos.coils import Coils, Curves, CreateEquallySpacedCurves +from essos.coils import Coils, Curves, create_equally_spaced_curves from essos.fields import BiotSavart import numpy as np from pandas.plotting import parallel_coordinates @@ -31,8 +31,8 @@ def __init__(self, loss_functions, vmec, coils_init=None, function_inputs=None, self.study = None - self.order_Fourier = self.opt_config.get("order_Fourier", 6) - self.num_points = self.order_Fourier * 10 + self.fourier_order = self.opt_config.get("fourier_order", 6) + self.num_points = self.fourier_order * 10 self.num_coils = self.opt_config.get("num_coils", 4) self.max_nfev = self.opt_config.get("max_nfev", 300) self.n_trials = self.opt_config.get("n_trials", 1) @@ -46,9 +46,9 @@ def _generate_initial_coils(self): nfp = self.vmec.nfp R = self.vmec.r_axis r = R / 1.5 - curves = CreateEquallySpacedCurves( + curves = create_equally_spaced_curves( n_curves=self.num_coils, - order=self.order_Fourier, + order=self.fourier_order, R=R, r=r, n_segments=self.num_points, nfp=nfp, stellsym=True @@ -111,7 +111,7 @@ def _objective(self, trial): loss_fn = lambda x: self.weighted_loss(x, weights) grad_fn = jax.grad(loss_fn) - x = self.initial_coils.x + x = self.initial_coils.dofs opt = getattr(optax, method)(lr) state = opt.init(x) @@ -152,7 +152,7 @@ def run(self, seed: int = 42): def optimize_with_optax(self, weights, method="adam", lr=1e-2): loss_fn = lambda x: self.weighted_loss(x, weights) grad_fn = jax.grad(loss_fn) - x = self.initial_coils.x + x = self.initial_coils.dofs optimizer = getattr(optax, method)(lr) state = optimizer.init(x) diff --git a/essos/objective_functions.py b/essos/objective_functions.py index 1d62acbf..32448c34 100644 --- a/essos/objective_functions.py +++ b/essos/objective_functions.py @@ -6,8 +6,8 @@ from jax import jit, vmap from functools import partial from essos.dynamics import Tracing -from essos.fields import BiotSavart,BiotSavart_from_gamma -from essos.surfaces import BdotN_over_B +from essos.fields import BiotSavart,BiotSavartFromGamma +from essos.surfaces import bdotn_over_b from essos.coils import Curves, Coils from essos.constants import mu_0 from essos.coil_perturbation import perturb_curves, perturb_curves_systematic, perturb_curves_statistic @@ -30,13 +30,13 @@ def near_axis_field_quantities(field_nearaxis): -def loss_B_difference_coils_near_axis(field, field_nearaxis): +def loss_b_difference_coils_near_axis(field, field_nearaxis): points, B_nearaxis, _ = near_axis_field_quantities(field_nearaxis) B_coils = vmap(field.B)(points.T) B_difference_loss = jnp.sum(jnp.abs(jnp.array(B_coils)-jnp.array(B_nearaxis))) return B_difference_loss -def loss_gradB_difference_coils_near_axis(field, field_nearaxis): +def loss_gradb_difference_coils_near_axis(field, field_nearaxis): points, _, gradB_nearaxis = near_axis_field_quantities(field_nearaxis) gradB_coils = vmap(field.dB_by_dX)(points.T) gradB_difference_loss = jnp.sum(jnp.abs(jnp.array(gradB_coils)-jnp.array(gradB_nearaxis))) @@ -51,7 +51,7 @@ def loss_r0_near_axis(field_nearaxis, r0_target=1.0): ##############################Particle confinement losses ############################## def _orbit(field, particles, *, timestep=None, tmax=1e-5, n_save=300, rtol=1e-7, atol=None, max_steps=None, - model='GuidingCenterAdaptative', boundary=None): + model='GuidingCenterAdaptive', boundary=None): """Trace and return xyz, the cylindrical radius and the offsets (R, Z) from the axis.""" xyz = Tracing(field=field, particles=particles, model=model, tmax=tmax, timestep=timestep, n_save=n_save, rtol=rtol, atol=atol, max_steps=max_steps, boundary=boundary).trajectories[:, :, :3] @@ -84,7 +84,7 @@ def loss_particle_rcross_final(field, particles, **trace): _, _, dR, dZ = _orbit(field, particles, **trace) return jnp.linalg.norm(jnp.average(_r_cross(dR, dZ), axis=1)) -def loss_particle_Br(field, particles, **trace): +def loss_particle_br(field, particles, **trace): xyz, fac_xy, dR, dZ = _orbit(field, particles, **trace) r_cross = _r_cross(dR, dZ) B = jax.vmap(jax.vmap(field.B_covariant))(xyz) @@ -104,20 +104,20 @@ def loss_particle_iota(field, particles, target_iota=0.41, **trace): ################### B ON SURAFCE LOSSES ########################## @partial(jit, static_argnames=['npoints']) -def normB_axis(field, npoints=15): +def norm_b_axis(field, npoints=15): R_axis=field.r_axis phi_array = jnp.linspace(0, 2 * jnp.pi, npoints) B_axis = vmap(lambda phi: field.AbsB(jnp.array([R_axis * jnp.cos(phi), R_axis * jnp.sin(phi), 0])))(phi_array) return B_axis @partial(jit, static_argnames=['npoints', 'target_B']) -def loss_normB_axis_average(field,npoints=15, target_B=5.7): - B_axis = normB_axis(field, npoints) +def loss_norm_b_axis_average(field,npoints=15, target_B=5.7): + B_axis = norm_b_axis(field, npoints) return jnp.abs(jnp.average(B_axis)-target_B) def loss_bdotn(field,surface): - return jnp.sum(jnp.abs(BdotN_over_B(surface, field))) + return jnp.sum(jnp.abs(bdotn_over_b(surface, field))) def _sqrt_sum_positive(u): """sqrt(sum(max(u, 0))) with a zero (not NaN) gradient where the constraint is met.""" @@ -126,8 +126,8 @@ def _sqrt_sum_positive(u): @partial(jit, static_argnames=['target_tol']) def loss_bdotn_constraint(field,surface,target_tol=1.e-6): - bdotn_over_b = BdotN_over_B(surface, field) - return _sqrt_sum_positive(jnp.square(bdotn_over_b)-target_tol) + ratio = bdotn_over_b(surface, field) + return _sqrt_sum_positive(jnp.square(ratio)-target_tol) ########################### B ON SURAFCE LOSSES FOR STOCHASTIC OPTIMIZATION ########################## @@ -148,8 +148,8 @@ def perturbed_field_from_field(field, key, sampler): def loss_bdotn_stochastic(field, surface, sampler, keys): def perturbed_loss(key): perturbed_field = perturbed_field_from_field(field, key, sampler) - bdotn_over_b = BdotN_over_B(surface, perturbed_field) - return jnp.sum(jnp.abs(bdotn_over_b)) + ratio = bdotn_over_b(surface, perturbed_field) + return jnp.sum(jnp.abs(ratio)) return jnp.mean(jax.vmap(perturbed_loss)(keys)) @@ -158,7 +158,7 @@ def perturbed_loss(key): def constraint_bdotn_stochastic(field, surface, sampler, keys, target_tol=1.0e-6): def perturbed_square(key): perturbed_field = perturbed_field_from_field(field, key, sampler) - return jnp.square(BdotN_over_B(surface, perturbed_field)) + return jnp.square(bdotn_over_b(surface, perturbed_field)) expected_square = jnp.mean(jax.vmap(perturbed_square)(keys), axis=0) return _sqrt_sum_positive(expected_square - target_tol) @@ -342,11 +342,11 @@ def integrand(r2, dr2): -# Lorentz force loss: accepts Coils object, keyword args, JAX-friendly +# lorentz force loss: accepts Coils object, keyword args, JAX-friendly @partial(jit, static_argnames=["p", "threshold", "block_size"]) def loss_lorentz_force_coils(coils, p=1, threshold=0.5e6, block_size=None, conductor_radius=None): """ - Loss function penalizing Lorentz force on coils using Landreman-Hurwitz method. + Loss function penalizing lorentz force on coils using Landreman-Hurwitz method. Matches SIMSOPT's ``LpCurveForce``:: @@ -388,7 +388,7 @@ def single_coil_loss(idx): gamma_dash_others = coils.gamma_dash[other_idx] gamma_dashdash_others = coils.gamma_dashdash[other_idx] currents_others = coils.currents[other_idx] - biot_savart = BiotSavart_from_gamma(gamma_others, gamma_dash_others, gamma_dashdash_others, currents_others) + biot_savart = BiotSavartFromGamma(gamma_others, gamma_dash_others, gamma_dashdash_others, currents_others) n_points = gamma_i.shape[0] use_block_size = min(n_points, n_points if block_size is None else block_size) n_blocks = (n_points + use_block_size - 1) // use_block_size @@ -405,7 +405,7 @@ def block_field(block_gamma_i, block_valid): block_B_mutual = jax.vmap(block_field)(gamma_i_blocks, valid_blocks).reshape(padded_points, 3)[:n_points] block_gammadash_norm = jnp.linalg.norm(gamma_dash_i, axis=1) block_tangent = gamma_dash_i / block_gammadash_norm[:, None] - block_B_self = B_regularized_pure( + block_B_self = b_regularized_pure( gamma_i, gamma_dash_i, gamma_dashdash_i, quadpoints, current_i, regularization ) @@ -423,7 +423,7 @@ def block_field(block_gamma_i, block_valid): -def B_regularized_singularity_term(rc_prime, rc_prime_prime, regularization): +def b_regularized_singularity_term(rc_prime, rc_prime_prime, regularization): """The term in the regularized Biot-Savart law in which the near-singularity has been integrated analytically. @@ -439,7 +439,7 @@ def B_regularized_singularity_term(rc_prime, rc_prime_prime, regularization): return jnp.cross(rc_prime, rc_prime_prime) * (0.5 * (-2 + jnp.log(64 * norm_rc_prime * norm_rc_prime / regularization)) / (norm_rc_prime**3))[:, None] -def B_regularized_pure(gamma, gammadash, gammadashdash, quadpoints, current, regularization): +def b_regularized_pure(gamma, gammadash, gammadashdash, quadpoints, current, regularization): # The factors of 2π in the next few lines come from the fact that simsopt # uses a curve parameter that goes up to 1 rather than 2π. phi = quadpoints * 2 * jnp.pi @@ -448,7 +448,7 @@ def B_regularized_pure(gamma, gammadash, gammadashdash, quadpoints, current, reg rc_prime_prime = gammadashdash / 4 / jnp.pi**2 n_quad = phi.shape[0] dphi = 2 * jnp.pi / n_quad - analytic_term = B_regularized_singularity_term(rc_prime, rc_prime_prime, regularization) + analytic_term = b_regularized_singularity_term(rc_prime, rc_prime_prime, regularization) dr = rc[:, None] - rc[None, :] first_term = jnp.cross(rc_prime[None, :], dr) / ((jnp.sum(dr * dr, axis=2) + regularization) ** 1.5)[:, :, None] cos_fac = 2 - 2 * jnp.cos(phi[None, :] - phi[:, None]) @@ -481,12 +481,12 @@ def rectangular_xsection_delta(a, b): #def loss_bdotn_only_with_perturbation(x, vmec, dofs_curves, currents_scale, nfp,n_segments=60, stellsym=True, N_stells=10): # """ -# Compute the loss function for BdotN with a perturbation applied to the BdotN value.): +# Compute the loss function for bdotn with a perturbation applied to the bdotn value.): # field=field_from_dofs(x,dofs_curves, currents_scale, nfp,n_segments, stellsym) # -# bdotn_over_b = BdotN_over_B(vmec.surface, field) +# bdotn_over_b = bdotn_over_b(vmec.surface, field) # -# # Apply perturbation to the BdotN value +# # Apply perturbation to the bdotn value # bdotn_over_b += perturbation # # bdotn_over_b_loss = jnp.sum(jnp.abs(bdotn_over_b)) diff --git a/essos/optimization.py b/essos/optimization.py index bcf1b9eb..29ac594b 100644 --- a/essos/optimization.py +++ b/essos/optimization.py @@ -85,33 +85,33 @@ def optimize_loss_function(func, initial_dofs, coils, tol=1e-4, max_nfev=30, met dofs_curves = jnp.reshape(result.x[:len_dofs_curves], (dofs_curves_shape)) try: - if len(initial_dofs) == len(coils.x): + if len(initial_dofs) == len(coils.dofs): dofs_currents = result.x[len_dofs_curves:] curves = Curves(dofs_curves, n_segments, nfp, stellsym) new_coils = Coils(curves=curves, currents=dofs_currents*coils.currents_scale) return new_coils - elif 'field_nearaxis' in kwargs and len(initial_dofs) == len(coils.x) + len(kwargs['field_nearaxis'].x): + elif 'field_nearaxis' in kwargs and len(initial_dofs) == len(coils.dofs) + len(kwargs['field_nearaxis'].x): dofs_currents = result.x[len_dofs_curves:-len(kwargs['field_nearaxis'].x)] curves = Curves(dofs_curves, n_segments, nfp, stellsym) new_coils = Coils(curves=curves, currents=dofs_currents * coils.currents_scale) new_field_nearaxis = new_nearaxis_from_x_and_old_nearaxis(result.x[-len(kwargs['field_nearaxis'].x):], kwargs['field_nearaxis']) return new_coils, new_field_nearaxis - elif 'surface_all' in kwargs and len(initial_dofs) == len(coils.x) + len(kwargs['surface_all'].x): + elif 'surface_all' in kwargs and len(initial_dofs) == len(coils.dofs) + len(kwargs['surface_all'].dofs): surface_all = kwargs['surface_all'] - dofs_currents = result.x[len_dofs_curves:-len(surface_all.x)] + dofs_currents = result.x[len_dofs_curves:-len(surface_all.dofs)] curves = Curves(dofs_curves, n_segments, nfp, stellsym) new_coils = Coils(curves=curves, currents=dofs_currents * coils.currents_scale) new_surface = SurfaceRZFourier(rc=surface_all.rc, zs=surface_all.zs, nfp=nfp, range_torus=surface_all.range_torus, nphi=surface_all.nphi, ntheta=surface_all.ntheta,mpol=surface_all.mpol,ntor=surface_all.ntor) - new_surface.dofs = result.x[-len(surface_all.x):] + new_surface.dofs = result.x[-len(surface_all.dofs):] return new_coils, new_surface - elif 'surface_all' in kwargs and 'field_nearaxis' in kwargs and len(initial_dofs) == len(coils.x) + len(kwargs['surface_all'].x) + len(kwargs['field_nearaxis'].x): + elif 'surface_all' in kwargs and 'field_nearaxis' in kwargs and len(initial_dofs) == len(coils.dofs) + len(kwargs['surface_all'].dofs) + len(kwargs['field_nearaxis'].x): surface_all = kwargs['surface_all'] field_nearaxis = kwargs['field_nearaxis'] - dofs_currents = result.x[len_dofs_curves:-len(surface_all.x)-len(field_nearaxis.x)] + dofs_currents = result.x[len_dofs_curves:-len(surface_all.dofs)-len(field_nearaxis.x)] curves = Curves(dofs_curves, n_segments, nfp, stellsym) new_coils = Coils(curves=curves, currents=dofs_currents * coils.currents_scale) new_surface = SurfaceRZFourier(rc=surface_all.rc, zs=surface_all.zs, nfp=nfp, range_torus=surface_all.range_torus, nphi=surface_all.nphi, ntheta=surface_all.ntheta,mpol=surface_all.mpol,ntor=surface_all.ntor) - new_surface.dofs = result.x[-len(surface_all.x)-len(field_nearaxis.x):-len(field_nearaxis.x)] + new_surface.dofs = result.x[-len(surface_all.dofs)-len(field_nearaxis.x):-len(field_nearaxis.x)] new_field_nearaxis = new_nearaxis_from_x_and_old_nearaxis(result.x[-len(field_nearaxis.x):], field_nearaxis) return new_coils, new_surface, new_field_nearaxis except Exception as e: diff --git a/essos/surfaces.py b/essos/surfaces.py index e8f8035c..c5e6b20b 100644 --- a/essos/surfaces.py +++ b/essos/surfaces.py @@ -55,7 +55,7 @@ def poloidal_flux(surface, field, idx=0) -> jnp.ndarray: @jit -def B_on_surface(surface, field): +def b_on_surface(surface, field): ntheta = surface.ntheta nphi = surface.nphi gamma = surface.gamma @@ -66,20 +66,20 @@ def B_on_surface(surface, field): gamma_reshaped = jax.lax.with_sharding_constraint(gamma_reshaped, sharding) # Map field.B over all positions - B_on_surface = vmap(field.B)(gamma_reshaped) + b_on_surface = vmap(field.B)(gamma_reshaped) - return B_on_surface.reshape(nphi, ntheta, 3) + return b_on_surface.reshape(nphi, ntheta, 3) @jit -def BdotN(surface, field): - B_surface = B_on_surface(surface, field) +def bdotn(surface, field): + B_surface = b_on_surface(surface, field) B_dot_n = jnp.sum(B_surface * surface.unitnormal, axis=2) return B_dot_n @jit -def BdotN_over_B(surface, field, **kwargs): - return BdotN(surface, field) / jnp.linalg.norm(B_on_surface(surface, field), axis=2) +def bdotn_over_b(surface, field, **kwargs): + return bdotn(surface, field) / jnp.linalg.norm(b_on_surface(surface, field), axis=2) def _surface_mean(surface, values): """Average of ``values`` (on the ``(nphi, ntheta)`` grid) over the whole torus. @@ -103,19 +103,19 @@ def _surface_mean(surface, values): @jit def _squared_flux_local(surface, field): - return 0.5 * _surface_mean(surface, BdotN(surface, field)**2 / jnp.sum(B_on_surface(surface, field)**2, axis=2) + return 0.5 * _surface_mean(surface, bdotn(surface, field)**2 / jnp.sum(b_on_surface(surface, field)**2, axis=2) * surface.area_element) @jit def _squared_flux_global(surface, field): - return 0.5 * _surface_mean(surface, BdotN(surface, field)**2 * surface.area_element) + return 0.5 * _surface_mean(surface, bdotn(surface, field)**2 * surface.area_element) @jit def _squared_flux_normalized(surface, field): - return 0.5 * _surface_mean(surface, BdotN(surface, field)**2 * surface.area_element) / \ - _surface_mean(surface, jnp.sum(B_on_surface(surface, field)**2, axis=2) * surface.area_element) + return 0.5 * _surface_mean(surface, bdotn(surface, field)**2 * surface.area_element) / \ + _surface_mean(surface, jnp.sum(b_on_surface(surface, field)**2, axis=2) * surface.area_element) -def SquaredFlux(surface, field, definition='local'): +def squared_flux(surface, field, definition='local'): if definition == 'local': return _squared_flux_local(surface, field) elif definition == 'quadratic flux': @@ -676,16 +676,6 @@ def area_element(self): return values[2] return self._area_element - # TODO: remove x property. This is a placeholder for compatibility with the examples that need to be updated. - # x property and setter - @property - def x(self): - return self.dofs - - @x.setter - def x(self, new_dofs): - self.dofs = new_dofs - @property def volume(self): """Enclosed volume, ``(1/3) |integral of x . n dtheta dphi|``.""" @@ -807,7 +797,7 @@ def to_vtk(self, filename, extra_data=None, field=None): z = boundary[:, :, 2].reshape((1, self.nphi, self.ntheta)).copy() pointData = {} if field is not None: - B_dot_n_over_B = np.array(BdotN_over_B(self, field)).reshape((1,self. nphi, self.ntheta)).copy() + B_dot_n_over_B = np.array(bdotn_over_b(self, field)).reshape((1,self. nphi, self.ntheta)).copy() pointData["B_dot_n_over_B"] = B_dot_n_over_B B_BiotSavart = np.array(vmap(lambda surf: vmap(lambda x: field.AbsB(x))(surf))(boundary)).reshape((1, self.nphi, self.ntheta)).copy() pointData["B_BiotSavart"] = B_BiotSavart diff --git a/examples/coil_optimization/optimize_coils_and_nearaxis.py b/examples/coil_optimization/optimize_coils_and_nearaxis.py index 20ef993d..717c6fcf 100644 --- a/examples/coil_optimization/optimize_coils_and_nearaxis.py +++ b/examples/coil_optimization/optimize_coils_and_nearaxis.py @@ -2,7 +2,7 @@ from time import time import jax.numpy as jnp import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart from pyqsc_jax.near_axis import near_axis from essos.dynamics import Tracing @@ -11,7 +11,7 @@ # In this exmple, `scipy.optimize.least_squares` is used, but any other optimizer, e.g. from # `scipy.optimize.minimize`, can be used as well and may even be preferable. from scipy.optimize import least_squares -from essos.losses import custom_loss +from essos.losses import CustomLoss """ Creating starting coils and surface """ @@ -33,7 +33,7 @@ number_of_field_periods = NFP major_radius_coils = field_nearaxis_initial.R0[0] minor_radius_coils = major_radius_coils/2.0 -init_curves = CreateEquallySpacedCurves(n_curves=N_COILS, +init_curves = create_equally_spaced_curves(n_curves=N_COILS, order=FOURIER_ORDER, R=major_radius_coils, r=minor_radius_coils, n_segments=N_SEGMENTS, @@ -68,13 +68,13 @@ def near_axis_field_quantities(field_nearaxis): -def loss_B_difference_coils_near_axis(field, field_nearaxis): +def loss_b_difference_coils_near_axis(field, field_nearaxis): points, B_nearaxis, _ = near_axis_field_quantities(field_nearaxis) B_coils = vmap(field.B)(points.T) B_difference_loss = jnp.sum(jnp.abs(jnp.array(B_coils)-jnp.array(B_nearaxis))) return B_difference_loss -def loss_gradB_difference_coils_near_axis(field, field_nearaxis): +def loss_gradb_difference_coils_near_axis(field, field_nearaxis): points, _, gradB_nearaxis = near_axis_field_quantities(field_nearaxis) gradB_coils = vmap(field.dB_by_dX)(points.T) gradB_difference_loss = jnp.sum(jnp.abs(jnp.array(gradB_coils)-jnp.array(gradB_nearaxis))) @@ -94,12 +94,12 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): """ Defining custom losses """ -L_B_difference = custom_loss(loss_B_difference_coils_near_axis, "field", "field_nearaxis") -L_gradB_difference = custom_loss(loss_gradB_difference_coils_near_axis, "field", "field_nearaxis") -L_length = custom_loss(loss_length, "field") -L_curvature = custom_loss(loss_curvature, "field") -L_iota = custom_loss(loss_iota_near_axis, "field_nearaxis") -L_r0 = custom_loss(loss_r0_near_axis, "field_nearaxis") +L_B_difference = CustomLoss(loss_b_difference_coils_near_axis, "field", "field_nearaxis") +L_gradB_difference = CustomLoss(loss_gradb_difference_coils_near_axis, "field", "field_nearaxis") +L_length = CustomLoss(loss_length, "field") +L_curvature = CustomLoss(loss_curvature, "field") +L_iota = CustomLoss(loss_iota_near_axis, "field_nearaxis") +L_r0 = CustomLoss(loss_r0_near_axis, "field_nearaxis") """ Defining total loss + setting dependencies """ @@ -123,11 +123,11 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): opt_field_nearaxis = L_total.dofs_to_pytree(res.x)["field_nearaxis"] -B_difference_initial = loss_B_difference_coils_near_axis(init_field, field_nearaxis_initial) -gradB_difference_initial = loss_gradB_difference_coils_near_axis(init_field, field_nearaxis_initial) +B_difference_initial = loss_b_difference_coils_near_axis(init_field, field_nearaxis_initial) +gradB_difference_initial = loss_gradb_difference_coils_near_axis(init_field, field_nearaxis_initial) -B_difference_optimized = loss_B_difference_coils_near_axis(opt_field, opt_field_nearaxis) -gradB_difference_optimized = loss_gradB_difference_coils_near_axis(opt_field, opt_field_nearaxis) +B_difference_optimized = loss_b_difference_coils_near_axis(opt_field, opt_field_nearaxis) +gradB_difference_optimized = loss_gradb_difference_coils_near_axis(opt_field, opt_field_nearaxis) print(f'############################################') @@ -157,9 +157,9 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): initial_xyz_optimized = jnp.array([R0_optimized*jnp.cos(phi0), R0_optimized*jnp.sin(phi0), Z0]).T time0 = time() -tracing_initial = Tracing(field=init_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_initial, +tracing_initial = Tracing(field=init_field, model='FieldLineAdaptive', initial_conditions=initial_xyz_initial, tmax=tmax, n_save=n_save, rtol=rtol) -tracing_optimized = Tracing(field=opt_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_optimized, +tracing_optimized = Tracing(field=opt_field, model='FieldLineAdaptive', initial_conditions=initial_xyz_optimized, tmax=tmax, n_save=n_save, rtol=rtol) print(f"Tracing took {time()-time0:.2f} seconds") diff --git a/examples/coil_optimization/optimize_coils_for_nearaxis.py b/examples/coil_optimization/optimize_coils_for_nearaxis.py index efae0d1c..777eebb7 100644 --- a/examples/coil_optimization/optimize_coils_for_nearaxis.py +++ b/examples/coil_optimization/optimize_coils_for_nearaxis.py @@ -3,7 +3,7 @@ from time import time import jax.numpy as jnp import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart from pyqsc_jax.near_axis import near_axis @@ -13,7 +13,7 @@ # In this exmple, `scipy.optimize.least_squares` is used, but any other optimizer, e.g. from # `scipy.optimize.minimize`, can be used as well and may even be preferable. from scipy.optimize import least_squares -from essos.losses import custom_loss +from essos.losses import CustomLoss """ Creating starting coils and surface """ @@ -35,7 +35,7 @@ number_of_field_periods = NFP major_radius_coils = field_nearaxis_initial.R0[0] minor_radius_coils = major_radius_coils/2.0 -init_curves = CreateEquallySpacedCurves(n_curves=N_COILS, +init_curves = create_equally_spaced_curves(n_curves=N_COILS, order=FOURIER_ORDER, R=major_radius_coils, r=minor_radius_coils, n_segments=N_SEGMENTS, @@ -65,13 +65,13 @@ def near_axis_field_quantities(field_nearaxis): return points, B_nearaxis, gradB_nearaxis -def loss_B_difference_coils_near_axis(field, field_nearaxis): +def loss_b_difference_coils_near_axis(field, field_nearaxis): points, B_nearaxis, _ = near_axis_field_quantities(field_nearaxis) B_coils = vmap(field.B)(points.T) B_difference_loss = jnp.sum(jnp.abs(jnp.array(B_coils)-jnp.array(B_nearaxis))) return B_difference_loss -def loss_gradB_difference_coils_near_axis(field, field_nearaxis): +def loss_gradb_difference_coils_near_axis(field, field_nearaxis): points, _, gradB_nearaxis = near_axis_field_quantities(field_nearaxis) gradB_coils = vmap(field.dB_by_dX)(points.T) gradB_difference_loss = jnp.sum(jnp.abs(jnp.array(gradB_coils)-jnp.array(gradB_nearaxis))) @@ -85,10 +85,10 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): """ Defining custom losses """ -L_B_difference = custom_loss(loss_B_difference_coils_near_axis, "field", field_nearaxis=field_nearaxis_initial) -L_gradB_difference = custom_loss(loss_gradB_difference_coils_near_axis, "field", field_nearaxis=field_nearaxis_initial) -L_length = custom_loss(loss_length, "field") -L_curvature = custom_loss(loss_curvature, "field") +L_B_difference = CustomLoss(loss_b_difference_coils_near_axis, "field", field_nearaxis=field_nearaxis_initial) +L_gradB_difference = CustomLoss(loss_gradb_difference_coils_near_axis, "field", field_nearaxis=field_nearaxis_initial) +L_length = CustomLoss(loss_length, "field") +L_curvature = CustomLoss(loss_curvature, "field") """ Defining total loss + setting dependencies """ L_total = B_DIFFERENCE_WEIGHT*L_B_difference + GRADB_DIFFERENCE_WEIGHT*L_gradB_difference + LENGTH_WEIGHT*L_length + CURVATURE_WEIGHT*L_curvature @@ -108,11 +108,11 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): opt_coils = opt_field.coils -B_difference_initial = loss_B_difference_coils_near_axis(init_field, field_nearaxis_initial) -gradB_difference_initial = loss_gradB_difference_coils_near_axis(init_field, field_nearaxis_initial) +B_difference_initial = loss_b_difference_coils_near_axis(init_field, field_nearaxis_initial) +gradB_difference_initial = loss_gradb_difference_coils_near_axis(init_field, field_nearaxis_initial) -B_difference_optimized = loss_B_difference_coils_near_axis(opt_field, field_nearaxis_initial) -gradB_difference_optimized = loss_gradB_difference_coils_near_axis(opt_field, field_nearaxis_initial) +B_difference_optimized = loss_b_difference_coils_near_axis(opt_field, field_nearaxis_initial) +gradB_difference_optimized = loss_gradb_difference_coils_near_axis(opt_field, field_nearaxis_initial) print(f'############################################') @@ -136,9 +136,9 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): initial_xyz_optimized = jnp.array([R0_optimized*jnp.cos(phi0), R0_optimized*jnp.sin(phi0), Z0]).T time0 = time() -tracing_initial = Tracing(field=init_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_initial, +tracing_initial = Tracing(field=init_field, model='FieldLineAdaptive', initial_conditions=initial_xyz_initial, tmax=tmax, n_save=n_save, rtol=rtol) -tracing_optimized = Tracing(field=opt_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_optimized, +tracing_optimized = Tracing(field=opt_field, model='FieldLineAdaptive', initial_conditions=initial_xyz_optimized, tmax=tmax, n_save=n_save, rtol=rtol) print(f"Tracing took {time()-time0:.2f} seconds") diff --git a/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py b/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py index 1c835697..d531ca08 100644 --- a/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py +++ b/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py @@ -4,12 +4,12 @@ import jax.numpy as jnp import matplotlib.pyplot as plt from essos.dynamics import Particles, Tracing -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from jax import vmap, jit # In this exmple, `scipy.optimize.least_squares` is used, but any other optimizer, e.g. from # `scipy.optimize.minimize`, can be used as well and may even be preferable. from scipy.optimize import least_squares -from essos.losses import custom_loss +from essos.losses import CustomLoss from essos.fields import BiotSavart @@ -19,7 +19,7 @@ MAXTIME_TRACING = 1e-4 NUMBER_COILS_PER_HALF_FIELD_PERIOD = 3 NUMBER_OF_FIELD_PERIODS = 2 -MODEL = 'FullOrbit_Boris' +MODEL = 'FullOrbitBoris' TIMESTEP=1.e-14 TRACE_TOLERANCE=1e-8 NUM_STEPS=1000 @@ -40,7 +40,7 @@ MAXIMUM_FUNCTION_EVALUATIONS =200 # Initialize coils -init_curves = CreateEquallySpacedCurves(n_curves=N_COILS, +init_curves = create_equally_spaced_curves(n_curves=N_COILS, order=FOURIER_ORDER, R=LARGE_R, r=SMALL_R, n_segments=N_SEGMENTS, @@ -54,7 +54,7 @@ BAXIS_WEIGHT = 1.; BAXIS_TARGET = 5.7 RADIAL_DRIFT_WEIGHT = 1. -def loss_particle_radial_drift(field, particles, timestep=1.e-8, tmax=1e-5, n_save=300, rtol=1e-5, model='GuidingCenterAdaptative',boundary=None): +def loss_particle_radial_drift(field, particles, timestep=1.e-8, tmax=1e-5, n_save=300, rtol=1e-5, model='GuidingCenterAdaptive',boundary=None): particles.to_full_orbit(field) tracing = Tracing(field=field, model=model, particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, rtol=rtol,boundary=boundary) @@ -66,14 +66,14 @@ def loss_particle_radial_drift(field, particles, timestep=1.e-8, tmax=1e-5, n_sa v_r_cross=jnp.diff(r_cross,axis=1)#/tracing.n_save*tracing.tmax return (jnp.sum(jnp.square(jnp.average(v_r_cross,axis=1)))) -def normB_axis(field, npoints=15): +def norm_b_axis(field, npoints=15): R_axis=field.r_axis phi_array = jnp.linspace(0, 2 * jnp.pi, npoints) B_axis = vmap(lambda phi: field.AbsB(jnp.array([R_axis * jnp.cos(phi), R_axis * jnp.sin(phi), 0])))(phi_array) return B_axis -def loss_normB_axis_average(field,npoints=15, target_B=BAXIS_TARGET): - B_axis = normB_axis(field, npoints) +def loss_norm_b_axis_average(field,npoints=15, target_B=BAXIS_TARGET): + B_axis = norm_b_axis(field, npoints) return jnp.abs(jnp.average(B_axis)-target_B) def loss_length(field,length_target=LENGTH_TARGET): @@ -89,10 +89,10 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): """ Defining custom losses """ -L_radial_drift= custom_loss(loss_particle_radial_drift, "field", particles=particles, timestep=TIMESTEP, tmax=MAXTIME_TRACING, n_save=NUM_STEPS, rtol=TRACE_TOLERANCE, model=MODEL) -L_B_axis= custom_loss(loss_normB_axis_average, "field") -L_length = custom_loss(loss_length, "field") -L_curvature = custom_loss(loss_curvature, "field") +L_radial_drift= CustomLoss(loss_particle_radial_drift, "field", particles=particles, timestep=TIMESTEP, tmax=MAXTIME_TRACING, n_save=NUM_STEPS, rtol=TRACE_TOLERANCE, model=MODEL) +L_B_axis= CustomLoss(loss_norm_b_axis_average, "field") +L_length = CustomLoss(loss_length, "field") +L_curvature = CustomLoss(loss_curvature, "field") """ Defining total loss + setting dependencies """ L_total = RADIAL_DRIFT_WEIGHT*L_radial_drift + L_B_axis + LENGTH_WEIGHT*L_length + CURVATURE_WEIGHT*L_curvature diff --git a/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py b/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py index eb23f428..060e17e0 100644 --- a/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py +++ b/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py @@ -4,12 +4,12 @@ import jax.numpy as jnp import matplotlib.pyplot as plt from essos.dynamics import Particles, Tracing -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from jax import vmap, jit # In this exmple, `scipy.optimize.least_squares` is used, but any other optimizer, e.g. from # `scipy.optimize.minimize`, can be used as well and may even be preferable. from scipy.optimize import least_squares -from essos.losses import custom_loss +from essos.losses import CustomLoss from essos.fields import BiotSavart # Particle optimization parameters @@ -18,7 +18,7 @@ MAXTIME_TRACING = 1e-4 NUMBER_COILS_PER_HALF_FIELD_PERIOD = 3 NUMBER_OF_FIELD_PERIODS = 2 -MODEL = 'GuidingCenterAdaptative' +MODEL = 'GuidingCenterAdaptive' TIMESTEP=1.e-14 TRACE_TOLERANCE=1e-8 NUM_STEPS=1000 @@ -40,7 +40,7 @@ MAXIMUM_FUNCTION_EVALUATIONS =200 # Initialize coils -init_curves = CreateEquallySpacedCurves(n_curves=N_COILS, +init_curves = create_equally_spaced_curves(n_curves=N_COILS, order=FOURIER_ORDER, R=LARGE_R, r=SMALL_R, n_segments=N_SEGMENTS, @@ -57,7 +57,7 @@ BAXIS_WEIGHT = 1.; BAXIS_TARGET = 5.7 RADIAL_DRIFT_WEIGHT = 1. -def loss_particle_radial_drift(field, particles, timestep=1.e-8, tmax=1e-4, n_save=300, rtol=1e-5, model='GuidingCenterAdaptative',boundary=None): +def loss_particle_radial_drift(field, particles, timestep=1.e-8, tmax=1e-4, n_save=300, rtol=1e-5, model='GuidingCenterAdaptive',boundary=None): particles.to_full_orbit(field) tracing = Tracing(field=field, model=model, particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, rtol=rtol,boundary=boundary) @@ -68,14 +68,14 @@ def loss_particle_radial_drift(field, particles, timestep=1.e-8, tmax=1e-4, n_sa r_cross=jnp.sqrt(jnp.square(jnp.sqrt(jnp.square(xyz[:,:,0])+jnp.square(xyz[:,:,1]))-R_axis+1.e-12)+jnp.square(xyz[:,:,2]-Z_axis+1.e-12)) return jnp.average(r_cross[:,-1]) # Average radial end position of all particles at the end of the tracing, ideally this should be zero for perfect confinement -def normB_axis(field, npoints=15): +def norm_b_axis(field, npoints=15): R_axis=field.r_axis phi_array = jnp.linspace(0, 2 * jnp.pi, npoints) B_axis = vmap(lambda phi: field.AbsB(jnp.array([R_axis * jnp.cos(phi), R_axis * jnp.sin(phi), 0])))(phi_array) return B_axis -def loss_normB_axis_average(field,npoints=15, target_B=BAXIS_TARGET): - B_axis = normB_axis(field, npoints) +def loss_norm_b_axis_average(field,npoints=15, target_B=BAXIS_TARGET): + B_axis = norm_b_axis(field, npoints) return jnp.abs(jnp.average(B_axis)-target_B) def loss_length(field,length_target=LENGTH_TARGET): @@ -93,10 +93,10 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): """ Defining custom losses """ -L_radial_drift= custom_loss(loss_particle_radial_drift, "field", particles=particles, timestep=TIMESTEP, tmax=MAXTIME_TRACING, n_save=NUM_STEPS, rtol=TRACE_TOLERANCE, model=MODEL) -L_B_axis= custom_loss(loss_normB_axis_average, "field") -L_length = custom_loss(loss_length, "field") -L_curvature = custom_loss(loss_curvature, "field") +L_radial_drift= CustomLoss(loss_particle_radial_drift, "field", particles=particles, timestep=TIMESTEP, tmax=MAXTIME_TRACING, n_save=NUM_STEPS, rtol=TRACE_TOLERANCE, model=MODEL) +L_B_axis= CustomLoss(loss_norm_b_axis_average, "field") +L_length = CustomLoss(loss_length, "field") +L_curvature = CustomLoss(loss_curvature, "field") """ Defining total loss + setting dependencies """ L_total = RADIAL_DRIFT_WEIGHT*L_radial_drift + L_B_axis + LENGTH_WEIGHT*L_length + CURVATURE_WEIGHT*L_curvature diff --git a/examples/coil_optimization/optimize_coils_virtual_casing.py b/examples/coil_optimization/optimize_coils_virtual_casing.py index c04c9bdb..fa119fda 100644 --- a/examples/coil_optimization/optimize_coils_virtual_casing.py +++ b/examples/coil_optimization/optimize_coils_virtual_casing.py @@ -13,10 +13,10 @@ from vmex.core.wout import read_wout from vmex.core.virtual_casing import surface_field_data_from_wout -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart from essos.surfaces import SurfaceRZFourier -from essos.losses import custom_loss +from essos.losses import CustomLoss from essos.objective_functions import loss_coil_separation, loss_coil_surface_distance input_filepath = os.path.join(os.path.dirname(__file__), "..", "input_files") @@ -49,7 +49,7 @@ """ Creating starting coils and surface (initial current fitted to the target) """ surface = SurfaceRZFourier.from_wout_file(vmec_file, s=1, ntheta=NTHETA, nphi=NPHI, range_torus="half period") -init_curves = CreateEquallySpacedCurves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) +init_curves = create_equally_spaced_curves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) B_unit = jax.vmap(BiotSavart(Coils(init_curves, [1.] * N_COILS)).B)(points) COIL_CURRENT = float(jnp.vdot(B_unit, B_target) / jnp.vdot(B_unit, B_unit)) init_coils = Coils(curves=init_curves, currents=[COIL_CURRENT] * N_COILS) @@ -76,8 +76,8 @@ def report(label, field): f"lengths {jnp.round(field.coils.length[:N_COILS], 2)} m, max curvature {jnp.max(field.coils.curvature):.2f} 1/m") """ Defining total loss + setting dependencies """ -L_total = (FIELD_WEIGHT * custom_loss(loss_field, "field") + LENGTH_WEIGHT * custom_loss(loss_length, "field") - + CURVATURE_WEIGHT * custom_loss(loss_curvature, "field") + DISTANCE_WEIGHT * custom_loss(loss_distance, "field")) +L_total = (FIELD_WEIGHT * CustomLoss(loss_field, "field") + LENGTH_WEIGHT * CustomLoss(loss_length, "field") + + CURVATURE_WEIGHT * CustomLoss(loss_curvature, "field") + DISTANCE_WEIGHT * CustomLoss(loss_distance, "field")) L_total.dependencies = {"field": init_field} """ Optimizing the total loss """ diff --git a/examples/coil_optimization/optimize_coils_vmec_surface.py b/examples/coil_optimization/optimize_coils_vmec_surface.py index 0a18dd42..a37b68b5 100644 --- a/examples/coil_optimization/optimize_coils_vmec_surface.py +++ b/examples/coil_optimization/optimize_coils_vmec_surface.py @@ -3,10 +3,10 @@ import jax.numpy as jnp import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart -from essos.surfaces import SurfaceRZFourier, BdotN_over_B -from essos.losses import custom_loss +from essos.surfaces import SurfaceRZFourier, bdotn_over_b +from essos.losses import CustomLoss # In this exmple, `scipy.optimize.least_squares` is used, but any other optimizer, e.g. from # `scipy.optimize.minimize`, can be used as well and may even be preferable. @@ -19,7 +19,7 @@ N_COILS = 3; FOURIER_ORDER = 3; LARGE_R = 10; SMALL_R = 5.6; NFP = 2; N_SEGMENTS = 45; STELLSYM = True # Curve parameters COIL_CURRENT = 1. # Amperes (optimization does not depend on current magnitude) -init_curves = CreateEquallySpacedCurves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) +init_curves = create_equally_spaced_curves(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') @@ -31,7 +31,7 @@ """ Creating the loss functions """ def loss(field, surface): - return jnp.sum(jnp.abs(BdotN_over_B(surface, field))) + 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)) @@ -40,9 +40,9 @@ 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") +L_normal_field = CustomLoss(loss, "field", surface=surface) +L_length = CustomLoss(loss_length, "field") +L_curvature = CustomLoss(loss_curvature, "field") """ Defining total loss + setting dependencies """ L_total = NORMAL_FIELD_WEIGHT*L_normal_field + LENGTH_WEIGHT*L_length + CURVATURE_WEIGHT*L_curvature diff --git a/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_comparison.py b/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_comparison.py index 4758aa3f..6b66c540 100644 --- a/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_comparison.py +++ b/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_comparison.py @@ -4,10 +4,10 @@ import jax.numpy as jnp import matplotlib.pyplot as plt from essos.optimization import optimize_loss_function -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart -from essos.surfaces import SurfaceRZFourier, BdotN_over_B -from essos.losses import custom_loss, base_loss +from essos.surfaces import SurfaceRZFourier, bdotn_over_b +from essos.losses import CustomLoss, BaseLoss import essos.augmented_lagrangian as alm from functools import partial @@ -44,7 +44,7 @@ EXPORT = False -init_curves = CreateEquallySpacedCurves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) +init_curves = create_equally_spaced_curves(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) init_surface=surface @@ -52,12 +52,11 @@ """ Creating the loss functions """ def loss(field, surface): - return jnp.sum(jnp.abs(BdotN_over_B(surface, field))) + return jnp.sum(jnp.abs(bdotn_over_b(surface, field))) def BdotN_constraint(field,surface,target_tol=1.e-6): - bdotn_over_b = BdotN_over_B(surface, field) - bdotn_over_b_loss = jnp.sqrt(jnp.sum(jnp.maximum(jnp.square(bdotn_over_b)-target_tol,0.0))) - return bdotn_over_b_loss + ratio = bdotn_over_b(surface, field) + return jnp.sqrt(jnp.sum(jnp.maximum(jnp.square(ratio)-target_tol,0.0))) def loss_length_constraint(field): return jnp.maximum(0, field.coils.length - LENGTH_TARGET) @@ -74,12 +73,12 @@ def loss_curvature(field): """ Defining custom losses """ -L_normal_field = custom_loss(loss, "field", surface=surface) -L_normal_field_constraint = custom_loss(BdotN_constraint, "field", surface=surface) -L_length_constraint = custom_loss(loss_length_constraint, "field") -L_curvature_constraint = custom_loss(loss_curvature_contraint, "field") -L_length = custom_loss(loss_length, "field") -L_curvature = custom_loss(loss_curvature, "field") +L_normal_field = CustomLoss(loss, "field", surface=surface) +L_normal_field_constraint = CustomLoss(BdotN_constraint, "field", surface=surface) +L_length_constraint = CustomLoss(loss_length_constraint, "field") +L_curvature_constraint = CustomLoss(loss_curvature_contraint, "field") +L_length = CustomLoss(loss_length, "field") +L_curvature = CustomLoss(loss_curvature, "field") """ Defining total loss + setting dependencies """ L_normal_field.dependencies = {"field": init_field} @@ -99,7 +98,7 @@ def loss_curvature(field): sq_grad=0.0 #Initial square gradient parameter value for Mu adaptative model_lagrangian='Standard' #Use standard augmented lagragian suitable for bounded optimizers #Since we are using L-BFGS, model_mu will be updated with tolerances so we do not need to difinte the model -model_mu='Tolerance' +model_mu='MuTolerance' beta=2. #penalty update parameter @@ -134,7 +133,7 @@ def loss_curvature(field): #If loss=cost_function(x) is not prescribed, f(x)=0 is considered, uncomment second line to use B dot N as a loss and not a constraint -ALM=alm.ALM_model_lbfgs(constraints=C_Total_constraint,model_lagrangian=model_lagrangian,beta=beta,mu_max=mu_max,alpha=alpha,gamma=gamma,epsilon=epsilon,eta_tol=eta_tol,omega_tol=omega_tol) +ALM=alm.alm_model_lbfgs(constraints=C_Total_constraint,model_lagrangian=model_lagrangian,beta=beta,mu_max=mu_max,alpha=alpha,gamma=gamma,epsilon=epsilon,eta_tol=eta_tol,omega_tol=omega_tol) #Initializing lagrange multipliers lagrange_params=C_Total_constraint.init(init_field.dofs) @@ -182,9 +181,9 @@ def loss_curvature(field): print(f"\nOptimization took {t_end - t_start:.2f} seconds") -print("Initial B dot N:", jnp.max(BdotN_over_B(surface, init_field))) -print("B dot N after optimization:", jnp.max(BdotN_over_B(surface, opt_field))) -print("B dot N after optimization alm:", jnp.max(BdotN_over_B(surface, opt_field_alm))) +print("Initial B dot N:", jnp.max(bdotn_over_b(surface, init_field))) +print("B dot N after optimization:", jnp.max(bdotn_over_b(surface, opt_field))) +print("B dot N after optimization alm:", jnp.max(bdotn_over_b(surface, opt_field_alm))) print("Initial curvature :", jnp.average(init_field.coils.curvature,axis=0)) print("Curvature after optimization:",jnp.average(opt_field.coils.curvature,axis=0)) print("Curvature after optimization alm:",jnp.average(opt_field_alm.coils.curvature,axis=0)) diff --git a/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_stochastic.py b/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_stochastic.py index 34a6334c..83820313 100644 --- a/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_stochastic.py +++ b/examples/coil_optimization/optimize_coils_vmec_surface_augmented_lagrangian_stochastic.py @@ -11,10 +11,10 @@ perturb_curves_statistic, perturb_curves_systematic, ) -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart, Vmec -from essos.losses import custom_loss -from essos.surfaces import BdotN_over_B +from essos.losses import CustomLoss +from essos.surfaces import bdotn_over_b """ Creating stochastic field losses """ @@ -34,15 +34,15 @@ def perturbed_field_from_field(field, key, sampler): def loss_bdotn_stochastic(field, surface, sampler, keys): def perturbed_loss(key): perturbed_field = perturbed_field_from_field(field, key, sampler) - bdotn_over_b = BdotN_over_B(surface, perturbed_field) - return jnp.sum(jnp.abs(bdotn_over_b)) + ratio = bdotn_over_b(surface, perturbed_field) + return jnp.sum(jnp.abs(ratio)) return jnp.mean(jax.vmap(perturbed_loss)(keys)) def constraint_bdotn_stochastic(field, surface, sampler, keys, target_tol=1.0e-6): def perturbed_square(key): perturbed_field = perturbed_field_from_field(field, key, sampler) - return jnp.square(BdotN_over_B(surface, perturbed_field)) + return jnp.square(bdotn_over_b(surface, perturbed_field)) expected_square = jnp.mean(jax.vmap(perturbed_square)(keys), axis=0) return jnp.sqrt(jnp.sum(jnp.maximum(expected_square - target_tol, 0.0))) @@ -79,7 +79,7 @@ def loss_curvature_constraint(field, max_coil_curvature): number_of_field_periods = vmec.nfp major_radius_coils = vmec.r_axis minor_radius_coils = vmec.r_axis / 1.5 -curves = CreateEquallySpacedCurves(n_curves=N_COILS,order=FOURIER_ORDER, R=major_radius_coils, +curves = create_equally_spaced_curves(n_curves=N_COILS,order=FOURIER_ORDER, R=major_radius_coils, r=minor_radius_coils,n_segments=N_SEGMENTS, nfp=number_of_field_periods,stellsym=True) coils_initial = Coils(curves=curves,currents=[COIL_CURRENT] * N_COILS) field_initial = BiotSavart(coils_initial) @@ -93,10 +93,10 @@ def loss_curvature_constraint(field, max_coil_curvature): stochastic_keys = jnp.arange(N_samples) """ Defining custom losses """ -L_normal_field = custom_loss(loss_bdotn_stochastic, "field", surface=surface, sampler=sampler, keys=stochastic_keys) -L_normal_field_constraint = custom_loss(constraint_bdotn_stochastic, "field", surface=surface, sampler=sampler, keys=stochastic_keys, target_tol=BDOTN_TARGET_TOL) -L_length_constraint = custom_loss(loss_length_constraint, "field", max_coil_length=MAX_COIL_LENGTH) -L_curvature_constraint = custom_loss(loss_curvature_constraint, "field", max_coil_curvature=MAX_COIL_CURVATURE) +L_normal_field = CustomLoss(loss_bdotn_stochastic, "field", surface=surface, sampler=sampler, keys=stochastic_keys) +L_normal_field_constraint = CustomLoss(constraint_bdotn_stochastic, "field", surface=surface, sampler=sampler, keys=stochastic_keys, target_tol=BDOTN_TARGET_TOL) +L_length_constraint = CustomLoss(loss_length_constraint, "field", max_coil_length=MAX_COIL_LENGTH) +L_curvature_constraint = CustomLoss(loss_curvature_constraint, "field", max_coil_curvature=MAX_COIL_CURVATURE) """ Defining total loss + setting dependencies """ L_normal_field.dependencies = {"field": field_initial} @@ -132,7 +132,7 @@ def loss_curvature_constraint(field, max_coil_curvature): C_curvature_constraint.dependencies = {"field": field_initial} C_total_constraint.dependencies = {"field": field_initial} -ALM = alm.ALM_model_lbfgs(constraints=C_total_constraint, model_lagrangian=model_lagrangian, beta=beta, mu_max=mu_max, alpha=alpha, gamma=gamma, epsilon=epsilon, eta_tol=eta_tol, omega_tol=omega_tol) +ALM = alm.alm_model_lbfgs(constraints=C_total_constraint, model_lagrangian=model_lagrangian, beta=beta, mu_max=mu_max, alpha=alpha, gamma=gamma, epsilon=epsilon, eta_tol=eta_tol, omega_tol=omega_tol) """ Optimizing with alm """ lagrange_params = C_total_constraint.init(field_initial.dofs) @@ -153,8 +153,8 @@ def loss_curvature_constraint(field, max_coil_curvature): print(f"Stochastic optimization with ALM took {time() - time0:.2f} seconds") -BdotN_over_B_initial = BdotN_over_B(surface, field_initial) -BdotN_over_B_optimized = BdotN_over_B(surface, field_optimized) +BdotN_over_B_initial = bdotn_over_b(surface, field_initial) +BdotN_over_B_optimized = bdotn_over_b(surface, field_optimized) curvature = jnp.mean(field_optimized.coils.curvature, axis=1) length = jnp.max(jnp.ravel(field_optimized.coils.length)) stochastic_loss_initial = L_normal_field(L_normal_field.starting_dofs) @@ -162,12 +162,12 @@ def loss_curvature_constraint(field, max_coil_curvature): print("Mean curvature:", curvature) print("Length:", length) -print(f"Stochastic |BdotN/B| loss before optimization: {stochastic_loss_initial:.2e}") -print(f"Stochastic |BdotN/B| loss after optimization: {stochastic_loss_final:.2e}") -print(f"Maximum BdotN/B before optimization: {jnp.max(BdotN_over_B_initial):.2e}") -print(f"Maximum BdotN/B after optimization: {jnp.max(BdotN_over_B_optimized):.2e}") -print(f"Average BdotN/B before optimization: {jnp.average(jnp.abs(BdotN_over_B_initial)):.2e}") -print(f"Average BdotN/B after optimization: {jnp.average(jnp.abs(BdotN_over_B_optimized)):.2e}") +print(f"Stochastic |bdotn/B| loss before optimization: {stochastic_loss_initial:.2e}") +print(f"Stochastic |bdotn/B| loss after optimization: {stochastic_loss_final:.2e}") +print(f"Maximum bdotn/B before optimization: {jnp.max(BdotN_over_B_initial):.2e}") +print(f"Maximum bdotn/B after optimization: {jnp.max(BdotN_over_B_optimized):.2e}") +print(f"Average bdotn/B before optimization: {jnp.average(jnp.abs(BdotN_over_B_initial)):.2e}") +print(f"Average bdotn/B after optimization: {jnp.average(jnp.abs(BdotN_over_B_optimized)):.2e}") fig = plt.figure(figsize=(8, 4)) ax1 = fig.add_subplot(121, projection="3d") diff --git a/examples/coil_optimization/optimize_coils_vmec_surface_distance_forces.py b/examples/coil_optimization/optimize_coils_vmec_surface_distance_forces.py index ac7374a5..ed329bfb 100644 --- a/examples/coil_optimization/optimize_coils_vmec_surface_distance_forces.py +++ b/examples/coil_optimization/optimize_coils_vmec_surface_distance_forces.py @@ -3,10 +3,10 @@ import jax.numpy as jnp import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart -from essos.surfaces import SurfaceRZFourier, BdotN_over_B -from essos.losses import custom_loss +from essos.surfaces import SurfaceRZFourier, bdotn_over_b +from essos.losses import CustomLoss from essos.objective_functions import ( loss_coil_separation, loss_coil_surface_distance, @@ -25,7 +25,7 @@ N_COILS = 3; FOURIER_ORDER = 3; LARGE_R = 10; SMALL_R = 5.6; NFP = 2; N_SEGMENTS = 45; STELLSYM = True COIL_CURRENT = 1. -init_curves = CreateEquallySpacedCurves( +init_curves = create_equally_spaced_curves( 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) @@ -50,7 +50,7 @@ """ Creating the loss functions """ def loss(field, surface): - return jnp.sum(jnp.abs(BdotN_over_B(surface, field))) + return jnp.sum(jnp.abs(bdotn_over_b(surface, field))) def loss_surface_distance(field): @@ -94,11 +94,11 @@ def print_loss_costs(label, field): """ Defining custom losses """ -L_normal_field = custom_loss(loss, "field", surface=surface) -L_surface_distance = custom_loss(loss_surface_distance, "field") -L_coil_distance = custom_loss(loss_coil_distance, "field") -L_force = custom_loss(loss_force, "field") -L_linking = custom_loss(loss_linking, "field") +L_normal_field = CustomLoss(loss, "field", surface=surface) +L_surface_distance = CustomLoss(loss_surface_distance, "field") +L_coil_distance = CustomLoss(loss_coil_distance, "field") +L_force = CustomLoss(loss_force, "field") +L_linking = CustomLoss(loss_linking, "field") """ Defining total loss + setting dependencies """ L_total = ( diff --git a/examples/coil_optimization/optimize_multiple_objectives.py b/examples/coil_optimization/optimize_multiple_objectives.py index a9a54863..f1be80b2 100644 --- a/examples/coil_optimization/optimize_multiple_objectives.py +++ b/examples/coil_optimization/optimize_multiple_objectives.py @@ -3,15 +3,15 @@ import jax.numpy as jnp from essos.fields import BiotSavart from essos.fields import Vmec -from essos.surfaces import BdotN_over_B -from essos.objective_functions import loss_normB_axis_average, loss_coil_length, loss_coil_curvature, loss_bdotn +from essos.surfaces import bdotn_over_b +from essos.objective_functions import loss_norm_b_axis_average, loss_coil_length, loss_coil_curvature, loss_bdotn from essos.multiobjectiveoptimizer import MultiObjectiveOptimizer vmec = Vmec(os.path.join(os.path.dirname(__file__), "..", "input_files", "wout_LandremanPaul2021_QA_reactorScale_lowres.nc"), ntheta=32, nphi=32, range_torus='half period') # inputs manager = MultiObjectiveOptimizer( - loss_functions=(loss_bdotn, loss_coil_length, loss_coil_curvature, loss_normB_axis_average), + loss_functions=(loss_bdotn, loss_coil_length, loss_coil_curvature, loss_norm_b_axis_average), vmec=vmec, function_inputs={ "max_coil_length": 42, @@ -23,7 +23,7 @@ "tol": 1e-5, "optimizer_choices": ["adam", "amsgrad", "sgd"], "num_coils": 4, - "order_Fourier": 6, + "fourier_order": 6, } ) @@ -42,10 +42,10 @@ best_coils = manager.rebuild_best_coils(weights=weights, plot=True) print("--------Optax refinement completed!") -BdotN_over_B_initial = BdotN_over_B(vmec.surface, BiotSavart(manager.initial_coils)) -BdotN_over_B_optimized = BdotN_over_B(vmec.surface, BiotSavart(manager.best_coils)) -print(f"Maximum BdotN/B before optimization: {jnp.max(BdotN_over_B_initial):.2e}") -print(f"Maximum BdotN/B after optimization: {jnp.max(BdotN_over_B_optimized):.2e}") +BdotN_over_B_initial = bdotn_over_b(vmec.surface, BiotSavart(manager.initial_coils)) +BdotN_over_B_optimized = bdotn_over_b(vmec.surface, BiotSavart(manager.best_coils)) +print(f"Maximum bdotn/B before optimization: {jnp.max(BdotN_over_B_initial):.2e}") +print(f"Maximum bdotn/B after optimization: {jnp.max(BdotN_over_B_optimized):.2e}") diff --git a/examples/comparisons_simsopt/full_orbit.py b/examples/comparisons_simsopt/full_orbit.py index c36f9ee3..ea533f01 100644 --- a/examples/comparisons_simsopt/full_orbit.py +++ b/examples/comparisons_simsopt/full_orbit.py @@ -83,7 +83,7 @@ tmax=tmax, timestep=tmax/100, n_save=100, atol=rtol_array[0], rtol=rtol_array[0]) else: - compile_tracing = Tracing(field=field_essos, model='FullOrbit_Boris', particles=particles, + compile_tracing = Tracing(field=field_essos, model='FullOrbitBoris', particles=particles, tmax=tmax, timestep=tmax/100, n_save=100) block_until_ready(compile_tracing.trajectories) @@ -98,7 +98,7 @@ atol=rtol_ESSOS, rtol=rtol_ESSOS) else: num_steps_essos = int(avg_steps_SIMSOPT_array[tolerance_idx]*3) - tracing = Tracing(field=field_essos, model='FullOrbit_Boris', particles=particles, + tracing = Tracing(field=field_essos, model='FullOrbitBoris', particles=particles, tmax=tmax, timestep=tmax/num_steps_essos, n_save=num_steps_essos) block_until_ready(tracing.trajectories) diff --git a/examples/comparisons_simsopt/surfaces.py b/examples/comparisons_simsopt/surfaces.py index f422c5c0..52226e80 100644 --- a/examples/comparisons_simsopt/surfaces.py +++ b/examples/comparisons_simsopt/surfaces.py @@ -4,12 +4,12 @@ plt.rcParams.update({'font.size': 18}) import jax.numpy as jnp from jax import block_until_ready -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import Vmec, BiotSavart -from essos.surfaces import B_on_surface, BdotN_over_B, SurfaceRZFourier as SurfaceRZFourier_ESSOS, SquaredFlux as SquaredFlux_ESSOS +from essos.surfaces import b_on_surface, bdotn_over_b, SurfaceRZFourier as SurfaceRZFourier_ESSOS, squared_flux as SquaredFlux_ESSOS from simsopt.field import BiotSavart as BiotSavart_simsopt from simsopt.geo import SurfaceRZFourier as SurfaceRZFourier_SIMSOPT -from simsopt.objectives import SquaredFlux as SquaredFlux_SIMSOPT +from simsopt.objectives import squared_flux as SquaredFlux_SIMSOPT output_dir = os.path.join(os.path.dirname(__file__), '../output') if not os.path.exists(output_dir): @@ -17,7 +17,7 @@ # Optimization parameters max_coil_length = 42 -order_Fourier_series_coils = 4 +fourier_order = 4 number_coil_points = 50 function_evaluations_array = [30]*1 diff_step_array = [1e-2]*1 @@ -36,8 +36,8 @@ number_of_field_periods = vmec.nfp major_radius_coils = vmec.r_axis minor_radius_coils = vmec.r_axis/1.5 -curves_essos = CreateEquallySpacedCurves(n_curves=number_coils_per_half_field_period, - order=order_Fourier_series_coils, +curves_essos = create_equally_spaced_curves(n_curves=number_coils_per_half_field_period, + order=fourier_order, R=major_radius_coils, r=minor_radius_coils, n_segments=number_coil_points, nfp=number_of_field_periods, stellsym=True) @@ -118,7 +118,7 @@ print('B on surface') start_time = time() -B_on_surface_essos = block_until_ready(B_on_surface(surface_essos, field_essos)) +B_on_surface_essos = block_until_ready(b_on_surface(surface_essos, field_essos)) t_B_on_surface_essos = time() - start_time start_time = time() diff --git a/examples/fieldline_tracing/poincare_guiding_center_coils.py b/examples/fieldline_tracing/poincare_guiding_center_coils.py index 83adfb26..d39bca97 100644 --- a/examples/fieldline_tracing/poincare_guiding_center_coils.py +++ b/examples/fieldline_tracing/poincare_guiding_center_coils.py @@ -36,7 +36,7 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, +tracing = Tracing(field=field, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, n_save=n_save, rtol=rtol) print(f"ESSOS tracing took {time()-time0:.2f} seconds") diff --git a/examples/fieldline_tracing/trace_fieldlines_coils.py b/examples/fieldline_tracing/trace_fieldlines_coils.py index 6c7cf416..701d1c48 100644 --- a/examples/fieldline_tracing/trace_fieldlines_coils.py +++ b/examples/fieldline_tracing/trace_fieldlines_coils.py @@ -27,7 +27,7 @@ # Trace in ESSOS time0 = time() -tracing = block_until_ready(Tracing(field=field, model='FieldLineAdaptative', initial_conditions=initial_xyz, +tracing = block_until_ready(Tracing(field=field, model='FieldLineAdaptive', initial_conditions=initial_xyz, tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing took {time()-time0:.2f} seconds") trajectories = tracing.trajectories diff --git a/examples/fieldline_tracing/trace_fieldlines_vmec.py b/examples/fieldline_tracing/trace_fieldlines_vmec.py index 02354199..5f753537 100644 --- a/examples/fieldline_tracing/trace_fieldlines_vmec.py +++ b/examples/fieldline_tracing/trace_fieldlines_vmec.py @@ -25,7 +25,7 @@ # Trace in ESSOS time0 = time() -tracing = block_until_ready(Tracing(field=vmec, model='FieldLineAdaptative', initial_conditions=initial_xyz, +tracing = block_until_ready(Tracing(field=vmec, model='FieldLineAdaptive', initial_conditions=initial_xyz, tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing took {time()-time0:.2f} seconds") trajectories = tracing.trajectories diff --git a/examples/input_files/ESSOS_biot_savart_LandremanPaulQA.json b/examples/input_files/ESSOS_biot_savart_LandremanPaulQA.json index 74b9abca..cf68fb54 100644 --- a/examples/input_files/ESSOS_biot_savart_LandremanPaulQA.json +++ b/examples/input_files/ESSOS_biot_savart_LandremanPaulQA.json @@ -1 +1,182 @@ -{"nfp": 2, "stellsym": true, "order": 5, "dofs_curves": [[[1.2342202093074022, -0.03062945905137559, 0.5859232396336616, -0.010453826682475369, 0.1807413644900858, 0.010524283264586053, -0.021175348387922132, 0.0051393040213452285, -0.025441174813357854, -0.008662235858813448, -0.009546342243353753], [0.22940878352487568, -0.18584333093424768, 0.13771853785494897, 0.11039833778016522, -0.014372204966377944, -0.03925464427392012, -0.001460015434476671, -0.013771456774234823, 0.03183330416809828, 0.0033851663114857376, -0.02301977707844521], [0.03462019954507091, 0.7776849956819668, -0.0045987237680771426, 0.1393689068648977, -0.059898740346820696, -0.037071793804959154, 0.03348836525136044, -0.03179947900814274, -0.009528934246173005, -0.012505654412082531, 0.0036547912728659817]], [[0.9882326369098944, -0.017125138515033757, 0.47248592653894833, 0.09415263846494398, 0.24805658301787445, 0.012478656328766836, -0.00825339351944372, -0.04338202335195167, -0.03283901748400876, -0.012783068290926397, 0.0009483557501863601], [0.5597250604721756, -0.11300669852454369, 0.4729318195953315, 0.04329555872934745, -0.025912809957839067, -0.00801903940993418, 0.005033441551533881, 0.005984482149246342, 0.003395650358859674, -0.0006785647471796169, 0.0035137657330705876], [0.1183741826321684, 0.6526522871030928, -0.08546440888936001, 0.12872030841185422, -0.06399461134209485, 0.008897597261852535, 0.016393591363414183, -0.005551475232563431, 0.024582673862440146, 0.007857160765996891, 0.02801113154496591]], [[0.6456062213465997, -0.026695072324189946, 0.2887688718846646, 0.18986190296430233, 0.18014284064858352, 0.0018632682673255488, -0.03817234422117952, -0.04702323227146416, 0.02294895737145391, -0.0013622023088461891, 0.015495436977844081], [0.8290949425164272, -0.04729467098454378, 0.6182436945259812, 0.07623726908452709, -0.0041675855189795205, -0.02318806621873853, 0.020983206803089818, -0.020581446964001028, -0.006579479768460712, 0.00041097344898501445, 0.010115876636966909], [0.08722314911342346, 0.6027800005898932, -0.03152665631968138, 0.09173977838975904, -0.036700422718936254, 0.016358063388399187, -0.00019255092311576947, 0.010660801629619035, 0.01793542492416056, 0.02149138764562687, 0.005974317080745912]], [[0.2198367022992294, -0.086161018440248, 0.09892081082879264, 0.20560696376050197, 0.05604993215569217, -0.04461662514177469, -0.0029859265578968805, 0.015488224306749128, 0.012282519560304284, -0.010566935703441938, -0.020583782081530798], [0.9557777030768178, -0.004704968398667282, 0.6896395868097475, -0.011144742279336376, 0.00992513930189489, -0.004723252611822423, 0.043494685367776065, 0.014501777121375221, -0.0031145869864486653, 0.0133022020529558, -0.024266306195855125], [0.046985899952392766, 0.5727367597186483, -0.02901578889948077, 0.08143655649218613, -0.0226572063250086, -0.007290254768090654, -0.013583236094360148, -0.011360347813184197, -0.01694307134295157, -0.02050154671659323, -0.02035458103402258]]], "n_segments": 75, "dofs_currents": [100000.0, 99999.99999158102, 99999.99999120792, 99999.9999904831]} \ No newline at end of file +{ + "nfp": 2, + "stellsym": true, + "order": 5, + "n_segments": 75, + "dofs_curves_raw": [ + [ + [ + 1.2342202093074022, + -0.03062945905137559, + 0.5859232396336616, + -0.010453826682475369, + 0.1807413644900858, + 0.010524283264586053, + -0.021175348387922132, + 0.0051393040213452285, + -0.025441174813357854, + -0.008662235858813448, + -0.009546342243353753 + ], + [ + 0.22940878352487568, + -0.18584333093424768, + 0.13771853785494897, + 0.11039833778016522, + -0.014372204966377944, + -0.03925464427392012, + -0.001460015434476671, + -0.013771456774234823, + 0.03183330416809828, + 0.0033851663114857376, + -0.02301977707844521 + ], + [ + 0.03462019954507091, + 0.7776849956819668, + -0.0045987237680771426, + 0.1393689068648977, + -0.059898740346820696, + -0.037071793804959154, + 0.03348836525136044, + -0.03179947900814274, + -0.009528934246173005, + -0.012505654412082531, + 0.0036547912728659817 + ] + ], + [ + [ + 0.9882326369098944, + -0.017125138515033757, + 0.47248592653894833, + 0.09415263846494398, + 0.24805658301787445, + 0.012478656328766836, + -0.00825339351944372, + -0.04338202335195167, + -0.03283901748400876, + -0.012783068290926397, + 0.0009483557501863601 + ], + [ + 0.5597250604721756, + -0.11300669852454369, + 0.4729318195953315, + 0.04329555872934745, + -0.025912809957839067, + -0.00801903940993418, + 0.005033441551533881, + 0.005984482149246342, + 0.003395650358859674, + -0.0006785647471796169, + 0.0035137657330705876 + ], + [ + 0.1183741826321684, + 0.6526522871030928, + -0.08546440888936001, + 0.12872030841185422, + -0.06399461134209485, + 0.008897597261852535, + 0.016393591363414183, + -0.005551475232563431, + 0.024582673862440146, + 0.007857160765996891, + 0.02801113154496591 + ] + ], + [ + [ + 0.6456062213465997, + -0.026695072324189946, + 0.2887688718846646, + 0.18986190296430233, + 0.18014284064858352, + 0.0018632682673255488, + -0.03817234422117952, + -0.04702323227146416, + 0.02294895737145391, + -0.0013622023088461891, + 0.015495436977844081 + ], + [ + 0.8290949425164272, + -0.04729467098454378, + 0.6182436945259812, + 0.07623726908452709, + -0.0041675855189795205, + -0.02318806621873853, + 0.020983206803089818, + -0.020581446964001028, + -0.006579479768460712, + 0.00041097344898501445, + 0.010115876636966909 + ], + [ + 0.08722314911342346, + 0.6027800005898932, + -0.03152665631968138, + 0.09173977838975904, + -0.036700422718936254, + 0.016358063388399187, + -0.00019255092311576947, + 0.010660801629619035, + 0.01793542492416056, + 0.02149138764562687, + 0.005974317080745912 + ] + ], + [ + [ + 0.2198367022992294, + -0.086161018440248, + 0.09892081082879264, + 0.20560696376050197, + 0.05604993215569217, + -0.04461662514177469, + -0.0029859265578968805, + 0.015488224306749128, + 0.012282519560304284, + -0.010566935703441938, + -0.020583782081530798 + ], + [ + 0.9557777030768178, + -0.004704968398667282, + 0.6896395868097475, + -0.011144742279336376, + 0.00992513930189489, + -0.004723252611822423, + 0.043494685367776065, + 0.014501777121375221, + -0.0031145869864486653, + 0.0133022020529558, + -0.024266306195855125 + ], + [ + 0.046985899952392766, + 0.5727367597186483, + -0.02901578889948077, + 0.08143655649218613, + -0.0226572063250086, + -0.007290254768090654, + -0.013583236094360148, + -0.011360347813184197, + -0.01694307134295157, + -0.02050154671659323, + -0.02035458103402258 + ] + ] + ], + "scaling_type": 2, + "scaling_factor": 0.0, + "scale_fixed": 1.0, + "dofs_currents_raw": [ + 100000.0, + 99999.99999158102, + 99999.99999120792, + 99999.9999904831 + ], + "currents_scale": 99999.99999331801 +} \ No newline at end of file diff --git a/examples/paper/fo_integrators.py b/examples/paper/fo_integrators.py index dd60dfcc..34bff0c6 100644 --- a/examples/paper/fo_integrators.py +++ b/examples/paper/fo_integrators.py @@ -64,7 +64,7 @@ for n_points_in_gyration in [10, 20, 50, 75, 100, 150, 200]: dt = 1/(n_points_in_gyration*cyclotron_frequency) time0 = time() - tracing = Tracing(field=field, model='FullOrbit_Boris', particles=particles, + tracing = Tracing(field=field, model='FullOrbitBoris', particles=particles, tmax=tmax, timestep=dt) block_until_ready(tracing.trajectories) tracing_times += [time() - time0] diff --git a/examples/paper/gc_integrators.py b/examples/paper/gc_integrators.py index 5ae79310..618e068a 100644 --- a/examples/paper/gc_integrators.py +++ b/examples/paper/gc_integrators.py @@ -51,7 +51,7 @@ tolerances = [1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16] for rtol in tolerances: time0 = time() - tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, + tracing = Tracing(field=field, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=1e-7, rtol=rtol, solver=solver_class()) diff --git a/examples/paper/gradients.py b/examples/paper/gradients.py index 1b946349..3731b978 100644 --- a/examples/paper/gradients.py +++ b/examples/paper/gradients.py @@ -5,11 +5,11 @@ import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 18}) -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import Vmec from essos.fields import BiotSavart -from essos.surfaces import BdotN -from essos.losses import custom_loss +from essos.surfaces import bdotn +from essos.losses import CustomLoss output_dir = os.path.join(os.path.dirname(__file__), 'output') if not os.path.exists(output_dir): @@ -30,15 +30,15 @@ LARGE_R = vmec.r_axis SMALL_R = vmec.r_axis/1.5 -curves = CreateEquallySpacedCurves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) +curves = create_equally_spaced_curves(N_COILS, FOURIER_ORDER, LARGE_R, SMALL_R, n_segments=N_SEGMENTS, nfp=NFP, stellsym=STELLSYM) coils = Coils(curves=curves, currents=[COIL_CURRENT]*N_COILS) field = BiotSavart(coils) """ Creating the loss functions """ def loss(field, surface): - return jnp.sum(jnp.abs(BdotN(surface, field))) + return jnp.sum(jnp.abs(bdotn(surface, field))) -Loss = custom_loss(loss, "field", surface=vmec.surface) +Loss = CustomLoss(loss, "field", surface=vmec.surface) Loss.dependencies = {"field": field} dofs = Loss.starting_dofs @@ -50,7 +50,7 @@ def loss(field, surface): t_start = timer() block_until_ready(Loss(dofs)) t_end = timer() -print(f"Loss took {t_end - t_start:.4f} seconds. Gradient would take {(t_end - t_start)*(coils.x.size +1):.4f} seconds") +print(f"Loss took {t_end - t_start:.4f} seconds. Gradient would take {(t_end - t_start)*(coils.dofs.size +1):.4f} seconds") t_start = timer() block_until_ready(Loss.grad(dofs)) diff --git a/examples/particle_tracing/trace_particles_boozer_vs_vmec.py b/examples/particle_tracing/trace_particles_boozer_vs_vmec.py index 09f5df91..407455e1 100644 --- a/examples/particle_tracing/trace_particles_boozer_vs_vmec.py +++ b/examples/particle_tracing/trace_particles_boozer_vs_vmec.py @@ -61,7 +61,7 @@ def run_time(function): # Trace in VMEC coordinates (adaptive guiding centre) particles = Particles(initial_xyz=jnp.array([s, theta, phi]).T, initial_vparallel_over_v=pitch, mass=ALPHA_PARTICLE_MASS, charge=ALPHA_PARTICLE_CHARGE, energy=FUSION_ALPHA_PARTICLE_ENERGY) -tracing, time_vmec = run_time(lambda: Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, +tracing, time_vmec = run_time(lambda: Tracing(field=vmec, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=1e-8, n_save=n_save, atol=1e-7, rtol=1e-7)) # Loss fractions with binomial errors, and wall times without compilation diff --git a/examples/particle_tracing/trace_particles_coils_fullorbit.py b/examples/particle_tracing/trace_particles_coils_fullorbit.py index 81b29b7c..bc74a5be 100644 --- a/examples/particle_tracing/trace_particles_coils_fullorbit.py +++ b/examples/particle_tracing/trace_particles_coils_fullorbit.py @@ -32,7 +32,7 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=field, model='FullOrbit_Boris', particles=particles, +tracing = Tracing(field=field, model='FullOrbitBoris', particles=particles, tmax=tmax, n_save=n_save,timestep=dt, rtol=rtol) print(f"ESSOS tracing took {time()-time0:.2f} seconds") trajectories = tracing.trajectories diff --git a/examples/particle_tracing/trace_particles_coils_guidingcenter.py b/examples/particle_tracing/trace_particles_coils_guidingcenter.py index f071590f..781f94fe 100644 --- a/examples/particle_tracing/trace_particles_coils_guidingcenter.py +++ b/examples/particle_tracing/trace_particles_coils_guidingcenter.py @@ -31,7 +31,7 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, +tracing = Tracing(field=field, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol) print(f"ESSOS tracing took {time()-time0:.2f} seconds") trajectories = tracing.trajectories diff --git a/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier.py b/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier.py index ea1abaf4..bee8f16e 100644 --- a/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier.py +++ b/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier.py @@ -10,7 +10,7 @@ from essos.coils import Coils from essos.constants import ALPHA_PARTICLE_MASS, ALPHA_PARTICLE_CHARGE, FUSION_ALPHA_PARTICLE_ENERGY,ONE_EV from essos.dynamics import Tracing, Particles -from essos.objective_functions import normB_axis +from essos.objective_functions import norm_b_axis # Input parameters tmax = 1.e-4 @@ -32,12 +32,12 @@ # field = BiotSavart(coils) #renormalize coisl to have B_target=5.7 on axis -B_axis_old=normB_axis(field,npoints=200) +B_axis_old=norm_b_axis(field,npoints=200) #print(jnp.average(B_axis_old)) B_target=5.7 coils.dofs_currents=coils.dofs_currents*B_target/jnp.average(B_axis_old) field=BiotSavart(coils) -#B_axis_new=normB_axis(field,npoints=200) +#B_axis_new=norm_b_axis(field,npoints=200) #print(jnp.average(B_axis_new)) # Load coils and field wout_file = os.path.join(os.path.dirname(__file__), '..', 'input_files','wout_QH_simple_scaled.nc') @@ -56,7 +56,7 @@ print(f"Initialization performed") # Trace in ESSOS time0 = time() -tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, +tracing = Tracing(field=field, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol,boundary=boundary) print(f"ESSOS tracing took {time()-time0:.2f} seconds") print(f"Final loss fraction: {tracing.loss_fractions[-1]*100:.2f}%") diff --git a/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier_scaled_currents.py b/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier_scaled_currents.py index 3b75b1c8..8e9602f5 100644 --- a/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier_scaled_currents.py +++ b/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier_scaled_currents.py @@ -10,7 +10,7 @@ from essos.coils import Coils from essos.constants import ALPHA_PARTICLE_MASS, ALPHA_PARTICLE_CHARGE, FUSION_ALPHA_PARTICLE_ENERGY,ONE_EV from essos.dynamics import Tracing, Particles -from essos.objective_functions import normB_axis +from essos.objective_functions import norm_b_axis # Input parameters tmax = 1.e-4 @@ -29,12 +29,12 @@ field = BiotSavart(coils) #renormalize coisl to have B_target=5.7 on axis -B_axis_old=normB_axis(field,npoints=200) +B_axis_old=norm_b_axis(field,npoints=200) #print(jnp.average(B_axis_old)) B_target=5.7 coils.dofs_currents=coils.dofs_currents*B_target/jnp.average(B_axis_old) field=BiotSavart(coils) -#B_axis_new=normB_axis(field,npoints=200) +#B_axis_new=norm_b_axis(field,npoints=200) #print(jnp.average(B_axis_new)) # Load coils and field wout_file = os.path.join(os.path.dirname(__file__), '..', 'input_files','wout_QH_simple_scaled.nc') @@ -52,7 +52,7 @@ print(f"Initialization performed") # Trace in ESSOS time0 = time() -tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, +tracing = Tracing(field=field, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol,boundary=boundary) print(f"ESSOS tracing took {time()-time0:.2f} seconds") print(f"Final loss fraction: {tracing.loss_fractions[-1]*100:.2f}%") diff --git a/examples/particle_tracing/trace_particles_interpolated_dipoles.py b/examples/particle_tracing/trace_particles_interpolated_dipoles.py index 5bc5a65f..fa598111 100644 --- a/examples/particle_tracing/trace_particles_interpolated_dipoles.py +++ b/examples/particle_tracing/trace_particles_interpolated_dipoles.py @@ -90,9 +90,9 @@ def tree_unflatten(cls, aux, children): traces = {} for name, f in (("direct", field), ("interpolated", interp)): time0 = time() - traces[name] = tracing = Tracing(field=f, model='GuidingCenterAdaptative', particles=particles, tmax=tmax, + traces[name] = tracing = Tracing(field=f, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, n_save=200, atol=1e-8, rtol=1e-8, - condition=lambda t, y, args, **kwargs: classifier.evaluate_xyz(y[:3])) + stopping_criteria=lambda t, y, args, **kwargs: classifier.evaluate_xyz(y[:3])) tracing.trajectories.block_until_ready() tracing.lost_times = tracing.loss_fraction(classifier)[2] print(f"GC tracing of {nparticles} particles, {name}: {time() - time0:.2f} s, " diff --git a/examples/particle_tracing/trace_particles_vmec.py b/examples/particle_tracing/trace_particles_vmec.py index 97557810..1699e351 100644 --- a/examples/particle_tracing/trace_particles_vmec.py +++ b/examples/particle_tracing/trace_particles_vmec.py @@ -34,7 +34,7 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, tmax=tmax, +tracing = Tracing(field=vmec, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol) print(f"ESSOS tracing of {nparticles} particles during {tmax}s took {time()-time0:.2f} seconds") print(f"Final loss fraction: {tracing.loss_fractions[-1]*100:.2f}%") diff --git a/examples/particle_tracing/trace_particles_vmec_Electric_field.py b/examples/particle_tracing/trace_particles_vmec_Electric_field.py index e78806bb..68b10a76 100644 --- a/examples/particle_tracing/trace_particles_vmec_Electric_field.py +++ b/examples/particle_tracing/trace_particles_vmec_Electric_field.py @@ -5,7 +5,7 @@ from essos.fields import Vmec from essos.constants import ALPHA_PARTICLE_MASS, ALPHA_PARTICLE_CHARGE, FUSION_ALPHA_PARTICLE_ENERGY from essos.dynamics import Tracing, Particles -from essos.electric_field import Electric_field_flux +from essos.electric_field import ElectricFieldFlux import numpy as np # Input parameters @@ -27,7 +27,7 @@ #Load electric field Er_file = os.path.join(os.path.dirname(__file__), "..", "input_files", "Er.h5") -Electric_field=Electric_field_flux(Er_filename=Er_file,vmec=vmec) +Electric_field=ElectricFieldFlux(Er_filename=Er_file,vmec=vmec) # Initialize particles Z0 = jnp.zeros(nparticles) @@ -38,7 +38,7 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, electric_field=Electric_field,model='GuidingCenterAdaptative', particles=particles, tmax=tmax, +tracing = Tracing(field=vmec, electric_field=Electric_field,model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol) print(f"ESSOS tracing of {nparticles} particles during {tmax}s took {time()-time0:.2f} seconds") print(f"Final loss fraction: {tracing.loss_fractions[-1]*100:.2f}%") diff --git a/examples/particle_tracing/trace_particles_vmec_classifier.py b/examples/particle_tracing/trace_particles_vmec_classifier.py index 88549474..004c7c05 100644 --- a/examples/particle_tracing/trace_particles_vmec_classifier.py +++ b/examples/particle_tracing/trace_particles_vmec_classifier.py @@ -35,7 +35,7 @@ charge=ALPHA_PARTICLE_CHARGE, energy=energy, field=vmec) # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, tmax=tmax, +tracing = Tracing(field=vmec, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol,boundary=boundary) print(f"ESSOS tracing of {nparticles} particles during {tmax}s took {time()-time0:.2f} seconds") print(f"Final loss fraction: {tracing.loss_fractions[-1]*100:.2f}%") diff --git a/examples/particle_tracing/trace_particles_vmec_to_wall.py b/examples/particle_tracing/trace_particles_vmec_to_wall.py index 4086da9a..73e6ea44 100644 --- a/examples/particle_tracing/trace_particles_vmec_to_wall.py +++ b/examples/particle_tracing/trace_particles_vmec_to_wall.py @@ -63,7 +63,7 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, tmax=tmax, timestep=timestep, +tracing = Tracing(field=vmec, model='GuidingCenterAdaptive', particles=particles, tmax=tmax, timestep=timestep, n_save=n_save, atol=atol, rtol=rtol, exterior_field=outside, wall=wall) print(f"ESSOS tracing of {nparticles} particles during {tmax}s took {time()-time0:.2f} seconds") crossed = np.isfinite(tracing.lcfs_times) diff --git a/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_adaptive.py similarity index 99% rename from examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py rename to examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_adaptive.py index d0789899..450f7dab 100644 --- a/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py +++ b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_adaptive.py @@ -72,7 +72,7 @@ time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuAdaptative', particles=particles, +tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuAdaptive', particles=particles, tmax=tmax, timestep=dt,n_save=n_save,species=species,tag_gc=0.) print(f"ESSOS tracing took {time()-time0:.2f} seconds") trajectories = tracing.trajectories diff --git a/examples/simple_examples/coils_from_BOOZ_XFORM.py b/examples/simple_examples/coils_from_BOOZ_XFORM.py index 8920f3f6..f80e161c 100644 --- a/examples/simple_examples/coils_from_BOOZ_XFORM.py +++ b/examples/simple_examples/coils_from_BOOZ_XFORM.py @@ -21,7 +21,7 @@ nfieldlines_per_core=1 rtol = 1e-9 n_save = 22000 -order_Fourier_coils = 4 +fourier_order = 4 current_on_each_coil = 2e8 refine_nphi_for_surface_plot = 4 radial_extension_of_the_surface = 0.0 @@ -114,7 +114,7 @@ coils_gamma[i, :, 2] = Z[:, i] time0 = time() -dofs, gamma_uni = fit_dofs_from_coils(coils_gamma[:ncoils], order=order_Fourier_coils, n_segments=ntheta, assume_uniform=True) +dofs, gamma_uni = fit_dofs_from_coils(coils_gamma[:ncoils], order=fourier_order, n_segments=ntheta, assume_uniform=True) curves = Curves(dofs=dofs, n_segments=ntheta, nfp=b.nfp, stellsym=True) coils = Coils(curves=curves, currents=[-current_on_each_coil]*(ncoils)) field_coils_DOFS = BiotSavart(coils) @@ -183,7 +183,7 @@ coils_gamma_phi[i, :, 2] = Z_phi[:, i] time0 = time() - dofs_phi, gamma_uni_phi = fit_dofs_from_coils(coils_gamma_phi[:ncoils], order=order_Fourier_coils, n_segments=ntheta, assume_uniform=True) + dofs_phi, gamma_uni_phi = fit_dofs_from_coils(coils_gamma_phi[:ncoils], order=fourier_order, n_segments=ntheta, assume_uniform=True) curves_phi = Curves(dofs=dofs_phi, n_segments=ntheta, nfp=b.nfp, stellsym=True) coils_phi = Coils(curves=curves_phi, currents=[-current_on_each_coil]*(ncoils)) field_coils_phi = BiotSavart(coils_phi) @@ -195,13 +195,13 @@ initial_xyz=jnp.array([R0*jnp.cos(phi0), R0*jnp.sin(phi0), Z0]).T time0 = time() -tracing_coils_DOFS = block_until_ready(Tracing(field=field_coils_DOFS, model='FieldLineAdaptative', initial_conditions=initial_xyz, +tracing_coils_DOFS = block_until_ready(Tracing(field=field_coils_DOFS, model='FieldLineAdaptive', initial_conditions=initial_xyz, tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing coils_DOFS took {time()-time0:.2f} seconds") trajectories_coils_DOFS = tracing_coils_DOFS.trajectories if plot_fieldlines_constant_phi: time0 = time() - tracing_coils_phi = block_until_ready(Tracing(field=field_coils_phi, model='FieldLineAdaptative', initial_conditions=initial_xyz, + tracing_coils_phi = block_until_ready(Tracing(field=field_coils_phi, model='FieldLineAdaptive', initial_conditions=initial_xyz, tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing coils_phi took {time()-time0:.2f} seconds") trajectories_coils_phi = tracing_coils_phi.trajectories diff --git a/examples/simple_examples/coils_from_nearaxis.py b/examples/simple_examples/coils_from_nearaxis.py index 8bceda83..83014ec2 100644 --- a/examples/simple_examples/coils_from_nearaxis.py +++ b/examples/simple_examples/coils_from_nearaxis.py @@ -3,7 +3,7 @@ import jax.numpy as jnp from jax import block_until_ready, vmap import matplotlib.pyplot as plt -from essos.fields import BiotSavart_from_gamma, BiotSavart +from essos.fields import BiotSavartFromGamma, BiotSavart from pyqsc_jax.near_axis import near_axis import plotly.graph_objects as go @@ -76,13 +76,13 @@ initial_xyz=jnp.array([R0*jnp.cos(phi0), R0*jnp.sin(phi0), Z0]).T if plot_coils_without_Fourier_fit: time0 = time() - field_coils_gamma = BiotSavart_from_gamma(coils_gamma, currents=current_on_each_coil*jnp.ones(len(coils_gamma))) - tracing_coils_gamma = block_until_ready(Tracing(field=field_coils_gamma, model='FieldLineAdaptative', initial_conditions=initial_xyz, + field_coils_gamma = BiotSavartFromGamma(coils_gamma, currents=current_on_each_coil*jnp.ones(len(coils_gamma))) + tracing_coils_gamma = block_until_ready(Tracing(field=field_coils_gamma, model='FieldLineAdaptive', initial_conditions=initial_xyz, tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing coils_gamma took {time()-time0:.2f} seconds") trajectories_coils_gamma = tracing_coils_gamma.trajectories time0 = time() -tracing_coils_DOFS = block_until_ready(Tracing(field=field_coils_DOFS, model='FieldLineAdaptative', initial_conditions=initial_xyz, +tracing_coils_DOFS = block_until_ready(Tracing(field=field_coils_DOFS, model='FieldLineAdaptive', initial_conditions=initial_xyz, tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing coils_DOFS took {time()-time0:.2f} seconds") trajectories_coils_DOFS = tracing_coils_DOFS.trajectories diff --git a/examples/simple_examples/combined_field_demo.py b/examples/simple_examples/combined_field_demo.py index 4612529d..c06004b6 100644 --- a/examples/simple_examples/combined_field_demo.py +++ b/examples/simple_examples/combined_field_demo.py @@ -1,5 +1,5 @@ import jax.numpy as jnp -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import CombinedField, BiotSavart @@ -7,12 +7,12 @@ number_coils_per_half_field_period = 4 major_radius_coils = 1.0 minor_radius_coils = 0.3 -order_Fourier_series_coils = 1 +fourier_order = 1 number_coil_points = 50 -curves = CreateEquallySpacedCurves( +curves = create_equally_spaced_curves( n_curves=number_coils_per_half_field_period, - order=order_Fourier_series_coils, + order=fourier_order, R=major_radius_coils, r=minor_radius_coils, n_segments=number_coil_points, nfp=number_of_field_periods, stellsym=True, diff --git a/examples/simple_examples/create_perturbed_coils.py b/examples/simple_examples/create_perturbed_coils.py index 1206f0db..8dcbbbe3 100644 --- a/examples/simple_examples/create_perturbed_coils.py +++ b/examples/simple_examples/create_perturbed_coils.py @@ -7,12 +7,12 @@ jax.config.update("jax_enable_x64", True) import jax.numpy as jnp import matplotlib.pyplot as plt -from essos.coils import Coils, CreateEquallySpacedCurves,Curves +from essos.coils import Coils, create_equally_spaced_curves,Curves from functools import partial from essos.coil_perturbation import GaussianSampler, perturb_curves # Coils parameters -order_Fourier_series_coils = 4 +fourier_order = 4 number_coil_points = 80 number_coils_per_half_field_period = 3 number_of_field_periods = 2 @@ -21,8 +21,8 @@ current_on_each_coil = 1.84e7 major_radius_coils = 7.75 minor_radius_coils = 4.45 -curves = CreateEquallySpacedCurves(n_curves=number_coils_per_half_field_period, - order=order_Fourier_series_coils, +curves = create_equally_spaced_curves(n_curves=number_coils_per_half_field_period, + order=fourier_order, R=major_radius_coils, r=minor_radius_coils, n_segments=number_coil_points, nfp=number_of_field_periods, stellsym=True) diff --git a/examples/simple_examples/create_stellarator_coils.py b/examples/simple_examples/create_stellarator_coils.py index 812fa8be..feb2c852 100644 --- a/examples/simple_examples/create_stellarator_coils.py +++ b/examples/simple_examples/create_stellarator_coils.py @@ -1,4 +1,4 @@ -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves # Initialize coils current_on_each_coil = 1e5 @@ -6,10 +6,10 @@ number_coils_per_half_field_period = 4 major_radius_coils = 1.0 minor_radius_coils = 0.3 -order_Fourier_series_coils = 1 +fourier_order = 1 number_coil_points = 50 -curves = CreateEquallySpacedCurves(n_curves=number_coils_per_half_field_period, - order=order_Fourier_series_coils, +curves = create_equally_spaced_curves(n_curves=number_coils_per_half_field_period, + order=fourier_order, R=major_radius_coils, r=minor_radius_coils, n_segments=number_coil_points, nfp=number_of_field_periods, stellsym=True) @@ -17,14 +17,14 @@ # Change the parameters of a given coil print("Coils before changing parameters:") -print(coils.x) +print(coils.dofs) -coils.x = coils.x.at[0].set(1.0) -coils.x = coils.x.at[1].set(0.4) -coils.x = coils.x.at[2].set(0.3) +coils.dofs = coils.dofs.at[0].set(1.0) +coils.dofs = coils.dofs.at[1].set(0.4) +coils.dofs = coils.dofs.at[2].set(0.3) print("Coils after changing parameters:") -print(coils.x) +print(coils.dofs) # Plot the result coils.plot() diff --git a/examples/simple_examples/get_derivatives_coils_particle_confinement_guidingcenter.py b/examples/simple_examples/get_derivatives_coils_particle_confinement_guidingcenter.py index baedacb7..2bc99f38 100644 --- a/examples/simple_examples/get_derivatives_coils_particle_confinement_guidingcenter.py +++ b/examples/simple_examples/get_derivatives_coils_particle_confinement_guidingcenter.py @@ -2,12 +2,12 @@ import os from jax import vmap import jax.numpy as jnp -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart -from essos.losses import custom_loss +from essos.losses import CustomLoss # Optimization parameters -order_Fourier_series_coils = 2 +fourier_order = 2 number_coil_points = 80 number_coils_per_half_field_period = 3 number_of_field_periods = 2 @@ -20,8 +20,8 @@ current_on_each_coil = 1.84e7 major_radius_coils = 7.75 minor_radius_coils = 4.45 -curves = CreateEquallySpacedCurves(n_curves=number_coils_per_half_field_period, - order=order_Fourier_series_coils, +curves = create_equally_spaced_curves(n_curves=number_coils_per_half_field_period, + order=fourier_order, R=major_radius_coils, r=minor_radius_coils, n_segments=number_coil_points, nfp=number_of_field_periods, stellsym=True) @@ -35,15 +35,15 @@ def loss_length(field): def loss_curvature(field): return jnp.mean(jnp.maximum(0, field.coils.curvature - CURVATURE_TARGET)) -def loss_normB_axis_average(field): +def loss_norm_b_axis_average(field): R_axis=field.r_axis phi_array = jnp.linspace(0, 2 * jnp.pi, 15) B_axis = vmap(lambda phi: field.AbsB(jnp.array([R_axis * jnp.cos(phi), R_axis * jnp.sin(phi), 0])))(phi_array) return jnp.mean(jnp.maximum(0, B_axis - AXIS_B_TARGET)) -curvature_loss = custom_loss(loss_curvature, "field") -length_loss = custom_loss(loss_length, "field") -Baxis_average_loss = custom_loss(loss_normB_axis_average, "field") +curvature_loss = CustomLoss(loss_curvature, "field") +length_loss = CustomLoss(loss_length, "field") +Baxis_average_loss = CustomLoss(loss_norm_b_axis_average, "field") total_loss = curvature_loss + length_loss + Baxis_average_loss total_loss.dependencies = {"field": field} diff --git a/tests/test_augmented_lagrangian.py b/tests/test_augmented_lagrangian.py index c337797e..0719ba31 100644 --- a/tests/test_augmented_lagrangian.py +++ b/tests/test_augmented_lagrangian.py @@ -15,7 +15,7 @@ penalty_average, BaseConstraint, ALM, - ALM_model_lbfgs, + alm_model_lbfgs, ) class TestAugmentedLagrangian(unittest.TestCase): @@ -161,13 +161,13 @@ def fun(x, y=0): return x + y - 2 # ---- ALM model tests ---- - def test_ALM_model_lbfgs_init_and_update(self): + def test_alm_model_lbfgs_init_and_update(self): def fun(x): return x - 1 constraint = eq(fun) main_params = jnp.array([6.0,2.0]) lagrange_params = constraint.init(main_params) params = main_params,lagrange_params - alm = ALM_model_lbfgs(constraint) + alm = alm_model_lbfgs(constraint) self.assertIsInstance(alm, ALM) state,grad,info = alm.init(params) alm.update(params, state,grad,info) @@ -178,7 +178,7 @@ def loss(x): constraint = ineq(h, model_lagrangian=model_lagrangian) main_params = jnp.array([0.0]) params = main_params, constraint.init(main_params) - alm = ALM_model_lbfgs( + alm = alm_model_lbfgs( constraint, loss=loss, model_lagrangian=model_lagrangian) state, grad, info = alm.init(params) for _ in range(iters): @@ -205,7 +205,7 @@ def test_ALM_lbfgsb_unbounded_by_default(self): constraint = eq(lambda x: x - 150.0) main_params = jnp.array([0.0]) params = main_params, constraint.init(main_params) - alm = ALM_model_lbfgs(constraint) + alm = alm_model_lbfgs(constraint) state, grad, info = alm.init(params) for _ in range(10): params, state, grad, info = alm.update(params, state, grad, info) @@ -215,7 +215,7 @@ def test_ALM_lbfgs_respects_bounds(self): # eq constraint x = 150 inside the box [0, 100] -> x at the upper bound constraint = eq(lambda x: x - 150.0) params = jnp.array([10.0]), constraint.init(jnp.array([10.0])) - alm = ALM_model_lbfgs(constraint, bounds=(0.0, 100.0)) + alm = alm_model_lbfgs(constraint, bounds=(0.0, 100.0)) state, grad, info = alm.init(params) for _ in range(5): params, state, grad, info = alm.update(params, state, grad, info) @@ -240,7 +240,7 @@ def test_alm_lbfgs_supports_infinite_and_fixed_bounds(bounds, start, target): constraint = eq(lambda x: x - target) x = jnp.asarray(start) params = x, constraint.init(x) - solver = ALM_model_lbfgs(constraint, bounds=bounds) + solver = alm_model_lbfgs(constraint, bounds=bounds) state, gradient, info = solver.init(params) for _ in range(10): params, state, gradient, info = solver.update(params, state, gradient, info) diff --git a/tests/test_background_species.py b/tests/test_background_species.py index b9f97e6e..b0231623 100644 --- a/tests/test_background_species.py +++ b/tests/test_background_species.py @@ -86,7 +86,7 @@ def test_deflection_rate_matches_rutherford_pitch_decay(mass, charge): def test_deflection_rate_matches_maxwellian_flow_decay(): - """NRL Lorentz flow rate, 4 sqrt(2pi)/3 n e^4 lnL / [(4pi eps0)^2 sqrt(m) T^1.5].""" + """NRL lorentz flow rate, 4 sqrt(2pi)/3 n e^4 lnL / [(4pi eps0)^2 sqrt(m) T^1.5].""" from scipy.special import roots_genlaguerre species = BackgroundSpecies(2, MASS.at[1].set(1e6), CHARGE, jnp.array([1e19, 1e19]), jnp.array([100., 1e-8])) diff --git a/tests/test_boozer.py b/tests/test_boozer.py index 3a45e36e..9f21c784 100644 --- a/tests/test_boozer.py +++ b/tests/test_boozer.py @@ -181,9 +181,9 @@ def test_nonfinite_step_is_reported_as_failed_not_confined(): assert np.isinf(out.energy_error[0]) with pytest.raises(RuntimeError, match="trajectories fail"): out.loss_fractions() - legacy = dataclasses.replace(out, failed_times=None) + without_times = dataclasses.replace(out, failed_times=None) with pytest.raises(RuntimeError, match="trajectories fail"): - legacy.loss_fractions() + without_times.loss_fractions() @pytest.mark.parametrize("method", ["rk4", "dopri5"]) diff --git a/tests/test_coils.py b/tests/test_coils.py index d8bac8dc..c10cd256 100644 --- a/tests/test_coils.py +++ b/tests/test_coils.py @@ -271,8 +271,8 @@ def physical_value(coefficients, currents): def test_coils_indexing_addition_and_exclusion(): - from essos.coils import CreateEquallySpacedCurves - coils = Coils(CreateEquallySpacedCurves(2, 2, 1.0, 0.3, 32, 2, True), jnp.array([1e5, 2e5])) + from essos.coils import create_equally_spaced_curves + coils = Coils(create_equally_spaced_curves(2, 2, 1.0, 0.3, 32, 2, True), jnp.array([1e5, 2e5])) one, part = coils[3], coils[1:5] np.testing.assert_allclose(one.gamma[0], coils.gamma[3], atol=1e-14) np.testing.assert_allclose(one.currents, coils.currents[3:4]) @@ -295,7 +295,7 @@ def test_discretized_coils_copy_and_json_round_trip(tmp_path): def test_zero_currents_give_finite_dofs(): - from essos.coils import CreateEquallySpacedCurves - curves = CreateEquallySpacedCurves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) + from essos.coils import create_equally_spaced_curves + curves = create_equally_spaced_curves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) coils = Coils(curves=curves, currents=[0.0, 0.0]) assert jnp.all(jnp.isfinite(coils.dofs)) and jnp.all(jnp.isfinite(coils.currents)) diff --git a/tests/test_collision_mu_drifts.py b/tests/test_collision_mu_drifts.py index 7f4cf14e..708b2612 100644 --- a/tests/test_collision_mu_drifts.py +++ b/tests/test_collision_mu_drifts.py @@ -14,8 +14,8 @@ from essos.background_species import JOULE_PER_EV, BackgroundSpecies, nu_D_ab, nu_par_ab, nu_s_ab from essos.constants import ELEMENTARY_CHARGE, PROTON_MASS, SPEED_OF_LIGHT -from essos.dynamics import (GuidingCenterCollisionsDiffusionMu, GuidingCenterCollisionsDriftMuIto, - GuidingCenterCollisionsDriftMuStratonovich) +from essos.dynamics import (guiding_center_collisions_diffusion_mu, guiding_center_collisions_drift_mu_ito, + guiding_center_collisions_drift_mu_stratonovich) B0 = 2.0 M = PROTON_MASS @@ -96,7 +96,7 @@ def _code(fn, z, species): def _code_sigma(z, species): state = jnp.concatenate([X0, z / _SCALE]) - out = GuidingCenterCollisionsDiffusionMu(0.0, state, (FIELD, PARTICLE, EFIELD, species, 1.0)) + out = guiding_center_collisions_diffusion_mu(0.0, state, (FIELD, PARTICLE, EFIELD, species, 1.0)) return out[3:, 3:] * _SCALE[:, None] @@ -119,7 +119,7 @@ def test_diffusion_matrix_matches_velocity_space_tensor(v, xi, T): def test_ito_drift_matches_divergence_of_diffusion_tensor(v, xi, T): species, z = _species(T), _z(v, xi) expected = _ito_reference(z, species) - np.testing.assert_allclose(_code(GuidingCenterCollisionsDriftMuIto, z, species), expected, + np.testing.assert_allclose(_code(guiding_center_collisions_drift_mu_ito, z, species), expected, rtol=1e-8, atol=1e-10 * np.abs(expected).max()) @@ -129,7 +129,7 @@ def test_stratonovich_drift_is_ito_minus_noise_induced_drift(v, xi, T): sigma = _code_sigma(z, species) dsigma = jax.jacfwd(_code_sigma)(z, species) # [i, k, j] = d sigma_ik / d z_j expected = _ito_reference(z, species) - 0.5 * jnp.einsum('jk,ikj->i', sigma, dsigma) - np.testing.assert_allclose(_code(GuidingCenterCollisionsDriftMuStratonovich, z, species), expected, + np.testing.assert_allclose(_code(guiding_center_collisions_drift_mu_stratonovich, z, species), expected, rtol=1e-7, atol=1e-9 * np.abs(expected).max()) @@ -146,7 +146,7 @@ def Df(z): sigma = _code_sigma(z, species) return sigma @ sigma.T / 2 * f(z) - advective = _code(GuidingCenterCollisionsDriftMuIto, z, species) * f(z) + advective = _code(guiding_center_collisions_drift_mu_ito, z, species) * f(z) flux = advective - jnp.einsum('ijj->i', jax.jacfwd(Df)(z)) np.testing.assert_allclose(flux, 0.0, atol=1e-8 * np.abs(advective).max()) @@ -155,7 +155,7 @@ def test_cold_background_speed_drift_is_slowing_down(): # T_b -> 0: energy diffusion vanishes and pitch scattering conserves speed, # so the Ito drift of v = |v| reduces to -nu_s v. species, z = _species(1e-2), _z(2e6, 0.4) - A = _code(GuidingCenterCollisionsDriftMuIto, z, species) + A = _code(guiding_center_collisions_drift_mu_ito, z, species) sigma = _code_sigma(z, species) def speed(z): diff --git a/tests/test_dynamics.py b/tests/test_dynamics.py index 70928396..3f43186c 100644 --- a/tests/test_dynamics.py +++ b/tests/test_dynamics.py @@ -7,11 +7,11 @@ import matplotlib.pyplot as plt from essos.constants import ALPHA_PARTICLE_MASS, ALPHA_PARTICLE_CHARGE, FUSION_ALPHA_PARTICLE_ENERGY,ELECTRON_MASS,PROTON_MASS from essos.dynamics import ( - FieldLine, - FieldLineArclength, - FieldLineToroidal, - GuidingCenter, - Lorentz, + field_line, + field_line_arclength, + field_line_toroidal, + guiding_center, + lorentz, Particles, Tracing, LevelsetStoppingCriterion, @@ -118,11 +118,11 @@ class ScaledField(MockField): def B_contravariant(self, points): return jnp.array([3.0, 4.0, 0.0]) - derivative = FieldLineArclength(0.0, jnp.zeros(3), ScaledField()) + derivative = field_line_arclength(0.0, jnp.zeros(3), ScaledField()) assert jnp.allclose(derivative, jnp.array([0.6, 0.8, 0.0])) tracing = Tracing( - field=ScaledField(), model="FieldLineArclength", + field=ScaledField(), model="FieldLineArcLength", initial_conditions=jnp.zeros((1, 3)), tmax=2.0, timestep=0.1, n_save=11) assert jnp.allclose( @@ -137,7 +137,7 @@ def B_contravariant(self, points): return jnp.array([3.0, 4.0, 0.0]) def end_x(x0): - tracing = Tracing(field=ScaledField(), model="FieldLineArclength", initial_conditions=x0, + tracing = Tracing(field=ScaledField(), model="FieldLineArcLength", initial_conditions=x0, tmax=2.0, timestep=0.1, n_save=11) return tracing.trajectories[0, -1, 0] @@ -152,7 +152,7 @@ def B_contravariant(self, points): def toroidal_angle_batch(self, points): return points[:, 2] - derivative = FieldLineToroidal(0.0, jnp.zeros(3), FluxField()) + derivative = field_line_toroidal(0.0, jnp.zeros(3), FluxField()) assert jnp.allclose(derivative, jnp.array([0.0, 0.5, 1.0])) tracing = Tracing( @@ -172,7 +172,7 @@ def B_contravariant(self, point): offsets = 2*jnp.pi*jnp.array([0., 10000.]) seeds = jnp.tile(jnp.array([.5, .2, .3]), (2, 1)).at[:, 1:].add(offsets[:, None]) tracing = Tracing(field=PeriodicField(), model="FieldLineToroidal", initial_conditions=seeds, - maxtime=20*jnp.pi, timestep=.1, times_to_trace=65, + tmax=20*jnp.pi, timestep=.1, n_save=65, rtol=1e-7, atol=atol, progress=False) theta = tracing.trajectories[:, :, 1] - offsets[:, None] # Exact first integral: theta + epsilon*sin(theta) - phi is constant. @@ -189,7 +189,7 @@ def _tolerance_controller(model, axis_regular, flag=False, atol=1e-8, size=4): tracing.initial_conditions = jnp.ones((1, size)) tracing.rtol, tracing.atol = 1e-7, atol tracing.timestep, tracing.solver = .1, None - tracing.ODE_term = diffrax.ODETerm(lambda t, y, args: jnp.ones_like(y)) + tracing.ode_term = diffrax.ODETerm(lambda t, y, args: jnp.ones_like(y)) return tracing, tracing._terms(None, flag=flag) @@ -198,7 +198,7 @@ def _tolerance_controller(model, axis_regular, flag=False, atol=1e-8, size=4): @pytest.mark.parametrize("atol", [1e-8, 0]) @pytest.mark.parametrize("size", [4, 5]) def test_vmec_controller_error_budget_is_independent_of_phi_and_theta_winding(flag, angle_name, atol, size): - tracing, (terms, solver, controller) = _tolerance_controller("GuidingCenterAdaptative", True, flag, atol, size) + tracing, (terms, solver, controller) = _tolerance_controller("GuidingCenterAdaptive", True, flag, atol, size) angle = 2 if angle_name == "phi" else size y = jnp.array([.5, .3, .2, .7] + ([.9] if size == 5 else []) + [.4] + ([0.] if flag else [])) error = jnp.zeros_like(y).at[angle].set(1e-5) @@ -220,7 +220,7 @@ def adapt(state): def test_angular_tolerance_change_preserves_cartesian_and_fixed_step_paths(monkeypatch): import diffrax - tracing, (_, _, controller) = _tolerance_controller("FullOrbitAdaptative", False) + tracing, (_, _, controller) = _tolerance_controller("FullOrbitAdaptive", False) assert controller.rtol is tracing.rtol and controller.atol is tracing.atol tracing.model, tracing._axis_regular = "GuidingCenter", True def unexpected(*args): @@ -244,7 +244,7 @@ def toroidal_angle_batch(self, points): FluxField(), jnp.zeros((1, 3)), toroidal_turns=0.5, n_save=11, rtol=1.0e-8, progress=False, label=None) - assert arclength.model == "FieldLineArclength" + assert arclength.model == "FieldLineArcLength" assert toroidal.model == "FieldLineToroidal" assert float(arclength.tmax) == pytest.approx(2.0) assert float(toroidal.tmax) == pytest.approx(float(jnp.pi)) @@ -319,19 +319,19 @@ def test_particles_initialization(particles): def test_guiding_center(field, particles,electric_field): initial_conditions = jnp.array([1.0, 0.0, 0.0, 1]) t = 0.0 - result = GuidingCenter(t, initial_conditions, (field, particles,electric_field)) + result = guiding_center(t, initial_conditions, (field, particles,electric_field)) assert result.shape == (4,) def test_lorentz(field, particles): initial_condition = jnp.array([1.0, 0.0, 0.0, 0.1, 0.1, 0.1]) t = 0.0 - result = Lorentz(t, initial_condition, (field, particles)) + result = lorentz(t, initial_condition, (field, particles)) assert result.shape == (6,) def test_field_line(field): initial_condition = jnp.array([1.0, 0.0, 0.0]) t = 0.0 - result = FieldLine(t, initial_condition, field) + result = field_line(t, initial_condition, field) assert result.shape == (3,) @@ -362,15 +362,15 @@ def flux_field(t, y, args): def test_vmec_axis_events_cover_every_guiding_center_stepper(): assert _VMEC_GUIDING_CENTER_MODELS == { "GuidingCenter", - "GuidingCenterAdaptative", + "GuidingCenterAdaptive", "GuidingCenterCollisions", "GuidingCenterCollisionsMuIto", "GuidingCenterCollisionsMuFixed", - "GuidingCenterCollisionsMuAdaptative", + "GuidingCenterCollisionsMuAdaptive", } assert "FullOrbit" not in _VMEC_GUIDING_CENTER_MODELS - assert "FullOrbitAdaptative" not in _VMEC_GUIDING_CENTER_MODELS - assert "FullOrbit_Boris" not in _VMEC_GUIDING_CENTER_MODELS + assert "FullOrbitAdaptive" not in _VMEC_GUIDING_CENTER_MODELS + assert "FullOrbitBoris" not in _VMEC_GUIDING_CENTER_MODELS def test_levelset_stopping_criterion_stops_and_fills_field_line(): @@ -380,7 +380,7 @@ def evaluate_xyz(self, xyz): criterion = LevelsetStoppingCriterion(PlaneClassifier(), maximum_distance=0.2) tracing = Tracing( - field=MockField(), model="FieldLineAdaptative", + field=MockField(), model="FieldLineAdaptive", initial_conditions=jnp.array([[1.0, 0.0, 0.0]]), tmax=1.0, timestep=0.01, n_save=21, stopping_criteria=criterion, @@ -442,9 +442,6 @@ def test_levelset_stopping_criterion_validates_inputs(): LevelsetStoppingCriterion(MockField(), maximum_distance=-0.1) with pytest.raises(TypeError, match="evaluate_xyz"): LevelsetStoppingCriterion(object()) - with pytest.raises(ValueError, match="condition or stopping_criteria"): - Tracing(field=MockField(), model="FieldLine", initial_conditions=jnp.ones((1, 3)), - condition=lambda *args: False, stopping_criteria=lambda *args: False) with pytest.raises(ValueError, match="callable criteria"): Tracing(field=MockField(), model="FieldLine", initial_conditions=jnp.ones((1, 3)), stopping_criteria=[]) @@ -466,10 +463,10 @@ def test_surface_classifier_signed_distance_for_circular_torus(): def test_vmec_fieldline_uses_the_lcfs_event(): tracing = Tracing( - field=MockVmec(), model="FieldLineArclength", + field=MockVmec(), model="FieldLineArcLength", initial_conditions=jnp.array([[0.5, 0.0, 0.0]]), tmax=0.01, timestep=0.001, n_save=3) - assert callable(tracing.condition) + assert callable(tracing.event) WOUT_QA = str(Path(__file__).resolve().parents[1] / "examples" / "input_files" @@ -510,7 +507,7 @@ def test_vmec_guiding_centers_cross_the_magnetic_axis(monkeypatch): """The orbit born at s = 1e-7 used to stop at once, at s <= axis_threshold = 1e-6.""" monkeypatch.delenv("ESSOS_PROGRESS") # default progress must not break the vmapped segment loop particles = _near_axis_particles() - tracing = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model="GuidingCenterAdaptative", + tracing = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model="GuidingCenterAdaptive", particles=particles, tmax=2e-5, timestep=1e-9, n_save=200, atol=1e-9, rtol=1e-9) s = tracing.trajectories[:, :, 0] @@ -522,17 +519,16 @@ def test_vmec_guiding_centers_cross_the_magnetic_axis(monkeypatch): assert jnp.abs(tracing.energy() / particles.energy - 1).max() < 1e-5 -def test_vmec_guiding_center_condition_sees_flux_coordinates(): - def below(t, y, args, **kwargs): - return y[0] < 5e-3 +def test_vmec_guiding_center_stopping_criteria_see_flux_coordinates(): + def above(t, y, args, **kwargs): + return y[0] - 5e-3 - tracing = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model="GuidingCenterAdaptative", + tracing = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model="GuidingCenterAdaptive", particles=_near_axis_particles(), tmax=2e-5, timestep=1e-9, n_save=200, - atol=1e-9, rtol=1e-9, condition=below) + atol=1e-9, rtol=1e-9, stopping_criteria=above) s = tracing.trajectories[:, :, 0] - stopped = ~jnp.isfinite(s[:, -1]) - assert stopped.all() - assert (jnp.where(jnp.isfinite(s), s, 1.0).min(axis=1) > 4e-3).all() + assert jnp.isfinite(s).all() and tracing.boundary_hits.any() + assert (s[:, -1] == s[:, -2]).all() # every orbit is held once it is outside s > 5e-3 @pytest.mark.parametrize("model", ["GuidingCenterCollisions", "GuidingCenterCollisionsMuFixed"]) @@ -574,7 +570,7 @@ def test_tracing_trace_adaptative(field, particles,electric_field): y = jnp.zeros(particles.nparticles) z = jnp.zeros(particles.nparticles) initial_conditions =jnp.array([x, y, z]).T - tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterAdaptative', particles=particles, n_save=200) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterAdaptive', particles=particles, n_save=200) trajectories = tracing.trace() assert trajectories.shape == (particles.nparticles, 200, 4) @@ -633,7 +629,7 @@ def test_tracing_trace_collisions_adaptative(field, particles,electric_field): n_array=jnp.array([n0,n0]) T_array=jnp.array([T0,T0]) species = BackgroundSpecies(number_species=number_species, mass_array=mass_array, charge_array=charge_array, n_array=n_array, T_array=T_array) - tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterCollisionsMuAdaptative', particles=particles, n_save=200,tmax=1.e-6,species=species) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterCollisionsMuAdaptive', particles=particles, n_save=200,tmax=1.e-6,species=species) trajectories = tracing.trace() assert species.mass.shape == (2,) assert species.charge.shape == (2,) @@ -710,8 +706,8 @@ def below_ceiling(t, y, args, **kwargs): @pytest.mark.skipif(sys.version_info < (3, 11), reason="needs diffrax>=0.7.1 (Python>=3.11)") def test_tracing_pytree_round_trip_and_jit(): - """Unflatten re-ran __init__ with times as n_save, passed both - condition and stopping_criteria, and dropped species and boundary.""" + """Unflatten re-ran __init__ with times as n_save and dropped + species, boundary and stopping_criteria.""" field = _UniformField((0., 0., 1.), magnitude=1e-3) particles = Particles([[1., 0., 0.]], [.5], field=field) species = BackgroundSpecies(1, jnp.array([1.]), jnp.array([1.]), jnp.array([1e18]), jnp.array([1e3])) @@ -723,7 +719,7 @@ def below_ceiling(t, y, args, **kwargs): leaves, treedef = jax.tree_util.tree_flatten(trace) rebuilt = jax.tree_util.tree_unflatten(treedef, leaves) assert rebuilt.species is species and rebuilt.n_save == 3 - assert rebuilt.stopping_criteria == trace.stopping_criteria and rebuilt.condition is trace.condition + assert rebuilt.stopping_criteria == trace.stopping_criteria and rebuilt.event is trace.event np.testing.assert_array_equal(rebuilt.times, trace.times) np.testing.assert_array_equal(rebuilt.trajectories, trace.trajectories) np.testing.assert_allclose(jax.jit(lambda tr: tr.energy())(trace), trace.energy(), rtol=1e-12) @@ -749,14 +745,14 @@ def sqrtg(self, x): def _mu_collision_setup(v, xi): from essos.constants import SPEED_OF_LIGHT - from essos.dynamics import Electric_field_zero + from essos.dynamics import ElectricFieldZero m = PROTON_MASS particles = type("P", (), {"mass": m, "charge": 1.602176634e-19})() species = BackgroundSpecies(1, jnp.array([1.]), jnp.array([1.]), jnp.array([1e20]), jnp.array([1e3])) scale = jnp.array([SPEED_OF_LIGHT, SPEED_OF_LIGHT**2 * m]) z = jnp.array([xi * v, m * v**2 * (1 - xi**2) / 4.0]) state = jnp.concatenate([jnp.array([1., 0., 0.]), z / scale]) - return state, scale, (_MuField(), particles, Electric_field_zero(), species, 1.0) + return state, scale, (_MuField(), particles, ElectricFieldZero(), species, 1.0) def _enable_x64(): @@ -769,15 +765,15 @@ def _enable_x64(): @pytest.mark.parametrize("xi", [0., .3, 1., -1.]) def test_zero_density_mu_collisions_have_zero_noise_and_collisionless_drift(xi): - from essos.dynamics import (GuidingCenterCollisionsDiffusionMu, - GuidingCenterCollisionsDriftMuIto, - GuidingCenterCollisionsDriftMuStratonovich) + from essos.dynamics import (guiding_center_collisions_diffusion_mu, + guiding_center_collisions_drift_mu_ito, + guiding_center_collisions_drift_mu_stratonovich) with _enable_x64()(): state, scale, args = _mu_collision_setup(1e5, xi) absent = BackgroundSpecies(1, jnp.array([1.]), jnp.array([1.]), jnp.array([0.]), jnp.array([1e3])) args = (*args[:3], absent, args[4]) - noise = lambda y: GuidingCenterCollisionsDiffusionMu(0., y, args) + noise = lambda y: guiding_center_collisions_diffusion_mu(0., y, args) sigma, tangent = jax.jvp(noise, (state,), (jnp.ones(5),)) np.testing.assert_array_equal(sigma, np.zeros((5, 5))) np.testing.assert_array_equal(tangent, np.zeros((5, 5))) @@ -786,7 +782,7 @@ def test_zero_density_mu_collisions_have_zero_noise_and_collisionless_drift(xi): np.testing.assert_array_equal(sigma, np.zeros((2, 5, 5))) np.testing.assert_array_equal(tangent, np.zeros((2, 5, 5))) expected = np.array([0., 0., state[3]*scale[0], 0., 0.]) - for drift in (GuidingCenterCollisionsDriftMuIto, GuidingCenterCollisionsDriftMuStratonovich): + for drift in (guiding_center_collisions_drift_mu_ito, guiding_center_collisions_drift_mu_stratonovich): np.testing.assert_allclose(drift(0., state, args), expected, rtol=1e-14, atol=1e-14) np.testing.assert_allclose(jax.vmap(lambda y: drift(0., y, args))(batch), np.stack([expected, expected]), rtol=1e-14, atol=1e-14) @@ -797,11 +793,11 @@ def test_mu_collision_noise_is_finite_and_matches_the_diffusion_tensor(v, xi): """The eigenvectors were 0/0 at xi = 0, and jnp.select returned zero noise when rounding put |xi| just above 1.""" enable_x64 = _enable_x64() - from essos.dynamics import GuidingCenterCollisionsDiffusionMu, GuidingCenterCollisionsDriftMuStratonovich + from essos.dynamics import guiding_center_collisions_diffusion_mu, guiding_center_collisions_drift_mu_stratonovich from essos.background_species import nu_D_ab, nu_par_ab with enable_x64(): state, scale, args = _mu_collision_setup(v, xi) - sigma = GuidingCenterCollisionsDiffusionMu(0., state, args)[3:, 3:] * scale[:, None] + sigma = guiding_center_collisions_diffusion_mu(0., state, args)[3:, 3:] * scale[:, None] m, species = args[1].mass, args[3] speed = jnp.sqrt((state[3] * scale[0])**2 + 4 * state[4] * scale[1] / m) nus = [f(m, args[1].charge, 0, speed, state[:3], species) for f in (nu_par_ab, nu_D_ab)] @@ -811,9 +807,9 @@ def test_mu_collision_noise_is_finite_and_matches_the_diffusion_tensor(v, xi): J = jnp.array([[0., 0., 1.], [m * vvec[0] / 2.0, 0., 0.]]) # d(vpar, mu)/dv D = J @ Dv @ J.T np.testing.assert_allclose(sigma @ sigma.T / 2, D, rtol=1e-9, atol=1e-12 * float(jnp.abs(D).max())) - assert jnp.all(jnp.isfinite(GuidingCenterCollisionsDriftMuStratonovich(0., state, args))) + assert jnp.all(jnp.isfinite(guiding_center_collisions_drift_mu_stratonovich(0., state, args))) # Milstein differentiates the noise; sqrt(mu) must not give an infinite slope at |xi| = 1 - assert jnp.all(jnp.isfinite(jax.jvp(lambda y: GuidingCenterCollisionsDiffusionMu(0., y, args), (state,), (jnp.ones(5),))[1])) + assert jnp.all(jnp.isfinite(jax.jvp(lambda y: guiding_center_collisions_diffusion_mu(0., y, args), (state,), (jnp.ones(5),))[1])) @pytest.mark.parametrize("v,xi", [(1e5, 0.3), (1e6, 0.3), (1e5, 1e-3), (1e6, 0.9)]) @@ -821,23 +817,23 @@ def test_mu_collision_stratonovich_correction_matches_noise_derivative(v, xi): """Stratonovich minus Ito drift is -1/2 sigma_jk d_j sigma_ik; the hand-coded derivatives disagreed with the noise at generic xi.""" enable_x64 = _enable_x64() - from essos.dynamics import (GuidingCenterCollisionsDiffusionMu, GuidingCenterCollisionsDriftMuIto, - GuidingCenterCollisionsDriftMuStratonovich) + from essos.dynamics import (guiding_center_collisions_diffusion_mu, guiding_center_collisions_drift_mu_ito, + guiding_center_collisions_drift_mu_stratonovich) with enable_x64(): state, scale, args = _mu_collision_setup(v, xi) z = state[3:] * scale def sigma(z): - return GuidingCenterCollisionsDiffusionMu(0., jnp.concatenate([state[:3], z / scale]), args)[3:, 3:] * scale[:, None] + return guiding_center_collisions_diffusion_mu(0., jnp.concatenate([state[:3], z / scale]), args)[3:, 3:] * scale[:, None] steps = 1e-4 * jnp.array([v, args[1].mass * v**2 / 4.0]) dsigma = jnp.stack([(sigma(z + e) - sigma(z - e)) / (2 * e.sum()) for e in jnp.diag(steps)], axis=-1) expected = -0.5 * jnp.einsum('jk,ikj->i', sigma(z), dsigma) - drift = (GuidingCenterCollisionsDriftMuStratonovich(0., state, args) - - GuidingCenterCollisionsDriftMuIto(0., state, args))[3:] * scale + drift = (guiding_center_collisions_drift_mu_stratonovich(0., state, args) + - guiding_center_collisions_drift_mu_ito(0., state, args))[3:] * scale np.testing.assert_allclose(drift, expected, rtol=1e-5, atol=1e-8 * float(jnp.abs(expected).max())) -def _legacy_positive_charge_start(field, xyz, vpar, total_speed, mass, charge, phase): +def _reference_positive_charge_start(field, xyz, vpar, total_speed, mass, charge, phase): """The pre-fix construction, correct for a positive charge and B not along z.""" b = field.B_contravariant(xyz) / jnp.linalg.norm(field.B_contravariant(xyz)) p2 = jnp.array([0.0, 0.0, 1.0]) @@ -871,11 +867,11 @@ def test_gc_to_fullorbit_recovers_the_guiding_center(charge_sign, direction, pha np.testing.assert_allclose(velocities @ b, vpar, rtol=1e-12) np.testing.assert_allclose(jnp.linalg.norm(velocities, axis=1), total_speed, rtol=1e-12) if charge_sign > 0 and abs(b[2]) < 0.9: - legacy = jnp.stack([ - _legacy_positive_charge_start(field, x, v, total_speed, mass, charge, phase) + reference = jnp.stack([ + _reference_positive_charge_start(field, x, v, total_speed, mass, charge, phase) for x, v in zip(centers, vpar) ]) - np.testing.assert_allclose(positions, legacy, rtol=0, atol=1e-13) + np.testing.assert_allclose(positions, reference, rtol=0, atol=1e-13) def test_particles_honours_the_full_orbit_phase_argument(): @@ -957,7 +953,7 @@ def _boris(tmax, timestep, n_save=None, stopping_criteria=None): initial_vxvyvz=jnp.asarray([[v_perp, 0.0, v_par]]), ) tracing = Tracing( - field=field, particles=particles, model="FullOrbit_Boris", tmax=tmax, + field=field, particles=particles, model="FullOrbitBoris", tmax=tmax, timestep=timestep, n_save=n_save, stopping_criteria=stopping_criteria, ) period = 2 * np.pi * mass / (charge * 1.0) @@ -1005,7 +1001,7 @@ def _edge_tracing(model, s0, n_save, **kwargs): def test_vmec_losses_are_counted_at_the_lcfs(): """Orbits born at s = 0.993 used to count as lost at t = 0 (r_max = 0.99).""" - tracing = _edge_tracing("GuidingCenterAdaptative", 0.993, 50, atol=1e-9, rtol=1e-9) + tracing = _edge_tracing("GuidingCenterAdaptive", 0.993, 50, atol=1e-9, rtol=1e-9) assert 0 < tracing.boundary_hits.sum() < 16 assert tracing.total_particles_lost == tracing.boundary_hits.sum() assert jnp.all((tracing.lost_times > 0) == tracing.boundary_hits) @@ -1028,10 +1024,10 @@ def test_vmec_lost_energies_come_from_the_last_finite_state(): def test_particle_batches_report_completed_particles_and_match_one_batch(capsys, monkeypatch): """Batches of 6 (the last one padded) give the orbits, events and losses of one batch.""" - whole = _edge_tracing("GuidingCenterAdaptative", 0.993, 50, atol=1e-9, rtol=1e-9) + whole = _edge_tracing("GuidingCenterAdaptive", 0.993, 50, atol=1e-9, rtol=1e-9) capsys.readouterr() monkeypatch.delenv("ESSOS_PROGRESS") - batched = _edge_tracing("GuidingCenterAdaptative", 0.993, 50, atol=1e-9, rtol=1e-9, + batched = _edge_tracing("GuidingCenterAdaptive", 0.993, 50, atol=1e-9, rtol=1e-9, particle_batch_size=6) progress = capsys.readouterr().err assert "Tracing particles" in progress and "16/16" in progress @@ -1048,13 +1044,13 @@ def test_particle_batches_report_completed_particles_and_match_one_batch(capsys, @pytest.mark.parametrize("batch_size", [0, -2, 1.5, True]) def test_particle_batch_size_is_validated(batch_size): with pytest.raises(ValueError, match="particle_batch_size"): - Tracing(field=MockField(), model="FieldLineAdaptative", initial_conditions=jnp.array([[1.0, 0.0, 0.0]]), + Tracing(field=MockField(), model="FieldLineAdaptive", initial_conditions=jnp.array([[1.0, 0.0, 0.0]]), tmax=1.0, timestep=0.01, particle_batch_size=batch_size) def test_particle_batches_are_bypassed_under_jit(): def final(y0, batch): - return Tracing(field=MockField(), model="FieldLineAdaptative", initial_conditions=y0, tmax=1.0, + return Tracing(field=MockField(), model="FieldLineAdaptive", initial_conditions=y0, tmax=1.0, timestep=0.01, n_save=3, particle_batch_size=batch).trajectories y0 = jnp.array([[1.0, 0.0, 0.0], [1.1, 0.0, 0.1], [0.9, 0.1, 0.0]]) np.testing.assert_allclose(jax.jit(final, static_argnums=1)(y0, 2), final(y0, None), rtol=1e-12) @@ -1062,24 +1058,24 @@ def final(y0, batch): def test_custom_loss_grad_through_adaptive_guiding_center_matches_finite_difference(): - # custom_loss jits its value and gradient, so Tracing.trace sees tracer + # CustomLoss jits its value and gradient, so Tracing.trace sees tracer # initial conditions and must not pull them back to the host. - from essos.coils import Coils, CreateEquallySpacedCurves + from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart - from essos.losses import custom_loss + from essos.losses import CustomLoss - curves = CreateEquallySpacedCurves(n_curves=2, order=1, R=1.0, r=0.4, n_segments=24, nfp=2, stellsym=True) + curves = create_equally_spaced_curves(n_curves=2, order=1, R=1.0, r=0.4, n_segments=24, nfp=2, stellsym=True) coils = Coils(curves=curves, currents=jnp.array([1e6, 1e6])) R0 = jnp.linspace(0.95, 1.05, 2) particles = Particles(initial_xyz=jnp.array([R0, 0 * R0, 0 * R0]).T) def final_position(field, particles): - tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, + tracing = Tracing(field=field, model="GuidingCenterAdaptive", particles=particles, tmax=1e-7, n_save=4, atol=1e-10, rtol=1e-10) xyz = tracing.trajectories[:, -1, :3] return jnp.sum(jnp.sqrt(xyz[:, 0]**2 + xyz[:, 1]**2)) + jnp.sum(xyz[:, 2]) - loss = custom_loss(final_position, "field", particles=particles) + loss = CustomLoss(final_position, "field", particles=particles) loss.dependencies = {"field": BiotSavart(coils)} dofs = loss.starting_dofs @@ -1102,20 +1098,20 @@ def test_vmec_guiding_centers_seeded_on_the_axis_leave_it(): particles = Particles(initial_xyz=jnp.array([[0.0, 0.0, 0.3], [0.0, 1.0, 1.0]]), initial_vparallel_over_v=jnp.array([0.9, -0.5]), mass=PROTON_MASS, charge=ELEMENTARY_CHARGE, energy=5e3 * ELEMENTARY_CHARGE) - tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, + tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=2e-5, timestep=1e-8, n_save=5) s = tracing.trajectories[:, :, 0] assert jnp.all(jnp.isfinite(s)) and jnp.all(s[:, -1] > 1e-8) -def _exterior_tracing(xyz, vpar_over_v, tmax, model="GuidingCenterAdaptative", wall_gap=0.05, **kwargs): +def _exterior_tracing(xyz, vpar_over_v, tmax, model="GuidingCenterAdaptive", wall_gap=0.05, **kwargs): """Alphas in the bundled reactor-scale QA; outside, its coils scaled to it (|B| agrees to 0.2% on the LCFS).""" from essos.coils import Coils, Curves vmec = Vmec(WOUT_QA, ntheta=8, nphi=8) qa = Coils.from_json(str(Path(WOUT_QA).parent / "ESSOS_biot_savart_LandremanPaulQA.json")) coils = Coils(Curves(qa.dofs_curves * 10.127, qa.curves.n_segments, qa.nfp, qa.stellsym), qa.dofs_currents_raw * -19.62 * 10.127) - options = dict(timestep=1e-9, atol=1e-8, rtol=1e-8) if model == "GuidingCenterAdaptative" else dict(timestep=2e-8) + options = dict(timestep=1e-9, atol=1e-8, rtol=1e-8) if model == "GuidingCenterAdaptive" else dict(timestep=2e-8) options.update(dict(exterior_field=coils, wall=lambda x: vmec.boundary_distance(x) + wall_gap), **kwargs) particles = Particles(initial_xyz=jnp.asarray(xyz), initial_vparallel_over_v=jnp.asarray(vpar_over_v)) return Tracing(field=vmec, model=model, particles=particles, tmax=tmax, n_save=40, **options) @@ -1138,7 +1134,7 @@ def test_wall_given_as_a_gap_or_a_surface(): def test_vmec_lcfs_crossings_are_exact(): - tracing = _edge_tracing("GuidingCenterAdaptative", 0.975, 50, atol=1e-9, rtol=1e-9) + tracing = _edge_tracing("GuidingCenterAdaptive", 0.975, 50, atol=1e-9, rtol=1e-9) crossed = jnp.isfinite(tracing.lcfs_times) assert crossed.any() and jnp.all(crossed == tracing.boundary_hits) assert jnp.all(tracing.status[crossed] == 1) and jnp.all(tracing.status[~crossed] == 0) @@ -1226,14 +1222,14 @@ def test_vmec_wall_trace_differentiates_in_both_modes_with_respect_to_launch_and def objective(s, params, adjoint=None): xyz = jnp.stack([s, jnp.array([2.2941, 0.6628, 1.0]), jnp.array([5.0876, 3.5216, 1.0])], 1) particles = Particles(initial_xyz=xyz, initial_vparallel_over_v=jnp.array([-0.9872, 0.5453, 0.3])) - tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, tmax=3e-6, timestep=1e-9, + tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=3e-6, timestep=1e-9, n_save=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(_toroidal_source, params), wall=0.05, max_returns=2, adjoint=adjoint) return 1e6 * (finite(tracing.wall_times) + finite(tracing.lcfs_times)) + finite(tracing.wall_positions[:, 2]) s, params = jnp.array([0.9732, 0.9821, 0.5]), jnp.array([60.0, 0.5]) ds, dparams = jnp.array([1.0, -0.5, 0.3]) * 1e-4, jnp.array([1.0, 0.05]) - tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", tmax=3e-6, timestep=1e-9, n_save=4, atol=1e-8, + tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", tmax=3e-6, timestep=1e-9, n_save=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(_toroidal_source, params), wall=0.05, max_returns=2, particles=Particles(initial_xyz=jnp.array([[0.9732, 2.2941, 5.0876], [0.9821, 0.6628, 3.5216], [0.5, 1.0, 1.0]]), initial_vparallel_over_v=jnp.array([-0.9872, 0.5453, 0.3]))) @@ -1258,7 +1254,7 @@ def test_vmec_launch_derivative_of_the_exit_time_is_dual_in_both_modes_for_an_or def exit_time(eps, adjoint=None): particles = Particles(initial_xyz=jnp.array([[0.9786 + 1e-3 * eps, 2.3925, 5.5137]]), initial_vparallel_over_v=jnp.array([0.1781]), mass=PROTON_MASS, charge=ELEMENTARY_CHARGE, energy=1e6 * ONE_EV) - return Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, maxtime=3.3e-6, timestep=1e-9, times_to_trace=2, + return Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=3.3e-6, timestep=1e-9, n_save=2, atol=1e-8, rtol=1e-8, adjoint=adjoint).lcfs_times[0] forward = jax.jvp(lambda eps: exit_time(eps, diffrax.ForwardMode()), (0.0,), (1.0,))[1] @@ -1277,8 +1273,8 @@ def test_vmec_non_finite_exterior_field_has_a_finite_masked_gradient_in_both_mod def objective(params, adjoint=None): particles = Particles(initial_xyz=jnp.asarray(STRIKING[0]), initial_vparallel_over_v=jnp.asarray(STRIKING[1])) - tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, maxtime=3e-6, timestep=1e-9, - times_to_trace=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(above, params), wall=0.05, + tracing = Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=3e-6, timestep=1e-9, + n_save=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(above, params), wall=0.05, adjoint=adjoint) assert tracing.failed.any() and not tracing.failed.all() return 1e6 * jnp.sum(jnp.where(jnp.isfinite(tracing.wall_times), tracing.wall_times, 0.0)) @@ -1307,7 +1303,7 @@ def objective(scale): **{**arrays, 'rmnc': arrays['rmnc'] * rows, 'zmns': arrays['zmns'] * rows}) particles = Particles(initial_xyz=jnp.array([[0.9732, 2.2941, 5.0876], [0.5, 1.0, 1.0]]), initial_vparallel_over_v=jnp.array([-0.9872, 0.3])) - tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, tmax=1e-6, timestep=1e-9, + tracing = Tracing(field=field, model="GuidingCenterAdaptive", particles=particles, tmax=1e-6, timestep=1e-9, n_save=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(_toroidal_source, jnp.array([60.0, 0.5])), wall=wall, max_returns=1) return jnp.sum(jnp.where(jnp.isfinite(tracing.trajectories_xyz), tracing.trajectories_xyz, 0.0)) @@ -1328,7 +1324,7 @@ def crossing_times(s): xyz = jnp.stack([s, jnp.full_like(s, 0.3), jnp.full_like(s, 0.2)], 1) particles = Particles(initial_xyz=xyz, initial_vparallel_over_v=pitch, mass=PROTON_MASS, charge=ELEMENTARY_CHARGE, energy=1e6 * ELEMENTARY_CHARGE) - return Tracing(field=vmec, model="GuidingCenterAdaptative", particles=particles, tmax=1e-4, timestep=1e-9, + return Tracing(field=vmec, model="GuidingCenterAdaptive", particles=particles, tmax=1e-4, timestep=1e-9, n_save=3, atol=1e-10, rtol=1e-10).lcfs_times objective = lambda s: jnp.sum(jnp.where(jnp.isfinite(t := crossing_times(s)), t, 0.0)) @@ -1349,26 +1345,26 @@ def test_exterior_arguments_are_validated(): def test_guiding_center_mu_matches_guiding_center(): - from essos.dynamics import GuidingCenterMu - from essos.electric_field import Electric_field_zero + from essos.dynamics import guiding_center_mu + from essos.electric_field import ElectricFieldZero field, particles = MockField(), Particles(jnp.array([[1.0, 0.0, 0.0]])) y = jnp.array([1.0, 0.2, 0.1, 3e6]) mu = (particles.energy - 0.5 * particles.mass * y[3]**2) / field.AbsB(y[:3]) - args = (field, particles, Electric_field_zero()) - assert jnp.allclose(GuidingCenterMu(0.0, jnp.append(y, mu), args)[:4], GuidingCenter(0.0, y, args)) - assert GuidingCenterMu(0.0, jnp.append(y, mu), args)[4] == 0.0 + args = (field, particles, ElectricFieldZero()) + assert jnp.allclose(guiding_center_mu(0.0, jnp.append(y, mu), args)[:4], guiding_center(0.0, y, args)) + assert guiding_center_mu(0.0, jnp.append(y, mu), args)[4] == 0.0 def test_full_orbit_collision_noise_is_parallel_plus_perpendicular(): """Velocity noise amplitude sqrt(2 D_par) v v^T/v^2 + sqrt(2 D_perp) (I - v v^T/v^2).""" - from essos.dynamics import LorentzCollisionsDiffusion + from essos.dynamics import lorentz_collisions_diffusion from essos.background_species import nu_D_ab, nu_par_ab field = _UniformField((0., 0., 1.), magnitude=1.) particles = Particles([[1., 0., 0.]], [.5], field=field) species = BackgroundSpecies(1, jnp.array([1.]), jnp.array([1.]), jnp.array([1e20]), jnp.array([1e3])) v = jnp.array([3e6, -1e6, 2e6]) - block = LorentzCollisionsDiffusion(0., jnp.concatenate([jnp.ones(3), v]), (field, particles, species))[3:, 3:] + block = lorentz_collisions_diffusion(0., jnp.concatenate([jnp.ones(3), v]), (field, particles, species))[3:, 3:] m, q, speed = particles.mass, particles.charge, jnp.linalg.norm(v) nu_D = nu_D_ab(m, q, 0, speed, jnp.ones(3), species) nu_par = nu_par_ab(m, q, 0, speed, jnp.ones(3), species) @@ -1385,10 +1381,10 @@ def test_collisional_guiding_center_v_perp_uses_speed_and_pitch(): def test_mu_collision_models_accept_coils_as_the_field(monkeypatch): - from essos.coils import Coils, CreateEquallySpacedCurves + from essos.coils import Coils, create_equally_spaced_curves from essos.constants import SPEED_OF_LIGHT from essos.fields import BiotSavart - coils = Coils(CreateEquallySpacedCurves(1, 1, 1.0, 0.4, 8, 1, False), [1e6]) + coils = Coils(create_equally_spaced_curves(1, 1, 1.0, 0.4, 8, 1, False), [1e6]) species = BackgroundSpecies(1, jnp.array([1.]), jnp.array([1.]), jnp.array([1e18]), jnp.array([1e3])) particles = Particles([[1.05, 0., 0.]], [.5]) monkeypatch.setattr(Tracing, "trace", lambda self: jnp.zeros((1, 2, 5))) # only the setup is tested @@ -1411,7 +1407,7 @@ def qa_coil_alphas(): @pytest.mark.parametrize("model, options, bound", [ - ("GuidingCenterAdaptative", {}, 1e-6), # default tolerance + ("GuidingCenterAdaptive", {}, 1e-6), # default tolerance ("GuidingCenter", {}, 1e-6), # default timestep ]) def test_default_tracing_conserves_energy(qa_coil_alphas, model, options, bound): @@ -1423,7 +1419,7 @@ def test_default_tracing_conserves_energy(qa_coil_alphas, model, options, bound) def test_truncated_tracing_warns(qa_coil_alphas): field, particles = qa_coil_alphas with pytest.warns(RuntimeWarning, match="did not finish"): - Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, tmax=1e-5, max_steps=20) + Tracing(field=field, model="GuidingCenterAdaptive", particles=particles, tmax=1e-5, max_steps=20) @pytest.mark.parametrize("method, steps, order", [ @@ -1447,7 +1443,7 @@ def test_full_orbit_magnetic_moment_is_an_adiabatic_invariant(qa_coil_alphas): field, particles = qa_coil_alphas cold = Particles(initial_xyz=particles.initial_xyz, initial_vparallel_over_v=particles.initial_vparallel_over_v, energy=40 * 1.602176634e-19, field=field) - tracing = Tracing(field=field, model="FullOrbitAdaptative", particles=cold, tmax=2e-5, n_save=400) + tracing = Tracing(field=field, model="FullOrbitAdaptive", particles=cold, tmax=2e-5, n_save=400) y = tracing.trajectories B = jax.vmap(jax.vmap(field.AbsB))(y[:, :, :3]) vpar = jnp.sum(y[:, :, 3:6] * jax.vmap(jax.vmap(field.B))(y[:, :, :3]), -1) / B @@ -1483,7 +1479,7 @@ def end(x0, energy=particles.energy): def adaptive_end(energy): launched = Particles(initial_xyz=particles.initial_xyz, energy=energy, initial_vparallel_over_v=particles.initial_vparallel_over_v) - tracing = Tracing(field=field, particles=launched, **{**kwargs, "model": "GuidingCenterAdaptative"}) + tracing = Tracing(field=field, particles=launched, **{**kwargs, "model": "GuidingCenterAdaptive"}) seen.append((tracing.timestep, tracing.max_steps)) return tracing.trajectories[0, -1, 0] @@ -1511,13 +1507,13 @@ class Sphere: def test_tracings_with_the_same_shapes_share_one_compiled_solve(): - from essos.coils import Coils, CreateEquallySpacedCurves + from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart from essos.constants import ONE_EV from essos.dynamics import _compiled_solver def trace(currents, shift): - coils = Coils(curves=CreateEquallySpacedCurves(n_curves=2, order=2, R=1.0, r=0.4, nfp=2, stellsym=True), currents=currents) + coils = Coils(curves=create_equally_spaced_curves(n_curves=2, order=2, R=1.0, r=0.4, nfp=2, stellsym=True), currents=currents) particles = Particles(initial_xyz=jnp.array([[1.1 + shift, 0., 0.], [1.2 + shift, 0., 0.]]), energy=1e3 * ONE_EV) return Tracing(field=BiotSavart(coils), model='GuidingCenter', particles=particles, tmax=1e-6, timestep=1e-8, n_save=10, progress=False).trajectories @@ -1543,8 +1539,8 @@ def test_vmec_tracings_share_one_compiled_solve(): lambda event, duration, **kw: compiles.append(event) if event.endswith('backend_compile_duration') else None) def trace(field): - return Tracing(field=field, model="GuidingCenterAdaptative", particles=_near_axis_particles(), maxtime=1e-7, - timestep=1e-9, times_to_trace=5, progress=False).trajectories + return Tracing(field=field, model="GuidingCenterAdaptive", particles=_near_axis_particles(), tmax=1e-7, + timestep=1e-9, n_save=5, progress=False).trajectories _compiled_solver.cache_clear() first = trace(vmec) @@ -1568,7 +1564,7 @@ def test_implicit_solver_guiding_center_trace(): field = BiotSavart(coils) particles = Particles(initial_xyz=jnp.array([[1.23, 0, 0]]), mass=PROTON_MASS, energy=5000 * ONE_EV, initial_vparallel_over_v=[0.8], field=field) - tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, tmax=1e-7, + tracing = Tracing(field=field, model='GuidingCenterAdaptive', particles=particles, tmax=1e-7, timestep=5e-8, n_save=2, atol=1e-4, rtol=1e-4, solver=diffrax.Kvaerno5()) assert tracing.trajectories.shape == (1, 2, 4) assert jnp.isfinite(tracing.trajectories).all() diff --git a/tests/test_fields.py b/tests/test_fields.py index 8a6ba6f9..aff36286 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -133,10 +133,10 @@ def AbsB_of_scale(scale): def test_combined_field_sums_correctly(): - from essos.coils import Coils, CreateEquallySpacedCurves + from essos.coils import Coils, create_equally_spaced_curves from essos.fields import CombinedField - curves = CreateEquallySpacedCurves(n_curves=2, order=1, R=1.0, r=0.3, + curves = create_equally_spaced_curves(n_curves=2, order=1, R=1.0, r=0.3, n_segments=20, nfp=2, stellsym=True) field = BiotSavart(Coils(curves=curves, currents=[1e5] * 2)) points = jnp.array([0.5, 0.5, 0.5]) @@ -327,10 +327,10 @@ def test_fused_guiding_center_quantities_match_the_separate_methods(): import jax import jax.numpy as jnp import numpy as np - from essos.coils import Coils, CreateEquallySpacedCurves + from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart, MagneticField - curves = CreateEquallySpacedCurves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) + curves = create_equally_spaced_curves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) field = BiotSavart(Coils(curves=curves, currents=[1.1e6, 0.9e6])) rng = np.random.default_rng(4) points = jnp.asarray(rng.normal(scale=0.2, size=(6, 3)) + np.array([1.7, 0.1, 0.05])) @@ -762,10 +762,10 @@ def test_external_field_params_are_differentiable_and_share_one_compile(): def test_combined_field_fused_gc_quantities_match_generic_path(): import jax import jax.numpy as jnp - from essos.coils import Coils, CreateEquallySpacedCurves + from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart, CombinedField, ExternalField, MagneticField - curves = CreateEquallySpacedCurves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) + curves = create_equally_spaced_curves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) bs = BiotSavart(Coils(curves=curves, currents=[1.1e6, 0.9e6])) ext = ExternalField(lambda xyz: 0.01 * jnp.stack([-xyz[:, 1], xyz[:, 0], xyz[:, 2] ** 2], axis=-1)) x = jnp.array([1.7, 0.1, 0.05]) diff --git a/tests/test_interpolated_field.py b/tests/test_interpolated_field.py index 1d7b1a49..ef77cdf9 100644 --- a/tests/test_interpolated_field.py +++ b/tests/test_interpolated_field.py @@ -3,7 +3,7 @@ import numpy as np import pytest from jax import vmap -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.dynamics import Particles, Tracing from essos.fields import BiotSavart, InterpolatedField, MagneticField @@ -12,7 +12,7 @@ @pytest.fixture(scope="module") def field(): - curves = CreateEquallySpacedCurves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) + curves = create_equally_spaced_curves(n_curves=2, order=2, R=1.7, r=0.6, nfp=2, stellsym=True) return BiotSavart(Coils(curves=curves, currents=[1.1e6, 0.9e6])) @@ -64,7 +64,7 @@ def test_pytree_grad_and_tracing(field): # births committed to one device while the orbits are split over several births = jax.device_put(jnp.array([[1.75, 0.0, 0.0], [1.8, 0.0, 0.0]]), jax.devices()[0]) particles = Particles(initial_xyz=births, energy=3.5e6 * 1.602e-19 / 100) - runs = [Tracing(field=g, model="GuidingCenterAdaptative", particles=particles, tmax=2e-6, n_save=20, + runs = [Tracing(field=g, model="GuidingCenterAdaptive", particles=particles, tmax=2e-6, n_save=20, atol=1e-9, rtol=1e-9, devices=jax.devices()[:2]) for g in (field, f)] np.testing.assert_allclose(runs[1].trajectories[..., :3], runs[0].trajectories[..., :3], atol=1e-4) assert jnp.abs(runs[1].energy() / particles.energy - 1).max() < 1e-6 diff --git a/tests/test_mgrid.py b/tests/test_mgrid.py index eacf796a..0ef056a2 100644 --- a/tests/test_mgrid.py +++ b/tests/test_mgrid.py @@ -9,7 +9,7 @@ from netCDF4 import Dataset import essos.mgrid as mgrid_module -from essos.coils import Coils, CreateEquallySpacedCurves +from essos.coils import Coils, create_equally_spaced_curves from essos.fields import BiotSavart from essos.mgrid import MGrid, coils_to_mgrid @@ -54,7 +54,7 @@ def test_mgrid_write_read_roundtrip(tmp_path): def test_coils_to_mgrid_writes_expected_shape_and_finite_values(tmp_path, monkeypatch): # Keep JIT compilation independent of the cache populated by earlier tests. jax.clear_caches() - coils = CreateEquallySpacedCurves(1, order=1, R=1.0, r=0.2, n_segments=32, nfp=1, stellsym=False) + coils = create_equally_spaced_curves(1, order=1, R=1.0, r=0.2, n_segments=32, nfp=1, stellsym=False) coil_set = Coils(coils, jnp.asarray([2.0])) monkeypatch.setattr(mgrid_module, "_BIOT_SAVART_PAIR_BUDGET", 32 * 31) filename = tmp_path / "mgrid.coils.nc" diff --git a/tests/test_multiobjectives.py b/tests/test_multiobjectives.py index be51c28a..2a52e053 100644 --- a/tests/test_multiobjectives.py +++ b/tests/test_multiobjectives.py @@ -1,13 +1,10 @@ import pytest import numpy as np from unittest.mock import MagicMock, patch -import essos.objective_functions as objf -from essos.losses import custom_loss +from essos.losses import CustomLoss from essos.multiobjectiveoptimizer import MultiObjectiveOptimizer from essos.coils import Coils,Curves from essos.fields import BiotSavart -from essos.objective_functions import loss_coil_length, loss_coil_curvature -from essos.surfaces import BdotN_over_B # test_multiobjectiveoptimizer.py @@ -40,7 +37,7 @@ def test_custom_loss_named_unraveler(): def loss_fn(curve_dofs, current): return jnp.sum(curve_dofs**2) + jnp.sum(current) - loss = custom_loss(loss_fn, "curve_dofs", "current") + loss = CustomLoss(loss_fn, "curve_dofs", "current") loss.dependencies = { "curve_dofs": jnp.array([[1.0, 2.0], [3.0, 4.0]]), "current": jnp.array([5.0]), @@ -71,59 +68,6 @@ def loss_fn(curve_dofs, current): assert jnp.array_equal(gradient_tuple["unused"], gradient["unused"]) -@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( - loss_functions=[dummy_loss_fn], - vmec=vmec, - coils_init=None, - function_inputs={"extra": 42}, - opt_config={"order_Fourier": 2, "num_coils": 2} - ) - x = jnp.arange(32, dtype=float) - - result = optimizer._build_available_inputs(x) - - - expected_keys = { - "field", "coils", "vmec", "surface", "x", "dofs_curves", "currents_scale", "nfp", "extra" - } - assert expected_keys.issubset(result.keys()) - assert isinstance(result["x"], jnp.ndarray) - assert result["vmec"] is vmec - assert result["surface"] is vmec.surface - assert result["currents_scale"] == 1.0 - assert result["nfp"] == 2 - assert result["extra"] == 42 - assert result["dofs_curves"].shape == (2, 3,5) - - weights=jnp.array([1.0]) - loss_result=optimizer._call_loss_fn(dummy_loss_fn,result) - assert loss_result.shape == () - assert loss_result == 496 - loss_weight_result=optimizer.weighted_loss( x, weights) - assert loss_weight_result.shape == () - assert loss_weight_result == 496 - - optimized_coils=optimizer.optimize_with_optax(weights, method="adam", lr=1e-2) - assert optimized_coils.currents_scale==0.01999998979999997872 - - dofs_curves=optimized_coils.dofs_curves - currents_scale=optimized_coils.currents_scale - nfp=optimized_coils.nfp - n_segments=optimized_coils.n_segments - stellsym=optimized_coils.stellsym - x=optimized_coils.x - bdotn_b=objf.loss_bdotn_over_b(x,vmec=vmec,dofs_curves=dofs_curves, currents_scale=currents_scale, nfp=nfp, n_segments=n_segments, stellsym=stellsym) - #assert bdotn_b==0.0000000000000037761977058799732810080238 - - max_length=loss_coil_length(x,dofs_curves=dofs_curves, currents_scale=currents_scale, nfp=nfp, n_segments=n_segments, stellsym=stellsym) - max_curvature=loss_coil_curvature(x,dofs_curves=dofs_curves, currents_scale=currents_scale, nfp=nfp, n_segments=n_segments, stellsym=stellsym) - normB_axis=objf.loss_normB_axis(x,dofs_curves=dofs_curves, currents_scale=currents_scale, nfp=nfp, n_segments=n_segments, stellsym=stellsym) - - optimizer.run() - - def test_weighted_loss_then_jitted_loss_keeps_static_currents_scale(): # Regression: coils rebuilt inside the jitted weighted_loss used to recompute # currents_scale as a tracer, which then leaked into later jitted losses. @@ -137,9 +81,9 @@ def loss_coil_length_sum(coils): optimizer = MultiObjectiveOptimizer( loss_functions=[loss_coil_length_sum], vmec=mock_vmec(), - opt_config={"order_Fourier": 2, "num_coils": 2}, + opt_config={"fourier_order": 2, "num_coils": 2}, ) - x = optimizer.initial_coils.x + x = optimizer.initial_coils.dofs weighted = optimizer.weighted_loss(x, [1.0]) jax.grad(lambda y: optimizer.weighted_loss(y, [1.0]))(x) direct = optimizer._call_loss_fn(loss_coil_length_sum, optimizer._build_available_inputs(x)) @@ -155,7 +99,7 @@ def test_plots_without_plotly_raise_clear_error(monkeypatch): def test_scaling_an_initialized_custom_loss_preserves_dependencies(): - loss = custom_loss(lambda x: jnp.sum(x*x), 'x') + loss = CustomLoss(lambda x: jnp.sum(x*x), 'x') loss.dependencies = {'x': jnp.array([2., 3.])} scaled = 3*loss np.testing.assert_allclose(scaled(scaled.starting_dofs), 39.) @@ -163,7 +107,7 @@ def test_scaling_an_initialized_custom_loss_preserves_dependencies(): def test_first_jitted_call_does_not_cache_traced_starting_dofs(): - loss = custom_loss(lambda x, y: jnp.sum(x*x)+jnp.sum(y), 'x', 'y') + loss = CustomLoss(lambda x, y: jnp.sum(x*x)+jnp.sum(y), 'x', 'y') loss.dependencies = {'x': jnp.array([2., 3.]), 'y': jnp.array([4.])} np.testing.assert_allclose(loss(jnp.array([2., 3., 4.])), 17.) np.testing.assert_allclose(loss.starting_dofs + 0., jnp.array([2., 3., 4.])) @@ -173,8 +117,8 @@ def test_first_jitted_call_does_not_cache_traced_starting_dofs(): def test_composite_first_jit_access_preserves_dofs_and_dependency_gradients(first_access): import jax - quadratic = custom_loss(lambda x, y: jnp.sum(x*x) + jnp.sum(y), 'x', 'y') - coupling = custom_loss(lambda x: x[0]*x[1], 'x') + quadratic = CustomLoss(lambda x, y: jnp.sum(x*x) + jnp.sum(y), 'x', 'y') + coupling = CustomLoss(lambda x: x[0]*x[1], 'x') total = quadratic + coupling total.dependencies = {'x': jnp.array([2., 3.]), 'y': jnp.array([4.]), 'unused': jnp.array([99.])} diff --git a/tests/test_objective_functions.py b/tests/test_objective_functions.py index cd669efd..45362fb7 100644 --- a/tests/test_objective_functions.py +++ b/tests/test_objective_functions.py @@ -205,8 +205,8 @@ def test_near_axis_losses(self): self.assertEqual(points.shape, (3, 2)) self.assertEqual(B_nearaxis.shape, (2, 3)) self.assertEqual(gradB_nearaxis.shape, (2, 3, 3)) - self.assertTrue(jnp.isfinite(objf.loss_B_difference_coils_near_axis(self.field, self.field_nearaxis))) - self.assertTrue(jnp.isfinite(objf.loss_gradB_difference_coils_near_axis(self.field, self.field_nearaxis))) + self.assertTrue(jnp.isfinite(objf.loss_b_difference_coils_near_axis(self.field, self.field_nearaxis))) + self.assertTrue(jnp.isfinite(objf.loss_gradb_difference_coils_near_axis(self.field, self.field_nearaxis))) self.assertTrue(jnp.isfinite(objf.loss_iota_near_axis(self.field_nearaxis))) self.assertTrue(jnp.isfinite(objf.loss_r0_near_axis(self.field_nearaxis))) @@ -217,13 +217,13 @@ def test_particle_losses(self, tracing): self.assertTrue(jnp.isfinite(objf.loss_particle_alpha_drift(self.field, self.particles))) self.assertTrue(jnp.isfinite(objf.loss_particle_gammac(self.field, self.particles))) self.assertTrue(jnp.isfinite(objf.loss_particle_rcross_final(self.field, self.particles))) - self.assertTrue(jnp.isfinite(objf.loss_particle_Br(self.field, self.particles))) + self.assertTrue(jnp.isfinite(objf.loss_particle_br(self.field, self.particles))) self.assertTrue(jnp.isfinite(objf.loss_particle_iota(self.field, self.particles))) - @patch("essos.objective_functions.BdotN_over_B", return_value=jnp.ones((2, 3), dtype=jnp.float64)) + @patch("essos.objective_functions.bdotn_over_b", return_value=jnp.ones((2, 3), dtype=jnp.float64)) def test_surface_losses(self, bdotn): - self.assertTrue(jnp.isfinite(objf.normB_axis(self.field)).all()) - self.assertTrue(jnp.isfinite(objf.loss_normB_axis_average(self.field))) + self.assertTrue(jnp.isfinite(objf.norm_b_axis(self.field)).all()) + self.assertTrue(jnp.isfinite(objf.loss_norm_b_axis_average(self.field))) self.assertTrue(jnp.isfinite(objf.loss_bdotn(self.field, self.surface))) self.assertTrue(jnp.isfinite(objf.loss_bdotn_constraint(self.field, self.surface))) @@ -242,7 +242,7 @@ def test_perturbed_field_from_field(self, statistical, systematic, biot_savart): systematic.assert_called_once() statistical.assert_called_once() - @patch("essos.objective_functions.BdotN_over_B", return_value=jnp.ones((2, 3), dtype=jnp.float64)) + @patch("essos.objective_functions.bdotn_over_b", return_value=jnp.ones((2, 3), dtype=jnp.float64)) @patch("essos.objective_functions.perturbed_field_from_field", return_value=DummyField()) def test_stochastic_surface_losses(self, perturbed_field, bdotn): self.assertTrue(jnp.isfinite(objf.loss_bdotn_stochastic(self.field, self.surface, self.sampler, self.keys))) @@ -291,7 +291,7 @@ def displaced_coils(displacement): self.assertTrue(jnp.isfinite(exact)) self.assertAlmostEqual(float(exact), float(finite_difference), places=6) - @patch("essos.objective_functions.BiotSavart_from_gamma") + @patch("essos.objective_functions.BiotSavartFromGamma") def test_loss_lorentz_force_coils(self, biot_savart_from_gamma): class DummyBS: def B(self, point): @@ -312,8 +312,8 @@ def test_regularization_helpers(self): gammadash = jnp.ones((10, 3)) gammadashdash = jnp.ones((10, 3)) quadpoints = jnp.linspace(0, 1, 10) - self.assertTrue(jnp.isfinite(objf.B_regularized_singularity_term(rc_prime, rc_prime_prime, 1.0)).all()) - self.assertTrue(jnp.isfinite(objf.B_regularized_pure(gamma, gammadash, gammadashdash, quadpoints, 1.0, 1.0)).all()) + self.assertTrue(jnp.isfinite(objf.b_regularized_singularity_term(rc_prime, rc_prime_prime, 1.0)).all()) + self.assertTrue(jnp.isfinite(objf.b_regularized_pure(gamma, gammadash, gammadashdash, quadpoints, 1.0, 1.0)).all()) self.assertTrue(objf.regularization_circ(2.0) > 0) self.assertTrue(jnp.isfinite(objf.regularization_rect(2.0, 1.0))) self.assertTrue(jnp.isfinite(objf.rectangular_xsection_k(2.0, 1.0))) @@ -359,10 +359,10 @@ def _two_distant_loops(n, radius=1.3, current=2.0e6, separation=1.0e5): def test_biot_savart_from_gamma_constructs_and_measures_length(): - from essos.fields import BiotSavart_from_gamma + from essos.fields import BiotSavartFromGamma coils, radius, _ = _two_distant_loops(64) - field = BiotSavart_from_gamma(coils.gamma, coils.gamma_dash, coils.gamma_dashdash, coils.currents) + field = BiotSavartFromGamma(coils.gamma, coils.gamma_dash, coils.gamma_dashdash, coils.currents) np.testing.assert_allclose(field.coils_length, 2 * np.pi * radius, rtol=1e-12) @@ -406,7 +406,7 @@ def test_particle_iota_uses_the_poloidal_angle_gradient(monkeypatch): def test_bdotn_constraint_gradient_is_zero_not_nan_when_satisfied(monkeypatch): import essos.objective_functions as of - monkeypatch.setattr(of, "BdotN_over_B", lambda surface, field: field) + monkeypatch.setattr(of, "bdotn_over_b", lambda surface, field: field) g = jax.grad(lambda b: of.loss_bdotn_constraint(b, None, target_tol=1e-6))(jnp.array([1e-4, 2e-4])) np.testing.assert_array_equal(g, 0.) g = jax.grad(lambda b: of.loss_bdotn_constraint(b, None, target_tol=1e-6))(jnp.array([1e-2, 2e-4])) diff --git a/tests/test_surface_integrals.py b/tests/test_surface_integrals.py index fe121175..714b7af4 100644 --- a/tests/test_surface_integrals.py +++ b/tests/test_surface_integrals.py @@ -44,13 +44,13 @@ def test_shaped_surface_integrals_do_not_depend_on_the_grid(range_torus, close): @pytest.mark.parametrize("definition", ["local", "quadratic flux", "normalized"]) def test_squared_flux_does_not_count_duplicated_end_points(definition): import equinox as eqx - from essos.surfaces import SquaredFlux + from essos.surfaces import squared_flux class Field(eqx.Module): # stellarator-symmetric: toroidal plus vertical def B(self, x): return jnp.array([-x[1], x[0], 0.]) / (x[0]**2 + x[1]**2) + jnp.array([0., 0., .3]) - flux = [SquaredFlux(SurfaceRZFourier(RC, ZS, nfp=3, mpol=1, ntor=2, ntheta=32, nphi=n, close=close, + flux = [squared_flux(SurfaceRZFourier(RC, ZS, nfp=3, mpol=1, ntor=2, ntheta=32, nphi=n, close=close, range_torus=r), Field(), definition) for r, n, close in [("full torus", 96, False), ("full torus", 97, True), ("half period", 48, False), ("half period", 49, True)]]