Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
2508f0b
Add native Dopri5/Dopri8 orbit tracing and CUDA adapters
eduardolneto Oct 27, 2026
3d20e36
Fix native field adapter compatibility with older JAX
eduardolneto Oct 27, 2026
4bb9e6e
Add native split orbit and collision tracing
eduardolneto Oct 28, 2026
8a9c238
Add checkpointed native AD and GC coil ALM examples
eduardolneto Oct 29, 2026
8b12b48
Enable specialized collisional GC optimization and save iteration DOFs
eduardolneto Oct 29, 2026
a7cc4a5
Fix discarded outputs in native predictor preparation
eduardolneto Oct 29, 2026
dec1aa7
Handle placement annotations in native GPU kernels
eduardolneto Oct 29, 2026
59278af
Add SciPy ALM optimizer and particle comparison plots
eduardolneto Oct 29, 2026
9199e0b
Store the split-solver README figures as 256-color PNGs
rogeriojorge Oct 30, 2026
9f796f6
Store the split-solver README figures as 256-color PNGs
rogeriojorge Oct 30, 2026
38a99f4
Handle the JAX 0.12 SearchSorted primitive in scalar lowering
rogeriojorge Oct 31, 2026
b6df6ee
Handle the JAX 0.12 SearchSorted primitive in scalar lowering
rogeriojorge Oct 31, 2026
5dbc94d
Fix native Pallas compatibility with JAX 0.6.2
eduardolneto Oct 30, 2026
ba63fd3
Support JAX 0.6.2 in split scalar lowering and save loop
rogeriojorge Oct 31, 2026
8037eeb
Fix native Pallas compatibility with JAX 0.6.2
eduardolneto Oct 30, 2026
926b611
Support JAX 0.6.2 in split scalar lowering and save loop
rogeriojorge Oct 31, 2026
d41c5a4
Allow float64 round-off in the diffusion factorization check
rogeriojorge Oct 31, 2026
53590f1
Allow float64 round-off in the diffusion factorization check
rogeriojorge Oct 31, 2026
8d265a5
Read save times in the loop body for GPU lowering
rogeriojorge Nov 10, 2026
9ae1fff
Read save times in the loop body for GPU lowering
rogeriojorge Nov 10, 2026
e9f3733
Merge main into feat/native_split_collisions
rogeriojorge Nov 11, 2026
4bf32ce
Merge main into feat/native_ad_split
rogeriojorge Nov 11, 2026
cd44664
Apply the radial speed drift as a perpendicular kick in the guiding-c…
rogeriojorge Nov 12, 2026
469c614
Merge remote-tracking branch 'origin/feat/native_split_collisions' in…
rogeriojorge Nov 13, 2026
f42fe07
Merge main into feat/native_split_collisions
rogeriojorge Nov 13, 2026
9a2855a
Merge remote-tracking branch 'origin/feat/native_split_collisions' in…
rogeriojorge Nov 13, 2026
106fff3
Update the guiding-center collision map test for the perpendicular-ki…
rogeriojorge Nov 13, 2026
ff5c401
Merge remote-tracking branch 'origin/feat/native_split_collisions' in…
rogeriojorge Nov 13, 2026
e874b51
Merge main into feat/native_split_collisions
rogeriojorge Nov 16, 2026
a45330f
Fix the native orbit test on JAX releases whose partial_eval facade i…
rogeriojorge Nov 16, 2026
10db234
Merge main into feat/native_ad_split
rogeriojorge Nov 16, 2026
6653757
Merge feat/native_split_collisions into feat/native_ad_split
rogeriojorge Nov 16, 2026
1d98001
Merge main into feat/native_ad_split
rogeriojorge Nov 18, 2026
c85ba45
Share current VMEC radial interpolation with native adapter
rogeriojorge Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
540 changes: 540 additions & 0 deletions README.md

Large diffs are not rendered by default.

Binary file added docs/readme_split_coordinate_diffusion.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_coordinate_helix_moments.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_coordinate_mirror_moments.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_distributions.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_first_stopping_distribution.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_first_stopping_moments.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_multirate.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_multirate_gc.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_thermalization.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/readme_split_thermalization_lorentz.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
86 changes: 83 additions & 3 deletions essos/background_species.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# to use higher precision
config.update("jax_enable_x64", True)
from jax import jit
from essos.constants import ELEMENTARY_CHARGE, EPSILON_0, PROTON_MASS, SPEED_OF_LIGHT
from essos.constants import ELEMENTARY_CHARGE, EPSILON_0, PROTON_MASS, SPEED_OF_LIGHT, HBAR



Expand All @@ -21,8 +21,23 @@ class BackgroundSpecies():
first coordinate of the traced points (``s`` for a VMEC field), shape
``(number_species, len(radial_grid))``. Profiles are interpolated
linearly and held constant beyond the ends of the grid.

``coulomb_log_model="nrl"`` preserves the original pairwise NRL formulas.
``"impact"`` selects smooth Landau--Spitzer cutoffs at the RMS relative
speed, with static Debye screening (see :func:`impact_coulomb_logarithm`). Screening
uses these background species unless ``screening_species`` supplies a
separate BackgroundSpecies, e.g. electrons which screen without adding
electron collisions. No screening electron population is inferred for
the impact model. Both tracers and both time solvers use this selection.
"""
def __init__(self, number_species, mass_array, charge_array, n_array, T_array, radial_grid=None):
def __init__(self, number_species, mass_array, charge_array, n_array, T_array, radial_grid=None,
*, coulomb_log_model="nrl", screening_species=None):
if coulomb_log_model not in ("nrl", "impact"):
raise ValueError("coulomb_log_model must be 'nrl' or 'impact'")
if screening_species is not None and coulomb_log_model != "impact":
raise ValueError("screening_species is only used by the impact Coulomb-log model")
self.coulomb_log_model = coulomb_log_model
self.screening_species = screening_species
self.number_species = number_species
self.species_indeces = jnp.arange(number_species)
self.temperature = T_array
Expand Down Expand Up @@ -61,7 +76,8 @@ def gamma_ab(ma: float, ea: float, species_b: int,v: float, points, species: Bac
def dlog_coulomb_dv(ma, ea, species_b, v, points, species):
"""d(ln lnLambda)/dv: the Coulomb logarithm depends on the test-particle speed."""
ln, slope = jax.jvp(lambda u: coulomb_logarithm(ma, ea, species_b, u, points, species), (v,), (jnp.ones_like(v),))
return slope/ln
# The impact model returns zero in a vacuum, where all rates vanish.
return slope/jnp.where(ln == 0, 1., ln)


@partial(jit, static_argnames=['species'])
Expand Down Expand Up @@ -115,8 +131,72 @@ def nu_s_ab(ma: float, ea: float,species_b: int,v:float, points,species: Backgro
gamma_ab(ma,ea, species_b, v, points,species)* nb * (ma+mb)/Tb * chandrasekhar(v / vtb) /v
)*(ma/(ma+mb))


# Smooth Landau-Spitzer GMS-1 (ls_min_interp) impact cutoffs.
# RMS relative speed squared v**2+3*T_b/m_b approximates a Maxwellian average.
# Screening uses the supplied species; dynamic screening is excluded.
# Temperatures are in eV; masses, charges, densities and speeds use SI.
# https://docs.plasmapy.org/en/stable/api/plasmapy.formulary.collisions.coulomb.Coulomb_logarithm.html

def debye_inverse_squared(density, temperature, charge):
"""Sum n_s q_s**2/(epsilon_0 T_s) over explicitly supplied screeners.

Absent species contribute zero, including an absent species with T=0.
Invalid occupied temperatures or negative densities propagate NaN.
"""
density, temperature, charge = map(jnp.asarray, (density, temperature, charge))
active = (density != 0) & (charge != 0)
energy = jnp.where(active, temperature, 1.)*ELEMENTARY_CHARGE
terms = jnp.where(active, density*charge**2/(EPSILON_0*energy), 0.)
valid = (density >= 0) & (~active | (temperature > 0))
return jnp.sum(jnp.where(valid, terms, jnp.nan))


def impact_parameters(mass_a, charge_a, mass_b, charge_b, speed, temperature_b,
screening_length):
"""Return (b_min, b_max), using reduced mass and smooth quantum crossover.

``screening_length`` is specified independently of test-particle speed.
The charge product is |q_a q_b|, including unlike charge magnitudes.
"""
reduced_mass = mass_a*(mass_b/(mass_a+mass_b))
relative_speed_squared = speed**2+3*temperature_b*ELEMENTARY_CHARGE/mass_b
b90 = jnp.abs(charge_a*charge_b)/(4*jnp.pi*EPSILON_0*reduced_mass*relative_speed_squared)
quantum = HBAR/(2*reduced_mass*jnp.sqrt(relative_speed_squared))
return jnp.hypot(b90, quantum), screening_length


def impact_coulomb_logarithm(mass_a, charge_a, mass_b, charge_b, speed,
temperature_b, density, temperature, charge):
"""Smooth effective-speed Landau--Spitzer log for a specified background.

A vacuum has zero collision contribution and returns zero. A nonpositive
occupied-background log returns NaN rather than silently clipping an
invalid weak-coupling model into a positive collision frequency.
"""
inverse_squared = debye_inverse_squared(density, temperature, charge)
# Use a finite inactive value so vacuum derivatives do not contain 0*inf.
length = 1/jnp.sqrt(jnp.where(inverse_squared == 0, 1., inverse_squared))
bmin, bmax = impact_parameters(mass_a, charge_a, mass_b, charge_b, speed,
temperature_b, length)
logarithm = jnp.log(bmax)-jnp.log(bmin)
occupied = jnp.where(logarithm > 0, logarithm, jnp.nan)
return jnp.where(inverse_squared == 0, 0., occupied)


@partial(jit, static_argnames=['species'])
def coulomb_logarithm(ma:float, ea: float, species_b: int, v: float, points, species: BackgroundSpecies) -> float:
"""Selected pairwise Coulomb logarithm; NRL remains the default."""
if species.coulomb_log_model == "impact":
screening = species if species.screening_species is None else species.screening_species
n = jnp.stack([screening.get_density(i, points) for i in range(screening.number_species)])
T = jnp.stack([screening.get_temperature(i, points) for i in range(screening.number_species)])
return impact_coulomb_logarithm(ma, ea, species.mass[species_b], species.charge[species_b],
v, species.get_temperature(species_b, points), n, T, screening.charge)
return nrl_coulomb_logarithm(ma, ea, species_b, v, points, species)


def nrl_coulomb_logarithm(ma:float, ea: float, species_b: int, v: float, points, species: BackgroundSpecies) -> float:
"""NRL Plasma Formulary (2019, p. 34) Coulomb logarithm of a test particle
(mass ``ma``, charge ``ea``, speed ``v``) on background species ``species_b``.

Expand Down
54 changes: 51 additions & 3 deletions essos/boozer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Fixed-step K=0 Boozer guiding-centre tracing (White, 2014).
"""K=0 Boozer guiding-centre tracing (White, 2014).

Interpolate the |B| spectrum in sqrt(s), with m>=1 coefficients divided by
sqrt(s) for axis regularity; interpolate iota, G and I in s. Explicit RK runs in
Expand Down Expand Up @@ -309,6 +309,9 @@ class BoozerTrace:
its end point and energy error are kept apart in ``terminal_states``
(``(particles, 5)``, as ``states``) and ``terminal_energy_error``; both are
NaN for particles that were not lost and neither is a physical diagnostic.
Native runs also return ``step_stats`` (trials, accepted, rejected) and
``solver_status`` (``essos.rk.RKStatus``), each per particle.
Their terminal extrapolation fields remain None: native events stop at the root.
"""

times: np.ndarray
Expand All @@ -319,6 +322,8 @@ class BoozerTrace:
failed_times: np.ndarray | None = None
terminal_states: np.ndarray | None = None
terminal_energy_error: np.ndarray | None = None
step_stats: np.ndarray | None = None # native only: (particles, 3), trials/accepted/rejected
solver_status: np.ndarray | None = None # native RKStatus per particle

@property
def lost(self):
Expand Down Expand Up @@ -486,7 +491,10 @@ 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=None, tolerance=1e-8,
integrator=None, adaptive=True, rtol=1e-9, atol=1e-9,
native_controller="i", native_pcoeff=.4, native_icoeff=.3,
native_execution="jax", max_steps=MAX_ATTEMPTS):
"""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 @@ -511,8 +519,37 @@ def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, tim
``"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.

For the shared native orbit driver, select ``integrator="essos_rk45"`` or
``"essos_dopri8"`` and omit ``method``. ``adaptive=True`` (default) uses
the I-controller with ``rtol=atol=1e-9``; ``adaptive=False`` uses ``timestep``
directly, clipping only at tmax. Native controller/PI coefficients and
standard dense output match the options in ``Tracing``.
Saves use dense output and do not constrain the orbit steps. The native
error budget is ``max(norm(du,dw), abs(dzeta), abs(dv_par)/speed)/(rtol+atol)``:
unit flux radius, radians and birth speed, rather than Cartesian metres.
The drift and field representation are unchanged. Native mode currently
supports collisionless orbits only. It solves the whole horizon, so legacy
interval compaction is unused and progress reports completion. Native
``step_stats`` and ``solver_status`` are returned on ``BoozerTrace``;
energy error is measured at saved and terminal states. LCFS events are
root-found and subsequent saves hold that state; failures are reported.
"""
if method not in ("rk4", "dopri5", "dopri8", "adaptive", "adaptive8"):
if integrator not in (None, "essos_rk45", "essos_dopri8"):
raise ValueError("integrator must be None, 'essos_rk45' or 'essos_dopri8'")
if integrator is not None:
if method is not None:
raise ValueError("method selects a legacy Boozer stepper; omit it for a native integrator")
if species is not None:
raise ValueError("native Boozer integrators currently support collisionless orbits only")
if not isinstance(adaptive, (bool, np.bool_)):
raise ValueError("adaptive must be boolean")
for name, value, positive in (("rtol", rtol, False), ("atol", atol, True)):
if np.ndim(value) or not np.isfinite(value) or (value <= 0 if positive else value < 0):
raise ValueError(f"{name} must be finite and {'positive' if positive else 'nonnegative'}")
else:
method = "dopri8" if method is None else method
if integrator is None and 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")
Expand Down Expand Up @@ -560,6 +597,17 @@ def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, tim
sharding = NamedSharding(Mesh(np.asarray(devices[:ndev]), ("p",)), PartitionSpec("p"))
args = [jax.device_put(a, sharding) for a in args]
y0, mu0, keys = args
if integrator is not None:
times = np.linspace(0., float(tmax), n_int + 1)
from essos.rk import trace_boozer_orbits as native_orbits
result = native_orbits(field, y0, mu0, mass, charge, speed[0], jnp.asarray(times),
float(timestep), rtol, atol, "dopri5" if integrator == "essos_rk45" else "dopri8",
bool(adaptive), native_controller, native_pcoeff, native_icoeff, max_steps, execution=native_execution)
states, t_loss, t_fail, err, stats, status = (np.asarray(a)[:n] for a in result)
if progress is not None:
progress(n_int, n_int)
return BoozerTrace(times, states, t_loss, np.full(n, -1.), err, t_fail,
step_stats=stats, solver_status=status)
carry, first = _start(field, y0, mu0)
chunk = n_int if progress is None and not compact else -(-n_int // 10)
states = np.empty((n, n_int + 1, 5), dtype=np.asarray(first).dtype)
Expand Down
48 changes: 37 additions & 11 deletions essos/dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1050,10 +1050,22 @@ 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: int = 1.e-8,
rtol= 1.e-7, atol = 1e-7, particles=None, condition=None,species=None,tag_gc=1.,boundary=None,rejected_steps=None,
rtol=None, 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,
max_steps=1_000_000, exterior_field=None, wall=None, max_returns=16, reentry_depth=None,
particle_batch_size=None, adjoint=None):
particle_batch_size=None, integrator="diffrax", native_error_control="physics",
orbit_length_scale=1., orbit_speed_scale=None,
native_controller="i", native_pcoeff=.4, native_icoeff=.3,
native_adjoint="none", native_adjoint_checkpoint_steps=16,
native_adjoint_max_accepted_steps=None, native_adjoint_parameter_accumulation="segment", adjoint=None):

self.native_adjoint, self.native_adjoint_checkpoint_steps = native_adjoint, native_adjoint_checkpoint_steps
self.native_adjoint_max_accepted_steps = native_adjoint_max_accepted_steps
self.native_adjoint_parameter_accumulation = native_adjoint_parameter_accumulation

from essos.rk import _configure_tracing as configure
configure(self, integrator, model, solver, native_error_control, orbit_length_scale,
orbit_speed_scale, native_controller, native_pcoeff, native_icoeff)

if condition is not None and stopping_criteria is not None:
raise ValueError("Pass condition or stopping_criteria, not both")
Expand Down Expand Up @@ -1089,8 +1101,9 @@ def __init__(self, trajectories_input=None, initial_conditions=None, times_to_tr
self.times_to_trace = times_to_trace
self.maxtime = maxtime
self.timestep = timestep
self.rtol = rtol
self.atol = atol
default_tolerance = 1e-7 if integrator == "diffrax" else 1e-9
self.rtol = default_tolerance if rtol is None else rtol
self.atol = default_tolerance if atol is None else atol
self._trajectories = trajectories_input
self.particles = particles
self.species=species
Expand Down Expand Up @@ -1384,9 +1397,11 @@ def _adaptive_tolerances(self, flag=False):
return rtol.at[indices].set(0), atol

def _terms(self, key, flag=False, events=()):
"""Diffrax terms, solver and step-size controller of self.model (with _with_failure_flag if ``flag``)."""
"""Terms and stepping configuration, with a failure flag for VMEC segments."""
flagged = (lambda f, drift=True: _with_failure_flag(f, drift)) if flag else (lambda f, drift=True: f)
dt0, model = self.timestep, self.model
if self.integrator != "diffrax":
return flagged(self.ODE_term.vector_field), None, model in _ADAPTIVE_MODELS
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
Expand All @@ -1412,8 +1427,11 @@ def _terms(self, key, flag=False, events=()):
dtmin=dt0 if model == 'FullOrbitCollisions' else None, events=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."""
def _solve(self, terms, solver, controller, t0, y0, args, event, throw=False, *, exterior=False, flag=False):
"""Integrate to maxtime, saving at self.times (clipped to t0) and at the end."""
if self.integrator != "diffrax":
from essos.rk import _solve_tracing as solve_trace
return solve_trace(self, terms, controller, t0, y0, args, event, throw, exterior, flag)
import warnings
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,
Expand Down Expand Up @@ -1450,9 +1468,16 @@ def _vmec_orbit(self, y0, key):
if ext is not None:
wall = self.wall if self.wall is not None else (lambda x: jnp.ones(()))
depth = lambda y: self.field.boundary_distance(y[:3]) - self.reentry_depth
outside = (ODETerm(_with_failure_flag(lambda t, y, args: self._masked(GuidingCenterMu, t, y, args))), self.solver if self.solver is not None else
diffrax.Dopri8(), _EventSteps(pcoeff=0.4, icoeff=0.3, dcoeff=0, rtol=self.rtol, atol=self.atol,
events=(lambda y: wall(y[:3]), depth)),
if self.integrator != "diffrax":
exterior_terms = (_with_failure_flag(GuidingCenterMu), None, True)
else:
exterior_terms = (
ODETerm(_with_failure_flag(lambda t, y, args: self._masked(GuidingCenterMu, t, y, args))),
self.solver if self.solver is not None else diffrax.Dopri8(),
_EventSteps(pcoeff=0.4, icoeff=0.3, dcoeff=0, rtol=self.rtol, atol=self.atol,
events=(lambda y: wall(y[:3]), depth)),
)
outside = (*exterior_terms,
(ext, self.particles, Electric_field_zero()),
Event((lambda t, y, args, **kwargs: wall(y[:3]), lambda t, y, args, **kwargs: depth(y), _failed_event),
root_finder=_EVENT_ROOT_FINDER))
Expand All @@ -1464,7 +1489,8 @@ def segment(o, run, spec, y, code, to_flux=lambda y: y):
# 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()
run, bad, y = run & ok, run & ~ok, jnp.where(ok, y, 0.5)
solution = self._solve(*spec[:3], jnp.where(run, o["t"], T * (1 - 1e-9)), jnp.append(y, 0.0), *spec[3:])
solution = self._solve(*spec[:3], jnp.where(run, o["t"], T * (1 - 1e-9)), jnp.append(y, 0.0), *spec[3:],
exterior=code != 0, flag=True)
saves, end = vmap(to_flux)(solution.ys[0][:, :-1]), to_flux(solution.ys[1][-1, :-1])
failed = bad | run & (solution.event_mask[-1] | ~((solution.result == diffrax.RESULTS.successful)
| (solution.result == diffrax.RESULTS.event_occurred)
Expand Down
Loading
Loading