Skip to content
27 changes: 22 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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])
```

Expand Down Expand Up @@ -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)
```
Expand All @@ -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])
```

Expand All @@ -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]'`.

Expand Down Expand Up @@ -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(...)`
Expand Down Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion docs/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/make_readme_figures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -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")
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion docs/tracing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
18 changes: 9 additions & 9 deletions essos/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
17 changes: 9 additions & 8 deletions essos/boozer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading