diff --git a/README.md b/README.md index 28421c11..0221fbb1 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ 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, - maxtime=8000, times_to_trace=40000, atol=1e-8, rtol=1e-8) + tmax=8000, n_save=40000, atol=1e-8, rtol=1e-8) tracing.poincare_plot(shifts=[0.0]) ``` @@ -133,7 +133,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, - maxtime=1e-4, times_to_trace=800, atol=1e-7, rtol=1e-7) + tmax=1e-4, n_save=800, atol=1e-7, rtol=1e-7) tracing.plot() print(tracing.loss_fractions) ``` @@ -156,7 +156,7 @@ with a wall 3 cm outside the LCFS. 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, - maxtime=4e-5, exterior_field=outside, wall=0.03) # gap [m] or a surface + 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]) ``` @@ -170,7 +170,7 @@ Transform a VMEC equilibrium with [booz_xform_jax](https://github.com/uwplasma/b then trace guiding centres in an axis-regular chart with optional Monte Carlo collisions. `method="rk4"` (default), `"dopri5"` or `"dopri8"` take fixed steps; `"adaptive"` (Dopri5) and `"adaptive8"` (Dopri8) control each -particle's step to `tolerance`. This tracer provides forward diagnostics. +particle's step to `rtol` (with `atol=None` meaning `atol = rtol`). This tracer provides forward diagnostics. Install the transform extra with `pip install 'essos[booz]'`. @@ -263,7 +263,7 @@ the `wout` directly and DESC fits it. ± is the binomial standard error. (`essos.dynamics.VMEC_STATUS`); `trajectories_xyz` and `region` hold the whole orbit. A non-finite step ends that orbit as `failed`, with its time. Loss fractions use the exact wall, or LCFS, times. Collisions are switched - off outside the LCFS. Supplying `condition` replaces these events; it is + 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(...)` @@ -291,6 +291,23 @@ pip install git+https://github.com/uwplasma/pyQSC_JAX.git Everything else works without it; the near-axis entry points raise with this command if it is missing. +## API changes: tracing and optimizer keywords + +These renames are breaking and have no aliases. Tracing options are keyword-only after `field`, +`particles` and `initial_conditions`. + +| Old | New | +| --- | --- | +| `Tracing(maxtime=...)`, loss functions `maxtime` | `tmax` | +| `Tracing(times_to_trace=...)`, loss functions `num_steps`, `trace_field_lines(samples=...)` | `n_save` | +| `trace_boozer`, `trace_field_lines`, `connection_length` `tolerance`; loss functions `trace_tolerance` | `rtol`, plus `atol=None` meaning `atol = rtol` | +| `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. + ## Examples | Folder | Contents | diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 85455cd5..685cc06d 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -83,7 +83,7 @@ Tracing many VMEC orbits ------------------------ ``Tracing`` converts each saved VMEC state to Cartesian one point at a time, so the memory of a trace grows slowly with -``times_to_trace``. Peak memory for 500 guiding centres on one CPU device, with the old vectorized conversion for +``n_save``. Peak memory for 500 guiding centres on one CPU device, with the old vectorized conversion for comparison: .. image:: _static/vmec_tracing_memory.png diff --git a/docs/make_readme_figures.py b/docs/make_readme_figures.py index a934d022..ebf00c4b 100644 --- a/docs/make_readme_figures.py +++ b/docs/make_readme_figures.py @@ -77,7 +77,7 @@ def field_line_tracing() -> None: seeds = jnp.array([R0, zeros, zeros]).T tracing = Tracing(field=field, model="FieldLineAdaptative", initial_conditions=seeds, - maxtime=8000, times_to_trace=40000, atol=1e-8, rtol=1e-8) + tmax=8000, n_save=40000, atol=1e-8, rtol=1e-8) fig, ax = plt.subplots(figsize=(4.4, 4.4)) tracing.poincare_plot(ax=ax, show=False, shifts=[0.0]) @@ -98,7 +98,7 @@ def particle_tracing() -> None: energy=4000 * ONE_EV) tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, - maxtime=1e-4, times_to_trace=800, atol=1e-7, rtol=1e-7) + tmax=1e-4, n_save=800, atol=1e-7, rtol=1e-7) fig = plt.figure(figsize=(5.0, 4.0)) ax = fig.add_subplot(projection="3d") @@ -145,7 +145,7 @@ def wall_tracing() -> None: 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, - maxtime=4e-5, timestep=1e-9, times_to_trace=2000, atol=1e-8, rtol=1e-8, + tmax=4e-5, timestep=1e-9, n_save=2000, atol=1e-8, rtol=1e-8, exterior_field=outside, wall=gap) crossed = np.isfinite(np.asarray(tracing.lcfs_times)) diff --git a/docs/tracing.rst b/docs/tracing.rst index 580b33d8..29dce482 100644 --- a/docs/tracing.rst +++ b/docs/tracing.rst @@ -27,7 +27,7 @@ Defaults ``v`` the largest particle speed. For adaptive models it only sets the first trial step. These values must be concrete: under ``jax.grad`` with traced coil degrees of freedom or energies a fixed-step model raises an error asking for an explicit ``timestep``. -* ``max_steps=None`` is 16 times the steps of a fixed-step solve over ``maxtime``, enough for adaptive tolerances +* ``max_steps=None`` is 16 times the steps of a fixed-step solve over ``tmax``, enough for adaptive tolerances down to about 1e-12 (1e6 when the timestep could not be derived, as in an adaptive trace under ``jax.grad`` of the coil dofs). * An orbit that ends non-finite or reaches ``max_steps`` raises a ``RuntimeWarning``; raise ``max_steps`` or lower the tolerance. diff --git a/essos/__main__.py b/essos/__main__.py index 25f993f4..dd1acef2 100644 --- a/essos/__main__.py +++ b/essos/__main__.py @@ -29,9 +29,9 @@ def main(cl_args=sys.argv[1:]): max_coil_curvature = 4 order_Fourier_series_coils = 5 number_coil_points = order_Fourier_series_coils*10 - maximum_function_evaluations = 100 + max_nfev = 100 number_coils_per_half_field_period = 3 - tolerance_optimization = 1e-8 + tol = 1e-8 # Initialize Near-Axis field rc=jnp.array([1, 0.045]) @@ -60,19 +60,19 @@ def main(cl_args=sys.argv[1:]): coils_initial = Coils(curves=curves, currents=[current_on_each_coil]*number_coils_per_half_field_period) # Optimize coils - print(f'Optimizing coils with {maximum_function_evaluations} function evaluations.') + 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=coils_initial, tolerance_optimization=tolerance_optimization, - maximum_function_evaluations=maximum_function_evaluations, field_nearaxis=field, + coils=coils_initial, tol=tol, + max_nfev=max_nfev, field_nearaxis=field, max_coil_length=max_coil_length, max_coil_curvature=max_coil_curvature,) print(f"Optimization took {time()-time0:.2f} seconds") # Trace fieldlines nfieldlines = 6 - num_steps = 1000 + n_save = 1000 tmax = 150 - trace_tolerance = 1e-7 + rtol = 1e-7 R0 = jnp.linspace(field.R0[0], 1.05*field.R0[0], nfieldlines) Z0 = jnp.zeros(nfieldlines) @@ -81,9 +81,9 @@ def main(cl_args=sys.argv[1:]): time0 = time() tracing_initial = Tracing(field=BiotSavart(coils_initial), model='FieldLine', initial_conditions=initial_xyz, - maxtime=tmax, timesteps=num_steps, tol_step_size=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) tracing_optimized = Tracing(field=BiotSavart(coils_optimized), model='FieldLine', initial_conditions=initial_xyz, - maxtime=tmax, timesteps=num_steps, tol_step_size=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) print(f"Tracing took {time()-time0:.2f} seconds") # Plot coils, before and after optimization diff --git a/essos/boozer.py b/essos/boozer.py index fed90fb4..bfcdbaa7 100644 --- a/essos/boozer.py +++ b/essos/boozer.py @@ -384,7 +384,7 @@ def one(y, mu): @partial(jax.jit, static_argnames=("count", "species", "method")) def _advance(field, dt, n_sub, mass, charge, species, thermal_cutoff, - carry, keys, first_interval, count, method="rk4", tolerance=1e-8): + carry, keys, first_interval, count, method="rk4", rtol=1e-8, atol=1e-8): def one(carry, key): def finish(carry, y1, h): """Accept ``y1`` after a step of ``h``: energy, collisions, loss and failure.""" @@ -442,7 +442,7 @@ def attempt(state): carry, attempts = state y, t, h = carry[0], carry[2], carry[9] h_try = jnp.minimum(h, t_end - t) - scale = tolerance * jnp.array([1.0, 1.0, 1.0, jnp.sqrt(2 * carry[8])]) + scale = jnp.array([atol, atol, atol, rtol * jnp.sqrt(2 * carry[8])]) y1, norm = _embedded_step(rhs_of(carry), y, h_try, scale, method) ok = jnp.isfinite(norm) & (norm <= 1.0) safe = jnp.where(jnp.isfinite(norm) & (norm > 0), norm, jnp.where(ok, 0.0, 1e10)) @@ -486,7 +486,7 @@ def interval(carry, i): def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, timestep=None, n_save=100, species=None, seed=0, thermal_cutoff=1.5, devices=None, - progress=True, compact=True, method="dopri8", tolerance=1e-8): + progress=True, compact=True, method="dopri8", rtol=1e-8, atol=None): """Trace guiding centres from Boozer ``(s, theta, zeta)`` with pitch ``v_par/v``. The default ``timestep`` is ``R0 / (2 nfp speed)``, with ``R0 = |G| / |B|`` on the @@ -509,13 +509,14 @@ def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, tim ``"rk4"``; ``"dopri8"`` matches RK4 in cost and energy error at 3x its step and is far more accurate at smaller steps. Refine timestep and modes to check loss labels and bounce phase. ``"adaptive"`` (Dopri5) and ``"adaptive8"`` (Dopri8) control each particle's step so the embedded error - stays below ``tolerance`` (in ``sqrt(s)`` and ``zeta`` units and relative to the - speed for ``v_par``); ``timestep`` is then only the first trial step. + stays below ``atol`` in ``sqrt(s)``, ``theta`` and ``zeta`` and ``rtol`` times the speed for ``v_par`` + (``atol=None`` means ``atol = rtol``); ``timestep`` is then only the first trial step. """ if method not in ("rk4", "dopri5", "dopri8", "adaptive", "adaptive8"): raise ValueError("method must be 'rk4', 'dopri5', 'dopri8', 'adaptive' or 'adaptive8'") - if not (np.isfinite(tolerance) and tolerance > 0): - raise ValueError("tolerance must be positive and finite") + atol = rtol if atol is None else atol + if not (np.isfinite(rtol) and rtol > 0 and np.isfinite(atol) and atol > 0): + raise ValueError("rtol and atol must be positive and finite") inputs = tuple(np.atleast_1d(np.asarray(a, float)) for a in (s, theta, zeta, pitch)) n = inputs[0].size if n < 1 or any(a.ndim != 1 or a.size != n or not np.isfinite(a).all() for a in inputs): @@ -571,7 +572,7 @@ def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, tim for start in range(0, n_int, chunk): count = min(chunk, n_int - start) carry, part = _advance(field, dt, n_sub, mass, charge, species, thermal_cutoff, - carry, keys, start, count, method, tolerance) + carry, keys, start, count, method, rtol, atol) states[selected, start + 1:start + count + 1] = np.asarray(part)[:selected.size] if progress is not None: progress(start + count, n_int) diff --git a/essos/dynamics.py b/essos/dynamics.py index 32832355..8162f868 100644 --- a/essos/dynamics.py +++ b/essos/dynamics.py @@ -4,7 +4,7 @@ import jax jax.config.update("jax_enable_x64", True) # Tracings that differ only in array values (particles, coil currents, field coefficients) share one compiled solve -# within a process; maxtime and the save times are constants of it, so a new one compiles: about 4 s on a CPU and +# within a process; tmax and the save times are constants of it, so a new one compiles: about 4 s on a CPU and # 20 s on a GPU. XLA's persistent cache, keyed by the compiled program, serves it from disk in a rerun. # ESSOS_XLA_CACHE names the directory; an empty value disables it. _XLA_CACHE = os.environ.get("ESSOS_XLA_CACHE", os.path.join(os.path.expanduser("~"), ".cache", "essos", "xla")) @@ -814,9 +814,9 @@ def _warn_unfinished(count, max_steps): # Outcome of each VMEC guiding center, ``Tracing.status``. VMEC_STATUS = { - 0: "inside the LCFS at maxtime", + 0: "inside the LCFS at tmax", 1: "stopped at the LCFS (no exterior field)", - 2: "outside the LCFS at maxtime", + 2: "outside the LCFS at tmax", 3: "struck the wall", 4: "failed: non-finite state or solver failure", 5: "stopped after max_returns re-entries", @@ -1060,10 +1060,10 @@ def _batch_solver(tracing, place): class Tracing(): - def __init__(self, trajectories_input=None, initial_conditions=None, times_to_trace=None, - field=None, electric_field=None,model=None, maxtime: float = 1e-7, timestep=None, - rtol=1.e-8, atol=None, particles=None, condition=None,species=None,tag_gc=1.,boundary=None,rejected_steps=None, - solver=None, stopping_criteria=None, progress=True, devices=None, + 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, + 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): @@ -1098,20 +1098,20 @@ def __init__(self, trajectories_input=None, initial_conditions=None, times_to_tr self.model = model self.initial_conditions = initial_conditions - self.times_to_trace = times_to_trace - self.maxtime = maxtime + self.n_save = n_save + self.tmax = tmax # timestep=None: 1/_STEPS_PER_TRANSIT (400, 100 for VMEC) of the transit time R0/speed, evaluated eagerly - # (also under jit); maxtime/100 for a field line. A traced R0 or speed (coil dofs, energy under jax.grad) cannot size a step. + # (also under jit); tmax/100 for a field line. A traced R0 or speed (coil dofs, energy under jax.grad) cannot size a step. if timestep is None: with jax.ensure_compile_time_eval(): scales = [getattr(field, "r_axis", 1.0), jnp.max(particles.total_speed) if particles is not None else 1.0] if particles is None: - timestep = maxtime / 100 + timestep = tmax / 100 elif any(isinstance(x, jax.core.Tracer) for x in scales): if model not in ('GuidingCenterAdaptative', 'FullOrbitAdaptative'): raise ValueError("timestep=None needs the axis radius and particle speed as concrete values; " "they are traced here, so pass an explicit timestep") - timestep = maxtime / 100 # only the first trial step of an adaptive solve, which cannot size max_steps + timestep = tmax / 100 # only the first trial step of an adaptive solve, which cannot size max_steps max_steps = 1_000_000 if max_steps is None else max_steps else: timestep = float(abs(scales[0]) / scales[1]) / _STEPS_PER_TRANSIT.get(type(field), 400) @@ -1149,7 +1149,7 @@ def __init__(self, trajectories_input=None, initial_conditions=None, times_to_tr # Diffrax's ceiling was effectively unbounded, so a trace that could not # finish ran until the process was killed rather than returning. # max_steps=None: 16 times the steps of a fixed-step solve, enough for tolerances down to 1e-12. - self.max_steps = int(16 * np.ceil(maxtime / timestep)) + 16 if max_steps is None else max_steps + self.max_steps = int(16 * np.ceil(tmax / timestep)) + 16 if max_steps is None else max_steps # Reverse mode (jax.grad) by default; diffrax.ForwardMode() for jax.jvp and jax.jacfwd, which # diffrax's checkpointed adjoint cannot do. self.adjoint = diffrax.RecursiveCheckpointAdjoint() if adjoint is None else adjoint @@ -1203,8 +1203,8 @@ def condition_BioSavart(t, y, args, **kwargs): elif model == 'GuidingCenterCollisions': # Brownian motion #t0=0.0 - #t1=self.maxtime - #tol=self.maxtime / self.timesteps*0.5 + #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(GuidingCenterCollisionsDrift),ControlTerm(GuidingCenterCollisionsDiffusion, bm)) @@ -1214,8 +1214,8 @@ def condition_BioSavart(t, y, args, **kwargs): elif model == 'GuidingCenterCollisionsMuIto' or model == 'GuidingCenterCollisionsMuFixed' or model == 'GuidingCenterCollisionsMuAdaptative': # Brownian motion #t0=0.0 - #t1=self.maxtime - #tol=self.maxtime / self.timesteps*0.5 + #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)) @@ -1250,10 +1250,10 @@ def condition_BioSavart(t, y, args, **kwargs): self.ODE_term = ODETerm(field_line_rhs) self.args = self.field - if self.times_to_trace is None: - self.times = jnp.linspace(0, self.maxtime, 100,endpoint=True) + if self.n_save is None: + self.times = jnp.linspace(0, self.tmax, 100,endpoint=True) else: - self.times = jnp.linspace(0, self.maxtime, self.times_to_trace,endpoint=True) + self.times = jnp.linspace(0, self.tmax, self.n_save,endpoint=True) if self._vmec_default: @@ -1309,12 +1309,12 @@ def compute_trajectory(initial_condition, particle_key) -> jnp.ndarray: if self._axis_regular: initial_condition = _to_axis_regular(initial_condition) if self.model == 'FullOrbit_Boris': - # Integrate the whole [0, maxtime] span: an inner scan of + # 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. n_saves = len(self.times) - 1 - per_save = max(1, int(np.ceil(float(self.maxtime) / (n_saves * float(self.timestep)) - 1e-9))) - dt = self.maxtime / (n_saves * per_save) + per_save = max(1, int(np.ceil(float(self.tmax) / (n_saves * float(self.timestep)) - 1e-9))) + dt = self.tmax / (n_saves * per_save) charge_over_mass = self.particles.charge / self.particles.mass criteria = self.stopping_criteria @@ -1423,9 +1423,9 @@ def _terms(self, key, flag=False, events=()): dt0, model = self.timestep, self.model if model in _SDE_MODELS: drift, diffusion, solver, dim = _SDE_MODELS[model] - # With flag (segments), a vmapped solve of an orbit that starts at maxtime evaluates the path + # With flag (segments), a vmapped solve of an orbit that starts at tmax evaluates the path # one step past it. - bm = diffrax.VirtualBrownianTree(0.0, self.maxtime + flag * dt0, tol=dt0 * 0.5, shape=(dim,), key=key, + bm = diffrax.VirtualBrownianTree(0.0, self.tmax + flag * dt0, tol=dt0 * 0.5, shape=(dim,), key=key, levy_area=diffrax.SpaceTimeTimeLevyArea) terms = MultiTerm(ODETerm(flagged(self._vector_field(drift))), ControlTerm(flagged(self._vector_field(diffusion), drift=False), bm)) @@ -1447,10 +1447,10 @@ def _terms(self, key, flag=False, events=()): return terms, solver, controller def _solve(self, terms, solver, controller, t0, y0, args, event, throw=False): - """diffeqsolve from t0 to maxtime, saving at self.times (clipped to t0) and at the end.""" + """diffeqsolve from t0 to tmax, saving at self.times (clipped to t0) and at the end.""" warnings.simplefilter("ignore", category=FutureWarning) # see https://github.com/patrick-kidger/diffrax/issues/445 - return diffeqsolve(terms, solver, t0=t0, t1=self.maxtime, dt0=self.timestep, y0=y0, args=args, - saveat=SaveAt(subs=[diffrax.SubSaveAt(ts=jnp.clip(self.times, t0, self.maxtime)), + return diffeqsolve(terms, solver, t0=t0, t1=self.tmax, dt0=self.timestep, y0=y0, args=args, + saveat=SaveAt(subs=[diffrax.SubSaveAt(ts=jnp.clip(self.times, t0, self.tmax)), diffrax.SubSaveAt(t1=True)]), stepsize_controller=controller, event=event, throw=throw, max_steps=self.max_steps, progress_meter=self.progress_meter, adjoint=self.adjoint) @@ -1460,13 +1460,13 @@ def _solve(self, terms, solver, controller, t0, y0, args, event, throw=False): def _vmec_orbit(self, y0, key): """Trace one VMEC guiding center segment by segment: inside, outside, and back inside. - Inside the LCFS the model runs in the axis-regular chart until maxtime, + Inside the LCFS the model runs in the axis-regular chart until tmax, the root-found LCFS crossing, or a non-finite state. Without exterior_field a crossing ends the orbit. With it, the orbit continues as a collisionless guiding center (x, y, z, v_par, mu) with its energy - and magnetic moment, until it strikes the wall, reaches maxtime or + and magnetic moment, until it strikes the wall, reaches tmax or re-enters the LCFS; it then continues inside, up to max_returns times. - Solves of inactive orbits start at maxtime and take no steps. + Solves of inactive orbits start at tmax and take no steps. Differentiable with respect to the launch states and the parameters of the fields: jax.grad by default, jax.jvp and jax.jacfwd with ``adjoint=diffrax.ForwardMode()``. Event times differentiate by the implicit function @@ -1475,7 +1475,7 @@ def _vmec_orbit(self, y0, key): does not toggle the segment. The derivative is that of the orbit's own sequence of segments: where a small change adds or removes a crossing or a re-entry, the result jumps (it is finite, not smoothed). """ - T, times, ext = self.maxtime, self.times, self.exterior_field + T, times, ext = self.tmax, self.times, self.exterior_field lcfs = lambda y: 1.0 - y[0]**2 - y[1]**2 inside = (*self._terms(key, flag=True, events=(lcfs,)), self.args, Event((lambda t, y, args, **kwargs: lcfs(y), _failed_event), @@ -1492,7 +1492,7 @@ def _vmec_orbit(self, y0, key): def segment(o, run, spec, y, code, to_flux=lambda y: y): """Solve one segment of the orbits in ``run`` and record its saves.""" - # A lane that does not run starts just before maxtime, not at it: diffrax 0.7.0 differentiates an event root + # A lane that does not run starts just before tmax, not at it: diffrax 0.7.0 differentiates an event root # find over a zero-length step with a non-finite Jacobian, which its linear solver rejects in reverse mode. # A non-finite start fails at once; it is replaced by a finite one so that no NaN enters the derivative. ok = jnp.isfinite(y).all() @@ -1527,7 +1527,7 @@ def step(o): inside=o["inside"] & ~crossed, x=jnp.where(crossed, x, o["x"])) if ext is None: return o - # Outside, to the wall, maxtime, or back inside. + # Outside, to the wall, tmax, or back inside. run = o["active"] & ~o["inside"] behind = run & (wall(o["x"][:3]) <= 0) # the wall is already crossed at the exit point: a hit at the exit time o, t_end, end, (struck, returned), failed = segment(o, run & ~behind, outside, o["x"], 1) @@ -1856,7 +1856,7 @@ def poincare_plot(self, shifts = [jnp.pi/2], orientation = 'toroidal', length = def _tree_flatten(self): # Rebuilding through __init__ would trace again and mapped times onto - # times_to_trace; every attribute holding arrays is a child instead. + # n_save; every attribute holding arrays is a child instead. def has_arrays(value): return any(isinstance(leaf, (jax.Array, np.ndarray)) for leaf in tree_util.tree_leaves(value)) names = tuple(name for name, value in vars(self).items() if has_arrays(value)) @@ -1883,8 +1883,9 @@ def trace_field_lines( *, toroidal_turns=None, length=None, - samples=1000, - tolerance=1.0e-7, + n_save=1000, + rtol=1.0e-7, + atol=None, stopping_criteria=None, progress=True, label="field lines", @@ -1895,7 +1896,7 @@ def trace_field_lines( Specify exactly one of ``toroidal_turns`` or ``length``. Toroidal tracing is intended for fields represented in flux coordinates; Cartesian coil fields use arclength, so multiplying the magnetic field does not change - the traced distance. ``samples`` includes both endpoints. The returned + the traced distance. ``n_save`` includes both endpoints. The returned :class:`Tracing` object provides trajectories, event flags, plotting, and Poincare sections. @@ -1904,9 +1905,10 @@ def trace_field_lines( initial_conditions: One seed per row, in the field's coordinates. toroidal_turns: Number of full toroidal turns to follow. length: Physical arclength to follow for a Cartesian field. - samples: Number of saved points along each line. - tolerance: Relative and absolute adaptive-integration tolerance. Flux-coordinate - angles use a fixed one-radian reference scale, independent of winding. + n_save: Number of saved points along each line. + rtol: Relative adaptive-integration tolerance. + atol: Absolute tolerance; ``None`` means ``atol = rtol``. + Flux-coordinate angles use a fixed one-radian reference scale, independent of winding. stopping_criteria: Optional event callable or sequence of callables. progress: Show Diffrax's terminal progress bar. label: Text printed before compilation and after completion; set to @@ -1915,8 +1917,8 @@ def trace_field_lines( """ if (toroidal_turns is None) == (length is None): raise ValueError("specify exactly one of toroidal_turns or length") - if int(samples) < 2: - raise ValueError("samples must be at least 2") + if int(n_save) < 2: + raise ValueError("n_save must be at least 2") if toroidal_turns is not None and float(toroidal_turns) <= 0.0: raise ValueError("toroidal_turns must be positive") if length is not None and float(length) <= 0.0: @@ -1932,11 +1934,11 @@ def trace_field_lines( field=field, model=model, initial_conditions=initial_conditions, - maxtime=extent, - timestep=extent / (int(samples) - 1), - times_to_trace=int(samples), - atol=float(tolerance), - rtol=float(tolerance), + tmax=extent, + timestep=extent / (int(n_save) - 1), + n_save=int(n_save), + rtol=float(rtol), + atol=None if atol is None else float(atol), stopping_criteria=stopping_criteria, progress=bool(progress), devices=devices, @@ -1952,13 +1954,13 @@ def trace_field_lines( def connection_length(field, initial_conditions, wall, *, max_length, - tolerance=1.0e-8, max_steps=100000): + rtol=1.0e-8, atol=None, max_steps=100000): """Connection length and wall strike points of field lines. Each seed is followed along ``+B`` and ``-B`` by physical arclength until it crosses the wall or reaches ``max_length``. The crossing is located by Diffrax event root finding, so the strike point is exact up to - ``tolerance`` rather than limited by a sampling interval. The result is + ``rtol`` rather than limited by a sampling interval. The result is differentiable with respect to the seeds and field parameters. Args: @@ -1968,7 +1970,8 @@ def connection_length(field, initial_conditions, wall, *, max_length, wall: Object with ``evaluate_xyz(xyz)`` (e.g. :class:`SurfaceClassifier`) or a callable ``wall(xyz)``, positive inside the wall and zero on it. max_length: Cap on the length followed in each direction. - tolerance: Relative and absolute integration and root-finding tolerance. + rtol: Relative integration and root-finding tolerance. + atol: Absolute tolerance; ``None`` means ``atol = rtol``. max_steps: Maximum adaptive steps per direction; a line that exhausts them returns ``nan`` length and ``hit`` false. @@ -1980,9 +1983,10 @@ def connection_length(field, initial_conditions, wall, *, max_length, if float(max_length) <= 0.0: raise ValueError("max_length must be positive") distance = wall.evaluate_xyz if hasattr(wall, "evaluate_xyz") else wall - controller = PIDController(rtol=tolerance, atol=tolerance) + atol = rtol if atol is None else atol + controller = PIDController(rtol=rtol, atol=atol) event = Event(lambda t, y, args, **kwargs: distance(y), - root_finder=optx.Newton(rtol=tolerance, atol=tolerance)) + root_finder=optx.Newton(rtol=rtol, atol=atol)) def vector_field(t, y, sign): B = field.B_contravariant(y) diff --git a/essos/multiobjectiveoptimizer.py b/essos/multiobjectiveoptimizer.py index 6b1f8916..dd7907f7 100644 --- a/essos/multiobjectiveoptimizer.py +++ b/essos/multiobjectiveoptimizer.py @@ -34,9 +34,9 @@ def __init__(self, loss_functions, vmec, coils_init=None, function_inputs=None, self.order_Fourier = self.opt_config.get("order_Fourier", 6) self.num_points = self.order_Fourier * 10 self.num_coils = self.opt_config.get("num_coils", 4) - self.max_eval = self.opt_config.get("maximum_function_evaluations", 300) + self.max_nfev = self.opt_config.get("max_nfev", 300) self.n_trials = self.opt_config.get("n_trials", 1) - self.tol = self.opt_config.get("tolerance_optimization", 1e-5) + self.tol = self.opt_config.get("tol", 1e-5) self.optimizer_choices = self.opt_config.get("optimizer_choices", ["adam", "amsgrad", "sgd"]) self.initial_coils = coils_init or self._generate_initial_coils() @@ -115,7 +115,7 @@ def _objective(self, trial): opt = getattr(optax, method)(lr) state = opt.init(x) - for _ in range(self.max_eval): + for _ in range(self.max_nfev): loss = loss_fn(x) grads = grad_fn(x) updates, state = opt.update(grads, state) @@ -156,7 +156,7 @@ def optimize_with_optax(self, weights, method="adam", lr=1e-2): optimizer = getattr(optax, method)(lr) state = optimizer.init(x) - for _ in range(self.max_eval): + for _ in range(self.max_nfev): loss = loss_fn(x) grads = grad_fn(x) updates, state = optimizer.update(grads, state) diff --git a/essos/objective_functions.py b/essos/objective_functions.py index 97371a91..1d62acbf 100644 --- a/essos/objective_functions.py +++ b/essos/objective_functions.py @@ -50,12 +50,11 @@ def loss_r0_near_axis(field_nearaxis, r0_target=1.0): ##############################Particle confinement losses ############################## -def _orbit(field, particles, timestep=None, maxtime=1e-5, num_steps=300, trace_tolerance=1e-7, +def _orbit(field, particles, *, timestep=None, tmax=1e-5, n_save=300, rtol=1e-7, atol=None, max_steps=None, model='GuidingCenterAdaptative', boundary=None): """Trace and return xyz, the cylindrical radius and the offsets (R, Z) from the axis.""" - xyz = Tracing(field=field, model=model, particles=particles, maxtime=maxtime, timestep=timestep, - times_to_trace=num_steps, atol=trace_tolerance, rtol=trace_tolerance, - boundary=boundary).trajectories[:, :, :3] + 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] fac_xy = jnp.sqrt(jnp.square(xyz[:, :, 0]) + jnp.square(xyz[:, :, 1])) return xyz, fac_xy, fac_xy - field.r_axis + 1.e-12, xyz[:, :, 2] - field.z_axis + 1.e-12 @@ -117,7 +116,7 @@ def loss_normB_axis_average(field,npoints=15, target_B=5.7): return jnp.abs(jnp.average(B_axis)-target_B) -def loss_BdotN(field,surface): +def loss_bdotn(field,surface): return jnp.sum(jnp.abs(BdotN_over_B(surface, field))) def _sqrt_sum_positive(u): @@ -126,7 +125,7 @@ def _sqrt_sum_positive(u): return jnp.where(total > 0, jnp.sqrt(jnp.where(total > 0, total, 1.0)), 0.0) @partial(jit, static_argnames=['target_tol']) -def loss_BdotN_constraint(field,surface,target_tol=1.e-6): +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) @@ -480,7 +479,7 @@ def rectangular_xsection_delta(a, b): return jnp.exp(-25/6 + rectangular_xsection_k(a, b)) -#def loss_BdotN_only_with_perturbation(x, vmec, dofs_curves, currents_scale, nfp,n_segments=60, stellsym=True, N_stells=10): +#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.): # field=field_from_dofs(x,dofs_curves, currents_scale, nfp,n_segments, stellsym) diff --git a/essos/optimization.py b/essos/optimization.py index 77c2757d..bcf1b9eb 100644 --- a/essos/optimization.py +++ b/essos/optimization.py @@ -39,7 +39,7 @@ def new_nearaxis_from_x_and_old_nearaxis(new_field_nearaxis_x, field_nearaxis): nphi=field_nearaxis.nphi, spsi=field_nearaxis.spsi, sG=field_nearaxis.sG, nfp=field_nearaxis.nfp) return new_field_nearaxis -def optimize_loss_function(func, initial_dofs, coils, tolerance_optimization=1e-4, maximum_function_evaluations=30, method='L-BFGS-B', **kwargs): +def optimize_loss_function(func, initial_dofs, coils, tol=1e-4, max_nfev=30, method='L-BFGS-B', **kwargs): """Minimize a coil loss with ``scipy.optimize.least_squares``. Gradients are finite differences (``diff_step=1e-4``). ``method`` is only @@ -51,8 +51,8 @@ def optimize_loss_function(func, initial_dofs, coils, tolerance_optimization=1e- initial_dofs: Starting vector: coil curve dofs, then currents, then optionally surface and near-axis dofs. coils: Initial ``Coils``; supplies the symmetry and scaling arguments. - tolerance_optimization: Used for both ``ftol`` and ``gtol``. - maximum_function_evaluations: ``max_nfev`` of the solver. + tol: Used for both ``ftol`` and ``gtol``. + max_nfev: Evaluation limit of the solver. **kwargs: Passed to ``func``. ``field_nearaxis`` and ``surface_all`` select which extra objects are returned. @@ -72,16 +72,16 @@ def optimize_loss_function(func, initial_dofs, coils, tolerance_optimization=1e- ## Without JAX gradients, using finite differences result = least_squares(loss_partial, x0=initial_dofs, verbose=2, diff_step=1e-4, - ftol=tolerance_optimization, gtol=tolerance_optimization, - xtol=1e-14, max_nfev=maximum_function_evaluations) + ftol=tol, gtol=tol, + xtol=1e-14, max_nfev=max_nfev) ## With JAX gradients ##jac_loss_partial = jit(grad(loss_partial)) # result = least_squares(loss_partial, x0=initial_dofs, verbose=2, jac=jac_loss_partial, - # ftol=tolerance_optimization, gtol=tolerance_optimization, - # xtol=1e-14, max_nfev=maximum_function_evaluations) + # ftol=tol, gtol=tol, + # xtol=1e-14, max_nfev=max_nfev) ##result = minimize(loss_partial, x0=initial_dofs, jac=jac_loss_partial, method=method, - ## tol=tolerance_optimization, options={'maxiter': maximum_function_evaluations, 'disp': True, 'gtol': 1e-14, 'ftol': 1e-14}) + ## tol=tol, options={'maxiter': max_nfev, 'disp': True, 'gtol': 1e-14, 'ftol': 1e-14}) dofs_curves = jnp.reshape(result.x[:len_dofs_curves], (dofs_curves_shape)) try: diff --git a/examples/coil_optimization/optimize_coils_and_nearaxis.py b/examples/coil_optimization/optimize_coils_and_nearaxis.py index 242fe93c..20ef993d 100644 --- a/examples/coil_optimization/optimize_coils_and_nearaxis.py +++ b/examples/coil_optimization/optimize_coils_and_nearaxis.py @@ -17,8 +17,8 @@ """ Creating starting coils and surface """ N_COILS = 3; FOURIER_ORDER = 6; LARGE_R = 10; SMALL_R = 5.6; NFP = 3; N_SEGMENTS = 60; STELLSYM = True # Curve parameters COIL_CURRENT = 1. # Amperes (optimization does not depend on current magnitude) -tolerance_optimization = 1e-8 -maximum_function_evaluations = 200 +tol = 1e-8 +max_nfev = 200 @@ -110,7 +110,7 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): """ Optimizing the total loss """ t_start = time() -res = least_squares(L_total, L_total.starting_dofs, L_total.grad, verbose=2, ftol=1e-5, gtol=1e-5, xtol=1e-14, max_nfev=maximum_function_evaluations) +res = least_squares(L_total, L_total.starting_dofs, L_total.grad, verbose=2, ftol=1e-5, gtol=1e-5, xtol=1e-14, max_nfev=max_nfev) t_end = time() print(f"\nOptimization took {t_end - t_start:.2f} seconds") @@ -145,9 +145,9 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): # Trace fieldlines nfieldlines = 6 -num_steps = 1000 +n_save = 1000 tmax = 1.e-6 -trace_tolerance = 1e-7 +rtol = 1e-7 R0_initial = jnp.linspace(field_nearaxis_initial.R0[0], 1.05*field_nearaxis_initial.R0[0], nfieldlines) R0_optimized = jnp.linspace(opt_field_nearaxis.R0[0], 1.05*opt_field_nearaxis.R0[0], nfieldlines) @@ -158,9 +158,9 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): time0 = time() tracing_initial = Tracing(field=init_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_initial, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) tracing_optimized = Tracing(field=opt_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_optimized, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) print(f"Tracing took {time()-time0:.2f} seconds") # Plot coils, before and after optimization diff --git a/examples/coil_optimization/optimize_coils_for_nearaxis.py b/examples/coil_optimization/optimize_coils_for_nearaxis.py index 0be0f870..efae0d1c 100644 --- a/examples/coil_optimization/optimize_coils_for_nearaxis.py +++ b/examples/coil_optimization/optimize_coils_for_nearaxis.py @@ -19,8 +19,8 @@ """ Creating starting coils and surface """ N_COILS = 3; FOURIER_ORDER = 6; LARGE_R = 10; SMALL_R = 5.6; NFP = 3; N_SEGMENTS = 60; STELLSYM = True # Curve parameters COIL_CURRENT = 1. # Amperes (optimization does not depend on current magnitude) -tolerance_optimization = 1e-8 -maximum_function_evaluations =200 +tol = 1e-8 +max_nfev =200 @@ -124,9 +124,9 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): # Trace fieldlines nfieldlines = 6 -num_steps = 1000 +n_save = 1000 tmax = 1.e-6 -trace_tolerance = 1e-7 +rtol = 1e-7 R0_initial = jnp.linspace(field_nearaxis_initial.R0[0], 1.05*field_nearaxis_initial.R0[0], nfieldlines) R0_optimized = jnp.linspace(field_nearaxis_initial.R0[0], 1.05*field_nearaxis_initial.R0[0], nfieldlines) @@ -137,9 +137,9 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): time0 = time() tracing_initial = Tracing(field=init_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_initial, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) tracing_optimized = Tracing(field=opt_field, model='FieldLineAdaptative', initial_conditions=initial_xyz_optimized, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) print(f"Tracing took {time()-time0:.2f} seconds") # Plot coils, before and after optimization diff --git a/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py b/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py index 9dde0e8a..1c835697 100644 --- a/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py +++ b/examples/coil_optimization/optimize_coils_particle_confinement_fullorbit.py @@ -54,16 +54,16 @@ BAXIS_WEIGHT = 1.; BAXIS_TARGET = 5.7 RADIAL_DRIFT_WEIGHT = 1. -def loss_particle_radial_drift(field, particles, timestep=1.e-8, maxtime=1e-5, num_steps=300, trace_tolerance=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='GuidingCenterAdaptative',boundary=None): particles.to_full_orbit(field) - tracing = Tracing(field=field, model=model, particles=particles, maxtime=maxtime, - timestep=timestep,times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance,boundary=boundary) + tracing = Tracing(field=field, model=model, particles=particles, tmax=tmax, + timestep=timestep,n_save=n_save, rtol=rtol,boundary=boundary) xyz = tracing.trajectories[:,:, :3] R_axis=field.r_axis Z_axis=field.z_axis #Ideally here one would differentiate in time through diffrax !TODO 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)) - v_r_cross=jnp.diff(r_cross,axis=1)#/tracing.times_to_trace*tracing.maxtime + 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): @@ -89,7 +89,7 @@ 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, maxtime=MAXTIME_TRACING, num_steps=NUM_STEPS, trace_tolerance=TRACE_TOLERANCE, model=MODEL) +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") @@ -116,8 +116,8 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): initial_xyz_plot=jnp.array([LARGE_R*jnp.cos(phi_array_plot), LARGE_R*jnp.sin(phi_array_plot), 0*phi_array_plot]).T particles_plot = Particles(initial_xyz=initial_xyz_plot) particles_plot.to_full_orbit(opt_field) -tracing_initial = Tracing(field=init_field, particles=particles_plot, maxtime=MAXTIME_TRACING_PLOT, model=MODEL, times_to_trace=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) -tracing_optimized = Tracing(field=opt_field, particles=particles_plot, maxtime=MAXTIME_TRACING_PLOT, model=MODEL, times_to_trace=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) +tracing_initial = Tracing(field=init_field, particles=particles_plot, tmax=MAXTIME_TRACING_PLOT, model=MODEL, n_save=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) +tracing_optimized = Tracing(field=opt_field, particles=particles_plot, tmax=MAXTIME_TRACING_PLOT, model=MODEL, n_save=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) # Plot trajectories, before and after optimization fig = plt.figure(figsize=(9, 8)) diff --git a/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py b/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py index f4d69849..eb23f428 100644 --- a/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py +++ b/examples/coil_optimization/optimize_coils_particle_confinement_guidingcenter.py @@ -57,10 +57,10 @@ BAXIS_WEIGHT = 1.; BAXIS_TARGET = 5.7 RADIAL_DRIFT_WEIGHT = 1. -def loss_particle_radial_drift(field, particles, timestep=1.e-8, maxtime=1e-4, num_steps=300, trace_tolerance=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='GuidingCenterAdaptative',boundary=None): particles.to_full_orbit(field) - tracing = Tracing(field=field, model=model, particles=particles, maxtime=maxtime, - timestep=timestep,times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance,boundary=boundary) + tracing = Tracing(field=field, model=model, particles=particles, tmax=tmax, + timestep=timestep,n_save=n_save, rtol=rtol,boundary=boundary) xyz = tracing.trajectories[:,:, :3] R_axis=field.r_axis Z_axis=field.z_axis @@ -93,7 +93,7 @@ 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, maxtime=MAXTIME_TRACING, num_steps=NUM_STEPS, trace_tolerance=TRACE_TOLERANCE, model=MODEL) +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") @@ -119,8 +119,8 @@ def loss_curvature(field,curvature_target=CURVATURE_TARGET): initial_xyz_plot=jnp.array([LARGE_R*jnp.cos(phi_array_plot), LARGE_R*jnp.sin(phi_array_plot), 0*phi_array_plot]).T particles_plot = Particles(initial_xyz=initial_xyz_plot) particles_plot.to_full_orbit(opt_field) -tracing_initial = Tracing(field=init_field, particles=particles_plot, maxtime=MAXTIME_TRACING_PLOT, model=MODEL, times_to_trace=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) -tracing_optimized = Tracing(field=opt_field, particles=particles_plot, maxtime=MAXTIME_TRACING_PLOT, model=MODEL, times_to_trace=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) +tracing_initial = Tracing(field=init_field, particles=particles_plot, tmax=MAXTIME_TRACING_PLOT, model=MODEL, n_save=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) +tracing_optimized = Tracing(field=opt_field, particles=particles_plot, tmax=MAXTIME_TRACING_PLOT, model=MODEL, n_save=NUM_STEPS, timestep=TIMESTEP, atol=TRACE_TOLERANCE, rtol=TRACE_TOLERANCE) # Plot trajectories, before and after optimization fig = plt.figure(figsize=(9, 8)) 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 b2a96a2b..4758aa3f 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 @@ -16,7 +16,7 @@ from scipy.optimize import least_squares # Optimization parameters -maximum_function_evaluations=100 +max_nfev=100 input_filepath = os.path.join(os.path.dirname(__file__), "..", "input_files") vmec_input = os.path.join(input_filepath, 'wout_LandremanPaul2021_QA_reactorScale_lowres.nc') @@ -148,7 +148,7 @@ def loss_curvature(field): t_start = time() i=0 -while i<=maximum_function_evaluations and (jnp.linalg.norm(grad[0])>omega_tol or alm.norm_constraints(info[2])>eta_tol): +while i<=max_nfev and (jnp.linalg.norm(grad[0])>omega_tol or alm.norm_constraints(info[2])>eta_tol): #One step of ALM optimization params, lag_state,grad,info = ALM.update(params,lag_state,grad,info) #if i % 5 == 0: @@ -170,7 +170,7 @@ def loss_curvature(field): """ Optimizing the total loss """ t_start = time() -res = least_squares(L_total, L_total.starting_dofs, L_total.grad, verbose=2, ftol=1e-5, gtol=1e-5, xtol=1e-14, max_nfev=maximum_function_evaluations) +res = least_squares(L_total, L_total.starting_dofs, L_total.grad, verbose=2, ftol=1e-5, gtol=1e-5, xtol=1e-14, max_nfev=max_nfev) t_end = time() print(f"\nOptimization took {t_end - t_start:.2f} seconds") 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 26b86db6..34a6334c 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 @@ -57,7 +57,7 @@ def loss_curvature_constraint(field, max_coil_curvature): # Optimization parameters -maximum_function_evaluations = 10 +max_nfev = 10 MAX_COIL_LENGTH = 40.0 MAX_COIL_CURVATURE = 0.5 @@ -139,11 +139,11 @@ def loss_curvature_constraint(field, max_coil_curvature): params = field_initial.dofs, lagrange_params lag_state, grad, info = ALM.init(params) -print(f"Optimizing coils with {maximum_function_evaluations} function evaluations using stochastic ALM.") +print(f"Optimizing coils with {max_nfev} function evaluations using stochastic ALM.") time0 = time() i = 0 -while i <= maximum_function_evaluations and (jnp.linalg.norm(grad[0]) > omega_tol or alm.norm_constraints(info[2]) > eta_tol): +while i <= max_nfev and (jnp.linalg.norm(grad[0]) > omega_tol or alm.norm_constraints(info[2]) > eta_tol): params, lag_state, grad, info = ALM.update(params, lag_state, grad, info) print(f"i: {i}, loss f: {info[0]:g}, loss L: {info[1]:g}, " f"infeasibility: {alm.total_infeasibility(info[2]):g}") i += 1 diff --git a/examples/coil_optimization/optimize_multiple_objectives.py b/examples/coil_optimization/optimize_multiple_objectives.py index 7923f5d2..a9a54863 100644 --- a/examples/coil_optimization/optimize_multiple_objectives.py +++ b/examples/coil_optimization/optimize_multiple_objectives.py @@ -4,14 +4,14 @@ 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.objective_functions import loss_normB_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_normB_axis_average), vmec=vmec, function_inputs={ "max_coil_length": 42, @@ -19,8 +19,8 @@ }, opt_config={ "n_trials": 4, - "maximum_function_evaluations": 300, - "tolerance_optimization": 1e-5, + "max_nfev": 300, + "tol": 1e-5, "optimizer_choices": ["adam", "amsgrad", "sgd"], "num_coils": 4, "order_Fourier": 6, diff --git a/examples/comparisons_simsopt/field_lines.py b/examples/comparisons_simsopt/field_lines.py index 34a7c96a..1f3d302f 100644 --- a/examples/comparisons_simsopt/field_lines.py +++ b/examples/comparisons_simsopt/field_lines.py @@ -16,8 +16,8 @@ nfieldlines = 5 axis_shift=0.02 R0 = jnp.linspace(1.2125346+axis_shift, 1.295-axis_shift, nfieldlines) -trace_tolerance_array = [1e-5, 1e-7, 1e-9, 1e-11, 1e-13] -trace_tolerance_ESSOS = 1e-9 +rtol_array = [1e-5, 1e-7, 1e-9, 1e-11, 1e-13] +rtol_ESSOS = 1e-9 mass=PROTON_MASS energy=5000*ONE_EV @@ -46,11 +46,11 @@ print(f'Output being saved to {output_dir}') print(f'SIMSOPT LandremanPaulQA json file location: {LandremanPaulQA_json_file}\n') -for trace_tolerance_SIMSOPT in trace_tolerance_array: - print(f'Tracing SIMSOPT field lines with tolerance={trace_tolerance_SIMSOPT}') +for rtol_SIMSOPT in rtol_array: + print(f'Tracing SIMSOPT field lines with tolerance={rtol_SIMSOPT}') t1 = time() trajectories_SIMSOPT, trajectories_SIMSOPT_phi_hits = block_until_ready(compute_fieldlines( - field_simsopt, R0, Z0, tmax=tmax_fl, tol=trace_tolerance_SIMSOPT, phis=phis_poincare)) + field_simsopt, R0, Z0, tmax=tmax_fl, tol=rtol_SIMSOPT, phis=phis_poincare)) runtime_SIMSOPT = time() - t1 runtime_SIMSOPT_array.append(runtime_SIMSOPT) avg_steps_SIMSOPT = sum([len(l) for l in trajectories_SIMSOPT]) // nfieldlines @@ -70,18 +70,18 @@ # Creating a tracing object for compilation compile_tracing = Tracing(field=field_essos, model='FieldLine', initial_conditions=jnp.array([R0*jnp.cos(phi0), R0*jnp.sin(phi0), Z0]).T, - maxtime=tmax_fl, timestep=tmax_fl/100, times_to_trace=100, - atol=trace_tolerance_array[0], rtol=trace_tolerance_array[0]) + tmax=tmax_fl, timestep=tmax_fl/100, n_save=100, + atol=rtol_array[0], rtol=rtol_array[0]) block_until_ready(compile_tracing.trajectories) -for index, trace_tolerance_ESSOS in enumerate(trace_tolerance_array): +for index, rtol_ESSOS in enumerate(rtol_array): num_steps_essos = int(avg_steps_SIMSOPT_array[index]) - print(f'Tracing ESSOS field lines with tolerance={trace_tolerance_ESSOS}') + print(f'Tracing ESSOS field lines with tolerance={rtol_ESSOS}') start_time = time() tracing = Tracing(field=field_essos, model='FieldLine', initial_conditions=jnp.array([R0*jnp.cos(phi0), R0*jnp.sin(phi0), Z0]).T, - maxtime=tmax_fl, timestep=tmax_fl/num_steps_essos, times_to_trace=num_steps_essos, - atol=trace_tolerance_ESSOS, rtol=trace_tolerance_ESSOS) + tmax=tmax_fl, timestep=tmax_fl/num_steps_essos, n_save=num_steps_essos, + atol=rtol_ESSOS, rtol=rtol_ESSOS) block_until_ready(tracing.trajectories) runtime_ESSOS = time() - start_time runtime_ESSOS_array.append(runtime_ESSOS) @@ -97,8 +97,8 @@ print('Plotting the results to output directory...') # Plot time comparison in a bar chart -quantities = [(fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$", runtime_ESSOS_array[tolerance_idx], runtime_SIMSOPT_array[tolerance_idx]) - for tolerance_idx in range(len(trace_tolerance_array))] +quantities = [(fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$", runtime_ESSOS_array[tolerance_idx], runtime_SIMSOPT_array[tolerance_idx]) + for tolerance_idx in range(len(rtol_array))] labels = [q[0] for q in quantities] essos_vals = [q[1] for q in quantities] @@ -136,7 +136,7 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): plt.figure(figsize=(9, 6)) avg_relative_xyz_error_array = [] -for tolerance_idx in range(len(trace_tolerance_array)): +for tolerance_idx in range(len(rtol_array)): this_trajectory_SIMSOPT = jnp.stack([interpolate_SIMSOPT_to_ESSOS( trajectories_SIMSOPT_array[tolerance_idx][particle_idx], times_essos_array[tolerance_idx] ) for particle_idx in range(nfieldlines)]) @@ -148,7 +148,7 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): avg_relative_xyz_errors = jnp.mean(relative_xyz_errors, axis=0) avg_relative_xyz_error_array.append(jnp.mean(avg_relative_xyz_errors)) - plt.plot(times_essos_array[tolerance_idx], avg_relative_xyz_errors, label=rf'tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$') + plt.plot(times_essos_array[tolerance_idx], avg_relative_xyz_errors, label=rf'tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$') plt.legend() plt.xlabel('Time (a.u.)') @@ -157,8 +157,8 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): plt.ylabel(r'Relative $x,y,z$ Error') plt.savefig(os.path.join(output_dir, f'comparisons_fl_error_xyz.pdf'), dpi=150) -quantities = [(fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$", avg_relative_xyz_error_array[tolerance_idx]) - for tolerance_idx in range(len(trace_tolerance_array))] +quantities = [(fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$", avg_relative_xyz_error_array[tolerance_idx]) + for tolerance_idx in range(len(rtol_array))] labels = [q[0] for q in quantities] xyz_vals = [q[1] for q in quantities] diff --git a/examples/comparisons_simsopt/full_orbit.py b/examples/comparisons_simsopt/full_orbit.py index 44355fe1..c36f9ee3 100644 --- a/examples/comparisons_simsopt/full_orbit.py +++ b/examples/comparisons_simsopt/full_orbit.py @@ -21,8 +21,8 @@ nparticles = 5 axis_shft=0.02 R0 = jnp.linspace(1.2125346+axis_shft, 1.295-axis_shft, nparticles) -trace_tolerance_array = [1e-5, 1e-7, 1e-9, 1e-11, 1e-13] -trace_tolerance_ESSOS = 1e-9 +rtol_array = [1e-5, 1e-7, 1e-9, 1e-11, 1e-13] +rtol_ESSOS = 1e-9 mass=PROTON_MASS energy=5000*ONE_EV @@ -49,13 +49,13 @@ relative_energy_error_SIMSOPT_array = [] print(f'Output being saved to {output_dir}') print(f'SIMSOPT LandremanPaulQA json file location: {LandremanPaulQA_json_file}\n') -for trace_tolerance_SIMSOPT in trace_tolerance_array: - print(f'Tracing SIMSOPT full orbit with tolerance={trace_tolerance_SIMSOPT}') +for rtol_SIMSOPT in rtol_array: + print(f'Tracing SIMSOPT full orbit with tolerance={rtol_SIMSOPT}') t1 = time() trajectories_SIMSOPT, trajectories_SIMSOPT_phi_hits = block_until_ready(trace_particles( field=field_simsopt, xyz_inits=particles.initial_xyz, mass=particles.mass, parallel_speeds=particles.initial_vparallel, tmax=tmax, mode='full', - charge=particles.charge, Ekin=particles.energy, tol=trace_tolerance_SIMSOPT)) + charge=particles.charge, Ekin=particles.energy, tol=rtol_SIMSOPT)) runtime_SIMSOPT = time() - t1 runtime_SIMSOPT_array.append(runtime_SIMSOPT) avg_steps_SIMSOPT = sum([len(l) for l in trajectories_SIMSOPT]) // nparticles @@ -80,26 +80,26 @@ # Creating a tracing object for compilation if method == 'Dopri5': compile_tracing = Tracing(field=field_essos, model='FullOrbit', particles=particles, - maxtime=tmax, timestep=tmax/100, times_to_trace=100, - atol=trace_tolerance_array[0], rtol=trace_tolerance_array[0]) + 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, - maxtime=tmax, timestep=tmax/100, times_to_trace=100) + tmax=tmax, timestep=tmax/100, n_save=100) block_until_ready(compile_tracing.trajectories) -for tolerance_idx, trace_tolerance_ESSOS in enumerate(trace_tolerance_array): - print(f'Tracing ESSOS full orbit with tolerance={trace_tolerance_ESSOS}') +for tolerance_idx, rtol_ESSOS in enumerate(rtol_array): + print(f'Tracing ESSOS full orbit with tolerance={rtol_ESSOS}') start_time = time() if method == 'Dopri5': num_steps_essos = 10000 tracing = Tracing(field=field_essos, model='FullOrbit', particles=particles, - maxtime=tmax, timestep=tmax/num_steps_essos, times_to_trace=num_steps_essos, - atol=trace_tolerance_ESSOS, rtol=trace_tolerance_ESSOS) + tmax=tmax, timestep=tmax/num_steps_essos, n_save=num_steps_essos, + 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, - maxtime=tmax, timestep=tmax/num_steps_essos, times_to_trace=num_steps_essos) + tmax=tmax, timestep=tmax/num_steps_essos, n_save=num_steps_essos) block_until_ready(tracing.trajectories) runtime_ESSOS = time() - start_time @@ -121,7 +121,7 @@ SIMSOPT_energy_interp = [] -for tolerance_idx in range(len(trace_tolerance_array)): +for tolerance_idx in range(len(rtol_array)): interpolation = jnp.stack([ jnp.interp(times_essos_array[tolerance_idx], trajectories_SIMSOPT_array[tolerance_idx][particle_idx][:, 0], relative_energy_error_SIMSOPT_array[tolerance_idx][particle_idx]) for particle_idx in range(nparticles) @@ -131,8 +131,8 @@ plt.plot(times_essos_array[tolerance_idx]*1000, jnp.mean(interpolation, axis=0), '--', color=colors[tolerance_idx]) plt.plot(times_essos_array[tolerance_idx]*1000, jnp.mean(relative_energy_error_ESSOS_array[tolerance_idx], axis=0), '-', color=colors[tolerance_idx]) -legend_elements = [Line2D([0], [0], color=colors[tolerance_idx], linestyle='-', label=fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$") - for tolerance_idx in range(len(trace_tolerance_array))] +legend_elements = [Line2D([0], [0], color=colors[tolerance_idx], linestyle='-', label=fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$") + for tolerance_idx in range(len(rtol_array))] plt.legend(handles=legend_elements, loc='lower right', title='ESSOS (─), SIMSOPT (--)', fontsize=14, title_fontsize=14) plt.yscale('log') @@ -146,8 +146,8 @@ # Plot time comparison in a bar chart -quantities = [(fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$", runtime_ESSOS_array[tolerance_idx], runtime_SIMSOPT_array[tolerance_idx]) - for tolerance_idx in range(len(trace_tolerance_array))] +quantities = [(fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$", runtime_ESSOS_array[tolerance_idx], runtime_SIMSOPT_array[tolerance_idx]) + for tolerance_idx in range(len(rtol_array))] labels = [q[0] for q in quantities] essos_vals = [q[1] for q in quantities] @@ -197,7 +197,7 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): avg_relative_xyz_error_array = [] avg_relative_v_error_array = [] -for tolerance_idx in range(len(trace_tolerance_array)): +for tolerance_idx in range(len(rtol_array)): this_trajectory_SIMSOPT = jnp.stack([interpolate_SIMSOPT_to_ESSOS( trajectories_SIMSOPT_array[tolerance_idx][particle_idx], times_essos_array[tolerance_idx] ) for particle_idx in range(nparticles)]) @@ -212,8 +212,8 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): avg_relative_xyz_error_array.append(jnp.mean(avg_relative_xyz_errors)) avg_relative_v_error_array.append(jnp.mean(avg_relative_v_errors)) - xyz_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_xyz_errors, label=rf'tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$') - v_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_v_errors, label=rf'tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$') + xyz_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_xyz_errors, label=rf'tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$') + v_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_v_errors, label=rf'tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$') for ax, fig in zip([xyz_error_ax, v_error_ax], [xyz_error_fig, v_error_fig]): ax.legend() @@ -229,8 +229,8 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): xyz_error_fig.savefig(os.path.join(output_dir, f'comparisons_fo_boris_error_xyz.pdf'), dpi=150) v_error_fig.savefig(os.path.join(output_dir, f'comparisons_fo_boris_error_v.pdf'), dpi=150) -quantities = [(fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$", avg_relative_xyz_error_array[tolerance_idx], avg_relative_v_error_array[tolerance_idx]) - for tolerance_idx in range(len(trace_tolerance_array))] +quantities = [(fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$", avg_relative_xyz_error_array[tolerance_idx], avg_relative_v_error_array[tolerance_idx]) + for tolerance_idx in range(len(rtol_array))] labels = [q[0] for q in quantities] xyz_vals = [q[1] for q in quantities] diff --git a/examples/comparisons_simsopt/guiding_center.py b/examples/comparisons_simsopt/guiding_center.py index 80ee1681..fdc47cd8 100644 --- a/examples/comparisons_simsopt/guiding_center.py +++ b/examples/comparisons_simsopt/guiding_center.py @@ -16,8 +16,8 @@ nparticles = 5 axis_shft=0.02 R0 = jnp.linspace(1.2125346+axis_shft, 1.295-axis_shft, nparticles) -trace_tolerance_array = [1e-5, 1e-7, 1e-9, 1e-11, 1e-13] -trace_tolerance_ESSOS = 1e-9 +rtol_array = [1e-5, 1e-7, 1e-9, 1e-11, 1e-13] +rtol_ESSOS = 1e-9 mass=PROTON_MASS energy=5000*ONE_EV @@ -46,13 +46,13 @@ relative_energy_error_SIMSOPT_array = [] print(f'Output being saved to {output_dir}') print(f'SIMSOPT LandremanPaulQA json file location: {LandremanPaulQA_json_file}\n') -for trace_tolerance_SIMSOPT in trace_tolerance_array: - print(f'Tracing SIMSOPT guiding center with tolerance={trace_tolerance_SIMSOPT}') +for rtol_SIMSOPT in rtol_array: + print(f'Tracing SIMSOPT guiding center with tolerance={rtol_SIMSOPT}') t1 = time() trajectories_SIMSOPT, trajectories_SIMSOPT_phi_hits = block_until_ready(trace_particles( field=field_simsopt, xyz_inits=particles.initial_xyz, mass=particles.mass, parallel_speeds=particles.initial_vparallel, tmax=tmax_gc, mode='gc_vac', - charge=particles.charge, Ekin=particles.energy, tol=trace_tolerance_SIMSOPT)) + charge=particles.charge, Ekin=particles.energy, tol=rtol_SIMSOPT)) runtime_SIMSOPT = time() - t1 runtime_SIMSOPT_array.append(runtime_SIMSOPT) avg_steps_SIMSOPT = sum([len(l) for l in trajectories_SIMSOPT]) // nparticles @@ -81,18 +81,18 @@ # Creating a tracing object for compilation compile_tracing = Tracing(field=field_essos, model='GuidingCenter', particles=particles, - maxtime=tmax_gc, timestep=tmax_gc/100, times_to_trace=100, - atol=trace_tolerance_array[0], rtol=trace_tolerance_array[0]) + tmax=tmax_gc, timestep=tmax_gc/100, n_save=100, + atol=rtol_array[0], rtol=rtol_array[0]) block_until_ready(compile_tracing.trajectories) -for index, trace_tolerance_ESSOS in enumerate(trace_tolerance_array): +for index, rtol_ESSOS in enumerate(rtol_array): num_steps_essos = avg_steps_SIMSOPT_array[index] - print(f'Tracing ESSOS guiding center with tolerance={trace_tolerance_ESSOS}') + print(f'Tracing ESSOS guiding center with tolerance={rtol_ESSOS}') start_time = time() num_steps_int = int(num_steps_essos) tracing = Tracing(field=field_essos, model='GuidingCenter', particles=particles, - maxtime=tmax_gc, timestep=tmax_gc/num_steps_int, times_to_trace=num_steps_int, - atol=trace_tolerance_ESSOS, rtol=trace_tolerance_ESSOS) + tmax=tmax_gc, timestep=tmax_gc/num_steps_int, n_save=num_steps_int, + atol=rtol_ESSOS, rtol=rtol_ESSOS) block_until_ready(tracing.trajectories) runtime_ESSOS = time() - start_time runtime_ESSOS_array.append(runtime_ESSOS) @@ -113,7 +113,7 @@ SIMSOPT_energy_interp = [] -for tolerance_idx in range(len(trace_tolerance_array)): +for tolerance_idx in range(len(rtol_array)): interpolation = jnp.stack([ jnp.interp(times_essos_array[tolerance_idx], trajectories_SIMSOPT_array[tolerance_idx][particle_idx][:, 0], relative_energy_error_SIMSOPT_array[tolerance_idx][particle_idx]) for particle_idx in range(nparticles) @@ -123,8 +123,8 @@ plt.plot(times_essos_array[tolerance_idx]*1000, jnp.mean(interpolation, axis=0), '--', color=colors[tolerance_idx]) plt.plot(times_essos_array[tolerance_idx]*1000, jnp.mean(relative_energy_error_ESSOS_array[tolerance_idx], axis=0), '-', color=colors[tolerance_idx]) -legend_elements = [Line2D([0], [0], color=colors[tolerance_idx], linestyle='-', label=fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$") - for tolerance_idx in range(len(trace_tolerance_array))] +legend_elements = [Line2D([0], [0], color=colors[tolerance_idx], linestyle='-', label=fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$") + for tolerance_idx in range(len(rtol_array))] plt.legend(handles=legend_elements, loc='lower right', title='ESSOS (─), SIMSOPT (--)', fontsize=14, title_fontsize=14) plt.yscale('log') @@ -135,8 +135,8 @@ # Plot time comparison in a bar chart -quantities = [(fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$", runtime_ESSOS_array[tolerance_idx], runtime_SIMSOPT_array[tolerance_idx]) - for tolerance_idx in range(len(trace_tolerance_array))] +quantities = [(fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$", runtime_ESSOS_array[tolerance_idx], runtime_SIMSOPT_array[tolerance_idx]) + for tolerance_idx in range(len(rtol_array))] labels = [q[0] for q in quantities] essos_vals = [q[1] for q in quantities] @@ -177,7 +177,7 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): avg_relative_xyz_error_array = [] avg_relative_v_error_array = [] -for tolerance_idx in range(len(trace_tolerance_array)): +for tolerance_idx in range(len(rtol_array)): this_trajectory_SIMSOPT = jnp.stack([interpolate_SIMSOPT_to_ESSOS( trajectories_SIMSOPT_array[tolerance_idx][particle_idx], times_essos_array[tolerance_idx] ) for particle_idx in range(nparticles)]) @@ -192,8 +192,8 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): avg_relative_xyz_error_array.append(jnp.mean(avg_relative_xyz_errors)) avg_relative_v_error_array.append(jnp.mean(avg_relative_v_errors)) - xyz_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_xyz_errors, label=rf'tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$') - vpar_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_v_errors, label=rf'tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$') + xyz_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_xyz_errors, label=rf'tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$') + vpar_error_ax.plot(times_essos_array[tolerance_idx]*1000, avg_relative_v_errors, label=rf'tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$') for ax, fig in zip([xyz_error_ax, vpar_error_ax], [xyz_error_fig, vpar_error_fig]): ax.legend() @@ -205,8 +205,8 @@ def interpolate_SIMSOPT_to_ESSOS(trajectory_SIMSOPT, time_ESSOS): xyz_error_fig.savefig(os.path.join(output_dir, f'comparisons_gc_error_xyz.pdf'), dpi=150) vpar_error_fig.savefig(os.path.join(output_dir, f'comparisons_gc_error_vpar.pdf'), dpi=150) -quantities = [(fr"tol=$10^{{{int(jnp.log10(trace_tolerance_array[tolerance_idx])-1e-3)}}}$", avg_relative_xyz_error_array[tolerance_idx], avg_relative_v_error_array[tolerance_idx]) - for tolerance_idx in range(len(trace_tolerance_array))] +quantities = [(fr"tol=$10^{{{int(jnp.log10(rtol_array[tolerance_idx])-1e-3)}}}$", avg_relative_xyz_error_array[tolerance_idx], avg_relative_v_error_array[tolerance_idx]) + for tolerance_idx in range(len(rtol_array))] labels = [q[0] for q in quantities] xyz_vals = [q[1] for q in quantities] diff --git a/examples/fieldline_tracing/connection_length_coils.py b/examples/fieldline_tracing/connection_length_coils.py index 9e826b07..134c9659 100644 --- a/examples/fieldline_tracing/connection_length_coils.py +++ b/examples/fieldline_tracing/connection_length_coils.py @@ -34,7 +34,7 @@ def wall(xyz): # positive inside the wall, zero on it # Poincare section of the closed vacuum surfaces for context poincare = trace_field_lines(field, jnp.stack([jnp.linspace(1.22, 1.42, 10), jnp.zeros(10), jnp.zeros(10)], 1), - length=1000.0, samples=100000, progress=False, label=None) + length=1000.0, n_save=100000, progress=False, label=None) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.8), gridspec_kw={"width_ratios": [1, 1.3]}) plt.sca(ax1) poincare.poincare_plot(ax=ax1, show=False, shifts=[0.0], color="0.65", s=0.2) diff --git a/examples/fieldline_tracing/poincare_guiding_center_coils.py b/examples/fieldline_tracing/poincare_guiding_center_coils.py index 9ea33580..83adfb26 100644 --- a/examples/fieldline_tracing/poincare_guiding_center_coils.py +++ b/examples/fieldline_tracing/poincare_guiding_center_coils.py @@ -12,8 +12,8 @@ nparticles_per_core=6 nparticles = nparticles_per_core R0 = jnp.linspace(1.2, 1.33, nparticles) -trace_tolerance = 1e-7 -num_steps = 10000 +rtol = 1e-7 +n_save = 10000 mass=PROTON_MASS energy=4000*ONE_EV # pitch angle = jnp.arctan(jnp.sqrt((v^2/vparallel^2) - 1)) * 180 / jnp.pi, in degrees @@ -37,7 +37,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance) + tmax=tmax, n_save=n_save, rtol=rtol) print(f"ESSOS tracing took {time()-time0:.2f} seconds") # Plot results diff --git a/examples/fieldline_tracing/trace_fieldlines_coils.py b/examples/fieldline_tracing/trace_fieldlines_coils.py index 4ba77e5a..6c7cf416 100644 --- a/examples/fieldline_tracing/trace_fieldlines_coils.py +++ b/examples/fieldline_tracing/trace_fieldlines_coils.py @@ -12,8 +12,8 @@ nfieldlines_per_core=3 nfieldlines = nfieldlines_per_core R0 = jnp.linspace(1.21, 1.4, nfieldlines) -trace_tolerance = 1e-8 -num_steps = 6000 +rtol = 1e-8 +n_save = 6000 # Load coils and field json_file = os.path.join(os.path.dirname(__file__), '..', 'input_files', 'ESSOS_biot_savart_LandremanPaulQA.json') @@ -28,7 +28,7 @@ # Trace in ESSOS time0 = time() tracing = block_until_ready(Tracing(field=field, model='FieldLineAdaptative', initial_conditions=initial_xyz, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance)) + 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 ca4e360b..02354199 100644 --- a/examples/fieldline_tracing/trace_fieldlines_vmec.py +++ b/examples/fieldline_tracing/trace_fieldlines_vmec.py @@ -11,8 +11,8 @@ nfieldlines_per_core=6 nfieldlines = nfieldlines_per_core R0 = jnp.linspace(0.05, 0.6, nfieldlines) -trace_tolerance = 1e-10 -num_steps = 10000 +rtol = 1e-10 +n_save = 10000 # Load coils and field wout_file = os.path.join(os.path.dirname(__file__), '..', 'input_files',"wout_QH_simple_scaled.nc") @@ -26,7 +26,7 @@ # Trace in ESSOS time0 = time() tracing = block_until_ready(Tracing(field=vmec, model='FieldLineAdaptative', initial_conditions=initial_xyz, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance)) + tmax=tmax, n_save=n_save, rtol=rtol)) print(f"ESSOS tracing took {time()-time0:.2f} seconds") trajectories = tracing.trajectories diff --git a/examples/paper/fo_integrators.py b/examples/paper/fo_integrators.py index 691312d3..dd60dfcc 100644 --- a/examples/paper/fo_integrators.py +++ b/examples/paper/fo_integrators.py @@ -42,16 +42,16 @@ for method_name, solver_class in adaptive_solvers: energies = [] tracing_times = [] - for trace_tolerance in [1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15]: + for rtol in [1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15]: time0 = time() tracing = Tracing(field=field, model='FullOrbit', particles=particles, - maxtime=tmax, timestep=1e-9, - atol=trace_tolerance, rtol=trace_tolerance, + tmax=tmax, timestep=1e-9, + rtol=rtol, solver=solver_class()) block_until_ready(tracing.trajectories) tracing_times += [time() - time0] - print(f"Tracing with adaptive {method_name} and tolerance {trace_tolerance:.0e} took {tracing_times[-1]:.2f} seconds") + print(f"Tracing with adaptive {method_name} and tolerance {rtol:.0e} took {tracing_times[-1]:.2f} seconds") energies += [jnp.mean(jnp.abs(tracing.energy()-particles.energy)/particles.energy)] ax.plot(tracing_times, energies, label=f'{method_name} adapt', marker='o', markersize=3, linestyle='-') @@ -65,7 +65,7 @@ dt = 1/(n_points_in_gyration*cyclotron_frequency) time0 = time() tracing = Tracing(field=field, model='FullOrbit_Boris', particles=particles, - maxtime=tmax, timestep=dt) + 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 fdccdd39..5ae79310 100644 --- a/examples/paper/gc_integrators.py +++ b/examples/paper/gc_integrators.py @@ -34,11 +34,11 @@ # Tracing parameters tmax = 1e-4 -# Two figures: energy error vs computation time, and energy error vs tolerance. +# Two figures: energy error vs computation time, and energy error vs rtol. fig, ax = plt.subplots(figsize=(9, 6)) fig_tol, ax_tol = plt.subplots(figsize=(9, 6)) markers = ["o-", "^-", "*-", "s-"] -# For each adaptive solver, sweep the integration tolerance and record both the +# For each adaptive solver, sweep the integration rtol and record both the # resulting energy error and the wall-clock time. Kvaerno5 is implicit; the # others are explicit Runge-Kutta methods. solvers = [('Tsit5', diffrax.Tsit5), @@ -49,16 +49,16 @@ energies = [] tracing_times = [] tolerances = [1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16] - for tolerance in tolerances: + for rtol in tolerances: time0 = time() tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, - maxtime=tmax, timestep=1e-7, - atol=tolerance, rtol=tolerance, + tmax=tmax, timestep=1e-7, + rtol=rtol, solver=solver_class()) block_until_ready(tracing.trajectories) tracing_times += [time() - time0] - print(f"Tracing with adaptive {method} and {tolerance=:.0e} took {tracing_times[-1]:.2f} seconds") + print(f"Tracing with adaptive {method} and {rtol=:.0e} took {tracing_times[-1]:.2f} seconds") energies += [jnp.max(jnp.abs(tracing.energy()-particles.energy)/particles.energy)] ax.plot(tracing_times, energies, label=f'{method} adapt', marker='o', markersize=3) @@ -66,7 +66,7 @@ gc.collect() ax.set_xlabel('Computation time (s)') -ax_tol.set_xlabel('Tracing tolerance') +ax_tol.set_xlabel('Tracing rtol') ax.set_xlim(1e-1, 1e2) ax_tol.set_xlim(tolerances[-1], tolerances[0]) diff --git a/examples/paper/gc_vs_fo.py b/examples/paper/gc_vs_fo.py index 39046e90..60cefc77 100644 --- a/examples/paper/gc_vs_fo.py +++ b/examples/paper/gc_vs_fo.py @@ -35,7 +35,7 @@ # Tracing parameters tmax = 1e-5 -trace_tolerance = 1e-14 +rtol = 1e-14 dt_gc = 1e-7 dt_fo = 1e-9 num_steps_gc = int(tmax/dt_gc) @@ -44,15 +44,15 @@ # Trace in ESSOS time0 = time() tracing_gc = Tracing(field=field, model='GuidingCenter', particles=particles, - maxtime=tmax, timestep=dt_gc, atol=trace_tolerance, rtol=trace_tolerance, - times_to_trace=200) + tmax=tmax, timestep=dt_gc, rtol=rtol, + n_save=200) trajectories_guidingcenter = block_until_ready(tracing_gc.trajectories) print(f"ESSOS guiding center tracing took {time()-time0:.2f} seconds") time0 = time() -tracing_fo = Tracing(field=field, model='FullOrbit', particles=particles, maxtime=tmax, - timestep=dt_fo, atol=trace_tolerance, rtol=trace_tolerance, - times_to_trace=600) +tracing_fo = Tracing(field=field, model='FullOrbit', particles=particles, tmax=tmax, + timestep=dt_fo, rtol=rtol, + n_save=600) block_until_ready(tracing_fo.trajectories) print(f"ESSOS full orbit tracing took {time()-time0:.2f} seconds") diff --git a/examples/paper/poincare_plots.py b/examples/paper/poincare_plots.py index 9a27a72d..f4f4d4dc 100644 --- a/examples/paper/poincare_plots.py +++ b/examples/paper/poincare_plots.py @@ -22,7 +22,7 @@ nparticles = 1 nfieldlines = 8 s = 0.25 # s-coordinate: flux surface label -trace_tolerance = 1e-15 +rtol = 1e-15 dt_fo = 1e-9 dt_gc = 1e-7 timesteps_gc = int(tmax_gc/dt_gc) @@ -51,13 +51,13 @@ # Trace in ESSOS # time0 = time() # tracing_fl = Tracing(field=field, model='FieldLine', initial_conditions=initial_xyz_fieldlines, -# maxtime=tmax_fl, timesteps=tmax_fl*10, tol_step_size=trace_tolerance) +# tmax=tmax_fl, timesteps=tmax_fl*10, tol_step_size=rtol) # block_until_ready(tracing_fl) # print(f"ESSOS tracing of {nfieldlines} field lines took {time()-time0:.2f} seconds") time0 = time() -tracing_fo = Tracing(field=field, model='FullOrbit', particles=particles, maxtime=tmax_fo, - timestep=dt_fo, atol=trace_tolerance, rtol=trace_tolerance) +tracing_fo = Tracing(field=field, model='FullOrbit', particles=particles, tmax=tmax_fo, + timestep=dt_fo, rtol=rtol) # tracing_fo.trajectories = tracing_fo.trajectories[:, 0::100, :] # tracing_fo.times = tracing_fo.times[0::100] # tracing_fo.energy = tracing_fo.energy[:, 0::100] @@ -65,8 +65,8 @@ print(f"ESSOS tracing of {nparticles} particles with FO for {tmax_fo:.1e}s took {time()-time0:.2f} seconds") time0 = time() -tracing_gc = Tracing(field=field, model='GuidingCenter', particles=particles, maxtime=tmax_gc, - timestep=dt_gc, atol=trace_tolerance, rtol=trace_tolerance) +tracing_gc = Tracing(field=field, model='GuidingCenter', particles=particles, tmax=tmax_gc, + timestep=dt_gc, rtol=rtol) block_until_ready(tracing_gc) print(f"ESSOS tracing of {nparticles} particles with GC for {tmax_gc:.1e}s took {time()-time0:.2f} seconds") diff --git a/examples/particle_tracing/trace_particles_boozer_vs_vmec.py b/examples/particle_tracing/trace_particles_boozer_vs_vmec.py index 30094196..09f5df91 100644 --- a/examples/particle_tracing/trace_particles_boozer_vs_vmec.py +++ b/examples/particle_tracing/trace_particles_boozer_vs_vmec.py @@ -16,7 +16,7 @@ # Needs booz_xform_jax (pip install booz_xform_jax). tmax = 1e-4 nparticles = number_of_processors_to_use*16 -times_to_trace = 200 +n_save = 200 j = 69 # half-grid surface of the births, s = (j + 1/2) / (ns - 1) # Wall time without JIT: subtract the tracing, lowering and compile events JAX reports @@ -56,13 +56,13 @@ def run_time(function): speed = np.sqrt(2*FUSION_ALPHA_PARTICLE_ENERGY/ALPHA_PARTICLE_MASS) boozer, time_boozer = run_time(lambda: trace_boozer( boozer_field, s, theta_b, zeta_b, pitch, speed=speed, mass=ALPHA_PARTICLE_MASS, - charge=ALPHA_PARTICLE_CHARGE, tmax=tmax, timestep=1.25e-7, n_save=times_to_trace)) + charge=ALPHA_PARTICLE_CHARGE, tmax=tmax, timestep=1.25e-7, n_save=n_save)) # 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, - maxtime=tmax, timestep=1e-8, times_to_trace=times_to_trace, atol=1e-7, rtol=1e-7)) + 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 for name, lost, run in (("Boozer", boozer.lost.mean(), time_boozer), diff --git a/examples/particle_tracing/trace_particles_coils_fullorbit.py b/examples/particle_tracing/trace_particles_coils_fullorbit.py index 9e439b38..81b29b7c 100644 --- a/examples/particle_tracing/trace_particles_coils_fullorbit.py +++ b/examples/particle_tracing/trace_particles_coils_fullorbit.py @@ -14,8 +14,8 @@ nparticles_per_core=2 nparticles = nparticles_per_core R0 = jnp.linspace(1.23, 1.27, nparticles) -trace_tolerance = 1e-7 -num_steps = 3000 +rtol = 1e-7 +n_save = 3000 mass=PROTON_MASS energy=4000*ONE_EV @@ -33,7 +33,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=field, model='FullOrbit_Boris', particles=particles, - maxtime=tmax, times_to_trace=num_steps,timestep=dt, atol=trace_tolerance,rtol=trace_tolerance) + 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 014c5d59..f071590f 100644 --- a/examples/particle_tracing/trace_particles_coils_guidingcenter.py +++ b/examples/particle_tracing/trace_particles_coils_guidingcenter.py @@ -10,7 +10,7 @@ # Input parameters tmax = 1.e-4 timestep=1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=2 nparticles = nparticles_per_core R0 = jnp.linspace(1.23, 1.27, nparticles) @@ -32,7 +32,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, - maxtime=tmax, timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol) + 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 edd6ccb9..ea1abaf4 100644 --- a/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier.py +++ b/examples/particle_tracing/trace_particles_coils_guidingcenter_with_classifier.py @@ -15,7 +15,7 @@ # Input parameters tmax = 1.e-4 timestep=1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=2 nparticles = nparticles_per_core R0 = 17.0 @@ -57,7 +57,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, - maxtime=tmax, timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol,boundary=boundary) + 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}%") trajectories = tracing.trajectories 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 a2816b0a..3b75b1c8 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 @@ -15,7 +15,7 @@ # Input parameters tmax = 1.e-4 timestep=1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=2 nparticles = nparticles_per_core R0 = 17.0 @@ -53,7 +53,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=field, model='GuidingCenterAdaptative', particles=particles, - maxtime=tmax, timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol,boundary=boundary) + 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}%") trajectories = tracing.trajectories diff --git a/examples/particle_tracing/trace_particles_interpolated_dipoles.py b/examples/particle_tracing/trace_particles_interpolated_dipoles.py index c454afc9..5bc5a65f 100644 --- a/examples/particle_tracing/trace_particles_interpolated_dipoles.py +++ b/examples/particle_tracing/trace_particles_interpolated_dipoles.py @@ -90,8 +90,8 @@ 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, maxtime=tmax, - times_to_trace=200, atol=1e-8, rtol=1e-8, + traces[name] = tracing = Tracing(field=f, model='GuidingCenterAdaptative', particles=particles, tmax=tmax, + n_save=200, atol=1e-8, rtol=1e-8, condition=lambda t, y, args, **kwargs: classifier.evaluate_xyz(y[:3])) tracing.trajectories.block_until_ready() tracing.lost_times = tracing.loss_fraction(classifier)[2] diff --git a/examples/particle_tracing/trace_particles_vmec.py b/examples/particle_tracing/trace_particles_vmec.py index 9bacce9a..97557810 100644 --- a/examples/particle_tracing/trace_particles_vmec.py +++ b/examples/particle_tracing/trace_particles_vmec.py @@ -10,7 +10,7 @@ # Input parameters tmax = 1e-4 timestep = 1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=6 nparticles = nparticles_per_core n_particles_to_plot = 4 @@ -34,8 +34,8 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, maxtime=tmax, - timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol) +tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', 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}%") trajectories = tracing.trajectories diff --git a/examples/particle_tracing/trace_particles_vmec_Electric_field.py b/examples/particle_tracing/trace_particles_vmec_Electric_field.py index 1625ea6b..e78806bb 100644 --- a/examples/particle_tracing/trace_particles_vmec_Electric_field.py +++ b/examples/particle_tracing/trace_particles_vmec_Electric_field.py @@ -11,7 +11,7 @@ # Input parameters tmax = 1.e-4 timestep = 1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=6 nparticles = nparticles_per_core s = 0.6 # s-coordinate: flux surface label @@ -38,8 +38,8 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, electric_field=Electric_field,model='GuidingCenterAdaptative', particles=particles, maxtime=tmax, - timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol) +tracing = Tracing(field=vmec, electric_field=Electric_field,model='GuidingCenterAdaptative', 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}%") trajectories = tracing.trajectories diff --git a/examples/particle_tracing/trace_particles_vmec_classifier.py b/examples/particle_tracing/trace_particles_vmec_classifier.py index 6767990c..88549474 100644 --- a/examples/particle_tracing/trace_particles_vmec_classifier.py +++ b/examples/particle_tracing/trace_particles_vmec_classifier.py @@ -11,7 +11,7 @@ # Input parameters tmax = 1e-4 timestep = 1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=6 nparticles = nparticles_per_core n_particles_to_plot = 4 @@ -35,8 +35,8 @@ charge=ALPHA_PARTICLE_CHARGE, energy=energy, field=vmec) # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, maxtime=tmax, - timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol,boundary=boundary) +tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', 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}%") trajectories = tracing.trajectories diff --git a/examples/particle_tracing/trace_particles_vmec_to_wall.py b/examples/particle_tracing/trace_particles_vmec_to_wall.py index b8ce69f2..4086da9a 100644 --- a/examples/particle_tracing/trace_particles_vmec_to_wall.py +++ b/examples/particle_tracing/trace_particles_vmec_to_wall.py @@ -22,7 +22,7 @@ # Input parameters tmax = 4e-5 timestep = 1.e-9 -times_to_trace = 2000 +n_save = 2000 nparticles_per_core = 8 nparticles = number_of_processors_to_use*nparticles_per_core energy = 3e3*ONE_EV @@ -63,8 +63,8 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', particles=particles, maxtime=tmax, timestep=timestep, - times_to_trace=times_to_trace, atol=atol, rtol=rtol, exterior_field=outside, wall=wall) +tracing = Tracing(field=vmec, model='GuidingCenterAdaptative', 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) print(f"Stayed inside the LCFS: {np.mean(~crossed)*100:.1f}%") diff --git a/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py index ab1639b2..d0789899 100644 --- a/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py +++ b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Adaptative.py @@ -17,7 +17,7 @@ # Input parameters tmax = 1e-4 dt=1.e-14 -times_to_trace=1000 +n_save=1000 nparticles_per_core=10 nparticles = nparticles_per_core s=0.25 @@ -73,7 +73,7 @@ time0 = time() tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuAdaptative', particles=particles, - maxtime=tmax, timestep=dt,times_to_trace=times_to_trace,species=species,tag_gc=0.) + 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/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Fixed.py b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Fixed.py index d7261e53..7d301d30 100644 --- a/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Fixed.py +++ b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_Fixed.py @@ -17,7 +17,7 @@ # Input parameters tmax = 1.e-4 dt=1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=10 nparticles = nparticles_per_core s=0.25 @@ -74,7 +74,7 @@ time0 = time() tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuFixed', particles=particles, - maxtime=tmax, timestep=dt,times_to_trace=times_to_trace,species=species,tag_gc=0.) + 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/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_time.py b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_time.py index 9d4bd199..f8b5d968 100644 --- a/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_time.py +++ b/examples/particle_tracing_collisions/statistics_collisions_velocity_distributions_mu_time.py @@ -17,8 +17,8 @@ nparticles_per_core=100 nparticles = nparticles_per_core s=0.25 -trace_tolerance = 1e-7 -times_to_trace=1000 +rtol = 1e-7 +n_save=1000 mass=PROTON_MASS mass_a=4.*mass mass_e=ELECTRON_MASS @@ -82,7 +82,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuFixed', particles=particles, - maxtime=tmax, timestep=dt,times_to_trace=times_to_trace,species=species,tag_gc=0.) + 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 fig = plt.figure(figsize=(9, 8)) diff --git a/examples/particle_tracing_collisions/trace_particles_coils_guidingcenter_with_classifier_with_collisionsMu.py b/examples/particle_tracing_collisions/trace_particles_coils_guidingcenter_with_classifier_with_collisionsMu.py index df1c4d4e..66f78833 100644 --- a/examples/particle_tracing_collisions/trace_particles_coils_guidingcenter_with_classifier_with_collisionsMu.py +++ b/examples/particle_tracing_collisions/trace_particles_coils_guidingcenter_with_classifier_with_collisionsMu.py @@ -13,7 +13,7 @@ # Input parameters tmax = 1e-4 timestep=1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=2 nparticles = nparticles_per_core R0 = 17.0 @@ -66,7 +66,7 @@ # Trace in ESSOS time0 = time() tracing = Tracing(field=field, model='GuidingCenterCollisionsMuFixed', particles=particles, - maxtime=tmax, timestep=timestep,times_to_trace=times_to_trace, atol=atol,rtol=rtol,tag_gc=1.,species=species,boundary=boundary) + tmax=tmax, timestep=timestep,n_save=n_save, atol=atol,rtol=rtol,tag_gc=1.,species=species,boundary=boundary) print(f"ESSOS tracing took {time()-time0:.2f} seconds") print(f"Final loss fraction: {tracing.loss_fractions[-1]*100:.2f}%") print(f"Particle 1 lost {tracing.lost_energies[1]} Joules while hitting (s,$\\theta$,$\\phi$)=({tracing.lost_positions[1,0]:.2f},{tracing.lost_positions[1,1]:.2f},{tracing.lost_positions[1,2]:.2f})") diff --git a/examples/particle_tracing_collisions/trace_particles_vmec_collisionsMu.py b/examples/particle_tracing_collisions/trace_particles_vmec_collisionsMu.py index 71eee54d..d9dee258 100644 --- a/examples/particle_tracing_collisions/trace_particles_vmec_collisionsMu.py +++ b/examples/particle_tracing_collisions/trace_particles_vmec_collisionsMu.py @@ -11,7 +11,7 @@ # Input parameters tmax = 1.e-4 timestep=1.e-8 -times_to_trace=1000 +n_save=1000 nparticles_per_core=6 nparticles = nparticles_per_core n_particles_to_plot = 4 @@ -47,8 +47,8 @@ # Trace in ESSOS time0 = time() -tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuFixed', particles=particles, maxtime=tmax, - timestep=timestep, times_to_trace=times_to_trace, species=species,tag_gc=1.) +tracing = Tracing(field=vmec, model='GuidingCenterCollisionsMuFixed', particles=particles, tmax=tmax, + timestep=timestep, n_save=n_save, species=species,tag_gc=1.) 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}%") print(f"Particle 1 lost {tracing.lost_energies[0]} Joules while hitting (s, theta, phi)=({tracing.lost_positions[0,0]:.2f},{tracing.lost_positions[0,1]:.2f},{tracing.lost_positions[0,2]:.2f})") diff --git a/examples/simple_examples/coils_from_BOOZ_XFORM.py b/examples/simple_examples/coils_from_BOOZ_XFORM.py index cf38794a..8920f3f6 100644 --- a/examples/simple_examples/coils_from_BOOZ_XFORM.py +++ b/examples/simple_examples/coils_from_BOOZ_XFORM.py @@ -19,8 +19,8 @@ ncoils = 6 tmax = 1100 nfieldlines_per_core=1 -trace_tolerance = 1e-9 -num_steps = 22000 +rtol = 1e-9 +n_save = 22000 order_Fourier_coils = 4 current_on_each_coil = 2e8 refine_nphi_for_surface_plot = 4 @@ -196,13 +196,13 @@ time0 = time() tracing_coils_DOFS = block_until_ready(Tracing(field=field_coils_DOFS, model='FieldLineAdaptative', initial_conditions=initial_xyz, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance)) + 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, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance)) + 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 016099cd..8bceda83 100644 --- a/examples/simple_examples/coils_from_nearaxis.py +++ b/examples/simple_examples/coils_from_nearaxis.py @@ -23,8 +23,8 @@ ncoils = 4 tmax = 800 nfieldlines_per_core=1 -trace_tolerance = 1e-8 -num_steps = 22000 +rtol = 1e-8 +n_save = 22000 order = 4 current_on_each_coil = 2e8 Poincare_plot_phi = jnp.array([0]) @@ -78,12 +78,12 @@ 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, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance)) + 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, - maxtime=tmax, times_to_trace=num_steps, atol=trace_tolerance,rtol=trace_tolerance)) + 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/tests/test_boozer.py b/tests/test_boozer.py index 9a5d3b60..3a45e36e 100644 --- a/tests/test_boozer.py +++ b/tests/test_boozer.py @@ -135,7 +135,7 @@ def test_orbits_conserve_energy_and_toroidal_canonical_momentum(method): theta = jnp.linspace(0, 2 * np.pi, n, endpoint=False) out = trace_boozer(field, jnp.full(n, 0.3), theta, jnp.zeros(n), pitch, speed=V0, mass=M, charge=Q, tmax=2e-4, timestep=2e-8, n_save=5, - devices=jax.devices()[:1], method=method, tolerance=1e-11) + devices=jax.devices()[:1], method=method, rtol=1e-11) assert not out.lost.any() and np.all(out.energy_error < 1e-8) s, th, ze, vpar, v = np.moveaxis(out.states, -1, 0) B = B0 * (1 - EPS * np.sqrt(s) * np.cos(th)) @@ -573,14 +573,14 @@ def test_adaptive_error_follows_the_tolerance(method): errors = [] for tolerance, first in ((1e-6, 1e-9), (1e-9, 1e-6), (1e-11, 1e-8)): out = trace_boozer(field, *args, speed=V0, mass=M, charge=Q, tmax=1e-4, timestep=first, - n_save=5, method=method, tolerance=tolerance, devices=jax.devices()[:1]) + n_save=5, method=method, rtol=tolerance, devices=jax.devices()[:1]) assert not out.lost.any() and not out.failed.any() errors.append(out.energy_error.max()) assert errors[0] > errors[1] > errors[2] and errors[2] < 1e-8 -def test_adaptive_tolerance_is_validated(): - with pytest.raises(ValueError, match="tolerance"): +def test_adaptive_rtol_is_validated(): + with pytest.raises(ValueError, match="rtol"): trace_boozer(tokamak(), [0.3], [0.0], [0.0], [0.2], speed=V0, mass=M, charge=Q, - tmax=1e-6, timestep=1e-8, method="adaptive", tolerance=0.0) + tmax=1e-6, timestep=1e-8, method="adaptive", rtol=0.0) diff --git a/tests/test_dynamics.py b/tests/test_dynamics.py index 228c9307..70928396 100644 --- a/tests/test_dynamics.py +++ b/tests/test_dynamics.py @@ -123,8 +123,8 @@ def B_contravariant(self, points): tracing = Tracing( field=ScaledField(), model="FieldLineArclength", - initial_conditions=jnp.zeros((1, 3)), maxtime=2.0, - timestep=0.1, times_to_trace=11) + initial_conditions=jnp.zeros((1, 3)), tmax=2.0, + timestep=0.1, n_save=11) assert jnp.allclose( tracing.trajectories[0, -1], jnp.array([1.2, 1.6, 0.0])) @@ -138,7 +138,7 @@ def B_contravariant(self, points): def end_x(x0): tracing = Tracing(field=ScaledField(), model="FieldLineArclength", initial_conditions=x0, - maxtime=2.0, timestep=0.1, times_to_trace=11) + tmax=2.0, timestep=0.1, n_save=11) return tracing.trajectories[0, -1, 0] assert jnp.allclose(jax.grad(end_x)(jnp.zeros((1, 3))), jnp.array([[1.0, 0.0, 0.0]])) @@ -157,8 +157,8 @@ def toroidal_angle_batch(self, points): tracing = Tracing( field=FluxField(), model="FieldLineToroidal", - initial_conditions=jnp.zeros((1, 3)), maxtime=2.0, - timestep=0.1, times_to_trace=11) + initial_conditions=jnp.zeros((1, 3)), tmax=2.0, + timestep=0.1, n_save=11) assert jnp.allclose(tracing.trajectories[0, -1], jnp.array([0.0, 1.0, 2.0])) assert jnp.allclose(tracing.toroidal_angles[0], tracing.trajectories[0, :, 2]) @@ -238,16 +238,16 @@ def toroidal_angle_batch(self, points): return points[:, 2] arclength = trace_field_lines( - MockField(), jnp.zeros((1, 3)), length=2.0, samples=11, - tolerance=1.0e-8, progress=False, label="Cartesian test") + MockField(), jnp.zeros((1, 3)), length=2.0, n_save=11, + rtol=1.0e-8, progress=False, label="Cartesian test") toroidal = trace_field_lines( - FluxField(), jnp.zeros((1, 3)), toroidal_turns=0.5, samples=11, - tolerance=1.0e-8, progress=False, label=None) + 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 toroidal.model == "FieldLineToroidal" - assert float(arclength.maxtime) == pytest.approx(2.0) - assert float(toroidal.maxtime) == pytest.approx(float(jnp.pi)) + assert float(arclength.tmax) == pytest.approx(2.0) + assert float(toroidal.tmax) == pytest.approx(float(jnp.pi)) assert "Tracing Cartesian test" in capsys.readouterr().out @@ -261,7 +261,7 @@ def evaluate_xyz(self, xyz): return 0.2 - xyz[0] result = trace_field_lines( - BatchedField(), jnp.zeros((1, 3)), length=1.0, samples=11, + BatchedField(), jnp.zeros((1, 3)), length=1.0, n_save=11, stopping_criteria=LevelsetStoppingCriterion(PlaneClassifier()), progress=False, label="bounded test") assert result.boundary_hits.tolist() == [True] @@ -275,11 +275,11 @@ def test_trace_field_lines_requires_one_extent(kwargs): @pytest.mark.parametrize("kwargs, message", ( - ({"length": 1.0, "samples": 1}, "samples"), + ({"length": 1.0, "n_save": 1}, "n_save"), ({"length": 0.0}, "length"), ({"toroidal_turns": 0.0}, "toroidal_turns"), )) -def test_trace_field_lines_validates_positive_extent_and_samples(kwargs, message): +def test_trace_field_lines_validates_positive_extent_and_n_save(kwargs, message): with pytest.raises(ValueError, match=message): trace_field_lines(MockField(), jnp.zeros((1, 3)), progress=False, **kwargs) @@ -382,7 +382,7 @@ def evaluate_xyz(self, xyz): tracing = Tracing( field=MockField(), model="FieldLineAdaptative", initial_conditions=jnp.array([[1.0, 0.0, 0.0]]), - maxtime=1.0, timestep=0.01, times_to_trace=21, + tmax=1.0, timestep=0.01, n_save=21, stopping_criteria=criterion, ) @@ -468,7 +468,7 @@ def test_vmec_fieldline_uses_the_lcfs_event(): tracing = Tracing( field=MockVmec(), model="FieldLineArclength", initial_conditions=jnp.array([[0.5, 0.0, 0.0]]), - maxtime=0.01, timestep=0.001, times_to_trace=3) + tmax=0.01, timestep=0.001, n_save=3) assert callable(tracing.condition) @@ -499,7 +499,7 @@ def test_full_orbit_collisions_keep_a_maxwellian_at_the_background_temperature() particles = Particles(initial_xyz=xyz, initial_xyz_fullorbit=xyz, mass=PROTON_MASS, charge=ELEMENTARY_CHARGE, initial_vxvyvz=vth * jax.random.normal(jax.random.key(0), (n, 3))) trace = Tracing(field=_UniformField((0., 0., 1.), magnitude=1e-6), particles=particles, species=species, - model="FullOrbitCollisions", maxtime=2 / nu, timestep=1e-2 / nu, times_to_trace=6, + model="FullOrbitCollisions", tmax=2 / nu, timestep=1e-2 / nu, n_save=6, rtol=1e-4, atol=1e-4) energy = 0.5 * PROTON_MASS * jnp.sum(trace.trajectories[:, :, 3:]**2, axis=-1) / (1.5 * temperature) error = np.sqrt(2 / 3 / n) @@ -511,7 +511,7 @@ def test_vmec_guiding_centers_cross_the_magnetic_axis(monkeypatch): 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", - particles=particles, maxtime=2e-5, timestep=1e-9, times_to_trace=200, + particles=particles, tmax=2e-5, timestep=1e-9, n_save=200, atol=1e-9, rtol=1e-9) s = tracing.trajectories[:, :, 0] assert not tracing.axis_hits.any() and not tracing.boundary_hits.any() @@ -527,7 +527,7 @@ def below(t, y, args, **kwargs): return y[0] < 5e-3 tracing = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model="GuidingCenterAdaptative", - particles=_near_axis_particles(), maxtime=2e-5, timestep=1e-9, times_to_trace=200, + particles=_near_axis_particles(), tmax=2e-5, timestep=1e-9, n_save=200, atol=1e-9, rtol=1e-9, condition=below) s = tracing.trajectories[:, :, 0] stopped = ~jnp.isfinite(s[:, -1]) @@ -541,7 +541,7 @@ def test_vmec_collisional_guiding_centers_cross_the_magnetic_axis(model): charge_array=jnp.array([-1.0, 1.0]), n_array=jnp.array([1e20, 1e20]), T_array=jnp.array([1e4, 1e4])) tracing = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model=model, particles=_near_axis_particles(), - maxtime=2e-5, timestep=1e-8, times_to_trace=100, species=species) + tmax=2e-5, timestep=1e-8, n_save=100, species=species) s = tracing.trajectories[:, :, 0] assert not tracing.axis_hits.any() assert jnp.isfinite(tracing.trajectories).all() @@ -554,7 +554,7 @@ def test_tracing_initialization(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='GuidingCenter', particles=particles, times_to_trace=200) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenter', particles=particles, n_save=200) assert tracing.field == field assert tracing.model == 'GuidingCenter' assert tracing.initial_conditions.shape == (particles.nparticles, 4) @@ -565,7 +565,7 @@ def test_tracing_trace(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='GuidingCenter', particles=particles, times_to_trace=200) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenter', particles=particles, n_save=200) trajectories = tracing.trace() assert trajectories.shape == (particles.nparticles, 200, 4) @@ -574,7 +574,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, times_to_trace=200) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterAdaptative', particles=particles, n_save=200) trajectories = tracing.trace() assert trajectories.shape == (particles.nparticles, 200, 4) @@ -593,7 +593,7 @@ def test_tracing_trace_collisions_fixed(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='GuidingCenterCollisionsMuFixed', particles=particles, times_to_trace=200,maxtime=1.e-6,species=species) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterCollisionsMuFixed', particles=particles, n_save=200,tmax=1.e-6,species=species) trajectories = tracing.trace() assert species.mass.shape == (2,) assert species.charge.shape == (2,) @@ -613,7 +613,7 @@ def test_tracing_trace_collisions_ito(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='GuidingCenterCollisionsMuIto', particles=particles, times_to_trace=200,maxtime=1.e-6,species=species) + tracing = Tracing(initial_conditions=initial_conditions, field=field,electric_field=electric_field, model='GuidingCenterCollisionsMuIto', particles=particles, n_save=200,tmax=1.e-6,species=species) trajectories = tracing.trace() assert species.mass.shape == (2,) assert species.charge.shape == (2,) @@ -633,7 +633,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, times_to_trace=200,maxtime=1.e-6,species=species) + 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) trajectories = tracing.trace() assert species.mass.shape == (2,) assert species.charge.shape == (2,) @@ -651,7 +651,7 @@ def test_tracing_max_steps_is_configurable_and_bounded(): from essos.dynamics import Tracing default = inspect.signature(Tracing).parameters["max_steps"].default - assert default is None # derived from maxtime and timestep + assert default is None # derived from tmax and timestep source = inspect.getsource(Tracing) assert "max_steps=10000000000" not in source @@ -695,8 +695,8 @@ def checked_controller(**kwargs): def below_ceiling(t, y, args, **kwargs): return ceiling - y[2] trace = Tracing(field=field, particles=particles, species=species, - model="FullOrbitCollisions", maxtime=1e-5, timestep=1e-7, - times_to_trace=3, rtol=1e-6, atol=1e-7, + model="FullOrbitCollisions", tmax=1e-5, timestep=1e-7, + n_save=3, rtol=1e-6, atol=1e-7, stopping_criteria=below_ceiling if stop else None) assert trace.trajectories.shape == (1, 3, 6) assert jnp.all(jnp.isfinite(trace.trajectories)) @@ -710,7 +710,7 @@ 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 times_to_trace, passed both + """Unflatten re-ran __init__ with times as n_save, passed both condition and stopping_criteria, and dropped species and boundary.""" field = _UniformField((0., 0., 1.), magnitude=1e-3) particles = Particles([[1., 0., 0.]], [.5], field=field) @@ -719,10 +719,10 @@ def test_tracing_pytree_round_trip_and_jit(): def below_ceiling(t, y, args, **kwargs): return 1.0 - y[2] trace = Tracing(field=field, particles=particles, species=species, model="FullOrbitCollisions", - maxtime=1e-6, timestep=1e-7, times_to_trace=3, stopping_criteria=below_ceiling) + tmax=1e-6, timestep=1e-7, n_save=3, stopping_criteria=below_ceiling) leaves, treedef = jax.tree_util.tree_flatten(trace) rebuilt = jax.tree_util.tree_unflatten(treedef, leaves) - assert rebuilt.species is species and rebuilt.times_to_trace == 3 + assert rebuilt.species is species and rebuilt.n_save == 3 assert rebuilt.stopping_criteria == trace.stopping_criteria and rebuilt.condition is trace.condition np.testing.assert_array_equal(rebuilt.times, trace.times) np.testing.assert_array_equal(rebuilt.trajectories, trace.trajectories) @@ -945,7 +945,7 @@ def AbsB(self, point): return jnp.linalg.norm(self.vector) -def _boris(maxtime, timestep, times_to_trace=None, stopping_criteria=None): +def _boris(tmax, timestep, n_save=None, stopping_criteria=None): from essos.dynamics import Particles, Tracing field = _UniformCartesianField((0.0, 0.0, 1.0), magnitude=1.0) @@ -957,8 +957,8 @@ def _boris(maxtime, timestep, times_to_trace=None, stopping_criteria=None): initial_vxvyvz=jnp.asarray([[v_perp, 0.0, v_par]]), ) tracing = Tracing( - field=field, particles=particles, model="FullOrbit_Boris", maxtime=maxtime, - timestep=timestep, times_to_trace=times_to_trace, stopping_criteria=stopping_criteria, + field=field, particles=particles, model="FullOrbit_Boris", tmax=tmax, + timestep=timestep, n_save=n_save, stopping_criteria=stopping_criteria, ) period = 2 * np.pi * mass / (charge * 1.0) return tracing, v_par, v_perp, period @@ -966,7 +966,7 @@ def _boris(maxtime, timestep, times_to_trace=None, stopping_criteria=None): def test_boris_integrates_the_whole_requested_time_span(): period = 2 * np.pi * 1.6726e-27 / 1.602e-19 - tracing, v_par, v_perp, _ = _boris(maxtime=200 * period, timestep=period / 50, times_to_trace=11) + tracing, v_par, v_perp, _ = _boris(tmax=200 * period, timestep=period / 50, n_save=11) trajectory = tracing.trajectories[0] assert trajectory.shape[0] == 11 np.testing.assert_allclose(trajectory[-1, 2], v_par * 200 * period, rtol=1e-10) @@ -985,7 +985,7 @@ def test_boris_honours_stopping_criteria_with_an_event_mask(): def below_ceiling(t, y, args, **kwargs): return ceiling - y[2] - tracing, *_ = _boris(maxtime=100 * period, timestep=period / 40, times_to_trace=21, + tracing, *_ = _boris(tmax=100 * period, timestep=period / 40, n_save=21, stopping_criteria=below_ceiling) trajectory = tracing.trajectories[0] assert bool(tracing.boundary_hits[0]) @@ -993,14 +993,14 @@ def below_ceiling(t, y, args, **kwargs): np.testing.assert_allclose(trajectory[-1], trajectory[-2], rtol=0, atol=0) -def _edge_tracing(model, s0, times_to_trace, **kwargs): +def _edge_tracing(model, s0, n_save, **kwargs): from pathlib import Path wout = Path(__file__).resolve().parents[1] / "examples" / "input_files" / "wout_LandremanPaul2021_QA_reactorScale_lowres.nc" n = 16 particles = Particles(initial_xyz=jnp.stack([jnp.full(n, s0), jnp.linspace(0, 6, n), jnp.zeros(n)], axis=1), initial_vparallel_over_v=jnp.linspace(-0.9, 0.9, n)) - return Tracing(field=Vmec(str(wout), ntheta=8, nphi=8), model=model, particles=particles, maxtime=1e-5, - timestep=1e-8, times_to_trace=times_to_trace, **kwargs) + return Tracing(field=Vmec(str(wout), ntheta=8, nphi=8), model=model, particles=particles, tmax=1e-5, + timestep=1e-8, n_save=n_save, **kwargs) def test_vmec_losses_are_counted_at_the_lcfs(): @@ -1049,13 +1049,13 @@ def test_particle_batches_report_completed_particles_and_match_one_batch(capsys, 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]]), - maxtime=1.0, timestep=0.01, particle_batch_size=batch_size) + 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, maxtime=1.0, - timestep=0.01, times_to_trace=3, particle_batch_size=batch).trajectories + return Tracing(field=MockField(), model="FieldLineAdaptative", 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) np.testing.assert_allclose(final(y0, 2), final(y0, None), rtol=1e-12) @@ -1075,7 +1075,7 @@ def test_custom_loss_grad_through_adaptive_guiding_center_matches_finite_differe def final_position(field, particles): tracing = Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, - maxtime=1e-7, times_to_trace=4, atol=1e-10, rtol=1e-10) + 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]) @@ -1103,12 +1103,12 @@ def test_vmec_guiding_centers_seeded_on_the_axis_leave_it(): 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, - maxtime=2e-5, timestep=1e-8, times_to_trace=5) + 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, maxtime, model="GuidingCenterAdaptative", wall_gap=0.05, **kwargs): +def _exterior_tracing(xyz, vpar_over_v, tmax, model="GuidingCenterAdaptative", 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) @@ -1118,7 +1118,7 @@ def _exterior_tracing(xyz, vpar_over_v, maxtime, model="GuidingCenterAdaptative" options = dict(timestep=1e-9, atol=1e-8, rtol=1e-8) if model == "GuidingCenterAdaptative" 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, maxtime=maxtime, times_to_trace=40, **options) + return Tracing(field=vmec, model=model, particles=particles, tmax=tmax, n_save=40, **options) # Four orbits that cross the LCFS and strike a wall 5 cm outside it within 3 us. @@ -1151,7 +1151,7 @@ def test_vmec_lcfs_crossings_are_exact(): def test_vmec_orbits_continue_outside_and_strike_the_wall_exactly(): - tracing = _exterior_tracing(*STRIKING, maxtime=3e-6) + tracing = _exterior_tracing(*STRIKING, tmax=3e-6) struck = tracing.wall_hits assert struck.all() assert jnp.abs(jax.vmap(tracing.field.boundary_distance)(jnp.asarray(tracing.wall_positions)) + 0.05).max() < 1e-10 @@ -1166,7 +1166,7 @@ def test_vmec_orbits_continue_outside_and_strike_the_wall_exactly(): def test_vmec_orbits_that_come_back_inside_return_to_flux_coordinates(): xyz, vpar = [[0.9037, 1.2536, 3.6827]], [0.9639] - tracing = _exterior_tracing(xyz, vpar, maxtime=5e-6) + tracing = _exterior_tracing(xyz, vpar, tmax=5e-6) assert tracing.returns[0] == 1 and tracing.status[0] == 0 region = np.asarray(tracing.region[0]) changes = np.flatnonzero(np.diff(region)) @@ -1174,7 +1174,7 @@ def test_vmec_orbits_that_come_back_inside_return_to_flux_coordinates(): # Inside again, the flux-coordinate trajectory resumes with its energy. later = region[changes[1] + 1:] == 0 assert jnp.abs(tracing.energy()[0][changes[1] + 1:][later] / tracing.particles.energy - 1).max() < 1e-5 - capped = _exterior_tracing(xyz, vpar, maxtime=5e-6, max_returns=0) + capped = _exterior_tracing(xyz, vpar, tmax=5e-6, max_returns=0) assert capped.status[0] == 5 and capped.returns[0] == 0 @@ -1183,7 +1183,7 @@ def test_vmec_collisional_orbits_continue_outside(model): species = BackgroundSpecies(number_species=2, mass_array=jnp.array([ELECTRON_MASS / PROTON_MASS, 1.0]), charge_array=jnp.array([-1.0, 1.0]), n_array=jnp.array([1e19, 1e19]), T_array=jnp.array([300.0, 300.0])) - tracing = _exterior_tracing(*STRIKING, maxtime=3e-6, model=model, species=species) + tracing = _exterior_tracing(*STRIKING, tmax=3e-6, model=model, species=species) struck = tracing.wall_hits assert struck.any() and not tracing.failed.any() assert jnp.all(tracing.wall_times[struck] > tracing.lcfs_times[struck]) @@ -1196,7 +1196,7 @@ def toroidal(xyz): R2 = xyz[:, 0]**2 + xyz[:, 1]**2 return jnp.where(xyz[:, 2:] > 0.0, jnp.nan, 60.0 * jnp.stack([-xyz[:, 1] / R2, xyz[:, 0] / R2, 0 * R2], 1)) - tracing = _exterior_tracing(*STRIKING, maxtime=3e-6, exterior_field=toroidal, wall=None) + tracing = _exterior_tracing(*STRIKING, tmax=3e-6, exterior_field=toroidal, wall=None) failed = tracing.failed assert failed.any() and jnp.all(tracing.status[failed] == 4) assert jnp.all(tracing.failure_times[failed] >= tracing.lcfs_times[failed]) @@ -1207,7 +1207,7 @@ def toroidal(xyz): def test_vmec_wall_already_crossed_at_the_exit_point_is_a_hit_at_the_exit_time(): - tracing = _exterior_tracing(*STRIKING, maxtime=3e-6, wall_gap=-1e-3) + tracing = _exterior_tracing(*STRIKING, tmax=3e-6, wall_gap=-1e-3) assert tracing.wall_hits.all() and jnp.allclose(tracing.wall_times, tracing.lcfs_times, rtol=1e-12) @@ -1226,14 +1226,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, maxtime=3e-6, timestep=1e-9, - times_to_trace=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(_toroidal_source, params), + tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", 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", maxtime=3e-6, timestep=1e-9, times_to_trace=4, atol=1e-8, + tracing = Tracing(field=vmec, model="GuidingCenterAdaptative", 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]))) @@ -1307,8 +1307,8 @@ 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, maxtime=1e-6, timestep=1e-9, - times_to_trace=4, atol=1e-8, rtol=1e-8, exterior_field=ExternalField(_toroidal_source, jnp.array([60.0, 0.5])), + tracing = Tracing(field=field, model="GuidingCenterAdaptative", 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,8 +1328,8 @@ 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, maxtime=1e-4, timestep=1e-9, - times_to_trace=3, atol=1e-10, rtol=1e-10).lcfs_times + return Tracing(field=vmec, model="GuidingCenterAdaptative", 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)) s = jnp.full(8, 0.9) @@ -1380,7 +1380,7 @@ def test_collisional_guiding_center_v_perp_uses_speed_and_pitch(): species = BackgroundSpecies(1, jnp.array([1.]), jnp.array([1.]), jnp.array([1e18]), jnp.array([1e3])) particles = _near_axis_particles() trace = Tracing(field=Vmec(WOUT_QA, ntheta=8, nphi=8), model="GuidingCenterCollisions", particles=particles, - maxtime=1e-9, timestep=1e-10, times_to_trace=2, species=species) + tmax=1e-9, timestep=1e-10, n_save=2, species=species) np.testing.assert_allclose(trace.v_perp()[:, 0], particles.initial_vperpendicular, rtol=1e-10) @@ -1393,7 +1393,7 @@ def test_mu_collision_models_accept_coils_as_the_field(monkeypatch): particles = Particles([[1.05, 0., 0.]], [.5]) monkeypatch.setattr(Tracing, "trace", lambda self: jnp.zeros((1, 2, 5))) # only the setup is tested trace = Tracing(field=coils, model="GuidingCenterCollisionsMuFixed", particles=particles, - maxtime=1e-9, timestep=1e-10, times_to_trace=2, species=species) + tmax=1e-9, timestep=1e-10, n_save=2, species=species) B = BiotSavart(coils).AbsB(particles.initial_xyz[0]) mu = particles.initial_vperpendicular[0]**2 / (2 * B * SPEED_OF_LIGHT**2) np.testing.assert_allclose(trace.initial_conditions[0, 4], mu, rtol=1e-6) @@ -1416,14 +1416,14 @@ def qa_coil_alphas(): ]) def test_default_tracing_conserves_energy(qa_coil_alphas, model, options, bound): field, particles = qa_coil_alphas - tracing = Tracing(field=field, model=model, particles=particles, maxtime=1e-4, times_to_trace=20, **options) + tracing = Tracing(field=field, model=model, particles=particles, tmax=1e-4, n_save=20, **options) assert float(jnp.max(jnp.abs(tracing.energy() / particles.energy - 1))) < 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, maxtime=1e-5, max_steps=20) + Tracing(field=field, model="GuidingCenterAdaptative", particles=particles, tmax=1e-5, max_steps=20) @pytest.mark.parametrize("method, steps, order", [ @@ -1447,7 +1447,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, maxtime=2e-5, times_to_trace=400) + tracing = Tracing(field=field, model="FullOrbitAdaptative", 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 @@ -1461,7 +1461,7 @@ def test_full_orbit_magnetic_moment_is_an_adiabatic_invariant(qa_coil_alphas): def test_default_timestep_is_a_transit_fraction_and_survives_grad(qa_coil_alphas): field, particles = qa_coil_alphas speed = float(particles.total_speed.max()) - kwargs = dict(model="GuidingCenter", maxtime=1e-7, times_to_trace=2) + kwargs = dict(model="GuidingCenter", tmax=1e-7, n_save=2) assert Tracing(field=field, particles=particles, **kwargs).timestep == pytest.approx(float(field.r_axis) / speed / 400) vmec = Vmec(WOUT_QA, ntheta=8, nphi=8) near_axis = _near_axis_particles() @@ -1478,7 +1478,7 @@ def end(x0, energy=particles.energy): with pytest.raises(ValueError, match="explicit timestep"): jax.grad(lambda energy: end(particles.initial_xyz, energy))(particles.energy) - seen = [] # an adaptive trace of a traced energy starts from maxtime/100 and keeps a generous step budget + seen = [] # an adaptive trace of a traced energy starts from tmax/100 and keeps a generous step budget def adaptive_end(energy): launched = Particles(initial_xyz=particles.initial_xyz, energy=energy, @@ -1519,8 +1519,8 @@ def test_tracings_with_the_same_shapes_share_one_compiled_solve(): 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) 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, maxtime=1e-6, timestep=1e-8, - times_to_trace=10, progress=False).trajectories + return Tracing(field=BiotSavart(coils), model='GuidingCenter', particles=particles, tmax=1e-6, timestep=1e-8, + n_save=10, progress=False).trajectories _compiled_solver.cache_clear() first, second = trace([1e6, 2e6], 0.), trace([2e6, 1e6], 0.01) @@ -1568,7 +1568,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, maxtime=1e-7, - timestep=5e-8, times_to_trace=2, atol=1e-4, rtol=1e-4, solver=diffrax.Kvaerno5()) + tracing = Tracing(field=field, model='GuidingCenterAdaptative', 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_gpu.py b/tests/test_gpu.py index 88dea773..32710959 100644 --- a/tests/test_gpu.py +++ b/tests/test_gpu.py @@ -68,7 +68,7 @@ def test_field_line_tracing_in_a_coil_field_is_differentiable(): def end_z(x0): tracing = Tracing(field=field, model="FieldLine", initial_conditions=x0, - maxtime=1e-2, timestep=1e-3, times_to_trace=3) + tmax=1e-2, timestep=1e-3, n_save=3) return tracing.trajectories[0, -1, 2] x0 = jnp.array([[0.1, 0.0, Z]]) diff --git a/tests/test_interpolated_field.py b/tests/test_interpolated_field.py index 07cd8dec..1d7b1a49 100644 --- a/tests/test_interpolated_field.py +++ b/tests/test_interpolated_field.py @@ -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, maxtime=2e-6, times_to_trace=20, + runs = [Tracing(field=g, model="GuidingCenterAdaptative", 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 685784a6..eacf796a 100644 --- a/tests/test_mgrid.py +++ b/tests/test_mgrid.py @@ -186,8 +186,8 @@ def test_mgrid_can_be_traced_directly(): mgrid.add_field_cylindrical(0 * ones, 0 * ones, ones) particles = Particles(initial_xyz=jnp.array([[1.0, 0.0, 0.0]]), initial_vparallel_over_v=jnp.array([0.5]), mass=PROTON_MASS, charge=ELEMENTARY_CHARGE, energy=1e3 * ELEMENTARY_CHARGE) - tracing = Tracing(field=mgrid, model="GuidingCenter", particles=particles, maxtime=1e-7, timestep=1e-9, - times_to_trace=3, progress=False) + tracing = Tracing(field=mgrid, model="GuidingCenter", particles=particles, tmax=1e-7, timestep=1e-9, + n_save=3, progress=False) v = jnp.sqrt(2 * 1e3 * ELEMENTARY_CHARGE / PROTON_MASS) np.testing.assert_allclose(tracing.trajectories[0, -1, 2], 0.5 * v * 1e-7, rtol=1e-6) diff --git a/tests/test_objective_functions.py b/tests/test_objective_functions.py index 8f8acff3..cd669efd 100644 --- a/tests/test_objective_functions.py +++ b/tests/test_objective_functions.py @@ -86,8 +86,8 @@ def __init__(self, *args, **kwargs): self.trajectories = xyz self.field = kwargs.get("field", DummyField()) self.loss_fractions = jnp.array([0.1, 0.2, 1.0]) - self.times_to_trace = 4 - self.maxtime = 1e-5 + self.n_save = 4 + self.tmax = 1e-5 @jax.tree_util.register_pytree_node_class @@ -224,8 +224,8 @@ def test_particle_losses(self, tracing): 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.loss_BdotN(self.field, self.surface))) - self.assertTrue(jnp.isfinite(objf.loss_BdotN_constraint(self.field, self.surface))) + self.assertTrue(jnp.isfinite(objf.loss_bdotn(self.field, self.surface))) + self.assertTrue(jnp.isfinite(objf.loss_bdotn_constraint(self.field, self.surface))) def test_copy_coils_from_field(self): copied = objf.copy_coils_from_field(self.field) @@ -407,8 +407,8 @@ 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) - g = jax.grad(lambda b: of.loss_BdotN_constraint(b, None, target_tol=1e-6))(jnp.array([1e-4, 2e-4])) + 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])) + g = jax.grad(lambda b: of.loss_bdotn_constraint(b, None, target_tol=1e-6))(jnp.array([1e-2, 2e-4])) assert jnp.isfinite(g).all() and g[0] > 0